Skip to content

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.

best

best(metric='mean')

The record with the lowest metric (default "mean").

to_dataframe

to_dataframe()

Return the records as a pandas DataFrame (pandas imported lazily).

Raises:

Type Description
ImportError

if pandas is not installed (it is not a hard dependency).

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 f(list[float]) -> float to minimize, OR the name (str) of a native benchmark: "sphere", "rastrigin", "rosenbrock", "ackley", "griewank", "schwefel".

required
bounds

either a list of (min, max) pairs (one per dimension, so each dimension can have its own range) or a single (min, max) pair used for every dimension (then pass dim).

required
integer bool

if True, optimizes over integer variables (the position is discretized by rounding when evaluated). Defaults to False.

False
n_particles int

swarm size. Defaults to 30.

30
max_iter int

number of iterations. Defaults to 100.

100
w float

inertia weight ("inertia" variant). Defaults to 0.729.

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", "constriction" or "fips". Defaults to "inertia". "constriction" and "fips" derive their factor from c1 + c2 (use 2.05/4.1 if the sum does not exceed 4).

'inertia'
topology str

social structure: "global", "ring", "vonneumann" or "random". Defaults to "global". FIPS performs better with local topologies ("ring", "vonneumann").

'global'
seed int | None

RNG seed. Fix it for reproducible runs. Defaults to None (system seed).

None
record_history bool

if True (the default), stores the swarm trace for visualization. Disable it to save memory and time.

True
v_max float | None

if set, clamps every velocity component to [-v_max, v_max] after each update. Defaults to None (off).

None
patience int

early stopping. Stop when the global best does not improve by more than tol for patience consecutive iterations. 0 (default) disables it (always runs max_iter).

0
tol float

minimum improvement counted as progress for the patience window. Defaults to 0.0.

0.0
constraints list[callable] | None

inequality constraints, each a callable g(x) -> float that is feasible when g(x) <= 0. A quadratic penalty penalty * sum(max(0, g(x))**2) is added to the objective. Requires objective to be a Python callable (not a native benchmark name). Defaults to None.

None
penalty float

weight of the constraint penalty (shared by the inequality and equality terms). Defaults to 1e6.

1000000.0
equality_constraints list[callable] | None

equality constraints, each a callable h(x) -> float that is feasible when h(x) == 0. A quadratic penalty penalty * sum(h(x)**2) is added to the objective. Like constraints, requires a Python objective (not a native benchmark). Defaults to None. Note: equality constraints are sensitive to penalty — a very large value (e.g. the 1e6 default) makes the feasible valley so steep the swarm converges onto a feasible but sub-optimal point; moderate weights (1e3-1e4) usually balance feasibility and objective better. For hard equalities a repair operator is often more robust.

None
repair callable | None

a repair operator repair(x) -> x' applied to each candidate before it is evaluated, mapping infeasible points back to (or towards) the feasible region. The objective and the constraints see the repaired point, and the returned best_position is repaired too, so the reported solution is consistent with its value. Requires a Python objective. Defaults to None.

None
binary bool

if True, optimize over binary variables {0, 1} (a {0,1} integer space); the dimension is taken from bounds. Defaults to False.

False
max_evals int | None

stop after this many objective evaluations.

None
target float | None

stop as soon as the best value is <= target.

None
max_time float | None

stop after this many seconds of wall-clock time.

None
callback callable | None

called once per iteration as callback(iteration, best_value). Return False to stop early (reported as stop_reason="callback"); None or any other return continues. Useful for live logging or custom stopping.

None
bounds_handling str

what to do with particles that leave the bounds: "clamp" (default), "reflect", "wrap" or "reinit".

'clamp'
vectorized bool

if True, objective receives the WHOLE swarm per call as a NumPy array (shape n_particles x dim) and must return one value per row. This lets a NumPy-vectorized objective amortize its overhead over the swarm. Uses synchronous updates; incompatible with native benchmarks, constraints and callback. Defaults to False.

False
var_types list[str] | None

per-dimension variable types for a mixed problem — each "real", "integer" or "binary" (same length as bounds). Integer/binary dimensions come back as whole-valued floats. Takes precedence over integer/binary.

None
dim int | None

number of dimensions when bounds is a single (min, max) pair (ignored when bounds is already a list).

None

Returns:

Name Type Description
PsoResult

with best_position, best_value, convergence and

