Skip to content

cds2.optimize

Optimization and root finding on scipy.optimize.

Curve-fitting diagnostics

curve_fit supports measurement uncertainty (sigma / absolute_sigma), parameter bounds, solver selection and optional Jacobians. In addition to fitted parameters and covariance, FitResult reports parameter standard errors, predictions, residuals, RSS, RMSE, R² and residual degrees of freedom.

The residual diagnostics are calculated on the original, unweighted residuals; sigma controls the parameter fit and covariance estimation.

import numpy as np

from cds2 import optimize

x = np.linspace(0.0, 4.0, 20)
y = 2.5 * x + 1.2
sigma = np.full_like(x, 0.2)

fit = optimize.curve_fit(
    lambda t, slope, intercept: slope * t + intercept,
    x,
    y,
    p0=[1.0, 0.0],
    sigma=sigma,
    absolute_sigma=True,
    bounds=([0.0, -5.0], [5.0, 5.0]),
)

print(fit.params)
print(fit.parameter_std)
print(fit.rmse, fit.r_squared)

Optimization — convenience re-export of scipy.optimize with normalized result types; see cds2.metaheuristics and cds2.bayesopt for CDS-native global search.

OptimizationResult dataclass

Outcome of an optimization or root-finding run.

Source code in src/cds2/optimize.py
29
30
31
32
33
34
35
36
37
@dataclass(frozen=True)
class OptimizationResult:
    """Outcome of an optimization or root-finding run."""

    x: object
    fun: float | None
    success: bool
    message: str
    n_iterations: int | None

LinprogResult dataclass

Outcome of a linear-programming solve.

Source code in src/cds2/optimize.py
40
41
42
43
44
45
46
47
@dataclass(frozen=True)
class LinprogResult:
    """Outcome of a linear-programming solve."""

    x: np.ndarray | None
    fun: float | None
    success: bool
    message: str

FitResult dataclass

Non-linear least-squares fit and residual diagnostics.

The first two fields preserve the pre-5.x construction API. Additional diagnostics default to None so existing manual FitResult construction remains valid.

Source code in src/cds2/optimize.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@dataclass(frozen=True)
class FitResult:
    """Non-linear least-squares fit and residual diagnostics.

    The first two fields preserve the pre-5.x construction API. Additional
    diagnostics default to ``None`` so existing manual ``FitResult``
    construction remains valid.
    """

    params: np.ndarray
    covariance: np.ndarray | None
    parameter_std: np.ndarray | None = None
    predictions: np.ndarray | None = None
    residuals: np.ndarray | None = None
    rss: float | None = None
    rmse: float | None = None
    r_squared: float | None = None
    dof: int | None = None

GlobalResult dataclass

Outcome of a stochastic global optimization run.

Source code in src/cds2/optimize.py
177
178
179
180
181
182
183
184
185
186
@dataclass(frozen=True)
class GlobalResult:
    """Outcome of a stochastic global optimization run."""

    x: np.ndarray
    fun: float
    success: bool
    message: str
    n_iterations: int
    n_evaluations: int

minimize(fun, x0, method='BFGS', **kwargs)

Minimize an unconstrained (or method-constrained) multivariate function.

Source code in src/cds2/optimize.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def minimize(
    fun: Callable[..., float],
    x0: Sequence[float],
    method: str = "BFGS",
    **kwargs: object,
) -> OptimizationResult:
    """Minimize an unconstrained (or method-constrained) multivariate function."""
    res = spo.minimize(fun, np.asarray(x0, dtype=float), method=method, **kwargs)
    return OptimizationResult(
        x=res.x,
        fun=float(res.fun),
        success=bool(res.success),
        message=str(getattr(res, "message", "")),
        n_iterations=getattr(res, "nit", None),
    )

minimize_scalar(fun, bracket=None, bounds=None, method=None)

Minimize a univariate function, optionally over a bounded interval.

Source code in src/cds2/optimize.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def minimize_scalar(
    fun: Callable[[float], float],
    bracket: tuple[float, float] | None = None,
    bounds: tuple[float, float] | None = None,
    method: str | None = None,
) -> OptimizationResult:
    """Minimize a univariate function, optionally over a bounded interval."""
    if method is None:
        method = "bounded" if bounds is not None else "brent"
    kwargs: dict[str, object] = {}
    if bracket is not None:
        kwargs["bracket"] = bracket
    if bounds is not None:
        kwargs["bounds"] = bounds
    res = spo.minimize_scalar(fun, method=method, **kwargs)
    return OptimizationResult(
        x=float(res.x),
        fun=float(res.fun),
        success=bool(res.success),
        message=str(getattr(res, "message", "")),
        n_iterations=int(res.nit) if hasattr(res, "nit") else None,
    )

