FICO Xpress OptimizationR

Last update March 2020

5.2
REFERENCE MANUAL

FICO Xpress MoselR©2001–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 described in this documentation, oras 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 is permitted.
The information in this documentation is subject to change without notice. If you ﬁnd any problems in thisdocumentation, please report them to us in writing. Neither FICO nor its afﬁliates warrant that thisdocumentation is error-free, nor are there any other warranties with respect to the documentation except
as may be provided in the license agreement. FICO and its afﬁliates speciﬁcally disclaim any warranties,
express or implied, including, but not limited to, non-infringement, merchantability and ﬁtness for aparticular purpose. Portions of this documentation and the software described in it may contain copyrightof various authors and may be licensed 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 advised of 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 registeredtrademark of Fair Isaac Corporation in other countries. Other product and company names herein may be
trademarks of their respective owners.
Xpress Mosel
Deliverable Version: A
Last Revised: March 2020
Version 5.2

Contents
1

Introduction
1.1 What is Mosel? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 General organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3 Running Mosel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.1 mosel command: invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.2 mosel command: interactive debugger . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.3 mosel command: tracing mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.4 mosel command: restricted mode . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.5 mosel command: securing bim ﬁles . . . . . . . . . . . . . . . . . . . . . . . . . .
1.4 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5 Structure of this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1
1
1
2
2
6
10
11
12
12
13

I

Core System

14

2 The Mosel Language
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1.1 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1.2 Identiﬁers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1.3 Reserved words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1.4 Separation of instructions, line breaking . . . . . . . . . . . . . . . . . . . . . . . .
2.1.5 Conventions in this document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 Structure of the source ﬁle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 The compiler directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3.1 Directive uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3.2 Directive imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3.3 Directive options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3.4 Directive version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4 The parameters block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5 Source ﬁle preprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5.1 Source ﬁle character encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5.2 Source ﬁle inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5.3 Line control directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6 The declaration block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.1 Elementary types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.1.1 Basic types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.1.2 MP types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.2 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.3 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.4 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.4.1 Special case of dynamic arrays of a type not supporting assignment . . .
2.6.5 Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.6 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.7 User deﬁned types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.7.1 Naming new types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Fair Isaac Corporation Conﬁdential and Proprietary Information

15
15
15
15
16
16
16
17
17
17
18
19
19
20
20
20
20
21
21
22
22
22
23
23
24
24
24
25
26
26

i

Contents

2.6.7.2 Combining types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.1 Type conversions and constructors . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.2 Aggregate operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.3 Arithmetic expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.4 String expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.5 Set expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.6 List expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.7 Boolean expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.8 Linear constraint expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7.9 Automatic arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.1 Simple statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.1.1 Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.1.2 Assignment of structured types . . . . . . . . . . . . . . . . . . . . . . . .
2.8.1.3 About implicit declarations . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.1.4 Inline initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.1.5 Linear constraint expression . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.1.6 Procedure call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.2 Initialization block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.2.1 About automatic ﬁnalization . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.3 Selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.3.1 If statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.3.2 Case statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.4 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.4.1 Forall loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.4.2 While loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.4.3 Repeat loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.4.4 break and next statements . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.4.5 with statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9.1 Deﬁnition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9.2 Formal parameters: passing convention . . . . . . . . . . . . . . . . . . . . . . . .
2.9.3 Local declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9.4 Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9.5 Forward declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9.6 Sufﬁx notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.10 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.10.1 The mpproblem type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.11 The public qualiﬁer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.12 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.12.1 Version management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.12.2 The requirements block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.12.3 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.13 Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.14 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.14.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.14.2 Symbol association . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.14.3 Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.15 File names and input/output drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.16 Character encoding of text ﬁles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.17 Working directory and temporary directory . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.18 Handling of input/output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.19 Deploying models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20 Documenting models using annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Fair Isaac Corporation Conﬁdential and Proprietary Information

26
26
28
29
30
31
31
32
32
33
34
34
34
34
35
35
35
36
36
36
39
39
39
40
40
40
41
41
41
42
42
42
43
44
44
44
45
45
46
47
48
48
48
49
49
50
51
52
52
54
55
56
56
57
58

ii

Contents

2.20.1 doc annotation category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.1.1 Global deﬁnitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.1.2 Document structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.1.3 Symbol deﬁnitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.1.4 Annotation deﬁnitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.1.5 Package control parameters . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.2 moseldoc documentation processor . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.2.1 Running moseldoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.20.2.2 Structure of the generated document . . . . . . . . . . . . . . . . . . . . .
2.20.2.3 Processing of annotation values . . . . . . . . . . . . . . . . . . . . . . .
2.21 Message translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.21.1 Preparing the model source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.21.2 Building the message catalogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.21.3 Model execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59
59
60
60
62
62
62
62
63
63
63
63
64
65

3 Predeﬁned functions and procedures
abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
arctan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
asproc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
assert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bitﬂip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bitneg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bitset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bitshift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bittest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bitval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ceil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
currentdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
currenttime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cutelt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cutﬁrst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cuthead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cutlast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cuttail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delcell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
datablock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
exists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
exportprob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
fclose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
fﬂush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ﬁnalize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ﬁndﬁrst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ﬁndlast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ﬂoor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
fopen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
fselect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
fskipline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
fwrite, fwriteln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getcoeff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
95
96
97
98
99
100
101
102
103
104
105
106

Fair Isaac Corporation Conﬁdential and Proprietary Informationiii

Contents

getcoeffs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getelt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getﬁd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getﬁrst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gethead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getfname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getlast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getobjval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getrcost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getreadcnt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getreverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getslack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getvars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isdynamic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
iseof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isﬁnite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ishidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isinf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isnan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isodd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
localsetparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
makesos1, makesos2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
maxlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
memoryuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
minlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
newmuid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
publish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
random . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
read, readln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
restoreparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
reverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
round . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setcoeff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sethidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setioerr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setmatherr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setrandseed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setrange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
settype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
splithead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
splittail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
strfmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Fair Isaac Corporation Conﬁdential and Proprietary Information

107
108
109
110
111
112
113
114
115
116
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

iv

Contents

II

substr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
timestamp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
unpublish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
versionnum, versionstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
write, writeln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

164
165
166
167
168

Modules169

4 mmetc
170
4.1 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
disc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
diskdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
4.2 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
4.2.1 Driver diskdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
5 mmhttp
176
5.1 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
5.1.1 The type reqqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
5.2 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
http_async . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
http_browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
http_cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
http_defpage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
http_defport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
http_expire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
http_freeasync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
http_keephdr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
http_listen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
http_maxconn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
http_maxcontime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
http_maxreq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
http_maxreqtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
http_maxasync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
http_port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
http_proxy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
http_proxyport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
http_srvconﬁg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
http_startwb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
https_defport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
https_listen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
https_port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
5.3 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
5.4 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
5.4.1 HTTP client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
delcookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
ﬁndcookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
httpcancel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
httpdel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
httpget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
httpgetheader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
httphead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
httppost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
httpput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
httpreason . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

Fair Isaac Corporation Conﬁdential and Proprietary Informationv

Contents

loadcookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
savecookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setcookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
tcpping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
urlencode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.4.2 HTTP server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httppending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpqueueinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreplycode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreplyjson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqcookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqﬁle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqfrom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqheader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqlabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqpop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqpush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqpushlim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpreqtype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpstartsrv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
httpstopsrv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
jsonwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mksetcookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.5 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.5.1 Driver url . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

197
198
199
200
201
202
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
224

6 mmjava
225
6.1 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
6.1.1 Driver java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
6.1.2 Driver jraw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
7 mmjobs
227
7.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
7.2 Data sharing between models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
7.3 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
conntmpl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
nodenumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
defaultnode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
jobid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
parentnumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
keepalive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
fsrvport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
fsrvdelay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
fsrvnbiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
sshcmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
7.4 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
7.4.1 Mosel instance management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
disconnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
clearaliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
getbanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
gethostalias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
getaliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

Fair Isaac Corporation Conﬁdential and Proprietary Informationvi

Contents

sethostalias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ﬁndxsrvs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.4.2 Model management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
compile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
detach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setdefstream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
resetmodpar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setcontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setmodpar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setworkdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdsoprop, getdsopropnum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getgid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getmodprop, getmodpropnum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getnode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getrmtid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getstatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getuid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getexitcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
unload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getannidents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getannotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.4.3 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
canceltimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
settimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setuid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setgid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
waitexpired . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
waitfor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
waitforend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getnextevent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dropnextevent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isqueueempty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
nullevent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getfromid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getfromgid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getfromuid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
peeknextevent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5.1 Driver shmem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5.2 Driver mempipe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5.3 Driver rcmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5.4 Driver xsrv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5.5 Driver xssh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5.6 Driver rmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.6 The Mosel Remote Launcher xprmsrv . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Fair Isaac Corporation Conﬁdential and Proprietary Information

239
240
241
242
244
245
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
277
278
279
280
281
282
283
284
285
286
287
288
289
289
289
290
290
290
291
291

vii

Contents

7.6.1

7.6.2

Running the xprmsrv command . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.6.1.1 Main command line options . . . . . . . . . . . . . . . . . . . . . . . . . .
7.6.1.2 Secure server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.6.1.3 Private key management . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.6.1.4 Mode of operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conﬁguration ﬁle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.6.2.1 Access control list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

291
291
293
293
293
294
296

8 mmnl298
8.1 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
8.1.1 The problem type mpproblem.nl . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
8.1.2 The type nlctr and its operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
8.1.3 Setting initial values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
8.1.4 Example: using mmnl for QCQP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
8.2 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
clearinitvals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
copysoltoinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
setinitval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
getsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
ishidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
sethidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
gettype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
setname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
settype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
9 mmoci
310
9.1 Prerequisite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
9.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
9.3 Data transfer between Mosel and Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
9.3.1 From Oracle to Mosel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
9.3.2 From Mosel to Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
9.4 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
OCIautocommit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
OCIautondx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
OCIbufsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
OCIcolsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
OCIconnection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
OCIdebug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
OCIﬁrstndx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
OCIndxcol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
OCIrowcnt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
OCIrowxfr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
OCIsuccess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
OCItruncsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
OCIverbose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
9.5 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
OCIlogon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
OCIlogoff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
OCIexecute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
OCIreadinteger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
OCIreadreal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
OCIreadstring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
OCIcommit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
OCIrollback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
9.6 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

Fair Isaac Corporation Conﬁdential and Proprietary Informationviii

Contents

9.6.1

Driver oci . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

10 mmodbc
329
10.1 Prerequisite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
10.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
10.3 Data transfer between Mosel and the database . . . . . . . . . . . . . . . . . . . . . . . . 330
10.3.1 From the database to Mosel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
10.3.2 From Mosel to the database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
10.4 ODBC and MS Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
10.5 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
SQLautocommit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
SQLautondx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
SQLbufsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
SQLcolsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
SQLconnection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
SQLdebug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
SQLdm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
SQLextn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
SQLﬁrstndx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
SQLndxcol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
SQLrowcnt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
SQLrowxfr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
SQLsuccess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
SQLtruncsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
SQLverbose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
10.6 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
SQLcolumns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
SQLcommit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
SQLconnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
SQLdisconnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
SQLexecute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
SQLparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
SQLgetparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
SQLindices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
SQLprimarykeys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
SQLreadinteger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
SQLreadreal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
SQLreadstring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
SQLrollback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
SQLtables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
SQLupdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
10.7 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
10.7.1 Driver odbc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
11 mmquad359
11.1 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
11.1.1 The type qexp and its operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
11.1.1.1 Example: using mmquad for Quadratic Programming . . . . . . . . . . . 359
11.1.2 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
exportprob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
getsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
11.2 Published library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
11.2.1 Complete module example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
11.2.2 Description of the library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
getqexpsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366

Fair Isaac Corporation Conﬁdential and Proprietary Informationix

Contents

getqexpstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
clearqexpstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
getqexpnextterm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
12 mmrobust
370
12.1 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
12.1.1 The problem type mpproblem.xprs.robust . . . . . . . . . . . . . . . . . . . . 370
12.1.2 The type uncertain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
12.1.3 The type robustctr and its operators . . . . . . . . . . . . . . . . . . . . . . . . . 371
12.1.4 The type uncertainctr and its operators . . . . . . . . . . . . . . . . . . . . . . 371
12.1.5 Example: using mmrobust for solving a robust problem . . . . . . . . . . . . . . . . 371
12.2 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
robust_uncertain_overlap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
robust_check_feas_uncertainty_set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
robust_check_feas_original_problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
12.3 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
cardinality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
getsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
getact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
ishidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
sethidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
getnominal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
gettype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
setnominal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
settype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
13 mmsheet
384
13.1 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
13.1.1 Driver excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
13.1.2 Driver xls/xlsx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
13.1.3 Driver csv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
14 mmssl
388
14.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
14.1.1 Document encryption in Mosel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
14.1.2 The mmssl command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
14.2 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
https_cacerts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
https_ciphers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
https_cltcrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
https_cltkey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
https_srvcrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
https_srvkey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
https_trustsrv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
ssl_cipher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
ssl_digest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
ssl_dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
ssl_privkey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
14.3 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
RSAﬁngerprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
RSAgenkey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
RSAgetkeysize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
RSAisprivate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
RSAloadkey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399

Fair Isaac Corporation Conﬁdential and Proprietary Informationx

Contents

RSApubdecrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RSAprivdecrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RSAprivencrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RSApubencrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RSAsavekey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
msgdigest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
msgsign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
msgverify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sslivsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sslkeysize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sslmdsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sslrandom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sslrandomdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
x509check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
x509getinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
x509newcrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.4 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.4.1 Driver base64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.4.2 Driver hex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.4.3 Driver crypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.4.4 Driver hmac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
416
416
416
417

15 mmsvg
418
15.1 SVG graph structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
15.1.1 Object groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
15.1.2 SVG styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
15.1.3 Interaction with the graphical display . . . . . . . . . . . . . . . . . . . . . . . . . . 420
15.1.4 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
15.2 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
MMSVGDISPLAY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
MMSVGTGZ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
15.3 Procedures and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
svgaddgroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
svgaddarrow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
svgaddcircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
svgaddellipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
svgaddﬁle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
svgaddimage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
svgaddline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
svgaddpie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
svgaddpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
svgaddpolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
svgaddrectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
svgaddtext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
svgaddxmltext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
svgclosing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
svgcolor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
svgdelobj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
svgerase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
svggetgraphstyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
svggetgraphstylesheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
svggetgraphviewbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
svggetlastobj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
svggetstyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
svggetstylesheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446

Fair Isaac Corporation Conﬁdential and Proprietary Informationxi

Contents

svgpause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgrefresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetgraphlabels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetgraphpointsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetgraphscale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetgraphstyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetgraphstylesheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetgraphviewbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetreffreq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetstyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgsetstylesheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgshowgraphaxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
svgwaitclose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

447
448
449
450
451
452
453
454
455
456
457
458
459
460

16 mmsystem461
16.1 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
16.1.1 The type text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
16.1.2 The type date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
16.1.3 The type time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
16.1.4 The type datetime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
16.1.5 The type parsectx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
16.1.6 The type textarea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
16.2 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
datefmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
timefmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
datetimefmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
monthnames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
sys_endparse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
sys_ﬁllchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
sys_pid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
sys_qtype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
sys_regcache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
sys_sepchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
sys_trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
sys_txtmem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
16.3 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
addmonths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
compareic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
copytext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
cuttext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
deltext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
endswith . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
erase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
expandpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
fcopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
fdelete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
ﬁndﬁles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
ﬁndtext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
fmove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
formattext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
getasnumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
getchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
getcwd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
getdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

Fair Isaac Corporation Conﬁdential and Proprietary Informationxii

Contents

getday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdaynum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdirsep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdsoparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getendparse, setendparse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getenv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getfsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getfstat, getﬂstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getftime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gethour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getminute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getmonth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getmsec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getoserror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getoserrmsg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getpathsep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsucc, setsucc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getqtype, setqtype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsecond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsepchar, setsepchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getstart, setstart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsysinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsysstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettmpdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettrim, settrim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getweekday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getyear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
inserttext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isvalid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
jointext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
makedir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
makepath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
newtar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
newzip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
nextﬁeld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
openpipe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
parseextn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
parseint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
parsereal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
parsetext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
pastetext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
pathmatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
pathsplit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
qsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
quote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
readlink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
readtextline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
regmatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
regreplace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
removedir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
removeﬁles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Fair Isaac Corporation Conﬁdential and Proprietary Information

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
532
533
535
536
537
538
540
541
542
543
545
546
547
548

xiii

Contents

setdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setdsoparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setenv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setoserror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sethour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setminute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setmonth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setmsec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setsecond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
settime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setyear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
splittext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
startswith . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
symlink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
tarlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
textfmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
tolower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
toupper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
untar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
unzip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ziplist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
16.4 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
16.4.1 Driver text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
16.4.2 Driver pipe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
16.5 Published library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
16.5.1 Description of the library functions . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
settime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdatetime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setdatetime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettxtsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettxtbuf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
txtresize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
569
570
571
572
573
574
575
575
575
576
576
578
579
580
581
582
583
584
585
586

17 mmxml
587
17.1 Document representation in mmxml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
17.1.1 Data model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
17.1.2 Paths in a document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
17.1.2.1 Axis speciﬁer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
17.1.2.2 Node test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
17.1.2.3 Abbreviated notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
17.1.2.4 Predicate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
17.1.3 JSON document as an XML tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
17.2 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
17.2.1 The type xmldoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
17.3 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
addnode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
copynode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
delattr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597

Fair Isaac Corporation Conﬁdential and Proprietary Informationxiv

Contents

delnode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getattr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
testattr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getencoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getﬁrstattr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getnext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getﬁrstchild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getlastchild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getnode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getnodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getparent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gettype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getstandalone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getxmlversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
gethspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getvspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getindentmode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getindentskip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getlinelen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getmaxnodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
jsonload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
jsonparse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
jsonsave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
save . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setattr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setencoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setmaxnodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sethspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setvspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setindentmode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setindentskip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setlinelen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setstandalone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setxmlversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xmlattr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xmlencode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xmldecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xmlparse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
624
625
626
627
628
629
630
631
632
634
635
636
637
638
639
640
641
642
643

18 mmxnlp
645
18.1 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
18.1.1 The userfunc type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
18.1.2 The tolset type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
18.1.3 The mpproblem.xprs.xnlp problem type . . . . . . . . . . . . . . . . . . . . . 646
18.2 mmxnlp and the other Mosel modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
18.2.1 Overloaded functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
18.2.2 Module compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
18.3 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
XNLP_AUTOELIM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648

Fair Isaac Corporation Conﬁdential and Proprietary Information

xv

Contents

XNLP_LOADASNL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XNLP_LOADNAMES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XNLP_NLPSTATUS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XNLP_SOLVER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XNLP_VERBOSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
18.4 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
addmultistart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
chgdeltatype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
generateUFparallel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
printmodelmemory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
printmodelscaling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setcallback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setcomplementary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setdelayedctr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setdefvar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setdetrow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setenforcedctr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setinitsb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
settol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
settolset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
userfuncDLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
userfuncExcel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
userfuncExcelMacro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
userfuncinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
userfuncMosel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
validate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
18.5 Error codes issued by mmxnlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

648
649
649
649
650
650
652
653
654
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674

19 mmxprs
676
19.1 New functionality for the Mosel language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
19.1.1 The problem type mpproblem.xprs . . . . . . . . . . . . . . . . . . . . . . . . . . 676
19.1.2 The type basis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
19.1.3 The type mpsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
19.1.4 The type logctr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
19.2 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
XPRS_colorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
XPRS_enumsols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
XPRS_enummaxsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
XPRS_enumduplpol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
XPRS_fullversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
XPRS_loadnames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
XPRS_problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
XPRS_probname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
XPRS_verbose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
19.3 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
addmipsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
basisstability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
calcsolinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
clearmipdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
clearmodcut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
copysoltoinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
crossoverlpsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
defdelayedrows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691

Fair Isaac Corporation Conﬁdential and Proprietary Information

xvi

Contents

defsecurevecs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
estimatemarginals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ﬁxglobal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getbstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getdualray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getiis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getiissense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getiistype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getinfcause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getinfeas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getlb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getloadedlinctrs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getloadedmpvars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getprimalray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getprobstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getrange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsensrng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getvars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
hasfeature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
implies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
indicator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isiisvalid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
isintegral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
loadbasis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
loadlpsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
loadmipsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
loadprob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
maximize, minimize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
postsolve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
readbasis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
readdirs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
readsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
reﬁnemipsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
rejectintsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
repairinfeas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
resetbasis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
resetiis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
resetsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
savebasis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
savemipsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
savesol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
savestate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
selectsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setarchconsistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setbstat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setcallback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setcbcutoff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setgndata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setlb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setmipdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setmodcut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Fair Isaac Corporation Conﬁdential and Proprietary Information

692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
723
724
726
727
728
729
730
731
732
734
735
736
737
738
739
740
741
742
743
744
747
748
749
750
751

xvii

Contents

setsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
setucbdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
stopoptimize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
unloadprob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
uselastbarsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
writebasis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
writedirs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
writeprob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
writesol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
19.4 Cut Pool Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
addcut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
addcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dropcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getcnlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
getcplist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
loadcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
storecut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
storecuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772

20 python3773
20.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
20.1.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
20.1.2 Windows Anaconda Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
20.1.3 Linux Anaconda Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
20.1.4 Python initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
20.1.5 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
20.2 Xpress Insight conﬁguration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 776
20.3 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
pyinitverbose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
pyusepandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
20.4 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
pycall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
pyexec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
pyget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
pygetdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
pyinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
pyinitpandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
pyrun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
pyset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
pysetdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
pyunload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
20.5 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
20.5.1 Driver python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
20.5.1.1 Type mapping to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
20.5.1.2 Type mapping from Python . . . . . . . . . . . . . . . . . . . . . . . . . . 792
20.6 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
21 R
795
21.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
21.1.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
21.1.2 R initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
21.1.3 Memory limit on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796

Fair Isaac Corporation Conﬁdential and Proprietary Information

xviii

Contents

21.1.4 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21.3 Control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rverbose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rinteractive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rusemosstreams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rcleanscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Runloadscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rsessionmode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21.4 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Reval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rfree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rgetarr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rgetbool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rgetint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rgetreal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rgetstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rsetdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rsource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rerrcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rerrmsg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rclearerr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21.5 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21.5.1 Driver rws . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21.6 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

797
799
800
801
801
801
801
802
802
802
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
819
819

22 zlib821
22.1 I/O drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
22.1.1 Driver gzip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
22.1.2 Driver deflate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
22.1.3 Driver zip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821

Appendix823

A Syntax diagrams for the Mosel language
824
A.1 Main structures and statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
A.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 828
A.3 Initializations data ﬁle format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
B Remote Invocation Protocol
832
B.1 Instance control parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832
B.2 mcmd pseudo ﬁle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
B.3 Proﬁler interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
B.4 Debugger interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
C Error messages
839
C.1 General errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839
C.2 Parser/compiler errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
C.2.1 Errors related to modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
C.2.2 Errors related to packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
C.3 Runtime errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
C.3.1 Initializations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849

Fair Isaac Corporation Conﬁdential and Proprietary Informationxix

Contents

C.3.2 General runtime errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 850
C.3.3 BIM reader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 852
C.3.4 Module manager errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
D Contacting FICO
854
Product support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854
Product education . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854
Product documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854
Sales and maintenance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
Related services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
FICO Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
About FICO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855

Index

Fair Isaac Corporation Conﬁdential and Proprietary Information

856

xx

CHAPTER 1

Introduction
1.1

What is Mosel?
Mosel is an environment for modeling and solving problems. To this aim, it provides a language that isboth a modeling and a programming language. The originality of the Mosel language is that there is no
separation between a modeling statement (e.g. declaring a decision variable or expressing a
constraint) and a procedure that actually solves the problem (e.g. call to an optimizing command).
Thanks to this synergy, one can program a complex solution algorithm by combining modeling andsolving statements.
Each category of problem comes with its own particular types of variables and constraints and a single
kind of solver cannot be efﬁcient in all cases. To take this into account, the Mosel system does not
integrate any solver by default but offers a dynamic interface to external solvers provided as modules.
Each solver module comes with its own set of procedures and functions that directly extends the
vocabulary and capabilities of the Mosel language. The link between Mosel and a solving module isachieved at the memory level and does not require any modiﬁcation of the core system.
This open architecture can also be used as a means to connect Mosel to other software. For instance,a module could deﬁne the functionality required to communicate with a speciﬁc database.
The modeling and solving tasks are usually not the only operations performed by a software
application. This is why the Mosel environment is provided either in the form of libraries or as astandalone program.

1.2

General organization
As input, Mosel expects a text ﬁle containing the source of the model/program to execute (henceforth
we use just the term ’model’ for ’model/program’ except where there might be an ambiguity). This
source ﬁle is ﬁrst compiled by the Mosel compiler. During this operation, the syntax of the model ischecked but no operation is executed. The result of the compilation is a BInary Model (BIM) that issaved in a second ﬁle. In this form, the model is ready to be executed and the source ﬁle is not required
any more. To actually ’run’ the model, the BIM ﬁle must be read in again by Mosel and then executed.
These different phases are handled by different modules that comprise the Mosel environment:
The runtime library: This library contains the VIrtual MAchine (VIMA) interpreter. It knows how to loada model in its binary format and how to execute it. It also implements a model manager (for handlingseveral models at a time) and a Dynamic Shared Objects manager (for loading and unloading modules
required by a given model). All the features of this library can be accessed from a user application.
The compiler library: The role of this module is to translate a source ﬁle into a binary format suitablefor being executed by the VIMA Interpreter.
The standalone application: The ’mosel’ application, also known as ’Mosel Console’, is a command line

Fair Isaac Corporation Conﬁdential and Proprietary Information

1

Introduction

interpreter linked to the two previous modules. It provides a single program to compile and executemodels.
Various modules: These modules complete the Mosel set of functionalities by providing, for instance,
optimization procedures. As an example, the mmxprs module extends the Mosel language with theprocedure maximize that optimizes the current problem using the Xpress Optimizer.
This modularized structure offers various advantages:












1.3

Once compiled, a model can be run several times, for instance with different data sets, without
the need for recompiling it.
The compiled form of the program is system and architecture independent: it can be run on any
operating system equipped with the Mosel runtime library and any modules required.
The BIM ﬁle can be generated in order to contain no symbols at all. It is then safe, in terms ofintellectual property, to distribute a model in its binary form.
As a library, Mosel can be easily integrated into a larger application. The model may be provided
as a BIM ﬁle and the application only linked to the runtime library.
The Mosel system does not integrate any kind of solver but is designed in a way that a module
can provide solving facilities. The direct consequence of this is that Mosel can be linked todifferent solvers and communicate with them directly through memory.
This open architecture of Mosel makes extensions of the functionality possible on a case by casebasis, without the need to modify the Mosel internals.

Running Mosel
The Mosel environment may be accessed either through its libraries or by means of two applications,perhaps the simplest of which is Xpress Workbench, a development studio type environment forworking with your Mosel models. Xpress Workbench is a complete modeling and optimization
development environment that presents Mosel in an easy-to-use graphical interface with a built-in text
editor.
In its standalone version, Mosel offers a simple interface to execute certain generic commands directlyfrom the command prompt (or shell) of the operating system. The user may compile or execute source
models or programs (.mos ﬁles), run binary models (.bim ﬁles) or retrieve information related to theMosel environment itself (like properties of modules or version number of the system). An interactive
debugger as well as a proﬁler are also included: the debugger allows to execute the model step by step,
specify breakpoints from where status of the model can be examined. Running a model with the
proﬁler provides detailed information on what part of the code is actually executed and how much timeeach statement requires. This information may be helpful for optimizing the model (by locating hot
spots where the code is using a great deal of computer time) and also for building testsuites (bychecking whether the data sets used in the test set exercise all statements of a given model).

1.3.1

mosel command: invocation
The mosel executable is typically used with the following syntax from an operating system console:mosel command [-l lang] [-d dir] [-tf trf] [-sdm sdm] [-sr rst][-dp dsopath] [-bx bimpfx] cmd_args

Where the option -l selects the language for message translation (see Section 2.21); the option -dsets the working directory of the process; the option -tf deﬁnes a trace ﬁle (see command trace

Fair Isaac Corporation Conﬁdential and Proprietary Information2

Introduction

below); the option -sdm speciﬁes the maximum size of stack dumps (displayed when a model
terminates on a runtime error, this can also be set via the environment variable MOSEL_SDMAX, thedefault value of 0 disables the display of the stack trace); the option -sr deﬁnes the active restrictions(see Section 1.3.4) and -dp specify an initial DSO path (to locate modules and packages) while -bx
sets a list of bim ﬁle preﬁxes (used to ﬁnd packages, see Section 2.3.1). Both options -dp and -bx
might be stated several times, the resulting setting will correspond to the concatenation of the provided
values separated by the appropriate symbol. The command parameter is one of the following
commands and cmd_args are the associated arguments that must be stated after the options
described above (square brackets indicate optional arguments):
comp[ile] [-gGIpwiwenixSETVFD] [-pwd pwd] [-pk priv] [-k|-kf pub][-ix incpfx] [-o outf] [-c usrcom] src [src2 ...]
Compile the model src and generate the corresponding Binary Model (BIM) ﬁle if thecompilation succeeds. The extension .mos is appended to src if no extension is provided. If
option ’-o outf’ (ﬁlename to use for saving BIM ﬁle) is not given, the extension .bim is used toform the name of the binary ﬁle. The ﬂag ’-g’ adds debugging information: private object names(e.g. variables, constraints) are included in the BIM ﬁle as well as required information forlocating runtime errors. The ﬂag ’-G’ adds both debugging and tracing information: it is required
to run the model with the debugger. When the ’-G’ ﬂag is used, the compiler adds instructions in
the generated code that may slow down execution speed of the model. The ﬂag ’-I’ may also be
added to enable the xbim extension (see Section 2.3.3). The ﬂag ’-D’ enables generation of
documentation annotations in the resulting BIM ﬁle (by default documentation annotations are
ignored). With the ﬂag ’-wi’, the compiler emits a warning message each time a symbol is
implicitly declared and the ﬂag ’-ni’ disables implicit declarations (see Section 2.8.1.3). Whenthe ﬂag ’-we’ is used warnings are handled like errors such that any warning will make thecompilation fail. The option ’-c usrcom’ may be used to add a commentary to the BIM ﬁle (seedebugger command LSMODS). The option ’-ix’ deﬁnes the ﬁle name preﬁx for ﬁle inclusion (seeSection 2.5.2). If the ﬂag ’-p’ is selected, only the syntax of the source ﬁle is checked, thecompilation is not performed and no output ﬁle is generated.
The ﬂag ’-x’ will be used to generate a POT ﬁle (Portable Object Template) for message
translation (see Section 2.21).
The other options are related to handling encrypted or signed BIM ﬁles (see Section 1.3.5):
option ’-S’ will be used to produce a signed ﬁle. Unless the option ’-pk’ is speciﬁed, the default
private key personal.key (see ssl_dir) is used for the signature. The options ’-V’ and ’-T’
control how to handle signed packages: by default signature of packages is ignored but, if theﬁrst option is used, the signature is checked and the loading fails if it cannot be veriﬁed. With
option ’-T’, only signed packages with a valid signature can be used (i.e. packages without
signature are not allowed). Public keys that are required for the veriﬁcation are searched for in
the default public keys directory pubkeys (see ssl_dir).
BIM ﬁle encryption is enabled by the ’-E’ option: the encryption key is either deduced from thepassword stated via option ’-pwd’ (if the ﬂag ’-F’ is active, the value of ’-pwd’ is interpreted as atext ﬁle the ﬁrst line of which is the password) or generated randomly. Optionally, the encryption
key can be stored in the BIM ﬁle itself in encrypted form (this is required if it has been randomly
generated): in this case the encryption requires public keys of the recipients of the BIM ﬁle (whowill be able to decrypt the ﬁle using their own private keys). Public keys can be listed by using
the ’-k’ or ’-kf’ options: in the ﬁrst case, one public key is listed at a time (the ’-k’ parameter
may be used several times) and in the second case a ﬁle containing a list of keys is speciﬁed.
Each line of this ﬁle is interpreted as a key ﬁle name (except empty lines or lines starting with ’!’
or ’#’ that are ignored). Unless they include a path speciﬁcation, key ﬁles are considered to belocated in the default public keys directory (for instance the key ﬁle "somekey" is searched in
the public keys directory but the ﬁle "./somekey" comes from the current working directory).
An encrypted BIM ﬁle can always be decrypted by its creator thanks to his private key.
Several source ﬁles may be passed to the compiler command in a single step (this is notcompatible with option ’-o’): each ﬁle gets compiled individually.

Fair Isaac Corporation Conﬁdential and Proprietary Information

3

Introduction

run [-TVF] [-pwd pwd] [-pk priv] [-k|-kf pub] [-is in] [-os out] [-es err][-dbg|-prof|-cov|-trac] [-sdir dir] [-nl] bim [param=value [...]]
Load the provided BIM ﬁle bim and then run it. Options ’-is in’, ’-os out’ and ’-es err’ canbe speciﬁed to deﬁne alternative default input, ouput and error streams to be used by Mosel.
With option ’-prof’ or ’-cov’ the model is run through the proﬁler (see commands profileand coverage below), the option ’-trac’ activates the tracing mode (see command trace)
and with option ’-dbg’ it is passed to the interactive debugger (see command debug). The
option ’-sdir’ can be used in addition to the proﬁler or debugger to indicate alternative
locations for source ﬁles (this option may be stated several times).
The options ’-V’ and ’-T’ control how to handle signed BIM ﬁles (see Section 1.3.5): by default
signature of ﬁles is ignored but, if the ﬁrst option is used, the signature is checked and theloading fails if it cannot be veriﬁed. With the second option, only signed BIM ﬁles with a valid
signature can be used (i.e. ﬁles without signature are not allowed). For this veriﬁcation task
public keys are usually searched for in the default public keys directory pubkeys (see ssl_dir)
but alternatively a list of expected keys may be speciﬁed with the ’-k’ or ’-kf’ options: in the ﬁrst
case, one public key is listed at a time (the ’-k’ parameter may be used several times) and in thesecond case a list of keys is read from the given ﬁle. Each line of this ﬁle is interpreted as a key
ﬁle name (except empty lines or lines starting with ’!’ or ’#’ that are ignored). Unless they include
a path speciﬁcation, key ﬁles are considered to be located in the default public keys directory(for instance the key ﬁle "somekey" is searched in the public keys directory but the ﬁle"./somekey" comes from the current working directory). Moreover, the special ﬁle name ⁎implies that keys stored in the default location can also be used.
The options ’-pwd’ and ’-pk’ may be required to load an encrypted BIM ﬁle: the former deﬁnes
the password to use (if the ﬂag ’-F’ is active, the value of ’-pwd’ is interpreted as a text ﬁle theﬁrst line of which is the password) and the option ’-pk’ servers to specify a private key ﬁle (to be
used in place of the default personal.key in ssl_dir).
Optionally, a list of parameter values may be provided in order to initialize the run-timeparameters of the model and/or the control parameters of the modules used. The syntax ofsuch an initialization is param_name = value for a model parameter anddsoname.ctrpar_name = value for a control parameter, where dsoname is the name of amodule and ctrpar_name the control parameter to set.
The option ’-nl’ can be used when running the debugger on Unix/Linux systems to deactivate
the command history if the terminal is not properly handled by the command history mechanism.
exec[ute] [compile_opts] [run_opts] src [param=value [...]]
Compile src, load, and then run the model. This command is equivalent to the consecutive
execution of compile and run except that no BIM ﬁle is generated. All options documented for
both, compile and run, can be used with this command. The use of option ’-prof’, ’-cov’ or’-trac’ implies the compiler ﬂag ’-G’ and the use of option -dbg will also add compiler ﬂag ’-G’
if ﬂag ’-g’ is not explicitly speciﬁed.
debug [compile_opts] [run_opts] src [param=value [...]]
This command is equivalent to ’execute -dbg’, the model is compiled and then run throughthe interactive debugger. If the model is compiled with ﬂag ’-G’ (the default with this command),the execution is immediately suspended before the ﬁrst statement. Otherwise the execution
starts as usual but can be suspended by pressing ctrl-C. Note that if a critical operation is being
processed, the interruption is delayed until the operation completes (for instance, the Optimizer
cannot be interrupted during an iteration of its algorithm). Execution is suspended once morejust before the program terminates: this makes it possible to inspect model data before the endof execution. Refer to the Section 1.3.2 below for further information on the use of the debugger.
prof[ile] [compile_opts] [run_opts] src [param=value [...]]
This command is equivalent to ’execute -prof’, the model is compiled and then run throughthe proﬁler. After execution, the total execution time and some source coverage information isdisplayed. Moreover a ﬁle sourceﬁle.prof is generated based on the original source ﬁle. Eachline of this ﬁle consists in:Fair Isaac Corporation Conﬁdential and Proprietary Information

4

Introduction








the number of times the corresponding statement has been executed;
the total amount of time (in seconds) or the percentage of the total execution time (ifoption ’-prof 2’ is used) spent on this particular line (this measure is not valid if thestatement is a recursive call);the elapsed time (in seconds) between the beginning of the execution and the last time theline was executed;
the text of the model source

All lines of the original source ﬁle are transferred, lines that do not correspond to the beginningof a statement are directly copied without further information.
If the model runs additional submodels via mmjobs, a report for each model execution is also
displayed and the associated annotated ﬁles are generated in a similar way as for the mainmodel.
cover[age] [compile_opts] [run_opts] src [param=value [...]]
This command is equivalent to ’execute -cov’, the model is compiled and then run throughthe proﬁler. The difference with the proﬁle command described above is the type of reports
generated: the ﬁles produced are taking the .cov extension and only collect the number of times
each statement has been executed (if option ’-cov 2’ is used it is 0 or 1). Moreover existing ﬁles
are updated instead of being replaced (i.e. iteration counts of each statement are added up).
trace [compile_opts] [run_opts] src [param=value [...]]
This command is equivalent to ’execute -trac’, the model is compiled and then run in tracing
mode: the activity of the program is logged in a trace ﬁle that is automatically generated or
extended (if the ﬁle already existed). The ﬁle name for this report is either deﬁned using the ’-tf’
option or taken from the environment variable MOSEL_TRFILE. In both cases a question mark inthe ﬁle name will be replaced by the process ID expressed in hexadecimal. If no trace ﬁle isdeﬁned the default name ’tmpdir/xprm_?.trac’ will be used (’tmpdir’ being the
temporary directory of the system). Refer to the Section 1.3.3 below for further information on
the trace ﬁle.
exam[ine] [-pwd pwd] [-pk priv] [-cspthHirvaumLVF] [mod|pkg [mod|pkg...]]
Display the list of constants, procedures/functions, types, IO drivers, control parameters andannotations of modules, packages or the Mosel core library. By default required packages are
not loaded (but modules are loaded): using option ’-L’ will force loading of all dependencies. To
load only the header of the bim ﬁle to check its dependencies use option ’-H’. Optional ﬂags may
be used to select which type of information is displayed: ’-h’ for general information, ’-c’ forconstants, ’-s’ for subroutines, ’-v’ for variables, ’-r’ for requirements, ’-t’ for types, ’-i’ for IO
drivers, ’-p’ for control parameters and ’-a’ for annotations. By default, listings are sorted inalphabetical order, option ’-u’ disables sorting. If both, a package and a module of the same
name, are available only the information relating to the package is displayed. To select either the
package or the module, extension .bim or .dso can be appended to the library name. If the ﬂag’-m’ is used and no package or module can be located then a binary model ﬁle is searched for in
the current working directory. The displayed information is related to the Mosel core library if noname is speciﬁed with the command.
The option ’-V’ can be added for checking the signature of signed BIM ﬁles (the result of theveriﬁcation is reported in the header output). The options ’-pwd’ and ’-pk’ may be required toload an encrypted BIM ﬁle: the former deﬁnes the password to use (if the ﬂag ’-F’ is active, thevalue of ’-pwd’ is interpreted as a text ﬁle the ﬁrst line of which is the password) and the second
option speciﬁes a private key ﬁle (to be used in place of the default personal.key in
ssl_dir).
lslib [-p|-m]
Display a list of available modules and packages. Use the optional ﬂag ’-p’ to list only packages
and ’-m’ to get modules only.

Fair Isaac Corporation Conﬁdential and Proprietary Information

5

Introduction

If none of the above keywords is recognized, the ﬁrst argument of the command is interpreted as a
Mosel ﬁle. In the case of a BIM ﬁle, the command ’run’ is executed; otherwise the ﬁle name is passed
to the command ’execute’.
The mosel command may also be started using only ﬂags. Besides options ’-V’ (Mosel version
information) and ’-h’ (short help message), all other options relate to starting Mosel in server mode
when it is invoked from a remote instance: they should not be used directly (see the documentation ofmodule mmjobs in Chapter 7 for further explanations).
After the completion of a command the mosel executable returns a non-zero status to the operating
system in case of error and the execution status of the model if a model has been run (e.g. with thecommand execute). This execution status is the value provided via the procedure exit in the model(by default this is 0).
Some examples:
Execute model ’mymodel.mos’ setting values for the model parameters A,B,C and D> mosel mymodel A=33 B="word" C=true D=5.3e-5

Compile model ’m.mos’ located on a web service and store the bim ﬁle locally in compressed form
> mosel comp -o zlib.gzip:m.bim.gz mmhttp.url:http://websrv/m.mos

Run ’optmod.bim’ from the debugger enabling verbose mode of module ’mmxprs’> mosel run -dbg optmod mmxprs.XPRS_verbose=true

List all available modules and packages> mosel lslib

Display the list of subroutines deﬁned by ’mmxprs’> mosel exam -s mmxprs

Display all constants deﬁned in the Mosel language> mosel exam -c

Display version information of Mosel> model -V

1.3.2 mosel command: interactive debugger
When a model that is executed through the debugger is interrupted (for instance, because the user has
typed ctrl-C or an error has occured), the execution is suspended, the text source of the statement
being processed is displayed and an interactive session starts. This mode is signaled by the speciﬁc
prompt ’dbg>’ and the following commands may be entered (the arguments enclosed in square
brackets [] are optional). The command line interpreter is case-insensitive, although we display
commands in upper case for clarity:
BCONDITION bk [cond]Deﬁne or remove a condition on a breakpoint. This command may be used to put a condition(Boolean expression) on the speciﬁed break point: the execution is suspended at the

Fair Isaac Corporation Conﬁdential and Proprietary Information

6

Introduction

breakpoint only if the given condition is veriﬁed. To remove a condition previously set up, enter
this command without specifying any condition.
BREAK [procname]|[line [file]]
Install a breakpoint. When a breakpoint has been set up, execution is interrupted whenever thestatement corresponding to the speciﬁed location is reached. A procedure or function namemay be used as the location: in this case a breakpoint is installed at the beginning of eachprocedure or function of the provided name. If this command is used without parameters, thebreakpoint is deﬁned at the current location.
BREAKPOINTS
List the deﬁned breakpoints.
BREAKSUB [0|1]
Decide whether to suspend execution whenever a submodel is started.
CONTINUE
Resume execution. If the interruption was not due to an error, execution of the model
continues, otherwise the execution of the model is aborted and Mosel exits.
DELETE [bk]Delete a breakpoint.
DISPLAY [expression]
Record an expression to be displayed at every interruption. Used with no expression, thiscommand gives a list of all recorded expressions.
DOWN [nblev]
Go down in the calling stack. If an argument is provided, it indicates how many levels down togo (default is 1).
EXPORTPROB [-pms] [filename [objective]]
Display or save to the given ﬁle (option filename) the matrix corresponding to the active
problem. The matrix output uses the LP format (default) or the MPS format (ﬂag ’-m’). A
problem is available after the execution of a model. The ﬂags may be used to select thedirection of the optimization (’-p’: maximize), the ﬁle format (’-m’: MPS format) and whether
real object names should be used (’-s’: scrambled names — this is the default if the object
names are not available). The objective may also be selected by specifying a constraint name.
FINISH

Continue execution until the end of the current subroutine. The execution continues but will beinterrupted again after the subroutine terminates.

INFO [⁎|symbol [symbol...]]
Without arguments, this command displays information about the program being executed(this may be useful for problem reporting). Any speciﬁed argument is interpreted as a symbolfrom the current model. If the requested symbol exists in the model, this command displays
some information about its type and structure. Several symbols may be given in a single calland if ’⁎’ is used in place of a symbol name then the information is displayed for every
symbol of the model.
LIST [[start] nblines]
Display the source ﬁle that corresponds to the model being executed. When used with no extra
argument, this command lists 10 lines of the source model starting at the current statement;
used with a single positive parameter nblines, it displays nblines lines instead of the default 10
lines. If the parameter nblines is negative, it is interpreted as a starting point for the listing
relative to the current statement. When 2 parameters are used, the ﬁrst one is understood as
the ﬁrst line to display (a negative value is relative to the current line) and the second one as
the number of lines to display.
Examples (assuming current line is 5):

Fair Isaac Corporation Conﬁdential and Proprietary Information

7

Introduction>list>list 5>list -2
>list -2 5

displays lines 5 to 14
displays lines 5 to 9
displays lines 3 to 14
displays lines 3 to 7

LSATTR [typename]
Display the list of available attributes for all used native types or only those related to thespeciﬁed type typename
LSLIBS

Display the list of all loaded dynamic shared objects (DSO) together with, for each module, itsversion number and its number of references (i.e. number of loaded models using it).

LSLOCAL
Display the list of symbols deﬁned locally to the current context.
LSMODS

Display the list of all models currently loaded in core memory. The information displayed foreach model is:

name: the model name and version number (given by the model and version
statements in the source ﬁle);

number: the model number is automatically assigned when the model is loaded;

size: the amount of memory used by the model (in bytes);










system comment: a text string generated by the compiler indicating the source ﬁlename
and if the model contains debugging information and/or symbols;
user comment: the comment deﬁned by the user at compile time (cf. commandcompile);modules: the name and version number of each module required by the model;
pkg. req.: if the model is a package, the name and version number of each package
required by a model using this package;
pkg. imp.: the name and version number of each package included by this model.

The active model is marked by an asterisk (’⁎’) in front of its name.
LSSYMB [-cspou]
Display the list of symbols published by the current model. The optional ﬂags may be used toﬁlter what kind of symbol to display: ’-c’ for constants, ’-s’ for subroutines, ’-p’ forparameters and ’-o’ for everything else. By default the list is sorted in alphabetical order,
option ’-u’ disables sorting.
MODEL [modnum]
With no argument this command lists all models running concurrently. The active model(debugger commands are applied to this model) is identiﬁed by a star ("⁎"). If provided, theargument is interpreted as a model number that becomes the active model.
NEXT [line [file]]
Continue execution until the next statement. The execution continues but will be interrupted
again after the current statement has been completed. If a location information is provided (bymeans of a line number and, if necessary, a ﬁle name), the next interruption will occur before
the speciﬁed statement is executed.
OPTION name [[=] value]
View or change the value of a command line parameter. These parameters are used by thecommand line interpreter to display real values (especially in command PRINT):

realfmt: C-style format for printing ﬂoating point numbers (default value: "%.10g")

Fair Isaac Corporation Conﬁdential and Proprietary Information

8

Introduction

zerotol: zero tolerance to decide whether two values are equal (default value: 1e-13).
It is also used when printing very small numbers: if a value is smaller than zerotol, "0"is displayed instead.

Although these parameters have the same name and function as those used by Mosel whenrunning a model, they are not synchronised with their internal counterpart.
PRINT expression [>>filename]Evaluate then display the value of the given arithmetic or Boolean expression. For building theexpression, the following functions can be used: getparam, ceil, floor, round, abs,
getsize, getmodprop as well as all attributes (see LSATTR command above). In addition tothese Mosel functions, the interpreter implements getnbdim that returns the number ofdimensions of an array and getndx# that gets the index set of dimension number ’#’ of anarray (’#’ being an integer between 1 and the number of dimensions of the array).
get-functions may be called using the sufﬁx notation (e.g. getact(c) is equivalent to c.act).
Some functions can be applied to arrays: the result is the evaluation of the function for eachcell of the array. Symbols are expected to be fully qualiﬁed: even if a symbol is expressed
without namespace reference in the model source (thanks to the namespace search, see
Section 2.13) it is necessary to use its full name from the debugger. In particular private
symbols of packages must be preﬁxed by the package name (for instance the identiﬁer aa
declared in the package mypkg can be accessed using mypkg~aa). It is possible to report only
a part of a collection (array, set or list) by specifying range information. Ranges deﬁnitions
take one of these two forms:[ maxelt ]: get at most ’maxelt’ elements[ skip maxelt ]: get at most ’maxelt’ entries after skipping ’skip’ elements

Several range deﬁnitions may be speciﬁed (separated by blanks): they are used when
exploring complex structures (e.g. a list of list).
The display format of this command is compatible with the data ﬁle format of Mosel. Use theoperator >>ﬁlename to append output of the command to the ﬁle ﬁlename.
Examples:>print getsol(x) >> solfile.txt>print getact(C(1,"tut"))+c.size>print toto~a>print abs(mytol)>1>print myarray.ndx2 [3]

QUIT
STEP

Terminate the debug session. Model execution is aborted and Mosel exits.
Continue execution until the next statement stepping into procedures and functions. The
execution continues but will be interrupted again after the current statement has been
completed. If the current statement contains function or procedure calls, interruption will
happen in these procedures or functions.

UNDISPLAY [disp]
Remove an expression recorded with DISPLAY. If no parameter is provided, all recorded
expressions are removed, otherwise the parameter is understood as a record number.
UP [nblev]
Go up in the calling stack. If an argument is provided, it indicates how many levels up to go(default is 1). Note that expressions are evaluated according to the current stack frame. For
example, if variable i is deﬁned in procedure B and execution is suspended in procedure A
called by B; it is necessary to go up in the stack in order to view the value of i because it does
not exist in the current frame.

Fair Isaac Corporation Conﬁdential and Proprietary Information

9

Introduction

WHERE [nblev]
Display the calling stack. The calling stack corresponds to the sequence of procedure andfunction calls being processed. For instance assume the model calls procedure A which calls
procedure B and the execution is suspended in procedure B: the calling stack will contain 3
records (location where A is called, location where B is called and current statement).
If a command is not recognized, a list of possible keywords is displayed together with a short
explanation. The command names can be shortened as long as there is no ambiguity (e.g. un can beused in place of UNDISPLAY but u is not sufﬁcient because it could equally denote the UP command).
String arguments (the parameter 10 is a number, but "10" or ’10’ are text strings) may be quoted
with either single or double quotes. Quoting is required if the text string starts with a digit or contains
spaces and/or quotes.
Execution step by step and breakpoints can be used only if the model has been compiled using option-G. In this case, before the execution starts, a breakpoint is automatically put at the ﬁrst statement of
the model. Otherwise (model has been compiled with option -g), the model will be interrupted only if
an error occurs or keys ctrl-C are pressed.
When debugging a model that runs submodels via mmjobs a message is displayed each time asubmodel starts or terminates. Moreover, interrupting the execution of the model also suspends theexecution of all submodels: the entered commands are applied to the selected active model, the choiceof which can be changed with the command MODEL.
A program may interrupt its execution and trigger the interactive debugger by using the following
special annotation (See section 2.14):!@mc.dbgmsg break

When the program is compiled with tracing information (option -G) this annotation is replaced by aspecial instruction that will cause an interruption when the program is being run through the debugger(otherwise it is silently ignored).

1.3.3 mosel command: tracing mode
Running a program in tracing mode results in the generation of a trace ﬁle that collects the activity of the
program. Each record of this ﬁle consists in a single line of text that can take the following forms:
0O timestamp
The ﬁle has been open
0C timestamp
The ﬁle has been closed
mmS timestamp modelname
The model number mm with name modelname is starting. Line tracing is enabled
mmTrr timestamp modelname
The model number mm with name modelname is ﬁnishing, its status code is rr
mm- timestamp msg
The model number mm has disabled line tracing (with optional message msg), submodels are
not affected
mm+ timestamp msg
The model number mm has enabled line tracing (with optional message msg), submodels are
not affected
mm! timestamp msg
The model number mm logs message msg

Fair Isaac Corporation Conﬁdential and Proprietary Information

10

Introduction

mmLpp timestamp
The model number mm is loaded by model number pp
mmUpp timestamp
The model number mm is unloaded by model number pp
mm:nn fname
The model number mm is executing the statement at line nn of ﬁle fname (that becomes thecurrent ﬁle for this model). These records are not emitted when line tracing is disabled.
mm nn
The model number mm is executing the statement at line nn of current ﬁle as speciﬁed
previously for the given model These records are not emitted when line tracing is disabled.
A program may control the behaviour of the tracer using the special annotation mc.dbgmsg (Seesection 2.14). The following annotations are interpreted:!@mc.dbgmsg traceoff msg!@mc.dbgmsg traceon msg!@mc.dbgmsg tracelog msg

When the program is compiled with tracing information (option -G) this annotation is replaced by aspecial instruction that communicates with the tracer (it is silently ignored if the program is not run intracing mode). The ﬁrst syntax disables the line tracing (it is active by default), the second has the
opposite effect while the last syntax makes it possible to insert a message in the trace ﬁle. In all cases
the message text msg is optional.

1.3.4 mosel command: restricted mode
Mosel may be run in restricted mode: by selecting which restrictions are to be applied, it is possible tocontrol what operations models can perform (in particular regarding disk access). Upon startup, if theoption -sr is not stated, the command line interpreter uses the value of the environment variable
MOSEL_RESTR for setting the execution restrictions. These restrictions are bit-encoded as an integer(each bit corresponding to a speciﬁc restriction) but restrictions can also be expressed by a list of one
or more of the following keywords (symbols are not case-sensitive and can be optionally separated by
spaces):
NoWrite (bit 0, value 1)
Disable write access on the local system. This restriction concerns all ﬁle access except
databases. Access to the temporary directory is not affected.
NoRead (bit 1, value 2)
Disable read access on the local system (this also implies NoWrite). This restriction
concerns all ﬁle access except databases. When this option is selected, the current working
directory is automatically set to the temporary directory (which can still be accessed).
NoExec (bit 2, value 4)
Disable external command execution. This restriction deactivates some procedures/functions
allowing execution of commands external to Mosel (for instance system or command). Also,
Mosel can only load modules from read-only locations when this restriction is active.
WDOnly (bit 3, value 8)
File access is limited to the current working directory and its subdirectories as well as thepaths speciﬁed by the environment variables MOSEL_RWPATH (for reading and writing) and
MOSEL_ROPATH (for reading only). The temporary directory can still be accessed.
NoTmp (bit 4, value 16)
Access to the temporary directory is disabled.

Fair Isaac Corporation Conﬁdential and Proprietary Information

11

Introduction

NoDB (bit 5, value 32)
Disable access to databases by blocking connection routines (e.g. SQLconnect or
OCIlogon).
For example, to disable write access and execution of external commands the environment variable
MOSEL_RESTR will have to be either the integer value 5 (1+4) or the string "NoWrite NoExec".
Restricted mode is observed by the Mosel core libraries (when accessing ﬁles and managing
directories) and the system requires that modules also satisfy the stated restrictions (althoughimplementation of restrictions may vary depending on the type of functionality provided by a given
module): a module that does not support the restricted mode of execution will fail to load when Mosel
is running in this mode.

1.3.5 mosel command: securing bim ﬁles
The bim ﬁle format is secure with respect to the intellectual property of the author of the model (i.e. it is
not possible to recover the original model from the bim ﬁle). However, further security mechanisms
may be required when a bim ﬁle is to be transferred over an insecure media (like the internet): inparticular it might be necessary to (1) make sure the ﬁle has not been modiﬁed during the transfer and(2) guarantee that only the addressee can access the ﬁle.
A digital signature ensures the ﬁrst requirement: it is computed using a private key (exclusively ownedby the sender of the document) such that any addressee having the corresponding public key (provided
by the sender) can, at the same time, verify that the document has been prepared by the sender andthat it has not been altered during the transfer. From the Mosel command line tool, creating a signed
bim ﬁle can be done by using the ’-S’ compiler option. When loading a signed bim ﬁle with the runcommand, it is required to enable the signature veriﬁcation with options ’-V’ or ’-T’ as veriﬁcation is not
performed by default.
The second requirement can be satisﬁed by encrypting the bim ﬁle such that it appears as random data
during the transfer. Mosel supports two kinds of encryption processes: it can use a usual password
based key. In this case the same password is used for both encrypting and decrypting the bim ﬁle (thesender and the recipient have to share this key). The alternative is to rely on private/public key pairs likefor the signature procedure outlined above: encryption is achieved with the public key of the adressee.
Only the recipient will be able to decrypt the bim ﬁle using his private key. From the Mosel commandline tool, creating an encrypted bim ﬁle can be done by using the ’-E’ compiler option. A password isspeciﬁed with the ’-pwd’ option otherwise the public keys of the recipients have to be stated with the’-k’ or ’-kf’ options (a bim ﬁle can be encrypted for up to 128 public keys).
Both signature and encryption require the management of private and public keys. These keys are
expected to be stored in a predeﬁned location speciﬁed by the module parameter ssl_dir.
Mosel relies on the RSA cryptographic system for the management of private/public key pairs (keysmust be of at least 1024bits). The signature procedure uses the SHA256 message digest algorithm.
Bim ﬁles are encrypted using the AES block cipher with keys of 128 bits.

1.4

References
Mosel could be described as an original combination of a couple of well known technologies. Here is a
non-exhaustive list of the most important ’originators’ of Mosel:The overall architecture of the system (compiler, virtual machine, native interface) is directly
inspired by the Java language. Similar implementations are also commonly used in the languages
for artiﬁcial intelligence (e.g. Prolog, Lisp).

Fair Isaac Corporation Conﬁdential and Proprietary Information

12

Introduction







1.5

The syntax and the major building blocks of the Mosel language are in some aspects a
simpliﬁcation and for other aspects extensions of the Pascal language.
The aggregate operators (like ’sum’) are inherited from the ’tradition of model builders’ and can befound in most of today’s modeling languages.
The dynamic arrays and their particular link with sets are probably unique to Mosel but are at their
origin a generalization of the sparse tables of the mp-model model builder.

Structure of this manual
The main body of this manual is essentially organized into two parts. In Chapter 2, the basic building
blocks of Mosel’s modeling and programming language are discussed.
Chapter 3 begins the reference section of this manual, providing a full description of all the functions
and procedures deﬁned as part of the core Mosel language. The functionality of the Mosel language
may be expanded by loading modules: the following chapters describe the modules currently provided
with the standard Mosel distribution.

Fair Isaac Corporation Conﬁdential and Proprietary Information

13

I. Core System

CHAPTER 2

The Mosel Language
The Mosel language can be thought of as both a modeling language and a programming language.
Like other modeling languages it offers the required facilities to declare and manipulate problems,decision variables, constraints and various data types and structures like sets and arrays. On the other
hand, it also provides a complete set of functionalities proper to programming languages: it iscompiled and optimized, all usual control ﬂow constructs are supported (selection, loops) and can beextended by means of modules. Among these extensions, optimizers can be loaded just like any othertype of modules and the functionality they offer may be used in the same way as any Mosel proceduresor functions. These properties make of Mosel a powerful modeling, programming and solving languagewith which it is possible to write complex solution algorithms.
The syntax has been designed to be easy to learn and maintain. As a consequence, the set of reserved
words and syntax constructs has deliberately been kept small avoiding shortcuts and ‘tricks’ often
provided by modeling languages. These facilities are sometimes useful to reduce the size of a model
source (not its readability) but also are likely to introduce inconsistencies and ambiguities in thelanguage itself, making it harder to understand and maintain.

2.1

Introduction

2.1.1

Comments
A comment is a part of the source ﬁle that is ignored by the compiler. It is usually used to explain what
the program is supposed to do. Either single line comments or multi lines comments can be used in asource ﬁle. For the ﬁrst case, the comment starts with the ’!’ character and terminates with the end of
the line. A multi-line commentary must be inclosed in ’(!’ and ’!)’. Note that it is possible to nest
several multi-line commentaries.
! In a comment
This text will be analyzed(! Start of a multi line(! Another comment
blablaend of the second level comment !)end of the first level !) Analysis continues here

Comments may appear anywhere in the source ﬁle.

2.1.2

Identiﬁers
Identiﬁers are used to name objects (variables, for instance). An identiﬁer is an alphanumeric (plus ’_’)
character string starting with an alphabetic character or ’_’. All characters of an identiﬁer are signiﬁcantand the case is important (the identiﬁer ’word’ is not equivalent to ’Word’).

Fair Isaac Corporation Conﬁdential and Proprietary Information

15

The Mosel Language

2.1.3

Reserved words
The reserved words are identiﬁers with a particular meaning that determine a speciﬁc behaviour within
the language. Because of their special role, these keywords cannot be used to name user deﬁned
objects (i.e. they cannot be redeﬁned). The list of reserved words is:and, array, as, boolean, break, case, constant, count, counter, declarations, div, do,dynamic, elif, else, end, evaluation, false, forall, forward, from, function, hashmap, if,
imports, in, include, initialisations, initializations, integer, inter, is_binary,is_continuous,
is_free, is_integer, is_partint, is_semcont, is_semint, is_sos1, is_sos2, linctr,
list, max, min, mod, model, mpvar, namespace, next, not, nsgroup, nssearch, of, options, or,package, parameters, procedure, public, prod, range, real, record, repeat, requirements,
return, set, shared, string, sum, then, to, true, union, until, uses, version, while, with.
Note that, although the lexical analyzer of Mosel is case-sensitive, the reserved words are deﬁned bothas lower and upper case (i.e. AND and and are keywords but not And).

2.1.4

Separation of instructions, line breaking
In order to improve the readability of the source code, each statement may be split across several lines
and indented using as many spaces or tabulations as required. However, as the line breaking is theexpression terminator, if an expression is to be split, it must be cut after a symbol that implies acontinuation like an operator (’+’, ’-’, ...) or a comma (’,’) in order to warn the analyzer that theexpression continues in the following line(s).
A+B-C+D
A+BC+D! Expression 1! Expression 2! Expression 3...
! ...end of expression 3

Moreover, the character ’;’ can be used as an expression terminator.
A+B ; -C+D

! 2 expressions on the same line

Some users prefer to explicitly mark the end of each expression with a particular symbol. This ispossible using the option explterm (see Section 2.3) which disables the default behaviour of thecompiler. In that case, the line breaking is not considered any more as an expression separator andeach statement ﬁnishing with an expression must be terminated by the symbol ’;’.
A+B;
-C+D;
A+B
-C+D;

2.1.5

! Expression 1! Expression 2! Expression 3...
! ...end of expression 3

Conventions in this document
In the following sections, the language syntax is explained. In all code templates, the following
conventions are employed:

word: ’word’ is a keyword and should be typed as is;todo: ’todo’ is to be replaced by something else that is explained later;[ something ]: ’something’ is optional and the entire block of instructions may be omitted;

[ something ...]: ’something’ is optional but if used, it can be repeated several times.

Fair Isaac Corporation Conﬁdential and Proprietary Information

16

The Mosel Language

2.2

Structure of the source ﬁle
The Mosel compiler may compile both models and packages source ﬁles. Once compiled, a model isready for execution but a package is intended to be used by a model or another package (see Section
2.3).
The general structure of a model source ﬁle is as follows:model model_name[ Directives ][ Parameters ][ Body ]end-model

The model statement marks the beginning the program and the statement end-model its end. Any
text following this instruction is ignored (this can be used for adding plain text comments after the endof the program). The model name may be any quoted string or identiﬁer, this name will be used as themodel name in the Mosel model manager. An optional set of directives and a parameters block may
follow. The actual program/model is described in the body of the source ﬁle which consists of a
succession of declaration blocks, subroutine deﬁnitions and statements.
The structure of a package (see Section 2.12) source ﬁle is similar to the one of a model:
package package_name[ Directives ][ Parameters ][ Body ]end-package

The package statement marks the beginning the library and the statement end-package its end. The
package name must be a valid identiﬁer.
It is important to understand that the language is procedural and not declarative: the declarations andstatements are compiled and executed in the order of their appearance. As a consequence, it is notpossible to refer to an identiﬁer that is declared later in the source ﬁle or consider that a statement
located later in the source ﬁle has already been executed. Moreover, the language is compiled and notinterpreted: the entire source ﬁle is ﬁrst translated — as a whole — into a binary form (the BIM ﬁle), thenthis binary form of the program is read again to be executed. During the compilation, except for some
simple constant expressions, no action is actually performed. This is why only some errors can bedetected during the compilation time, any others being detected when running the program.

2.3

The compiler directives
The compiler accepts four different types of directives: the uses statement, the imports statement,
the options statement and the version statement. Namespace declarations are also expressed bymeans of directives, see Section 2.13 for further explanations.

2.3.1

Directive uses
The general form of a uses statement is:uses libname1 [, libname2 ...][;]

This clause asks the compiler to load the listed modules or packages and import the symbols they

Fair Isaac Corporation Conﬁdential and Proprietary Information

17

The Mosel Languagedeﬁne. Both modules and packages must still be available for running the model. If the source ﬁlebeing processed is a package, the bim ﬁles associated to the listed packages must be available forcompiling another ﬁle using this package. It is also possible to merge bim ﬁles of several packages byusing imports instead of uses when building packages.
By default the compiler tries ﬁrst to ﬁnd a package (the corresponding ﬁle is libname.bim) then, if thisfails, it searches for a module (which ﬁle name is libname.dso). It is possible to indicate the type oflibrary to look for by appending either ".bim" or ".dso" to the name (then the compiler does not try
the alternative in case of failure). A package may also be speciﬁed by an extended ﬁle name (seeSection 2.15) including the IO driver in order to disable the automatic search (i.e. "a.bim" searches
the ﬁle a.bim in the library path but ":a.bim" takes the ﬁle a.bim from the current directory).
For example,
uses 'mmsystem','mmxprs.dso','mypkg.bim'
uses ':/tmp/otherpkg.bim'

Both packages and modules are searched in a list of possible locations. Upon startup, Mosel uses as
the default for this list the value of the environment variable MOSEL_DSO completed by a path deduced
from the location (rtdir) of the Mosel runtime library (in the following # can be "32" on a 32bit system,"64" on a 64bit system or an empty string):"rtdir\..\dso#" Under Windows if rtdir terminates by "\bin#" and "rtdir\..\dso#" exists or"rtdir/../dso#"
or"rtdir/dso#"

On Posix systems if rtdir terminates by "/lib#" and "rtdir/../dso#" exists

if this directory exists or"rtdir" if none of the above rules apply
The variable MOSEL_DSO is expected to be a list of paths conforming to the operating system
conventions: for a Posix system the path separator is ’:’ (e.g. "/opt/Mosel/dso:/tmp") and it is ’;’under Win32 (e.g. "E:\Mosel\Dso;C:\Temp"). The search path for modules and packages may also
be set from the mosel command (using the -dp option, see Section 1.3) as well as inspected andmodiﬁed from the Mosel Libraries (see functions XPRMgetdsopath and XPRMsetdsopath in the
Mosel Libraries Reference Manual). Note however that Mosel will ignore modules not located inread-only locations when the restriction NoExec is active (see Section 1.3.4).
For locating packages Mosel will use the list of preﬁxes deﬁned by the compiler option -bx (Section
1.3) or the environment variable MOSEL_BIM before proceeding to the search as decribed above. Thisparameter consists in a list of strings separated by the sequence || that are used as preﬁxes to the
package name. For instance if the option -bx "bimdir/||tmp:" is used with the directive uses
’mypkg’, the compiler will try to load the package "bimdir/mypkg.bim", then "tmp:mypkg.bim"
before looking for "mypkg.bim" and "mypkg.dso" in the usual locations.

2.3.2

Directive imports
The general form of an imports statement is:imports pkgname1 [, pkgname2 ...][;]

This clause is a special version of the uses directive that can only be used for packages: it asks thecompiler to load the listed packages, import the symbols they deﬁne and incorporate thecorresponding bim ﬁle. As a consequence, the generated ﬁle provides the functionality of the packages
it imports. When used on a model ﬁle it removes the dynamic dependency on the listed packages (i.e.
these packages are no longer required to run the model).

Fair Isaac Corporation Conﬁdential and Proprietary Information

18

The Mosel Language

For example,
imports 'mypkg'

2.3.3

Directive options
The compiler options may be used to modify the default behaviour of the compiler. The general form ofan options statement is:
options optname1 [, optname2 ...]The supported options are:















explterm: asks the compiler to expect explicit expression termination (see Section 2.1.4).
noimplicit: disables the implicit declarations (see Section 2.8.1.3). This option can also be
activated by using the ’-ni’ compiler ﬂag (see Section 1.3)
noautofinal: by default initialization from blocks ﬁnalize sets they populate (section 2.8.2.1).
This option disables this behaviour that may be activated afterwards using the autofinal
control parameter (cf. setparam).
keepassert: assertions (cf. assert) are compiled only in debug mode. With this option
assertions are preserved regardless of the compilation mode.
xbim: store additional symbol information in the generated bim ﬁle (in particular array index
names). This option can also be enabled by using the ’-I’ compiler ﬂag (see Section 1.3).
fctasproc: by default return values of functions must be used such that a function call is not avalid statement. With this option functions can be used as procedures: when a statement
consists in a function call its return value is silently ignored (see also asproc).
tagpriv: when the model is compiled with debug information private symbols are preserved.
When this option is used these symbols are preﬁxed with ’~’ such that they can be easily
identiﬁed.
dynonly: this option can only be applied to a package: it marks the package as dynamic only
such that it cannot be imported (see Section 2.3.2).

For example,
options noimplicit,explterm

2.3.4

Directive version
In addition to the model/package name, a ﬁle version number may be speciﬁed using this directive: aversion number consists in 1, 2 or 3 integers between 0 and 999 separated by the character ’.’.
version major [. minor [. release ]]For example,
version 1.2

The ﬁle version is stored in the BIM ﬁle and can be displayed from the Mosel console (command list)or retrieved using the Mosel Libraries (see function XPRMgetmodprop in the Mosel Libraries Reference
Manual). From the model itself, the version number is recorded as a string in the control parametermodel_version (see function getparam).

Fair Isaac Corporation Conﬁdential and Proprietary Information

19

The Mosel Language

2.4

The parameters block
A model parameter is a symbol, the value of which can be set just before running the model (optionalparameter of the ’run’ command of the command line interpreter). The general form of the parameters
block is:parameters
ident1 = Expression1[ ident2 = Expression2 ...]
end-parameters

where each identiﬁer identi is the name of a parameter and the corresponding expression Expressioni
its default value. This value is assigned to the parameter if no explicit value is provided at the start ofthe execution of the program (e.g. as a parameter of the ’run’ command). Note that the type (integer,
real, text string or Boolean) of a parameter is implied by its default value. Model parameters aremanipulated as constants in the rest of the source ﬁle (it is not possible to alter their original value).
parameters
size=12R=12.67
F="myfile"
B=trueend-parameters! Integer parameter! Real parameter! Text string parameter! Boolean parameter

In addition to model parameters, Mosel and some modules and packages provide control parameters :they can be used to give information on the system (e.g. success of an I/O operation) or control its
behaviour (e.g. select output format of real numbers). These parameters can be accessed andmodiﬁed using the routines getparam and setparam. Refer to the documentation of these functions
for a complete listing of available Mosel parameters. The documentation of the modules include thedescription of the parameters they publish.

2.5

Source ﬁle preprocessing

2.5.1

Source ﬁle character encoding
The Mosel compiler expects source ﬁles to be encoded in UTF-8 and will handle properly UTF-16 and
UTF-32 encodings when the ﬁle begins with a BOM (Byte Order Mark). It is also possible to select analternative encoding using the encoding annotation (see section 2.14).
For instance to notify the compiler that the the source ﬁle is encoded using ISO-8859-1, the following
comment has to be copied at the beginning of the ﬁe:!@encoding:iso-8859-1

2.5.2

Source ﬁle inclusion
A Mosel program may be split into several source ﬁles by means of ﬁle inclusion. The ’include’
instruction performs this task:
include filename

where ﬁlename is the name of the ﬁle to be included. This ﬁle name may contain environment variablereferences using the notation ${varname} (e.g. ’${MOSEL}/examples/mymodel’) that are

Fair Isaac Corporation Conﬁdential and Proprietary Information

20

The Mosel Language

expanded to generate the actual name. The ’include’ instruction is replaced at compile time by thecontents of the ﬁle ﬁlename.
Assuming the ﬁle a.mos contains:model "Example for file inclusion"
writeln('From the main file')
include "b.mos"
end-model

And the ﬁle b.mos:writeln('From an included file')

Due to the inclusion of b.mos, the ﬁle a.mos is equivalent to:model "Example for file inclusion"
writeln('From the main file')
writeln('From an included file')
end-model

If the compiler option -ix is used (Section 1.3) all ﬁle names used in the ’include’ instruction will be
preﬁxed as requested. For instance, if the option -ix "incdir/" is used with the compiler, thestatement include "myfile.mos" will be replaced by the content of "incdir/myfile.mos".
Note that ﬁle inclusion cannot be used inside of blocks of instructions or before the body of the
program (as a consequence, a ﬁle included cannot contain any of the following statements: uses,
options or parameters).

2.5.3

Line control directives
In some cases it may be useful to process a Mosel source through an external preprocessor before
compilation. For instance this may enable the use of facilities not supported by the Mosel compiler likemacros, unrestricted ﬁle inclusion or conditional compilation. In order to generate meaningful error
messages, the Mosel compiler supports line control directives: these directives are inserted by
preprocessors (e.g. cpp or m4) to indicate the original location (ﬁle name and line number) ofgenerated text.
#[line] linenum [ﬁlename]To be properly interpreted, a line control directive must be the only statement of the line. Malformed
directives and text following valid directives are silently ignored.

2.6

The declaration block
The role of the declaration block is to give a name, a type, and a structure to the entities that theprocessing part of the program/model will use. The type of a value deﬁnes its domain (for instance
integer or real) and its structure, how it is organized, stored (for instance a reference to a single value or
an ordered collection in the form of an array). The declaration block is composed of a list of declaration
statements enclosed between the instructions declarations and end-declarations.
declarations
Declare_stat[ Declare_stat ...]
end-declarations

Fair Isaac Corporation Conﬁdential and Proprietary Information

21

The Mosel Language

Several declaration blocks may appear in a single source ﬁle but a symbol introduced in a given blockcannot be used before that block. Once a name has been assigned to an entity, it cannot be reused foranything else.

2.6.1

Elementary types
Elementary objects are used to build up more complex data structures like sets or arrays. It is, ofcourse, possible to declare an entity as a reference to a value of one of these elementary types. Such a
declaration looks as follows:
ident1 [, ident2 ...]: [shared] type_namewhere type_name is the type of the objects to create. Each of the identiﬁers identi is then declared as areference to a value of the given type. The type name may be either a basic type (integer, real,
string, boolean), an MP type (mpvar, linctr), an external type or a user deﬁned type (see section
2.6.7). MP types are related to Mathematical Programming and allow declaration of decision variables
and linear constraints. Note that the linear constraint objects can also be used to store linear
expressions. External types are deﬁned by modules (the documentation of each module describes how
to use the type(s) it implements). The qualiﬁer shared identiﬁes variables that will be shared between
several concurrent models (see Section 7.2). Only entities of basic types and external types supporting
sharing can be shared.
declarations
i,j: integer
str: string
x,y,z: mpvar
end-declarations

2.6.1.1

Basic types

The basic types are:







integer: an integer value between -2147483648 and 2147483647. Integers may also be
expressed in hexadecimal by using the preﬁx 0x or 0X (e.g. 0x7b is the same as 123)
real: a real value between -1.7e+308 and 1.7e+308. Floating point numbers expressed inhexadecimal can also be used as real constants. The general form of such a constant is
0xh.hhhp[+/-]ddd where ’h’ are hexadecimal digits and ’d’ decimal digits (e.g. 0x1.9p+3
is the same as 12.5)
string: some text.
boolean: the result of a Boolean (logical) expression. The value of a Boolean entity is either thesymbol true or the symbol false.

After its declaration, each entity receives an initial value of 0, an empty string, or false depending on
its type.
2.6.1.2

MP types

Two special types are provided for mathematical programming.
mpvar: a decision variable

linctr: a linear constraint

Fair Isaac Corporation Conﬁdential and Proprietary Information

22

The Mosel Language

2.6.2

Sets
Sets are used to group an unordered collection of elements of a given type. Set elements are unique: if
an element is added several times it is only contained once in the set. Declaring a set consists ofdeﬁning the type of elements to be collected.
The general form of a set declaration is:
ident1 [, ident2 ...] : [shared] [dynamic] set of [constant] type_namewhere type_name is one of the elementary types. Each of the identiﬁers identi is then declared as a setof the given type. The qualiﬁer shared identiﬁes sets that will be shared between several concurrent
models (see Section 7.2). Only sets of basic types can be shared. If the qualiﬁer dynamic is used thecorresponding set(s) will never be ﬁnalized (see Section 2.8.2.1 and procedure finalize).
A set may collect references to constant elements of a native type (the type must support constantdeclaration): this kind of set will be created if the type name is preceded by the constant keyword. As
opposed to an ordinary set, a set of constant references behaves as if it was collecting values of thenative type entities instead of their references. For instance adding 2 different variables of some native
type to a normal set will always result in 2 elements added to the set. However a single element will be
added to a set of constant references if these 2 variables have the same content (or the same textual
representation). Moreover, since references are not directly collected, any change to a variable
previously added to a set of constant references has no impact on the content of this set.
A particular set type is also available that should be preferred to the general form wherever possible
because of its better efﬁciency: the range set is an ordered collection of consecutive integers in a given
interval. The declaration of a range set is achieved by:ident1 [, ident2 ...] : [shared] [dynamic] range [set of integer]

Each of the identiﬁers identi is then declared as a range set of integers. Every newly created set is
empty.
declarations
s1: set of string
r1: range
end-declarations

2.6.3

Lists
Lists are used to group a collection of elements of a given type. An element can be stored several times
in a list and order of the elements is speciﬁed by construction. Declaring a list consists of deﬁning thetype of elements to be collected.
The general form of a list declaration is:
ident1 [, ident2 ...] : [shared] list of type_namewhere type_name is one of the elementary types. Each of the identiﬁers identi is then declared as a listof the given type. The qualiﬁer shared identiﬁes lists that will be shared between several concurrent
models (see Section 7.2). Only lists of basic types can be shared.
Every newly created list is empty.
declarations
l1: list of string
l2: list of real
end-declarations

Fair Isaac Corporation Conﬁdential and Proprietary Information

23

The Mosel Language

A list element can be accessed using its order number. The ﬁrst element has number 1 and index
values inferior to 1 point to elements starting from the end of the list. For instance if l is a list, l(2) isthe second element of this list, l(0) is the last element of the list and l(-1) its predecessor.

2.6.4

ArraysAn array is a collection of labelled objects of a given type. A label is deﬁned by a list of indices taking
their values in domains characterized by sets: the indexing sets. An array may be either dense orsparse: every possible index tuple is associated to a cell in a dense array while sparse arrays are
created empty. The cells are then created explicitly (cf. procedure create) or when they are assigned avalue (cf. Section 2.8.1.1) and the array may then grow ‘on demand’. It is also possible to delete some or
all cells of a dynamic array using the procedure delcell. A cell that has not been created can be
identiﬁed using the exists function and its value is the default initial value of the type of the array. The
general form of an array declaration is:
ident1 [, ident2 ...] : [shared] [dynamic|hashmap] array(list_of_sets) of type_namewhere list_of_sets is a list of set declarations/expressions separated by commas and type_name is oneof the elementary types. Each of the identiﬁers identi is then declared as an array of the given type andindexed by the given sets. In the list of indexing sets, a set declaration can be anonymous (i.e. rs:setof real can be replaced by set of real if no reference to rs is required) or shortened to the typeof the set (i.e. set of real can be replaced by real in that context). The qualiﬁer shared identiﬁes
arrays that will be shared between several concurrent models (see Section 7.2). Only arrays of basic
types and indiced by shared or constant sets of basic types can be shared.
declarations
e: set of string
t1:array ( e, rs:set of real, range, integer ) of realt2:array ( {"i1","i2"}, 1..3 ) of integer
end-declarations

By default an array is dense (or static). For best performane it is better to index static arrays withconstant sets or initialize and ﬁnalize indexing sets as soon as possible (cf. procedure finalize). An
array is sparse (or dynamic) and created empty if either the qualiﬁer dynamic or hashmap is used.
Arrays declared with either of these qualiﬁers behave the same but their internal representation differ:the dynamic representation requires less memory and is faster for linear enumeration while thehashmap representation is faster for random access.
Note that once a set is employed as an indexing set, Mosel makes sure that its size is never reduced inorder to guarantee that no entry of any array becomes inaccessible. Such a set is called ﬁxed.
2.6.4.1

Special case of dynamic arrays of a type not supporting assignment

Certain types do not have assignment operators: for instance, writing x:=1 is a syntax error if x is oftype mpvar. If an array of such a type is deﬁned as dynamic the corresponding cells are not created. Inthat case, it is required to create each of the relevant entries of the array by using the procedure
create since entries cannot be deﬁned by assignment.

2.6.5

Records
A record is a ﬁnite collection of objects of any type. Each component of a record is called a ﬁeld and ischaracterized by its name (an identiﬁer) and its type. The general form of a record declaration is:

Fair Isaac Corporation Conﬁdential and Proprietary Information

24

The Mosel Language

ident1 [, ident2 ...] : recordﬁeld1 [, ﬁeld2 ...]: type_name[...]end-record

where ﬁeldi are the identiﬁers of the ﬁelds of the record and type_name one of the elementary types.
Each of the identiﬁers identi is then declared as a record including the listed ﬁelds.
Example:declarations
r1: record
i,j:integer
r:realend-record
end-declarations

Each record declaration is considered unique by the compiler. In the following example, although r1
and r2 have the same deﬁnitions, they are not of the same type (but r3 is of course of the type of r2):
declarations
r1: record
i,j:integer
end-record
r2,r3: record
i,j:integer
end-record
end-declarations

2.6.6

Constants
A constant is an identiﬁer for which the value is known at declaration time and that will never be
modiﬁed. The general form of a constant declaration is:
identiﬁer = Expression

where identiﬁer is the name of the constant and Expression its initial and only value. The expression
must be of one of the basic types, a set or a list of one of these types, a native type supporting constantdeﬁnition, or a record type containing only basic types.
Example:declarations
STR='my const string'
I1=12
R=1..10! constant range
S={2.3,5.6,7.01} ! constant set
L=[2,4,6]! constant list
end-declarations

The compiler supports two kinds of constants: a compile time constant is a constant which value canbe computed by the compiler. A run time constant will be known only when the model is run.
Example:parameters
P=0
end-parameters
declarations
I=1/3
J=P⁎2

! compile time constant! run time constantFair Isaac Corporation Conﬁdential and Proprietary Information

25

The Mosel Language
end-declarations

2.6.7

User deﬁned types
2.6.7.1

Naming new types

A new type may be deﬁned by associating an identiﬁer to a type declaration. The general form of a type
deﬁnition is:
identiﬁer = Type_def

where Type_def is a type (elementary, set, list, array or record) to be associated to the symbol identiﬁer.
After such a deﬁnition, the new type may be used wherever a type name is required.
Example:declarations
entier=integer
setint=set of entier
i:entier! <=> i:integers:setint! <=> s:set of integer
end-declarations

Note that only compile time constant or globally deﬁned sets are allowed as indices to array types:
declarations
ar1=array(1..10) of integer
ar2=array(range) of integer
R:range
ar3=array(R) of integer
end-declarations

2.6.7.2! OK! incorrect! OK

Combining types

Thanks to user deﬁned types one can create complex data structures by combining structures offeredby the language. For instance an array of sets may be deﬁned as follows:declarations
typset=set of integer
a1:array(1..10) of typset
end-declarations

In order to simplify the description of complex data structures, the Mosel compiler can generate
automatically the intermediate user types. Using this property, the example above can be written as
follows (both arrays a1 and a2 are of the same type):declarations
a2:array(1..10) of set of integer
end-declarations

2.7

Expressions
Expressions are, together with the keywords, the major building blocks of a language. This section
summarizes the different basic operators and connectors used to build expressions.
Expressions are constructed using constants, operators and identiﬁers (of objects or functions). If an
identiﬁer appears in an expression its value is the value referenced by this identiﬁer. In the case of a set,

Fair Isaac Corporation Conﬁdential and Proprietary Information

26

The Mosel Language

a list, an array or a record, it is the whole structure. To access a single cell of an array, it is required to’dereference’ this array. The dereferencing of an array is denoted as follows:array_ident (Exp1 [, Exp2 ...])

where array_ident is the name of the array and Expi an expression of the type of the ith indexing set ofthe array. The type of such an expression is the type of the array and its value the value stored in thearray with the label ’Exp1 [, Exp2 ...]’. In order to access the cell of an array of arrays, the list of indicesfor the second array has to be appended to the list of indices of the ﬁrst array. For instance, the arraya:array(1..10) of array(1..10) of integer can be dereferenced with a(1,2).
Similarly, to access the ﬁeld of a record, it is required to ’dereference’ this record. The dereferencing ofa record is denoted as follows:
record_ident.ﬁeld_ident

where record_ident is the name of the record and ﬁeld_ident the name of the required ﬁeld.
Dereferencing arrays of records is achieved by combining the syntax for the two structures. For
instance a(1).b
A function call is denoted as follows:
function_ident
or
function_ident (Exp1 [, Exp2 ...])

where function_ident is the name of the function and Expi the ith parameter required by this function(note that function parameters are evaluated from right to left). The ﬁrst form is for a function requiringno parameter.
The special function if is an operator that allows one to make a selection among expressions. Its
syntax is the following:
if (Bool_expr, Exp1, Exp2)

which evaluates to Exp1 if Bool_expr is true or Exp2 otherwise. The type of this expression is the typeof Exp1 and Exp2 which must be of the same type.
Parentheses may be used to modify the predeﬁned evaluation order of the operators (see Table 2.1) or
simply to group subexpressions.
Table 2.1: Priority and evaluation order of operators in Mosel (smaller values indicate higher priority)
Priority

Operators

Sense of evaluation

1
2
3
4
5
6
7
8
9

() {} [] . if count function calls type conversions-unary ˆ⁎ / div mod prod inter+ -binary sum union max min< <= > >= = <> in not in
not
and
or
array

→
←
→
→
→
→
→
→
→

Operators that result in statements are discussed in other sections:

Fair Isaac Corporation Conﬁdential and Proprietary Information

27

The Mosel Language

assignment operators: := += -= (see Section 2.8.1.1)



inline array initialization: :: (see Section 2.8.1.4))

Table 2.2 summarizes the meaning and applicability of operators that are discussed for the different
expression types in the following sections.
Table 2.2: Meaning of operators for different expression types
Type

2.7.1

Operators

Description

All expressions
All expect linear constraints()
ifChanging the evaluation order
Inline ’if’

Arithmetic expressionscountˆ⁎ / prod
div mod+ - sum
max min< <= > >=<>Counter
Exponential operator
Multiplication and division
Integer division and modulo
Addition and substraction
Maximum and minimum value
Comparators

String expressions

+
<

<>

Concatenation
Difference
Comparators (see Section 2.7.7)

Set expressions{}⁎ inter+ union
< <=
> >=
= <>
in not inrange set

Constant set deﬁnition
Intersection
Union
Difference
SubsetSuperset
Equality and difference of contents
Set element
Constructors; clone operators

List expressions

[]
+ sum
= <>
list

Constant list deﬁnition
Concatenation
Difference
Equality and difference of contentsConstructor; clone operator

Boolean expressions

not
and
or

Negation
Logic ’and’
Logic ’or’

Linear constraint expressions⁎+ - sum<= >= =

Multiplication (one operand must be of numerical type)
Addition / subtraction
Relational operators

Automatic arrays

::
= <>
array

Inline array initialization (see Section 2.8.1.4)
Equality and difference of contentsConstructor

<=

>

>=

=

=

Type conversions and constructors
The Mosel compiler operates automatic conversions to the type required by a given operator in thefollowing cases:in the dereference list of an array:
integer → real;
in a function or procedure parameter list:

Fair Isaac Corporation Conﬁdential and Proprietary Information

28

The Mosel Language

integer → real, linctr;
real → linctr;
mpvar → linctr;
anywhere else:
integer → real, string, linctr;
real → string, linctr;
mpvar → linctr;
boolean → string.

It is possible to force a basic type conversion using the type name as a function (i.e. integer, real,
string, boolean). In the case of string, the result is the textual representation of the converted
expression. In the case of boolean, for numerical values, the result is true if the value is nonzero andfor strings the result is true if the string is the word ‘true’. When converting a real to an integer the
result is the integral part of the number (no rounding is performed). Note that explicit conversions are
not deﬁned for MP types, and structured types (e.g. linctr(x) is a syntax error).
For generating numerical values from strings it is in general preferrable to use the subroutinesparseint/parsereal that provide error handling functionality in place of the basic conversion
available through integer/real.
! Assuming A=3.6, B=2
integer(A+B)
string(A-B)
real(integer(A+B))! = 5! = "1.6"! = 5.6 (because the compiler simplifies
the expression)

Some native and record types might be used as function names to create new instances of thecorresponding type (see the documentation of each individual type for a list of possible constructors).
If the only argument of such a function call is an entity of the same type the result is a copy of theargument (the type must support assignment). For record types a speciﬁc syntax makes it possible tocreate and initialise each ﬁeld of the newly created entity in a single operation:
type_name (.ﬁeld1:=val1 [, .ﬁeld2:=val2 ...])

where type_name is the name of a record type and ﬁeldi one of its ﬁelds to be initialised with thecorresponding vali value.
The constructor array (see 2.7.9) for creating new arrays ad-hoc is an aggregate operator, via list
(see 2.7.6), set and range (see 2.7.5) it is possible to perform transformations between set and list
structures.

2.7.2

Aggregate operators
An operator is said to be aggregate when it is associated to a list of indices for each of which a set or listof values is deﬁned. This operator is then applied to its operands for each possible tuple of values (e.g.
the summation operator sum is an aggregate operator). The general form of an aggregate operator is:Aggregate_ident (Iterator1 [, Iterator2 ...]) Expression
orcount (Iterator1 [, Iterator2 ...])

where the Aggregate_ident is the name of the operator and Expression an expression compatible withthis operator (see below for the different available operators). The type of the result of such an
aggregate expression is the type of Expression. The count operator does not require an additional
expression: its value, an integer, corresponds to the number of times the expression of another

Fair Isaac Corporation Conﬁdential and Proprietary Information

29

The Mosel Language

Table 2.3: Aggregate operators in Mosel with default values for empty expressions
Operator

Description

Default values

count
prod
inter
sum
union
max
min
and
or
array

Counter
Product
Intersection of sets
Sum (arithmetic); concatenation (list, text)
Union of sets
Maximum value
Minimum value
Logic ’and’
Logic ’or’
Array creation

01
empty setarithmetic: 0, list: empty list
empty set
real: -MAX_REAL, integer: -MAX_INT-1
real: MAX_REAL, integer: MAX_INT
true
false
dynamic empty array

aggregate operator used with the same iterator list would be evaluated (i.e. it is equivalent tosum(iteratorlist) 1).
An iterator is one of the following constructs:
SetList_expr
orident1 [, ident2 ...] in SetList_expr [| Bool_expr]
orident = Expression [| Bool_expr]
orident as counter

The ﬁrst form gives the list of the values to be taken without specifying an index name. With the second
form, the indices named identi take successively all values of the set or list deﬁned by SetList_expr.
With the third form, the index ident is assigned a single value (which must be a scalar). For the second
and third cases, the scope of the created identiﬁer is limited to the scope of the operator (i.e. it exists
only for the following iterators and for the operand of the aggregate operator). Moreover, an optional
condition can be stated by means of Bool_expr which can be used as a ﬁlter to select the relevant
elements of the domain of the index. It is important to note that this condition is evaluated as early as
possible. As a consequence, a Boolean expression that does not depend on any of the deﬁned indicesin the considered iterator list is evaluated only once, namely before the aggregate operator itself and
not for each possible tuple of indices. The last form of an iterator declares a counter for the operator:
the value of the corresponding symbol is incremented each time the operator’s expression is evaluated.
For this case, if ident has been declared before, it must be integer or real and its value is not reset.
Otherwise, as for indices, the scope of the created integer identiﬁer is limited to the scope of theoperator and its initial value is 0. There can be only one counter for a given aggregate operator.
The Mosel compiler performs loop optimization when function exists is used as the ﬁrst factors of
the condition in order to enumerate only those tuples of indices that correspond to actual cells in thearray instead of all possible tuples. To be effective, this optimization requires that sets used to declare
the array on which the exist condition applies must be named and the same sets must be used todeﬁne the index domains. Moreover, the maximum speedup is obtained when order of indices isrespected and all indices are deﬁned in the same aggregate operator.
An index is considered to be a constant: it is not possible to change explicitly the value of a named
index (using an assignment for instance).

2.7.3

Arithmetic expressions
Numerical constants can be written using the common scientiﬁc notation. Arithmetic expressions are

Fair Isaac Corporation Conﬁdential and Proprietary Information

30

The Mosel Language

naturally expressed by means of the usual operators (+, -, ⁎, / division, unary -, unary +,ˆraise to thepower). For integer values, the operators mod (remainder of division) and div (integral division) arealso deﬁned. Note that mpvar objects are handled like real values in expression.
The sum (summation) aggregate operators is deﬁned on integers, real and mpvar. The aggregate
operators prod (product), min (minimum) and max (maximum) can be used on integer and real values.
x⁎5.5+(2+z)^4+cos(12.4)
sum(i in 1..10) (min(j in s) t(i)⁎(a(j) mod 2))

2.7.4

String expressions
Constant strings of characters must be quoted with single (’) or double quote (") and may extend over
several lines. Strings enclosed in double quotes may contain C-like escape sequences introduced by
the ’backslash’ character (\a \b \f \n \r \t \v \xxx \uhhhh with xxx being the character code as
an octal number and hhhh a Unicode code as a four hexadecimal digits number).
Each sequence is replaced by the corresponding control character (e.g. \n is the ‘new line’ command)or, if no control character exists, by the second character of the sequence itself (e.g. \\ is replaced by’\’).
The escape sequences are not interpreted if they are contained in strings that are enclosed in single
quotes.
Example:’c:\ddd1\ddd2\ddd3’ is understood as c:\ddd1\ddd2\ddd3"c:\ddd1\ddd2\ddd3" is understood as c:ddd1ddd2ddd3

There are two basic operators for strings: the concatenation, written ’+’ and the difference, written ’-’.
"a1b2c3d5"+"e6"'a1b2c3d5'-"3d5"! = "a1b2c3d5e6"! = "a1b2c"

A constant string may also take 2 additional forms: initialised from the content of an external ﬁle or as
a portion of the current input ﬁle. For the ﬁrst case, a text string enclosed in backquotes will be
replaced by the content of the ﬁle identiﬁed by this enclosed text. For the second case, a line ending by
the backquote character optionally followed by some label (consisting in any sequence of characters
not including backquote) will be interpreted as the beginning of a text block. The end of this text blockis marked by a line starting with the previously used label (if any) followed by the backquote character.
Example:`afile.txt` ! This string is the content of "afile.txt"`MyMarker
line1
line2
MyMarker` ! This string is equivalent to "line1\nline2\n"

2.7.5

Set expressions
Constant sets are described using one of the following constructs:{[ Exp1 [, Exp2 ...]]}
orInteger_exp1 .. Integer_exp2

The ﬁrst form enumerates all the values contained in the set and the second form, restricted to sets ofintegers, gives an interval of integer values. This form implicitly deﬁnes a range set.

Fair Isaac Corporation Conﬁdential and Proprietary Information

31

The Mosel Language

The basic operators on sets are the union written +, the difference written - and the intersection written⁎.
The aggregate operators union and inter can also be used to build up set expressions.
{1,2,3}+{4,5,6}-(5..8)⁎{6,10}{'a','b','c'}⁎{'b','c','d'}union(i in 1..4|i<>2) {i⁎3}! = {1,2,3,4,5}! = {'b','c'}! = {3,9,12}

If several range sets are combined in the same expression, the result is either a range or a set of
integers depending on the continuity of the produced domain. If range sets and sets of integers ofmore than one element are combined in an expression, the result is a set of integers. It is however
possible to convert a set of integers to a range by using the notation range(setexpr) where
setexpr is a set expression which result is either a set of integers or a range. Similarly stating
set(lstexpr) will generate a set from the elements of the list expression lstexpr.

2.7.6

List expressions
A constant list consist in a list of expressions enclosed in square brackets:[[ Exp1 [, Exp2 ...]]]

There are two basic operators for lists: the concatenation, written ’+’ and the difference, written ’-’. The
aggregate operator sum can also be used to build up list expressions.
[1,2,3]+[1,2,3][1,2,3,4]-[3,4]sum(i in 1..3) [i⁎3]! = [1,2,3,1,2,3]! = [1,2]! = [3,6,9]

A list can also be constructed from the elements of a set using the syntax list(setexpr) where
setexpr is a set expression.

2.7.7

Boolean expressions
A Boolean expression is an expression whose result is either true or false. The traditional comparators
are deﬁned on integer and real values: <, <=, =, <> (not equal), >=, >.
These operators are also deﬁned for string expressions. In that case, the order is deﬁned by theISO-8859-1 character set (i.e. roughly: punctuation <digits <capitals <lower case letters <accented
letters).
With sets, the comparators <= (‘is subset of’), >= (‘is superset of’), = (‘equality of contents’) and <>(‘difference of contents’) are deﬁned. These comparators must be used with two sets of the same type.
Moreover, the operator ‘expr in Set_expr’ is true if the expression expr is contained in the set Set_expr.
The opposite, the operator not in is also deﬁned.
With lists, the comparators = (‘equality of contents’) and <> (‘difference of contents’) are deﬁned.
These comparators must be used with two lists of the same type.
With arrays, the comparators = (‘equality of contents’) and <> (‘difference of contents’) are deﬁned.
These comparators must be used with two arrays of the same type and this type must support therequested operator (for instance arrays of mpvar cannot be compared).
With records, the comparators = (‘equality of contents’) and <> (‘difference of contents’) are deﬁned.
These comparators must be used with two records of the same type and all ﬁelds of this record typemust support the requested operator (for instance records including mpvar entries cannot becompared).
To combine Boolean expressions, the operators and (logical and) and or (logical or) as well as the

Fair Isaac Corporation Conﬁdential and Proprietary Information

32

The Mosel Language

unary operator not (logical negation) can be used. The evaluation of an arithmetic expression stops assoon as its value is known.
The aggregate operators and and or are the natural extension of their binary counterparts.
3<=v1 and v2>=45 or t<>r and not r in {1..10}
and(i in 1..10) 3<=arr(i)2.7.8

Linear constraint expressions
Linear constraints are built up using linear expressions on the decision variables (type mpvar).
The different forms of constraints are:Linear_expr
orLinear_expr1 Ctr_cmp Linear_expr2
orLinear_expr SOS_type
ormpvar_ref mpvar_type1
or
mpvar_ref mpvar_type2 Arith_expr

In the case of the ﬁrst form, the constraint is unconstrained and is just a linear expression. For thesecond form, the valid comparators are <=, >=, = (range constraints may be created using theprocedure setrange). The third form is used to declare special ordered sets. The types are thenis_sos1 and is_sos2. The coefﬁcients of the variables in the linear expression are used as weights
for the SOS (as a consequence, a 0-weighted variable cannot be represented this way, proceduremakesos1 or makesos2 has to be used instead).
The last two types are used to set up special types for decision variables. The ﬁrst series does not
require any extra information: is_continuous (default), is_integer, is_binary, is_free.
Continuous and integer variables have the default lower bound 0, binary variables only take the values 0
or 1, and ’free’ means that the variable is unbounded (i.e. ranging from - ∞ to + ∞ ). The second seriesof types is associated with a threshold value stated by an arithmetic expressions: is_partint forpartial integer, the value indicates the limit up to which the variable must be integer, above which it iscontinuous. For is_semcont (semi-continuous) and is_semint (semi-continuous integer) the value
gives the semi-continuous limit of the variable (that is, the lower bound on the part of its domain that iscontinuous or consecutive integers respectively). Note that these constraints on single variables arealso considered as common linear constraints.
3⁎y+sum(i in 1..10) x(i)⁎i >= z-t
x is_free! Define an unbounded variable
x <= -2! Upper bound on xt is_integer! Define an integer variable t=0,1,2,...
t >= -7! Change lower bound on t: t=-7,-6,-5,...
sum(i in 1..10) i⁎x(i) is_sos1! SOS1 {x(1),x(2),...} with! weights 1,2,...
y is_partint 5! y=0 or y=5,6,...
y <= 20! Upper bound on y: y=0 or y=5,6,...,20Internally all linear constraints are stored in the same form: a linear expression (including a constantterm) and a constraint type (the right hand side is always 0). This means, the constraint expression
3⁎x>=5⁎y-10 is internally represented by: 3⁎x-5⁎y+10 and the type ‘greater than or equal to’. Whena reference to a linear constraint appears in an expression, its value is the linear expression it contains.
For example, if the identiﬁer ctl refers to the linear constraint 3⁎x>=5⁎y-10, the expression z-x+ctl
is equal to: z-2⁎x-5⁎y+10.

Fair Isaac Corporation Conﬁdential and Proprietary Information

33

The Mosel Language

Note that the value of a unary constraint of the type x is_type threshold is x-threshold.

2.7.9

Automatic arrays
The array keyword can be used as an aggregate operator in order to create an array that will exist
only for the duration of the expression.
array (Iterator1 [, Iterator2 ...]) Expression

here, the iterators deﬁne the indices of the array and the expression, the associated values.
This automatic array may be used wherever a reference to an array is expected: for instance to save thesolution values of an array of decision variables in an initialization block (see Section 2.8.2).
initializations to "mydata.txt"
evaluation of array(i in 1..10) x(i).sol as "mylabel"
end-initializations

2.8

Statements
Four types of statements are supported by the Mosel language. The simple statements can be seen as
elementary operations. The initialization block is used to load data from a ﬁle or save data to a ﬁle.
Selection statements allow one to choose between different sets of statements depending on
conditions. Finally, the loop statements are used to repeat operations.
Each of these constructs is considered as a single statement. A list of statements is a succession ofstatements. No particular statement separator is required between statements except if a statement
terminates by an expression. In that case, the expression must be ﬁnished by either a line break or thesymbol ’;’.

2.8.1

Simple statements
2.8.1.1

Assignment

An assignment consists in changing the value associated to an identiﬁer. The general form of anassignment is:
ident_ref := Expression
orident_ref += Expression
orident_ref -= Expression

where ident_ref is a reference to a value (i.e. an identiﬁer or an array/record dereference) andExpression is an expression of a compatible type with ident_ref. The direct assignment, denoted :=replaces the value associated with ident_ref by the value of the expression. The additive assignment,
denoted +=, and the subtractive assignment, denoted -=, are basically combinations of a direct
assignment with an addition or a subtraction. They require an expression of a type that supports these
operators (for instance it is not possible to use additive assignment with Boolean objects).
The additive and subtractive assignments have a special meaning with linear constraints in the sensethat they preserve the constraint type of the assigned identiﬁer: normally a constraint used in an
expression has the value of the linear expression it contains, the constraint type is ignored.
c:= 3⁎x+y >= 5

Fair Isaac Corporation Conﬁdential and Proprietary Information

34

The Mosel Languagec+= yc:= 3⁎x+y >= 5
c:= c + y

2.8.1.2! Implies c is 3⁎x+2⁎y-5 >= 0
! Implies c is 3⁎x+2⁎y-5 (c becomes unconstrained)

Assignment of structured types

The direct assignment := can also be used with sets, lists, arrays and records under certain conditions.
For sets and lists, reference and value must be of the same type, the system performing no conversion
on structures. For instance it is not possible to assign a set of integers to a set of reals althoughassigning an integer value to a real object is valid.
When assigning records, reference and value must be of the same type and this type must be
assignment compatible: two records having identical deﬁnitions are not considered to be the same typeby the compiler. In most cases it will be necessary to employ a user type to declare the objects. A
record is assignment compatible if all the ﬁelds it includes can be assigned a value. For instance a
record including a decision variable (type mpvar) cannot be used in an assignment: copying a value ofsuch a type has to be performed one ﬁeld at a time skiping those ﬁelds that cannot be assigned.
Two arrays can be used in an assignment if they have strictly the same deﬁnition and are assignment
compatible (i.e. their type supports assignment).
2.8.1.3

About implicit declarations

Each symbol should be declared before being used. However, an implicit declaration is issued when a
new symbol is assigned a value the type of which is unambiguous.
! Assuming A,S,SE are unknown symbols
A:= 1! A is automatically defined!
as an integer reference
S:={1,2,3}! S is automatically defined!
as a set of integers
SE:={}! This produces a parser error as! the type of SE is unknown

In the case of arrays, the implicit declaration should be avoided or used with particular care as Mosel
tries to deduce the indexing sets from the context and decides automatically whether the created arraymust be dynamic. The result is not necessarily what is expected.
A(1):=1
A(t):=2.5! Implies: A:array(1..1) of integer! Assuming "t in 1..10|f(t) > 0"
! implies: A:dynamic array(range) of real

The option noimplicit disables implicit declarations (see Section 2.3.3).
2.8.1.4

Inline initialization

Using inline initialization it is possible to assign several cells of an array in a single statement. The
general form of an inline initialization is:
ident_ref ::[ Exp1 [, Exp2 ...] ]orident_ref ::(Ind1 [, Ind2 ...] )[ Exp1 [, Exp2 ...] ]where ident_ref is the object to initialize (array, set or list) and Expi are expressions of a compatible typewith ident_ref. The ﬁrst form of this statement may be used with lists, sets and arrays indiced byranges: the list of expressions is used to initialize the object. In the case of lists and sets this operation

Fair Isaac Corporation Conﬁdential and Proprietary Information

35

The Mosel Language

is similar to a direct assignment, with an array, the ﬁrst index of each dimension is the lower bound of
the indexing range or 1 if the range is empty.
The second form is used to initialize regions of arrays or arrays indiced by general sets: each Indi
expression indicates the index or list of indices for the corresponding dimension. An index list can be aconstant, a list of constants (e.g. [’a’,’b’,’c’]) or a constant range (e.g. 1..10) but all values
must be known at compile time.
declarations
T:array(1..10) of integer
U:array(1..9,{'a','b','c'}) of integer
end-declarations
T::[2,4,6,8]! <=> T(1):=2; T(2):=4;...
T::(2..5)[7,8,9,19]! <=> T(2):=7; T(3):=8;...
U::([1,3,6],'b')[1,2,3]! <=> U(1,'b'):=1; U(3,'b'):=2;...

2.8.1.5

Linear constraint expression

A linear constraint expression can be assigned to an identiﬁer but can also be stated on its own. In thatcase, the constraint is said to be anonymous and is added to the set of already deﬁned constraints. The
difference from a named constraint is that it is not possible to refer to an anonymous constraint again,
for instance to modify it.
10<=x; x<=20
x is_integer

2.8.1.6

Procedure call

Not all required actions are coded in a given source ﬁle. The Mosel language comes with a set ofpredeﬁned procedures that perform speciﬁc actions (like displaying a message). It is also possible toimport procedures from external locations by using modules or packages (cf. Section 2.3).
The general form of a procedure call is:
procedure_ident
procedure_ident (Exp1 [, Exp2 ...])

where procedure_ident is the name of the procedure and, if required, Expi is the ith parameter for the call(note that parameters of procedures are evaluated from right to left). Refer to Chapter 3 of this manual
for a comprehensive listing of the predeﬁned procedures.The modules documentation should also be
consulted for explanations about the procedures provided by each module.
writeln("hello!")

2.8.2! Displays the message: hello!

Initialization block
The initialization block may be used to initialize objects (scalars, arrays, lists or sets) of basic type fromﬁles or to save the values of such objects to ﬁles. Scalars and arrays of external/user types supporting
this feature may also be initialized using this facility.
The ﬁrst form of an initialization block is used to initialize data from a ﬁle:Fair Isaac Corporation Conﬁdential and Proprietary Information

36

The Mosel Language

initializations from Filename
item1 [ as Label1]
or[itemT11,itemT12 [ ,IdentT13 ...]] asLabelT1[
item2 [ as Label2]
or[itemT21,itemT22 [ ,IdentT23 ...]] asLabelT2...]
end-initializations

where Filename, a string expression, is the name of the ﬁle to read, itemi any object identiﬁer and
itemTij an array identiﬁer. Each identiﬁer is automatically associated to a label: by default this label isthe identiﬁer itself but a different name may be speciﬁed explicitly using a string expression Labeli. If agiven item is of a record type, the operation is permitted only if all ﬁelds it contains can be initialized.
For instance, if one of the ﬁelds is a decision variable (type mpvar), the compilation will fail.
Alternatively, the ﬁelds to be initialized can be listed using the following syntax as an item:
Identiﬁer(ﬁeld1 [ ,ﬁledi ...])

If a given item is a namespace (see Section 2.13) all the identiﬁers it includes at the time of parsing thestatement are implicitly added to the block with the exception of namespaces and entities that are notcompatible with initializations (like decision variables). The associated labels are the fully qualiﬁed
names of the objects (i.e. the identiﬁer preﬁxed by the namespace) unless a label is speciﬁed for thisrecord: in this case it is used as a replacement for the default preﬁx when generating the per entity
labels such that an empty string will remove entirely the preﬁx. Using the compiler option -wi makes it
possible to get a list of included identiﬁers by means of a compiler warning (see Section 1.3).
When an initialization block is executed, the given ﬁle is opened and the requested labels are searched
for in this ﬁle to initialize the corresponding objects. Several arrays may be initialized with a single
record. In this case they must be all indexed by the same sets, have scalar types and the label isobligatory. After the execution of an initializations from block, the control parameter nbreadreports the number of items actually read in. Moreover, if control parameter readcnt is set to true
before the execution of the block, counting is also achieved at the label level: the number of items
actually read in for each label may be obtained using function getreadcnt.
An initialization ﬁle must contain one or several records of the following form:
Label: value

where Label is a text string and value either a constant of a basic type (integer, real, string or
boolean) or a collection of values separated by spaces and enclosed in square brackets. Collectionsof values are used to initialize lists, sets records or arrays — if such a record is requested for a scalar,then the ﬁrst value of the collection is selected. When used for arrays, indices enclosed in roundbrackets may be inserted in the list of values to specify a location in the corresponding array.
Note also that:

no particular formatting is required: spaces, tabulations, and line breaks are just normal
separatorsthe special value ’*’ implies a no-operation (i.e. the corresponding entity is not initialized)single line comments are supported (i.e. starting with ’!’ and terminated by the end of the line)

Boolean constants are either the identiﬁers false (FALSE) and true (TRUE) or the numericalconstants 0 and 1

Fair Isaac Corporation Conﬁdential and Proprietary Information

37

The Mosel Language

all text strings (including the labels) may be quoted using either single or double quotes. In thelatter case, escape sequences are interpreted (i.e. use of ’\’).

By default Mosel expects that initialization ﬁles are encoded in UTF-8 and it can handle UTF-16 and
UTF-32 when a BOM (Byte Order Mark) is used. To process ﬁles in another encoding, a special
encoding comment line must be put at the beginning of the ﬁle (see section 2.5.1). For instance a dataﬁle encoded with CP1252 should start with the following comment line:!@encoding:CP1252

The second form of an initialization block is used to save data to a ﬁle:initializations to Filename
item1 [as Label1]
or[itemT11,itemT12 [ ,IdentT13 ...]]asLabelT1[
item2 [ as Label2]
or[itemT21,itemT22 [ ,IdentT23 ...]]asLabelT2...]
end-initializations

In this form, any itemi can be replaced by the value of an expression using the following construct(Labeli is mandatory in this case):evaluation of expression

When this second form is executed, the value of all provided labels is updated with the current value ofthe corresponding identiﬁer1 in the given ﬁle. If a label cannot be found, a new record is appended tothe end of the ﬁle and the ﬁle is created if it does not yet exist.
For example, assuming the ﬁle a.dat contains:! Example of the use of initialization blocks
t:[ (1 un) [10 11] (2 deux) [⁎ 22] (3 trois) [30 33]]
t2:[ 10 (4) 30 40 ]'nb used': 0

consider the following program:model "Example initblk"
declarations
nb_used:integers: set of stringta,tb: dynamic array(1..3,s) of realt2: array(1..5) of integer
end-declarations
initializations from 'a.dat'[ta,tb] as 't'! ta=[(1,'un',10),(3,'trois',30)]! tb=[(1,'un',11),(2,'deux',22),(3,'trois',33)]t2! t2=[10,0,0,30,40]
nb_used as "nb used" ! nb_used=0
end-initializations
nb_used+=1ta(2,"quatre"):=1000
1 A copy of the original ﬁle is saved prior to the update (i.e. the original version of fname can be found in fname˜).

Fair Isaac Corporation Conﬁdential and Proprietary Information

38

The Mosel Language

initializations to 'a.dat'[ta,tb] as 't'
nb_used as "nb used"s
end-initializations
end-model

After the execution of this model, the data ﬁle contains:! Example of the use of initialization blocks
t:[(1 'un') [10 11] (2 'deux') [⁎ 22] (2 'quatre') [1000 ⁎](3 'trois') [30 33]]
t2:[ 10 (4) 30 40 ]'nb used': 1's': ['un' 'deux' 'trois' 'quatre']

In case of error (e.g. ﬁle not found, corrupted data format) during the processing of an initialization
block, the execution of the model is interrupted. However if the value of control parameter ioctrl istrue, executions continues. It is up to the user to verify whether data has been properly transfered bychecking the value of control parameter iostatus.
2.8.2.1

About automatic ﬁnalization

During the execution of an initializations from block all sets are automatically ﬁnalized just after having
been initialized (unless they have been explicitly declared as dynamic). This also applies to setsindirectly initialized through the non-dynamic arrays for which they are index sets. In addition, such anarray is created as a static array if it has not been used before the initialization block.
This behaviour is controled by the autofinal control parameter which value may be changed using
the setparam procedure (i.e. it is therefore possible to have automatic ﬁnalization active for only
some initializations blocks). The compiler option noautofinal (see section 2.3.3) allows to disable
this feature from the beginning of the model (although it can be re-enabled as required using thecontrol parameter).

2.8.3

Selections
2.8.3.1

If statement

The general form of the if statement is:
if Bool_exp_1
then Statement_list_1[
elif Bool_exp_2
then Statement_list_2...][ else Statement_list_E ]end-if

The selection is executed as follows: if Bool_exp_1 is true then Statement_list_1 is executed and theprocess continues after the end-if instruction. Otherwise, if there are elif statements, they are
executed in the same manner as the if instruction itself. If, all boolean expressions evaluated arefalse and there is an else instruction, then Statement_list_E are executed; otherwise no statement is
executed and the process continues after the end-if keyword.
if c=1

Fair Isaac Corporation Conﬁdential and Proprietary Information

39

The Mosel Language
then writeln('c=1')
elif c=2
then writeln('c=2')
else writeln('c<>1 and c<>2')
end-if

2.8.3.2

Case statement

The general form of the case statement is:case Expression_0 ofExpression_1: Statement_1
orExpression_1: do Statement_list_1 end-do[
Expression_2: Statement_2
orExpression_2: do Statement_list_2 end-do...][ else Statement_list_E ]end-case

The selection is executed as follows: Expression_0 is evaluated and compared sequentially with each
expression of the list Expression_i until a match is found. Then the statement Statement_i (resp. list of
statements Statement_list_i) corresponding to the matching expression is executed and the execution
continues after the end-case instruction. If no matching is found and an else statement is present,
the list of statements Statement_list_E is executed, otherwise the execution continues after theend-case instruction. Note that, each of the expression lists Expression_i can be either a scalar, a set
or a list of expressions separated by commas. In the last two cases, the matching succeeds if theexpression Expression_0 corresponds to an element of the set or an entry of the list.
case c of1: writeln('c=1')
2..5 : writeln('c in 2..5')
6,8,10: writeln('c in {6,8,10}')else writeln('c in {7,9} or c >10 or c <1')end-case

2.8.4

Loops
2.8.4.1

Forall loop

The general form of the forall statement is:forall (Iterator_list) Statement
or
forall (Iterator_list) do Statement_list end-do

The statement Statement (resp. list of statements Statement_list) is repeated for each possible index
tuple generated by the iterator list (cf. Section 2.7.2).
forall (i in 1..10, j in 1..10 | i<>j) dowrite(' (' , i, ',' , j, ')')
if isodd(i⁎j) then s+={i⁎j}end-ifend-doFair Isaac Corporation Conﬁdential and Proprietary Information

40

The Mosel Language

2.8.4.2

While loop

The general form of the while statement is:while (Bool_expr) Statement
or
while (Bool_expr) do Statement_list end-do

The statement Statement (resp. list of statements Statement_list) is repeated as long as the condition
Bool_expr is true. If the condition is false at the ﬁrst evaluation, the while statement is entirely
skipped.
i:=1
while(i<=10) do
write(' ',i)
if isodd(i) then s+={i}end-ifi+=1
end-do2.8.4.3

Repeat loop

The general form of the repeat statement is:repeatStatement1[ Statement2 ...]
until Bool_expr

The list of statements enclosed in the instructions repeat and until is repeated until the condition
Bool_expr is true. As opposed to the while loop, the statement(s) is (are) executed at least once.
i:=1
repeatwrite(' ',i)
if isodd(i) then s+={i}end-ifi+=1
until i>10

2.8.4.4 break and next statements
The statements break and next are respectively used to interrupt and jump to the next iteration of aloop. The general form of the break and next statements is:break [n|label]ornext [n|label]

where n is an optional integer constant: n-1 nested loops are stopped before applying the operation.
This optional argument may also be a label (in the form an identiﬁer or a string constant): in this casethe loop to consider is identiﬁed by a label that must be deﬁned just before the corresponding loop
using the following syntax:
label :

Fair Isaac Corporation Conﬁdential and Proprietary Information

41

The Mosel Language

The label can be either an identiﬁer (that is not associated to any entity) or a constant string. The scopeof each label is limited to the loop it identiﬁes.
! in this example only the loop controls are shown
L1:! 1: Define label "L1"
repeat! 2: Loop L1
forall (i in S) do ! 3: Loop L2
while (C3) do! 4: Loop L3
break 3
! 5: Stop the 3 loops and continue after line 12
next! 6: Go to next iteration of L3 (line 4)
next 2! 7: Stop L3 and go to next 'i' (line 3)
end-do! 8: End of L3
next "L1"! 9: Stop L2, go to next iteration of L1 (line 12)
break!10: Stop L2 and continue after line 11
end-do!11: End of L2
until C1
!12: End of L1

2.8.4.5 with statement
The general syntax of this statement is:with ident_1=exp_1 [, ident_2=exp_2...] doStatement[ Statement ...]
end-doAlthough the with statement is not a loop it is handled like a single iteration forall loop such that it
is possible to use the break statement within the block of instructions. The identiﬁers ident_i aredeﬁned as local symbols to the block.
! in this example LR is an array of records
with r=LR(10) do
r.x:=10! update LR(10).xr.y:=20! update LR(10).y
end-do2.9

Procedures and functions
It is possible to group sets of statements and declarations in the form of subroutines that, oncedeﬁned, can be called several times during the execution of the model. There are two kinds ofsubroutines in Mosel, procedures and functions. Procedures are used in the place of statements (e.g.
writeln("Hi!")) and functions as part of expressions (because a value is returned, e.g.
round(12.3)). Procedures and functions may both receive arguments, deﬁne local data and callthemselves recursively.

2.9.1

Deﬁnition
Deﬁning a subroutine consists of describing its external properties (i.e. its name and arguments) andthe actions to be performed when it is executed (i.e. the statements to perform). The general form of aprocedure deﬁnition is:procedure name_proc [(list_of_parms)]
Proc_body
end-procedure

Fair Isaac Corporation Conﬁdential and Proprietary Information

42

The Mosel Language

where name_proc is the name of the procedure and list_of_parms its list of formal parameters (if any).
This list is composed of symbol declarations (cf. Section 2.6) separated by commas. The only
difference from usual declarations is that no constants or expressions are allowed, including in theindexing list of an array (for instance A=12 or t1:array(1..4) of real are not valid parameter
declarations). The body of the procedure is the usual list of statements and declaration blocks exceptthat no procedure or function deﬁnition can be included.
procedure myproc
writeln("In myproc")
end-procedure
procedure withparams(a:array(r:range) of real, i,j:integer)
writeln("I received: i=",i," j=",j)forall(n in r) writeln("a(",n,")=",a(n))
end-procedure
declarations
mytab:array(1..10) of real
end-declarations
myprocwithparams(mytab,23,67)! Call myproc! Call withparams

The deﬁnition of a function is very similar to the one of a procedure:function name_func [(List_of_params)]: TypeFunc_bodyend-function

The only difference with a procedure is that the function type must be speciﬁed: it can be any typename except mpvar. Inside the body of a function, a special variable of the type of the function is
automatically deﬁned: returned. This variable is used as the return value of the function, it must
therefore be assigned a value during the execution of the function.
function multiply_by_3(i:integer):integer
returned:=i⁎3
end-function
writeln("3⁎12=", multiply_by_3(12))! Call the function

Normally all statements of a subroutine are executed in sequence. It is however possible to interrupt
the execution and return to the caller by using the special statement return.

2.9.2

Formal parameters: passing convention
Formal Parameters of basic types are passed by value and all other types are passed by reference. In
practice, when a parameter is passed by value, the subroutine receives a copy of the information so, if
the subroutine modiﬁes this parameter, the effective parameter remains unchanged. But if a parameteris passed by reference, the subroutine receives the parameter itself. As a consequence, if theparameter is modiﬁed during the process of the subroutine, the effective parameter is also affected.
procedure alter(s:set of integer,i:integer)i+=1
s+={i}
end-procedure
gs:={1}gi:=5alter(gs,gi)
writeln(gs," ",gi)

Fair Isaac Corporation Conﬁdential and Proprietary Information! Displays: {1,6} 5

43

The Mosel Language

2.9.3

Local declarations
Several declaration blocks may be used in a subroutine and all identiﬁers declared are local to thissubroutine. This means that all of these symbols exist only in the scope of the subroutine (i.e. between
the declaration and the end-procedure or end-function statement) and all of the resource theyuse is released once the subroutine terminates its execution unless they are referenced outside of theroutine (e.g. member of a set deﬁned globally). As a consequence, active constraints (linctr that are
not just linear expressions) declared inside a subroutine and the variables they employ are still effective
after the termination of the subroutine (because they are part of the current problem) even if thesymbols used to name the related objects are not deﬁned any more. Note also that a local declaration
may hide a global symbol.
declarations
i,j:integer
end-declarations! Global definition

procedure myproc
declarations
i:string! This declaration hides the global symbol
end-declarations
i:="a string"! Local 'i'
j:=4writeln("Inside of myproc, i=",i," j=",j)end-procedurei:=45! Global 'i'
j:=10
myprocwriteln("Outside of myproc, i=",i," j=",j)This code extract displays:
Inside of myproc, i=a string j=4
Outside of myproc, i=45 j=4

2.9.4

Overloading
Mosel supports overloading of procedures and functions. One can deﬁne the same function several
times with different sets of parameters and the compiler decides which subroutine to use dependingon the parameter list. This also applies to predeﬁned procedures and functions.
! Returns a randomly generated integer in the interval [1,limit]
function random(limit:integer):integer
returned:=round(.5+random⁎limit)! Use the predefined! 'random' function
end-function

It is important to note that:



2.9.5

a procedure cannot overload a function and vice versa;
it is not possible to redeﬁne any identiﬁer; this rule also applies to procedures and functions. A
subroutine deﬁnition can be used to overload another subroutine only if it differs for at least one
parameter. This means, a difference in the type of the return value of a function is not sufﬁcient.

Forward declaration
During the compilation phase of a source ﬁle, only symbols that have been previously declared can beused at any given point. If two procedures call themselves recursively (cross recursion), it is therefore

Fair Isaac Corporation Conﬁdential and Proprietary Information

44

The Mosel Language

necessary to be able to declare one of the two procedures in advance. Moreover, for the sake of clarity
it is sometimes useful to group all procedure and function deﬁnitions at the end of the source ﬁle. A
forward declaration is provided for these uses: it consists of stating only the header of a subroutinethat will be deﬁned later. The general form of a forward declaration is:forward procedure Proc_name [(List_of_params)]orforward function Func_name [(List_of_params)]: Basic_typewhere the procedure or function Func_name will be deﬁned later in the source ﬁle. Alternatively asubroutine can be declared by stating its header inside of a declarations block. Note that a forward
declaration for which no actual deﬁnition can be found is considered as an error by Mosel.
forward function f2(x:integer):integer

2.9.6

function f1(x:integer):integer
returned:=x+if(x>0,f2(x-1),0)
end-function! f1 needs to know f2

function f2(x:integer):integer
returned:=x+if(x>0,f1(x-1),0)
end-function! f2 needs to know f1

Sufﬁx notation
Functions which name begins with get and taking a single argument may be called using a sufﬁx
notation. This alternative syntax is constructed by appending to the variable name (the intended
function parameter) a dot followed by the function name without its preﬁx get. For instance the callgetsol(x) is the same as x.sol. The compiler performing internally the translation from the sufﬁx
notation to the usual function call notation, the two syntaxes are equivalent.
Similarly, calls to procedures which name begins with set and taking two arguments may be written as
an assignment combined with a sufﬁx notation. In this case the statement can be replaced by thevariable name (the intended ﬁrst procedure parameter) followed by a dot and the procedure namewithout its preﬁx set then the assignment sign := and the value corresponding to the second
parameter. For instance the statement sethidden(ctl,true) can also be written
ctl.hidden:=true. As for the other alternative notation, the compiler performs the rewriting
internally and the two syntaxes are equivalent.

2.10

Problems
In Mosel terms, a problem is a container holding various attributes and entities. The nature of theinformation stored is characterised by a problem type. The core system of Mosel provides thempproblem problem type for the representation of mathematical programming problems with linear
constraints. Other types may be published by modules either as entirely new problem types or as
problem type extensions. An extension adds extra functionality or properties to an existing type; forinstance, mpproblem.xprs provided by the module mmxprs adds support for solving mpproblem
problems while the type mpproblem.nl of mmnl makes it possible to include non-linear constraints in
an mpproblem.
When the execution of the model starts, an instance of each of the available problem types is created:
this main problem constitutes the default problem context. As a consequence, all problem related
operations (e.g., add constraints, solve...) refer to this context. Further problem instances may bedeclared just like any other symbol using a declarations section. The speciﬁcation of a problem type(that is used as an elementary type in a declaration) has two forms:

Fair Isaac Corporation Conﬁdential and Proprietary Information

45

The Mosel Language

problem_type
orproblem_type1 and problem_type2 [and problem_typen ...]

where problem_type* are problem type names. The second syntax allows to deﬁne a problem instancethat refers to several problem types: this can be useful if a particular problem consists in the
combination of several problem types. Note also that the main problem can be seen as an instance ofthe combination of all available problem types.
The with construct can be used to switch to a different problem context for the duration of a block of
instructions. The general form of this construct is:with prob doStatement[ Statement ...]
end-dowhere prob is a problem reference or a problem type speciﬁcation. In the ﬁrst case the referenced
problem is selected, in the second case, a new problem instance is created for the duration of the block(i.e., it is released after the block has been processed). Both statements and declaration blocks as wellas other with constructs may be included in this section: they are all executed in the context of theselected problem.
declarations
p1,p2:mpproblem
p3:mpproblem and mypb
PT=mpproblem and mypb
a:array(1..10) of PT
x,y:mpvar
end-declarations
with p1 do
x+y>=0
end-dowith p2 do
x-y=1
end-do! assuming 'mypb' is a problem type! user defined problem type

Some problem types support assignment (operator :=) and additive assignment (operator +=). These
operators can be used between objects of same type but also when the right parameter of the operator
is a component of the assigned object. For instance, assuming the declarations of the previous
example we could state p3:=p2 meaning that the mpproblem part of p3 must be replaced by a copyof p2, the mypb part of p3 remaining unchanged. From the same context, the assignment p2:=p3
produces a compilation error.

2.10.1

The mpproblem typeAn mpproblem instance basically consists in a set of linear constraints (the decision variables deﬁned
anywhere in a model are shared by all problems). A constraint is incorporated into a problem when it isexpressed, so having the declaration of a linctr identiﬁer in the context of a problem is not sufﬁcient
to attach it to this problem. The association will occur when the symbol is assigned its ﬁrst value.
Afterwards, the constraint will remain part of the same problem even if it is altered from within thecontext of another problem (a constraint cannot belong to several problems at the same time).
with p1 do
C1:=x+y+z>=0
x is_integer
end-dowith p2 do

Fair Isaac Corporation Conﬁdential and Proprietary Information

46

The Mosel Language2⁎x-3⁎z=0! here we state constraints of p2...
minimize(z)C1+= x.sol⁎z.sol
end-doIn the example above, the constraint C1 is part of problem p1. From the context of a second problem
p2 the constraint C1 is modiﬁed using solution information of p2: this change affects only the ﬁrst
problem since the constraint does not belong to the current context. Note that since is_integer is a(unary) constraint, the decision variable x is integer for problem p1 but it is a continuous variable in p2.
When a problem is released or reset (see reset), all its constraints are detached. Constraints which
are not referenced (anonymous constraints) are released at the same time, named constraints however
are not freed, they become available to be associated to some other problem.
with mpproblem do
C1:=x+y+z>=0 ! (1)x-2⁎y=10! (2)x is_integer ! (3)end-dowith p1 do
C1
end-doIn this example, at the end of the ﬁrst with block, the local problem is released. As a consequence theconstraint C1 is detached from this problem (but remains unchanged) and the 2 other constraints are
freed. The following statements add C1 to the problem p1.
The type mpproblem supports both assignment (operator :=) and additive assignment (operator +=).

2.11

The public qualiﬁer
Once a source ﬁle has been compiled, the identiﬁers used to designate the objects of the model
become useless for Mosel. In order to access information after a model has been executed (forinstance using the print command of the interractive debugger), a table of symbols is saved in theBIM ﬁle.
The qualiﬁer public can be used in declaration and deﬁnition of objects to mark those identiﬁers(including subroutines) that must be published in the table of symbols. Without this qualiﬁer a symbol
is considered to be private and it is not recorded in the table of symbols (unless the source is compiled
with debugging information).
public declarations
e:integer
f:integer
end-declarations! e is published! f is publisheddeclarations
public a,b,c:integerd:real
end-declarations! a,b and c are published! d is private

forward public procedure myproc(i:integer)! 'myproc' is publishedThis qualiﬁer can also be used when declaring record types in order to select the ﬁelds of the recordthat can be accessed from outside of the ﬁle making the deﬁnitions: this allows to make available only
a few ﬁelds of a record, hidding what is considered to be internal data.
declarations
public t1=record

Fair Isaac Corporation Conﬁdential and Proprietary Information

47

The Mosel Language
i:integer
public j:real
end-record
public t2=public record
i:integer
j:realend-record
end-declarations! t1.i is private! t1.j is public! t2.i is public! t2.j is public

Note that a public record type can only contain public types even if it does not publish its ﬁelds.

2.12

Packages
Declarations may be stored in a package: once compiled, the package can be used by any model bymeans of the uses or import statements (see Section 2.3.1). Except for its beginning and termination(keyword model is replaced by package) a package source is similar to a normal model source. The
following points should be noticed:








2.12.1

all statements and declarations outside procedure or function deﬁnitions are used as an
initialization routine: they are automatically executed before statements of the model using the
package;symbols that should be published by the package must be made explicitly public using the
public qualiﬁer (see Section 2.11);
model parameters of a package are automatically added to the list of parameters of the modelusing the package;a package cannot be imported several times by a model and packages publish symbols of
packages they import. For instance, assuming package P1 imports package P2, a model using P1
cannot import or use explicitly P2 but has access to the functionality of P2 via P1.

Version management
When a package deﬁnes a version number (see Section 2.3.4) Mosel implements a compatility rulesimilar to the one used for modules: a package version A can be used in place of package version B if
major(A) = major(B) and minor(A) ≥ minor(B). This mechanism applies at compile time (when using
different packages with the same dependencies) and at runtime when loading a model.

2.12.2

The requirements block
Requirements are symbols a package requires for its processing but does not deﬁne. These required
symbols are declared in requirement blocks which are a special kind of declaration blocks in whichconstants are not allowed but procedure/functions can be declared. The symbols of such a block haveto be deﬁned when the model using the package is compiled: the deﬁnitions may appear either in themodel or in another package but cannot come from a module. Several packages used by a given model
may have the same requirements (i.e. same identiﬁer and same declaration). It is also worth notingthat a package inherits the requirements of the packages it uses.
requirements
an_int:integers0: set of string
bigar: array(S0) of realprocedure doit(i:integer)
end-requirements

Fair Isaac Corporation Conﬁdential and Proprietary Information

48

The Mosel Language

2.12.3Control parameters
Packages may deﬁne control parameters that can be used just like those of modules via routines
getparam and setparam. A control parameter is deﬁned in the parameters block (see Section 2.4)
using the following syntax:
pname: type_namewhere pname is the name of the parameter as a constant string and type_name its type (either
integer, real, string or boolean). In addition to this declaration accessor routines must be
deﬁned: for handling integer parameters the public function
pkgname~getiparam(pname:string):integer and the public procedure
pkgname~setparam(pname:string,v:integer) must be deﬁned (pkgname being the name of
the current package). The function will be called by getparam to retrieve the value of the speciﬁed
parameter (as a string in lower case) and the procedure will be used by setparam to change theparameter value. Similar deﬁnitions will be required for the other types (assuming the package declaresparameters of the corresponding types), namely getrparam (real parameters), getsparam (string
parameters) and getbparam (Boolean parameters) as well as the associated procedures setparam.
The following example shows the required deﬁnitions for the package mypkg to publish realparameters p1 and p2:
parameters"p1":real"p2":real
end-parameters
declarations
myp1,myp2:real
end-declarations! private variables to hold parameter values! get value function for real parameters
public function mypkg~getrparam(p:string):realcase p of"p1": returned:=myp1"p2": returned:=myp2
end-caseend-function! set value procedure for real parameters
public procedure mypkg~setparam(p:string,v:real)case p of"p1": myp1:=v"p2": myp2:=v
end-case
end-procedure

2.13

Namespaces
All identiﬁers (variables and subroutines names) of a program are implicitly collected in a global
dictionary shared by the program itself and all packages and modules it uses. It is also possible togroup certain identiﬁers under a namespace that is characterised by a name. A given identiﬁer may
appear in several namespaces and each of its occurrences refers to a different entity, as aconsequence an entity is unambiguously identiﬁed by its name and the namespace to which it is amember: this is the fully qualiﬁed name of this entity that is noted:
nspc~ident

Where nspc is a namespace name and ident an identiﬁer in this namespace.

Fair Isaac Corporation Conﬁdential and Proprietary Information

49

The Mosel Language

A namespace’s name is also an identiﬁer that must be declared before being used even if it is deﬁned
by a package already loaded. This declaration is achieved using the namespace compiler directive:
namespace ns1 [, ns2 ...]

Where nsi are the names of the namespaces that will be used in the program. As an identiﬁer anamespace may be declared as part of another namespace and any of the nsi may have the form
nsx~nsy to declare nsy as a namespace included in nsx. Several namespace directives may bestated.
When the compilation starts a namespace is automatically created: it is used to collect all private
symbols of the program. When compiling a model this namespace has an empty name (i.e. a fully
qualiﬁed name of this namespace is of the form ~ident) and for a package it has the same name as the
package.
When looking for an identiﬁer (that is not fully qualiﬁed) the compiler tries ﬁrst to ﬁnd it in the global
dictionary and then searches in a predeﬁned list of namespaces. This list is initialised with thenamespace of private symbols and may be extended using the nssearch directive:
nssearch ns1 [, ns2 ...]

This statement adds the speciﬁed namespaces to the search list. If the directive is stated several
times, each added list is appended to the current list of namespaces. The namespace search is notrecursive: it is not sufﬁcient to add a namespace to the search list to have all its included namespaces
to be also part of the search list (e.g. if ns1 includes ns11 and ns12, the 3 names ns1,ns1~ns11 andns1~ns12 must be put into the search list for all the identiﬁers to be searchable). Note thatnamespaces listed in a nssearch directive do not need to be declared in a namespace directive.
Any namespace deﬁned in a package is available to any model or package using it (and all theidentiﬁers it includes are implicitly public). Deﬁning a namespace group makes it possible to allow only
certain packages to access a given namespace. The deﬁnition of such a group requires the use of a
dedicated compiler directive:
nsgroup nspc: pkg1 [, pkg2 ...]
or
nsgroup nspc

Where pkgi are the package names (as constant strings) that will be allowed to access namespacenspc. By default the automatic namespace containing the private symbols of a package has a groupcontaining only the package itself such that it cannot be used by any external component. It is however
possible to redeﬁne this initial group with a nsgroup directive, in particular the second form of thedirective (without specifying any package) makes the corresponding namespace available to any
package. Note that namespaces listed in a nsgroup directive do not need to be declared in anamespace directive.

2.14

Annotations
Annotations are meta data expressed in the Mosel source ﬁle that are stored in the resulting bim ﬁleafter compilation. Thanks to a dedicated API it is possible to retrieve the information both from themodel itself during its execution (see getannotations) or before/after execution from a hostapplication (see function XPRMgetannotations in the Mosel Libraries Reference Manual).

Fair Isaac Corporation Conﬁdential and Proprietary Information

50

The Mosel Language

2.14.1

SyntaxAnnotations are organised in categories. A category groups a set of annotations and other categories(or sub-categories). When expressing a full annotation name, categories are separated by the ’.’symbol. For instance:
doc.name

will be used to select the annotation name that is a member of the doc category. Similarly:
mycat1.cat2.info

will reference the annotation info recorded in the category cat2 that is itself part of category
mycat1. Annotations and annotation categories must be valid Mosel identiﬁers: their names can only
use alpha-numeric symbols plus ’_’.
Some predeﬁned categories are available at the beginning of the compilation:

the default category (its name is empty) collects annotations that are not explicitly member ofany particular category. For instance the annotation myannot will be recorded in the default
category. This annotation may also be referenced by its full name .myannot
mc (for Mosel Compiler) is used to pass information to the compiler during the compilation. For
example, the mc.def annotation makes it possible to declare an annotation type (see section
2.14.3)doc can be used to document a model or package ﬁle (see section 2.20)

In the Mosel source ﬁle annotations are included in special comments. A single-line annotation is of theform:!@ name value

Here name is the name of the annotation (spaces between ’@’ and the name are ignored) and thefollowing text (up to the end of line) its corresponding value. The separation character between thename and the value can be a space, ’:’ or ’=’ (there must be no space between the name and thesymbol). There is no restriction on the content of the value: it can be any kind of text (unless theannotation is typed—see section 2.14.3).
A multi-line annotation is of the form:(!@name value...
@name2 value2...
!)

where name is an annotation name while the text following this name is its associated value. With this
syntax the value may spread over several lines, its termination is marked either by the end of thecomment block or by a new annotation speciﬁcation. In this context, a new annotation must start withthe ’@’ symbol at the beginning of a new line (leading spaces are ignored). As for a one-line
annotation, symbols ’:’ and ’=’ can be used instead of a space to separate the name and its value.
If several annotations of the same category have to be deﬁned in the same block, a current category
may be deﬁned such that following annotation names can be shortened. This mechanism is activatedby specifying the category name terminated by a dot (the remainder of this line is ignored) before theﬁrst annotation statement. The category selection is effective for the current comment block only andFair Isaac Corporation Conﬁdential and Proprietary Information

51

The Mosel Language

remains active until the next selection. Using a dot in place of a category name restores the default
behaviour (i.e. the full path must be used for annotation reference). For instance:(!@doc.
Switch to 'doc' category (this text is ignored)@name:my_function@type:integer@mycat.cat1. Switch to 'mycat.cat1'@memb1 10@memb2 20@.
Unselect current category@glb=useless!)Is equivalent to:(!@doc.name:my_function@doc.type:integer@mycat.cat1.memb1 10@mycat.cat1.memb2 20@glb=useless!)

By default any new annotation name is added to the internal dictionary and no checking is applied tothe provided value. If a given annotation is deﬁned several times only the last assignment is preserved.
The compiler will however emit a warning if an attempt is made to assign a value to a category or touse an annotation as a category. For instance:!@mycat.memb1 10!@mycat.memb1.memb2 20

The second deﬁnition will fail to use mycat.memb1 as a category because the ﬁrst one has already
implicitly declared it as an annotation.

2.14.2

Symbol association
An annotation is either global or associated with a speciﬁc public symbol (see section 2.11). The
association depends on the location of the deﬁnition in the source code:annotations preceding a subroutine declaration (forward statement) or deﬁnition are associatedwith the subroutine nameannotations preceding a declarations block are distributed to all the symbols declared in the block
inside of a declarations block: annotations preceding or terminating the line of a declaration areassociated with the corresponding symbols

In all other cases the annotations are global (i.e. not associated with any particular symbol) — inparticular trying to associate annotations to private symbols will result in global annotations.
Annotations that precede a subroutine declaration, a declarations block or an entity in a declarations
block can be turned into global annotations by inserting the compiler annotation mc.flush between
the annotation and the following code.

2.14.3Declaration
Declaration of annotations is achieved via the mc.def compiler annotation. Once an annotation isdeclared, the compiler checks the validity of deﬁnitions and rejects those that are not compliant,

Fair Isaac Corporation Conﬁdential and Proprietary Information

52

The Mosel Language

issuing a warning message (invalid annotations will not make the compilation fail unless the ﬂag
strict is used).
The general syntax of the annotation declaration statement is:!@mc.def aname [prop1[,prop2...]]

Where aname is an annotation name and prop? a property keyword. The possible keywords are:alias name1 name2...

aname Deﬁning an alias to name1, name2...

text|integer|real|boolean
last|first|merge|multiType of the annotation value (default:text).

Handling of multiple deﬁnitions of an annotation (default:last)

last: the last deﬁnition is kept

first: keep the ﬁrst deﬁnition (the following ones are ignored)merge: deﬁnitions are concatenated (separated by new lines)

multi: all deﬁnitions are kept

global|specific By default, the association of annotations depends on the location of thedeﬁnition. If global is stated, the annotation is always global; with option specific,
the annotation will be kept only if it can be associated with a symbol (otherwise it isignored instead of being stored as a global one).
values=v1 v2 v3... If used, this option must be the last one of the deﬁnition and it cannot be
combined with range. It deﬁnes a list of possible values for the annotation.
range=lb ub

If used, this option must be the last one of the deﬁnition, it requires the type to be
speciﬁed (integer or real) and it cannot be combined with values. It deﬁnes arange of possible values.

strictWhen this option has been stated any error detected on this annotation (or path whenapplied to a category) will make the compilation fail

Example:!@mc.def person.name text,first,specific!@mc.def person.age integer,first,specific,range=0 150!@mc.def person.gender values=male female

Categories are implicitly declared by the annotations they include (for instance declaring@mycat.myann implies the creation of mycat as a category). It is also possible to explicitly declare an
empty category (i.e. containing no annotation) using the mc.def construct by appending a dot to thecategory name (the only supported property is strict). For instance:!@mc.def mycat.

For a given annotation the declaration may be stated several times but the properties of an annotation
cannot be changed. For instance, the following declarations can be used in the same source:!@mc.def myann!@mc.def myann text,last

But the following declaration cannot be combined with any of the two preceding ones as they bothresult in the annotation type text:

Fair Isaac Corporation Conﬁdential and Proprietary Information

53

The Mosel Language!@mc.def myann integer

Declarations included in models are not exported to the bim ﬁle (i.e. they are only used during thecompilation procedure) but declarations stated in packages are published if they are relative to a user
deﬁned category: any model using the package inherits the annotation declarations of the package.
Additional properties can be set using the mc.set compiler annotation. The general syntax of thisspecial statement is:!@mc.set name flag

Where name is an annotation or category name and flag one of the following keywords:
complete

Applied to a category this ﬂag indicates that no other annotation can be added to thiscategory (ignored for an annotation). It is however still possible to declare aliases. Notethat sub-categories are not concerned by this ﬂag: if required each sub-category has
also to be tagged.

disableDisable the named category or annotation. From the point where this ﬂag has been set
onwards, all deﬁnitions deriving from the provided name are silently ignored.

enableRevert the effect of disable.

unpublish

Disable the automatic publication of the speciﬁed declaration.

publishPublish the speciﬁed declaration.

Note that mc.set expects a full explicit name: for this command ann refers to category ann and not toannotation .ann as in other places.

2.15

File names and input/output drivers
Mosel handles data streams using I/O drivers: a driver is an interface between Mosel and a physicaldata source. Its role is to expose the data source in a standard way such that from the user perspective,
all data sources can be accessed using the same methods (i.e. initializations blocks, ﬁlehandling functions). Drivers are speciﬁed in ﬁle names: all Mosel functions supporting I/O operations
through drivers can be given an extended ﬁle name. This type of name is composed of the pairdriver_name:ﬁle_name. When Mosel needs to access a ﬁle, it looks for the speciﬁed driver in the tableof available drivers. This table contains all predeﬁned drivers as well as drivers published by modules
currently loaded in memory. If the driver is provided by a module, the module name may also be
indicated in the extended ﬁle name: module_name.driver_name:ﬁle_name. Using this notation, Mosel
loads the required module if necessary (otherwise the ﬁle operation fails if the module is not alreadyloaded). For instance it is better to use mmodbc.odbc:database than odbc:database.
The ﬁle_name part of the extended ﬁle name is speciﬁc to the driver and its structure and meaning
depends on the driver. For instance, the sysfd driver expects a numerical ﬁle descriptor so ﬁlesysfd:1 is a valid name but sysfd:myfile cannot work. A driver may act as a ﬁlter and expects as
ﬁle_name another extended ﬁle name (e.g. zlib.deflate:mem:myblk).
When no driver name is speciﬁed, Mosel uses the default driver which name is an empty string(myfile is equivalent to :myfile). This driver relies on OS functions to access ﬁles from the ﬁlesystem. Note that on the Windows operating system Mosel does not support relative paths on a
speciﬁed drive (i.e. the ﬁle "C:myfile" is equivalent to "C:\myfile", the behaviour may be different
in other environments).
The tmp driver is an extension to the default driver: it locates the speciﬁed ﬁle in the temporary directory
used by Mosel (i.e. "tmp:toto" is equivalent to the expression getparam("tmpdir")+"/toto").

Fair Isaac Corporation Conﬁdential and Proprietary Information

54

The Mosel Language

The null driver can be used to disable a stream: whatever written to ﬁle "null:" is ignored andreading from it is like reading from an empty ﬁle.
The mem driver uses a memory block instead of a ﬁle handled by the operating system. A ﬁle name forthis driver is of the form mem:label[/minsize[/incstep]] where label is an identiﬁer whoseﬁrst character is a letter and minsize an optional initial amount of memory to be reserved (size isexpressed in bytes, in kilobytes with sufﬁx "k" or in megabytes with sufﬁx "m"). The label being
recorded in the dictionary of the model symbols it cannot be identical to any of the identiﬁers of themodel (the function newmuid might be used to generate a unique identiﬁer). The memory block isallocated dynamically and resized as necessary. By default the size of the memory block is increasedby pages of 4 kilobytes: the optional parameter incstep may be used to change this page size (i.e. thedefault setting is "label/0/4k"). The special value 0 modiﬁes the allocation policy: instead of being
increased of a ﬁxed amount, the block size is doubled. In all cases unused memory is released when
the ﬁle is closed.
The mem driver may also be used to exchange data with an application using the Mosel libraries (referto the Mosel Libraries Reference Manual for further explanation).
The tee driver can only be open for writing and expects as ﬁle name a list of up to 6 extended ﬁlenames separated with ‘&’: it opens all the speciﬁed ﬁles and duplicates what it receives to each ofthem. If only one ﬁle is given or if the string terminates with ‘&’, output is also sent to the default output
stream (or error stream if the ﬁle is used for errors). For instance, writing to the ﬁle"tee:log1&log2&" has the effect of writing at the same time to ﬁles "log1" and "log2" as well as
sending a copy to the console.
The bin driver can only be used for initializations blocks as a replacement of the default driver:it allows to write (and read) data ﬁles in a platform independent binary format. This ﬁle format is
generally smaller than its ASCII equivalent and preserves accuracy of ﬂoating point numbers. Thisdriver can be used in 2 different ways: a single ﬁle including all records of the initialisations block is
produced if a ﬁle name is provided. For instance, in the following example the ﬁle "mydata" willcontain both A and B:
initialisations to "bin:mydata"AB
end-initialisations

With the second form (without ﬁle name) one ﬁle is generated for each record of the block. The
following example produces 2 ﬁles: "mydata_A" to contain the values of record A and "mydata_B"
for values of B:
initialisations to "bin:"
A as "mydata_A"
B as "mydata_B"
end-initialisations

When using this form in an initialisations to block, the option append may be speciﬁed suchthat ﬁles are open in append mode.
The other predeﬁned drivers (sysfd, cb and raw) are useful when interfacing Mosel with a hostapplication. They are described in detail in the Mosel Libraries Reference Manual.
I/O drivers provided by modules of the Mosel distribution are documented with the corresponding
module (see Part II of this manual).

2.16

Character encoding of text ﬁlesMosel uses UTF-8 for its internal representation of text strings and this is also the default character

Fair Isaac Corporation Conﬁdential and Proprietary Information

55

The Mosel Language

encoding for text ﬁles. It is however possible to read and write text ﬁles in different encodings: formodel source and initialization block ﬁles the selection can be achieved by means of a special
comment (see sections 2.5.1 and 2.8.2) but the encoding may also be speciﬁed at the time of opening
a ﬁle by preﬁxing its name with the "enc:" preﬁx:
enc:encoding [+unix|+dos|+sys] [+bom|+nobom],ﬁlename

Mosel supports natively the encodings UTF-8, UTF-16, UTF-32, ISO-8859-1, ISO-8859-15, CP1252 and
US-ASCII. For UTF-16 and UTF-32 the byte ordering depends on the architecture of the running system(e.g. this is Little Endian on an x86 processor) but it can also be speciﬁed by appending LE (Little
Endian) or BE (Big Endian) to the encoding name (e.g. UTF-16LE). The availability and names of otherencodings depends on the operating system.
The following aliases may also be used in place of an encoding name: RAW (no encoding), SYS (default
system encoding), WCHAR (wide character for the C library), FNAME (encoding used for ﬁle names), TTY(encoding of the output stream of the console), TTYIN (encoding of the input stream of the console),
STDIN, STDOUT, STDERR (encoding of the default input/output/error stream).
In addition to the encoding name a couple of options might be applied: +unix and +dos select the line
termination (note that +dos is automatically used when writing to a physical ﬁle on Windows). Options+bom and +nobom decides whether a Byte Order Mark is to be inserted at the beginning of the ﬁle (thisoption only applies to UTF encodings when the ﬁle is not open in appending mode). By default a BOM isinserted when the encoding is UTF-16 or UTF-32, the option +nobom disables this insertion. The option+bom implies the insertion of a BOM on UTF-8 encoded ﬁles (this is usually not required for thisencoding but often used on Windows systems). The option +sys selects the line termination and BOM
convention of the running system (i.e. it is equivalent to +unix on a Posix system and +dos+bom on a
Windows machine).

2.17

Working directory and temporary directory
Except for absolute path names, ﬁle or path name expansion are relative to the current working
directory. By default this reference location corresponds to the operating system current working
directory which usually is the directory from which Mosel has been started. Since the working directory
is an execution parameter, a model may be running with a current working directory which might bedifferent from the one used by the operating system. It is therefore recommended to use absolute ﬁlenames when a Mosel model communicates with an external component (for instance when a ﬁle nameis part of the DSN to be used for an ODBC connection).
In addition to the current working directory, Mosel creates a temporary directory that is shared by allmodels for storing temporary data handled as physical ﬁles. This directory is located in the systemtemporary directory as speciﬁed by one of the environment variables TMP, TEMP or USERPROFILE
under Windows and TMPDIR on Posix systems. If none of these environment variables is deﬁned, thedefault base directory will be "C:\" on Windows and "/tmp" on Posix systems. The Mosel temporary
directory is automatically created when needed and deleted at program termination.
The path names of the working directory and the temporary directory are identiﬁed respectively by the"workdir" and "tmpdir" control parameters and can be retrieved using the getparam function. It is
possible to change the current working directory of a running model by updating the "workdir"
parameter using setparam.

2.18

Handling of input/output
At the start of the execution of a program/model, three text streams are created automatically: thestandard input, output and error streams. The standard output stream is used by the procedures writing

Fair Isaac Corporation Conﬁdential and Proprietary Information

56

The Mosel Language

text (write, writeln, fflush). The standard input stream is used by the procedures reading text
(read, readln, fskipline). The standard error stream is the destination of error messages reported
by Mosel during its execution. These streams are inherited from the environment in which Mosel isbeing run: usually using an output procedure implies printing something to the console and using an
input procedure implies expecting something to be typed by the user.
The procedures fopen and fclose make it possible to associate text ﬁles to the input, output anderror streams: in this case the IO functions can be used to read from or write to ﬁles. Note that when aﬁle is opened, it is automatically made the active input, output or error stream (according to its opening
status) but the ﬁle that was previously assigned to the corresponding stream remains open. It is
however possible to switch between different open ﬁles using the procedure fselect in combination
with the function getfid.
model "test IO"
def_out:=getfid(F_OUTPUT)
fopen("mylog.txt",F_OUTPUT)
my_out:=getfid(F_OUTPUT)
repeatfselect(def_out)
write("Text? ")text:=''
readln(text)
fselect(my_out)
writeln(text)
until text=''
fclose(F_OUTPUT)
writeln("Finished!")end-model

2.19! Save file ID of default output! Switch output to 'mylog.txt'! Save ID of current output stream! Select default ouput...
! ...to print a message! Read a string from the default input! Select the file 'mylog.txt'! Write the string into the file
! Close current output (='mylog.txt')! Display message to default output

Deploying models
Once a model has been compiled to a BIM ﬁle it may be deployed in a variety of ways. It may berun from some remote code using the remote invocation library XPRD (see the XPRD reference
manual),

be integrated in an application through the Mosel libraries (see Mosel libraries reference manual),

form part of an Xpress Insight application (see the Xpress Insight Developer Guide), or

simply be invoked from a command window or shell.

For the last option the usual approach consists in using the mosel command line tool (see section 1.3)
with the run command. For instance, the following command may be used to run the model
mycmd.bim:> mosel run mycmd.bim

The aim of the deploy module is to ease the use of a model published this way. This module makes it
possible to generate an executable program from the BIM ﬁle. Moreover, it gives the model access tothe command line arguments and exposes a method for embedding conﬁguration ﬁles into theresulting program. The deploy module is usually used through one of its two IO drivers: the ﬁrst driver,
csrc, generates a C program (based on the Mosel libraries) from a BIM ﬁle and the second one, exe,
produces directly the executable by running a C compiler on the generated C source (this requires theavailability of a C compiler on the system). For example the following command will create the programrunmycmd (or runmycmd.exe on Windows) from the model mycmd.mos:

Fair Isaac Corporation Conﬁdential and Proprietary Information

57

The Mosel Language> mosel comp mycmd.mos -o deploy.exe:runmycmd

In addition to its IO drivers, the deploy module publishes two functions for accessing the program
arguments: argc returns the number of parameters passed to the command (counting the command
itself as the ﬁrst) and argv(i) returns the ith argument (as a string). As an example, the following
model displays the arguments it receives:model mycmd
uses 'deploy'
writeln("My arguments:")
forall(i in 1..argc) writeln(argv(i))
end-model

After compiling this example into an executable with the command shown above, an execution of thecommand runmycmd a b c will display:
My arguments:
runmycmdabc

In addition to giving access to command line arguments, deploy makes it possible to embed ﬁles into
the resulting executable. File locations are passed via model parameters. The following example
outputs its source when the program is called with the argument ’src’ — otherwise it reports an error
message:model mycmd2
uses 'deploy','mmsystem'
parameters
SRC="null:"
end-parameters
if argc<>2 or argv(2)<>"src" thenwriteln("Usage: ", argv(1), " src")
exit(1)else
writeln("Source:")
fcopy(SRC,"")
end-ifend-model

In this example, the source ﬁle is identiﬁed by the model parameter SRC. To generate the program, thefollowing command has to be issued:> mosel comp mycmd2.mos -o deploy.exe:runmycmd2,SRC=mycmd2.mos

With the command above, the ﬁle mycmd2.mos is included in the executable and the SRC parameter is
redeﬁned such that the model can access the ﬁle through memory. Note that the model ﬁle can also be
included in the executable in compressed form. To enable this feature, the parameter name has to be
sufﬁxed with -z in the compilation command:> mosel comp mycmd2.mos -o deploy.exe:runmycmd2,SRC-z=mycmd2.mos

2.20

Documenting models using annotations
The predeﬁned doc annotation category can be used to document a Mosel ﬁle. Using a dedicated set

Fair Isaac Corporation Conﬁdential and Proprietary Information

58

The Mosel Languageof annotations the model author can add descriptions to the various entities deﬁned in the source, theuser-deﬁned descriptions are completed by deﬁnitions automatically generated by the Mosel compiler.
From a bim ﬁle that includes such deﬁnitions a documentation processor may produce a complete
document: as an example, the Xpress distribution comes with the moseldoc processor that generates
an HTML documentation from an annotated bim ﬁle.

2.20.1 doc annotation category
Unlike other annotation categories, the doc annotation category is disabled by default such that thecorresponding annotations are silently ignored. To generate a documentation-enabled bim ﬁle thecompiler has to be run with the option -D. In addition to enabling the doc category, this ﬂag also
activates the automatic generation of certain documentation annotations by the compiler. Alternatively
to using this ﬂag, a model may deﬁne the following annotations:!@mc.set doc enable!@doc.autogen=true

Note that these special annotations can also be used in the source ﬁle as a means to exclude somedeﬁnitions from the documentation, setting doc.autogen to false right before the deﬁnitions to be
excluded and back to true immediately after.
2.20.1.1

Global deﬁnitions

The following global annotations are automatically generated by the compiler:@doc.nameName of the package or model@doc.version

Version number as stated by the ’version’ statement@doc.dateCurrent date@doc.ispkg

Set to ’true’ if the ﬁle is a package

All automatic annotations can also be deﬁned explicitly in the Mosel source to overwrite their default
values.
The following annotations may be added to complete the general appearance of the document to be
produced (they are used by the moseldoc documentation processor):@doc.title

Title of the document@doc.subtitle

Subtitle of the document@doc.xmlheader

Header of the XML document@doc.xmlroot

Name of the XML element containing the documentation@doc.idPreﬁx used to generate IDs of chapters, sections, and subsections. If the
documentation for several packages is generated from a single master model
then a unique ID must be explicitly deﬁned in each of the packages in order toavoid ID collision

The @doc category is complete (i.e. it is not possible to create new doc.X annotations), however, thecategory @doc.ext can be used to deﬁne further information assuming a particular documentation
processor can exploit it.

Fair Isaac Corporation Conﬁdential and Proprietary Information

59

The Mosel Language

2.20.1.2

Document structure

Optionally, the resulting document may be organised in chapters, sections and subsections. Each ofthese constructs can contain both text paragraphs and entity descriptions (declarations andsubroutines). To enter a new documentation component, one of the following annotations has to bedeﬁned:@doc.chapter

Start a chapter@doc.section

Start a section inside of a chapter@doc.subsection Start a subsection inside of a section
In addition to the provided title a short title might also be deﬁned (using @doc.shorttitle) that will
be used in place of the (long) title in the table of contents. Whenever a new division starts, a unique ID
is automatically generated based on the section number and any deﬁned preﬁx speciﬁed in the headerof the document with @doc.id. It is also possible to explicitly deﬁne an ID using @doc.id just after
entering the section (this is required when the section has to be referenced using a <ref> tag).
From inside of any of these divisions a new paragraph is added with the @doc.p annotation. By default
any new addition (paragraph or entity description) is appended to the current component but it ispossible to select an alternative location. A target location has ﬁrst to be deﬁned using the annotation@doc.location: this creates a label associated with the current section. Deﬁning the annotation@doc.relocate with this target elsewhere in the source ﬁle will move all subsequent additions to thetarget location; this relocation will continue up to the next division marker or relocation deﬁnition. Notethat deﬁning an empty relocation reverts to the effective current location. Example:(!@doc.
@chapter My first chapter@p some text related to the first chapter@location first_chap@section first section of first chapter@p something about the section@relocate first_chap@p this paragraph will be inserted directly under first chapter@relocate@p but this one will remain in the section!)

2.20.1.3

Symbol deﬁnitions

The following sections list the various documentation annotations that can be deﬁned depending on
the kind of the entity (parameter, variable, type or subroutine) to be documented. Some of theseannotations are automatically deﬁned by the compiler: in the case of values (like the value of aconstant) the automatic deﬁnition may not be performed if the value is the result of a calculation thatcannot be evaluated at compile time ("runtime constant"). In this case it is required to explicitly specify
the text that should be retained in the documentation.
Parameters@doc.descr

Description (1-2 text lines)@doc.default

Default value (automatically generated)@doc.typeType (automatically generated)@doc.value

Possible value and explanation of its meaning (may be deﬁned several times)@doc.info

Some more detailed explanations (may be deﬁned several times)

Fair Isaac Corporation Conﬁdential and Proprietary Information

60

The Mosel Language@doc.ignore

The symbol will be ignored by the documentation processor

Types, constants and variables
This set of annotations apply to symbols declared in declarations blocks. Record ﬁelds (both for a typedeclaration and for a variable) can be described using @doc.recflddescr: the value of thisannotation consists in the name of the ﬁeld followed by its description (a space should separate thesetwo components)@doc.descr

Description (1-2 text lines)@doc.const

For a constant: value (automatically generated)@doc.typeType (automatically generated)@doc.typedef

For a type deﬁnition: type (automatically generated)@doc.value

Possible value and explanation of its meaning (may be deﬁned several times)@doc.info

Some more detailed explanations (may be deﬁned several times)@doc.setby

Name of subroutines modifying this entity@doc.recfldtype Type of a record ﬁeld (automatically generated)@doc.recflddescr@doc.ignore

Description of a record ﬁeld

The symbol will be ignored by the documentation processor

Procedures and functions
Information from different overloaded versions of a given subroutine is merged automatically. The@doc.group annotation may be used to merge information of routines with different names but used
for a similar task (up to 3 different subroutine names can be grouped). The @doc.param annotation isused to describe the parameters of the routine: the value of this annotation consists in the name of theparameter followed by its description (a space should separate these two components)@doc.group

Name of another subroutine that this one should be grouped with@doc.descr

Description (1-2 text lines)@doc.shortdescr Shortened description for table of contents and list display@doc.syntax

Routine signature (automatically generated)@doc.param

Name and meaning of a subroutine argument (may be deﬁned several times)@doc.paramval

Possible value and meaning of a subroutine argument (may be deﬁned several
times). The value of this annotation is the name of the parameter (as speciﬁedwith a preceding @doc.param) followed by the value and the explanation@doc.return

For functions only: what is returned@doc.err

Possible error code (may be deﬁned several times)@doc.example

Example of use (may be deﬁned several times)@doc.info

Some more detailed explanations (may be deﬁned several times)@doc.related

List of related symbols@doc.ignore

The subroutine will be ignored by the documentation processor

Fair Isaac Corporation Conﬁdential and Proprietary Information

61

The Mosel Language

2.20.1.4

Annotation deﬁnitions

A special set of annotations (category @doc.annot) is available for documenting annotationdeﬁnitions in Mosel packages (not supported for Mosel models). The annotations for documenting
annotation deﬁnitions are global annotations, their value must start with an annotation name in order toassociate them with the corresponding annotation deﬁnition.
@doc.annot.descr

Annotation name followed by a short description (1-2 text lines)@doc.annot.default

Annotation name and default value@doc.annot.value Annotation name, possible value and explanation of its meaning (may bedeﬁned several times)@doc.annot.type Annotation type@doc.annot.info Annotation name and some more detailed explanations (may be deﬁned several
times)@doc.annotcat

Annotation category to document (may be deﬁned several times), if undeﬁned all
categories are documented@doc.annotloc

Insertion point (speciﬁed via @doc.location) for annotations documentation

2.20.1.5

Package control parameters

A special set of annotations (category @doc.cparam) is available for documenting control parametersof Mosel packages. The annotations for documenting control parameters are global annotations, theirvalue must start with a parameter name in order to associate them with the corresponding control
parameter.
@doc.cparam.descr Parameter name followed by a short description (1-2 text lines)@doc.cparam.default

Parameter name and default value@doc.cparam.value Parameter name, possible value and explanation of its meaning (may bedeﬁned several times)@doc.cparam.type

Parameter type (automatically generated by the compiler)@doc.cparam.info Parameter name and some more detailed explanations (may be deﬁned several
times)@doc.cparamloc

Insertion point (speciﬁed via @doc.location) for control parameters
documentation

2.20.2 moseldoc documentation processor
2.20.2.1

Running moseldoc

The moseldoc program takes as input either a bim ﬁle produced from a Mosel model compiled with the-D compiler option or directly a Mosel source ﬁle (in which case a compilation step is automatically
executed). Typically the generation of the documentation from a source ﬁle will be obtained with thefollowing command:>moseldoc mymodel.mos

Fair Isaac Corporation Conﬁdential and Proprietary Information

62

The Mosel Language

The result of this process is an XML ﬁle ("mymodel_doc.xml") and a directory containing an HTMLversion of the documentation ("mymodel_html"). The program will produce only the XML ﬁle (from abim or source ﬁle) if option -xml is used and only the HTML output (from an XML ﬁle) if -html is
selected. The option -f is required to force the replacement of existing ﬁles.
As a Mosel program available in source form, moseldoc can be adapted to ﬁt speciﬁc requirements. To
re-generate the executable use this compilation command:>mosel comp -s moseldoc.mos -o deploy.exe:moseldoc,css-z=moseldoc.css

2.20.2.2

Structure of the generated document

The resulting document respects the structure deﬁned by the dedicated annotations (chapter, section,subsection). In each of these divisions, the paragraphs are exposed ﬁrst, then the parameters andvariables and ﬁnally the list of subroutines. If no structural elements have been deﬁned, a chapter per
entity type is automatically created to group similar objects (Parameters, Constants, Types, Variables
and Subroutines).
2.20.2.3

Processing of annotation values

Values associated with descriptive text annotations (like section titles or descriptions) are interpreted
as XML. Paragraphs (@doc.p) and examples (@doc.example) are handled in a speciﬁc way: by
default the value is inserted as XML but, if the value starts with [TXT], the content is treated as plain
text; if it starts with [SRC], the value is considered to be some example code and it is reproduced
preserving spacing. If it starts with [NOD], it is interpreted as a self-contained XML node (i.e. it is notinserted in a paragraph block). In an XML block of text, the markers ref (chapter/section/subsectionreference), fctRef (subroutine reference) and entRef (entity reference) are processed such that in
the HTML document they are turned into hyperlinks to the corresponding objects. Similarly, the tt
element type is replaced by an appropriate style for displaying code samples.

2.21

Message translation
Mosel supports a message translation mechanism that makes it possible to display messages in thecurrent language of the operating environment. This system requires that all messages are originally
written in English and identiﬁed as messages to be translated (it is usually not desirable to translate all
text strings of a model). The Mosel compiler can then collect all messages to be translated for building
message catalogs. Each message catalog ﬁle contains the translations of the messages for a given
language: Mosel will select the appropriate ﬁle for the current language during its execution to use theright set of translations. The system is designed such that it will not fail if a translation or an entire
language is missing: in such a case the original English text is used.

2.21.1

Preparing the model source
Most often, not all text strings occurring in a program are to be translated to native language. This is
why it is necessary to tag each message to be translated such that the automatic message translation
system can process only the relevant texts. The tagging is achieved by using the operators _c(), _()or the modiﬁed procedures write_(), writeln_(), fwrite_() and fwriteln_().
The operator _c() is used to identify constant strings that should be collected for translation but thestring will not be translated at the place where it is used. This operator can be applied to a list of string
constants. A similar effect can be obtained with the annotation mc.msgid.
The function _() applies to both constant strings and variables: it replaces its argument by the

Fair Isaac Corporation Conﬁdential and Proprietary Information

63

The Mosel Languagetranslated string. As with the operator _c() constant strings are collected for the message catalogs,
but they will also be replaced by their translation at the place where the operator is applied to the string.
The write_ and writeln_ procedures are equivalent to their normal versions except that they
process the constant strings they have to display for translation.
All translations of a model (or package) are grouped under a domain: this identiﬁer is used to name themessage catalog ﬁles. The default domain name is the model (or package) name after having replaced
spaces and non-ascii characters by underscores (for instance the domain name of the model "mymod" is "my_mod"). The domain name can also be speciﬁed using the mc.msgdom annotation.
The following model example shows the use of the various markers:model translate! The message domain is 'trs' (default name would be the model name 'translate')!@mc.msgdom trs
declarations! The elements of 'nums' are kept in English, but collected for translation
nums=[_c("one","two","three")]! Add 'four' to the message catalogs (although it is not used here)!@mc.msgid:four
end-declarations! Translate the message text, without translating 'nums'
writeln_("all numbers (in English): ", nums)
n:=getfirst(nums)! Translate the message text and the first occurrence of 'n', but not! its second occurrence
writeln_("the first number is: ", _(n), " (in English:", n, ")")
end-model

2.21.2

Building the message catalogs
Once the model source has been prepared, the list of messages to be translated can be extracted. This
operation is performed by the Mosel compiler when executed with the option -x:>mosel comp -x mymod.mos -o trs.pot

The output of this command is a Portable Object Template (POT): this is a text ﬁle consisting of a list ofpairs msgid (message to translate), msgstr (translation) for which only the ﬁrst entry is populated.
With the example model from the previous section the generated POT ﬁle results in the following:# Created by Mosel v4.0.0 from 'translate.mos'# Domain name: trs
msgid "all numbers (in English): %L\n"msgstr ""msgid "four"
msgstr ""msgid "one"msgstr ""msgid "the first number is: %s (in English:%s)\n"msgstr ""msgid "three"msgstr ""msgid "two"msgstr ""Fair Isaac Corporation Conﬁdential and Proprietary Information

64

The Mosel Language

For each of the supported languages a separate PO (Portable Object) ﬁle that will contain thecorresponding translations has to be created from this template. The command xprnls is used forthis task (for further details please refer to the XPRNLS Reference Manual). For instance the following
command will create the ﬁle for the Italian translations of the messages:>xprnls init -o trs.it.po trs.pot

Here we name the ﬁle domain.language.po in order to ease the management of these translation ﬁles
(where language stands for the ISO639 language code).
The generated ﬁle is a copy of the template with an additional header that should be completed by thetranslator (it is pre-populated with information obtained from the system), in particular the language(property "Language") and the encoding (property "Content-Type"). For each of the msgid
records the translation in the language associated to the ﬁle has to be provided in the msgstr record.
Note that some messages include escape sequences (like "\n") and format markers (e.g. "%s"): thecorresponding translation must include the same format markers as the original text and they must
appear in the same order (otherwise the translation will be ignored).
The beginning of the translation ﬁle of our example for French (named "trs.fr.po") should be
similar to the following (the extract below shows only the header and the translation of the ﬁrst
message):
msgid ""
msgstr """Project-Id-Version: My translation example\n""POT-Creation-Date: 2015-12-04 18:16+0100\n""PO-Revision-Date: 2015-12-04 18:16+0100\n""Last-Translator: Jules Verne\n""Language: fr\n""Content-Type: text/plain; charset=ISO8859-15\n"msgid "all numbers (in English): %L\n"msgstr "tous les nombres (en anglais): %L\n"

The message catalogs for the PO ﬁles are obtained by running once more the xprnls command, thistime using the option mogen:>xprnls mogen -d locale trs.⁎.po

This command will compile each of the PO ﬁles into a Machine Object (MO) ﬁle named trs.mo that will
be saved under the directory locale/lang/LC_MESSAGES. This directory tree must be distributed
along with the model ﬁle for the automatic translation to work.

2.21.3Model execution
During the execution of the model the message catalogs for the current language (as indicated by theoperating system) are loaded automatically from the ’locale’ directory. This location is deﬁned by the"localedir" control parameter (by default this is "./locale"). If no message catalog can be found
for the requested language then the original English text is used. This will also be the case if atranslation is missing (e.g. if the message catalog has not been updated after some model sourcechange).
When run on a computer conﬁgured for French our example displays:
tous les nombres (en anglais): [`one',`two',`three']le premier nombre est: un (en anglais:one)

Fair Isaac Corporation Conﬁdential and Proprietary Information

65

CHAPTER 3

Predeﬁned functions and proceduresThis chapter lists in alphabetical order all predeﬁned functions and procedures included in the Mosel
language. Certain functions or procedures take predeﬁned constants as input values or return values
that correspond to predeﬁned constants. In every case, these constants are documented with thefunction or procedure. In addition, Mosel deﬁnes a few other useful numerical constants:
MAX_INT

maximum integer number

MAX_REAL

maximum real number

M_Ebase of natural logarithms e

M_PIvalue of π

INFINITY

Inﬁnity

NAN

Not A Number

Fair Isaac Corporation Conﬁdential and Proprietary Information

66

Predeﬁned functions and procedures

abs
Purpose
Synopsis

Get the absolute value of an integer or real.
function abs(i:integer):integerfunction abs(r:real):realArgumentsirInteger number for which to calculate the absolute value
Real number for which to calculate the absolute value

Return value
Absolute value of an integer or real number.
Further information
This function returns the absolute value of an integer or real number. The returned type corresponds tothe type of the input.
Related topics
exp, ln, log, sqrt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

67

Predeﬁned functions and procedures

arctanPurpose
Synopsis

Get the arctangent of a value.
function arctan(r:real):realArgumentrReal number to which to apply the trigonometric function

Return value
Arctangent of the argument.
ExampleThe following functions compute the arcsine and arccosine of a value:function arcsin(s:real):real
returned:=arctan(s/sqrt(1-s^2))
end-function
function arccos(c:real):real
returned:=arctan(sqrt(1-c^2)/c)
end-function

Related topics
cos, sin

Fair Isaac Corporation Conﬁdential and Proprietary Information

68

Predeﬁned functions and procedures

asprocPurpose
SynopsisIgnore the return value of a function call.
procedure asproc(fctcall)

Argument
fctcall A function call
Exampleasproc(splithead(L,2))
Further information
This procedure makes it possible to call a function and ignore its return value (see also option
fctasproc in section 2.3.3).

Fair Isaac Corporation Conﬁdential and Proprietary Information

69

Predeﬁned functions and procedures

assertPurpose
Synopsis

Abort execution if a condition is not satisﬁed.
procedure assert(c:boolean)
procedure assert(c:boolean,m:string)procedure assert(c:boolean,m:string,e:integer)

Argumentscme

Condition to verify
Error message to display in case of failure
Error code to return in case of failure (default: 8)

Exampleassert(and(i in I) mydata(i)>0)
assert(isodd(a),"a is not odd!!")Further information
1. If the condition c is satisﬁed, this procedure has no effect, otherwise it displays an error message andaborts execution by calling exit. The versions of the procedure with 2 and 3 parameters can be used
to replace the default message (location of the statement in the source) and default exit value (8).
2. Assertions are usually used as a debugging tool and are ignored when the model is compiled without
debugging information (i.e. none of options -g or -G is used). It is however possible to keep assert
statements even when no debugging information is included by specifying the compiler directive
keepassert (see Section 2.3).
Related topics
exit

Fair Isaac Corporation Conﬁdential and Proprietary Information70

Predeﬁned functions and procedures

bitﬂipPurpose
Synopsis

Flip bits (bitwise XOR).
function bitflip(i:integer, j:integer):integer

ArgumentsijInteger to be set
Value to ﬂip

Return value
Bitwise XOR of the operands.
ExampleIn the following, i takes the value 9, j takes the value 141, and k takes the value 7:
i:= bitflip(12, 5)
j:= biflip(13, 128)k:= bitflip(13, 10)

Further information
This function computes the bitwise exclusive OR of its operands.
Related topics
bittest, bitshift, bitset, bitneg, bitval

Fair Isaac Corporation Conﬁdential and Proprietary Information

71

Predeﬁned functions and procedures

bitnegPurpose
Synopsis

Bitwise negation (bitwise NOT).
function bitneg(i:integer):integer

ArgumentiInteger to negate

Return value
Negated value of argument.
ExampleIn the following, i takes the value -6, j takes the value 2147483647, and k takes the value -4:i:= bitneg(5)j:= bitneg(-2147483647-1)
k:= bitneg(3)Further information
The bitwise NOT (or complement) consists in computing the logical negation of each bit: 1 is replacedby 0 and 0 is replaced by 1.
Related topics
bitset, bittest, bitflip, bitshift, bitval

Fair Isaac Corporation Conﬁdential and Proprietary Information

72

Predeﬁned functions and procedures

bitsetPurpose
Synopsis

Set bits (bitwise OR).
function bitset(i:integer, j:integer):integer

ArgumentsijInteger to be set
Value to set

Return value
Bitwise OR of the operands.
ExampleIn the following, i takes the value 13, j takes the value 141, and k takes the value 15:
i:= bitset(12, 5)
j:= bitset(13, 128)k:= bitset(13, 10)

Further information
This function computes the bitwise OR of its operands.
Related topics
bittest, bitshift, bitflip, bitneg, bitval

Fair Isaac Corporation Conﬁdential and Proprietary Information73

Predeﬁned functions and procedures

bitshift
Purpose
Synopsis

Shift an integer by a number of bits.
function bitshift(i:integer, n:integer):integer

ArgumentsinInteger to be shifted
Number of bits: >0 for shifting to the left and <0 for shifting to the right

Return value
Shifted integer.
ExampleIn the following, i takes the value 160, j takes the value 32, and k takes the value 1:
i:= bitshift(5, 5)
j:= bitshit(1, 5)
k:= bitshit(128, -7)

Further information
Shifting of 1 bit to the right is the same as dividing it by 2 and shifting of 1 bit to the left is the same as
multiplying by 2.
Related topics
bitset, bittest, bitflip, bitneg, bitval

Fair Isaac Corporation Conﬁdential and Proprietary Information74

Predeﬁned functions and procedures

bittestPurpose
Synopsis

Test bit settings (bitwise AND).
function bittest(i:integer, mask:integer):integer

Argumentsimask

Integer to be tested
Bit mask

Return value
Bits selected by the mask.
ExampleIn the following, i takes the value 4, j takes the value 5, and k takes the value 8:i:= bittest(12, 5)
j:= bittest(13, 5)
k:= bittest(13, 10)

Further information
This function compares a given number with a bit mask and returns those bits selected by the maskthat are set in the number (bit 0 has value 1, bit 1 has value 2, bit 2 has value 4, and so on - use function
bitval to get the value of a bit).
Related topics
bitset, bitshift, bitflip, bitneg, bitval

Fair Isaac Corporation Conﬁdential and Proprietary Information75

Predeﬁned functions and procedures

bitvalPurpose
Synopsis

Compute the value corresponding to a bit number.
function bitval(i:integer):integer

Argumenti

Bit number (between 0 and 31)

Return value
Value of the selected bit.
ExampleIn the following, i takes the value 1, j takes the value -2147483648, and k takes the value 16:i:= bitval(0)j:= bitval(7)k:= bitval(4)Further information
This function computes the value corresponding to a bit number. The evaluation of bitval(i)corresponds to bitshift(1,i)
Related topics
bitset, bitshift, bitflip, bitneg, bittest

Fair Isaac Corporation Conﬁdential and Proprietary Information76

Predeﬁned functions and procedures

ceil
Purpose
SynopsisRound a number to the next largest integer.
function ceil(r:real):integer

ArgumentrReal number to be rounded

Return value
Rounded value.
ExampleIn the following, i takes the value 6, j takes the value -6, and k takes the value 13:
i := ceil(5.6)
j := ceil(-6.7)
k := ceil(12.3)

Related topics
floor, round.

Fair Isaac Corporation Conﬁdential and Proprietary Information

77

Predeﬁned functions and procedures

comparePurpose
Synopsis

Compare 2 values.
function compare(arg1:ordered type, arg2:same type as arg1):integer

Arguments
arg1
arg2

First operand for the comparison
Second operand for the comparison (same type as arg1)

Return value
0 if arguments are identical, -1 if the ﬁrst argument is less than the second argument and 1 otherwise.
Further information
This function is deﬁned for integer, real, string and boolean variables. It is also available for module
types that implement the necessary functionality.

Fair Isaac Corporation Conﬁdential and Proprietary Information

78

Predeﬁned functions and procedurescos
Purpose
Synopsis

Get the cosine of a value.
function cos(r:real):realArgumentrReal number to which to apply the trigonometric function

Return value
Cosine value of the argument.
ExampleThe function tangent can be implemented as follows:
function tangent(x:real):real
returned:=sin(x)/cos(x)end-function

Related topics
arctan, sin.

Fair Isaac Corporation Conﬁdential and Proprietary Information

79

Predeﬁned functions and procedures

createPurpose
SynopsisCreate explicitly a cell of a dynamic array.
procedure create(x:array reference)

Argumentx
ExampleCell to be created

The following declares a dynamic array of variables, creating only those corresponding to the odd
indices. Finally, it deﬁnes the linear expression x(1) + x(3) + x(5) + x(7):declarations
x: dynamic array(1..8) of mpvar
end-declarations
forall(i in 1..8| isodd(i)) create(x(i))
c:= sum(i in 1..8) x(i)Further information
Usually cells of dynamic arrays are created by means of assignments. This procedure can be used as areplacement for an assignment especially when the type of a dynamic array does not provide any
assignment operator (like mpvar for instance).
Related topics
Section 2.6.4, delcell.

Fair Isaac Corporation Conﬁdential and Proprietary Information

80

Predeﬁned functions and procedures

currentdate
Purpose
Synopsis

Return the current date as a Julian Day Number (JDN).
function currentdate:integer

Return value
The number of days elapsed since 1/1/1970 as an integer.
Further information
1. The control parameter "UTC" indicates whether this function returns a date in local or UTC time.
2. Refer to the module mmsystem for a set of dedicated types for handling date and time.
Related topics
setparam,timestamp,currenttime

Fair Isaac Corporation Conﬁdential and Proprietary Information81

Predeﬁned functions and procedures

currenttime
Purpose
Synopsis

Return the current time as the number of milliseconds since midnight.
function currenttime:integer

Return value
The number of milliseconds since midnight as an integer.
Further information
1. The control parameter "UTC" indicates whether this function returns a time in local or UTC time.
2. Refer to the module mmsystem for a set of dedicated types for handling date and time.
Related topics
setparam,timestamp,currentdate

Fair Isaac Corporation Conﬁdential and Proprietary Information82

Predeﬁned functions and procedures

cuteltPurpose
Synopsis

Extract an element from a set or a list.
function cutelt(e:set):type_of_efunction cutelt(l:list):type_of_lfunction cutelt(l:list,p:integer):type_of_l

Arguments
e
l
p

A set
A listIndex of the element to remove (default:1)

Return value
An element of the set or list after it has been removed from its container.
Further information
When applied to a range set or list this function behaves like cutfirst. An error is generated if theargument of the function is empty.
Related topics
getelt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

83

Predeﬁned functions and procedures

cutﬁrstPurpose
Synopsis

Extract the ﬁrst element of a range set or a list.
function cutfirst(r:range):integerfunction cutfirst(l:list):type_of_l

Argumentsrl

A range set
A listReturn value
The ﬁrst element of the set or list after it has been removed from its container.
Further information
This function is equivalent to calling getfirst and then cuthead for dropping one element.
Related topics
cutlast, cutelt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

84

Predeﬁned functions and procedures

cutheadPurpose
SynopsisCut the ﬁrst elements of a list.
procedure cuthead(l:list, o:integer)

Argumentslo

A listNumber of elements to remove if >0 or number of elements to keep if <0

ExampleL:=[1,2,3,4,5]
cuthead(L,2)
cuthead(L,-1)! => L=[3,4,5]! => L=[5]Further information
If the second parameter is 0, the list is unchanged. If the same parameter is larger than the size of thelist, all elements are deleted.
Related topics
cuttailFair Isaac Corporation Conﬁdential and Proprietary Information

85

Predeﬁned functions and procedures

cutlastPurpose
Synopsis

Extract the last element of a range set or a list.
function cutlast(r:range):integerfunction cutlast(l:list):type_of_l

Argumentsrl

A range set
A listReturn value
The last element of the set or list after it has been removed from its container.
Further information
This function is equivalent to calling getlast and then cuttail for dropping one element.
Related topics
cutfirst, cutelt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

86Predeﬁned functions and procedures

cuttailPurpose
SynopsisCut the last elements of a list.
procedure cuttail(l:list, o:integer)

Argumentslo

A listNumber of elements to remove if >0 or number of elements to keep if <0

ExampleL:=[1,2,3,4,5]
cuttail(L,2)
cuttail(L,-1)! => L=[1,2,3]! => L=[1]Further information
If the second parameter is 0, the list is unchanged. If the same parameter is larger than the size of thelist, all elements are deleted.
Related topics
cutheadFair Isaac Corporation Conﬁdential and Proprietary Information

87

Predeﬁned functions and procedures

delcellPurpose
Synopsis

Delete a cell or all cells of a dynamic array.
procedure delcell(x:array reference)
procedure delcell(a:array)

ArgumentsxaCell to be deleted
An arrayFurther information
1. The ﬁrst form of the routine can only be applied to dynamic arrays (it is not possible to delete a cell of adense array). Using the second syntax of the procedure will release all cells of the array, note that in thecase of a dense array the entire data set will be reallocated when the array is accessed again.
2. Deleting a cell of an array of referenced objects (like mpvar) may not effectively release that object.
Actually, a referenced object is released only when all its references have been removed. For instance,
if an object appears in a set, deleting its main reference using delcell will not remove this object
from the set.
Related topics
Section 2.6.4, create, reset.

Fair Isaac Corporation Conﬁdential and Proprietary Information

88

Predeﬁned functions and procedures

datablockPurpose
Synopsis

Get the ﬁle name of an embedded data block .
function datablock(src:string, prefix:string):string
function datablock(src:string):stringArguments
src
prefixName of the ﬁle to be embedded
Preﬁx to be used for accessing the data block (default: "zlib.deflate:")Return value
A ﬁle name pointing to the data block
ExampleIn the following code extract the bim ﬁle for submod.mos is generated during the compilation of thecurrent (master) model and is included in the resulting bim ﬁle for this model. At execution time themaster model will therefore not require any additional ﬁle for this submodel:load(submod,datablock("mmsystem.pipe:mosel comp -o - submod.mos"))run(submod)
waitforend(submod)
Note that the output of the compilation for the ﬁle submod.mos is redirected via the ’pipe’ onto themaster model while this model itself is being compiled.

Further information
1. This function makes it possible to embed in a bim ﬁle any data ﬁles that are available during thecompilation of the model source but cannot be accessed at execution time. The ﬁles speciﬁed by thisroutine are made available as memory blocks (see Section 2.15) during the execution of the model.
2. The ﬁle speciﬁed by the src argument is loaded into memory and saved in the resulting bim ﬁle during
the compilation of the source model. At execution time this function call results in a ﬁle name pointing
to a memory location storing the previously saved data.
3. The ﬁle name src is handled in the same way as for source ﬁle inclusion (see Section 2.5.2), in
particular the same rules apply regarding the ﬁle location and the expansion of environment variables.
4. The prefix argument can be used to select a driver for processing the ﬁle. With its default value("zlib.deflate:") the ﬁle is compressed before being stored in the bim ﬁle, the decompression
occurs when the ﬁle is accessed during execution (i.e. the ﬁle name returned by the function begins
with the string "zlib.deflate:"). To keep the ﬁle in its original form use an empty string as thepreﬁx (i.e. "").
5. When several data blocks with the same name and preﬁx are used in a model source the correspondingﬁle is loaded and stored only once.
6. If the ﬁle to store is empty (or if its name is an empty string) the function call is replaced by theconstant "null:" and no memory block is created.

Fair Isaac Corporation Conﬁdential and Proprietary Information89

Predeﬁned functions and procedures

existsPurpose
SynopsisCheck if a given entry in a dynamic array has been created.
function exists(x):boolean

Argumentx

Array reference (e.g. t(1))

Return value
true if the entry exists, false otherwise.
ExampleThe following, a dynamic array of decision variables only has its even elements created, which ischecked by displaying the existing variables:
declarations
S=1..8x: dynamic array(S) of mpvar
end-declarations
forall(i in S| not isodd(i)) create(x(i))
forall(i in S| exists(x(i)))
writeln("x(", i, ") exists")

Further information
1. If an array is declared dynamic its elements are not created at its declaration. This function indicates if
a given element has been created.
2. Under certain conditions, the exists function call is optimized by the compiler when used for ﬁltering
an aggregate operator: the loop is only performed for the existing entries instead of enumerating all
possible tuples of indices for ﬁnding the relevant ones.
Related topics
Section 2.7.2, create.

Fair Isaac Corporation Conﬁdential and Proprietary Information

90

Predeﬁned functions and procedures

exit
Purpose
Synopsis

Terminate the program.
procedure exit(code:integer)

Argumentcode

Value to be returned by the program

Further information
This procedure terminates the current program and returns the given value. Models exit by default witha value of 0 unless this is changed using exit. The Mosel command line interpreter uses this value as
exit status.
Related topics
Section 1.3.

Fair Isaac Corporation Conﬁdential and Proprietary Information

91

Predeﬁned functions and procedures

exp
Purpose
Synopsis

Get the natural exponent of a value.
function exp(r:real):realArgumentrReal value the function is applied to.

Return value
Natural exponent (er ) of the argument.
Related topics
abs, exp, ln, log, sqrt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

92

Predeﬁned functions and procedures

exportprob
Purpose
Synopsis

Export a problem to a ﬁle.
procedure exportprob(options:integer, filename:string, obj:linctr)
procedure exportprob(options:integer, filename:string)procedure exportprob(filename:string, obj:linctr)
procedure exportprob(filename:string)procedure exportprob

Arguments
options

File format options:

EP_MIN
minimization (default)
EP_MAX
maximization
EP_MPSMPS format
EP_STRIP Use scrambled names
EP_HEX
Ouput numbers in hexadecimal when using MPS format
Several options may be combined using +.
filename Name of the output ﬁle. If the empty string "" is given, output is printed to the standard
output (the screen)
obj
Objective function constraint
ExampleThe following prints the current problem to the screen using the default format and with MinCost as
objective function. The second statement exports the problem in LP-format and with scrambled names
to the ﬁle prob1.lp maximizing the constraint Profit:
declarations
MinCost, Profit:linctr
end-declarations
exportprob(0, "", MinCost)
exportprob(EP_MAX+EP_STRIP, "prob1", Profit)

Fair Isaac Corporation Conﬁdential and Proprietary Information

93

Predeﬁned functions and procedures

Further information
1. If the given ﬁlename uses the default IO driver (no driver speciﬁed) and has no extension, Mosel
appends .lp to it for LP format ﬁles and .mps for MPS format.
2. Except when option EP_MPS+EP_HEX is used numbers are ouput according to the realfmt andzerotol model parameters (see setparam).
3. Normally, local symbols (i.e. deﬁned in a procedure or function) are replaced by generated names in theexported matrix. However, if the model has been compiled with option -G, names deﬁned locally to theroutine calling exportprob are used in the exported matrix. Moreover, if a local symbol hides a global
one, this symbol is preﬁxed by ’~’.
4. If the model is compiled with -G and the control parameter recloc is set to true (see setparam),missing constraint names are replaced by the source location of the constraint deﬁnition (i.e. a
combination of the row number, source ﬁle name and line number in the ﬁle).
5. If no option is provided, the default format is LP for a minimization; if no constraint is given, the current
objective (if available) is exported. The matrix is printed to the standard output when this function isused without parameter.
6. This function exports only the LP/MIP problem directly handled by the Mosel core libraries. It cannot
report problem extensions managed by external modules. For instance, quadratic constraints orindicator constraints provided by the Xpress Optimizer are not shown by this routine: for this type ofproblems, the module-speciﬁc writeprob routine has to be used instead of exportprob.
Related topics
setname.

Fair Isaac Corporation Conﬁdential and Proprietary Information

94

Predeﬁned functions and procedures

fclosePurpose
Synopsis

Close the active input, output or error stream.
procedure fclose(stream:integer)

Argument
streamThe stream to close:
F_INPUT
Input stream
F_OUTPUT Output stream
F_ERROR
Error stream

Further information
This procedure closes the ﬁle that is currently associated with the given stream. The ﬁle preceding theclosed ﬁle (in the order of opening) is then assigned to the corresponding stream. A ﬁle that is closedwith this procedure must previously have been opened with fopen. This function has no effect if thecorresponding stream is not associated with any explicitly opened ﬁle (i.e. it is not possible to close thedefault input, output or error streams). All open streams are automatically closed when the program
terminates.
Related topics
fflush, fopen, fselect, getfid, iseof.

Fair Isaac Corporation Conﬁdential and Proprietary Information

95

Predeﬁned functions and procedures

fﬂush
Purpose
Synopsis

Force the operating system to write buffered data.
procedure fflush

Further information
This procedure forces a write of all buffered data of the default output stream. fflush is automaticallycalled when the stream is closed either with fclose or when the program terminates.
Related topics
fclose, fopen.

Fair Isaac Corporation Conﬁdential and Proprietary Information

96

Predeﬁned functions and procedures

ﬁnalize
Purpose
Synopsis

Finalize the deﬁnition of a set or list.
procedure finalize(s:set)procedure finalize(l:list)

ArgumentsslExampleDynamic set
Dynamic list

In the following, an indexing set is deﬁned, on which depends a dynamic array of decision variables.
The set is subsequently deﬁned to have three elements and is ﬁnalized. A static array is then deﬁned:
declarations
Set1: set of string
x: array(Set1) of mpvar! Declare a dynamic array of variables! (entries need to be created! subsequently)

end-declarations
Set1:= {"first", "second", "fifth"}
finalize(Set1)! Finalize the set definition
declarations
y: array(Set1) of mpvar
end-declarations! Declare a static array of variables! (entries are created immediately)

Further information
1. This procedure ﬁnalizes the deﬁnition of a set (or list), that is, it turns a dynamic set into a constant set
consisting of the elements that are currently in the set. All subsequently declared arrays that areindexed by this set will be created as static (= ﬁxed size). Any arrays indexed by this set that have been
declared prior to ﬁnalizing the set retain the status dynamic but their set of elements cannot be
modiﬁed any more.
2. Using this routine on sets declared dynamic has no effect.

Fair Isaac Corporation Conﬁdential and Proprietary Information

97

Predeﬁned functions and procedures

ﬁndﬁrstPurpose
Synopsis

Find the ﬁrst occurrence of an element in a list.
function findfirst(l:list, e:type_of_l):integer

Argumentsle

A list
The element to look for (it must be of the type of l)

Return value
The position of the element or 0 if the element is not included in the list.
ExampleL:=['a','b','c','d','b']i:=findfirst(L,'b')! => i=2
i:=findlast(L,'f')! => i=0
Related topics
findlast

Fair Isaac Corporation Conﬁdential and Proprietary Information

98

Predeﬁned functions and procedures

ﬁndlastPurpose
Synopsis

Find the last occurrence of an element in a list.
function findlast(l:list, e:type_of_l):integer

Argumentsle

A list
The element to look for (it must be of the type of l)

Return value
The position of the element or 0 if the element is not included in the list.
ExampleL:=['a','b','c','d','b']i:=findlast(L,'b')! => i=5
i:=findlast(L,'f')! => i=0
Related topics
findfirst

Fair Isaac Corporation Conﬁdential and Proprietary Information99

Predeﬁned functions and procedures

ﬂoor
Purpose
SynopsisRound a number to the next smallest integer.
function floor(r:real):integer

ArgumentrReal number to be rounded

Return value
Rounded value.
ExampleIn the following, i takes the value 5, j the value -7, and k the value 12:
i := floor(5.6)
j := floor(-6.7)
k := floor(12.3)

Related topics
ceil, round.

Fair Isaac Corporation Conﬁdential and Proprietary Information

100Predeﬁned functions and procedures

fopen
Purpose
Synopsis

Open a ﬁle and make it the active input or output stream.
procedure fopen(f:string, mode:integer)

Arguments
fmode

The name of the ﬁle to be opened
Open mode (may be combined):
F_INPUT
F_OUTPUTF_ERRORF_APPEND
F_TEXT
F_BINARY
F_LINBUF

Open for reading
Empty the ﬁle and open it for writing
Empty the ﬁle and open it for writing as the error stream
Open for writing, appending new data to the end of the ﬁleOpen in text mode (the default)
Open in binary mode
If open for writing, ﬂushes buffer after end of each line (default when writing to a
console or for an error stream)
F_SILENT Do not display IO error messages
Further information
1. This procedure opens a ﬁle for reading or writing. If the operation succeeds, depending on the opening
mode, the ﬁle becomes the active input, output or error stream. The procedures write and writeln
are used to write data to the default output stream and the functions read, readln, and fskipline
are used to read data from the default input stream. Error messages are sent to the error stream.
2. The behavior of this function in case of an IO error (i.e. the ﬁle cannot be opened) is directed by thecontrol parameter ioctrl (see setparam): if the value of this parameter is ‘false’ (default value), theinterpreter stops. Otherwise, the interpreter ignores the error and continues. The error status of an IO
operation is stored in the control parameter iostatus (see getparam) which is 0 when the lastoperation has been executed successfully. Note that this parameter is automatically reset once its
value has been read using the function getparam. The behavior of IO operations after an unhandled
error is not deﬁned.
3. The binary mode disables character encoding conversion (see section 2.16).
Related topics
fclose, fselect, getfid.

Fair Isaac Corporation Conﬁdential and Proprietary Information

101

Predeﬁned functions and procedures

fselect
Purpose
Synopsis

Select the active input, output or error stream.
procedure fselect(stream:integer)

Argument
streamExampleThe stream number

The following saves the ﬁle ID of the default output before switching output to the ﬁle mylog.txt.
Subsequently, the ﬁle ID of the current output stream is saved and the default output is again selected.
def_out:= getfid(F_OUTPUT)
fopen("mylog.txt", F_OUTPUT)...
my_out:= getfid(F_OUTPUT)
fselect(def_out)

Further information
1. This procedure selects the given stream as the active input, output or error stream. The concerned
stream is designated by the opening status of the given stream (that is, if the given stream has been
opened for reading, it will be assigned to the default input stream). The stream number can be obtainedwith the function getfid.
2. The default input, output and error streams have respectively numbers 0, 1 and 2.
Related topics
fclose, fopen, getfid, fwrite, fwriteln.

Fair Isaac Corporation Conﬁdential and Proprietary Information

102

Predeﬁned functions and procedures

fskipline
Purpose
Synopsis

Advance in the default input stream as long as comment lines are found.
procedure fskipline(filter:string)Argument
filterExampleList of comment signs

In the following, the ﬁrst statement skips all lines beginning with either ‘#’ or ‘!’. The second statement
skips any following blank lines:
fskipline("!#")
fskipline("\n")Further information
This procedure advances in the input stream using the given list of comment signs as a ﬁlter. Eachcharacter of the given string is considered to be a symbol that marks the beginning of a comment line.
Note that the character ‘\n’ designates lines starting with nothing, that is, empty lines. During theparsing, spaces and tabulations are ignored.
Related topics
read, readln.

Fair Isaac Corporation Conﬁdential and Proprietary Information

103

Predeﬁned functions and procedures

fwrite, fwriteln
Purpose
Synopsis

Send an expression or list of expressions to the speciﬁed output stream.
procedure fwrite(fd:integer, e1:expr[, e2:expr...])
procedure fwriteln(fd:integer)
procedure fwriteln(fd:integer, e1:expr[, e2:expr...])

Argumentsfd
An output stream number
e1, e2,... Expression or list of expressions
Further information
1. These procedures are equivalent to calling fselect before using the corresponding output procedureand then restore the initial current stream with a second call to fselect.
2. The selected stream may also be an error stream.
Related topics
write, writeln, fselect, getfid.

Fair Isaac Corporation Conﬁdential and Proprietary Information

104

Predeﬁned functions and procedures

getactPurpose
Synopsis

Get the activity value of a constraint.
function getact(c:linctr):realArgumentc

A linear constraint

Return value
Activity value or 0.
Further information
This function returns the activity value of a constraint if the problem has been solved successfully,
otherwise 0 is returned.
Related topics
getdual, getslack, getsol.

Fair Isaac Corporation Conﬁdential and Proprietary Information

105

Predeﬁned functions and procedures

getcoeff
Purpose
Synopsis

Get a constraint coefﬁcient or constant term.
function getcoeff(c:linctr):realfunction getcoeff(c:linctr, x:mpvar):realfunction getcoeff(c:linctr, n:integer):realArgumentscxn

A linear constraint
A decision variable-1 for constant term, -2 for range lower bound

Return value
Coefﬁcient of the variable or a constant term.
ExampleIn this example a single constraint with three variables is deﬁned. The calls to getcoeff result in r
taking the value -1 and s taking the value -12.
declarations
x,y,z:mpvar
end-declarations
c:= 4⁎x + y -z <= 12
r:= getcoeff(c, z)
r:= getcoeff(c)Further information
This function returns the coefﬁcient of a given variable in a constraint, or if no variable is given, theconstant term (= -RHS) of the constraint. The returned values correspond to a normalised constraint
representation with all variable and constant terms on the left side of the (in)equality sign.
Related topics
getcoeffs, getvars, setcoeff.

Fair Isaac Corporation Conﬁdential and Proprietary Information

106

Predeﬁned functions and procedures

getcoeffs
Purpose
Synopsis

Get all variable coefﬁcients of a constraint.
procedure getcoeffs(c:linctr, a:array(set of mpvar) of real, s:set of
mpvar)

Argumentscas

A linear constraint
An array of reals indiced by decision variables
A set of decision variables

Further information
1. This procedure returns in the parameter a the coefﬁcients of all variables of a constraint. After calling
this procedure, the coefﬁcient of variable v of constraint c is a(v). The set s is used to specify forwhich variables the coefﬁcients have to be retrieved (if this set is empty all variables are considered).
2. If set s is empty all cells of array a are updated (i.e. cells corresponding to variables not included inconstraint c are set to 0). Otherwise only cells corresponding to elements of s are modiﬁed.
Related topics
getcoeffs, getcoeff

Fair Isaac Corporation Conﬁdential and Proprietary Information

107

Predeﬁned functions and procedures

getdualPurpose
Synopsis

Get the dual value of a constraint.
function getdual(c:linctr):realArgumentc

A linear constraint

Return value
Dual value or 0.
Further information
This function returns the dual value of a constraint if the problem has been solved successfully and theconstraint is contained in the problem, otherwise 0 is returned.
Related topics
getrcost, getslack, getsol.

Fair Isaac Corporation Conﬁdential and Proprietary Information

108

Predeﬁned functions and procedures

geteltPurpose
Synopsis

Get an element of a set or a list.
function getelt(e:set):type_of_efunction getelt(l:list):type_of_l

Arguments
e
l

A set
A listReturn value
An element of the set or list.
Further information
When applied to a range set or list this function behaves like getfirst. An error is generated if theargument of the function is empty.
Related topics
cutelt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

109

Predeﬁned functions and procedures

getﬁdPurpose
Synopsis

Get the stream number of the active input, output or error stream.
function getfid(stream:integer):integer

Argument
streamThe stream to query:
F_INPUT
Input stream
F_OUTPUT Output stream
F_ERROR
Error stream

Return value
Stream number.
Further information
The returned value can be used as parameter for the function fselect.
Related topics
fselect.

Fair Isaac Corporation Conﬁdential and Proprietary Information

110Predeﬁned functions and procedures

getﬁrstPurpose
Synopsis

Get the ﬁrst element of a range set or a list.
function getfirst(r:range):integerfunction getfirst(l:list):type_of_l

Argumentsrl

A range set
A listReturn value
The ﬁrst element of the set or list.
ExampleIn this example the range set r is deﬁned before its ﬁrst and last elements are retrieved and displayed:declarations
r=2..8end-declarations...
writeln("First element of r: ", getfirst(r),"\nLast element of r: ", getlast(r))

Further information
When applied to a list, the type of the function is the type of the list. An error is generated if theargument of the function is empty.
Related topics
getlast, cutfirst.

Fair Isaac Corporation Conﬁdential and Proprietary Information

111

Predeﬁned functions and procedures

getheadPurpose
Synopsis

Get a copy of the ﬁrst elements of a list.
function gethead(l:list, o:integer):list

Argumentslo

A listNumber of elements to copy if >0 or number of elements to ignore if <0

Return value
A (partial) copy of the list.
ExampleL:=[1,2,3,4,5]
L2:=gethead(L,2)
L2:=gethead(L,-1)! => L2=[1,2]! => L2=[1,2,3,4]

Further information
This function does not alter its input list. If the second parameter is 0 an empty list is returned. If thesame parameter is larger than the size of the list the function returns a copy of the original list.
Related topics
gettailFair Isaac Corporation Conﬁdential and Proprietary Information

112

Predeﬁned functions and procedures

getfname
Purpose
Synopsis

Get the ﬁle name associated to the active input, output or error stream.
function getfname(stream:integer):stringArgument
streamThe stream to query:
F_INPUT
Input stream
F_OUTPUT Output stream
F_ERROR
Error stream

Return value
File name.

Fair Isaac Corporation Conﬁdential and Proprietary Information

113

Predeﬁned functions and procedures

getlastPurpose
Synopsis

Get the last element of a range set or a list.
function getlast(r:range):integerfunction getlast(l:list):type_of_l

Argumentsrl

A range set
A listReturn value
The last element of the set or list.
ExampleIn this example the range set r is deﬁned before its ﬁrst and last elements are retrieved and displayed:declarations
r=2..8end-declarations...
writeln("First element of r: ", getfirst(r),"\nLast element of r: ", getlast(r))

Further information
When applied to a list, the type of the function is the type of the list. An error is generated if theargument of the function is empty.
Related topics
getfirst.

Fair Isaac Corporation Conﬁdential and Proprietary Information

114

Predeﬁned functions and procedures

getobjval
Purpose
Synopsis

Get the objective function value.
function getobjval:real

Return value
Objective function value or 0.
Further information
This function returns the objective function value if the problem has been solved successfully. If integer
feasible solution(s) have been found, the value of the best is returned, otherwise the value of the last LP
solved.
Related topics
getsol.

Fair Isaac Corporation Conﬁdential and Proprietary Information

115

Predeﬁned functions and procedures

getparam
Purpose
Synopsis

Get the current value of a control parameter.
function getparam(name:string):integer|string|real|boolean

Argument
name

Name of the control parameter whose value is to be returned (case insensitive).

Return value
Current setting of the control parameter.

Fair Isaac Corporation Conﬁdential and Proprietary Information

116

Predeﬁned functions and procedures

Further information
1. Parameters whose values may be returned by this function include the settings of Mosel as well as
those of any loaded module or package. The location of the parameter may be speciﬁed by preﬁxing its
name with the name of the module or package deﬁning it (e.g. mmxprs.XPRS_verbose). The type ofthe return value corresponds to the type of the parameter.
2. This function can be applied only to control parameters whose value can be accessed.
3. The name argument must be a constant string: a model parameter, variable or string expression cannot
be used as a control parameter name.
4. The following control parameters are supported by Mosel:
realfmt Default C printing format for real numbers (string)
zerotol zero tolerance in comparisons between reals (real)
ioctrl the interpreter ignores IO errors (Boolean)
iostatus status of the last IO operation (integer), which is 0 when the last operation has been
executed successfully. This parameter is automatically reset once its value has been read. Not
doing so may result in undeﬁned behavior. When ioctrl is active the IO status must be read(and reset) after every IO operationnbread number of items recognized by the last read procedure or read in by the last initializations
block (integer)
readcnt generate per label counting when executing ‘initializations from’ blocks (Boolean)UTC
indicate whether the time functions return time expressed in local (false) or UTC (true) time
(Boolean)
autofinal indicate whether initialisation from blocks are ﬁnalizing sets (Boolean)
tmpdir the Mosel temporary directory (string)
workdir the current working directory of the model (string)
restrict active restrictions (integer). See Section 1.3.4 for further details.
modelname internal unique name of the model being executed.
modelnumber order number of the model being executed.
recloc indicate whether automatic recording of source location of constraints deﬁnitions is active(Boolean)
localedir directory where message catalogs are stored (string)lang current language (string)runparams parameter string used for the current execution (string)bimprefix list of bim ﬁle preﬁxes (string)
sharingstatus sharing status of the model (integer). This parameter is -1 if the model does notshare any data; 0 if the model shares data but no submodel is using it; 1 when shared data isin use; 2 if the model is a submodel using shared data (see Section 7.2)
5. Function getparam may also be used to retrieve parser parameters. As opposed to the otherparameters whose value is computed at run time, these parameters are evaluated as soon as they areparsed:parser_line number of the line being parsed (integer)parser_file current source ﬁle name (string)parser_date current local date (string)parser_time current local time (string)parser_UTCdate current UTC date (string)parser_UTCtime current UTC time (string)parser_version Mosel version (string)model_version Version of the model as given by the version directive (string)
Fair Isaac Corporation Conﬁdential and Proprietary Information

117

Predeﬁned functions and procedures

Related topics
setparam, getdsoparam.

Fair Isaac Corporation Conﬁdential and Proprietary Information

118

Predeﬁned functions and procedures

getrcost
Purpose
Synopsis

Get the reduced cost value of a variable.
function getrcost(v:mpvar):realArgumentv

A decision variable

Return value
Reduced cost value or 0.
Further information
This function returns the reduced cost value of a variable if the problem has been solved successfully
and the variable is contained in the problem, otherwise 0 is returned.
Related topics
getslack, getsol, getdual.

Fair Isaac Corporation Conﬁdential and Proprietary Information

119Predeﬁned functions and procedures

getreadcnt
Purpose
Synopsis

Get the number of items read in during last ‘initializations from’ for a given label.
function getreadcnt(l:string):integer

Argumentl

A labelReturn value
Number of items read in for label l.
Further information
Value 0 is returned if the given string does not correspond to a label or if control parameter readcnt
has not been set to true before execution of the initializations block.

Fair Isaac Corporation Conﬁdential and Proprietary Information120

Predeﬁned functions and procedures

getreverse
Purpose
Synopsis

Duplicate and reverse a list.
function getreverse(l:list):list

Argumentl

A listReturn value
A reversed copy of the provided list.
ExampleL:=[1,2,3,4,5]
L2:=L.reverse! => L=[5,4,3,2,1]

Related topics
reverse.

Fair Isaac Corporation Conﬁdential and Proprietary Information

121

Predeﬁned functions and procedures

getsize
Purpose
Synopsis

Get the size of an array, set, list, constraint or string.
function getsize(a:array):integerfunction getsize(s:set):integerfunction getsize(l:list):integerfunction getsize(t:string):integerfunction getsize(c:linctr):integer

Arguments
a
s
l
t
c

An array
A set
A listA string
A linear constraint

Return value
Number of effective entries for an array, number of elements for a set or a list, number of characters fora string, number of terms for a constraint.
ExampleIn the following, a dynamic array is declared holding eight elements, of which only two are actuallydeﬁned. Calling getsize on this array returns 2 rather than 8. The length lw of the string w is 9.
declarations
a:dynamic array(1..8) of realw = "some text"
end-declarationsa(1):= 4a(5):= 7.2
la:= getsize(a)lw:= getsize(w)Further information
In the case of a dynamic array that has been declared with a maximal range this number may besmaller than the size of the range, but it cannot exceed it. When used with a string, this function returns
the length of the string (i.e. the number of characters it contains). If used with a linear constraint, thisfunction returns the number of terms of the constraint (the constant term is not taken into account).

Fair Isaac Corporation Conﬁdential and Proprietary Information

122

Predeﬁned functions and procedures

getslack
Purpose
Synopsis

Get the slack value of a constraint.
function getslack(c:linctr):realArgumentc

A linear constraint

Return value
Slack value or 0.
Further information
This function returns the slack value of a constraint if the problem has been solved successfully andthe constraint is contained in the problem, otherwise 0 is returned.
Related topics
getdual, getrcost, getsol.

Fair Isaac Corporation Conﬁdential and Proprietary Information

123

Predeﬁned functions and procedures

getsolPurpose
Synopsis

Get the solution value of a variable or a linear expression (constraint).
function getsol(v:mpvar):realfunction getsol(c:linctr):realArgumentscv

A linear constraint
A decision variable

Return value
Solution value or 0.
Further information
This function returns the (primal) solution value of a variable if the problem has been solved
successfully and the variable is contained in the problem (otherwise 0). If used with a constraint, it
returns the evaluation of the corresponding linear expression using the current solution.
Related topics
getdual, getrcost, getobjval.

Fair Isaac Corporation Conﬁdential and Proprietary Information

124

Predeﬁned functions and procedures

gettailPurpose
Synopsis

Get a copy of the last elements of a list.
function gettail(l:list, o:integer):list

Argumentslo

A listNumber of elements to copy if >0 or number of elements to ignore if <0

Return value
A (partial) copy of the list.
ExampleL:=[1,2,3,4,5]
L2:=gettail(L,2)
L2:=gettail(L,-1)! => L2=[4,5]! => L2=[2,3,4,5]

Further information
This function does not alter its input list. If the second parameter is 0 an empty list is returned. If thesame parameter is larger than the size of the list the function returns a copy of the original list.
Related topics
getheadFair Isaac Corporation Conﬁdential and Proprietary Information

125

Predeﬁned functions and procedures

gettype
Purpose
Synopsis

Get the type of a constraint.
function gettype(c:linctr):integer

Argumentc

A linear constraint

Return value
Constraint type. Values applicable to any type of linear constraint are:
CT_EQ Equality, ‘=’
CT_GEQ Greater than or equal to, ‘ ≥ ’
CT_LEQ Less than or equal to, ‘ ≤ ’
CT_RNG Range
CT_UNB Non-binding constraint
CT_SOS1 Special ordered set of type 1
CT_SOS2 Special ordered set of type 2
Values applicable for unary constraints are:
CT_CONT Continuous
CT_INT Integer
CT_BIN Binary
CT_PINT Partial integer
CT_SEC Semi-continuous
CT_SINT Semi-continuous integer
CT_FREE Free
Related topics
settype.

Fair Isaac Corporation Conﬁdential and Proprietary Information

126

Predeﬁned functions and procedures

getvars
Purpose
Synopsis

Get the set of variables of a constraint.
procedure getvars(c:linctr,s:set of mpvar)

Argumentscs
ExampleA linear constraint
A set of decision variables

The following returns the set of variables in a linear constraint to the set variable vset, and then loops
through them to ﬁnd their solution values:
declarations
c:linctr
vset: set of mpvar
end-declarations
getvars(c,vset)
forall(x in vset) writeln(getsol(x))

Further information
This procedure returns in the parameter s the set of variables of a constraint. Note that this procedure
replaces the content of the set.
Related topics
getcoeffs, getcoeff

Fair Isaac Corporation Conﬁdential and Proprietary Information

127

Predeﬁned functions and procedures

isdynamic
Purpose
SynopsisCheck whether an array, set, or list is dynamic.
function isdynamic(a:array):booleanfunction isdynamic(s:set):booleanfunction isdynamic(l:list):boolean

Argumentsasl

An array
A set
A listReturn value
true if the provided entity is dynamic.
Further information
This function returns true when applied to sparse arrays (i.e. declared either as dynamic orhashmap).

Fair Isaac Corporation Conﬁdential and Proprietary Information

128

Predeﬁned functions and procedures

iseof
Purpose
Synopsis

Test whether the end of the default input stream has been reached.
function iseof:boolean

Return value
true if the end of the default input stream has been reached, false otherwise.
ExampleThe following opens a dataﬁle of integers, reads one from each line and prints it to the console until theend of the ﬁle is reached:declarations
d:integer
end-declarations...
fopen("datafile.dat", F_INPUT)
while(not iseof) do
readln(d)writeln(d)end-dofclose(F_INPUT)

Further information
This function returns the “end of ﬁle” status of the active input stream.
Related topics
fclose, fopen.

Fair Isaac Corporation Conﬁdential and Proprietary Information

129

Predeﬁned functions and procedures

isﬁnitePurpose
Synopsis

Test whether a real value is ﬁnite.
function isfinite(r: real):boolean

Argumentr

The value to test

Return value
true if the value is neither (-)INFINITY nor NAN.
Further information
The call isfinite(v) is equivalent to (not isnan(v) and not isinf(v)).
Related topics
setmatherr, isnan, isinf.

Fair Isaac Corporation Conﬁdential and Proprietary Information

130

Predeﬁned functions and procedures

ishiddenPurpose
Synopsis

Test whether a constraint is hidden.
function ishidden(c:linctr):boolean

Argumentc

A linear constraint

Return value
true if the constraint is hidden, false otherwise.
Further information
This function tests the current status of a constraint. At its creation a constraint is added to the current
problem, but using the function sethidden it may be hidden. This means, the constraint will not be
contained in the problem that is solved by the optimizer but it is not deleted from the deﬁnition of the
problem in Mosel.
Related topics
sethidden.

Fair Isaac Corporation Conﬁdential and Proprietary Information

131

Predeﬁned functions and procedures

isinf
Purpose
Synopsis

Test whether a real value is an inﬁnity.
function isinf(r: real):boolean

Argumentr

The value to test

Return value
true if the value is INFINITY or -INFINITY.
Further information
When the parameter matherr is set to true (see setparam) mathematical functions return theconstant NAN or INFINITY instead of failing. This function can be used to identify incorrect results(direct comparison to NAN or INFINITY always fails).
Related topics
setmatherr, isnan, isfinite.

Fair Isaac Corporation Conﬁdential and Proprietary Information132

Predeﬁned functions and procedures

isnan
Purpose
Synopsis

Test whether a real value is valid.
function isnan(r: real):boolean

Argumentr

The value to test

Return value
true if the value is not valid (i.e. it corresponds to Not A Number).
Further information
When the parameter matherr is set to true (see setparam) mathematical functions return theconstant NAN or INFINITY instead of failing. This function can be used to identify incorrect results(direct comparison to NAN or INFINITY always fails).
Related topics
setmatherr, isinf, isfinite.

Fair Isaac Corporation Conﬁdential and Proprietary Information

133

Predeﬁned functions and procedures

isodd
Purpose
Synopsis

Test whether an integer is odd.
function isodd(i:integer):boolean

Argumenti

An integer number

Return value
true if the given integer is odd, false if it is even.

Fair Isaac Corporation Conﬁdential and Proprietary Information

134

Predeﬁned functions and proceduresln
Purpose
Synopsis

Get the natural logarithm of a value.
function ln(r:real):realArgumentrReal value the function is applied to. This value must be positive.

Return value
Natural logarithm of the argument.
ExampleThe following example provides a function for calculating logarithms to any (positive) base:function logn(base,number: real):realif (number > 0 and base > 0) thenreturned:= ln(number)/ln(base)else
exit(1)
end-ifend-function

Related topics
exp, log, sqrt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

135

Predeﬁned functions and procedures

localsetparam
Purpose
Synopsis

Set the value of a control parameter locally to a subroutine.
procedure localsetparam(name:string,val:integer|string|real|boolean)

Arguments
namevalName of a control parameter (case insensitive).
New value for the control parameter

Further information
1. This procedure is a special version of setparam that can only be used from a subroutine: the effect ofthe parameter change is reverted at the end of the subroutine.
2. Independently of the location of the call to this procedure and whether other modiﬁcations are
performed on the parameter (using for instance setparam) the original value of the parameter issaved at the beginning of the execution of the routine and restored before its termination.
Related topics
setparam, setdsoparam, restoreparam.

Fair Isaac Corporation Conﬁdential and Proprietary Information

136

Predeﬁned functions and procedures

log
Purpose
Synopsis

Get the base 10 logarithm of a value.
function log(r:real):realArgumentrReal value the function is applied to. This value must be positive.

Return value
Base 10 logarithm of the argument.
Related topics
exp, ln, sqrt.

Fair Isaac Corporation Conﬁdential and Proprietary Information

137

Predeﬁned functions and procedures

makesos1, makesos2
Purpose
SynopsisCreates a special ordered set (SOS) using a set of decision variables and a linear constraint.
procedure makesos1(cs:linctr, s:set of mpvar, c:linctr)
procedure makesos1(s:set of mpvar, c:linctr)
procedure makesos2(cs:linctr, s:set of mpvar, c:linctr)
procedure makesos2(s:set of mpvar, c:linctr)

Argumentscssc
ExampleA linear constraint
A set of decision variables
A linear constraint

The following generates the SOS1 set mysos based on the linear constraint rr. The resulting set
contains the variables x, y, and z with the weights 0,2, and 4.
declarations
x,y,z: mpvar
rr,mysos: linctr
end-declarations
rr:= 2⁎y+4⁎z
makesos1(mysos, {x,y,z}, rr)

Further information
These procedures generate a SOS set containing the decision variables of the set s with the
coefﬁcients of the linear constraint c. The resulting set it assigned to cs if it is provided. Note thatthese procedures simplify the generation of SOS with weights of value 0.

Fair Isaac Corporation Conﬁdential and Proprietary Information138

Predeﬁned functions and procedures

maxlistPurpose
Synopsis

Get the maximum value of a list of integers or reals.
function maxlist(i1:integer, i2:integer[, i3:integer...]):integerfunction maxlist(r1:real, r2:real[, r3:real...]):realArguments
i1,i2,...
r1,r2,...

List of integer numbers
List of real numbers

Return value
Largest value in the given list.
ExampleIn the following r is assigned the value 7 by maxlist:
r:= maxlist(-1, 4.5, 2, 7, -0.3)

Further information
The returned type corresponds to the type of the input.
Related topics
minlist.

Fair Isaac Corporation Conﬁdential and Proprietary Information

139

Predeﬁned functions and procedures

memoryusePurpose
Synopsis

Get an estimate of the memory usage of an entity, a module or the entire model.
function memoryuse:realfunction memoryuse(ent:any entity):realfunction memoryuse(mname:string):realArguments
ent
An entity
mname A Module nameReturn value
An estimate of the memory usage in bytes or -1 if the evaluation cannot be performed.
Further information
1. When used with no argument this function returns the total amount of memory used by the runningmodel including the loaded modules (if they implement the functionality). A constant string isinterpreted as the name of a module: the returned value is the memory consumed by this module thatmust be currently used by the model.
2. For entities of type integer, real, boolean and mpvar the value returned is the constant amount ofmemory required by a variable of the corresponding type. For a reference to a string or linctr theeffective memory used by the internal datastructure is returned. In the case of a set or a list only thememory used to represent the collection is accounted, not its content. However the value reported foran array or record includes the memory used by the content of the structure except for strings.
Related topics
getmodpropnum.

Fair Isaac Corporation Conﬁdential and Proprietary Information

140

Predeﬁned functions and procedures

minlistPurpose
Synopsis

Get the minimum value of a list of integers or reals.
function minlist(i1:integer, i2:integer[, i3:integer...]):integerfunction minlist(r1:real, r2:real[, r3:real...]):realArguments
i1,i2,...
r1,r2,...

List of integer numbers
List of real numbers

Return value
Smallest value in the given list.
ExampleIn the following r is assigned the value -1 by maxlist:
r:= minlist(-1, 4.5, 2, 7, -0.3)

Further information
The returned type corresponds to the type of the input.
Related topics
maxlist.

Fair Isaac Corporation Conﬁdential and Proprietary Information

141

Predeﬁned functions and procedures

newmuid
Purpose
Synopsis

Generate a unique identiﬁer.
function newmuid:string

Return value
An identiﬁer string.
Further information
This function returns a string of the form muid#_xxx where # is an execution number in hexadecimal(speciﬁc to this model execution) and xxx a random hexadecimal number. It is guaranteed that eachgenerated value does not correspond to any symbol of the model and that it will never be returned
again.

Fair Isaac Corporation Conﬁdential and Proprietary Information

142

Predeﬁned functions and procedures

publishPurpose
Synopsis

Publish a symbol.
procedure publish(name:string, ref:string, external or structured)

Arguments
namerefSymbol to identify the object
A reference to an object of an external type, a structure (e.g. set, list or array) or a string

Further information
1. This procedure can be used to publish an object in the model dictionary such that it can be found bynative code using name. Any entity (including local and private) can be exposed with this routine aslong as it is of a referenced type (basically any type except integer, real and boolean). If a string variable
is used the published symbol corresponds to a string constant initialized with the current value of thisvariable.
2. The provided name must be a valid identiﬁer that is not yet being used by the model as symbol name(including entity and subroutine names). In case of error the procedure raises an IO error.
Related topics
unpublish, newmuid.

Fair Isaac Corporation Conﬁdential and Proprietary Information

143

Predeﬁned functions and procedures

randomPurpose
Synopsis

Generate a random number.
function random:real

Return value
A randomly generated number in the interval [0,1).
ExampleIn the following i is assigned a random integer value between 1 and 10:
i:= integer(round((10⁎random)+0.5))

Further information
Each model uses its own generator which is randomly initialized when the model execution starts. The
sequence may also be reset using procedure setrandseed.
Related topics
setrandseed.

Fair Isaac Corporation Conﬁdential and Proprietary Information

144

Predeﬁned functions and procedures

read, readln
Purpose
Synopsis

Read in formatted data from the active input stream.
procedure read(e1:expr[, e2:expr...])
procedure readln
procedure readln(e1:expr[, e2:expr...])

Argument
e1, e2,... Expression or list of expressions of basic type
ExampleThe following reads (possible split over several lines) 12 45 word, followed by toto(12 and45)=word:
declarations
i,j:integers:string
ts:array (range,range) of string
end-declarations
read(i, j, s)
readln("toto(", i, "and", j, ")=", ts(i,j))

Further information
1. These procedures assign the data read from the active input stream to the given symbols or try tomatch the given expressions with what is read from the input stream. If ei is a symbol that can be
assigned a value, the procedure tries to recognise from the input stream a constant of the required typeand, if successful, assigns the resulting value to ei. If ei is a constant or a symbol that cannot bereassigned, the procedure tries to read in a constant of the required value and succeeds if the resulting
value corresponds to ei. These procedures do not fail but set the control parameter nbread to thenumber of items actually recognized.
2. Note that the read procedures are based on the lexical analyser of Mosel: items are separated by
spaces and a string that contains spaces must be quoted using either single or double quotes (thequotes are automatically removed once the string has been identiﬁed).
3. The procedure readln expects all the items to be recognized to be contained in single line. The
function read ignores changes of line. If the procedure readln is used without parameters it skips theend of the current line.
Related topics
write, writeln.

Fair Isaac Corporation Conﬁdential and Proprietary Information

145

Predeﬁned functions and procedures

reset
Purpose
Synopsis

Reset an entity.
procedure reset(x:resettable entity)

Argumentx

A reference to a set, a list, an array, an object of an external type or problem

Further information
Only types supporting the ’copy’ operation (i.e. they can be assigned a value) can be reset. The effect of
this routine depends on the type of the object, typically the object returns to its state just after being
created. For instance, applying it to an mpproblem will clear the problem by detaching all constraints it
contains.
Related topics
delcell.

Fair Isaac Corporation Conﬁdential and Proprietary Information

146

Predeﬁned functions and procedures

restoreparam
Purpose
Synopsis

Restore the value of a control parameter.
procedure restoreparam(name:string)Argument
name

Name of a control parameter (case insensitive).

Further information
1. This procedure can only be used from a subroutine to restore the value of a parameter to its state at the
beginning of the routine.
2. Independently of the location of the call to this procedure and whether modiﬁcations are performed on
the parameter (using for instance setparam) the original value of the parameter is saved at the
beginning of the execution of the routine and restored before its termination.
Related topics
setparam, setdsoparam, localsetparam.

Fair Isaac Corporation Conﬁdential and Proprietary Information

147

Predeﬁned functions and procedures

reverse
Purpose
Synopsis

Reverse a list.
procedure reverse(l:list)

Argumentl

A listExampleL:=[1,2,3,4,5]
reverse(L)! => L=[5,4,3,2,1]
reverse(L)! => L=[1,2,3,4,5]
Related topics
getreverse.

Fair Isaac Corporation Conﬁdential and Proprietary Information

148

Predeﬁned functions and procedures

round
Purpose
SynopsisRound a number to the nearest integer.
function round(r:real):integer

ArgumentrReal number to be rounded

Return value
Rounded value.
ExampleIn the following, i takes the value 6, j the value -7, and k the value 12:
i := round(5.5)
j := round(-6.7)
k := round(12.3)

Related topics
ceil, floor.

Fair Isaac Corporation Conﬁdential and Proprietary Information

149

Predeﬁned functions and procedures

setcoeff
Purpose
Synopsis

Set the coefﬁcient of a variable or the constant term.
procedure setcoeff(c:linctr, x:mpvar, r:real)procedure setcoeff(c:linctr, r:real)

Argumentscxr
ExampleA linear constraint
A decision variable
Coefﬁcient or constant term

The following declares a constraint c and then changes some of its terms:
declarations
x,y,z: mpvar
end-declarations
c:= 4⁎x + y -z <= 12
setcoeff(c, y, 2)
setcoeff(c, 8.1)
The constraint is now 4 · x + 2 · y – z ≤ –8.1.

Further information
If a variable is given then this procedure sets the coefﬁcient of this variable in the constraint to thegiven value. Otherwise, it sets the constant term of the constraint.
Related topics
getcoeff.

Fair Isaac Corporation Conﬁdential and Proprietary Information

150

Predeﬁned functions and procedures

sethidden
Purpose
Synopsis

Hide or unhide a constraint.
procedure sethidden(c:linctr, b:boolean)

Argumentscb

ExampleA linear constraint
Constraint status:
true
Hide the constraint
false
Unhide the constraint

THe following deﬁnes a constraint and then sets it as hidden:
declarations
x,y,z: mpvar
end-declarations
c:= 4⁎x + y -z <= 12sethidden(c, true)

Further information
At its creation a constraint is added to the current problem, but using this procedure it may be hidden.
This means that the constraint will not be contained in the problem that is solved by the optimizer but it
is not deleted from the deﬁnition of the problem in Mosel. Function ishidden can be used to test thecurrent status of a constraint.
Related topics
ishidden.

Fair Isaac Corporation Conﬁdential and Proprietary Information

151

Predeﬁned functions and procedures

setioerr
Purpose
Synopsis

Raise an IO error.
procedure setioerr(msg:string)Argument
msg

Error message to display (or an empty string)

Further information
This function sets the control parameter iostatus (see getparam) such that an IO error is raised. If IO
errors are not handled by the model (see setparam), the execution is interrupted.
Related topics
setmatherr.

Fair Isaac Corporation Conﬁdential and Proprietary Information

152

Predeﬁned functions and procedures

setmatherr
Purpose
Synopsis

Raise a Math error.
procedure setmatherr(msg:string)Argument
msg

Error message to display (or an empty string)

Further information
If mathematical errors are not handled by the model (see setparam), the execution is interrupted. A
function ending with a call to this routine may set its return value to NAN or INFINITY in order toindicate its error status.
Related topics
setioerr, isnan, isinf, isfinite.

Fair Isaac Corporation Conﬁdential and Proprietary Information

153

Predeﬁned functions and procedures

setname
Purpose
Synopsis

Associate a matrix name to a constraint or variable.
procedure setname(c:linctr, n:string)procedure setname(v:mpvar, n:string)Argumentscvn

A linear constraint
A decision variable
Name given to the constraint or variable

Further information
1. When exporting a problem to a matrix ﬁle, constraint/variable names are deduced from the global
public symbols: anonymous and local entities are usually named after their row/column number in thematrix. This procedure makes it possible to give a name to these entities.
2. If the given name starts with the ’#’ character, the generated matrix name will include the ordernumber of the constraint or variable in the matrix.
Related topics
exportprob.

Fair Isaac Corporation Conﬁdential and Proprietary Information

154

Predeﬁned functions and procedures

setparam
Purpose
Synopsis

Set the value of a control parameter.
procedure setparam(name:string,val:integer|string|real|boolean)

Arguments
namevalExampleName of a control parameter (case insensitive).
New value for the control parameterSee example of function getparam.

Further information
1. Control parameters include the settings of Mosel as well as those of any loaded module or package.
The location of the parameter may be speciﬁed by preﬁxing its name with the name of the module or
package deﬁning it (e.g. mmxprs.XPRS_verbose). The type of the value must correspond to the type
expected by the parameter.
2. This procedure can be applied only to control parameters the value of which can be modiﬁed.
3. The name argument must be a constant string: a model parameter, variable or string expression cannot
be used as a control parameter name.
4. The following control parameters, supported by Mosel, can be altered with this procedure:
realfmt Default C printing format for real numbers (string, default: "%.10g")
zerotol zero tolerance in comparisons between reals (real, default: 1.0e-13). This parameter isalso used when displaying reals: any value smaller than the zero tolerance is handled like thezero constantioctrl specify whether the interpreter ignores IO errors (Boolean, default: false). When ioctrl isenabled it is required to get (and reset) the iostatus parameter (see getparam) after every
IO operation. Not doing so may result in undeﬁned behavior
mathctrl specify whether the interpreter ignores Maths errors (Boolean, default: false)
readcnt generate per label counting when executing ‘initializations from’ blocks (Boolean, default:
false)
UTC
indicate whether the time functions return time expressed in local (false) or UTC (true) time
(Boolean, default: false)
autofinal indicate whether initialisation from blocks are ﬁnalizing sets (Boolean, default: true or
false if compiler option noautofinal is used)
workdir specify the current working directory of the model (string, initialised with the current
working directory of the Mosel instance). The provided value can be a relative path (e.g.
"../somedir")recloc enable (or disable) automatic recording of source location of constraints deﬁnitions(Boolean, default: false). This parameter can be set to true only if the model has been
compiled with option -G; it makes it possible the creation of meaningful constraint names
when exporting a matrix (see exportprob)
localedir directory where message catalogs are stored (string, default: "./locale")bimprefix list of bim ﬁle preﬁxes (string). This parameter is used to locate packages whencompiling a model (compile) and loading a bim ﬁle (load), see Section 2.3.1.
Related topics
getparam, setdsoparam, localsetparam, restoreparam.

Fair Isaac Corporation Conﬁdential and Proprietary Information

155

Predeﬁned functions and procedures

setrandseed
Purpose
Synopsis

Initialize the random number generator.
procedure setrandseed(s:integer)

Arguments

Seed value

Further information
This procedure sets its argument as the seed for a new sequence of pseudo-random numbers to be
returned by the function random.
Related topics
random.

Fair Isaac Corporation Conﬁdential and Proprietary Information

156

Predeﬁned functions and procedures

setrange
Purpose
Synopsis

Set the domain range of a constraint.
procedure setrange(c:linctr, lb:real, ub:real)

Argumentsclbub
ExampleA linear constraint expression
Lower boundUpper bound

The following sets the domain of the x variable and deﬁnes c as a range constraint.
declarations
x,y,z: mpvar
c: linctr
end-declarations
c:= 2⁎y+4⁎z+5
setrange(x,3,10)
setrange(c,1,30)! 3<=x<=10! -4<=2⁎y+4⁎z<=25

Further information
1. If the parameter c is a linear expression a new anonymous range constraint is added to the problem.
Otherwise, the provided constraint is turned into a range constraint (and added to the problem if
required).
2. This procedure changes the type of the provided constraint to CT_RNG, stores the provided lower
bound as an external information and records the upper bound as the constant term of the constraint.
As a consequence deﬁning the range of a constraint modiﬁes its constant term, this has to be taken
into account if a range constraint is converted to another type or used as part of a linear expression.

Fair Isaac Corporation Conﬁdential and Proprietary Information

157

Predeﬁned functions and procedures

settype
Purpose
Synopsis

Set the type of a constraint.
procedure settype(c:linctr, type:integer)

Argumentsctype

A linear constraint
Constraint type

Further information
The type (type) of a linear constraint may be set to one of:
CT_EQ Equality, ‘=’
CT_GEQ Greater than or equal to, ‘ ≥ ’
CT_LEQ Less than or equal to, ‘ ≤ ’
CT_UNB Non-binding constraint
CT_SOS1 Special ordered set of type 1
CT_SOS2 Special ordered set of type 2
Values applicable for unary constraints only are:
CT_CONT Continuous
CT_INT Integer
CT_BIN Binary
CT_PINT Partial integer
CT_SEC Semi-continuous
CT_SINT Semi-continuous integer
CT_FREE Free
Related topics
gettype

Fair Isaac Corporation Conﬁdential and Proprietary Information

158

Predeﬁned functions and proceduressin
Purpose
Synopsis

Get the sine of a value.
function sin(r:real):realArgumentrReal number to which to apply the trigonometric function

Return value
Sine value of the argument.
Related topics
arctan, cos.

Fair Isaac Corporation Conﬁdential and Proprietary Information

159

Predeﬁned functions and procedures

splithead
Purpose
Synopsis

Split a list returning the ﬁrst elements.
function splithead(l:list, o:integer):list

Argumentslo

A listNumber of elements to remove if >0 or number of elements to keep if <0

Return value
The list of elements removed.
ExampleL:=[1,2,3,4,5]
L2:=splithead(L,2)
L2:=splithead(L,-1)! => L=[3,4,5] L2=[1,2]! => L=[5] L2=[3,4]Further information
If the second parameter is 0, the list is unchanged and an empty list is returned. If the same parameteris larger than the size of the list, all elements are deleted and the function returns a copy of the originallist.
Related topics
splittailFair Isaac Corporation Conﬁdential and Proprietary Information

160

Predeﬁned functions and procedures

splittailPurpose
Synopsis

Split a list returning the last elements.
function splittail(l:list, o:integer):list

Argumentslo

A listNumber of elements to remove if >0 or number of elements to keep if <0

Return value
The list of elements removed.
ExampleL:=[1,2,3,4,5]
L2:=splittail(L,2)
L2:=splittail(L,-1)! => L=[1,2,3] L2=[4,5]! => L=[1] L2=[2,3]Further information
If the second parameter is 0, the list is unchanged and an empty list is returned. If the same parameteris larger than the size of the list, all elements are deleted and the function returns a copy of the originallist.
Related topics
splithead

Fair Isaac Corporation Conﬁdential and Proprietary Information

161

Predeﬁned functions and procedures

sqrt
Purpose
Synopsis

Get the positive square root of a value.
function sqrt(r:real):realArgumentrReal value the function is applied to. This value must be non-negative.

Return value
Square root of the argument.
Related topics
abs, exp, ln, log.

Fair Isaac Corporation Conﬁdential and Proprietary Information

162

Predeﬁned functions and procedures

strfmtPurpose
SynopsisCreate a formatted string from a string or a number.
function strfmt(str:string,len:integer):string
function strfmt(i:integer, len:integer):string
function strfmt(r:real, len:integer):string
function strfmt(r:real, len:integer, dec:integer):stringArguments
str
i
r
len

dec

String to be formatted
Integer to be formatted
Real to be formatted
Reserved length (may be exceeded if given string is longer, in this case the string is always left
justiﬁed).
<0
Left justiﬁed within reserved space>0
Right justiﬁed within reserved space0
Use defaults
Number of digits after the decimal point

Return value
Formatted string.
ExampleThe following:
writeln("text1", strfmt("text2",8), "text3")
writeln("text1", strfmt("text2",-8), "text3")
r:=789.123456
writeln(strfmt(r,0)," ", strfmt(r,4,2), strfmt(r,8,0))
produces this output:
text1
text2text3
text1text2
text3
789.123 789.12

789

Further information
1. This function creates a formatted string from a string or an integer or real number. It can be used at any
place where strings may be used. Its most likely use is for generating printed output (in combination
with write and writeln).
2. If the resulting string is longer than the reserved space it is not cut but printed in its entirety, overﬂowing
the reserved space to the right.
Related topics
write, writeln.

Fair Isaac Corporation Conﬁdential and Proprietary Information

163

Predeﬁned functions and procedures

substrPurpose
Synopsis

Get a substring of a string.
function substr(str:string, i1:integer, i2:integer):stringArguments
str
i1
i2

StringStarting position of the substring
End position of the substring

Return value
Substring of the given string.
Examplewrite(substr("Example text", 3, 10))
This outputs the text: ample te
Further information
This function returns the substring from the i1th to the i2th character of a given string (the counting
starts from 1). This function returns an empty string if the bounds are not compatible with the string(e.g. starting position larger than the length of the string) or inconsistent (e.g. starting position afterend position).

Fair Isaac Corporation Conﬁdential and Proprietary Information

164

Predeﬁned functions and procedurestimestamp
Purpose
Synopsis

Generate a timestamp by combining the current UTC date and time.
function timestamp:real

Return value
The number of seconds since 1/1/1970 at midnight as a real.
Further information
1. This function corresponds to the expression (using UTC time):real(currentdate)⁎86400+currenttime/1000
2. A local time timestamp may be obtained using: getasnumber(datetime(SYS_NOW))
3. Refer to the module mmsystem for a set of dedicated types for handling date and time.
Related topics
currenttime,currentdate

Fair Isaac Corporation Conﬁdential and Proprietary Information

165

Predeﬁned functions and procedures

unpublish
Purpose
Synopsis

Unpublish a symbol.
procedure unpublish(name:string)Argument
nameSymbol to be removed from the dictionary

Further information
This procedure has the opposite effect of publish. If the given name does not correspond to apreviously published symbol no operation is performed.
Related topics
publish.

Fair Isaac Corporation Conﬁdential and Proprietary Information

166

Predeﬁned functions and procedures

versionnum, versionstr
Purpose
Synopsis

Version of Mosel, a module or package.
function versionnum(what:string):integerfunction versionstr(what:string):stringArgumentwhat

A module name, a package name or an empty string

Return value
A version number as a string formatted as "maj.min.rel" (with versionstr) or as an integer (withversionnum). An empty string or -1 is returned if the requested library cannot be found.
Further information
With an empty string these routines return the version of Mosel currently running. Otherwise theargument is expected to be the name of a module (no sufﬁx or name ending with ".dso"), or the nameof a package (name ending with ".bim"). In both cases the library must be currently used by themodel. For a package both imported and loaded at runtime packages are considered.

Fair Isaac Corporation Conﬁdential and Proprietary Information

167

Predeﬁned functions and procedures

write, writeln
Purpose
Synopsis

Send an expression or list of expressions to the active output stream.
procedure write(e1:expr[, e2:expr...])
procedure writeln
procedure writeln(e1:expr[, e2:expr...])

Argument
e1, e2,... Expression or list of expressions
ExampleThe following lines
Set1:={"first", "second", "fifth"}
write(Set1)! Print set contents without return
writeln! Print an empty line
b:=truewriteln("A real:", strfmt(7.1234, 4, 2), ", a Boolean:",b)! Output followed by return
produce this output:{`first', `second', `fifth'}
A real:7.12, a Boolean:true

Further information
These procedures write the given expression or list of expressions to the active output stream. The
procedure writeln adds the return character to the end of the output. Numbers may be formatted
using function strfmt (default formatting relies on parameters realfmt and zerotol, seesetparam). Basic types are printed "as is". For elementary but non-basic types (linctr, mpvar) only
the address is printed. If the expression is a set or array, all its elements are printed.
Related topics
fwrite, fwriteln, read, readln, strfmt, formattext.

Fair Isaac Corporation Conﬁdential and Proprietary Information

168

II. Modules

CHAPTER 4

mmetc
This compatibility module just deﬁnes the diskdata procedure required to use data ﬁles formatted for
mp-model from Mosel and provides a commercial discounting function. To use this module, thefollowing line must be included in the header of the Mosel model ﬁle:uses 'mmetc'

4.1

Procedures and functions
disc

Annual discount.

p. 171

diskdata

Read in or write an array or set of strings to a ﬁle.

p. 172

Fair Isaac Corporation Conﬁdential and Proprietary Information

170

mmetcdisc
Purpose
SynopsisAnnual discount.
function disc(a:real, t:real)

ArgumentsatDiscount factor, real number greater than -1
Time, real number

Return value
Annual discount value: 1/(1 + a)t–1 .
Further information
This function calculates the annual discount for the given period of time and discount factor.
Modulemmetc

Fair Isaac Corporation Conﬁdential and Proprietary Information171

mmetcdiskdata
Purpose
Synopsis

Read in or write an array or set of strings to a ﬁle.
procedure diskdata(format:integer, file:string, a:array)procedure diskdata(format:integer, file:string, s:set)procedure diskdata(format:integer, file:string, l:list)

Arguments
formatFormat options:
ETC_DENSE
ETC_SPARSEETC_SGLQETC_NOQETC_OUTETC_APPENDETC_TRANSETC_INETC_NOZEROSETC_CSV
ETC_SKIPH
ETC_AUTONDX

dense data format
sparse data format
strings quoted with single quotes
strings are not quoted in the ﬁlewrite to a ﬁleappend output to the end of an existing ﬁletables are transposed
read from ﬁle (default)
skip zero values
use CSV format
skip ﬁrst line (header) of the ﬁlesimilar to sparse format but indices are not read or written (only applies
to 1-dimension arrays indiced by ranges)
ETC_EMPTYNDX missing indices are replaced by a default value
Several options may be combined using ‘+’.
Extended ﬁle nameArray to export or initialize
Set to export or initialize
List to export or initialize

file
a
s
l
ExampleThe following example declares two sets and two dynamic arrays. The array ar1 is read in from the ﬁlein.dat. Then both arrays, ar1 and ar2, are saved to the ﬁle out.dat (in sparse format) and ﬁnallythe contents of the set Set1 is appended to the ﬁle out.dat.
declarations
Set1: set of string
R: range
ar1,ar2: array(Set1,R) of real
end-declarations
diskdata(ETC_SPARSE, "in.dat", ar1)
diskdata(ETC_OUT, "out.dat", [ar1, ar2])
diskdata(ETC_OUT+ETC_APPEND, "out.dat", Set1)

Further information
1. This procedure reads in data from a ﬁle or writes to a ﬁle, depending on the parameter settings. The ﬁleformat used is compatible with the command DISKDATA of the modeler mp-model (unless the option
ETC_CSV is speciﬁed).
2. Only arrays lists and sets of basic and native types (including mpvar and linctr for writing) can beused with this procedure, in particular records are not supported.

Fair Isaac Corporation Conﬁdential and Proprietary Information

172

mmetcModulemmetc

Fair Isaac Corporation Conﬁdential and Proprietary Information

173

mmetc

4.2

I/O drivers
This module provides the diskdata IO driver designed to be used as an interface for
initializations blocks for both reading and writing ﬁles formated for the diskdata procedure.

4.2.1

Driver diskdata
diskdata:[dense|sparse|autondx;][sglq|noq|csv;][skiph;emptyndx;append;trans;nozeros;fsep=c;dsep=c]

The driver can only be used in ‘initializations’ blocks. In the opening part of the block, no ﬁle name has
to be provided, but general options can be stated at this point: they will be applied to all labels. In theblock, each label entry is understood as the ﬁle name to use for the actual processing. Note that, before
the ﬁle name, one can add further options separated by comas or semicolons, that are effective to theparticular entry. Here, the csv option might be followed by a list of columns separated by commas andenclosed in parenthesis. The columns are identiﬁed by their number (ﬁrst column has index 1) andmust be given in ascending order without duplicate. If the last column number is sufﬁxed by the plus
sign, the following columns will also be included in the selection (e.g. "csv(1,3+)" skips the second
column). To use names, the option skiph must be used and the column names are taken from theheader row that is skipped through this option. When using skiph, column numbers need to be statedby preﬁxing the column number by # (even in this case columns must be given in ascending order).This
column selection is ignored for a writing operation. The ﬁle name given can use extended notation.
The diskdata driver takes the following options:dense

dense data format

sparsesparse data format

autondx

sparse data format with automatic indexation (applies only to 1-dimension arrays
indiced by ranges)

autondx=st same as autondx but starting index is set to st (instead of 1)
sglq

strings quoted with single quotes

noq

strings are not quoted in the ﬁlecsv

use CSV format: quoting and escaping with double quotes, all lines are processed (i.e.
characters ’!’ and ’&’ are ordinary symbols)

skiph

When reading, the ﬁrst line of the ﬁle is skipped, when writing, the ﬁrst line of the ﬁle ispreserved (or a comment line is inserted if the ﬁle does not already exist)

emptyndx

When reading array indices an empty cell causes a failure. With this option empty cells
are replaced by the default value of the corresponding type (e.g. 0 for a numerical value)

appendappend output to the end of an existing ﬁletranstables are transposed

nozeros

skip zero values

fsep=ccharacter used to separate ﬁelds. The default value is ","; tabulation or ";" are also
often employed

dsep=ccharacter used as decimal separator (default: ".")

Example:Fair Isaac Corporation Conﬁdential and Proprietary Information

174

mmetcdeclarations
Set1: set of string
ar1,ar2: array(Set1,range) of real
r: realend-declarations
initializations from "diskdata:"
ar1 as "sparse;csv(1,3,4);ind.dat"r as "r_init.dat"
end-initializations! Declare a set of strings! Declare two dynamic arrays! Declare a real value! Use 'diskdata' format for reading! Read `ar1' from 'in.dat' in sparse format! using CSV conventions and selecting columns 1,3 and 4! Initialize `r' from 'r_init.dat'

initializations to "diskdata:append" ! Use 'diskdata' format for output[ar1, ar2] as "out.dat"! Save two arrays in sparse format
Set1 as "out.dat"! Save set `Set1' to the same file
end-initializations

Fair Isaac Corporation Conﬁdential and Proprietary Information

175

CHAPTER 5

mmhttp
The module mmhttp makes it possible to communicate with external components via HTTP requests.
Both modes, client or server side, can be used in a Mosel model: the client routines allow a Mosel
model to send the HTTP requests GET, POST, PUT or DELETE to a web service. A model may also act
as a web service by starting the integrated HTTP server. In this mode, the model gets notiﬁed about
connections from remote clients via speciﬁc mmjobs events. The model can then reply to theserequests using a set of dedicated routines.
To use this module, the following line must be included in the header of the Mosel model ﬁle:uses 'mmhttp'5.1

New functionality for the Mosel language

5.1.1

The type reqqueue
The type reqqueue can be used to implement multithreaded HTTP servers: it represents a queue ofpending HTTP requests to be processed by the server. A queue of this type must be declared as a
global shared entity such that each cloned submodel of the master model can access it. A submodel
ready to handle a new request has to call httpreqpop in order to warn the queue manager of its
availability and then wait for an event. When the server receives a request that has to be processed by
one of these submodels it moves this request to the queue using httpreqpushlim or httpreqpush,
as a result the request is sent to one of the available submodels that is notiﬁed as if the request had
been directly received from the network (see Section 5.4.2). If no submodel is ready, the request isrecorded in the queue until a model becomes available for processing it.

5.2

Control parameters
The following parameters are deﬁned by mmhttp:http_async

HTTP requests processing mode.

p. 177

http_browser

Path to the web browser.

p. 177

http_cookies

Handling of cookies.

p. 178

http_defpage

Default page of the web server.

p. 178

http_defport

Default server TCP port.

p. 178

http_expire

Expiration delay of open connections.

p. 179http_freeasync

Number of available asynchronous connections.

p. 179Fair Isaac Corporation Conﬁdential and Proprietary Information176

mmhttp

http_keephdr

Whether to keep HTTP headers in results.

p. 179http_listenInterface used by server.

p. 179http_maxasync

Maximum number of pending asynchronous requests.

p. 181

http_maxconn

Maximum number of open connections.

p. 180

http_maxcontime

Maximum time for a connection.

p. 180

http_maxreq

Maximum number of waiting connections.

p. 180

http_maxreqtime

Maximum time for a connection.

p. 181

http_port

Server TCP port.

p. 181

http_proxy

Proxy address.

p. 182

http_proxyport

Proxy TCP port.

p. 182

http_srvconfig

Server options.

p. 182

http_startwb

Decide whether to start a web browser with the server.

p. 183https_defport

Default secure server TCP port.

p. 183https_listenInterface used by secure server.

p. 183https_port

Secure server TCP port.

p. 184

http_async
Description

This parameter selects the processing mode of the HTTP request functions(httpget|put|post|del). These functions return immediately after the connection to the server
has been established (without waiting for the reply by the server) when this parameter is set
to true. The model is notiﬁed about the completion of the request via an event of class
EVENT_HTTPEND.

Type

Boolean, read/write

Default value

false

Affects routines

httpdel, httpget, httppost, httpput.

See also

http_maxasync.

Modulemmhttphttp_browser
Description

The path to a web browser to be executed when the parameter http_startwb is active.

Type

String, read/write

ValuesPath to a web browser

Affects routines

httpstartsrv.

See also

http_startwb.

ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

177

mmhttp

http_cookies
Description

Decides whether cookie management is enabled: when this parameter is set to true thecookie store is updated according to server replies and request headers are completed withthe relevant cookies. Changing the value of this parameter does not affect the cookie store(i.e. existing cookies are not modiﬁed).

Type

Boolean, read/write

Default value

false

Affects routines

httpdel, httpget, httppost, httpput.

Modulemmhttphttp_defpage
Description

The default page is selected when the server receives a request not specifying any path (e.g.
"http://server/").

Type

String, read/write

ValuesThe label to be used as the default page. Selecting an empty string restores the default value

Default value"index.html"

Affects routines

httpstartsrv.

Modulemmhttphttp_defport
Description

This is the port number used by the web server upon its startup. If this parameter is 0, theport number is selected automatically by the operating system (the actual port number canbe retrieved through parameter http_port).

Type

Integer, read/write

Values

Between 0 and 65535

Default value0

Affects routines

httpstartsrv.

See also

http_port.

ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

178

mmhttp

http_expire
Description

Connections held in the connection pool are automatically closed if they are not used formore than the amount of time (in seconds) deﬁned by this parameter.

Type

Integer, read/write

Values

Between 5 and 60 by steps of 5 seconds

Default value

5

See also

http_maxconn.

Modulemmhttphttp_freeasync
Description

Up to http_maxasync asynchronous requests can be used concurrently. This parameter
reports the current number of asynchronous requests that can still be initiated.

Type

Integer, read only

See also

http_maxasync.

Modulemmhttphttp_keephdr
Description

By default results of HTTP queries do not include the HTTP header lines. This parameter canbe used to retrieve these header lines in addition to the result document (usehttpgetheader to separate the header from the effective result document).

Type

Boolean, read/write

Default value

false

Affects routines

httpdel, httpget, httppost, httpput.

Modulemmhttphttp_listen
Description

This is the interface used by the web server upon its startup. The default value implies
binding to all available interfaces.

Type

String, read/write

Default value

0.0.0.0

Fair Isaac Corporation Conﬁdential and Proprietary Information

179

mmhttp

Affects routines

httpstartsrv.

Modulemmhttphttp_maxconn
Description

This parameter deﬁnes the size of the connection pool: whenever an HTTP request is emitted
mmhttp tries to use one of the already open connections. After the end of the operation theconnection is saved into the pool (if the server supports this functionality). Setting thisparameter to 0 disables the pool (i.e. each query is executed on a new connection). When thisparameter is changed all connections of the pool are closed.

Type

Integer, read/write

Values

Between 0 and 8

Default value

4

See also

http_expire.

Modulemmhttphttp_maxcontime
Description

Maximum amount of time (in seconds) allowed for connecting to a HTTP server and send arequest. If the operation is longer than the speciﬁed duration the request is cancelled and theprocedure results in an IO error. A value of 0 disables this time limit.

Type

Integer, read/write

Default value0

See also

http_maxreqtime.

Affects routines

httpdel, httpget, httppost, httpput.

Modulemmhttphttp_maxreq
Description

The maximum number of active concurrent connections the server is maintaining. Above thislimit, connections are rejected and clients are notiﬁed with the HTTP code 500.

Type

Integer, read/write

ValuesAt least 1

Default value

16

Affects routines

httpstartsrv.

ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

180mmhttp

http_maxreqtime
Description

Maximum amount of time (in seconds) allowed for processing a request. If the operation islonger than the speciﬁed duration the request is cancelled and the procedure results in an IO
error. A value of 0 disables this time limit.

Type

Integer, read/write

Default value0

See also

http_maxcontime.

Affects routines

httpdel, httpget, httppost, httpput.

Modulemmhttphttp_maxasync
Description

This parameter deﬁnes the maximum number of active asynchronous requests that can besent by a Mosel model. This parameter can only be changed if asynchronous mode is not
active and there is no active request.

Type

Integer, read/write

Values

Between 4 and 58

Default value

8

Affects routines

httpdel, httpget, httppost, httpput.

See also

http_async, http_freeasync.

Modulemmhttphttp_port
Description

This parameter reports the port number currently used by the web server.

Type

Integer, read only

Affects routines

httpstartsrv.

See also

http_defport.

ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

181mmhttp

http_proxy
Description

When this parameter is deﬁned, HTTP connections are sent through this proxy server (insteadof establishing direct connections).

Type

Integer, read/write

Default value""

Affects routines

httpdel, httpget, httppost, httpput.

See also

http_proxyport.

Modulemmhttphttp_proxyport
Description

The value of this parameter corresponds to the connection port of the proxy server (whendeﬁned).

Type

Integer, read/write

Values

Between 1 and 65535

Default value

80

Affects routines

httpdel, httpget, httppost, httpput.

See also

http_proxy.

Modulemmhttphttp_srvconﬁg
Description

This parameter speciﬁes which request types are accepted by the HTTP server started from a
Mosel model. For instance, if the application will only process HTTP GET queries the value of
this parameter should be HTTP_GET. Moreover, if the ﬂag HTTP_SSL is set, the server will
also listen for HTTPS connections and, if the ﬂag HTTP_SSLONLY is used, only the HTTPS
server will be started (i.e. normal HTTP queries will be rejected). When an HTTPS server isstarted, the ﬂag HTTP_CLTAUTH enables client authentication: clients are accepted only ifthey present a known certiﬁcate.

Type

Integer, read/write

Default value

HTTP_DELETE+HTTP_GET+HTTP_POST+HTTP_PUT

Affects routines

httpstartsrv.

ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

182

mmhttp

http_startwb
Description

If this parameter is true a web browser pointing to the default page is launched just after the
web server starts.

Type

Boolean, read/write

Default value

false

Affects routines

httpstartsrv.

See also

http_browser.

Modulemmhttphttps_defport
Description

This is the port number used by the web secure server upon its startup. If this parameter is 0,
the port number is selected automatically by the operating system (the actual port number
can be retrieved through parameter https_port).

Type

Integer, read/write

Values

Between 0 and 65535

Default value0

Affects routines

httpstartsrv.

See also

https_port.

Modulemmhttphttps_listen
Description

This is the interface used by the secure web server upon its startup. The default value implies
binding to all available interfaces.

Type

String, read/write

Default value

0.0.0.0

Affects routines

httpstartsrv.

ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

183

mmhttp

https_port
Description

This parameter reports the port number currently used by the secure web server.

Type

Integer, read only

Affects routines

httpstartsrv.

See also

https_defport.

Modulemmhttp5.3

Constants
mmhttp deﬁnes the following constants for frequently used HTTP status codes (the codes of the 200
series indicate success, the 400 series are error codes, according to the RFC 2616 speciﬁcation). Notethat the textual representations of HTTP status codes can be obtained via function httpreason.


HTTP_OK: 200

HTTP_CREATED: 201

HTTP_ACCEPTED: 202

HTTP_NO_CONTENT: 204

HTTP_RESET_CONTENT: 205

HTTP_BAD_REQUEST: 400

HTTP_UNAUTHORIZED: 401



HTTP_PAYMENT_REQUIRED: 402



HTTP_FORBIDDEN: 403



HTTP_NOT_FOUND: 404

HTTP_METHOD_NOT_ALLOWED: 405



HTTP_NOT_ACCEPTABLE: 406



HTTP_PROXY_AUTHENTICATION_REQUIRED: 407



HTTP_REQUEST_TIMEOUT: 408

5.4

Procedures and functions

5.4.1

HTTP client
The HTTP requests GET, HEAD, POST, PUT and DELETE can be sent to a web service using functions
httpget, httphead, httppost, httpput and httpdel respectively. Each of these functions takes
at least two parameters: the URL of the resource and a ﬁle name where to store the result of theoperation. POST and PUT requests require an additional ﬁle, namely the data source to be sent to the
web service.

Fair Isaac Corporation Conﬁdential and Proprietary Information

184

mmhttp

HTTP requests are either processed synchronously or asynchronously.
When a request is sent in synchronous mode (the default), the HTTP function call returns after theprocessing has completed and the return value corresponds to the status of the request (a successful
request will have a status value between 200 and 299). The following example uses www.bing.com tosearch for ’FICO’ using a synchronous request:
status:=httpget("http://www.bing.com/search?q=FICO", "result.html")
if status div 100=2 thenwriteln("Found FICO!")else
writeln("Request failed with code :", status, " (", httpreason(status), ")")
end-ifIf the asynchronous mode is active (that is, the parameter http_async is set to true) the HTTP
functions return just after the request has been sent, without waiting for the reply by the server. The
processing continues in a separate thread of execution (up to http_maxasync requests can behandled at the same time) and the function returns a request identiﬁer (or an error code in case of
failure during the connection phase). Once the request has completed (i.e. the server has replied) an
event of class EVENT_HTTPEND is raised (please refer to the documentation of the module mmjobs forfurther explanation on how to handle events). The associated value of this event isrequest_id+status/1000. For instance if request number 1300 succeeded with status 204 (’nodata’) the corresponding event value is 1300.204. An asynchronous request can be cancelled using
httpcancel: in this case an event is still generated but its status is 998.
In the following example, search for ’FICO’ is sent to BING, Yahoo and Ask at the same time. A loop isthen started to wait for answers from each of the search engines.
setparam("http_async",true)! Switch to asynchronous modereqyahoo:=httpget("http://us.search.yahoo.com/search/?p=FICO", "resyahoo.html")
writeln("Request ", reqyahoo, " sent to Yahoo")reqbing:=httpget("http://www.bing.com/search?q=FICO", "resbing.html")
writeln("Request ", reqbing, " sent to BING")
reqask:=httpget("http://uk.ask.com/web?q=FICO", "resask.html")
writeln("Request ", reqask, " sent to Ask")
if reqbing<1000 or reqyahoo<1000 or reqask<1000 thenwriteln("A request has failed!")else
nbdone:=0
repeatwait! Wait for an event
evt:=getnextevent
if evt.class = EVENT_HTTPEND then
! One of the requests completed
reqnum:=floor(evt.value)! Get request number
write("Request ", reqnum, " done: ")status:=round((evt.value-reqnum)⁎1000)! Get HTTP status
if status div 100=2 then
! 200<=status<300 is successwriteln("Found FICO!")else! Any other value is an error code
writeln("Failed with code :", status, " (", httpreason(status), ")")
end-ifnbdone+=1
end-ifuntil nbdone=3! Finished when all requests are done
end-ifBy default the module performs direct TCP connections to the servers but a proxy may be speciﬁedusing the http_proxy and http_proxyport parameters.
It is possible to set a limit on the time spent for connecting to a server by using http_maxcontime.
The parameter http_maxreqtime deﬁnes a time limit on the entire request (i.e. connection andretrieval of result). mmhttp will wait undeﬁnitely for each request if none of these parameters is
deﬁned.

Fair Isaac Corporation Conﬁdential and Proprietary Information

185mmhttp

When requests are sent to a secure server (i.e. URL starting with "https://") the trusted certiﬁcatesﬁle https_cacerts must be available such that authenticity of servers can be veriﬁed. If thisveriﬁcation is not required, the control parameter https_trustsrv has to be set to true. If therequested secure server requires client authentication, client certiﬁcate https_cltcrt andassociated private key https_cltkey must be deﬁned. Note that these parameters are published bymmssl: this module has to be used when a secure requests have to be sent.
HTTP client functions:delcookies

Delete cookies from the cookie store.

p. 187findcookie

Get the value of a cookie from the cookie store.

p. 188

httpcancel

Cancel an asynchronous request.

p. 189httpdelPerform an HTTP DELETE request.

p. 190

httpgetPerform an HTTP GET request.

p. 191

httpgetheader

Extract the HTTP header of a result ﬁle.

p. 192httphead

Perform an HTTP HEAD request.

p. 193

httppost

Perform an HTTP POST request.

p. 194

httpput

Perform an HTTP PUT request.

p. 195httpreason

Generate the text representation of an HTTP status code.

p. 196

loadcookies

Load cookies from a ﬁle.

p. 197savecookies

Save the cookie store into a ﬁle.

p. 198setcookie

Deﬁne or update a cookie.

p. 199tcpping

Test availability of a service on a server.

p. 200urlencode

Encode a text string for a URL.

p. 201

Fair Isaac Corporation Conﬁdential and Proprietary Information

186

mmhttpdelcookies
Purpose
Synopsis

Delete cookies from the cookie store.
procedure delcookies(domain:text|string)Argument
domain

Domain ﬁlter of the cookies to be deleted or an empty string to select all cookies

Related topics
setcookie.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

187

mmhttpﬁndcookie
Purpose
Synopsis

Get the value of a cookie from the cookie store.
function findcookie(name:string, domain:text, path:text, strict:boolean,val:text)

Arguments
namedomainpath
strictval

Cookie name
Domain of the cookie
Path in the domain
If true perfect matching is required for name, domain and path (like for setcookie),otherwise any cookie of the requested name with a compatible domain and path is returned
Returned value when a corresponding cookie is found

Return value
true if the cookie was found (its value is saved in val), false otherwise
Related topics
delcookies, findcookie.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

188mmhttp

httpcancel
Purpose
SynopsisCancel an asynchronous request.
procedure httpcancel(id: integer)

Argument
id

Number of the request to cancel

Further information
This procedure has no effect if the request number cannot be found (e.g. the request has completed in
the meantime). If the request is effectively cancelled an event of class EVENT_HTTPEND is raised witha request status of value 998.
Related topics
httppost, httpput, httpget, httphead, httpdel.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

189mmhttp

httpdelPurpose
Synopsis

Perform an HTTP DELETE request.
function httpdel(url:string|text, result:string):integerfunction httpdel(url:string|text, result:string, xhdr:string|text):integer

Arguments
url
result
xhdr

URL to process
File to store the result of the request
Additional headers to add to the request

Return value
HTTP status of the request (e.g. 200 for success, see Section 5.3 for a list of predeﬁned status code
constants; value 999 indicates that an I/O error occurred during the operation) or the request number (≥ 1000) if the asynchronous mode is active
Further information
1. The function returns after the request has been processed when synchronous mode is active (seehttp_async). Otherwise, using asynchronous mode, the function returns immediately after having
sent the request and the model is notiﬁed about the completion of the operation by an event of class
EVENT_HTTPEND. In this mode the result ﬁle result must be a physical ﬁle (although drivers "tmp:"
and "null:" can still be used).
2. When cookie management is enabled (see http_cookies) an additional header "Cookie:" isinserted into the request if the cookie store contains compatible cookies. This behaviour is disabled if
this optional header is already speciﬁed via the parameter xhdr.
Related topics
httppost, httpput, httpget, httphead, httpcancel.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

190

mmhttp

httpgetPurpose
Synopsis

Perform an HTTP GET request.
function httpget(url:string|text, result:string):integerfunction httpget(url:string|text, result:string, xhdr:string|text):integer

Arguments
url
result
xhdr

URL to process
File to store the result of the request
Additional headers to add to the request

Return value
HTTP status of the request (e.g. 200 for success, see Section 5.3 for a list of predeﬁned status code
constants; value 999 indicates that an I/O error occurred during the operation) or the request number (≥ 1000) if asynchronous mode is active
ExampleRetrieve the default entry page of the FICO website in French and store it in the ﬁle "fico.html":
status:=httpget('http://www.fico.com/fr/Pages/default.aspx', 'fico.html')

Further information
1. The function returns after the request has been processed when synchronous mode is active (seehttp_async). Otherwise, using asynchronous mode, the function returns immediately after having
sent the request and the model is notiﬁed about the completion of the operation by an event of class
EVENT_HTTPEND. In this mode the result ﬁle result must be a physical ﬁle (although drivers "tmp:"
and "null:" can still be used).
2. When building a query it is important to encode data to be sent using urlencode
3. By default the header "Accept-Encoding: gzip" is inserted into the request and the result data is
automatically decompressed if the server supports compression. This behaviour is disabled if thisoptional header is already speciﬁed (e.g. the parameter xhdr includes "Accept-Encoding:identity").
4. When cookie management is enabled (see http_cookies) an additional header "Cookie:" isinserted into the request if the cookie store contains compatible cookies. This behaviour is disabled if
this optional header is already speciﬁed via the parameter xhdr.
Related topics
httppost, httpput, httpdel, httphead, urlencode, httpcancel.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

191

mmhttp

httpgetheader
Purpose
Synopsis

Extract the HTTP header of a result ﬁle.
function httpgetheader(sfile:string|text):text
function httpgetheader(sfile:string|text, dfile:string|text):text

Arguments
sfile Name of the ﬁle to process
dfile Destination ﬁle (can be the same as sfile)
Return value
Header of the result document
Further information
1. Result ﬁles of queries inlude the HTTP header when the parameter http_keephdr is set to true: thisfunction returns the header of a result ﬁle when this setting is active.
2. The optional destination ﬁle dfile receives a copy of the original result ﬁle after the header has been
removed.
Related topics
httpget, httppost, httpput, httpdel.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

192

mmhttp

httphead
Purpose
Synopsis

Perform an HTTP HEAD request.
function httphead(url:string|text, result:string):integerfunction httphead(url:string|text, result:string, xhdr:string|text):integer

Arguments
url
result
xhdr

URL to process
File to store the result of the request
Additional headers to add to the request

Return value
HTTP status of the request (e.g. 200 for success, see Section 5.3 for a list of predeﬁned status code
constants; value 999 indicates that an I/O error occurred during the operation) or the request number (≥ 1000) if asynchronous mode is active
Further information
The HEAD request is equivalent to a GET request except that no result is returned by the server, only theheader can be retrieved (see httpgetheader).
Related topics
httppost, httpput, httpdel, httpget, urlencode, httpcancel.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information193

mmhttp

httppost
Purpose
Synopsis

Perform an HTTP POST request.
function httppost(url:string|text, data:string, result:string):integerfunction httppost(url:string|text, data:string, result:string,
xhdr:string|text):integer

Arguments
url
data
result
xhdr

URL to process
Data ﬁle to be sent to the server
File to store the result of the request
Additional headers to add to the request

Return value
HTTP status of the request (e.g. 200 for success, see Section 5.3 for a list of predeﬁned status code
constants; value 999 indicates that an I/O error occurred during the operation) or the request number (≥ 1000) if asynchronous mode is active
Further information
1. The function returns after the request has been processed when synchronous mode is active (seehttp_async). Otherwise, using asynchronous mode, the function returns immediately after having
sent the request and the model is notiﬁed about the completion of the operation by an event of class
EVENT_HTTPEND. In this mode the result ﬁle result must be a physical ﬁle (although drivers "tmp:"
and "null:" can still be used).
2. The parameter xhdr is typically used when the data type has to be speciﬁed. For instance, when thedata sent is URL-encoded it may be necessary to use "Content-Type:application/x-www-form-urlencoded" as the value for xhdr in order to indicate to the server
how to decode and process the data.
3. By default the header "Accept-Encoding: gzip" is inserted into the request and the result data is
automatically decompressed if the server supports compression. This behaviour is disabled if thisoptional header is already speciﬁed (e.g. the parameter xhdr includes "Accept-Encoding:identity").
4. When cookie management is enabled (see http_cookies) an additional header "Cookie:" isinserted into the request if the cookie store contains compatible cookies. This behaviour is disabled if
this optional header is already speciﬁed via the parameter xhdr.
Related topics
httpget, httphead, httpput, httpdel, urlencode, httpcancel.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

194

mmhttp

httpput
Purpose
Synopsis

Perform an HTTP PUT request.
function httpput(url:string|text, data:string, result:string):integerfunction httpput(url:string|text, data:string, result:string,
xhdr:string|text):integer

Arguments
url
data
result
xhdr

URL to process
Data ﬁle to be sent to the server
File to store the result of the request
Additional headers to add to the request

Return value
HTTP status of the request (e.g. 200 for success, see Section 5.3 for a list of predeﬁned status code
constants; value 999 indicates that an I/O error occurred during the operation) or the request number (≥ 1000) if asynchronous mode is active
Further information
1. The function returns after the request has been processed when synchronous mode is active (seehttp_async). Otherwise, using asynchronous mode, the function returns immediately after having
sent the request and the model is notiﬁed about the completion of the operation by an event of class
EVENT_HTTPEND. In this mode the result ﬁle result must be a physical ﬁle (although drivers "tmp:"
and "null:" can still be used).
2. The parameter xhdr is typically used when the data type has to be speciﬁed. For instance, when thedata sent is URL-encoded it may be necessary to use "Content-Type:application/x-www-form-urlencoded" as the value for xhdr in order to indicate to the server
how to decode and process this data.
3. When cookie management is enabled (see http_cookies) an additional header "Cookie:" isinserted into the request if the cookie store contains compatible cookies. This behaviour is disabled if
this optional header is already speciﬁed via the parameter xhdr.
Related topics
httpget, httphead, httppost, httpdel, urlencode, httpcancel.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

195

mmhttp

httpreason
Purpose
Synopsis

Generate the text representation of an HTTP status code.
function httpreason(code:integer):stringArgument
code

HTTP status code (see Section 5.3 for a list of predeﬁned status code constants)

Return value
Text associated to the provided status code or an empty string if the code is unknown
ExampleThe following displays "Bad Request":
writeln(httpreason(400))

Further information
The HTTP standard speciﬁes a set of predeﬁned status codes. This function returns the text
associated with a given code. For instance, upon success a request will reply with code 200 ("OK") or
204 ("No Content").
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

196

mmhttploadcookies
Purpose
Synopsis

Load cookies from a ﬁle.
function loadcookies(fname:string|text, host:string):integer

Arguments
fname Source ﬁle namehost If not empty only cookies compatible with this host name are recorded
Return value
Number of cookies added to the store
Further information
This function loads cookies from the speciﬁed ﬁle and record them into the cookie store. The ﬁle must
be encoded as a HTTP header and only "Set-Cookie" headers are processed (other lines are silently
ignored).
Related topics
savecookies, setcookie.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information197

mmhttp

savecookies
Purpose
Synopsis

Save the cookie store into a ﬁle.
function savecookies(fname:string|text, domain:string):integer

Arguments
fnamedomainDestination ﬁle name
Domain ﬁlter of the cookies to be saved or an empty string to select all cookies

Return value
Number of records generated
Further information
This function saves the selected cookies into a text ﬁle. The cookies are encoded according to thestandard "Set-Cookie" header (one record per line per cookie).
Related topics
loadcookies, findcookie.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

198

mmhttp

setcookie
Purpose
SynopsisDeﬁne or update a cookie.
procedure setcookie(name:string, value:text, domain:text, path:text,
exp:integer)

Arguments
name
value
domainpath
exp

Cookie name
Associated value
Domain of the cookie: if it does not start with a dot the domain is interpreted as a host nameand the cookie is a host only cookie
Path in the domain
Expiration time: with a negative value the cookie is deleted; with 0 the cookie never expires(session cookie) and a positive value is interpreted as an amount of time in seconds after
which the cookie will expire

Further information
This procedure adds a cookie to the cookie store. If an existing cookie has the same name, domain andpath as those speciﬁed to the procedure its value and expiration information is updated.
Related topics
delcookies, findcookie.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

199

mmhttptcpping
Purpose
Synopsis

Test availability of a service on a server.
function tcpping(host:string|text,port:integer):integer

Arguments
host
port

Name of server to test
Service port

Return value
Test result:0Connection succeeded
1
Invalid parameters
2
Host name not found3
Connection failed
Further information
This function opens a TCP connection to to the given host and port and closes it immediately in case of
success.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information200

mmhttp

urlencode
Purpose
Synopsis

Encode a text string for a URL.
function urlencode(data:string|text):text

Argument
data

Text to encode

Return value
Encoded text suitable for building a URL
ExampleThe following request sends query "qry" to the server "srv" requiring parameters "a" and "b". The
values associated with these parameters are URL-encoded:
status:=httpget("http://srv/qry?a="+urlencode(a)+"&b="+urlencode(b), "result.txt")

Further information
1. This function converts a text string into a format that is compatible with URL conventions. The
conversion consists in replacing characters with a special meaning by a portable representation basedon the character code. For example, the character "&" is replaced by "%26".
2. Typically, query parameters have to be encoded when sending them via an HTTP GET request, data
sent via POST may also have to be encoded.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

201

mmhttp

5.4.2

HTTP server
The mmhttp module integrates an HTTP server that is started using the procedure httpstartsrv andstopped with httpstopsrv (the server is stopped in any case when the execution of the model
terminates). The server behaviour may be changed using these module parameters: http_defportdeﬁnes the TCP port on which the server is listening (by default a random port is selected);
http_defpage indicates which page or label the server has to consider when no path is speciﬁed in arequest (by default this is "index.html"); http_srvconfig deﬁnes the set of request types
supported by the model (for instance only GET and POST) as well as whether a secure server is to be
started; http_maxreq sets a limit on the number of simultaneous connections that are kept active.
When a secure server (HTTPS) is requested (the server conﬁg includes ﬂags HTTP_SSL or
HTTP_SSLONLY) besides the optional basic settings similar to those used for the standard server (likehttps_defport) additional parameters have to be set. The server certiﬁcate https_srvcrt as wellas its private key https_srvkey are required. Moreover, if the clients are requested to authenticate
themselves (server option HTTP_CLTAUTH), the authorised certiﬁcate ﬁle https_cacerts must
include the expected certiﬁcates. Note that these parameters are published by mmssl: this module has
to be used when a secure server is started.
The server runs in the background and notiﬁes the model of incoming connections through events ofclass EVENT_HTTPNEW (please refer to the documentation of mmjobs for further explanation on how
to handle events). The value associated with this event is a request number: the connection to theclient is kept open and the model has to reply to the request in order to complete the operation. Anydata associated with the incoming request (query in the case of a GET or data sent via POST or PUT) is
saved into a temporary ﬁle before the event is sent. URL encoded information is automatically decodedand converted to a format compatible with initialisations from blocks. The function
httppending may also be used to retrieve the list of requests currently waiting for a reply.
Request properties can be obtained through a set of dedicated routines: httpreqfrom is the IP
address of the client; httpreqtype is the request type (i.e. GET, POST, PUT or DELETE);
httpreqheader is the request header; httpreqstat reports the status associated to a request
number (for instance whether it is active, or has associated data); httpreqlabel is the label of therequest; httpreqcookies returns the cookies found in the header. The label of a request is its URL
after having removed server reference and the query data (for example, the label returned for"http://srv/some/path?a=10" is "some/path"); httpreqfile is the name of the temporaryﬁle holding data associated to the request.
Three different methods can be used to reply to a request: httpreplycode will only return a status
code associated with a short (error) message; httpreply takes as input a ﬁle to be sent back to theclient (with a success status code) and httpreplyjson converts its input parameter into JSON datathat is sent back to the client.
The following example shows how to implement a simple ﬁle server. This program expects GET(download a ﬁle) and PUT (upload a ﬁle) requests sent to the port 2533. The URI of the request isinterpreted as the ﬁle name: for example, the URL "http://srv:2533/myfile.txt" could be used
to access ﬁle "myfile.txt" stored on host "srv" running this example.
setparam("http_defport", 2533)! Set server port (2533)
setparam("http_srvconfig",HTTP_GET+HTTP_PUT) ! Only GET and PUT requests
setparam("workdir", getparam("tmpdir"))! Move to temporary directory
httpstartsrv! Server now running
repeatwait! Wait for an event
ev:=getnextevent
if ev.class=EVENT_HTTPNEW then
! Request pending
r:=integer(ev.value)! Get request ID
fname:=httpreqlabel(r)! File name will be the URI
if httpreqtype(r)=HTTP_GET then! Client wants to get the fileif bittest(getfstat(fname), SYS_TYP) = SYS_REG then
httpreply(r,fname)! If available: send it

Fair Isaac Corporation Conﬁdential and Proprietary Information

202

mmhttpelse
httpreplycode(r,404)
end-ifelif httpreqtype(r)=HTTP_PUT and
httpreqstat(r)>=2 thenfmove(httpreqfile(r), fname)
if getsysstat=0 then
httpreplycode(r,204)
else
httpreplycode(r,403)
end-ifelse
httpreplycode(r,400)
end-ifend-ifuntil false! Otherwise: reply "Not Found"! Client wants to put a file
! File must be non-empty! Try to save it! If success: reply "No Content"! Otherwise: reply "Forbidden"! Empty files are refused

In the above example all requests are handled by the same model but it is also possible to dispatch theprocessing of the requests to several submodels running concurrently to improve the efﬁciency of theservice. To implement a multithreaded server a queue of requests of type reqqueue (See Section 5.1)
has to be declared as a global shared entity and each of the submodels must be clones of the server
model (in order to have access to this shared queue). The master model can then start all of its
submodels and initialise the HTTP server as in the preceding example but it can move the HTTP
requests it receives to the queue using httpreqpush. The submodels enter a loop starting with a callto httpreqpop (to indicate that they are ready to handle a request) followed by a wait: requests
coming from the master model are notiﬁed via an event of class EVENT_HTTPNEW and exposed just as
in a single-model server. The general structure of the server looks like the following:parameters
MASTER=true
NBW=5
end-parameters! Running the master or a worker?
! Number of submodels to startdeclarations
queue: shared reqqueue! The shared queue of requests
procedure run_masterprocedure run_worker
procedure process_request(req:integer)
end-declarations
if MASTER thenrun_masterelse
run_worker
end-if! The master model runs the HTTP server
procedure run_masterdeclarations
workers:array(1..NBW) of Model
end-declarations
forall(i in 1..NBW) doload(workers(i))! Each worker is a clone of the serverrun(workers(i),"MASTER=false")
end-dosetparam("http_defport", 2533)! Set server port (2533)
setparam("http_srvconfig",HTTP_GET+HTTP_PUT) ! Only GET and PUT requests
setparam("workdir", getparam("tmpdir"))! Move to temporary directory
httpstartsrv! Server now running
repeatwait! Wait for an event
ev:=getnextevent
if ev.class=EVENT_HTTPNEW then
! Request pending
r:=integer(ev.value)! Get request ID
httpreqpush(r,queue)! Move it to the queue
end-ifFair Isaac Corporation Conﬁdential and Proprietary Information

203mmhttp
until false
end-procedure! Each worker waits for requests sent by the master model and processes themprocedure run_worker
setparam("workdir", getparam("tmpdir"))! Move to temporary directory
repeathttpreqpop(queue)! Model readywait! Wait for an event
ev:=getnextevent
if ev.class=EVENT_HTTPNEW then
! Request pending
r:=integer(ev.value)! Get request ID
process_request(r)! Actual processing
end-ifuntil false
end-procedure

HTTP server functions:
httppending

Get a list of requests waiting for a reply.

p. 205

httpqueueinfo

Get size information of a queue of requests.

p. 206

httpreply

Reply to an HTTP request with a ﬁle.

p. 207

httpreplycode

Reply to an HTTP request only with a status code.

p. 208httpreplyjson

Reply to an HTTP request with JSON data.

p. 209httpreqcookies

Retrieve the cookies of a request.

p. 210

httpreqfile

Get the data ﬁle associated to a request.

p. 211

httpreqfrom

Get the IP address of the sender of a request.

p. 212

httpreqheader

Get the header associated to a request.

p. 213

httpreqlabel

Get the label associated to a request.

p. 214

httpreqpop

Ask for a HTTP request from a queue.

p. 215httpreqpush

Move a request to a queue.

p. 216

httpreqpushlim

Move a request to a queue with restriction.

p. 217

httpreqstat

Get the status associated with a request.

p. 218httpreqtype

Get the type of a request.

p. 219httpstartsrv

Start the HTTP server.

p. 220httpstopsrv

Stop the HTTP server.

p. 221

jsonwrite

Generate a JSON representation of a Mosel entity.

p. 222mksetcookie

Generate a set-cookie header line.

p. 223

Fair Isaac Corporation Conﬁdential and Proprietary Information

204

mmhttp

httppending
Purpose
Synopsis

Get a list of requests waiting for a reply.
function httppending(lp:list of integer):integerfunction httppending:integer

Argument
lp

List of request numbers

Return value
Number of requests in the waiting queue
Further information
This function returns in lp the list of requests currently waiting for a reply in the server queue (thecontent of the list is replaced).
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

205

mmhttp

httpqueueinfo
Purpose
Synopsis

Get size information of a queue of requests.
function httpqueueinfo(rq:reqqueue, what:integer):integer

Argumentsrq
what

A queue of requests
What information to retrieve:
0
Number of requests waiting in the queue
1
Number of models having access to the queue
2
Number of models ready for processing a request
3
The result of httpqueueinfo(rq,2)-httpqueueinfo(rq,0)Return value
Requested information or 0 for an unknown code.
Related topics
httpreqpushlim.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

206

mmhttp

httpreply
Purpose
Synopsis

Reply to an HTTP request with a ﬁle.
procedure httpreply(reqid:integer)
procedure httpreply(reqid:integer, fname:string)procedure httpreply(reqid:integer, fname:string|text, xhdr:string|text)

Arguments
reqid Request number
fname Name of the ﬁle holding the response data
xhdr Additional headers to include in the response
Further information
1. This procedure replies to the speciﬁed request sending the provided ﬁle and using 200 (’OK’) as the
HTTP status code.
2. The ﬁrst form of the procedure is the same as providing an empty ﬁle name with the second form: inthis case no data is sent to the client and the returned status code becomes 204 (’No Content’).
3. If the speciﬁed request is of type HEAD (see httphead) this procedure sends only the header part of
the result.
Related topics
httpreplycode, httpreplyjson, mksetcookie.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information207

mmhttp

httpreplycode
Purpose
Synopsis

Reply to an HTTP request only with a status code.
procedure httpreplycode(reqid:integer, code:integer)
procedure httpreplycode(reqid:integer, code:integer, msg:string)procedure httpreplycode(reqid:integer, code:integer, msg:string,
xhdr:string|text)

Arguments
reqid Request number
code HTTP status code to be returned (see Section 5.3 for a list of predeﬁned status code
constants)
msg
Explanation text
xhdr Additional headers to include in the response
Further information
1. This procedure replies to the speciﬁed request using the provided code that should be a valid HTTP
status (i.e. 3 digit number).
2. Unless the provided code is 204 (No Content) a basic HTML page is generated as the data associatedto the response including the standard reason (e.g. Bad Request for code 400) as well as the given
explanation text.
3. If the speciﬁed request is of type HEAD (see httphead) this procedure sends only the header part of
the result.
Related topics
httpreply, httpreplyjson, mksetcookie, Section 5.3.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

208

mmhttp

httpreplyjson
Purpose
Synopsis

Reply to an HTTP request with JSON data.
procedure httpreplyjson(reqid:integer)
procedure httpreplyjson(reqid:integer, mosobj:⁎)

Arguments
reqidmosobjRequest number
Mosel object to use for the reply

Further information
1. This procedure replies to the speciﬁed request by sending the provided Mosel object encoded as a
JSON object.
2. When the ﬁrst form is used, the returned data is the JSON constant null.
3. If the speciﬁed request is of type HEAD (see httphead) this procedure sends only the header part of
the result.
Related topics
httpreply, httpreplycode.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

209

mmhttp

httpreqcookies
Purpose
Synopsis

Retrieve the cookies of a request.
procedure httpreqcookies(reqid:integer, cook:array(string) of text)

Arguments
reqid Request number
cook An array where cookie values are returned (indiced by the names of the cookies)
Further information
This procedure decodes the header "Cookie" of a request to populate the provided array.
Related topics
httpreqfrom, httpreqlabel, httpreqstat, httpreqtype, httpreqheader, httpreqfile,mksetcookie.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

210mmhttp

httpreqﬁlePurpose
Synopsis

Get the data ﬁle associated to a request.
function httpreqfile(reqid:integer):stringArgument
reqid Request number
Return value
Full path to the data ﬁleFurther information
1. Each request is associated with a data ﬁle located in the temporary directory. This function returns thefull path to this ﬁle.
2. The data ﬁle is speciﬁc to the given request number and can be used (for instance, to store theresponse to the request) even if no data is associated with the request.
Related topics
httpreqfrom, httpreqlabel, httpreqstat, httpreqtype, httpreqheader,httpreqcookies.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

211

mmhttp

httpreqfrom
Purpose
Synopsis

Get the IP address of the sender of a request.
function httpreqfrom(reqid:integer):text

Argument
reqid Request number
Return value
IP of the sender of the request as a text string
Related topics
httpreqtype, httpreqfile, httpreqstat, httpreqlabel, httpreqheader,httpreqcookies.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information212

mmhttp

httpreqheader
Purpose
Synopsis

Get the header associated to a request.
function httpreqheader(reqid:integer):text

Argument
reqid Request number
Return value
Header of the request
Further information
The header of the request is a block of text consisting of lines of the form ﬁeldname:value (e.g.
Content-Type: application/json).
Related topics
httpreqfrom, httpreqfile, httpreqstat, httpreqlabel, httpreqtype, httpreqcookies.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

213

mmhttp

httpreqlabel
Purpose
Synopsis

Get the label associated to a request.
function httpreqlabel(reqid:integer):text

Argument
reqid Request number
Return value
Label of the request
Further information
1. The label of the GET or DELETE request is the URL after having removed server reference and query
data (for instance the label returned for "http://srv/some/path?a=10" is "some/path"). Any
query data is automatically saved into the associated request ﬁle (httpreqfile) in a format
compatible with initialisations blocks. When such a ﬁle has been created the request status(httpreqstat) has value 3.
2. In the case of a POST or PUT request the returned value also includes the undecoded data.
Related topics
httpreqfrom, httpreqfile, httpreqstat, httpreqtype, httpreqheader, httpreqcookies.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

214

mmhttp

httpreqpop
Purpose
Synopsis

Ask for a HTTP request from a queue.
procedure httpreqpop(rq:reqqueue)

Argumentrq

A queue of requests

Further information
1. This procedure has to be used by a model to notify the manager of a queue of requests that it is readyfor processing an HTTP request. After this call, as soon as a new request is available an event of class
EVENT_HTTPNEW is sent to the model that can handle it as if it was running the HTTP server.
2. The model is ﬂagged as available if no request is waiting in the queue. This ﬂag is cleared when arequest is passed to the model: it is therefore required to call the procedure again after a request has
been processed.
Related topics
httpreqpushlim, httpreqpush, httpqueueinfo.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

215

mmhttp

httpreqpush
Purpose
SynopsisMove a request to a queue.
procedure httpreqpush(reqid:integer,rq:reqqueue)

Arguments
reqid Request number or -1
rq
A queue of requests
Further information
1. This routine moves the selected request to a queue of requests in order to make it available to otherserver models. The request can no longer be accessed by the calling model after it has been passed tothis procedure.
2. If the provided request is -1 this routine only clears the availability ﬂag of the model (i.e. it is no longer
ready to process a request).
Related topics
httpreqpushlim, httpreqpop, httpqueueinfo.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

216

mmhttp

httpreqpushlim
Purpose
SynopsisMove a request to a queue with restriction.
function httpreqpushlim(reqid:integer,rq:reqqueue,lim:integer):boolean

Arguments
reqid Request number or -1
rq
A queue of requests
lim
Maximum number of waiting requests or -1 for no limit
Return value
true if the operation succeeded, false otherwise.
Further information
1. This function moves the selected request to a queue of requests in order to make it available to otherserver models. The operation is canceled if the current number of elements in the queue exceeds thegiven limit lim and false is returned. Otherwise, true is returned and the request can no longer beaccessed by the calling model.
2. If the provided request is -1 this routine only clears the availability ﬂag of the model (i.e. it is no longer
ready to process a request). In this case the return value indicates whether the ﬂag was reset or not:with a false result the ﬂag was already cleared before the function call.
Related topics
httpreqpush, httpreqpop, httpqueueinfo.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

217

mmhttp

httpreqstat
Purpose
Synopsis

Get the status associated with a request.
function httpreqstat(reqid:integer):integer

Argument
reqid Request number
Return value
Request status:<0
Invalid request number
0
Request not active1
No associated data2
Raw data available
3’initialisations from’ data available
Further information
1. If the return value is 2 or 3 a data ﬁle is available (see httpreqfile). If this function returns 3 then theﬁle can be read using an initialisations from block: data that was originally URL-encoded has been
decoded by the server and stored using Mosel’s initialisations format.
2. The status 3 will be produced when the request is of type GET or DELETE and has associated data.
This will also be the case with a query of type POST or DELETE if the content type is"application/x-www-form-urlencoded".
Related topics
httpreqfrom, httpreqfile, httpreqlabel, httpreqtype, httpreqheader,httpreqcookies.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

218

mmhttp

httpreqtype
Purpose
Synopsis

Get the type of a request.
function httpreqtype(reqid:integer):integer

Argument
reqid Request number
Return value
Request type:<0
Invalid request number
0
Request not active
HTTP_GET GET (1)HTTP_POST POST (2)HTTP_PUT PUT (4)HTTP_DELETE DELETE (8)HTTP_HEAD HEAD (128)
Related topics
httpreqfrom, httpreqfile, httpreqstat, httpreqlabel, httpreqheader,httpreqcookies.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information219

mmhttp

httpstartsrv
Purpose
SynopsisStart the HTTP server.
procedure httpstartsrv
procedure httpstartsrv(srvdir:string, moslab:string)Arguments
srvdirmoslabServer directory
Label identifying commands

Further information
1. The server takes its conﬁguration from the parameters http_defport, http_srvconfig,
http_listen, http_maxreq and http_defpage.
2. Only one server can be run by a model: if the server is already running, no operation is performed.
3. The server processes only authorised request types (see http_srvconfig): the model is notiﬁed ofevery valid request by an event of class EVENT_HTTPNEW. Malformed or unauthorised requests areautomatically rejected.
4. When the function is used with arguments, srvdir designates a directory: mmhttp will act as a ﬁleserver for the ﬁles stored in this directory (via GET queries). The argument moslab is a preﬁx that
identiﬁes requests that are to be handled by the model.
5. An IO error is raised if the server cannot start because of a network setting (typically the TCP port isalready used or requires higher privileges).
6. If the parameter http_startwb is set to true a web browser (as deﬁned by http_browser) is
launched just after the server has started.
Related topics
httpstopsrv.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

220mmhttp

httpstopsrv
Purpose
Synopsis

Stop the HTTP server.
procedure httpstopsrv

Further information
1. This procedure has no effect if no server is running.
2. During its shutting down procedure the server closes all waiting requests (with a response code 410)
such that it is no longer possible for the model to reply to these requests (however, events
corresponding to these requests may still be in the event queue).
Related topics
httpstartsrv.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

221mmhttp

jsonwrite
Purpose
Synopsis

Generate a JSON representation of a Mosel entity.
procedure jsonwrite(fname:string, mosobj:⁎)

Arguments
fname
mosobjName of a ﬁle to store the generated text
A Mosel object

Further information
This procedure generates a JSON representation of a Mosel entity. If the ﬁle name is an empty string,
the generated string is sent to the current output stream (by default this is the console).
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

222

mmhttp

mksetcookie
Purpose
Synopsis

Generate a set-cookie header line.
function mksetcookie(name:string, value:text, domain:text, path:text,
exp:integer):text

Arguments
name
value
domainpath
exp

Cookie name
Associated value
Domain of the cookie: if it does not start with a dot the domain is interpreted as a host nameand the cookie is a host only cookie
Path in the domain
Expiration time: with a negative value the cookie will be deleted; with 0 the cookie never
expires (session cookie) and a positive value is interpreted as an amount of time in seconds
after which the cookie will expire

Return value
A text string of the form "Set-Cookie: name=value\n"Further information
This function may be used to send cookies to a client by generating a set-cookie header that can bedirectly appended to the additional headers string of httpreply or httpreplycode. The returned
string is terminated by an end of line.
Related topics
httpreply, httpreplycode, httpreqcookies.
ModulemmhttpFair Isaac Corporation Conﬁdential and Proprietary Information

223

mmhttp

5.5

I/O drivers
The mmhttp module publishes the url driver with which a URL can be used as a ﬁle. Thanks to thisfacility it is possible to use ﬁles stored on an HTTP enabled ﬁle server just as if they were located on
the local ﬁle system. For example, the following command downloads and executes the Mosel ﬁle"hello.mos" stored on the web server mysrv:> mosel exec mmhttp.url:http://mysrv/hello.mos

5.5.1

Driver url
url:URL

The ﬁle name for this driver is a URL. Currently only HTTP URLs are supported (i.e. the name must
begin with "http://"). The behaviour of the driver depends on the ﬁle operation:
reading

A GET request is sent to the speciﬁed URL at the time of opening the ﬁle. The following
read operations are executed directly from the result stream generated by the server.

writing

The written data is ﬁrst saved into a temporary ﬁle and then sent to the speciﬁed URL
via a PUT request when the ﬁle is closed.

deleting

When deleting a ﬁle (e.g., using fdelete) through this driver a DELETE request is sent
to the speciﬁed URL.

Fair Isaac Corporation Conﬁdential and Proprietary Information

224

CHAPTER 6

mmjavaThe mmjava module for Mosel is intended for users who integrate their Mosel models into Javaapplications. This module can only be used from a Java enabled application.

6.1

I/O drivers
This module provides the java and jraw IO drivers. The ﬁrst one can be used to link a Mosel output(input) stream to a Java OutputStream (InputStream) or a Java ByteBuffer. The second driver isa modiﬁed version of the raw driver suitable for Java: instead of an address, this driver takes as input areference to an object.
For both drivers, ﬁle names are replaced by references to objects. These references are of two kinds:
direct references to public static objects (e.g. "java.lang.Sytem.out") and names deﬁned using
the XPRM.bind method. The second technique will be used with non static objects: the method
XPRM.bind establishes a link between a name and an object. This name can then be used as an
object reference for mmjava drivers.
When using Java object from Mosel, it is important to make sure objects and related ﬁelds can beaccessed: in particular the class and its ﬁelds must be public.

6.1.1

Driver java
java:[rewind,]static object|named object

With this driver a Java stream (OutputStream or InputStream) as well as a ByteBuffer can beused in place of a ﬁle in Mosel. This facility is specially useful for redirecting default Mosel streams toJava objects. Note that the Mosel Java interface uses this driver for redirecting default streams (in, out,
and error) to the corresponding Java streams (System.in, System.out and System.err).
When the ﬁle is open for reading and the referenced object is a ByteBuffer, the option rewind can beused in order to rewind the buffer before starting to read.
Example:mosel=new XPRM();
mosel.bind("out", myout);/⁎ Associate 'myout' object with string "out" ⁎//⁎ Redirect default output to 'myout' ⁎/mosel.setDefaultStream(XPRM.F_OUTPUT|XPRM.F_LINBUF, "java:out")/⁎ Redirect error stream to Java output stream ⁎/mosel.setDefaultStream(XPRM.F_ERROR, "java:java.lang.System.out"

If the driver is used in an initializations from block (resp. initializations to block) andthe provided object implements interface XPRMInitializationFrom (resp.
XPRMInitializationTo) then the corresponding Java methods are used to process the initialization(refer to the Mosel Library JavaDoc for further explanation).

Fair Isaac Corporation Conﬁdential and Proprietary Information

225

mmjavaThis driver supports the delete operation: deleting a java ﬁle name from the Mosel code (e.g.
fdelete("java:out")) corresponds to executing unbind on the corresponding identiﬁer. The
operator ﬁrst tries to unbind the identiﬁer associated to the running model (XPRMModel.unbind) andthen uses the global reference (XPRM.unbind) if the ﬁrst attempt fails.

6.1.2

Driver jraw
jraw:[noindex,all]The driver can only be used in ‘initializations’ blocks. In the opening part of the block, no ﬁle name has
to be provided, but general options can be stated at this point: they will be applied to all labels. Two
options are supported:
allforces output of all cells of an array even if it is dynamic (by default only existing cells
are considered).

noindexindicates that only data (no indices) are transfered between the Java objects and Mosel.
By default, the ﬁrst ﬁelds of each object are interpreted as index values for the array to
be transfered. This behavior is changed by this option.

In the block, each label entry is understood as an object reference to use for the actual processing.
Note that, before the object reference, one can add further options separated by comas, that are
effective to the particular entry.
If the Model object to be initialized (or saved) is a scalar or an array with option noindex, the driver
expects a Java object of a corresponding type (i.e. same basic type and scalar or one dimension array).
If the option noindex is not used and the Mosel object is an array, the label must specify which ﬁeldsof the class have to be taken into account for the mapping. This is indicated by a list of ﬁeld names
separated by commas and noted in brackets (e.g. "myobj(fi1,fi2,fi3)").
In the following example the jraw driver is used to initialize an array of reals, a, and an array of integers,ia, with data held in the Java application that executes the model.
Java part:
public class MyData {/⁎ A class to store an `array(string, int) of real' ⁎/public String s; public int r; public double v;
MyData(String i1, int i2, double v0) { s=i1; r=i2; v=v0; }}...
MyData[] data;
int[] intarr;...
mosel=new XPRM();
mosel.bind("data", data);/⁎ Associate `data' object with string "data" ⁎/mosel.bind("ia", intarr);/⁎ Associate `intarr' object with string "ia" ⁎/Mosel part:declarations
a:array(string, range) of real
ia:array(range) of integer
end-declarations...
initializations from "jraw:"
aa as "data(s,r,v)" ! Initialize `aa' with fields s,r,v of object `data'ia as "noindex,ia" ! Initialize `ia' with array `ia'; no index (only values)
end-initializations

Fair Isaac Corporation Conﬁdential and Proprietary Information

226

CHAPTER 7

mmjobsThanks to this module it is possible to load several models in memory and execute them concurrently.
In addition, other instances of Mosel might be started (either locally to the running system or remotely
on another machine through the network) and used to run additional models controlled by the modelthat has started them. This means that the computing capacity of the running model is not restricted tothe executing process. A general synchronization mechanism based on event queues as well as two
specialized IO drivers are also provided in order to ease the implementation of parallel algorithms in
Mosel.
To use this module, the following line must be included in the header of the Mosel model ﬁle:uses 'mmjobs'

7.1

ExampleThe following example shows how to compile, load, and then run a model from another model. After
having started the execution, it waits for 60 seconds before stopping the secondary model if the latterhas not yet ﬁnished.
model "mmjobs example"
uses "mmjobs","mmsystem"
declarations
mymod: Model
event: Event
end-declarations! Compile 'mymod.mos' to memory
if compile("","mymod.mos","shmem:bim")<>0
thenexit(1)
end-ifload(mymod,"shmem:bim")
fdelete("shmem:bim")! Load bim file from memory...
! ... and release the memory block! Disable model output
setdefstream(mymod,"","null:","null:")run(mymod)! Start execution andwait(60)! wait 1 min for an event
if waitexpired then
! No event has been sent...
writeln("Model too long: stopping it!")stop(mymod)! ... stop the model then wait
wait
end-if! An event is available: model finishedevent:=getnextevent

Fair Isaac Corporation Conﬁdential and Proprietary Information

227

mmjobs
writeln("Exit status: ", getvalue(event))
writeln("Exit code : ", getexitcode(mymod))unload(mymod)
end-model

7.2

Data sharing between models
A model may share data with its submodels under certain conditions: any initialisation performed by
the master model on these shared entities is available to the submodels at their startup and any
modiﬁcation carried out by both the master model and its submodels are effective for all models.
Entities to be shared must be global and identiﬁed by the declaration qualiﬁer shared (they do notneed to be public). Only scalars of basic types and native types supporting sharing, as well as sets, lists
and arrays of basic types can be shared. For the arrays, index sets must be either shared or constantsof basic types, shared hashmap arrays cannot have more than 1 dimension.
declarations
sci: shared integer
ss: shared set of stringsa: shared dynamic array(ss,1..2) of real
end-declarations

Data sharing is possible only between a model (the master model) and its clones (i.e. submodels
loaded from the running model see load). The master model can manipulate its shared entities justlike any other data structure as long as no compatible submodel is running. However, as soon as a
submodel using shared data is started the sharing mode is enabled and access to shared entities isaltered as follows: sets and lists behave as if they were constant, the structure of arrays is locked (i.e. it
is no longer possible to add or remove cells of sparse arrays). Normal access to shared entities is
restored when all submodels using them are reset (reset) or unloaded (unload). The current statusof the sharing mode can be obtained from the sharingstatus control parameter (getparam).
model "shared example"
uses 'mmjobs'
declarations
a: shared array(1..3) of integer
m: Modelend-declarations
if getparam("sharingstatus")<>2 then! in master model ('a' is empty)
forall(i in 1..3) a(i):=i ! initialise 'a'writeln("master:",a)! output: master:[1,2,3]load(m)! clone master then run itrun(m)
waitforend(m)! wait for its termination
writeln("aftersub:",a)! output: aftersub:[2,3,4]
else! in submodel ('a' is already initialised)
writeln("sub:",a)! output: sub:[1,2,3]
forall(i in 1..3) a(i)+=1 ! modify 'a'end-ifend-model

7.3

Control parameters
The following parameters are deﬁned by mmjobs:

Fair Isaac Corporation Conﬁdential and Proprietary Information

228

mmjobs

conntmpl

Default connection template.

p. 229defaultnodeDefault node number used by driver ’rmt:’.

p. 229fsrvdelay

Maximum wait time for ﬁndxsrvs.

p. 231

fsrvnbiter

Number of iterations performed by ﬁndxsrvs.

p. 231

fsrvport

UDP port used by ﬁndxsrvs.

p. 230jobid

ID of the current model.

p. 230keepalive

Keepalive timer setting.

p. 230nodenumber

ID of the current instance.

p. 229parentnumber

ID of the parent of the current instance.

p. 230sshcmd

SSH command for xssh driver.

p. 231

conntmpl
Description

The connection template is used by the connect function to generate a valid hostspeciﬁcation from an identiﬁer (typically corresponding to a host name). The generation is
performed by replacing in the template each occurrence of the %h marker by the originalidentiﬁer.

TypeString, read/write

Values

A string containing "%h" at least once

Default value"xsrv:%h"Affects routines

connect.

Modulemmjobsnodenumber
Description

The ID (or node number) of the current instance as returned by the function getid. The ID of
the initial (root) instance is 0

Type

Integer, read only

Modulemmjobsdefaultnode
Description

This parameter is used by the IO driver "rmt:" when it is not given any node reference (seeSection 7.5.6). By default its value is 0 (the initial node) but it may be changed by a parent
model using the instance parameter defaultnode (see Annex B).

Type

Integer, read only

ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information229

mmjobs

jobid
Description

The ID of the current model as returned by the function getid. The ID of the initial (root)
model is 0

Type

Integer, read only

Modulemmjobsparentnumber
Description

The ID (or node number) of the parent (i.e., creator) of the current instance. The ID of theinitial instance is 0 and its parent is -1.

Type

Integer, read only

Modulemmjobskeepalive
Description

When using a Mosel remote instance (see connect), the server sends to its client a keepalive
message at ﬁxed interval. A connection is considered broken if more thanmaxfail*interval seconds have elapsed since the last message received. Setting 0 for
maxfail disables this mechanism. This parameter can only be changed if no remote Mosel
instance is connected.

Type

String, read/write

Values

A string of the form "maxfail/interval"

Default value"2/60"

Modulemmjobsfsrvport
Description

This parameter deﬁnes the UDP port to be used by the findxsrvs routine for its broadcast
messages.

Type

Integer, read/write

Default value

2514

Affects routines

findxsrvs.

See also

fsrvnbiter, fsrvdelay.

ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

230

mmjobsfsrvdelay
Description

After it has sent its broadcast message, the findxsrvs routine waits for up to fsrvdelay
milliseconds for answers before aborting.

Type

Integer, read/write

Default value

1000

Affects routines

findxsrvs.

See also

fsrvnbiter, fsrvport.

Modulemmjobsfsrvnbiter
Description

This control parameter speciﬁes the number of times the procedure findxsrvs sends a
broadcast message.

Type

Integer, read/write

Default value

1

Affects routines

findxsrvs.

See also

fsrvdelay, fsrvport.

ModulemmjobssshcmdDescription

When connecting to a remote host via the "xssh:" I/O driver, an external program is used toestablish the SSH tunnel: this parameter speciﬁes which program to use. The arguments ofthe program are identiﬁed with the symbol "%h" for the target host, "%p" for the TCP port
and "%f" for the known host ﬁle (which is "-" when no ﬁle is provided). For instance thefollowing string will select ssh as the program to handle the secure tunnel: "ssh -q -p %p-s %h xprmsrv".
Note that this control parameter is read-only when Mosel is running under restriction NoExec(see Section 1.3.4).

TypeString, read/write

Affects routines

connect.

Values

A string including at least "%h"Default value"xprmsrv -sshclt %h -p %p -kh %f"

ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

231

mmjobs

7.4

Procedures and functions

7.4.1

Mosel instance management
The type Mosel is used to reference a Mosel instance. Before an instance can execute commands (likeloading or running a model), it must be connected. Connecting an instance consists in starting an
additional operating system process running Mosel: this is done by the connect function. To improvereadability of the model source, one can use host aliases (deﬁned by means of the sethostalias
routine) to designate connection targets. Once work with a particular instance has been ﬁnished, theinstance can be disconnected (disconnect): this terminates the process running Mosel (and releases
all associated resources).
clearaliases

Delete all deﬁned aliases.

p. 235connect

Connect a Mosel instance.

p. 233

disconnect

Disconnect a Mosel instance.

p. 234findxsrvs

Search xprmsrv servers on the local network.

p. 240getaliases

Retrieve the list of all deﬁned aliases.

p. 238getbanner

Get the banner displayed by an instance on startup.

p. 236gethostalias

Get the value of a host alias.

p. 237sethostalias

Deﬁne a host alias.

p. 239Fair Isaac Corporation Conﬁdential and Proprietary Information

232mmjobs

connect
Purpose
Synopsis

Connect a Mosel instance.
function connect(mi:Mosel, host:string|text):integer

Argumentsmihost

The instance to connect
A host speciﬁcation

Return value
0 if successful, a positive value otherwise
ExampleStart instance inst1 on a separate process:r:=connect(ins1,"")
With default settings, the 2 following statements are equivalent:
r:=connect(ins2,"ariane")
r:=connect(ins3,"xsrv:ariane")

Further information
1. Any Mosel instance has to be connected before it can be used for executing commands.
2. If the host provided is an empty string (""), it is replaced by "rcmd:" (instance started on the samemachine in a separate process). Otherwise, the string host is searched in the list of deﬁned aliases(see sethostalias) and, if found, it is replaced by the associated text. If the resulting speciﬁcation
does not contain any IO driver reference, a valid speciﬁcation is generated using the current connection
template (see conntmpl): each occurrence of the %h marker in the template is replaced by the value ofhost.
3. The host argument (or the string resulting from the transformations described above) is expected to
be an extended ﬁle name using an IO driver the task of which is to start a process running the mosel
program in remote mode and create/manage the communication streams between the processes. The
mmjobs module provides three drivers supporting this service (see Section 7.5): "rcmd:" to start a
Mosel instance on a separate process on the same machine, "xsrv:" to start a Mosel instance on ahost running the Mosel Remote Launcher (see Section 7.6) and "xssh:" to use a secure connection
with an xprmsrv server.
Related topics
sethostalias, findxsrvs, disconnect, Driver rcmd, Driver xsrv, Driver xssh
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

233

mmjobs

disconnect
Purpose
Synopsis

Disconnect a Mosel instance.
procedure disconnect(mi:Mosel)

Argumentmi

The instance to disconnect

Further information
This routine should be used to terminate a Mosel instance started by connect.
Related topics
connect.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information234

mmjobs

clearaliases
Purpose
Synopsis

Delete all deﬁned aliases.
procedure clearaliases

Further information
This routine deletes all host aliases previously deﬁned by sethostalias.
Related topics
sethostalias,getaliases,gethostalias,connect.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

235

mmjobsgetbanner
Purpose
Synopsis

Get the banner displayed by an instance on startup.
function getbanner(mi:Mosel):stringArgumentmi

A connected instance

Return value
The text displayed by Mosel when it started the instanceFurther information
When a new instance is started, the text displayed by Mosel is saved (this includes typically copyrightnotice and version information): this function returns this startup banner.
Related topics
connect.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information236

mmjobs

gethostalias
Purpose
Synopsis

Get the value of a host alias.
function gethostalias(alias:string):stringArgument
alias Internal identiﬁer
Return value
The host speciﬁcation corresponding to the alias or an empty string if the alias is not deﬁned
Related topics
sethostalias,clearaliases,getaliases, connect.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information237

mmjobsgetaliases
Purpose
Synopsis

Retrieve the list of all deﬁned aliases.
procedure getaliases(aliases:list of string)Argument
aliases A list to return the aliases
ExampleThe following procedure displays all aliases:
procedure showaliases
declarations
l:list of string
end-declarations
getaliases(l)forall(h in l)
writeln(h,"->",gethostalias(h))
end-procedure

Further information
This procedure resets its aliases argument.
Related topics
sethostalias,clearaliases,gethostalias, connect.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information238

mmjobs

sethostalias
Purpose
SynopsisDeﬁne a host alias.
procedure sethostalias(alias:string,host:string)Arguments
alias Internal identiﬁer
host Corresponding host speciﬁcation
ExampleThe ﬁrst statement deﬁnes "localhost" as a separate process on the same machine and "win" fora remote access to the machine "winpc":
sethostalias("localhost","rcmd:")
sethostalias("win","xsrv:winpc")

Further information
Host aliases are used by connect to start Mosel instances. If the argument host is the empty string,the corresponding alias is removed from the list (or nothing is done if the alias was not deﬁned before).
Related topics
gethostalias,clearaliases,getaliases, connect.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information239

mmjobsﬁndxsrvs
Purpose
Synopsis

Search xprmsrv servers on the local network.
procedure findxsrvs(group:integer,maxip:integer,addrs:set of string)Argumentsgroup Group number of the request
maxip Maximum number of addresses to collectaddrs Set to store the addresses foundFurther information
1. This procedure sends a broadcast message over the local network and waits for replies from running
xprmsrv servers (see Section 7.6). A given server will reply only to selected group numbers: the groupargument speciﬁes this property.
2. The IP addresses of the hosts having replied to the request are returned via the last argument of theprocedure in the form of strings. The maximum size of this set is ﬁxed by maxip. Note that theprovided set is not cleared: if it already contains maxip elements the routine returns immediately.
3. Control parameters fsrvnbiter, fsrvdelay and fsrvport can be used to tune the behaviour offindxsrvs. This routine repeats fsrvnbiter times the following procedure: it sends a broadcast
message to the fsrvport UDP port and then waits for up to fsrvdelay milliseconds for replies.
Related topics
connect, disconnect.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

240

mmjobs

7.4.2

Model management
The type Model is used to reference a Mosel model. This section describes the procedures andfunctions available for model management: compilation of source model ﬁles, loading of bim ﬁles,
execution and retrieval of model information. Note that before it can be used, a model has to be
initialized by loading a bim ﬁle (load).
compileCompile a source model.

p. 242

detachDetach the current model from its parent node.

p. 244getannidents

Get model identitiﬁers for which annotations are available.

p. 265getannotations

Get model annotations associated to a given symbol.

p. 266

getdsoprop, getdsopropnum

Get module information.

p. 253getexitcode

Get the exit code of a model.

p. 261

getgidGet the group ID of a model.

p. 254getid

Get the ID of a model or Mosel instance.

p. 255

getmodprop, getmodpropnum

Get model information.

p. 256

getnodeGet the ID (node number) of the Mosel instance of a model.

p. 257

getrmtid

Get the ID of a model on a remote instance.

p. 258

getstatus

Get the status of a model.

p. 259getuidGet the user ID of a model.

p. 260load

Load a Binary Model ﬁle.

p. 245reset

Reset a model.

p. 263

resetmodpar

Remove a parameter from a model parameter string.

p. 248run

Run a model.

p. 252

setcontrol

Set an instance control parameter on a remote instance.

p. 249setdefstream

Set default input/output streams of a model.

p. 247

setmodpar

Add or change the value of a parameter in a model parameter string. p. 250

setworkdir

Set the initial working directory of a model.

p. 251

stop

Stop a running model.

p. 262

unloadUnload a model.

p. 264

Fair Isaac Corporation Conﬁdential and Proprietary Information241

mmjobscompilePurpose
Synopsis

Compile a source model.
function compile(src:string|text):integerfunction compile(opt:string|text, src:string|text):integerfunction compile(opt:string|text, src:string|text, dst:
string|text):integerfunction compile(opt:string|text, src:string|text, dst: string|text,
com:string|text, pass:string|text, pke:string|text,
kls:string|text):integerfunction compile(mi:Mosel, opt:string|text, src:string|text, dst:
string|text):integerfunction compile(mi:Mosel, opt:string|text, src:string|text, dst:
string|text, com:string|text, pass:string|text, pke:string|text,
kls:string|text):integer

Arguments
opt

src
dst
com
mi
pass
pke
kls
Return value
0
1
2
3
4
ExampleCompilation options (may be separated by spaces or ’-’ symbols):"g"Include debugging information"G"
Include tracing information"s"
Strip symbols"p"parse only: stop after the syntax analysis of the source ﬁle, do not compile (no ﬁlegenerated)"bx=prefix" Package preﬁx list (can be quoted with single or double quotes)"ix=prefix" Include source preﬁx (can be quoted with single or double quotes)"S"
Sign the bim ﬁle"E"
Encrypt the bim ﬁle"F"
The argument pass is a ﬁle name (not the password itself)"V"
Accept to load signed packages only if their signature can be veriﬁed"T"Accept to load only signed packages with a valid signature
Source ﬁle name
Destination ﬁle nameComment to store in the bim ﬁle
The Mosel instance to perform the compilation
Password or password ﬁle (for encryption with a password)
Private key ﬁle (for bim ﬁle signing)
File of public keys (for encryption with public keys)
Function executed successfully
Parsing phase has failed (syntax error or ﬁle access error)
Error in compilation phase (a semantic error has been detected)
Error writing the output ﬁleLicense error (compiler not authorized)

Compile the local ﬁle "src.mos" stored on the current directory using the instance inst1 and store
the resulting BIM ﬁle on the current directory of this instance:
r:=compile(ins1,"","rmt:src.mos","dst.bim")

Fair Isaac Corporation Conﬁdential and Proprietary Information242

mmjobs

Further information
1. This function compiles a given model source ﬁle into a binary model ﬁle (bim ﬁle) that is required as
input to function load for executing the model.
2. If no destination ﬁle name is provided, the output ﬁle takes the same name as the source ﬁle with theextension .bim.
3. When sending a compilation request to a separate Mosel instance, it is important to keep in mind thatthe operation is performed in the environment of this instance (in particular its current working
directory) and ﬁle names should be speciﬁed appropriately (the rmt: IO driver can be particularly
helpful in this context).
4. The argument kls is a list of public key ﬁles (i.e. each line of the ﬁle is a key ﬁle name): whenencrypting a ﬁle, the encryption is performed for each of the listed public keys such that the bim ﬁle canbe decrypted by any of the corresponding private keys.
5. When preﬁxes provided via bx or ix are quoted with double quotes, backslashes are interpreted suchthat special characters can be included in the string. It is therefore required to double this symbol when
it has to be included (e.g. ’bx="C:\\mydir"’).
6. If the option bx is not stated, the current value of the control parameter bimprefix will be usedinstead during the compilation for loading packages (See section 2.3.1).
Related topics
load.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information243

mmjobs

detach
Purpose
Synopsis

Detach the current model from its parent node.
procedure detach

Further information
1. This procedure detaches the model calling it from its parent model such that it becomes a mastermodel running on a root node. As a consequence the connection to its parent model is closed, its
model number is set to 0 and the node number of its instance becomes 0 (root node). The parent node
is notiﬁed of the detachment by means of a termination event for the model which gets the status
RT_DETACHED.
2. The operation is possible only if the hosting intance is running exclusively this model (i.e. no submodel
is loaded at the time of calling detach) and no ﬁle is open between the hosting instance or the modeland its parent (in particular the default streams have to be set to "null:").
3. After a model is detached, it can no longer communicate with its parent using events or access ﬁlesthrough the "rmt:" driver. The HTTP protocol (available through the module mmhttp) might be used
as an alternative to the facilities provided by mmjobs in this case.
4. The instance running the detached model terminates automatically after the end of execution of themodel.
5. This routine can only be called by a submodel running on a remote instance. It has no effect if used bya master model.
Related topics
getstatus, run.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information244

mmjobsload
Purpose
Synopsis

Load a Binary Model ﬁle.
procedure load(mo:Model)
procedure load(mo:Model, bimf:string|text)
procedure load(mo:Model, mr:Model)
procedure load(mo:Model, bimf:string|text, opt:string|text,
pass:string|text, pke:string|text, kls:string|text)
procedure load(mi:Mosel, mo:Model, bimf:string|text)
procedure load(mi:Mosel, mo:Model, bimf:string|text, opt:string|text,
pass:string|text, pke:string|text, kls:string|text)

Arguments
mo
mr
bimf
mi
opt

pass
pke
kls

Model object to be initialized
Model object used a reference
Bim ﬁle name
The instance on which the model will be run
Loading options (may be separated by spaces or ’-’ symbols):"c"
Check signature (if the ﬁle is signed)"V"
If the ﬁle is signed, load it only if the signature is valid"T"
Load only signed ﬁles with a valid signature"F"
The argument pass is a ﬁle name (not the password itself)"l"
Do not load required packages
Password or password ﬁle (for encrypted bim ﬁles)Private key ﬁle (for encrypted bim ﬁles)File of public keys

Further information
1. This procedure initializes the model mo with the bim ﬁle bimf. If mo has already been initialized, themodel it references is unloaded before trying to load the new ﬁle (note that this operations fails if themodel is running). If the ﬁle bimf cannot be accessed or one of the required modules cannot be loaded,
the procedure generates an IO error (which may be intercepted if the control parameter ioctrl is true).
2. When loading a model from a separate Mosel instance, it is important to keep in mind that the operationis performed in the environment of this instance (in particular its current working directory) and ﬁlenames should be speciﬁed appropriately (the rmt: IO driver can be particularly helpful in this context).
3. The argument kls is a list of public key ﬁles (i.e. each line of the ﬁle is a key ﬁle name): when a signed
bim ﬁle is loaded, its signature is checked with the keys listed in this ﬁle. If this argument is not
speciﬁed, the signing key is searched in the default public keys directory located at
getparam("ssl_dir")+"/pubkeys".
4. Packages required for the loading of a model are located using the list of preﬁxes deﬁned by the control
parameter bimprefix (See section 2.3.1).
5. When invoked with a single argument this routine creates a new model from the one being executed(without using any bim ﬁle): this clone can access data shared by its master model (see Section 7.2).
Similarly, when a model is used in place of a bim ﬁle the new generated model is a copy of the provided
reference model. Note that all copies of a given model share the constant information (like constantstrings or the code segment) of the reference model. As a consequence, during a debugging session,
setting a breakpoint in a model loaded this way also installs the same breakpoint in all other models
coming from the same source (including the reference model).

Fair Isaac Corporation Conﬁdential and Proprietary Information245

mmjobs

Related topics
compile, setdefstream, run, unload.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

246

mmjobssetdefstream
Purpose
Synopsis

Set default input/output streams of a model.
procedure setdefstream(mo:Model, wmd:integer, fname:string)procedure setdefstream(mo:Model, input:string, output:string, error:string)procedure setdefstream(mi:Mosel, wmd:integer, fname:string)procedure setdefstream(mi:Mosel, input:string, output:string, error:string)Arguments
mo
mi
wmd

fname
input
outputerror

A ModelA Mosel instanceStream to set. Possible values:
F_INPUT
Default input stream
F_OUTPUT
Default output stream
F_ERROR
Default error stream
F_LINBUF
Use line buffering
Extended ﬁle name to be used for the stream.
Extended ﬁle name to be used for the input stream.
Extended ﬁle name to be used for the output stream.
Extended ﬁle name to be used for the error stream.

Further information
1. This function sets default IO streams to be used by a model. Model streams can be changed only whenthe model is not running. Each stream is associated to an extended ﬁle name (i.e. IO drivers can beused). For output streams, F_LINBUF may be speciﬁed (e.g.F_OUTPUT+F_LINBUF) in order to enableline buffering for the corresponding stream (the error stream is always open using line buffering).
2. For input and output streams, the ﬁlename is stored and streams are actually open when execution of
the model starts: in case of an invalid ﬁle name, the error is not reported by this function. The error
stream is immediately opened so in the case of an invalid ﬁle name it is detected by this function.
3. Using an empty string as the ﬁle name implies resetting to the original default stream.
4. When applied to a Mosel instance, this routine sets the default streams for this instance. These
streams can only be changed if the instance has not yet loaded any model.
5. When using this routine on a separate Mosel instance or on a model loaded on a separate Mosel
instance, it is important to keep in mind that the operation is performed in the environment of thisinstance (in particular its current working directory) and ﬁle names should be speciﬁed appropriately(the rmt: IO driver can be particularly helpful in this context).
Related topics
getfname.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information247

mmjobs

resetmodpar
Purpose
Synopsis

Remove a parameter from a model parameter string.
procedure resetmodpar(plist:text, pname:string|text)

Arguments
plist Text object storing the parameterspname Parameter name
Further information
1. This function helps in building the model parameter string to be passed to the run procedure by
removing a parameter deﬁnition (previously set with setmodpar) from a parameter string. The plist
text is left unchanged if the requested parameter cannot be found.
2. It is expected that the provided text string is either empty or composed of a list of assignments of theform "pname=val,pname2=val2...".
Related topics
setmodpar, run.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information248

mmjobs

setcontrol
Purpose
Synopsis

Set an instance control parameter on a remote instance.
procedure setcontrol(mi:Mosel, ctrl:string, val:string)procedure setcontrol(mo:Model, ctrl:string, val:string)Arguments
mi
mo
ctrl
val

A Mosel instanceA model reference (it must be loaded onto a remote instance)
Control nameControl value

Further information
1. This procedure is used to change an instance control parameter in the context of the Remote
Invocation Protocol (see Annex B).
2. An IO error is raised in case of error.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information249

mmjobs

setmodpar
Purpose
Synopsis

Add or change the value of a parameter in a model parameter string.
procedure setmodpar(plist:text, pname:string|text,
val:integer|real|boolean|string|text)

Arguments
plist Text object storing the parameterspname Parameter nameval
Value assigned to the parameter.
Further information
1. This function helps in building the model parameter string to be passed to the run procedure. As input
it takes a text object that it modiﬁes by either adding an assignment of the form pname=val or byreplacing an existing assignment. The routine adds the necessary quoting as necessary.
2. It is expected that the provided text string is either empty or composed of a list of assignments of theform "pname=val,pname2=val2...".
Related topics
resetmodpar, run.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information250

mmjobs

setworkdir
Purpose
Synopsis

Set the initial working directory of a model.
procedure setworkdir(mo:Model, cwd:string)Argumentsmocwd
ExampleA model reference
Initial working directory

The following statement sets the initial working directory of submodel sub to the current directory of
its master model:
setworkdir(sub,'.')

Further information
1. This procedure deﬁnes the initial working directory to be used when the execution of the model(re)starts. As a consequence it cannot be used to change the environment of a running model.
2. For a local execution the provided path is expanded just before the beginning of the execution relatively
to the current working directory of the caller. For a remote execution the path is relative to the directoryof the instance running the model.
Related topics
run.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information251

mmjobsrun
Purpose
Synopsis

Run a model.
procedure run(mo:Model)
procedure run(mo:Model, plist:string|text)

Arguments
moModel to be executed
plist String composed of model parameter initializations separated by commas
Further information
1. This procedure starts the execution of a model in a new thread: when the procedure returns, the model
is not necessarily started (this may be delayed depending on the operating system load) and notnecessarily terminated (the second model is executing concurrently to the caller).
2. By default the execution starts in the working directory of the Mosel instance (that might be different
from the working directory of the calling model). A different initial path can be setup using
setworkdir.
3. When the execution of the model is completed (normal termination, interruption after calling stop, or
runtime error) or could not be started, an event of class EVENT_END is sent to the caller. The execution
status is returned via the event value but it may also be obtained using getstatus. The exit code
related to the last execution may be retrieved using getexitcode.
4. An event EVENT_END is also received after a model has detached itself although its execution may
continue (see detach). In this case the model status is RT_DETACHED and its associated instance isdisconnected.
5. The speciﬁed model must have been previously initialized with load and must not be running. If thesame model has to be executed several times concurrently, it must be loaded several times in different
model objects.
6. The parameter string plist may be built and modiﬁed using setmodpar and resetmodpar. Theseroutines handle transparently the protection of parameter values by adding the appropriate quotes
when required.
Related topics
load, wait, waitforend, setmodpar, stop, getstatus, getexitcode, reset.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information252

mmjobsgetdsoprop, getdsopropnum
Purpose
Synopsis

Get module information.
function getdsoprop(dso:string, prop:integer):string
function getdsopropnum(dso:string, prop:integer):realArguments
dso
prop

The name of a module currently loaded into memory
The property to retrieve. Possible values:
PROP_NAME
Module name
PROP_VERSION Module version
PROP_PATH
Path to the module ﬁleReturn value
The property as a string (real for getdsopropnum) or an empty string (-1 for getdsopropnum) incase of error (invalid property or the module was not found)
Related topics
getmodprop
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

253

mmjobs

getgidPurpose
Synopsis

Get the group ID of a model.
function getgid(mo:Model):integer

Argumentmo

A modelReturn value
Group ID of the model
Further information
A model can be associated with a group ID using setgid. This group ID may be used to identify theorigin of an event (see getfromgid) or as a ﬁlter for a wait (see waitfor).
Related topics
getuid, getid, setgid
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information254

mmjobs

getid
Purpose
Synopsis

Get the ID of a model or Mosel instance.
function getid(mo:Model):integerfunction getid(mi:Mosel):integer

Argumentsmomi

A modelA Mosel instance

Return value
ID of the model or instance as an integer
Further information
1. Each model object has a unique ID number that can be obtained with this function. This ID may be used
to identify the origin of an event (see getfromid) or as a ﬁlter for a wait (see waitfor).
2. The ID number of a Mosel instance is its node number. The initial instance has node number 0.
Related topics
getuid, getgid, jobid
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

255

mmjobsgetmodprop, getmodpropnum
Purpose
Synopsis

Get model information.
function getmodprop(mo:Model, prop:integer):string
function getmodprop(prop: integer):string
function getmodpropnum(mo:Model, prop:integer):realfunction getmodpropnum(prop: integer):realArgumentsmo
prop

A modelThe property to retrieve. Possible values:
PROP_NAME
Model name (cf. model statement)
PROP_ID
Order number
PROP_VERSION Model version
PROP_SYSCOM
System comment
PROP_USRCOM
User comment
PROP_SIZE
Amount of memory (in bytes) used by the model
PROP_DATE
Compilation date
PROP_UNAME
Unique model nameReturn value
The property as a string (real for getmodpropnum) or an empty string (-1 for getmodpropnum) incase of error
Further information
The second form of the function reports information for the calling model.
Related topics
getdsoprop, memoryuse
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

256

mmjobs

getnodePurpose
Synopsis

Get the ID (node number) of the Mosel instance of a model.
function getnode(mo:Model):integerfunction getnode(mi:Mosel):integer

Argumentsmomi

A modelA Mosel instance

Return value
ID of the instance on which the model is loaded as an integer or -1 if the model has not been loaded
Further information
1. This function returns the node number of the current instance if the provided model is local.
2. When applied to a Mosel instance this function returns the same information as getid.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information257

mmjobsgetrmtid
Purpose
Synopsis

Get the ID of a model on a remote instance.
function getrmtid(mo:Model):integer

Argumentmo

A modelReturn value
ID of the model on the remote instance as an integer or -1 if the model has not been loaded or is local to
the running instance.
Further information
This ID corresponds to the model number assigned to the model by Mosel when it is loaded (i.e. thevalue of the control parameter modelnumber). This function can only be used on models handled byremote instances.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information258

mmjobs

getstatus
Purpose
Synopsis

Get the status of a model.
function getstatus(mo:Model):integerfunction getstatus(mi:Mosel):integer

Argumentmo

A modelReturn value
The status of a Mosel instance is 0 if it is connected, any other value indicates that it is not ready. The
model status can be:
RT_NOTINIT Model has not been initialized or has been unloaded
RT_RUNNING Model is running
RT_OK Model is ready for execution and/or no error occurred during last execution
RT_MATHERR A mathematical error occurred
RT_ERROR A runtime error occurred
RT_IOERR An IO error occurred
RT_NULL A NULL reference error occurred
RT_LICERR Execution could not start because no license was available
RT_FDCLOSED Execution on a separate instance has been interrupted
RT_DETACHED Execution on a separate instance continues although the instance has been
disconnected (see detach)
RT_STOP Execution has been interrupted by a call to stop
Related topics
connect, stop, getexitcode.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information259

mmjobs

getuidPurpose
Synopsis

Get the user ID of a model.
function getuid(mo:Model):integer

Argumentmo

A modelReturn value
User ID of the model
Further information
A model can be associated with a user ID using setuid. This user ID may be used to identify the originof an event (see getfromuid) or as a ﬁlter for a wait (see waitfor).
Related topics
getgid, getid, setuid
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

260

mmjobsgetexitcode
Purpose
Synopsis

Get the exit code of a model.
function getexitcode(mo:Model):integer

Argumentmo

A modelReturn value
Exit code of the last execution or 0
Further information
The exit code of the last execution corresponds to the value stated via a call to the procedure exit.
The default exit value (i.e. procedure exit has not been called) is 0.
Related topics
getstatus.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

261

mmjobsstop
Purpose
Synopsis

Stop a running model.
procedure stop(mo:Model)

ArgumentmoModel to interrupt

Further information
If the model is not currently running, no operation is performed. Note that the effect of this call may not
be immediate and the corresponding model may continue running a few seconds before its effective
interruption (for instance the time required to complete an IO operation).
Related topics
run.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information262

mmjobs

reset
Purpose
Synopsis

Reset a model.
procedure reset(mo:Model)

ArgumentmoModel to reset

Further information
This procedure resets a model after its execution: all resources it has allocated are released. The
model returns to its state just after it has been loaded into memory. Note that this function is
automatically called before a model is unloaded or run.
Related topics
run, unload.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information263

mmjobs

unloadPurpose
Synopsis

Unload a model.
procedure unload(mo:Model)

ArgumentmoModel to unload

Further information
This procedure unloads the given model. All resources used by this model, including modules, arereleased. The function fails if the model is running.
Related topics
load.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

264

mmjobsgetannidents
Purpose
Synopsis

Get model identitiﬁers for which annotations are available.
procedure getannidents(mo:Model, si:set of string)procedure getannidents(si:set of string)Argumentsmosi

A model reference
Set receiving the identiﬁers

Further information
1. When used with a single argument this procedure returns information for the calling model.
2. This routine cannot be used with remote models.
Related topics
getannotations.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

265

mmjobsgetannotations
Purpose
Synopsis

Get model annotations associated to a given symbol.
procedure getannotations(mo:Model, id:string, prefix:string, si:set of
string, ann:array(string) of string)procedure getannotations(mo:Model, id:string, prefix:string, lsa:list of
string)procedure getannotations(id:string, prefix:string, si:set of string,
ann:array(string) of string)procedure getannotations(id:string, prefix:string, lsa:list of string)Argumentsmo
id
prefixsiannlsa
ExampleA model reference
Symbol for which annotations are requested (an empty string will report global declarations)Preﬁx ﬁlter: only annotations with a name starting by the speciﬁed preﬁx will be returned
Set receiving the annotation names
Array receiving the annotation values (indiced by names)
List receiving the annotation names and values

The following code snippet implements a function to retrieve a speciﬁc annotation for the speciﬁed
model entity (if several matching annotations are found the value of the ﬁrst is returned):public function getannotation(symb:string, aname:string):string
declarations
l:list of string
end-declarations
getannotations(symb,aname,l)if l.size>=2 and getfirst(l)=aname thencuthead(l,1)
returned:=getfirst(l)end-ifend-function
writeln("Value of first annotation 'my.annot' for entity 'x': ",getannotation("x","my.annot"))
writeln("Value of first global annotation 'my.annot': ",getannotation("","my.annot"))

Further information
1. With the version taking a list, each annotation is represented by 2 entries: the ﬁrst one is the annotation
name and the second one its value. Note that the version returning information via an array will only
report partial information in the case of annotations deﬁned several times.
2. When used without a model reference these procedures return information for the calling model.
3. These routines cannot be used with remote models.
Related topics
getannidents.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information266

mmjobs

7.4.3

Synchronization
Synchronization between running models can be implemented using events. Events are characterized
by a class and a value and may be exchanged between a model and its parent model. The model fromwhich an event has been sent is identiﬁed by its unique ID, its user ID and its group ID. An event queue isattached to each model to collect all events sent to this model and is managed with a FIFO policy (FirstIn – First Out). Depending on the needs, a model may check whether its queue is empty or simply
suspend its execution until it has been sent an event.
The type Event represents an event in the Mosel language. Objects of type Event may be compared with= or <> and assigned with :=. The function nullevent returns an event without class and value: thisis the initial value of a newly created event and no model can send an event of this kind (i.e. the class isnecessarily not null).
canceltimer

Cancel an active timer.

p. 268dropnextevent

Drop the next event in the event queue of the model.

p. 279getclass

Get the class of an event.

p. 285getfromgid

Get the group ID of the sender of an event.

p. 283getfromid

Get the ID of the sender of an event.

p. 282

getfromuid

Get the user ID of the sender of an event.

p. 284getnextevent

Get the next event in the event queue of the model.

p. 278gettimer

Get the amount of time remaining before a timer expires.

p. 286

getvalueGet the value associated with an event.

p. 287

isqueueempty

Check whether there are events waiting in the event queue.

p. 280nullevent

Return a ‘null’ event.

p. 281

peeknextevent

Peek the next event in the event queue of the model.

p. 288send

Send an event to a running model.

p. 269setgidSet the group ID of a model.

p. 272

settimer

Create or update a timer.

p. 270setuidSet the user ID of a model.

p. 271

wait

Wait for an event.

p. 273

waitexpired

Indicate whether the previous ’wait’ or ’waitfor’ expired.

p. 274

waitfor

Wait for speciﬁc events.

p. 275

waitforend

Wait for the end of execution of a model.

p. 277

Fair Isaac Corporation Conﬁdential and Proprietary Information267

mmjobscanceltimer
Purpose
SynopsisCancel an active timer.
procedure canceltimer(tid:integer)

Argumenttid

A timer identiﬁer

Further information
1. This procedure has no effect if it cannot ﬁnd the requested timer. However it will delete from the event
queue the event EVENT_TIMER coresponding to a timer that is no longer active.
2. If the provided timer identiﬁer tid is negative or null all timers are cancelled.
Related topics
settimer, gettimer.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information268

mmjobs

send
Purpose
Synopsis

Send an event to a running model.
procedure send(mo:Model, class:integer, value:real)procedure send(class:integer, value:real)

Arguments
moModel to send the event toclass Event class (must be >1)
value Event value
Further information
1. Events can be sent to models started by the caller (the child models) by using the ﬁrst form of theprocedure and to the model having started the caller (the parent model) with the second form of theprocedure. An event can be received only by a running model using the mmjobs module: sending an
event to a model that is not running or not using mmjobs is a no-operation.
2. Events are characterized by a class and a value. Event class values can be used to indicate thecause of the event (for instance, 2 could mean ‘a new solution has been found’) and the associatedvalue may specify a property of the given instance (for example an objective value). Except for the
special value 1 (EVENT_END) class values have no predeﬁned meaning.
3. An event of class EVENT_END (=1) and model status as the event value is automatically sent by eachmodel to its parent model when it terminates its execution.
Related topics
wait, waitfor.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information269

mmjobs

settimer
Purpose
SynopsisCreate or update a timer.
function settimer(tid:integer, dur:integer, rep:boolean):integerfunction settimer(dur:integer, rep:boolean):integer

Arguments
tid
dur
rep

A timer identiﬁer
A duration in milliseconds
Decides whether the timer will be armed one time only or automatically repeated

Return value
Timer identiﬁer as a positive integer
Further information
1. This function creates or updates an interval timer: after a timer has been armed by a call to this routine
an event of class EVENT_TIMER is scheduled for being sent to the model after the speciﬁed amount oftime has elapsed. The value of such an event is the timer identiﬁer tid. Note that the system will not
emit a new event if an identical event is already in the queue.
2. If the option rep is set to false the timer is released after its termination, otherwise it is immediately
re-armed with the same interval after each expiration until it is explicitly cancelled (see canceltimer).
3. If the provided identiﬁer tid is not positive a new timer is created with a newly generated identiﬁer, thiscorresponds to the behaviour of the second form of this function.
4. When the provided identiﬁer corresponds to an existing timer, this one is ﬁrst cancelled with a call tocanceltimer before being re-created with the new properties.
Related topics
canceltimer, gettimer.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

270mmjobs

setuidPurpose
Synopsis

Set the user ID of a model.
procedure setuid(mo:Model,uid:integer)

Argumentsmouid

A modelNew user ID

Further information
This function deﬁnes the user ID associated to a model (by default it is 0). This user ID may be used to
identify the origin of an event (see getfromuid).
Related topics
setgid, getuid
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information271

mmjobs

setgidPurpose
Synopsis

Set the group ID of a model.
procedure setgid(mo:Model,gid:integer)

Argumentsmogid

A modelNew group ID

Further information
This function deﬁnes the group ID associated to a model (by default it is 0). This group ID may be used
to identify the origin of an event (see getfromgid).
Related topics
setuid, getgid
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information272

mmjobs

wait
Purpose
Synopsis

Wait for an event.
procedure wait
procedure wait(dur:integer)

Argumentdur

A duration in seconds or the constant WAIT_INFINITE

Further information
This procedure suspends the execution of the caller until an event is available. The second form
speciﬁes a time limit: the processing is suspended for at most dur seconds, the special value
WAIT_INFINITE is interpreted as an inﬁnite duration. The behaviour of the procedure is undeﬁned if
the speciﬁed duration is smaller than 1 second.
Related topics
send, waitfor, waitforend, waitexpired, isqueueempty, getnextevent, dropnextevent.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information273

mmjobs

waitexpired
Purpose
Synopsis

Indicate whether the previous ’wait’ or ’waitfor’ expired.
function waitexpired:boolean

Return value
true if the last call to wait or waitfor terminated after expiration of a time limit
Related topics
wait, waitfor.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information274

mmjobs

waitforPurpose
Synopsis

Wait for speciﬁc events.
procedure waitfor(mask:integer)
procedure waitfor(mask:integer,dur:integer)
procedure waitfor(mask:integer,dur:integer,opt:integer)
procedure waitfor(mask:integer,id:integer,dur:integer,opt:integer)

Arguments
mask
id
dur
opt

ExampleBit mask of expected events
ID of model for which events are expected
A duration in seconds, the constant WAIT_INFINITE or a timer identiﬁer as a negative integer
Options:
WAIT_EXACT Mask must be exactly matched
WAIT_KEEP Keep unexpected events
WAIT_UID
Wait for a particular user ID
WAIT_GID
Wait for a particular group ID

The following statement waits for an event of class 3 coming from a model of group 100 without
dropping any event:waitfor(3,100,WAIT_INFINITE,WAIT_KEEP+WAIT_EXACT+WAIT_GID)

Further information
1. This procedure suspends the execution of the caller until an event of a particular class is available. The
second form speciﬁes a time limit: the processing is suspended for at most dur seconds, the special
value WAIT_INFINITE is interpreted as an inﬁnite duration.
2. If the time limit is 0 the execution is not suspended but the queue of events is processed once and asubsequent call to waitexpired will return true if no valid event was found.
3. The parameter dur may also take a negative value: in this case it is interpreted as the opposite of atimer identiﬁer (see settimer) and the function will wait until this timer expires if no valid event
arrives. When the routine interrupts its monitoring due to the expiration of a timer the ﬁrst event in thequeue is the event EVENT_TIMER associated to this timer. Note that if no timer corresponds to thegiven value the routine will terminate only when an expected event is available as if WAIT_INFINITE
had been used.
4. By default, the parameter mask is interpreted as a bit mask to select the expected events: all events
sent to the model are automatically dropped until an event ev satisﬁes the following condition:
bittest(getclass(ev),mask)<>0

5. If the parameter opt includes option WAIT_EXACT, the parameter mask becomes the target eventclass: the wait will end when an event of a class equal to mask is found.
6. If the parameter opt includes option WAIT_KEEP, unexpected events are not dropped but the ﬁrst
event satisfying the condition is moved to the top of the queue such that it is returned by the next call togetnextevent.
7. With the last form of the function an ID is speciﬁed: it characterises events coming from a particularmodel or a group of models. By default the argument id is interpreted as the unique model ID (seegetid), if option WAIT_UID is used, the ID is interpreted as a user ID (see getuid) and with option
WAIT_GID the argument is a group ID (see getgid).

Fair Isaac Corporation Conﬁdential and Proprietary Information275

mmjobs

Related topics
send, wait, waitexpired, isqueueempty, getnextevent, dropnextevent.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information276

mmjobs

waitforend
Purpose
Synopsis

Wait for the end of execution of a model.
procedure waitforend(mo:Model)
procedure waitforend(mo:Model,dur:integer)

Argumentsmodur

A modelA duration in seconds, the constant WAIT_INFINITE or a timer identiﬁer as a negative integer

Further information
1. This procedure suspends the execution of the caller until a given model has terminated its execution.
The second form speciﬁes a time limit: the processing is suspended for at most dur seconds, thespecial value WAIT_INFINITE is interpreted as an inﬁnite duration.
2. Before the procedure returns all events received from the model to monitor are removed from the event
queue (including the EVENT_END event) unless the time limit has been reached. In this case some ofthe events of the submodel may have been removed from the event queue.
3. If the time limit is 0 the execution is not suspended but the queue of events is processed once and asubsequent call to waitexpired will return true if the model was still running when the procedure
was called (the event queue is not modiﬁed in this case).
4. The parameter dur may also take a negative value: in this case it is interpreted as the opposite of atimer identiﬁer (see settimer) and the function will wait until this timer expires if no valid event
arrives. When the routine interrupts its monitoring due to the expiration of a timer the ﬁrst event in thequeue is the event EVENT_TIMER associated to this timer. Note that if no timer corresponds to thegiven value the routine will terminate only when an expected event is available as if WAIT_INFINITE
had been used.
Related topics
wait, waitexpired.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information277

mmjobsgetnextevent
Purpose
Synopsis

Get the next event in the event queue of the model.
function getnextevent:Event

Return value
The next event or nullevent if the queue is empty
Further information
The returned event is removed from the queue after it has been retrieved with this function.
Related topics
peeknextevent, dropnextevent, isqueueempty.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information278

mmjobs

dropnextevent
Purpose
Synopsis

Drop the next event in the event queue of the model.
procedure dropnextevent

Further information
This procedure has no effect if the event queue is empty.
Related topics
peeknextevent, getnextevent, isqueueempty.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information279

mmjobs

isqueueempty
Purpose
SynopsisCheck whether there are events waiting in the event queue.
function isqueueempty:boolean

Return value
false if at least one event is available in the queue, true otherwise.
Related topics
dropnextevent, peeknextevent, getnextevent.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information

280

mmjobsnulleventPurpose
Synopsis

Return a ‘null’ event.
function nullevent:Event

Return value
An event of class and value equal to 0
Further information
Variables of type Event are initialized with this function.
Related topics
getnextevent.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information281

mmjobs

getfromid
Purpose
Synopsis

Get the ID of the sender of an event.
function getfromid(ev:Event):integer

Argumentev

An event

Return value
The ID of the sender of the event. 0 is returned for a nullevent
Further information
1. Each model has a unique ID that is attached to each event it sends. With this function one can identify
the sender of a given event.
2. The ID of an event sent from the parent model is always 0.
Related topics
getid, getfromgid, getfromuid, getvalue, getclass.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information282

mmjobs

getfromgid
Purpose
Synopsis

Get the group ID of the sender of an event.
function getfromgid(ev:Event):integer

Argumentev

An event

Return value
The group ID of the sender of the event. 0 is returned for a nullevent
Further information
1. Each model can be associated with a group ID that is attached to each event it sends. With thisfunction one can identify the sender of a given event.
2. The group ID of an event sent from the parent model is always 0.
Related topics
getgid, setgid, getvalue, getfromid, getfromuid, getclass.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information283

mmjobs

getfromuid
Purpose
Synopsis

Get the user ID of the sender of an event.
function getfromuid(ev:Event):integer

Argumentev

An event

Return value
The user ID of the sender of the event. 0 is returned for a nullevent
Further information
1. Each model can be associated with a user ID that is attached to each event it sends. With this function
one can identify the sender of a given event.
2. The user ID of an event sent from the parent model is always 0.
Related topics
getuid, setuid, getvalue, getfromid, getfromgid, getclass.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information284

mmjobs

getclass
Purpose
Synopsis

Get the class of an event.
function getclass(ev:Event):integer

Argumentev

An event

Return value
The class of the event (>0) or 0 for a nullevent
Further information
A model sends automatically an event of class EVENT_END(=1) when it terminates its processing.
Other values are application speciﬁc.
Related topics
getvalue, getfromid, getfromgid, getfromuid.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information285

mmjobsgettimer
Purpose
Synopsis

Get the amount of time remaining before a timer expires.
function gettimer(tid:integer):integer

Argumenttid

A timer identiﬁer

Return value
Remaining time in milliseconds before the timer expires or 0 if the corresponding event is alreadyavailable in the queue or -1 if no timer corresponds to the provided identiﬁer
Further information
This function will return 0 if an event corresponding to the speciﬁed timer is waiting in the queue of
event even if this timer has been automatically re-armed.
Related topics
canceltimer, settimer.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information286

mmjobsgetvalue
Purpose
Synopsis

Get the value associated with an event.
function getvalue(ev:Event):realArgumentev

An event

Return value
The value of the event
Further information
In the case of an event of class EVENT_END(=1), this value corresponds to the model status.
Related topics
getclass, getfromid, getfromgid, getfromuid.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information287

mmjobspeeknextevent
Purpose
Synopsis

Peek the next event in the event queue of the model.
function peeknextevent:Event

Return value
A copy of the next event or nullevent if the queue is empty
Further information
The returned event is a copy of the ﬁrst available event of the queue. The event queue is not changedby this function.
Related topics
getnextevent, dropnextevent, isqueueempty.
ModulemmjobsFair Isaac Corporation Conﬁdential and Proprietary Information288

mmjobs

7.5

I/O drivers
The mmjobs module provides a modiﬁed version of the mem IO driver designed to be used in a
multithreaded environment: memory blocks allocated by the shmem IO driver are persistent (i.e. they
are not released after the model terminates) and can be used by several models. Thanks to this facility,
models running concurrently may exchange data through memory by means of initialization blocks for
instance.
The driver mempipe offers another communication mechanism between models: a memory pipe may
be open by two models simultaneously. One of them for writing and the other one for reading. Thisdriver also supports initialization blocks through which data is transfered in binary form.
The drivers rcmd, xsrv and xssh allow to start additional Mosel instances: they have to be used tobuild host speciﬁcations as expected by the connect function. Finally, thanks to the rmt driver a
Mosel instance can access ﬁles available from the environment of another instance.

7.5.1

Driver shmem
shmem:label[/minsize[/incstep]]

The ﬁle name for this driver is a label: this is the identiﬁer (the ﬁrst character must be a letter) of thememory block. A label is not local to a particular model and remains valid after the end of the executionof the model having created it. All memory blocks are released when the module mmjobs is unloaded
but a given memory block may also be deleted explicitly by calling the fdelete procedure of module
mmsystem or by using the fremove C-function of the Native Interface. Note also that deleting thespecial ﬁle "shmem:⁎" has the effect of releasing all memory blocks handled by the driver.
Several models may open a given label at the same time and several read operations may be performed
concurrently. However, writing to a memory block can be done by only one model at a time: if several
models try to read and write from/to the same label, only one (it becomes the owner of the memory
block) performs its IO operations for writing and the others are suspended until the owner closes its ﬁledescriptor to the speciﬁed label. Then, one of the waiting models is restarted and becomes the newowner: this process continues until all ﬁle descriptors to the label are closed.
The memory block is allocated dynamically and resized as necessary. By default the size of thememory block is increased by pages of 4 kilobytes: the optional parameter incstep may be used tochange this page size (i.e. the default setting is "label/0/4k"). The special value 0 modiﬁes the
allocation policy: instead of being increased of a ﬁxed amount, the block size is doubled. In all cases
unused memory is released when the ﬁle is closed.

7.5.2

Driver mempipe
mempipe:nameA memory pipe is characterized by its name. Only one model may open a pipe for reading but several
models may open the same pipe for writing. However, if several models try to write to the same pipe,
only one (it becomes the owner of the memory pipe) performs its IO operations and the others are
suspended until the owner closes its ﬁle descriptor to the speciﬁed pipe. Then, one of the waiting
models is restarted and becomes the new owner: this process continues until all ﬁle descriptors to thepipe are closed.
Pipe operations are possible only if the two ends of the pipe are open: one model for reading and at
least one model for writing. There is no notion of ’end of ﬁle’ in a pipe: if a model tries to read from anempty pipe (i.e. no model is writing to the other end) no error is raised and the model is suspended until
something is available. Similarly trying to write to a pipe for which no model is reading from the otherend is a blocking operation. In order to avoid lock ups, it is usually good practice to synchronize theFair Isaac Corporation Conﬁdential and Proprietary Information289

mmjobsmodels using events. For instance a model waits for a speciﬁc event before trying to read from a pipe;
before starting to write to the same pipe, the other model sends the expected event.
Memory pipes may be used with initialization blocks. This driver does not use labels for each record of
the initialization block: it is assumed (but not checked) that both ends of the pipe are using the same
sequence of records. For instance, if the writer sends an integer, a string and then an array of reals, thereader must expect an integer, a string and an array of reals: it is not allowed to skip records or changeorder as it is usually possible with these blocks.

7.5.3

Driver rcmd
rcmd:[command]

This driver starts the speciﬁed command in a new process and connects its standard input and output
streams to the calling Mosel instance. The created process is executed in the same current working
directory as the controlling model and inherits the environment variables deﬁned using setenv. The
default command is "mosel -r". A typical use for this driver is to start an instance on the current
machine or on a remote computer through an external program. For instance:
rcmd:rsh sunbox mosel -r

When Mosel is running in restricted mode (see Section 1.3.4), the restriction NoExec disables thisdriver.

7.5.4

Driver xsrv
xsrv:hostname[(port)][/ctx[/pass]][|var=val...]This driver connects to the host hostname running the Mosel Remote Launcher (see Section 7.6)
through a TCP socket on port port (default value: 2513) asking for the context ctx (default: xpress)
using the password pass (default: no password). Additional environment variables can be speciﬁed:
assignments of the form var=val must be separated by the symbol | and variable values may include
variable references noted ${varname} (expansion is performed on the remote host in the context of
its environment). The special environment variable MOSEL_CWD deﬁnes the current working directory
for the newly created instance.
xsrv:winbox(3211)/xpr64|MOSEL_CWD=C:\workdir|MYDATA=${MOSEL_CWD}\data

7.5.5

Driver xssh
xssh:hostname[(port,kwf)][/ctx[/pass]][|var=val...]This driver is the secure version of the xsrv driver decribed above: it establishes the connection to thexprmsrv server through an encrypted SSH tunnel (using 2515 as the default TCP port number). In
addition to the port number, the driver can also take a ﬁle name (kwf) used as the known host ﬁle forserver authentication: this ﬁle contains the list of known hosts with their corresponding public keys.
When the connection is established to the remote host, the public key stored in this ﬁle is comparedwith the key provided by the server. The connection is canceled if keys do not match. Generating thisknown hosts ﬁle requires running the command xprmsrv -key public on the remote server inorder to retrieve its public key (see Section 7.6.1).
For instance, the following command will include the server mysun in the knownhosts.txt ﬁle (thecommand must be run on the server):xprmsrv -key public -hn mysun >>knownhosts.txt

Fair Isaac Corporation Conﬁdential and Proprietary Information

290

mmjobs

Then after having moved the ﬁle to the machine(s) from where connections are initiated, the following
connection string may be used to open secure connections with server authentication:
xssh:mysun(knownhosts.txt)

The remote connection is handled by a separate process. By default the program xprmsrv is used as
the helper program but it can be replaced by another SSH client by changing the control parametersshcmd.

7.5.6

Driver rmt
rmt:[node,bs]filename

This driver can be used with any routine expecting a physical ﬁle for accessing ﬁles on remote
instances. By default, the ﬁle is located on the instance running on the node identiﬁed by the parameter
defaultnode but a particular instance may be speciﬁed by preﬁxing the ﬁle name by its node number
enclosed in square brackets. The special node number -1 designates the parent node of the current
instance.
load(mi,mo,"rmt:[-1]model.bim")

By default the driver creates a buffer of 8k for its communication operations. The size of this buffer
might be changed by specifying the desired buffer size after the node number (for instance"rmt:[0,4]filename" to use a 4k buffer). If only the buffer size has to stated the node number canbe omitted (e.g. "rmt:[,4]filename"). Note that a buffer size must be between 2k and 64k.
In addition to physical ﬁles, this driver also emulates the behaviour of drivers cb, sysfd, tmp, shmem
and java such that it can transfer streams from one instance to another. For instance,"rmt:sysfd:2" is the standard error stream of the process running the default node.

7.6

The Mosel Remote Launcher xprmsrv
The xprmsrv program is the server part of the "xsrv:" and "xssh:" IO drivers: it must be runningon each computer on which instances will be started using these drivers. The communication between
two Mosel instances is achieved through a single TCP stream. Mosel instances are started in thecontext of execution environments: such an environment consists in a set of environment variables aswell as the name of the program to start with its initial working directory. The server can manage
different execution environments which are identiﬁed by a name and optionally protected by apassword. Thanks to this feature a single server can offer several versions of Xpress or dedicatedsettings for particular distributed applications.
This program is also used as an SSH client by mmjob and XPRD when connecting to an xprmsrv server
through a secure tunnel. Therefore it must be available when using the "xssh:" IO driver even if noserver is to be run on the host machine.

7.6.1

Running the xprmsrv command
7.6.1.1

Main command line options

The ﬁrst argument of the command that is not identiﬁed as an option is used as the name for a
conﬁguration ﬁle. The following options are accepted:-hDisplay a short help message and terminate.

Fair Isaac Corporation Conﬁdential and Proprietary Information291

mmjobs-V

Display the version number and terminate.

-tc

Display the current conﬁguration and terminate.

-fForce automatic setting of environment variable XPRESSDIR even if it is already deﬁned.

-v [#]

Set the verbosity level of the communication protocol. The default value is 1 (report only
errors) when the server is running in background (service/daemon) and 2 (report
activity) when the server is run from a console.

-l fname

Set a logﬁle to record all messages.

-li addr

Set the address of the interface to use (default: 0.0.0.0 for all interfaces).

-p portSet the TCP port to listen to (default port is 2513, -1 to disable).

-bp port

Set the UDP port for broadcast (default port is 2514, -1 to disable).

-pf pfname Deﬁne a ﬁle name for recording the process number of the server. This ﬁle is removed
when the server exits.
-dStart the server in background (or as a daemon on Posix systems).

The following options are used by the Windows version of the server:-service install Install the server as a service. All other provided options (including
conﬁguration ﬁle) are recorded and will be used by the server. If the corresponding
service has already been installed, its execution settings are updated with the provided
options.
-service remove Remove the previously installed service.
-service start

Start the previously installed service.

-service reload Reload conﬁguration.
-service stop

Stop the previously started service.

-service status Check whether the service is already running.
-u userThis option is used only when installing the service: it selects the user running theservice.

-pwd pwd

This option speciﬁes the password required for the user indicated by the -u option.

The following options are used by all other platforms:-u user

User that should be running the server.

-g groupGroup that should be running the server.

When the server is run as a service (under Windows) or as a daemon (on Posix systems) that areusually started by a privileged user, it is recommended to use the appropriate option to run the process
as an unprivileged user for security reasons. For instance, under Windows, installing the service can bedone using the following command in order to use the network service account:xprmsrv -service install -u "NT AUTHORITY\NetworkService" conffile

Similarly on a Posix system, the server can be run as the nobody user:
xprmsrv -d -u nobody conffile

Fair Isaac Corporation Conﬁdential and Proprietary Information292

mmjobs

7.6.1.2

Secure server

xprmsrv can also accept secure connections through SSH tunnels: this is the protocol used by thexssh IO driver. The following options are used to setup the secure server:-sp port

Set the TCP port for SSH connections (default port is 2515, -1 to disable).

-k fname

Private key ﬁle name.

-sc cilst

Set the list of accepted ciphers in order of preference (default: "aes256-ctr
aes192-ctr aes128-ctr aes256-cbc aes192-cbc aes128-cbc
blowfish-cbc 3des-cbc").

The secure server requires a private key to authenticate itself (see following section). By default it will
use the ﬁle "xprmsrv_rsa.pem" located in the same directory as the xprmsrv executable. It is
important to store this ﬁle in a secure location as it identiﬁes the server, in particular it must not bereadable by Mosel models started by the server. If this ﬁle is missing or the provided ﬁle name cannot
be accessed the secure server will be disabled.
7.6.1.3

Private key management

A new private key can be generated with the following command:
xprmsrv -key new

Additionally, option -k filename can be speciﬁed to change the default key ﬁle location. Note that
this procedure does not remove an existing key ﬁle.
The following command loads and check the validity of a key ﬁle:xprmsrv -key check

When executed on a valid key ﬁle this command displays the ﬁngerprint of the public part of the key aswell as its properties.
The SSH protocol makes possible authentication of a server by a client. This optional feature,
supported by the IO driver xssh, requires a known host ﬁle on the client side: this text ﬁle consists in alist of host server names with their associated public key. The command xprmsrv -key publicgenerates the required data for such a ﬁle using the hostname reported by the operating system toidentify the server. Often this hostname does not correspond to the public name of the machine. In
such a case, it is possible to replace the label in the ﬁle or use the option -hn name to select a
different name. For instance, the following command will append to the ﬁle knownhosts.txt the
public data key for the server using keyﬁle mykey.pem with host name srvname:xprmsrv -key public -k mykey.pem -hn srvname >>knownhosts.txt

7.6.1.4

Mode of operation

The server proceeds as follows:
1. If the environment variable XPRESSDIR is not deﬁned or if the -f option is in use, the value of thisenvironment variable is deduced from the location of the program itself. Under Posix operating
systems, the environment variable XPRESS is also set up.

Fair Isaac Corporation Conﬁdential and Proprietary Information293

mmjobs

2. The environment variables MOSEL_DSO and MOSEL_BIM (see Section 2.3.1), MOSEL_EXECPATH(see system), MOSEL_RWPATH, MOSEL_ROPATH (see Section 1.3.4) and XPRMSRV_ACCESS (seeSection 7.6.2.1) are cleared and the environment variable MOSEL_RESTR is initialised with value"NoReadNoWriteNoExecNoDBWDOnly" (see Section 1.3.4).
3. The default execution environment xpress is created: it refers to the Xpress installation detected
at the ﬁrst step.
4. If available, the conﬁguration ﬁle is read (see Section 7.6.2): it can be used to deﬁne global
settings (e.g., deﬁning the logﬁle) or/and create and modify execution environments by deﬁning
environment variables.
5. The process then starts its main loop listening to the speciﬁed TCP and UDP ports.
6. When a connection is requested, a new session is started to process commands from the client.
These commands are used to authenticate the client, select an environment and ﬁnally start theMosel program in a separate process. This process inherits all the environment variables deﬁned
in the context and starts in the speciﬁed working directory (by default: the location pointed by
XPRESSDIR). In addition, on Posix systems, the path ${XPRESSDIR}/lib is added to the
dynamic library path of the operating system. Once the process is started, xprmsrv detaches
itself from the client — the communication is established directly between the two Mosel
instances.

7.6.2

Conﬁguration ﬁle
The conﬁguration ﬁle consists in a list of variable deﬁnitions of one of the following forms:
varname=value
varname?=value

Each statement is recorded in the current environment. The value may contain variable references
noted ${varname}, the expansion is executed when the environment is processed except for self
references that are expanded at the time of deﬁning the variable (e.g.PATH=${PATH}:otherpath).
When the ﬁrst syntax is used, the variable cannot be changed by a remote host; the second syntax(using ?=) allows a remote host to modify the corresponding variable before starting the Mosel
instance.
Switching to a different environment is done by giving the name of the environment enclosed in square
brackets:[newenv]

If the environment name has not yet been used, a new environment is created unless the line ends withthe symbol ’+’ (e.g. [myenv]+). In this case the following deﬁnitions are included only if theenvironment already exists. If the line ends with the symbol ’=’ (e.g. [myenv]=) the previous
deﬁnitions for this context are cleared. These markers can be combined (e.g. [myenv]+=) such thatthe deﬁnition block replaces the corresponding context only if it exists.
Upon startup, two environments are automatically created: "global" to store general conﬁgurationand settings shared by all environments and "xpress" (it can also be referred to as ⁎ or default) the
default execution environment. When the reading of the conﬁguration ﬁle begins, the global
environment is selected: in this environment all variable deﬁnitions are processed immediatly andadded to the xprmsrv process environment. In this context, some variables have a special meaning
and are not handled as ordinary environment variables:
LOGFILEthe ﬁle to be used for recording all messages. Messages are sent to the standard error
stream when this parameter is not set.

Fair Isaac Corporation Conﬁdential and Proprietary Information294

mmjobs

LISTENaddress of the interface to use (default value: 0.0.0.0 for all interfaces).

TCP_PORT

the port number to use for TCP connections (default value: 2513, -1 to disable).

UDP_PORT

the port number to use for UDP connections (default value: 2514, -1 to disable). The
server listen to this port for broadcast messages (see procedure findxsrvs).

SSH_PORT

the port number to use for SSH connections (default value: 2515, -1 to disable).

KEYFILE

private key ﬁle name used by the SSH protocol (default value: xprmsrv_rsa.pem locatedin the same directory as the xprmsrv executable).

SSH_CIPHERS

the list of accepted ciphers in order of preference (default: "aes256-ctr
aes192-ctr aes128-ctr aes256-cbc aes192-cbc aes128-cbc
blowfish-cbc 3des-cbc").

VERBOSITY

verbosity level for the communication protocol (default value: 1 if the server is running inbackground and 2 if it is run from a console).

GROUPMASK

Bit mask to select what broadcast requests to accept (default value: ANY). The server
replies to a request of group grp only if bit test grp&GROUPMASK is not 0 (seeprocedure findxsrvs). The mask value can be given as an integer (e.g. 3 to allow
groups 1 and 2), an hexadecimal number (e.g. 0xFF for groups 1 to 128) or the special
keyword ANY (all groups allowed).

MAXAUTHTIMEa connection is closed if the authentication procedure takes more than the speciﬁed
amount of time in seconds (default value:30).

MAXSESSIONS

maximum number of concurrent sessions (the default value 0 disables this limitation).

XPRMSRV_ACCESSCONFDIR

access control list (see Section 7.6.2.1).

a conﬁguration directory path. The server includes each of the ﬁles stored in thisdirectory (sorted in alphabetical order) after it has ﬁnished reading the main
conﬁguration ﬁle.

If the corresponding command line options are used (namely options -l, -p, -bp, -sp, -k, -sc and -v)
the settings of the conﬁguration ﬁle are ignored.
In other contexts, the following variables have a special meaning:
MOSEL_CMD

the command to execute. The default value is "${XPRESSDIR}/bin/mosel -r"

MOSEL_CWD

default working directory. The default value is "${XPRESSDIR}"RUN_BEFORE command to be run before MOSEL_CMD. This command is executed in the sameenvironment as MOSEL_CMD after all variables have been deﬁned.
RUN_AFTER

command to be run after MOSEL_CMD. This command is executed in the environment of
the server but the variable itself is expanded in the context of MOSEL_CMD before its
execution.

PASS

password required to use this environment (empty by default). If this variable is set tothe special value "⁎", the associated environment is disabled.

MAXSESSIONS

maximum number of concurrent sessions running under this context (by default there
is no limit; a maximum of 0 or less disables the environment).

XPRMSRV_ACCESSXPRMSRV_SID

context speciﬁc access control list (applied after the global access list).

session ID: if not explicitly deﬁned this variable is automatically set by the server.

Fair Isaac Corporation Conﬁdential and Proprietary Information295

mmjobs

XPRMSRV_PEER IP address of the remote host: if not explicitly deﬁned this variable is automaticallyset by the server.
For instance, the following conﬁguration ﬁle sets the logﬁle to "/tmp/logfile.txt"; adds the
password "hardone" to the default context and deﬁnes an additional context named xptest pointing
to a different installation of xpress:# simple xprmsrv config file
LOGFILE=/tmp/logfile.txt[xpress]
PASS=hardone[xptest]XPRESSDIR=/opt/xpressmp/testing
XPRESS=/opt/xpressmp/lic
MOSEL_RESTR=NoWriteNoDBNoExecWDOnly
MOSEL_CWD?=${XPRESSDIR}/workdir

Assuming the server using this conﬁguration is running on the machine mypc, the following statements
will create two instances on this machine, one for each of the deﬁned execution environments:
r1:=connect(m1, "xsrv:mypc/xpress/hardone")r2:=connect(m2, "xsrv:mypc/xptest")

Since MOSEL_CWD has been initialised with the ?= symbol, the remote host can change its working
directory. For instance:
r2:=connect(m2, "xsrv:mypc/xptest|MOSEL_CWD=/tmp")

While the server is running it is possible to request a reload of its conﬁguration: this procedure consists
in reading again the conﬁguration ﬁle(s) in order to update the deﬁnition of the contexts. During thisoperation only context speciﬁc deﬁnitions are processed (all global deﬁnitions are silently ignored).
Under Windows conﬁguration change can only be requested on a running service using the reload
command:xprmsrv -service reload

On a Unix system conﬁguration change is performed after reception of a signal USR1. For instance if
PID is the process ID of a running xprmsrv server:
kill -USR1 PID

The conﬁguration update can only be executed when the server is not monitoring any Mosel instance. If
a request cannot be processed immediately it is delayed until the server is idle. Moreover if an error is
detected while reading the conﬁguration an error is reported but the server continues running with its
current settings.
7.6.2.1

Access control list

The environment variable XPRMSRV_ACCESS may be deﬁned in each context of the conﬁguration ﬁle.
This variable deﬁnes which hosts are allowed to connect to the server or use a particular context. The
restriction applies to the server itself when the variable is deﬁned in the global context and as asupplementary restriction when it is included in any other context (i.e. a host cannot be allowed in acontext if it is rejected by the global context).

Fair Isaac Corporation Conﬁdential and Proprietary Information296

mmjobs

The value of the variable must consist in a list of hosts and subnetworks separated by spaces. Each
entry of this list can optionally be preceded by the + sign (for accepting the host; this is the default if nopolicy is speciﬁed) or - sign (to reject connection). Order of the list members is important: whenchecking authorisation for a given host the list is processed from left to right. The ﬁrst matching entry
will decide whether access is allowed or denied. A given host will be rejected if no matching entry canbe found.
A host is identiﬁed by its name (e.g. myhost) or its IP address (e.g. 192.168.1.1). A subnetwork is
deﬁned by a routing preﬁx that can be expressed as a partial address (e.g. 192.168.1); or using the
CIDR notation - the ﬁrst address of the network followed by the bit-length of the preﬁx, separated by aslash "/" character (e.g. 192.168.1.0/24). The subnet mask may also be used instead of the
bit-length which is a quad-dotted decimal representation like an address (e.g.
192.168.1.0/255.255.255.0). The special identiﬁer ALL is replaced by the subnetwork deﬁnition
0.0.0.0/0 (any host) and the identiﬁer SELF is replaced by the hostname of the server.
In the ﬁrst example below, host uranus is rejected and subnetwork 192.168.1.0/24 is allowed toconnect. Note that uranus will be rejected even if it is part of the autorised subnetwork because its
reference appears ﬁrst in the list. In the second example, all hosts are allowed except 2 subnetworks(192.168.1.0/24 and 192.168.2.0/24):
XPRMSRV_ACCESS=-uranus 192.168.1
XPRMSRV_ACCESS=-192.168.1.0/255.255.255.0 -192.168.2.0/24 +ALL

All deﬁned control lists are preprocessed just after the conﬁguration ﬁle has been read in order toresolve host names and check for syntax errors. Unresolved host names are ignored (although awarning is displayed in such a case) but a syntax error on a control list will cause the server to abort its
processing.

Fair Isaac Corporation Conﬁdential and Proprietary Information

297

CHAPTER 8

mmnl
The mmnl module extends the Mosel language with a new type for representing nonlinear expressions
and constraints and also with some additional subroutines. To use this module the following line must
be included in the header of the Mosel model ﬁle:uses 'mmnl'

The ﬁrst section presents the new functionality for the Mosel language provided by mmnl, namely the
new type nlctr and a set of subroutines that may be applied to objects of this type.
The following sections give detailed documentation of the subroutines (other than mathematicaloperators) deﬁned by this module.

8.1

New functionality for the Mosel language

8.1.1

The problem type mpproblem.nl
This module exposes its functionality through an extension to the mpproblem problem type. As aconsequence, all routines presented here are executed in the context of the current problem.

8.1.2

The type nlctr and its operators
The module mmnl deﬁnes the type nlctr to represent nonlinear constraints in the Mosel Language.
As shown in the following example (Section 8.1.4), mmnl also deﬁnes the standard arithmetic
operations that are required for working with objects of this type. By and large, these are the same
operations as for linear expressions (type linctr of the Mosel language) with additionally thepossibility to multiply or divide by decision variables and to use the exponential notation xˆr (assumingthat x is of type mpvar). Nonlinear constraints may also be deﬁned by using overloaded versions ofMosel’s arithmetic and trigonometric functions on expressions involving decision variables (seeSection 8.2 for a complete list).

8.1.3

Setting initial values
An important feature in Nonlinear Programming is the possibility to set initial values for decisionvariables. With mmnl this is done by the procedure setinitval. Nonlinear solvers use initial values
as starting point for the search. The choice of the initial values may not only have an impact on the timespent by the solver but also, depending on the problem type, on the best (locally optimal) solution
found by the solver.
The deﬁnitions of initial values can be removed with clearinitvals. It is also possible to employ thesolution values obtained from the immediately preceding optimization run as initial values to the next
by calling the procedure copysoltoinit.

Fair Isaac Corporation Conﬁdential and Proprietary Information

298

mmnl

8.1.4

Example: using mmnl for QCQP
The following example shows how to solve a QCQP (Quadratically Constrained Quadratic
Programming) problem with the Xpress-MP QCQP solver. To use this solver we need to load themodule mmxprs in addition to mmnl since the module mmnl does not include any solver.
The problem we wish to solve is a classical NLP test problem (source:
http://www.orfe.princeton.edu/ rvdb/ampl/nlmodels/ that determines the shape of a hanging chain byminimizing its potential energy. The objective function is linear and the problem has convex quadratic
constraints.
model "catenary"
uses "mmxprs", "mmnl"
parameters
N = 100
L = 1
H = 2⁎L/N
end-parameters
declarations
RN = 0..N
x: array(RN) of mpvar
y: array(RN) of mpvar
end-declarations! Number of chainlinks! Difference in x-coordinates of endlinks! Length of each link

! x-coordinates of endpoints of chainlinks! y-coordinates of endpoints of chainlinks

forall(i in RN) x(i) is_free
forall(i in RN) y(i) is_free! Objective: minimise the potential energy
potential_energy:= sum(j in 1..N) (y(j-1)+y(j))/2! Bounds: positions of endpoints! Left anchor
x(0) = 0; y(0) = 0! Right anchor
x(N) = L; y(N) = 0! Constraints: positions of chainlinks
forall(j in 1..N)
Link_up(j):= (x(j)-x(j-1))^2+(y(j)-y(j-1))^2 <= H^2! Setting start values
forall(j in RN) setinitval(x(j), j⁎L/N)
forall(j in RN) setinitval(y(j), 0)
setparam("XPRS_verbose", true)
minimise(potential_energy)
writeln("Solution: ", getobjval)
forall(j in RN)
writeln(strfmt(getsol(x(j)),10,5), " ", strfmt(getsol(y(j)),10,5))
end-model

A QCQP matrix can be exported to a text ﬁle (in MPS or LP format) by adding the following lines to yourmodel after the problem deﬁnition:
setparam("XPRS_loadnames", true)loadprob(potential_energy)
writeprob("catenary.mat", "")! Enable loading of names! Load the problem! Write an MPS matrix ("l" for LP format)

Not all problems with quadratic constraints conform with the properties required by QCQP solvers.
Xpress-Optimizer therefore performs a convexity check before starting the optimization. This test
takes some time and if you know that your problem is convex you may disable it by setting theFair Isaac Corporation Conﬁdential and Proprietary Information

299

mmnl

following parameter before starting the optimization.
setparam("XPRS_ifcheckconvexity", false)

8.2! Disable convexity check

Procedures and functions
The module mmnl overloads certain mathematical functions of the Mosel language, replacing anargument of type real by the types linctr and nlctr. The return value of these functions is of typenlctr. This means they can be used as operators in the deﬁnition of nonlinear constraints as shown in
the example of Section 8.1.4. The relevant functions are:

Arithmetic functions:
abs
ceil
exp
floor
ln
log
round
sqrt
sign



absolute value
rounding to the next largest integer
natural exponent of the argument
rounding to the next smallest integer
natural logarithm of the argument
base 10 logarithm of the argument
rounding to the nearset integer
positive square root of the argument
sign of an expression (-1 if negative, 1 if positive, 0 othewise)

Trigonometric functions:arccosarcsinarctancos
sintan

arccosine of the argument
arcsine of the argument
arctangent of the argument
cosine of the argument
sine of the argument
tangent of the argument

Since these mathematical operators are fairly self-explanatory, we shall forego any more detailed
documentation of these functions.
The following list gives an overview of all other functions and procedures deﬁned by mmnl for which we
give detailed descriptions later.
clearinitvals

Delete all initial value deﬁnitions.

p. 301copysoltoinit

Copy solution values to initial values.

p. 302

getsolGet the solution value of a nonlinear constraint.

p. 304gettypeGet the type of a nonlinear constraint.

p. 307ishidden

Test whether a constraint is hidden.

p. 305sethidden

Hide or unhide a nonlinear constraint.

p. 306setinitval

Set an initial value (start value) for a variable.

p. 303setname

Associate a matrix name to a nonlinear constraint.

p. 308settypeSet the type of a nonlinear constraint.

p. 309Fair Isaac Corporation Conﬁdential and Proprietary Information

300

mmnl

clearinitvals
Purpose
Synopsis
ExampleDelete all initial value deﬁnitions.
procedure clearinitvals
The following copies the solution values from an optimization run to the initial values of the variables
involved. Later all initial value deﬁnitions are deleted and a new initial value is set for variable x.
uses "mmnl"
declarations
x,y: mpvar
end-declarations...
minimize(sin(x+y))
copysoltoinit...
clearinitvals
setinitval(x, -1)

Further information
This procedure deletes all previously deﬁned initial values for decision variables.
Related topics
copysoltoinit, setinitval.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

301

mmnl

copysoltoinit
Purpose
Synopsis
ExampleCopy solution values to initial values.
procedure copysoltoinit
The following copies the solution values of all variables in an optimization run to their initial values andthen sets a different initial value for variable x(1).
uses "mmnl"
declarations
x: array(1..10) of mpvar
y,z: mpvar
end-declarations...
maximize(x(1)⁎x(3) + ln(y+z))
copysoltoinit
setinitval(x(1), 0)

Further information
This procedure copies the solution values of decision variables in the immediately preceding
optimization run to their initial values for the next run. Doing so it overrides any previously set initialvalues for the involved variables. However, the settings for decision variables that did not occur in thepreviously solved problem remain unchanged.
Related topics
copysoltoinit, clearinitvals, setinitval.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

302

mmnl

setinitval
Purpose
Synopsis

Set an initial value (start value) for a variable.
procedure setinitval(x:mpvar, val:real)

Argumentsxval
ExampleA decision variable
A real number to be used as initial value

The following sets an initial value of 0 for variable x. For y its solution from the preceding optimizationis set as its new initial value.
uses "mmnl"
declarations
x,y: mpvar
end-declarations
setinitval(x, 0)
setinitval(y, getsol(y))

Further information
This procedure sets an initial value for a decision variable. Initial values are used by nonlinear solvers
as a (good) starting point for the search. It is in general not required that the initial values be part of afeasible solution to the optimization problem. All previously set initial values can be removed by calling
clearinitvals. The procedure copysoltoinit can be used to turn the solution of a previous
optimization run into initial values for the next run.
Related topics
clearinitvals, copysoltoinit.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

303

mmnl

getsolPurpose
Synopsis

Get the solution value of a nonlinear constraint.
function getsol(c:nlctr):realArgumentc

A nonlinear constraint

Return value
Solution value or 0.
ExampleThe following prints the solution values of a nonlinear constraint and a nonlinear expression.
uses "mmnl"
declarations
x,y,z: mpvar
Ctr: nlctr
end-declarations...
! (Define and solve the problem)
writeln("Evalution of Ctr: ", getsol(Ctr))
writeln("Evaluation of an expression: ", getsol(abs(x⁎y)+5⁎z^3))

Further information
This function returns the evaluation of a nonlinear constraint using the current solution values of its
variables. Note that the solution value of a variable is 0 if the problem has not been solved or thevariable is not contained in the problem that has been solved.
Related topics
maximize/minimize, copysoltoinit.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

304

mmnl

ishiddenPurpose
Synopsis

Test whether a constraint is hidden.
function ishidden(c:nlctr):boolean

Argumentc

A nonlinear constraint

Return value
true if the constraint is hidden, false otherwise.
ExampleThe following tests whether a nonlinear constraint is hidden.
uses "mmnl"
declarations
c: nlctr
end-declarations
if ishidden(c) thenwriteln("Constraint 'c' is currently hidden.")end-ifFurther information
This function tests the current status of a constraint. At its creation a constraint is added to the current
problem, but using the function sethidden it may be hidden. This means, the constraint will not be
contained in the problem that is solved by the nonlinear solver but it is not deleted from the deﬁnition of
the problem in Mosel.
Related topics
sethidden.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

305

mmnl

sethidden
Purpose
Synopsis

Hide or unhide a nonlinear constraint.
procedure sethidden(c:nlctr, b:boolean)

Argumentscb

ExampleA nonlinear constraint
Constraint status:
true
Hide the constraint
false
Unhide the constraint

The following deﬁnes a constraint and then sets it as hidden:
uses "mmnl"
declarations
x,y,z: mpvar
end-declarations
c:= 4⁎cos(x) + y - z^2 <= 12sethidden(c, true)

Further information
At its creation a constraint is added to the current problem, but using this procedure it may be hidden.
This means that the constraint will not be contained in the problem that is solved by the nonlinear
solver but it is not deleted from the deﬁnition of the problem in Mosel. Function ishidden can be used
to test the current status of a constraint.
Related topics
ishidden.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

306

mmnl

gettype
Purpose
Synopsis

Get the type of a nonlinear constraint.
function gettype(c:nlctr):integer

Argumentc

A nonlinear constraint

Return value
Constraint type. Applicable values for nonlinear constraints are:
CT_EQ
Equality, ‘=’
CT_GEQ Greater than or equal to, ‘ ≥ ’
CT_LEQ Less than or equal to, ‘ ≤ ’
CT_UNB Non-binding constraint, i.e. free
Related topics
settype.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

307

mmnl

setname
Purpose
Synopsis

Associate a matrix name to a nonlinear constraint.
procedure setname(c:nlctr, n:string)Argumentscn

A nonlinear constraint
Name given to the constraint

Further information
1. When exporting a problem to a matrix ﬁle, constraint names are deduced from the global public
symbols: anonymous and local constraints are usually named after their row number in the matrix. This
procedure makes it possible to give a name to these constraints.
2. If the given name starts with the ’#’ character, the generated matrix name will include the row numberof the constraint in the matrix.

Fair Isaac Corporation Conﬁdential and Proprietary Information

308

mmnl

settype
Purpose
Synopsis

Set the type of a nonlinear constraint.
procedure settype(c:nlctr, type:integer)

Argumentsctype

A nonlinear constraint
Constraint type. Applicable values are:
CT_EQ
CT_GEQ
CT_LEQ
CT_UNB

Equality, ‘=’Greater than or equal to, ‘ ≥ ’Less than or equal to, ‘ ≤ ’
Non-binding constraint

Further information
This procedure can be used to change the type of a nonlinear constraint, turning it into an equality or
inequality or making it unbounded, i.e. free.
Related topics
gettype.
Modulemmnl

Fair Isaac Corporation Conﬁdential and Proprietary Information

309

CHAPTER 9

mmoci
The Mosel OCI (Oracle Call Interface) interface provides a set of procedures and functions that may be
used to access Oracle databases. To use the OCI interface, the following line must be included in theheader of a Mosel model ﬁle:uses 'mmoci'This manual describes the Mosel OCI interface and shows how to use some standard PL/SQL
commands, but it is not meant to serve as a manual for PL/SQL. The reader is referred to the
documentation of Oracle for more detailed information on these topics.

9.1

Prerequisite
The Oracle interface deﬁned by the module mmoci accesses Oracle databases via the Oracle Call
Interface (OCI). Oracle’s Instant Client package must be installed on the machine that runs the Mosel
model.

9.2

ExampleAssume that the Oracle database contains a table “pricelist” of the following form:
articlenum

color

price

1001

blue

10.49

1002

red

10.49

1003

black

5.99

1004

blue

3.99

...
The following small example shows how to logon to a database from an Mosel model ﬁle, read in data,
and logoff from the database.
model 'OCIexample'
uses 'mmoci'declarations
prices: array (range) of real
end-declarations
setparam("OCIverbose", true)

Fair Isaac Corporation Conﬁdential and Proprietary Information! Enable OCI message printing in case of error

310mmoci
OCIlogon("scott","tiger","")! connect to Oracle as the user 'scott/tiger'

writeln("Connection number: ", getparam("OCIconnection"))OCIexecute("select articlenum,price from pricelist", prices)! Get the entries of field `price' (indexed by! field `articlenum') in table `pricelist'
OCIlogoff
end-model! Disconnect from the database

Here the OCIverbose control parameter is set to true to enable OCI message printing in case oferror. Following the connection, the procedure OCIexecute is called to retrieve entries from the ﬁeld
price (indexed by ﬁeld articlenum) in the table pricelist. Finally, the connection is closed.
For further examples of working with databases and spreadsheets, the reader is referred to the Xpress
whitepaper Using ODBC and other database interfaces with Mosel.

9.3

Data transfer between Mosel and Oracle
Data transfer beetween Mosel and Oracle is achieved by calls to the procedure OCIexecute. The valueof the control parameter OCIndxcol and the type and structure of the second argument of theprocedure decide how the data are transferred between the two systems.

9.3.1

From Oracle to Mosel
Information is moved from Oracle to Mosel when performing a SELECT command for instance.
Assuming mt has been declared as follows:
mt: array(1..10,1..3) of integer

the execution of the call:
OCIexecute("SELECT c1,c2,c3 from T", mt)behaves differently depending on the value of OCIndxcol. If this control parameter is true, thecolumns c1 and c2 are used as indices and c3 is the value to be assigned. For each row (i,j,k) of theresult set, the following assignment is performed by mmoci:mt(i,j):=k

With a table T containing:c1 c2 c3 c4
1 2 5 74 3 6 8

We obtain the initialization:m2(1,2)=5, m(4,3)=6

If the control parameter OCIndxcol is false, all columns are treated as data. In this case, for eachrow (i,j,k) the following assignments are performed:
mt(r,1):=i; mt(r,2):=j; mt(r,3):=k

where r is the row number in the result set.
Here, the resulting initialization is:

Fair Isaac Corporation Conﬁdential and Proprietary Information

311

mmocimt(1,1)=1, mt(1,2)=2, mt(1,3)=5mt(2,1)=4, mt(2,2)=3, mt(2,3)=6

If the SQL statement selects 4 columns (instead of 3) as in:
OCIexecute("SELECT c1,c2,c3,c4 from T", mt)

and the control parameter OCIndxcol is false, the ﬁrst column is used as the ﬁrst array index while
the remaining columns are treated as data. As a consequence, for each row (i,j,k,l) the following
assignments are performed:
mt(i,1):=j; mt(i,2):=k; mt(i,3):=l

The resulting initialization is therefore:mt(1,1)=2, mt(1,2)=5, mt(1,3)=7
mt(4,1)=3, mt(4,2)=6, mt(4,3)=8The second argument of OCIexecute may also be a list of arrays. When using this version, the valueof OCIndxcol is ignored and the ﬁrst column(s) of the result set are always considered as indices andthe following ones as values for the corresponding arrays. For instance, assuming we have thefollowing declarations:m1, m2: array(1..10) of integer

With the statement:
OCIexecute("SELECT c1,c2,c3 from T", [m1,m2])

for each row (i,j,k) of the result set, the following assignments are performed:
m1(i):=j; m2(i):=k

So, if we use the table T of our previous example, we get the initialization:m1(1)=2, m1(4)=5m2(1)=3, m2(4)=6

9.3.2

From Mosel to Oracle
Information is transferred from Mosel to Oracle when performing an INSERT command for instance. In
this case, the way to use the Mosel arrays has to be speciﬁed by using parameters in the SQL
command. These parameters are identiﬁed by their name in the expression. For instance in thefollowing expression 3 parameters (:1, :2 and :3) are used:
INSERT INTO T (c1,c2,c3) VALUES (:1,:2,:3)

mmoci expects that parameters are always named :n where n is the parameter number starting at 1
but does not impose any order (i.e. :3,:1,:2 is also valid) and a given parameter may be used several
times in an expression. The command is then executed repeatedly as many times as the provided data
allows to build new tuples of parameters. The initialization of parameters is similar to what is done fora SELECT statement.
Assuming mt has been declared as follows:
mt: array(1..2,1..3) of integer

and initialized with this assignment:
mt::[1,2,3,

Fair Isaac Corporation Conﬁdential and Proprietary Information

312mmoci
4,5,6]

the execution of the call:
OCIexecute("INSERT INTO T (c1,c2,c3) VALUES (:1,:2,:3)",mt)behaves differently depending on the value of OCIndxcol. If this control parameter is true, for each
execution of the command, the following assignments are performed by mmoci:':1':= i, ':2':= j, ':3':= mt(i,j)

The execution is repeated for all possible values of i and j (in our example 6 times). The resulting
table T is therefore:c1 c2 c3
1 1 1
1 2 2
1 3 3
2 1 4
2 2 5
2 3 6

Note that mmoci uses the names of the parameters to perform an initialization and not their relative
position. This property is particularly useful for UPDATE statements where the order of parametersneeds to be changed. For instance, if we want to update the table T instead of inserting new rows, we
can write:
OCIexecute("UPDATE T c3=:3 WHERE c1=:1, c2=:2",mt)This command is executed exactly in the same way as the INSERT example above (i.e. we do not have’:3’:=i, ’:1’:=j, ’:2’:=mt(i,j) as the order of appearance in the command suggests but’:1’:=i, ’:2’:=j, ’:3’:=mt(i,j)).
The same functionality may also be used to reorder or repeat columns. With the same deﬁnition of thearray mt as before and a 4-column table S in the database the execution of the command
OCIexecute("INSERT INTO S (c1,c2,c3,c4) VALUES (:1,:2,:3,:2)",mt)results in the following contents of table S:c1 c2 c3 c4
1 1 1 11 2 2 2
1 3 3 32 1 4 12 2 5 22 3 6 3

If the control parameter OCIndxcol is false, only the values of the Mosel array are used to initialize
the parameters. So, for each execution of the command of our initial example (with 3 parameters), we
have:':1':=mt(i,1), ':2':=mt(i,2), ':3':=mt(i,3)

The execution is repeated for all possible values of i (in our example 2 times). The resulting table T istherefore:c1 c2 c3
1 2 3
4 5 6

Fair Isaac Corporation Conﬁdential and Proprietary Information

313

mmoci

However if the SQL query deﬁnes 4 parameters (instead of 3) as in:
OCIexecute("INSERT INTO T (c1,c2,c3,c4) VALUES (:1,:2,:3,:4)",mt)and the control parameter OCIndxcol is false, the ﬁrst parameter is used as the ﬁrst array index
while the remaining parameters are populated with data. As a consequence, for each execution of thecommand, the following assignments are performed by mmoci:':1':= i, ':2':= mt(i,1), ':3':= mt(i,2), ':4':=mf(i,3)

The execution is repeated for all possible values of i (in our example 2 times). The resulting table T istherefore:c1 c2 c3 c4
1 1 2 32 4 5 6

When OCIexecute is used with a list of arrays, the behavior is again similar to what has been
described earlier for the SELECT command: the ﬁrst parameter(s) are assigned index values and theﬁnal ones the actual array values. For instance, assuming we have the following declarations:m1,m2: array(1..3) of integer

And the arrays have been initialized as follows:
m1::[1,2,3]
m2::[4,5,6]

Then the following call:
OCIexecute("INSERT INTO T (c1,c2,c3) VALUES (:1,:2,:3)",[m1,m2])

executes 3 times the INSERT command. For each execution, the following parameter assignments are
performed:':1':=i, ':2':=m1(i), ':3':=m2(i)The resulting table T is therefore:c1 c2 c3
1 1 4
2 2 5
3 3 6

9.4

Control parameters
The following parameters are deﬁned by mmoci:
OCIautocommit

Enable/disable "commit on success" in OCI.

p. 315

OCIautondx

Enable automatic indexation of arrays.

p. 315

OCIbufsize

Data buffer size.

p. 316

OCIcolsize

Maximum string length.

p. 316

OCIconnection

Identiﬁcation number of the active OCI connection.

p. 316

OCIdebug

Enable/disable debug mode.

p. 317

Fair Isaac Corporation Conﬁdential and Proprietary Information

314mmoci

OCIfirstndx

Initial index value for an automatic indexation.

p. 317

OCIndxcol

Indicate whether to use ﬁrst columns as indices.

p. 317

OCIrowcnt

Number of lines affected by the last SQL command.

p. 318

OCIrowxfr

Number of lines transferred during the last SQL command.

p. 318

OCIsuccessIndicate whether the last SQL command succeeded.

p. 318

OCItruncsize

Length of the largest string that has been truncated.

p. 318OCIverbose

Enable/disable message printing by OCI.

p. 319All parameters can be accessed with the Mosel function getparam, and those that are not marked
read-only in the list below may be set using the procedure setparam.
Example:setparam("OCIverbose", true)
csize:=getparam("OCIcolsize")setparam("OCIconnection", 3)! Enable message printing by OCI! Get the maximum string length! Select the connection number 3

OCIautocommit
Description

Enable/disable "commit on success" in OCI.

Type

Boolean, read/write

Valuestrue Changes to the database are committed automatically.
false transactions have to be explicitly committed (or rolled back) using OCIcommit (orOCIrollback).

Default value

true

Modulemmoci

OCIautondx
Description

Enable automatic indexation of arrays.

Type

Boolean, read/write

Valuestrue Enable automatic indexation.
false Disable automatic indexation.
false

Default value
Note

Automatic indexation affects handling of arrays in SQL queries. It can be used only on
1-dimension arrays indiced by ranges: when this mode is enabled indices are not imported orexported, only array values are exchanged with the database. For reading, the initial index
value is taken from the parameter OCIfirstndx and incremented at each iteration. When
writing all cells of the arrays are exported.

Affects routines

OCIexecute.

See also

OCIfirstndx.

Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

315mmoci

OCIbufsize
Description

Size in kilobytes of the buffer used for exchanging data between Mosel and Oracle.

Type

Integer, read/write

ValuesAt least 1

Default value

4

Affects routines

OCIexecute, OCIreadstring.

Modulemmoci

OCIcolsize
Description

Maximum length of strings accepted to exchange data, anything exceeding this size is cut off.

Type

Integer, read/write

ValuesAt least 8

Default value

64

Note

When exporting external type entities as text strings to the database and the column size is
too small the resulting cells might be empty.

Affects routines

OCIexecute, OCIreadstring.

See also

OCItruncsize.

Modulemmoci

OCIconnection
Description

Identiﬁcation number of the active OCI connection. By changing the value of this parameter, it
is possible to work with several connections simultaneously.

Type

Integer, read/write

Affects routines

OCIlogoff, OCIexecute, OCIreadinteger.OCIreadreal, OCIreadstring.

Set by routines

OCIlogon.

Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

316mmoci

OCIdebug
Description

When this parameter is set to true, OCIverbose is also enabled and any SQL request sent
to Oracle is displayed to the error stream before execution. This option is ignored if the model
is not compiled with debug information.

Type

Boolean, read/write

Valuestrue Enable debug mode.
false Disable debug mode.

Default value

false

See also

OCIverbose.

Modulemmoci

OCIﬁrstndx
Description

Initial index value for an automatic indexation.

Type

Integer, read/write

Default value

1

Affects routines

OCIexecute.

See also

OCIautondx.

Modulemmoci

OCIndxcol
Description

Indicates whether the ﬁrst columns of each row must be interpreted as indices in all cases.
Setting it to the value false might be useful, for example, if one is trying to access a
non-relational table, perhaps a dense table. Note this mode can be enabled only is at least thelast dimension of each array is of ﬁxed size.

Type

Boolean, read/write

Valuestrue Interpret the ﬁrst columns of each row as indices.
false Do not interpret the ﬁrst columns of each row as indices.

Default valuetrue

Affects routines

OCIexecute, OCIreadinteger.OCIreadreal, OCIreadstring.

Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

317mmociOCIrowcnt
Description

Number of lines affected by the last SQL command.

Type

Integer, read only

Set by routines

OCIexecute, OCIreadinteger.OCIreadreal, OCIreadstring.

See also

OCIrowxfr.

Modulemmoci

OCIrowxfr
Description

Number of lines transferred during the last SQL command.

Type

Integer, read only

Set by routines

OCIexecute, OCIreadinteger.OCIreadreal, OCIreadstring.

See also

OCIrowcnt.

Modulemmoci

OCIsuccess
Description

Indicate whether the last SQL command has been executed successfully.

Type

Boolean, read only

Valuestrue Succes.
false Error.

Set by routines

All OCI functions.

Modulemmoci

OCItruncsize
Description

Length of the largest string that has been truncated.

Type

Integer, read only

Note

When exporting text to the database all strings must ﬁt into the predeﬁned column size
(OCIcolsize). If strings are truncated due to this limit the operation status is set to false(see OCIsuccess) and this parameter receives the size that should be used to avoid any
truncation.

Set by routines

OCIexecute.

Fair Isaac Corporation Conﬁdential and Proprietary Information

318mmociSee also

OCIsuccess, OCIcolsize.

Modulemmoci

OCIverbose
Description

Enable/disable message printing by OCI.

Type

Boolean, read/write

Valuestrue Enable message printing.
false Disable message printing.

Default value

true

Modulemmoci

9.5

Procedures and functions
This section lists in alphabetical order the functions and procedures that are provided by the mmocimodule.
OCIcommit

Commit the current transaction.

p. 326

OCIexecute

Execute an SQL command.

p. 322

OCIlogoff

Terminate the active database connection.

p. 321

OCIlogon

Connect to a database.

p. 320

OCIreadinteger

Read an integer value from a database.

p. 323

OCIreadreal

Read a real value from a database.

p. 324

OCIreadstring

Read a string from a database.

p. 325

OCIrollback

Roll back the current transaction.

p. 327

Fair Isaac Corporation Conﬁdential and Proprietary Information319

mmoci

OCIlogon
Purpose
Synopsis

Connect to a database.
procedure OCIlogon(s:string|text)
procedure OCIlogon(u:string|text, p:string|text, db:string|text)

Argumentssnpdb
ExampleLogon string as "user/password@db"
User name
Password
Database name (may be "" for the default database)

The following connects to the database ‘test’ as the user ‘yves’ with the password ‘DaSH’:
OCIlogon("yves/DaSH@test")
Open a connection to the default database the user ’scott’ with the password ’tiger’
OCIlogon("scott","tiger","")

Further information
1. This procedure establishes a connection to the database db as user n/p. It is possible to open several
connections but the connection established last becomes active. Each connection is assigned an
identiﬁcation number which can be obtained by getting the value of the parameter OCIconnection
after this procedure has been executed. This parameter can also be used to change the active
connection.
2. When Mosel is running in restricted mode (see Section 1.3.4), the restriction NoDB disables this routine.
Related topics
OCIlogoff.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

320mmoci

OCIlogoff
Purpose
Synopsis

Terminate the active database connection.
procedure OCIlogoff

Further information
The active connection can be accessed or changed by setting the control parameter OCIconnection.
Related topics
OCIlogon.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

321mmoci

OCIexecute
Purpose
Synopsis

Execute an SQL command.
procedure OCIexecute(s:string|text)
procedure OCIexecute(s:string|text, a:array)procedure OCIexecute(s:string|text, l:list)
procedure OCIexecute(s:string|text, m:set)

Argumentssalm
ExampleSQL command to be executed
An array
A list. May be a list of arrays
A set

The following example contains four OCIexecute statements performing the following tasks:
 Get all different values of the column color in the table pricelist.
 Initialize the arrays colors and prices with the values of the columns color and price of thetable pricelist.

 Create a new table newtab in the active database with 2 columns, ndx and price.
 Add data entries to table newtab.

declarations
prices: array(1001..1004) of realcolors: array(1001..1004) of string
allcolors: set of string
end-declarations
OCIexecute("select color from pricelist", allcolors)
OCIexecute("select articlenum,color,price from pricelist",[colors,prices])
OCIexecute("create table newtab (ndx integer, price double)")OCIexecute("insert into newtab (ndx, price) values (:1,:2)", prices)
Further information
1. This procedure executes the given SQL command. The user is referred to the Oracle documentation forfurther information on PL/SQL.
2. For output commands (like insert into) this procedure accepts arrays, sets and lists of basic types(integer, real, string or Boolean) as well as module types for which from/to string conversions areavailable. Record types composed of scalars or other records can also be used (the ﬁelds that cannot
be handled are silently ignored). It is also possible to use a list of arrays of basic types (all arrays must
be indexed by the same sets) or a list of scalar elements of different basic or module types.
3. For input commands (like select from) the same restrictions apply for arrays,lists and list of arrays
but sets must be of a basic type.
Related topics
OCIreadinteger, OCIreadreal, OCIreadstring.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

322

mmociOCIreadinteger
Purpose
Synopsis

Read an integer value from a database.
function OCIreadinteger(s:string|text):integer

Arguments

SQL command for selecting the value to be read

Return value
Integer value read or 0.
ExampleThe following gets the article number of the ﬁrst data item in table pricelist for which the ﬁeld
color is set to blue:
i:=OCIreadinteger("select articlenum from pricelist where color=blue")

Further information
1. 0 is returned if no integer value can be found.
2. If the given SQL selection command does not denote a single value, the ﬁrst value to which theselection criterion applies is returned.
Related topics
OCIexecute, OCIreadreal, OCIreadstring.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

323

mmociOCIreadreal
Purpose
Synopsis

Read a real value from a database.
function OCIreadreal(s:string|text):realArguments

SQL command for selecting the value to be read

Return value
Real value read or 0.
ExampleThe following returns the price of the data item with index 2 in table newtab:
r:=OCIreadreal("select price from newtab where ndx=2")

Further information
1. 0 is returned if no real value can be found.
2. If the given SQL selection command does not denote a single value, the ﬁrst value to which theselection criterion applies is returned.
Related topics
OCIexecute, OCIreadinteger, OCIreadstring.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

324

mmociOCIreadstring
Purpose
Synopsis

Read a string from a database.
function OCIreadstring(s:string|text):stringArguments

SQL command for selecting the string to be read

Return value
String read or empty string.
ExampleThe following retrieves the color of the (ﬁrst) data item in table pricelist with article number 1004:
s:=OCIreadstring("select color from pricelist where articlenum=1004")

Further information
1. The empty string is returned if no real value can be found.
2. If the given SQL selection command does not denote a single entry, the ﬁrst string to which theselection criterion applies is returned.
Related topics
OCIexecute, OCIreadinteger, OCIreadreal.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

325mmoci

OCIcommit
Purpose
Synopsis

Commit the current transaction.
procedure OCIcommit

Further information
This procedure is required only if the control parameter OCIautocommit is set to false.
Related topics
OCIrollback.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

326

mmociOCIrollback
Purpose
Synopsis

Roll back the current transaction.
procedure OCIrollback

Further information
This procedure can be used only if the control parameter OCIautocommit is set to false.
Related topics
OCIcommit.
Modulemmoci

Fair Isaac Corporation Conﬁdential and Proprietary Information

327

mmoci

9.6

I/O drivers
This module provides a driver designed to be used in initializations blocks for both reading andwriting data. The oci IO driver simpliﬁes access to Oracle databases.

9.6.1

Driver oci
oci:[debug;][noindex;][colsize=#;][bufsize=#;]logstring

The driver can only be used in ‘initializations’ blocks. The database to use has to be given in the
opening part of the block as user/password@dbname. Before this identiﬁer, the following options
may be stated:debug

to execute the block in debug mode (to display what SQL queries are produced). This
option is ignored if the model is not compiled with debug information.

noindexto indicate that only data (no indices) are transferred between the data source andMosel. By default, the ﬁrst columns of each table are interpreted as index values for thearray to be transferred. This behaviour is changed by this option.

colsize=c

to set the size of a text column (default 64 characters).

bufsize=c

to set the size of the data buffer in kilobytes (default 4).

In the block, each label entry is understood as a table name optionally followed by a list of column
names in brackets (e.g. "my_table(col1,col2)"). All columns are used if no list of names is
speciﬁed. Note that, before the table name, one can add option noindex to indicate that for thisparticular entry indices are not used.
Example:initializations from "mmoci.oci:scott/tiger@orcl"
NWeeks as "PARAMS(Weeks)"! Initialize `NWeeks' with column `Weeks'! of table `PARAMS'BPROF as "noindex;BPROFILE"! Initialize `BPROF' with table `BPROFILE'! all columns being data (no indices)
end-initializations

Fair Isaac Corporation Conﬁdential and Proprietary Information

328

CHAPTER 10

mmodbcThe Mosel ODBC interface provides a set of procedures and functions that may be used to accessdatabases for which an ODBC driver is available. This module also includes the SQLite database engine
that can be directly run without the need for any additional software.
To use the ODBC interface, the following line must be included in the header of a Mosel model ﬁle:uses 'mmodbc'

This manual describes the Mosel ODBC interface and shows how to use some standard SQL
commands, but it is not meant to serve as a manual for SQL. The reader is referred to the
documentation of the software he is using for more detailed information on these topics.

10.1

Prerequisite
The ODBC technology relies on a driver manager that is used as an interface between applications (likemmodbc) and a data source itself accessed through a dedicated driver. As a consequence, this module
requires that both, a driver manager and the necessary drivers (one for each data source to be used),
are installed and set up on the operating system.
Under Windows, usually the driver manager is part of the system and most data sources are provided
with their ODBC driver (for instance Excel, Access or SQLServer).
On the other supported operating systems it may be necessary to install a driver manager (as well as
the necessary drivers). The module mmodbc supports two driver managers: iODBC(http://www.iodbc.org) and unixODBC (http://www.unixodbc.org). Upon startup the module tries to load
the dynamic library "libiodbc.so" then, if this fails, tries "libodbc.so". If none of these libraries
can be found only the SQLite integrated driver will be available, please make sure that one of the drivermanagers is installed and that the corresponding libraries can be accessed (in general this requires
updating some environment variable).

10.2

ExampleAssume that the data source “mydata” deﬁnes a database that contains a table “pricelist” of thefollowing form:

Fair Isaac Corporation Conﬁdential and Proprietary Information329

mmodbc

articlenum

color

price

1001

blue

10.49

1002

red

10.49

1003

black

5.99

1004

blue

3.99

...
The following small example shows how to connect to a database from an Mosel model ﬁle, read indata, and disconnect from the data source.
model 'ODBCexample'
uses 'mmodbc'
declarations
prices: array (range) of real
end-declarations
setparam("SQLverbose", true)
SQLconnect("DSN=mydata")! Enable ODBC message printing in case of error! Connect to the database defined by `mydata'

writeln("Connection number: ", getparam("SQLconnection"))SQLexecute("select articlenum,price from pricelist", prices)! Get the entries of field `price' (indexed by! field `articlenum') in table `pricelist'
SQLdisconnect
end-model! Disconnect from the database

Here the SQLverbose control parameter is set to true to enable ODBC message printing in case oferror. Following the connection, the procedure SQLexecute is called to retrieve entries from the ﬁeld
price (indexed by ﬁeld articlenum) in the table pricelist. Finally, the connection is closed.
For further examples of working with databases and spreadsheets, the reader is referred to the Xpress
whitepaper Using ODBC and other database interfaces with Mosel.

10.3

Data transfer between Mosel and the database
Data transfer beetween Mosel and the database is achieved by calls to the procedure SQLexecute.
The value of the control parameter SQLndxcol and the type and structure of the second argument of
the procedure decide how the data are transferred between the two systems.

10.3.1

From the database to Mosel
Information is moved from the database to Mosel when performing a SELECT command for instance.
Assuming mt has been declared as follows:
mt: array(1..10,1..3) of integer

the execution of the call:
SQLexecute("SELECT c1,c2,c3 from T", mt)behaves differently depending on the value of SQLndxcol. If this control parameter is true, thecolumns c1 and c2 are used as indices and c3 is the value to be assigned. For each row (i,j,k) of theresult set, the following assignment is performed by mmodbc:

Fair Isaac Corporation Conﬁdential and Proprietary Information

330mmodbc
mt(i,j):=k

With a table T containing:c1 c2 c3 c4
1 2 5 74 3 6 8

We obtain the initialization:m2(1,2)=5, m(4,3)=6

If the control parameter SQLndxcol is false, all columns are treated as data. In this case, for eachrow (i,j,k) the following assignments are performed:
mt(r,1):=i; mt(r,2):=j; mt(r,3):=k

where r is the row number in the result set.
Here, the resulting initialization is:mt(1,1)=1, mt(1,2)=2, mt(1,3)=5mt(2,1)=4, mt(2,2)=3, mt(2,3)=6

If the SQL statement selects 4 columns (instead of 3) as in:
SQLexecute("SELECT c1,c2,c3,c4 from T", mt)

and the control parameter SQLndxcol is false, the ﬁrst column is used as the ﬁrst array index while
the remaining columns are treated as data. As a consequence, for each row (i,j,k,l) the following
assignments are performed:
mt(i,1):=j; mt(i,2):=k; mt(i,3):=l

The resulting initialization is therefore:mt(1,1)=2, mt(1,2)=5, mt(1,3)=7
mt(4,1)=3, mt(4,2)=6, mt(4,3)=8The second argument of SQLexecute may also be a list of arrays. When using this version, the valueof SQLndxcol is ignored and the ﬁrst column(s) of the result set are always considered as indices andthe following ones as values for the corresponding arrays. For instance, assuming we have thefollowing declarations:m1, m2: array(1..10) of integer

With the statement:
SQLexecute("SELECT c1,c2,c3 from T", [m1,m2])

for each row (i,j,k) of the result set, the following assignments are performed:
m1(i):=j; m2(i):=k

So, if we use the table T of our previous example, we get the initialization:m1(1)=2, m1(4)=5m2(1)=3, m2(4)=6Fair Isaac Corporation Conﬁdential and Proprietary Information

331mmodbc

10.3.2

From Mosel to the database
Information is transferred from Mosel to the database when performing an INSERT command for
instance. In this case, the way to use the Mosel arrays has to be speciﬁed by using parameters in the
SQL command. These parameters are identiﬁed by the symbol ‘?’ in the expression. For instance in thefollowing expression 3 parameters are used:
INSERT INTO T (c1,c2,c3) VALUES (?,?,?)

The command is then executed repeatedly as many times as the provided data allows to build newtuples of parameters. The initialization of parameters is similar to what is done for a SELECT
statement.
Assuming mt has been declared as follows:
mt: array(1..2,1..3) of integer

and initialized with this assignment:
mt::[1,2,3,
4,5,6]

the execution of the call:
SQLexecute("INSERT INTO T (c1,c2,c3) VALUES (?,?,?)",mt)behaves differently depending on the value of SQLndxcol. If this control parameter is true, for each
execution of the command, the following assignments are performed by mmodbc (?1,?2,?3 denoterespectively the ﬁrst second and third parameter):'?1':= i, '?2':= j, '?3':= mt(i,j)

The execution is repeated for all possible values of i and j (in our example 6 times). The resulting
table T is therefore:c1 c2 c3
1 1 1
1 2 2
1 3 3
2 1 4
2 2 5
2 3 6

If the control parameter SQLndxcol is false, only the values of the Mosel array are used to initialize
the parameters. So, for each execution of the command, we have:'?1':=mt(i,1), '?2':=mt(i,2), '?3':=mt(i,3)

The execution is repeated for all possible values of i (in our example 2 times). The resulting table T istherefore:c1 c2 c3
1 2 3
4 5 6

However if the SQL query deﬁnes 4 parameters (instead of 3) as in:
SQLexecute("INSERT INTO T (c1,c2,c3,c4) VALUES (?,?,?,?)",mt)and the control parameter SQLndxcol is false, the ﬁrst parameter is used as the ﬁrst array index

Fair Isaac Corporation Conﬁdential and Proprietary Information332

mmodbc

while the remaining parameters are populated with data. As a consequence, for each execution of thecommand, the following assignments are performed by mmodbc:'?1':= i, '?2':= mt(i,1), '?3':= mt(i,2), '?4':=mf(i,3)

The execution is repeated for all possible values of i (in our example 2 times). The resulting table T istherefore:c1 c2 c3 c4
1 1 2 32 4 5 6

When SQLexecute is used with a list of arrays, the behavior is again similar to what has been
described earlier for the SELECT command: the ﬁrst parameter(s) are assigned index values and theﬁnal ones the actual array values. For instance, assuming we have the following declarations:m1,m2: array(1..3) of integer

And the arrays have been initialized as follows:
m1::[1,2,3]
m2::[4,5,6]

Then the following call:
SQLexecute("INSERT INTO T (c1,c2,c3) VALUES (?,?,?)",[m1,m2])

executes 3 times the INSERT command. For each execution, the following parameter assignments are
performed:'?1':=i, '?2':=m1(i), '?3':=m2(i)The resulting table T is therefore:c1 c2 c3
1 1 4
2 2 5
3 3 6

10.4

ODBC and MS Excel
Microsoft Excel is a spreadsheet application. Since ODBC was primarily designed for databases
special rules have to be followed to read and write Excel data using ODBC:

A table of data is referred to as either a named range (e.g. MyRange), a worksheet name (e.g.
[Sheet1$]) or an explicit range (e.g. [Sheet1$B2:C12]).
By default, the ﬁrst row of a range is used for naming the columns (to be used in SQL
statements). The option FIRSTROWHASNAMES=0 disables this feature and columns are implicitly
named F1, F2... However, even with this option, the ﬁrst row is ignored and cannot contain data.
The data type of columns is deduced by the Excel driver by scanning the ﬁrst 8 rows. The numberof rows analyzed can be changed using the option MAXSCANROWS=n (n between 1 and 8).

It is important to be aware that when writing to database tables speciﬁed by a named range in Excel,
they will increase in size if new data is added using an INSERT statement. To overwrite existing data in
the worksheet, the SQL statement UPDATE can be used in most cases (although this command is not

Fair Isaac Corporation Conﬁdential and Proprietary Information333mmodbc

fully supported). Now suppose that we wish to write further data over the top of data that has alreadybeen written to a range using an INSERT statement. Within Excel it is not sufﬁcient to delete theprevious data by selecting it and hitting the Delete key. If this is done, further data will be added after ablank rectangle where the deleted data used to reside. Instead, it is important to use Edit/Delete/Shift
cells up within Excel, which will eliminate all traces of the previous data, and the enlarged range.
Microsoft Excel tables can be created and opened by only one user at a time. However, the "Read Only"
option available in the Excel driver options allows multiple users to read from the same .xls ﬁles.
When ﬁrst experimenting with acquiring or writing data via ODBC it is tempting to use short names forcolumn headings. This can lead to horrible-to-diagnose errors if you inadvertently use an SQL keyword.
We strongly recommend that you use names like “myParameters”, or “myParams”, or “myTime”, which
will not clash with SQL reserved keywords.

10.5

Control parameters
The following parameters are deﬁned by mmodbc:
SQLautocommit

Enable/disable auto commit mode.

p. 335

SQLautondx

Enable automatic indexation of arrays.

p. 335

SQLbufsize

Data buffer size.

p. 335

SQLcolsize

Maximum string length.

p. 336

SQLconnection

Identiﬁcation number of the active ODBC connection.

p. 336

SQLdebug

Enable/disable debug mode.

p. 336

SQLdm

Driver manager currently used.

p. 337

SQLextn

Enable/Disable extended syntax.

p. 337

SQLfirstndx

Initial index value for an automatic indexation.

p. 337

SQLndxcol

Indicate whether to use ﬁrst columns as indices.

p. 338SQLrowcnt

Number of lines affected by the last SQL command.

p. 338SQLrowxfr

Number of lines transferred during the last SQL command.

p. 338

SQLsuccessIndicate whether the last SQL command succeeded.

p. 338

SQLtruncsize

Length of the largest string that has been truncated.

p. 339

SQLverbose

Enable/disable message printing by the ODBC driver.

p. 339All parameters can be accessed with the Mosel function getparam, and those that are not marked
read-only in the list below may be set using the procedure setparam.
Example:setparam("SQLverbose", true)
csize:=getparam("SQLcolsize")setparam("SQLconnection", 3)

Fair Isaac Corporation Conﬁdential and Proprietary Information! Enable message printing by the ODBC driver! Get the maximum string length! Select the connection number 3334

mmodbc

SQLautocommit
Description

When this parameter is set to true (the default), any change to the database is sent
immediately. Otherwise, if transactions are supported by the database, changes are retained
until a call to SQLcommit (commit changes) or SQLrollback (discard changes) is issued.
The value of this parameter is used at the time the database is open with SQLconnect: once
connection is established, changing this parameter has no impact on the existing
connections (i.e. they remain in their initial transaction mode)Type

Boolean, read/write

Valuestrue Enable auto commit mode.
false Disable auto commit mode (i.e. transactions).

Default valuetrue

Affects routines

SQLconnect.

Modulemmodbc

SQLautondx
Description

Enable automatic indexation of arrays.

Type

Boolean, read/write

Valuestrue Enable automatic indexation.
false Disable automatic indexation.

Default value

false

Note

Automatic indexation affects handling of arrays in SQL queries. It can be used only on
1-dimension arrays indiced by ranges: when this mode is enabled indices are not imported orexported, only array values are exchanged with the database. For reading, the initial index
value is taken from the parameter SQLfirstndx and incremented at each iteration. When
writing all cells of the arrays are exported.

Affects routines

SQLexecute.

See also

SQLfirstndx.

ModulemmodbcSQLbufsize
Description

Size in kilobytes of the buffer used for exchanging data between Mosel and the ODBC driver.

Type

Integer, read/write

ValuesAt least 1

Default value

4 on Posix systems and 8 on Windows

Fair Isaac Corporation Conﬁdential and Proprietary Information

335

mmodbc

Affects routines

SQLexecute, SQLreadstring.

Modulemmodbc

SQLcolsize
Description

Maximum length of strings accepted to exchange data, anything exceeding this size is cut off.

Type

Integer, read/write

ValuesAt least 8

Default value

64

Affects routines

SQLexecute, SQLreadstring.

Note

The column size is expressed in bytes when using an ANSI interface (with a multibyte
encoding a single character may occupy more than one byte) and in characters when using aUnicode interface. When exporting text strings to the database and the column size issigniﬁcantly too small the resulting cells might be empty.

See also

SQLtruncsize.

Modulemmodbc

SQLconnection
Description

Identiﬁcation number of the active ODBC connection. By changing the value of thisparameter, it is possible to work with several connections simultaneously.

Type

Integer, read/write

Affects routines

SQLdisconnect, SQLexecute, SQLreadinteger.SQLreadreal, SQLreadstring.

Set by routines

SQLconnect.

ModulemmodbcSQLdebug
Description

When this parameter is set to true, SQLverbose is also enabled and any SQL request sent
to ODBC is displayed to the error stream before execution. This option is ignored if the model
is not compiled with debug information.

Type

Boolean, read/write

Valuestrue Enable debug mode.
false Disable debug mode.

Default value

false

See also

SQLverbose.

ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

336

mmodbc

SQLdm
Description

Driver manager currently used.

Type

Integer, read only

Values

<0
0
1
2

Note

A negative value for this parameter indicates that no driver manager could be found on thesystem. As a consequence only the integrated SQLite driver can be accessed.

ModulemmodbcNo driver manager available (Unix/Linux).
Unspeciﬁed (manager not loaded dynamically).
iODBC.
unixODBC.

SQLextn
Description

Enable/Disable extended syntax.

Type

Boolean, read/write

Valuestrue Enable extended syntax.
false Disable extended syntax.

Default valuetrue

Affects routines

SQLconnect, SQLexecute.

Modulemmodbc

SQLﬁrstndx
Description

Initial index value for an automatic indexation.

Type

Integer, read/write

Default value

1

Affects routines

SQLexecute.

See also

SQLautondx.

ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

337

mmodbc

SQLndxcol
Description

Indicates whether the ﬁrst columns of each row must be interpreted as indices in all cases.
Setting it to the value false might be useful, for example, if one is trying to access a
non-relational table, perhaps a dense spreadsheet table. Note this mode can be enabled only
if at least the last dimension of each array is of ﬁxed size.

Type

Boolean, read/write

Valuestrue Interpret the ﬁrst columns of each row as indices.
false Do not interpret the ﬁrst columns of each row as indices.

Default valuetrue

Affects routines

SQLexecute, SQLreadinteger.SQLreadreal, SQLreadstring.

ModulemmodbcSQLrowcnt
Description

Number of lines affected by the last SQL command.

Type

Integer, read only

Set by routines

SQLexecute, SQLreadinteger.SQLreadreal, SQLreadstring.

See also

SQLrowxfr.

ModulemmodbcSQLrowxfr
Description

Number of lines transferred during the last SQL command.

Type

Integer, read only

Set by routines

SQLexecute, SQLreadinteger.SQLreadreal, SQLreadstring.

See also

SQLrowcnt.

ModulemmodbcSQLsuccess
Description

Indicate whether the last SQL command has been executed successfully.

Type

Boolean, read only

Fair Isaac Corporation Conﬁdential and Proprietary Information

338

mmodbc

Valuestrue Succes.
false Error.

Set by routines

All ODBC functions.

Modulemmodbc

SQLtruncsize
Description

Length of the largest string that has been truncated.

Type

Integer, read only

Note

When exporting text to the database all strings must ﬁt into the predeﬁned column size
(SQLcolsize). If strings are truncated due to this limit the operation status is set to false(see SQLsuccess) and this parameter receives the size that should be used to avoid any
truncation.

Set by routines

SQLexecute.

See also

SQLsuccess, SQLcolsize.

ModulemmodbcSQLverbose
Description

Enable/disable message printing by the ODBC driver.

Type

Boolean, read/write

Valuestrue Enable message printing.
false Disable message printing.

Default value

true

Modulemmodbc

10.6

Procedures and functions
This section lists in alphabetical order the functions and procedures that are provided by the mmodbc
module.
SQLcolumns

Get the columns of a given table.

SQLcommit

Terminate the current transaction by committing any pending changes.
p. 342

SQLconnect

Connect to a database.

p. 343

SQLdisconnect

Terminate the active database connection.

p. 345

SQLexecute

Execute an SQL command.

p. 346

Fair Isaac Corporation Conﬁdential and Proprietary Information

p. 341339

mmodbc

SQLgetparamGet the value of an SQL parameter.

p. 349SQLindicesGet the list of indices of a given table.

p. 350

SQLparam

Generate an SQL parameter.

p. 348SQLprimarykeys

Get the list of primary keys of a given table.

p. 351

SQLreadinteger

Read an integer value from a database.

p. 352

SQLreadreal

Read a real value from a database.

p. 353

SQLreadstring

Read a string from a database.

p. 354

SQLrollback

Terminate the current transaction by discarding any pending changes.
p. 355

SQLtables

Get the list of tables available in the database.

p. 356

SQLupdate

Update the selected data with the provided array(s).

p. 357

Fair Isaac Corporation Conﬁdential and Proprietary Information

340

mmodbc

SQLcolumns
Purpose
Synopsis

Get the columns of a given table.
function SQLcolumns(t:string,cname:array(range) ofstring,cstype:array(range) of string):integerfunction SQLcolumns(t:string,cname:array(range) ofstring,citype:array(range) of integer):integerfunction SQLcolumns(t:string,cname:array(range) of string):integer

Argumentst
cname
cstypecitype

The table nameAn array of strings to return the column names
An array of strings to return the column types (textual representation)
An array of integers to return the column types (type codes)

Return value
Number of columns.
ExampleThe following example displays the names and types of columns of table ’dtt’:
declarations
CR:range
cname:dynamic array(CR) of string
ctype:dynamic array(CR) of string
end-declarations
nbc:=SQLcolumns("dtt",cname,ctype)write("Table 'dtt' has columns:")
forall(c in 1..nbc) write(' ',cname(c),'(',ctype(c),')')
writeln

Related topics
SQLtables, SQLprimarykeys, SQLindices.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

341

mmodbc

SQLcommit
Purpose
Synopsis

Terminate the current transaction by committing any pending changes.
procedure SQLcommit

Further information
If the database supports transactions and the connection has been created in manual commit mode(see SQLautocommit), all changes to the database are recorded as a transaction. This procedurecommits all pending changes corresponding to the current transaction and starts a new transaction.
Related topics
SQLrollback.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information342

mmodbc

SQLconnect
Purpose
Synopsis

Connect to a database.
procedure SQLconnect(s:string|text)

Arguments
ExampleConnection string

The following connects to the MySQL database ‘test’ as the user ‘yves’ with the password ‘DaSH’:
SQLconnect("DSN=mysql;DB=test;UID=yves;PWD=DaSH")
Open the database mydata.sqlite with the integrated SQLite engine:
SQLconnect("mydata.sqlite")

Fair Isaac Corporation Conﬁdential and Proprietary Information

343

mmodbc

Further information
1. This procedure establishes a connection to the database deﬁned by the given connection string. If
extended mode is in use (default) and the ODBC driver manager publishes its driver list, the connection
string may be reduced to a ﬁle name as long as this name allows identiﬁcation of the required driver (byusing the ﬁlename extension).
2. Both Unicode and ANSI ODBC interfaces are supported. By default the Unicode interface is used on
Windows and the ANSI interface is selected on Posix systems. It is possible to choose the interface byusing the "enc:" ﬁle name preﬁx: any of the UTF encodings (except UTF-8) will enable the Unicodeinterface. Otherwise the ANSI interface is selected using the speciﬁed encoding. For instance for using
the ANSI interface under Windows with an Access database: "enc:sys,mydb.mdb". Similarly, to use
the Unicode interface of MySQL on a Unix machine, the connection strings looks like:"enc:wchar,DSN=mysql;DB=test".
3. It is possible to open several connections but the connection established last becomes active. Eachconnection is assigned an identiﬁcation number which can be obtained by getting the value of theparameter SQLconnection after this procedure has been executed. This parameter can also be used
to change the active connection.
4. ODBC drivers are not necessarily executed from the same working directory as the model. As aconsequence, a driver expecting a ﬁle as data source may not be able to locate the ﬁle if its name isrelative to the current directory (e.g. "DSN=Microsoft Access Driver; DBQ=mydb.mdb"). The
use of the function expandpath from mmsystem allows to avoid this problem by generating an
absolute path name for the given name (e.g. "DSN=Microsoft Access Driver;
DBQ="+expandpath("mydb.mdb")).
5. When Mosel is running in restricted mode (see Section 1.3.4), connections using a ﬁle name are notpossible if restriction NoRead or NoWrite is active and connections using a DSN are disabled by
restriction NoDB.
6. The embedded SQLite database engine is selected when specifying a ﬁle name with extension ".db",".db3", ".sqlite" or ".sqlite3". The driver may also be selected with the help of an extended
connection string starting with the DRIVER keyword and using "mmsqlite" as the driver name. In thiscase the option DB has to be set in order to select the database ﬁle and READONLY may also be added
to open the database read-only. The option TIMEOUT will deﬁne the busy timeout for the connection:
this is an amount of time (in milliseconds) indicating for how long SQLite will try to execute a querywhen the database is locked (by default the query fails if the database is already used by a concurrent
connection). A typical connection string for this SQLite driver is therefore of the form:"DRIVER=mmsqlite;READONLY=FALSE;TIMEOUT=0;DB=mydata.db" (that is the same as"mydata.db"). When using this syntax a temporary database can be created by using an empty ﬁlename and an in-memory database is generated if the ﬁle name is ":memory:".
Related topics
SQLdisconnect.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information344

mmodbc

SQLdisconnect
Purpose
Synopsis

Terminate the active database connection.
procedure SQLdisconnect

Further information
The active connection can be accessed or changed by setting the control parameter SQLconnection.
Related topics
SQLconnect.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

345

mmodbc

SQLexecute
Purpose
Synopsis

Execute an SQL command.
procedure SQLexecute(s:string|text)
procedure SQLexecute(s:string|text, a:array)procedure SQLexecute(s:string|text, l:list)
procedure SQLexecute(s:string|text, m:set)procedure SQLexecute(s:string|text, lp:list, a:array)procedure SQLexecute(s:string|text, lp:list, l:list)
procedure SQLexecute(s:string|text, lp:list, m:set)

Arguments
s
a
l
m
lp
ExampleSQL command to be executed
An array
A listA set
A list of parameters

The following example contains four SQLexecute statements performing the following tasks:
 Get all different values of the column color in the table pricelist.
 Initialize the arrays colors and prices with the values of the columns color and price of thetable pricelist.

 Create a new table newtab in the active database with 2 columns, ndx and price.
 Add data entries to table newtab.

declarations
prices: array(1001..1004) of realcolors: array(1001..1004) of string
allcolors: set of string
end-declarations
SQLexecute("select color from pricelist", allcolors)
SQLexecute("select articlenum,color,price from pricelist",[colors,prices])
SQLexecute("create table newtab (ndx integer, price double)")SQLexecute("insert into newtab (ndx, price) values (?,?)", prices)

Fair Isaac Corporation Conﬁdential and Proprietary Information

346

mmodbc

Further information
1. This procedure executes the given SQL command. The user is referred to the documentation of thedatabase driver he is using for more information about the commands that are supported by it. Notethat if extended syntax is in use (default), parameters usually noted ’?’ in normal SQL queries may benumbered (like ’?1’,’?2’,...) in order to control in which order are mapped columns of data source table toMosel arrays. This feature is especially useful when writing ’update’ queries for which indices must
appear after values (e.g. "update mytable set datacol=?2 where ndxcol=?1").
2. For output commands (like insert into) this procedure accepts arrays, sets and lists of basic types(integer, real, string or Boolean) as well as module types for which from/to string conversions areavailable. Record types composed of scalars or other records can also be used (the ﬁelds that cannot
be handled are silently ignored). It is also possible to use a list of arrays of basic types (all arrays must
be indexed by the same sets) or a list of scalar elements of different basic or module types.
3. For input commands (like select from) the same restrictions apply for arrays,lists and list of arrays
but sets must be of a basic type.
4. The form using an extra list argument will be used with input commands requiring parameters: the list
deﬁnes the value of the parameters.
Related topics
SQLupdate, SQLreadinteger, SQLreadreal, SQLreadstring.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

347

mmodbc

SQLparam
Purpose
Synopsis

Generate an SQL parameter.
function SQLparam(i:integer):SQLparameter
function SQLparam(r:real):SQLparameter
function SQLparam(s:string):SQLparameter

Argumentsirs

The initial value as an integer
The initial value as a real
The initial value as a string

Return value
SQL parameter suitable for SQL routines.
ExampleThe following calls a procedure named myproc using 3 parameters. The ﬁrst one is an input string
parameter (’hello’), the second is an input/output integer parameter (10) and the last one is an
output string parameter. The procedure returns a result set that mmodbc will use to initialise result.
After execution of the query, the new values of the 2 input/output parameters set by the procedure may
be displayed using the appropriate SQLgetparam routines.
SQLexecute("CALL myproc(?,?,?)",['hello',SQLparam(10),SQLparam("")],result)writeln("P1=",SQLgetiparam(1))
writeln("P2=",SQLgetsparam(2))

Further information
1. This routine can only be used in a list of parameters for an SQL query: it deﬁnes an input/output
parameter. The input value of the parameter is provided via the argument function (an integer, a real ora string) and the output value (set by the database during the execution of the query) can be retrieved
using one of the SQLgetparam functions.
2. SQL parameters are typed: the type of the parameter is deduced from its initial values (passed to the
SQLparam function).
Related topics
SQLexecute, SQLreadreal, SQLreadstring, SQLreadinteger, SQLgetparam.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

348

mmodbc

SQLgetparam
Purpose
Synopsis

Get the value of an SQL parameter.
function SQLgetiparam(n:integer):integerfunction SQLgetrparam(n:integer):realfunction SQLgetsparam(n:integer):stringArgumentnParameter number ( ≥ 1)

Return value
The value of the corresponding parameter.
Further information
1. This routine can be used after a query using input/output SQL parameters has been executed toretrieve the values of the parameters.
2. Each of the 3 functions is associated to a speciﬁc type: for instance SQLgetiparam will return values
only for integer parameters.
Related topics
SQLparam.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information349

mmodbc

SQLindices
Purpose
Synopsis

Get the list of indices of a given table.
procedure SQLindices(t:string,ls:list of string)Argumentst
ls

The table name
A list of strings to return the index names

Further information
The provided list is reset.
Related topics
SQLtables, SQLcolumns, SQLprimarykeys.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

350

mmodbc

SQLprimarykeys
Purpose
Synopsis

Get the list of primary keys of a given table.
procedure SQLprimarykeys(t:string,ls:list of string)procedure SQLprimarykeys(t:string,li:list of integer)

Argumentst
lsli

The table name
A list of strings to return the column names
A list of strings to return the column numbers

Further information
The provided list is reset.
Related topics
SQLtables, SQLcolumns, SQLindices.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

351

mmodbc

SQLreadinteger
Purpose
Synopsis

Read an integer value from a database.
function SQLreadinteger(s:string|text):integerfunction SQLreadinteger(s:string|text,p:list):integer

Argumentssp

SQL command for selecting the value to be readA list of SQL parameters

Return value
Integer value read or 0.
ExampleThe following gets the article number of the ﬁrst data item in table pricelist for which the ﬁeld
color is set to blue:
i:=SQLreadinteger("select articlenum from pricelist where color=blue")

Further information
1. 0 is returned if no integer value can be found.
2. If the given SQL selection command does not denote a single value, the ﬁrst value to which theselection criterion applies is returned.
3. The second argument can be used to specify SQL parameter values if the SQL query contains
parameter markers.
Related topics
SQLexecute, SQLreadreal, SQLreadstring.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information352

mmodbc

SQLreadreal
Purpose
Synopsis

Read a real value from a database.
function SQLreadreal(s:string|text):realfunction SQLreadreal(s:string|text,p:list):realArgumentssp

SQL command for selecting the value to be readA list of SQL parameters

Return value
Real value read or 0.
ExampleThe following returns the price of the data item with index 2 in table newtab:
r:=SQLreadreal("select price from newtab where ndx=2")

Further information
1. 0 is returned if no real value can be found.
2. If the given SQL selection command does not denote a single value, the ﬁrst value to which theselection criterion applies is returned.
3. The second argument can be used to specify SQL parameter values if the SQL query contains
parameter markers.
Related topics
SQLexecute, SQLreadinteger, SQLreadstring.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

353

mmodbc

SQLreadstring
Purpose
Synopsis

Read a string from a database.
function SQLreadstring(s:string|text):string
function SQLreadstring(s:string|text,p:list):stringArgumentssp

SQL command for selecting the string to be readA list of SQL parameters

Return value
String read or empty string.
ExampleThe following retrieves the color of the (ﬁrst) data item in table pricelist with article number 1004:
s:=SQLreadstring("select color from pricelist where articlenum=1004")

Further information
1. The empty string is returned if no real value can be found.
2. If the given SQL selection command does not denote a single entry, the ﬁrst string to which theselection criterion applies is returned.
3. The second argument can be used to specify SQL parameter values if the SQL query contains
parameter markers.
Related topics
SQLexecute, SQLreadinteger, SQLreadreal.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information354

mmodbc

SQLrollback
Purpose
Synopsis

Terminate the current transaction by discarding any pending changes.
procedure SQLrollback

Further information
If the database supports transactions and the connection has been created in manual commit mode(see SQLautocommit), all changes to the database are recorded as a transaction. This procedure
discards all pending changes corresponding to the current transaction and starts a new transaction.
Related topics
SQLcommit.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

355

mmodbc

SQLtables
Purpose
Synopsis

Get the list of tables available in the database.
procedure SQLtables(l:list of string)Argumentl

A list of strings to return the table names

Further information
This procedure retrieves the list of tables available in the current database. The provided list is reset.
Related topics
SQLcolumns, SQLprimarykeys, SQLindices.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

356

mmodbc

SQLupdatePurpose
Synopsis

Update the selected data with the provided array(s).
procedure SQLupdate(s:string|text, a:array)procedure SQLupdate(s:string|text, la:list)

Argumentssala
ExampleAn SQL ‘SELECT’ command
An array of one of the basic types (integer, real, string or Boolean)
A list of arrays of basic types (integer, real string or Boolean)

The following example initializes the array prices with the values of the table pricelist, changes
some values in the array and ﬁnally, updates the date in the table pricelist.
declarations
prices: array(1001..1004) of real
end-declarations
SQLexecute("select articlenum,price from pricelist", prices)
prices(1002):=prices(1002)⁎0.9; prices(1003):=prices(1003)⁎0.8
SQLupdate("select articlenum,price from pricelist", prices)

Further information
This procedure updates the data selected by an SQL command (usually ‘SELECT’) with an array or tupleof arrays. This procedure is available only if the data source supports positioned updates (for instance,
MS Access does but MS Excel does not).
Related topics
SQLexecute.
ModulemmodbcFair Isaac Corporation Conﬁdential and Proprietary Information

357

mmodbc

10.7

I/O drivers
In order to simplify access to ODBC enabled data sources, this module provides a driver designed to be
used in initializations blocks for both reading and writing data.

10.7.1

Driver odbc
odbc:[debug;][noindex;][colsize=#;][bufsize=#;]DSN

The driver can only be used in ‘initializations’ blocks. The Data Source Name to use has to be given in
the opening part of the block. Before the DSN, the following options may be stated:debug

to execute the block in debug mode (to display what SQL queries are produced). This
option is ignored if the model is not compiled with debug information,

noindexto indicate that only data (no indices) are transferred between the data source andMosel. By default, the ﬁrst columns of each table are interpreted as index values for thearray to be transferred. This behaviour is changed by this option,colsize=c

to set the size of a text column (default 64 characters),

bufsize=c

to set the size of the data buffer in kilobytes (default 4).

In the block, each label entry is understood as a table name optionally followed by a list of column
names in brackets (e.g. "my_table(col1,col2)"). All columns are used if no list of names is
speciﬁed. Note that, before the table name, one can add option noindex to indicate that for thisparticular entry indices are not used.
Example:initializations from "mmodbc.odbc:auction.db3"
NWeeks as "PARAMS(Weeks)"! Initialize `NWeeks' with column `Weeks'! of table `PARAMS'BPROF as "noindex;BPROFILE"! Initialize `BPROF' with table `BPROFILE'! all columns being data (no indices)
end-initializations

Fair Isaac Corporation Conﬁdential and Proprietary Information

358

CHAPTER 11

mmquadThe mmquad module extends the Mosel language with a new type for representing quadratic
expressions.To use this module, the following line must be included in the header of the Mosel modelﬁle:uses 'mmquad'The ﬁrst section presents the new functionality for the Mosel language that is provided by mmquad,
namely the new type qexp and a set of subroutines that may be applied to objects of this type.
Via the inter-module communication interface, the module mmquad publishes several of its libraryfunctions. These are documented in the second section. By means of an example it is shown how thefunctions published by mmquad can be used in another module for accessing quadratic expressions
and working with them.

11.1

New functionality for the Mosel language

11.1.1

The type qexp and its operators
The module mmquad deﬁnes the type qexp to represent quadratic expressions in the Mosel Language.
As shown in the following example, mmquad also deﬁnes the standard arithmetic operations that are
required for working with objects of this type. By and large, these are the same operations as for linear
expressions (type linctr of the Mosel language) with in addition the possibility to multiply two
decision variables or one variable with itself. For the latter, the exponential notation xˆ2 may be used(assuming that x is of type mpvar).
11.1.1.1

Example: using mmquad for Quadratic Programming

Quadratic expressions as deﬁned with the help of mmquad may be used to deﬁne quadratic objectivefunctions for Quadratic Programming (QP) or Mixed Integer Quadratic Programming (MIQP) problems.
The Xpress-Optimizer module mmxprs for instance accepts expressions of type qexp as arguments for
its optimization subroutines minimize and maximize, and for the procedure loadprob (see also the
mmxprs Reference Manual). The following
model "Small MIQP example"
uses "mmxprs", "mmquad"declarations
x: array(1..4) of mpvar
Obj: qexp
end-declarations! Define some linear constraints

Fair Isaac Corporation Conﬁdential and Proprietary Information359

mmquadx(1) + 2⁎x(2) - 4⁎x(4) >= 03⁎x(1) - 2⁎x(3) - x(4) <= 100
x(1) + 3⁎x(2) + 3⁎x(3) - 2⁎x(4) >= 10
x(1) + 3⁎x(2) + 3⁎x(3) - 2⁎x(4) <= 30
2 <= x(1); x(1) <= 20
x(2) is_integer; x(3) is_integerx(4) is_free! The objective function is a quadratic expression
Obj:= x(1) + x(1)^2 + 2⁎x(1)⁎x(2) + 2⁎x(2)^2 + x(4)^2! Solve the problem and print its solution
minimize(Obj)writeln("Solution: ", getobjval)
forall(i in 1..4) writeln(getsol(x(i)))
end-model

11.1.2

Procedures and functions
The module mmquad overloads certain subroutines of the Mosel language, replacing an argument oftype linctr by the type qexp.
exportprob

Export a quadratic problem to a ﬁle.

p. 361

getsolGet the solution value of a quadratic expression.

p. 362

Fair Isaac Corporation Conﬁdential and Proprietary Information

360mmquadexportprob
Purpose
Synopsis

Export a quadratic problem to a ﬁle.
procedure exportprob(options:integer, filename:string, obj:qexp)
procedure exportprob(filename:string, obj:qexp)

Arguments
options

File format options:

EP_MINLP format, minimization
EP_MAX
LP format, maximization
EP_MPSMPS format
EP_STRIP Use scrambled names
EP_HEX
Ouput numbers in hexadecimal when using MPS format
filename Name of the output ﬁle; if empty, output printed to standard output (screen)
obj
Objective function (quadratic expression)
ExampleThe following example prints the problem to screen using the default format, and then exports the
problem in LP-format to the ﬁle prob1.lp maximizing constraint Profit:
uses "mmquad"declarations
Profit:qexp
end-declarations...
exportprob(0, "", Profit)
exportprob(EP_MAX, "prob1", Profit)

Further information
This procedure overloads the exportprob subroutine of Mosel to handle quadratic objectivefunctions. It exports the current problem to a ﬁle, or if no ﬁle name is given (empty string ""), prints it
on screen. If the given ﬁlename has no extension, Mosel appends .lp to it for LP format ﬁles and .mat
for MPS format.
ModulemmquadFair Isaac Corporation Conﬁdential and Proprietary Information

361

mmquadgetsolPurpose
Synopsis

Get the solution value of a quadratic expression.
function getsol(q:qexp):realArgumentq

A quadratic expression

Return value
Solution value or 0.
Exampleuses "mmquad"declarations
x,y,z: mpvar
Profit:qexp
end-declarations...
! (Define and solve the problem)
writeln("Profit value: ", getsol(Profit))
writeln("Evaluation of an expression: ", getsol(x⁎y+5⁎z^2))
Further information
This function returns the evaluation of a given quadratic expression using the current (primal) solution
values of its variables. Note that the solution value of a variable is 0 if the problem has not been solvedor the variable is not contained in the problem that has been solved.
ModulemmquadFair Isaac Corporation Conﬁdential and Proprietary Information362

mmquad11.2

Published library functions
The module mmquad publishes some of its library functions via the service IMCI for use by othermodules (see the Mosel Native Interface Reference Manual for more detail about services). The list of
published functions is contained in the interface structure mmquad_imci that is deﬁned in the module
header ﬁle mmquad.h.
From another module, the context of mmquad and its communication interface can be obtained using
functions of the Mosel Native Interface as shown in the following example.
static XPRMnifct mm;
XPRMcontext mmctx;
XPRMdsolib dso;
mmquad_imci mq;
void ⁎⁎quadctx;
dso=mm->finddso("mmquad");/⁎ Retrieve the mmquad module⁎/
quadctx=⁎(mm->getdsoctx(mmctx, dso, (void ⁎⁎)(&mq)));/⁎ Get the module context and thecommunication interface of mmquad ⁎/Typically, a module calling functions that are provided by mmquad will include this module into its list of
dependencies in order to make sure that mmquad will be loaded by Mosel at the same time as thecalling module. The “dependency” service of the Mosel Native Interface has to be used to set the list of
module dependencies:

11.2.1static const char ⁎deplist[]={"mmquad",NULL};/⁎ Module dependency list ⁎/static XPRMdsoserv tabserv[]={{XPRM_SRV_DEPLST, (void ⁎)deplist}};/⁎ Table of services ⁎/Complete module example
If the Mosel procedures write / writeln are applied to a quadratic expression, they print the addressof the expression and not its contents (just the same would happen for types mpvar or linctr).
Especially for debugging purposes, it may be useful to be able to display some more detailed
information. The module example printed below deﬁnes the procedure printqexp that displays all theterms of a quadratic expression (for simplicity’s sake, we do not retrieve the model names for thevariables but simply print their addresses).
model "Test printqexp module"
uses "printqexp"
declarations
x: array(1..5) of mpvar
q: qexp
end-declarations
printqexp(10+x(1)⁎x(2)-3⁎x(3)^2)
q:= x(1)⁎(sum(i in 1..5) i⁎x(i))
printqexp(q)end-model

Note that in this model it is not necessary to load explicitly the mmquad module. This will be done by
the printqexp module because mmquad appears in its dependency list.
#include <stdlib.h>

Fair Isaac Corporation Conﬁdential and Proprietary Information363

mmquad#include "xprm_ni.h"#include "mmquad.h"/⁎⁎⁎⁎ Function prototypes ⁎⁎⁎⁎/
static int printqexp(XPRMcontext ctx,void ⁎libctx);/⁎⁎⁎⁎ Structures for passing info to Mosel ⁎⁎⁎⁎//⁎ Subroutines ⁎/static XPRMdsofct tabfct[]={{"printqexp", 1000, XPRM_TYP_NOT, 1, "|qexp|", printqexp}};
static const char ⁎deplist[]={"mmquad",NULL};/⁎ Module dependency list ⁎//⁎ Services ⁎/static XPRMdsoserv tabserv[]={{XPRM_SRV_DEPLST, (void ⁎)deplist}};/⁎ Interface structure ⁎/static XPRMdsointer dsointer={
0,NULL, sizeof(tabfct)/sizeof(XPRMdsofct),tabfct,
0,NULL, sizeof(tabserv)/sizeof(XPRMdsoserv),tabserv};/⁎⁎⁎⁎ Structures used by this module ⁎⁎⁎⁎/
static XPRMnifct mm;/⁎ For storing Mosel NI function table ⁎//⁎⁎⁎⁎ Initialize the module library just after loading it ⁎⁎⁎⁎/
DSO_INIT printqexp_init(XPRMnifct nifct, int ⁎interver,int ⁎libver, XPRMdsointer ⁎⁎interf){
mm=nifct;/⁎ Save the table of Mosel NI functions ⁎/⁎interver=MM_NIVERS;/⁎ Mosel NI version ⁎/⁎libver=MM_MKVER(0,0,1);/⁎ Module version ⁎/⁎interf=&dsointer;/⁎ Pass info about module contents to Mosel ⁎/return 0;}/⁎⁎⁎⁎ Implementation of "printqexp" ⁎⁎⁎⁎/
static int printqexp(XPRMcontext ctx, void ⁎libctx){
XPRMdsolib dso;
mmquad_imci mq;
mmquad_qexp q;
void ⁎⁎quadctx;
void ⁎prev;
XPRMmpvar v1,v2;
double coeff;
int nlin,i;
dso=mm->finddso("mmquad");/⁎ Retrieve reference to the mmquad module⁎/
quadctx=⁎(mm->getdsoctx(ctx, dso, (void ⁎⁎)(&mq)));/⁎ Get the module context and thecommunication interface of mmquad ⁎/q = XPRM_POP_REF(ctx);/⁎ Get the quadratic expression from the stack ⁎//⁎ Get the number of linear terms ⁎/mq->getqexpstat(ctx, quadctx, q, &nlin, NULL, NULL, NULL);/⁎ Get the first term (constant) ⁎/prev=mq->getqexpnextterm(ctx, quadctx, q, NULL, &v1, &v2, &coeff);
if(coeff!=0) mm->printf(ctx, "%g ", coeff);for(i=0;i<nlin;i++)/⁎ Print all linear terms ⁎/{Fair Isaac Corporation Conﬁdential and Proprietary Information364

mmquadprev=mq->getqexpnextterm(ctx, quadctx, q, prev, &v1, &v2, &coeff);
mm->printf(ctx,"%+g %p ", coeff, v2);}
while(prev!=NULL)/⁎ Print all quadratic terms ⁎/{prev=mq->getqexpnextterm(ctx, quadctx, q, prev, &v1, &v2, &coeff);
mm->printf(ctx,"%+g %p ⁎ %p ", coeff, v1, v2);}
mm->printf(ctx,"\n");return XPRM_RT_OK;}

11.2.2

Description of the library functions
clearqexpstat

Free the memory allocated by getqexpstat.

p. 368getqexpnextterm

Enumerate the terms of a quadratic expression.

p. 369getqexpsol

Evaluate a quadratic expression.

p. 366getqexpstat

Get information about a quadratic expression.

p. 367

Fair Isaac Corporation Conﬁdential and Proprietary Information365

mmquadgetqexpsol
Purpose
Synopsis

Return an evaluation of a quadratic expression based on the current solution.
double getqexpsol(XPRMctx ctx, void ⁎quadctx, mmquad_qexp q);

Arguments
ctx
Mosel’s execution context
quadctx Context of mmquadqReference to a quadratic expression
Return value
An evaluation of the expression on the current solution.
Further information
This function returns an evaluation of a quadratic expression based on last solution obtained from theoptimizer. This is the function called when using getsol on a quadratic expression from a Mosel
program.
ModulemmquadFair Isaac Corporation Conﬁdential and Proprietary Information366mmquadgetqexpstat
Purpose
Synopsis

Get information about a quadratic expression.
int getqexpstat(XPRMctx ctx, void ⁎quadctx, mmquad_qexp q, int ⁎nblin, int⁎nbqd, int ⁎changed, XPRMmpvar ⁎⁎lsvar);

Arguments
ctx
quadctx
q
nblin
nbqd
changedlsvar

Mosel’s execution context
Context of mmquad
Reference to a quadratic expression
Pointer to which the number of linear terms is returned (may be NULL)
Pointer to which the number of quadratic terms is returned (may be NULL)
Pointer to which the change ﬂag is returned (may be NULL). Possible values of this ﬂag:
1
The expression q has been modiﬁed since the last call to this function
0
Otherwise
Pointer to which is returned the table of variables that appear in the quadratic expression q(may be NULL)

Return value
Total number of terms in the expression.
Further information
This function returns in its arguments information about a given quadratic expression. Any of thesearguments may be NULL to indicate that the corresponding information is not required. The last entryof the table lsvar is NULL to indicate its end. This table is allocated by the module mmquad, it must
be freed by the next call to this function or with function clearqexpstat.
ModulemmquadFair Isaac Corporation Conﬁdential and Proprietary Information

367mmquadclearqexpstat
Purpose
Synopsis

Free the memory allocated by getqexpstat.
void clearqexpstat(XPRMctx ctx, void ⁎quadctx);

Arguments
ctx
Mosel’s execution context
quadctx Context of mmquad
Further information
A call to this function frees the table of variables that has previously been allocated by a call to function
getqexpstat.
Related topics
getqexpstat.
ModulemmquadFair Isaac Corporation Conﬁdential and Proprietary Information368mmquadgetqexpnextterm
Purpose
Synopsis

Enumerate the list of terms contained in a quadratic expression.
void ⁎getqexpnextterm(XPRMctx ctx, void ⁎quadctx, mmquad_qexp q, void
⁎prev, XPRMmpvar ⁎v1, XPRMmpvar ⁎v2, double ⁎coeff);

Arguments
ctx
quadctx
q
prev
v1,v2
coeff

Mosel’s execution context
Context of mmquad
Reference to a quadratic expression
Last value returned by this function. Should be NULL for the ﬁrst call
Pointers to return the decision variable references for the current term
Pointer to return the coefﬁcient of the current term

Return value
The value to be used as prev for the next call o NULL when all terms have been returned.
ExampleThe following displays the terms of a quadratic expression:
void dispqexp(XPRMcontext ctx, mmquad_qexp q){
void ⁎prev;
XPRMmpvar v1,v2;
double coeff;
int nlin,ct;
mq->getqexpstat(ctx, quadctx, q, &nlin, NULL, NULL, NULL);
ct=0;
prev=mq->getqexpnextterm(ctx, quadctx, q, NULL, &v1, &v2, &coeff);
mm->printf(ctx, "%g ", coeff);
while(prev!=NULL) {prev=mq->getqexpnextterm(ctx, quadctx, q, prev, &v1, &v2, &coeff);if(ct<nlin) { mm->printf(ctx,"%+g %p", coeff, v2); ct++; }else mm->printf(ctx,"%+g %p ⁎ %p", coeff, v1, v2);}
mm->printf(ctx,"\n");}Further information
This function can be called repeatedly to enumerate all terms of a quadratic expression. For the ﬁrst
call, the parameter prev must be NULL and the function returns the constant term of the quadratic
expression (for v1 and v2 the value NULL is returned and coeff contains the constant term). For thefollowing calls, the value of prev must be the last value returned by the function. The enumeration iscompleted when the function returns NULL.
If this function is called repeatedly, after the constant term it returns next all linear terms and then thequadratic terms.
ModulemmquadFair Isaac Corporation Conﬁdential and Proprietary Information

369

CHAPTER 12

mmrobust
The mmrobust module extends the Mosel language with new types for representing robust constraints
and describe the associated uncertainty sets. To use this module the following line must be included in
the header of the Mosel model ﬁle:uses 'mmrobust'

This is the reference manual of mmrobust. It is highly recommended to study the Xpress white paperon robust optimization found under docs/robust in the Xpress installation.
The ﬁrst section presents the new functionality for the Mosel language provided by mmrobust, namely
the new types uncertain, robustctr and uncertainctr and a set of subroutines that may be
applied to objects of these types.
The following sections give detailed documentation of the subroutines (other than mathematicaloperators) deﬁned by this module.

12.1

New functionality for the Mosel language

12.1.1The problem type mpproblem.xprs.robust
This module exposes its functionality through an extension to the mpproblem.xprs problem type. As
a consequence, all routines presented here are executed in the context of the current problem.

12.1.2The type uncertain
An uncertain is a quantity whose value is not known, but carries a level of uncertainty. The type
uncertain is used in the robust constraints of type robctr to express constraints that are subject touncertainty, and in uncertainctr constraints that describe the set of values that the uncertain cantake. The values of the uncertain quantity will take the possible worst case against the optimality andfeasibility of the problem. An uncertain can be intuitively thought of as a variable that is not under
our control, but which has a value deﬁned by an opponent to be the worst with respect to the model.
It is important to note that an uncertain does not have a default lower bound of zero imposed by
Mosel, in contrast to mpvars. This difference in default behavior is to reﬂect the most typical use
cases.
An uncertain can be assigned a nominal value using the assignement operator :=. The working of thenominal value is discussed in the Xpress robust optimization white paper found under docs/robust in
the Xpress installation.
The actual value of uncertains and robust constraints can be obtained after the solution of the robust
problem through getsol and getact. The usage of getsol is extended as explained below.

Fair Isaac Corporation Conﬁdential and Proprietary Information

370mmrobust

If an uncertain u is used in a single robust constraint or only in the objective function, then getsol(u)returns one of the possible realizations of the uncertainty set that induced the optimal solution foundby Mosel.
If the same uncertain is used in two robust constraints named RCon1 and RCon2 respectively, theoptimal solution of the problem may imply that the uncertain has different values for RCon1 andRCon2. Then its value can be obtained for the two constraints via the command getsol(u,RCon1)and getsol(u,RCon2).
Finally, the left-hand side of a robust constraint (e.g. RCon1) can simply be obtained via the command
getact(RCon1), whereas getsol(RCon1) returns the evaluation of left-hand side - right-hand side.

12.1.3

The type robustctr and its operators
The module mmrobust deﬁnes the type robustctr to represent robust constraints in the Mosel
Language. It also deﬁnes the standard arithmetic operations that are required for working with objectsof this type. By and large, these are the same operations as for linear expressions (type linctr of theMosel language) with additionally the possibility to include uncertain terms (i.e. of type uncertain).

12.1.4

The type uncertainctr and its operators
An uncertainty constraint uncertainctr describes the possible values of the uncertain data, or inother words deﬁnes the feasible set of the uncertains. Intuitively, if we visualize the role of anuncertain as a value under the control of an opponent, then the set of uncertainctrs deﬁnes thelimitations under which the opponent is operating when choosing the worst possible values in respectof the optimality and feasibility of the model.

12.1.5

Example: using mmrobust for solving a robust problem
Consider the following example
model BaseModel
uses "mmrobust";
declarations
x, y, z : mpvar
end-declarations
x + 2⁎y + 3⁎z <= 10
maximize(x+y+z)
writeln("x = ", getsol(x), "y = ", getsol(y), "z = ", getsol(z))

end-modelThis problem will solve to "x = 10 y = 0 z = 0".
Let us now assume that we only know that the sum of the ﬁrst two coefﬁcients is 3, and we need asolution that is valid for all realizations within this assumption.
model RobustModel
uses "mmrobust";
declarations
x, y, z : mpvar
u, v : uncertain
end-declarationsu⁎x + v⁎y + 3⁎z <= 10

Fair Isaac Corporation Conﬁdential and Proprietary Information

371

mmrobust

u+v <= 4
setparam("xprs_verbose", true)
maximize(x+y+z)
writeln("x = ", getsol(x), "y = ", getsol(y), "z = ", getsol(z), "; u = ", getsol(u), "end-modelThis problem will solve to "x = 2.5 y = 2.5 z = 0; u = 2 v = 2".
It is easy to check that any realization of the uncertains u and v will keep the solution vector feasible,
and that it is optimal within this assumption.

12.2

Control parameters
The following parameter is deﬁned by mmrobust:robust_check_feas_original_problem

Check if original, non-robust problem is feasible. p. 373

robust_check_feas_uncertainty_set

Check if uncertainty sets are non-empty.

p. 372robust_uncertain_overlap Use of uncertain data in multiple robust constraints.

p. 372robust_uncertain_overlap
Description

This parameter allows for models where more than one robust constraint can use an
uncertain. Because each robust constraint is dealt with independently in the robust
problem, the optimal solution implicitly may associate different values of the uncertain
quantities with each robust constraint.

Type

Boolean, read/write

Default value

false

Modulemmrobust

robust_check_feas_uncertainty_set
Description

This parameter allows for checking whether the uncertainty sets contain at least one feasible
vector of uncertains. In other words, with this parameter set to true Mosel will check if the
opponent actually has a choice of uncertains. If at least one uncertainty set is empty, awarning will be issued. Uncertainty sets should not be empty as otherwise a robust problem
cannot be created.

Type

Boolean, read/write

Default value

false

Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information372

v = ",

mmrobustrobust_check_feas_original_problem
Description

This parameter allows for checking whether the problem where all uncertains are set to theirdefault value is feasible or not. This is off by default but can be useful to check correctness of
one’s model without uncertainty before solving the robust problem.

Type

Boolean, read/write

Default value

false

Modulemmrobust

12.3

Procedures and functions
The module mmrobust overloads certain mathematical operators making possible the expression of
linear and quadratic expressions involving the type uncertain in order to create both robustctr anduncertainctr objects. Since these mathematical operators are fairly self-explanatory, we shallforego any more detailed documentation of these functions.
The following list gives an overview of all other functions and procedures deﬁned by mmrobust for
which we give detailed descriptions later.
cardinality

Create a cardinality uncertain constraint.

p. 374getact

Get the activity value of a robust constraint.

p. 376

getnominal

Get the nominal value of an uncertain.

p. 380

getsolGet the realisation of an uncertain or robust constraint.

p. 375gettypeGet the type of a constraint.

p. 381

ishidden

Test whether a constraint is hidden.

p. 377

scenario

Create a scenario uncertain constraint.

p. 378sethidden

Hide or unhide a constraint.

p. 379setnominal

Set the nominal value of an uncertain.

p. 382

settypeSet the type of a constraint.

p. 383

Fair Isaac Corporation Conﬁdential and Proprietary Information

373

mmrobustcardinality
Purpose
SynopsisCreate a cardinality uncertain constraint.
function cardinality(su:set of uncertain,m:integer):uncertainctr

Argumentssum

Uncertains to be added to the constraint
Maximum number of uncertains that can be different from their nominal value

Return value
The new cardinality uncertain constraint.
Further information
A cardinality unertain constraint limits the number of unceratins that can take a non-zero value, or bedifferent from their nominal value.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

374

mmrobust

getsolPurpose
Synopsis

Get the realisation of an uncertain or robust constraint.
function getsol(u:uncertain, rc:robustctr):realfunction getsol(u:uncertain):realfunction getsol(rc:robustctr):realArgumentsrcu

A robust constraint
An uncertain

Return value
Solution value or 0.
Further information
This function returns the realization of uncertain u for the robust optimization problem solved. The
value of u is only available after solving the robust optimization problem. The value of u is 0 if the
problem has not been solved or the uncertain or constraint is not contained in the problem that has
been solved.
If the uncertain u appears in more than one constraint, it is necessary to specify the constraint withfunction call getsol(u,rc): this is a consequence of robust optimization, for which the same
uncertain can assume different values in different constraints. If the uncertain u only appears in one
constraint, then it sufﬁces to call getsol(u).
The function getsol(rc) returns the evaluation of a constraint with the current realization of thesolution and the uncertains. Therefore, if a constraint is of the form u⁎x + v⁎y + z ≤ 3 andx,y,zare variables while u,v are uncertains, the current realization of x,y,z,u,v will be used toreturn u⁎x + v⁎y + z - 3.
Note that robust equality constraints (for instance, u⁎x + v⁎y + z = 3) have a special status in
Mosel. The value of uncertains u and v is, in general, related to an inequality constraint and can besafely obtained in this case only. In order to use getsol for equality robust constraints as well, it would
be best to decompose these constraints into two inequality constraints (i.e. u⁎x + v⁎y + z ≤ 3
and u⁎x + v⁎y + z ≥ 3) and then request u and v from each of the two constraints. Note that both
uncertains might differ in value when requested from either inequality constraint.
Related topics
getact.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

375

mmrobust

getactPurpose
Synopsis

Get the activity value of a robust constraint.
function getact(rc:robustctr):realArgumentrc

A robust constraint

Return value
Solution value or 0.
Further information
This function returns returns the value of the left-hand side of a constraint with the current realizationof the solution and the uncertains. Therefore, if a constraint is of the form u⁎x + v⁎y + z ≤ 3 andx,y,zare variables while u,v are uncertains, the current realization of x,y,z,u,v will be used toreturn u⁎x + v⁎y + z.
Note that robust equality constraints (for instance, u⁎x + v⁎y + z = 3) have a special status in
Mosel. The value of uncertains u and v is, in general, related to an inequality constraint and can besafely obtained in this case only. In order to use getact for equality robust constraints as well, it would
be best to decompose these constraints into two inequality constraints (i.e. u⁎x + v⁎y + z ≤ 3
and u⁎x + v⁎y + z ≥ 3) and then request u and v from each of the two constraints. Note that both
uncertains might differ in value when requested from either inequality constraint.
Related topics
getsol.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

376

mmrobustishiddenPurpose
Synopsis

Test whether a constraint is hidden.
function ishidden(rc:robustctr):booleanfunction ishidden(uc:uncertainctr):boolean

Argumentsrc
uc

A robust constraint
An uncertain constraint

Return value
true if the constraint is hidden, false otherwise.
Further information
This function tests the current status of a constraint. At its creation a constraint is added to the current
problem, but using the function sethidden it may be hidden. This means, the constraint will not be
contained in the problem that is solved by the solver but it is not deleted from the deﬁnition of the
problem in Mosel.
Related topics
sethidden.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

377

mmrobust

scenario
Purpose
SynopsisCreate a scenario uncertain constraint.
function scenario(data:array (range,set of uncertain) of real):uncertainctr

Argument
data

Scenario data

Return value
The new scenario uncertain constraint.
Further information
A scenario uncertain constraint takes historical data of the possible realizations of the uncertain
data. In effect, the introduced uncertain constraint enforced that for any solution to the robust
optimization problem, any robust constraint robustctr is satisﬁed for all realizations of theuncertains as deﬁned by the data array.
This function stores a reference to the provided array (i.e. it does not make a copy of it). As aconsequence any modiﬁcation to the array will imply modiﬁcations to the constraint even after theconstraint has been built. Invalid data is only reported at the time of loading the problem into the
optimiser.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

378

mmrobust

sethidden
Purpose
Synopsis

Hide or unhide a constraint.
procedure sethidden(rc:robustctr, b:boolean)
procedure sethidden(uc:uncertainctr, b:boolean)

Argumentsrcucb

A robust constraint
An uncertain constraint
Constraint status:
true
Hide the constraint
false
Unhide the constraint

Further information
At its creation a constraint is added to the current problem, but using this procedure it may be hidden.
This means that the constraint will not be contained in the problem that is solved by the solver but it is
not deleted from the deﬁnition of the problem in Mosel. Function ishidden can be used to test thecurrent status of a constraint.
Related topics
ishidden.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

379

mmrobust

getnominal
Purpose
Synopsis

Get the nominal value of an uncertain.
function getnominal(u:uncertain):realArgumentu

An uncertain

Return value
The nominal value of the uncertain
Related topics
setnominal.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

380

mmrobust

gettype
Purpose
Synopsis

Get the type of a constraint.
function gettype(rc:robustctr):integerfunction gettype(uc:uncertainctr):integer

Argumentsrc
uc

A robust constraint
An uncertain constraint

Return value
Constraint type. Applicable values for nonlinear constraints are:
CT_EQ
Equality, ‘=’
CT_GEQ Greater than or equal to, ‘ ≥ ’
CT_LEQ Less than or equal to, ‘ ≤ ’
CT_CARD Cardinality
CT_SCEN Scenario
CT_UNB Non-binding constraint, i.e. free
Related topics
settype.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

381

mmrobust

setnominal
Purpose
Synopsis

Set the nominal value of an uncertain.
procedure setnominal(u:uncertain,n:real)

Argumentsun

An uncertain
A real constant

Further information
Calling this procedure has the same effect as assigning a value to the uncertain using the operator :=.
Related topics
getnominal.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

382

mmrobust

settype
Purpose
Synopsis

Set the type of a constraint.
procedure settype(rc:robustctr, type:integer)
procedure settype(uc:uncertainctr, type:integer)

Arguments
rc
uc
type

A robust constraint
An uncertain constraint
Constraint type. Applicable values are:
CT_EQ
CT_GEQ
CT_LEQ
CT_UNB

Equality, ‘=’Greater than or equal to, ‘ ≥ ’Less than or equal to, ‘ ≤ ’
Non-binding constraint

Further information
This procedure can be used to change the type of a constraint, turning it into an equality or inequality or
making it unbounded, i.e. free.
Related topics
gettype.
Modulemmrobust

Fair Isaac Corporation Conﬁdential and Proprietary Information

383

CHAPTER 13

mmsheetThe Mosel module mmsheet implements several I/O drivers for accessing and modifying spreadsheetﬁles in different formats from ‘initializations’ blocks. The I/O drivers rely on different technologies foraccessing spreadsheets.

13.1

I/O drivers
The I/O drivers provided by mmsheet are all designed to be used in ‘initializations’ blocks and expect
the same type of information regarding ﬁle names and record references. The common form of a ﬁlespeciﬁcation for all the mmsheet drivers is:
mmsheet.⁎:[noindex|partndx|autondx[=#];][grow;][skiph;][emptyndx;][bufsize=#;]filename

The spreadsheet ﬁle name must be a physical ﬁle (with its extension), except for the "csv:" driver that
accepts extended ﬁle names. The driver options (stated before the ﬁle name) shared by all mmsheet
drivers are:noindex

Indicates that only data (no indices) are transferred between the spreadsheet andMosel. By default, the ﬁrst columns of each table are interpreted as index values for thearray to be transferred. This behaviour is changed by this option.

partndx

Indicates that the ﬁrst nbdim-1 columns are interpreted as indices (nbdim being thenumber of dimensions of the array to process) and remaining ones are used as data forthe last dimension.

autondx[=st] Indices are not read or written but automatically generated from the line number(this option only applies to 1-dimension arrays indiced by ranges). By default the ﬁrst
index has value 1 but a different value st may be stated.
grow

When writing data, the driver uses the provided range ignoring the end of the data if
there is not enough space. When this option is speciﬁed, the driver extends the range byadding lines if necessary.

skiphWith this option, the driver skips the ﬁrst line (or header) of the provided range. If therange contains only one line, the following line is selected.

emptyndx

When reading array indices an empty cell causes a failure. With this option empty cells
are replaced by the default value of the corresponding type (e.g. 0 for a numerical value)bufsize=c

To set the size of the data buffer in kilobytes (default c=2).

Fair Isaac Corporation Conﬁdential and Proprietary Information

384

mmsheet

The driver-speciﬁc options are documented separately for each driver in the following sections.
In the initializations block, each label entry is understood as a range in the workbook: named ranges are
represented by their name (e.g. "MyRange") and explicit ranges are noted using square brackets (e.g.
"[sheet1$a1:c2]"). For explicit ranges, the sheet is identiﬁed by its name or number and separated
from the cell selection with the $ sign. The ﬁrst sheet of the workbook is selected if no indication is
given. Similarly, the used cells of the selected sheet are assumed if no selection is provided. The cellselection can be stated either using the usual format with a letter to select the column followed by aline number (e.g. "a1:c1") or by specifying row and column numbers by preﬁxing the row number by
the letter "R" and the column number by the letter "C" (e.g. "R1C1:R1C3"). It is also possible toselect some of the columns from the speciﬁed range: this can be done either with a list of names or alist of column numbers (relative to the beginning of the range) noted in parentheses after the range
description. To use names, the option skiph must be used and the column names are taken from theheader row that is skipped through this option. When using skiph, column numbers need to be statedby preﬁxing the column number by #. Note that, before the range selection, one can add options as forthe ﬁle opening. For instance, "skiph;grow;" can be used for writing data to a named range
formatted for an ODBC connection.
In addition to the above options a label may consist in the string "rangesize;" followed by a range
speciﬁcation (e.g. "rangesize;[]"), this special label can only be used to populate a list of integers
that receives the size of the range in the form of 2 integers (number of lines and number of columns).
Example:initializations from "mmsheet.excel:skiph;auction.xls"
NWeeks as "[b1:d12]"! Initialize `NWeeks' with data in b2:d12
BPROF as "noindex;BPROFILE"! Initialize `BPROF' with named range `BPROFILE'! all columns being data (no indices)
mycols as "[b1:h12](3,5,7)"! Initialize `mycols' with columns d2:d12,! f2:f12 and h2:h12
mycol2 as "[b1:h12](nam1,#5,nam3)"! Initialize `mycol2' with the column named! 'nam1', the column f2:f12 and the column! named 'nam3'
end-initializations

The mapping between the selected cells of the workbook and the Mosel data structures is similar tothe one used for databases (options noindex and partndx correspond to setting parameter
mmodbc.SQLndxcol to false): refer to the section Data transfer between Mosel and the database of
the mmodbc chapter for further explanation.
Although direct read and write operations are not supported by these drivers, a spreadsheet may be
open using fopen: this allows to keep the document open across several ’initializations’ blocks andavoid the cost of loading and unloading the ﬁle (that may be expensive particularly with the "excel:"driver).
Cells of a spreadsheet are implicitly typed as either numbers, booleans or text strings. When getting thevalue of a cell the driver may have to perform a type conversion: the conversion from a number to its
textual representation relies on the real format "realfmt" (see setparam) that may have to bechanged when using a driver of this module. For instance the number 1234567 will be converted to thetext string 1.23457e+06 with the default real format ("%g"). To preserve the integer representation ofsuch a cell it is required to use "%.10g" as the real format.
For further examples of working with databases and spreadsheets, the reader is referred to the Xpress
whitepaper Using ODBC and other database interfaces with Mosel.

13.1.1

Driver excel
mmsheet.excel:[noindex|partndx;][grow;][skiph;][emptyndx;][newxl;][bufsize=#;]filename

Fair Isaac Corporation Conﬁdential and Proprietary Information

385

mmsheetThis driver uses directly the application Excel for accessing the ﬁle (relying on COM/OLE as thecommunication channel): as a consequence it is available only under the Windows platform andrequires Excel to be installed on the host executing the Mosel model. All ﬁle formats handled by theversion of Excel can be used but this driver does not support creation of new ﬁles (i.e. it can only
modify existing ﬁles). In addition to the options described in the introductory section, the option newxl
may be used: by default the driver does not open the ﬁle if it can ﬁnd a running instance of Excel having
the required ﬁle open: it works directly with the application and modiﬁcations made to the workbook arenot saved when the ﬁle is closed in Mosel. If this option is speciﬁed a new instance of Excel is started
in all cases and the workbook is saved before quitting the application when the ﬁle is closed in Mosel.

13.1.2

Driver xls/xlsx
mmsheet.xls:[noindex|partndx|autondx[=#];][grow;][skiph[+];][emptyndx;][bufsize=#;]filename
mmsheet.xlsx:[noindex|partndx|autondx[=#];][grow;][skiph[+];][emptyndx;][bufsize=#;]filename

These two drivers rely on the libxl library to access the spreadsheet ﬁle: they are available on the
Windows, Linux and MacOS platforms and do not require any additional software. The ﬁrst driver
handles xls ﬁles while the second deals with xlsx and xlsm format Excel ﬁles. These drivers can beused to create new ﬁles: when used for writing (through an ‘initializations to’ block) non-existing sheets
are automatically added to the workbook and the ﬁle is created if necessary. When the option skiph+
is used instead of skiph when writing to a ﬁle, the necessary header row is created if this row is empty(this option behaves like skiph when reading a ﬁle and when no column name is provided).

13.1.3

Driver csv

mmsheet.csv:[noindex|partndx|autondx[=#];][alltxt;][grow;][skiph[+];][emptyndx;][bufsize=#;][fsep=c;This driver works on spreadsheets saved in ascii CSV format (Comma Separated Values). It is available
on all platforms that are supported by Mosel and can open or create ﬁles using extended format ﬁlenames (i.e. combining several I/O drivers). A CSV ﬁle contains a single sheet (number 1 identiﬁed as"Sheet1") and does not support named ranges, that is, cell references must use the explicit notation.
When the option skiph+ is used instead of skiph when writing to a ﬁle, the necessary header row iscreated if this row is empty (this option behaves like skiph when reading a ﬁle and when no column
name is provided). The following driver-speciﬁc options may be used to specify the properties of theformat to handle:
alltxtby default the driver tries to guess the type of the cells while reading the document(cells can be either numbers, booleans or text strings). When this option is used all cells
are recorded as text strings

dsep=ccharacter used as decimal separator (default: ".")

fsep=ccharacter used to separate ﬁelds. The default value is ","; tabulation or ";" are also
often employed

dsep=ccharacter used as decimal separator (default: ".")

true=stext representing the true value of a Boolean (default: "true")false=stext representing the false value of a Boolean (default: "false")

For example, the following statements will read data from a ﬁle formatted for the French language andthat has been compressed with gzip:

Fair Isaac Corporation Conﬁdential and Proprietary Information

386

mmsheetinitializations from "mmsheet.csv:fsep=;;dsep=,;true=vrai;false=faux;zlib.gzip:mydata.csv.gz"
A as "[a1:c12]"
end-initializations

The csv driver supports the getfsize function applied to a ﬁle already loaded into memory: it reports
the amount of memory currently allocated for the corresponding document. For instance the following
displays the memory used by "mydata.csv":
fopen("mmsheet.csv:mydata.csv",F_INPUT)
writeln(getfsize("mmsheet.csv:mydata.csv"))
fclose(F_INPUT)

Fair Isaac Corporation Conﬁdential and Proprietary Information

387

CHAPTER 14

mmssl
The Mosel module mmssl is an interface to the OpenSSL cryptographic library(http://www.openssl.org). It brings most of the functionality of this library to the Mosel language andserves as the cryptographic component in other parts of Mosel. In particular, it provides support for the
HTTPS protocol in mmhttp and implements the encryption and signing mechanisms used by the Mosel
core libraries when secure BIM ﬁles are used.

14.1

Overview

14.1.1Document encryption in Mosel
Encryption and decryption of documents are achieved by cipher algorithms. Ciphers can be of two
kinds: symmetric ciphers use the same encryption key to perform the encryption and decryption tasks
while asymmetric ciphers require one key to execute the encryption and another one for the decryption.
In mmssl, symmetric ciphers are made available through the crypt I/O driver (Section 14.4.3): theencryption key (the size of which depends on the cipher) is automatically generated based on somegiven passphrase (either input from an external ﬁle or directly in the ﬁle name speciﬁcation). The
implementation of the crypt driver allows the user to select which speciﬁc cipher algorithm it shoulduse (for instance AES, DES or IDEA).
For asymmetric encryption, mmssl relies on the RSA cryptographic system. For the RSA algorithm, a key(RSAgenkey) consists of two components: a public part that is usually distributed to the individuals
with whom documents are to be exchanged and a private part that must be kept secret by the owner of
the key (this private key also includes the public key). In this framework, a document encrypted using apublic key (RSApubencrypt) can only be decrypted with the corresponding private key(RSAprivdecrypt). Moreover, the key pair can also be used for signing documents: the electronic
signature of a document is created with a private key (msgsign) and the corresponding public key isused to verify this signature (msgverify). Since only the owner of the private key can create thesignature, the recipient has a guarantee on the origin of the document.
RSA keys are commonly stored as text ﬁles in the OpenSSL PEM standard format, this is also the mostconvenient representation for exchanging key information (RSAsavekey). In addition to this ﬁleformat, mmssl can store a key in the form of a Mosel array of integers (RSAloadkey). By using thisencoding a model may embbed keys or retrieve them from any of the usual model data sources.

14.1.2The mmssl command
The module mmssl is distributed together with a command line tool of the same name as the module:
mmssl. This program helps setting up an initial working environment and performs basic key andcertiﬁcate operations directly from a shell (Unix) or command window (Windows). Running the mmssl
program without any arguments will display a short help message, otherwise the following commands
can be used:

Fair Isaac Corporation Conﬁdential and Proprietary Information

388

mmsslsetup
Check the conﬁguration directory of mmssl and create it if necessary (see parameter
ssl_dir)
genkey keyfile [size]
Generate a new RSA key pair of the speciﬁed size (default: 1024) and save it into keyfile.
getpub keyfile keyfilepub
Extract the public key of the private RSA key ﬁle keyfile and save it into keyfilepub
chkkey keyfile [keyfile...]Check the validity of the provided key ﬁle(s)gencert certfile [prod=value...]Generate an X509 certiﬁcate using the provided properties (see x509newcrt for further
detail)chkcert certfile [keyfile]
Check the validity of the provided X509 certiﬁcate. If an additional private key ﬁle is provided,
its compatibility with the certiﬁcate is also checked.
list [digest|cipher]
Display the list of supported message digests (digest) or cipher algorithms (cipher). Bothlists are reported with the short form of the command.
Many procedures of the mmssl module require the availability of a conﬁguration directory. To create
and populate an initial setup it is recommended to run the following command before starting to use
the module:> mmssl setup

Note that the setup procedure is not destructive: if the conﬁguration directory has already been createdthe command will only check its validity, add any missing components and suggest how to proceed incase of incorrect settings.

14.2

Control parameters
Via the getparam function and the setparam procedure it is possible to access the following control
parameters of module mmssl (the reader is reminded that parameters may be spelled with lower orupper case letters or a mix of both):
https_cacerts

List of trusted certiﬁcation authorities.

p. 390https_ciphers

Ciphers accepted for SSL communication.

p. 390https_cltcrt

HTTPS client certiﬁcate.

p. 390https_cltkey

HTTPS client private key.

p. 391

https_srvcrt

HTTPS server certiﬁcate.

p. 391

https_srvkey

HTTPS server private key.

p. 391

https_trustsrv

Whether to trust server certiﬁcates.

p. 392

ssl_cipher

Default symmetric cipher.

p. 392

ssl_digest

Default message digest algorithm.

p. 392

ssl_dir

mmssl conﬁguration directory.

p. 393

ssl_privkey

Default user private key.

p. 394

Fair Isaac Corporation Conﬁdential and Proprietary Information389

mmsslhttps_cacerts
Description

Location of the ﬁle containing the certiﬁcates of the trusted certiﬁcation authorities.

Type

String, read/writeNote

The ﬁle identiﬁed by this parameter consists of a list of certiﬁcates (in PEM format) of trusted
certiﬁcation authorities (in order to be able to check the validity of servers they have certiﬁed)
and certiﬁcates of servers trusted by the application (typically using self-signed certiﬁcatesthat could not be certiﬁed by an external authority, see x509newcrt). This ﬁle is used when
HTTPS client connections are established to check the identity of the server unless thecontrol parameter https_trustsrv is set to true. It is also required by servers that
perform client authentication (see option HTTP_CLTAUTH of server conﬁguration
http_srvconfig): in this case the certiﬁcates are used to identify the clients.
When this parameter has not been initialised, the default location
getparam("ssl_dir")+"/ca-bundle.crt" is used. This default ﬁle collecting thecertiﬁcates of the major certiﬁcation authorities is installed by the mmssl setup command(Section 14.1.2).

Affects routines

httpget, httppost, httpdel, httpput, httpstartsrv

See also

https_trustsrv

Modulemmssl

https_ciphers
Description

This parameter is used during the algorithm negociation of an HTTPS session initialisation to
select which cryptographic algorithm to use.

Type

String, read/write

Default value"TLSv1.2+HIGH:TLSv1+HIGH:@STRENGTH"

Note

This parameter is employed by both the server and the client in an HTTPS session. Pleaserefer to the OpenSSL documentation for a detailed explanation on how to build this selection
string.

Affects routines

httpstartsrv, httpget, httppost, httpdel, httpput

Modulemmssl

https_cltcrt
Description

Location of the client certiﬁcate (for HTTPS queries).

Type

String, read/write

Note

This parameter speciﬁes the location of the client certiﬁcate (that must be in PEM format).
Such a certiﬁcate (and its associated private key https_cltkey) is required when sending
HTTPS requests to a server that requires client authentication (see option HTTP_CLTAUTH ofserver conﬁguration http_srvconfig).

Fair Isaac Corporation Conﬁdential and Proprietary Information

390

mmsslAffects routines

httpget, httppost, httpdel, httpput

See also

https_cltkey

Modulemmssl

https_cltkey
Description

Location of the client private key (for HTTPS queries).

Type

String, read/write

Note

This parameter speciﬁes the location of the client private key. Such a key (and its associatedcertiﬁcate https_cltcrt) is required when sending HTTPS requests to a server that
requires client authentication (see option HTTP_CLTAUTH of server conﬁguration
http_srvconfig).

Affects routines

httpget, httppost, httpdel, httpput

See also

https_cltcrt

Modulemmssl

https_srvcrt
Description

Location of the server certiﬁcate (required by an HTTPS server).

Type

String, read/write

Note

Running an HTTPS server requires a server certiﬁcate and its associated private key. Thisparameter deﬁnes the location of the certiﬁcate ﬁle (in PEM format); to create a certiﬁcate
you can either use the mmssl command (Section 14.1.2) or the Mosel function x509newcrt.
If no value has been assigned to this parameter the default certiﬁcate ﬁlegetparam("ssl_dir")+"/server.crt" will be used by the server.

Affects routines

httpstartsrv

See also

https_srvkey

Modulemmssl

https_srvkey
Description

Location of the server private key (required by an HTTPS server).

Type

String, read/write

Note

Running an HTTPS server requires a server certiﬁcate and its associated private key. Thisparameter deﬁnes the location of the private key ﬁle; to create a certiﬁcate use either themmssl command (Section 14.1.2) or the function x509newcrt). If no value has been
assigned to this parameter the default key ﬁle getparam("ssl_dir")+"/server.key"
will be used by the server.

Fair Isaac Corporation Conﬁdential and Proprietary Information

391

mmsslAffects routines

httpstartsrv

See also

https_srvcrt

Modulemmssl

https_trustsrv
Description

This parameter decides whether the HTTPS client should trust servers without checking theircertiﬁcates.

Type

Boolean, read/write

Default value

false

Note

When this parameter is false (the default) whenever an HTTPS connection is opened (via
httpget for instance) the authenticity of the remote server is checked using the list oftrusted certiﬁcation authorities (as deﬁned by the control parameter https_cacerts) andthe operation is aborted if the veriﬁcation fails. Changing the value of this parameter disables
this test.

Affects routines

httpget, httppost, httpdel, httpput

See also

https_cacerts

Modulemmssl

ssl_cipher
Description

Name of symmetric cipher to use when no algorithm is speciﬁed.

TypeString, read/write

Default value"AES-128-CBC"

Note

This parameter deﬁnes the default symmetric cipher used by the crypt I/O driver. The name ofa cipher consists in up to 3 components separated by the "-" symbol: the algorithm name(e.g. aes, bf, des), the key size (when the algorithm may be used with different sizes of keys)
and the block chaining mode (e.g. cbc, cfb1, cfb8, ecb, ofb). For instance, "des-ofb"designates DES with Output Feedback chaining.
Use the command mmssl list cipher to get a full list of the supported cipher names.

Affects routines

I/O driver "crypt:" (Section 14.4.3)

Modulemmssl

ssl_digest
Description

Name of message digest to use when no algorithm is speciﬁed.

TypeString, read/write

Fair Isaac Corporation Conﬁdential and Proprietary Information

392

mmsslDefault value"SHA256"

Note

This parameter deﬁnes the default message digest algorithm used by the crypt I/O driver,
msgdigest, msgsign and msgverify.
Use the command mmssl list digest to get a full list of the supported names.

Affects routines

msgdigest, msgsign, msgverify, I/O driver "crypt:" (Section 14.4.3)

Modulemmssl

ssl_dir
Description

This parameter is the path to the conﬁguration directory of mmssl. Its content is used by boththe mmssl routines and the Mosel core libraries for handling signed and encrypted bim ﬁles.

Type

String, read only

Note

By default this location is the path "$HOME/.mmssl" (on Unix systems) or"%USERPROFILE%\.mmssl" (on Windows). Assuming the active restrictions do not preventthe operation, this directory will be created if it does not exist at the time of loading themodule. It is also possible to select a different location by deﬁning the environment variable
MOSEL_SSL (in this case, the directory is not automatically created and must be available atloading time).
The conﬁguration directory should contain the following entries:
personal.key

RSA private key of the user: it is used for signing documents to be
published and for decrypting documents that have been encrypted withthe corresponding public key.

personal

RSA public key of the user: to be provided with documents signed withpersonal.key such that recipients can check the signature. The
public key is also used to encrypt documents to be decrypted withpersonal.key.

pubkeyspublic keys repository: this directory is the default location where publickeys are searched for checking the signature of a document.

ca-bundle.crt

trusted certiﬁcates ﬁle: mmhttp uses this ﬁle when checking
authenticity of servers (HTTPS client) or clients (HTTPS server).

server.crt

HTTPS server certiﬁcate: this ﬁle is required by the HTTPS server ofmmhttp together with the corresponding private key.

server.key

HTTPS server private key: this ﬁle is required by the HTTPS server ofmmhttp together with the corresponding certiﬁcate.

The program mmssl can be used to create and populate this directory (Section 14.1.2).
Even if Mosel is run under restrictions, mmssl can still access its conﬁguration directory forgetting public keys stored under the pubkeys directory, read the ﬁle of trusted certiﬁcatesca-bundle.crt and load the private key personal.key to decrypt a document. However,
the module requires explicit read access to use the private key personal.key for signingtasks and load the HTTPS server conﬁguration (ﬁles server.key and server.crt).
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

393

mmsslssl_privkey
Description

Name of the ﬁle holding the user’s private key.

Type

String, read/writeNote

The key identiﬁed by this parameter is used when a required private key is not provided.
If no value has been assigned to this parameter the default key ﬁlegetparam("ssl_dir")+"/personal.key" will be used.

Affects routines

msgsign, x509newcrt, RSAprivdecrypt, BIM ﬁle signing and encryption

Module

mmssl

14.3

Procedures and functions
msgdigest

Compute the message digest of a document.

p. 405

msgsignCompute the digital signature of a document.

p. 406

msgverify

Verify the digital signature of a document.

p. 407

RSAfingerprint

Generate the ﬁngerprint of an RSA key.

p. 395

RSAgenkey

Create a new RSA key pair.

p. 396

RSAgetkeysize

Get the size of an RSA key.

p. 397

RSAisprivate

Check whether an RSA key is private.

p. 398

RSAloadkey

Load an RSA key ﬁle into memory.

p. 399

RSAprivdecrypt

Decrypt a document using an RSA private key.

p. 401

RSAprivencrypt

Encrypt a document using an RSA private key.

p. 402

RSApubdecrypt

Decrypt a document using an RSA public key.

p. 400

RSApubencrypt

Encrypt a document using an RSA public key.

p. 403

RSAsavekey

Save an RSA key to a ﬁle.

p. 404sslivsize

Get the size of the initialisation vector of a cipher.

p. 408sslkeysize

Get the size of the key required by a symmetric cipher.

p. 409sslmdsize

Get the size of a message digest.

p. 410sslrandom

Generate a random number.

p. 411

sslrandomdata

Generate a random data ﬁle.

p. 412x509check

Check the compatibility of a private key with an X509 certiﬁcate.

p. 413x509getinfo

Retrieve information stored in an X509 certiﬁcate.

p. 414x509newcrt

Create a new self-signed X509 certiﬁcate.

p. 415

Fair Isaac Corporation Conﬁdential and Proprietary Information394

mmssl

RSAﬁngerprint
Purpose
Synopsis

Generate the ﬁngerprint of an RSA key.
function RSAfingerprint(key:array(range) of integer):text
function RSAfingerprint(key:array(range) of integer, mdalg:string):text
function RSAfingerprint(kfile:string):text

Arguments
key
RSA key in the form of an array of integer
kfile File containing the key
mdalg Name of the digest algorithm to use (default: MD5)Return value
Fingerprint as a text string of hexadecimal digits.
Further information
1. By default mmssl uses an MD5 hash of the public part of the RSA key as its ﬁngerprint. Unless anotherdigest algorithm is selected, the return value of this function is therefore a text string of 32 hexadecimal
digits that characterises a given key.
2. The function can process both public and private keys either directly from a key ﬁle or from an array ofintegers (as produced by RSAloadkey or RSAgenkey).
Related topics
RSAloadkey
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

395

mmsslRSAgenkey
Purpose
SynopsisCreate a new RSA key pair.
function RSAgenkey(size:integer, key:array(range) of integer):integerfunction RSAgenkey(size:integer, kfile:string):integer

Arguments
size Size of the key to generate (in bits, must be at least 1024)
key
Array to store the new key
kfile File where to save the key
Return value
Number of integers (ﬁrst syntax) or size of the ﬁle (second syntax) or -1 in case of I/O error and -2 if
the provided array is not suitable to store the key.
Further information
1. The generated key can be retrieved either as an array of integers or directly saved into a ﬁle. In bothcases, the public key may be extracted using RSAsavekey.
2. The function creates keys of at least 1024 bits: a request for a key of a smaller size will result in a 1024
bits key.
Related topics
RSAloadkey, RSAsavekey
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

396

mmsslRSAgetkeysize
Purpose
Synopsis

Get the size of an RSA key.
function RSAgetkeysize(key:array(range) of integer):integerfunction RSAgetkeysize(kfile:string, ispriv:boolean):integer

Arguments
key
RSA key in the form of an array of integer
kfile File containing the key
ispriv Must be true if the key ﬁle contains a private key
Return value
Size of the key (number of bits) or -1 in case of an error.
Further information
A return value of -1 indicates an error condition. Typically this will occur if the ﬁle cannot be accessed or
the ispriv parameter is not correct (e.g. ispriv is true and the ﬁle is a public key).
Related topics
RSAisprivate, RSAloadkey
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

397

mmsslRSAisprivate
Purpose
SynopsisCheck whether an RSA key is private.
function RSAisprivate(key:array(range) of integer):booleanfunction RSAisprivate(kfile:string):boolean

Arguments
key
RSA key in the form of an array of integer
kfile File containing the key
Return value
true if the key is an RSA private key, false otherwise.
Further information
A return value of false does not necessarily indicate that the provided data corresponds to a valid
public key: this value is also returned in the case of an I/O error (e.g. the ﬁle does not exist).
Related topics
RSAloadkey
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

398

mmssl

RSAloadkey
Purpose
Synopsis

Load an RSA key ﬁle into memory.
function RSAloadkey(key:array(range) of integer, kfile:string,
ispriv:boolean):integerfunction RSAloadkey(key:array(range) of integer, kfile:string):integer

Arguments
key
RSA key in the form of an array of integer
kfile File containing the key
ispriv Must be true if the key ﬁle contains a private key
Return value
The number of integers saved into the array, or -1 in the case of an I/O error, or -2 if the provided arrayis not suitable to store the key.
Further information
If the ispriv parameter is not provided, the function calls ﬁrst RSAisprivate to determine its value.
Related topics
RSAsavekey
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information399

mmssl

RSApubdecrypt
Purpose
Synopsis

Decrypt a document using an RSA public key.
function RSApubdecrypt(kfile:string, src:string, dest:string):integer

Arguments
kfile File containing the public key
src
Name of the ﬁle to decryptdst
Name of the ﬁle to store the decrypted document
Return value
Length of the resulting document or -1 in the case of an error.
Further information
1. This function is used to decrypt a document that has been encrypted using RSAprivencrypt. It
requires the public part of the key used for encryption.
2. If the key ﬁle name does not include an explicit path (e.g."somekey"), it is searched for in the default
public keys directory located at getparam("ssl_dir")+"/pubkeys" instead of the current working
directory. It is required to preﬁx the key ﬁle name with "./" in order to access a key ﬁle from thecurrent directory (e.g."./somekey").
Related topics
RSAprivencrypt, msgverify
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

400

mmsslRSAprivdecrypt
Purpose
Synopsis

Decrypt a document using an RSA private key.
function RSAprivdecrypt(kfile:string, src:string, dest:string):integer

Arguments
kfile File containing the private key
src
Name of the ﬁle to decryptdst
Name of the ﬁle to store the decrypted document
Return value
Length of the resulting document or -1 in the case of an error.
Further information
This function is used to decrypt a document that has been encrypted using RSApubencrypt. It
requires the private part of the key used for encryption.
Related topics
RSApubencrypt
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

401mmsslRSAprivencrypt
Purpose
Synopsis

Encrypt a document using an RSA private key.
function RSAprivencrypt(kfile:string, src:string, dest:string):integer

Arguments
kfile File containing the private key
src
Name of the ﬁle to encryptdst
Name of the ﬁle to store the encrypted document
Return value
Length of the resulting document or -1 in the case of an error.
Further information
1. This function can be used to encrypt a document using an RSA private key (with PKCS1 as the padding
algorithm). Decryption will be done using function RSApubdecrypt with the help of the corresponding
RSA public key.
2. The algorithm used here cannot handle documents larger than (RSAgetkeysize(kfile)/8-11)
bytes. It is usually used to generate a digital signature from a message digest.
Related topics
RSApubdecrypt, msgsign
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information402

mmssl

RSApubencrypt
Purpose
Synopsis

Encrypt a document using an RSA public key.
function RSApubencrypt(kfile:string, src:string, dest:string):integer

Arguments
kfile File containing the public key
src
Name of the ﬁle to encryptdst
Name of the ﬁle to store the encrypted document
Return value
Length of the resulting document or -1 in the case of an error.
Further information
1. This function can be used to encrypt a document using an RSA public key (with PKCS1 OAEP as the
padding algorithm). Decryption will be done using function RSAprivdecrypt with the help of thecorresponding RSA private key.
2. The algorithm used here cannot handle documents larger than (RSAgetkeysize(kfile)/8-41)
bytes. Typically, encryption of larger documents will be performed with a symmetric cipher (see crypt
I/O driver, Section 14.4.3) using a randomly generated key (that can be produced withsslrandomdata), in which case the asymmetric cipher is used to encrypt only this random key. The
decryption then also operates in two steps: the key is ﬁrst decrypted using RSAprivdecrypt (with a
private key) and after this the document can be restored from the decrypted symmetric key.
3. If the key ﬁle name does not include an explicit path (e.g."somekey"), it is searched for in the default
public keys directory located at getparam("ssl_dir")+"/pubkeys" instead of the current working
directory. It is required to preﬁx the key ﬁle name with "./" in order to access a key ﬁle from thecurrent directory (e.g."./somekey").
Related topics
RSAprivdecrypt
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information403

mmssl

RSAsavekey
Purpose
Synopsis

Save an RSA key to a ﬁle.
function RSAsavekey(key:array(range) of integer, kfile:string,
ispriv:boolean):integerfunction RSAsavekey(key:array(range) of integer, kfile:string):integer

Arguments
key
RSA key in the form of an array of integer
kfile Destination ﬁleispriv Save the private key if true, only the public key otherwise
Return value
A positive value on success or -1 in case of error.
ExampleIn the code below a new 2048 bits key is generated and both, private and public parts are saved into
different ﬁles:
if RSAgenkey(2048,k)<=0 thenwriteln("Failed to create RSA key")elif RSAsavekey(k,"perso.key",true)<1 or
RSAsavekey(k,"perso",false)<1 thenwriteln("Failed to save key file")
end-ifFurther information
1. This function saves the RSA key that is provided as an array of string into a ﬁle in a textual
representation. The ispriv parameter can be used to select which part of the key to export.
2. If the ispriv parameter is not provided, the function will produce a private key ﬁle if the key is private
and a public key ﬁle otherwise.
Related topics
RSAloadkey, RSAgenkey
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information404

mmsslmsgdigest
Purpose
Synopsis

Compute the message digest of a document.
function msgdigest(mdalg:string, fname:string, mdf:string):integerfunction msgdigest(fname:string, mdf:string):integer

Arguments
mdalg Name of the algorithm to use
fname Name of the ﬁle to be processed
mdf
File where to store the digest
Return value
Size of the message digest in bytes or -1 if case of error.
ExampleThe following procedure implements the command ’md5sum’:
procedure md5sum(f:string)if msgdigest("md5",f,"mem:dgst")<>16 thenwriteln("Failed to compute digest")
else
fcopy("mem:dgst",F_BINARY,"hex:",F_TEXT)
writeln(" ",f)end-ifend-procedure

Further information
1. This function computes a message digest (MD) using either the algorithm speciﬁed by the mdalg
argument or the default algorithm as deﬁned by the control parameter ssl_digest. The produced
output takes the form of a binary ﬁle the size of which is returned by the function.
2. The set of supported algorithms includes "md5", "sha", and "sha256". For a full list use thecommand mmssl list digest.
Related topics
sslmdsize
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information405

mmsslmsgsignPurpose
Synopsis

Compute the digital signature of a document.
function msgsign(mdalg:string, pkey:string, fname:string,
sgf:string):integerfunction msgsign(fname:string, sgf:string):integer

Arguments
mdalg
pkey
fname
sgf

Name of the message digest algorithm to use
Name of the private key ﬁle to use for signing
File to sign
File where the signature is to be saved

Return value
Length of the signature or -1 in the case of an error.
Further information
1. This function computes the digital signature of a document by encrypting the message digest of its
input ﬁle using an RSA private key. The resulting signature can be veriﬁed with the function msgverify
used with the appropriate public key.
2. If no message digest algorithm is speciﬁed, the default algorithm deﬁned by the control parameter
ssl_digest is used. Unless a speciﬁc key ﬁle is selected, the default private key deﬁned by thecontrol parameter ssl_privkey or, (if this parameter is not deﬁned) the key undergetparam("ssl_dir")+"/personal.key" is used.
Related topics
msgverify
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information406

mmsslmsgverify
Purpose
Synopsis

Verify the digital signature of a document.
function msgverify(mdalg:string, key:string, fname:string,
sgf:string):integerfunction msgverify(key:string, fname:string, sgf:string):integer

Arguments
mdalg
key
fname
sgf

Name of the message digest algorithm to use
Name of the public key ﬁle to use
File to verify
Signature used for the veriﬁcation

Return value
1 if the signature is valid, 0 if the veriﬁcation failed and -1 in the case of an error.
Further information
1. This function veriﬁes the digital signature of a document by comparing the message digest of the
document with the information obtained by decrypting the provided signature with a given RSA public
key. Typically this signature has been obtained with the function msgsign and the appropriate private
key.
2. If no message digest algorithm is speciﬁed, the default algorithm deﬁned by the control parameter
ssl_digest is used. Note that the same algorithm has to be used for both signing and verifying.
3. If the key ﬁle name does not include an explicit path (e.g."somekey"), it is searched for in the default
public keys directory located at getparam("ssl_dir")+"/pubkeys" instead of the current working
directory. It is required to preﬁx the key ﬁle name with "./" in order to access a key ﬁle from thecurrent directory (e.g."./somekey").
Related topics
msgsign
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information407

mmsslsslivsize
Purpose
Synopsis

Get the size of the initialisation vector (IV) required by a symmetric cipher.
function sslivsize(cipalg:string):integer

Argument
cipalgName of the cipher to consider

Return value
Size of a IV in bytes or -1 if the cipher is not supported.
ExampleThe following statement generates a random IV for the default cipher algorithm:
sslrandomdata("myiv",sslivsize(""))

Further information
Some encryption algorithms require an initialisation vector (IV) in addition to the encryption key. Like
the key, the IV is an array of bytes of a ﬁxed size. This function returns the length (in bytes) of the IV
required by a given symmetric cipher algorithm. A return value of -1 indicates an unrecognisedalgorithm name: this property can be used to check whether a given algorithm is available.
Related topics
sslkeysize
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information408

mmsslsslkeysize
Purpose
Synopsis

Get the size of the key required by a symmetric cipher.
function sslkeysize(cipalg:string):integer

Argument
cipalgName of the cipher to consider

Return value
Size of a key in bytes or -1 if the cipher is not supported.
Further information
This function returns the length (in bytes) of an encryption key required by a given symmetric cipher
algorithm. A return value of -1 indicates that the algorithm name has not been recognised: thisproperty can be used to check whether a given algorithm is available.
Related topics
sslivsize
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information409

mmsslsslmdsize
Purpose
Synopsis

Get the size of a message digest.
function sslmdsize(mdalg:string):integer

Argument
mdalg Algorithm to consider
Return value
Size of the message digest in bytes or -1 if the algorithm is not supported.
Further information
This function returns the length (in bytes) of a digest produced by the requested message digest
algorithm. A return value of -1 indicates that the algorithm name has not been recognised: thisproperty can be used to check whether a given algorithm is available.
Related topics
msgdigest
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

410

mmsslsslrandom
Purpose
Synopsis

Generate a random number.
function sslrandom:integer

Return value
A randomly generated integer.
Further information
This function returns an integer by combining 4 bytes obtained from a cryptographically strong
pseudo-random generator.
Related topics
sslrandomdata
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

411

mmsslsslrandomdata
Purpose
Synopsis

Generate a random data ﬁle.
procedure sslrandomdata(fname:string, size:integer)

Arguments
fname Name of the ﬁle where to save the generated data
size Number of bytes to generate
ExampleThe following statement generates a random key for the default cipher algorithm:
sslrandomdata("mykey",sslkeysize(""))

Further information
This function generates size bytes from a cryptographically strong pseudo-random generator that it
saves in the speciﬁed ﬁle fname.
Related topics
sslrandom
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

412

mmsslx509check
Purpose
SynopsisCheck the compatibility of a private key with an X509 certiﬁcate.
function x509check(x509:string, kfile:string):integer

Arguments
x509 File containing the certiﬁcate in PEM format
kfile File containing the private key
Return value
0 if the key is compatible with the certiﬁcate, 1 if the key is not compatibe and -1 in the case of an error.
Further information
This function checks whether the public key recorded in the speciﬁed certiﬁcate corresponds to theprovided private key (the certiﬁcate can only be used by the owner of the public key).
Related topics
x509getinfo
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

413

mmsslx509getinfo
Purpose
Synopsis

Retrieve information stored in an X509 certiﬁcate.
function x509getinfo(x509:string, info:array(string) of text):integer

Arguments
x509
info

Certiﬁcate ﬁle in PEM format
Array where to store certiﬁcate information

Return value
Number of items stored in the array or -1 in case of error.
ExampleThe example below shows how to display the properties of a certiﬁcate:declarations
info:array(S:set of string) of text
end-declarations
if x509getinfo("srv.crt",info)<1 thenwriteln("Failed to load certificate")
else
forall(s in S | exists(info(s)))
writeln("", s, ":", info(s))
end-ifFurther information
This function retrieves some of the information recorded in an X509 certiﬁcate. The data is recorded in
the provided array indexed by the labels of the records in the certiﬁcate. The possible labels are:Version Format version of the certiﬁcate
Serial Serial number
Issuer Issuer of the certiﬁcate
Subject Entity associated to the public key stored in the certiﬁcate
NotBefore Valid after this date
NotAfter Valid until this date
SgnAlg Algorithm used to sign the certiﬁcate
A self-signed certiﬁcate (such as those created with x509newcrt) will have identical values for
Issuer and Subject.
Related topics
x509check
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

414

mmsslx509newcrt
Purpose
SynopsisCreate a new self-signed X509 certiﬁcate.
function x509newcrt(x509:string, kfile:string, info:array(string) oftext):integer

Arguments
x509 Certiﬁcate ﬁle to create (PEM format)
kfile File containing the private key
info Array describing the certiﬁcate properties
Return value
0 if success or -1 in the case of an error.
ExampleThe following example creates a certiﬁcate that is valid for 3 years, using a new RSA key:info("Version"):="1"
info("Serial"):="123456789"
info("Duration"):=text(365⁎3)
info("C"):="FR"info("O"):="My Company"
info("CN"):="www.mycomp.com"
if RSAgenkey(1024,"srv.key")<=0 thenwriteln("Failed to create RSA key")elif x509newcrt("srv.crt","srv.key",info)<>0 thenwriteln("Failed to create certificate")
end-ifFurther information
1. This function creates a self-signed X509 certiﬁcate. Such a certiﬁcate can be used to run an HTTPS
server but clients of such a server have to disable server certiﬁcate veriﬁcation (seehttps_trustsrv) or include this certiﬁcate in their trusted certiﬁcate ﬁle (see https_cacerts).
2. The routine expects an array with indices deﬁning the following entries (a default value applies if theentry is missing):
Version Format version of the certiﬁcate (default: 1)
Serial Serial number (default: 1)
Duration Validity (in days) from the current date (default: 365)CCountry code (default: system country or ’EU’)O
Organisation name (default: anonymous)
CN
Common Name (typically the host name to authenticate, default: localhost)
The entries C, O and CN are used to generate the Issuer and Subject records of the certiﬁcate. The
provided key is used both as the certiﬁcate key (using the public part of the key) and as the signing key.
Related topics
x509check, x509getinfo
Modulemmssl

Fair Isaac Corporation Conﬁdential and Proprietary Information

415mmssl14.4

I/O drivers
The mmssl module publishes two drivers for converting binary documents to textual representation
and a driver dedicated to symmetric encryption. These drivers have the same behaviour: encryption or
encoding is performed when the driver is used for writing while decryption/decoding is done on a
stream that is open for reading.

14.4.1

Driver base64
base64:[nonl,]filename

This driver can be used to handle documents encoded using the base64 standard. When used in an
output stream, it generates the base64 encoded version of its binary input and in an input stream it
expects a base64 encoded document that it decodes.
For instance the following statement encodes "mydata.bin":fcopy("mydata.bin",F_BINARY,"mmssl.base64:mydata.b64",F_TEXT)

By default a base64 document is split into lines of 76 characters but with the option nonl the entire
document is output as (or read from) a single line.

14.4.2

Driver hex
hex:filename

This driver produces a textual representation of a binary document by replacing each byte by its
hexadecimal representation (e.g. the value 13 is converted to the string "0d").
The following code extract displays the hexadecimal representation of the binary input ﬁle "mem:md5":
fcopy("mem:md5",F_BINARY,"mmssl.hex:",F_TEXT)
writeln

14.4.3

Driver crypt
crypt:[[nosalt,][md=a,][cipher=c,][key=kf,][iv=if,]pwd=p|pf]filename

The crypt driver performs encryption (when writing) or decryption (when reading) of its stream using asymmetric cipher (that is, the same key is used for encryption and decryption). Options are provided
enclosed in square brackets, at the least a password has to be provided. For instance, the following
statement encrypts the ﬁle "mydata" using the password stored in the ﬁle "passfile":
fcopy("mydata","mmssl.crypt:[passfile]mydata.enc")

The password is read from the ﬁrst line of the password ﬁle (that is opened as a text document).
Alternatively, the password may be directly passed through the ﬁle name using the pwd= option:
fcopy("mydata","mmssl.crypt:[pwd=mysecret]mydata.enc")

Encryption (or decryption) is performed using the default cipher as deﬁned by the control parameter
ssl_cipher. Another cipher can be selected using the cipher option.
The encryption (or decryption) process requires a key as well as an initialisation vector. The size ofthese components depends of the selected cipher and the appropriate data is generated by a key

Fair Isaac Corporation Conﬁdential and Proprietary Information

416

mmsslderivation routine using the provided password as input. This procedure employs a message digest
algorithm and may use some initial value (or salt). Without any speciﬁc option the driver relies on thedefault message digest algorithm deﬁned by the control parameter ssl_digest and generates arandom salt of 8 bytes. These bytes are then saved at the beginning of the encrypted document suchthat the decryption process can retrieve them and regenerate the encryption key and initialisation
vector from the provided password. This default behaviour can be changed using the nosalt option to
avoid using a salt and the option md to select some other message digest algorithm. It is also possible
to provide the encryption key and the initialisation vector via dedicated ﬁles using options key and iv.
In this case no password has to be provided.

14.4.4

Driver hmac
hmac:[[md=a,]key=kf|key]filename

The hmac driver computes a HMAC (keyed-hash message authentication code) of its input stream
using the provided key and hash function (the driver does not support reading). Options are provided
enclosed in square brackets, at the least a key has to be provided. For instance, the following statement
generates the HMAC of the ﬁle "mydata" using the key stored in the ﬁle "keyfile":
fcopy("mydata","mmssl.hmac:[keyfile]mydata.hmac")

The key is read from the key ﬁle that is opened as a binary document. Alternatively, the key may bedirectly passed through the ﬁle name using the key= option:
fcopy("mydata","mmssl.hmac:[key=mykey]mydata.hmac")

Computation of a HMAC is based on a message digest algorithm, without any speciﬁc option the driverrelies on the default message digest algorithm deﬁned by the control parameter ssl_digest
otherwise, the option md can be used to select some other algorithm.

Fair Isaac Corporation Conﬁdential and Proprietary Information

417

CHAPTER 15

mmsvg
The mmsvg package provides a set procedures which allow users to display graphs of functions,diagrams, networks, various shapes etc. in SVG format. To use this module the following line must be
included in the header of the Mosel model ﬁle:uses "mmsvg"

mmsvg requires a webbrowser in order to be able to display graphics. Running a Mosel model that uses
the svgrefresh routine provided by this module opens a window in the default browser that is
conﬁgured on the system. In the absence of a webbrowser, it is still possible to generate graphics andsave them to ﬁle via svgsave.

15.1

SVG graph structure
The SVG graph format is an XML format, that is, the elements of a graph are organized in a hierarchicaltree structure. mmsvg structures graphical objects in three levels:
1. SVG graph
2. object group
3. graphical object
Each individual graphical object (line, polygon, text etc.) must be created within an object group. By
default this is the last group that has been added to the graph, but some other object reference can bestated. A default graph object is always present and object groups are created within this default graph.

15.1.1

Object groups
Object groups are identiﬁed via a string ID that is speciﬁed by the user at their creation, this ID must be
unique. Each object group receives an entry in the legend of the graph. Typically a group serves torepresent a collection of graphical objects that are logically related. The style deﬁned for a group isapplied to all its objects unless it is overwritten by individual settings, meaning that it is usually more
efﬁcient to state generally valid style settings for an entire group instead of repeating them for eachindividual object.
At the creation of a group, optionally a group color can be speciﬁed. If no color is given, then a default
color will be selected from a built-in list of color values.
Graphical objects are displayed in the order of deﬁnition of object groups, and within each group in theorder of their deﬁnition.

Fair Isaac Corporation Conﬁdential and Proprietary Information

418

mmsvg15.1.2

SVG styling
Style deﬁnitions can be applied to all levels of SVG elements, to the graph, object groups, or forindividual objects. mmsvg deﬁnes a set of property constants but other SVG styling options can equally
be used by directly stating their name in the svgset[graph]style routines. For a complete list of
SVG style properties and their permissible values the reader is refered to the SVG property
speciﬁcations at https://www.w3.org/TR/SVG/propidx.html.
SVG_COLOR

Default color name (for object groups)

SVG_DECORATION

Text decoration; possible values include ’none’, ’underline’, ’overline’,’line-through’, ’blink’

SVG_FILL

Fill color name

SVG_FILLOPACITY

Fill opacity; values between 0.0 and 1.0

SVG_FONTWhitespace separated list of font settings

SVG_FONTFAMILY

Font family deﬁnition; this can be generic families (’serif’, ’sans-serif’,’cursive’, ’fantasy’, ’monospace’) or speciﬁc font names

SVG_FONTSIZE

Font size; constants (’xx-small’, ’x-small’, ’small’, ’medium’, ’large’, ’x-large’,’xx-large) or percentage value or length (e.g. in ’em’, ’pt’, ’px’, ’cm’)

SVG_FONTSTYLE

Font style; values ’normal’, ’italic’, ’oblique’

SVG_FONTWEIGHT

Font weight; numbers 100,...900 or constants (’bold’, ’bolder’, ’lighter’,’normal’)SVG_OPACITY

Generic opacity setting; values between 0.0 and 1.0

SVG_STROKE

Color for lines and borders

SVG_STROKEDASH

Line style; comma-separated list of lengths or percentages specifying
lengths of alternating dashes and gaps

SVG_STROKEOPACITY

Stroke opacity, values between 0.0 and 1.0

SVG_STROKEWIDTH

Stroke width; percentage or length

SVG_TEXTANCHOR

Vertical alignment of text; possible values include ’start’, ’middle’, ’end’

Other predeﬁned constants are SVG_CURRENT for the current color and SVG_NONE.
mmsvg deﬁnes the following color constants (applicable to the properties SVG_COLOR, SVG_FILL,
SVG_STROKE) that can be used in place of SVG color keywords or color deﬁnitions generated via thesvgcolor routine:

SVG_BLACK, SVG_BLUE, SVG_BROWN, SVG_CYAN, SVG_GOLD, SVG_GRAY, SVG_GREEN,
SVG_LIME, SVG_MAGENTA, SVG_ORANGE, SVG_PINK, SVG_PURPLE, SVG_RED, SVG_SILVER,
SVG_WHITE, SVG_YELLOW

For a full list of SVG color keywords and their deﬁnitions please see
https://www.w3.org/TR/SVG/types.html.
The complete set of style properties speciﬁed for a graph, object group or individual objects can be
retrieved via the routines svggetstylesheet and svggetgraphstylesheet, for example in order
to copy them to some other object via svgsetstylesheet or svgsetgraphstylesheet
respectively.

Fair Isaac Corporation Conﬁdential and Proprietary Information

419

mmsvg15.1.3

Interaction with the graphical display
The command svgrefresh sends the current graph and any additional ﬁles that might have been
added to it (see svgaddfile) to the built-in server that handles the coordination with the display andtriggers an update of the graphical display. The end of the model execution will also terminate thedisplay, unless a call to the routine svgwaitclose is added at the end of the model, in which case themodel waits for the closing of the display window.
Inserting a call to the routine svgpause into a model will pause its execution at this point until the user
hits the ’Continue’ button in the graphical display. Typically, this feature will be used to allow the user
time for visual inspection of the output if a model iteratively generates graphics or updates to a graphic.

15.1.4

ExampleThe following example shows how to deﬁne a few simple graphical objects, saves the resulting graphic
to a ﬁle and also displays it in a webbrowser. The model waits until the browser is closed.
model "svg example"
uses "mmsvg"! ⁎⁎⁎⁎ Line objects ⁎⁎⁎⁎
svgaddgroup("gl", "Lines")! Group with automatic color
svgaddline(10,10,250,10)! Simple line with default style
PointList:=sum(i in 1..20)[i⁎10,40+round(20⁎random)]svgaddline(PointList)! Polyline
l:=svggetlastobj! Retrieve object reference
svgsetstyle(l, SVG_STROKE, SVG_MAGENTA) ! Change line color
svgsetstyle(l, SVG_STROKEDASH, "1,1")! Dotted line! ⁎⁎⁎⁎ Various shapes ⁎⁎⁎⁎
svgaddgroup("gs", "Shapes", SVG_GREY)! Group with user-defined color
svgaddrectangle(275,25,250,250)! Draw a squaresvgsetstyle(svggetlastobj, SVG_STROKEWIDTH, 3)! Wider bordersvgaddcircle(400,150,75)! Draw a circle
svgsetstyle(svggetlastobj, SVG_FILL, SVG_CURRENT) ! Fill with group color
svgaddpolygon([200,400,200,350,300,300,500,350,600,350,600,400])
svgsetstyle(svggetlastobj, SVG_FILL, SVG_GREEN)! Fill with user color! ⁎⁎⁎⁎ Pie chart ⁎⁎⁎⁎
forall(i in 1..6) svgaddgroup("gp"+i,"Pie"+i)setrandseed(3); ttl:=0.0
forall(i in 1..5) do
rd:=random/6
svgaddpie("gp"+i, 150, 525, 100, ttl, ttl+rd)
ttl+=rdend-dosvgaddpie("gp6", 150, 525, 100, ttl, 1)! Pie slices with auto-colors! ⁎⁎⁎⁎ Text objects ⁎⁎⁎⁎
svgaddgroup("gt", "Text", SVG_BLACK)! Group with user-defined color
svgaddtext(20, 100, "Text with default formatting")
svgaddtext(20, 120, "Formatted text")
t:=svggetlastobj
svgsetstyle(t, SVG_FONTSIZE, "20pt")
svgsetstyle(t, SVG_FONTSTYLE, "italic")
svgsetstyle(t, SVG_FONTWEIGHT, "bold")
svgsetstyle(t, SVG_COLOR, SVG_BLUE)svgaddxmltext(20, 150, 'XML formatted text:<tspan font-size="large"> large</tspan><tspan text-decoration="underline">underlined</tspan><tspan stroke="red"> red</tspan>')svgsetgraphviewbox(0,0,610,635)! Optional: specify graph size

svgsave("svgexpl.svg")! Save graphic to file

Fair Isaac Corporation Conﬁdential and Proprietary Information

420mmsvgsvgrefreshsvgwaitclose
end-model! Display graphic! Wait until window is closed

Figure 15.1: Graphical output produced by the example

15.2

Control parameters
The following parameters are deﬁned by mmsvg:
MMSVGDISPLAY

Enable/disable rendering.

p. 421MMSVGTGZ

Location of the mmsvg.tgz archive.

p. 422MMSVGDISPLAY
Description

When this parameter is set to true (the default) the ﬁrst call to svgrefresh starts a web
browser for displaying the current graph. Changing the value of this parameter disables
rendering: after a warning message is reported calls to svgrefresh have no effect and thefunction svgclosing always returns true. Note that setting the environment variable
MMSVGDISPLAY to a non empty string has the same effect as changing this control
parameter.

Type

Boolean, read/write

Valuestrue Enable rendering.
false Disable rendering.

Default valuetrue

Affects routines

svgrefresh, svgclosing.

Modulemmsvg

Fair Isaac Corporation Conﬁdential and Proprietary Information

421

mmsvgMMSVGTGZ
Description

The function svgrefresh requires the archive mmsvg.tgz for its processing. By default thisﬁle is expected to be located in the same directory as the module mmsystem. This parameter
makes it possible to specify an alternate location.

Type

String, read/write

Default value""

Affects routines

svgrefresh.

Module

mmsvg

15.3

Procedures and Functions
svgaddarrow

Add an arrow to an object group.

p. 425

svgaddcircle

Add a circle to an object group.

p. 426

svgaddellipse

Add an ellipse to an object group.

p. 427

svgaddfile

Add a ﬁle to a graph.

p. 428

svgaddgroup

Add a new object group to the user graph.

p. 424

svgaddimage

Add an image to an object group.

p. 429svgaddline

Add a line or polyline to an object group.

p. 430svgaddpie

Add a pie slice.

p. 431

svgaddpoint

Add a small square to mark a point.

p. 432

svgaddpolygon

Add a polygon to an object group.

p. 433

svgaddrectangle

Add a rectangle to an object group.

p. 434

svgaddtext

Add a text to an object group.

p. 435

svgaddxmltext

Add an XML formatted text to an object group.

p. 436

svgclosing

Test whether the display window is being closed.

p. 437

svgcolor

Compute a composite color.

p. 438svgdelobj

Delete the speciﬁed graphical object.

p. 439svgerase

Erase all object groups or the contents of a speciﬁc group.

p. 440svggetgraphstyle

Retrieve a style property of a graph.

p. 441

svggetgraphstylesheet

Retrieve the style deﬁnitions of a graph.

p. 442

svggetgraphviewbox

Retrieve the viewbox deﬁnition of a graph.

p. 443

svggetlastobj

Retrieve the identiﬁer of a graphical object.

p. 444svggetstyle

Retrieve a style property of a graphical object or object group.

p. 445

Fair Isaac Corporation Conﬁdential and Proprietary Information

422

mmsvgsvggetstylesheet

Retrieve style deﬁnitions of a graphical object or object group.

p. 446

svgpause

Suspend the execution of a model.

p. 447

svgrefresh

Refresh the graph display.

p. 448

svgsave

Save a graph to a ﬁle.

p. 449svgsetgraphlabels

Set x- and y-axis labels for a graph.

p. 450svgsetgraphpointsize

Set point size property for a graph.

p. 451

svgsetgraphscale

Set scaling value for a graph.

p. 452

svgsetgraphstyle

Set a style property of a graph.

p. 453

svgsetgraphstylesheet

Set the style deﬁnitions for a graph.

p. 454

svgsetgraphviewbox

Set the visible area for a user graph.

p. 455

svgsetreffreq

Set the refresh frequency for a graph.

p. 456

svgsetstyle

Set a style property for a graphical object or object group.

p. 457

svgsetstylesheet

Set the style for a graphical object or object group.

p. 458svgshowgraphaxes

Force displaying of graph axes.

p. 459svgwaitclose

Delay model termination.

p. 460Fair Isaac Corporation Conﬁdential and Proprietary Information

423

mmsvgsvgaddgroup
Purpose
Synopsis

Add a new object group to the user graph.
procedure svgaddgroup(gid: string, desc: text, color: text)
procedure svgaddgroup(gid: string, desc: text)

Arguments
gid
Object group ID (must be unique within a graph).
desc A text that will appear in the legend.
color A color speciﬁcation obtained using svgcolor or one of the predeﬁned constants (see list in
section 15.1.2).
ExampleThe following adds two groups ’g1’ and ’g2’ to the user graph:svgaddgroup("g1", "sine", SVG_RED)
svgaddgroup("g2", "random numbers")! User-specified group color! Automatically selected color

Further information
1. A group is identiﬁed by its ID whereas the ’desc’ serves as text for the legend of the graphic. A groupcontains any number of individual objects (points, lines, arrows, texts etc.) which were added to it.
2. An empty string for the ’desc’ attribute indicates that the group is not to be included in the legend.
3. If no color is speciﬁed at the creation of a group it will be assigned a default color from a built-in list.
This setting can be overwritten for individual objects within the group. Note that any style settings thatare common to a large number of objects within a group should preferrably be speciﬁed for the grouprather than for the individual objects.
Related topics
svgsetstyle.

Fair Isaac Corporation Conﬁdential and Proprietary Information

424

mmsvgsvgaddarrow
Purpose
Synopsis

Add an arrow to an object group.
procedure svgaddarrow(gid: string, x1: real, y1: real, x2: real, y2: real)procedure svgaddarrow(x1: real, y1: real, x2: real, y2: real)

Arguments
gid
x1
y1
x2
y2
ExampleObject group ID.
The x coordinate of the ﬁrst point.
The y coordinate of the ﬁrst point.
The x coordinate of the second point.
The y coordinate of the second point.

The following adds two arrows to a group named ‘thetime’. The arrows suggest three o’clock:svgaddgroup("arrows", "thetime", SVG_BLACK)
svgaddarrow("arrows", 0, 0, 0, 5)
svgaddarrow(0, 0, 4.5, 0)
svgsetgraphviewbox(-5, -6, 10, 12)

Further information
1. The arrow connects the two points whose coordinates are given as parameters, pointing to the secondone.
2. If no group ID is speciﬁed, the arrow is added to the last group that has been created.

Fair Isaac Corporation Conﬁdential and Proprietary Information

425

mmsvgsvgaddcircle
Purpose
Synopsis

Add a circle to an object group.
procedure svgaddcircle(gid: string, x: real, y: real, r: real)procedure svgaddcircle(x: real, y: real, r: real)

Argumentsgidxyr
ExampleObject group ID.
The x coordinate of the center point.
The y coordinate of the center point.
The length of the radius of the circle.

The following code draws a ﬁlled, semi-transparent circle centered at the origin with a radius of 10.
declarations
circ: integer
end-declarations
svgaddcircle(0, 0, 10)
circ:=svggetlastobj
svgsetstyle(circ, SVG_FILL, SVG_CYAN)
svgsetstyle(circ, SVG_OPACITY, 0.5)

Further information
If no group ID is speciﬁed, the circle is added to the last group that has been created.

Fair Isaac Corporation Conﬁdential and Proprietary Information

426

mmsvgsvgaddellipse
Purpose
Synopsis

Add an ellipse to an object group.
procedure svgaddellipse(gid: string, x: real, y: real, rx: real, ry: real)procedure svgaddellipse(x: real, y: real, rx: real, ry: real)

Arguments
gid
x
y
rx
ry
ExampleObject group ID.
The x coordinate of the center point of the ellipse.
The y coordinate of the center point of the ellipse.
The horizontal radius.
The vertical radius.

The following code draws a very "ﬂat" ellipse centered at the origin ﬁlled with the group color.
svgaddellipse(0,0,5,0.5)
svgsetstyle(svggetlastobj, SVG_FILL, SVG_CURRENT)

Further information
If no group ID is speciﬁed, the ellipse is added to the last group that has been created.

Fair Isaac Corporation Conﬁdential and Proprietary Information

427

mmsvgsvgaddﬁlePurpose
Synopsis

Add a ﬁle to a graph.
procedure svgaddfile(fname: string, fid: string)Arguments
fname Filename (including path) of the ﬁle to be included.
fid
Name for the ﬁle used within the SVG graph.
ExampleThe following code adds an image ﬁle to the current graph and displays it in an area with corner points
at the coordinates (100,100) and (250,250).
svgaddfile("./someimage.png", "myimg.png")
svgaddimage("myimg.png", 100, 100, 150, 150)

Further information
1. This routine is typically used in combination with svgaddimage to associate some external ﬁle withthe graph.
2. Using an empty ﬁle name fname will remove the corresponding fid from the ﬁle database.
Related topics
svgaddimage.

Fair Isaac Corporation Conﬁdential and Proprietary Information

428

mmsvgsvgaddimage
Purpose
Synopsis

Add an image to an object group.
procedure svgaddimage(gid: string, fid: text, x: real, y: real, w: real, h:
real)
procedure svgaddimage(fid: text, x: real, y: real, w: real, h: real)

Arguments
gid
fid
x
y
w
h
ExampleObject group ID.
Name for the ﬁle used within the SVG graph.
The x coordinate of the lower left corner.
The y coordinate of the lower left corner.
The width of the image.
The height of the image.

The following code adds an image ﬁle to the current graph and displays it 3 times at different positions(3 squares forming a row).
svgaddfile("./someimage.png", "myimg.png")
forall(i in 1..3)
svgaddimage("myimg.png", 100⁎i, 100, 100, 100)

Further information
1. Any external ﬁle to be displayed within a graph needs to be associated with the graph via a call to
svgaddfile.
2. If no group ID is speciﬁed, the image is added to the last group that has been created.
Related topics
svgaddfile.

Fair Isaac Corporation Conﬁdential and Proprietary Information

429

mmsvgsvgaddline
Purpose
Synopsis

Add a line or polyline to an object group.
procedure svgaddline(gid: string, x1: real, y1: real, x2: real, y2: real)procedure svgaddline(x1: real, y1: real, x2: real, y2: real)procedure svgaddline(gid: string, points: list of integer|real)procedure svgaddline(points: list of integer|real)

Arguments
gid
x1
y1
x2
y2
pointsExampleObject group ID.
The x coordinate of the ﬁrst point.
The y coordinate of the ﬁrst point.
The x coordinate of the second point.
The y coordinate of the second point.
A list of points.

The following code draws the outline of a triangle, given the correct aspect ratio of the user graph.
svgaddgroup("t", "triangle", SVG_ORANGE)
svgaddline([-2, -2, 0, 2, 2, -2, -2, -2)])
svgsetgraphviewbox(-5, -5, 10, 10)
If the shape is to be ﬁlled (here: using the group color), you need to use polygon drawing instead of apolyline:
svgaddpolygon([-2, -2, 0, 2, 2, -2)])
svgsetstyel(svggetlastobj, SVG_FILL, SVG_CURRENT)

Further information
1. The line connects the two points whose coordinates are given as parameters or the points contained in
the speciﬁed list in their order of appearance in the list.
2. If no group ID is speciﬁed, the line is added to the last group that has been created.
Related topics
svgaddpolygon.

Fair Isaac Corporation Conﬁdential and Proprietary Information

430

mmsvgsvgaddpie
Purpose
Synopsis

Add a ﬁlled pie slice at the given coordinates.
procedure svgaddpie(gid: string, x: real, y: real, r: real, p1: real, p2:
real)procedure svgaddpie(x: real, y: real, r: real, p1: real, p2: real)

Arguments
gid
x
y
r
p1
p2
ExampleObject group ID.
The x coordinate of the center point.
The y coordinate of the center point.
Radius (side length of the pie slice).
Start position on the circle (percentage).
End position on the circle (percentage).

This code draws a pie chart with 5 slices of 20% width each around the center point (150,150) with aradius of 100.
forall(i in 1..5) do
svgaddgroup("gp"+i, "Pie"+i)
svgaddpie(150, 150, 100, (i-1)⁎0.2, i⁎0.2)
end-doFurther information
1. Pie slices are by default ﬁlled with the group color. If they are not to be ﬁlled with any color specify
value SVG_NONE for the style property SVG_FILL.
2. If no group ID is speciﬁed, the pie slice is added to the last group that has been created.

Fair Isaac Corporation Conﬁdential and Proprietary Information

431

mmsvgsvgaddpoint
Purpose
Synopsis

Add a small square to mark a point at the given coordinates.
procedure svgaddpoint(gid: string, x: real, y: real)procedure svgaddpoint(x: real, y: real)

Argumentsgidxy
ExampleObject group ID.
The x coordinate of the point.
The y coordinate of the point.

This code plots 100 random points:
svgaddgroup("cloud", "Random points", SVG_YELLOW)
svgsetgraphviewbox(-5, -5, 10, 10)
forall(i in 1..100)
svgaddpoint("cloud", -2+4⁎random, -2+4⁎random)

Further information
If no group ID is speciﬁed, the point is added to the last group that has been created.
Related topics
svgsetgraphpointsize.

Fair Isaac Corporation Conﬁdential and Proprietary Information

432

mmsvgsvgaddpolygon
Purpose
Synopsis

Add a polygon to an object group.
procedure svgaddpolygon(gid: string, points: list of integer|real)procedure svgaddpolygon(points: list of integer|real)

Arguments
gid
pointsExampleObject group ID.
A list of points.

The following code draws two semi-transparent, partially overlapping polygons, the ﬁrst is ﬁlled withthe group color, the second with a different color:svgaddgroup("p", "Polygons")
svgsetstyle(SVG_OPACITY, 0.5)
svgsetstyle(SVG_FILL, SVG_CURRENT)
svgaddpolygon([-2, -2, 0, 2, 2, -2)])
svgaddpolygon([-1, -2, 1, 2, 3, -2)])
svgsetstyle(svggetlastobj, SVG_FILL, SVG_GREY)

Further information
1. The last point in the list of points is automatically connected to the ﬁrst point in the list to form a closed
shape.
2. If no group ID is speciﬁed, the polygon is added to the last group that has been created.
Related topics
svgaddline.

Fair Isaac Corporation Conﬁdential and Proprietary Information

433

mmsvgsvgaddrectangle
Purpose
Synopsis

Add a rectangle to an object group.
procedure svgaddrectangle(gid: string, x: real, y: real, w: real, h: real)

Arguments
gid
x
y
w
h
ExampleObject group ID.
The x coordinate of the lower left corner.
The y coordinate of the lower left corner.
The width of the rectangle.
The height of the rectangle.

The following code draws a rectangle ﬁlled with the group color covering an area 10 units long and 1
unit high starting at the origin.
svgaddrectangle(0,0,10,1)
svgsetstyle(svggetlastobj, SVG_FILL, SVG_CURRENT

Further information
If no group ID is speciﬁed, the rectangle is added to the last group that has been created.

Fair Isaac Corporation Conﬁdential and Proprietary Information

434

mmsvgsvgaddtext
Purpose
Synopsis

Add a text to an object group.
procedure svgaddtext(gid: string, x: real, y: real, msg: text)
procedure svgaddtext(x: real, y: real, msg: text)

Arguments
gid
x
y
text
ExampleObject group ID.
The x coordinate of the point.
The y coordinate of the point.
The text that will be displayed at the given point.

This code complements the time graph with a dial:! This should complement the example for svgaddarrowforall(i in 1..12)
svgaddtext(4.8⁎cos(1.57-6.28⁎i/12), 5⁎sin(1.57-6.28⁎i/12), text(i))

Further information
1. By default the speciﬁed point denotes the lower left corner of the text display area; the verticalalignment can be changed via the style option SVG_ANCHOR (values ’start’, ’middle’, or ’end’).
2. If no group ID is speciﬁed, the text is added to the last group that has been created.
Related topics
svgaddxmltext.

Fair Isaac Corporation Conﬁdential and Proprietary Information

435

mmsvgsvgaddxmltext
Purpose
Synopsis

Add an XML formatted text to an object group.
procedure svgaddxmltext(x: real, y: real, msg: text)
procedure svgaddxmltext(gid: string, x: real, y: real, msg: text)

Arguments
gid
x
y
text
ExampleObject group ID.
The x coordinate of the point.
The y coordinate of the point.
The text that will be displayed at the given point.

This code displays some text with individual formatting on different words:
svgaddxmltext(20, 150, 'XML formatted text:<tspan font-size="20px">large</tspan>,<tspan font-style="oblique">oblique</tspan>,<tspan font-weight="bold">bold</tspan>,<tspan text-decoration="underline">underlined</tspan>,<tspan stroke="red">red</tspan>')Further information
1. By default the speciﬁed point denotes the lower left corner of the text display area; the verticalalignment can be changed via the style option SVG_ANCHOR (values ’start’, ’middle’, or ’end’).
2. If no group ID is speciﬁed, the text is added to the last group that has been created.
Related topics
svgaddtext.

Fair Isaac Corporation Conﬁdential and Proprietary Information

436

mmsvgsvgclosing
Purpose
Synopsis

Test whether the display window is being closed.
function svgclosing:boolean

Return value’false’ until the display window is about to be closed, ’true’ afterwards.
ExampleThe following loop uses the browser window opening status as stopping criterion.
solct:= 0
svgrefresh! Start graph display before svgclosing test
while (solct<NBSOL and not svgclosing) do
solct+=1
draw_solution(solct) ! Draws a graph calling svgrefresh and svgpause
end-dosvgwaitclose

Further information
This function can be used to intercept the event of the display window being closed in order to adapt
the behaviour of the model execution (e.g. to interrupt a loop with repeated graphical displays or an
optimization solver run).
Related topics
svgwaitclose.

Fair Isaac Corporation Conﬁdential and Proprietary Information

437

mmsvgsvgcolor
Purpose
Synopsis

Compute a composite color by combining amounts of red, green and blue.
function svgcolor(red, green, blue: integer): text
function svgcolor(red, green, blue: real): text
function svgcolor(red, green, blue: text): text

Arguments
red

Amount of red (integer between 0 and 255, real between 0 and 1, or hexadecimal value
between 0 and FF).
green Amount of green (integer between 0 and 255, real between 0 and 1, or hexadecimal value
between 0 and FF).
blue Amount of blue (integer between 0 and 255, real between 0 and 1, or hexadecimal value
between 0 and FF).

Return value
Hexadecimal representation of the composite color.
ExampleThe following deﬁnitions mix red with green and store the result in a variable. All three forms result inthe same color.
declarations
a_color: text
end-declarations
a_color:=svgcolor(255,255,0)a_color:=svgcolor(1.0,1.0,0.0)
a_color:=svgcolor("FF","FF","0")Further information
If the color component values are out of range, mmsvg will raise an I/O error.

Fair Isaac Corporation Conﬁdential and Proprietary Information

438

mmsvgsvgdelobj
Purpose
Synopsis

Delete the speciﬁed graphical object.
procedure svgdelobj(obj: integer)

Argument
obj

Object ID as returned by svggetlastobj.

Further information
This procedure serves for deleting a speciﬁc graphical object. Use svgerase to delete the wholecontents of an object group or all groups.
Related topics
svgerase, svggetlastobj.

Fair Isaac Corporation Conﬁdential and Proprietary Information

439

mmsvgsvgerase
Purpose
Synopsis

Erase all object groups or the contents of a speciﬁc group.
procedure svgerase
procedure svgerase(gid: string)Argument
gid

Object group ID.

Further information
1. This procedure can be used together with svgpause to explore a number of different user graphversions during the execution of a Mosel model.
2. If a group ID is speciﬁed only the objects within this group are removed without deleting the groupdeﬁnition itself.
3. Use svgdelobj to delete individual graphical objects.
Related topics
svgdelobj, svgpause.

Fair Isaac Corporation Conﬁdential and Proprietary Information

440mmsvgsvggetgraphstylePurpose
Synopsis

Retrieve a style property of a graph.
function svggetgraphstyle(prop: string):text

Argument
prop

The desired property (mmsvg constant or SVG property name).

Return value
Value of the property or empty string.
ExampleThis code retrieves the font family deﬁned for a graph and applies it to an object group.
svgaddgroup("g", "A group")svgsetstyle("g", SVG_FONTFAMILY, svggetgraphstyle("b", SVG_FONTFAMILY))

Further information
This function can be used to retrieve a style property of a graph in order to apply it to some object orgroup of objects. Use svggetgraphstylesheet to retrieve the whole set of style properties of agraph.
Related topics
svggetstyle, svgsetstyle, svgsetgraphstyle, svggetgraphstylesheet,svgsetgraphstylesheet, svggetstylesheet, svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

441

mmsvgsvggetgraphstylesheet
Purpose
Synopsis

Retrieve the style deﬁnitions of a graph.
function svggetgraphstylesheet:array of text

Return value
An array of style properties (’stylesheet’) with their respective values.
ExampleThis code retrieves the style properties of a graph and applies them to an object group.
svgaddgroup("a", "A group")svgsetstylesheet("a", svggetgraphstylesheet)

Further information
This function can be used to retrieve the set of style properties (’stylesheet’) of a graph in order to apply
it to some object or group of objects. Use svggetgraphstyle to retrieve individual style properties ofa graph.
Related topics
svggetstyle, svgsetstyle, svggetgraphstyle, svgsetgraphstyle,svgsetgraphstylesheet, svggetstylesheet, svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

442

mmsvgsvggetgraphviewbox
Purpose
Synopsis

Retrieve the viewbox deﬁnition of a graph.
function svggetgraphviewbox:svgbox

Return value
An object of type ’svgbox’ that holds the view box deﬁned for the graph.
ExampleThis code displays the viewbox deﬁned for a graph.
writeln(svggetgraphviewbox)

Further information
This function can be used to retrieve the viewbox (=visible area) deﬁned for a graph.
Related topics
svgsetgraphviewbox.

Fair Isaac Corporation Conﬁdential and Proprietary Information

443

mmsvgsvggetlastobj
Purpose
Synopsis

Retrieve the identiﬁer of a graphical object.
function svggetlastobj:integer

Return value
Integer identiﬁer of the last graphical object that has been added.
ExampleThis code retrieves an object identiﬁer to apply several style settings.
declarations
t: integer
end-declarations
svgaddgroup("gt", "Text")
svgaddtext(20, 120, "Formatted text")
t:=svggetlastobj
svgsetstyle(t, SVG_COLOR, SVG_GREEN)
svgsetstyle(t, SVG_FONTSTYLE, "italic")

Further information
This function serves for retrieving the identiﬁer of a graphical object, in particular in order to apply stylesettings to this object.
Related topics
svgsetstyle.

Fair Isaac Corporation Conﬁdential and Proprietary Information

444

mmsvgsvggetstylePurpose
Synopsis

Retrieve a style property of a graphical object or object group.
function svggetstyle(gid: string, prop: string):text
function svggetstyle(prop: string):text
function svggetstyle(obj: integer, prop: string):text

Arguments
gid
obj
prop

Object group ID.
Object ID.
The desired property (mmsvg constant or SVG property name).

Return value
Value of the property or empty string.
ExampleThis code retrieves the color of a group and applies it to an object belonging to another group.
svgaddgroup("a", "Group A")
svgaddgroup("b", "Group B")
svgaddtext("a", 20, 120, "Formatted text")
svgsetstyle(svggetlastobj, SVG_COLOR, svggetstyle("b", SVG_COLOR))

Further information
This function can be used to retrieve a style property of some object in order to apply it to some otherobject or group of objects. Use svggetstylesheet to retrieve the whole set of style properties of an
object or group of objects.
Related topics
svgsetstyle, svggetgraphstylesheet, svgsetgraphstylesheet, svggetstylesheet,svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

445

mmsvgsvggetstylesheet
Purpose
Synopsis

Retrieve style deﬁnitions of a graphical object or object group.
function svggetstylesheet(gid: string):array of text
function svggetstylesheet:array of text
function svggetstylesheet(obj: integer):array of text

Arguments
gid
obj

Object group ID.
Object ID.

Return value
An array of style properties (’stylesheet’) with their respective values.
ExampleThis code retrieves the style properties of a group and applies them to an object belonging to anothergroup.
svgaddgroup("a", "Group A")
svgaddgroup("b", "Group B")
svgaddtext("a", 20, 120, "Formatted text")
svgsetstylesheet(svggetlastobj, svggetstylesheet("b"))Further information
This function can be used to retrieve the set of style properties (’stylesheet’) of some object in order toapply it to some other object or group of objects. Use svggetstyle to retrieve individual styleproperties of an object or group of objects.
Related topics
svggetstyle, svgsetstyle, svggetgraphstylesheet, svgsetgraphstylesheet,svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

446

mmsvgsvgpause
Purpose
Synopsis

Suspend the execution of a Mosel model at the line where the call occurs.
procedure svgpause

Further information
While the model run is suspended, the displayed graph or other model output can be inspected. This
allows for visualization of intermediate states or solutions. To continue, click on the ’Continue’ button in
the display window.

Fair Isaac Corporation Conﬁdential and Proprietary Information

447

mmsvgsvgrefresh
Purpose
Synopsis
ExampleRefresh the graph display.
procedure svgrefreshThis code deﬁnes some objects and draws the graph, it then adds further objects and updates tedisplay..
svgaddgroup("a", "Group A")
svgaddtext(0, 0, "Some text")
svgrefresh! Display the graphsvgaddgroup("b", "Group B")
svgaddtext("a", 0, 20, "Some more text")
svgaddcircle(10,10, 45)
svgrefresh! Update the display

Further information
svgrefresh needs to be called in order to trigger the display of a graph. The subroutine can be called
repeatedly in order to update the display—each time it will be completely redrawn. The refresh
frequency can be controlled via svgsetreffreq.
Related topics
svgsetreffreq.

Fair Isaac Corporation Conﬁdential and Proprietary Information

448

mmsvgsvgsave
Purpose
Synopsis

Save a graph to a ﬁle.
procedure svgsave(fname: string)Argument
fname The (extended) ﬁlename to be used as output destination.
ExampleThis code saves a graph to the ﬁle ’mygraph.svg’ in the model working directory.
svgaddgroup("a", "Group A")
svgaddrectangle(20, 120, 200, 250)
svgsave("mygraph.svg")

Further information
This procedure can be used independently of the graphical display in order to produce output in SVG
format of the current graph deﬁnition.

Fair Isaac Corporation Conﬁdential and Proprietary Information

449

mmsvgsvgsetgraphlabels
Purpose
SynopsisSet x- and y-axis labels for a graph.
procedure svgsetgraphlabels(xlabel: text, ylabel: text)

Arguments
xlabelylabelExampleLabel text for the x-axis.
Label text for the y-axis.

The following line sets the x-axis label text to ’Time in sec’ and the y-axis label to ’Solution value’.
svgsetgraphlabels("Time in sec", "Solution value")

Further information
1. By default (no labels speciﬁed or empty strings) no label text is displayed.
2. The axes are displayed only if a label is deﬁned (for x or y axis) unless svgshowgraphaxes has been
used.
Related topics
svgsetgraphscale, svgsetgraphpointsize, svgsetgraphviewbox, svgshowgraphaxes.

Fair Isaac Corporation Conﬁdential and Proprietary Information

450mmsvgsvgsetgraphpointsize
Purpose
SynopsisSet point size property for a graph.
procedure svgsetgraphpointsize(val: real)

Argumentval
ExampleThe new value for the point size.

This code shows how to modify graph scaling properties.
svgsetgraphpointsize(0.5)
svgsetgraphscale(10)Further information
This routine is likely to be used in combination with svgsetgraphscale in order to resize a graph.
Related topics
svgsetgraphscale, svggetgraphstyle, svgsetgraphstyle, svggetgraphstylesheet,svgsetgraphstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

451

mmsvgsvgsetgraphscale
Purpose
Synopsis

Set scaling value for a graph.
procedure svgsetgraphscale(val: real)

Argumentval
ExampleThe new scaling value.

This code shows how to modify graph scaling properties.
svgsetgraphpointsize(0.5)
svgsetgraphscale(10)Further information
This routine is likely to be used in combination with svgsetgraphpointsize in order to resize agraph for display.
Related topics
svgsetgraphpointsize, svggetgraphstyle, svgsetgraphstyle, svggetgraphstylesheet,svgsetgraphstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

452

mmsvgsvgsetgraphstylePurpose
Synopsis

Set a style property of a graph.
procedure svgsetgraphstyle(prop: string, val: text|real)

Arguments
prop
val

The desired property (mmsvg constant or SVG property name).
The new value for the property (usually a text, but properties like SVG_OPACITY or
SVG_STROKEWIDTH also accept numerical values).

Return value
Value of the property or empty string.
ExampleThis code retrieves the font family deﬁned for a group and applies it to the entire graph.
svgaddgroup("g", "A group")svgsetgraphstyle(SVG_FONTFAMILY, svggetstyle("g", SVG_FONTFAMILY))

Further information
This procedure can be used to deﬁne a style property of a graph. Use svgsetgraphstylesheet todeﬁne the whole set of style properties of a graph.
Related topics
svggetstyle, svgsetstyle, svggetgraphstyle, svggetgraphstylesheet,svgsetgraphstylesheet, svggetstylesheet, svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

453

mmsvgsvgsetgraphstylesheet
Purpose
Synopsis

Set the style deﬁnitions for a graph.
procedure svgsetgraphstylesheet(stsh: array (svgstyleattrs) of text)

Argument
stsh
ExampleStyle deﬁnition.

This code retrieves the style properties of a group and applies them to the entire graph.
svgaddgroup("a", "A group")svgsetgraphstylesheet(svggetstylesheet("a"))Further information
This procedure can be used to deﬁne the set of style properties (’stylesheet’) of a graph. Use
svgsetgraphstyle to deﬁne individual style properties of a graph.
Related topics
svggetstyle, svgsetstyle, svggetgraphstyle, svgsetgraphstyle,svggetgraphstylesheet, svggetstylesheet, svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

454

mmsvgsvgsetgraphviewbox
Purpose
Synopsis

Set the visible area for a user graph.
procedure svgsetgraphviewbox(x: real, y: real, w: real, h: real)procedure svgsetgraphviewbox(box: svgbox)

Arguments
x
y
w
h
box

The x coordinate of the lower left corner.
The y coordinate of the lower left corner.
The width of the viewbox.
The height of the viewbox.
Viewbox speciﬁcation as returned by svggetgraphviewbox.

Further information
1. The viewable area is determined by its lower left corner, its width and height.
2. mmsvg automatically determines a viewbox (enclosing all speciﬁed coordinates) that can be retrieved
with svggetgraphviewbox.
Related topics
svggetgraphviewbox, svgsetgraphlabels, svgsetgraphscale.

Fair Isaac Corporation Conﬁdential and Proprietary Information

455

mmsvgsvgsetreffreq
Purpose
Synopsis

Set the refresh frequency for a graph.
procedure svgsetreffreq(val: real)

Argumentval

The new refresh frequency (maximum number of refreshs per second).

Further information
The refresh frequency indicates how often individual calls to svgrefresh are posted to the display. If
several refresh occur during the speciﬁed time span, only the last one is executed.
Related topics
svgrefresh.

Fair Isaac Corporation Conﬁdential and Proprietary Information

456

mmsvgsvgsetstylePurpose
Synopsis

Set a style property for a graphical object or object group.
procedure svgsetstyle(gid: string, prop: string, val: text|real)procedure svgsetstyle(prop: string, val: text|real)procedure svgsetstyle(obj: integer, prop: string, val: text|real)

Arguments
gid
obj
prop
val
ExampleObject group ID.
Object ID.
The desired property (mmsvg constant or SVG property name).
The new value for the property (usually a text, but properties like SVG_OPACITY or
SVG_STROKEWIDTH also accept numerical values).

This code retrieves the color of a group and applies it to an object belonging to another group.
svgaddgroup("a", "Group A")
svgaddgroup("b", "Group B")
svgaddtext("a", 20, 120, "Formatted text")
svgsetstyle(svggetlastobj, SVG_COLOR, svggetstyle("b", SVG_COLOR))

Further information
This procedure can be used to deﬁne a style property of some object or group of objects. Use
svgsetstylesheet to redeﬁne the whole set of style properties of an object or group of objects.
Related topics
svggetstyle, svggetgraphstylesheet, svgsetgraphstylesheet, svggetstylesheet,svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

457

mmsvgsvgsetstylesheet
Purpose
Synopsis

Set the style for a graphical object or object group.
procedure svgsetstylesheet(gid: string, stsh: array (svgstyleattrs) of
text)
procedure svgsetstylesheet(stsh: array(svgstyleattrs) of text)
procedure svgsetstylesheet(obj: integer, stsh: array(svgstyleattrs) of
text)

Arguments
gid
obj
stsh
ExampleObject group ID.
Object ID.
Style deﬁnition.

This code retrieves the style properties of a group and applies them to an object belonging to anothergroup.
svgaddgroup("a", "Group A")
svgaddgroup("b", "Group B")
svgaddtext("a", 20, 120, "Formatted text")
svgsetstylesheet(svggetlastobj, svggetstylesheet("b"))Further information
This procedure can be used to deﬁne a set of style properties (’stylesheet’) of some object or group of
objects. Use svgsetstyle to modify individual style properties of an object or group of objects.
Related topics
svggetstyle, svgsetstyle, svggetgraphstylesheet, svgsetgraphstylesheet,svgsetstylesheet.

Fair Isaac Corporation Conﬁdential and Proprietary Information

458

mmsvgsvgshowgraphaxes
Purpose
Synopsis

Force displaying of graph axes.
procedure svgshowgraphaxes(force:boolean)

Argument
force Decide whether graph axes must be shown when no label is deﬁned.
Further information
By default the axes are only shown if a label text is deﬁned (for x or y axis). This procedure makes it
possible to display the axes even if no label is used.
Related topics
svgsetgraphlabels.

Fair Isaac Corporation Conﬁdential and Proprietary Information

459

mmsvgsvgwaitclose
Purpose
Synopsis

Delay model termination.
procedure svgwaitclose(msg:text,mode:integer)
procedure svgwaitclose(msg:text)
procedure svgwaitclose

Arguments
msg
mode

ExampleSome message to display.
Mode of operation:0
Wait until the browser window is closed
1Same as above except if running from Workbench: termination occurs after thegraph is loaded

This code shows a typical call sequence for graphical display.
svgaddgroup("a", "Group A")
svgaddrectangle(20, 120, 200, 250)
svgrefresh! Display the graphic
svgwaitclose! Model waits here until display window is closed

Further information
1. A call to this routine is typically added to the end of any model that includes graphical display (that is,calls to svgrefresh) via mmsvg to allow the user time for inspecting the graphical output. If thissubroutine call is not present, then model termination may close the display window or prevent thebrowser to load the graph.
2. The last form of the routine is equivalent to svgwaitclose("",0).
Related topics
svgrefresh, svgclosing.

Fair Isaac Corporation Conﬁdential and Proprietary Information

460

CHAPTER 16

mmsystem
The mmsystem module provides a set of procedures and functions related to the operating system.
Note that the behavior of these operators may vary between systems. To use this module, the following
line must be included in the header of the Mosel model ﬁle:uses 'mmsystem'

16.1

New functionality for the Mosel language

16.1.1

The type text
This module provides the type text for text manipulation. Like the Mosel basic type string, this new
type may be generated from all objects that can be converted to a text representation and supports theusual string operations (like concatenation or formatting). In addition, text objects can be generated
from structured entities (like arrays or lists); altered (one can get and change a single as well as asequence of characters in a text); offer a wider set of operations (like insertion/deletion/search of
substrings) and, as all module types, are passed by reference to subroutines. Note that this typesupports implicit conversion from string: a routine expecting a text as parameter may be used witha string instead (in this case the compiler creates a temporary text from the provided string). Whencreating a text object from a structured type it is possible to specify a limit on the size of the generated
string. For instance if S is a set, text(S,128) will produce a textual representation of S of at most 128
characters.

16.1.2The type date
As the name suggests, the type date is used to represent a calendar date. Internally, a date is stored
as three independent integers for representing the year (-32768 to 32767), the month (-128 to 127) andthe day in the month (-128 to 127). The validity of a date can be checked using the function isvalid. A
date object can be initialized by a text string, a single or three numerical values. In the ﬁrst case, theconversion is processed using a predeﬁned date format (see datefmt); in the second case, the integer
is interpreted as the number of days elapsed since 1/1/1970; ﬁnally, if three integers are used, they are
respectively interpreted as the year, month and day for the date. The constant SYS_NOW may also be
used to initialize a date: date(SYS_NOW) is the current date (local time). This type also supports
creation of constants (i.e. it can be used in sets of constants), assignment, comparison as well as
difference (returned in number of days) and addition/subtraction of an integer (number of days).

16.1.3

The type time
The type time is used to represent a time during the day. Internally, a time object is stored as aninteger representing a number of milliseconds. A time object can be initialized by a text string or one tofour numerical values. In the ﬁrst case, the conversion is processed using a predeﬁned time format

Fair Isaac Corporation Conﬁdential and Proprietary Information

461

mmsystem(see timefmt); in the second case, the integer is interpreted as a number of milliseconds. When two tofour integers are used, they are understood as the hours, minutes, seconds and milliseconds. The
constant SYS_NOW may also be used to initialize a time: time(SYS_NOW) is the current time (localtime). This type also supports creation of constants (i.e. it can be used in sets of constants),
assignment, comparison as well as difference (returned in number of milliseconds) andaddition/subtraction of an integer (number of milliseconds).

16.1.4

The type datetime
The type datetime is used to represent a timestamp by combining a date and a time. A datetime
object can be initialized by a text string, a pair date and time or a numerical value. In the ﬁrst case, theconversion is processed using a predeﬁned time format (see datetimefmt); in the third case, thenumber is interpreted as the number of seconds elapsed since 1/1/1970 at midnight. If the provided
number is a real value, the fractional part is stored as a number of milliseconds. The constant SYS_NOW
may also be used to initialize a datetime: datetime(SYS_NOW) is the current date and time (localtime). This type also supports creation of constants (i.e. it cand be used in sets of constants),
assignment, comparison as well as difference (returned in number of seconds) andaddition/subtraction of a numerical value (number of seconds).

16.1.5The type parsectx
This module publishes a set of routines for parsing input text strings (for instance parseint or
nextfield). These routines use several module parameters for both their conﬁguration and as a way
to record their internal state: a variable of type parsectx may be used as a replacement for thesemodule parameters in order to implement parsing procedures independent of the rest of the program.
A single parsectx object integrates endparse (see sys_endparse), sepchar (see sys_sepchar),trim (see sys_trim) and qtype (see sys_qtype). The current value of each of these components
can be accessed using the corresponding set and get routine (for instance getendparse).

16.1.6

The type textarea
The textarea type is used by the regular expression matching function regmatch to return locationsin the input string. Each text area is deﬁned by a starting position (that is an offset in the original string)
and an ending position characterised by the offset of the character following the region to beconsidered. Functions getstart and getsucc can be used to retrieve these properties.
For instance, the following statement displays the region ta of the text txt:
writeln(copytext(txt,ta.start,ta.succ-1))

This can also be written as follows:
writeln(copytext(txt,ta))

16.2

Control parameters
Via the getparam function and the setparam procedure it is possible to access the following control
parameters of module mmsystem (the reader is reminded that parameters may be spelled with lower orupper case letters or a mix of both):datefmt

Date text format.

p. 463

datetimefmt

Date and time text format.

p. 464

Fair Isaac Corporation Conﬁdential and Proprietary Information462

mmsystem

monthnames

List of month names.

p. 464

sys_endparse

End of parsing position.

p. 465sys_fillchar

Padding character for text resize.

p. 465sys_pid

Process identiﬁcation.

p. 465sys_qtype

Text quoting convention.

p. 465sys_regcache

Number of regular expressions in cache.

p. 466sys_sepchar

Separator character.

p. 466

sys_trim

Whether to trim spaces in text parsing.

p. 466

sys_txtmem

Size of the text block.

p. 467

timefmt

Time text format.

p. 463

datefmt
Description

Deﬁne the text format for both reading and writing a date.

Type

String, read/write

Default value"%.y-%0m-%0d"

Note

The date format consists in a text string in which the date information (like day number) is
speciﬁed using tags. A tag begins by the character "%" optionally followed by "." or "0" anda character indicating which speciﬁc information must be provided. The possible values are:
C Century
Y Year number in the century
y Yearm Month (1-12)
N Name of month according to parameter monthnamesd Day (1-31)% The symbol "%"If the second character is used, the corresponding information is produced in ﬁxed format
with space (".") or zero ("0") as the padding character. For instance, the day 1 will be
displayed as "1" with the format "%d"; as " 1" with "%.d" and as "01" with "%0d".

See also

datetimefmt,monthnames

Modulemmsystem

timefmt
Description

Deﬁne the text format for both reading and writing time.

Type

String, read/write

Default value"%0H:%0M:%0S%f"

Fair Isaac Corporation Conﬁdential and Proprietary Information

463

mmsystem

Note

The time format consists in a text string in which the time information (like number of
seconds) is speciﬁed using tags. A tag begins by the character "%" optionally followed by"." or "0" and a character indicating which speciﬁc information must be provided. The
possible values are:
H Hour (0-23)
h Hour (1-12)
M Minute (0-59)
S Seconds (0-59)
s Milliseconds (0-999)
f Milliseconds as a fractonal value with a comma as the decimal separator (,001-,999)
F Milliseconds as a fractonal value with a dot as the decimal separator (.001-.999)
p text "pm" or "am"P text "PM" or "AM"% The symbol "%"If the second character is used, the corresponding information is produced in ﬁxed format
with space (".") or zero ("0") as the padding character. For instance, the hour 1 will be
displayed as "1" with the format "%H"; as " 1" with "%.H" and as "01" with "%0H". Whenthe formats f or F are used for parsing they both accept dot and comma as the decimal
separator. The formats f and F without second character ("." or "0") display nothing if thenumber of milliseconds is 0.

See also

datetimefmt

Modulemmsystem

datetimefmt
Description

Deﬁne the text format for both reading and writing a datetime object.

Type

String, read/write

Default value"%.y-%0m-%0dT%0H:%0M:%0S%f"

Note

The datetime format accepts the syntaxes of the date format and the time format in the same
string.

See also

datefmt,timefmt

Modulemmsystemmonthnames
Description

Deﬁne month names to be used with the %N format.

Type

String, read/write

Default value"jan feb mar apr may jun jul aug sep oct nov dec"

NoteThis parameter is used when converting dates from/to strings with the %N format. The string
must contain 12 words separated by spaces. For conversions from strings, the comparison is
not case sensitive.

See also

datefmt,datetimefmt

ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

464

mmsystem

sys_endparse
Description

Index in the text string where the parsing stopped. This parameter is updated and may be
used (as a starting position) by the parse⁎ routines.

Type

Integer, read/write

Set by routinesparseint, parsereal, parseextn, parsetext, nextfield

Modulemmsystem

sys_ﬁllchar
Description

Character code used to ﬁll empty regions generated in text strings when using the function
setchar.

Type

Integer, read/write

Values

Between 1 and 127

Default value

32 (space character)

Affects routines

setcharModulemmsystem

sys_pid
Description

System identiﬁcation (Process ID) of the process running Mosel.

Type

Integer, read only

Default value

assigned by the operating system

Modulemmsystem

sys_qtype
Description

Convention to use when quoting/parsing a text string.

Type

Integer, read/write

Default value

0

Fair Isaac Corporation Conﬁdential and Proprietary Information

465

mmsystem

Note

Supported quoting conventions are:0
Mosel: strings optionally quoted with either single or double quotes. With double quotes, escape sequences starting with the backslash character ("\") aresupported
1
C/C++: double quotes with escape sequences starting with the backslashcharacter ("\")
2
CSV: strings are optionally quoted with double quotes. The symbol "double
quotes" is doubled when it is included in a quoted string-1 No quoting

Affects routinesparsetext, quote

Modulemmsystem

sys_regcache
Description

Regular expression searches require a compilation procedure to be performed before theactual search. In order to speedup handling of expressions, a number of compiled
expressions are saved in a cache pool: this parameter speciﬁes the size of this pool. Notethat setting this parameter has the effect of clearing the cache (even if the pool size if kept
unchanged).

Type

Integer, read/write

Values

Between 1 and 25

Default value

3

Affects routines

regmatch, regreplace

Modulemmsystem

sys_sepchar
Description

Character code used as a ﬁeld separator for text parsing routines.

Type

Integer, read/write

Values

Between 1 and 127

Default value

32 (space character)

Affects routinesparsetext, quote, nextfield

Modulemmsystem

sys_trim
Description

If this parameter is true, function nextfield skips blank characters around ﬁeld
separators.

Fair Isaac Corporation Conﬁdential and Proprietary Information

466

mmsystemType

Boolean, read/write

Default valuetrue

Affects routines

nextfield

Set by routines

nextfield

See also

sys_sepchar

Modulemmsystem

sys_txtmem
Description

All text objects are stored in a single block of memory. This parameter corresponds to thesize of this block expressed in kilobytes. Changing this value makes it possible either topre-allocate memory by increasing the size of the block or release unused memory by
reducing its size. If the requested size is not large enough to contain the currently deﬁned text
objects, the memory block is reduced to the smallest possible size.

Type

Integer, read/write

Default value

0 (at program startup)

Modulemmsystem

16.3

Procedures and functions
In general, the procedures and functions of mmsystem do not fail but set a status variable that can beread with getsysstat. To make sure the operation has been performed correctly, check the value of
this variable after each system call.
addmonths

Add a number of months to a date or datetime.

p. 471compareic

Compare 2 text strings ignoring case.

p. 472

copytext

Copy a part of a text or string.

p. 473cuttext

Cut a part of a text returning a copy of the deleted string.

p. 474deltext

Delete a part of a text.

p. 475endswith

Check whether a text or string ends with a given string.

p. 476erase

Securely deletes the content of a text entity.

p. 477

expandpath

Expand a path or ﬁle name.

p. 478fcopy

Copy a ﬁle.

p. 479fdeleteDelete a ﬁle.

p. 480findfiles

Search for ﬁles according to ﬁle name patterns.

p. 481

findtext

Search for a string in a text or string.

p. 482

fmove

Rename or move a ﬁle.

p. 483

Fair Isaac Corporation Conﬁdential and Proprietary Information

467

mmsystem

formattext

Create a text from a format string and its parameters.

p. 484

getasnumber

Convert a date, time or datetime into a number.

p. 486getcharGet a character in a string or text.

p. 487

getcwdGet the current working directory.

p. 488getdateGet the date part of a datetime.

p. 489getdayGet the day number in the month of a date or datetime.

p. 490getdaynum

Get the day number in the year of a date or datetime.

p. 491getdaysGet the number of days of a month.

p. 492

getdirsep

Get the directory separator of the running operating system.

p. 493getdsoparamGet the value of a control parameter.

p. 494getendparse, setendparse Get and set endparse property of a parser context.

p. 495getenv

Get the value of an environment variable.

p. 496

getfsize

Get the size of a ﬁle.

p. 497

getfstat, getflstat Get the status of a ﬁle or directory.

p. 498getftime

Get time information of a ﬁle.

p. 499gethour

Get the hour part of a time or datetime.

p. 500getminuteGet the minute part of a time or datetime.

p. 501

getmonth

Get the month number of a date or datetime.

p. 502

getmsec

Get the millisecond part of a time or datetime.

p. 503getoserrmsg

Get the message associated to a system error code.

p. 505getoserror

Get the system error code of the last command.

p. 504getpathsep

Get the path separator of the running operating system.

p. 506

getqtype, setqtype

Get and set qtype property of a parser context.

p. 508getsecondGet the second part of a time or datetime.

p. 509getsepchar, setsepchar

Get and set sepchar property of a parser context.

p. 510getsizeGet the size of a text.

p. 511getstart, setstart

Get and set start property of a text area.

p. 512

getsucc, setsucc

Get and set succ (position of successor character) property of a text area.
p. 507

getsysinfo

Get information about the running operating system.

p. 513getsysstat

Get the system status.

p. 514gettimeGet a time measure or the time part of a datetime.

p. 515gettmpdir

Get the temporary directory as a text object.

p. 516

gettrim, settrim

Get and set trim property of a parser context.

p. 517

Fair Isaac Corporation Conﬁdential and Proprietary Information

468

mmsystem

getweekday

Compute the day of the week for a date or datetime.

p. 518getyearGet the year part of a date or datetime.

p. 519inserttext

Paste a text or string into a text.

p. 520isvalid

Check whether a date, time or datetime is valid.

p. 521

jointext

Merge elements of a list or set into a text string.

p. 522

makedir

Create a new directory in the given ﬁle system.

p. 523

makepath

Create a new directory including its parents if necessary.

p. 524

newtarCreate a Unix tar archive from a list of ﬁles.

p. 525newzipCreate a Zip archive from a list of ﬁles.

p. 526

nextfield

Advance to next ﬁeld in a structured text string.

p. 527

openpipe

Start an external process for bidirectional communication.

p. 528parseextn

Initialise an object of a module type from a text.

p. 529parseint

Convert a text into an integer.

p. 530parsereal

Convert a text into a real.

p. 532parsetext

Extract a text from a text.

p. 533

pastetext

Paste a text or string into a text.

p. 535

pathmatch

Check whether a ﬁle name matches a given pattern.

p. 536

pathsplit

Split a path into its components.

p. 537

qsort

Sort a list or an array or (a subset of) the indices of an array.

p. 538quote

Quote and encode a text string.

p. 540

readlink

Get the value of a symbolic link.

p. 541

readtextline

Read a line of text from the current input stream.

p. 542regmatchCompare text strings using a regular expression.

p. 543regreplace

Replace portions of a text string based on a regular expression.

p. 545

removedir

Remove a directory.

p. 546

removefiles

Remove ﬁles selected using ﬁle name patterns.

p. 547setcharSet a character in a text.

p. 548setdateSet the date part of a datetime.

p. 549setdaySet the day number of a date or datetime.

p. 550setdsoparamSet the value of a control parameter.

p. 551

setenv

Set the value of an environment variable.

p. 552sethour

Set the hour part of a time or datetime.

p. 554

setminuteSet the minute part of a time or datetime.

p. 555

setmonth

Set the month number of a date or datetime.

p. 556

Fair Isaac Corporation Conﬁdential and Proprietary Information469

mmsystem

setmsec

Set the millisecond part of a time or datetime.

p. 557

setoserror

Set the current system error code.

p. 553setsecond

Set the second part of a time or datetime.

p. 558settimeSet the time part of a datetime.

p. 559setyearSet the year part of a date or datetime.

p. 560sleep

Suspend execution for a ﬁxed amount of time.

p. 561

splittext

Split a text string.

p. 562startswith

Check whether a text or string starts with a given string.

p. 563symlink

Create a symbolic link.

p. 564systemExecute an external program.

p. 565tarlistGet the list of ﬁles included in a Unix tar archive.

p. 566

textfmt

Create a formatted text from a string, a text or a number.

p. 567

tolower

Generate the lowercase version of the provided text.

p. 569

toupper

Generate the uppercase version of the provided text.

p. 570trim

Remove blank characters at the beginning and/or end of a text string.
p. 571

untar

Extract ﬁles from a Unix tar archive.

p. 572

unzip

Extract ﬁles from a Zip archive.

p. 573ziplistGet the list of ﬁles included in a Zip archive.

p. 574

Fair Isaac Corporation Conﬁdential and Proprietary Information

470

mmsystem

addmonths
Purpose
Synopsis

Add a number of months to a date or datetime.
function addmonths(d:date, nbm:integer):datefunction addmonths(dt:datetime, nbm:integer):datetime

Argumentsddt
nbm

A date object
A datetime object
The number of months to be added (can be negative)

Return value
The modiﬁed date or datetime.
Examplewriteln(addmonths(date(2000,1,31),1))! displays: 2000-02-29
writeln(addmonths(date(2012,12,12),-12)) ! displays: 2011-12-12
Further information
The day number is preserved unless it is not compatible with the computed month: in this case the day
number is moved to the last day of the month.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

471

mmsystemcompareic
Purpose
Synopsis

Compare 2 text strings ignoring case.
function compareic(arg1:string|text, arg2:string|text):integer

Arguments
arg1
arg2

First operand for the comparison
Second operand for the comparison

Return value
0 if strings are identical, -1 if the ﬁrst string is less than the second string and 1 otherwise.
Further information
This function behaves like compare but ignoring case.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

472

mmsystem

copytext
Purpose
Synopsis

Copy a part of a text or string.
function copytext(t:text|string, i1:integer, i2:integer):text
function copytext(t:text|string, ta:textarea):text

Arguments
t
i1
i2
ta

A string or text object
Starting position of the region to copy
End position of the region to copy
A text area object

Return value
A copy of the region.
ExampleThe following:
writeln(copytext("abcdefgh",3,7))
writeln(copytext("abcdefgh",7,10))
produces this output:
cdefg
gh

Further information
This function returns an empty text if the bounds are not compatible with the string (e.g. starting
position larger than the length of the string) or inconsistent (e.g. starting position after end position).
Related topics
deltext, inserttext, pastetext, cuttext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

473

mmsystem

cuttext
Purpose
SynopsisCut a part of a text returning a copy of the deleted string.
function cuttext(txt:text, i1:integer, i2:integer):text
function cuttext(txt:text, ta:textarea):text

Arguments
txt
i1
i2
ta

A text object
Starting position of the region to cut
End position of the region to cut
A text area object

Return value
A copy of the region. The input text is modiﬁed accordingly.
ExampleThe following:t:=text("abcdefgh")writeln(cuttext(t,3,7))
writeln(t)produces this output:
cdefg
abh

Further information
This function returns an empty text if the bounds are not compatible with the string (e.g. starting
position larger than the length of the string) or inconsistent (e.g. starting position after end position).
Related topics
deltext, inserttext, pastetext, copytext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

474

mmsystem

deltext
Purpose
Synopsis

Delete a part of a text.
procedure deltext(txt:text, i1:integer, i2:integer)
procedure deltext(txt:text, ta:textarea)

Arguments
txt
i1
i2
ta
ExampleA text object
Starting position of the region to delete
End position of the region to delete
A text area object

The following:t:=text("abcdefgh")deltext(t,3,7)
writeln(t)produces this output:
abh

Related topics
cuttext, inserttext, pastetext, copytext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

475

mmsystemendswith
Purpose
SynopsisCheck whether a text or string ends with a given string.
function endswith(txt:text|string, tofs:text|string):boolean

Arguments
txt
tofs

A string or text object
String to ﬁnd

Return value
true if the ending of txt corresponds to tofs.
Related topics
startswith
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

476

mmsystem

erase
Purpose
Synopsis

Securely deletes the content of a text entity.
procedure erase(txt:text)

Argumenttxt

A text object to be erased

Further information
This function resets the text string it receives after having replaced each of its characters by a space.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

477

mmsystem

expandpath
Purpose
Synopsis

Expand a path or ﬁle name.
function expandpath(fname:string|text):text

Argument
fname File name to be expanded
Return value
An absolute path to the given ﬁle name.
Further information
This function expands a path or ﬁle name: it replaces all relative references (like "." or "..") andcompletes the path such that the returned string is an absolute path to the provided ﬁle name.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

478

mmsystem

fcopy
Purpose
Synopsis

Copy a ﬁle.
procedure fcopy(namesrc:string|text, namedest:string|text)
procedure fcopy(namesrc:text, opts:integer, namedest:text, optd:integer)

Arguments
namesrc
opts
namedest
optd
ExampleThe name of the ﬁle to be copied
Open options for the input ﬁleThe destination nameOpen options for the output ﬁleThe following statement appends ﬁle "src" to ﬁle "dst":
fcopy("src",0,"dst",F_APPEND)

Further information
1. This procedure copies the ﬁle namesrc to namedest (that is replaced if it already exists). The
provided names may use extended notation.
2. With the second form of the procedure it is possible to select options used to open the 2 ﬁles (as usedwith the fopen procedure). The ﬁrst syntax corresponds to:
fcopy(src,F_SILENT+F_BINARY,dst,F_SILENT+F_BINARY)
Related topics
fopen
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

479

mmsystem

fdeletePurpose
Synopsis

Delete a ﬁle.
procedure fdelete(filename:string|text)

Argument
filename The extended name of the ﬁle to be deleted
Further information
The provided name may use extended notation.
Related topics
removedir, removefiles.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

480mmsystem

ﬁndﬁles
Purpose
Synopsis

Search for ﬁles according to ﬁle name patterns.
procedure findfiles(opt:integer,lsf:list of text,
dir:string|text,filters:string|text)
procedure findfiles(opt:integer,lsf:list of text,filters:string|text)
procedure findfiles(lsf:list of text,filters:string|text)
procedure findfiles(lsf:list of text)

Arguments
opt

Options (several options can be combined):

SYS_RECURS
Recursive search in subdirectories
SYS_NODIR
Do not report directories (only ﬁles)SYS_DIRONLY Report only directories
SYS_REVORD
Reverse sort order
SYS_NOSORTDo not sort resulting list
lsf
Resulting list of ﬁle names
dirBase directory for the search (default: current directory)
filters File name ﬁlters (default: all ﬁles reported)
ExampleThe following prints the list of ﬁles with extension .mos and .bim of the current directory:
findfiles(lsf,"⁎.mos|⁎.bim")
writeln(lsf)

Further information
1. The filters argument consists in a list of patterns separated by the symbol ";": for each of thesepatterns the function executes a search from the speciﬁed dir directory. A pattern is composed of apath (using the usual operating system conventions) which last component may include wildcard
characters "⁎" (any text of any length), "?" (any single character) and "|" (logical "or"). For instance"bin/⁎.exe;models/⁎.mos|⁎.dat" will select all ﬁles with extension ".exe" in the "bin"directory as well as ﬁles with extension ".mos" and ".dat" in the "models" directory.
2. File name matching is achieved using function pathmatch and differences may be observed
depending on the operating system (e.g. ﬁle names are case sensitive under Posix systems but notunder Windows).
3. Unless option SYS_NOSORT is used, the resulting list is sorted and duplicate entries are removed. Notealso that the provided list lsf is not reset: the result of the search is appended to this list.
Related topics
removefiles
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

481

mmsystem

ﬁndtext
Purpose
Synopsis

Search for a string in a text or string.
function findtext(txt:text, toft:text, start:integer):integerfunction findtext(txt:text, tofs:string, start:integer):integerfunction findtext(str:string, tofs:string, start:integer):integer

Arguments
txt
str
toft
tofs
start

A text object
StringText to ﬁnd
String to ﬁnd
Starting position for the search

Return value
Index of the string or 0 if not found.
ExampleThe following:
writeln(findtext("abcdefgh","de",2))writeln(findtext("abcdefgh","de",5))produces this output:
40

Related topics
regmatch
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

482

mmsystemfmove
Purpose
Synopsis

Rename or move a ﬁle.
procedure fmove(namesrc:string|text,namedest:string|text)

Arguments
namesrc
The name of the ﬁle to be moved or renamed
namedest The destination name and/or path
Further information
This procedure renames the ﬁle namesrc to namedest. If the second name is a directory, the ﬁle is
moved into that directory; if it is an existing ﬁle it is ﬁrst removed before the renaming. The provided
names may use extended notation.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

483

mmsystem

formattext
Purpose
SynopsisCreate a text from a format string and its parameters.
function formattext(fmt:string, a1, a2...):text
function formattext(fmt:string, l: list):text

Arguments
fmt
ailFormat string
Parameters of the format string
List of parameters of the format string

Return value
Formatted text.
ExampleThe following:
writeln(formattext("text1%8stext3", "text2"))
writeln(formattext("text1%-8stext3", "text2"))r:=789.123456
writeln(formattext("%1$r %1$4.2f%1$8.0f",r))produces this output:
text1
text2text3
text1text2
text3
789.123 789.12

789

Fair Isaac Corporation Conﬁdential and Proprietary Information

484

mmsystem

Further information
1. This procedure behaves in a similar way as the sprintf function of the C language: the resulting text
is generated by inserting each of the parameters ai in the format string at locations identiﬁed by amarker. This marker is of the form:%[index$][flags][width][.precision]conv

Where index (a non negative integer), ﬂags (string of ’ ’, ’-’, ’+’, ’0’ and ’#’), width (positive
integer) and precision (non negative integer) are optional.
The index indicates which parameter to use for the conversion (ﬁrst parameter has number 1), when it is
not speciﬁed the marker position is used instead (e.g. the third marker is used for the third parameter).
The ﬂags essentially affect numerical conversions: with the ﬂag ’0’ the value is zero padded; with ’-’
the value is left justiﬁed; with a space a blank is put before positive numbers and with ’+’ positive
numbers are preceded by the ’+’ sign.
The width deﬁnes a minimum width for the ﬁeld.
The precision gives the minimum number of digits to appear for an integer conversion. With a ﬂoating
point value and a conversion ’a’, ’A’, ’e’, ’E’ or ’f’ it states the number of digits to appear after
the radix and for a ’g’ conversion it is the maximum number of signiﬁcant digits. The precisionindicates a maximum number of characters to display with textual conversions.
The conversion speciﬁer conv is a letter indicating how to process the corresponding parameter andwhat to ouput. Possible values for this character are:diouxX an integer value is output: the parameter must be an integer or a Boolean. The value isdisplayed as a decimal number (’d’ or ’i’), an octal number (’o’), an unsigned number(’u’) or a hexadecimal number (’x’ or ’X’)
eEfgraA a real value is output: the parameter must be a real or an integer. When using the ’r’
conversion the optional part components of the marker are ignored and the value is converted
using the current real printing format (according to realfmt and zerotol parameters, seesetparam). The conversion ’e’ and ’E’ format the number as [-]d.ddde+/-dd;
conversion ’f’ uses a format of the form [-]ddd.ddd and conversion ’g’ selects format’e’ or ’f’ depending on the value of the number. With ’a’ and ’A’ the value is converted toan hexadecimal representation of the form [-]0xh.hhhp[+/-]ddd where ’h’ arehexadecimal digits and ’d’ decimal digits.
b’true’ or ’false’ is output: the parameter must be a Booleanca character is output: the parameter must be an integer that is interpreted as a Unicode codepointsa text string is output: the parameter must be a string or any type supporting conversion to textpa pointer expressed in hexadecimal is output: the parameter can be any referenced entity
2. To include the symbol ’%’ in the format string use the sequence ’%%’.
Related topics
textfmt
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

485

mmsystem

getasnumber
Purpose
Synopsis

Convert a date, time or datetime into a number.
function getasnumber(d:date):integerfunction getasnumber(t:time):integerfunction getasnumber(dt:datetime):realArgumentsdt
dt

A date object
A time object
A datetime object

Return value
The numerical representation of the argument.
Further information
A date is converted to an integer Julian Day Number (number of days since 1/1/1970 at midnight). Thisfunction returns an integer number of milliseconds for a time and a real number of seconds for a
datetime. This number represents the number of seconds and milliseconds (as the fractional part of
the number) since 1/1/1970 at midnight.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

486

mmsystem

getchar
Purpose
Synopsis

Get a character in a string or text.
function getchar(txt:text, index:integer):integerfunction getchar(str:string, index:integer):integer

Argumentstxt
A text object
str
Stringindex Position of the character
Return value
Character code or -1 if the index is not valid.
Related topics
setcharModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

487

mmsystem

getcwdPurpose
Synopsis

Get the current working directory.
function getcwd:string

Return value
The current working directory.
Further information
1. This function returns the current working directory, that is the directory where the model is being
executed and where ﬁles are looked for.
2. The returned value corresponds to getparam("workdir"). The current working directory can also
be changed via this control parameter (for instance setparam("workdir","../somedir").
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

488

mmsystem

getdatePurpose
Synopsis

Get the date part of a datetime.
function getdate(dt:datetime):dateArgumentdt

A datetime object

Return value
A date object.
Related topics
gettime, getasnumber
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

489

mmsystem

getdayPurpose
Synopsis

Get the day number in the month of a date or datetime.
function getday(d:date):integerfunction getday(dt:datetime):integer

Argumentsddt

A date object
A datetime object

Return value
Day number in the month.
Related topics
getyear, getmonth, getdaynum
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

490

mmsystem

getdaynum
Purpose
Synopsis

Get the day number in the year of a date or datetime.
function getdaynum(d:date):integerfunction getdaynum(dt:datetime):integer

Argumentsddt

A date object
A datetime object

Return value
Day number in the year.
Examplewriteln(getdaynum(date(2010,2,1)))! displays: 32

Related topics
getdayModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

491

mmsystem

getdays
Purpose
Synopsis

Get the number of days of a month.
function getdays(y:integer, m:integer):integerfunction getdays(d:date):integerfunction getdays(dt:datetime):integer

Arguments
y
m
d
dt

Year
Month
A date object
A datetime object

Return value
Number of days for the given month in the speciﬁed year.
Examplewriteln(getdays(2016,2))
Module! displays: 29

mmsystemFair Isaac Corporation Conﬁdential and Proprietary Information492

mmsystem

getdirsep
Purpose
Synopsis

Get the directory separator of the running operating system.
function getdirsep:string

Return value"/" on Posix systems and "\" on Windows.
Related topics
getpathsep
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information493

mmsystem

getdsoparam
Purpose
Synopsis

Get the value of a control parameter.
function getdsoparam(name:string|text):text

Argument
name

Name of a control parameter (including the module name).

Return value
Current setting of the control parameter as a text.
Further information
1. This function is similar to getparam except that the control parameter name is searched at runtime.
As a consequence this identiﬁer does not need to be a constant string but the execution is signiﬁcantly
slower than getparam and it cannot be applied to package parameters.
2. The provided parameter name must include the module name (e.g. "mmsystem.datefmt") otherwise
the identiﬁer is searched only in the list of Mosel parameters.
3. As opposed to getparam this procedure does not raise an error in case of failure (like parameter notfound): use getsysstat to detect error conditions.
Related topics
setdsoparam.

Fair Isaac Corporation Conﬁdential and Proprietary Information494

mmsystem

getendparse, setendparse
Purpose
Synopsis

Get and set endparse property of a parser context.
function getendparse(pctx:parsectx):integer
procedure setendparse(pctx:parsectx, ep:integer)

Arguments
pctx
ep

A parser context
New endparse value

Return value
Current endparse value stored in the context.
Related topics
sys_endparse, getsepchar, gettrim, getqtype
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

495

mmsystem

getenv
Purpose
Synopsis

Get the value of an environment variable of the operating system.
function getenv(name:string|text):stringArgument
name

Name of the environment variable

Return value
Value of the environment variable (an empty string if the variable is not deﬁned).
Further information
This procedure is included in the published interface of mmsystem (see Section 16.5).
ExampleThe value of the environment variable PATH is retrieved as follows:
str:= getenv("PATH")

Related topics
setenvModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

496

mmsystem

getfsize
Purpose
Synopsis

Get the size of a ﬁle.
function getfsize(filename:string|text):integer

Argument
filename Name (and path) of the ﬁleReturn value
The size of the ﬁle in bytes or -1 in case of error
Further information
The function returns -1 if the ﬁle cannot be found or accessed and MAX_INT if the size exceeds theinteger capacity (~2Gb).
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

497

mmsystem

getfstat, getﬂstat
Purpose
Synopsis

Get the status (type and access mode) of a ﬁle or directory.
function getfstat(filename:string|text):integerfunction getflstat(filename:string|text):integer

Argument
filename Name (and path) of the ﬁle or directory to check
Return value
Bit encoded type and mode of the given ﬁle or 0 if the ﬁle cannot be accessed.
ExampleThe following determines whether ftest is a directory and if it is writable:
fstat:= getfstat("ftest")
if bittest(fstat, SYS_TYP)=SYS_DIR
then writeln("ftest is a directory")
end-ifif bittest(fstat, SYS_WRITE)=SYS_WRITE
then writeln("ftest is writeable")
end-ifFurther information
1. The returned status type may be decoded using the constant mask SYS_TYP (the types are exclusive).
Possible values are:
SYS_DIR Directory
SYS_REG Regular ﬁle
SYS_LNK Symbolic link
SYS_OTH Special ﬁle (device, pipe...)
The access mode may be decoded using the constant mask SYS_MOD (the access modes are
additive). Possible values are:
SYS_READ Can be read
SYS_WRITE Can be modiﬁed
SYS_EXEC Is executable
2. The 2 versions of this function behave the same except for symbolic links: the ﬁrst one (getfstat)reports the properties of the linked ﬁle while the second (getﬂstat) reports a type SYS_LNK.
Related topics
readlink
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

498

mmsystem

getftime
Purpose
Synopsis

Get time information of a ﬁle.
function getftime(filename:string|text,what:integer):realArguments
filename Name (and path) of the ﬁlewhat
Information requested. Possible values:
SYS_FTIM_ACC Last access
SYS_FTIM_MOD Last modiﬁcation
Return value
The time requested as the number of seconds elapsed since 1/1/1970 at midnight or 0 in case of error.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information499

mmsystem

gethour
Purpose
Synopsis

Get the hour part of a time or datetime.
function gethour(t:time):integerfunction gethour(dt:datetime):integer

Argumentst
dt

A time object
A datetime object

Return value
Hour as an integer.
Related topics
getminute, getsecond, getmsec
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

500mmsystem

getminutePurpose
Synopsis

Get the minute part of a time or datetime.
function getminute(t:time):integerfunction getminute(dt:datetime):integer

Argumentst
dt

A time object
A datetime object

Return value
Minute as an integer.
Related topics
gethour, getsecond, getmsec
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

501

mmsystem

getmonth
Purpose
Synopsis

Get the month number of a date or datetime.
function getmonth(d:date):integerfunction getmonth(dt:datetime):integer

Argumentsddt

A date object
A datetime object

Return value
Month number in the year.
Related topics
getyear, getday

Fair Isaac Corporation Conﬁdential and Proprietary Information502

mmsystem

getmsec
Purpose
Synopsis

Get the millisecond part of a time or datetime.
function getmsec(t:time):integerfunction getmsec(dt:datetime):integer

Argumentst
dt

A time object
A datetime object

Return value
Millisecond as an integer.
Related topics
gethour, getminute, getsecond
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information503

mmsystem

getoserror
Purpose
Synopsis

Get the system error code of the last command.
function getoserror:integer

Return value
A system error code or 0 if the last operation of the module was executed sucessfully.
Further information
This function reports the current system error code (corresponding to the C-variable errno on Posix
and the C-function GetLastError() on Windows): it can be used after getsysstat has returned a
non-zero status to get the actual system error (if the failure was actually due to a system error). This
code is system dependent but the corresponding error message might be retrieved using
getoserrmsg.
Related topics
setoserror
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information504

mmsystem

getoserrmsg
Purpose
Synopsis

Get the message associated to a system error code.
function getoserrmsg(ec:integer):text

Argumentec

A system error code

Return value
The message corresponding to the provided code or an empty string if the code is not known.
Further information
This function returns an explanatory message associated to the error code obtained fromgetoserror.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

505

mmsystem

getpathsep
Purpose
Synopsis

Get the path separator of the running operating system.
function getpathsep:string

Return value":" on Posix systems and ";" on Windows.
Related topics
getdirsep
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

506

mmsystem

getsucc, setsucc
Purpose
Synopsis

Get and set succ (position of successor character) property of a text area.
function getsucc(ta:textarea):integer
procedure setsucc(ta:textarea, st:integer)

Argumentstast

A text area object
New succ value

Return value
Current succ value stored in the object.
Related topics
getstart
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

507

mmsystem

getqtype, setqtype
Purpose
Synopsis

Get and set qtype property of a parser context.
function getqtype(pctx:parsectx):integer
procedure setqtype(pctx:parsectx, qt:integer)

Arguments
pctx
qt

A parser context
New qtype value

Return value
Current qtype value stored in the context.
Related topics
sys_qtype, getsepchar, gettrim, getendparse
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information508

mmsystem

getsecond
Purpose
Synopsis

Get the second part of a time or datetime.
function getsecond(t:time):integerfunction getsecond(dt:datetime):integer

Argumentst
dt

A time object
A datetime object

Return value
Second as an integer.
Related topics
gethour, getminute, getmsec
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information509

mmsystem

getsepchar, setsepchar
Purpose
Synopsis

Get and set sepchar property of a parser context.
function getsepchar(pctx:parsectx):integer
procedure setsepchar(pctx:parsectx, sc:integer)

Arguments
pctx
sc

A parser context
New sepchar value

Return value
Current sepchar value stored in the context.
Related topics
sys_sepchar, getendparse, gettrim, getqtype
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

510mmsystem

getsize
Purpose
Synopsis

Get the size of a text.
function getsize(txt:text):integerfunction getsize(ta:textarea):integer

Argumentstxt
ta

A text object
A text area object

Return value
The number of characters included in the text or text area.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

511

mmsystem

getstart, setstartPurpose
Synopsis

Get and set start property of a text area.
function getstart(ta:textarea):integer
procedure setstart(ta:textarea, st:integer)

Argumentstast

A text area object
New start value

Return value
Current start value stored in the object.
Related topics
getsucc
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

512mmsystem

getsysinfo
Purpose
Synopsis

Get information about the running operating system.
function getsysinfo:string
function getsysinfo(what:integer):string
function getsysinfo(I:Mosel):string
function getsysinfo(I:Mosel,what:integer):stringArguments
what

I

What information to collect:
SYS_NAME Name of the operating system
SYS_VER
Version name of the operating system
SYS_REL
Release number of the operating system
SYS_PROC Processor type
SYS_ARCH Processor architecture (32 or 64 bit)
SYS_NODE Computer name
SYS_RAM
Total amount of system memory (in megabytes)
A Mosel instance

Return value
A text string reporting the requested information.
ExampleThe following prints the computer name and its operating system version:
writeln("Node ",getsysinfo(SYS_NODE)," is running ",getsysinfo(SYS_NAME+SYS_REL))

Further information
1. Several information items can be obtained in a single call by summing up the option codes. In such acase, the resulting string consists in the different items separated by commas.
2. When the function is used without the what parameter, all information items are returned.
3. This function may also be used with a Mosel instance as its ﬁrst parameter. In this case the returned
information relates to the system running this instance instead of the current system.
Related topics
mmjobsModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

513

mmsystem

getsysstat
Purpose
Synopsis

Get the system status.
function getsysstat:integer

Return value
0 if the last operation of the module was executed sucessfully.
ExampleIn this example we attempt to delete the ﬁle randomfile. If this is unsuccessful, a warning message
is displayed:fdelete("randomfile")
if getsysstat <> 0 thenwriteln("randomfile could not be deleted.")end-ifRelated topics
getoserror, getoserrmsg
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

514

mmsystem

gettime
Purpose
Synopsis

Get a time measure or the time part of a datetime.
function gettime:realfunction gettime(dt:datetime):time

Argumentdt

A datetime object

Return value
Time measure in seconds or a time object.
ExampleThe following prints the program execution time:
starttime:= gettime...
write("Time: ",gettime-starttime)! Get the start time
! Do something

Further information
1. The measure returned by this function corresponds to the elapsed time since the module has been
initialized (just before execution of the model starts).
2. The second form of this function is used to extract the time part of a datetime structure.
Related topics
getdate, getasnumber
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

515

mmsystem

gettmpdir
Purpose
Synopsis

Get the temporary directory as a text object.
function gettmpdir:text

Return value
Temporary directory as a text object.
Further information
This function is equivalent to text(getparam("tmpdir")).
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

516

mmsystem

gettrim, settrim
Purpose
Synopsis

Get and set trim property of a parser context.
function gettrim(pctx:parsectx):boolean
procedure settrim(pctx:parsectx, t:boolean)

Arguments
pctx
t

A parser context
New trim value

Return value
Current trim value stored in the context.
Related topics
sys_trim, getsepchar, getendparse, getqtype
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

517

mmsystem

getweekday
Purpose
Synopsis

Compute the day of the week for a date or datetime.
function getweekday(d:date):integerfunction getweekday(dt:datetime):integer

Argumentsddt

A date object
A datetime object

Return value
The number of the day in the week (1-7).
Further information
The ﬁrst day of the week (number 1) is Monday.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

518

mmsystem

getyear
Purpose
Synopsis

Get the year part of a date or datetime.
function getyear(d:date):integerfunction getyear(dt:datetime):integer

Argumentsddt

A date object
A datetime object

Return value
Year as an integer.
Related topics
getmonth, getday
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

519

mmsystem

inserttext
Purpose
Synopsis

Paste a text or string into a text.
procedure inserttext(txt:text, str:string, start:integer)
procedure inserttext(txt:text, src:text, start:integer)

Arguments
txt
src
str
start
ExampleA text object
A text object
A string
Insert position

The following:t:=text("abcdefgh")inserttext(t,"123",2)
writeln(t)inserttext(t,"456",8)
writeln(t)produces this output:
a123bcdefgh
a123bcd456efgh

Related topics
cuttext, deltext, pastetext, copytext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

520mmsystem

isvalid
Purpose
SynopsisCheck whether a date, time or datetime is valid.
function isvalid(d:date):booleanfunction isvalid(t:time):booleanfunction isvalid(dt:datetime):boolean

Argumentsdt
dt

A date object
A time object
A datetime object

Return value
True if the argument is valid.
Further information
A date is valid if its month number is in the range 1-12 and its day number is in the range 1-31 and iscompatible with its month number (for instance 2006-2-29 is not a valid date). A time is valid if it ispositive and smaller than an entire day. A datetime is valid if both its date part and its time part are
valid.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

521

mmsystem

jointext
Purpose
SynopsisMerge elements of a list or set into a text string.
function jointext(ls:list|set):text
function jointext(ls:list|set, mxe:integer):text
function jointext(ls:list|set, sep:string):text
function jointext(ls:list|set, sep:string, mxe:integer):text

Arguments
ls
sep
mxe

List or set to use as input
Separator string (default: ’,’)
Maximum number of elements to merge (default: 0 for no limit)

Return value
A text string consisting of the concatenation of set or list elements.
Further information
1. This function concatenates the elements of an input list or set to produce a text string. Items are
separated by the provided separator string that may be an empty string.
2. The argument mxe may be used to specify a maximum number of elements to process (the remaining
portion of the input data is ignored). If this limit is negative then the elements are taken from the end of
the collection (e.g. with -3 the last 3 elements of the collection are used), otherwise elements aretaken from the beginning.
Related topics
splittext.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information522

mmsystem

makedir
Purpose
SynopsisCreate a new directory in the given ﬁle system.
procedure makedir(dirname:string|text)

Argument
dirname The name and path of the directory to be createdRelated topics
removedir, makepath.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

523

mmsystem

makepath
Purpose
SynopsisCreate a new directory including its parents if necessary.
procedure makepath(dirname:string|text)
procedure makepath(dirname:string|text,last_is_file:boolean)

Arguments
dirnameThe name and path of the directory to be createdlast_is_file If true, the last component of the path is ignored
Further information
1. This routine creates the directory dirname as well as intermediate directories in the path if necessary.
For instance, makepath("/tmp/dir1/dir2") will create "/tmp" then "/tmp/dir1" before"/tmp/dir1/dir2" if these directories are missing.
2. As opposed to makedir, this routine does not return an error condition if the path already exists.
3. The second form of this procedure can be used when the argument is a path to a ﬁle in order to create
the directory in which the ﬁle can be created. For instance, makepath("/tmp/dir1/myfile",true)
will create "/tmp/dir1" such that ﬁle /tmp/dir1/myfile" can be created.
Related topics
removedir, makedir.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information524

mmsystem

newtarPurpose
SynopsisCreate a Unix tar archive from a list of ﬁles.
procedure newtar(opt:integer, tarfile:text, dir:text,
lsf:list of text|string)procedure newtar(tarfile:text, lsf:list of text|string)Arguments
opt

Options:
SYS_NODIRSYS_DIRONLY
SYS_FLAT

Do not store directories (only ﬁles)Store only directories
Store all ﬁles in the root directory of the archive (i.e. do not preserve
directory structure)tarfile File name of the archive
dirBase directory (default: current directory)
lsf
List of ﬁles and directories to store in the archive (ﬁle names are relative to the dir
directory)
ExampleThe following creates an archive of the Xpress installation including only binary ﬁles:
findfiles(SYS_RECURS,lsf,getenv("XPRESSDIR"),"bin/⁎;lib/⁎;dso/⁎")newtar(0,"xpress.tar",getenv("XPRESSDIR"),lsf)

Further information
1. This implementation processes only regular ﬁles, symbolic links (on Posix systems) and directories:
other ﬁle types are silently ignored and not included in the archive.
2. By default ﬁle names are represented according the current system encoding in the archive. To select a
different encoding use the enc: ﬁle name preﬁx (see Section 2.16) on the archive name (e.g.
"enc:utf-8,myarc.tar").
3. File names including ".." are silently ignored unless option SYS_FLAT is used.
Related topics
tarlist, untar, newzip
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

525

mmsystemnewzipPurpose
SynopsisCreate a Zip archive from a list of ﬁles.
procedure newzip(opt:integer, zipfile:text, dir:text,
lsf:list of text|string, password:text)
procedure newzip(opt:integer, zipfile:text, dir:text,
lsf:list of text|string)procedure newzip(zipfile:text, lsf:list of text|string)Arguments
opt

Options:
SYS_NODIRSYS_DIRONLY
SYS_FLAT

Do not store directories (only ﬁles)Store only directories
Store all ﬁles in the root directory of the archive (i.e. do not preserve
directory structure)
zipfileFile name of the archive (that must be a physical ﬁle)dirBase directory (default: current directory)
lsf
List of ﬁles and directories to store in the archive (ﬁle names are relative to the dir
directory)
password Password to generate en encrypted zip ﬁleExampleThe following creates an archive of the Xpress installation including only binary ﬁles:
findfiles(SYS_RECURS,lsf,getenv("XPRESSDIR"),"bin/⁎;lib/⁎;dso/⁎")newzip(0,"xpress.zip",getenv("XPRESSDIR"),lsf)

Further information
1. This implementation only supports the standard Zip format (only 32bit and basic encryption algorithm)
with symbolic links on Posix systems.
2. By default ﬁle names are represented according the current system encoding in the archive. To select a
different encoding use the enc: ﬁle name preﬁx (see Section 2.16) on the archive name (e.g.
"enc:utf-8,myarc.zip").
3. File names including ".." are silently ignored unless option SYS_FLAT is used.
Related topics
ziplist, unzip, newtar
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

526

mmsystem

nextﬁeld
Purpose
Synopsis

Advance to next ﬁeld in a structured text string.
function nextfield(txt:text,start:integer,trim:boolean):booleanfunction nextfield(txt:text):booleanfunction nextfield(txt:text,pctx:parsectx):boolean

Arguments
txt
pctx
start
trim

A text object
A parser context
Starting position in the text
Whether to skip blank characters around separators

Return value
true if more data can be parsed.
ExampleThe following function returns the list of records of a text string using comma as the ﬁeld separator
character:function split(t:text):list of text
declarations
pctx:parsectx
end-declarations
pctx.sepchar:=44 ! ','while(nextfield(t,pctx)) doreturned+=[parsetext(t,pctx)]
end-doend-function

Further information
1. When start is 0, this routine saves the position of the ﬁrst character of the text string in the control
parameter sys_endparse and returns true.
2. When start is greater than 0 and the character located at position start is the separator character
sys_sepchar, the position start+1 is saved in control parameter sys_endparse and true isreturned. In all other cases false is returned.
3. This function returns false if the provided text txt is empty or the starting position start is not valid.
4. If argument trim is true, blank characters are skipped before and after the separator character. The
provided value is saved in parameter sys_trim when start is 0.
5. In the second form of the routine, parameters sys_endparse and sys_trim are used as default
values for arguments start and trim.
6. The version using a parser context works with the information contained in this context instead of the
global parameters (see Section 16.1.5).
Related topics
parseint, parsereal, parseextn, parsetext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

527

mmsystem

openpipe
Purpose
SynopsisStart an external process for bidirectional communication.
procedure openpipe(cmd:string|text)

Argument
cmd
ExampleThe command to be executed in the separate process

The following example uses an external program sort (we assume it writes a sorted copy of what it
reads) to display a sorted list of the content of set ToSort:
openpipe("sort")
forall(i in ToSort)
writeln(i)fclose(F_OUTPUT)
while(not iseof) do
readln(l)writeln(l)end-dofclose(F_INPUT)

Further information
1. Pipes required by this procedure are created using the pipe driver of this module (see Section 16.4.2).
As a consequence, the string provided as argument must be suitable for the driver (i.e. a program namefollowed by its options separated by spaces).
2. This procedure opens both an input and output streams that must be closed explicitly using fclose.
Note that the output stream must be closed ﬁrst otherwise the program may lock up.
3. When Mosel is running in restricted mode (see Section 1.3.4), this procedure behaves like the systemprocedure.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information528

mmsystem

parseextn
Purpose
Synopsis

Initialise an object of a module type from a text.
procedure parseextn(txt:text,start:integer,e:mtype)procedure parseextn(txt:text,e:mtype)procedure parseextn(txt:text,pctx:parsectx,e:mtype)procedure parseextn(txt:text,ta:textarea,e:mtype)

Arguments
txt
pctx
ta
start
e
ExampleA text object
A parser context
A text area object
Starting position in the text
An object of an external typeThe following:
d:=date(SYS_NOW)
t:=text("1-Oct-2015")
setparam("datefmt", "%d-%N-%y")parseextn(t,1,d)
if getsysstat<>0 thenwriteln("Error")else
writeln("year:",d.year)
end-ifproduces this output:
year:2015

Further information
1. This function can only be used with types supporting initialisation from a string (like date or time for
instance). The parsing begins at the speciﬁed starting position and stops as soon as an invalidcharacter is found or when the end of the text is reached.
Standard (initial two) versions: if start is not provided then the value of the control parameter
sys_endparse is used as starting position; the location where parsing stops is stored in theparameter sys_endparse.
Version using a parser context: the information contained in the parser context is used instead of
the global parameters (see Section 16.1.5); the context property endparse indicates the starting
position and is updated with the location where parsing stops.
Version using a textarea object: the routine uses the start property of the object (see Section
16.1.6) as the starting position but it does not store the position where parsing stops, in particular
it does not modify the parameter sys_endparse.

2. In case of error the system status is set with a non-zero value (see getsysstat).
Related topics
parseint, parsereal, parsetext, nextfield, sys_endparse
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information529

mmsystem

parseint
Purpose
Synopsis

Convert a text into an integer.
function parseint(txt:text,start:integer):integerfunction parseint(txt:text,start:integer,base:integer):integerfunction parseint(txt:text):integerfunction parseint(txt:text,pctx:parsectx):integerfunction parseint(txt:text,pctx:parsectx,base:integer):integerfunction parseint(txt:text,ta:textarea):integerfunction parseint(txt:text,ta:textarea,base:integer):integer

Arguments
txt
pctx
ta
start
base

A text object
A parser context
A text area object
Starting position in the text
Base to use for the conversion (between 2 and 36)

Return value
The integer represented by the string.
ExampleThe following:t:=text("a123.4b")
writeln(parseint(t,2))
writeln(getparam("sys_endparse"))produces this output:
123
5

Fair Isaac Corporation Conﬁdential and Proprietary Information

530

mmsystem

Further information
1. The parsing begins at the speciﬁed starting position and stops as soon as an invalid character is foundor when the end of the text is reached.
Standard (initial three) versions: if start is not provided then the value of the control parameter
sys_endparse is used as starting position; the location where parsing stops is stored in theparameter sys_endparse.
Version using a parser context: the information contained in the parser context is used instead of
the global parameters (see Section 16.1.5); the context property endparse indicates the starting
position and is updated with the location where parsing stops.
Version using a textarea object: the routine uses the start property of the object (see Section
16.1.6) as the starting position but it does not store the position where parsing stops, in particular
it does not modify the parameter sys_endparse.

2. In case of error (no valid character found or overﬂow) the system status is set with a non-zero value(see getsysstat) and, depending on the situation, 0, MAX_INT or -MAX_INT-1 is returned.
3. The optional base argument may be used if the text is not expressed in base 10. Valid values for thisparameter is 0 and 2 to 36. If base is zero or 16, the string may then include a ’0x’ preﬁx, and thenumber will be read in base 16. Furthermore, if the base is 0, the text will be read in base 8 if the ﬁrst
character is 0 and in base 10 otherwise.
4. The base value may also be negative: in this case the input data is interpreted as an unsigned integer.
Related topics
parsereal, parseextn, parsetext, nextfield, sys_endparse
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

531

mmsystem

parsereal
Purpose
Synopsis

Convert a text into a real.
function parsereal(txt:text,start:integer):realfunction parsereal(txt:text):realfunction parsereal(txt:text,pctx:parsectx):realfunction parsereal(txt:text,ta:textarea):realArguments
txt
pctx
ta
start

A text object
A parser context
A text area object
Starting position in the text

Return value
The real represented by the string.
ExampleThe following:t:=text("a123.4b")
writeln(parsereal(t,2))
writeln(getparam("sys_endparse"))produces this output:
123.4
7

Further information
1. The parsing begins at the speciﬁed starting position and stops as soon as an invalid character is foundor when the end of the text is reached.
Standard (initial two) versions: if start is not provided then the value of the control parameter
sys_endparse is used as starting position; the location where parsing stops is stored in theparameter sys_endparse.
Version using a parser context: the information contained in the parser context is used instead of
the global parameters (see Section 16.1.5); the context property endparse indicates the starting
position and is updated with the location where parsing stops.
Version using a textarea object: the routine uses the start property of the object (see Section
16.1.6) as the starting position but it does not store the position where parsing stops, in particular
it does not modify the parameter sys_endparse.

2. If the string starts with the sequence "0x" or "OX" an hexadecimal representation of a ﬂoating pointvalue will be expected. This representation is of the form "[+/-]0xh.hhhp[+/-]ddd" where ’h’
are hexadecimal digits and ’d’ decimal digits.
3. In case of error (no valid character found or overﬂow) the system status is set with a non-zero value(see getsysstat) and, depending on the situation, 0, MAX_REAL or -MAX_REAL is returned.
Related topics
parseint, parseextn, parsetext, nextfield, sys_endparse
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

532

mmsystem

parsetext
Purpose
Synopsis

Extract a text from a text.
function parsetext(txt:text,start:integer):text
function parsetext(txt:text):text
function parsetext(txt:text,pctx:parsectx):text
function parsetext(txt:text,ta:textarea):text

Arguments
txt
pctx
ta
start

A text object
A parser context
A text area object
Starting position in the text

Return value
Decoded text.
ExampleThe following:t:=text("a123.4b")
setparam("sys_sepchar",46) ! '.'writeln(parsetext(t,2))
writeln(getparam("sys_endparse"))produces this output:
123
5

Fair Isaac Corporation Conﬁdential and Proprietary Information

533

mmsystem

Further information
1. The behaviour of this routine depends on 2 control parameters: sys_sepchar (or context property
sepchar) deﬁnes a ﬁeld separator that may mark the end of a non-quoted string and the parameter
sys_qtype (or context property qtype) speciﬁes the convention to use for quoted strings: if thisparameter has value 0 (the default), Mosel quoting convention is used (both single and double quotes
may be employed and with double quotes escape sequences are allowed); with value -1 no quoting is
expected; with value 1, C/C++ quoting convention applies (only double quotes with escape sequences).
Finally, with value 2, CSV convention is expected (double quotes and repetition of double quotes toescape this character). The returned string is decoded: quotes are removed and escape sequences are
replaced by their corresponding characters.
2. The parsing begins at the speciﬁed starting position and stops as soon as the separator character(sys_sepchar or context property sepchar respectively) is found or the quoted string is terminated.
Standard (initial two) versions: if start is not provided then the value of the control parameter
sys_endparse is used as starting position; the location where parsing stops is stored in theparameter sys_endparse.
Version using a parser context: the information contained in the parser context is used instead of
the global parameters (see Section 16.1.5); the context property endparse indicates the starting
position and is updated with the location where parsing stops.
Version using a textarea object: the routine uses the start property of the object (see Section
16.1.6) as the starting position but it does not store the position where parsing stops, in particular
it does not modify the parameter sys_endparse.

3. In case of error, getsysstat will return a negative value. A positive value indicates that a quoted string
is unﬁnished (i.e. the end of the source text is reached although no matching quote has been found).
Related topics
parseint, parsereal, parseextn, nextfield, sys_sepchar, sys_qtype, sys_endparse
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

534

mmsystem

pastetext
Purpose
Synopsis

Paste a text or string into a text.
procedure pastetext(txt:text, str:string, start:integer)
procedure pastetext(txt:text, src:text, start:integer)

Arguments
txt
src
str
start
ExampleA text object
A text object
A string
Paste position

The following:t:=text("abcdefgh")
pastetext(t,"123",2)
writeln(t)pastetext(t,"456",8)
writeln(t)produces this output:
a123efgha123efg456

Related topics
cuttext, inserttext, deltext, copytext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

535

mmsystem

pathmatch
Purpose
SynopsisCheck whether a ﬁle name matches a given pattern.
function pathmatch(filename:string|text,pattern:string|text):boolean

Arguments
filename The ﬁle name to evaluate
pattern
Matching pattern that may include ⁎ (any text of any length) or ? (any single character)
Return value
true if the ﬁle name matches the pattern.
ExampleThe following function identiﬁes Mosel source ﬁle names:
function is_mosel_file(f:text):boolean
returned:=pathmatch(f,"⁎.mos")end-function

Further information
The comparison respects the operating environment conventions and behaviour may differ dependingof the operating system. In particular, under Posix systems comparisons are case sensitive; this is not
the case on Windows (i.e. ﬁle names are not case sensitive).
Related topics
regmatch
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

536

mmsystem

pathsplit
Purpose
Synopsis

Split a path into its components.
function pathsplit(how:integer,path:text,rem:text):text
function pathsplit(how:integer,path:text):text

Arguments
how

path
rem

How to split the path:
SYS_DIR
Directory (i.e. part preceding the last directory separator)
SYS_FNAME File name (i.e. part following the last directory separator)
SYS_EXTN
File name extension (i.e. part following the last dot)
The path name to split
Remaining part of the path after the returned value has been removed

Return value
The requested part of the path.
ExampleThe following function returns the base name of a path (ﬁle name without directory and extension):function basename(f:text):text
returned:=pathsplit(SYS_FNAME,f)dummy:=pathsplit(SYS_EXTN,returned,returned)
end-function

Further information
Arguments path and rem can be the same object.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

537

mmsystem

qsort
Purpose
Synopsis

Sort a list or an array or (a subset of) the indices of an array.
procedure qsort(sense:boolean, lvals:list)
procedure qsort(sense:boolean, vals:array of integer|real|string)procedure qsort(sense:boolean, cvals:array|list of array, ndx:array)procedure qsort(sense:boolean, cvals:array|list of array, ndx:array,sel:set)procedure qsort(sense:boolean, cvals:array|list of array, lndx:list)
procedure qsort(sense:boolean, cvals:array|list of array, lndx:list,
sel:set)procedure qsort(sense:boolean, cmpfct:string, cmpctx:?, vals:array,ndx:array)procedure qsort(sense:boolean, cmpfct:string, cmpctx:?, vals:array,ndx:array, sel:set)procedure qsort(sense:boolean, cmpfct:string, cmpctx:?, vals:array,lndx:list)
procedure qsort(sense:boolean, cmpfct:string, cmpctx:?, vals:array,lndx:list, sel:set)

Arguments
sense

lvals
vals
cvals
cmpfctcmpctxndx
lndx
sel
ExampleSense of the sorting:
SYS_UP
Ascending order
SYS_DOWN Descending order
List to be sorted
One-dimensional array to be sorted
One-dimensional array to be sorted or list of one-dimensional arrays
The name of a comparator function of the form function
cmpfct(cmpctx,e1,e2):integer that behaves as compare with e1 and e2 of the same
type as the array to sort
The value to be passed as the ﬁrst argument to cmpfct (this parameter is not used by
qsort)
One-dimensional array of the same type and size as the indexing set of vals
List of the same type as the indexing set of vals
Subset of the indexing set of vals

The following example sorts an array of real numbers:
declarations
ar: array(1..10) of real
end-declarations
ar:: [1.2, -3, -8, 10.5, 4, 7, 2.9, -1, 0, 5]
qsort(true, ar)writeln("Sorted array: ", ar)

Fair Isaac Corporation Conﬁdential and Proprietary Information

538

mmsystem

Further information
1. In the ﬁrst two versions of the procedure (with two arguments, sense and vals or lvals) the input
array (list) vals (lvals) is overwritten by the resulting sorted array (list).
2. When an array ndx is provided, the resulting sorted array is returned in the argument ndx in the form of
its sorted index set. If a selection set sel of indices is provided, only the speciﬁed indices areprocessed.
3. When a list lndx is provided, the resulting sorted array is returned in the argument lndx in the form ofa list of sorted indices. If a selection set sel of indices is provided, only the speciﬁed indices areprocessed.
4. When applied to a dynamic array this procedure processes all indices of the index set including those
not referring to an existing cell (a subset of the indexing set sel can be used to select only the existing
entries).
5. The second version of the routine can handle arrays of integers, reals and strings. Other versions also
accept module types supporting ordering (like text or date for instance).
6. When the parameter cvals is a list of arrays it is expected that all these arrays have one dimension
and are all indiced by the same set. The list can contain up to 10 arrays. When performing the sorting
the routine will use the ﬁrst array values as the primary sorting criteria and then the following array incase of equality.
7. A comparator routine may also be provided in the form of user-deﬁned function which name is cmpfct(the function must be declared public). The ﬁrst parameter of this function is given via cmpctx that canbe of any scalar type (including a record), it is not used by the qsort algorithm but may be employedby the comparator function to store data required for the comparison. The 2 other arguments, that areof the same type as the array to sort, are the elements to compare: the function must return 0 if the 2elements are identical, -1 if the ﬁrst element is smaller or 1 otherwise. When using this form there is norestriction on the type of the array to sort.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

539

mmsystem

quote
Purpose
Synopsis

Quote and encode a text string.
function quote(txt:text,qtype:integer,sepchar:integer):text
function quote(txt:text):text

Argumentstxt
A text object
qtype
Quoting convention
sepchar Code of the separator character or 0
ExampleThe following statement:
writeln(quote('test CSV "quoted" string',2,44))
displays: "test CSV ""quoted"" string"

Further information
1. This function generates an encoded form of the provided text string according to the given quoting
convention qtype (see sys_qtype) and separator character sepchar. The provided text may bereturned unchanged if the selected convention does not require quotes and the text does not include
any special character or the speciﬁed separator character.
2. If argument sepchar is 0, quoting is enforced even if the selected quoting convention would not
require quotes.
3. In the second form of the routine, parameters sys_qtype and sys_sepchar are used as default
values for arguments qtype and sepchar.
Related topics
parsetext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

540

mmsystem

readlink
Purpose
Synopsis

Get the value of a symbolic link.
function readlink(string|txt:fname):text

Argument
fname A ﬁle nameReturn value
Linked ﬁle name or an empty string if the ﬁle cannot be accessed.
Further information
This function can be applied to a symbolic link to get its value. The ﬁle name itself is returned if theprovided ﬁle is not a symbolic link.
Related topics
getflstat, symlink

Fair Isaac Corporation Conﬁdential and Proprietary Information

541

mmsystem

readtextline
Purpose
Synopsis

Read a line of text from the current input stream.
function readtextline(txt:text):integer

Argumenttxt

A text object

Return value
Number of characters read or -1 if end of ﬁle.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information542

mmsystem

regmatch
Purpose
Synopsis

Compare text strings using a regular expression.
function regmatch(src:text, regex:string):booleanfunction regmatch(src:text, regex:string, start:integer,
flags:integer):booleanfunction regmatch(src:text, regex:string, start:integer, flags:integer,
mp:array(range) of textarea):boolean

Arguments
src
regex
start
flags

mp

Text to process
Regular expression
Position where to start the search
Search options:
REG_EXTENDED Use Extended Regular Expression syntax (ERE), default is to interpret theexpression as a Basic Regular Expression (BRE)
REG_ICASE
Comparison is performed case insensitive (by default it is case sensitive)
REG_NEWLINE
The character newline (\n) is treated as the end of line (by default it ishandled as an ordinary symbol)
REG_NOTBOLThe beginning of the text string is not the beginning of a line
REG_NOTEOLThe end of the text string is not the end of a line
Matching regions as an array of text area objects

Return value
true if a match was found.
ExampleThe following example extracts the value of ’pars2’ from an input text consisting of lines of the form
name=value:declarations
m:array(range) of textarea
t:textend-declarations
t:="p1=10\npars2=234\nparam9=56\n"
if regmatch(t,'pars2=\(.⁎\)$',1,REG_NEWLINE,m) thenpars2:=parseint(t,m(1))
writeln(pars2)
end-ifFurther information
1. This function relies on the TRE library (see http://laurikari.net/tre). Please refer to the documentation ofthis library for a detailed description of the supported expression syntax.
2. When the mp argument is provided and the search is successful, the result of the processing is returned
via this array as textarea objects (see Section 16.1.6): the array cell 0 refers to the entire matchingregion and the following ones to each of the subexpressions.
Related topics
findtext, pathmatch, regreplace, sys_regcache

Fair Isaac Corporation Conﬁdential and Proprietary Information

543

mmsystem

ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

544

mmsystem

regreplace
Purpose
Synopsis

Replace portions of a text string based on a regular expression.
function regreplace(src:text, regex:string, repl:string):integerfunction regreplace(src:text, regex:string, repl:string, start:integer,
flags:integer):integer

Arguments
src
regex
repl
start
flags

Text to process
Regular expression
Replacement string expression
Position where to start the search
Search options:
REG_EXTENDED Use Extended Regular Expression syntax (ERE), default is to interpret theexpression as a Basic Regular Expression (BRE)
REG_ICASE
Comparison is performed case insensitive (by default it is case sensitive)
REG_NEWLINE
The character newline (\n) is treated as the end of line (by default it ishandled as an ordinary symbol)
REG_NOTBOLThe beginning of the text string is not the beginning of a line
REG_NOTEOLThe end of the text string is not the end of a line
REG_ONCE
Stop after the ﬁrst replacement (by default the entire input string is
processed)

Return value
The number of replacements performed.
ExampleThe following statement transforms dates expressed as year-month-day to dates in the form
day/month/year
nbr:=regreplace(t,'([[:digit:]]{4})-([01]?[[:digit:]])-([0-3]?[[:digit:]])','\3/\2/\1',1,REG_EXTENDED)

Further information
1. This function relies on the TRE library (see http://laurikari.net/tre). Please refer to the documentation ofthis library for a detailed description of the supported expression syntax.
2. In the replacement string repl the backslash character (’\’) has a special meaning: if followed byanother baskslash character it is replaced by a single backslash; if followed by a digit it is replaced by
the corresponding subexpression deﬁned by the regular expression. The subexpression number 0
corresponds to the entire matching region.
Related topics
regmatch, sys_regcache
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

545

mmsystem

removedir
Purpose
Synopsis

Remove a directory.
procedure removedir(dirname:string|text)

Argument
dirname The name and path of the directory to delete
Further information
For deletion of a directory to succeed, the given directory must be empty.
Related topics
fdelete, makedir, removefiles.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

546

mmsystem

removeﬁlesPurpose
Synopsis

Remove ﬁles selected using ﬁle name patterns.
procedure removefiles(opt:integer, dir:text,filters:text)
procedure removefiles(filters:text)

Arguments
opt

Options (several options can be combined):

SYS_RECURS
Recursive search in subdirectories
SYS_NODIR
Do not remove directories (only ﬁles)SYS_DIRONLY Remove only directories
dir
Base directory for the search (default: current directory)
filters File name ﬁlters (default: all ﬁles removed)
ExampleThe following deletes directory "mydir" including its content:removefiles(SYS_RECURS,"mydir","⁎")
removedir("mydir")Further information
1. The filters argument consists in a list of patterns separated by the symbol ";". A pattern iscomposed of a path (using the usual operating system conventions) which last component may
include wildcard characters "⁎" (any text of any length), "?" (any single character) and "|" (logical"or"). For instance "bin/⁎.exe;models/⁎.mos|⁎.dat" will select all ﬁles with extension ".exe"in the "bin" directory as well as ﬁles with extension ".mos" and ".dat" in the "models" directory.
2. File name matching is achieved using function pathmatch and differences may be observed
depending on the operating system (e.g. ﬁle names are case sensitive under Posix systems but notunder Windows).
Related topics
findfiles, fdelete, removedir
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

547

mmsystem

setchar
Purpose
Synopsis

Set a character in a text.
procedure setchar(txt:text, index:integer, c:integer)

Arguments
txt
str
index
c

A text object
StringPosition of the character
Character code

Further information
If the index requested is after the end of the text, the text is expanded as necessary and the newly
created space is padded with the character which code is the parameter sys_fillchar.
Related topics
getchar, sys_fillchar, pastetext
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

548

mmsystem

setdatePurpose
Synopsis

Set the date part of a datetime.
procedure setdate(dt:datetime,d:date)Argumentsdt
dA datetime object
A date object

Related topics
settimeModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information549

mmsystem

setdayPurpose
Synopsis

Set the day number of a date or datetime.
procedure setday(d:date,j:integer)
procedure setday(dt:datetime,j:integer)

Argumentsddt
jA date object
A datetime object
Day number

Related topics
setyear, setmonth
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

550mmsystem

setdsoparam
Purpose
Synopsis

Set the value of a control parameter.
proceduresetdsoparam(name:string|text,val:integer|string|text|real|boolean)

Arguments
namevalName of a control parameter (including the module name).
New value for the control parameter

Further information
1. This procedure is similar to setparam except that the control parameter name is searched at runtime.
As a consequence this identiﬁer does not need to be a constant string but the execution is signiﬁcantly
slower than setparam and it cannot be applied to package parameters.
2. The provided parameter name must include the module name (e.g. "mmsystem.datefmt") otherwise
the identiﬁer is searched only in the list of Mosel parameters.
3. As opposed to setparam this procedure does not raise an error in case of failure (like parameter notfound or invalid value): use getsysstat to detect error conditions.
Related topics
getdsoparam.

Fair Isaac Corporation Conﬁdential and Proprietary Information

551

mmsystem

setenv
Purpose
Synopsis

Set the value of an environment variable of the operating system.
procedure setenv(name:string|text,value:string|text)

Arguments
name Name of the environment variablevalue New value for the environment variable
Further information
1. The environment variable is deleted if it is assigned an empty string.
2. Variables created or modiﬁed with this procedure can be retrieved using the getenv function and are
inherited by processes started by system or openpipe.
3. The effect of this procedure is local to the running model (i.e. system calls like the C function getenv
will not work for these variables). However, another module may access the environment maintained bymmsystem using the IMCI function getenv (see Section 16.5).
4. This procedure is included in the published interface of mmsystem (see Section 16.5).
Related topics
getenv, system, openpipe.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

552

mmsystem

setoserror
Purpose
Synopsis

Set the current system error code.
procedure setoserror(ec:integer)

Argumentec

A system error code

Further information
This function sets the current system error code that can be retrieved using getoserror. As a side
effect of using this routine the status returned by getsysstat is 0 if the error code is also 0 and 1
otherwise.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

553

mmsystem

sethour
Purpose
Synopsis

Set the hour part of a time or datetime.
procedure sethour(t:time,h:integer)
procedure sethour(dt:datetime,h:integer)

ArgumentstdthA time object
A datetime object
Hour

Related topics
setminute, setsecond, setmsec

Fair Isaac Corporation Conﬁdential and Proprietary Information

554

mmsystem

setminutePurpose
Synopsis

Set the minute part of a time or datetime.
procedure setminute(t:time,m:integer)
procedure setminute(dt:datetime,m:integer)

Argumentstdtm

A time object
A datetime object
MinuteRelated topics
sethour, setsecond, setmsec
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

555

mmsystem

setmonth
Purpose
Synopsis

Set the month number of a date or datetime.
procedure setmonth(d:date,m:integer)
procedure setmonth(dt:datetime,m:integer)

Argumentsddt
m

A date object
A datetime object
Month number

Related topics
setyear, setday

Fair Isaac Corporation Conﬁdential and Proprietary Information

556

mmsystem

setmsec
Purpose
Synopsis

Set the millisecond part of a time or datetime.
procedure setmsec(t:time,ms:integer)
procedure setmsec(dt:datetime,ms:integer)

Argumentst
dt
ms

A time object
A datetime object
Millisecond

Related topics
sethour, setminute, setsecond
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

557

mmsystem

setsecond
Purpose
Synopsis

Set the second part of a time or datetime.
procedure setsecond(t:time,s:integer)
procedure setsecond(dt:datetime,s:integer)

Argumentstdts

A time object
A datetime object
SecondRelated topics
sethour, setminute, setmsec
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

558

mmsystem

settime
Purpose
Synopsis

Set the time part of a datetime.
procedure settime(dt:datetime,t:time)

Argumentsdt
t

A datetime object
A time object

Related topics
setdateModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

559

mmsystem

setyear
Purpose
Synopsis

Set the year part of a date or datetime.
procedure setyear(d:date,y:integer)
procedure setyear(dt:datetime,y:integer)

Argumentsddt
yA date object
A datetime object
Year

Related topics
setmonth, setday
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

560

mmsystem

sleep
Purpose
Synopsis

Suspend execution for a ﬁxed amount of time.
procedure sleep(duration:int)

Argument
duration Sleep time in milliseconds
Further information
The model uses no CPU while it is suspended.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

561

mmsystem

splittext
Purpose
Synopsis

Split a text string.
function splittext(ts:text, sep:string):list of text
function splittext(ts:text, sep:string, mxe:integer):list of text
function splittext(qt:integer, ts:text, sep:string):list of text
function splittext(qt:integer, ts:text, sep:string, mxe:integer):list of
text

Arguments
qt
ts
sep
mxe

Quoting type (see parameter sys_qtype, default: -1 for no quoting)
Text string to process
Separator string
Maximum number of elements to collect (default: 0 for no limit)

Return value
The list of identiﬁed items.
ExampleThe following statements:
write(splittext(lst,"some/path/to/a.file","/",-2))
writeln(splittext(2,lst,'cv1,"cv""2""",cv3',","))
result in this display: [some/path/to,a.file][cv1,cv"2",cv3]

Further information
1. This function splits the input text string ts using the string sep as the ﬁeld delimiter and returns theidentiﬁed items as a list of texts. The argument mxe deﬁnes a maximum number of elements to put
into this result list. If this limit is reached while the input string has not been entirely processed the last
added item includes the remaining part of the input data as a single record.
2. When the quoting type is not speciﬁed or when it is set to -1 the separator string may be an empty
string and the maximum number of elements may take a negative value. With an empty separator the
input text is split into individual characters. If the maximum number of elements is negative thedecomposition is performed from the end of the string.
3. When quoting is active (i.e. qt is not -1) a parsing error may occur: in this case the system status it set
to a non-zero value (see getsysstat) and the parsing is interrupted (typically after an error the lastitem added to the result list is not valid).
Related topics
jointext.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

562

mmsystem

startswith
Purpose
SynopsisCheck whether a text or string starts with a given string.
function startswith(txt:text|string, tofs:text|string):booleanfunction startswith(txt:text|string, tofs:text|string,
start:integer):boolean

Argumentstxt
A string or text object
tofs String to ﬁndstart Starting position for the search
Return value
true if the beginning of txt corresponds to tofs.
Related topics
endswith
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

563

mmsystem

symlink
Purpose
SynopsisCreate a symbolic link.
procedure symlink(string|txt:target, string|txt:linkpath)

Arguments
targetValue of the link
linkpath File to create
Further information
This procedure works only on systems supporting symbolic links, in particular it cannot be executed on
Windows (i.e. on this platform getsysstat will always report a failure after calling this routine).
Related topics
readlink

Fair Isaac Corporation Conﬁdential and Proprietary Information

564

mmsystem

systemPurpose
Synopsis

Execute an external program.
procedure system(command:string|text)

Argument
command The command to be executed
ExampleThe following displays the functionality of the mmsystem module using the program mosel:
system('mosel -s -c "exam mmsystem"')

Further information
1. The given program is executed directly: if the speciﬁed expression is a shell command, it is necessary
to call the shell explicitly. For instance to get a directory listing under Windows the command will be"cmd /C dir".
2. Using this procedure should be avoided in applications that are to be run on different systems becausesuch a call is always system dependent and may not be portable.
3. The generated process inherits the current system environment plus the environment variables
modiﬁed/created using the setenv procedure.
4. On Windows the program to execute is located using the current process environment, as aconsequence any modiﬁcation of the PATH environment variable or working directory has no effect on
ﬁnding this executable. The behaviour is different on Posix systems where the search for the program
to execute is performed from the subprocess environment.
5. The default output and error streams of the generated process are redirected to the corresponding
Mosel streams. The default input stream is closed.
6. This procedure is included in the published interface of mmsystem (see Section 16.5).
7. When Mosel is running in restricted mode (see Section 1.3.4), the restriction NoExec disables thisroutine unless the environment variable MOSEL_EXECPATH is deﬁned. This variable, used in a similar
way as the PATH environment variable, gives a list of paths than can still be used under the restriction.
In addition to directories, the deﬁnition of the variable may include paths to executables such that it
may directly specify a list of programs. It is also worth noting that no search is performed (i.e.
executables must be given with their full path) and that path expansion is performed a the time ofloading mmsystem relative to the Mosel initial working directory.
8. The command may be preceded by the preﬁx "enc:" to specify the encoding of the output streams(see Section 2.16).
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

565

mmsystem

tarlistPurpose
Synopsis

Get the list of ﬁles included in a Unix tar archive.
procedure tarlist(opt:integer,tarfile:text,lsf:list of text,
filters:string)procedure tarlist(tarfile:text,lsf:list of text)

Arguments
opt

Options:

SYS_NODIR
Do not report directories (only ﬁles)SYS_DIRONLY Report only directories
tarfile File name of the archivelsf
Resulting list of ﬁle names
filters File name ﬁlters (default: all ﬁles reported)
ExampleThe following prints the list of ﬁles included in the archive myfiles.tar:
tarlist("myfiles.tar",lsf)
writeln(lsf)

Further information
1. The filters argument has a similar structure as the corresponding argument of procedure
findfiles except that wildcard characters "⁎" and "?" may appear anywhere in a path. A ﬁle isreported if it matches any of the patterns of this list.
2. When evaluating the ﬁlters, ﬁle name matching is achieved using function pathmatch and differences
may be observed depending on the operating system (e.g. ﬁle names are case sensitive under Posix
systems but not under Windows).
3. This implementation processes only regular ﬁles and directories: other ﬁle types included in the archive(like links) are silently ignored.
4. By default ﬁle names are expected to be represented according the current system encoding in thearchive. To select a different encoding use the enc: ﬁle name preﬁx (see Section 2.16) on the archive
name (e.g. "enc:utf-8,myarc.tar").
Related topics
untar, newtar, ziplist
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

566

mmsystem

textfmt
Purpose
SynopsisCreate a formatted text from a string, a text or a number.
function textfmt(str:string, len:integer):text
function textfmt(txt:text, len:integer):text
function textfmt(i:integer, len:integer):text
function textfmt(i:integer, len:integer, flag:integer, base:integer):text
function textfmt(r:real, len:integer):text
function textfmt(r:real, len:integer, dec:integer):text

Arguments
str
txt
i
r
len

flag
base
dec

String to be formatted
Text to be formatted
Integer to be formatted
Real to be formatted
Reserved length (may be exceeded if given string is longer, in this case the string is always left
justiﬁed).
<0
Left justiﬁed within reserved space>0
Right justiﬁed within reserved space0
Use defaults
Bit encoded options:1
Left padding with "0" (instead of space)2
Use capital letters for bases greater than 10
Encoding base (between 2 and 36)
Number of digits after the decimal point

Return value
Formatted text.
ExampleThe following:
writeln("text1", textfmt("text2",8), "text3")
writeln("text1", textfmt("text2",-8), "text3")
r:=789.123456
writeln(textfmt(r,0)," ", textfmt(r,4,2), textfmt(r,8,0))
produces this output:
text1
text2text3
text1text2
text3
789.123 789.12

789

Further information
1. If the resulting string is longer than the reserved space it is not cut but printed in its entirety, overﬂowing
the reserved space to the right.
2. When processing an integer specifying a base, the provided value is treated as an unsigned integer if
the base is negative.
Related topics
formattext

Fair Isaac Corporation Conﬁdential and Proprietary Information

567

mmsystem

ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

568

mmsystem

tolower
Purpose
Synopsis

Generate the lowercase version of the provided text.
function tolower(t:text|string):text
function tolower(c:integer):integer

Return value
The lowercase version of the input string or a character code.
ArgumentstcText to convert
Character code

Further information
When this function is used with a text string, it returns a copy of its argument converted to lowercase.
When it is called with an integer, the returned value corresponds to the character code of the lowercase
version of the provided code. In both cases, the function will return an unmodiﬁed copy of its argument
if no conversion can be done.
Related topics
toupperModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

569

mmsystem

toupper
Purpose
Synopsis

Generate the uppercase version of the provided text.
function toupper(t:text|string):text
function toupper(c:integer):integer

Return value
The uppercase version of the input string or a character code.
ArgumentstcText to convert
Character code

Further information
When this function is used with a text string, it returns a copy of its argument converted to uppercase.
When it is called with an integer, the returned value corresponds to the character code of the uppercase
version of the provided code. In both cases, the function will return an unmodiﬁed copy of its argument
if no conversion can be done.
Related topics
tolowerModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

570

mmsystemtrim
Purpose
Synopsis

Remove blank characters at the beginning and/or end of a text string.
procedure trim(t:text)
procedure trim(t:text,where:boolean)

Argumentst
Text to trim
where Part of the text to trim:
SYS_LEFTSYS_RIGHT

Beginning of the string
End of the string

Further information
When the function is used with a single argument, both starting and ending blank characters aredeleted.
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

571

mmsystem

untar
Purpose
Synopsis

Extract ﬁles from a Unix tar archive.
procedure untar(opt:integer,tarfile:text,dir:text,
filters:string)procedure untar(tarfile:text,dir:text)
procedure untar(tarfile:text)

Arguments
opt

Options:

SYS_OVERWRT Replace existing ﬁles
SYS_NODIR
Do not extract directories (only ﬁles)SYS_DIRONLY Extract only directories
SYS_FLAT
Extract ﬁles without directory structure
SYS_VERB
Report activity to the error stream
SYS_NOFAIL
Do not abort procedure if a ﬁle cannot be written
tarfile File name of the archive
dir
Destination path (default: current directory)
filters File name ﬁlters (default: all ﬁles extracted)
ExampleThe following extracts all ﬁles included in the archive myfiles.tar to directory mydir:
untar("myfiles.tar","mydir")Further information
1. The filters argument has a similar structure as the corresponding argument of procedure
findfiles except that wildcard characters "⁎" and "?" may appear anywhere in a path. A ﬁle isextracted if it matches any of the patterns of this list.
2. When evaluating the ﬁlters, ﬁle name matching is achieved using function pathmatch and differences
may be observed depending on the operating system (e.g. ﬁle names are case sensitive under Posix
systems but not under Windows).
3. This implementation processes only regular ﬁles, symbolic links (when supported by the system) anddirectories: other ﬁle types included in the archive are silently ignored.
4. By default ﬁle names are expected to be represented according the current system encoding in thearchive. To select a different encoding use the enc: ﬁle name preﬁx (see Section 2.16) on the archive
name (e.g. "enc:utf-8,myarc.tar").
Related topics
tarlist, newtar, unzip
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information572

mmsystem

unzip
Purpose
Synopsis

Extract ﬁles from a Zip archive.
procedure unzip(opt:integer, zipfile:text, dir:text,
filters:string, password:text)
procedure unzip(opt:integer, zipfile:text, dir:text,
filters:string)procedure unzip(zipfile:text, dir:text)
procedure unzip(zipfile:text)

Arguments
opt

Options:

SYS_OVERWRT Replace existing ﬁles
SYS_NODIR
Do not extract directories (only ﬁles)SYS_DIRONLY Extract only directories
SYS_FLAT
Extract ﬁles without directory structure
SYS_VERB
Report activity to the error stream
SYS_NOFAIL
Do not abort procedure if a ﬁle cannot be written
zipfileFile name of the archive (that must be a physical ﬁle)dir
Destination path (default: current directory)
filters
File name ﬁlters (default: all ﬁles extracted)
password Password to access an encrypted archive
ExampleThe following extracts all ﬁles included in the archive myfiles.zip to directory mydir:
unzip("myfiles.zip","mydir")Further information
1. The filters argument has a similar structure as the corresponding argument of procedure
findfiles except that wildcard characters "⁎" and "?" may appear anywhere in a path. A ﬁle isextracted if it matches any of the patterns of this list.
2. When evaluating the ﬁlters, ﬁle name matching is achieved using function pathmatch and differences
may be observed depending on the operating system (e.g. ﬁle names are case sensitive under Posix
systems but not under Windows).
3. This implementation only supports the standard Zip format (only 32bit and basic encryption algorithm)
and symbolic links are silently ignored if the system does not support them.
4. By default ﬁle names are expected to be represented according the current system encoding in thearchive. To select a different encoding use the enc: ﬁle name preﬁx (see Section 2.16) on the archive
name (e.g. "enc:utf-8,myarc.zip").
Related topics
ziplist, newzip, untar
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

573

mmsystem

ziplistPurpose
Synopsis

Get the list of ﬁles included in a Zip archive.
procedure ziplist(opt:integer, zipfile:text, lsf:list of text,
filters:string)procedure ziplist(zipfile:text, lsf:list of text)

Arguments
opt

Options:

SYS_NODIR
Do not report directories (only ﬁles)SYS_DIRONLY Report only directories
zipfile File name of the archivelsf
Resulting list of ﬁle names
filters File name ﬁlters (default: all ﬁles reported)
ExampleThe following prints the list of ﬁles included in the archive myfiles.zip:
ziplist("myfiles.zip",lsf)
writeln(lsf)

Further information
1. The filters argument has a similar structure as the corresponding argument of procedure
findfiles except that wildcard characters "⁎" and "?" may appear anywhere in a path. A ﬁle isreported if it matches any of the patterns of this list.
2. When evaluating the ﬁlters, ﬁle name matching is achieved using function pathmatch and differences
may be observed depending on the operating system (e.g. ﬁle names are case sensitive under Posix
systems but not under Windows).
3. By default ﬁle names are expected to be represented according the current system encoding in thearchive. To select a different encoding use the enc: ﬁle name preﬁx (see Section 2.16) on the archive
name (e.g. "enc:utf-8,myarc.zip").
Related topics
unzip, newzip, tarlist
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information574

mmsystem

16.4

I/O drivers
The mmsystem module provides two IO drivers: the ﬁrst one allows to use a string or text object as a
ﬁle and the second connects a Mosel input or output stream to a program started in a different
process. Using this driver, it is possible to get the output of an external program (for instance the resultof a preprocessor to feed the Mosel compiler) or implement a basic bidirectional inter process
communication thanks to the openpipe procedure (which relies on this IO driver).

16.4.1

Driver text
text:ident

This driver uses a model variable of type string or text as its input or output media. The ident
argument it requires is therefore the name of this variable that must be declared globally public to themodel or have been published with publish (such that it can always be found independently of thecompiler settings).String objects can only be accessed for reading while text entities can be used forboth reading and writing.
In the following example the constant string "T" is used as the initialization ﬁle for variable "A":declarations
public T="A:123"
A:integer
end-declarations
initializations from "text:T"A
end-initializations

16.4.2

Driver pipe
pipe:program [options...]The ﬁle name for this driver is an external program with its options. Options are separated by spaces ortabulations and may be quoted using either single or double quotes. A quoted option may contain any
kind of character except the quote used to delimit the string.
When the system opens a pipe, a new process is started for executing the given program and default
input and output streams are directed to system pipes. If the ﬁle is open for reading (resp. writing), thedefault ouput stream (resp. input stream) of the new process becomes the current input stream (resp.
output stream) of the model. To locate the program to be executed, the system relies on the PATH
environment variable. Detection of error (typically the program cannot be found or is not executable)
differs depending on the operating system: under Windows, the error is reported immediately and thepipe is not open. With Posix systems, no error is reported but following IO operations fail.
When the ﬁle is closed, both input and output streams of the external process are closed then thesystem waits for its termination: in order to avoid a lock up of the Mosel program one must make surethat the external program ends its execution when default input and output streams are closed.
Example: the following command could be used with Mosel Console for compiling the model
mymod.mos after it has been processed by the C preprocessor. Note that we have to provide an output
ﬁle name since the compiler cannot deduce it from the source ﬁle name.
For a Posix systems:
compile 'mmsystem.pipe:cpp mymod.mos' '' mymod.bim

For Windows (with MSVC):

Fair Isaac Corporation Conﬁdential and Proprietary Information

575

mmsystemcompile 'mmsystem.pipe:cl /E mymod.mos' '' mymod.bim

When Mosel is running in restricted mode (see Section 1.3.4), this driver behaves like the systemprocedure.

16.5

Published library functions
The module mmsystem publishes its implementation of getenv, setenv and system as well as thefunctions gettxtsize, gettxtbuf and txtresize for text access via the service IMCI for use byother modules (see the Mosel Native Interface Reference Manual for more detail about services). The
list of published functions is contained in the interface structure mmsystem_imci that is deﬁned in themodule header ﬁle mmsystem.h.
From another module, the context of mmsystem and its communication interface can be obtainedusing functions of the Mosel Native Interface as shown in the following example.
static XPRMnifct mm;
XPRMcontext mmctx;
XPRMdsolib dso;
mmsystem_imci mmsys;
void ⁎⁎sysctxref;
dso=mm->finddso("mmsystem");/⁎ Retrieve the mmsystem module⁎/
sysctxref=mm->getdsoctx(mmctx, dso, (void ⁎⁎)(&mmsys));/⁎ Get the module context and thecommunication interface of mmsystem ⁎/Typically, a module calling functions that are provided by mmsystem will include this module into its listof dependencies in order to make sure that mmsystem will be loaded by Mosel at the same time as thecalling module. The “dependency” service of the Mosel Native Interface has to be used to set the list of
module dependencies:
static const char ⁎deplist[]={"mmsystem",NULL}; /⁎ Module dependency list ⁎/static XPRMdsoserv tabserv[]={{XPRM_SRV_DEPLST, (void ⁎)deplist}};/⁎ Table of services ⁎/Using these functions a module may access and modify the environment of the calling model andexecute an external program with automatic redirection of default streams:
mmsys->setenv(ctx,⁎sysctxref,"MYVAR","A_VALUE");
rts=mmsys->system(ctx,⁎sysctxref,"myprogram arg1 arg2");

16.5.1

Description of the library functions
getdateGet the date of a date object.

p. 580getdatetime

Get the date and time of a datetime object.

p. 582

gettimeGet the time of a time object.

p. 578gettxtbuf

Get a reference to the character buffer of a text object.

p. 585gettxtsize

Get the size of a text object.

p. 584setdateSet the date of a date object.

p. 581

Fair Isaac Corporation Conﬁdential and Proprietary Information

576

mmsystem

setdatetime

Set the date and time of a datetime object.

p. 583settimeSet the time of a time object.

p. 579txtresize

Resize a text object.

p. 586

Fair Isaac Corporation Conﬁdential and Proprietary Information

577

mmsystem

gettime
Purpose
Synopsis

Get the time of a time object.
int gettime(XPRMctx ctx, void ⁎sysctx, void ⁎t, int ⁎h, int ⁎mi, int ⁎s,
int ⁎ms);

Arguments
ctx
sysctxth
mis
ms

Mosel’s execution context
Context of mmsystem
Reference to a time object
Reference to store the hours or NULL
Reference to store the minutes or NULL
Reference to store the seconds or NULL
Reference to store the milliseconds or NULL

Return value
0 if successful or -1 if t is NULL.
Further information
Provided references are set even if the function fails.
Related topics
settimeModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

578

mmsystem

settime
Purpose
Synopsis

Set the time of a time object.
int settime(XPRMctx ctx, void ⁎sysctx, void ⁎t, int h, int mi, int s, int
ms);Arguments
ctx
sysctxth
mis
ms

Mosel’s execution context
Context of mmsystem
Reference to a time object
hours
minutesseconds
milliseconds

Return value
0 if successful or -1 if t is NULL.
Related topics
gettimeModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information579

mmsystem

getdatePurpose
Synopsis

Get the date of a date object.
int getdate(XPRMctx ctx, void ⁎sysctx, void ⁎t, int ⁎y, int ⁎m, int ⁎d);Arguments
ctx
sysctxtymd

Mosel’s execution context
Context of mmsystem
Reference to a date object
Reference to store the years or NULL
Reference to store the months or NULL
Reference to store the days or NULL

Return value
0 if successful or -1 if t is NULL.
Further information
Provided references are set even if the function fails.
Related topics
setdateModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

580

mmsystem

setdatePurpose
Synopsis

Set the date of a date object.
int setdate(XPRMctx ctx, void ⁎sysctx, void ⁎t, int y, int m, int d);Arguments
ctx
sysctxtymd

Mosel’s execution context
Context of mmsystem
Reference to a date object
Years
Monthsdays

Return value
0 if successful or -1 if t is NULL.
Related topics
getdateModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

581

mmsystem

getdatetime
Purpose
Synopsis

Get the date and time of a datetime object.
int getdatetime(XPRMctx ctx, void ⁎sysctx, void ⁎t, int ⁎y, int ⁎m, int ⁎d,int ⁎h, int ⁎mi, int ⁎s, int ⁎ms);

Arguments
ctx
sysctx
t
y
m
d
h
mi
s
ms

Mosel’s execution context
Context of mmsystem
Reference to a date object
Reference to store the years or NULL
Reference to store the months or NULL
Reference to store the days or NULL
Reference to store the hours or NULL
Reference to store the minutes or NULL
Reference to store the seconds or NULL
Reference to store the milliseconds or NULL

Return value
0 if successful or -1 if t is NULL.
Further information
Provided references are set even if the function fails.
Related topics
setdatetime
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

582

mmsystem

setdatetime
Purpose
Synopsis

Set the date and time of a datetime object.
int setdatetime(XPRMctx ctx, void ⁎sysctx, void ⁎t, int y, int m, int d,
int h, int mi, int s, int ms);

Arguments
ctx
sysctx
t
y
m
d
h
mi
s
ms

Mosel’s execution context
Context of mmsystem
Reference to a date object
Years
Monthsdays
hours
minutesseconds
milliseconds

Return value
0 if successful or -1 if t is NULL.
Related topics
getdatetime
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

583

mmsystem

gettxtsize
Purpose
Synopsis

Get the size of a text object.
int gettxtsize(XPRMctx ctx, void ⁎sysctx, void ⁎t);

Arguments
ctx
sysctxt

Mosel’s execution context
Context of mmsystem
Reference to a text object

Return value
The size of the character buffer (excluding the terminating 0 character).
Related topics
txtresize, gettxtbuf
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

584

mmsystem

gettxtbuf
Purpose
Synopsis

Get a reference to the character buffer of a text object.
char ⁎gettxtbuf(XPRMctx ctx, void ⁎sysctx, void ⁎t);

Arguments
ctx
sysctxt

Mosel’s execution context
Context of mmsystem
Reference to a text object

Return value
A reference to the character buffer.
Further information
1. The buffer returned is terminated by the character 0 (like a C string) and can be modiﬁed as long as thesize is not changed. If the length of the buffer has to be altered, use the function txtresize.
2. Since the memory management of the module may move text buffers when allocating memory, thepointer returned by this function is only valid until the next memory allocation.
Related topics
txtresize, gettxtsize
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

585

mmsystem

txtresize
Purpose
Synopsis

Resize and get a reference to the character buffer of a text object.
char ⁎txtresize(XPRMctx ctx, void ⁎sysctx, void ⁎t, int s);

Arguments
ctx
sysctxts

Mosel’s execution context
Context of mmsystem
Reference to a text object
New size of the buffer (terminating 0 is not counted)

Return value
A reference to the new character buffer or NULL in case of memory error.
Further information
1. The buffer returned is terminated by the character 0 (like a C string) and can be modiﬁed as long as thesize is not changed.
2. Since the memory management of the module may move text buffers when allocating memory, thepointer returned by this function is only valid until the next memory allocation.
Related topics
gettxtsize
ModulemmsystemFair Isaac Corporation Conﬁdential and Proprietary Information

586

CHAPTER 17

mmxml
This module provides an XML parser and generator for the manipulation of XML documents from Mosel
models. To use this module, the following line must be included in the header of the Mosel model ﬁle:uses 'mmxml'

mmxml relies on the XML parser EXPAT by James Clark (http://www.libexpat.org) for loading
documents.

17.1

Document representation in mmxml

17.1.1

Data model
The XML document is stored as a list of nodes. Different node types are used to represent the
document structure:element nodetext sectioncomment



CDATA



processing instruction

In addition to these usual node types, the type DATA is used for XML constructs not supported by
mmxml (for instance a DOCTYPE declaration is recorded as a DATA section). Although they are notdirectly recorded in the document tree, attributes are also stored as nodes of a dedicated type.
Each node is characterised by a name and a value. Nodes of type text, comment, CDATA and DATA havea constant name. The name of a processing instruction is the processing instruction’s target and its
value the remaining part of the statement (e.g. the name of <?proc inst> is proc and its value isinst). The value of comment and CDATA sections is the content of the section without its delimiters
but the value of a DATA block includes the delimiters. Element nodes have also an ordered list of childnodes. The value of an element node corresponds to the value of the ﬁrst child text node (if any).
The root node is a special element node with no name, no parent and no successor that includes theentire document as its children.

Fair Isaac Corporation Conﬁdential and Proprietary Information

587

mmxmlExample of an XML document with node types:

17.1.2<?xml version="1.0" encoding="iso-8859-1" standalone="no" ?><?xml-stylesheet type="text/css" href="examplestyle.css" ?><!DOCTYPE exampleList SYSTEM "examples.dtd" [<!ENTITY otherfile SYSTEM "anotherfile.xml">]>

XML header
Processing instruc.
DATA<!-- List of optimization application examples --><exampleList><!-- Example B3 --><model id="book_B_3"><modFile date="Mar.2002">
b3jobshop.mos</modFile><modData file="b3jobshop.dat" /><modData file="b3jobshop2.dat" /><modTitle>
Job shop scheduling</modTitle><modRating>3</modRating><modFeatures><![CDATA[dynamic array, range, exists, forall-do]]></modFeatures></model></exampleList>

Comment
Element node
Comment
Element node
Element node
Text node
Element node
Element node
Element node
Text node
Element node
Text node
Element node
CDATA

Paths in a document
Nodes can be retrieved using a path similar to a directory path used to locate a ﬁle. An XML pathconsists in a list of location steps separated by the slash character ("/"): each step selects a set ofnodes from the input set resulting from the preceding step (context nodes). The initial set of the path iseither the root node (absolute path) or some speciﬁed node (relative path).
A step is composed of an optional axis speciﬁer followed by a node test and possibly completed by apredicate. The axis speciﬁes the tree relationship between the nodes selected by the step and thecontext node. The node test is either an element name (to select elements of the given name) or anode type (to select nodes by their type). The predicate is a Boolean expression the truth value of which
decides whether a selected node is kept in the result set of the step.
Examples:/examples/chapter

all element nodes ’chapter’ under elements ’examples’/examples/chapter/model/modRating[number()>=4]/.. all ’model’ nodes under’examples/chapter’ for which element ’modRating’ has a value greater thanor equal to 4//⁎[@attribute1 and @attribute2=’value2’] all element nodes of the document having’attribute1’ deﬁned and ’attribute2’ with value ’value2’/descendant::text()

all text sections of the document.//mytagall element nodes named ’mytag’ starting from the current node

Fair Isaac Corporation Conﬁdential and Proprietary Information

588

mmxml

17.1.2.1

Axis speciﬁer

An axis speciﬁer consists in an axis name followed the the symbol ::. The supported axes are:child

children of the context node (this is the default if no axis is given)parentparent of the context node

self

the context node itself

attributethe attributes of the context nodefollowing

following node of the context nodedescendant-or-self

the context node as well as all its descendants

descendant

all descendants of the context node

17.1.2.2

Node test

By default only element nodes are considered, the node test is used to select the nodes by their name.
The special name "⁎" will keep all element nodes. Alternatively, the test can be related to the type ofthe nodes; in this case all nodes are considered and the test is one of the following expressions:text()

to select text nodes

comment()

to select comment nodes

cdata()

to select CDATA nodes

data()

to select DATA nodes

processing-instruction() to select processing instruction nodes
node()
17.1.2.3

to keep all nodes (independently of the type and name)
Abbreviated notation

Common combinations of axis-node tests have an abbreviated notation. The supported abbrevations
are:.

is equivalent to self::node()..

is equivalent to parent::node()//(used in place of /) is the same as descendant-or-self::node()

17.1.2.4

Predicate

A predicate is a Boolean expression enclosed in square brakets. The expression evaluator supports
Boolean, text and numerical values (encoded as ﬂoating point numbers). Type conversions are implicit
and implied by the operators: for instance the additive operator "+" operates on numbers, as aconsequence its operands are systematically converted to numbers. Constant strings must be quoted
using either single or double quotes.
The notation @attname designates the attribute which name is "attname": if used where a Boolean
value is expected, it is true if the attribute is deﬁned for the current node. Otherwise, this is the value ofthe attribute.

Fair Isaac Corporation Conﬁdential and Proprietary Information

589

mmxmlSupported arithmetic operators include +, -, *, div (division on ﬂoating point numbers, not integral
division as in Mosel!), mod (modulo on ﬂoating point numbers). Boolean expressions can becomposed using and and or; the usual comparators <, <=, >=, >, =, <>(or !=) can be applied to numbers.
Note that equality testing (= and <>) is deﬁned for all types. The following predeﬁned functions can also
be used in expressions:
name()

name of the node

string()value of the node

number()value of the node as a number

boolean()value of the node as a Boolean

position()

position of the current node in the selected set (ﬁrst node has
position 1)

not(boolexp)

true if ’boolexp’ is false, false otherwise

true()

value true

false()

value false

string-length()/getsize()

length of the node value

string-length(strexp)/getsize(strexp)
starts-with(strexp1,strexp2)
contains(strexp1,strexp2)

length of the text passed as parametertrue if text ’strexp1’ starts with text ’strexp2’

true if text ’strexp1’ contains text ’strexp2’

round(numexp)

rounded value of ’numexp’

floor(numexp)

ﬂoor value of ’numexp’

ceiling(numexp)/ceil(numexpr)
abs(numexp)

ceil value of ’numexp’

absolute value of ’numexp’

If the predicate [expr] is not a Boolean value, the whole expression is interpreted as[position()=expr].

17.1.3

JSON document as an XML tree
In addition to XML documents mmxml can also load and generate JSON documents represented as
XML trees such that the information contained in the document can be handled using the routines
published by this module. The procedure jsonload parses a JSON ﬁle that it maps to the internal XML
representation using the following conventions: every JSON syntactic entity is converted to an XML
element the value of which corresponds to the associated JSON value. The type of the value isidentiﬁed via the attribute "jst" that can be "str" (string), "num" (numeric), "boo" (Boolean),"nul" (null object), "obj" (object) or "arr" (array). Names of object components can be mapped toeither the name of the XML element or to an attribute (the behaviour of the parser is selected via an
option of jsonload).
For instance, consider the following JSON document:[{"name": "bob","age": 25,"student": true,"phone": [Fair Isaac Corporation Conﬁdential and Proprietary Information

590

mmxml{ "type": "home", "number": "1234567900" },{ "type": "work", "number": "6789012345" }]}]It will be represented by the following XML document when object member names are turned into XML
element names:<?xml version="1.0" encoding="iso-8859-1"?><jsv jst="arr"><jsv jst="obj"><name jst="str">bob</name><age jst="num">25</age><student jst="boo">true</student><phone jst="arr"><jsv jst="obj"><type jst="str">home</type><number jst="str">1234567900</number></jsv><jsv jst="obj"><type jst="str">work</type><number jst="str">6789012345</number></jsv></phone></jsv></jsv>

Note that with this representation the generated XML document is not necessarily valid XML (thismapping can for instance produce XML elements that have a number as name) and trying to export a
JSON document using the save procedure may produce a ﬁle that cannot be processed by an XML
parser. Using the second mode of operation avoids this problem: all elements are named "jsv" andobject names are represented by attributes. The resulting XML document is larger than the one
produced with the ﬁrst mode:<?xml version="1.0" encoding="iso-8859-1"?><jsv jst="arr"><jsv jst="obj"><jsv jst="str" name="name">bob</jsv><jsv jst="num" name="age">25</jsv><jsv jst="boo" name="student">true</jsv><jsv jst="arr" name="phone"><jsv jst="obj"><jsv jst="str" name="type">home</jsv><jsv jst="str" name="number">1234567900</jsv></jsv><jsv jst="obj"><jsv jst="str" name="type">work</jsv><jsv jst="str" name="number">6789012345</jsv></jsv></jsv></jsv></jsv>

Assuming an XML tree has been built using the above conventions, the procedure jsonsave can beused to generate a JSON document. The XML document may combine the two representations
described above and in most cases the jst attribute can be omitted. Therefore, jsonsave willproduce the same JSON document as the example shown at the start of this section from the following
XML ﬁle:<?xml version="1.0" encoding="iso-8859-1"?>
<jsv>
<jsv>
<name>bob</name><jsv name="age">25</jsv>

Fair Isaac Corporation Conﬁdential and Proprietary Information

591

mmxml<student>true</student><jsv name="phone"><jsv><type>home</type><jsv name="number" jst="str">1234567900</jsv></jsv><jsv><jsv name="type">work</jsv><jsv name="number" jst="str">6789012345</jsv></jsv></jsv></jsv></jsv>

17.2

New functionality for the Mosel language

17.2.1

The type xmldoc
The type xmldoc represents an XML document stored in the form of a tree. Each node of the tree is
identiﬁed by a node number (an integer) that is attached to the document (i.e. a node number cannot beshared by different documents and in two different documents the same number represents two
different nodes). The root node of the document has number 0: the content of the document is stored
as the children of this root node. In addition to structural properties (e.g. name, value, successor,
parent) nodes have 2 formatting properties: vertical (setvspace) and horizontal (sethspace)spacing. These indications are used when the document is saved in text form for controling how theresulting text has to be organised (see save). The general formatting policy is deﬁned by a set of
document settings: indentation mode (setindentmode), indentation skip (setindentskip) and line
length (setlinelen). Also used when exporting the documents are the XML version(setxmlversion), standalone status (setstandalone) and encoding (setencoding).

17.3

Procedures and functions
addnodeAdd a node to a document tree.

p. 594

copynode

Copy a node.

p. 596delattr

Delete an attribute of an element node.

p. 597delnodeDelete a node in a document tree.

p. 598getattr

Get the value of an attribute.

p. 599getencoding

Get the character encoding of the document.

p. 601

getfirstattr

Get the ﬁrst attribute of an element node.

p. 604getfirstchildGet the ﬁrst child of an element node.

p. 606

gethspace

Get horizontal spacing of a node.

p. 614getindentmodeGet indent mode of the document.

p. 616getindentskip

Get the size of an indentation step.

p. 617

getlastchildGet the last child of an element node.

p. 607

getlinelen

Get the length of a line.

p. 618getmaxnodes

Get the number of nodes currently allocated for a document.

p. 619Fair Isaac Corporation Conﬁdential and Proprietary Information592

mmxmlgetnameGet the name of a node.

p. 602getnext

Get the successor of a node.

p. 605

getnodeGet the ﬁrst node returned by a path speciﬁcation.

p. 608getnodesGet the list of nodes returned by a path speciﬁcation.

p. 609getparent

Get the parent of a node.

p. 610getsizeGet the size of a document.

p. 620getstandalone

Get the standalone ﬂag of the document.

p. 612gettypeGet the type of a node.

p. 611

getvalueGet the value of a node.

p. 603

getvspaceGet vertical spacing of a node.

p. 615getxmlversion

Get the XML version of the document.

p. 613jsonload

Load a JSON document.

p. 621

jsonparse

Parse a JSON document.

p. 622jsonsave

Save a JSON document.

p. 624

load

Load an XML document.

p. 625save

Save an XML document.

p. 626

setattr

Set the value of an attribute.

p. 627setencoding

Set the character encoding of the document.

p. 628sethspace

Set horizontal spacing of a node.

p. 632

setindentmodeSet indent mode for the document.

p. 635setindentskip

Set the size of an indentation step.

p. 636setlinelen

Set the length of a line.

p. 637setmaxnodes

Set the number of allocated nodes for a document.

p. 629setnameSet the name of a node.

p. 630setstandalone

Set the standalone ﬂag of the document.

p. 638setvalue

Set the value of a node.

p. 631

setvspaceSet vertical spacing of a node.

p. 634

setxmlversion

Set the XML version of the document.

p. 639testattr

Test existence of an attribute for a given element node.

p. 600xmlattr

Get an attribute during parsing of an element.

p. 640xmldecode

Decode a text string for XML.

p. 642

xmlencode

Encode a text string for XML.

p. 641

xmlparse

Parse an XML document.

p. 643

Fair Isaac Corporation Conﬁdential and Proprietary Information593

mmxmladdnodePurpose
Synopsis

Add a node to a document tree.
function addnode(doc:xmldoc, n:integer, where:integer, type:integer,
name:string, value:text):integerfunction addnode(doc:xmldoc, n:integer, where:integer, type:integer,
nameval:string|text):integerfunction addnode(doc:xmldoc, n:integer, type:integer, name:string,value:text):integerfunction addnode(doc:xmldoc, n:integer, type:integer,
nameval:string|text):integerfunction addnode(doc:xmldoc, n:integer, type:integer):integerfunction addnode(doc:xmldoc, n:integer, name:string,value:text|string|boolean|integer|real):integer

Arguments
doc
n
where

type

Document to use
Node number where to attach the new node
How to attach the new node to the node n:
XML_FIRST
as the ﬁrst element of the list where node n is located
XML_LAST
as the last element of the list where node n is located
XML_NEXT
after node n
XML_FIRSTCHILD as the ﬁrst child of node n (node n must be an element)
XML_LASTCHILD
as the last child of node n (node n must be an element)
When the function is used without this parameter, XML_LASTCHILD is assumed.
Type of node to add:

XML_ELTan element
XML_TXTa text block
XML_CDATAa CDATA section
XML_COM
a comment
XML_DATA
non interpreted data
XML_PINST
processing instruction
When the function is used without this parameter, XML_ELT is assumed.
name
Name associated to the new node. Only element and processing instruction nodes have a
name
value
Value associated to the new node. An element node does not have any value: if thisparameter is provided for a node of this type, an additional text node with the speciﬁed
value is added as the ﬁrst child of the new node
nameval If the type is XML_ELT or XML_PINST this parameter is used as the name of this node.
Otherwise it is the value of the new node
Return value
Number of the newly created node within the document.
ExampleThe following code extract appends a new node ’employee’ as last child to the node APAC. It shows
how to use diffrent versions of addnode for the creation of descendants of the new node.
declarations
DB: xmldoc

Fair Isaac Corporation Conﬁdential and Proprietary Information

594

mmxmlAPAC, NewPers, n, k: integer
end-declarations
APAC:= getnode(DB, "personnelList/region[@id='APAC']")! Append a new node to 'APAC' and set its attribute 'id':
NewPers:= addnode(DB, APAC, XML_LASTCHILD, XML_ELT, "employee")setattr(DB, NewPers, "id", "T432")! Create a comment:n:= addnode(DB, NewPers, XML_COM, "This is a new employee")! Add 2 nodes containing the specified text (nodes):n:= addnode(DB, NewPers, XML_ELT, "startDate", text(2012))
n:= addnode(DB, NewPers, XML_ELT, "name", "Tim")! Add an empty node, then set its contents:
n:= addnode(DB, NewPers, XML_ELT, "address")setvalue(DB, n, "Sydney")! Add an empty node, then create its contents as a text node:n:= addnode(DB, NewPers, XML_ELT, "language")k:= addnode(DB, n, XML_TXT, "English")
XML resulting from this code:<employee id="T432"><!--This is a new employee--><startDate>2012</startDate><name>Tim</name><address>Sydney</address><language>English</language></employee>
Further information
1. An element or processing instruction node must be named: trying to create a node of these types with
an empty name will cause an error.
2. It is not possible to add attributes with this function. Use setattr for this purpose.
Related topics
copynode, delnode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

595

mmxmlcopynode
Purpose
Synopsis

Copy a node.
function copynode(src:xmldoc, s:integer, dst:xmldoc, d:integer,
where:integer):integer

Arguments
src
s
dst
d
where

Document of node to be copied
Number of the node to copy
Destination document
Node number where to attach the new node in the destination document
How to attach the copy of the source node to the node d:
XML_FIRST
XML_LAST
XML_NEXT
XML_FIRSTCHILD
XML_LASTCHILD

Exampleas the ﬁrst element of the list where node d is locatedas the last element of the list where node d is locatedafter node das the ﬁrst child of node d (node d must be an element)
as the last child of node d (node d must be an element)

The following code extract shows how to move (copy node, then delete original) and edit a node with allits descendants
declarations
DB: xmldoc
APAC, NewPers, Pers: integer
end-declarations! Retrieve destination region node
APAC:= getnode(DB, "personnelList/region[@id='APAC']")! Retrieve employee record (node) for 'Lisa'
Pers:=
getnode(DB, "personnelList/region/employee/name[string()='Lisa']/..")! Employee Lisa moves to Delhi: copy node & delete in original location
NewPers:= copynode(DB, Pers, DB, APAC, XML_LASTCHILD)
delnode(DB, Pers)! Update the 'address' information
setvalue(DB, getnode(DB, NewPers, "address"), "Delhi")

Further information
This routine copies the node as well as all of its descendants if it is an element node. Source anddestination documents may be the same.
Related topics
addnode, delnode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

596

mmxmldelattr
Purpose
Synopsis

Delete an attribute of an element node.
procedure delattr(doc:xmldoc, n:integer, name:string)Arguments
doc
n
name
ExampleDocument to use
Element node to modify
Name of the attribute to remove

See testattr.

Further information
This routine has no effect if the element does not have any attribute of the speciﬁed name.
Related topics
setattrModulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

597

mmxmldelnodePurpose
Synopsis

Delete a node in a document tree.
procedure delnode(doc:xmldoc, n:integer)

Arguments
docnExampleDocument to use
Number of the node to delete

See copynode.

Further information
This routine deletes the node as well as all of its descendants if it is an element node.
Related topics
addnode, copynode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

598

mmxmlgetattr
Purpose
Synopsis

Get the value of an attribute.
function getattr(doc:xmldoc, n:integer, name:string):text
function getboolattr(doc:xmldoc, n:integer, name:string):booleanfunction getintattr(doc:xmldoc, n:integer, name:string):integerfunction getrealattr(doc:xmldoc, n:integer, name:string):realfunction getstrattr(doc:xmldoc, n:integer, name:string):stringArguments
doc
n
name

Document to use
Node number (must be an element)
Name of the attribute

Return value
The value of the attribute or an empty string, 0 or false depending on the expected type.
ExampleThe following code extract prints the contents of ’name’ (leftbound in a 10 character space) and theattributes ’id’ of all ’employee’ nodes, and the ’id’ of their parent node.
declarations
DB: xmldoc
AllEmployees: list of integer
end-declarations
getnodes(DB, "personnelList/region/employee", AllEmployees)
forall(p in AllEmployees)
writeln(textfmt(getvalue(DB, getnode(DB, p, "name")), -10),"(ID: ", getattr(DB,p,"id"), ") ","region: ", getattr(DB, getparent(DB, p), "id"))
Output produced by this code will look as follows:
Lisa
James
Sarah

(ID: L234) region: EMEA
(ID: J876) region: APAC
(ID: S678) region: AM

Further information
1. Values of attributes are stored as text objects: the ﬁrst version of the routine returns a reference tothe object containing the attribute value. Modifying this text will also alter the attribute value. Using oneof the alternative versions of this routine allows to avoid having to perform a type conversion. Notehowever that no validation is performed and a conversion error will result in a 0 for a number andfalse for a Boolean without raising any error.
2. A default value (empty string, 0 or false) is returned if the requested attribute is not deﬁned. Usefunction testattr to check whether a given node has a particular attribute.
Related topics
setattr, testattr, getfirstattr
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

599

mmxmltestattr
Purpose
Synopsis

Test existence of an attribute for a given element node.
function testattr(doc:xmldoc, n:integer, name:string):boolean

Arguments
doc
n
name

Document to use
Node number (must be an element)
Name of the attribute

Return value
true if the requested attribute is deﬁned for the node.
ExampleThis example tests whether the attribute ’parttime’ is deﬁned for an employee, and if this is the case theattribute gets deleted after printing the name of the employee.
declarations
DB: xmldoc
AllEmployees: list of integer
end-declarations
getnodes(DB, "personnelList/region/employee", AllEmployees)
forall(p in AllEmployees | testattr(DB, p, "parttime")) dowriteln(getvalue(DB, getnode(DB, p, "name")))delattr(DB, p, "parttime")
end-doRelated topics
setattr, getattr
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

600mmxmlgetencoding
Purpose
Synopsis

Get the character encoding of the document.
function getencoding(doc:xmldoc):stringArgument
doc

Document to use

Return value
Character encoding of the document
Related topics
getstandalone, getxmlversion
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

601mmxmlgetname
Purpose
Synopsis

Get the name of a node.
function getname(doc:xmldoc, n:integer):stringArguments
docnDocument to use
Node number

Return value
The name of the node depending on the node type:
XML_ELTname of the element section
XML_TXT"#text"
XML_CDATA"#cdata-section"
XML_COM"#comment"
XML_DATA"#data"XML_PINST
processing instruction target
XML_ATTR
name of the attribute
ExampleThe following example collects the names of all element nodes occurring in a document.
declarations
DB: xmldoc
NodeList: list of integer
NodeNames: set of string
end-declarations
getnodes(DB, "/descendant-or-self::node()", NodeList)
NodeNames:= union(r in NodeList | gettype(DB,r)=XML_ELT) {getname(DB,r)}writeln("Names of element nodes: ", NodeNames)

Further information
Only element, attribute and processing instruction nodes have a name, for all other node types theabove listed constant name is returned.
Related topics
gettype, getvalue, setname
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information602

mmxmlgetvalue
Purpose
Synopsis

Get the value of a node.
function getvalue(doc:xmldoc, n:integer):text
function getboolvalue(doc:xmldoc, n:integer):booleanfunction getintvalue(doc:xmldoc, n:integer):integerfunction getrealvalue(doc:xmldoc, n:integer):realfunction getstrvalue(doc:xmldoc, n:integer):stringArguments
docnDocument to use
Node number

Return value
The value of the node.
ExampleThis code prints out the name of the employee with attribute id="T345".
declarations
DB: xmldoc
end-declarations
writeln("Person with id='T345': ", getvalue(DB, getnode(DB,"personnelList/region/employee[@id='T345']/name") ))Further information
1. Values of nodes are stored as text objects: the ﬁrst version of the routine returns a reference to theobject containing the value. Modifying this text will also alter the node value. Using one of thealternative versions of this routine allows to avoid having to perform a type conversion. Note howeverthat no validation is performed and a conversion error will result in a 0 for a number and false for a
Boolean without raising any error.
2. Element nodes have no value: the returned value corresponds to the value of the ﬁrst child of type textof this element (or an empty string if no such child can be found).
Related topics
gettype, getname, setvalue
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

603

mmxmlgetﬁrstattr
Purpose
Synopsis

Get the ﬁrst attribute of an element node.
function getfirstattr(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number (must be an element)

Return value
The node number of the ﬁrst attribute of the element node provided or -1 if there is no attribute.
ExampleThe following example displays all attributes of node e:
declarations
DB: xmldoc
a,e: integer
end-declarations
a:=getfirstattr(DB,e)while(a>0) do
writeln(getname(DB,a), "=", getvalue(DB,a))a:=getnext(DB,a)end-doFurther information
Attributes are represented by nodes of type XML_ATTR: all node-related routines can be applied toattribute nodes.
Related topics
getnext, getfirstchild, getlastchild, getparent
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

604

mmxmlgetnext
Purpose
Synopsis

Get the successor of a node.
function getnext(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number

Return value
The node number of the following node or -1 if the current node is the last of the list.
ExampleThis example enumerates all child nodes within a speciﬁc region and displays the ’id’ for all ’employee’nodes on a single line, adding a line break after the last name:declarations
DB: xmldoc
APAC, Pers: integer
end-declarations
APAC:= getnode(DB, "personnelList/region[@id='APAC']")
Pers:= getfirstchild(DB, APAC)
LastPers:= getlastchild(DB, APAC)
while(Pers>-1) do
if getname(DB, Pers)="employee" thenwrite(" ", getattr(DB,Pers,"id"))
end-ifif Pers=LastPers then writeln; end-if
Pers:= getnext(DB, Pers)
end-doFurther information
Node numbers returned by Mosel are not directly related to the order of nodes within the XML document(i.e. a larger node number does not imply that a node succeeds a node with a smaller number).
Related topics
getfirstattr, getfirstchild, getlastchild, getparent
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

605

mmxmlgetﬁrstchild
Purpose
Synopsis

Get the ﬁrst child of an element node.
function getfirstchild(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number (must be an element)

Return value
The node number of the ﬁrst child or -1 if there is no child.
ExampleSee getnext.

Related topics
getfirstattr, getnext, getlastchild, getparent
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

606

mmxmlgetlastchild
Purpose
Synopsis

Get the last child of an element node.
function getlastchild(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number (must be an element)

Return value
The node number of the last child or -1 if there is no child.
ExampleSee getnext.

Related topics
getfirstattr, getfirstchild, getnext, getparent
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

607

mmxmlgetnodePurpose
Synopsis

Get the ﬁrst node returned by a path speciﬁcation.
function getnode(doc:xmldoc, n:integer, p:string|text):integerfunction getnode(doc:xmldoc, n:integer):integerfunction getnode(doc:xmldoc, p:string):integer

Arguments
docnpDocument to use
Base node number (0 when not provided)
Path to the node ("⁎" when not provided)

Return value
The node number of the ﬁrst node selected by the path p; -1 if no node can be found.
ExampleThe following example shows different forms of the getnode function.
declarations
DB: xmldoc
Root, EMEA: integer
end-declarations! Get the first element that is not a comment or a processing instruction
Root:= getnode(DB,"⁎")! Same as: getnode(DB,0,"⁎")! Get the 'region' node with id=EMEA
EMEA:= getnode(DB, "personnelList/region[@id='EMEA']")! Check for employee record (node) for 'Sam' under 'EMEA'
if getnode(DB, EMEA, "employee/name[string()='Sam']/..")<0 thenwriteln("No employee called 'Sam' in EMEA")
end-ifFurther information
1. Refer to section 17.1.2 for a detailed description of the syntax and semantic of XML paths.
2. This function is the same as getfirstchild when used without path speciﬁcation.
Related topics
getnodes, getfirstchild
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

608

mmxmlgetnodesPurpose
Synopsis

Get the list of nodes returned by a path speciﬁcation.
procedure getnodes(doc:xmldoc, n:integer, p:string|text, l:list of integer)
procedure getnodes(doc:xmldoc, p:string, l:list of integer)
procedure getnodes(doc:xmldoc, n:integer, l:list of integer)

Arguments
docnplExampleDocument to use
Base node number (0 when not provided)
Path to the node ("⁎" when not provided)
List where result is returned

Here are a number of examples how to retrieve nodes with speciﬁc properties:
declarations
DB: xmldoc
Employees, AllEmployees: list of integer
end-declarations! Get all employees in the Americas
getnodes(DB, "personnelList/region[@id='AM']/employee", Employees)! All employees who started before 2005
getnodes(DB, "personnelList/region/employee/startDate[number()<2005]/..",
Employees)! All employees whose names start with "J"getnodes(DB, "personnelList/region/employee", AllEmployees)
forall(n in AllEmployees) do
getnodes(DB, n, "./name[starts-with(string(),'J')]/..", Employees)
forall(p in Employees) save(DB, p, "")end-do! Employees speaking at least 3 languages (=have a third "language" entry)
getnodes(DB, "personnelList/region/employee/language[position()=3]/..",
Employees)

Further information
1. Refer to section 17.1.2 for a detailed description of the syntax and semantic of XML paths.
2. This function resets the list it receives as parameter: the provided list is returned empty if no node canbe found.
Related topics
getnodeModulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information609

mmxmlgetparent
Purpose
Synopsis

Get the parent of a node.
function getparent(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number

Return value
The node number of the parent node or -1 if n=0 (root node has no parent).
ExampleSee getattr.

Related topics
getfirstattr, getfirstchild, getlastchild, getnext
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

610mmxmlgettype
Purpose
Synopsis

Get the type of a node.
function gettype(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number

Return value
The type of the node:
XML_ELTan element
XML_TXTa text
XML_CDATAa CDATA section
XML_COM
a comment
XML_DATAa data section
XML_PINST
a processing instruction
XML_ATTRan attribute-1
if the node number is not valid
ExampleSee getname.

Further information
This function returns -1 if the provided node number is not valid: this feature can be used to verify thevalidity of a node number before using it with other functions.
Related topics
getname, getvalue
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

611

mmxmlgetstandalone
Purpose
Synopsis

Get the standalone ﬂag of the document.
function getstandalone(doc:xmldoc):integer

Argument
doc

Document to use

Return valueStandalone ﬂag:-1
ﬂag not speciﬁed
0standalone=no1
standalone=yes
Further information
The value of this ﬂag is not used by mmxml. This is just an information to be saved in the header of the
XML document. The default value for this ﬂag is -1.
Related topics
getencoding, getxmlversion
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

612

mmxmlgetxmlversion
Purpose
Synopsis

Get the XML version of the document.
function getxmlversion(doc:xmldoc):stringArgument
doc

Document to use

Return value
XML version as a text string
Further information
The XML version number is not used by mmxml. This is just an information to be saved in the header ofthe XML document. The default value for this option is 1.0.
Related topics
getencoding, getstandalone
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

613

mmxmlgethspace
Purpose
Synopsis

Get horizontal spacing of a node.
function gethspace(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number

Return value
Number of spaces inserted before the node output
Further information
This spacing indicates the number of spaces to insert before displaying the node from the start of a
new line when outputing the document. The horizontal spacing setting is only used when the
indentation is in manual mode (see setindentmode).
Related topics
getvspace, getindentmode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

614

mmxmlgetvspace
Purpose
Synopsis

Get vertical spacing of a node.
function getvspace(doc:xmldoc, n:integer):integer

Arguments
docnDocument to use
Node number

Return value
Number of carriage returns inserted before the node output
Further information
This spacing indicates the number of empty lines to insert before displaying the node when outputing
the document. The vertical spacing setting is only used when the indentation is in manual mode (seesetindentmode).
Related topics
gethspace, getindentmode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

615

mmxmlgetindentmodePurpose
Synopsis

Get indent mode of the document.
function getindentmode(doc:xmldoc):integer

Argument
doc

Document to use

Return value
Indent mode:
XML_AUTO
XML_NONE
XML_MANUAL

automatic indentation
no formatting
use vertical/horizontal spacing settings of each node

Related topics
setindentmode, getindentskip, getlinelen
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

616

mmxmlgetindentskip
Purpose
Synopsis

Get the size of an indentation step.
function getindentskip(doc:xmldoc):integer

Argument
doc

Document to use

Return value
Number of spaces to add for each indentation
Related topics
setindentskip, getindentmode, getlinelen
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

617

mmxmlgetlinelen
Purpose
Synopsis

Get the length of a line.
function getlinelen(doc:xmldoc):integer

Argument
doc

Document to use

Return value
Length of a line in characters for outputting the XML document
Related topics
setlinelen, getindentmode, getindentskip
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

618

mmxmlgetmaxnodes
Purpose
Synopsis

Get the number of nodes currently allocated for a document.
function getmaxnodes(doc:xmldoc):integer

Argument
doc

Document to use

Return value
Number of nodes currently allocatedFurther information
This function returns the amount of memory (in number of nodes) currently allocated for a given
document. This amount may be larger than the amount actually in use.
Related topics
setmaxnodes, getsize
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

619

mmxmlgetsize
Purpose
Synopsis

Get the size of a document.
function getsize(doc:xmldoc):integer

Argument
doc

Document to use

Return value
The number of nodes used by the document.
Related topics
getmaxnodes
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

620

mmxmljsonloadPurpose
Synopsis

Load a JSON document.
procedure jsonload(doc:xmldoc, fname:text)
procedure jsonload(doc:xmldoc, fname:text, mode:integer)

Arguments
doc
Document to use
fname File name of the document to loadmode How to handle JSON object names:
0
Object names are converted to XML element names (default)
1
Object names are saved as the attribute "name"
Further information
1. This routine replaces the content of the provided document object with the JSON ﬁle given as second
argument. If the ﬁle cannot be accessed or if an error occurs during reading, the procedure generates
an IO error (which may be intercepted if the control parameter ioctrl is true).
2. The parser converts the original JSON document into an XML representation (See Section 17.1.3). Using
the version of the procedure without the mode argument is the same as using 0 for this parameter.
Related topics
jsonsave, jsonparse, load
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

621

mmxmljsonparse
Purpose
Synopsis

Parse a JSON document.
function jsonparse(afct:array(range) of string,ctx:ctxtype): integer

Arguments
afct

ctx

Event function table. Each entry of this array is the name of the function to call when thecorresponding event occurs. The expected events are (all of these entries are optional):
JSON_FCT_OPEN_OBJ
Opening of an object
JSON_FCT_CLOSE_OBJ Closing of an object
JSON_FCT_OPEN_ARR
Opening of an array
JSON_FCT_CLOSE_ARR Closing of an array
JSON_FCT_TEXT
A textual value
JSON_FCT_NUM
A numerical value
JSON_FCT_BOOL
A Boolean value
JSON_FCT_NULL
The null value
Value passed as ﬁrt argument of all event functions

Return value
0 if successful, 1 in case of parsing error or a non-zero value returned by an event function
ExampleThis example displays values of object members "name" and "age" of a JSON document:
declarations
afct:array(range) of strings_ctx=record
cnt:integer
end-record
c:s_ctx
end-declarations

public function setvalue_all(ctx:s_ctx,name:text,type:integer,val:text):integer
if name="name" or name="age" thenwriteln(name,":",val)
ctx.cnt+=1
end-ifend-function
afct(JSON_FCT_TEXT):="setvalue_all"fopen("mydoc.json",F_INPUT)
rts:=jsonparse(afct,c)fclose(F_INPUT)
writeln("line count:",c.cnt)

Fair Isaac Corporation Conﬁdential and Proprietary Information! A value as a text622

mmxmlFurther information
1. This function is an alternative approach to jsonload for processing JSON documents: instead ofloading into memory the entire document this function calls a dedicated routine whenever it identiﬁes a
JSON entity. For instance a speciﬁc function is called when an object is open and another one when it
is closed. It is up to the Mosel program to decide how to handle the document via these event handling
functions.
2. To each event type corresponds a speciﬁc function signature. These functions return an integer that
decides whether parsing should continue: a non-zero value will cause the parsing to cancel (this value
is used as the return value of jsonparse). The expected function signatures are:
JSON_FCT_OPEN_OBJ

function open_object(ctx:ctxtype, name:text):integer

JSON_FCT_CLOSE_OBJ

function close_object(ctx:ctxtype):integer

JSON_FCT_OPEN_ARR

function open_array(ctx:ctxtype, name:text):integer

JSON_FCT_CLOSE_ARR

function close_array(ctx:ctxtype):integer

JSON_FCT_TEXT function text_val(ctx:ctxtype, name:text, type:integer,
val:text):integer
JSON_FCT_NUM function num_val(ctx:ctxtype, name:text, name:text,
val:real):integer
JSON_FCT_BOOL function bool_val(ctx:ctxtype, name:text, name:text,
val:boolean):integer
JSON_FCT_NULL

function null_val(ctx:ctxtype, name:text):integer

In addition to the pre-deﬁned arguments these functions take a context as their ﬁrst parameter. Thisvariable (that can be of any type) is provided to the jsonparse routine and can be used by the event
functions for storing progress information.
The name argument is not empty only when the value corresponds to an object member: in this casethis parameter is the label of this member. The type argument passed to the text_val function
indicates the type of the data (0 for null, 1 for text, 2 for numerical and 3 for Boolean): this function isused with the textual representation of the value when the required type-speciﬁc function is notavailable. For instance this function will be called with type=3 if a Boolean value has been read andthe entry JSON_FCT_BOOL is not deﬁned in the function table.
3. An error message indicating the location of the error is displayed when the parsing fails or if an event
function returns a negative value (a positive value also interrupts parsing but no message is displayed).
Related topics
jsonload
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

623

mmxmljsonsave
Purpose
Synopsis

Save a JSON document.
procedure jsonsave(doc:xmldoc, fname:text)

Arguments
doc
Document to savefname Destination ﬁle name
Further information
1. This routine generates a JSON ﬁle from the provided xmldoc object. It is assumed that the document
is built according to the JSON conventions (See Section 17.1.3). The result is undeﬁned if theconventions are not respected.
2. This procedure does not require that the elements of the tree are typed using the "jst" attribute: thetype is deduced from the value of the node when this attribute is missing. Moreover, both object
member naming conventions can be used: when outputing an object, the member name can be taken
either from the element name or from the attribute "name". If both are available, the attribute takes
precedence.
Related topics
jsonload, save
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

624

mmxmlload
Purpose
Synopsis

Load an XML document.
procedure load(doc:xmldoc, fname:text)

Arguments
doc
Document to use
fname File name of the document to load
ExampleThis code reads in a document and displays its contents on screen applying automatic formatting
instead of its original formatting.
declarations
DB: xmldoc
end-declarations! Reading data from an XML fileload(DB, "refexample.xml")! Set indentation mode for XML output (default after load: MANUAL)
setindentmode(DB, XML_AUTO)! Display document contents on screen
save(DB, "")Further information
This routine replaces the content of the provided document object with the XML ﬁle given as second
argument: all properties of the document are reset to their default value and the indentation mode is
set to XML_MANUAL (see setindentmode). Vertical and horizontal spacing of each loaded node are
set in order to preserve as much as possible the original formatting of the document. If the ﬁle cannot
be accessed or if an error occurs during reading, the procedure generates an IO error (which may beintercepted if the control parameter ioctrl is true).
Related topics
save, xmlparse, jsonload
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

625

mmxmlsave
Purpose
Synopsis

Save an XML document.
procedure save(doc:xmldoc, fname:text)
procedure save(doc:xmldoc, n:integer, fname:text)

Arguments
doc
n
fname
ExampleDocument to save
Node number to use as root node (default: 0)
Destination ﬁle name

This example shows the two versions of this procedure.
declarations
DB: xmldoc
Pers: integer
end-declarations! Save XML document to file 'results.xml'
save(DB, "results.xml")! Display a subtree on screen
Pers:= getnode(DB, "personnelList/region/employee[@id='T345']")save(DB, Pers, "")Further information
1. This routine generates an XML ﬁle from the provided xmldoc object. The XML header is produced
using the properties deﬁned with setencoding, setxmlversion and setstandalone. No header
is emitted if either the encoding or the version is an empty string.
2. When providing an alternative root node, only the speciﬁed part of the document tree is exported
without any XML header.
3. The document is formatted according to the indentation mode and its associated settings (seesetindentmode); XML control characters are encoded (see xmlencode).
Related topics
load, save
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

626

mmxmlsetattr
Purpose
Synopsis

Set the value of an attribute.
procedure setattr(doc:xmldoc, n:integer, name:string,v:text|string|boolean|integer|real)

Arguments
doc
n
name
v
ExampleDocument to use
Node number (must be an element)
Name of the attribute
New value for the attribute

See addnode.

Further information
1. Attribute values are stored as text objects: the versions of this procedure accepting other types
perform the conversion implicitly.
2. Attributes are nodes of type XML_ATTR: procedure setvalue may also be used to change the value ofan attribute.
3. Setting an empty value to an attribute does not remove this attribute from the attribute list of theelement. Use delattr for this purpose.
Related topics
getattr, delattr
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

627

mmxmlsetencoding
Purpose
Synopsis

Set the character encoding of the document.
procedure setencoding(doc:xmldoc, enc:string)Arguments
doc
encDocument to use
Name of the character encoding

Further information
The default character encoding is UTF-8.
Related topics
save, setstandalone, setxmlversion
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

628

mmxmlsetmaxnodes
Purpose
Synopsis

Set the number of allocated nodes for a document.
procedure setmaxnodes(doc:xmldoc, m:integer)

Arguments
docmDocument to use
Number of nodes to reserve

Further information
This procedure sets the amount of memory reserved for a document. Normally, mmxml allocatesmemory on demand but using this procedure it is possible to allocate at once a larger block of memory
to possibly speedup the loading of very large documents. If the requested amount is smaller than what
is required to represent the document currently held in the doc object, the memory block is reduced asmuch as possible such that the document can still be stored.
Related topics
getmaxnodes
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

629

mmxmlsetname
Purpose
Synopsis

Set the name of a node.
procedure setname(doc:xmldoc, n:integer,name:string)Arguments
doc
n
name

Document to use
Node number (must be an element or processing instruction)
New name for the node

Further information
Only element and processing instruction nodes can be modiﬁed with this routine; for all other nodetypes an error will be raised.
Related topics
setvalue
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

630

mmxmlsetvalue
Purpose
Synopsis

Set the value of a node.
procedure setvalue(doc:xmldoc, n:integer,
v:text|string|integer|real|boolean)

Arguments
docnv
ExampleDocument to use
Node number
New value for the nodeSee copynode.

Further information
1. Node values are stored as text objects: the versions of this procedure accepting other types performthe conversion implicitly.
2. Element nodes have no value: this procedure will modify the value of the ﬁrst child text node of theelement. If no such node exists, a new text node will be added to the beginning of the list of children.
Related topics
setnameModulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

631

mmxmlsethspace
Purpose
Synopsis

Set horizontal spacing of a node.
procedure sethspace(doc:xmldoc, n:integer, s:integer)

Arguments
docns
ExampleDocument to use
Node number
Number of spaces to put before the node output

The following example reformats the XML document layout by adding an additional line before ’region’nodes and printing three consecutive tags within ’employee’ on a single line. The indentmode is set to’manual’ in order to apply the user formatting (instead of automatic or none).
declarations
DB: xmldoc
NodeList, Employees: list of integer
end-declarations! New line without indentation for Root
setvspace(DB, Root, 1)! Add extra line in between regions, keeping original indentation
getnodes(DB, "personnelList/region", NodeList)
forall(r in NodeList) setvspace(DB, r, 2)! Spacing/indentation for 'employee' taggetnodes(DB, "personnelList/region/employee", Employees)
forall(p in Employees) do
setvspace(DB, p, 1); sethspace(DB, p, 4)! Within 'employee', display up to 3 consecutive tags on a single line
getnodes(DB, p, "child::node()[position() mod 3=1]", NodeList)
forall(r in NodeList) do
setvspace(DB, r, 1); sethspace(DB, r, 6)
end-dogetnodes(DB, p, "child::node()[position() mod 3<>1]", NodeList)
forall(r in NodeList) do
setvspace(DB, r, 0); sethspace(DB, r, 1)
end-doend-do! Set indentation mode to 'manual' to use our own formatting for display
setindentmode(DB, XML_MANUAL)
save(DB, "")Further information
This spacing indicates the number of spaces to skip from the start of a new line before displaying thenode when outputing the document. The horizontal spacing setting is only used when the indentation isin manual mode (see setindentmode).

Fair Isaac Corporation Conﬁdential and Proprietary Information

632

mmxmlRelated topics
setvspace, setindentmode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

633

mmxmlsetvspace
Purpose
Synopsis

Set vertical spacing of a node.
procedure setvspace(doc:xmldoc, n:integer, s:integer)

Arguments
docns
ExampleDocument to use
Node number
Number of carriage return to put before the node output

See sethspace.

Further information
This spacing indicates the number of empty lines to add before displaying the node when outputing the
document. The vertical spacing setting is only used when the indentation is in manual mode (seesetindentmode).
Related topics
sethspace, setindentmode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

634

mmxmlsetindentmodePurpose
Synopsis

Set indent mode for the document.
procedure setindentmode(doc:xmldoc, imod:integer)

Arguments
doc
imod

Document to use
Indent mode:
XML_AUTO
XML_NONE
XML_MANUAL

Exampleautomatic indentation
no formatting
use vertical/horizontal spacing of each node

See sethspace.

Further information
This parameter speciﬁes how the XML document must be formatted by the save routine. Automaticindentation can be tuned by redeﬁning the indent skip (setindentskip) and line length(setlinelen). If the indent mode is set to XML_NONE, the document is exported on a single line
without formatting. Finally, with manual indenting, each node is placed according to its
horizontal/vertical spacing as speciﬁed by setvspace and sethspace.
Related topics
save, setindentskip, setlinelen
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

635

mmxmlsetindentskip
Purpose
Synopsis

Set the size of an indentation step.
procedure setindentskip(doc:xmldoc, skip:integer)

Arguments
doc
skip
ExampleDocument to use
Number of spaces to add for each indentation (at least 1; default is 2)

This code reads in a document and displays its contents on screen applying automatic formatting withsingle space indentation and increased line length.
declarations
DB: xmldoc
end-declarations! Reading data from an XML fileload(DB, "refexample.xml")! Set indentation mode for XML output (default after load: MANUAL)
setindentmode(DB, XML_AUTO)! Set smaller indentation skip than default
setindentskip(DB, 1)! Increase default line length
setlinelen(DB, 80)! Display document contents on screen
save(DB, "")Further information
When the document is formatted automatically (see setindentmode) the number of spaces speciﬁedby this procedure is added to the current margin each time a new indent step is created.
Related topics
save, setindentmode, setlinelen
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

636

mmxmlsetlinelen
Purpose
Synopsis

Set the length of a line.
procedure setlinelen(doc:xmldoc, len:integer)

Argumentsdoc
len
ExampleDocument to use
Length of a line in characters (at least 1; default is 70)

See setindentskip.

Further information
When outputing the document, a line break is inserted between nodes or while displaying a list ofelement attributes whenever more than the speciﬁed number of characters has been written.
Related topics
save, setindentmode, setindentskip
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

637

mmxmlsetstandalone
Purpose
Synopsis

Set the standalone ﬂag of the document.
procedure setstandalone(doc:xmldoc, std:integer)

Arguments
doc
std

Document to use
Standalone ﬂag:-1
ﬂag not speciﬁed
0standalone=no1
standalone=yes

Further information
The value of this ﬂag is not used by mmxml. This is just an information to be saved in the header of the
XML document. The default value for this ﬂag is -1.
Related topics
save, setencoding, setxmlversion
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

638

mmxmlsetxmlversion
Purpose
Synopsis

Set the XML version of the document.
procedure setxmlversion(doc:xmldoc, xv:string)Arguments
doc
xv

Document to use
XML version

Further information
The XML version number is not used by mmxml. This is just an information to be saved in the header ofthe XML document. The default value for this option is 1.0.
Related topics
save, setencoding, setstandalone
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

639

mmxmlxmlattr
Purpose
Synopsis

Get an attribute during parsing of an element.
procedure xmlattr(ndx:integer, name:text, val:text)
procedure xmlattr(aname:string, val:text)

Arguments
ndx
name
val
aname

Attribute index
Attribute name (returned by the procedure)
Attribute value (returned by the procedure)
Attribute name (provided to the procedure)

Further information
1. This procedure can only be used from the open element function while parsing an XML document withthe xmlparse function.
2. With the ﬁrst syntax, the attribute index ndx is returned by the procedure (both its name and value).
This index value must range between 1 and the last index as passed to the open element function. With
the second syntax the name of the attribute to retrieve is given to the procedure. An empty string isreturned if this attribute is not deﬁned for the current element.
Related topics
xmlparse
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

640mmxmlxmlencode
Purpose
Synopsis

Encode a text string for XML.
function xmlencode(t:text):text

Argumentt

text to encode

Further information
Encode a text string for XML by replacing control characters (<, >, &, ’, ") by their encoded equivalent.
Related topics
xmldecode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

641

mmxmlxmldecode
Purpose
Synopsis

Decode a text string for XML.
function xmldecode(t:text):text

Argumentt

text to decode

Further information
Decode a text string from XML by replacing encoded sequences (&lt; &gt; &amp; &apos; &quot;) by thecorresponding control characters.
Related topics
xmlencode
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

642

mmxmlxmlparse
Purpose
Synopsis

Parse an XML document.
function xmlparse(afct:array(range) of string,mode:integer,ctx:ctxtype):
integer

Arguments
afct

mode
ctx

Event function table. Each entry of this array is the name of the function to call when thecorresponding event occurs. The expected events are (all of these entries are optional):
XML_FCT_DECL
Document declarations
XML_FCT_TXT
A text node (same value as ML_TEXT)
XML_FCT_CDATA
A CDATA node
XML_FCT_COM
A commentary node
XML_FCT_DATAA DATA node
XML_FCT_PINSTA processing instruction node
XML_FCT_OPEN_ELTOpening of a new element node
XML_FCT_CLOSE_ELT Closing of an element node
If 0, spaces are preserved and returned as text elements. Otherwise all text elements aretrimmed
Value passed as ﬁrst argument of all event functions

Return value
0 if successful, 1 in case of parsing error or a non-zero value returned by an event function
ExampleThis example displays the structure of an XML document without loading it into memory.
! Display element name and update indentation
public function start_elt(spce:text,name:text,nba:integer):integer
writeln(spce,name)spce+=" "end-function! Update indentation when element closes
public function end_elt(spce:text):integer
spce-=" "end-function
declarations
afct:array(range) of string
end-declarations
afct(XML_FCT_OPEN_ELT):="start_elt" ! define open elementafct(XML_FCT_CLOSE_ELT):="end_elt" ! define close element
fopen("mydocument.xml",F_INPUT)
rts:=xmlparse(afct,1,text(""))
fclose(F_INPUT)

Fair Isaac Corporation Conﬁdential and Proprietary Information

643

mmxmlFurther information
1. This function is an alternative approach to load for processing XML documents: instead of loading
into memory the entire document this function calls a dedicated routine whenever it identiﬁes an XML
entity. For instance a speciﬁc function is called when an element is open and another one when it isclosed. It is up to the Mosel program to decide how to handle the document via these event handling
functions.
2. To each event type corresponds a speciﬁc function signature. These functions return an integer that
decides whether parsing should continue: a non-zero value will cause the parsing to cancel (this value
is used as the return value of xmlparse). The expected function signatures are:
XML_FCT_DECL function xmldecl(ctx:ctxtype, vers:text, enc:text,
std:integer):integer
XML_FCT_TXT

function text_node(ctx:ctxtype, type:integer,
data:text):integer

XML_FCT_CDATA function cdata_node(ctx:ctxtype, type:integer,
data:text):integer
XML_FCT_COM

function comment_node(ctx:ctxtype, type:integer,
data:text):integer

XML_FCT_DATA function data_node(ctx:ctxtype, type:integer,
data:text):integer
XML_FCT_PINST function processing_instr(ctx:ctxtype, target:text,
data:text):integer
XML_FCT_OPEN_ELT function open_element(ctx:ctxtype, name:text,
nba:integer):integer
XML_FCT_CLOSE_ELT

function close_element(ctx:ctxtype):integer

In addition to the pre-deﬁned arguments these functions take a context as their ﬁrst parameter. Thisvariable (that can be of any type) is provided to the xmlparse routine and can be used by the event
functions for storing progress information.
The type passed to the text node functions is the XML type corresponding to the function (namely
XML_TXT, XML_CDATA, XML_COM, XML_DATA).
The open_element function receives the name of the element as well as the number of deﬁned
attributes. To retrieve these attributes xmlattr can be used.
3. An error message indicating the location of the error is displayed when the parsing fails or if an event
function returns a negative value (a positive value also interrupts parsing but no message is displayed).
Related topics
load
Modulemmxml

Fair Isaac Corporation Conﬁdential and Proprietary Information

644

CHAPTER 18

mmxnlp
The mmxnlp module provides access to nonlinear solvers, extending the capabilities provided by the
mmxprs and mmnl modules. In particular, this module allows existing linear or mixed integer (MIP)
models to be upgraded to include nonlinearities, without requiring unnecessary changes to theformulation. To use this module, the following line must be included in the header of the Mosel modelﬁle:uses 'mmxnlp'

Problem type and module hierarchy
Module mmxprs provides
linear models andmixed integer linear models.

Module mmnl adds support for

convex quadratic models,

convex quadratic mixed integer models,

convex, quadratically constrained models, and

convex, quadratically constrained mixed integer models.

Module mmxnlp adds support forgeneral nonlinear problems andgeneral nonlinear mixed integer problems.

If the mmxnlp module is used for a model which does not require a general nonlinear solver, this shouldbe equivalent to using the appropriate mmxprs or mmnl module directly.

18.1

New functionality for the Mosel language

18.1.1The userfunc type
A nonlinear model may employ one or more black box evaluation functions, which can be used toprovide function evaluations to the solver. These are represented in mmxnlp by the new userfunc
type. The implementation of each userfunc must be described by calling one of:Fair Isaac Corporation Conﬁdential and Proprietary Information

645

mmxnlpuserfuncMosel: to declare that a user function is implemented as a Mosel function

userfuncExcel: to declare that a user function is implemented in an Excel ﬁle

userfuncExcelMacro: to declare that a user function is implemented as a Visual Basic macro
in ExceluserfuncDLL: to declare that a user function is implemented in a dynamically linked library (DLL)

Note that user functions returning multiple arguments are support by the mmxnlp module. The F
construction allows a userfunc to be included in any nonlinear (nlctr) expression, and groups eachoccurrence of the userfunc with its parameters . During the solve, the parameters (which are of typenlctr themselves) will be evaluated at the current solution, and the real-valued results passed to theuserfunc implementation. The function userfuncinfo can be used to ﬁnd out which parameters
the system has deduced it needs to pass to a particular userfunc.

18.1.2The tolset typeThe module provides a large number of conﬁgurable tolerances for users of the Xpress NonLinear SLP
solver. A tolset describes a convergence tolerance set, which can be used for those nonlinear solvers
supporting variable-speciﬁc convergence tolerances. The elements of a tolerance set are deﬁned byusing settol, and assigned to a variable or list of variables using settolset. For more details on
tolerance sets, please refer to the Xpress NonLinear Reference Manual.

18.1.3

XNLP_TOL_TC: The absolute closure tolerance

XNLP_TOL_TA: The absolute delta tolerance

XNLP_TOL_RA: The relative delta tolerance

XNLP_TOL_TM: The absolute matrix tolerance

XNLP_TOL_RM: The relative matrix tolerance

XNLP_TOL_TI: The absolute impact tolerance

XNLP_TOL_RI: The relative impact tolerance

XNLP_TOL_TS: The relative slack impact tolerance

XNLP_TOL_RS: The absolute slack impact tolerance

The mpproblem.xprs.xnlp problem type
When using the mmxnlp module, the type of the active Mosel problem is changed frommpproblem.xprs to the extended type mpproblem.xprs.xnlp. This means that all of the routinespresented in this section operate in the context of the current Mosel problem.

18.2 mmxnlp and the other Mosel modules
mmxnlp is designed to provide seamless integration with other Mosel functionalities. However, thefundamentally different nature of nonlinear problems makes some compromises necessary; these arelisted in this section.

Fair Isaac Corporation Conﬁdential and Proprietary Information

646

mmxnlp

18.2.1

Overloaded functions
The following functionality is modiﬁed or extended by the mmxnlp module:
Retrieval of solution values with getsol, both for variables and nonlinear constraints. A detailed
description of the behaviour of this function can be found in the documentation for the mmxprs
and mmnl modules.
Functions implemented in the mmnl module are extended for nonlinear solvers:– setinitval, clearinitvals and copysoltoinit to manage initial values.
– Mathematical functions: abs, exp, ln, log, sqrt, cos, sin, tan, arccos, arcsin, arctan.
– Mosel constraint and constraint visibility functions: gettype, settype, ishidden andsethidden.

Functions implemented in the mmxprs module are extended for nonlinear solvers:– maximize and minimize to solve the problem.
– getprobstat to return the problem solution status.
– fixglobal for managing integer problems.
– Exporting the current status (for debugging purposes) with loadprob, writeprob andsavestate.

18.2.2Module compatibility
The mmquad module is incompatible with the mmxnlp module, and should not be used together with it.
The mmxprs and mmnl modules are automatically loaded when using the mmxnlp module.
The mmnl module deﬁnes several discontinuous functions for use with decision variables (mpvar),which are not supported by the mmxnlp module. These constructions should instead be modelled withinteger constraints. The functions are: round, ceil, floor, idiv and mod.
The following standard functionalities are not available for nonlinear problems:









18.3

Functions for working with a basis: loadbasis, readbasis and savebasis.
Logical constraints of the form logctr, and their operators: implies, indicator, or, xor andand.
Functions for working with multiple MIP solutions, the solution pool and the solution enumerator:
selectsol, XPRS_enumduplpol, XPRS_enummaxsol and XPRS_enumsols.
Functions for cut management, including model cuts and delayed rows: addcut, addcuts,
loadcuts, storecut, storecuts, delcuts, dropcuts, getcnlist and getcplist.
Functions for determining irreducible infeasible sets, and for repairing infeasibility: getiis,
getiissense, getiistype, isiisvalid, resetiis and repairinfeas and getinfeas.

Control parameters
When using mmxnlp, getparam and setparam are extended to additionally provide access to all thecontrol and problem parameters of the Xpress NonLinear SLP solver. The module also provides thefollowing controls of its own:

Fair Isaac Corporation Conﬁdential and Proprietary Information

647

mmxnlp

XNLP_AUTOELIM

When set to true, Mosel uses the model’s semantics to break downnonlinear formulas and feed the information to the solver for nonlinear
eliminations and to detect network structures in the model.
p. 648XNLP_LOADASNLWhen set to true, quadratic expressions will be treated as being of general
nonlinear type. If they are known to be non-convex, the overhead ofattempting to treat the expression as convex initially is avoided.
p. 648XNLP_LOADNAMES

When set to true, names from the Mosel ﬁle will be passed to theunderlying solver to improve the readability of messages it generates. Thisis an alias for XPRS_LOADNAMES.
p. 649XNLP_NLPSTATUS

The solution status of the problem. For a detailed description of this value,please see the documentation for the XSLP_NLPSTATUS attribute in the
Xpress NonLinear Reference Manual.
p. 649XNLP_SOLVER

Solver selection when available.

XNLP_VERBOSE

When set to true, informative messages from any underlying nonlinear
solver will be displayed. This is an alias for XPRS_VERBOSE.
p. 650p. 649XNLP_AUTOELIM
Description

When set to true, Mosel uses the model’s semantics to break down nonlinear formulas andfeed the information to the solver for nonlinear eliminations and to detect network structuresin the model.

Type

Integer, read/write

Values0
1

Default value

1

ModulemmxnlpDisableEnableXNLP_LOADASNL
Description

When set to true, quadratic expressions will be treated as being of general nonlinear type. Ifthey are known to be non-convex, the overhead of attempting to treat the expression as
convex initially is avoided.

Type

Integer, read/write

Values0
1

Default value

0

ModulemmxnlpAssume that quadratic expressions are convex
Assume that quadratic expressions are non-convex

Fair Isaac Corporation Conﬁdential and Proprietary Information

648

mmxnlp

XNLP_LOADNAMES
Description

When set to true, names from the Mosel ﬁle will be passed to the underlying solver to improve
the readability of messages it generates. This is an alias for XPRS_LOADNAMES.

Type

Integer, read/write

Values0
1

Default value

0

ModulemmxnlpNames are not loaded into the solver
Names are loaded into the solver

XNLP_NLPSTATUS
Description

The solution status of the problem. For a detailed description of this value, please see thedocumentation for the XSLP_NLPSTATUS attribute in the Xpress NonLinear Reference Manual.

Type

Integer, read only

Values

0
1
2
3
4
5
6

Default value

0

ModulemmxnlpOptimization unstarted
Locally optimal
OptimalLocally infeasible
Infeasible
Unbounded
Unﬁnished

XNLP_SOLVER
Description

Solver selection when available.

Type

Integer, read/write

Values-1
01

Default value-1

Modulemmxnlp

Determine automatically, based on problem characteristics and availability of solvers
Xpress NonLinear (SLP)
KnitroFair Isaac Corporation Conﬁdential and Proprietary Information

649

mmxnlp

XNLP_VERBOSE
Description

When set to true, informative messages from any underlying nonlinear solver will be
displayed. This is an alias for XPRS_VERBOSE.

Type

Integer, read/write

Values0
1

Default value

0

Modulemmxnlp18.4

No solver logging
Solver log is displayed

Procedures and functions
This section lists in alphabetical order the functions and procedures that are provided by the mmxnlp
module.
addmultistart

Loads a single or a set of multistart job(s) into the multistart job pool.
p. 652chgdeltatype

Changes the type of a delta variable associated to an mpvar.

p. 653F

Include a user function in a nonlinear constraint.

p. 654

generateUFparallel

Generates a parallel version of a Mosel user function that is implemented
as a Mosel package.
p. 656

printmodelmemory

Print a summary of the current memory usage of the nonlinear module.
p. 657

printmodelscaling

Print a summary of the scaling of the model, as loaded into the solver.
p. 658setcallback

Set nonlinear callback functions and procedures.

p. 659setcomplementary

Set two variables as being complementary.

p. 660setdefvar

Set a variable to be purely deﬁned by a constriant.

p. 662setdelayedctr

Mark a constraint as delayed.

p. 661setdetrow

Set the determining row for a variable.

p. 663setenforcedctr

Mark a nonlinear constraint as enforced.

p. 664setinitsb

Provide the initial step bound for a variable.

p. 665settolDeﬁne a particular tolerance in a tolerance set.

p. 666settolset

Assigns a tolerance set to a variable, or list of variables.

p. 667userfuncDLL

Create a user function implemented as a dynamic linked library.

p. 668userfuncExcel

Create a user function from a Microsoft Excel spreadsheet.

p. 669userfuncExcelMacro

Create a user function from a Microsoft Excel macro.

p. 670Fair Isaac Corporation Conﬁdential and Proprietary Information

650mmxnlp

userfuncinfo

Print the inferred prototype of the given user function.

p. 671

userfuncMosel

Create a user function from a Mosel function.

p. 672

validate

Print a summary of the feasibility of the current solution.

p. 673

Fair Isaac Corporation Conﬁdential and Proprietary Information

651

mmxnlpaddmultistartPurpose
Synopsis

Loads a single or a set of multistart job(s) into the multistart job pool.
addmultistart(descr:string)
addmultistart(descr:string, controls:array(set of string) of real)addmultistart(descr:string, initvalues:array(set of mpvar) of real)addmultistart(descr:string, initvalues:array(set of mpvar) of real,controls: array(set of string) of real)addmultistart(descr:string, controls:array(set of string) of real,
initvalues:array(set of mpvar) of real)addmultistart(descr:string, preset:integer)
addmultistart(descr:string, preset:integer, cnt:integer)
addmultistart(descr:string, preset:integer, initvalues:array(set of mpvar)of real, controls:array(set of string) of real)addmultistart(descr:string, preset:integer, cnt:integer,
initvalues:array(set of mpvar) of real, controls:array(set of string)of real)Arguments
descr
controls
initvalues
presetcnt

Text description of the job. Used in reporting and in callbacks.
An array containing the controls to be set for the loaded multistart job.
An array containing initial values to be set for the loaded multistart job.
The multistart preset of jobs to be loaded. Please see the Xpress NonLinear Reference
Manual for the list of possible presets.
The upper bound on the number of jobs to be created, in case a preset is used.

Further information
Adds a job or a preset to the multistart job pool. Multistart jobs are automatically executed on the next
minimize/maximize command, unless the XSLP_MULTISTART control is set to 0. Please refer to theXpress NonLinear Reference Manual for a detailed description of multistart.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

652

mmxnlp

chgdeltatype
Purpose
Synopsis

Changes the type of a delta variable associated to an mpvar.
procedure chgdeltatype(col:mpvar, type:integer, value:real)

Arguments
col
The column for which the delta is to be changed.
type The new type of the delta.
value Value associated to the new delta type.
Further information
Please refer to the Xpress NonLinear Reference Manual for more details about delta types.
Related topics
setinitval, setinitsb, setdetrow, setenforcedctr.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

653

mmxnlp

F
Purpose
Synopsis

Include a user function in a nonlinear constraint.
function F(UF:userfunc, arg:linctr):nlctr
function F(UF:userfunc, arg:nlctr):nlctr
function F(UF:userfunc, arg:list of nlctr):nlctr
function F(UF:userfunc, arg:array(any sets) of nlctr):nlctr
function F(UF:userfunc, arg:list of nlctr, returnarg:integer):nlctr
function F(UF:userfunc, arg:array(any sets) of nlctr,
returnarg:integer):nlctr

ArgumentsUF
arg
returnarg

A user function of type userfunc
Argument to be passed to the user function
Return argument to be substituted into the formula for multivalued user functions

Return value
A nonlinear expression which may form part of any nlctr.
ExampleThe following example shows how to implement a negative cosine function.
model "SimpleUF"
uses "mmxnlp"
declarations
obj: nlctr
x: mpvar
MinusSine: userfunc
end-declarations! Creation and assignment of the user function
MinusSine := userfuncMosel("MinusSineImplementation")! which can then be embedded into any nonlinear expression
obj := F(MinusSine,x)
minimize(obj)public function MinusSineImplementation (x:real): real
returned := -sin(x)end-function
end-model

Further information
User functions allow extremely complex, recursive or non-algebraic expressions to be included in
nonlinear formulae. As such they may make use of simulators or other black box evaluators. The actual
parameters to a user function depend upon the way it is bound to the model by the F function. Please
see the chapter on user functions for more details. Each user function instance deﬁned by the meansof the F function must share the same argument syntax structure, however the actual formula content
may differ: e.g. if a function takes an array of nonlinear expressions as input arguments, each instanceof the function corresponding to the same deﬁnition based on the same F instance must have the sameunderlying array structure, although the expressions stored in them may differ. If a separate F instanceis used using the same function implementation, this rule does not apply. Also note, that for Mosel tobe able to correctly cross reference the sets used in the deﬁnition of an array, the sets must be named.

Fair Isaac Corporation Conﬁdential and Proprietary Information

654

mmxnlp

Related topics
userfuncDLL, userfuncMosel, userfuncExcel, userfuncExcelMacro.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

655

mmxnlp

generateUFparallel
Purpose
Synopsis

Generates a parallel version of a Mosel user function that is implemented as a Mosel package.
procedure generateUFparallel(bimname:string, fctname:string)Arguments
bimname Path to the compiled Mosel package implementing the user function.
fctname The public user function inside the package.
Further information
Please refer to the Xpress NonLinear Reference Manual for more details about this functionality.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

656

mmxnlp

printmodelmemory
Purpose
Synopsis

Print a summary of the current memory usage of the nonlinear module.
procedure printmodelmemory

Further information
This procedure has no effect unless XNLP_VERBOSE is set. It is provided solely for the purpose ofmodel analysis and debugging.
Related topics
validate, printmodelscaling, userfuncinfo.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

657

mmxnlp

printmodelscaling
Purpose
Synopsis

Print a summary of the scaling of the model, as loaded into the solver.
procedure printmodelscaling

Further information
This procedure has no effect unless XNLP_VERBOSE is set. It is provided solely for the purpose ofmodel analysis and debugging.
Related topics
validate, printmodelmemory, userfuncinfo.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

658

mmxnlp

setcallback
Purpose
Synopsis

Set nonlinear callback functions and procedures.
procedure setcallback(cbtype:integer, cb:string)Arguments
cbtypecb

ModuleType of the callback:
XSLP_CB_ITERSTARTSLP iteration start callback
XSLP_CB_ITERENDSLP iteration end callback
XSLP_CB_ITERVAR
Nonlinear variable convergence check callback
XSLP_CB_CASCADESTART Cascading start callback
XSLP_CB_CASCADEVAR
Variable cascaded callback
XSLP_CB_CASCADEEND
Cascading end callback
XSLP_CB_STARTSLP solve start callback
XSLP_CB_END
SLP solve end callback
XSLP_CB_PRENODE
MISLP node setup callback
XSLP_CB_INTSOLNew integer solution found callback
XSLP_CB_OPTNODEMISLP node solved and (SLP) optimal callback
XSLP_CB_CONSTRUCT
Construct start callback
XSLP_CB_MSJOBSTARTA new multistart job is about to be solved callback
XSLP_CB_MSJOBEND
A multistart job has been solved callback
XSLP_CB_MSWINNER
Winner multistart job callback
Name of the callback function/procedure; the parameters and the type of the return value (ifany) vary depending on the type of the callback:function cb:integerXSLP_CB_ITERSTART
function cb:integerXSLP_CB_ITEREND
function cb(var:mpvar) : integerXSLP_CB_ITERVAR
function cb:integerXSLP_CB_CASCADESTART
function cb(var:mpvar):integerXSLP_CB_CASCADEVAR
function cb:integerXSLP_CB_CASCADEEND
function cb:integerXSLP_CB_START
function cb:integerXSLP_CB_END
function cb:integerXSLP_CB_PRENODE
function cb:integerXSLP_CB_INTSOL
function cb:integerXSLP_CB_OPTNODE
function cb:integerXSLP_CB_CONSTRUCT
function cb(description:string):integer XSLP_CB_MSJOBSTART
function cb(description:string):integer XSLP_CB_MSJOBEND
function cb(description:string):integer XSLP_CB_MSWINNER

mmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

659

mmxnlp

setcomplementary
Purpose
Synopsis

Set two variables as being complementary.
procedure setcomplementary(var1:mpvar, var2:mpvar)

Arguments
var1
var2

The ﬁrst variable of the variable pair to be set as complementing
The ﬁrst variable of the variable pair to be set as complementing

Further information
A complementing variable pair implements the constraint that is equivalent with the product of thevariables being zero. However, the solvers may be able to treat such constraints in a special, more
efﬁcient ways, which may make a difference if the complementarity constraints are the problematicpart of the model. Note that Knitro only allows non-overlapping complementary variables, and in thepresence of overlaps Xpress will default to use SLP. Complementary variables must have a lower boundof zero.
Related topics
setinitval, setinitsb, setdetrow, setenforcedctr.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

660

mmxnlp

setdelayedctr
Purpose
Synopsis

Mark a constraint as delayed.
procedure setdelayedctr(row:nlctr, delay:integer)

Argumentsrow
The constraint to be delayed
delay Integer value deﬁning the number of iterations in which the constraint should be ignored
Further information
A delayed constraint will be introduced after some number of solver iterations have occurred. This may
be useful for constraints that could aid the convergence of a solver, but which are not expected to bebinding at an optimal solution and which could make early iterations more expensive.
Related topics
setinitval, setinitsb, setdetrow, setenforcedctr.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

661

mmxnlp

setdefvar
Purpose
Synopsis

Set a variable to be purely deﬁned by a constriant.
procedure setdefvar(var:mpvar, row:linctr)
procedure setdefvar(var:mpvar, row:nlctr)

Argumentsvarrow

The variable being made deﬁned by the constraint.
The constraint that deﬁnes the value of the variable.

Further information
The variable will be made free (its bounds removed) since it’s value is now deﬁned by the contraint’svalue. Ideally, the variable should appear linearly in the constriant, in which case unless a circularreference is detected it will used for eliminate on in the nonlinear presolver. The purpose of theconstruct is to break large nonliner expressions.
Related topics
setdetrow
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

662

mmxnlp

setdetrow
Purpose
Synopsis

Set the determining row for a variable.
procedure setdetrow(var:mpvar, row:linctr)
procedure setdetrow(var:mpvar, row:nlctr)
procedure setdetrow(row:linctr, var:mpvar)
procedure setdetrow(row:nlctr, var:mpvar)

Argumentsvarrow

The variable for which the determining row is provided
The row that determines the value of the variable.

Further information
A row which is determining for a variable deﬁnes the value of that variable. This means that the variable
is a derived value which is calculated in another part of the model. Some solvers will use suchdesignations to reﬁne their search, and in particular in sequential linear programming, a process calledcascading makes use of determining rows. Please refer to the Xpress NonLinear Reference Manual(chapter ’Cascading’) for more information.
Related topics
setinitval, setinitsb, setenforcedctr, setdelayedctr.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

663

mmxnlp

setenforcedctr
Purpose
Synopsis

Mark a nonlinear constraint as enforced.
procedure setenforcedctr(row:nlctr)

Argumentrow

The constraint to be set enforced

Further information
A constraint which is marked as enforced will not have penalty error vectors introduced upon it bysolvers which use such techniques. This may be useful for constraints which are hard to satisfy.
Related topics
setinitval, setinitsb, setdetrow, setdelayedctr.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

664

mmxnlp

setinitsb
Purpose
Synopsis

Provide the initial step bound for a variable.
procedure setinitsb(var:mpvar, value:real)

Argumentsvar
The variable for which the step bound is provided
value Value to be used as initial value
Further information
The initial step bounds deﬁne in turn the size of the initial trust region. Please refer to the Xpress
NonLinear Reference Manual for more information.
Related topics
setinitval, setdetrow, setenforcedctr, setdelayedctr.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

665

mmxnlp

settolPurpose
SynopsisDeﬁne a particular tolerance in a tolerance set.
procedure settol(tset:tolset, which:integer, value:real)

Arguments
tset The tolerance set to be modiﬁed
which The tolerance which is being deﬁned
value The new value of the tolerance
Further information
The tolerances which may be deﬁned by this method are:XNLP_TOL_TC

The absolute closure tolerance

XNLP_TOL_TA

The absolute delta tolerance

XNLP_TOL_RA

The relative delta tolerance

XNLP_TOL_TM

The absolute matrix tolerance

XNLP_TOL_RM

The relative matrix tolerance

XNLP_TOL_TI

The absolute impact tolerance

XNLP_TOL_RI

The relative impact tolerance

XNLP_TOL_TS

The relative slack impact tolerance

XNLP_TOL_RS

The absolute slack impact tolerance

Please refer to the Xpress NonLinear Reference Manual, and particularly the chapter ’Convergencecriteria’, for more information on these tolerances.
Related topics
setinitval, setinitsb, setdetrow, setenforcedctr.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

666

mmxnlp

settolset
Purpose
Synopsis

Assigns a tolerance set to a variable, or list of variables.
procedure settolset(var:mpvar, tset:tolset)
procedure settolset(vars:list of mpvar, tset:tolset)

Arguments
var
vars
tset

Variable to which the tolerance set is to be assigned
List pf variable to which the tolerance set is to be assigned
The tolerance set to be assigned to the variable(s)Related topics
settol.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

667

mmxnlp

userfuncDLL
Purpose
SynopsisCreate a user function implemented as a dynamic linked library.
function userfuncDLL(libfile:string, fctname:string):userfunc

Arguments
libfile Name of the dynamically linked library containing the implementation of the user function
fctname Name of the function inside the dynamic library
Return value
A userfunc object that can be used in the F functions to be embedded in formulas.
Further information
User functions allow extremely complex, recursive or non-algebraic expressions to be included in
nonlinear formulae. As such they may make use of simulators or other black box evaluators. The actual
parameters to a user function depend upon the way it is bound to the model by the F function. Please
see the chapter ’User functions’ of the Xpress NonLinear Reference Manual for more details.
Dynamically linked libraries are supported on all platforms, and are usually the most computationally
efﬁcient way to implement user functions in mmxnlp.
Related topics
F, userfuncMosel, userfuncExcel, userfuncExcelMacro.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

668

mmxnlp

userfuncExcel
Purpose
SynopsisCreate a user function from a Microsoft Excel spreadsheet.
function userfuncExcel(filename:string, sheetname:string):userfunc
function userfuncExcel(filename:string, sheetname:string,macro:string):userfunc

Arguments
filenamesheetnamemacro

Name of the Excel ﬁle including the function implementation
Name of the worksheet in the workbook used for input and output
Name of the Visual Basic macro to be called to recalculate the spreadsheet. Optional, if
not provided recalculation is done by the standard recalculation request

Return value
A userfunc object that can be used in the F functions to be embedded in formulas.
Further information
User functions allow extremely complex, recursive or non-algebraic expressions to be included in
nonlinear formulae. As such they may make use of simulators or other black box evaluators. The actual
parameters to a user function depend upon the way it is bound to the model by the F function. Please
see the chapter on user functions for more details. Communication with Excel carries signiﬁcant
overhead and performance degradation may result from using functions of this type.
Related topics
F, userfuncMosel, userfuncExcelMacro, userfuncDLL.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

669

mmxnlp

userfuncExcelMacro
Purpose
SynopsisCreate a user function from a Microsoft Excel macro.
function userfuncExcelMacro(filename:string, sheetname:string,macro:string):userfunc

Arguments
filenamesheetnamemacro

Name of the Excel ﬁle including the function implementation
Name of the worksheet in the workbook including the Visual Basic macro
Name of the Visual Basic macro implementing the user function

Return value
A userfunc object that can be used in the F functions to be embedded in formulas.
Further information
User functions allow extremely complex, recursive or non-algebraic expressions to be included in
nonlinear formulae. As such they may make use of simulators or other black box evaluators. The actual
parameters to a user function depend upon the way it is bound to the model by the F function. Please
see the chapter on user functions for more details. Communication with Excel carries signiﬁcant
overhead and performance degradation may result from using functions of this type.
Related topics
F, userfuncMosel, userfuncExcel, userfuncDLL.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

670

mmxnlp

userfuncinfo
Purpose
Synopsis

Print the inferred prototype of the given user function.
procedure userfuncinfo(UF:userfunc)

ArgumentUF

The user function to be analyzed

Further information
The type and signature of a user function are inferred from its use in calls to the F function in thecurrent model. This procedure has no effect unless XNLP_VERBOSE is set. It is provided solely for the
purpose of model analysis and debugging.
Related topics
validate, printmodelmemory, printmodelscaling.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

671

mmxnlp

userfuncMosel
Purpose
SynopsisCreate a user function from a Mosel function.
function userfuncMosel(fctname:string):userfunc
function userfuncMosel(fctname:string, options:integer):userfunc

Arguments
fctname Name of the Mosel function to wrap
options Options describing special properties of the user function
Return value
A userfunc object that can be used in the F functions to be embedded in formulas.
Further information
User functions allow extremely complex, recursive or non-algebraic expressions to be included in
nonlinear formulae. As such they may make use of simulators or other black box evaluators. The actual
parameters to a user function depend upon the way it is bound to the model by the F function. Please
see the chapter on user functions for more details.
There is support for user functions providing their own derivatives. Currently, user functions taking anarray of nlctr and returning a single function values may provide their own derivatives. To mark afunction as returning it’s own derivatives, use option XNLP_DERIVATIVES or XNLP_DELTAS to
indicate that the solver should suggest perturbation values for the variables.
Related topics
F, userfuncExcel, userfuncExcelMacro, userfuncDLL.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

672

mmxnlp

validate
Purpose
Synopsis

Print a summary of the feasibility of the current solution.
procedure validate

Further information
This procedure has no effect unless XNLP_VERBOSE is set. It is provided solely for the purpose ofmodel analysis and debugging.
Related topics
printmodelmemory, printmodelscaling, userfuncinfo.
ModulemmxnlpFair Isaac Corporation Conﬁdential and Proprietary Information

673

mmxnlp

18.5

Error codes issued by mmxnlp
1

Out of memory
The system has run out of memory.

2

No purchase authorization foundNo license found3

Failed to initialize XSLPCannot initialize the XPRS library. There may be a licensing problem

4

Unsupported XSLP version
The version of the ’XSLP’ library is incompatible with the current module. The Xpress installation
may be corrupt

5

Failed to create the XSLP problem object
Cannot create the XSLP optimizer problem. There may be a licensing problem

6

Unexpected mmxnlp user function signature
The provided user functions’ signature does not match any expected format.

7

Unexpected external token in mmxnlp
An unexpected external token found by the ’mmxnlp’ module. Please contact support.

8

Unsupported operator
The provided operator is not supported by ’mmxnlp’.

9

Failed to load problem
Could not load the problem into the optimizer.

10

Variable bound conﬂict in problem
Inconsistent bounds provided for the variable.

11

Failed to load user function
The user function could not be loaded into the optimizer.

12Error evaluating user function
Error while evaluation the user function. The user function likely to have returned an error code.

13

Unknown tolerance set
The provided tolerance set is invalid.

14

List tpype error in user function
The list provided to the user function is not valid for the function.

15

Failed to create save ﬁleThe saveﬁle could not be created.

16

Error in optimization
An error has occured during optimization.

17

Cannot reoptimize using a different objective (use named linctr or nlctr)
The objective has unexpectedly changed

Fair Isaac Corporation Conﬁdential and Proprietary Information

674

mmxnlp

18

Internal error in mmxnlp. Please contact FICO support
An internal error has occurred. Please contact support.

20

Incompatible array deﬁnitions for user function arguments
The user function received incompatible arrays.

21

Non-Mosel user functions only take ’list of nlctr’ type arguments
User functions that are not implemented as a Mosel function can only take list of ’nlctr’arguments (no arrays).

22

Invalid argument list for external function
The provided argument list is not valid for the external function.

23

Provided user function is not returning a single real
The provided user function was expected to return a single real value.

24

Provided user function is not returning an array indexed by integers
The provided user function was expected to return an array of reals indexed by integers.

25

User function must be loaded before it’s properties can be retrieved
The user function must be loaded before it’s properties are interrogated. Please use ’loadprob’ toload the model including the user function.

26

Unexpected variable found. Please reload problem ﬁrst using ’loadprob’
An unexpected variable has been used. Please reload the problem to load the variable.

27

Operation only supported on the main problem (e.g. not inside multi-start callbacks)This operation is only supported in the main problem. It cannot be used on worker problems.

28

Math error while evaluating expression
A mathematical error has occurred while evaluating the expression.

Fair Isaac Corporation Conﬁdential and Proprietary Information

675

CHAPTER 19

mmxprsThe mmxprs module provides access to FICO R Xpress Optimizer from within a Mosel model and assuch it requires the Xpress Optimizer library (XPRS) to be installed on the system. To use this module,
the following line must be included in the header of the Mosel model ﬁle:uses 'mmxprs'

A large number of optimization-related routines are provided, ranging from those for ﬁnding a solution
to the problem, to those for setting callbacks and cut manager functions. Whilst a description of theirusage is provided in this manual, further details relating to the usage of these may be found by
consulting the Xpress Optimizer Reference Manual.

19.1

New functionality for the Mosel language

19.1.1The problem type mpproblem.xprs
This module exposes its functionality through an extension to the mpproblem problem type. As aconsequence, all routines presented here are executed in the context of the current problem. In
particular, the setting of a control parameter is applied only to the current problem and each problem
has its own set of settings and solution information. However, when a new problem instance is created,the value of the control parameters XPRS_colorder, XPRS_enummaxsol, XPRS_enumduplpol,
XPRS_loadnames and XPRS_verbose are initialised with the settings of the main problem.

19.1.2The type basis
The module mmxprs deﬁnes the type basis to represent solution basis in the Mosel Language. Thisnew type is used to store a basis computed by the optimizer during its solution process (savebasis).
A basis can then be loaded again into the optimiser with loadbasis, inspected (by getting the basis
status of each variable/constraint it includes with getbstat) or modiﬁed (by changing this basis
status using setbstat). The type basis supports assignment and test of equality. This comparison
only checks whether two basis contain the same information, it does not indicate whether the basis areequivalent.

19.1.3

The type mpsol
The type mpsol characterises a solution of an MP problem by associating a value to each decisionvariable (type mpvar) of the problem. Initialising such an object can be achieved by saving the current
solution found by the optimiser (savesol or savemipsol) or by building it one variable at a time(setsol). Various routines requiring solution information support the solution object. For instancegetsol may be used to evaluate an expression on a speciﬁc solution; loadmipsol and addmipsol
accept this object as input. A solution might be saved into a ﬁle using writesol and the resulting ﬁleFair Isaac Corporation Conﬁdential and Proprietary Information

676

mmxprs

can be loaded into the optimiser with readsol. The type mpsol supports assignment and test ofequality.

19.1.4

The type logctr
The type logctr represents either a logical expression over linear constraints or an indicator constraint(see indicator). Logical expressions can be built using standard operators (and, or, not) or with thehelp of the dedicated functions implies and xor. These logical constructs are handled like linear
constraints: they are associated to the current problem, can be (re)deﬁned via assignments and hidden
using sethidden. Note however that logical constructs are not shown by exportprob although the
mmxprs routine writeprob will report them.
If logical expressions are employed in a model, the loading of the problem into the optimizer requires
the use of the helper package "advmod":uses 'advmod'

This package is not necessary when a model uses only indicator constraints directly.

19.2

Control parameters
This module extends the getparam function and the setparam procedure in order to access all thecontrol and problem parameters of Optimizer (for example the problem attribute LPSTATUS is mapped
to the mmxprs control parameter XPRS_lpstatus). In addition to these, the following control
parameters are also deﬁned:
XPRS_colorder

Reorder matrix columns before loading the problem.

p. 677

XPRS_enumduplpol

Handling of duplicate solutions during an enumeration.

p. 678

XPRS_enummaxsol

Maximum number of solutions to be saved during an enumeration. p. 678

XPRS_enumsols

Number of solutions found during the last enumeration.

p. 678

XPRS_fullversion

Optimizer version number.

p. 679

XPRS_loadnames

Enable/disable loading of MPS names into the Optimizer.

p. 679

XPRS_problem

Optimizer problem pointers.

p. 679

XPRS_probname

Read/set the problem name used by the Optimizer.

p. 679

XPRS_verbose

Enable/disable message printing by the Optimizer.

p. 680

Example:setparam("XPRS_verbose", true)! Turn on message printing
pstat:= getparam("XPRS_lpstatus")! Get the problem LP optimization statuswriteln("Best bound=", getparam("XPRS_bestbound")) ! Display the best bound value

XPRS_colorder
Description

Reorder matrix columns before loading the problem.

Fair Isaac Corporation Conﬁdential and Proprietary Information

677

mmxprs

Type

Integer, read/write

Values0
1,3
2
4Default value

0

Modulemmxprs

Mosel implicit ordering
Reorder using a numeric criterion
Alphabetical order of the variable names (this requires the names to be available)
Random ordering

XPRS_enumsols
Description

Number of solutions found during the last enumeration. The value of this parameter is -1 isno enumeration has been run.

Type

Integer, read only

Affects routines

maximize, minimize.

Modulemmxprs

XPRS_enummaxsol
Description

Maximum number of solutions to be saved during an enumeration.

Type

Integer, read/write

Default value

10

Affects routines

maximize, minimize.

Modulemmxprs

XPRS_enumduplpol
Description

Handling of duplicate solutions during an enumeration. Refer to the MSP control parameter
MSP_DUPLICATESOLUTIONSPOLICY for further information.

Type

Integer, read/write

Values0
1
2
3

Default value

3

Affects routines

maximize, minimize.

ModulemmxprsAll solutions kept
Continuous
Discrete and continuous separate
Discrete only

Fair Isaac Corporation Conﬁdential and Proprietary Information

678

mmxprs

XPRS_fullversion
Description

The full Optimizer version number in the form major.minor.build (e.g."20.01.03").

Type

String, read only

Modulemmxprs

XPRS_loadnames
Description

Enable/disable loading of MPS names into the Optimizer.

Type

Boolean, read/write

Valuestrue Enable loading of names
false Disable loading of names

Default value

false

Affects routines

loadprob, maximize, minimize.

Modulemmxprs

XPRS_problem
Description

The Optimizer problem (XPRSprob), MIP solution pool (XPRSmipsolpool) and MIP solution
enumerator (XPRSmipsolenum) pointers separated by spaces. This attribute is only requiredin applications using both Mosel and the Optimizer at the C level.

Type

String, read only

Modulemmxprs

XPRS_probname
Description

Read/set the problem name used by the Optimizer to build its working ﬁles (this name may
contain a full path). If set to the empty string (default value), a unique name with a path to thetemporary directory of the operating system is generated.

Type

String, read/write

ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

679

mmxprs

XPRS_verbose
Description

Enable/disable message printing by the Optimizer.

Type

Boolean, read/write

Valuestrue Enable message printing
false Disable message printing

Default value

false

Modulemmxprs19.3

Procedures and functions
This section lists in alphabetical order the functions and procedures that are provided by the mmxprs
module.
addmipsol

Add a MIP solution to the optimizer.

p. 683basisstability

Get basis stability information.

p. 684

calcsolinfo

Calculates a property of an mpsol solution.

p. 685clearmipdir

Delete all deﬁned MIP directives.

p. 686clearmodcut

Delete all deﬁned model cuts.

p. 687command

Execute an Optimizer command.

p. 688copysoltoinit

Copy solution values to initial values of an NL problem.

p. 689crossoverlpsol

Crosses over a previously loaded LP solution to a basic solution.

p. 690defdelayedrows

Deﬁne the set of constraints to be treated as delayed rows.

p. 691

defsecurevecs

Deﬁne the variables and constraints to be preserved.

p. 692estimatemarginals

Estimate better marginal values for variables and constraints fordegenerate problems.

p. 693

fixglobal

Fix values of global entitites.

p. 694getbstatGet the status of a variable or constraint in a basis.

p. 695

getdualray

Get a dual ray for an infeasible problem.

p. 696

getiisCompute then get the Irreductible Infeasible Sets (IIS).

p. 697

getiissense

Decode the sense part of an IIS bound type information.

p. 698getiistype

Decode the type part of an IIS bound type information.

p. 699getinfcause

Returns the variable or constraint causing infeasibility.

p. 700getinfeas

Returns sets of infeasible primal and dual variables.

p. 701getlb

Get the lower bound of a variable.

p. 702

Fair Isaac Corporation Conﬁdential and Proprietary Information

680

mmxprs

getloadedlinctrs

Get the linear constraints loaded into the optimiser.

p. 703getloadedmpvars

Get the decision variables loaded into the optimiser.

p. 704getnameGet the name of a decision variable or constraint.

p. 705getprimalray

Get a primal ray for an unbounded problem.

p. 706

getprobstat

Get the Optimizer problem status.

p. 707

getrange

Get a range value for a variable or constraint.

p. 708getsensrng

Get sensitivity ranges for objective or RHS function coefﬁcients.

p. 709getsizeGet the size of a solution.

p. 710

getsolGet the solution value of an expression from a solution object.

p. 711getub

Get the upper bound of a variable.

p. 712getvars

Get the set of variables of a solution.

p. 713hasfeature

Check if a speciﬁc feature is supported by the currently used license. p. 714

impliesCreate an implies expression.

p. 715indicator

Create an indicator constraint.

p. 716

isiisvalid

Check whether an IIS number exists.

p. 717

isintegral

Check whether a solution value is integral.

p. 718loadbasis

Load a previously saved basis.

p. 719loadlpsol

Load an LP solution into the optimizer.

p. 720loadmipsol

Load a MIP solution into the optimizer.

p. 721loadprob

Load a problem into the optimizer.

p. 723maximize, minimize

Maximize/minimize the current problem.

p. 724postsolve

Postsolve the current matrix.

p. 726

readbasis

Read a basis from a ﬁle.

p. 727

readdirs

Read directives from a ﬁle.

p. 728readsol

Read a solution from a ﬁle.

p. 729refinemipsol

Executes the MIP solution reﬁner on an mpsol solution.

p. 730rejectintsol

Reject a PREINTSOL solution.

p. 731

repairinfeas

Relaxing bounds to repair infeasibility.

p. 732

resetbasis

Reset a basis.

p. 734

resetiis

Reset the search for IIS.

p. 735

resetsol

Reset a solution.

p. 736

savebasis

Save the current basis.

p. 737

savemipsol

Save the current solution into the provided array or solution object.

p. 738savesol

Save the current solution into a solution object.

p. 739Fair Isaac Corporation Conﬁdential and Proprietary Information

681

mmxprs

savestate

Save current state of the Optimizer to a ﬁle.

p. 740selectsol

Select one of the solutions found by solution enumerator.

p. 741

setarchconsistency

Sets the optimizer architecture control.

p. 742

setbstat

Set the status of a variable or constraint in a basis.

p. 743

setcallback

Set optimizer callback functions and procedures.

p. 744setcbcutoff

Set cutoff for PREINTSOL callback.

p. 747

setgndata

Update data for GAPNOTIFY callback.

p. 748setlb

Set the lower bound of a variable.

p. 749setmipdir

Set a directive on a variable or Special Ordered Set.

p. 750

setmodcut

Mark a constraint as a model cut.

p. 751

setsolDeﬁne the value associated to a decision variabe in a solution object. p. 752

setub

Set the upper bound of a variable.

p. 753setucbdata

Update data for CHGBRANCH callback.

p. 754stopoptimize

Interrupt the optimizer algorithms.

p. 755

unloadprob

Unload the problem held in the optimizer.

p. 756uselastbarsol

Sets up the last barrier solve’s solution as the current one if one is available
p. 757

writebasis

Write the current basis to a ﬁle.

p. 758

writedirs

Write current directives to a ﬁle.

p. 759writeprob

Write the current problem to a ﬁle.

p. 760

writesolWrite a solution to a ﬁle.

p. 761xor

Create an exclusive or expression.

p. 762

Fair Isaac Corporation Conﬁdential and Proprietary Information

682

mmxprs

addmipsol
Purpose
Synopsis

Add a MIP solution to the optimizer.
procedure addmipsol(solid:string,s:array(set of mpvar) of real)procedure addmipsol(solid:string,ms:mpsol)Arguments
solid Identiﬁer to be assigned to the solutions
An array containing the solutionms
A solution object
Further information
1. This function is used to provide the expectations of the modeler on the values of selected variables inpossible MIP solutions. It is different to loadmipsol in that it is not necessary to provide full, feasible
MIP solutions. The values provided will be used by the Optimizer to attempt to generate full MIP
solutions. The addmipsol function can therefore be used to trial the feasibility of certain variablevalue assignments without the need to ﬁx them in the problem formulation itself.
2. The solution value array s is created by assigning values to discrete variables in the problem, such ass(x):= 1 (where x is a decision variable of type mpvar). It is also possible to use a solution that has
previously been saved using the procedure savemipsol.
3. If the provided solution is found to be infeasible, a limited local search heuristic will be run in an
attempt to ﬁnd a close feasible integer solution.
4. The current problem deﬁnition must be loaded into the Optimizer for addmipsol to have any effect. If
this has not recently been done, e.g., by calling maximize or minimize, the problem must be explicitly
loaded using loadprob.
5. The function returns immediately after passing the solution to the Optimizer. The solution is placed in apool until the optimizer is able to analyze the solution during a MIP solve.
6. The SOLNOTIFY callback function can be used to discover the outcome of a loaded solution, based on
the identiﬁer assigned to the solution (see setcallback).
Related topics
savemipsol, loadmipsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

683

mmxprs

basisstability
Purpose
SynopsisGet basis stability information.
function basisstability(type:integer,norm:integer,scaled:boolean):realArguments
type

norm

scaledWhich information to return. Possible values:0
Condition number of the basis
1
Stability measure for the solution relative to the current basis
2
Stability measure for the duals relative to the current basis
3
Stability measure for the right hand side relative to the current basis
4
Stability measure for the basic part of the objective relative to the current basis
Which norm to use. Possible values:0
Use the inﬁnity norm
1
Use the 1 norm
2
Use the Euclidian norm for vectors, and the Frobenius norm for matrices
If false, work on the unscaled matrix

Return value
Basis stability information.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

684

mmxprs

calcsolinfo
Purpose
SynopsisCalculates a property of an mpsol solution.
function calcsolinfo(solution:mpsol, option:integer):mpsol

Arguments
solution The solution to be checked
optionWhich information to return. Possible values:
XPRS_SOLINFO_ABSPRIMALINFEAS
Calculate the maximum absolute primal
infeasibility
XPRS_SOLINFO_RELPRIMALINFEAS
Calculate the maximum relative primal
infeasibility
XPRS_SOLINFO_MAXMIPFRACTIONAL Calculate the maximum fractionality of theinteger variables
Related topics
refinemipsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

685

mmxprs

clearmipdir
Purpose
Synopsis

Delete all deﬁned MIP directives.
procedure clearmipdir

Further information
This procedure clears the list of directives deﬁned so far.
Related topics
setmipdir.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

686

mmxprs

clearmodcut
Purpose
Synopsis

Delete all deﬁned model cuts.
procedure clearmodcut

Further information
This procedure clears the list of model cuts deﬁned so far.
Related topics
setmodcut.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

687

mmxprscommandPurpose
Synopsis

Execute an Optimizer command or enter interactive mode of the Optimizer.
procedure command(cmd:string)procedure command

Argument
cmd
ExampleCommand or sequence of commands separated by "\n" character

Solve a MIP problem and then enter interactive mode:
command("minim\nglobal")commandFurther information
1. When used without parameter, this procedure enters an interactive mode of the Optimizer similar to theconsole mode: model execution is suspended and Optimizer commands can be typed directly. Model
execution resumes after command quit has been typed or the input stream has reached an end of ﬁle.
Using the alternate form of the procedure with an argument, one can send a command (or sequence ofcommands) to the Optimizer: this may be useful to execute commands for which there is no mmxprs
interface.
During the execution of this procedure, callbacks set up in the model are effective and the problem
solution status of mmxprs is updated upon termination. Note that, commands altering the problem
must be avoided (like readprob, change of name of the problem, etc.) in order to preserve consistency
between Mosel and Optimizer representations of the problem.
2. When Mosel is running in restricted mode (see Section 1.3.4), the restriction NoExec disables thisroutine.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

688

mmxprs

copysoltoinit
Purpose
Synopsis

Copy solution values to initial values of an NL problem.
procedure copysoltoinit(ms:mpsol)Argumentms

A solution object

Further information
1. This procedure copies the solution values of decision variables from the provided solution ms to theirinitial values for the next run. Doing so it overrides any previously set initial values for the involved
variables. However, the settings for decision variables that are not included in the solution ms remainunchanged.
2. This operation can only be performed on a non-linear problem described using the module mmnl.
Related topics
copysoltoinit, clearinitvals, setinitval.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

689

mmxprs

crossoverlpsol
Purpose
Synopsis

Crosses over a previously loaded LP solution to a basic solution.
function crossoverlpsol:boolean

Return value
Operation status:
FALSE No valid starting solution provided prior to call using loadlpsol
TRUE Crossover called
Further information
This procedure calls the crossover procedure for an already loaded LP solution followed by the usual
simplex solve afterwards. The solution, solution status and all attributes are set up to match the solve
and are available the usual way.
Related topics
loadlpsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

690

mmxprs

defdelayedrows
Purpose
SynopsisDeﬁne the set of constraints to be treated as delayed rows.
procedure defdelayedrows(cset:set of linctr)

Argumentcset

Set of constraints to load or {} to reset a previous setting

Further information
This procedure stores a reference to the provided set that is used when the problem is loaded into the
optimizer. This set can be modiﬁed after the call to this procedure: the optimizer will use the current
content of the set at the time of loading the problem.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

691

mmxprs

defsecurevecs
Purpose
SynopsisDeﬁne the sets of variables and constraints that must not be removed by presolve.
procedure defsecurevecs(vset:set of mpvar,cset:set of linctr)

Arguments
vset
cset

Set of decision variables to preserve or {} to reset a previous setting
Set of constraints to preserve or {} to reset a previous setting

Further information
This procedure stores references to the provided sets that are used when the problem is loaded into the
optimizer. These sets can be modiﬁed after the call to this procedure: the optimizer will use the current
content of the sets at the time of loading the problem.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information692

mmxprs

estimatemarginals
Purpose
Synopsis

Estimate better marginal values for variables and constraints for degenerate problems.
procedure estimatemarginals(sbvars:array(vars: set of mpvar) of real)procedure estimatemarginals(dualslb:array(constriants: set of linctr) ofreal, dualsub:array(constriants: set of linctr) of real)procedure estimatemarginals(sbvars:array(vars: set of mpvar) of real,
efforlimit:integer, delta:real)procedure estimatemarginals(dualslb:array(constriants: set of linctr) ofreal, dualsub:array(constriants: set of linctr) of real,
effortlimit:integer)

Arguments
sbvarsAn array of reals that will be populated with the approximations for the marginal values.
The approximation is carried out for the variables included in the variables set.
dualslb
An array of reals that will be populated with the approximations for the lower bounds
for the row marginal values. The approximation is carried out for the constraints in theconstraints set.
dualsub
An array of reals that will be populated with the approximations for the upper bounds
for the row marginal values. The approximation is carried out for the constraints in theconstraints set.
efforlimit Effort limit spent to approximate the effect of the move of a variable, expressed as an
upper limit of simplex iterations per variable.
delta
The size of the perturbation applied to force a movement in the variable.

Further information
1. This procedure can be used to estimate the marginal values of variables in degenerate problems. In
degenerate problems, the reduced costs and row duals do not always provide a good representation of
the effect on the objective when forcing a move in a variable. Also, in degenerate problems, the reduced
costs and row duals may depend on the ﬁnal basis found, and multiple correct alternatives might
exists. This function attempts to identify better marginal values by simulating a move in the variables.
2. Prior to calling estimatemarginals, the current LP problem must have been solved to optimality and an
optimal basis must be available.
3. It is important to note that the procedure provides an estimate only.
4. This procedure relies on the XPRSstrongbranch and XPRSestimaterowdualranges functions,refer to the Xpress Optimizer Reference Manual for more information.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

693

mmxprsﬁxglobalPurpose
SynopsisFix values of global entitites according to the current solution.
procedure fixglobal
procedure fixglobal(ifrnd:boolean)

Argument
ifrnd if true, integer solution values are rounded
ExampleSolve the MIP problem, reload the problem after solving, ﬁx global entities to their solution values, andﬁnally solve the LP for the continous variables in order to be able to use getrange.
minimize(obj)
fixglobal
minimize(XPRS_LIN, obj)
writeln(getrange(XPRS_UPACT,x))

Further information
1. This procedure ﬁxes the non-continuous variables to their value of the current solution. A call to thisfunction is required when performing sensitivity analysis on MIP problems using getrange.
2. The ﬁrst form of the procedure corresponds to fixglobal(false).
Related topics
getrange.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

694

mmxprs

getbstat
Purpose
Synopsis

Get the status of a variable or constraint in a basis.
function getbstat(b:basis,v:mpvar):integerfunction getbstat(b:basis,c:linctr):integer

Argumentsbv
c

A basisA decision variable
A linear constraint

Return value
Basis status. For a variable:-1
Variable is not in the basis
0
Variable is non-basic at lower bound, or superbasic at zero if the variable has no lower bound1
Variable is basic
2
Variable is non-basic at upper bound3
Variable is super-basic
For a constraint:-1
Constraint is not in the basis
0Slack, surplus or artiﬁcial is non-basic at lower bound1
Slack, surplus or artiﬁcial is basic
2
Slack or surplus is non-basic at upper bound3
Slack or surplus is super-basic
Related topics
savebasis, setbstat, resetbasis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

695

mmxprs

getdualray
Purpose
Synopsis

Get a dual ray for an infeasible problem.
function getdualray(ray:array(set of linctr) of real):boolean

Argumentray

An array of reals over all constraints in the problem (as loaded) in which the dual ray isreturned.

Return value
This procedure returns the dual ray found for the problem if the problem is found to be dual unbounded(thus primal infeasible) and one is available.
Further information
1. The return value of the function is true if a dual ray is available, and false otherwise.
2. The dimension and base set of the ray argument will be set up by the function.
Exampledeclarations
all_constraints : set of linctr
dual_ray : array(all_constraints) of real
end-declarations
if getprobstat <> XPRS_INF thenwriteln("Problem not infeasible.")else
HasRay := getdualray(dual_ray)
if HasRay thenwriteln("Dual ray:")
forall (c in all_constraints)
writeln(getname(c), " ", dual_ray(c))
elsewriteln("No dual ray was found")end-ifend-ifRelated topics
getprimalray
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

696

mmxprs

getiisPurpose
Synopsis

Compute then get the Irreductible Infeasible Sets (IIS).
procedure getiis(vset:set of mpvar,cset:set of linctr)
procedure getiis(numiis:integer,vset:set of mpvar,cset:set of linctr)
procedure getiis(numiis:integer,ctrtype:array(linctr) of integer)
procedure getiis(numiis:integer,duals:array(linctr) of real)procedure getiis(numiis:integer,isolrow:array(linctr) of boolean)
procedure getiis(numiis:integer,bndtype:array(mpvar) of integer)
procedure getiis(numiis:integer,rdcs:array(mpvar) of real)procedure getiis(numiis:integer,isolcol:array(mpvar) of boolean)

Arguments
vset
cset
numiisctrtypeSet to return the decision variables of the IIS or {} if not required
Set to return the constraints of the IIS or {} if not required
Ordinal number of the IIS
Array to return the sense or type of rows in the IIS (XPRS_IIS_LEQ, XPRS_IIS_GEQ,
XPRS_IIS_EQ , XPRS_IIS_SOS1, XPRS_IIS_SOS2 or XPRS_IIS_INDIC)
duals
Array to return the dual multipliers associated with the rows of the IIS
isolrow Array to return the isolation status of the the rows of the IIS
bndtype Array to return the encoded sense and type of bounds in the IIS
rdcs
Array to return the dual multipliers associated with the bounds of the IIS
isolcol Array to return the isolation status of the the bounds of the IIS

Further information
1. This procedure computes the IIS and stores the result in the provided parameters. The ﬁrst form of theroutine (numiis not speciﬁed) computes all IIS and returns the last set found.
2. The bndtype values have to be decoded using getiissense and getiistype. The ﬁrst routine may
return XPRS_IIS_LEQ (upper bound), XPRS_IIS_GEQ (lower bound), XPRS_IIS_RNG (lower andupper bound) or XPRS_IIS_EQ (ﬁxed bound). The second one may give XPRS_IIS_BIN (binary),
XPRS_IIS_INT (integer), XPRS_IIS_PINT (partial integer), XPRS_IIS_SEC (semi continuous) or
XPRS_IIS_SINT (semi continuous integer).
3. The sets passed to this procedure are reset before being used.
Related topics
resetiis, isiisvalid, getinfeas.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

697

mmxprs

getiissense
Purpose
Synopsis

Decode the sense part of an IIS bound type information.
function getiissense(i:bndtype):integer

Argument
bndtype A bound type as returned by getiis
Return value
Sense part of an IIS bound type.
Related topics
getiis, getiistype.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

698

mmxprs

getiistype
Purpose
Synopsis

Decode the type part of an IIS bound type information.
function getiistype(i:bndtype):integer

Argument
bndtype A bound type as returned by getiis
Return value
Type part of an IIS bound type.
Related topics
getiis, getiissense.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

699

mmxprs

getinfcause
Purpose
Synopsis

Returns the variable or constraint causing infeasibility.
procedure getinfcause(vars:set of mpvar,ctrs:set of linctr)

Arguments
vars
ctrs

Set to return the infeasible variable or {} if not required
Set to return infeasible constraint or {} if not required

Further information
1. This function can be used to get the variable or constraint responsible for an infeasibility detected
either during matrix generation (invalid bound) or when presolving the problem.
2. The sets passed to this procedure are reset before being used.
Related topics
getinfeas.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

700mmxprs

getinfeas
Purpose
Synopsis

Returns sets of infeasible primal and dual variables.
procedure getinfeas(mx:set of mpvar,mslack:set of linctr,mdual:set oflinctr,mdj:set of mpvar)

Arguments
mx
mslackmdual
mdj

Set to return the infeasible variables or {} if not required
Set to return infeasible constraints or {} if not required
Set to return dual infeasible constraints or {} if not required
Set to return the dual infeasible variables or {} if not required

Related topics
getiis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

701

mmxprs

getlb
Purpose
Synopsis

Get the lower bound of a variable.
function getlb(x:mpvar):realArgumentx

A decision variable

Return value
Lower bound of the variable.
Further information
This function returns the lower bound of a variable that is currently held by the Optimizer. The boundvalue may be changed directly in the Optimizer using setlb. Changes to the variable in Mosel are nottaken into account by this function unless the problem has been reloaded since (procedure loadprob).
Related topics
getub, setlb, setub.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information702

mmxprs

getloadedlinctrs
Purpose
Synopsis

Get the linear constraints loaded into the optimiser.
procedure getloadedlinctrs(sc:set of linctr)

Argumentsc

A set of linear constraints

Further information
The result of the operation is added to the current content of the provided set (i.e. the set is not cleared).
Related topics
getloadedmpvars
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

703

mmxprs

getloadedmpvars
Purpose
Synopsis

Get the decision variables loaded into the optimiser.
procedure getloadedmpvars(sv:set of mpvar)

Argumentsv

A set of decision variables

Further information
The result of the operation is added to the current content of the provided set (i.e. the set is not cleared).
Related topics
getloadedlinctrs
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

704

mmxprs

getname
Purpose
Synopsis

Get the name of a decision variable or constraint of the problem.
function getname(x:mpvar):string
function getname(c:linctr):string
function getname(nl:nlctr):stringArgumentsxcnl

A decision variable used in the problem
A constraint (or SOS) of the problem
A non linear constraint of the problem

Return value
Name of the given object.
Further information
1. This function returns the name of a decision variable or constraint of the problem that would be used
for matrix exportation. The parameter of this function must be part of the problem — for instance a
hidden constraint cannot be assigned a name.
2. This function requires that the matrix has been generated (e.g. by a call to exportprob or loadprob).
When used with a non linear constraint it is further required for the problem to be loaded into the
optimiser and the parameter XPRS_loadnames must be true.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

705

mmxprs

getprimalray
Purpose
Synopsis

Get a primal ray for an unbounded problem.
function getprimalray(ray:array(set of mpvar) of real):boolean

Argumentray

An array of reals over all constraints in the problem (as loaded) in which the primal ray isreturned.

Return value
This procedure returns the primal ray found for the problem if the problem is found to be primal
unbounded (thus dual infeasible) and one is available.
Further information
1. The return value of the function is true if a primal ray is available, and false otherwise.
2. The dimension and base set of the ray argument will be set up by the function.
Exampledeclarations
all_variables : set of mpvar
primal_ray : array(all_variables) of real
end-declarations
if getprobstat <> XPRS_UNB thenwriteln("Problem is not unbounded.")else
HasRay := getprimalray(primal_ray)
if HasRay thenwriteln("Primal ray:")
forall (c in all_variables)
writeln(getname(c), " ", primalray(c))
elsewriteln("No primal ray was found")end-ifend-ifRelated topics
getdualray
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

706

mmxprs

getprobstat
Purpose
Synopsis

Get the Optimizer problem status.
function getprobstat:integer

Return value
Status of the problem currently held in the Optimizer:
XPRS_OPT Solved to optimality
XPRS_UNF Unﬁnished
XPRS_INF Infeasible
XPRS_UNB Unbounded
XPRS_OTH Unsolved or objective worse than cutoff
ExampleThe following procedure displays the current problem status:
procedure print_status
declarations
status: string
end-declarations
case getprobstat of
XPRS_OPT: status:="Optimum found"
XPRS_UNF: status:="Unfinished"
XPRS_INF: status:="Infeasible"
XPRS_UNB: status:="Unbounded"
XPRS_OTH: status:="Failed"else status:="???"
end-case
writeln("Problem status: ", status)
end-procedure

Further information
More detailed information than what is provided by this function can be obtained with function
getparam, retrieving the problem attributes XPRS_presolvestate, XPRS_lpstatus, and
XPRS_mipstatus (see the Xpress Optimizer Reference Manual).
Related topics
getparam.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

707

mmxprs

getrange
Purpose
Synopsis

Get a range value for a variable or constraint.
function getrange(w:integer, x:mpvar):realfunction getrange(w:integer, c:linctr):realArgumentswxc

Which information to return. Possible values:
XPRS_UPACT Upper activity
XPRS_LOACT Lower activity
XPRS_UUP
Upper unit cost
XPRS_UDN
Lower unit cost
XPRS_UCOST Upper cost (variable only)
XPRS_LCOST Lower cost (variable only)
A variable of the problem
A constraint of the problem

Return value
Range information depending on the value of w.
Further information
This function returns ranging information to be used for sensitivity analysis after the problem has been
optimized. On MIP problems, global entities have to be “ﬁxed” using the procedure fixglobal before
this function can be called.
Related topics
fixglobal.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

708

mmxprs

getsensrng
Purpose
Synopsis

Get sensitivity ranges for objective or RHS function coefﬁcients.
function getsensrng(w:integer, x:mpvar):realfunction getsensrng(w:integer, c:linctr):realArgumentswxc

Which information to return. Possible values:
XPRS_UP Upper sensitivity range
XPRS_DN Lower sensitivity range
A variable of the problem
A constraint of the problem

Return value
Sensivity range information depending on the value of w.
Further information
This function returns sensitivity ranges for RHS function coefﬁcients (if used with a constraint) and for
objective function coefﬁcients (if used with a variable). getsensrng can be called only if an optimal
LP solution is available and the problem is not MIP presolved.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information709

mmxprs

getsize
Purpose
Synopsis

Get the size of a solution.
function getsize(ms:mpsol):integer

Argumentms

A solution object

Return value
The number of variables stored in the solution.
Related topics
getvars.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

710

mmxprs

getsolPurpose
Synopsis

Get the solution value of an expression from a solution object.
function getsol(ms:mpsol,v:mpvar):realfunction getsol(ms:mpsol,c:linctr):realfunction getsol(ms:mpsol,nl:nlctr):realArguments
ms
v
c
nl

A solution object
A decision variable
A linear constraint
A non linear constraint

Return value
Solution value or 0.
Further information
This function returns an evaluation of an expression using the provided solution object as solution
values for the decision variables.
Related topics
setsol, savesol, savemipsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

711

mmxprs

getub
Purpose
Synopsis

Get the upper bound of a variable.
function getub(x:mpvar):realArgumentx

A decision variable

Return value
Upper bound of the variable.
Further information
The bound value may be changed directly in the optimizer using setub. Changes to the variable inMosel are not taken into account by this function unless the problem has been reloaded since(procedure loadprob).
Related topics
getlb, setlb, setub.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

712

mmxprsgetvars
Purpose
Synopsis

Get the set of variables of a solution.
procedure getvars(ms:mpsol,s:set of mpvar)

Argumentsmss

A solution object
A set of decision variables

Further information
This procedure returns in the parameter s the set of variables used by a solution object. Note that thisprocedure replaces the content of the set.
Related topics
getsize.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

713

mmxprs

hasfeature
Purpose
SynopsisCheck if a speciﬁc feature is supported by the currently used license.
function hasfeature(feature:string):boolean

Argument
feature The name of the feature to check, as it would appear in the Xpress license ﬁleReturn value
true if the requested feature is supported, false otherwise.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

714

mmxprs

implies
Purpose
SynopsisCreate an implies expression.
function implies(c1:log_or_linctr,c2:log_or_linctr):logctr

Argumentsc1
c2

A linear constraint (linctr) or logical expression (logctr)
A linear constraint (linctr) or logical expression (logctr)

Return value
A new logctr representing the expression.
ExampleThe following example shows several ways of stating the logical relation ’if x1 ≥ 10 then x1 + x2 ≥ 12
and not x2 ≤ 5’. The implied constraint L is itself a logical constraint, built up by using the operators
and and not in combination with linear constraints.
declarations
R=1..2
C: array(range) of linctr
L: logctr
x: array(R) of mpvar
end-declarations! Linear constraints! Logical constraint! Decision variables

C(1):= x(1)>=10
C(2):= x(2)<=5
C(3):= x(1)+x(2)>=12! Define (temporary) linear ctrs

implies(C(1), C(3) and not C(2))
forall(j in 1..3) C(j):=0! State the implication! Delete the auxiliary ctrs

! The same implication constraint can be stated by:
implies(x(1)>=10, x(1)+x(2)>=12 and not x(2)<=5)! Or also by:
L:= x(1)+x(2)>=12 and not x(2)<=5 ! Define (temporary) logical ctr
implies(x(1)>=10, L)! State the implication
L:= 0! Delete the auxiliary ctr
Further information
1. This function creates a logctr constraint representing an implies condition: if c1 is valid then c2 isenforced.
2. The helper package ’advmod’ must be loaded if this function is used:
uses 'advmod'

Related topics
indicator, xor
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

715

mmxprs

indicator
Purpose
SynopsisCreate an indicator constraint.
function indicator(type:integer,y:mpvar,ctr:linctr):logctr

Arguments
type
y
ctr

The indicator type:-1
for indicator y=0 -> ctr
1
for indicator y=1 -> ctr
The variable associated to the constraint
A linear inequality constraint

Return value
A new logctr representing the indicator.
ExampleThis example shows how to deﬁne two indicator constraints. The second constraint labeled L is statedwith the help of an auxiliary linear constraint deﬁnition. This temporary constraint C needs to be deleted
from the problem after having been used in the deﬁnition of the indicator constraint. The notationb(1)=1 -> ... should be read as ’if b(1) takes the value 1 then ... must hold’declarations
R=1..2, S=1..3
C: linctr
L: logctr
x: array(S) of mpvar
b: array(R) of mpvar
end-declarations! Linear constraint! Logical (indicator) constraint! Decision variables! Indicator variables

forall(i in R)
b(i) is_binary! Indicator variables must be binaries

C:= x(2)+x(3)<=5! Constraint to transform into indicator ctr.

! Define 2 indicator constraints
indicator(1, b(1), x(1)+x(2)>=12)
L:= indicator(-1, b(2), C)
C:=0! b(1)=1 -> x(1)+x(2)>=12! b(2)=0 -> x(2)+x(3)<=5! Delete the auxiliary constraint definition

Related topics
implies, xor
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

716

mmxprs

isiisvalid
Purpose
SynopsisCheck whether an IIS number exists.
function isiisvalid(numiis:integer):boolean

Argument
numiisOrdinal number of the IIS

Return value
true if numiis corresponds to an existing IIS.
Related topics
resetiis, getiis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

717

mmxprs

isintegral
Purpose
SynopsisCheck whether a variable (or set of variables) solution value is integral.
function isintegral(x:mpvar):booleanfunction isintegral(s:set of mpvar):boolean

Argumentsxs

A decision variable
A set of decision variables

Return value
true if the variable (or all variables of the set) is integral.
Further information
This function checks whether the current solution value of a variable is integral with respect to thetolerance value of the optimizer (XPRS_MIPSOL). When used with a set, the function returns true if all
variables of the set satisfy the condition.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

718

mmxprsloadbasis
Purpose
Synopsis

Load a previously saved basis.
procedure loadbasis(b:basis)

Argumentb
ExampleA basisThe following saves a basis, changes the problem, and then loads it into the Optimizer, reloading theold basis:
declarations
MinCost:linctr
mybasis:basis
end-declarations
savebasis(mybasis)...
loadprob(MinCost)
loadbasis(mybasis)

Further information
1. This procedure loads a basis into the optimizer that has previously been saved using procedure
savebasis or constructed using setbstat.
2. The problem must be loaded in the Optimzer for loadbasis to have any effect. If this has not recently
been carried out using maximize or minimize it must be explicitly loaded using loadprob.
Related topics
loadprob, savebasis, setbstat, getbstat, resetbasis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

719

mmxprsloadlpsol
Purpose
Synopsis

Load an LP solution into the optimizer.
procedure loadlpsol(x:array(set of mpvar) of real, slack:array(set oflinctr) of real, dual:array(set of linctr) of real, dj:array(set of
mpvar) of real)procedure loadlpsol(x:array(set of mpvar) of real, dual:array(set oflinctr) of real)procedure loadlpsol(x:array(set of mpvar) of real)

Arguments
x
slack
dual
dj

An array containing the primal solution
An array containing the constraint slacks
An array containing the dual multipliers
An array containing the reduced cost values

Related topics
crossoverlpsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

720mmxprsloadmipsol
Purpose
Synopsis

Load a MIP solution into the optimizer.
function loadmipsol(s:array(set of mpvar) of real):integerfunction loadmipsol(solnum:integer):integerfunction loadmipsol(ms:mpsol):integer

Argumentsssolnumms

An array containing the solution
Solution number (between 1 and XPRS_enumsols)
A solution object

Return value
Operation status:-1
Solution rejected because an error occurred0
Solution accepted1
Solution rejected because it is infeasible
2
Solution rejected because it is cut off
3
Solution rejected because the LP reoptimization was interrupted
ExampleThe following saves a MIP solution, modiﬁes the problem, and then loads it into the Optimizer,
reloading the MIP solution:
declarations
MinCost:linctr
mysol: array(set of mpvar) of real
result: integer
end-declarations
savemipsol(mysol)...
! Make some changes
loadprob(MinCost)
result:= loadmipsol(mysol)
if result<>0 then writeln("Loading MIP solution failed"); end-if
minimize(MinCost)

Fair Isaac Corporation Conﬁdential and Proprietary Information

721

mmxprs

Further information
1. This function loads a MIP solution into the optimizer that has previously been saved using procedure
savemipsol or constructed by some external heuristic. In the latter case a value needs to be assigned
to each discrete variable in the problem, such as mysol(x):= 1 (where x is a decision variable of typempvar).
2. The values for the continuous variables in the s array are ignored and are calculated by ﬁxing the
integer variables and reoptimizing.
3. The second form of the routine can be called after a search for n-best solutions has been performed by
the optimiser: the selected solution is used as input.
4. The current problem deﬁnition must be loaded into the Optimizer for loadmipsol to have any effect. If
this has not recently been done, e.g., by calling maximize or minimize, the problem must be explicitly
loaded using loadprob.
5. If the MIP solution is accepted by the Optimizer it causes the MIPABSCUTOFF control to be set
accordingly. The provided MIP solution may help guiding the MIP heuristics but the branch-and-boundsearch will start from the initial LP relaxation solution as usual.
Related topics
savemipsol, addmipsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

722

mmxprsloadprob
Purpose
Synopsis

Load a problem into the optimizer.
procedure loadprob(obj:linctr)
procedure loadprob(force:boolean,obj:linctr)
procedure loadprob(obj:linctr, extravar:set of mpvar)
procedure loadprob(force:boolean, obj:linctr, extravar:set of mpvar)
procedure loadprob(qobj:qexp)
procedure loadprob(qobj:qexp, extravar:set of mpvar)
procedure loadprob(nlobj:nlctr)
procedure loadprob(nlobj:nlctr, extravar:set of mpvar)
procedure loadprob(rbobj:robustctr)
procedure loadprob(rbobj:robustctr, extravar:set of mpvar)

Arguments
obj
qobj
nlobj
rbobj
force
extravar

Objective function constraint
Quadratic objective function (with module mmquad)
Non linear objective function (with module mmnl)
Robust objective function (with module mmrobust)
Load the matrix even if not required
Extra variables to include

Further information
1. This procedure explicitly loads a problem into the optimizer. It gets called automatically by the
optimization procedures minimize and maximize if the problem has been modiﬁed in Mosel since
the last call to the optimizer. Nevertheless in some cases, namely before loading a basis, it may benecessary to reload the problem explicitly using this procedure. If the problem has not been modiﬁed
since the last call to loadprob, the problem is not reloaded into the optimizer. The parameter force
can be used to force a reload of the problem in such a case. The parameter extravar is a set ofvariables to be included into the problem even if they do not appear in any constraint (i.e. they become
empty columns in the matrix).
2. Support for quadratic programming requires the module mmnl.
3. Support for general nonlinear programming requires the module mmxnlp.
4. Support for robust programming requires the module mmrobust.
Related topics
maximize, minimize.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

723

mmxprs

maximize, minimize
Purpose
SynopsisMaximize/minimize the current problem.
procedure maximize(alg:integer, obj:linctr)
procedure maximize(obj:linctr)
procedure maximize(alg:integer, qobj:qexp)
procedure maximize(qobj:qexp)
procedure maximize(alg:integer, nlobj:nlctr)
procedure maximize(nlobj:nlctr)
procedure maximize(rbobj:robustctr)
procedure maximize(alg:integer, rbobj:robustctr)

Arguments
alg

Algorithm choice:

XPRS_BAR
Newton-Barrier to solve LP
XPRS_DUAL
Dual simplex
XPRS_NET
Network solver
XPRS_LIN
Only solve LP ignoring all global entities
XPRS_PRI
Primal simplex
XPRS_ENUM
Start a search for the n-best MIP solutions
XPRS_LPSTOP Stop the MIP solution process after solving the ﬁrst LP
XPRS_CONT
Continue a previously interrupted solution process
XPRS_LOCAL
Solve the linearization of the problem (mmxnlp only)
XPRS_CORELP Solve the linear part of the problem (mmxnlp only)
XPRS_TUNE
Enable the tuner
obj
Objective function constraint
qobj Quadratic objective function (with module mmquad)nlobj Non linear objective function (with module mmnl)
rbobj Robust objective function (with module mmrobust)
ExampleThe following maximizes Profit using the dual simplex algorithm and stops before the global search:declarations
Profit:linctr
end-declarations
maximize(XPRS_DUAL+XPRS_LPSTOP, Profit)
The following minimizes MinCost using the Newton-Barrier algorithm and ignoring all global entities
declarations
MinCost:linctr
end-declarations
minimize(XPRS_BAR+XPRS_LIN, MinCost)

Fair Isaac Corporation Conﬁdential and Proprietary Information

724

mmxprs

Further information
1. This procedure calls the Optimizer to maximize/minimize the current problem (excluding all hidden
constraints) using the given constraint as objective function. Optionally, the algorithm to be used canbe deﬁned. By default, the global search is executed automatically if the problem contains any global
entities. Where appropriate, several algorithm choice parameters may be combined (using plus signs).
2. If XPRS_LIN is speciﬁed, then the discreteness of all global entities is ignored, even during the presolve
procedure.
3. If XPRS_LPSTOP is speciﬁed, then just the LP at the top node is solved and no Branch-and-Boundsearch is initiated. But the discreteness of the global entities is taken into account in presolving the LP
at the top node. Note also that getprobstat still returns information related to the MIP problem when
this option is used although only an LP solve has been executed and the solution information returned
by getsol corresponds to the current LP solution. However, if the the MIP is solved to optimality
during this call, the MIP optimal solution will be returned by getsol.
4. If XPRS_CONT is used after a solve has completed, the routine returns immediately without altering thecurrent problem status.
5. If XPRS_ENUM is speciﬁed, the optimiser starts a search for the n-best MIP solutions. The maximum
number of solutions to store may be speciﬁed using the XPRS_enummaxsol (default: 10). After the
execution of the enumeration, the number of solutions found during the search is returned by thecontrol parameter XPRS_enumsols. The procedure selectsol can then be used to select one ofthese solutions.
6. If XNLP_LOCAL is speciﬁed for a non-linear problem having been loaded using mmxnlp and which havebeen solved using XSLP, then the current linearization will be reoptimized.
7. If XPRS_TUNE is speciﬁed the problem will be tuned and then solved with the best control settings
identiﬁed by the tuner. For a user guide about the tuner, please refer to the documentation of the Xpress
Optimizer.
8. If XNLP_CORELP is speciﬁed for a non-linear problem having been loaded using mmxnlp, then only thelinear part of the problem will be loaded and optimized. This is usefull for checking if the linear part ofthe problem is well posed.
9. Support for quadratic programming requires the module mmnl.
10. Support for general nonlinear programming requires the module mmxnlp.
11. Support for robust programming requires the module mmrobust.
Related topics
postsolve, loadprob, selectsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

725

mmxprs

postsolve
Purpose
Synopsis

Postsolve the current matrix.
procedure postsolve

Further information
After an optimisation operation has been interrupted before its completion, the matrix held into the
optimiser remains in a presolved state. In this state direct matrix operations (like ﬁxing bounds) cannot
be applied: this routine restores the problem in its original state that is just after it was loaded into the
optimiser. As an alternative to postsolving the matrix, the problem may be entirely reloaded using
loadprob.
Related topics
maximize, minimize.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

726

mmxprs

readbasis
Purpose
Synopsis

Read a basis from a ﬁle.
procedure readbasis(fname:string,options:string)Arguments
fname
Extended ﬁle nameoptions String of options
Further information
This procedure reads in a basis from a ﬁle by calling the function XPRSreadbasis of the Optimizer.
Note that basis save/read procedures can be used only if the constraint and variable names have been
loaded into the Optimizer (control parameter XPRS_loadnames set to true) and all constraints are
named. For more detail on the options and behavior of this procedure refer to the Xpress Optimizer
Reference Manual.
Related topics
writebasis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

727

mmxprs

readdirs
Purpose
Synopsis

Read directives from a ﬁle.
procedure readdirs(fname:string)Argument
fname Extended ﬁle name
Further information
This procedure reads in directives from a ﬁle by calling the function XPRSreaddirs of the Optimizer.
Note that directives save/read procedures can be used only if variable names have been loaded into the
Optimizer (parameter XPRS_loadnames set to true).
Related topics
writedirs.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

728

mmxprs

readsol
Purpose
Synopsis
Synopsis

Read a solution from a ﬁle.
procedure readsol(fname:string,options:string)procedure readsol(fname:string,options:string)procedure readsol(sol:array(mpvar) of real,fname:string,options:string)procedure readsol(sol:mpsol,fname:string,options:string)procedure readsol(sol:mpvar,fname:string,options:string)Arguments
fname
Extended ﬁle nameoptions String of options
sol
Object to load the solution into
Further information
This procedure reads in a solution from a ﬁle by calling the function XPRSreadslxsol of the
Optimizer. Note that solution save/read procedures can be used only if the constraint and variablenames have been loaded into the Optimizer (control parameter XPRS_loadnames set to true) and all
constraints are named. For more detail on the options and behavior of this procedure refer to theXpress Optimizer Reference Manual.
Related topics
writesol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

729

mmxprs

reﬁnemipsol
Purpose
Synopsis

Executes the MIP solution reﬁner on an mpsol solution.
function refinemipsol(solution:mpsol):mpsol
function refinemipsol(solution:mpsol, options:integer):mpsol

Arguments
solution The solution to be reﬁned
options
Options passed to the solution reﬁner. Please refer to XPRSrefinemipsol for theavailable options
Related topics
calcsolinfo.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

730

mmxprs

rejectintsol
Purpose
Synopsis

Reject the solution provided to the PREINTSOL callback.
procedure rejectintsol

Further information
This procedure cannot be called from outside of the PREINTSOL callback.
Related topics
setcallback.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

731

mmxprs

repairinfeas
Purpose
Synopsis

Relaxing bounds to repair infeasibility.
procedure repairinfeas(alrp:array(linctr) of real, agrp:array(linctr) ofreal, albp:array(mpvar) of real, aubp:array(mpvar) of real)procedure repairinfeas(alrp:array(linctr) of real, agrp:array(linctr) ofreal, albp:array(mpvar) of real, aubp:array(mpvar) of real,
phs2:string, delta:real,optfg:string)procedure repairinfeas(flags:string, lrp:real, grp:real, lbp:real,
ubp:real, delta:real)procedure repairinfeas(flags:string)procedure repairinfeas(alrp:array(linctr) of real, agrp:array(linctr) ofreal, albp:array(mpvar) of real, aubp:array(mpvar) ofreal,alrb:array(linctr) of real,agrb:array(linctr) ofreal,albb:array(mpvar) of real,aubb:array(mpvar) ofreal,phs2:string,delta:real,optfg:string)Arguments
alrp
agrp
albp
aubp
alrb

Array of preferences for relaxing the less or equal side of row
Array of preferences for relaxing the greater or equal side of row
Array of preferences for relaxing lower bounds
Array of preferences for relaxing upper bounds
Array of upper bounds to be imposed on the amount of relaxation allowed for the less or equalside of row
agrb Array of upper bounds to be imposed on the amount of relaxation allowed for the greater or
equal side of row
albb Array of upper bounds to be imposed on the amount of relaxation allowed for lower bounds
aubb Array of upper bounds to be imposed on the amount of relaxation allowed for upper bounds
phs2 A 1-character string controling the second phase optimization
lrp
Preference for relaxing the less or equal side of row
grp
Preference for relaxing the greater or equal side of row
lbp
Preference for relaxing lower bounds
ubp
Preference for relaxing upper bounds
delta Relaxation multiplier for the second phase-1
flags A 3-character string deﬁning the p/o/g ﬂags
optfg Flags to be passed to the optimizer

Fair Isaac Corporation Conﬁdential and Proprietary Information732

mmxprs

Further information
1. This routine is an interface to the Optimizer functions XPRSrepairweightedinfeas and
XPRSrepairinfeas. Please refer to the Xpress Optimizer Reference Manual for further details.
2. The 2 ﬁrst forms call the Optimizer routine XPRSrepairweightedinfeas. Missing preferences aretreated as 0; the default value for phs2 is "d" and the default value for delta is 0.001.
3. The third and fourth forms call the Optimizer routine XPRSrepairinfeas. If flags is not speciﬁed(empty string), a default value of "cog" is used. If preferences and delta are not given, allpreferences are set to 1 and delta is 0.001.
4. The last form calls the Optimizer routine XPRSrepairweightedinfeasbounds, allowing to boundthe amount of relaxation applied on a per row or bound basis. Only positive bounds are applied; a zeroor negative bound is ignored and the amount of relaxation allowed for the corresponding row or boundis not limited. The effect of a zero bound on a row or bound would be equivalent with not relaxing it, andcan be achieved by setting its preference array value to zero instead, or not including it in thepreference arrays. The default value for phs2 is "d".
5. Negative preferences translate to quadratic penalties applied for the corresponding rows or bounds.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information733

mmxprs

resetbasis
Purpose
Synopsis

Reset a basis.
procedure resetbasis(b:basis)

Argumentb

A basisFurther information
This function clears the information stored in a basis object.
Related topics
loadbasis, savebasis, setbstat, resetbasis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information734

mmxprs

resetiis
Purpose
Synopsis

Reset the search for IIS.
procedure resetiis

Further information
This procedure resets the search for IIS and clears all information already computed related to IIS.
Related topics
getiis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

735

mmxprs

resetsol
Purpose
Synopsis

Reset a solution.
procedure resetsol(ms:mpsol)Argumentms

A solution object

Further information
This function clears the information stored in a solution object.
Related topics
setsol, savesol, savemipsol, getsize.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

736

mmxprs

savebasis
Purpose
Synopsis

Save the current basis.
procedure savebasis(b:basis)

Argumentb

A basisFurther information
This function saves the current basis into the provided basis object.
Related topics
loadbasis, setbstat, getbstat, resetbasis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

737

mmxprs

savemipsol
Purpose
Synopsis

Save the current solution into the provided array or solution object.
procedure savemipsol(s:array(set of mpvar) of real)procedure savemipsol(ms:mpsol)Argumentssms

An array to return the solution
A solution object

Further information
1. This procedure saves the current solution into the provided array. The resulting datastructure may be
used as input for the loadmipsol function.
2. If the index set of the array is dynamic, the procedure may extend it in order to have all variables of the
problem. Otherwise the solution is saved only for the variables included in this set.
3. Only non-continuous variables are saved when this procedure is used with an mpsol argument. Usesavesol to save the values of all variables.
Related topics
loadmipsol, savesol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

738

mmxprs

savesol
Purpose
Synopsis

Save the current solution into a solution object.
procedure savesol(ms:mpsol)Argumentms

A solution object

Further information
This procedure saves the current solution into the provided solution object. As opposed to thesavemipsol routine all variables are saved independently of their type.
Related topics
savemipsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information739

mmxprs

savestate
Purpose
Synopsis

Save current state of the Optimizer to a ﬁle.
procedure savestate(fname:string)Argument
fname Extended ﬁle name
Further information
The produced ﬁle can then be used as input to Optimizer console using optimizer’s command RESTORE.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

740

mmxprs

selectsol
Purpose
Synopsis

Select one of the solutions found by solution enumerator.
procedure selectsol(solnum:integer)

Argument
solnumSolution number (between 1 and XPRS_enumsols)

Further information
1. This routine can be called after a search for n-best solutions has been performed by the optimizer inorder to select a particular solution.
2. Once a solution has been selected, the functions getsol (applied to decision variables) and
getobjval return values related to this solution.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

741

mmxprs

setarchconsistency
Purpose
Synopsis

Sets the value of the optimizer architecture control.
procedure setarchconsistency(controlvalue:integer)

Argument
controlvalue Value of the optimizer architecture control
Further information
Please refer to the Xpress Optimizer Reference Manual for more details.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information742

mmxprs

setbstat
Purpose
Synopsis

Set the status of a variable or constraint in a basis.
procedure setbstat(b:basis,v:mpvar,s:integer)
procedure setbstat(b:basis,c:linctr,s:integer)

Argumentsbv
cs

A basisA decision variable
A linear constraint
Basis status. For a variable:-1
Remove the variable from the basis
0
Variable is non-basic at lower bound, or superbasic at zero if the variable has nolower bound1
Variable is basic
2
Variable is non-basic at upper bound3
Variable is super-basic
For a constraint:-1
Remove the constraint from the basis
0Slack, surplus or artiﬁcial is non-basic at lower bound1
Slack, surplus or artiﬁcial is basic
2
Slack or surplus is non-basic at upper bound3
Slack or surplus is super-basic

Related topics
savebasis, getbstat, resetbasis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

743

mmxprs

setcallback
Purpose
Synopsis

Set optimizer callback functions and procedures.
procedure setcallback(cbtype:integer, cb:string)Arguments
cbtypeType of the callback:
XPRS_CB_LPLOG
XPRS_CB_CUTLOG
XPRS_CB_GLOBALLOG
XPRS_CB_BARLOG
XPRS_CB_CHGNODE
XPRS_CB_PRENODE
XPRS_CB_OPTNODE
XPRS_CB_INFNODEXPRS_CB_INTSOLXPRS_CB_NODECUTOFFXPRS_CB_NEWNODEXPRS_CB_BARITER
XPRS_CB_CUTMGR
XPRS_CB_CHGBRANCHXPRS_CB_PREINTSOLXPRS_CB_GAPNOTIFY
XPRS_CB_SOLNOTIFY

cb

Simplex log callback
Cut log callback
Global log callback
Barrier log callback
User select node callback
User preprocess node callback
User optimal node callback
User infeasible node callback
User integer solution callback
User cut-off node callback
New node callback
Barrier iteration callback
Cut manager (branch-and-bound node) callback
User choose branching variable callback
Integer solution callback called before acceptation
Gap notify callback
Integer notify callback called each time a solution added withaddmipsol is processed
XPRS_CB_PRESOLVE
A callback ﬁred after presolve is performed
Name of the callback function/procedure (that must be public); the parameters and the type

Fair Isaac Corporation Conﬁdential and Proprietary Information

744

mmxprsof the return value (if any) vary depending on the type of the callback:function cb:booleanfunction cb:booleanfunction cb:booleanfunction cb:booleanfunction cb(node:integer):integerfunction cb:booleanfunction cb:boolean
procedure cb
procedure cb
procedure cb(node:integer)
procedure cb(parent:integer,new:integer,branch:integer)function cb:integerfunction cb:boolean
procedure cb(e:integer,u:integer,d:real)procedure cb(soltype:integer,cutoff:real)procedure cb(rt:real,at:real,aot:real,abt:real)procedure cb(solid:string,status:integer)
procedure cb
ExampleXPRS_CB_LPLOG
XPRS_CB_CUTLOG
XPRS_CB_GLOBALLOG
XPRS_CB_BARLOG
XPRS_CB_CHGNODE
XPRS_CB_PRENODE
XPRS_CB_OPTNODE
XPRS_CB_INFNODEXPRS_CB_INTSOLXPRS_CB_NODECUTOFFXPRS_CB_NEWNODEXPRS_CB_BARITER
XPRS_CB_CUTMGR
XPRS_CB_CHGBRANCHXPRS_CB_PREINTSOLXPRS_CB_GAPNOTIFY
XPRS_CB_SOLNOTIFY
XPRS_CB_PRESOLVE

The following example deﬁnes a procedure to handle solution printing and sets it to be called wheneveran integer solution is found using the integer solution callback:public procedure printsol
declarations
objval:real
end-declarations
objval:= getparam("XPRS_lpobjval")
writeln("Solution value: ", objval)
end-procedure
setcallback(XPRS_CB_INTSOL, "printsol")

Fair Isaac Corporation Conﬁdential and Proprietary Information

745mmxprs

Further information
1. This procedure sets the optimizer callback functions and procedures. For a detailed description ofthese callbacks the user is referred to the Xpress Optimizer Reference Manual.
2. Passing an empty string ("") as the function name disables the corresponding callback.
3. The arguments of the Mosel subroutines implementing callback functions correspond to thearguments documented in the Xpress Optimizer Reference Manual, with the exception of argumentsthat are used for passing back information to the solver: these are replaced by the subroutine return
values. For the logging callbacks, the return value true interrupts the solving. For the PRENODE andOPTNODE callbacks the return value true declares the current node to be infeasible. The return valueof the BARITER callback is the selected barrier action (see XPRSaddcbbariteraction in the Xpress
Optimizer Reference Manual for details). The cut manager routine is called repeatedly at each node until
it returns false.
4. Whilst the solution values can be accessed from Mosel in any callback function/procedure, all otherinformation such as the problem status or the value of the objective function must be obtained directlyfrom the Optimizer using function getparam.
5. The function setucbdata can be used to return information to the optimizer from the callback‘CHGBRANCH’.
6. The functions rejectintsol and setcbcutoff can be used to return information to the optimizer
from the callback ‘PREINTSOL’.
7. The function setgndata can be used to return information to the optimizer from the callback‘GAPNOTIFY’.
8. When the mmxnlp model is used, this function can also be used to set the callbacks relevant tonon-linear problems only. Please see the documentation of the mmxnlp module for the list of extra
callbacks.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

746

mmxprs

setcbcutoff
Purpose
Synopsis

Set the cutoff to be returned to the Optimizer by the PREINTSOL callback.
procedure setcbcutoff(cutoff:real)

Argument
cutoff

New cutoff value for the current solution

Further information
This procedure cannot be called from outside of the PREINTSOL callback.
Related topics
setcallback.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

747

mmxprs

setgndata
Purpose
Synopsis

Update data to be returned to the Optimizer by the GAPNOTIFY callback.
procedure setgndata(what:integer, target:real)

Arguments
whattargetWhat target to update. Possible values:
XPRS_GN_RELTARGET
Relative gap
XPRS_GN_ABSTARGET
Absolute gap
XPRS_GN_ABSOBJTARGET
Absolute gap on objective
XPRS_GN_ABSBOUNDTARGET Absolute gap on boundNew target value

Further information
This procedure stores the provided information that will be returned to the optimizer when the callback
terminates. This procedure cannot be called from outside of the GAPNOTIFY callback.
Related topics
setcallback.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

748

mmxprs

setlb
Purpose
Synopsis

Set the lower bound of a variable.
procedure setlb(x:mpvar,r:real)

Argumentsxr

A decision variable
Lower bound value

Further information
This procedure changes the lower bound of a variable directly in the Optimizer, that is, the boundchange is not recorded in the problem deﬁnition held in Mosel. Since this change is immediate, there isno need to reload the problem into the Optimizer (indeed, doing so resets the variable to the lower
bound value computed by Mosel).
Related topics
getlb, getub, loadprob, setub.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

749

mmxprs

setmipdir
Purpose
Synopsis

Set a directive on a variable or Special Ordered Set.
procedure setmipdir(x:mpvar,t:integer,r:real)procedure setmipdir(x:mpvar,t:integer)
procedure setmipdir(c:linctr,t:integer,r:real)procedure setmipdir(c:linctr,t:integer)

Argumentsxcrt

A decision variable
A linear constraint (of type SOS)
A real value
Directive type, which may be one of:
XPRS_PR
XPRS_UPXPRS_DN
XPRS_PU
XPRS_PD
XPRS_BRr is a priority (integer value between 1 and 1000 where 1 is the highest priority,
1000 the lowest)
Force up ﬁrst
Force down ﬁrst
r is an up pseudo costr is a down pseudo cost
Force branching even if satisﬁed

Further information
This procedure sets a directive on a global entity. Note that the priority value is converted into an
integer. The directives are loaded into the Optimizer at the same time as the problem itself.
Related topics
clearmipdir, readdirs, writedirs.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

750mmxprs

setmodcut
Purpose
Synopsis

Mark a constraint as a model cut.
procedure setmodcut(c:linctr)

Argumentc

A linear constraint

Further information
This procedure marks the given constraint as a model cut. The list of model cuts is sent to the
Optimizer when the matrix is loaded.
Related topics
clearmodcut.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

751

mmxprs

setsolPurpose
SynopsisDeﬁne the value associated to a decision variabe in a solution object.
procedure setsol(ms:mpsol,v:mpvar,s:real)

Argumentsmsv
s

A solution object
A decision variable
The solution value

Further information
This procedure associates a solution value to a decision variable in a solution object. If the variable isalready included in the solution, its value is replaced. Otherwise the solution is extended with the newvariable.
Related topics
getsol, savesol, savemipsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information752

mmxprs

setub
Purpose
Synopsis

Set the upper bound of a variable.
procedure setub(x:mpvar,r:real)

Argumentsxr

A decision variable
Upper bound value

Further information
This procedure changes the upper(lower) bound of a variable directly in the Optimizer, that is, the boundis modiﬁed in the problem that is currently loaded in the Optimizer but does not get recorded in the
problem deﬁnition held in Mosel. If the problem has not yet been loaded into the Optimizer then the
new bound value is ignored. Reloading the problem into the Optimizer after a call to setub(setlb) will
reset the upper (lower) bound for the variable to the value computed by Mosel, that is, the bound value
resulting from setub(setlb) is overwritten.
Related topics
getlb, getub, loadprob, setlb.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

753

mmxprs

setucbdata
Purpose
Synopsis

Update data to be returned to the Optimizer by the CHGBRANCH callback.
procedure setucbdata(x:mpvar, u:integer, e:real)procedure setucbdata(s:linctr, u:integer, e:real)procedure setucbdata(n:integer, u:integer, e:real)

Arguments
x
s
n
u

e

A decision variable
An SOS
A column or SOS number as provided by the optimizer
Direction for branching. Possible values:0
Upward branch made second (branch on column)
1
Upward branch made ﬁrst (branch on column)
2
Upward branch made second (branch on SOS)
3
Upward branch made ﬁrst (branch on SOS)
Estimated degradation at the node

Further information
This procedure stores the provided information that will be returned to the optimizer when the callback
terminates. This procedure cannot be called from outside of the CHGBRANCH callback.
Related topics
setcallback.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

754

mmxprs

stopoptimize
Purpose
SynopsisInterrupt the optimizer algorithms.
procedure stopoptimize(why:integer)

Argument
why

The reason for stopping. Possible reasons:
XPRS_STOP_TIMELIMIT
XPRS_STOP_CTRLC
XPRS_STOP_NODELIMIT
XPRS_STOP_ITERLIMIT
XPRS_STOP_MIPGAPXPRS_STOP_SOLLIMIT
XPRS_STOP_USER

Time limit hit
Control C hit
Node limit hit
Iteration limit hit
MIP gap is sufﬁciently small
Solution limit hit
User interrupt

Further information
This procedure can be called from any callback. It is ignored if used from outside an optimization
process.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

755

mmxprs

unloadprob
Purpose
Synopsis

Unload the problem held in the optimizer.
procedure unloadprob

Further information
1. This procedure "unloads" the optimizer by releasing all the resources it has allocated for its processing(internal representation, solution information, working ﬁles).
2. This procedure resets the control parameters XPRS_EXTRACOLS, XPRS_EXTRAROWS,
XPRS_EXTRAELEMS to their default values.
Related topics
maximize, minimize, loadprob.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

756

mmxprs

uselastbarsol
Purpose
Synopsis

Sets up the last barrier solve’s solution as the current one if one is available
function uselastbarsol:boolean

Return value
Operation status:
FALSE No barrier solution is available
TRUE The barrier solution is now the active solution
Further information
This fucntion allows to access the barrier solution before a crossover was performed. The solution,
solution status and objective are set up to match the barrier solution and are available the usual way.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

757

mmxprs

writebasis
Purpose
SynopsisWrite the current basis to a ﬁle.
procedure writebasis(fname:string,options:string)Arguments
fname
Extended ﬁle nameoptions String of options
Further information
This procedure writes the current basis to a ﬁle by calling the Optimizer function XPRSwritebasis.
Note that basis save/read procedures can be used only if the constraint and variable names have been
loaded into the Optimizer (parameter XPRS_loadnames set to true) and all constraints are named.
For more detail on the options and behavior of this procedure, refer to the Xpress Optimizer Reference
Manual.
Related topics
readbasis.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

758

mmxprs

writedirs
Purpose
SynopsisWrite current directives to a ﬁle.
procedure writedirs(fname:string)Argument
fname Extended ﬁle name
Further information
This procedure writes the current directives to a ﬁle using the Optimizer ﬁle format.
Related topics
clearmipdir, setmipdir, readdirs.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information759

mmxprs

writeprob
Purpose
SynopsisWrite the current problem to a ﬁle.
procedure writeprob(fname:string, options:string)procedure writeprob(fname:string, options:string, fnamed:string)Arguments
fname
Extended ﬁle name for the matrix
options String of format options (default: full precision)
fnamedExtended ﬁle name for the directives
ExampleLoad the current problem into the Optimizer and save it to an MPS ﬁle "mypb.mps" in hexadecimalformat (’x’) and to the ﬁle "mypb.lp" in LP format (’l’) using scrambled names (’s’):loadprob(myobj)
setparam("xprs_objsense",1) ! for 'minimize'writeprob("mypb.mps","x")writeprob("mypb.lp","ls")Further information
This procedure writes the current problem held in the Optimizer to a ﬁle by calling the Optimizer
function XPRSwriteprob and XPRSwritedirs if a ﬁle name for the directives is also speciﬁed. Notethat the matrix written by this procedure may be different from the one produced by exportprob since
it may include the effects of presolve or cuts generated by the Optimizer. For more detail on the options
and behavior of this procedure, refer to the Xpress Optimizer Reference Manual.
Related topics
exportprob, writedirs.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

760

mmxprs

writesol
Purpose
SynopsisWrite a solution to a ﬁle.
procedure writesol(fname:string,options:string)procedure writesol(ms:mpsol,sname:string,fname:string,options:string)Arguments
fname
optionsms
sname

Extended ﬁle name
String of options
A solution object
Solution name

Further information
1. When using the ﬁrst syntax this procedure writes the current solution to a ﬁle by calling the Optimizer
function XPRSwriteslxsol. For more detail on the options and behavior of this procedure, refer tothe Xpress Optimizer Reference Manual.
2. With the second syntax, the ﬁle is generated from a solution object. In this case, the solution name has
to be provided (default name is "solution") and the only supported option is "x" to output the
numbers in hexadecimal.
3. Solution save/read procedures can be used only if the constraint and variable names have been loaded
into the Optimizer (parameter XPRS_loadnames set to true) and all constraints are named.
Related topics
readsol.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

761

mmxprs

xor
Purpose
SynopsisCreate an exclusive or expression.
function xor(c1:log_or_linctr,c2:log_or_linctr):logctr

Argumentsc1
c2

A linear constraint (linctr) or logical expression (logctr)
A linear constraint (linctr) or logical expression (logctr)

Return value
A new logctr representing the expression.
ExampleThis example shows how to state an exclusive ’or’ constraint that expresses the disjunction between
two tasks with start time sj and ﬁxed duration Dj . A non-exclusive ’or’ relation can be stated by using theor operator as shown in the last line (constraint L).
declarations
R=1..2
C: array(range) of linctr
L: logctr
s: array(R) of mpvar
D: array(R) of real
end-declarations! Linear constraints! Logical constraint! Decision variables (start times)! Data (durations)C(1):= s(1)+D(1)>=s(2)C(2):= s(2)+D(2)>=s(1)! Define (temporary) linear constraints

xor(C(1), C(2))
forall(j in 1..2) C(j):=0! State an exclusive 'or'
! Delete the auxiliary constraints! The same 'xor' constraint can be stated by:xor(s(1)+D(1)>=s(2), s(2)+D(2)>=s(1))! A non-exclusive 'or' relation is stated by using the 'or' operator:
L:= s(1)+D(1)>=s(2) or s(2)+D(2)>=s(1)Further information
1. This function creates a logctr constraint representing an exclusive or condition: either c1 or c2 isvalid, not both.
2. The helper package ’advmod’ must be loaded if this function is used:
uses 'advmod'

Related topics
indicator, implies
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

762

mmxprs

19.4

Cut Pool Manager
This section contains the functions and procedures of the Xpress Optimizer cut manager. For adetailed description of the cut manager and its functionality the user is referred to the Xpress Optimizer
Reference Manual. To run the cut manager from Mosel, it may be necessary to (re)set certain control
parameters of the optimizer. For example, switching off presolve and automatic cut generation, andreserving space for extra rows in the matrix may be useful:setparam("XPRS_presolve", 0);! Switch presolve off...
setparam("XPRS_presolveops", 2270); ! ...or use secure setting for presolve
setparam("XPRS_cutstrategy", 0);! Switch automatic cut generation off
setparam("XPRS_extrarows", 5000);! Reserve space for 5000 extra rows in! the matrix

The callback functions and procedures that are relevant to the cut manager are initialized with function
setcallback, in common with the other Optimizer callbacks.
It should be noted that cuts are not stored by Mosel but sent immediately to the Optimizer.
Consequently, if a problem is reloaded into the Optimizer, any previously deﬁned cuts will be lost. In
Mosel, cuts are deﬁned by specifying a linear expression (i.e. an unbounded constraint) and theoperator sign (inequality/equality). If instead of a linear expression a constraint is given, it will also be
added to the system as an additional constraint.
addcut

Add a cut to the problem in the optimizer.

p. 764

addcuts

Add an array of cuts to the problem in the optimizer.

p. 765delcuts

Delete cuts from the problem in the optimizer.

p. 766

dropcuts

Drop a set of cuts from the cut pool.

p. 767

getcnlist

Get the set of cuts active at the current node.

p. 768getcplist

Get a set of cut indices from the cut pool.

p. 769loadcuts

Load a set of cuts into the problem in the optimizer.

p. 770storecutStore a cut into the cut pool.

p. 771storecuts

Store an array of cuts into the cut pool.

p. 772

Fair Isaac Corporation Conﬁdential and Proprietary Information

763

mmxprs

addcutPurpose
Synopsis

Add a cut to the problem in the optimizer.
procedure addcut(cuttype:integer, type:integer, linexp:linctr)

Arguments
cuttype Integer number for identiﬁcation of the cuttype
Cut type (equation/inequality), which may be one of:
CT_GEQ
Inequality (greater or equal)
CT_LEQ
Inequality (less or equal)
CT_EQ
Equality
linexpLinear expression (= unbounded constraint)
Further information
This procedure adds a cut to the problem in the Optimizer. The cut is applied to the current node and allits descendants.
Related topics
addcuts, delcuts.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

764

mmxprs

addcuts
Purpose
Synopsis

Add an array of cuts to the problem in the optimizer.
procedure addcuts(cuttype:array(range) of integer, type:array(range) ofinteger, linexp:array(range) of linctr)

Arguments
cuttype Array of integer number for identiﬁcation of the cuts
type
Array of cut types (equation/inequality):
CT_GEQ
Inequality (greater or equal)
CT_LEQ
Inequality (less or equal)
CT_EQ
Equality
linexpArray of linear expressions (= unbounded constraints)
Further information
This procedure adds an array of cuts to the problem in the Optimizer. The cuts are applied to thecurrent node and all its descendants. Note that the three arrays that are passed as parameters to thisprocedure must have the same index set.
Related topics
addcut, delcuts.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

765mmxprs

delcuts
Purpose
Synopsis

Delete cuts from the problem in the optimizer.
procedure delcuts(keepbasis:boolean, cuttype:integer,interpret:integer,delta:real, cuts:set of integer)
procedure delcuts(keepbasis:boolean, cuttype:integer, interpret:integer,delta:real)

Arguments
keepbasis
cuttypeinterpret

delta
cuts

false
Cuts with non-basic slacks may be deleted
true
Ensures that the basis will be valid
Integer number for identiﬁcation of the cut(s)The way in which the cut type is interpreted:-1
Delete all cuts
1
Treat cut types as numbers
2
Treat cut types as bitmaps (delete cut if any bit matches any bit set in
cuttype)3
Treat cut types as bitmaps (delete cut if all bits match those set in
cuttype)
Only delete cuts with an absolute slack value greater than delta. To delete all the cuts
set this parameter to a very small value (e.g. -MAX_REAL)
Set of cut indices, if not speciﬁed all cuts of type cuttype are deleted

Further information
This procedure deletes cuts from the problem loaded in the Optimizer. If a cut is ruled out by any of thegiven criteria it will not be deleted.
Related topics
addcut, addcuts.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

766

mmxprs

dropcuts
Purpose
Synopsis

Drop a set of cuts from the cut pool.
procedure dropcuts(cuttype:integer, interpret:integer, cuts:set of integer)
procedure dropcuts(cuttype:integer, interpret:integer)

Arguments
cuttypeinterpret

cuts

Integer number for identiﬁcation of the cut(s)The way in which the cut type is interpreted:-1
Drop all cuts
1
Treat cut types as numbers
2
Treat cut types as bitmaps (delete cut if any bit matches any bit set in
cuttype)3
Treat cut types as bitmaps (delete cut if all bits match those set in
cuttype)Set of cut indices in the cut pool, if not speciﬁed all cuts of type cuttype are deleted

Further information
This procedure drops a set of cuts from the cut pool. Only those cuts which are not applied to active
nodes in the branch-and-bound tree will be deleted.
Related topics
storecut, storecuts.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

767

mmxprs

getcnlist
Purpose
Synopsis

Get the set of cuts active at the current node.
procedure getcnlist(cuttype:integer,interpret:integer, cuts:set of integer)

Arguments
cuttypeinterpret

cuts

Integer number for identiﬁcation of the cut(s), -1 to return all active cuts
The way in which the cut type is interpreted:-1
Get all cuts
1
Treat cut types as numbers
2
Treat cut types as bitmaps (get cut if any bit matches any bit set in
cuttype)3
Treat cut types as bitmaps (get cut if all bits match those set in cuttype)Set of cut indices

Further information
This procedure gets the set of active cut indices at the current node in the Optimizer. The set of cut
indices is returned in the parameter cuts.
Related topics
getcplist.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

768

mmxprs

getcplist
Purpose
Synopsis

Get a set of cut indices from the cut pool.
procedure getcplist(cuttype:integer,interpret:integer,delta:real, cuts:setof integer,viol:array(range) of real)

Arguments
cuttypeinterpret

delta
cuts
viol

Integer number for identiﬁcation of the cut(s)The way in which the cut type is interpreted:-1
Get all cuts
1
Treat cut types as numbers
2
Treat cut types as bitmaps (get cut if any bit matches any bit set in
cuttype)3
Treat cut types as bitmaps (get cut if all bits match those set in cuttype)
Only return cuts with an absolute slack value greater than deltaSet of cut indices in the cut pool
Array where the slack variables for the cuts will be returned

Further information
This procedure gets a set of cut indices from the cut pool. The set of indices is returned in theparameter cuts.
Related topics
getcnlist.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

769

mmxprsloadcuts
Purpose
Synopsis

Load a set of cuts from the cut pool into the problem in the optimizer.
procedure loadcuts(cuttype:integer, interpret:integer, cuts:set of integer)
procedure loadcuts(cuttype:integer, interpret:integer)

Arguments
cuttypeinterpret

cuts

Integer number for identiﬁcation of the cut(s)The way in which the cut type is interpreted:-1
Load all cuts
1
Treat cut types as numbers
2
Treat cut types as bitmaps (load cut if any bit matches any bit set in
cuttype)3
Treat cut types as bitmaps (load cut if all bits match those set in cuttype)Set of cut indices in the cut pool, if not speciﬁed all cuts of type cuttype are loaded

Further information
This procedure loads a set of cuts into the Optimizer. The cuts remain active at all descendant nodes.
Related topics
storecut, storecuts.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

770mmxprs

storecut
Purpose
SynopsisStore a cut into the cut pool.
function storecut(nodupl:integer, cuttype:integer, type:integer,
linexp:linctr):integer

Arguments
noduplFlag indicating how to deal with duplicate entries:
0
No check1
Check for duplicates among cuts of the same cut type2
Check for duplicates among all cuts
cuttype Integer number for identiﬁcation of the cuttype
Cut type (equation/inequality):
CT_GEQ
Inequality (greater or equal)
CT_LEQ
Inequality (less or equal)
CT_EQ
Equality
linexpLinear expression (= unbounded constraint)

Return value
Index number of the cut stored in the cut pool.
Further information
This function stores a cut into the cut pool without applying it to the problem at the current node. The
cut has to be loaded into the problem with procedure loadcuts in order to become active at thecurrent node.
Related topics
dropcuts, loadcuts, storecuts.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information771

mmxprs

storecuts
Purpose
SynopsisStore an array of cuts into the cut pool.
procedure storecuts(nodupl:integer, cuttype:array(range) of integer,
type:array(range) of integer,
linexp:array(range) of linctr,
ndx_a:array(range) of integer)
procedure storecuts(nodupl:integer, cuttype:array(range) of integer,
type:array(range) of integer,
linexp:array(range) of linctr,
ndx_s:set of integer)

Arguments
noduplFlag indicating how to deal with duplicate entries:
0
No check1
Check for duplicates among cuts of the same cut type2
Check for duplicates among all cuts
cuttype Array of integer number for identiﬁcation of the cuts
type
Array of cut types (equation/inequality):
CT_GEQ
Inequality (greater or equal)
CT_LEQ
Inequality (less or equal)
CT_EQ
Equality
linexpArray of linear expressions (= unbounded constraints)
ndx_aInterval of index numbers of stored cuts
ndx_s
Set of index numbers of stored cuts

Further information
This function stores an array of cuts into the cut pool without applying them to the problem at thecurrent node. The cuts have to be loaded into the problem with procedure loadcuts in order tobecome active at the current node. The cut manager returns the indices of the stored cuts in the formof an array ndx_a or a set of integers ndx_s. Note that the four arrays that are passed as parameters
to this procedure must have the same index set.
Related topics
dropcuts, loadcuts, storecut.
ModulemmxprsFair Isaac Corporation Conﬁdential and Proprietary Information

772

CHAPTER 20

python3
The python3 module makes it possible to easily exchange data with Python 3 and execute Python 3
scripts.
Python is an interpreted programming language for general-purpose programming that has also
become popular for scientiﬁc and numeric computing. The reference implementation (CPython) isavailable as Free Software under the terms of the Python Software Foundation License, which iscompatible with the GNU General Public License.
To use this module, the following line must be included in the header of the Mosel model ﬁle:uses "python3"

20.1

Introduction
This module implements functionality for exchanging data between a Mosel model and Python 3(CPython) and for calling Python 3 scripts.
The python3 module deﬁnes an I/O driver for exchanging data using the initializations fromand initializations to Mosel constructs.
It is the Mosel run-time library that loads and runs the Python interpreter, not the other way round.
The purpose of the module is to make the extensive scientiﬁc and numeric capabilities of Python
available from Mosel. This module does not implement an interactive Python shell. However, theinteraction of the Mosel model and the Python interpreter is similar to an interactive shell: transferring
data to Python and executing Python scripts changes the state of the interpreter.

20.1.1

Prerequisites
This module does not include Python binaries. In order to use Python you need a working installation of
Python 3 targeting the same platform as Mosel (you won’t be able to use, e.g., the Windows 32-bit
version of Python from the Windows 64-bit version of Mosel). The supported Python versions are 3.4.3
to 3.7.5. Version 3.8.0 is not supported. It is recommended to download and install the Anaconda
Python distribution from www.anaconda.com. Alternatively, Python binaries for Windows and Mac OS
are also available at www.python.org. On Linux, Python 3 is most likely part of your distribution andprovided in a package called "python3" that can be installed via the package manager. Note that Python
3 is not part of the Red Hat Enterprise Linux 7 standard repository. In order to use the latest Python
release on Linux, we recommend to download the latest Anaconda Python distribution for Linux fromthe Anaconda website.
The Mosel module python3 tries to automatically locate the correct Python libraries on your system,
applying the following rules. If the environment variable PYTHONHOME is speciﬁed, it will load thelibraries of the Python installation in that directory. Otherwise, it searches for the Python executable inthe directories speciﬁed in the PATH environment variable. If the Python executable has been found, theFair Isaac Corporation Conﬁdential and Proprietary Information773

python3

module will try to load the libraries of the Python installation of that Python executable. If the libraries
could not be loaded with the help of the environment variables, then on Windows they are loaded fromthe latest Python installation speciﬁed in the registry (keys: HKEY_CURRENT_USER andHKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\3.⁎\InstallPath). If the previous
steps failed, then the python3 module will load the most recent libraries from the standard library searchpaths. On Windows it looks for python3⁎.dll and python3.dll, on Linux for libpython3.⁎m.so
and libpython3.so, and on Mac OSX for libpython3.⁎m.dylib and libpython3.dylib.
If you have multiple installations of Python, or if Python could not be located automatically, or if theinitialization of Python fails, you will need to set the environment variable PYTHONHOME to point to yourPython installation directory or set PATH to include the location of the Python executable.
Note that the loading of Python is not inﬂuenced by Mosel statements like
setparam("workdir",...) or setenv("PYTHONHOME",...) in the Mosel model that uses the
Python module since these don’t affect the process environment used for Python loading. The
environment variables must be set before launching the Mosel instance that serves for executing
Python scripts in order to inﬂuence the loading of Python.
As an example, if Python 3.7.0 is installed on Windows in "C:\opt\python370" then this directory
is also the correct value for the PYTHONHOME environment variable or alternatively, add this directory to
the PATH environment variable.
The module supports the conversion between Mosel types and pandas and NumPy types. The
supported pandas versions are 0.19.2 to 0.25.2 and the supported NumPy versions are 1.11.3 to 1.17.3.

20.1.2

Windows Anaconda Setup
Set the PYTHONHOME system environment variable to the base directory of Anaconda or to the home
directory of a speciﬁc Anaconda environment, e.g., C:\opt\anaconda3\envs\py373. The NumPy
module that ships with Anaconda requires the Math Kernel Library (MKL). It is necessary to add%PYTHONHOME%\Library\bin

to the PATH system environment variable such that NumPy can ﬁnd the DLLs of that library. If NumPy
cannot ﬁnd the library, the import of NumPy and pandas will fail with an error message similar to:
Traceback ...
from . import _mklinit
ImportError: DLL load failed: The specified module could not be found.

If you change the system environment variables, then it is necessary to restart the Insight Execution
Worker and Workbench such that the changes take effect. Note that if you run an Insight Execution
Worker on the same machine, it will only pass the system environment variables to the Insight app, but
the user environment variables of your local user will not be applied in Insight apps, because the server
runs as a different user.

20.1.3

Linux Anaconda Setup
Set the PYTHONHOME environment variable to the base directory of Anaconda or to the home directoryof a speciﬁc Anaconda environment, e.g., /opt/anaconda3/envs/py373. The pandas module thatships with Anaconda may require a version of the C++ standard library which is more recent than the
one that ships with your operating system. The required library ships with Anaconda and the loading ofthat library can be forced by adding$PYTHONHOME/lib/libstdc++.soto the LD_PRELOAD environment variable. If an incompatible version gets loaded, then the initialization

Fair Isaac Corporation Conﬁdential and Proprietary Information774

python3of pandas will fail with an error message similar to:ImportError: /lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found20.1.4

Python initialization
The Python environment is automatically initialized at the point where a Mosel model uses for the ﬁrst
time any function that requires it. So we can have the following small example that just executes a
Python script:
model "Python script example"
uses "python3"
pyrun("my-python-script.py")
end-model

Alternatively it is possible to explicitly initialize Python using the pyinit function. If the initialization
fails, activate additional logging by setting the parameter pyinitverbose to true before initializing
Python and double check the values of your environment variables (see previous sections).
At the end of the model execution, the Python environment will automatically be released. It is also
possible to explicitly release the environment using pyunload. This can be useful for freeing
resources allocated by Python.
It is only possible to initialize one Python interpreter per Mosel instance. For that reason it is notpossible to initialize and use the Python interpreter in two models in parallel if both models are run in
the same Mosel instance. However, you can initialize and use multiple interpreters in concurrent
models if each model is run in a separate Mosel instance.

20.1.5

Data types
The types of data that can be exchanged with Python are the Mosel types boolean, integer, real,
string and text, plus arrays, lists and sets of these. Nested compositions are supported. Mosel lists
and sets are exported to Python lists and sets. Both, dense and sparse Mosel arrays are supported andby default they are mapped to dictionaries of the corresponding element type. If the pandas interface isinitialized, then arrays and lists of arrays can also be mapped to pandas Series and DataFrames.
Moreover, Mosel arrays can be initialized from NumPy ndarrays and Mosel scalars be initialized from
NumPy scalars (see pyinitpandas and pyusepandas for more details).
The following example shows how to invert a matrix with NumPy:
declarations
I, J: range
A, A_inverse: array(I, J) of real
end-declarations
writeln("Run Python script that defines invert_matrix function.")pyinitpandas
pyrun("invert_matrix.py")
I := 0..2
J := 0..2
A :: [1,0,3,
0,1,2,
0,0,1]
writeln("Invert matrix with NumPy.")
pycall("invert_matrix", A_inverse, A)
writeln("Matrix A_inverse:")writeln("A_inverse: ", A_inverse)

Fair Isaac Corporation Conﬁdential and Proprietary Information775

python3

At the beginning of this code snippet the pandas interface is initialized via a call to pyinitpandas.
This enables the conversion of Mosel arrays from and to pandas Series and from NumPy arrays fromthis point onwards—this statement will typically occur at the beginning of the program, but standard
python3 functionality can already be used before to it. After the pandas initialization a Python example
script in a separate ﬁle invert_matrix.py is executed, which deﬁnes the invert_matrix Python
function. This function is then invoked via the pycall procedure. The ﬁrst parameter of this procedureis the Python function name, the second one is the Mosel array that will be used for storing the result,and the last parameter is the input parameter for the Python function. The Python function takes apandas Series with a two-dimensional MultiIndex as input and returns a two-dimensional NumPy
ndarray:
def invert_matrix(series):# Get pivot table of MultiIndex Series as DataFrame.
df = series.unstack()# Compute and return inverse matrix as NumPy ndarray.
return inv(df)

See the model invert-matrix.mos for a full example. At ﬁrst, the function creates a pivot table ofthe MultiIndex Series, such that the resulting DataFrame looks like a two-dimensional matrix. Thismatrix-like DataFrame is used as an input value for the NumPy inv function, which returns a
two-dimensional ndarray, which is then passed to Mosel.
Note that sparse Mosel arrays are exported to sparse Python dictionaries or pandas Series. In thisexample, the Mosel matrix A is dense, hence the pandas Series is also dense, that is, for each index
tuple (i, j) in the cross product of I and J the pandas Series has a value.
When initializing a Mosel array, list, or set from a Python type, the initialization of the Mosel type isadditive, which means that the elements of the Python type are added to the existing Mosel array, list,or set. In the example above, the pandas Series is dense such that all elements of the Mosel array will
be overwritten. However, if the pandas Series (or dictionary) is sparse and the Mosel array is non-zero,
it is necessary to manually clear its contents before initializing it with values from the sparse Python
type. In that situation, the Mosel array should be cleared with reset. See Section 20.5.1 for an example
with a sparse array and reset: io_example.mos.

20.2

Xpress Insight conﬁguration
The python3 module can only be used when Mosel restrictions are disabled (MOSEL_RESTR=0). Whenthe restrictions are disabled, any executed Mosel and Python code have the same rights (in particularfor ﬁle system access) as the operating system user that runs the Insight Execution Worker. In order to
use the python3 module in an Insight app, it is necessary to relax the Mosel restrictions in the Insight
Execution Worker conﬁguration ﬁle (xprmsrv.cfg). After relaxing the Mosel restrictions, we strongly
recommend that the Insight administrator makes sure of the following points:








The operating system user that runs the Insight Execution Worker should only be granted theminimal rights that are necessary for running the Insight app.
Access to the workers should be protected by a password and additionally by IP ﬁlters (see theexample extract of the conﬁguration ﬁle xprmsrv.cfg below).
If the network is not trusted, the workers should only accept SSH connections: Set TCP_PORT=-1(conﬁgurable via xprmsrv.cfg) and use xssh instead of the xsrv protocol (Execution Worker
conﬁguration in the Insight admin interface).
Only trusted users should be granted the right to upload trusted Insight apps to the Insight Server.

And the Insight app developer needs to address the following points:

Fair Isaac Corporation Conﬁdential and Proprietary Information776

python3

The app should not execute any untrusted Python scripts that an end user may have uploaded as
an app attachment (see pyrun function).
The app should not concatenate untrusted strings entered by the end user (e.g. Insight scalars orarrays) into a Python evaluation string, because this could allow an attacker to inject and executecustom Python code. For example, the ﬁrst function input parameter of pycall, pyexec andpyget is a Python evaluation string. Note that it is safe to transfer untrusted data between Mosel
and Python variables. The developer just needs to avoid using untrusted strings directly in a
Python evaluation string parameter.

If the Insight Execution Worker runs on the same machine as the Insight Server, it is recommended tomodify the conﬁguration settings in xprmsrv.cfg as follows:...
XPRMSRV_ACCESS=+127.0.0.1[insight]
PASS=my_password
MOSEL_RESTR=0
PYTHONHOME=C:\opt\anaconda3
PATH=${PYTHONHOME}\Library\bin;${PATH}...

Restart the Execution Worker after changing the conﬁguration ﬁle. Then log into the Insight admininterface, go to Execution Services, edit the Execution Worker, enter the password in the password edit
ﬁeld and save the changes.
Depending on your system conﬁguration, the PYTHONHOME environment variable is optional. The PATH
entry is only necessary for Anaconda on Windows. You can also specify the PYTHONHOME and PATH
environment variables as system environment variables. Note that it is not sufﬁcient to specify themfor your personal user account, because the Insight service runs as a different user.

20.3

Control parameters
The following parameters are deﬁned by the module python3:
pyinitverbose

Show additional log messages when initializing Python.

p. 777pyusepandas

Enable and control pandas and NumPy conversion.

p. 778pyinitverbose
Description

Set this parameter to true to activate some additional logging of how the module looks forand ﬁnds your Python environment. The log messages are written to the model’s output
stream.

Type

Boolean, read/write

Default value

false

See also

pyinit, pyinitpandas

Modulepython3Fair Isaac Corporation Conﬁdential and Proprietary Information

777

python3

pyusepandas
Description

If this parameter is true, then the next usage of any Python functionality will trigger the
initialization of the pandas interface. When the interface is initialized, Mosel scalars can also
be initialized from NumPy scalars, arrays can also be initialized from NumPy ndarrays andpandas Series, and lists of arrays can be initialized from pandas DataFrames. Once initialized,
the pandas interface will remain initialized even after switching pyusepandas off. In
particular, it will still be possible to initialize Mosel types from pandas and NumPy types.
When converting data from Mosel to Python, the target type depends on the value of
pyusepandas: When the parameter is true, Mosel arrays and lists of arrays are converted
to pandas Series and DataFrames; when it is false, then Mosel arrays will be converted to
Python dictionaries. Mosel lists of arrays cannot be initialized to a Python type when thisparameter is disabled.

Type

Boolean, read/write

Default value

false

See also

pyinitpandas, Driver python

Modulepython3

20.4

Procedures and functions
The procedures and functions of the python3 module fail in case of Python compile-time or run-timeerrors.
pycallCall a Python object, a function, with optional input arguments and convert
the result to a Mosel variable.
p. 779pyexecExecute Python statements from a string.

p. 781pyget

Get the result of a Python expression as Mosel variable.

p. 782

pygetdf

Initialize a list of Mosel arrays from the columns of a pandas DataFrame.
p. 783pyinitInitialize the Python interpreter.

pyinitpandas

Set pyusepandas parameter to true and initialize the pandas interface.
p. 786pyrun

Run a Python script and wait until it is ﬁnished.

p. 787pyset

Assign a Mosel value to a global Python variable.

p. 788pysetdf

Convert a list of Mosel arrays to a pandas DataFrame.

p. 789pyunload

Release the Python interpreter and its resources.

p. 790Fair Isaac Corporation Conﬁdential and Proprietary Information

p. 785778

python3

pycallPurpose

SynopsisCall a Python object, e.g. a function, with optional input arguments and convert the result to a Mosel
variable.
procedure pycall(expr:string,result:array|set|list[, arg1...])
procedure pycallvoid(expr:string[, arg1...])
function pycallbool(expr:string[, arg1...]):booleanfunction pycallint(expr:string[, arg1...]):integerfunction pycallreal(expr:string[, arg1...]):realfunction pycallstr(expr:string[, arg1...]):string
function pycalltext(expr:string[, arg1...]):text

Arguments
expr

Global name of a callable Python object or Python expression that evaluates to a
callable object
resultResult Mosel array, set or list
arg1, arg2,... Optional input arguments for the object call

Example 1
The following example calls the Python print and max functions. The Mosel input arguments areautomatically converted to Python objects and the return value of max is converted to a Mosel real.
pycallvoid("print", "Python objects:", true, 1, 2.2, [3,4], {5})writeln("max: ", pycallreal("max", [1.1, 7.7, 4.4]))
Example 2
The following example uses pandas to compute the mean value of two Mosel arrays. The Mosel input
arrays are passed as a single list of arrays with compatible array indices and are automaticallyconverted to a single pandas DataFrame. The return value of the mean function is a pandas Series andits elements will be written to the Mosel Result array.
declarations
Input1, Input2, Result: array(range) of real
end-declarations
Input1 :: (0..4)[1, 2, 3, 4, 5]
Input2 :: (0..4)[7, -1, -3, 1, 2]
pyinitpandas
pyexec("def mean(df, axis): return df.mean(axis)")pycall("mean", Result, [Input1, Input2], 1)
writeln("mean: ", Result)
It is recommended to deﬁne small global wrapper functions like in this example, instead of calling
functions or methods with the help of an expression like "pandas.Series.mean". The global
function can be found directly without having to perform an expensive Python string evaluation to
retrieve the callable object.

Fair Isaac Corporation Conﬁdential and Proprietary Information779

python3

Further information
1. At ﬁrst, the function interprets the expression string as a global Python object name and tries to accessit by getting it from the attributes of the Python __main__ module. If this fails, the expression isevaluated by Python. Then the expression result object will be called with the optional input arguments.
Finally, the result of the object call is stored in or returned as a Mosel variable. This is equivalent to the
Python expression:
expr(arg1, ...)
It is a fatal error if the expression cannot be evaluated or if the object call or the type conversion
between Python and Mosel fails.
2. The ﬁrst version of the pycall routine stores the result in an array, set or list. Its behavior is additive: itwrites the new elements to the existing Mosel array, set or list without clearing previously existingelements. Use reset to manually clear an array, set or list before calling this function.
3. See the I/O Driver python Section for further details about type conversions.
4. Do not concatenate untrusted strings from the end user into the expr string. See Section Xpress
Insight conﬁguration for more information.
Related topics
pyexec, pyget, Driver python

Fair Isaac Corporation Conﬁdential and Proprietary Information780

python3

pyexecPurpose
Synopsis

Execute Python statements from a string.
procedure pyexec(code:string)Argumentcode
ExamplePython statements to execute

The following model runs Python statements from a string:model "Python script from string"uses "python3"
writeln("Python version:")pyexec("import platform; print(platform.python_version())")
end-model

Further information
1. This function compiles and runs a Python script from a string buffer and waits for its termination. It is a
fatal error if the compilation fails or if a Python run-time error occurs.
2. Use the I/O Driver python and the functions pyget and pyset to transfer data between Mosel andPython. Use pyget to evaluate a single expression with return value and use pycall to call a single
function with input arguments or return value.
3. Do not concatenate untrusted strings from the end user into the code string. See Section Xpress
Insight conﬁguration for more information.
Related topics
pycall, pyget, pyrun, Driver python

Fair Isaac Corporation Conﬁdential and Proprietary Information

781

python3

pyget
Purpose
Synopsis

Get the result of a Python expression as Mosel variable.
procedure pyget(expr:string,var:array|set|list)
function pygetbool(expr:string):booleanfunction pygetint(expr:string):integerfunction pygetreal(expr:string):realfunction pygetstr(expr:string):string
function pygettext(expr:string):text

Arguments
expr
var
ExamplePython expression to evaluate
Destination Mosel array, set or list

The following example evaluates a Python dictionary expression and writes the result to a Mosel array.
It then retrieves a real value from Python:declarations
Arr: dynamic array(set of integer) of real
end-declarations
pyexec("import math")
Arr(0) := 0.1; Arr(1) := 1.1! Old array data
reset(Arr)! Clear old array data
pyget("{1: math.pi, 2: math.e}", Arr) ! Add new data to arraywriteln("Arr: ", Arr)writeln("pi: ", pygetreal("math.pi"))

Further information
1. At ﬁrst, the function interprets the expression as a global variable name and tries to access the variable
by getting it from the attributes of the Python __main__ module. If this fails, the expression isevaluated by Python and the result is written to or returned as a Mosel variable. It is a fatal error if theexpression evaluation or the type conversion fails.
2. The ﬁrst version of the pyget routine is additive: it writes the new elements to the existing Mosel array,set or list without clearing previously existing elements. Use reset to manually clear an array, set orlist before calling this function.
3. See the I/O Driver python Section for further details about type conversions. Use pycall to call asingle function with input arguments or return value.
4. Do not concatenate untrusted strings from the end user into the expr string. See Section Xpress
Insight conﬁguration for more information.
Related topics
pycall, pygetdf, pyset, Driver python

Fair Isaac Corporation Conﬁdential and Proprietary Information782

python3

pygetdf
Purpose
Synopsis

Initialize a list of Mosel arrays from the columns of a pandas DataFrame.
procedure pygetdf(expr:string,result:list of array)procedure pygetdf(expr:string,result:list of array,labels:list of string)Arguments
expr
resultlabelsExamplePython expression that evaluates to a pandas DataFrame
Mosel list of arrays to be initialized from pandas DataFrame
Labels of the pandas DataFrame columns used for initialization

In this example, two Mosel arrays with the same index sets are initialized from a DataFrame. With theﬁrst call to pygetdf, the arrays are initialized based on the order of the DataFrame columns, with thesecond they are initialized using column labels.
declarations
I, J: set of integer
Numbers: dynamic array(I, J) of integer
Labels: dynamic array(I, J) of string
end-declarations
pyinitpandas
pyexec(`import pandas as pd
df = pd.DataFrame(
data=[[11, "eleven"], [23, "twenty-three"], [42, "forty-two"]],index=pd.MultiIndex.from_tuples([(1, 1), (2, 3), (4, 2)]),columns=["number", "label"])print(df)`)
pygetdf("df", [Numbers, Labels])
writeln("I: ", I, "\nJ: ", J)
writeln("Numbers: ", Numbers, "\nLabels:", Labels)

reset(Numbers); reset(Labels)
pygetdf("df", [Labels, Numbers], ["label", "number"])
writeln("Numbers: ", Numbers, "\nLabels: ", Labels)

Fair Isaac Corporation Conﬁdential and Proprietary Information783

python3

Further information
1. The ﬁrst version of the procedure initializes the arrays based on the order of the DataFrame columns.
The second version uses column labels to select the DataFrame columns that are used for the
initialization.
2. At ﬁrst, the procedure interprets the expression as a global variable name and tries to access thevariable by getting it from the attributes of the Python __main__ module. If this fails, the expression isevaluated by Python and the result is used for the Mosel array initialization. It is a fatal error if theexpression evaluation or the type conversion fails.
3. The initialization of the result arrays is additive: new elements are written to the existing arrays without
clearing previously existing elements. Use reset to manually clear the arrays before calling thisprocedure.
4. DataFrame conversion is supported in all module functions that accept lists of arrays. In particular, it is
supported by pycall and the I/O Driver python .
5. Do not concatenate untrusted strings from the end user into the expr string. See Section Xpress
Insight conﬁguration for more information.
Related topics
pyget, pysetdf, pyinitpandas

Fair Isaac Corporation Conﬁdential and Proprietary Information784

python3

pyinitPurpose
Synopsis
ExampleInitialize the Python interpreter.
procedure pyinit
The following example initializes Python:pyinitFurther information
1. The use of this procedure is optional: Python is automatically initialized upon ﬁrst use.
2. You can only initialize one Python interpreter per Mosel instance. The initialization will fail if you attempt
to initialize two interpreters in the same Mosel instance. Use pyunload to release the interpreter andits resources. The interpreter cannot be reinitialized in the same Mosel instance after unloading it.
3. In order to use multiple interpreters in parallel, it is necessary to create a new Mosel instance for each
additional interpreter. Use the connect function from the mmjobs module to create a new instance.
4. If the initialization of Python fails, activate additional logging by setting the parameter
pyinitverbose to true before initializing Python, double check the values of your environment
variables (see the Introduction section) and check the Troubleshooting section.
Related topics
connect, pyinitverbose, pyinitpandas, pyunload

Fair Isaac Corporation Conﬁdential and Proprietary Information785

python3

pyinitpandas
Purpose
Synopsis
ExampleSet pyusepandas parameter to true and initialize the pandas interface.
procedure pyinitpandas
The following example ﬁrst prints a Mosel array as Python dictionary and then initializes the pandas
interface and prints the array as pandas Series:
declarations
A: array(range) of real
end-declarations
A :: (-1..2)[-1.1, 0, 1.1, 2.2]
pycallvoid("print", "A as Python dict:\n", A)
pyinitpandas
pycallvoid("print", "A as pandas Series:\n", A)

Further information
1. This procedure is equivalent to the following two commands:
setparam("pyusepandas", true)
pyinitSee the documentation of pyusepandas and pyinit for further information. The I/O Driver python
section provides an overview of the additionally available type mappings after having initialized the
pandas interface.
2. At ﬁrst, the procedure sets the parameter pyusepandas to true, then it initializes the Python interpreter
if it has not yet been initialized and ﬁnally it initializes the pandas interface if it has not yet been
initialized. Once initialized, the pandas functionality will continue to be available even after switching
pyusepandas off. See pyusepandas for more information.
Related topics
pyinit, pyinitverbose, pyunload, pyusepandas, Driver python

Fair Isaac Corporation Conﬁdential and Proprietary Information786

python3

pyrun
Purpose
Synopsis

Run a Python script and wait until it is ﬁnished.
procedure pyrun(filename:string)Argument
filename Regular ﬁle name of a Python script
ExampleThe following model runs a Python script:
model "Python script example"
uses "python3"
pyrun("my-python-script.py")
end-model

Further information
1. The function compiles and runs a Python script and waits for its termination. It is a fatal error if thecompilation fails or if a Python run-time error occurs.
2. Use the I/O Driver python and the functions pyget and pyset to transfer data between Mosel andPython.
3. Do not run untrusted scripts, e.g., scripts provided by the end user. See Section Xpress Insight
conﬁguration for more information.
Related topics
pycall, pyexec, Driver python

Fair Isaac Corporation Conﬁdential and Proprietary Information787

python3

pyset
Purpose
Synopsis

Assign a Mosel value to a global Python variable.
procedure
pyset(varname:string,var:boolean|integer|real|string|text|array|list|set)

Arguments
varname Global Python variable namevar
Mosel value to be assigned to Python variable
ExampleThe following example writes a Mosel array to a Python dictionary and a Mosel list to a Python list:
declarations
MosArray: array(set of string) of real
end-declarations
pyset('py_list', [1, 2, 3])! Mosel list -> Python list.
pyexec('print("py_list:", py_list)')MosArray('e') := M_E; MosArray('pi') := M_PI
setparam('pyusepandas', false) ! Mosel array -> Python dictionary.
pyset('py_dict', MosArray)pyexec('print("py_dict:", py_dict)')
setparam('pyusepandas', true) ! Mosel array -> Pandas Series.
pyset('pd_series', MosArray)pyexec('print("pd_series:", pd_series, sep="\n")')Further information
1. The procedure creates or overwrites the global variable by writing the new value to the attributes of the
Python __main__ module. If the variable name is not a valid Python variable identiﬁer the procedure
will succeed anyway and write the value to the module attributes using the name speciﬁed in varname.
2. The procedure replaces previously existing global variables. It does not update or add data to existing
Python structures.
3. See the I/O Driver python Section for more details about type conversions.
Related topics
pyget, pyexec, pysetdf, pyusepandas, Driver python

Fair Isaac Corporation Conﬁdential and Proprietary Information788

python3

pysetdf
Purpose
Synopsis

Convert a list of Mosel arrays to a pandas DataFrame.
procedure pysetdf(varname:string,input:list of array)procedure pysetdf(varname:string,input:list of array,labels:list of string)Arguments
varname Global Python variable name for the new DataFrame
input
Mosel list of arrays to be converted to the DataFramelabelsLabels for the DataFrame columns
ExampleIn this example, two Mosel arrays with the same index sets are converted to a DataFrame. With the ﬁrst
call to pysetdf, a DataFrame is created with integer column labels and the second creates a
DataFrame with string column labels.
declarations
I, J: set of integer
Numbers: dynamic array(I, J) of integer
Labels: dynamic array(I, J) of string
end-declarations
pyinitpandas
Numbers(1,1) := 11;
Numbers(2,3) := 23;
Numbers(4,2) := 42;

Labels(1,1) := "eleven"Labels(2,3) := "twenty-three"Labels(4,2) := "forty-two"writeln("Integer column labels:")
pysetdf("df", [Numbers, Labels])
pyexec("print(df)")
pysetdf("df", [Numbers, Labels], ["number", "label"])writeln("\nString column labels:")
pyexec("print(df)")
Further information
1. The ﬁrst version of the procedure creates a new DataFrame with numbers as column labels and thesecond version uses the provided string column labels.
2. The procedure creates or overwrites the global variable by writing the new value to the attributes of the
Python __main__ module. If the variable name is not a valid Python variable identiﬁer the procedure
will succeed anyway and write the value to the module attributes using the name speciﬁed in varname.
3. The procedure replaces previously existing global variables. It does not update or add data to existing
Python structures.
4. DataFrame conversion is supported in all module functions that accept lists of arrays. In particular, it is
supported by pycall and the I/O Driver python .
Related topics
pygetdf, pyset, pyinitpandas

Fair Isaac Corporation Conﬁdential and Proprietary Information789

python3

pyunloadPurpose
Synopsis
ExampleRelease the Python interpreter and its resources.
procedure pyunload
The following example releases the Python interpreter:
pyunload

Further information
1. The use of this procedure is optional: the Python interpreter is automatically released at the end of amodel execution. However, you may prefer to release it sooner to free resources allocated by Python.
2. After unloading the interpreter it cannot be reinitialized in the same Mosel instance. This is due to a bug
in Python’s ﬁnalization function and its extension modules. For example, NumPy and pandas do notwork after reinitializing the interpreter in the same process, i.e., in the same Mosel instance. See
https://docs.python.org/3/c-api/init.html#c.Py_FinalizeEx andhttps://github.com/numpy/numpy/issues/8097 for more details.
Related topics
pyinitFair Isaac Corporation Conﬁdential and Proprietary Information790

python3

20.5

I/O drivers
The python3 module provides a driver that is designed to be used in initializations blocks forboth reading data from and writing data to Python.

20.5.1

Driver python
python:optional_module_name

The driver can only be used in ‘initializations’ blocks. The optional string after the colon is the Python
module name to read the data from or write the data to. If a module name is provided, then the optional
item labels are understood as attribute names of the speciﬁed module. Initializing data to, for example,"python:client_data" will create a new module called client_data. To access that module in
Python, you need to import it like a normal Python module ("import client_data"). After
importing the module, the converted Mosel variables will be the attributes of the module, for example,
client_data.demand.
If no module name is provided, i.e. if the ﬁle name is "python:", then the driver behaves like pyset
and pyget: When writing data to Python, the optional labels are understood as global variable names.
The driver creates or overwrites the global variables by writing the new values to the attributes of the
Python __main__ module. If a variable name is not a valid Python variable identiﬁer the driver will
succeed anyway and write the value to the module attributes using the name speciﬁed in the label.
When reading data from Python, the optional labels are understood as Python expressions. At ﬁrst, thedriver checks whether an expression is a global variable and tries to access it by getting it from theattributes of the Python __main__ module. If this fails, the expression is evaluated by Python and theresult is written to the Mosel variable.
The driver throws an I/O error if the expression evaluation or the type conversion fails. Use theparameters ioctrl (see setparam) and iostatus (see getparam) to catch I/O errors.
When initializing data from Mosel to Python, a possibly existing Python object with the same name will
be replaced by a new Python object with a Python object type that matches the type of the Mosel
source variable.
When initializing arrays, sets, or lists from Python to Mosel, the initialization behavior is additive: The
elements of the Python structures are added to the Mosel structures and existing elements in the
Mosel structures will not be deleted automatically. If, for example, the target Mosel array is dense andthe source Python dictionary or Series is sparse, then the Mosel array may contain old and new values
after initialization from Python. If the Mosel array is meant to contain only the values retrieved from the
Python dictionary, it is recommended to clear the array with reset before initializing it from Python.
20.5.1.1
Type mapping to Python

Mosel boolean →– Python bool
– NumPy bool_ if element of pandas SeriesMosel integer →– Python int– NumPy int64 if element of pandas SeriesMosel real →– Python ﬂoat

Fair Isaac Corporation Conﬁdential and Proprietary Information791

python3– NumPy ﬂoat64 if element of pandas SeriesMosel string/text → Python str

Mosel set → Python set

Mosel list → Python list

Mosel array(I) →– If pyusepandas: pandas Series with one-dimensional index– If not pyusepandas: Python dictionary with scalar keys

Mosel array(I, J, ...) →– If pyusepandas: pandas Series with multi-dimensional index– If not pyusepandas: Python dictionary with tuples of scalars as keys

Mosel list of array →– If pyusepandas: pandas DataFrame with one- or multi-dimensional index– If not pyusepandas: not supported



Mosel nested types → Python nested typeMosel records: not supported

Other Mosel external types: not supported

20.5.1.2

Type mapping from Python

The NumPy and pandas types are only supported if the pandas interface is initialized.


Mosel boolean ← Python bool; NumPy bool_Mosel int ← Python int, bool; NumPy integer, bool_Mosel real ← Python ﬂoat, int, bool; Numpy ﬂoating, integer, bool_Mosel string/text ← String representation of Python object as returned by repr()

Mosel list ← Python list

Mosel set ← iterable types (e.g., set, generator expression, classes that implement __iter__())

Mosel array ←– pandas Series with one- or multi-dimensional index– NumPy ndarray with one or multiple dimensions– Python dictionary with scalar or tuple keys

Mosel list of array ←– pandas DataFrame with one- or multi-dimensional index



Mosel nested types ← Python nested type of supported subtypes

Mosel records: not supported

Fair Isaac Corporation Conﬁdential and Proprietary Information792

python3Other Mosel external types: not supported

In the following example, a sparse array is transferred to Python and then the same array is reused for
retrieving data from a sparse Python dictionary.
model "Python I/O example"
uses "python3"
declarations
I = 1..4
A: dynamic array(I) of integer
end-declarations
A(1) := 1⁎2; A(3) := 3⁎2
initializations to "python:"
I as "MyRange"A
end-initializations
pyrun("io-example.py")
reset(A) ! Delete existing elements from array A.
initializations from "python:"A
end-initializations
writeln("Values initialized from Python:")writeln(" A= ", A)
end-model

The content of io-example.py:
print("Values initialized to Python:")print(" MyRange =", MyRange)
print(" A =", A)print("Modifying data in Python...")
A = {i: 2 ⁎ i for i in MyRange if i % 2 == 0}

Executing this model generates the following output:
Values initialized to Python:
MyRange = range(1, 5)
A = {1: 2, 3: 6}
Modifying data in Python...
Values initialized from Python:A= [(2,4),(4,8)]

20.6

TroubleshootingThis section describes some known issues and possible solutions.


Mosel: E-353: Module ‘python3’ disabled by restrictions.
This module does not handle Mosel restrictions, it will therefore fail to load if Mosel is run in
restricted mode. Section 20.2 provides information about conﬁguring the security restrictions.



If the initialization of a Python extension module fails when it is imported from within Mosel, thenﬁrst check which Python environment is used from within Mosel (set pyinitverbose to true)and check whether the extension module is installed in that environment. If it is installed and canbe imported from within the interactive shell of that environment, but fails when it is imported

Fair Isaac Corporation Conﬁdential and Proprietary Information793

python3

from within Mosel, then check whether your environment is set up correctly: Windows Anaconda
Setup, Linux Anaconda Setup.

Fair Isaac Corporation Conﬁdential and Proprietary Information

794

CHAPTER 21

R
The module r makes it possible to easily exchange data with R and execute R scripts or evaluate
expressions in the R language.
R is a free software environment for statistical computing and graphics. R is available as Free Software
under the terms of the Free Software Foundation’s GNU General Public License.
To use this module, the following line must be included in the header of the Mosel model ﬁle:uses 'r';

21.1

Introduction
This module implements functionality for exchanging data between a Mosel model and R and for
calling R functions from a Mosel model.
The r module also deﬁnes an I/O driver for exchanging data using the initializations from andinitializations to Mosel constructs.
It is the Mosel run-time library that loads and runs R, not vice versa.
The purpose of the module is to make the extensive data processing capabilities of R available within
Mosel. The interactive and graphing features of R are beyond the scope of this module as it does not
implement a full interactive R GUI. However, it is possible to use some of these to a limited extent.

21.1.1

Prerequisites
This module does not include R binaries. In order to use R you need a working installation of R, version
3.0 or newer and targeting the same platform as Mosel (you won’t be able to use, e.g., the Windows
32-bit version of R from the Windows 64-bit version of Mosel). The most recent supported R version is
3.6.x. To download R, please visit the R Project web site at www.r-project.org.
This module will try to load R from the directory speciﬁed by the R_HOME environment variable, if set, orfrom the default R installation locations otherwise.
More speciﬁcally Mosel looks for a ﬁle named R.dll in Windows, libR.so in Linux, and libR.dylib
in Mac OS X.
For Windows platforms, the default location is retrieved from the registry (from registry key
HKEY_LOCAL_MACHINE\Software\R-core\R\InstallationPath); it is/Library/Frameworks/R.framework/Resources for Mac OS X, /usr/lib/R for 32bit Linux,and either /usr/lib64/R or /usr/lib/R for 64bit Linux.
If R_HOME and R_ARCH environment variables are deﬁned, they are used to construct a path like
R_HOME/lib in Linux and like R_HOME\bin\R_ARCH in Windows (the default for R_ARCH is x64 or
i386 respectively for Windows 64-bit and Windows 32-bit).

Fair Isaac Corporation Conﬁdential and Proprietary Information

795

R

If you have multiple installations of R, or if R is installed in a different location or not automaticallyfound, you will need to set the environment variable R_HOME to point to your R installation directory.
Note that the loading of R is not inﬂuenced by eventual Mosel statements like
setparam(’workdir’,...) or setenv(’R_HOME’,...) as these don’t affect the process’s
environment used for R loading. The environment variables or current path must eventually be set
before launching Mosel in order for this to inﬂuence R loading.
As an example, if R 3.2.3 is installed in "C:\Program Files\R\R-3.2.3\bin\..." in Windows
64-bit, then the correct value for the R_HOME environment variable (or registry key) is C:\Program
Files\R\R-3.2.3 (thus, without the bin subdirectory) and Mosel would try and load R.dll from
C:\Program Files\R\R-3.2.3\bin\x64\R.dll.

21.1.2

R initialization
The R environment is automatically initialized at the point where a Mosel model uses for the ﬁrst time
any function that requires it. So we can have the following small example that just prints the R version(it prints the same output as if you typed R.version.string on an R console):model "r version example"
uses 'r';Rprint('R.version.string')
end-model

Alternatively it is possible to explicitly initialize R using the Rinit function. This can be useful in orderto retrieve a status code or to specify non-default initialization options.
By default, R is initialized with the options "–slave –vanilla", so no site or user environment, proﬁle,history and workspace ﬁles are processed. Please refer to the R documentation for more details onthese and other options (http://cran.r-project.org/doc/manuals/r-release/R-intro.html#Invoking-R).
Upon startup, only the "utils", "stats", and "methods" R packages are loaded by default. Other packages
can be loaded via R statements (using for example the library or require R functions) or a different
initial package list can be speciﬁed by setting the R_DEFAULT_PACKAGES environment variable (prior
to running Mosel).
As R is single-threaded, it is not possible to create more than one R session per model, nor to execute
two models in parallel if both use R.

21.1.3

Memory limit on Windows
On Windows platforms, R has an internal mechanism that can limit the maximum amount of memory it
can use. The limit can be read or changed using the R memory.limit function; for example, thecurrent limit can be printed from Mosel withwriteln('R memory limit is ',Rgetreal("memory.limit()"),' MB')and the limit can be set, e.g. to 16 GB, with
Reval("memory.limit(16⁎1024)")Note that in versions of R prior to 3.6 the default value for this limit is different when R is executed as astandalone application rather than embedded in another application (including Mosel): in the ﬁrst casethe limit is set to the amount of physical memory available whereas it is ﬁxed to 2 GB for embedded
mode. Therefore, in order to allow R to use more than 2 GB of memory from Mosel on Windows it isnecessary to explicitly raise this limit as shown above. Starting with R version 3.6, by default there is no
memory limit anymore when R is executed in embedded mode.

Fair Isaac Corporation Conﬁdential and Proprietary Information

796

R

21.1.4

Data types
The types of data that can be exchanged with R are the four Mosel elementary types boolean,integer, real and string, plus arrays, lists and sets of these (nested compositions are notsupported). Both static and dynamic Mosel arrays are supported and mapped into R atomic vectors of
the corresponding type. Mosel lists and sets can also be exported into R vectors.
In general, there is no direct mapping of more complex R types such as factors or data.frames, with the
exception of the Rsetdf function, however these can be exchanged after conversion to basic types.
For example, a factor can be loaded into a Mosel array as an array of integers with:
Rgetarr("unclass(f)", intarray)or as an array of strings with:
Rgetarr("levels(f)[f]", strarray)

Note that the ﬁrst is also equivalent to this simpler form:
Rgetarr("f", intarray)since this module ignores the factor’s "class" and "levels" attributes; similarly the second is equivalent
to the simpler:
Rgetarr("f", strarray)since the casting to string, performed within R, automatically takes into account the "levels" attribute.
To load a data.frame into Mosel, it should be converted to a matrix (for instance using as.matrix if
the column types allow that) or split into individual column vectors.
For the opposite operation, that is, exporting a Mosel array to R, note that, except for the Rsetdf
function, Mosel arrays are always exported as R (dense) atomic vectors. Any index that is not a 1-based
integer range is created in R as a named index. Index names, in R, are always strings, so for example,
when the Mosel array in the following example is converted to R, the index set J is kept as an unnamed
integer index, while I (which does not start with 1) and K (which has holes) are created as named
indices.
model "array to r"
uses "r"declarations
I= 2..3
J= {1,2}
K= {1,3}a: array(I,J,K) of integer
end-declarationsa(2,1,1):=4Rset('aR',a)writeln("Array in R:")
Rprint("aR")
writeln("dimnames(aR):")
Rprint("dimnames(aR)")
end-model! Define some test data entry! Copy data to R
! Display data held in R
! Display R indices

Executing this model generates the following output:
Array in R:, , 1

Fair Isaac Corporation Conﬁdential and Proprietary Information

797

R

2
3

[,1] [,2]
4
0
0
0

, , 3
2
3

[,1] [,2]0000dimnames(aR):[[1]][1] "2" "3"
[[2]]
NULL
[[3]]
[1] "1" "3"Note how the ﬁrst and last entry of dimnames, which correspond to indices I and K respectively, are
set to the list of index elements converted to strings; while the second entry is left to NULL since theindex set J is a 1-based integer index with contiguous elements.
Conversion to R data frames can be done using function Rsetdf. If this does not provide the required
data frame format or other complex R data structures are needed, then the conversion should be donein the R realm and is outside of the scope of this guide. A few examples are shown below, but pleaserefer to the R documentation for further information.
Some common and useful R functions to convert vectors into data frames are e.g. data.frame(),as.data.frame(), and the functions from the reshape or reshape2 packages, just to name a few.
Also functions names() (for 1-dimensional vectors) or dimnames() (for any vectors) can be used toretrieve the index names of a vector.
In the following example, a Mosel single-indexed demand array is converted to a 2-column R data
frame: the ﬁrst column for the index and the second column for the value:model "dataframe"
uses "r"declarations
Locations = {12,34,56}
demand: dynamic array(Locations) of real
end-declarations
forall(l in Locations) demand(l):=l⁎100! Fill array with some data
Rset("demand", demand)
Rprint("table <- data.frame(Loc=names(demand),Dem=demand,row.names=NULL)")
end-modelThis is the resulting output:
1
2
3

Loc Dem
12 1200
34 3400
56 5600

Note that this is the same result that you would get, more simply, with Rsetdf("table", demand,["Loc","Dem"]).
Alternatively, calling data.frame just as data.frame(demand) without any other parameters would
create a data frame with a single column (for demand) and named rows, thus yielding:demandFair Isaac Corporation Conﬁdential and Proprietary Information

798

R
12
34
56

1200
3400
5600

A bidimensional demand array such as:
declarations
Locations = {12,34,56}
C={"A","B"}demand: dynamic array(Locations,C) of real
end-declarations
demand(12,"A"):=1234
demand(56,"B"):=6789
Rset("demand", demand)using Rsetdf("df", demand, ["Loc","C", "Value"]) would yield:
1
2

Loc C Value
12 A 1234
56 B 6789

or it could be converted to a data frame via data.frame(Loc=dimnames(demand)[[1]],demand,row.names=NULL) which results in the following form:
1
2
3

Loc
A
B
12 1234
NA
34
NA
NA
56
NA 6789

Finally, for instance by calling function melt form the reshape2 package such as melt(demand,
varnames = c(’Loc’,’Prod’), value.name = ’Demand’), it is possible to obtain a data
frame with a column for each index plus a column with the array values like the following:
1
2
3
4
5
6

21.2

Loc Prod Demand
12
A
1234
34
A
NA
56
A
NA
12
B
NA
34
B
NA
56
B
6789

ExampleThe following example shows how to execute R statements and exchange data with the R workspace.
model "r example"
uses "r"declarations
CITIES = {"LONDON", "PARIS", "ROME"}ZONES = 1..4
mosarray, backarr, backarrio: array(ZONES, CITIES) of integer
backnum: real
end-declarations
setparam("Rverbose",true)! Enable showing R error messages! Reval evaluates arbitrary R statements
Reval("t<-Sys.time();now<-format(t, '%H:%M')")! Rprint also prints the result (via the R print function)
Rprint("paste('Hello from R at',now)")

Fair Isaac Corporation Conﬁdential and Proprietary Information

799

R

! Assign some Mosel scalars to R vars and show results
Rset("a_num", 1.2)
Reval("str(a_num)")Rset("a_chr", "word")
Reval("str(a_chr)")! The lvalue can be any R valid lvalue, e.g. the dim attributeRset("a_vec", 1..6)! a_vec is an R vector
Rset("dim(a_vec)", [2,3]) ! change its dimensions
writeln("a_vec")
Rprint("a_vec")! now it is a 2x3 matrix! Assign a Mosel array to an R variable
forall(i in ZONES, c in CITIES) mosarray(i,c):=i⁎10+getsize(c)Rset("arr", mos_array)! The R vector keeps index names
writeln("arr")
Rprint("arr")! Retrieve R variables
writeln("a_num is ", Rgetreal("a_num"))
writeln("a_chr is ", Rgetstr("a_chr"))
Rgetarr("arr", backarr)
writeln("arr is ", backarr)! Data can also be exchanged via the I/O driver
newnumber:=1.3
mosarray(1,"LONDON"):=1! Send data to R
initializations to "r.rws:"
newnumber as "a_num"
mosarray as "arr"end-initializations! Get data back from R
initializations from "r.rws:"
backnum as "a_num"
backarrio as "arr"end-initializations
writeln("backnum is ", backnum)
writeln("backarrio is ", backarrio)
end-model

21.3

Control parameters
The following parameters are deﬁned by the module r:
Rcleanscript

R cleanup script to be run at the end of a session.

p. 801

Rinteractive

Control the R interactive ﬂag.

p. 801

Rsessionmode

R session handling mode.

p. 802

Runloadscript

R unload script to be run at the end of a session.

p. 802

Rusemosstreams

Enable/disable R output redirection.

p. 801

Rverbose

Enable/disable R error messages.

p. 801

Fair Isaac Corporation Conﬁdential and Proprietary Information

800

R

Rverbose
Description

Enables or disables the printing of error messages when errors occur during the evaluation of
R statements. When this parameter is set, two corresponding R options are set accordingly,
namely show.error.messages, which is set to the same value as this parameter, and warn
which is set to 1 or -1 when this parameter is set to true or false respectively.

Type

Boolean, read/write

Default value

false

Moduler

Rinteractive
Description

This has effects on eventual user prompts and conﬁrmation requests from R, please refer to
R documentation (e.g. on "interactive()") for more details.

Type

Boolean, read/write

Default value

false

Moduler

Rusemosstreams
Description

By default R sends output to stdout and stderr. Using this parameter it is possible to redirect
R console output to Mosel streams instead. Note that the R notion of stdin connection is
not affected by this parameter.

Type

Boolean, read/write

Default value

true

Moduler

Rcleanscript
Description

This parameter can be used to specify the R statement(s) to be executed at the end of an R
session; its purpose should be to clear the R workspace. Note that this script is run only forsession modes 2 and 3.

Type

String, write only

Default value

remove all objects currently deﬁned in the R workspace

Affects routines

Rfree.

Moduler

Fair Isaac Corporation Conﬁdential and Proprietary Information

801

R

Runloadscript
Description

This parameter can be used to specify the R statement(s) to be executed at the end of an R
session; its purpose should be to free and unload all resources used by R. Note that this script
is run only for session mode 3 and after the Rcleanscript statement(s).

TypeString, write only

Default value

unload all packages and dynamic libraries

Affects routines

Rfree.

Moduler

Rsessionmode
Description

Speciﬁes what actions are taken at the end of an R session.

Type

Integer, read/write

Values0
1
2
3

Default value

2

Notes

This parameter is useful mainly when multiple Mosel models that use R are executed within
the same process.
When an R session is ended, R does not allow the creation of further sessions, therefore R will
not be usable again within the same process.
Session mode 3, by unloading R, should enable the possibility to create new R sessions within
the same process, however it may not completely free all resources allocated by R.

Affects routines

Rfree.

Moduler

21.4

END: the R session is ended.
KEEP: the R session is kept alive and the current R workspace is preserved.
CLEAR: the R session is kept alive and the Rcleanscript is executed.
UNLOAD: both the Rcleanscript and Runloadscript are executed, then R is unloaded.

Procedures and functions
All R statements are evaluated in the R Global Environment, more often known as the user’s workspace.
In general, the procedures and functions of r do not fail in case of R parsing or evaluation errors but set
an internal status variable that can be read with Rerrcode. To make sure that an operation has been
performed correctly, it is recommended to check the value of this variable after each call.
Rclearerr

Clear the last error code and message.

p. 818Rerrcode

Get the last error code.

p. 816

Rerrmsg

Get the last error message.

p. 817

Fair Isaac Corporation Conﬁdential and Proprietary Information

802

R

Reval

Evaluate R statements.

p. 804

Rfree

Terminate an R session.

p. 805

Rgetarr

Get the resulting array of an R expression.

p. 806

RgetboolGet the boolean value of an R expression.

p. 807

Rgetint

Get the integer value of an R expression.

p. 808Rgetreal

Get the real value of an R expression.

p. 809Rgetstr

Get the string value of an R expression.

p. 810

Rinit

Initialize an R session.

p. 811

RprintEvaluate R statements and print the result.

p. 812

Rset

Assign a Mosel value to an R object.

p. 813

RsetdfAssign a Mosel array to an R data.frame object.

p. 814

Rsource

Evaluate an R script ﬁle.

p. 815

Fair Isaac Corporation Conﬁdential and Proprietary Information

803

R

Reval
Purpose
Synopsis

Evaluate R statements.
procedure Reval(cmd:string)Argument
cmd
ExampleStatements to evaluate

The following example loads the datasets package, calculates summary statistics of the attenu
dataset and prints results:
Reval('library(datasets); s<-summary(attenu)')
Rprint('s')

Further information
It is possible to evaluate multiple statements separating them with semicolons.
Related topics
Rprint.

Fair Isaac Corporation Conﬁdential and Proprietary Information

804

R

Rfree
Purpose
Synopsis
ExampleTerminate an R session.
procedure Rfree
The following example terminates the R session:
Rfree

Further information
The use of this procedure is optional: R is automatically terminated at the end of a model execution.
However you may prefer to terminate it sooner to free resources allocated by R.
Related topics
Rinit.

Fair Isaac Corporation Conﬁdential and Proprietary Information

805

R

Rgetarr
Purpose
Synopsis

Get the resulting array of an R expression.
procedure Rgetarr(cmd:string, arr:array)

Arguments
cmd
arr
ExampleStatements to evaluate
Destination Mosel array

The following example loads the R cars example dataset into the Mosel array cars:
declarations
cars:array(range, set of string) of integer
end-declarations
Rgetarr('as.matrix(datasets::cars)',cars)

Further information
1. If cmd contains more than one statement, the returned value is the result of the last one.
2. The Mosel array arr must have the same number of dimensions as the R array; NA entries in R areskipped and corresponding entries in arr are left unchanged (note that arr is not cleared before
loading R data).
3. Supported index types for the arr array are string and integer. In the case of strings, the R array musthave a valid names or dimnames attribute for the corresponding dimension; in the case of integers, theR integer indices (1 to n) are used. All entries of the R array are converted to the same type as thedestination array within R.
Related topics
Rgetarr, Rgetint, Rgetreal, Rgetstr

Fair Isaac Corporation Conﬁdential and Proprietary Information

806

R

Rgetbool
Purpose
Synopsis

Get the boolean value of an R expression.
function Rgetbool(cmd:string):boolean

Argument
cmd

Statements to evaluate

Return value
The result of the evaluation as a boolean.
ExampleThe following example checks if the R entity vec is atomic and sets the boolean variable boolvar
accordingly:
boolvar:=Rgetbool('is.atomic(vec)')

Further information
If cmd contains more than one statement, the returned value is the result of the last one. If the results is
NA, then false is returned. The returned value is ﬁrst converted to logical within R.
Related topics
Rgetarr, Rgetint, Rgetreal, Rgetstr

Fair Isaac Corporation Conﬁdential and Proprietary Information

807

R

Rgetint
Purpose
Synopsis

Get the integer value of an R expression.
function Rgetint(cmd:string):integer

Argument
cmd

Statements to evaluate

Return value
The result of the evaluation as an integer.
ExampleThe following example retrieves the length of the R entity vec into variable intvar:
intvar:=Rgetint('length(vec)')

Further information
If cmd contains more than one statement, the returned value is the result of the last one. If the results is
NA, then the R NA_Integer value (-231 ) is returned. The returned value is ﬁrst converted to integer
within R.
Related topics
Rgetarr, Rgetbool, Rgetint, Rgetstr

Fair Isaac Corporation Conﬁdential and Proprietary Information

808

R

Rgetreal
Purpose
Synopsis

Get the real value of an R expression.
function Rgetreal(cmd:string):realArgument
cmd

Statements to evaluate

Return value
The result of the evaluation as a real.
ExampleThe following example retrieves the mean of the speed/dist ratios for the cars dataset into thevariable realvar:
realvar:=Rgetreal('mean(cars$speed/cars$dist)')Further information
If cmd contains more than one statement, the returned value is the result of the last one. If the results is
NA, then a NaN value is returned. The returned value is ﬁrst converted to numeric within R.
Related topics
Rgetarr, Rgetbool, Rgetint, Rgetstr

Fair Isaac Corporation Conﬁdential and Proprietary Information

809

R

Rgetstr
Purpose
Synopsis

Get the string value of an R expression.
function Rgetstr(cmd:string):stringArgument
cmd

Statements to evaluate

Return value
The result of the evaluation as a string.
ExampleThe following example retrieves the version string of R into the variable strvar:
strvar:=Rgetstr('R.version.string')

Further information
If cmd contains more than one statement, the returned value is the result of the last one. If the results is
NA, then the string "NA" is returned. The returned value is ﬁrst converted to string within R.
Related topics
Rgetarr, Rgetbool, Rgetreal, Rgetstr

Fair Isaac Corporation Conﬁdential and Proprietary Information

810

R

Rinit
Purpose
Synopsis

Initialize an R session.
function Rinit([args:string...]): integer

Argumentargs

List of R startup options (optional)

Return value
0 if the initialization was successful.
ExampleThe following example initializes R with default options:
initok:=Rinit
if initok<>0 then writeln('Failed to initialize R')
end-ifFurther information
The use of this function is optional: R is automatically initialized upon ﬁrst use. Default R startup
options are "–slave", "–vanilla", so no site or user environment, proﬁle, history and workspace ﬁles areprocessed. Please refer to the R documentation for the exact meaning of these and other options(http://cran.r-project.org/doc/manuals/r-release/R-intro.html#Invoking-R).
Related topics
Rfree.

Fair Isaac Corporation Conﬁdential and Proprietary Information

811

R

RprintPurpose
Synopsis

Evaluate R statements and print the result.
procedure Rprint(cmd:string)Argument
cmd
ExampleStatements to evaluate and print

The following example prints the R version number and summary statistics of the cars dataset:
Rprint("R.version.string")
Rprint('library(datasets); summary(cars)')

Further information
It is possible to evaluate multiple statements separating them with semicolons. The return value of thelast statement is printed using R’s own print function, thus with R style and formatting.
Related topics
Reval.

Fair Isaac Corporation Conﬁdential and Proprietary Information

812

R

Rset
Purpose
Synopsis

Assign a Mosel value to an R object.
procedure Rset(dst:string, value:[set|array|list of]boolean|integer|real|string)Arguments
dst
An R variable namevalue The Mosel value to be assigned to dst
ExampleThe following example assigns values 1.2, "hello" and an array with numbers 1 to 6 to the R objects
a_num, a_string and a_vec respectively:
Rset('a_num', 1.2)
Rset('a_string', 'hello')
Rset("a_vec", 1..6)
Rset("dim(a_vec)", [2,3])! An R vector with real values 1 to 6
! Change its dimensions into a 2x3 matrix

Further information
1. A new temporary R entity is created from value and then assigned to dst, unless value is a scalarand dst is an existing R entity of the corresponding type, in which case dst is just set to the new value
2. Argument dst can represent any assignable expression (including subsetting and attributes).
3. The type of argument value can be any elementary Mosel type, or an array, list or set of these(compositions are not supported).
4. When value is an array, for each of the array’s dimensions, its index values are exported into thecorresponding R array’s names or dimnames attribute (after conversion to string) unless the indices
are integer values from 1 to that dimension size.
5. If value is a dynamic array, only the existing values are copied to R and the remaining array entries are
set to NA (Not Available).
Related topics
Reval, Rsetdf.

Fair Isaac Corporation Conﬁdential and Proprietary Information

813

R

RsetdfPurpose
Synopsis
Synopsis

Assign a Mosel array to an R data.frame object.
procedure Rsetdf(dst:string, arr:array of boolean|integer|real|string)procedure Rsetdf(dst:string, arr:array of boolean|integer|real|string,
cname:list of string)Arguments
dst
An R variable namearr
The Mosel array to be assigned to dst
cname List of names to be assigned to the data.frame columns
ExampleThe following:
declarations
CITIES = {"LONDON", "NEW YORK", "ROME"}ZONES = 1..4
myarray: dynamic array(ZONES, CITIES) of integer
end-declarations
myarray(1,'LONDON') := 8
myarray(1,'ROME') := 3
myarray(2,'NEW YORK') := 9Rsetdf("a_df", myarray, ['Zone','City','Value'])
Rprint("a_df")
produces this output:
1
2
3

Zone
City Value1
LONDON
81ROME
3
2 NEW YORK
9

Further information
1. A new R data.frame is created from arr and assigned to dst
2. The argument dst can represent any assignable expression (including subsetting and attributes).
3. The R data.frame is constructed with n+1 columns (where n is the number of dimensions of arr): one
column for each of the array’s indices, plus one column for the array’s values; and one row for eachexisting value of the array.
4. Rows are numbered from 1 to the number of existing values of arr and column names are taken fromthe cname argument, when given.
5. Only the ﬁrst n+1 strings from cname are used; if cname is shorter, then the right-most columns are left
unnamed.
Related topics
Reval, Rset.

Fair Isaac Corporation Conﬁdential and Proprietary Information

814

R

Rsource
Purpose
Synopsis

Evaluate an R script ﬁle.
procedure Rsource(filename:string)Argument
filename Filename of the R script to evaluate
ExampleThe following example executes the myscript.R ﬁle:Rsource('myscript.R')

Related topics
Reval.

Fair Isaac Corporation Conﬁdential and Proprietary Information

815

R

Rerrcode
Purpose
Synopsis

Get the last error code.
function Rerrcode:integer

Return value
0 if the last operations were executed successfully.
ExampleThe following example prints an error message in case of errors in R evaluations:
Reval('missingfunction()')
if Rerrcode<>0 thenwriteln('Something went wrong: ', Rerrmsg)
Rclearerr
end-ifFurther information
The Rerrcode is set to non-zero values in case of errors, but not cleared after successful operations,
so it is possible to check it after several operations to verify that all executed without errors. To clear it,use function Rclearerr.
Related topics
Rclearerr, Rerrmsg.

Fair Isaac Corporation Conﬁdential and Proprietary Information

816

R

Rerrmsg
Purpose
Synopsis

Get the last error message.
function Rerrmsg:string

Return value
The last error message in case of errors, or the empty string otherwise.
ExampleThe following example prints an error message in case of errors in R evaluations:
Reval('missingfunction()')
if Rerrcode<>0 thenwriteln('Something went wrong: ', Rerrmsg)
Rclearerr
end-ifFurther information
The message returned by this function is a top-level description of the error. It is possible to also
retrieve R own error message for example with Rgetstr("geterrmessage()").
Related topics
Rclearerr, Rerrcode.

Fair Isaac Corporation Conﬁdential and Proprietary Information

817

R

Rclearerr
Purpose
Synopsis
ExampleClear the last error code and message.
procedure Rclearerr
The following example prints an error message in case of errors in R evaluations and subsequently
clears the error information:
Reval('missingfunction()')
if Rerrcode<>0 thenwriteln('Something went wrong: ', Rerrmsg)
Rclearerr
end-ifRelated topics
Rerrcode, Rerrmsg.

Fair Isaac Corporation Conﬁdential and Proprietary Information

818

R

21.5

I/O drivers
In order to simplify access to R this module provides a driver that is designed to be used ininitializations blocks for both reading and writing data, providing the same functionalities as the
Rget and Rset functions.

21.5.1

Driver rws
rws:

The driver can only be used in ‘initializations’ blocks. It does not take any argument and provides
access to the R workspace.
In the block, each label entry is understood as one or more R statements. For ’from’ blocks, if the label
contains more than one statement, the value from the last one is returned. For ’to’ blocks, the label
must contain only one expression.
This driver requires an existing R session, therefore it is necessary to initialize R (either by calling
function Rinit or any of the other module functions that create an R session) before using it.
Example:initok:=Rinit
initializations to "r.rws:"
scalarvar as "val"arrayvar as "arr"end-initializations
initializations from "r.rws:"
backscalar as "val"backarr as "arr"end-initializations

21.6! Initialize R! Send data to R

! Get data from R

TroubleshootingThis section describes some known issues and possible solutions.










When running a model in Windows, a dialog is shown with title ’Unable to locate component’ andcontent ’The application has failed to start because Rlapack.dll was not found...’.
This may occur with Windows 2003. Please add your R binary directory (usually ’C:\Program
Files\R\R-3.x.x\bin\i386’ or ’C:\Program Files\R\R-3.x.x\bin\x64’ to the system PATH environment
variable.
When an R session is initialized in Windows, R installs a console handler to detect Ctrl-C events
which may prevent Mosel from properly detecting these same events itself.
In Linux, R may fail to load if the dynamic libraries in $R_HOME/lib cannot be found by the
dynamic linker. In this case, please add $R_HOME/lib to the LD_LIBRARY_PATH environment
variable.
This module is not compatible with Mosel security restrictions, therefore it would fail to load if
Mosel is run in restricted mode.
On Mac OS X, if the R release being used is linking the Apple CoreFoundation library, then thismodule can only be successfully initialized from the main thread of the process in which Mosel isrunning (because the CoreFoundation library can only be loaded from the main thread of aprocess). So, for example, the module would fail to load R from an mmjobs submodel and would
display an error like ’R: this module requires CoreFoundation framework to be loaded from main

Fair Isaac Corporation Conﬁdential and Proprietary Information

819

R

thread’. In this case, it ispossible to overcome this issue by setting the environment variable DYLD_INSERT_LIBRARIES to/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation(use the correct path to the CoreFoundation library on your system) before launching the Mosel
process, thus forcing an anticipated loading of the CoreFoundation library at process creation.

Fair Isaac Corporation Conﬁdential and Proprietary Information

820

CHAPTER 22

zlib
The zlib Mosel module is an interface to the zlib compression library by Jean-Loup Gailly and Mark
Adler (http://zlib.net). Thanks to two IO drivers it makes possible the creation and use of compressedﬁles from Mosel models. As an additional feature this module also integrates the MiniZip library by
Gilles Vollant (http://www.winimage.com/zLibDll/minizip.html) for supporting the ZIP archive format.

22.1

I/O drivers
The following two drivers behave the same: a stream open for reading is decompressed and a stream
open for writing is created compressed. Both drivers are also based on the same compression
algorithm (deﬂate) but use different container formats. The last published driver (zip) can only be
open for reading: it will be used to access a ﬁle stored in a zip archive. For more advanced use of ZIP
archives please refer to the dedicated routines proposed by the mmsystem module.

22.1.1

Driver gzip
gzip:filename

This driver handles ﬁles compressed using the gzip compression format: this corresponds to ﬁlescreated using the gzip compression tool.
For instance the following statement decompresses the ﬁle "myfile.gz":
fcopy("zlib.gzip:myfile.gz","myfile")

22.1.2

Driver deflate
deflate:filename

This driver handles ﬁles compressed using the zlib compression format. This driver can read
documents compressed by gzip but compressed ﬁles it generates are not compatible with this tool.

22.1.3

Driver zip
zip:zipfile,filename

This driver handles archives using the ZIP format. It can be used only for reading ﬁles: the ﬁlename ofthis driver consists in two parts separated by a coma. The ﬁrst part is the name of the archive to open(that must be a physical ﬁle) and the second one is the archive member name.
For instance the following statement compiles the ﬁle "main.mos" stored in the archive"myproject.zip":

Fair Isaac Corporation Conﬁdential and Proprietary Information

821

zlib
compile("G","zlib.zip:myproject.zip,main.mos","tmp:main.bim")

Fair Isaac Corporation Conﬁdential and Proprietary Information

822

Appendix

APPENDIX A

Syntax diagrams for the Mosel language
A.1

Main structures and statements- ‘model’ hLabeli
hModeli ::=···

hDirectivesi

hParametersi

hLabeli ::=-  String
 Identifier···
hBodyi‘end-model’ -i- ‘package’ Identifier
hPackagei ::=···

hDirectivesi
hDirectivesi ::=hParametersi

hBodyi···‘end-package’ - ‘,’‘uses’  String 
 ‘,’



‘imports’
String ‘,’‘options’  Identifier 


‘,’



Identifier‘namespace’


‘,’

‘nssearch’  Identifier ‘nsgroup’ Identifier  ‘,’ ‘:’  String   ‘version’ Integer  ‘.’ Integer  ‘.’ Integer

hParametersi ::=- · · ·


 















· · ·  Identifier ‘=’ hExpressioni   · · · String ‘:’  ‘integer’   ‘real’ ‘string’  ‘boolean’ · · · ‘end-parameters’ ···‘parameters’···

Fair Isaac Corporation Conﬁdential and Proprietary Information

824

Syntax diagrams for the Mosel language
hBodyi ::=-  hDeclarationsihRequirementsi
hSubProgram decli
hSubProgram defi ‘include’  String
 IdentifierhStatementi


 







hDeclarationsi ::=- · · · ‘declarations’ · · ····  ‘public’ 
· · ·  
Identifier ‘=’  hExpressioni  ‘public’  hType descri ‘,’  Identifier  ‘:’  hType descri ‘shared’ hProcedure headi
hFunction headi· · · ‘end-declarations’ -hRequirementsi ::=- · · ·









‘,’
· · ·   Identifier  ‘:’ hType descri   · · ·
hProcedure headi

hFunction headi· · · ‘end-requirements’ -

···




  · · ·‘requirements’···

hType descri ::=- · · ·hType namei
··· 


 ‘range’  ‘dynamic’  ‘set’ ‘of’ ‘integer’  ‘set’ ‘of’  hType descri
 ‘dynamic’  ‘constant’ ‘list’ ‘of’ hType descri


‘and’

 ‘Identifier’ 


‘,’

 ‘array’ ‘(’  hSet defi  ‘)’ ‘of’ hType descri
 ‘dynamic’  ‘hashmap’  ‘record’  hField descri  ‘end-record’ ‘public’ hField descri ::=-  ‘public’








 Identifier ‘:’ hType namei 

1Fair Isaac Corporation Conﬁdential and Proprietary Information

825

Syntax diagrams for the Mosel language

hType namei ::=-  ‘integer’‘real’
 ‘string’ ‘boolean’ ‘mpvar’ ‘linctr’ Identifier








 ‘set’ ‘of’  hType namei
hSet defi ::=-  Identifier ‘:’  ‘constant’   ‘range’  Identifier ‘:’  ‘set’ ‘of’ ‘integer’ hType namei
hSet expri

hSubProgram_decli ::=- ‘forward’ hProcedure_headi  hFunction_headi 








hSubProgram_defi ::=- hProcedure_headi  hDeclarationsi   ‘end-procedure’  hStatementi  hFunction_headi  hDeclarationsi   ‘end-function’ hStatementi 

hProcedure_headi ::=-  ‘public’ ‘procedure’ Identifier  hForm_paramsi

hFunction headi ::=- · · · ‘function’ Identifier ···  ‘public’  hForm paramsi

‘,’
hForm_paramsi ::=- ‘(’  hForm_parami
hForm parami ::=- · · ·
‘,’· · ·   Identifier ‘:’  ‘)’ -

‘range’ 

hType namei ‘:’ hType namei 







 ‘set’ ‘of’ ‘integer’ ‘set’ ‘of’  hType namei  ‘constant’ ‘,’ Identifier ‘:’ ‘array’ ‘(’  hSet defi  ‘)’ ‘of’ hType namei 

1Fair Isaac Corporation Conﬁdential and Proprietary Information

826

Syntax diagrams for the Mosel language

hStatementi ::=- · · ···· hName refi  ‘:=’ ‘+=’
 ‘-=’

 hExpressioni




‘,’



IdentifierhExpressioni
‘(’
‘)’ 





-


hCtr expri
 ‘if’ hBool expri ‘then’ hStat listi hElif bodyi  ‘end-if’ hElse bodyi  ‘end-case’‘case’ hExpressioni ‘of’ hCase listi  hElse bodyi  ‘forall’ ‘(’ hIterator listi ‘)’  hStatementi  hLabeli  hDo blocki  ‘while’ ‘(’ hBool expri ‘)’  hStatementi  hLabeli  hDo blocki  ‘repeat’ hStat listi ‘until’ hBool expri
 hLabeli ‘next’  Integer  hLabeli ‘break’  Integer  hLabeli ‘,’ hName refi ‘::’  ‘[’  hExpressioni  ‘]’‘,’ ‘(’  hExpressioni  ‘)’  hWith blocki hLabeli hInit blocki
‘return’

hElif_bodyi ::=-  ‘elif’

hElse_bodyi ::=- ‘else’hBool_expri‘then’

hStat_listi

hStat_listi -hCase_bodyi ::=-  hExpressioni

hWith blocki ::=- ‘with’ 
























‘:’  hStatementi   hDo_blocki 






‘and’
 Identifier
hName refi





‘,’
  Identifier ‘=’ hExpressioni  ‘end-do’ · · ·   hStatementi hDeclarationsi  ‘do’





···

1
Fair Isaac Corporation Conﬁdential and Proprietary Information

827

Syntax diagrams for the Mosel language

hInit blocki ::=- ‘initializations’ ‘from’  hString expri · · · ‘to’  · · ····  hInit itemi ‘as’ hString expri 
hInit itemi‘,’ ‘[’  hInit itemi  ‘]’ · · · ‘end-initializations’ hInit itemi ::=- Identifier ‘,’ ‘(’  hInit fieldselihExpressioni


 ‘)’


‘,’
 ‘(’  hInit fieldseli


 ‘)’

‘evaluation of’hInit fieldseli ::=- Identifier 
hDo_blocki ::=- ‘do’hStat_listi

hStat_listi ::=-  hStatementi

A.2‘end-do’ -








-

Expressions
hExpressioni ::=-  hBool expri
 hSet expri
 hList expri
 hArith expri
 hString expri
 hArray expri
 hNewRec expri
 hCtr expri

hComparatori ::=-  ‘<’ ‘<=’ ‘=’
 ‘<>’
 ‘>=’
 ‘>’















1
Fair Isaac Corporation Conﬁdential and Proprietary Information

828

Syntax diagrams for the Mosel language

hBool_expri ::=- 







 ‘if’
hSet expri ::=- 

hBool_expri  ‘and’  hBool_expri
 ‘or’  ‘and’  ‘(’ hIterator_listi ‘)’ hBool_expri
 ‘or’  ‘in’ hSet_expri
hExpressioni  ‘not’ 
hExpressioni hComparatori hExpressioni‘not’ hBool_expri‘(’ hBool_expri ‘,’ hBool_expri ‘,’ hBool_expri
hName_refi‘true’‘false’‘boolean’ ‘(’ hExpressioni ‘)’‘(’ hBool_expri ‘)’

hSet expri  ‘+’  hSet expri ‘-’  ‘*’ 
 ‘union’  ‘(’ hIterator listi ‘)’ hSet expri
 ‘inter’  ‘if’ ‘(’ hBool expri ‘,’ hSet expri ‘,’ hSet expri
hName refi‘{’ ‘}’‘,’‘{’  hExpressioni  ‘}’hArith expri ‘..’ hArith expri‘set’ ‘(’  hSet expri  ‘)’ hList expri ‘(’ hSet expri ‘)’

hList expri ::=-  ‘if’


hList expri  ‘+’  hList expri ‘-’ ‘sum’ ‘(’ hIterator listi ‘)’ hList expri‘(’ hBool expri ‘,’ hList expri ‘,’ hList expri
hName refi‘[’ ‘]’


‘,’

‘[’
hExpressioni  ‘]’‘list’ ‘(’  hList expri  ‘)’ hSet expri ‘(’ hList expri ‘)’

Fair Isaac Corporation Conﬁdential and Proprietary Information

-





‘)’










-

‘)’












-

‘)’











829

Syntax diagrams for the Mosel language

hArith expri ::=-  ‘if’ hArith expri
hArith expri  ‘+’
 ‘-’

 ‘*’

 ‘/’

 ‘div’  ‘mod’  ‘ˆ’ ‘sum’  ‘(’ hIterator listi ‘)’ hArith expri
 ‘prod’  ‘min’  ‘max’ ‘count’ ‘(’ hIterator listi ‘)’‘-’ hArith expri‘(’ hBool expri ‘,’ hArith expri ‘,’ hArith expri
hName refi
IntegerReal‘integer’ ‘(’ hExpressioni ‘)’‘real’ ‘(’ hExpressioni ‘)’‘(’ hArith expri ‘)’

hString_expri ::=- hString_expri  ‘+’  hExpressioni ‘-’ 
hName_refiString ‘string’ ‘(’ hExpressioni ‘)’‘(’ hString_expri ‘)’

-







‘,’
hNewRec expri ::=- Identifier ‘(’  ‘.’ Identifier ‘:=’ hExpressioni
hArray expri ::=- ‘array’ ‘(’ hIterator listi ‘)’ hArith expri -hCtr_expri ::=- hArith_expri   ‘<=’  hArith_expri  ‘>=’  ‘=’ 
‘is_sos1’
‘is_sos2’
 hName_refi  ‘is_integer’ ‘is_binary’ ‘is_continuous’ ‘is_free’  ‘is_semcont’  hArith_expri
 ‘is_semint’  ‘is_partint’ ‘(’ hCtr_expri ‘)’‘,’
hIterator_listi ::=-  hIteratori


-





‘)’












 ‘)’ -

-






1
Fair Isaac Corporation Conﬁdential and Proprietary Information

830

Syntax diagrams for the Mosel language

hIteratori ::=-  hSet expri
 hList expri‘,’  Identifier








 ‘in’  hSet expri  hList expri   ‘|’ hBool expri

Identifier ‘=’ hExpressioni  ‘|’ hBool expri 
Identifier‘as counter’‘,’
hName refi ::=-  Identifier ‘(’  hExpressioni


A.3




‘.’



 ‘)’  

-







Initializations data ﬁle format
hRecordsi ::=-  Identifier  ‘:’ hValuei
 StringhValuei ::=-  Identifier String
 IntegerReal ‘true’ ‘false’‘*’ hValue listi
hValue listi ::=-  ‘[’  









‘[’


 ‘(’  hValuei


-

‘]’


 ‘)’

 hValuei



 ‘]’



1
Fair Isaac Corporation Conﬁdential and Proprietary Information

831

APPENDIX B

Remote Invocation Protocol
A Mosel instance may be started remotely using either the connect procedure of the module mmjobs
or its equivalent routine of the XPRD library. From any of these environments one can compile, load andrun models as well as access ﬁles on the remote system. The remote invocation protocol also makes it
possible to control more precisely the execution of models (e.g. suspending execution or proﬁling) andquery information of a model (such as the value of entities) or the entire instance (e.g. to retrieve thelist of available modules).
This protocol relies on two mechanisms:
1. the procedure setcontrol (available in mmjobs and XPRD) to (re)deﬁne Mosel instance control
parameters
2. the special remote ﬁle ’mcmd’ that only supports read access: the ﬁle name is interpreted as aquery and the retrieved data is the answer to this request

B.1

Instance control parameters
Mosel instance control parameters are either deﬁned at the instance level or they apply to a speciﬁcmodel (see setcontrol). Some of the parameters serve for changing the behaviour of othercommands, others provide a means to execute some speciﬁc command.
The supported instance parameters are:

zerotol (real,instance): set the zero tolerance used for comparison and displaying real numbers(i.e. a real number smaller than the tolerance is treated as 0)realfmt (string,instance): set the C-format used to display realsflushdso (none,instance): unloads unused modules (i.e. calls XPRMﬂushdso)

lang (string,instance): set the language of the instance

defaultnode (integer,instance): set the default node number used by the "rmt:" IO driverwhen it is used without node reference (see Section 7.5.6)
runmode (int,model): set the execution mode of a model (cannot be changed during theexecution of the model):– 0: default– 1: debug– 2: proﬁle– 3: tracing

Fair Isaac Corporation Conﬁdential and Proprietary Information

832

Remote Invocation Protocol

B.2

dbgctrl (string,model): send a command to the debugger (model must be running in debugmode). See Section B.4

dbgbrksub (int,model): toggle breaksub mode during a debugging session (default is 0)

sdmax (int,instance): set the maximum depth of a call stack dump (default is 0)

mcmd pseudo ﬁleThe special remote ﬁle ’mcmd’ takes the form of an I/O driver where the ﬁle name is interpreted as aquery and the retrieved data is the answer to this request. Except for the dsostream command that
can also be open in write mode, ’mcmd’ only supports read access. A ﬁle name for this driver has thefollowing form:
mcmd:cmd[-opts][@mod[.submod]] cmdargs

cmd:

the operation to execute (e.g. ’eval’,’profres’...).

opts: options to change the format of the result. By default all data are sent using the Mosel binary
format ’bin:’. Adding option ’t’ switches to text format (still compatible with initialisations
blocks) and ’j’ will cause results to be sent as a JSON object (not compatible withinitialisations blocks). If option ’z’ is used the resulting ﬁle is compressed with gzip. A given
command may also support additional options (see ’lslib’). Except for the ’eval’command, the result set publishes always the same records that are either scalars of basic
types or lists of basic types. When a collection of values is returned a speciﬁc label indicating
the dimension of the list precedes the list.
mod:master model on which the operation will be performed.

submod: submodel. Only some operations can be applied to a submodel. Note that submodel ’0’ isthe master model itself (the ﬁrst submodel has ID ’1’).
Supported commands:
covres (model)
Retrieve proﬁling results for test coverage. This command can only be called after the model has
been run in proﬁling mode (see Section B.3).
tottime:realRlines: range
lines: array(Rlines) of integer
iters: array(Rlines) of integer
Rfiles: range
files: array(Rfiles) of string
Rstarts:range
starts: array(Rstarts) of integer

dbgbrkp [ lndx [ cond|⁎ ] ] (model or submodel)
Breakpoint management. The model must be suspended. Without any parameters thiscommand returns the current list of breakpoints; the ﬁrst parameter is interpreted as a line index
and the second parameter is a logical expression (i.e. the breakpoint condition). With only one
parameter, the breakpoint on the corresponding line index is removed (no operation is performed
if there was no breakpoint). Use ’*’ to remove all breakpoints. With two parameters thecorresponding breakpoint is created (or modiﬁed). To set an unconditional breakpoint use ’*’ asthe condition. Note that breakpoints are attached to a model: even if several models runningconcurrently are resulting from the same source ﬁle, setting a breakpoint for one model(instance) will have no effect on the others.

Fair Isaac Corporation Conﬁdential and Proprietary Information

833

Remote Invocation Protocol
Rlndx: range
lndx: array(Rlndx) of integer
cond: array(Rlndx) of string

dbgflndx [ fctname|⁎ ] (model or submodel)
Line indices corresponding to a function name. This command returns the line indicescorresponding to the beginning of the requested function (several values are returned when theroutine is overloaded). Without any arguments or with argument ’*’, the command returns allfunctions of the model. If option ’N’ is used, the arrays are sorted according to the function
names. With option ’L’ arrays are sorted following the line indices order.
Rsign: range
sign: array(Rsign) of string
lndx: array(Rsign) of integer
name: array(Rsign) of string

dbglndx (model or submodel)
Retrieve the mapping of the line indices of a model/submodel. The model must be either
suspended or not running. The debugger interface works on line indices: each line index
corresponds to a ﬁle name and a line number in this ﬁle.
Rfiles: range
files: array(Rlines:range) of integer
Rlines: range
lines: array(Rfiles:range) of string

dbgstat (model or submodel)
Current execution status of a model. The model must be suspended. If no submodel is
speciﬁed, statuses of all submodels are returned in addition to the master model (to get thestatus of the master model only use submodel ’0’).
Rid: range
id:array(Rid) of integer
stat: array(Rid) of integer
stlev:array(Rid) of integer
lndx: array(Rid) of integer

dbgstlev [ stlev|⁎ [ maxlev ] ] (model or submodel)
Stack management. The model must be suspended. Without any arguments or with argument’*’, the command returns a stack dump (i.e. a list of line indices). If the argument is ≥ 0, it
becomes the current stack level. The optional argument ’maxlev’ deﬁnes the maximum numberof levels to return (default:10). The stack level deﬁnes the context in which expression
evaluations are performed in the ’eval’ command.
Rid: range
id: array(Rid) of integer
stat:array(Rid) of integer
stlev:array(Rid) of integer
lndx:array(Rid) of integer

dsostream dsoname [specific parameters] (model or submodel)This command opens a stream to the speciﬁed module (this command supports both read andwrite mode). The module must implement the SRV_DSOSTRE service. The behaviour of thestream and the expected parameters depend on the implementation.
eval label:expression [ range ] (model or submodel)
Evaluate an expression in the context of the provided model/submodel. Execution of the model
must be completed or suspended. If option ’i’ is used, array indices are reported as ordernumbers instead of values. With option ’n’ array values are replaced by empty strings. The
label "label" is used to identify the expresion in the result ﬁle: if it is ’.’ no label is generated (theFair Isaac Corporation Conﬁdential and Proprietary Information

834

Remote Invocation Protocol

data result is directly sent to the result ﬁle), if it is omitted then the expression itself is used as
the label, otherwise the provided string is the label. Several expressions may be evaluated in asingle request (in this case they must all be labelled).
It is possible to grab only a part of a collection (array, set or list) by specifying range information.
Ranges deﬁnitions take one of these two forms:[ maxelt ]: get at most ’maxelt’ elements[ skip maxelt ]: get at most ’maxelt’ entries after skipping ’skip’ elements

Several range deﬁnitions may be speciﬁed (separated by blanks): they are used when exploring
complex structures (e.g. a list of list). The structure and type of the result set depends on theexpression.
info (instance, model or submodel)This command reports all symbols deﬁned by Mosel (if used without specifying any argument),a module (the argument is the module name) or a model (the argument is a model or submodel
ID). In the case of a module, the command loads the module if it is not yet in memory. For amodel (or package), it must have been loaded prior to this command since it is referenced by its
ID and be either not running or suspended. Information returned by the ’info’ command:
fmt:
integer
Rhdr:
range
hdr:
array(Rhdr) of string
Rdeps:
range
deps:
array(Rdeps) of integer
depsvers:array(Rdeps) of integer
depstyp: array(Rdeps) of integer
Rtyps:
range
typs:
array(Rtyps) of string
typscod: array(Rtyps) of integer
Rparms: range
parms:
array(Rparms) of stringparmsval:array(Rparms) of integer
parmsdesc:array(Rparms) of string
Rconsts: range
consts: array(Rconsts) of string
conststyp:array(Rconsts) of integer
Rcstint: range
cstint: array(Rcstint) of integer
Rcststr: range
cststr: array(Rcststr) of string
Rcstdbl: range
cstdbl: array(Rcstdbl) of realRvars:
range
vars:
array(Rvars) of string
varstyp: array(Rvars) of integer
Rarrndx: range
arrndx: array(Rarrndx) of string
Rfct:
range
fct:
array(Rfct) of string
fctsign: array(Rfct) of string
fcttyp: array(Rfct) of integer
Rdtyp:
range
dtyp:
array(Rdtyp:range) of string
dtyptyp: array(Rdtyp) of integer
Rrecsstart:range
recsstart:array(Rrecsstart) of integer
Rrecfield:range
recfield:array(Rrecfield) of string
recftype:array(Rrecfield) of integer
Riodrv: range
iodrv:
array(Riodrv) of string
iodrvinfo:array(Riodrv) of string
Rannsident:range
annsident:array(Rannsidente) of string

Fair Isaac Corporation Conﬁdential and Proprietary Information

835

Remote Invocation Protocol
Rannsstart:range
annsstart:array(Rannsstart) of integer
Ranns:
range
anns:
array(Ranns) of string

lsattr (model or submodel)
Return the list of available types attributes. The array ’attrsntyp’ gives the type supporting theattribute and ’attrsatyp’ is the type of the attribute.
Rattrs:range
attrs:
array(Rattrs) of string
attrsntyp: array(Rattrs) of integer
attrsatyp: array(Rattrs) of integer

lslib (instance)
Return the list of available packages and modules. If option ’p’ is used, packages are reportedwith their full path.
Rpkgs: range
pkgs: array(Rpkgs) of string
Rdsos: range
dsos: array(Rdsos) of string

lsloc (model or submodel)This command is similar to ’info’ but it can only be applied to a suspended model: it reports all
local variables.
Rtyps:
range
typs:
array(Rtyps) of string
typscod: array(Rtyps) of integer
Rvars:
range
vars:
array(Rvars) of string
varstyp: array(Rvars) of integer
Rarrndx: range
arrndx: array(Rarrndx) of string

profrep [ srcpath ] (model)
Ask for generation of result ﬁles after a proﬁling or covering execution, the result of thisoperation is a list of strings corresponding to the messages displayed by the commands
profile or cover. This command can only be called after the model has been run in proﬁling
or covering mode (see Section B.3). The optional srcpath argument is a list of paths(conforming to the operating system conventions) where the source ﬁles can be found. The
option ’C’ implies the generation of the coverage ﬁles (e.g. ’ﬁle.mos.cov’), with option ’c’ thesame ﬁles are produced but without counting of lines (i.e. a line that is executed is marked with
’1’ instead of the actual number of executions). The option ’P’ (the default) will generate the
proﬁling ﬁles (e.g. ’ﬁle.mos.prof’), with option ’p’ timings are reported in percentage of the total
amount of time (instead of elapsed time).
msg:list of string

profres [ path ] (model)
Retrieve proﬁling results. This command can only be called after the model has been run in
proﬁling mode (see Section B.3). The path argument indicates which execution is requested:
several "executions" may be available when the model starts other models with ’mmjobs’ (thereturned data set includes the number of additional executions available via the nbsub ﬁeld).
For instance the path 1.3 corresponds to the third "execution" started by the ﬁrst "execution".
tottime:real
nbsub: integer
nbnoprf:integer

Fair Isaac Corporation Conﬁdential and Proprietary Information

836

Remote Invocation Protocol
Rlines: range
lines: array(Rlines) of integer
iters: array(Rlines) of integer
times: array(Rlines) of realelaps: array(Rlines) of real
Rfiles: range
files: array(Rfiles) of string
Rstarts:range
starts: array(Rstarts) of integer

B.3

Proﬁler interface
Proﬁling a model requires a bim ﬁle compiled with option ’-G’. The runmode has to be set to ’2’ before
starting the execution. After the end of the proﬁler run, calls to the command ’mcmd:profres’,’mcmd:profrep’ or ’mcmd:covres’ can be used for retrieving the results.

B.4

Debugger interface
The debugger can be started even if the ﬂag ’-G’ has not been used for compilation but in this casemost commands will fail to return useful information. To run a debugging session the runmode of themodel must be set to ’1’ before starting its execution. If the model was compiled with ’-G’, theexecution is immediately suspended before the ﬁrst statement of the model and a notiﬁcation event issent.
During a debugging session changes of the model execution status are notiﬁed by speciﬁc events ofclass ’EVENT_DBG’ (32770). The value of these events is a 32bit integer (cast to a real): the ﬁrst 16
bits are a parameter (meaning depending on the reason) and the following 16 bits indicate the reason
for the notiﬁcation:

DBG_NOTIF_START (1«16): Submodel starting (the parameter is the submodel ID)



DBG_NOTIF_END (2«16): Submodel ending (the parameter is the submodel ID)



DBG_NOTIF_STOP (3«16): Execution suspended (the parameter is the VM status)

When an event ’DBG_NOTIF_STOP’ is received, the model (and its submodels) is in suspended stateand can be sent commands (see Section B.2). To continue execution a control parameter ’dbgctrl’has to be set. The possible values are (the operation applies to the master model unless a submodel
number ’num’ is given):

C: continue

E: end of execution, abort debugging sessionN [num]: continue to next statementS [num]: step into subroutineF [num]: continue up to end of subroutineT num lndx: continue up to the speciﬁed line number on submodel ’num’ (0 for master model)

Additionally, during the execution of a model running in debugging mode (but that is not suspended),
the following ’dbgctrl’ commands can be used:

B: suspend execution (e.g. consequence of ctrl-C)

Fair Isaac Corporation Conﬁdential and Proprietary Information

837

Remote Invocation Protocol

E: end of execution, abort debugging session

When the execution of the model is about to end (including after an error), it is suspended just before
exiting such that the user can look at the current status.

Fair Isaac Corporation Conﬁdential and Proprietary Information

838

APPENDIX C

Error messages
The Mosel error messages listed in the following are grouped according to the following categories:

General errors: may occur either during compilation or when running a model.



Parser/compiler errors: raised during the model compilation.

Runtime errors: when running a model.

All messages are identiﬁed by their code number, preceded either by the letter E for error or W for
warning. Errors cause the compilation or execution of a model to fail, warnings simply indicate that
there may be something to look into without causing a failure or interruption.
This chapter documents the error mesages directly generated by Mosel, not the messages stemmingfrom Mosel modules or from other libraries used by modules.

C.1

General errors
These errors may occur either during compilation or when running a model.
E-1

Internal error in ‘location’ (errortype)
An unrecoverable error has been detected, Mosel exits. Please contact Xpress Support.

E-2

General error in ‘location’ (errortype)
An internal error has been detected but Mosel can recover. Please contact Xpress Support.

E-4

Not enough memory
Your system has not enough memory available to compile or execute a Mosel model.

E-21

I cannot open ﬁle ‘ﬁle’ for writing (driver_error)
Likely causes are an incorrect access path or write-protected ﬁles.

E-22

I cannot open ﬁle ‘ﬁle’ for reading (driver_error)
Likely causes are an incorrect access path or ﬁlename or not read-enabled ﬁles.

E-23

Error when writing to the ﬁle ‘ﬁle’ (driver_error)
The ﬁle could be opened for writing but an error occurred during writing (e.g. disk full).

E-24

Error when reading from the ﬁle ‘ﬁle’ (driver_error)
The ﬁle could be opened for reading but an error occurred while reading it.

E-25

Unﬁnished string
A string is not terminated, or different types of quotes are used to indicate start and end of astring.
Examples:Fair Isaac Corporation Conﬁdential and Proprietary Information

839

Error messages
writeln("mytext)

E-26

Identiﬁer expected
May occur when reading data ﬁles: a label is missing or a numerical value has been foundwhere a string is expected.
Examples:declarations
D: range
end-declarations
initializations from "test.dat"D
end-initializations

Contents of test.dat:[1 2 3]The label D: is missing.
E-27

Number expected
May occur when reading data ﬁles: another data type has been found where a numericalvalue is expected.
Examples:declarations
C: set of real
end-declarations
initializations from "test.dat"C
end-initializations

Contents of test.dat:
C: [1 2 c]c is not a number.
E-28

Digit expected for constant exponent
May occur when using scientiﬁc notation for real values.
Examples:b:= 2E -10

E must be immediately followed by a signed integer (i.e. no spaces).
E-29

Wrong ﬁle descriptor number for selection (num)fselect is used with an incorrect parameter value.

E-34

I cannot ﬁnd IO driver ‘driver’
The system cannot locate the IO driver driver for opening a ﬁle. This may happen if the driveris provided by a module not already loaded in memory. To avoid this problem the module
name should be given with the driver name. For instance use "mmodbc.odbc" instead of"odbc" alone.

E-35

Error when closing ﬁle ‘ﬁle’ (driver_error)
An error occurred while closing a ﬁle. Typically the last write operation for clearing buffers
failed.

E-36

Read error (ﬁle)I/O error during ﬁle reading.

Fair Isaac Corporation Conﬁdential and Proprietary Information

840

Error messages

C.2

E-37

Invalid character
Invalid character sequence found while reading a text ﬁle, non-conforming to the current
encoding. Possibly an incorrect encoding (Mosel default is UTF-8) has been speciﬁed foraccessing this ﬁle.

E-38

Unknown compiler ﬂag(s) ‘ﬂag’ ignored
Some of the ﬂag(s) used with compile have not been recognized, please refer to the list
documented for compile.

E-39

Unknown BIM reader ﬂag(s) ‘ﬂag’ ignored
Some of the ﬂag(s) used with load have not been recognized, please refer to the list
documented for load.

E-40

Unsupported encoding ‘encoding’ (ignored)
The encoding name speciﬁed after the marker !@encoding is unknown.

Parser/compiler errors
Whenever possible Mosel displays the location where an error has been detected during compilation in
the format (line_number/character_position_in_line).
E-100

Syntax error before token
The parser cannot continue to analyze the source ﬁle because it has encountered an
unexpected token. When the error is not an obvious syntax error, make sure you are not using
an identiﬁer that has not been deﬁned before.
Examples:token: )writeln(3 mod)mod must be followed by an integer (or a numerical expression evaluating to an
integer).
token: write
if i > 0
write("greater")end-ifthen has been omitted.
token: end
if i > 0 then write("greater") end-if

A semicolon must be added to indicate termination of the statement preceeding theend-if.
E-101

Incompatible types (type_of_problem)
We try to apply an operation to incompatible types. Check the types of the operands.
Examples:
type_of_problem: assignmenti:=0i:=1.5The ﬁrst assignment deﬁnes i as an integer, the second tries to re-assign it a realvalue: i needs to be explicitly declared as a real.
type_of_problem: cmp

Fair Isaac Corporation Conﬁdential and Proprietary Information

841

Error messages
12=1=2A truth value (the result of 12=1 is compared to a numerical value.
E-102

Incompatible types for parameters of ‘routine’A subroutine is called with the wrong parameter type. This message may also be displayed
instead of E-104 if a subroutine is called with the wrong number of parameters. (This is due tothe possibility to overload the deﬁnition of subroutines).
Examples:procedure myprint(a:integer)
writeln("a: ", a)end-procedure
myprint(1.5)

The subroutine myprint is called with a real-valued argument instead of an integer.
E-103

Incorrect number of subscripts for ‘array’(num1/num2)
An array is used with num2 subscripts instead of the number of subscripts num1 indicated at
its declaration.
Examples:‘array’(num1/num2): ‘A’(2/1)
declarations
A: array(1..5,range) of integer
end-declarations
writeln(A(3))

E-104

Incorrect number of parameters for ‘routine’(num1/num2)
Typically displayed if write or read are used without argument(s).

E-106

Division by zero detected
Explicit division by 0 (otherwise error only detected at runtime).

E-107

Math error detected on function ‘fct’
For example, a negative number is used with a fractional exponent.

E-108

Logical expression expected here
Something else than a logical condition is used in an if statement.

E-109

Trying to redeﬁne ‘name’
Objects can only be deﬁned once, changing their type is not possible.
Examples:i:=0
declarations
i: realend-declarations

i is already deﬁned as an integer by the assignment.
E-111

Logical expression expected for operator ‘op’
Examples:
op: and
2+3 and true

E-112

Numeric expression expected for operator ‘op’
Examples:Fair Isaac Corporation Conﬁdential and Proprietary Information

842

Error messages

op: +12+{13}

op: *uses "mmxprs"
declarations
x:mpvarend-declarations
minimize(x⁎x)

Multiplication of decision variables of type mpvar is only possible if a suitable
module (like mmnl) supporting non-linear expressions is loaded.
E-113

Wrong type for conversion
Mosel performs automatic conversions when required (for instance from an integer to a real)or when explicitly requested by using the type name, e.g. integer(12.5). This error israised when an unsupported conversion is requested or when no implicit conversion can beapplied.

E-114

Unknown type for constant ‘const’
A constant is deﬁned but there is not enough information to deduce its type or the typeimplied cannot be used for a constant (for instance a linear constraint).

E-115

Expression cannot be passed by reference
We try to use a constant where an identiﬁer is expected. For instance, only non-constants canbe used in an initializations block.

E-118

Wrong logical operator
A logical opeartor is used with a type for which it is not deﬁned.
Examples:if("abc" in "acd") then writeln("?"); end-if

The operator in is not deﬁned for strings.
W-121

Statement with no effectA statement is used that has no effet, for example r += 0.

E-122

Control parameter ‘param’ unknown
The control parameters of Mosel are documented in the Mosel Reference manual underfunction getparam. All control parameters provided by a module, e.g. mmxprs, can bedisplay with the command EXAM, e.g. exam -p mmxprs. In IVE this information is displayedby the module browser.

E-123‘identiﬁer’ is not deﬁned
identiﬁer is used without or before declaring it. Check the spelling of the name. If identiﬁer isdeﬁned by a module, make sure that the corresponding module is loaded. If identiﬁer is asubroutine that is deﬁned later in the program, add a forward declaration at the beginning of
the model.

E-124

An expression cannot be used as a statement
An expression stands where a statement is expected. In this case, the expression is ignored— typically, a constraint has been stated and the constraint type is missing (i.e. >= or <= ...) oran equality constraint occurs without decision variables, e.g. 2=1.
This error also appears when the return value of a function call is not retrieved.

E-125

Set expression expected
For instance computing the union between an integer constant and a set of integers:
union(12+{13})Fair Isaac Corporation Conﬁdential and Proprietary Information

843

Error messages

E-126

String expression expected
A string is expected here: for instance a ﬁle name for an initializations block.

E-127

A function cannot be of type ‘type’
Some types cannot be the return value of a function. Typically no function can return adecision variable (type mpvar).

E-128

Type ‘type’ has no ﬁeld named ‘ﬁeld’
Trying to access an unknown ﬁeld in a record type.
Examples:declarations
myrec=record
i,j:integer
end-record
r:myrec
end-declarations
r.k:=0k is not a ﬁeld of r.
E-129

Type ‘type’ is not a record
Trying to use a record dereference on an object that is not a record. For instance using i.j
with i deﬁned as an integer.

E-130

A type deﬁnition cannot be local
It is not possible to declare a type in a procedure or function.

W-131

Array ‘identiﬁer’ is not indexed by ranges: assignment may be incorrect
When performing an inline initialization (operator ::) on an array, it is recommended to list
indices if the indexing sets are not ranges. Indeed, since order of set elements is notguaranteed the values provided may not be assigned to the expected cells in the array.
Examples:declarations
a:array({3,2,1}) of integer
end-declarations! a::[3,2,1]!=> a(1)=3 a(2)=2 a(3)=1
a::([3,2,1])[3,2,1] !=> a(1)=1 a(2)=2 a(3)=3E-132

Set or list expression expected
Aggregate operators (like sum or forall) require sets or lists to describe the domains fortheir loops.
Examples:declarations
i:integer
end-declarations
forall(i = 2) writeln(i)Since i is declared as an integer before the loop, the expression i=2 is a logicalexpression (it checks whether i is equal to 2) instead of an index deﬁnition.
W-144

Symbol ‘identiﬁer’ implicitly declared
When a model is compiled with option -wi this message gets displayed for every symbol thatis not explicitly declared by the model.

E-147

Trying to interrupt a non existing loop
break or next is used outside of a loop.

E-148

Procedure/function ‘identiﬁer’ declared but not deﬁned
A procedure or functions is declared with forward, but no deﬁnition of the subroutine bodyhas been found or the subroutine body does not contain any statement.

Fair Isaac Corporation Conﬁdential and Proprietary Information

844

Error messages

E-149

Some requirements are not met
A package may declare requirements: these are symbols that must be declared by models
using this package. This error occurs when a model uses a package without providing thedeﬁnitions for all the requirements.

E-150

End of ﬁle inside a commentary
A commentary (usually started with (!) is not terminated. This error may occur, for instance,with several nested commentaries.

E-151

Incompatible type for subscript num of ‘identiﬁer’
The subscript counter num may be wrong if an incorrect number of subscripts is used.
Examples:declarations
A:array(1..2,3..4) of integer
end-declarations
writeln(A(1.3))

This prints the value 2 for num, although the second subscript is actually missing.
W-152

Empty set for a loop detected
This warning will be printed in a few cases where it is possible to detect an empty set duringcompilation.

E-153

Trying to assign the index ‘idx’
Loop indices cannot be re-assigned.
Examples:declarations
C: set of string
D: range
end-declarations
forall(d in D) d+=1
forall(c in C) if (c='a') then c:='A'; end-if

Both of these assignments will raise the error. To replace an element of the set C, theelement needs to be removed and the new element added to the set.
E-154

Unexpected end of ﬁle
May occur, for instance, if an expression at the end of the model ﬁle is incomplete and in
addition end-model is missing.

E-155

Empty ‘case’A case statement is used without deﬁning any choices.

E-156‘identiﬁer’ has no type
The type of identiﬁer cannot be deduced. Typically, an undeclared object is assigned an
empty set.

E-157

Scalar expression expected
Examples:declarations
B={'a','b','c'}
end-declarations
case B of
1: writeln("stop")
end-case

The case statement can only be used with the basic types (integer, real, boolean,string).

Fair Isaac Corporation Conﬁdential and Proprietary Information

845

Error messages
D:: [1,2]

Declaration of arrays by assignment is only possible if the index set can be deduced(e.g. deﬁnition of an array of linear constraints in a loop).
E-159

Compiler option ‘option’ unknown
Valid compiler options include explterm and noimplicit. See section 2.3.3 for moredetails.

E-160

Deﬁnition of functions and procedures cannot be nested
May occur, for instance, if end-procedure or end-function is missing and the deﬁnitionof a second subroutine follows.

E-161

Expressions not allowed as procedure/function parameter
Occurs typically if the index set(s) of an array are deﬁned directly in the procedure/function
prototype.
Examples:procedure myproc(F:array(1..5) of real)
writeln("something")
end-procedure

Replace either by array(range) or array(set of integer) or deﬁne
A:=1..5 outside of the subroutine deﬁnition and use array(A)E-162

Non empty string expected here
This error is raised, for example, by uses ""E-163

Array declarations in the form of a list are not allowed as procedure/function parameter
Basic types may be given in the form of a list, but not arrays.
Examples:procedure myproc(F,G,H:array(range) of real, a,b,c:real)
writeln("something")
end-procedure

Separate declaration of every array is required:procedure myproc(F:array(range) of real, G:array(range) of real,
H:array(range) of real, a,b,c:real)

W-164

A local symbol cannot be made public
Examples:procedure myproc
declarations
public i:integer
end-declarations
i:=1
end-procedure

Any symbol declared in a subroutine is local and cannot be made public.
E-165

Declaration of ‘identiﬁer’ hides a parameter
The name of a function/procedure parameter is re-used in a local declaration.
Examples:procedure myproc(D:array(range) of real)declarations
D: integer
end-declarations
writeln(D)end-procedure

Rename either the subroutine argument or the name used in the declaration.

Fair Isaac Corporation Conﬁdential and Proprietary Information

846

Error messages

W-166‘;’ missing at end of statement
If the option explterm is employed, then all statements must be terminated by a semicolon.

E-167

Operator ‘op’ not deﬁned
A constructor for a type is used in a form that is not deﬁned.
Examples:uses "complex"
c:=complex(1,2,3)

The module complex deﬁnes constructors for complex numbers from one or two
reals, but not from three.
E-168‘something’ expected here
Special case of “syntax error” (E-100) where the parser is able to provide a guess of what is
missing.
Examples:something: :=a: 3

The assignment is indicated by :=.
something: ofdeclarations
S: set integer
end-declarationsof has been omitted.
something: ..
declarations
A: array(1:2) of integer
end-declarations

Ranges are speciﬁed by ...
E-169‘identiﬁer’ cannot be used as an index name (the identiﬁer is already in use or declared)
Examples:i:=0
sum(i in 1..10)

The identiﬁer i has to be replaced by a different name in one of these lines.
E-170‘=’ expects a scalar here (use ‘in’ for a set)Special case of syntax error (E-100).
Examples:sum(i = 1..10)

Replace = by in.
E-171

The [upper/lower] bound of a range is not an integer expression
Examples:declarations
A: array(1..2.5) of integer
end-declarations

Ranges are intervals of integers, so the upper bound of the index range must bechanged to either 2 or 3.
E-172

Only a reference to a public set is allowed here
All index sets of a public array must also be public.

Fair Isaac Corporation Conﬁdential and Proprietary Information

847

Error messages

E-173

Statement allowed in packages only
The block requirements can only be used in packages.

E-175

Index sets of array types must be named
User types deﬁned as arrays must be indexed by named sets (i.e. declared separately). For
instance it is not allowed to use range or set of string as an index of such an array.

E-176

Only a public type is allowed here
If a user type depending on another user type is declared declared public, the secondary typemust also be public. For instance, assuming type T1 is private, it is not possible to declare T2
as a public T2=set of T1.

E-177

Incorrect number of initializers (n1/n2)
In an inline initialization (operator ::) the number of provided values to assign does notmatch the list of indices.

E-202

Integer constant expected
Versions numbers (stated by means of the version compiler directive) must consist in 1 to 3
numbers separated by dots (e.g. 1.2.3). This error is displayed if a version number does notconform to this syntax.

E-207

Problem reference/type expected here
The operator with is used with something that is not a problem.

E-208

There can be only one counter
The as counter declaration can appear only once in an iterator list.

E-209

Missing loop indices
Typically an iterator list contains only a counter declaration: it is necessary to provide at least
one index.

E-210

String starting at line line is unﬁnishedA multiline string is not correctly terminated with the matching end marker.

E-211

Invalid annotation syntax (ignored)
Malformed annotation that cannot be identiﬁed (e.g. containing .. or invalid characters—only
alphanumeric and underscore are allowed in annotation names).

E-212

Annotations: invalid path ‘name’
Some portion of the path forming an annotation identiﬁer, e.g. cat1.cat2 is the path for the
annotation !@cat1.cat2.name, cannot be accessed.

E-213

Annotations: name ‘name’ not foundSome portion of the path forming an annotation identiﬁer, e.g. cat1.cat2 is the path for the
annotation !@cat1.cat2.name, is not deﬁned.

E-214

Annotations: trying to redeﬁne ‘name’ (ignored)
An annotation can only be deﬁned once.

E-215

Annotations: invalid deﬁnition string for ‘name’ (value)
Incorrect or incomplete annotation declaration in an @mc.def statement, such as duplicate
or missing property or value, use of an unknown keyword. Please refer to the list of
permissible declaration statements in Section 2.14.3.

E-217

Annotations: wrong value ‘value’ for ‘name’ (expecting: value2)
An annotation is assigned a value that does not correpond to the value type or set of values
that have been speciﬁed in its declaration (via @mc.def).

E-218

Annotations: missing chapter for ‘name’
moseldoc is trying to add a documentation entry under a chapter or section that has not (yet)been deﬁned.

Fair Isaac Corporation Conﬁdential and Proprietary Information

848

Error messages

C.2.1

C.2.2

C.3

Errors related to modules
E-302

The symbol ‘identiﬁer’ from ‘module’ cannot be deﬁned (redeﬁnition)
Two different modules used by a model deﬁne the same symbol (incompatible deﬁnitions).

E-303

Wrong type for symbol ‘identiﬁer’ from ‘module’Internal error in the deﬁnition of a user module (an unknown type is used): refer to the list of
type codes in the Native Interface reference manual.

W-306

Unknown operator ‘op’ (code num) in module ‘module’Internal error in the deﬁnition of a user module: refer to the list of operator codes in the Native
Interface reference manual.

E-307

Operator ‘op’ (code num) from module ‘module’ rejectedInternal error in the deﬁnition of a user module: an operator is not deﬁned correctly.

E-308

Parameter string of a native routine corrupted
Internal error in the deﬁnition of a user module: refer to the list of parameter type codes in the
Native Interface reference manual.

W-309

Problem type ‘typ’ unknown: extension ‘ext’ ignored
A module declares a native type as a problem extension but the compiler cannot ﬁnd the base
type. For instance the new type is named "myprob.pb" but "myprob" does not exist.

Errors related to packages
E-320

Package ‘package’ not foundA package has not been found in the module path (see section 2.3.1 for the search rules).

E-321‘ﬁle’ is not a package
Typically displayed if a model is used as a package (the source for the bim ﬁle starts with themodel keyword instead of package).

E-322

Wrong version for package ‘package’(using:num1.num2.num3/required:num4.num5.num6)
A model is compiled with package A depending on a package B. The bim ﬁle Mosel has
loaded for B is not compatible with the one used for compiling A (found version
num1.num2.num3, required version is num4.num5.num6).

E-323

Package ‘package’ imported several times
A package cannot be imported several times in a model. This error occurs usually when amodel uses packages A and B, and package B already includes A.

Runtime errors
Runtime errors are usually displayed without any information about where they have occurred. To
obtain the location of the error, use the ﬂag g with the COMPILE, CLOAD, or EXECUTE command.

C.3.1

Initializations
E-30

Duplicate label ‘label’ at line num of ﬁle ‘ﬁle’ (ignored)
The same label is used repeatedly in a data ﬁle.
Examples:D: [1 2 3]
D: [1 2 4]

Fair Isaac Corporation Conﬁdential and Proprietary Information

849

Error messages

C.3.2

E-31

Error when reading label ‘label’ at (num1,num2) of ﬁle ‘ﬁle’
The data entry labeled label has not been read correctly. Usually this message is preceded bya more detailed one, e.g. E-24, E-27 or E-28.

E-32

Error when writing label ‘label’ at (num1,num2) of ﬁle ‘ﬁle’
The data entry labeled label has not been written correctly. Usually this message is precededby a more detailed one, e.g. E-23.

E-33

Initialization with ﬁle ‘ﬁle’ failed for: list_of_identiﬁer
Summary report at the end of an initializations section. Usually this message ispreceded by more detailed ones, e.g. E-27, E-28, E-30, E-31.

General runtime errors
E-6

Number of running concurrent models authorized by license is exceeded
A program or model is trying to use more (sub)models than what is authorized by the licence.

E-51

Division by zero
Division by 0 resulting from the evaluation of an expression.

E-52

Math error performing function ‘identiﬁer’
For example ln used with inadmissible argument, such as 0 or negative values.

E-72

Not a runnable model (main procedure not found)
Most likely, you are trying to execute a ’package’ as if it were a ’model’.

E-1000

Inconsistent range
Typically displayed if the lower bound speciﬁed for a range is greater than its upper bound.
Examples:D:=3..-1

E-1001Conﬂicting types in set operation (op)A set operation can only be carried out between sets of the same type.
Examples:declarations
C: set of integer
D: range
end-declarations
C:={5,7}
D:=C

The inverse, C:=D, is correct because ranges are a special case of sets of integers.
E-1002

An index is out of range
An attempt is being made to access an array entry that lies outside of the index sets of thearray.

E-1003Trying to modify a ﬁnalized or ﬁxed set
Occurs, for instance, when it is attempted to re-assign a constant set or to add elements to aﬁxed set.

E-1004Trying to access an uninitialized object (type_of_object)
Occurs typically in models that deﬁne subroutines.
Examples:
type_of_object: array

Fair Isaac Corporation Conﬁdential and Proprietary Information

850

Error messages
forward procedure myprint
myprint
declarations
A:array(1..2,3..4) of integer
end-declarations
procedure myprint
writeln(A(1,2))
end-procedure

Move the declaration of A before the call of the subroutine
E-1005

Wrong type for “procedure”
Occurs when procedures settype or getvars are used with incorrect types.

E-1006

Null reference (internal_function)
This error is a special case of E-1004 when the problem is detected on an external type orscalar (e.g. accessing a record ﬁeld on an object that has not been initialized).

E-1009Too many initializers
The number of data elements exceeds the maximum size of an array.
Examples:declarations
A:array(1..3) of integer
end-declarations
A::[1,2,3,4]

E-1010Trying to extend a unary constraint
Most types of unary constraints cannot be transformed into constraints on several variables.
Examples:declarations
x,y: mpvar
end-declarations
c:=x is_integerc+=yE-1011

Dense array too big
The model is trying to create a dense array with more than 4 billion cells, typically such anarray should have been declared as sparse (dynamic or hashmap). This error will be raised
when the array is allocated (after its declaration or when it is ﬁrst accessed).

E-1013

Infeasible constraint
The simple cases of infeasible unnamed constraints that are detected at run time include:
Examples:declarations
x:mpvarend-declarations
i:=-1
if(i>=0,x,0)>=1! or:x-x>=1

E-1014Conﬂicting types in array operation (op)An array operation (like assignment) can only be carried out between arrays of the same typeand structure.

E-1015Trying to modify a constant list
Occurs, for instance, when it is attempted to apply a destructive operation (like splittail)to a constant list.

Fair Isaac Corporation Conﬁdential and Proprietary Information

851

Error messages

C.3.3

E-1016Trying to get an element in an empty set
The function getfirst or getlast is applied to an empty set.

E-1017

Trying to get an element in an empty list
The function getfirst or getlast is applied to an empty list.

E-1018Invalid identiﬁer ‘identiﬁer’ for publish
The publish command has received an invalid identiﬁer name (e.g. not a valid Mosel
identiﬁer or the name is already in use as Mosel idientiﬁer).

E-1100Empty problem
We are trying to generate or load an empty problem into a solver (i.e. no constraints; bounds
do not count as constraints).

E-1102

Problem capacity of student license exceeded (num1 type_of_object >num2)
The problem is too large to be solved with a student license. Use a smaller data set or try toreformulate the problem to reduce the number of variables, constraints, or global entities.

E-1103

Too many matrix coefﬁcients
Matrix size exceeds machine capacity: for 32bit versions the limit are 2billion (2 · 10E9)elements.

BIM reader
E-80‘ﬁle’ is not a BIM ﬁleTrying to load a ﬁle that does not have the structure of a BIM ﬁle.

E-82

Wrong ﬁle version (current:num1/required:num2) for ﬁle ‘ﬁle’
A BIM ﬁle is loaded with an incompatible version of Mosel: preferably the same versions
should be used for generating and running a BIM ﬁle.

E-83

Bim ﬁle ‘ﬁle’ corrupted
A BIM ﬁle has been corrupted, e.g. by saving it with a text editor.

E-84

File ‘ﬁle’: model cannot be renamed
A model ﬁle that is being executed cannot be re-loaded at the same time.

W-85

Trailing data at end of ﬁle ‘ﬁle’ ignored
At the end of a BIM ﬁle additional, unidentiﬁable data has been found (may be a sign of ﬁlecorruption).

E-88

Bim ﬁle ‘ﬁle’ corrupted
Incomplete or otherwise damaged BIM ﬁle.

E-90

Signature error (description)
During the generation of a BIM ﬁle, a problem with the signature has occurred.

E-91

Signature veriﬁcation error (description)
While reading a BIM ﬁle, a problem with the signature has occurred (e.g. trying to checksignature for a ﬁle that is not signed; or the keys that have been employed don’t match).

E-92

Encryption error (description)
Problem with encryption during the generation of a BIM ﬁle (e.g. invalid or missing key).

E-93

Decryption error (description)
Problem with decryption while reading a BIM ﬁle (e.g. invalid or missing key).

Fair Isaac Corporation Conﬁdential and Proprietary Information

852

Error messages

C.3.4

Module manager errors
E-350

Module ‘module’ not foundA module has not been found in the module path (see section 2.3.1 for the search rules). Thismessage is also displayed, if a module depends on another library that has not been found(e.g. module mmxprs has been found but Xpress Optimizer has not been installed or cannot
be located by the operating system).

E-351

File ‘ﬁle’ is not a Mosel DSO
Typically displayed if Mosel cannot ﬁnd the module initialization function.

E-352

Module ‘module’ requires a more recent version of Mosel (unsupported interface)A module is not compatible with the Mosel version used to load it.

E-353

Module ‘module’ disabled by restrictions
Module module either does not implement restriction handling at all or it requires featuresthat are not authorized.
Examples:
mmxprs will fail with the restriction setting NoTmp

E-354

Error when initializing module ‘module’
Usually preceded by an error message generated by the module. Please refer to the
documentation of the module for further detail.

E-355

Wrong version for module ‘module’(using:num1.num2.num3/required:num4.num5.num6)
A model is run with a version of a module that is different from the version that has been used
to compile the model (trying to run with version num1.num2.num3, required version isnum4.num5.num6).

E-358

Error when resetting module ‘module’A module cannot be executed (e.g. due to a lack of memory).

E-359

Driver ‘pkg.driver’ rejected (reason)
A module publishes an IO driver which name is invalid or that is missing some mandatory
function.

E-360

Control parameter ‘module.param’ unknown (setting ignored)
It is possible to set module parameters when running a model (using the RUN command for
instance): in the list of assignments, a control parameter cannot be found in the indicatedmodule.

E-361

Version number truncated (‘vernum’)
A version number (for module, model or package) consists in three positive numbers a.b.c.
This error is raised if one of these numbers is larger than 999.

E-362

The operating system failed to load ﬁle ‘ﬁle’ (‘description’)
The module ﬁle has been found but cannot be loaded by the system—there will typically besome system error message indicating the exact cause, such as wrong architecture (e.g.
using a library compiled for Windows under Linux or bitness mismatch) or missing additional
ﬁles (e.g. tyring to use module matlab without having previously installed Matlab—see themanual Xpress MATLAB Interface for further detail, or attempting to use mmoci without
having installed the Oracle Instant Client—see setup instructions in the whitepaper Using
ODBC and other database interfaces with Mosel).

Fair Isaac Corporation Conﬁdential and Proprietary Information

853

APPENDIX D

Contacting FICO
FICO provides clients with support and services for all our products. Refer to the following sections formore information.

Product support
FICO offers technical support and services ranging from self-help tools to direct assistance with a FICO
technical support engineer. Support is available to all clients who have purchased a FICO product andhave an active support or maintenance contract. You can ﬁnd support contact information and a link to
the Customer Self Service Portal (online support) on the Product Support home page(www.ﬁco.com/en/product-support).
The FICO Customer Self Service Portal is a secure web portal that is available 24 hours a day, 7 days aweek from the Product Support home page. The portal allows you to open, review, update, and close
cases, as well as ﬁnd solutions to common problems in the FICO Knowledge Base.
Please include ’Xpress’ in the subject line of your support queries.

Product education
FICO Product Education is the principal provider of product training for our clients and partners.
Product Education offers instructor-led classroom courses, web-based training, seminars, and training
tools for both new user enablement and ongoing performance support. For additional information, visit
the Product Education homepage at www.ﬁco.com/en/product-training or email
producteducation@ﬁco.com.

Product documentation
FICO continually looks for new ways to improve and enhance the value of the products and services weprovide. If you have comments or suggestions regarding how we can improve this documentation, let
us know by sending your suggestions to techpubs@ﬁco.com.
Please include your contact information (name, company, email address, and optionally, your phone
number) so we may reach you if we have questions.

Fair Isaac Corporation Conﬁdential and Proprietary Information

854

Contacting FICO

Sales and maintenanceIf you need information on other Xpress Optimization products, or you need to discuss maintenancecontracts 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

Related services
Strategy Consulting: Included in your contract with FICO may be a speciﬁed amount of consulting time
to assist you in using FICO Optimization Modeler to meet your business needs. Additional consulting
time can be arranged by contract.
Conferences and Seminars: FICO offers conferences and seminars on our products and services. For
announcements concerning these events, go to www.ﬁco.com or contact your FICO accountrepresentative.

FICO Community
The FICO Community is a great resource to ﬁnd the experts and information you need to collaborate,
support your business, and solve common business challenges. You can get informal technicalsupport, build relationships with local and remote professionals, and improve your business practices.
For additional information, visit the FICO Community (community.ﬁco.com/welcome).

About FICO
FICO (NYSE:FICO) powers decisions that help people and businesses around the world prosper.
Founded in 1956 and based in Silicon Valley, the company is a pioneer in the use of predictive analytics
and data science to improve operational decisions. FICO holds more than 165 US and foreign patents
on technologies that increase proﬁtability, customer satisfaction, and growth for businesses inﬁnancial services, telecommunications, health care, retail, and many other industries. Using FICO
solutions, businesses in more than 100 countries do everything from protecting 2.6 billion payment
cards from fraud, to helping people get credit, to ensuring that millions of airplanes and rental cars arein the right place at the right time. Learn more at www.ﬁco.com.

Fair Isaac Corporation Conﬁdential and Proprietary Information

855

IndexSymbols!, 15!), 15!@, 51(!, 15(!@, 51⁎, 31, 32+, 31, 32+, 16, 31, 32+=, 34,, 16-, 31, 32-, 16, 31, 32-=, 34., 589.., 31, 589/, 31//, 589::, 35:=, 34;, 16;, 16, 34=, 32=, 32, 33@, 51_, 15, 63_c, 63
Numbers
1, 6742, 674
3, 6744, 674
5, 674
6, 674
7, 6748, 674
9, 674
10, 674
11, 674
12, 674
13, 674
14, 674
15, 674
16, 674
17, 674
18, 675
20, 675
21, 675
22, 675
23, 675
24, 675

Fair Isaac Corporation Conﬁdential and Proprietary Information25, 675
26, 675
27, 675
28, 675A
abs, 67, 300, 590
absolute value, 67, 300
access mode, 498
activity, 105
robust constraint, 376
addarray of cuts, 765
cut, 764
image, 428, 429
addcut, 764
addcuts, 765
addmipsol, 683
addmonths, 471
addmultistart, 652
addnode, 594
aggregate operator, 29
alias, 237
deﬁne, 239
delete, 235
list, 238
and, 16, 30, 32, 677
annotation, 50
category, 51
current category, 51
documentation, 59, 62
global, 52
multi-line, 51
name, 51
predeﬁned categories, 51
property, 53
annual discount, 171
anonymous constraint, 36
appendﬁle, 101
arccos, 300
arcsin, 300
arctan, 68, 300
arguments, 42arithmetic expression, 30
array, 24
automatic, 34
compare, 32
create a cell, 80
declaration, 24
delete a cell, 88
dereference, 27856

Indexin/output, 172
array, 16, 30, 34
as, 16
asproc, 69
assert, 70
assign R object, 813, 814
assignment, 34
additive, 34
constraints, 34
subtractive, 34
asymmetric ciphers, 388
asynchronous HTTP request, 185
attributedelete, 597
get ﬁrst, 604
get value, 599
set value, 627
test existence, 600
attribute, 589
autofinal, 117, 155axis speciﬁer, 588, 589
B
base64, 416
basic type, 22basis
load, 719
read, 727
reset, 734
save, 737
status, 695, 743
write, 758
basis, 676
basis stability, 684
basisstability, 684
BCONDITION, 6
best bound, 677
BIM, 1, 3
documentation enabled, 59
encryption, 3
signed, 3bimprefix, 117, 155bin, 55
bitflip, 71
bitneg, 72
bitset, 73
bitshift, 74
bittest, 75
bitval, 76
bitwiseand, 75
not, 72
or, 73
shift, 74
value, 76
xor, 71bodymodel, 17boolean, 16, 22, 29, 590
Boolean expression, 32

Fair Isaac Corporation Conﬁdential and Proprietary Information

BREAK, 7
break, 16, 41
BREAKPOINTS, 7
BREAKSUB, 7
buffer size, 316, 335
ByteBuffer, 225
C
calcsolinfo, 685
call Python function, 779
call Python object, 779
callback, 659, 744
canceltimer, 268
cardinality, 374
cascading, 663
case, 16, 40
case-insensitive, 6case-sensitive, 16
casting, 28
cb, 55
CDATA, 587
cdata, 589
ceil, 77, 300
ceiling, 590
certiﬁcateclient, 390
server, 391
certiﬁcate ﬁle, 390
character encoding, 55, 601, 628
chgdeltatype, 653
child, 589
child model, 269
cipher algortihm, 388
classevent, 267
clear error
R, 818clearaliases, 235
clearinitvals, 301
clearmipdir, 686
clearmodcut, 687
clearqexpstat, 368
client certiﬁcate, 390
client private key, 391
clone, 245
close
ﬁle, 57, 95
stream, 95
coefﬁcient, 106set, 150
color, 438
column order, 677
command
Optimizer, 688
system, 565
command, 688
command line interpreter, 1commands
shortening, 10comment, 8, 15, 37, 587

857

Indexsign, 103
skip, 103
comment, 589
commentary
multi-line, 15communication interface, 363, 576
comparator, 32
compare, 78
compareic, 472
compilemodel, 3compile, 242
compiled, 17compiler annotations, 51
compiler directives, 17
compiler library, 1
compiler options, 19
concatenation, 31
list, 32
condition, 30
conﬁguration directory, 389
path, 393
conﬁguration ﬁle, 294
connect, 320, 343
connect, 233
connection
number, 316, 336
connection template, 229
connector, 26
conntmpl, 229
constant, 25
compile time, 25
deﬁnition, 25
run time, 25
constant, 16, 23
constants, 66
constraint, 22
activity, 105
anonymous, 36
coefﬁcient, 106, 107dual, 108
hide, 151
name, 36, 154
ranging information, 708
right hand side, 33
sensitivity ranges, 709
set coefﬁcient, 150
set of variables, 127
set type, 158
slack, 123
test hidden, 131
type, 33, 126, 381
contains, 590
context, 363, 576
problem, 45
context node, 588
CONTINUE, 7
control parameter, 20
documentation, 62
get, 116, 494

Fair Isaac Corporation Conﬁdential and Proprietary Information

local set, 136
Mosel instance, 832
restore, 147set, 155, 551
convergence tolerance, 646
conversion
basic type, 29
copy
ﬁle, 479
copynode, 596
copysoltoinit, 302, 689
copytext, 473
cos, 79, 300
count, 16, 29, 30
counter, 16
createdirectory, 523, 524
create, 24, 80
cross recursion, 44
crossoverlpsol, 690
crypt, 416
csv, 386
CT_BIN, 126, 158
CT_CARD, 381
CT_CONT, 126, 158
CT_EQ, 126, 158, 307, 309, 381, 383
CT_FREE, 126, 158
CT_GEQ, 126, 158, 307, 309, 381, 383
CT_INT, 126, 158
CT_LEQ, 126, 158, 307, 309, 381, 383
CT_PINT, 126, 158
CT_RNG, 126
CT_SCEN, 381
CT_SEC, 126, 158
CT_SINT, 126, 158
CT_SOS1, 126, 158
CT_SOS2, 126, 158
CT_UNB, 126, 158, 307, 309, 381, 383
currentdate, 81
currenttime, 82
cut
add, 764
add array, 765
delete, 766
drop, 767
get active, 768
list from cut pool, 769
load, 770
store, 771
store array, 772
cutelt, 83
cutfirst, 84
cuthead, 85
cutlast, 86
cuttail, 87
cuttext, 474
D
DATA, 587
data

858

Indexinitialization, 36
input, 172
local, 42
output, 172
read, 145
save, 38
sharing, 228data, 589
data frame, 814
databaseconnect, 320, 343
disconnect, 345
logoff, 321
transaction, 342, 355
datablock, 89
date, 81date, 461
datefmt, 463
datetime, 462
datetimefmt, 464
debug mode
OCI, 317
ODBC, 336
debugger, 6
declaration, 17, 21
forward, 45
implicit, 35
list, 23
record, 24
set, 23declarations, 16, 21
declarative, 17
decrypt
private key, 401
public key, 400
defaultnode, 229
defdelayedrows, 691
deflate, 821
defsecurevecs, 692
delattr, 597
delayed rows, 691
nonlinear, 661
delcell, 88delcookies, 187
delcuts, 766
DELETE, 7
deletecut, 766
directives, 686
directory, 546
ﬁle, 480
model cuts, 687
delnode, 598
delta variable, 653
deltext, 475
dense, 317, 338
dependency
module, 363, 576
service, 363, 576
deploy executable, 57

Fair Isaac Corporation Conﬁdential and Proprietary Information

descendant, 589
descendant-or-self, 589
detach, 244
determining row, 663
difference, 32
list, 32
set, 32
string, 31
digital signature, see electronic signature
directive, 750delete, 686
directives
read, 728
write, 759
directory, 488
access mode, 498
create, 523, 524
delete, 546
new, 523, 524
remove, 546
status, 498
disc, 171
disconnect, 321, 345
disconnect, 234
diskdata, 172, 174
DISPLAY, 7
display
info, 7model, 7
models, 8
div, 16, 31
division
integral, 31
remainder, 31
do, 16doc, 51, 59
doc.annot, 62
doc.cparam, 62
documentation
enable, 59
target location, 60
documentation annotations, 59
DOWN, 7draw
arrow, 425
ellipse, 426, 427
line, 430, 433
pie, 431
point, 432
polyline, 430, 433
rectangle, 434
text, 435, 436
dropcut, 767
dropcuts, 767
dropnextevent, 279
DSO, 8dual value, 108
dynamic, 16, 24
dynamic array859

Indexof variables, 24
dynamic shared object
version, 8
Dynamic Shared Objects manager, 1dynonly, 19EE-1, 839
E-100, 841
E-1000, 850
E-1001, 850
E-1002, 850
E-1003, 850
E-1004, 850
E-1005, 851
E-1006, 851
E-1009, 851
E-101, 841
E-1010, 851
E-1011, 851
E-1013, 851
E-1014, 851
E-1015, 851
E-1016, 852
E-1017, 852
E-1018, 852
E-102, 842
E-103, 842
E-104, 842
E-106, 842
E-107, 842
E-108, 842
E-109, 842
E-1100, 852
E-1102, 852
E-1103, 852
E-111, 842
E-112, 842
E-113, 843
E-114, 843
E-115, 843
E-118, 843
E-122, 843
E-123, 843
E-124, 843
E-125, 843
E-126, 844
E-127, 844
E-128, 844
E-129, 844
E-130, 844
E-132, 844
E-147, 844
E-148, 844
E-149, 845
E-150, 845
E-151, 845
E-153, 845
E-154, 845
E-155, 845

Fair Isaac Corporation Conﬁdential and Proprietary Information

E-156, 845
E-157, 845
E-159, 846
E-160, 846
E-161, 846
E-162, 846
E-163, 846
E-165, 846
E-167, 847
E-168, 847
E-169, 847
E-170, 847
E-171, 847
E-172, 847
E-173, 848
E-175, 848
E-176, 848
E-177, 848
E-2, 839
E-202, 848
E-207, 848
E-208, 848
E-209, 848
E-21, 839
E-210, 848
E-211, 848
E-212, 848
E-213, 848
E-214, 848
E-215, 848
E-217, 848
E-218, 848
E-22, 839
E-23, 839
E-24, 839
E-25, 839
E-26, 840
E-27, 840
E-28, 840
E-29, 840
E-30, 849
E-302, 849
E-303, 849
E-307, 849
E-308, 849
E-31, 850
E-32, 850
E-320, 849
E-321, 849
E-322, 849
E-323, 849
E-33, 850
E-34, 840
E-35, 840
E-350, 853
E-351, 853
E-352, 853
E-353, 853
E-354, 853
E-355, 853

860

IndexE-358, 853
E-359, 853
E-36, 840
E-360, 853
E-361, 853
E-362, 853
E-37, 841
E-38, 841
E-39, 841
E-4, 839
E-40, 841
E-51, 850
E-52, 850
E-6, 850
E-72, 850
E-80, 852
E-82, 852
E-83, 852
E-84, 852
E-88, 852
E-90, 852
E-91, 852
E-92, 852
E-93, 852
electronic signature, 388
create, 406
verify, 407
element node, 587
elementary type, 22
elif, 16, 39
else, 16, 39, 40
enc:, 55
encoding, 55
encrypt
private key, 402
public key, 403
encryption
BIM, 3encryption key, 388
end, 16
end-case, 40
end-declarations, 21
end-function, 44
end-if, 39
end-model, 17
end-package, 17
end-procedure, 44
endswith, 476
enumerate
quadratic terms, 369
environment
current, 294
process, 294
environment variable, 496, 552
MOSEL_BIM, 18, 294
MOSEL_DSO, 18, 294
MOSEL_EXECPATH, 294, 565
MOSEL_RESTR, 11, 294
MOSEL_ROPATH, 11, 294
MOSEL_RWPATH, 11, 294

Fair Isaac Corporation Conﬁdential and Proprietary Information

MOSEL_SDMAX, 3
MOSEL_SSL, 393
eof, 129
EP_HEX, 93, 361
EP_MAX, 93, 361
EP_MIN, 93, 361
EP_MPS, 93, 361
EP_STRIP, 93, 361
erase, 477
error
detection, 17
ODBC, 334
error code
R, 816error control
IO, 101, 117, 155
Maths, 155error message
R, 817
error stream, 95, 101, 102
escape sequence, 31
escape sequences, 31
estimatemarginals, 693
ETC_APPEND, 172
ETC_AUTONDX, 172
ETC_CSV, 172
ETC_DENSE, 172
ETC_EMPTYNDX, 172
ETC_IN, 172
ETC_NOQ, 172
ETC_NOZEROS, 172
ETC_OUT, 172
ETC_SGLQ, 172
ETC_SKIPH, 172
ETC_SPARSE, 172
ETC_TRANS, 172
evaluate Python expression, 782
evaluate R script, 815
evaluate R statement, 804
evaluation, 16even number, 134
Event, 267
eventclass, 285
drop next, 279
get next, 278
null, 281
peek next, 288
queue, 280
send, 269
sender group ID, 283
sender ID, 282
sender user ID, 284
value, 287
wait for, 273
event class, 267
wait for, 275
event queue, 227
event value, 267
EVENT_END, 252

861

IndexEVENT_HTTPEND, 185
EVENT_HTTPNEW, 215, 220
EVENT_TIMER, 270
excel, 386
execution environment, 291, 294
exists, 90
exit, 91
exit code
model, 261
exp, 92, 300
expandpath, 478
explterm, 16, 19
exponential function, 92, 300
exportproblem, 93
quadratic problem, 361
EXPORTPROB, 7
exportprob, 93, 361
expression, 26
linear constraint, 33
list, 32
print, 104, 168set, 31
set type, 158, 309, 383
string, 31
terminator, 16
type, 27
extended syntax, 337
FF, 654
F_APPEND, 101
F_BINARY, 101
F_ERROR, 95, 101, 110, 113
F_INPUT, 95, 101, 110, 113
F_LINBUF, 101
F_OUTPUT, 95, 101, 110, 113
F_SILENT, 101
F_TEXT, 101
failure, 318, 338
false, 16, 22, 590
fclose, 57, 95
fcopy, 479
fctasproc, 19
fdelete, 480
fflush, 57, 96
ﬁleaccess mode, 498
append, 101
close, 95
compressed, 821
copy, 479
delete, 480
ID, 110in/output, 172
inclusion, 20, 89
initialization, 37
IO, 57
move, 483
name, 113

Fair Isaac Corporation Conﬁdential and Proprietary Information

open, 101
read, 56, 145rename, 483
select, 102
size, 497
status, 498
time, 499
write, 104, 168
ﬁle extension, 3ﬁle name preﬁx
ﬁle inclusion, 3ﬁlesBIM, 17
ﬁnalizeset, 97
finalize, 24, 97
findcookie, 188
findfiles, 481
findfirst, 98
findlast, 99
findtext, 482
findxsrvs, 240
FINISH, 7
ﬁxvariable, 694
fixglobal, 694
floor, 100, 300, 590
ﬂush buffer, 96
fmove, 483
following, 589
fopen, 57, 101
forall, 16, 40
format string, 163
formattext, 484
forward, 16, 45
free
info table, 368
from, 16
fselect, 57, 102
fskipline, 57, 101, 103
fsrvdelay, 231
fsrvnbiter, 231
fsrvport, 230
function
return value, 43
type, 43function, 16function call, 27
fwrite, 104
fwrite_, 63
fwriteln, 104
fwriteln_, 63GgenerateUFparallel, 656
get
active cuts, 768
cuts from cut pool, 769
get pandas DataFrame, 783
get Python variable, 782, 791

862

Indexget R array, 806
get R boolean, 807
get R integer, 808
get R real, 809
get R string, 810
getact, 105, 376
getaliases, 238
getannidents, 265
getannotations, 266
getasnumber, 486
getattr, 599
getbanner, 236
getboolattr, 599
getboolvalue, 603
getbstat, 695
getchar, 487
getclass, 285
getcnlist, 768
getcoeff, 106
getcoeffs, 107
getcplist, 769
getcwd, 488
getdate, 489, 580
getdatetime, 582
getday, 490
getdaynum, 491
getdays, 492
getdirsep, 493
getdsoparam, 494
getdsoprop, 253
getdsopropnum, 253
getdual, 108
getdualray, 696
getelt, 109
getencoding, 601
getendparse, 495
getenv, 496
getexitcode, 261
getfid, 57, 110
getfirst, 111
getfirstattr, 604
getfirstchild, 606
getflstat, 498
getfname, 113
getfromgid, 283
getfromid, 282
getfromuid, 284
getfsize, 497
getfstat, 498
getftime, 499
getgid, 254
gethead, 112
gethostalias, 237
gethour, 500
gethspace, 614
getid, 255
getiis, 697
getiissense, 698
getiistype, 699
getindentmode, 616

Fair Isaac Corporation Conﬁdential and Proprietary Information

getindentskip, 617
getinfcause, 700
getinfeas, 701
getintattr, 599
getintvalue, 603
getlast, 114
getlastchild, 607
getlb, 702
getlinelen, 618
getloadedlinctrs, 703
getloadedmpvars, 704
getmaxnodes, 619
getminute, 501
getmodprop, 256
getmodpropnum, 256
getmonth, 502
getmsec, 503
getname, 602, 705
getnext, 605
getnextevent, 278
getnode, 257, 608
getnodes, 609
getnominal, 380
getobjval, 115
getoserrmsg, 505
getoserror, 504
getparam, 101, 116, 315, 334, 389, 462, 677, 707
getparent, 610
getpathsep, 506
getprimalray, 706
getprobstat, 707
getqexpnextterm, 369
getqexpsol, 366
getqexpstat, 367
getqtype, 508
getrange, 708
getrcost, 119
getreadcnt, 120
getrealattr, 599
getrealvalue, 603
getreverse, 121
getrmtid, 258
getsecond, 509
getsensrng, 709
getsepchar, 510
getsize, 122, 511, 590, 620, 710
getslack, 123
getsol, 124, 304, 362, 366, 375, 711
getstandalone, 612
getstart, 512
getstatus, 259
getstrattr, 599
getstrvalue, 603
getsucc, 507
getsysinfo, 513
getsysstat, 514
gettail, 125gettime, 515, 578
gettimer, 286
gettmpdir, 516

863

Indexgettrim, 517
gettxtbuf, 585
gettxtsize, 584
gettype, 126, 307, 381, 611
getub, 712
getuid, 260
getvalue, 287, 603
getvars, 127, 713
getvspace, 615
getweekday, 518
getxmlversion, 613
getyear, 519
GID
event sender, 283
model, 254, 272
wait for, 275
graph, 418
graphical interface, 2gzip, 821
H
hasfeature, 714
hashmap, 16, 24
hex, 416
hidden constraint, 131, 151, 305, 306
robust constraint, 377, 379
hmac, 417
horizontal spacing, 614, 632
host alias, see alias
http driver, 224
HTTP request
asynchronous mode, 185delete, 190
get, 191
head, 193
post, 194
put, 195
status code, 196
synchronous mode, 185
HTTP server, 176
start, 220
stop, 221
HTTP_ACCEPTED, 184
http_async, 177
HTTP_BAD_REQUEST, 184
http_browser, 177
http_cookies, 178
HTTP_CREATED, 184
http_defpage, 178
http_defport, 178
http_expire, 179
HTTP_FORBIDDEN, 184
http_freeasync, 179
http_keephdr, 179
http_listen, 179
http_maxasync, 181
http_maxconn, 180
http_maxcontime, 180
http_maxreq, 180
http_maxreqtime, 181

Fair Isaac Corporation Conﬁdential and Proprietary Information

HTTP_METHOD_NOT_ALLOWED, 184
HTTP_NO_CONTENT, 184
HTTP_NOT_ACCEPTABLE, 184
HTTP_NOT_FOUND, 184
HTTP_OK, 184
HTTP_PAYMENT_REQUIRED, 184
http_port, 181
http_proxy, 182
HTTP_PROXY_AUTHENTICATION_REQUIRED, 184
http_proxyport, 182
HTTP_REQUEST_TIMEOUT, 184
HTTP_RESET_CONTENT, 184
http_srvconfig, 182
http_startwb, 183
HTTP_UNAUTHORIZED, 184
httpcancel, 189
httpdel, 190
httpget, 191
httpgetheader, 192
httphead, 193
httppending, 205
httppost, 194
httpput, 195
httpqueueinfo, 206
httpreason, 196
httpreply, 207
httpreplycode, 208
httpreplyjson, 209
httpreqcookies, 210
httpreqfile, 211
httpreqfrom, 212
httpreqheader, 213
httpreqlabel, 214
httpreqpop, 215
httpreqpush, 216
httpreqpushlim, 217
httpreqstat, 218
httpreqtype, 219
https_cacerts, 390
https_ciphers, 390
https_cltcrt, 390
https_cltkey, 391
https_defport, 183
https_listen, 183
https_port, 184
https_srvcrt, 391
https_srvkey, 391
https_trustsrv, 392
httpstartsrv, 220
httpstopsrv, 221
I
I/O driver, 54
bin:, 55
cb:, 55
default, 54
deploy.csrc:, 57
deploy.exe:, 57
mem:, 55
mmetc.diskdata:, 174864

IndexID

mmhttp.url:, 224
mmjava.java:, 225
mmjava.jraw:, 226
mmjobs.mempipe:, 289
mmjobs.rcmd:, 290
mmjobs.rmt:, 291
mmjobs.shmem:, 289
mmjobs.xsrv:, 290
mmjobs.xssh:, 290
mmoci.oci:, 328
mmodbc.odbc:, 358
mmsheet.csv:, 386
mmsheet.excel:, 386
mmsheet.xls:, 386
mmsheet.xlsx:, 386
mmssl.base64:, 416
mmssl.crypt:, 416
mmssl.hex:, 416
mmssl.hmac:, 417
mmsystem.pipe:, 575
mmsystem.text:, 575
null:, 55
python3.python:, 791
r.rws:, 819
raw:, 55
sysfd:, 55
tee:, 55
tmp:, 54
zlib.deﬂate:, 821
zlib.gzip:, 821
zlib.zip:, 821

event sender, 282
ﬁle, 110model, 255
stream, 110
identiﬁer, 15
if, 16, 27, 39
IIS, see irreducible infeasible set, see irreducible
infeasible set
reset search, 735
IMCI, 363, 576
implies, 715
imports, 16, 17
in, 16, 32
include, 16, 20
indent mode, 616, 635
indent skip, 617, 636
indexing set, 24
indicator, 716
indicator constraint, 677, 716
INFINITY, 130, 132, 153
INFINITY, 66
INFO, 7
info
quadratic expression, 367
initial step bound, 665
initial value, 298
copy solution, 302, 689
delete, 301

Fair Isaac Corporation Conﬁdential and Proprietary Information

set, 303
initialisation vector, 416
size, 408
initialisations, 16
initializations, 16
initialize pandas interface, 786
initialize Python, 785
initialize R, 811
inline initialization, 35
input ﬁle, 172
input stream, 95, 101, 102, 225, 247
read, 145
test eof, 129
InputStream, 225
inserttext, 520
instancebanner, 236
connect, 233
disconnect, 234
instance control parameter, 832
integerread, 323, 352
integer, 16, 22, 29
integrality check, 718
inter, 16, 30, 32
inter-module communication, 363, 576
interfaceinter-module communication, 363, 576
interpreted, 17intersection, 32
IO
error, 101, 117, 155
status, 101, 117
switching between streams, 57
IO driver, see I/O driver
ioctrl, 101, 117, 155
iostatus, 101, 117
irreducible infeasible set, 697, 717
is_binary, 16, 33
is_continuous, 16, 33
is_free, 16, 33
is_integer, 16, 33
is_partint, 16, 33
is_semcont, 16, 33
is_semint, 16, 33
is_sos1, 16, 33
is_sos2, 16, 33
isdynamic, 128
iseof, 129
isfinite, 130
ishidden, 131, 305, 377
isiisvalid, 717
isinf, 132
isintegral, 718
isnan, 133
isodd, 134
isqueueempty, 280
isvalid, 521
item
number read, 117865

Indexiterator, 30
JJava

IO drivers, 225
java, 225
jobid, 230
jointext, 522
jraw, 225
JSON_FCT_BOOL, 622
JSON_FCT_CLOSE_ARR, 622
JSON_FCT_CLOSE_OBJ, 622
JSON_FCT_NULL, 622
JSON_FCT_NUM, 622
JSON_FCT_OPEN_ARR, 622
JSON_FCT_OPEN_OBJ, 622
JSON_FCT_TEXT, 622
jsonload, 621
jsonparse, 622
jsonsave, 624
jsonwrite, 222
Kkeepalive, 230
keepassert, 19, 70
key, 416
key derivation, 416
key size, 409
keyword
SQL, 334
keywords, 10, 16
Llang, 117
language, 15
largest value, 139
legend, 418
lengthstring, 316, 336
library
Run Time, 1
linctr, 16, 22, 298, 300, 359, 360, 363, 371
line breaking, 16line control directive, 21
line length, 618, 637
lines
number affected, 318, 338
number transferred, 318, 338
LIST, 7
list, 23compare, 32
constant, 32
ﬁnalize, 97
ﬁnd element, 98, 99
ﬁrst element, 84, 111
head, 112
last element, 86, 114
remove elements, 85, 87
reverse, 121, 148size, 122

Fair Isaac Corporation Conﬁdential and Proprietary Information

split, 160, 161
tail, 125
list, 16, 32
ln, 135, 300
loadbasis, 719
cut, 770
module, 17
package, 17, 18
problem, 723
load, 245, 625
load document, 621, 625
loadbasis, 719
loadcookies, 197loadcuts, 770
loadlpsol, 720
loadmipsol, 721
loadprob, 359, 723
localedir, 117, 155
localsetparam, 136
location step, 588
log, 137, 300
logarithm
base 10, 137, 300
natural, 135, 300
logctr, 677, 716
logical and, 32
logical expression, 677
exclusive or, 762
implication, 715
logical negation, 33
logical or, 32
loop, 40loop statement, 34
lower bound, 702
set, 749
LP format, 7
maximization, 93
minimization, 93
LP solutionload, 720
save, 739
LP status, 677
LSATTR, 8
LSLIBS, 8
LSMODS, 8
M
M_E, 66
M_PI, 66
makedir, 523
makepath, 524
makesos1, 33, 138
makesos2, 33, 138
marginal values, 693
mathctrl, 155
Mathserror, 155
matrixcolumn order, 677

866

Indexmatrix output, 7max, 16, 30, 31
MAX_INT, 66
MAX_REAL, 66
maximize, 359, 724
maximum value, 31, 139
maxlist, 139
mc, 51
mc.def, 52
mc.flush, 52
mc.set, 54
mem, 55
memory pipe, 289
memory usage, 140, 256
memoryuse, 140
mempipe, 289
message catalog, 63, 65
message digest, 389, 392, 405
size, 410
message domain, 64
message printing, 319, 339
Optimizer, 680
message translation, 63
min, 16, 30, 31
minimize, 359, 724
minimum value, 31, 141
minlist, 141
MIP solution
add, 683
load, 721
save, 738
mksetcookie, 223
mmssl
conﬁguration directory, 389
MMSVGDISPLAY, 421
MMSVGTGZ, 422
mod, 16, 31
MODEL, 8
Model, 241
model
active, 8body, 17
clone, 245
compile, 242
exit code, 261
GID, 254, 272
handling multiple, 227
ID, 255
load, 245
memory usage, 140, 256
name, 8pause execution, 447
properties, 256
reset, 263
run, 3, 252
sequence number, 8
size, 8source, 1
status, 259
stop, 262

Fair Isaac Corporation Conﬁdential and Proprietary Information

structure, 17
UID, 260, 271
unload, 264
version, 8
web service, 176
model, 8, 16, 17
model cut, 751
delete, 687
model management, 241
model manager, 1
model parameter, 20
model_version, 117
modelname, 117
module, 2
dependency, 363, 576
memory usage, 140
module structureadvantages, 2
modules, 15monthnames, 464
Mosel, 232
mosel, 1
debugger, 6
invocation, 2
restricted mode, 11
Mosel compiler, 1
Mosel Console, 1
Mosel instance, see instance, 513
Mosel Remote Launcher, 291
MOSEL_BIM, 18, 294
MOSEL_DSO, 18, 294
MOSEL_EXECPATH, 294, 565
MOSEL_RESTR, 11, 294
MOSEL_ROPATH, 11, 294
MOSEL_RWPATH, 11, 294
MOSEL_SDMAX, 3
MOSEL_SSL, 393
moseldoc, 62
moveﬁle, 483
MP type, 22
mpproblem, 45
MPS format, 7, 93
mpsol
reset, 736
mpsol, 676
mpvar, 16, 22, 298, 359, 363
msgdigest, 405
msgsign, 406
msgverify, 407
multiple models, 227
multiple problems, 45
multistart job, 652
N
namescramble, 93, 361
variable, 705
name, 590
names

867

Indexloading, 679
namespace, 16
NAN, 130, 133, 153
NAN, 66
nbread, 117, 145
new line, 31
newmuid, 142
newtar, 525
newzip, 526
NEXT, 8
next, 16, 41
nextfield, 527
nlctr, 298, 300
noautofinal, 19
NoDB, 12node, 608, 609
add, 594
copy, 596
delete, 598
get ﬁrst child, 606
get last child, 607
get name, 602
get next, 605
get parent, 610
get type, 611
get value, 603
set name, 630
set value, 631
node, 589
node test, 588, 589
nodenumber, 229
NoExec, 11
noimplicit, 19, 35
nominal value, 380, 382
non-relational, 317, 338
nonlinearcomplementary variables, 660
feasibility, 673
memory usage, 657
scaling, 658
tolerance, 666
nonlinear constraint
enforced, 664
hide, 306
name, 308
set type, 309
solution, 304
test hidden, 305
type, 307
NoRead, 11
not, 16, 33, 590, 677
not in, 32
NoTmp, 11
NoWrite, 11
nsgroup, 16
nssearch, 16
null, 55
nullevent, 281
numberconnection, 316, 336

Fair Isaac Corporation Conﬁdential and Proprietary Informationlines, 318, 338
number, 590
NumPy conversion, 778O
object group, 418
objective value, 115
OCI
debug mode, 317
IO driver, 328
oci, 328
OCIautocommit, 315
OCIautondx, 315
OCIbufsize, 316
OCIcolsize, 316
OCIcommit, 326
OCIconnection, 316, 320
OCIdebug, 317
OCIexecute, 322
OCIfirstndx, 317
OCIlogoff, 321
OCIlogon, 320
OCIndxcol, 317
OCIreadinteger, 323
OCIreadreal, 324
OCIreadstring, 325
OCIrollback, 327
OCIrowcnt, 318
OCIrowxfr, 318
OCIsuccess, 318
OCItruncsize, 318
OCIverbose, 319
ODBC
debug mode, 336
odd number, 134of, 16open
ﬁle, 101
stream, 101
openpipe, 528
operation
elementary, 34
operator, 26
arithmetic, 31
ealuation order, 27
optimization
direction, 7
Optimizer
loading names, 679
message printing, 680
problem name, 679
problem pointer, 679
version number, 679
optimizer problem status, 707
OPTION, 8
options, 16, 17
or, 16, 30, 32, 677
output ﬁle, 172
output stream, 95, 101, 102, 225, 247
ﬂush, 96868

Indexwrite, 104, 168
OutputStream, 225
Ppackage, 48
annotation declaration, 54
structure, 17
package, 16, 17
pandas conversion, 778
parameter, 20, 116, 136, 147, 155, 494, 551
parameters, 17parameters, 16parent, 589
parent model, 269
parentnumber, 230parseextn, 529
parseint, 530
parser context, 462
parser parameter, 117parser_date, 117parser_file, 117parser_line, 117parser_time, 117parser_UTCdate, 117parser_UTCtime, 117parser_version, 117parsereal, 532
parsetext, 533
passphrase, 388
pastetext, 535
pathmatch, 536
pathsplit, 537
pause
model execution, 447
peeknextevent, 288
PEM format, 388
plotadd, 424
PO, see Portable Object
Portable Object, 65
Portable Object Template, 64
position, 590
postsolve, 726
POT, see Portable Object Template
predicate, 588, 589
primal solution, 124
PRINT, 9print, 104, 168
problem, 93
quadratic problem, 361
R, 812
printing, 319, 339
printing format, 117, 155
printmodelmemory, 657
printmodelscaling, 658
private key, 388
private key ﬁle, 394
private symbol, 47
problem, 7
export, 93

Fair Isaac Corporation Conﬁdential and Proprietary Information

handling multiple, 45
load, 723
main, 45
maximize, 724
postsolve, 726
print, 93
status, 707
unload, 756
write, 760
problem context, 45
problem name
Optimizer, 679
problem pointerOptimizer, 679
problem type, 45
extensions, 45
procedural, 17
procedure, 36body, 43
procedure, 16
procedures
passing of formal parameters, 43
processing instruction, 587
processing-instruction, 589
prod, 16, 30, 31
product, 31
public, 16, 47
public key, 388, 389
publish, 143
pycall, 779
pycallbool, 779
pycallint, 779
pycallreal, 779
pycallstr, 779
pycalltext, 779
pycallvoid, 779
pyexec, 781
pyget, 782
pygetbool, 782
pygetdf, 783
pygetint, 782
pygetreal, 782
pygetstr, 782
pygettext, 782
pyinit, 785
pyinitpandas, 786
pyinitverbose, 777
pyrun, 787
pyset, 788
pysetdf, 789
pyunload, 790
pyusepandas, 778
Q
QCQP, see Quadratically Constrained Quadratic
Programming
qexp, 359, 360
qsort, 538
quadratic expression
enumerate terms, 369

869

Indexget info, 367
solution, 362
quadratic problem
export, 361
print, 361
Quadratically Constrained Quadratic Programming,
299
QUIT, 9quote, 31
quote, 540
R
random, 144
random data ﬁle, 412
random number, 144, 156, 411
range, 23
ﬁrst element, 84, 111
last element, 86, 114
range, 16, 32
range set, 31
ranging information, 708
raw, 55
Rcleanscript, 801
Rclearerr, 818
rcmd, 290
readbasis, 727
directives, 728
integer value, 323, 352
number of items, 117real value, 324, 353
string, 325, 354
write, 758
read, 57, 101, 117, 145
readbasis, 727
readcnt, 117, 120, 155
readdirs, 728
readlink, 541
readln, 57, 101, 145
readsol, 729
readtextline, 542
realprinting format, 117, 155read, 324, 353
real, 16, 22, 29, 300
realfmt, 117, 155
recloc, 117, 155record, 24
compare, 32
dereference, 27
record, 16
recursion, 42
reduced cost value, 119
refinemipsol, 730
REG_EXTENDED, 543, 545
REG_ICASE, 543, 545
REG_NEWLINE, 543, 545
REG_NOTBOL, 543, 545
REG_NOTEOL, 543, 545
REG_ONCE, 545

Fair Isaac Corporation Conﬁdential and Proprietary Information

regmatch, 543
regreplace, 545
rejectintsol, 731
release Python, 790
remote command driver, 290
remote driver, 291
remote invocation protocol, 832
remote launcher, 291
removedirectory, 546
removedir, 546
removefiles, 547
renameﬁle, 483
repairinfeas, 732
repeat, 16, 41
reqqueue, 176
requestclient IP, 212
data ﬁle, 211
header, 213label, 214
status, 218
type, 219
requirement, 48
requirements, 16
Rerrcode, 816
Rerrmsg, 817
reset, 146
reset, 146, 263
resetbasis, 734
resetiis, 735
resetmodpar, 248
resetsol, 736
restoreparam, 147
restrict, 117
restricted mode, 11
restrictions, 11
return, 16, 43
returned, 43
Reval, 804
reverse, 148
Rfree, 805
Rgetarr, 806
Rgetbool, 807
Rgetint, 808
Rgetreal, 809
Rgetstr, 810
Rinit, 811
Rinteractive, 801rmt, 291
robctr, 370
robust_check_feas_original_problem, 373
robust_check_feas_uncertainty_set, 372
robust_uncertain_overlap, 372
robustctr, 370, 371, 378
root node, 587
round, 149, 300, 590
rounding, 77, 100, 149, 300
Rprint, 812

870

Index

RSA cryptographic system, 388
RSA key
check private, 398
ﬁngerprint, 395
load, 399
save, 404
size, 397
RSA key pair, 389, 396
RSAfingerprint, 395
RSAgenkey, 396
RSAgetkeysize, 397
RSAisprivate, 398
RSAloadkey, 399
RSAprivdecrypt, 401
RSAprivencrypt, 402
RSApubdecrypt, 400
RSApubencrypt, 403
RSAsavekey, 404
Rsessionmode, 802
Rset, 813
Rsetdf, 814
Rsource, 815
run, 252
run Python script, 787
run Python script from string, 781
Runloadscript, 802
running time, 515
runparams, 117
Rusemosstreams, 801
Rverbose, 801Ssalt, 417savebasis, 737
Optimizer status, 740
save, 626save document, 624, 626
savebasis, 737
savecookies, 198
savemipsol, 738
savesol, 739
savestate, 740
scenario, 378
secure vectors, 692
selectﬁle, 102
stream, 102
selection statement, 34, 39
selectsol, 741
self, 589
send, 269
sensitivity ranges, 709
servertrust, 392
server certiﬁcate, 391
server private key, 391
serviceinter-module communication, 363, 576
module dependency, 363, 576

Fair Isaac Corporation Conﬁdential and Proprietary Information

set, 23
callback, 659, 744
compare, 32
ﬁnalize, 97
ﬁxed, 24
in/output, 172
size, 122set, 16, 32
set pandas DataFrame, 789
set Python variable, 788
setarchconsistency, 742
setattr, 627
setbstat, 743
setcallback, 659, 744
setcbcutoff, 747
setchar, 548
setcoeff, 150
setcomplementary, 660
setcontrol, 249
setcookie, 199
setdate, 549, 581
setdatetime, 583
setday, 550
setdefstream, 247
setdefvar, 662
setdelayedctr, 661
setdetrow, 663
setdsoparam, 551
setencoding, 628
setendparse, 495
setenforcedctr, 664
setenv, 552
setgid, 272
setgndata, 748
sethidden, 151, 306, 379
sethostalias, 239
sethour, 554
sethspace, 632
setindentmode, 635
setindentskip, 636
setinitsb, 665
setinitval, 303
setioerr, 152
setlb, 749
setlinelen, 637
setmatherr, 153
setmaxnodes, 629
setminute, 555
setmipdir, 750
setmodcut, 751
setmodpar, 250
setmonth, 556
setmsec, 557
setname, 154, 308, 630
setnominal, 382
setoserror, 553
setparam, 155, 315, 334, 389, 462, 677
setqtype, 508
setrandseed, 156setrange, 157

871

Indexsetsecond, 558
setsepchar, 510
setsol, 752
setstandalone, 638
setstart, 512
setsucc, 507
settime, 559, 579
settimer, 270settol, 666
settolset, 667
settrim, 517
settype, 158, 309, 383
setub, 753
setucbdata, 754
setuid, 271
setvalue, 631
setvspace, 634
setworkdir, 251
setxmlversion, 639
setyear, 560
shared, 16, 22, 228
shared memory driver, 289
sharingstatus, 117, 228
shmem, 289
sign, 300
sign, 300
signatureelectronic, 388
sin, 159, 300
size
array, 122ﬁle, 497
list, 122set, 122skip
comment, 103
slack value, 123
sleep, 561
smallest value, 141
solution value, 124, 362
nonlinear constraint, 304
robust constraint, 375
uncertain, 375
sorting, 538
SOS, 138
declaration, 33
set type, 158
type, 126
special ordered set, 138
splithead, 160
splittail, 161
splittext, 562
SQL commandexecute, 322, 346
update, 357
SQL parametersdeﬁne, 348
get value, 349
SQLautocommit, 335
SQLautondx, 335

Fair Isaac Corporation Conﬁdential and Proprietary Information

SQLbufsize, 335
SQLcolsize, 336
SQLcolumns, 341
SQLcommit, 342
SQLconnect, 343
SQLconnection, 336, 344
SQLdebug, 336
SQLdisconnect, 345
SQLdm, 337
SQLexecute, 346
SQLextn, 337
SQLfirstndx, 337
SQLgetparam, 349
SQLindices, 350
SQLndxcol, 338
SQLparam, 348
SQLprimarykeys, 351
SQLreadinteger, 352
SQLreadreal, 353
SQLreadstring, 354
SQLrollback, 355
SQLrowcnt, 338
SQLrowxfr, 338
SQLsuccess, 338
SQLtables, 356
SQLtruncsize, 339
SQLupdate, 357
SQLverbose, 339
sqrt, 162, 300
square root, 162, 300
sshcmd, 231
ssl_cipher, 392
ssl_digest, 392
ssl_dir, 393
ssl_privkey, 394
sslivsize, 408
sslkeysize, 409
sslmdsize, 410
sslrandom, 411
sslrandomdata, 412
stack dump, 3
standalone ﬂag, 612, 638
start value, see initial value
starts-with, 590
startswith, 563
statement, 34
separator, 34
status, 318, 338
directory, 498
ﬁle, 498
IO, 101, 117
model, 259
problem, 707
save, 740
system, 514
STEP, 9stop, 262
stopoptimize, 755
store
array of cuts, 772

872

Indexcut, 771
storecut, 771
storecuts, 772
streamclose, 95
ID, 110
input, 247
open, 101
output, 247
select, 102
strfmt, 163
stringformatted, 163
get substring, 164
maximum length, 316, 336
read, 325, 354
string, 16, 22, 29, 590
string expression
compare, 32
string-length, 590
stylesheet, 442, 446, 454, 458
submodel, 227
subproblem, 45
subroutine, 42
subset, 32
substr, 164
success, 318, 338
sufﬁx notation, 9, 45
sum, 16, 30, 31
summation, 31
superset, 32
SVG, 418
SVG_BLACK, 419
SVG_BLUE, 419
SVG_BROWN, 419
SVG_COLOR, 419
SVG_CURRENT, 419
SVG_CYAN, 419
SVG_DECORATION, 419
SVG_FILL, 419
SVG_FILLOPACITY, 419
SVG_FONT, 419
SVG_FONTFAMILY, 419
SVG_FONTSIZE, 419
SVG_FONTSTYLE, 419
SVG_FONTWEIGHT, 419
SVG_GOLD, 419
SVG_GRAY, 419
SVG_GREEN, 419
SVG_LIME, 419
SVG_MAGENTA, 419
SVG_NONE, 419
SVG_OPACITY, 419
SVG_ORANGE, 419
SVG_PINK, 419
SVG_PURPLE, 419
SVG_RED, 419
SVG_SILVER, 419
SVG_STROKE, 419
SVG_STROKEDASH, 419

Fair Isaac Corporation Conﬁdential and Proprietary Information

SVG_STROKEOPACITY, 419
SVG_STROKEWIDTH, 419
SVG_TEXTANCHOR, 419
SVG_WHITE, 419
SVG_YELLOW, 419
svgaddarrow, 425
svgaddcircle, 426
svgaddellipse, 427
svgaddfile, 428
svgaddgroup, 424
svgaddimage, 429
svgaddline, 430
svgaddpie, 431
svgaddpoint, 432
svgaddpolygon, 433
svgaddrectangle, 434
svgaddtext, 435
svgaddxmltext, 436
svgclosing, 437
svgcolor, 438
svgdelobj, 439
svgerase, 440
svggetgraphstyle, 441
svggetgraphstylesheet, 442
svggetgraphviewbox, 443
svggetlastobj, 444
svggetstyle, 445
svggetstylesheet, 446
svgpause, 447
svgrefresh, 448
svgsave, 449
svgsetgraphlabels, 450
svgsetgraphpointsize, 451
svgsetgraphscale, 452
svgsetgraphstyle, 453
svgsetgraphstylesheet, 454
svgsetgraphviewbox, 455
svgsetreffreq, 456
svgsetstyle, 457
svgsetstylesheet, 458
svgshowgraphaxes, 459
svgwaitclose, 460
symboldeclaration, 43
import, 17
SYMBOLS, 8
symlink, 564
symmetric cipher, 392
symmetric ciphers, 388
symmetric cypher
initialisation vector, 408
key size, 409
synchronization mechanism, 227
syntax, 15
sys_endparse, 465
sys_fillchar, 465
SYS_MOD, 498
SYS_NOW, 461, 462
sys_pid, 465
sys_qtype, 465

873

Indexsys_regcache, 466
sys_sepchar, 466
sys_trim, 466
sys_txtmem, 467
SYS_TYP, 498
SYS_ARCH, 513
SYS_DIR, 498, 537
SYS_DIRONLY, 481, 525, 526, 547, 566, 572–574
SYS_DOWN, 538
SYS_EXEC, 498
SYS_EXTN, 537
SYS_FLAT, 525, 526, 572, 573
SYS_FNAME, 537
SYS_LEFT, 571
SYS_LNK, 498
SYS_NAME, 513
SYS_NODE, 513
SYS_NODIR, 481, 525, 526, 547, 566, 572–574
SYS_NOFAIL, 572, 573
SYS_NOSORT, 481
SYS_OTH, 498
SYS_OVERWRT, 572, 573
SYS_PROC, 513
SYS_RAM, 513
SYS_READ, 498
SYS_RECURS, 481, 547
SYS_REG, 498
SYS_REL, 513
SYS_REVORD, 481
SYS_RIGHT, 571
SYS_UP, 538
SYS_VER, 513
SYS_VERB, 572, 573
SYS_WRITE, 498
sysfd, 55
system, 565
system command, 565
system information, 513
system status, 514
Ttable of symbols, 47
tagpriv, 19tan, 300
tarlist, 566
tcpping, 200
tee, 55
temporary directory, 56
term
enumerate, 369
terminate R, 805
termination, 91
testeof, 129hidden constraint, 131
hidden nonlinear constraint, 305
testattr, 600
text, 461, 589
text section, 587
textfmt, 567

Fair Isaac Corporation Conﬁdential and Proprietary Information

then, 16
time, 82ﬁle, 499
time, 461
time measure, 515
timefmt, 463
timestamp, 165
timestamp, 165
tmp, 54
tmpdir, 117
to, 16
tolerance
zero, 117, 155tolerance set, 667
tolower, 569
tolset, 646
toupper, 570
transaction
commit, 326
rollback, 327
trigonometric functions, 68, 79, 159, 300
trim, 571
true, 16, 22, 29, 590
txtresize, 586
typeconstraint, 126, 158
nonlinear constraint, 307, 309
problem, 45
SOS, 126, 158
variable, 33, 126, 158
type conversion, 28
U
UID

event sender, 284
model, 260, 271
wait for, 275
uncertain, 370
uncertainctr, 370
unconstrained, 33
UNDISPLAY, 9
union, 32
union, 16, 30, 32
unique identiﬁer, 142
unload, 264
unloadprob, 756
unpublish, 166
untar, 572
until, 16, 41
unzip, 573
UP, 9upper bound, 712
set, 753
url, 224
URL encoding, 201
urlencode, 201
uselastbarsol, 757
user comment, 8user function, 645, 654
DLL, 668

874

Index

Excel, 669
Excel macro, 670
info, 671
Mosel, 672
parallel, 656
user graph, 418
add ﬁle, 428, 429
add plot, 424
axes labels, 450
closing, 437
color, 438
delete object, 439
draw arrow, 425
draw circle, 426
draw ellipse, 427
draw line, 430
draw pie, 431
draw point, 432
draw polygon, 433
draw rectangle, 434
draw text, 435, 436
erase, 440
get object, 444
get style, 442, 446
get style property, 441, 445
get viewbox, 443
model termination, 460
point size, 451
refresh, 448
refresh frequency, 456
save, 449
scaling, 452
set style, 454, 458
set style property, 453, 457
view box, 455
user type, 26
deﬁnition, 26
userfunc, 645
userfuncDLL, 668
userfuncExcel, 669
userfuncExcelMacro, 670
userfuncinfo, 671
userfuncMosel, 672
uses, 16, 17
UTC, 117, 155Vvalidate, 673
value
event, 267
variable, 22check intregrality, 718
environment, 496, 552
ﬁx, 694
initial value, 298, 303
lower bound, 702
name, 705
ranging information, 708
reduced cost, 119sensitivity ranges, 709

Fair Isaac Corporation Conﬁdential and Proprietary Information

set coefﬁcient, 150
set lower bound, 749
set type, 158
set upper bound, 753
solution, 124
type, 126
upper bound, 712
version, 8, 16, 17versionnum, 167
versionstr, 167vertical spacing, 615, 634
viewbox, 443
VIMA, 1visual environment, 2W
W-121, 843
W-131, 844
W-144, 844
W-152, 845
W-164, 846
W-166, 847
W-306, 849
W-309, 849
W-85, 852
wait, 273
waitexpired, 274
waitfor, 275
waitforend, 277
WDOnly, 11
WHERE, 10
while, 16, 41
with, 16, 42, 46
workdir, 117, 155
working directory, 56, 251, 488
write
directives, 759
problem, 760
write, 57, 101, 168, 363
write_, 63
writebasis, 758
writedirs, 759
writeln, 57, 101, 168, 363
writeln_, 63
writeprob, 760
writesol, 761
X
X509 certiﬁcate, 389
compatibility, 413
create, 415
information, 414
x509check, 413
x509getinfo, 414
x509newcrt, 415
xbim, 19
xls, 386
xlsx, 386XML
decode, 642

875

Index

encode, 641
XML document, 592
XML document structure, 587
XML node number, 592
XML node type, 587
XML path, 588
xml version, 613, 639
XML_ATTR, 602, 611
XML_AUTO, 616, 635
XML_CDATA, 594, 602, 611
XML_COM, 594, 602, 611
XML_DATA, 594, 602, 611
XML_ELT, 594, 602, 611
XML_FCT_CDATA, 643
XML_FCT_CLOSE_ELT, 643
XML_FCT_COM, 643
XML_FCT_DATA, 643
XML_FCT_DECL, 643
XML_FCT_OPEN_ELT, 643
XML_FCT_PINST, 643
XML_FCT_TXT, 643
XML_FIRST, 594, 596
XML_FIRSTCHILD, 594, 596
XML_LAST, 594, 596
XML_LASTCHILD, 594, 596
XML_MANUAL, 616, 635
XML_NEXT, 594, 596
XML_NONE, 616, 635
XML_PINST, 594, 602, 611
XML_TXT, 594, 602, 611
xmlattr, 640
xmldecode, 642
xmldoc, 592
xmlencode, 641
xmlparse, 643
XNLP_AUTOELIM, 648
XNLP_LOADASNL, 648
XNLP_LOADNAMES, 649
XNLP_NLPSTATUS, 649
XNLP_SOLVER, 649
XNLP_TOL_RA, 646
XNLP_TOL_RI, 646
XNLP_TOL_RM, 646
XNLP_TOL_RS, 646
XNLP_TOL_TA, 646
XNLP_TOL_TC, 646
XNLP_TOL_TI, 646
XNLP_TOL_TM, 646
XNLP_TOL_TS, 646
XNLP_VERBOSE, 650
xor, 762
Xpress Optimizer, 2
Xpress Workbench, 2
xprmsrv, 291
XPRS_colorder, 677
XPRS_enumduplpol, 678
XPRS_enummaxsol, 678
XPRS_enumsols, 678
XPRS_fullversion, 679
XPRS_loadnames, 679

Fair Isaac Corporation Conﬁdential and Proprietary Information

XPRS_problem, 679
XPRS_probname, 679
XPRS_verbose, 680
XPRS_BAR, 724
XPRS_BR, 750
XPRS_CB_BARITER, 744
XPRS_CB_BARLOG, 744
XPRS_CB_CHGBRANCH, 744
XPRS_CB_CHGNODE, 744
XPRS_CB_CUTLOG, 744
XPRS_CB_CUTMGR, 744
XPRS_CB_GAPNOTIFY, 744
XPRS_CB_GLOBALLOG, 744
XPRS_CB_INFNODE, 744
XPRS_CB_INTSOL, 744
XPRS_CB_LPLOG, 744
XPRS_CB_NEWNODE, 744
XPRS_CB_NODECUTOFF, 744
XPRS_CB_OPTNODE, 744
XPRS_CB_PREINTSOL, 744
XPRS_CB_PRENODE, 744
XPRS_CB_PRESOLVE, 744
XPRS_CB_SOLNOTIFY, 744
XPRS_CONT, 724
XPRS_CORELP, 724
XPRS_DN, 709, 750
XPRS_DUAL, 724
XPRS_ENUM, 724
XPRS_INF, 707
XPRS_LCOST, 708
XPRS_LIN, 724
XPRS_LOACT, 708
XPRS_LOCAL, 724
XPRS_LPSTOP, 724
XPRS_NET, 724
XPRS_OPT, 707
XPRS_OTH, 707
XPRS_PD, 750
XPRS_PR, 750
XPRS_PRI, 724
XPRS_PU, 750
XPRS_STOP_CTRLC, 755
XPRS_STOP_ITERLIMIT, 755
XPRS_STOP_MIPGAP, 755
XPRS_STOP_NODELIMIT, 755
XPRS_STOP_SOLLIMIT, 755
XPRS_STOP_TIMELIMIT, 755
XPRS_STOP_USER, 755
XPRS_TUNE, 724
XPRS_UCOST, 708
XPRS_UDN, 708
XPRS_UNB, 707
XPRS_UNF, 707
XPRS_UP, 709, 750
XPRS_UPACT, 708
XPRS_UUP, 708
XSLP_CB_CASCADEEND, 659
XSLP_CB_CASCADESTART, 659
XSLP_CB_CASCADEVAR, 659
XSLP_CB_CONSTRUCT, 659

876

IndexXSLP_CB_END, 659
XSLP_CB_INTSOL, 659
XSLP_CB_ITEREND, 659
XSLP_CB_ITERSTART, 659
XSLP_CB_ITERVAR, 659
XSLP_CB_MSJOBEND, 659
XSLP_CB_MSJOBSTART, 659
XSLP_CB_MSWINNER, 659
XSLP_CB_OPTNODE, 659
XSLP_CB_PRENODE, 659
XSLP_CB_START, 659
xsrv, 290
xssh, 290
Z
zero tolerance, 117, 155zerotol, 117, 155zip, 821
ziplist, 574

Fair Isaac Corporation Conﬁdential and Proprietary Information

877