history.

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 objective.

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 f(list) -> list[float] returning one value per objective (all minimized).

required
bounds list[tuple[float, float]]

(min, max) per dimension.

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" or "constriction" (single-leader rules; "fips" is not applicable to MOPSO).

'inertia'
seed int | None

RNG seed.

None
integer bool), binary (bool), var_types (list[str] | None

same meaning as in minimize.

False
mutation_rate float

turbulence strength in [0, 1] (default 0.1); improves front spread. 0 disables it.

0.1
grid_divisions int | None

archive diversity strategy. None (default) keeps the most isolated members by crowding distance; an int d uses Coello's adaptive hypercube grid with d divisions per objective (pruning drops members from the most crowded cell, leaders are drawn towards sparser cells), which tends to spread the front more evenly.

None

Returns:

Name Type Description
ParetoFront

with positions and objectives.

hypervolume builtin

hypervolume(front, reference)

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 front under reference.

sweep

sweep(objective, bounds, grid, *, seeds=1, **kwargs)

Sweep PSO over the Cartesian product of hyperparameter values.

Parameters:

Name Type Description Default
objective

objective passed to :func:turboswarm.minimize (a callable or the name of a native benchmark).

required
bounds

bounds passed to minimize (a list of (min, max) pairs, or a single pair together with dim=N in kwargs).

required
grid dict[str, list]

maps a hyperparameter name -- any keyword accepted by minimize, e.g. "w", "c1", "c2", "n_particles", "max_iter", "velocity", "topology" -- to the list of values to try. The sweep runs every combination.

required
seeds int | Iterable[int]

repetitions per combination. An int means range(seeds); an iterable is used verbatim. Defaults to 1; use more for robust, less noisy results.

1
**kwargs

fixed parameters forwarded to every minimize call (e.g. dim=2, n_particles=30, max_iter=100). Must not overlap with the keys in grid. history recording is turned off by default (only best_value is needed); pass record_history=True to override.

{}

Returns:

Name Type Description
SweepResult

one record per combination.

benchmark_info builtin

benchmark_info(name)

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

plot_convergence(result, label=None, ax=None, log=True)

Draw the best-value-per-iteration curve.

compare

compare(results, log=True)

results: dict {name: PsoResult}. Overlays convergence curves.

animate_swarm

animate_swarm(
    result, function, bounds, interval=150, cmap="Blues"
)

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

plot_pareto(
    front, ax=None, labels=("objective 1", "objective 2")
)

Scatter the objective values of a 2-objective ParetoFront.

plot_sensitivity

plot_sensitivity(sweep, x, y=None, metric='mean', ax=None)

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 turboswarm.sweep.

required
x str

hyperparameter for the x-axis (a key in sweep.param_names).

required
y str | None

hyperparameter for the y-axis -> heatmap; None -> line.

None
metric str

which per-combination statistic to plot ("mean", "min", "max", "std"). Defaults to "mean".

'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.

sphere

sphere(x)

Sphere: convex, unimodal. Global minimum f(0) = 0.

rastrigin

rastrigin(x)

Rastrigin: highly multimodal. Global minimum f(0) = 0.

rosenbrock

rosenbrock(x)

Rosenbrock: narrow banana valley. Global minimum f(1, ..., 1) = 0.

ackley

ackley(x)

Ackley: nearly flat far out with a narrow well. Minimum f(0) = 0.

griewank

griewank(x)

Griewank: many regular local minima. Global minimum f(0) = 0.

schwefel

schwefel(x)

Schwefel: multimodal, optimum FAR from the origin (≈420.97/dim).

Global minimum f(420.9687, ...) = 0.

bent_cigar

bent_cigar(x)

Bent Cigar: unimodal, severely ill-conditioned. Minimum f(0) = 0.

discus

discus(x)

Discus: one expensive direction (1e6), the rest cheap. Minimum f(0) = 0.

elliptic

elliptic(x)

High Conditioned Elliptic: condition number 1..1e6. Minimum f(0) = 0.

zakharov

zakharov(x)

Zakharov: unimodal, no local minima. Minimum f(0) = 0.

levy

levy(x)

Levy: multimodal. Global minimum f(1, ..., 1) = 0 (away from origin).

expanded_schaffer

expanded_schaffer(x)

Expanded Schaffer F6: deceptive, highly multimodal. Minimum f(0) = 0.

grey_sphere

grey_sphere(greys)

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).