Particle Swarm Optimization (PSO) for Python
pyswarm is a gradient-free, evolutionary optimization library for Python that implements Particle Swarm Optimization (PSO) with built-in support for constraints. It is lightweight, easy to use, and suitable for a wide range of optimization problems where gradient information is unavailable or impractical to compute.
from pyswarm import pso
def objective(x):
x1, x2 = x
return x1**4 - 2 * x2 * x1**2 + x2**2 + x1**2 - 2 * x1 + 5
lb = [-3, -1]
ub = [2, 6]
result = pso(objective, lb, ub)
print("Optimal solution:", result.x) # → [1.0, 1.0]
print("Function value:", result.fun) # → 4.0
print("Converged:", result.success)
print("Reason:", result.message)
print("Iterations:", result.nit)
print("Evaluations:", result.nfev)pso returns an OptimizeResult — a dict subclass with attribute
access, compatible with scipy.optimize.OptimizeResult.
pip install pyswarmRequires Python 3.10+ and NumPy. See the full installation guide for uv, poetry, and source builds.
- Theory — mathematical background, hierarchical basis, algorithms
- Quickstart — runnable examples
- API Reference — class and function signatures
- References — literature citations
BSD-3-Clause — see LICENSE.