Python API¶
Reference generated from the docstrings of the turboswarm package.
turboswarm ¶
turboswarm — Particle Swarm Optimization with a Rust core, Python API.
The computation runs in Rust (native module turboswarm_native); this Python
layer offers a convenient API and visualization utilities.
Example
import turboswarm as pso r = pso.minimize("rastrigin", bounds=[(-5.12, 5.12)]*2, seed=42) r.best_value < 1e-3 True
your own function (Python)¶
r = pso.minimize(lambda x: sum(xi*2 for xi in x), bounds=[(-5,5)]3)
integer variables¶
r = pso.minimize(f, bounds=[(-10,10)]*2, integer=True)
Variants (velocity=): "inertia", "constriction", "fips".
Topologies (topology=): "global", "ring", "vonneumann".
(FIPS performs better with local topologies: "ring" or "vonneumann".)
Native benchmarks: "sphere", "rastrigin", "rosenbrock", "ackley",
"griewank", "schwefel", plus the CEC-family functions "bent_cigar", "discus",
"elliptic", "zakharov", "levy", "expanded_schaffer".
Hyperparameter sensitivity (sweep): run PSO over a Cartesian product of
hyperparameter values and aggregate over seeds; visualize with
viz.plot_sensitivity.
SweepResult ¶
Result of a hyperparameter sweep.
Holds one record per Cartesian-product combination. Each record is a dict
with the swept hyperparameters plus aggregated statistics of the best
objective value across the seeds: mean, std (population), min,
max, the raw values list and n (number of seeds).
Iterable and indexable over its records; see :meth:best and
:meth:to_dataframe.
minimize
builtin
¶
minimize(
objective,
bounds,
integer=False,
n_particles=30,
max_iter=100,
w=0.729,
c1=1.49445,
c2=1.49445,
velocity="inertia",
topology="global",
seed=None,
record_history=True,
v_max=None,
patience=0,
tol=0.0,
constraints=None,
penalty=1000000.0,
binary=False,
max_evals=None,
target=None,
max_time=None,
callback=None,
bounds_handling="clamp",
vectorized=False,
var_types=None,
dim=None,
equality_constraints=None,
repair=None,
)
Minimizes an objective function with Particle Swarm Optimization.
The function to optimize can be a Python callable or the name of a native Rust benchmark (faster, runs without the GIL).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
callable |
required | |
bounds
|
either a list of |
required | |
integer
|
bool
|
if |
False
|
n_particles
|
int
|
swarm size. Defaults to 30. |
30
|
max_iter
|
int
|
number of iterations. Defaults to 100. |
100
|
w
|
float
|
inertia weight ( |
0.729
|
c1
|
float
|
cognitive coefficient (attraction to the personal best). |
1.49445
|
c2
|
float
|
social coefficient (attraction to the neighborhood best). |
1.49445
|
velocity
|
str
|
velocity variant: |
'inertia'
|
topology
|
str
|
social structure: |
'global'
|
seed
|
int | None
|
RNG seed. Fix it for reproducible runs. Defaults to
|
None
|
record_history
|
bool
|
if |
True
|
v_max
|
float | None
|
if set, clamps every velocity component to
|
None
|
patience
|
int
|
early stopping. Stop when the global best does not
improve by more than |
0
|
tol
|
float
|
minimum improvement counted as progress for the
|
0.0
|
constraints
|
list[callable] | None
|
inequality constraints, each a
callable |
None
|
penalty
|
float
|
weight of the constraint penalty (shared by the
inequality and equality terms). Defaults to |
1000000.0
|
equality_constraints
|
list[callable] | None
|
equality constraints, each
a callable |
None
|
repair
|
callable | None
|
a repair operator |
None
|
binary
|
bool
|
if |
False
|
max_evals
|
int | None
|
stop after this many objective evaluations. |
None
|
target
|
float | None
|
stop as soon as the best value is |
None
|
max_time
|
float | None
|
stop after this many seconds of wall-clock time. |
None
|
callback
|
callable | None
|
called once per iteration as
|
None
|
bounds_handling
|
str
|
what to do with particles that leave the bounds:
|
'clamp'
|
vectorized
|
bool
|
if |
False
|
var_types
|
list[str] | None
|
per-dimension variable types for a mixed
problem — each |
None
|
dim
|
int | None
|
number of dimensions when |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
PsoResult |
with |
|
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
if the name of a non-existent native benchmark is passed. |
ValueError
|
if the variant or topology does not exist. |
Exception
|
propagates any error raised by the Python |
Example
import turboswarm as pso r = pso.minimize("rastrigin", bounds=[(-5.12, 5.12)] * 2, seed=42) r.best_value < 1e-3 True r = pso.minimize(lambda x: sum(xi*xi for xi in x), ... bounds=[(-5, 5)] * 3, velocity="fips", topology="ring")
minimize_multi
builtin
¶
minimize_multi(
objective,
bounds,
n_particles=100,
max_iter=100,
archive_size=100,
w=0.729,
c1=1.49445,
c2=1.49445,
velocity="inertia",
seed=None,
integer=False,
binary=False,
var_types=None,
mutation_rate=0.1,
dim=None,
grid_divisions=None,
)
Multi-objective optimization (MOPSO). Returns the Pareto front.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
callable |
required | |
bounds
|
list[tuple[float, float]]
|
|
required |
n_particles
|
int
|
swarm size. Defaults to 100. |
100
|
max_iter
|
int
|
iterations. Defaults to 100. |
100
|
archive_size
|
int
|
maximum Pareto-front size. Defaults to 100. |
100
|
w, c1, c2
|
float
|
velocity coefficients. |
required |
velocity
|
str
|
|
'inertia'
|
seed
|
int | None
|
RNG seed. |
None
|
integer
|
bool), binary (bool), var_types (list[str] | None
|
same
meaning as in |
False
|
mutation_rate
|
float
|
turbulence strength in [0, 1] (default 0.1);
improves front spread. |
0.1
|
grid_divisions
|
int | None
|
archive diversity strategy. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ParetoFront |
with |
hypervolume
builtin
¶
Hypervolume of an arbitrary set of objective vectors (minimization).
A free-standing version of :meth:ParetoFront.hypervolume for fronts not
produced by minimize_multi (e.g. a reference front, or one loaded from
disk for benchmarking).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
front
|
list[list[float]]
|
objective vectors, one per solution. |
required |
reference
|
list[float]
|
the bounding "worst" point, one value per objective; each value must exceed the front in that objective. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
the hypervolume dominated by |
sweep ¶
Sweep PSO over the Cartesian product of hyperparameter values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
objective passed to :func: |
required | |
bounds
|
bounds passed to |
required | |
grid
|
dict[str, list]
|
maps a hyperparameter name -- any keyword
accepted by |
required |
seeds
|
int | Iterable[int]
|
repetitions per combination. An |
1
|
**kwargs
|
fixed parameters forwarded to every |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
SweepResult |
one record per combination. |
benchmark_info
builtin
¶
Metadata of a native benchmark: (bound, optimum_value). bound is the
recommended symmetric bound per dimension. Useful for auto-adjusting plot
domains or building bounds without hardcoding them by hand.
Visualization¶
turboswarm.viz ¶
Visualization helpers. Consume the PsoResult from the Rust core.
Requires matplotlib. Functions: - plot_convergence(result, label=None, ax=None) - animate_swarm(result, function, bounds) # 2D swarm over a contour - plot_surface(function, bounds, points=None) # 3D objective landscape - animate_swarm_3d(result, function, bounds) # 3D swarm over the surface - animate_swarm_projected(result, function=None) # 3D projection for >2D - plotly_convergence / plotly_compare / plotly_pareto # interactive (Plotly) - compare(results) # overlay convergence curves - plot_pareto(front, ax=None) # objective space of a ParetoFront - plot_sensitivity(sweep, x, y=None) # hyperparameter sweep (line/heatmap)
plot_convergence ¶
Draw the best-value-per-iteration curve.
animate_swarm ¶
Animate the 2D swarm over the contour map of function.
function: callable that receives [x, y] and returns a float.
bounds: [(xmin, xmax), (ymin, ymax)].
cmap: landscape colormap (a cool map so the particles stand out).
Returns a FuncAnimation object (in a notebook: HTML(anim.to_jshtml())).
plot_pareto ¶
Scatter the objective values of a 2-objective ParetoFront.
plot_sensitivity ¶
Visualize a hyperparameter sweep (the result of turboswarm.sweep).
1D (y=None): a line of metric vs the x hyperparameter. When the
sweep varies other hyperparameters too, the points are marginalized over
them (mean across the group) and the spread is shown as error bars.
2D (y given): a heatmap of metric over the x (columns) and y
(rows) grid, again marginalizing over any other swept hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sweep
|
SweepResult
|
from |
required |
x
|
str
|
hyperparameter for the x-axis (a key in |
required |
y
|
str | None
|
hyperparameter for the y-axis -> heatmap; |
None
|
metric
|
str
|
which per-combination statistic to plot ( |
'mean'
|
ax
|
optional matplotlib Axes. |
None
|
Returns:
| Type | Description |
|---|---|
|
The matplotlib Axes. |
Pure-Python benchmarks¶
turboswarm.benchmarks ¶
Test functions in pure Python (mirror of the Rust ones).
Useful for the notebooks before having the native core compiled.
schwefel ¶
Schwefel: multimodal, optimum FAR from the origin (≈420.97/dim).
Global minimum f(420.9687, ...) = 0.
expanded_schaffer ¶
Expanded Schaffer F6: deceptive, highly multimodal. Minimum f(0) = 0.
grey_sphere ¶
Grey sphere: expected (midpoint) sphere plus a unit uncertainty penalty.
greys is a list of (lower, upper) intervals. With center
c = (lo + hi) / 2 and spread r = (hi - lo) / 2 per variable::
f(greys) = sum(c_i ** 2) + sum(r_i)
Global minimum f = 0 at the crisp origin (every interval [0, 0]): it
rewards both accuracy (centers at 0) and certainty (zero spread).