Registry / data / nlopt
library2.11.0pypypi✓ verified 23d ago

NLopt is a free/open-source library providing a common interface to a variety of nonlinear optimization algorithms, encompassing both global and local, constrained and unconstrained problems. The `nlopt` Python package offers bindings to this library, enabling Python users to leverage its extensive suite of optimization routines. The current version is 2.10.0, and the project actively maintains and releases new versions, often aligning with updates to the underlying C library.

pip install nlopt
INSTALL
IMPORT
SIG · NLOPT
N
nlopt
datapythonv2.11.0
Install
3.6s avg
Import
278ms
Disk
89MB
Pass rate
5/ 10
Env Coverage5 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.11.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
build_error
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.6s · import 0.278s · 87MB
89MB installed
● package 89MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

nlopt
import nlopt
numpy
import numpy as np
from numpy import *
While older documentation or examples might use 'from numpy import *', 'import numpy as np' is the modern and recommended Python idiom to avoid namespace pollution and improve code readability.

This quickstart demonstrates how to set up and run a constrained minimization problem using NLopt. It defines an objective function and nonlinear inequality constraints, both capable of providing gradients. It then initializes an `nlopt.opt` object with a gradient-based algorithm (`LD_MMA`), sets the objective, bounds, and constraints, and performs the optimization. An example using a derivative-free algorithm (`LN_COBYLA`) is also included to show the common pattern for algorithms that do not utilize gradients.

