stevengj / nlopt

library for nonlinear optimization, wrapping many algorithms for global and local, constrained or unconstrained, optimization
Other
1.85k stars 570 forks source link

Returning number of function evaluations/iterations with python interface #159

Closed abrahamnunes closed 6 years ago

abrahamnunes commented 6 years ago

Hi all,

Sorry if this is the wrong place to post this question. Let me know, and if so I will move as necessary.

I'm running an experiment where I'm using BOBYQA from the nlopt package, I need to return the number of function evaluations and the number of iterations taken until solution. Perhaps I'm missing something somewhere in the documentation, but I can't seem to find out how to get these values with the Python interface.

Here is a simple demo program:

import numpy as np
import nlopt

xatol  = 1e-6
fatol  = 1e-6
maxfev = 1e7

def f(x, grad):
    return np.sum(x**2)

x0 = np.random.uniform(-100, 100, size=2)
opt = nlopt.opt(nlopt.LN_BOBYQA, len(x0))

opt.set_min_objective(f) # Sets objective function
opt.set_xtol_abs(xatol)  # Absolute X tolerance
opt.set_ftol_abs(fatol)  # Absolute f tolerance
opt.set_maxeval(int(maxfev))  # Maximum number of function evaluations

xmin = opt.optimize(x0)
fmin = opt.last_optimum_value()

print(xmin)
print(fmin)
print(nlopt.SUCCESS)
print(nlopt.WANT_N_ITERATIONS_HERE)
print(nlopt.WANT_N_FUNC_EVALS_HERE)

Any help will be much appreciated.

Cheers,

Abe

stevengj commented 6 years ago

Just increment a global counter in your objective function. (Or if you don't want to use a global, pass in the counter via a closure.)

stevengj commented 6 years ago

I guess we could provide a function to get this from opt, but it would have to be added in the underlying C library first.

jschueller commented 6 years ago

https://github.com/stevengj/nlopt/pull/160

abrahamnunes commented 6 years ago

Many thanks!

constructor-igor commented 6 years ago

please, could you publish sample how to get the iterations number? I cannot find a relevant method in nlopt '2.5.0'.

jschueller commented 6 years ago

you can try (recent git version only): opt.get_numevals()

constructor-igor commented 6 years ago

please, could you inform when are you going to release new nlopt version, which will include the method?

jschueller commented 6 years ago

A release is long overdue, but @stevengj is busy.