NAME
Math::NLopt - Math::NLopt - Perl interface to the NLopt optimization library
VERSION
version 0.12
SYNOPSIS
use Math::NLopt ':algorithms';
my $opt = Math::NLopt->new( NLOPT_LD_MMA, 2 );
$opt->set_lower_bounds( [ -HUGE_VAL(), 0 ] );
$opt->set_min_objective( sub ( $x, $grad, $data ) { ... } );
$opt->set_xtol_rel( ... );
\@optimized_pars = $opt->optimize( \@initial_pars );
DESCRIPTION
NLopt is a
library for nonlinear local and global optimization, for functions
with and without gradient information. It is designed as a simple,
unified interface and packaging of several free/open-source
nonlinear optimization libraries.
Math::NLopt is a Perl binding to NLopt. It uses the Alien::NLopt module to find or install a Perl local instance of the NLopt library.
This module provides an interface using native Perl arrays.
The main documentation for NLopt may be found at https://nlopt.readthedocs.io/; this document focuses on the Perl specific implementation, which is more Perlish than the C API (and is very similar to the Python one).
API
The Perl API uses an object, constructed by the "new" class method, to maintain state. The optimization process is controlled by invoking methods on the object.
In general results are returned directly from the methods; method parameters are used primarily as input data for the methods (the objective and constraint callbacks more closely follow the C API).
The Perl methods are named similarly to the C functions, e.g.
nlopt_<method>( opt, ... );
becomes
$opt->method( ... );
Where $opt is provided by the "new" class method.
As an example, the C API for starting the optimization process is
nlopt_result nlopt_optimize(nlopt_opt opt, double *x, double *opt_f);
where x is used for both passing in the initial model parameters as well as retrieving their final values. The final value of the optimization function is stored in opt_f. A code specifying the success or failure of the process is returned.
The Perl interface (similar to the Python and C++ versions) is
\@final = $opt->optimize( \@initial_pars );
$opt_f = $opt->last_optimum_value;
$result_code = $opt->last_optimize_result;
The Perl API throws exceptions on failures, similar to the behavior of the C++ and Python APIs. Where the C API returns an error code, Math::NLopt normally returns the corresponding numeric result code on success and throws an object in the corresponding exception class on failure. These classes extend Math::NLopt::Exception; see it for more information on retrieving messages from the objects.
Constants
Math::NLopt defines constants for the optimization algorithms, result codes, and utilities.
The algorithm constants have the same names as the NLopt constants, and may be imported individually by name or en-masse with the ':algorithms' tag:
use Math::NLopt 'NLOPT_LD_MMA';
use Math::NLopt ':algorithms';
Importing result codes is similar:
use Math::NLopt 'NLOPT_FORCED_STOP';
use Math::NLopt ':results';
NLopt Results, Errors and Exceptions
Result codes
While most methods (excluding "new" and "optimize") return a result code of NLOPT_SUCCESS upon success, they will all throw on error.
Methods returning arrays or other values either return that value or throw if the underlying operation fails.
Exceptions
Math::NLopt will throw exceptions if the underlying NLopt library detects an error.
Unfortunately, this behavior affects the results returned by "optimize", which are lost when an exception is raised. Depending upon the error, the results may actually be valid, so this is truly unfortunate.
There are a couple of ways to avoid the loss of information.
The simplest is to retrieve them via the "last_optimum_params" method.
Disable exceptions from NLopt result codes for "optimize" via the "set_exceptions_enabled" method. This is the approach used by the Python and C++ APIs.
"optimize" will always return the last set of evaluated parameters. However, the caller will have to call "last_optimize_result" to determine how the optimization concluded, and whether the results are valid.
Disabling exceptions only affects errors reported by "optimize". Other methods continue to throw exceptions, and exceptions thrown by user-provided objective, constraint, or pre-conditioner callbacks are always propagated.
Callbacks
NLopt handles the optimization of the objective function, relying upon user provided subroutines to calculate the objective function and non-linear constraints (see below for the required calling signature).
The callback subroutines are called with a user-provided structure which can be used to pass additional information to the callback (or the subroutines can use closures).
Exceptions thrown by Callback subroutines
Exceptions thrown by callback subroutines during processing by "optimize" are caught so that they do not unwind through the NLopt C stack. The optimization is halted with a forced stop (as if by "force_stop") and the original exception is rethrown after NLopt has returned. "last_optimize_result" will return NLOPT_FORCED_STOP.
Objective Functions
Objective functions callbacks are registered via either
$opt->set_min_objective( \&func, ?$data );
$opt->set_max_objective( \&func, ?$data );
where $data is an optional scalar, reference, or other Perl value passed to the callback unchanged.
The objective function has the signature
$value = sub ( \@params, \@gradient, $data ) { ... }
It returns the value of the optimization function for the passed set parameters, @params.
if \@gradient is not undef, it must be filled in by the objective function.
$data is the value registered with the callback. It will be undef if none was provided.
Non-linear Constraints
Scalar-valued Constraints
Scalar constraint callbacks are registered via either of
$opt->add_equality_constraint( \&func, %options );
$opt->add_inequality_constraint( \&func, %options );
%options accepts the following entries.
tolscalar [optional]-
The tolerance. Defaults to
0. data[optional]-
A structure passed to the callback function.
The constraint function has the signature
$value = sub ( \@params, \@gradient, $data ) { ... }
and must return exactly one numeric value, the value of the constraint function for the passed set of parameters, @params.
Vector-valued Constraints
Vector-valued callbacks are registered via either of
$opt->add_equality_mconstraint( \&func, %options );
$opt->add_inequality_mconstraint( \&func, %options );
%options accepts the following entries.
minteger-
The length of the vector.
tolarrayref-
An array of length
mcontaining the tolerance for each component of the vector. data[optional]-
an optional scalar, reference, or other Perl value passed to the callback unchanged.
One of m or tol must be provided. If tol is provided without m, its length is used for m. If both are provided, the number of array elements in tol must be equal to m.
Vector valued constraints callbacks have the signature
sub ( \@result, \@params, \@gradient, $data ) { ... }
The $m length vector of constraints should be stored in \@result. If \@gradient is not undef, it is an $m by $n two-dimensional array which should be filled by the callback.
The outer dimension indexes the $m constraint components, and the inner dimension indexes the $n optimization parameters; in other words, $gradient->[$i][$j] is the derivative of constraint $i with respect to parameter $j.
$data is the optional structure passed to the callback.
Preconditioned Objectives
These are registered via one of
$opt->set_precond_min_objective( \&func, \&precond, ?$data);
$opt->set_precond_max_objective( \&func, \&precond, ?$data);
\&func has the same signature as before (see "Objective Functions"), and $data is as before.
The \&precond fallback has this signature:
sub (\@x, \@v, \@vpre, $data) {...}
\@x, \@v, and \@vpre are arrays of length $n. \@x and \@v are inputs. \@vpre must be filled in by the routine before it returns.
CONSTRUCTORS
new
my $opt = Math::NLopt->new( $algorithm, $n );
Create an optimization object for the given algorithm and number of parameters. $algorithm is one of the algorithm constants, e.g.
use Math::NLopt 'NLOPT_LD_MMA';
my $opt = Math::NLopt->new( NLOPT_LD_MMA, 3 );
$n must be a positive integer.
Invalid inputs or failure to create the underlying NLopt object results in an exception.
METHODS
Most methods have the same calling signature as their C versions, but not all!
add_equality_constraint
$opt->add_equality_constraint( \&func, %options );
See "Scalar-valued Constraints".
Returns an NLopt result code, normally NLOPT_SUCCESS.
add_equality_mconstraint
$opt->add_equality_mconstraint( \&func, %options );
See "Vector-valued Constraints".
Returns an NLopt result code, normally NLOPT_SUCCESS.
add_inequality_constraint
$opt->add_inequality_constraint( \&func, %options );
See "Scalar-valued Constraints".
Returns an NLopt result code, normally NLOPT_SUCCESS.
add_inequality_mconstraint
$opt->add_inequality_mconstraint( \&func, %options );
See "Vector-valued Constraints".
Returns an NLopt result code, normally NLOPT_SUCCESS.
force_stop
$opt->force_stop;
Requests that the current optimization stop. Returns an NLopt result code.
get_algorithm
$algorithm_int_id = $opt->get_algorithm;
get_dimension
$n = $opt->get_dimension;
get_exceptions_enabled
$bool = $opt->get_exceptions_enabled;
Returns true if errors in the "optimize" method will result in exceptions.
get_errmsg
$string = $opt->get_errmsg;
Returns the most recent error message from NLopt.
get_force_stop
$stop = $opt->get_force_stop;
get_ftol_abs
$tol = $opt->get_ftol_abs;
get_ftol_rel
$tol = $opt->get_ftol_rel;
get_initial_step
\@steps = $opt->get_initial_step( \@init_x );
Returns an arrayref of initial steps for the supplied parameter vector, which must of length $n, the length passed to "new".
get_lower_bounds
\@lb = $opt->get_lower_bounds;
get_maxeval
$max_eval = $opt->get_maxeval;
get_maxtime
$max_time = $opt->get_maxtime;
get_numevals
$num_evals = $opt->get_numevals;
get_param
$val = $opt->get_param( $name, $defaultval);
Return parameter value, or $defaultval if not set.
get_population
$pop = $opt->get_population;
get_stopval
$val = $opt->get_stopval;
get_upper_bounds
\@ub = $opt->get_upper_bounds;
get_vector_storage
$dim = $opt->get_vector_storage;
get_x_weights
\@weights = $opt->get_x_weights;
get_xtol_abs
\@tol = $opt->get_xtol_abs;
get_xtol_rel
$tol = $opt->get_xtol_rel;
has_param
$bool = $opt->has_param( $name );
True if the parameter with $name was set.
nth_param
$name = $opt->nth_param( $i );
Return the name of algorithm specific parameter $i.
last_optimize_result
$result_code = $opt->last_optimize_result;
Return the result code after an optimization. Returns NLOPT_FAILURE prior to the first optimization.
last_optimum_value
$min_f = $opt->last_optimum_value;
Return the objective value obtained during the last call to "optimize". Returns NaN prior to the first call.
last_optimum_params
\@params = $opt->last_optimum_params;
Returns the final parameter vector recorded by the last call to "optimize". It is also updated when "optimize" stops with an NLopt error or a callback exception, so it can be used to inspect the last available result after catching an exception.
num_params
$n_algo_params = $opt->num_params;
Return the number of algorithm specific parameters.
optimize
\@optimized_pars = $opt->optimize( \@input_pars );
Returns the parameter values determined from the optimization. The status of the optimization (e.g. NLopt's result code) can be retrieved via the "last_optimize_result" method. The final value of the objective function is available via the "last_optimum_value" method.
The input arrayref must have length $n. With exceptions enabled, NLopt errors cause this method to throw instead of returning a parameter vector; use "last_optimum_params" to retrieve the vector recorded before the error. With exceptions disabled, NLopt errors are reported by "last_optimize_result" and the recorded parameter vector is returned. Exceptions raised by callbacks are always rethrown.
See "Exceptions thrown by Callback subroutines" for how callback exceptions are handled.
remove_equality_constraints
$opt->remove_equality_constraints;
Returns an NLopt result code.
remove_inequality_constraints
$opt->remove_inequality_constraints;
Returns an NLopt result code.
set_exceptions_enabled
$opt->set_exceptions_enabled( $bool );
Controls whether NLopt result-code failures from "optimize" are thrown. The default is true. This setting does not suppress exceptions from other methods or from callbacks.
set_force_stop
$opt->set_force_stop( $val );
Returns an NLopt result code.
set_ftol_abs
$opt->set_ftol_abs( $tol );
Returns an NLopt result code.
set_ftol_rel
$opt->set_ftol_rel( $tol );
Returns an NLopt result code.
set_initial_step
$opt->set_initial_step(\@dx);
Set the initial step. @dx must have length $n, the length passed to "new".
Returns an NLopt result code.
set_initial_step1
$opt->set_initial_step1( $dx );
Sets the same initial step $dx for every parameter.
Returns an NLopt result code.
set_local_optimizer
$opt->set_local_optimizer( $local_opt );
Sets the local optimizer used by a composite algorithm. $local_opt must be another Math::NLopt optimizer object.
Returns an NLopt result code.
set_lower_bound
$opt->set_lower_bound( $i, $lb );
Set the lower bound for parameter $i (zero based) to $lb.
Returns an NLopt result code.
set_lower_bounds
$opt->set_lower_bounds(\@lb);
@lb must have length $n, the length passed to "new".
Returns an NLopt result code.
set_lower_bounds1
$opt->set_lower_bounds1( $lb );
Sets the same lower bound $lb for every parameter.
Returns an NLopt result code.
set_max_objective
$opt->set_max_objective( \&func, ?$data );
Returns an NLopt result code.
set_maxeval
$opt->set_maxeval( $max_iterations );
Returns an NLopt result code.
set_maxtime
$opt->set_maxtime( $time );
Returns an NLopt result code.
set_min_objective
$opt->set_min_objective( \&func, ?$data );
Returns an NLopt result code.
set_param
$opt->set_param( $name, $value );
Returns an NLopt result code.
set_population
$opt->set_population( $pop );
Returns an NLopt result code.
set_precond_max_objective
$opt->set_precond_max_objective( \&func, \&precond, ?$data);
Returns an NLopt result code.
See "Preconditioned Objectives"
set_precond_min_objective
$opt->set_precond_min_objective( \&func, \&precond, ?$data);
See "Preconditioned Objectives"
Returns an NLopt result code.
set_stopval
$opt->set_stopval( $stopval);
Returns an NLopt result code.
set_upper_bound
$opt->set_upper_bound( $i, $ub );
Set the upper bound for parameter $i (zero based) to $ub
Returns an NLopt result code.
set_upper_bounds
$opt->set_upper_bounds(\@ub);
@ub must have length $n, the length passed to "new".
Returns an NLopt result code.
set_upper_bounds1
$opt->set_upper_bounds1( $ub );
Sets the same upper bound $ub for every parameter.
Returns an NLopt result code.
set_vector_storage
$opt->set_vector_storage( $dim );
Sets the amount of vector storage used by the algorithm.
Returns an NLopt result code.
set_x_weights
$opt->set_x_weights( \@weights );
@weights must have length $n, the length passed to "new".
Returns an NLopt result code.
set_x_weights1
$opt->set_x_weights1( $weight );
Sets the same weight for every parameter.
Returns an NLopt result code.
set_xtol_abs
$opt->set_xtol_abs( \@tol );
@tol must have length $n, the length passed to "new".
Returns an NLopt result code.
set_xtol_abs1
$opt->set_xtol_abs1( $tol );
Sets the same absolute tolerance for every parameter.
Returns an NLopt result code.
set_xtol_rel
$opt->set_xtol_rel( $tol );
Returns an NLopt result code.
SUBROUTINES
These are exportable individually, or en-masse via the :utils tag, but beware that srand has same name as the Perl srand routine, and version is rather generic.
algorithm_from_string
$algorithm_int_id = algorithm_from_string( $algorithm_string_id );
return an integer id (e.g. NLOPT_LD_MMA) from a string id (e.g. 'LD_MMA').
algorithm_name
$algorithm_name = algorithm_from_string( $algorithm_int_id );
return a descriptive name from an integer id
algorithm_to_string
$algorithm_string_id = algorithm_to_string( $algorithm_int_id );
result_from_string
$result_int_id = result_from_string( $result_string_id );
return an integer id (e.g. NLOPT_SUCCESS) from a string id (e.g. 'SUCCESS').
result_to_string
$result_string_id = result_to_string( $result_int_id );
srand
srand( $seed )
srand_time
version
($major, $minor, $bugfix ) = Math::NLopt::version()
CONSTANTS
Result Codes
These are constants available for import individually, or in bulk via the :result tag.
NLOPT_FAILURE
NLOPT_FORCED_STOP
NLOPT_FTOL_REACHED
NLOPT_INVALID_ARGS
NLOPT_MAXEVAL_REACHED
NLOPT_MAXTIME_REACHED
NLOPT_MINF_MAX_REACHED
NLOPT_NUM_FAILURES
NLOPT_NUM_RESULTS
NLOPT_OUT_OF_MEMORY
NLOPT_ROUNDOFF_LIMITED
NLOPT_STOPVAL_REACHED
NLOPT_SUCCESS
NLOPT_XTOL_REACHED
Algorithms
These are constants available for import individually, or in bulk via the :algorithms tag.
NLOPT_AUGLAG
NLOPT_AUGLAG_EQ
NLOPT_GD_MLSL
NLOPT_GD_MLSL_LDS
NLOPT_GD_STOGO
NLOPT_GD_STOGO_RAND
NLOPT_GN_AGS
NLOPT_GN_CRS2_LM
NLOPT_GN_DIRECT
NLOPT_GN_DIRECT_L
NLOPT_GN_DIRECT_L_NOSCAL
NLOPT_GN_DIRECT_L_RAND
NLOPT_GN_DIRECT_L_RAND_NOSCAL
NLOPT_GN_DIRECT_NOSCAL
NLOPT_GN_ESCH
NLOPT_GN_ISRES
NLOPT_GN_MLSL
NLOPT_GN_MLSL_LDS
NLOPT_GN_ORIG_DIRECT
NLOPT_GN_ORIG_DIRECT_L
NLOPT_G_MLSL
NLOPT_G_MLSL_LDS
NLOPT_LD_AUGLAG
NLOPT_LD_AUGLAG_EQ
NLOPT_LD_CCSAQ
NLOPT_LD_LBFGS
NLOPT_LD_MMA
NLOPT_LD_SLSQP
NLOPT_LD_TNEWTON
NLOPT_LD_TNEWTON_PRECOND
NLOPT_LD_TNEWTON_PRECOND_RESTART
NLOPT_LD_TNEWTON_RESTART
NLOPT_LD_VAR1
NLOPT_LD_VAR2
NLOPT_LN_AUGLAG
NLOPT_LN_AUGLAG_EQ
NLOPT_LN_BOBYQA
NLOPT_LN_COBYLA
NLOPT_LN_NELDERMEAD
NLOPT_LN_NEWUOA
NLOPT_LN_NEWUOA_BOUND
NLOPT_LN_PRAXIS
NLOPT_LN_SBPLX
NLOPT_NUM_ALGORITHMS
SUPPORT
Bugs
Please report any bugs or feature requests to bug-math-nlopt@rt.cpan.org or through the web interface at: https://rt.cpan.org/Public/Dist/Display.html?Name=Math-NLopt
Source
Source is available at
https://codeberg.org/djerius/p5-Math-NLopt
and may be cloned from
https://codeberg.org/djerius/p5-Math-NLopt.git
SEE ALSO
Please see those modules/websites for more information related to this module.
AUTHOR
Diab Jerius <djerius@cpan.org>
COPYRIGHT AND LICENSE
This software is Copyright (c) 2024 by Smithsonian Astrophysical Observatory.
This is free software, licensed under:
The GNU General Public License, Version 3, June 2007