import nlopt import numpy as np # Objective function to minimize: f(x) = sqrt(x[1]) # subject to x[1] >= (a*x[0] + b)**3 and x[1] >= 0 # for a1=2, b1=0, a2=-1, b2=1 def myfunc(x, grad): if grad.size > 0: grad[0] = 0.0 grad[1] = 0.5 / np.sqrt(x[1]) return np.sqrt(x[1]) def myconstraint(x, grad, a, b): if grad.size > 0: grad[0] = 3 * a * (a * x[0] + b)**2 grad[1] = -1.0 return (a * x[0] + b)**3 - x[1] # Problem dimension n = 2 # Create an optimizer object opt = nlopt.opt(nlopt.LD_MMA, n) # Set minimization objective opt.set_min_objective(myfunc) # Set bounds opt.set_lower_bounds([-float('inf'), 0.0]) # x[1] >= 0 # Add nonlinear inequality constraints (h(x) <= 0) # Constraint 1: x[1] >= (2*x[0])**3 => (2*x[0])**3 - x[1] <= 0 opt.add_inequality_constraint(lambda x, grad: myconstraint(x, grad, 2.0, 0.0), 1e-8) # Constraint 2: x[1] >= (-1*x[0] + 1)**3 => (-1*x[0] + 1)**3 - x[1] <= 0 opt.add_inequality_constraint(lambda x, grad: myconstraint(x, grad, -1.0, 1.0), 1e-8) # Set stopping criteria opt.set_xtol_rel(1e-4) opt.set_maxeval(1000) # Initial guess x0 = np.array([1.234, 5.678]) try: x_opt = opt.optimize(x0) minf = opt.last_optimum_value() result_code = opt.last_optimize_result() print(f"Optimized result: x = {x_opt}, f(x) = {minf}, return code: {result_code}") except nlopt.RunTimeError as e: print(f"NLopt failed: {e}") # Example of using a derivative-free algorithm opt_df = nlopt.opt(nlopt.LN_COBYLA, n) opt_df.set_min_objective(myfunc) # Note: grad argument will be empty for derivative-free opt_df.set_lower_bounds([-float('inf'), 0.0]) opt_df.add_inequality_constraint(lambda x, grad: myconstraint(x, grad, 2.0, 0.0), 1e-8) opt_df.add_inequality_constraint(lambda x, grad: myconstraint(x, grad, -1.0, 1.0), 1e-8) opt_df.set_xtol_rel(1e-4) try: x_opt_df = opt_df.optimize(x0) minf_df = opt_df.last_optimum_value() print(f"Derivative-free result: x = {x_opt_df}, f(x) = {minf_df}") except nlopt.RunTimeError as e: print(f"NLopt (derivative-free) failed: {e}")
Debug
Known issues
gotchaObjective and constraint functions must modify the `grad` array in-place, rather than reassigning it. Operations like `grad = 2*x` will not work as they create a new array; instead, use `grad[:] = 2*x` to overwrite the contents of the existing `grad` array.
fix
Ensure that any gradient calculations within your objective or constraint functions modify the `grad` parameter's contents directly using slice assignment (e.g., `grad[:] = ...`) or in-place operations.
affects: All versions
breakingPython version compatibility has changed across releases. As of version 2.10.0, `nlopt` officially supports Python 3.9 and above. Older Python versions (e.g., Python 3.8) were explicitly deprecated in NLopt 2.8.0.
fix
Upgrade your Python environment to version 3.9 or newer to ensure compatibility and access to the latest `nlopt` features and bug fixes. Check the `nlopt` PyPI page or GitHub releases for specific `requires_python` information for the version you intend to use.
affects: >=2.8.0
gotchaIncorrect or missing gradient information can lead to non-convergence or suboptimal results, especially when using gradient-based algorithms. Many NLopt algorithms expect analytically derived gradients for efficiency and accuracy.
fix
If possible, always provide accurate analytical gradients to gradient-based algorithms (e.g., `LD_MMA`, `LD_LBFGS`). If gradients are difficult or impossible to obtain, explicitly choose a derivative-free algorithm (e.g., `LN_COBYLA`, `LN_BOBYQA`). Test your gradient implementations by comparing them against finite-difference approximations.
affects: All versions
gotchaNLopt expects nonlinear inequality constraints to be formulated in the form `h(x) <= 0`. Incorrectly formulating these constraints (e.g., as `h(x) >= 0`) will lead to optimization issues or incorrect results.
fix
Always rewrite your inequality constraints to fit the `h(x) <= 0` format. For example, a constraint `g(x) >= C` should be written as `C - g(x) <= 0` in your constraint function.
affects: All versions
deprecatedSpecific algorithm constants, particularly those for sub-algorithms, may be removed or renamed in different underlying NLopt library versions. For instance, `NLOPT_LD_LBFGS_NOCEDAL` was temporarily removed in versions 2.9.x of the underlying NLopt library (affecting its R bindings `nloptr`) before being reintroduced in 2.10.0. While this specific change might not directly impact Python bindings in the same way, it indicates a potential for algorithm identifiers to change.
fix
Always consult the official NLopt documentation or the `nlopt` Python module's attributes (`dir(nlopt)`) for the exact algorithm constants available in your installed version. When upgrading, review the changelog for any mentions of algorithm name changes or removals.
affects: Potentially between major NLopt C library versions (e.g., 2.9.x vs 2.10.0)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'nlopt'
The `nlopt` Python package or its underlying C library bindings (`_nlopt.so` or `_nlopt.pyd`) are not correctly installed, not found in the Python environment's path, or there's an incompatibility with the active Python version or environment (e.g., virtual environment, Anaconda).
fix
Ensure `nlopt` is installed in your active Python environment using `pip install nlopt` or `conda install -c conda-forge nlopt`. If building from source, ensure SWIG and NumPy are installed, `cmake` is configured correctly with Python bindings enabled, and the resulting `_nlopt` shared library is in Python's search path.
ImportError: DLL load failed: The specified module could not be found.
(Primarily on Windows) This error occurs when `nlopt`'s Python bindings (`_nlopt.pyd`) cannot find required dynamic-link libraries (DLLs) for the underlying C `nlopt` library or its dependencies, usually because they are not in the system's PATH or a location Python can discover.
fix
Ensure the `nlopt` C library and its dependencies are properly installed and their DLLs are accessible to Python. This often means adding the directory containing `libnlopt.dll` (or similar) to the system's PATH environment variable, or installing via `conda install -c conda-forge nlopt` which typically manages these dependencies.
configure: error: C compiler cannot create executables
This error typically occurs when building `nlopt` from source and indicates that the C compiler (e.g., GCC, Visual C++) is not correctly installed, configured, or cannot compile simple C programs.
fix
Ensure a working C/C++ compiler is installed and configured on your system. For Linux, install `build-essential` (`sudo apt-get install build-essential`); for Windows, install Visual Studio build tools. Verify the compiler is in your system's PATH.
ValueError: nlopt invalid argument
This runtime error often arises when the objective or constraint functions provided to `nlopt` do not return the expected type (e.g., a NumPy scalar object instead of a standard Python float) or when critical optimization parameters like lower/upper bounds are not set for all variables, especially for global optimization algorithms.
fix
Review your objective and constraint function definitions to ensure they return a scalar Python float. For global optimization algorithms, explicitly set both lower and upper bounds for *all* optimization parameters using `opt.set_lower_bounds()` and `opt.set_upper_bounds()`.
Upgrade
Version history
2.11.0latest on PyPI · released Jul 17, 2026
Audit
Dependencies
numpyrequiredRequired for array data types used to communicate with NLopt's Python interface for objective functions, gradients, and optimization parameters.
pythonrequiredThe library explicitly requires Python versions 3.9 and above.
Agent activity
7 hits · last 30 days
node
6
Resources
nlopt — pip install nlopt · libregistry