chiark / gitweb /
Fix math layout
[nlopt.git] / doc / docs / NLopt_Python_Reference.md
1 ---
2 # NLopt Python Reference
3 ---
4
5 The NLopt includes an interface callable from the [Python programming language](https://en.wikipedia.org/wiki/Python_(programming_language)).
6
7 The main purpose of this section is to document the syntax and unique features of the Python 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 Python API
10 --------------------------
11
12 To use NLopt in Python, your Python program should include the lines:
13
14 ```
15 import nlopt
16 from numpy import *
17 ```
18
19
20 which imports the `nlopt` module, and also imports the numpy ([NumPy](https://en.wikipedia.org/wiki/NumPy)) that defines the array data types used for communicating with NLopt.
21
22 The `nlopt.opt` class
23 ---------------------
24
25 The NLopt API revolves around an object of type `nlopt.opt`. 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:
26
27 ```
28 opt = nlopt.opt(algorithm, n)
29 ```
30
31
32 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_LD_MMA`, `NLOPT_LN_COBYLA`, etcetera, the Python `algorithm` values are of the form `nlopt.LD_MMA`, `nlopt.LN_COBYLA`, etcetera (with the `NLOPT_` prefix replaced by the `nlopt.` namespace).
33
34 There are also a copy constructor `nlopt.opt(opt)` to make a copy of a given object (equivalent to `nlopt_copy` in the C API).
35
36 If there is an error in the constructor (or copy constructor, or assignment), a `MemoryError` exception is thrown.
37
38 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:
39
40 ```
41 opt.get_algorithm()
42 opt.get_dimension()
43 ```
44
45
46 You can get a string description of the algorithm via:
47
48 ```
49 opt.get_algorithm_name()
50 ```
51
52
53 Objective function
54 ------------------
55
56 The objective function is specified by calling one of the methods:
57
58 ```
59 opt.set_min_objective(f)
60 opt.set_max_objective(f)
61 ```
62
63
64 depending on whether one wishes to minimize or maximize the objective function `f`, respectively. The function `f` should be of the form:
65
66 ```
67 def f(x, grad):
68    if grad.size > 0:
69 ```
70
71 `       `*`...set` `grad` `to` `gradient,` `in-place...`*
72 `   return `*`...value` `of` `f(x)...`*
73
74 The return value should be the value of the function at the point `x`, where `x` is a NumPy array of length `n` of the optimization parameters (the same as the dimension passed to the constructor).
75
76 In addition, if the argument `grad` is not empty, i.e. `grad.size>0`, then `grad` is a NumPy array 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, `grad[i]` should upon return contain the partial derivative $\partial f / \partial x_i$, for $0 \leq i < n$, if `grad` is non-empty. 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.)
77
78 Note that `grad` must be modified *in-place* by your function `f`. Generally, this means using indexing operations `grad[...]` `=` `...` to overwrite the contents of `grad`, as described below.
79
80 ### Assigning results in-place
81
82 Your objective and constraint functions must overwrite the contents of the `grad` (gradient) argument in-place (although of course you can allocate whatever additional storage you might need, in addition to overwriting `grad`). However, typical Python assignment operations do *not* do this. For example:
83
84 ```
85 grad = 2*x
86 ```
87
88
89 might seem like the gradient of the function `sum(x**2)`, but it will *not work* with NLopt because this expression actually allocates a *new* array to store `2*x` and re-assigns `grad` to point to it, rather than overwriting the old contents of `grad`. Instead, you should do:
90
91 ```
92 grad[:] = 2*x
93 ```
94
95
96 Assigning any [slice or view](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) `grad[...]` of the array will overwrite the contents, which is what NLopt needs you to do. So, you should generally use indexing expressions `grad[...]` `=` `...` to assign the gradient result.
97
98 In specific cases, there are a few other NumPy and SciPy functions that are documented to operate in-place on their arguments, and you can also use such functions to modify `grad` if you want. If a function is not *explicitly documented to modify its arguments in-place*, however, you should assume that it does *not*.
99
100 Bound constraints
101 -----------------
102
103 The [bound constraints](NLopt_Reference#Bound_constraints.md) can be specified by calling the methods:
104
105 ```
106 opt.set_lower_bounds(lb)
107 opt.set_upper_bounds(ub)
108 ```
109
110
111 where `lb` and `ub` are arrays (NumPy arrays or Python 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.
112
113 To retrieve the values of the lower/upper bounds, you can call one of:
114
115 ```
116 opt.get_lower_bounds()
117 opt.get_upper_bounds()
118 ```
119
120
121 both of which return NumPy arrays.
122
123 To specify an unbounded dimension, you can use ±`float('inf')` (or ±`numpy.inf`) in Python to specify ±∞.
124
125 Nonlinear constraints
126 ---------------------
127
128 Just as for [nonlinear constraints in C](NLopt_Reference#Nonlinear_constraints.md), you can specify nonlinear inequality and equality constraints by the methods:
129
130 ```
131 opt.add_inequality_constraint(fc, tol=0)
132 opt.add_equality_constraint(h, tol=0)
133 ```
134
135
136 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.
137
138 To remove all of the inequality and/or equality constraints from a given problem, you can call the following methods:
139
140 ```
141 opt.remove_inequality_constraints()
142 opt.remove_equality_constraints()
143 ```
144
145
146 ### Vector-valued constraints
147
148 Just as for [nonlinear constraints in C](NLopt_Reference#Vector-valued_constraints.md), you can specify vector-valued nonlinear inequality and equality constraints by the methods
149
150 ```
151 opt.add_inequality_mconstraint(c, tol)
152 opt.add_inequality_mconstraint(c, tol)
153 ```
154
155
156 Here, `tol` is an array (NumPy array or Python list) of the tolerances in each constraint dimension; the dimensionality *m* of the constraint is determined by `tol.size`. The constraint function `c` must be of the form:
157
158 ```
159 def c(result, x, grad):
160    if grad.size > 0:
161 ```
162
163 `       `*`...set` `grad` `to` `gradient,` `in-place...`*
164 `   result[0] = `*`...value` `of` `c`<sub>`0`</sub>`(x)...`*
165 `   result[1] = `*`...value` `of` `c`<sub>`1`</sub>`(x)...`*
166 ```
167    ...
168 ```
169
170
171 `result` is a NumPy array whose length equals the dimensionality *m* of the constraint (same as the length of `tol` above), which upon return should be set *in-place* ([see above](#Assigning_results_in-place.md)) to the constraint results at the point `x` (a NumPy array whose length *n* is the same as the dimension passed to the constructor). Any return value of the function is ignored.
172
173 In addition, if the argument `grad` is not empty, i.e. `grad.size>0`, then `grad` is a 2d NumPy array of size *m*×*n* which should (upon return) be set in-place ([see above](#Assigning_results_in-place.md)) to the gradient of the function with respect to the optimization parameters at `x`. That is, `grad[i,j]` should upon return contain the partial derivative $\partial c_i / \partial x_j$ if `grad` is non-empty. 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.)
174
175 An inequality constraint corresponds to $c_i \le 0$ for $0 \le i < m$, and an equality constraint corresponds to $c_i = 0$, in both cases with tolerance `tol[i]` for purposes of termination criteria.
176
177 (You can add multiple vector-valued constraints and/or scalar constraints in the same problem.)
178
179 Stopping criteria
180 -----------------
181
182 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.)
183
184 For each stopping criteria, there are (at least) two methods: 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.
185
186 ```
187 opt.set_stopval(stopval)
188 opt.get_stopval()
189 ```
190
191
192 Stop when an objective value of at least `stopval` is found.
193
194 ```
195 opt.set_ftol_rel(tol)
196 opt.get_ftol_rel()
197 ```
198
199
200 Set relative tolerance on function value.
201
202 ```
203 opt.set_ftol_abs(tol)
204 opt.get_ftol_abs()
205 ```
206
207
208 Set absolute tolerance on function value.
209
210 ```
211 opt.set_xtol_rel(tol)
212 opt.get_xtol_rel()
213 ```
214
215
216 Set relative tolerance on optimization parameters.
217
218 ```
219 opt.set_xtol_abs(tol)
220 opt.get_xtol_abs()
221 ```
222
223
224 Set absolute tolerances on optimization parameters. The `tol` input must be an array (NumPy array or Python 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 NumPy array.
225
226 ```
227 opt.set_maxeval(maxeval)
228 opt.get_maxeval()
229 ```
230
231
232 Stop when the number of function evaluations exceeds `maxeval`. (0 or negative for no limit.)
233
234 ```
235 opt.set_maxtime(maxtime)
236 opt.get_maxtime()
237 ```
238
239
240 Stop when the optimization time (in seconds) exceeds `maxtime`. (0 or negative for no limit.)
241
242
243
244 ```
245 opt.get_numevals()
246 ```
247
248
249 Request the number of evaluations.
250
251
252
253 ### Forced termination
254
255 In certain cases, the caller may wish to *force* the optimization to halt, for some reason unknown to NLopt. For example, if the user presses Ctrl-C, or there is an error of some sort in the objective function. You can do this by raise *any* exception inside your objective/constraint functions:the optimization will be halted gracefully, and the same exception will be raised to the caller. See [Exceptions](#Exceptions.md), below. The Python equivalent of `nlopt_forced_stop` from the [C API](NLopt_Reference#Forced_termination.md) is to throw an `nlopt.ForcedStop` exception.
256
257 Performing the optimization
258 ---------------------------
259
260 Once all of the desired optimization parameters have been specified in a given object `opt`, you can perform the optimization by calling:
261
262 ```
263 xopt = opt.optimize(x)
264 ```
265
266
267 On input, `x` is an array (NumPy array or Python 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 `xopt` is a NumPy array containing the optimized values of the optimization parameters.
268
269 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:
270
271 ```
272 opt_val = opt.last_optimum_value()
273 result = opt.last_optimize_result()
274 ```
275
276
277 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).
278
279 ### Return values
280
281 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.
282
283 Exceptions
284 ----------
285
286 The [Error codes (negative return values)](NLopt_Reference#Error_codes_(negative_return_values).md) in the C API are replaced in the Python API by thrown exceptions. The following exceptions are thrown by the various routines:
287
288 ```
289 RunTimeError
290 ```
291
292 Generic failure, equivalent to `NLOPT_FAILURE`.
293
294 ```
295 ValueError
296 ```
297
298 Invalid arguments (e.g. lower bounds are bigger than upper bounds, an unknown algorithm was specified, etcetera), equivalent to `NLOPT_INVALID_ARGS`.
299
300 ```
301 MemoryError
302 ```
303
304 Ran out of memory (a memory allocation failed), equivalent to `NLOPT_OUT_OF_MEMORY`.
305
306 `nlopt.RoundoffLimited` (subclass of `Exception`)
307 Halted because roundoff errors limited progress, equivalent to `NLOPT_ROUNDOFF_LIMITED`.
308
309 `nlopt.ForcedStop` (subclass of `Exception`)
310 Halted because of a [forced termination](#Forced_termination.md): the user called `opt.force_stop()` from the user’s objective function or threw an `nlopt.ForcedStop` exception. Equivalent to `NLOPT_FORCED_STOP`.
311
312 If your objective/constraint functions throw *any* exception during the execution of `opt.optimize`, it will be caught by NLopt and the optimization will be halted gracefully, and `opt.optimize` will re-throw the *same* exception to its caller.
313
314 Local/subsidiary optimization algorithm
315 ---------------------------------------
316
317 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:
318
319 ```
320 opt.set_local_optimizer(local_opt)
321 ```
322
323
324 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`.
325
326 This function makes a copy of the `local_opt` object, so you can freely change your original `local_opt` afterwards without affecting `opt`.
327
328 Initial step size
329 -----------------
330
331 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 Python equivalents of the C functions are the following methods:
332
333 ```
334 opt.set_initial_step(dx)
335 opt.get_initial_step(x)
336 ```
337
338
339 Here, `dx` is an array (NumPy array or Python 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. `opt.get_initial_step(x)` returns the initial step that will be used for a starting guess of `x` in `opt.optimize(x)`.
340
341 Stochastic population
342 ---------------------
343
344 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:
345
346 ```
347 opt.set_population(pop)
348 opt.get_population()
349 ```
350
351
352 (A `pop` of zero implies that the heuristic default will be used.)
353
354 Pseudorandom numbers
355 --------------------
356
357 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:
358
359 ```
360 nlopt.srand(seed)
361 ```
362
363
364 where `seed` is an integer. To reset the seed based on the system time, you can call:
365
366 ```
367 nlopt.srand_time()
368 ```
369
370
371 (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.)
372
373 Vector storage for limited-memory quasi-Newton algorithms
374 ---------------------------------------------------------
375
376 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 methods:
377
378 ```
379 opt.set_vector_storage(M)
380 opt.get_vector_storage()
381 ```
382
383
384 (The default is *M*=0, in which case NLopt uses a heuristic nonzero value.)
385
386 Version number
387 --------------
388
389 To determine the version number of NLopt at runtime, you can call:
390
391 ```
392 nlopt.version_major()
393 nlopt.version_minor()
394 nlopt.version_bugfix()
395 ```
396
397
398 For example, NLopt version 3.1.4 would return `major=3`, `minor=1`, and `bugfix=4`.
399
400 [Category:NLopt](index.md)