root(fun, x0, method='hybr', **kwargs)

Find a root of a system of equations starting from x0.

Source code in src/cds2/optimize.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def root(
    fun: Callable[..., object],
    x0: Sequence[float],
    method: str = "hybr",
    **kwargs: object,
) -> OptimizationResult:
    """Find a root of a system of equations starting from ``x0``."""
    res = spo.root(fun, np.asarray(x0, dtype=float), method=method, **kwargs)
    return OptimizationResult(
        x=res.x,
        fun=None,
        success=bool(res.success),
        message=str(res.message),
        n_iterations=None,
    )

find_root_scalar(f, a, b, **kwargs)

Root of a univariate function on a sign-changing bracket via Brent's method.

Source code in src/cds2/optimize.py
128
129
130
def find_root_scalar(f: Callable[[float], float], a: float, b: float, **kwargs: float) -> float:
    """Root of a univariate function on a sign-changing bracket via Brent's method."""
    return float(spo.brentq(f, a, b, **kwargs))

newton_root(f, x0, fprime=None, tol=1.48e-08, maxiter=50)

Newton-Raphson (or secant when fprime omitted) root of a scalar function.

Source code in src/cds2/optimize.py
133
134
135
136
137
138
139
140
141
def newton_root(
    f: Callable[[float], float],
    x0: float,
    fprime: Callable[[float], float] | None = None,
    tol: float = 1.48e-08,
    maxiter: int = 50,
) -> float:
    """Newton-Raphson (or secant when ``fprime`` omitted) root of a scalar function."""
    return float(spo.newton(f, x0, fprime=fprime, tol=tol, maxiter=maxiter))

linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None)

Minimize c @ x subject to linear inequality/equality constraints.

Source code in src/cds2/optimize.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def linprog(
    c: Sequence[float],
    A_ub: Sequence[Sequence[float]] | None = None,
    b_ub: Sequence[float] | None = None,
    A_eq: Sequence[Sequence[float]] | None = None,
    b_eq: Sequence[float] | None = None,
    bounds: Sequence[tuple[float | None, float | None]] | None = None,
) -> LinprogResult:
    """Minimize ``c @ x`` subject to linear inequality/equality constraints."""
    res = spo.linprog(
        np.asarray(c, dtype=float), A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds
    )
    solution = None if res.x is None else np.asarray(res.x, dtype=float)
    value = None if res.fun is None else float(res.fun)
    return LinprogResult(x=solution, fun=value, success=bool(res.success), message=str(res.message))

least_squares(fun, x0, **kwargs)

Solve a nonlinear least-squares problem given a residual function.

Source code in src/cds2/optimize.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def least_squares(
    fun: Callable[..., object],
    x0: Sequence[float],
    **kwargs: object,
) -> OptimizationResult:
    """Solve a nonlinear least-squares problem given a residual function."""
    res = spo.least_squares(fun, np.asarray(x0, dtype=float), **kwargs)
    return OptimizationResult(
        x=res.x,
        fun=float(res.cost),
        success=bool(res.success),
        message=str(res.message),
        n_iterations=int(res.nfev),
    )

curve_fit(f, xdata, ydata, p0=None, *, sigma=None, absolute_sigma=False, bounds=(-np.inf, np.inf), method=None, jac=None)

Fit model parameters by non-linear least squares.

Parameters mirror the highest-value controls from :func:scipy.optimize.curve_fit: measurement uncertainty, absolute/relative uncertainty semantics, parameter bounds, solver selection and an optional Jacobian. The returned diagnostics are computed on the original (unweighted) residuals for easy model checking.

