SciPy, rebuilt in Rust19 cratesv0.5.2 on crates.io
SciPy’s math, without the Python.
FrankenSciPy is SciPy rebuilt from scratch in safe Rust, from linear algebra to statistics: 1,532 of the 1,538 functions and classes SciPy exports, 916 of them checked against a live SciPy in the test suite. Every dense solve returns a certificate saying which algorithm ran and why. The curves here are computed by those crates, running in your browser.
cargo add fsci-linalg fsci-stats
Pick a function
Orders v = 0 to 19, x from 0 to 40: 20 ridges of 300 points.
The same call, twice
SciPyscipy.special.jv(v, x)
Rustfsci_special::jv(&v, &x, mode)
– largest difference from SciPy 1.17.1 over 6,000 values
– same bits– ≤ 4 ulp– ≤ 256 ulp– more
Drawn from SciPy’s recorded values. Starting fsci-special…
Point at a ridge to read a value and SciPy’s value for the same input. SciPy’s answers were recorded with SciPy 1.17.1 and NumPy 2.4.3 when this page was built; FrankenSciPy’s are computed now, by its crates compiled to WebAssembly. An ulp is one step between neighbouring doubles.
- 1,532of 1,538 SciPy namesHave a real Rust implementation, across 33 SciPy modules.
- 783differential test filesEach starts a live SciPy, sends it the same inputs and compares.
- 1,167tolerance contractsNamed in the tests. CI fails if any one is loosened.
- 12,304#[test] functionsInline and integration tests across all 19 crates.
- 0lines of unsafe
forbid(unsafe_code)in every crate. No FFI to BLAS or LAPACK.
01The surface
Thirty-three SciPy modules, one Cargo workspace.
FrankenSciPy keeps SciPy’s names, defaults and edge cases, so code ports one call at a time. Of the 1,538 public functions and classes SciPy 1.17.1 exports, the project’s symbol census finds a real Rust implementation for 1,532; six are missing.
The module map
Every public name in SciPy, one square each.
Each square is a function or class SciPy 1.17.1 exports, coloured by what the census finds in the Rust: compared against a live SciPy in a differential test, implemented but not compared yet, missing, or not applicable to Rust. 1,555 squares; six are missing.
Point at a module or a square to see what it holds; select a square to look it up
1,555 names in 33 modules
- 916 compared against SciPy
- 616 implemented, not compared yet
- 6 missing
- 17 not applicable to Rust
fsci-stats360
stats241/303
stats.contingency2/6
stats.mstats11/31
stats.qmc4/11
stats.sampling4/9
fsci-special358
special211/358
fsci-signal182
signal83/157
signal.windows9/25
fsci-sparse117
sparse25/53
sparse.csgraph24/26
sparse.linalg29/38
fsci-linalg106
linalg72/98
linalg.interpolative7/8
fsci-opt78
differentiate0/3
optimize30/71
optimize.elementwise4/4
fsci-ndimage75
ndimage39/75
fsci-interpolate56
interpolate15/56
fsci-fft51
fft20/41
fftpack10/10
fsci-spatial49
spatial8/18
spatial.distance22/27
spatial.transform0/4
fsci-cluster36
cluster.hierarchy10/32
cluster.vq2/4
fsci-integrate33
integrate15/33
fsci-io31
io3/14
io.arff3/4
io.matlab4/10
io.wavfile2/3
fsci-odr10
odr2/10
fsci-constants8
constants5/8
fsci-datasets5
datasets0/5
Point at a module
Each square is one public name. Modules are grouped under the crate that implements them, largest first. The count beside a module is its compared names over all its names, brighter along viridis the more of them are compared.
__all__ in SciPy 1.17.1, counted once in the module that owns them, as scripts/symbol_census.py counts them; the counts beside each module are compared names over all names. Recorded at commit d2b206d3d. The committed census file, docs/planning/symbol_census.json, counts 909 compared; tests that landed after it was last regenerated bring the count on this tree to 916, the figure this page uses throughout.Look up a function
Does it have the one you use?
Search any SciPy name to see its Rust counterpart and, if it is compared live, the test files that compare it. Where a name is missing or does not apply to Rust, the census records why.
Type a SciPy name to see its Rust counterpart and the tests that compare it
The six SciPy names with no Rust implementation yet:
scipy.io.matlab.MatReadErrorMissingMATLAB read failures are IoError variants, not a distinct error class (frankenscipy-1ksfv.12)
scipy.io.matlab.MatReadWarningMissingno warning channel for recoverable MATLAB read issues (frankenscipy-1ksfv.12)
scipy.io.matlab.MatWriteErrorMissingMATLAB write failures are IoError variants, not a distinct error class (frankenscipy-1ksfv.12)
scipy.io.matlab.MatWriteWarningMissingno warning channel for recoverable MATLAB write issues (frankenscipy-1ksfv.12)
scipy.sparse.linalg.ArpackErrorMissingSparseError has no eigensolver error class (frankenscipy-6j5tz)
scipy.sparse.linalg.MatrixRankWarningMissingspsolve on a singular matrix returns SingularMatrix instead of warning (frankenscipy-6j5tz)
getattr is not seen. The file links open the test on GitHub.Same call, same answer
Port one call, check one answer.
Eight everyday SciPy calls from eight modules, each beside the Rust that replaces it. The Rust runs in this tab, and every output is compared with what SciPy returned for the same inputs, down to the bit.
Pick a call: the Rust runs here, and every output is checked against SciPy’s
SciPy
from scipy import linalg x = linalg.solve(a, b)
Rust · fsci-linalg
use fsci_linalg::{solve, SolveOptions}; let x = solve(&a, &b, SolveOptions::default())?.x;
The result also carries a CASP certificate; chapter 03 opens it.
Inputs
a = [[4, -2, 1, 3], [3, 6, -4, 2], [2, 1, 8, -5], [1, -3, 2, 7]]
b = [1, -2, 3, 4]
SciPy
from scipy import stats r = stats.ttest_ind(a, b, equal_var=False) r.statistic, r.pvalue, r.df
Rust · fsci-stats
use fsci_stats::ttest_ind_welch; let r = ttest_ind_welch(&a, &b); (r.statistic, r.pvalue, r.df)
SciPy’s equal_var flag becomes two functions: ttest_ind pools the variances and ttest_ind_welch does not.
Inputs
a = [5.1, 4.9, 6.2, 5.8, 6, 5.5, 5.3, 6.1]
b = [4.1, 4.5, 3.9, 4.8, 4.4, 5, 4.2]
SciPy
from scipy import optimize r = optimize.minimize(optimize.rosen, [-1.2, 1.0], method="BFGS") r.x, r.fun, r.nit, r.nfev
Rust · fsci-opt
use fsci_opt::{minimize, rosen, MinimizeOptions, OptimizeMethod}; let r = minimize(rosen, &[-1.2, 1.0], MinimizeOptions { method: Some(OptimizeMethod::Bfgs), ..Default::default() })?; (r.x, r.fun, r.nit, r.nfev)
Judge an iterative solver against its tolerance: BFGS stops once the gradient norm falls below 1e-5, so two correct runs can stop at slightly different points. The two rosen helpers are not quite the same function either: SciPy squares t before multiplying by 100, fsci multiplies first, so the objectives can differ in the last bit.
Inputs
x0 = [-1.2, 1]
SciPy
import math from scipy import integrate value, abserr, info = integrate.quad( lambda t: 1 / math.sqrt(t), 0, 1, full_output=1) info["neval"]
Rust · fsci-integrate
use fsci_integrate::{quad, QuadOptions}; let r = quad(|t: f64| 1.0 / t.sqrt(), 0.0, 1.0, QuadOptions::default())?; (r.integral, r.error, r.neval)
The integrand is infinite at 0, so QUADPACK subdivides toward it and extrapolates; neval in the table counts the evaluations each side made.
Inputs
a = 0
b = 1
SciPy
from scipy import fft spectrum = fft.rfft(x) spectrum.real, spectrum.imag
Rust · fsci-fft
use fsci_fft::{rfft, FftOptions}; // Vec<(re, im)> let spectrum = rfft(&x, &FftOptions::default())?;
Where one side computes an exact zero and the other a rounding residue near 10⁻¹⁶, the difference is shown in absolute terms, since a count of ulps away from zero is not meaningful.
Inputs
x = [-3, -1.875, 1.25, -0.625, -0.5, 1.625, -1.25, -2.125, -1, 2.125, 0.25, 0.375, 2.5, -0.375, -1.25, -0.125]
SciPy
from scipy import signal b, a = signal.butter(4, 0.2) y = signal.filtfilt(b, a, x)
Rust · fsci-signal
use fsci_signal::{butter, filtfilt, FilterType}; let ba = butter(4, &[0.2], FilterType::Lowpass)?; let y = filtfilt(&ba.b, &ba.a, &x)?;
Inputs
x = [-0.5, -0.32352941176470584, -0.14705882352941174, 0.02941176470588236, 0.20588235294117652, 0.38235294117647056, -0.4411764705882353, -0.2647058823529412, -0.08823529411764708, 0.08823529411764708, 0.2647058823529411, 0.4411764705882353, -0.38235294117647056, -0.20588235294117646, -0.02941176470588236, 0.1470588235294118, 0.32352941176470584, -0.5, -0.32352941176470584, -0.14705882352941174, 0.02941176470588236, 0.20588235294117652, 0.38235294117647056, -0.4411764705882353, -0.2647058823529412, -0.08823529411764708, 0.08823529411764708, 0.2647058823529411, 0.4411764705882353, -0.38235294117647056, -0.20588235294117646, -0.02941176470588236, 0.1470588235294118, 0.32352941176470584, -0.5, -0.32352941176470584, -0.14705882352941174, 0.02941176470588236, 0.20588235294117652, 0.38235294117647056, -0.4411764705882353, -0.2647058823529412, -0.08823529411764708, 0.08823529411764708, 0.2647058823529411, 0.4411764705882353, -0.38235294117647056, -0.20588235294117646, -0.02941176470588236, 0.1470588235294118, 0.32352941176470584, -0.5, -0.32352941176470584, -0.14705882352941174, 0.02941176470588236, 0.20588235294117652, 0.38235294117647056, -0.4411764705882353, -0.2647058823529412, -0.08823529411764708, 0.08823529411764708, 0.2647058823529411, 0.4411764705882353, -0.38235294117647056]
SciPy
from scipy import interpolate s = interpolate.CubicSpline(x, y) s(xq)
Rust · fsci-interpolate
use fsci_interpolate::{CubicSpline, SplineBc}; let s = CubicSpline::new(&x, &y, SplineBc::NotAKnot)?; let v: Vec<f64> = xq.iter().map(|&t| s.eval(t)).collect();
SciPy’s default end condition is not-a-knot; fsci’s SplineBc::default() is natural, so a port names the condition.
Inputs
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [-1, 1.5, 0.5, -0.5, 2, 1, 0, -1, 1.5, 0.5]
xq = [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 3.75, 4, 4.25, 4.5, 4.75, 5, 5.25, 5.5, 5.75, 6, 6.25, 6.5, 6.75, 7, 7.25, 7.5, 7.75, 8, 8.25, 8.5, 8.75, 9]
SciPy
from scipy import special special.ellipk(m)
Rust · fsci-special
use fsci_runtime::RuntimeMode; use fsci_special::{ellipk, SpecialTensor}; ellipk(&SpecialTensor::RealVec(m), RuntimeMode::Strict)?
Inputs
m = [-1, 0, 0.1, 0.5, 0.9, 0.99, 0.999999]
SciPy’s recorded answer is below. Starting fsci-linalg…
| Output | SciPy 1.17.1 | FrankenSciPy, live | Difference |
|---|
02Checked against SciPy
Tested against SciPy, case by case.
641 of the 783 differential test files hand their cases to a real SciPy 1.17.1 and compare its answers with FrankenSciPy’s under a tolerance named in the file; the rest check against NumPy, a closed form or an identity. In CI, a test that cannot reach SciPy fails instead of skipping, and a gate fails if any of the 1,167 named tolerances is loosened.
One test, start to finish
How a differential test works.
Each diff test is one Rust file. It builds its cases, hands them to SciPy in a child process, computes the same cases with FrankenSciPy, and holds each pair to a tolerance named in the file. This one checks SciPy’s exponentially scaled Bessel and Hankel functions on eight inputs, real and complex.
Step through one real test, then run its eight cases in this tab
1. Rust lists the cases. The test builds its inputs in Rust: eight calls of four functions, each with a readable id. They are serialized to JSON so both sides read exactly the same numbers.
let cases: &[(&str, &str, f64, f64, f64)] = &[
("jve_real", "jve", 0.5, 1.25, 0.0),
("yve_real", "yve", 0.5, 1.25, 0.0),
("hankel1e_real", "hankel1e", 1.0, 1.25, 0.0),
("hankel2e_real", "hankel2e", 1.0, 1.25, 0.0),
("jve_complex", "jve", 0.5, 1.25, 0.5),
("yve_complex", "yve", 0.5, 1.25, 0.5),
("hankel1e_complex", "hankel1e", 0.5, 1.25, 0.5),
("hankel2e_complex", "hankel2e", 0.5, 1.25, 0.5),
];diff_special_scaled_bessel.rs:552. SciPy answers them. A child process runs the Python script embedded in the test with the pinned SciPy. If that process cannot start and FSCI_REQUIRE_SCIPY_ORACLE is set, as it is in CI, the test fails instead of skipping.
let mut child = match fsci_conformance::scipy_oracle_command()
…
if std::env::var(REQUIRE_SCIPY_ENV).is_ok() {
return Err(test_error(format!("failed to spawn scipy oracle: {e}")));
…
import json
import sys
from scipy import special
q = json.loads(sys.argv[1])
points = []
for case in q["points"]:
z = complex(case["z_re"], case["z_im"])
if case["z_im"] == 0.0:
z = case["z_re"]
value = complex(getattr(special, case["function"])(case["order"], z))
points.append({"case_id": case["case_id"], "re": value.real, "im": value.imag})
print(json.dumps({"points": points}))diff_special_scaled_bessel.rs:973. FrankenSciPy answers them. The same cases go through fsci-special’s own functions, in Strict mode, which keeps SciPy’s observable behaviour.
let output = match case.function.as_str() {
"jve" => jve(&order, &z, RuntimeMode::Strict),
"yve" => yve(&order, &z, RuntimeMode::Strict),
"hankel1e" => hankel1e(&order, &z, RuntimeMode::Strict),
"hankel2e" => hankel2e(&order, &z, RuntimeMode::Strict),
other => return Err(test_error(format!("unknown function {other}"))),
}
.map_err(|err| test_error(err.to_string()))?;diff_special_scaled_bessel.rs:1524. Each pair meets the file’s tolerance. The tolerance is a named constant, 5 × 10⁻⁸, scaled by the larger of |SciPy| and 1. The comparison is written with <= so that a NaN fails instead of passing.
const SCALED_BESSEL_TOL: f64 = 5.0e-8;
…
let scale = expected.abs().max(1.0);
let diff = (actual - expected).abs();
// Written as `<=` so a NaN component (NaN diff) is a failure, not a silent pass.
let pass = diff <= SCALED_BESSEL_TOL * scale;
ledger.compared(arm, &case.case_id, pass);diff_special_scaled_bessel.rs:205. The ledger must have compared everything. Every case goes through a CompareLedger, and finish() fails the test unless each function compared at least its share of cases. A test that silently skipped every case used to pass; it no longer can.
let mut ledger = CompareLedger::new("diff_special_scaled_bessel", &ARMS);
…
ledger.finish(min_per_arm);diff_special_scaled_bessel.rs:182SciPy’s answers are recorded; FrankenSciPy’s are computed when you press Run.
Live, in this tab
Sixteen functions, 4,800 values.
Fourteen special functions and two distributions, each on 300 inputs that SciPy 1.17.1 evaluated when this page was built. FrankenSciPy evaluates the same inputs here, and every pair is compared bit for bit. The numbers below are whatever this run produces.
Run the battery: each strip holds all 300 values of one function, coloured by distance from SciPy
- Within 4 ulp
- –
- Worst relative difference
- –
- One pass of all sixteen
- –
- Same bits
- 1 to 4 ulp
- 5 to 256 ulp
- More
Bit for bit
Where the match is exact.
Some ports reproduce SciPy to the last bit, or to the last evaluation. Each claim says whether a test asserts it on every run or whether it was measured and logged, and links to the test and the commit that landed it.
Filter the claims by how each one is backed
111 / 111MAT files
loadmat reads SciPy’s own MAT test corpus as SciPy does
Every file in the corpus, under seven loadmat option sets. Floats are compared as hex bit patterns, and a built-in control shows that a one-bit change, a signed zero, a dtype change or a renamed variable would be caught. The 8 files SciPy rejects are rejected with the same error class.
Asserted by the testevery value equal to the bit
408 / 408layouts
dendrogram lays out trees exactly as SciPy does
Four linkage methods, six sizes from 2 to 60 points and seventeen option sets. Coordinates, leaf order, labels and colours must all be equal.
Asserted by the testevery field exactly equal
400 / 400matrices
matrix_balance finds LAPACK’s permutation
Sparse matrices where dgebal isolates eigenvalues by permutation. Permutations and power-of-two scalings are exact, so the balanced matrix, scaling and permutation are compared for equality.
Asserted by the testexact equality
0 ulpat every step
LSODA takes SciPy’s steps
fsci ports the C translation of ODEPACK that SciPy runs. On Robertson, van der Pol, HIRES, Arenstorf, the Oregonator and more, the test requires SciPy’s step and evaluation counts and its switches between Adams and BDF. On the pinned host every step row and every odeint row also came out bit-identical.
Asserted by the teststep counts, evaluations, LU count and switch history equalMeasured, loggedvalues bit-identical, logged
30 / 30cases
Trust-region minimizers match SciPy’s evaluation counts
trust-ncg, trust-krylov, dogleg and trust-exact took SciPy’s exact iteration, function, gradient and Hessian counts on all 30 cases. The test itself asserts the answers and an iteration count within 30%.
Measured, loggedexact counts, logged
24 / 25cases
COBYLA reproduces SciPy’s iterates
A transcription of PRIMA, which SciPy runs, that evaluates NumPy’s linear algebra in OpenBLAS’s order. 24 of 25 cases end with the same bits for x and f and the same number of evaluations. On hosts whose OpenBLAS uses older kernels, a borderline case can end differently (issue #17).
Measured, loggedbit-identical cases, logged
9 / 9problems
solve_bvp arrives at SciPy’s mesh
SciPy’s collocation method, transcribed: on nine boundary-value problems it took SciPy’s iteration count and node count and produced the same mesh. One problem’s exact path, 7 iterations and 233 nodes, is asserted in the crate’s own tests.
Asserted by the testone exact pathMeasured, loggedsame mesh on all nine
6.8 × 10⁻¹⁵worst, 198 cases
Complex linear algebra transcribes LAPACK
Complex solve, LU, QR, Hessenberg, Schur, eig and SVD follow the LAPACK routines SciPy calls, so eigenvalues come back in SciPy’s order. The test holds factors to 10⁻¹² and spectra to 10⁻¹⁰; the worst error measured was 6.8 × 10⁻¹⁵.
Measured, loggedworst relative error
7.8 × 10⁻¹⁶worst, 300 cases
The fftpack pseudo-differential operators
diff, tilbert, hilbert, cs_diff, shift and the rest of scipy.fftpack’s pseudo-differential operators. The test holds them to 10⁻¹³ relative to the signal; the worst error measured was 7.8 × 10⁻¹⁶.
Measured, loggedworst relative error
The tolerance ratchet
Tolerances can only tighten.
1,167 tolerance contracts in 782 diff files are recorded in fixtures/tolerance_baseline.json. CI gate G9 runs tolerance_lint against it: a contract looser than its baseline, or one the baseline has never seen, fails the build. Tightening always passes, and the baseline can only be loosened by editing it by hand, in a commit a reviewer can find.
Move the scaled-Bessel test’s tolerance and see what tolerance_lint says
1,167 contracts in 782 files
diff_special_scaled_bessel.rs
const SCALED_BESSEL_TOL: f64 = 5.0e-8;
diff_signal_stft_istft.rs, which the lint reports as unanchored until the baseline is refreshed.The CI job that runs one oracle test with no SciPy installed, and passes only if that test fails
With SciPy 1.17.1
Test runs and compares every case.
Without SciPy, oracle required
Test fails, so the control job passes.
If the test ever passed without SciPy
The job fails with “GATE DEFECT”.
if python -c "import scipy" 2>/dev/null; then
echo "control interpreter unexpectedly imports scipy" >&2
exit 1
fi
export SCIPY_PYTHON="$(which python)"
export FSCI_REQUIRE_SCIPY_ORACLE=1
if cargo test -p fsci-conformance --test diff_sparse_basic_queries -- --nocapture; then
echo "GATE DEFECT: the oracle-required lane PASSED with no SciPy present" >&2
exit 1
fi
echo "control ok: the lane failed closed without SciPy"03Condition-aware solving
Every solve shows its work.
A dense solve in FrankenSciPy returns the answer and a certificate: the conditioning it measured, the structure it found, a posterior over four condition states, the expected loss of every algorithm it could have used, the one that answered, the backward error it reached, and a digest that lets anyone replay the decision bit for bit. The part that decides is CASP, the Condition-Aware Solver Portfolio.
One solve, start to finish
Conditioning decides which algorithm is safe.
The reciprocal condition number, rcond, says how much a matrix can amplify error: near 10⁻¹², a rounding error in the sixteenth digit of b can reach the fourth digit of x. CASP estimates rcond from the factorization it computes anyway, detects the structure exactly as SciPy does, and ranks the algorithms by expected loss. In Strict mode SciPy’s own route for that structure runs first, so a general matrix gets LU as it does in scipy.linalg.solve, and the ranking decides what runs if LU misses the accuracy test, a backward error above 10⁻⁸.
Pick a matrix and watch the portfolio choose, attempt and certify
Matrix
Mode
Try
Starting fsci-linalg…
SolveCertificate fsci-linalg returns; the audit events are what solve_with_audit wrote to its ledger.The decision surface
Losses measured on 324 matrices.
Each action’s expected loss is its cost plus the cost of recovering from its failures, weighted by the posterior. The table behind it was measured: casp_calibrate ran every action on 324 seeded matrices at n = 8, 32, 128 (12 families, from Higham’s randsvd to Hilbert, Kahan and Wilkinson’s pivot-growth matrix) and priced each failure at the cheapest action that recovered it. On a fresh portfolio LU wins for every general matrix. The SVD costs 31.5 times LU’s flops and refuses a rank-deficient system, so it comes last.
Pick a structure, then move along rcond to read each action’s expected loss
SolverPortfolio for its choice at 321 values of rcond. Only the actions the structure admits are candidates: LU, QR and the SVD always, plus at most one fast path.Feedback
It learns from its own failures.
Every attempt goes back into the portfolio, tallied by decade of rcond. Once an action has attempts in a decade, what they showed replaces the calibrated failure term of its loss, through a Beta posterior worth four prior trials. Record outcomes for LU at rcond = 10⁻³ and watch the ranking change. In Strict mode solve still tries LU first on a general matrix; the ranking sets the order of the fallbacks, and Hardened mode tries the top choice first.
Record LU’s outcomes one at a time and watch the choice move
SolverPortfolio::record_outcome and asks it again. A miss is recorded as AttemptOutcome::Inaccurate, the outcome of a backward error above the accuracy test.Reproducibility
Replay any decision, bit for bit.
A certificate carries state_digest, a BLAKE3 hash of everything the portfolio decided from: its mode, its loss matrix, its outcome and failure tallies, and its calibration state. replay_decision refuses any snapshot with another digest, then feeds the certificate’s rcond and structure back in and demands the same choice, posterior and expected losses, compared as bit patterns. The conformance suite solves 1,000 systems through one portfolio that keeps learning and replays every certificate this way. Below, one certificate meets four portfolios.
Pick a matrix; one certificate is replayed against four portfolios
solve_with_casp, keeping a copy of the portfolio from just before, and runs replay_decision four times. A refused replay is how a postmortem finds out that the state it is reading is not the state that decided.04The algorithms
SciPy’s own algorithms, ported routine by routine.
Where SciPy runs a classic Fortran or C code, FrankenSciPy ports that code instead of writing its own: LSODA from SciPy’s C translation of ODEPACK, QUADPACK’s adaptive quadrature, Powell’s COBYLA as SciPy runs it through PRIMA, Kraft’s SLSQP, and the LAPACK routines behind complex eig. The tests then compare step counts, evaluation counts and iterates with SciPy’s, as well as the final answers.
ODEPACK’s LSODA
One solver that notices the stiffness.
Robertson’s chemical kinetics, run for 10¹¹ seconds, is the standard stiff test problem. LSODA starts with Adams steps of about 10⁻⁵ seconds. After 0.0055 seconds it detects stiffness, switches to backward differentiation formulas (BDF), and its steps grow to 10¹¹ seconds. FrankenSciPy’s LSODA ports the C file SciPy 1.17.1 calls, routine by routine, and its test requires the same step counts, evaluation counts and switch history as SciPy’s.
Move along the run to read LSODA’s state at each of its 200 output times
- t
- –
- Method
- –
- Step size
- –
- Steps
- –
- RHS evaluations
- –
- Jacobians
- –
- Running fsci-integrate…
odeint(robertson, 1, 0, 0], t, full_output=True) at odeint’s defaults (rtol = atol = 1.49 × 10⁻⁸), with t at 200 times spaced evenly in log t. SciPy’s answer was recorded with SciPy 1.17.1’s arm64 macOS wheel; the native column is the same engine compiled for that Mac. The repository’s test ([diff_integrate_lsoda.rs) asserts equal step counts, evaluation counts and switch history on its problems, and on its pinned x86-64 Linux host every row was also measured bit-identical to SciPy (89d2b1600).Minimizers
Follow a minimizer iterate by iterate.
Rosenbrock’s curved valley is the standard test for minimizers: easy to fall into, slow to follow to its floor at (1, 1). Pick a method and FrankenSciPy runs it here from (−1.2, 1), drawing each iterate and every point where it evaluated the function. SciPy’s recorded path is drawn beneath it. Click or tap the map to start from somewhere else.
Pick a method, then click the map to start from another point
Method
- Start
- (−1.2, 1)
- Iterations
- –
- Evaluations
- –
- Ends at
- –
- f there
- –
- Running fsci-opt…
100·(t·t) + u·u with t = y − x², u = 1 − x. SciPy’s rosen rounds 100·t² differently from fsci’s, so neither library’s helper is used. Gradients are finite differences on both sides, at SciPy’s default steps. SciPy’s paths come from minimize(..., callback=...), recorded from (−1.2, 1) with SciPy 1.17.1 on an arm64 Mac; the map itself is drawn by this page.QUADPACK
Split the panel with the largest error.
QUADPACK’s QAGS integrates each panel with a 21-point Gauss–Kronrod rule, bisects whichever panel has the largest error estimate, and extrapolates the sequence of sums with Wynn’s epsilon algorithm. The extrapolation is why 1/√x, infinite at 0, converges after six panels. FrankenSciPy’s port follows the Fortran statement by statement, and quad_full_output returns the same panel lists as SciPy’s full_output=1.
Pick an integrand, then point at a panel to read its share of the integral and its error
- Integral
- –
- Exact
- –
- Error estimate
- –
- Evaluations
- –
- Panels
- –
- Running fsci-integrate…
| Rank | Panel | Integral over it | Error estimate | vs SciPy |
|---|
quad(f, 0, 1, full_output=1) at its defaults (epsabs = epsrel = 1.49 × 10⁻⁸, limit = 50), recorded with SciPy 1.17.1. The panel errors need not add up to the reported error: the extrapolated sum is more accurate than its panels.Provenance
Where each port comes from.
Most of SciPy’s numerical core is old, carefully tuned code, and its behaviour at the edges is part of what users rely on. FrankenSciPy ports that code where it can, so iterates, counts and edge cases come out the same. Where it uses a different algorithm for the same contract, the list says so.
Each port, what SciPy runs, the Rust that replaces it and the test that compares them
LSODA
Ported routine by routineAdams and BDF in one ODE solver, switching when the problem turns stiff
- SciPy runs
- SciPy 1.17.1’s
lsoda.c, a C translation of ODEPACK’s DLSODA (Hindmarsh, with Petzold’s switching) - FrankenSciPy
fsci-integrate/src/lsoda.rs- Compared in
diff_integrate_lsoda.rs
- Asserted by the testStep counts, evaluation counts and switch history equal to SciPy’s
- Measured, loggedEvery row bit-identical on the pinned x86-64 host (89d2b1600)
QUADPACK
Ported routine by routineAdaptive quadrature: QAGS, QAGI, QAGP and the weighted QAW routines
- SciPy runs
- QUADPACK (Piessens, de Doncker-Kapenga, Überhuber, Kahaner, 1983), as
scipy.integrate.quadruns it - FrankenSciPy
fsci-integrate/src/quadpack.rs- Compared in
diff_integrate_quad_quadpack.rs
- Asserted by the testSciPy’s
ier; the value to QUADPACK’s own accuracy request - Measured, logged53 cases matched value, error, evaluation count and panel count exactly when the port landed (46c6065df)
COBYLA
Ported routine by routineDerivative-free minimization with constraints, by linear approximation
- SciPy runs
- Powell’s COBYLA as SciPy runs it:
scipy._lib.pyprima, the Python translation of Zaikun Zhang’s PRIMA - FrankenSciPy
fsci-opt/src/cobyla.rs- Compared in
diff_opt_cobyla_minimize.rs
- Asserted by the testSciPy’s status, success flag and message
- Measured, logged24 of 25 cases bit-identical in x and f, in OpenBLAS’s SkylakeX evaluation order (9ec3a5475)
SLSQP
Ported routine by routineSequential least-squares quadratic programming with equality and inequality constraints
- SciPy runs
- Kraft’s SLSQP (1988), from SciPy 1.17’s C translation
__slsqp.cand__nnls.c - FrankenSciPy
fsci-opt/src/slsqp.rs- Compared in
diff_opt_slsqp_constrained.rs
- Asserted by the testSciPy’s exit message; x within 10⁻⁶ on Hock–Schittkowski problems 6, 7, 21, 35, 71 and 76
- Measured, loggedThe same final iteration count as SciPy on 15 of 16 cases (569367b2c)
trust-constr
Ported routine by routineByrd–Omojokun SQP for equalities, a trust-region interior-point method for the rest
- SciPy runs
- SciPy’s
_trustregion_constrpackage, with its projections and its memoized function wrappers - FrankenSciPy
fsci-opt/src/trust_constr.rs- Compared in
diff_opt_trust_constr_constrained.rs
- Asserted by the testStatus and message; x to 10⁻⁵, f to 10⁻⁷, Lagrange multipliers to 10⁻⁴
Trust-region Newton
Ported routine by routinetrust-ncg, dogleg, trust-exact and trust-krylov: four subproblem solvers, one driver
- SciPy runs
- SciPy’s
_minimize_trust_regionwith CG–Steihaug, dogleg, Moré–Sorensen and GLTR - FrankenSciPy
fsci-opt/src/trust_region.rs- Compared in
diff_opt_trust_region_family.rs
- Asserted by the testSciPy’s status; x and f to tolerance; iteration count within 30%
- Measured, loggedAll 30 cases matched SciPy’s exact iteration, function, gradient and Hessian counts
Radau IIA and BDF
Ported routine by routineThe implicit
solve_ivpmethods for stiff problems- SciPy runs
- SciPy’s
_ivp/radau.pyand_ivp/bdf.py, step for step - FrankenSciPy
fsci-integrate/src/radau.rs- Compared in
diff_integrate_solve_ivp_stiff.rs
- Asserted by the testy within one unit of SciPy’s error scale; evaluation and step counts within 1%
- Measured, logged15 of 16 finite-difference rows reproduce SciPy’s counts exactly
DOP853
Ported routine by routineThe explicit eighth-order Runge–Kutta method with dense output
- SciPy runs
- SciPy’s
_ivp/rk.pywith Hairer’s coefficients and its blended E5/E3 error norm - FrankenSciPy
fsci-integrate/src/rk.rs- Compared in
diff_integrate_dop853.rs
- Asserted by the testy within one unit of SciPy’s error scale wherever SciPy’s own answer is reproducible at that scale
solve_bvp
Ported routine by routineBoundary-value problems by collocation with mesh refinement
- SciPy runs
- Kierzenka and Shampine’s algorithm, transcribed from SciPy’s
_bvp.py - FrankenSciPy
fsci-integrate/src/collocation.rs- Compared in
diff_integrate_solve_bvp_collocation.rs
- Asserted by the testSciPy’s status; one boundary-layer problem pinned at SciPy’s 7 iterations and 233 nodes
- Measured, loggedThe same iterations, node count and mesh on 9 problems (46c6065df)
Complex LAPACK
Ported routine by routineLU, QR, Hessenberg, Schur and eigenvectors of complex matrices
- SciPy runs
- The LAPACK routines SciPy calls: zgetf2, zgeqr2 and zung2r, zgebal, zgehd2 and zunghr, zlahqr, ztrevc3
- FrankenSciPy
fsci-linalg/src/complex.rs- Compared in
diff_linalg_complex_core.rs
- Asserted by the testFactors entry by entry to 10⁻¹², same pivots, signs and eigenvalue order
- Measured, logged198 cases within 6.8 × 10⁻¹⁵ (7ec9bee19)
Jonker–Volgenant
Same algorithmlinear_sum_assignment: the cheapest one-to-one assignment- SciPy runs
- The shortest augmenting path method SciPy uses for rectangular cost matrices
- FrankenSciPy
fsci-opt/src/lib.rs- Compared in
diff_opt_linear_sum_assignment.rs
- Asserted by the testThe total cost to 10⁻¹² (ties between optimal assignments may pick different pairs)
eigsh and eigs
Own algorithm, same contractA few eigenvalues of a large sparse matrix
- SciPy runs
- SciPy calls ARPACK’s implicitly restarted Lanczos and Arnoldi; FrankenSciPy restarts with Krylov–Schur instead
- FrankenSciPy
fsci-sparse/src/linalg.rs- Compared in
diff_sparse_eigs_eigsh_arpack_parity.rs
- Asserted by the testEigenvalues, residuals and convergence status against ARPACK’s, for every
which, shift-invert and a mass matrix
linprog
Own algorithm, same contractLinear programs, with HiGHS’s result shape: slacks, residuals and marginals
- SciPy runs
- SciPy calls HiGHS; FrankenSciPy has its own bounded revised simplex and a Mehrotra interior point with crossover
- FrankenSciPy
fsci-opt/src/linprog.rs- Compared in
diff_opt_linprog_highs.rs
- Asserted by the testStatus and message for each of SciPy’s three HiGHS methods
- Measured, logged102 outcomes compared with none failing when it landed
05Safe to embed
Safe Rust from the API down to the kernels.
All 19 crates declare #![forbid(unsafe_code)]. Nothing links BLAS or LAPACK (a test fails if a native BLAS enters the build), there is no async runtime, and a plain cargo build is the whole build. The same crates run in a server, a command-line tool or this browser tab. Bad input comes back as a typed error, and the audited entry points record why.
Two modes, one API
Strict for parity, hardened for services.
Every mode-aware routine takes a RuntimeMode. Strict behaves as SciPy does, warnings and quirks included. Hardened keeps the same signatures and refuses more: non-finite input even when check_finite is off, systems whose estimated reciprocal condition number is below 10⁻¹⁴, and matrices over 10,000 rows or columns. By default neither mode repairs input. Either way the caller gets a typed error and the ledger gets a reason code.
Each input goes through solve_with_audit in both modes; switch off check_finite to see where they part
…
…
…
…
…
…
…
…
…
…
No cap
Strict trusts the caller with resource budgets.
RefusedResourceExhausted
resource_exhausted above 10,000 rows or columns
check_finite is SciPy’s switch for skipping the scan for NaN and infinity. The reason codes are the ones the ledger records; audit_failclosed_property.rs drives 49 audited APIs with bad input in every mode they have and asserts that each error is recorded as exactly one fail-closed event, the call’s last. The size cap is not sent to your browser: a 10,001-row matrix in Hardened mode is refused before any work with resource_exhausted, while Strict leaves resource budgets to the caller.The audit ledger
An audit trail per call.
The _with_audit entry points write to an AuditLedger the caller owns: CASP decisions, mode decisions, bounded recoveries, and one fail-closed event for every error. Each event carries a BLAKE3 fingerprint of the routine and every input, hashed bit for bit, so a ledger can be filtered down to one request. Hashing bits has a consequence you can try here: 0.0 and −0.0 are equal numbers and give the same solution, and they still give different fingerprints.
Change one entry of the matrix by a single bit and watch the solve’s fingerprint
The system A·x = b
The highlighted entry, A[0][2]
x
…
Fingerprint of the solve
with 0.0…
now…
The ledger, one JSON line per event
Across platforms
The same decisions on every platform.
A last-bit difference matters most where it can tip a decision: a threshold crossed on one machine and missed on another, so one platform solves and another refuses. The solver’s decision path therefore computes exp and log10 with its own FDLIBM and musl ports, built from +, −, × and ÷ so they give the same bits everywhere, and estimates rcond for matrices up to 4×4 with one-sided Jacobi instead of an SVD that calls the platform’s math library. The battery below ran in your browser just now and natively on the machine that built this page.
Compare each result from this tab with the build machine’s, value by value
Running the battery…
- same bits
- different bits
The portfolio’s state digest after the 6×6 solve
this tab…
build machine…
powf and the FFT’s twiddle factors use sin and cos, and those functions’ last bits differ between libraries. LSODA still takes the same steps and evaluations on both, and its final state differs by far less than the tolerances it runs at, rtol = 10⁻³ and atol = 10⁻⁶ by default, as in SciPy.What runs this page
The engine in this tab.
Every live figure on this page calls fsci-web, a small Rust program over ten FrankenSciPy crates. It is built for wasm32-wasip1, reads one JSON request on stdin and writes one JSON reply on stdout, and runs through a WASI shim of a few dozen lines that gives it stdin, stdout, a clock and random bytes, and nothing else. It never reaches the network.
These numbers come from your browser, and the call count rises as you use the page
- 19 of 19 crates forbid unsafe code
Each
lib.rsopens with#![forbid(unsafe_code)], and each manifest inherits the workspace lintunsafe_code = "forbid". The engine on this page forbids it too. - No BLAS, no LAPACK
A test in fsci-linalg reads
Cargo.lockwhen the tests compile and fails if a package named like blas, lapack, mkl, openblas or netlib has entered the graph, transitively included. Every timing against SciPy stays a timing of FrankenSciPy’s own Rust. - No async runtime
Every routine is synchronous and returns a
Result, and no crate depends on tokio:cargo tree -i tokioprints nothing for x86-64 Linux, Apple silicon or either wasm32 target. The crates drop into whatever runtime the host uses. - One
cargo buildThere is no Python to embed, no Fortran compiler and no BLAS to install first. This engine is the same crates built with
--target wasm32-wasip1.
engine.info.06Performance
Faster in places, slower in others, all measured.
Every timing in this chapter comes from one run on one machine, FrankenSciPy and SciPy side by side, as the project’s performance rules require. Batched calls and structured stiff solves win by large factors. Dense eigensolves, sparse LU and sparse addition are still slower than the LAPACK, SuperLU and C++ code SciPy calls. Both kinds of result are published, with the line in the ledger that records each.
Same-run ratios
Wins and losses, on one scale.
Batched calls that SciPy can only loop, and solvers that use structure SciPy ignores, win by one or two orders of magnitude. Plain dense and sparse linear algebra still loses to the LAPACK, SuperLU and C++ code SciPy calls: 3.6× for eigh at n = 768, 16× for adding two sparse matrices. Open a row for its setup and the line in the ledger that records it.
Filter the rows, then open one to see what was timed and where it is recorded
-
curve_fit_many2,000 exponential-decay fits145×faster, FrankenSciPy faster. Open for the setup.
One call fits all 2,000 traces. SciPy ran five public routes to the same answers and the fastest, a joint sparse least-squares solve over the whole study, is the one compared: 633.3 ms against 4.38 ms. 32 pinned cores.
A batched API SciPy does not have. Each row of the batch is bit-identical to a single
curve_fitcall. -
minimize_manyBFGS from 128 starts102×faster, FrankenSciPy faster. Open for the setup.
Against SciPy's BFGS with the exact analytic gradient, the fastest of four public routes: 748.8 ms against 7.35 ms. 32 pinned cores.
Multistart is common in global optimization; SciPy runs the starts one at a time.
-
spsolveperiodic 9×11×13 grid, 32 solves84×faster, FrankenSciPy faster. Open for the setup.
Against
scipy.sparse.linalg.spsolve, one thread each: 6.08 ms against 510.1 ms.The same public call was 124.7× slower before its periodic structure was recognized.
-
solve_ivp, BDFn = 512, diagonal Jacobian39×faster, FrankenSciPy faster. Open for the setup.
Against
solve_ivp(method='BDF')at the same tolerances: 13.6 ms against 522.2 ms.The win comes from noticing the Jacobian is diagonal. SciPy runs a dense LU on every refresh.
-
solve_ivp, BDFn = 512, tridiagonal Jacobian12×faster, FrankenSciPy faster. Open for the setup.
Same harness and size, a tridiagonal Jacobian solved through the banded path: 43.1 ms against 514.9 ms.
Less structure, smaller win. The dense row further down is the same experiment with none.
-
tplquad_many100 triple integrals7.1×faster, FrankenSciPy faster. Open for the setup.
Against vectorized
cubatureon a persistent 32-worker process pool, SciPy's fastest public route: 14.24 ms against 2.03 ms.Batched quadrature over a parameter sweep.
-
quad_many2,048 integrals5.8×faster, FrankenSciPy faster. Open for the setup.
Against
quadon a persistent 32-worker process pool: 7.64 ms against 1.32 ms.A damped frequency-response study, one integral per parameter set.
-
normaltest, jarque_bera, shapiro2,048 channels × 4,096 samples4.9×faster, FrankenSciPy faster. Open for the setup.
Batched normality screening against a persistent 32-worker process pool: 83.8 ms against 17.0 ms.
Re-measured in September after the ledger retired the earlier 74–2,267× claims.
-
gmresn = 1,0244.9×faster, FrankenSciPy faster. Open for the setup.
Nonsymmetric convection-diffusion,
rtol = 1e-5. Both sides did the same 127 inner iterations: 2.36 ms against 11.55 ms.Same algorithm, same iteration count; the difference is per-iteration cost.
-
dblquad_many128 double integrals3.5×faster, FrankenSciPy faster. Open for the setup.
Against vectorized
cubatureon a 32-worker process pool: 4.19 ms against 1.20 ms.Just above the project's 3× bar for calling a win durable.
-
newton_many65,536 implied volatilities1.99×faster, FrankenSciPy faster. Open for the setup.
Against array
newtonon a 32-worker process pool: 13.07 ms against 6.56 ms.Faster, but under the 3× bar, so the ledger does not call it a durable win.
-
gmresn = 4,0961.57×faster, FrankenSciPy faster. Open for the setup.
The same problem on a larger grid, 163 inner iterations each: 13.90 ms against 20.79 ms.
The lead shrinks as the problem grows.
-
gmresn = 9,2161.06×slower, SciPy faster. Open for the setup.
Larger still, 227 inner iterations each: 38.33 ms against 36.06 ms.
Here SciPy is ahead, by 6%.
-
choleskyn = 8321.61×slower, SciPy faster. Open for the setup.
A = MMᵀ + nI, FrankenSciPy on all 64 threads against SciPy's threaded LAPACK.
One cell of a measured loss band from n ≈ 576 to 1,280. FrankenSciPy wins again at n = 2,048.
-
solve_ivp, BDFn = 512, dense Jacobian2.1×slower, SciPy faster. Open for the setup.
The BDF experiment above with no exploitable structure: 1,086.7 ms against 513.5 ms. 129 LU factorizations against LAPACK's
dgetrf, and 1.9× as many right-hand-side evaluations.On a dense stiff problem FrankenSciPy is 2.1× slower. Its BDF wins only where structure lets it.
-
splu, solve stagen = 16,384, 16 right-hand sides2.3×slower, SciPy faster. Open for the setup.
Convection-diffusion against SuperLU, one thread each, default settings: 52.0 ms for the 16 solves.
Declaring the 16 solves up front makes the solve stage 1.61× faster than SuperLU, at a cost of 1.29× on the factorization.
-
eighn = 7683.6×slower, SciPy faster. Open for the setup.
Dense symmetric eigendecomposition against SciPy with one BLAS thread: 3.63× slower.
The worst dense cell. 61.5% of the time is the eigenvector back-transform; a blocked rewrite of it was measured slower and rejected.
-
COO addition28,672², two 1-million-entry operands16×slower, SciPy faster. Open for the setup.
192.5 ms against SciPy's 12.0 ms.
The shipped path is still the slow one: a faster merge reached only 0.49× of SciPy and was reverted (see below).
The optimization loop
A speedup counts when it beats SciPy.
A change that claims to be faster goes through the same five steps, and the ledger keeps the ones that fail as carefully as the ones that pass, so nobody retries a dead end. Two of them, side by side: one kept, and one reverted after it had made the code nearly eight times faster.
Read down the five steps for a change that was kept and one that was reverted
- 1Baseline
Record p50, p95, p99 and memory, with SciPy timed in the same run.
KeptPublic
spsolveon a shifted periodic cuboid, one factor and solve per right-hand side: 124.7× slower than SciPy.RevertedAdding two 1-million-entry COO matrices, 28,672 square: 192.5 ms, against SciPy’s 12.0 ms.
- 2Profile
Find the real hotspot. No lever is pulled on a guessed one.
KeptThe one-shot call took the general sparse factorization every time. The crate already had a recognizer for periodic grids and a Fourier plan; this path never used them.
RevertedThe public addition cloned both operands and merged their entries through an ordered tree.
- 3One lever
Change one thing, with its expected effect written down first.
KeptReuse the periodic recognizer and Fourier plan inside
spsolve, falling back to LU when the true residual is too large.RevertedMerge the two sorted operands in one linear pass instead of through the tree.
- 4Prove nothing changed
Behaviour must match before a timing counts. No tolerance may be loosened to make it match.
KeptThe new route fired on 32 of 32 calls. Largest relative residual 2.1 × 10⁻¹², against SciPy’s 1.5 × 10⁻¹²; no component disagreed.
RevertedThe candidate, the old path and SciPy produced the same sparse matrix, every pointer, index and float bit for bit.
- 5Re-measure against SciPy
Beating your own old code is maintenance. Only beating SciPy in the same run is a win.
Kept6.08 ms against SciPy’s 510.1 ms: 84.2× faster. The 67.6× over the old code is recorded separately, as maintenance.
Reverted24.6 ms: 7.8× faster than the old code, and still 2.05× slower than SciPy’s 12.0 ms. The gate requires beating SciPy.
- Decision
Taken on the bootstrap-median interval, which must clear twice the noise of timing a side against itself.
KeptKeep The route ships, and the row joins the scoreboard above.
RevertedRevert The code is restored byte for byte in a new commit, so the attempt stays in the history and the result stays in the ledger.
07Get started
Add a crate. Keep your Rust.
Every fsci-* crate is on crates.io at version 0.5.2. Add the ones you need: each brings in only the fsci crates it depends on, and none of them brings in Python, a BLAS or a LAPACK.
Version 0.5.2
Pick the crates, copy one line.
Each crate covers one part of SciPy. Tick the ones you need and copy the cargo add line, or copy any crate on its own. Eleven of them use the unstable portable_simd feature, directly or through a dependency, so build with nightly Rust; the repository pins nightly-2026-08-31.
Tick the crates you need, then copy the command or the Cargo.toml lines
Your command
cargo add fsci-linalg fsci-stats
Cargo also builds fsci-fft, fsci-integrate, fsci-opt, fsci-runtime, fsci-sparse, fsci-special, which they depend on.
Or in Cargo.toml
[dependencies] fsci-linalg = "0.5" fsci-stats = "0.5"
Toolchain: rustup toolchain install nightly-2026-08-31, then a rust-toolchain.toml naming it in your project.
-
Linear algebra decompositions, solvers, and eigenvalues.
scipy.linalgscipy.linalg.interpolative79,519 lines · 920 tests
-
Probability distributions and statistical tests.
scipy.statsscipy.stats.contingencyscipy.stats.mstatsscipy.stats.qmcscipy.stats.sampling156,154 lines · 2,654 tests
-
Special mathematical functions.
scipy.special85,324 lines · 1,407 tests
-
Optimization and root-finding solvers.
scipy.differentiatescipy.optimizescipy.optimize.elementwise83,797 lines · 937 tests
-
Numerical integration and ODE/IVP solvers.
scipy.integrate57,491 lines · 690 tests
-
Sparse matrices and iterative solvers.
scipy.sparsescipy.sparse.csgraphscipy.sparse.linalg97,683 lines · 1,004 tests
-
Signal processing, filter design, and spectral analysis.
scipy.signalscipy.signal.windows45,645 lines · 831 tests
-
Fast Fourier Transform routines.
scipy.fftscipy.fftpack14,405 lines · 266 tests
-
Interpolation and spline routines.
scipy.interpolate30,114 lines · 318 tests
-
Spatial data structures and distance computations.
scipy.spatialscipy.spatial.distancescipy.spatial.transform20,441 lines · 329 tests
-
Vector quantization and hierarchical clustering.
scipy.cluster.hierarchyscipy.cluster.vq18,429 lines · 224 tests
-
Multi-dimensional image processing routines.
scipy.ndimage32,665 lines · 373 tests
-
File format I/O (MATLAB, Matrix Market, WAV).
scipy.ioscipy.io.arffscipy.io.matlabscipy.io.wavfile13,562 lines · 162 tests
-
Orthogonal Distance Regression.
scipy.odr5,780 lines · 39 tests
-
Physical and mathematical constants.
scipy.constants1,733 lines · 25 tests
-
Standard sample fixtures and datasets.
Synthetic stand-ins with the shapes of SciPy’s
ascent,faceandelectrocardiogram, not SciPy’s data.scipy.datasets669 lines · 9 tests
-
Condition-Aware Solver Portfolio (CASP) runtime.
CASP, the audit ledger and the Strict and Hardened modes. Add it to pass your own
SolverPortfolioorAuditLedgerto a call.9,453 lines · 414 tests
-
Reference Array API abstraction layer.
The reference Array API backend and broadcasting rules the conformance suite checks against.
5,058 lines · 64 tests
wc -l over each crate’s src/, inline tests included; tests count #[test] functions; the SciPy modules are the ones the symbol census assigns to each crate. A crate is marked nightly when it or one of its fsci dependencies enables an unstable feature (fsci-cluster, fsci-linalg, fsci-ndimage, fsci-spatial, fsci-special, fsci-stats enable portable_simd). fsci-conformance (36,535 lines, 1,638 tests) is on crates.io too, but it is the test harness that drives a live SciPy; leave it out of your dependencies.From Python
The same call, spelled in Rust.
The names and defaults follow SciPy, so most ports are mechanical. Pick an area to see the everyday calls side by side, with the use line to start from and the one difference worth knowing for each.
Pick an area of SciPy to see its calls next to their Rust equivalents
Linear algebra
use fsci_linalg::{eigh, expm, lstsq, solve, DecompOptions, LstsqOptions, SolveOptions};x = scipy.linalg.solve(a, b)
let x = solve(&a, &b, SolveOptions::default())?.x;ais aVec<Vec<f64>>, one inner vector per row. The result also carries the CASPcertificateand thebackward_error.x, res, rank, sv = scipy.linalg.lstsq(a, b)
let r = lstsq(&a, &b, LstsqOptions::default())?;One struct instead of a four-tuple:
r.x,r.residuals,r.rank,r.singular_values.w, v = scipy.linalg.eigh(a)
let r = eigh(&a, DecompOptions::default())?;r.eigenvaluesin ascending order andr.eigenvectorsas columns, as SciPy returns them.e = scipy.linalg.expm(a)
let e = expm(&a, DecompOptions::default())?;Padé approximation with scaling and squaring, the algorithm SciPy uses.
Sparse
use fsci_sparse::{cg, spsolve, CsrMatrix, IterativeSolveOptions, Shape2D, SolveOptions};a = csr_matrix((data, indices, indptr), shape=(m, n))
let a = CsrMatrix::from_components(Shape2D::new(m, n), data, indices, indptr, true)?;
The last argument asks for sorted indices with duplicate entries summed.
x = spsolve(a, b)
let x = spsolve(&a, &b, SolveOptions::default())?.solution;The result also names the backend and the fill-reducing ordering that were used.
x, info = cg(a, b)
let r = cg(&a, &b, None, IterativeSolveOptions::default())?;
infobecomesr.converged, withr.iterationsandr.residual_normbeside it. The third argument is the starting guess.
Optimize
use fsci_opt::{bfgs, brentq, lbfgsb, MinimizeOptions, RootOptions};res = minimize(f, x0, method="BFGS")let res = bfgs(&f, &x0, MinimizeOptions::default())?;fis anyFn(&[f64]) -> f64.minimize(f, &x0, options)withmethod: Some(OptimizeMethod::Bfgs)does the same.res = minimize(f, x0, method="L-BFGS-B", bounds=[(0, None)] * n)
let bounds = vec![(Some(0.0), None); n]; let res = lbfgsb(&f, &x0, MinimizeOptions::default(), Some(&bounds))?;
A bound is an
(Option<f64>, Option<f64>)pair, andNoneleaves that side open.root = brentq(f, a, b)
let root = brentq(f, (a, b), RootOptions::default())?.root;The result also reports
converged,iterationsandfunction_calls.
Integrate
use fsci_integrate::{quad, solve_ivp, QuadOptions, SolveIvpOptions, SolverKind};sol = solve_ivp(f, (0, 10), y0, method="LSODA")
let sol = solve_ivp(&mut f, &SolveIvpOptions { t_span: (0.0, 10.0), y0: &y0, method: SolverKind::Lsoda, ..Default::default() })?;
fis anFnMut(f64, &[f64]) -> Vec<f64>. RK23, RK45, DOP853, Radau, BDF and LSODA are all there, with SciPy’s defaults.val, err = quad(f, a, b)
let r = quad(f, a, b, QuadOptions::default())?;r.integralandr.error, from a port of QUADPACK’s qagse, the routine SciPy calls.
Signal and FFT
use fsci_fft::{rfft, FftOptions}; use fsci_signal::{butter, filtfilt, FilterType};
spec = scipy.fft.rfft(x)
let spec = rfft(&x, &FftOptions::default())?;Each bin comes back as an
(re, im)pair. SciPy’s normalization is the default.b, a = butter(4, [lo, hi], btype="bandpass")
let ba = butter(4, &[lo, hi], FilterType::Bandpass)?;
Frequencies are normalized to Nyquist, as in SciPy. The coefficients are
ba.bandba.a.y = filtfilt(b, a, x)
let y = filtfilt(&ba.b, &ba.a, &x)?;Zero-phase filtering, forward then backward, with SciPy’s default padding.
Statistics
use fsci_stats::{ttest_ind_welch, BetaDist, ContinuousDistribution, Normal};p = scipy.stats.norm.pdf(x, loc, scale)
let p = Normal::new(loc, scale).pdf(x);The
ContinuousDistributiontrait has to be in scope forpdf,cdf,ppfand the moments.q = scipy.stats.beta(2, 5).ppf(0.5)
let q = BetaDist::new(2.0, 5.0).ppf(0.5);
Distribution constructors panic on invalid parameters, the one documented exception to typed errors.
t, p = ttest_ind(a, b, equal_var=False)let t = ttest_ind_welch(&a, &b);Welch’s test is its own function;
ttest_indis the pooled-variance test, SciPy’s default.
Special
use fsci_runtime::RuntimeMode; use fsci_special::{elliprf, gamma, SpecialTensor};
g = scipy.special.gamma(x)
let g = gamma(&SpecialTensor::RealScalar(x), RuntimeMode::Strict)?;Tensor functions take a scalar, a vector or complex values, plus a mode.
RealVecevaluates a whole array in one call.rf = scipy.special.elliprf(x, y, z)
let rf = elliprf(x, y, z);The Carlson elliptic integrals are plain
f64functions.
Spatial
use fsci_spatial::KDTree;d, i = KDTree(points).query(q)
let (i, d) = KDTree::new(&points)?.query(&q)?;Index first, then distance: the reverse of SciPy’s tuple.
Result are shown with ?; the error types are LinalgError, SparseError, OptError and so on, one per crate.- 1
Keyword arguments become an options struct
Each routine takes one options struct with SciPy’s defaults. Set the fields you would have passed by keyword and leave the rest to
Default.# SciPy minimize(f, x0, tol=1e-10, options={"maxiter": 500}) // FrankenSciPy MinimizeOptions { tol: Some(1e-10), maxiter: Some(500), ..Default::default() }
- 2
Tuples become named result structs
Where SciPy returns a tuple or a result object, FrankenSciPy returns a struct. Read fields by name instead of unpacking by position.
# SciPy w, v = scipy.linalg.eigh(a) // FrankenSciPy let r = eigh(&a, opts)?; // r.eigenvalues, r.eigenvectors
- 3
Portfolios and ledgers are explicit
Plain
solvekeeps a portfolio per thread for you. To keep your own, or to record an audit trail per request, pass them in.# SciPy x = scipy.linalg.solve(a, b) // FrankenSciPy solve_with_audit(&a, &b, opts, &mut portfolio, &ledger)?
Honest scope
When it fits, and when it doesn’t.
FrankenSciPy is for Rust programs that need SciPy’s numerics. It does not replace SciPy for interactive work, and it does not try to beat vendor BLAS on large dense matrices.
Reach for it when
- You are writing a long-running Rust service that needs numerical routines, and you would rather not embed a Python interpreter in it.
- You need to show, in a postmortem, an audit or a report, which algorithm produced a number and on what evidence. Dense solves return a certificate, and audited calls write a ledger.
- You want no C or Fortran numerical library in your build: no FFI to BLAS or LAPACK, and
forbid(unsafe_code)in every fsci crate. - You want SciPy’s names and defaults in a synchronous, deterministic API with no async runtime underneath.
- You are building an agent or pipeline that calls numerical kernels and needs a record of every decision and every rejected input.
Look elsewhere when
- You are exploring data in a notebook. SciPy with NumPy, pandas and matplotlib is still the right tool there.
- You want to call it from Python. There is no Python binding today.
- You need the fastest large dense linear algebra. A BLAS-backed stack such as ndarray-linalg with OpenBLAS or MKL is faster on big matrices; the scoreboard above shows where FrankenSciPy loses.
- You need a GPU or a cluster. Every routine runs on one machine’s CPU.
- You need one of the six SciPy names with no implementation yet, or a stable API: the crates are pre-1.0, and option structs can still change between minor versions.
Check a specific name in the lookup, and the open defects and performance gaps in the README’s limitations.
Open source · version 0.5.2
Read the code. Run the tests.
Everything on this page can be checked from a clone: the 783 differential tests, the 1,167 tolerance contracts, the census of SciPy’s public names and the CASP calibration corpus. The README separates what is implemented from what is planned, and lists the places where FrankenSciPy is still slower than SciPy. Bug reports with a failing input are the most useful thing you can send.
git clone https://github.com/Dicklesworthstone/frankenscipy
cd frankenscipy
cargo test -p fsci-conformance # the live-SciPy tests need SciPy 1.17.1 and NumPy 2.4.3