chiark / gitweb /
Read the docs (#132)
[nlopt.git] / doc / docs / NLopt_Guile_Reference.md
1 ---
2 # NLopt Guile Reference
3 ---
4
5 The NLopt includes an interface callable from the [Scheme programming language](https://en.wikipedia.org/wiki/Scheme_(programming_language)) as implemented in [GNU Guile](https://en.wikipedia.org/wiki/GNU_Guile) (which allows Scheme to be used as an extension language for other programs).
6
7 The main purpose of this section is to document the syntax and unique features of the Guile API; for more detail on the underlying features, please refer to the C documentation in the [NLopt Reference](NLopt_Reference.md).
8
9 Using the NLopt Guile API
10 -------------------------
11
12 To use NLopt in Python, your Python program should include the lines:
13
14 ```
15 (use-modules (nlopt))
16 ```
17
18
19 which imports the `nlopt` module.
20
21 The `nlopt-opt` class
22 ---------------------
23
24 The NLopt API revolves around an opaque "object", analogous to `nlopt::opt` in C++. Via "methods" of this object, all of the parameters of the optimization are specified (dimensions, algorithm, stopping criteria, constraints, objective function, etcetera), and then one finally calls the `opt.optimize` method in order to perform the optimization. The object should normally be created via the constructor:
25
26 ```
27 (new-nlopt-opt algorithm n)
28 ```
29
30
31 given an `algorithm` (see [NLopt Algorithms](NLopt_Algorithms.md) for possible values) and the dimensionality of the problem (`n`, the number of optimization parameters). Whereas the C algorithms are specified by `nlopt_algorithm` constants of the form `NLOPT_MMA`, `NLOPT_COBYLA`, etcetera, the Guile `algorithm` values are of the form `nlopt-MMA`, `nlopt-COBYLA`, etcetera (i.e., underscores are turned into dashes).
32
33 There are also a copy constructor `(new-nlopt-opt` `opt)` to make a copy of a given object (equivalent to `nlopt_copy` in the C API).
34
35 If there is an error in the constructor (or copy constructor, or assignment), an exception is thrown.
36
37 The algorithm and dimension parameters of the object are immutable (cannot be changed without constructing a new object), but you can query them for a given object by the methods:
38
39 ```
40 (nlopt-opt-get-algorithm opt)
41 (nlopt-opt-get-dimension opt)
42 ```
43
44
45 You can get a string description of the algorithm via:
46
47 ```
48 (nlopt-opt-get-algorithm-name opt)
49 ```
50
51
52 ### Relationship to C++ interface
53
54 In general, there is a simple relationship between the Guile interface and the [C++ interface](NLopt_C-plus-plus_Reference.md):
55
56 -   The `nlopt::` namespace becomes a prefix`nlopt-`, and `nlopt::opt` becomes `nlopt-opt-`. (Constants are prefixed with `NLOPT-`, however.)
57 -   Underscores (_) are turned into hyphens (-).
58 -   The `nlopt-opt` object becomes the first parameter of its methods.
59 -   `std::vector`<double> is turned into a Scheme `vector` (a `list` is also supported for input parameters).
60
61 Objective function
62 ------------------
63
64 The objective function is specified by calling one of the methods:
65
66 ```
67 (nlopt-opt-set-min-objective opt f)
68 (nlopt-opt-set-max-objective opt f)
69 ```
70
71
72 depending on whether one wishes to minimize or maximize the objective function `f`, respectively. The function `f` should be of the form:
73
74 ```
75 (define (f x grad)
76    (if grad
77       (begin `*`...set` `grad` `to` `gradient,` `in-place...`*`))
78    return `*`...value` `of` `f(x)...`*`)
79 ```
80
81
82 The return value should be the value of the function at the point `x`, where `x` is a `vector` of length `n` of the optimization parameters (the same as the dimension passed to the constructor).
83
84 In addition, if the argument `grad` is not `#f` (false), then `grad` is a `vector` of length `n` which should (upon return) be set to the gradient of the function with respect to the optimization parameters at `x`. That is, `(vector-ref` `grad` `i)` should upon return contain the partial derivative $\partial f / \partial x_i$, for $0 \leq i < n$, if `grad` is not `#f`. Not all of the optimization algorithms (below) use the gradient information: for algorithms listed as "derivative-free," the `grad` argument will always be empty and need never be computed. (For algorithms that do use gradient information, however, `grad` may still be empty for some calls.)
85
86 Note that `grad` must be modified `in-place` by your function `f`, by using `(vector-set!` `grad` `i` *`value`*`)`.
87
88 Bound constraints
89 -----------------
90
91 The [bound constraints](NLopt_Reference#Bound_constraints.md) can be specified by calling the methods:
92
93 ```
94 (nlopt-opt-set-lower-bounds opt lb)
95 (nlopt-opt-set-lower-bounds opt ub)
96 ```
97
98
99 where `lb` and `ub` are vectors or lists of length *n* (the same as the dimension passed to the `nlopt.opt` constructor). For convenience, these are overloaded with functions that take a single number as arguments, in order to set the lower/upper bounds for all optimization parameters to a single constant.
100
101 To retrieve the values of the lower/upper bounds, you can call one of:
102
103 ```
104 (nlopt-opt-get-lower-bounds opt)
105 (nlopt-opt-get-upper-bounds opt)
106 ```
107
108
109 both of which return vectors.
110
111 To specify an unbounded dimension, you can use `(inf)` or `(-` `(inf))` in Guile to specify ±∞, respectively.
112
113 Nonlinear constraints
114 ---------------------
115
116 Just as for [nonlinear constraints in C](NLopt_Reference#Nonlinear_constraints.md), you can specify nonlinear inequality and equality constraints by the methods:
117
118 ```
119 (nlopt-opt-add-inequality-constraint opt fc tol)
120 (nlopt-opt-add-equality-constraint opt h tol)
121 ```
122
123
124 where the arguments `fc` and `h` have the same form as the objective function above. The (optional) `tol` arguments specify a tolerance in judging feasibility for the purposes of stopping the optimization, as in C (defaulting to zero if they are omitted).
125
126 To remove all of the inequality and/or equality constraints from a given problem, you can call the following methods:
127
128 ```
129 (nlopt-opt-remove-inequality-constraints opt)
130 (nlopt-opt-remove-equality-constraints opt)
131 ```
132
133
134 Stopping criteria
135 -----------------
136
137 As explained in the [C API Reference](NLopt_Reference#Stopping_criteria.md) and the [Introduction](NLopt_Introduction#Termination_conditions.md)), you have multiple options for different stopping criteria that you can specify. (Unspecified stopping criteria are disabled; i.e., they have innocuous defaults.)
138
139 For each stopping criteria, there are (at least) two method: a `set` method to specify the stopping criterion, and a `get` method to retrieve the current value for that criterion. The meanings of each criterion are exactly the same as in the C API.
140
141 ```
142 (nlopt-opt-set-stopval opt stopval)
143 (nlopt-opt-get-stopval opt)
144 ```
145
146
147 Stop when an objective value of at least `stopval` is found.
148
149 ```
150 (nlopt-opt-set-ftol-rel opt tol)
151 (nlopt-opt-get-ftol-rel opt tol)
152 ```
153
154
155 Set relative tolerance on function value.
156
157 ```
158 (nlopt-opt-set-ftol-abs opt tol)
159 (nlopt-opt-get-ftol-abs opt tol)
160 ```
161
162
163 Set absolute tolerance on function value.
164
165 ```
166 (nlopt-opt-set-xtol-rel opt tol)
167 (nlopt-opt-get-xtol-rel opt tol)
168 ```
169
170
171 Set relative tolerance on optimization parameters.
172
173 ```
174 (nlopt-opt-set-xtol-abs opt tol)
175 (nlopt-opt-get-xtol-abs opt tol)
176 ```
177
178
179 Set absolute tolerances on optimization parameters. The `tol` input must be a vector or list of length `n` (the dimension specified in the `nlopt.opt` constructor); alternatively, you can pass a single number in order to set the same tolerance for all optimization parameters. `get-xtol-abs()` returns the tolerances as a vector.
180
181 ```
182 (nlopt-opt-set-maxeval opt maxeval)
183 (nlopt-opt-get-maxeval opt)
184 ```
185
186
187 Stop when the number of function evaluations exceeds `maxeval`. (0 or negative for no limit.)
188
189 ```
190 (nlopt-opt-set-maxtime opt maxtime)
191 (nlopt-opt-get-maxtime opt)
192 ```
193
194
195 Stop when the optimization time (in seconds) exceeds `maxtime`. (0 or negative for no limit.)
196
197 Performing the optimization
198 ---------------------------
199
200 Once all of the desired optimization parameters have been specified in a given object `opt`, you can perform the optimization by calling:
201
202 ```
203 (nlopt-opt-optimize opt x)
204 ```
205
206
207 On input, `x` is a vector or list of length `n` (the dimension of the problem from the `nlopt.opt` constructor) giving an initial guess for the optimization parameters. The return value is a vector containing the optimized values of the optimization parameters.
208
209 You can call the following methods to retrieve the optimized objective function value from the last `optimize` call, and also the return code (including negative/failure return values) from the last `optimize` call:
210
211 ```
212 (nlopt-opt-last-optimum-value opt)
213 (nlopt-opt-last-optimize-result opt)
214 ```
215
216
217 The return code (see below) is positive on success, indicating the reason for termination. On failure (negative return codes), `optimize` throws an exception (see [Exceptions](#Exceptions.md), below).
218
219 ### Return values
220
221 The possible return values are the same as the [return values in the C API](NLopt_Reference#Return_values.md), except that the `NLOPT_` prefix is replaced with the `NLOPT-` namespace. That is, `NLOPT_SUCCESS` becomes `NLOPT-SUCCESS`, etcetera.
222
223 Exceptions
224 ----------
225
226 The [Error codes (negative return values)](NLopt_Reference#Error_codes_(negative_return_values).md) in the C API are replaced in the Guile API by thrown exceptions. The exception key takes the form of a Scheme symbol. The following exception keys are thrown by the various routines:
227
228 ```
229 runtime-error
230 ```
231
232 Generic failure, equivalent to `NLOPT_FAILURE`.
233
234 ```
235 invalid-argument
236 ```
237
238 Invalid arguments (e.g. lower bounds are bigger than upper bounds, an unknown algorithm was specified, etcetera), equivalent to `NLOPT_INVALID_ARGS`.
239
240 ```
241 bad-alloc
242 ```
243
244 Ran out of memory (a memory allocation failed), equivalent to `NLOPT_OUT_OF_MEMORY`.
245
246 `roundoff-limited` (subclass of `Exception`)
247 Halted because roundoff errors limited progress, equivalent to `NLOPT_ROUNDOFF_LIMITED`.
248
249 `forced-stop` (subclass of `Exception`)
250 Halted because of a [forced termination](#Forced_termination.md): the user called `opt.force_stop()` from the user’s objective function. Equivalent to `NLOPT_FORCED_STOP`.
251
252 Currently, NLopt does not catch any exceptions that you might throw from your objective or constraint functions. (In the future, we might catch these exceptions, halt the optimization gracefully, and then re-throw, as in Python or C++, but this is not yet implemented.) So, throwing an exception in your objective/constraint may result in a memory leak.
253
254 To catch an [exception in Guile](http://www.gnu.org/software/guile/manual/html_node/Exceptions.html), you need to define a [throw-handler](http://www.gnu.org/software/guile/manual/html_node/Throw-Handlers.html) function. For example, the following code calls `nlopt-opt-optimize`, catches *any* exception (a key of `#t` in `catch`), and prints out the error return code:
255
256 ```
257 (define xopt
258    (catch #t 
259       (lambda () (nlopt-opt-optimize opt x))
260       (lambda (key . args)
261          (display "Caught exception ") (display key) (display " ") (display args) (newline)
262          (display "NLopt result ") (display (nlopt-opt-last-optimize-result opt)) (newline)
263          #f)
264        ))
265 ```
266
267
268 Note that the [catch statement](http://www.gnu.org/software/guile/manual/html_node/Catch.html) takes three arguments: the first is a key to catch (\#t for all), the second is a [thunk](https://en.wikipedia.org/wiki/Thunk) function to do whatever it is that might throw exceptions (the equivalent of a C++ `try` block), and the third is a function that is called if there is an exception (the equivalent of a C++ `catch` block). Note that `xopt` is set to the return value of `nlopt-opt-optimize` on success, or `#f` (the return value of our throw handler) on an exception.
269
270 Local/subsidiary optimization algorithm
271 ---------------------------------------
272
273 Some of the algorithms, especially MLSL and AUGLAG, use a different optimization algorithm as a subroutine, typically for local optimization. You can change the local search algorithm and its tolerances by calling:
274
275 ```
276 (nlopt-opt-set-local-optimizer opt local-opt)
277 ```
278
279
280 Here, `local-opt` is another `nlopt-opt` object whose parameters are used to determine the local search algorithm, its stopping criteria, and other algorithm parameters. (However, the objective function, bounds, and nonlinear-constraint parameters of `local-opt` are ignored.) The dimension `n` of `local-opt` must match that of `opt`.
281
282 This function makes a copy of the `local-opt` object, so you can freely change your original `local-opt` afterwards without affecting `opt`.
283
284 Initial step size
285 -----------------
286
287 Just as in the C API, you can [get and set the initial step sizes](NLopt_Reference#Initial_step_size.md) for derivative-free optimization algorithms. The Guile equivalents of the C functions are the following methods:
288
289 ```
290 (nlopt-opt-set-initial-step opt dx)
291 (nlopt-opt-get-initial-step opt x)
292 ```
293
294
295 Here, `dx` is a vector or list of the (nonzero) initial steps for each dimension, or a single number if you wish to use the same initial steps for all dimensions. `nlopt-opt-get-initial-step` returns the initial step (vector) that will be used for a starting guess of `x` in `(nlopt-opt-optimize` `opt` `x)`.
296
297 Stochastic population
298 ---------------------
299
300 Just as in the C API, you can [get and set the initial population](NLopt_Reference#Stochastic_population.md) for stochastic optimization algorithms, by the methods:
301
302 ```
303 (nlopt-opt-set-population opt pop)
304 (nlopt-opt-get-population opt)
305 ```
306
307
308 (A `pop` of zero implies that the heuristic default will be used.)
309
310 Pseudorandom numbers
311 --------------------
312
313 For stochastic optimization algorithms, we use pseudorandom numbers generated by the [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_twister) algorithm, based on code from Makoto Matsumoto. By default, the [seed](https://en.wikipedia.org/wiki/Random_seed) for the random numbers is generated from the system time, so that you will get a different sequence of pseudorandom numbers each time you run your program. If you want to use a "deterministic" sequence of pseudorandom numbers, i.e. the same sequence from run to run, you can set the seed by calling:
314
315 ```
316 (nlopt-srand seed)
317 ```
318
319
320 where `seed` is an integer. o reset the seed based on the system time, you can call:
321
322 ```
323 (nlopt-srand-time)
324 ```
325
326
327 (Normally, you don't need to call this as it is called automatically. However, it might be useful if you want to "re-randomize" the pseudorandom numbers after calling `nlopt-srand` to set a deterministic seed.)
328
329 Vector storage for limited-memory quasi-Newton algorithms
330 ---------------------------------------------------------
331
332 Just as in the C API, you can get and set the [number *M* of stored vectors](NLopt_Reference#Vector_storage_for_limited-memory_quasi-Newton_algorithms.md) for limited-memory quasi-Newton algorithms, via the functions:
333
334 ```
335 (nlopt-opt-set-vector-storage opt M)
336 (nlopt-opt-get-vector-storage opt)
337 ```
338
339
340 (The default is *M*=0, in which case NLopt uses a heuristic nonzero value.)
341
342 Version number
343 --------------
344
345 To determine the version number of NLopt at runtime, you can call:
346
347 ```
348 (nlopt-version-major)
349 (nlopt-version-minor)
350 (nlopt-version-bugfix)
351 ```
352
353
354 For example, NLopt version 3.1.4 would return `major=3`, `minor=1`, and `bugfix=4`.
355
356 [Category:NLopt](index.md)