Source code in src/cds2/optimize.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def curve_fit(
    f: Callable[..., object],
    xdata: Sequence[float],
    ydata: Sequence[float],
    p0: Sequence[float] | None = None,
    *,
    sigma: Sequence[float] | Sequence[Sequence[float]] | np.ndarray | None = None,
    absolute_sigma: bool = False,
    bounds: tuple[Sequence[float] | float, Sequence[float] | float] = (-np.inf, np.inf),
    method: str | None = None,
    jac: Callable[..., object] | str | None = None,
) -> FitResult:
    """Fit model parameters by non-linear least squares.

    Parameters mirror the highest-value controls from :func:`scipy.optimize.curve_fit`:
    measurement uncertainty, absolute/relative uncertainty semantics, parameter
    bounds, solver selection and an optional Jacobian. The returned diagnostics
    are computed on the original (unweighted) residuals for easy model checking.
    """
    x_values = np.asarray(xdata, dtype=float)
    y_values = np.asarray(ydata, dtype=float)
    sigma_values = None if sigma is None else np.asarray(sigma, dtype=float)
    params, covariance = spo.curve_fit(
        f,
        x_values,
        y_values,
        p0=p0,
        sigma=sigma_values,
        absolute_sigma=absolute_sigma,
        bounds=bounds,
        method=method,
        jac=jac,
    )
    params_array = np.asarray(params, dtype=float)
    covariance_array = np.asarray(covariance, dtype=float)
    predictions = np.asarray(f(x_values, *params_array), dtype=float)
    residuals = y_values - predictions
    squared_residuals = residuals * residuals
    rss = float(np.sum(squared_residuals))
    rmse = float(np.sqrt(np.mean(squared_residuals)))
    centered = y_values - float(np.mean(y_values))
    total_sum_squares = float(np.sum(centered * centered))
    r_squared = None if total_sum_squares == 0.0 else float(1.0 - rss / total_sum_squares)
    with np.errstate(invalid="ignore"):
        parameter_std = np.sqrt(np.diag(covariance_array))

    return FitResult(
        params=params_array,
        covariance=covariance_array,
        parameter_std=np.asarray(parameter_std, dtype=float),
        predictions=predictions,
        residuals=np.asarray(residuals, dtype=float),
        rss=rss,
        rmse=rmse,
        r_squared=r_squared,
        dof=int(y_values.size - params_array.size),
    )

minimize_constrained(fun, x0, constraints=None, bounds=None, method='SLSQP', jac=None, **kwargs)

Minimize under equality/inequality constraints (SLSQP or trust-constr).

constraints uses SciPy's dict form, e.g. {"type": "eq", "fun": lambda v: v[0] + v[1] - 1}.

Source code in src/cds2/optimize.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def minimize_constrained(
    fun: Callable[..., float],
    x0: Sequence[float],
    constraints: Sequence[dict[str, object]] | None = None,
    bounds: Sequence[Sequence[float | None]] | None = None,
    method: str = "SLSQP",
    jac: Callable[..., object] | None = None,
    **kwargs: object,
) -> OptimizationResult:
    """Minimize under equality/inequality constraints (SLSQP or trust-constr).

    ``constraints`` uses SciPy's dict form, e.g.
    ``{"type": "eq", "fun": lambda v: v[0] + v[1] - 1}``.
    """
    res = spo.minimize(
        fun,
        np.asarray(x0, dtype=float),
        method=method,
        bounds=bounds,
        constraints=constraints,
        jac=jac,
        **kwargs,
    )
    return OptimizationResult(
        x=res.x,
        fun=float(res.fun),
        success=bool(res.success),
        message=str(res.message),
        n_iterations=getattr(res, "nit", None),
    )

differential_evolution(fun, bounds, maxiter=1000, popsize=15, seed=None, **kwargs)

Stochastic global minimization over a box via differential evolution.

Source code in src/cds2/optimize.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def differential_evolution(
    fun: Callable[..., float],
    bounds: Sequence[Sequence[float]],
    maxiter: int = 1000,
    popsize: int = 15,
    seed: int | None = None,
    **kwargs: object,
) -> GlobalResult:
    """Stochastic global minimization over a box via differential evolution."""
    box = [tuple(bound) for bound in bounds]
    res = spo.differential_evolution(
        fun,
        box,
        maxiter=maxiter,
        popsize=popsize,
        seed=seed,
        **kwargs,
    )
    return GlobalResult(
        x=np.asarray(res.x, dtype=float),
        fun=float(res.fun),
        success=bool(res.success),
        message=str(res.message),
        n_iterations=int(res.nit),
        n_evaluations=int(res.nfev),
    )