### Install Peroxide with Multiple Features Source: https://github.com/axect/peroxide/blob/master/README.md Installs Peroxide with multiple features enabled, including 'O3' for linear algebra, 'plot' for visualization, 'nc' and 'csv' for data handling, 'parquet' for efficient storage, and 'serde' for serialization. ```bash cargo add peroxide --features "O3 plot nc csv parquet serde" ``` -------------------------------- ### Install Peroxide with Single Feature Source: https://github.com/axect/peroxide/blob/master/README.md Installs Peroxide with the 'plot' feature enabled, which is necessary for visualization capabilities. ```bash cargo add peroxide --features "plot" ``` -------------------------------- ### Integrate function with Gauss-Kronrod quadrature Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Example demonstrating how to use the `integrate` function with Gauss-Kronrod quadrature, specifying a relative error tolerance and maximum iterations. ```rust use peroxide::fuga::*; fn main() { let f_integral = integrate(f, (0f64, 1f64), G7K15R(1e-4, 20)); f_integral.print(); } fn f(x: f64) -> f64 { x.powi(2) } ``` -------------------------------- ### ODE Solvers with BasicODESolver Source: https://context7.com/axect/peroxide/llms.txt Demonstrates solving Ordinary Differential Equations (ODEs) using the `BasicODESolver`. The example uses the Lorenz attractor and the `RKF45` integrator, showing how to define an `ODEProblem` and configure the solver. ```rust use peroxide::fuga::*; fn main() -> Result<(), Box> { // Lorenz attractor: 3-component system let initial_conditions = vec![10f64, 1f64, 1f64]; // RKF45: (tol, safety_factor, min_step, max_step, max_step_iter) let rkf45 = RKF45::new(1e-4, 0.9, 1e-6, 1e-2, 100); let solver = BasicODESolver::new(rkf45); let (t_vec, y_vec) = solver.solve( &Lorenz, (0f64, 100f64), // time span 1e-2, // initial step size &initial_conditions, )?; let y_mat = py_matrix(y_vec); println!("Steps taken: {}", t_vec.len()); println!("Final state: {:?}", y_mat.row(y_mat.nrow() - 1)); // User-defined constraint violation stops integration early Ok(()) } struct Lorenz; impl ODEProblem for Lorenz { fn rhs(&self, _t: f64, y: &[f64], dy: &mut [f64]) -> anyhow::Result<()> { dy[0] = 10f64 * (y[1] - y[0]); dy[1] = 28f64 * y[0] - y[1] - y[0] * y[2]; dy[2] = -8f64 / 3f64 * y[2] + y[0] * y[1]; Ok(()) } } ``` -------------------------------- ### Peroxide Installation with Features Source: https://context7.com/axect/peroxide/llms.txt Add Peroxide to your Cargo.toml file. Specify desired feature flags for extended functionality like BLAS optimization, plotting, and I/O. ```toml # Default (pure Rust, no external dependencies) [dependencies] peroxide = "0.41.0" # With optional features [dependencies] peroxide = { version = "0.41.0", features = ["O3", "plot", "nc", "csv", "parquet", "serde"] } ``` -------------------------------- ### Add Peroxide with Specific Features Source: https://github.com/axect/peroxide/blob/master/README.md Installs Peroxide with specified features enabled. Replace `` with a comma-separated list of desired features (e.g., "plot,O3"). ```bash cargo add peroxide --features "" ``` -------------------------------- ### Add Peroxide to Cargo Project Source: https://github.com/axect/peroxide/blob/master/README.md Basic installation of the Peroxide library using Cargo. This command adds the latest stable version of the peroxide crate to your project's dependencies. ```bash cargo add peroxide ``` -------------------------------- ### Usage of Custom Numeric Type Source: https://github.com/axect/peroxide/blob/master/peroxide-num/README.md Demonstrates how to use a custom numeric type, like `SimpleNumber`, after it has been implemented with the necessary traits. This example computes the sine of a `SimpleNumber` instance. ```rust let num = SimpleNumber(2.0); let result = num.sin(); // Compute the sine of 2.0 println!("{:?}", result); // Should display the sine of 2.0 ``` -------------------------------- ### Generate Gradient and Hessian with #[ad_function] Source: https://github.com/axect/peroxide/blob/master/peroxide-ad/README.md The `#[ad_function]` macro automatically generates `_grad` and `_hess` functions for a given function `f`. Use `f_grad` to get the gradient and `f_hess` for the Hessian. Ensure `peroxide::fuga::*` is imported. ```rust use peroxide::fuga::*; fn main() { f(2f64).print(); // x^3 = 8 f_grad(2f64).print(); // 3 * x^2 = 12 f_hess(2f64).print(); // 6 * x = 12 } #[ad_function] // generates f_grad, f_hess fn f(x: f64) -> f64 { x.powi(3) // x^3 } ``` -------------------------------- ### Matrix Construction and Operations in Peroxide Source: https://github.com/axect/peroxide/blob/master/README.md Demonstrates creating matrices using MATLAB-like and R-like syntax, initializing with zeros, performing matrix multiplication, and basic linear algebra operations like determinant and inverse. Requires the `peroxide` crate with appropriate features enabled. ```rust #[macro_use] extern crate peroxide; use peroxide::prelude::*; fn main() { // MATLAB like matrix constructor let a = ml_matrix("1 2;3 4"); // R like matrix constructor (default) let b = matrix(c!(1,2,3,4), 2, 2, Row); // Or use zeros let mut z = zeros(2, 2); z[(0,0)] = 1.0; z[(0,1)] = 2.0; z[(1,0)] = 3.0; z[(1,1)] = 4.0; // Simple but effective operations let c = a * b; // Matrix multiplication (BLAS integrated) // Easy to pretty print c.print(); // c[0] c[1] // r[0] 1 3 // r[1] 2 4 // Easy to do linear algebra c.det().print(); c.inv().print(); // and etc. } ``` -------------------------------- ### Peroxide Prelude and Fuga Usage Source: https://context7.com/axect/peroxide/llms.txt Import Peroxide's functionality. Use `prelude` for simple defaults or `fuga` for explicit algorithm selection. ```rust // Prelude: simple defaults (L2 norm, Frobenius norm, etc.) use peroxide::prelude::*; // Fuga: explicit algorithm selection use peroxide::fuga::*; ``` -------------------------------- ### Build with Native BLAS/LAPACK Features Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Use this command to build the project with native BLAS and LAPACK features enabled. This requires external BLAS/LAPACK libraries. ```sh cargo build --features native ``` -------------------------------- ### Build with Default Features (Pure Rust) Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Use this command to build the project with default features, which means no external BLAS or LAPACK libraries are used. This provides a pure Rust implementation. ```sh cargo build ``` -------------------------------- ### Solve Linear Systems with LU or WAZ Decomposition Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Demonstrates solving a linear system Ax = b using both LU and WAZ decomposition methods. Requires the `fuga` prelude. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::*; fn main() { let a = ml_matrix("1 2;3 4"); let b = c!(3, 7); a.solve(&b, LU).print(); // [1, 1] a.solve(&b, WAZ).print(); // [1, 1] } ``` -------------------------------- ### Run Tests with Features Source: https://github.com/axect/peroxide/blob/master/CONTRIBUTING.md Use this command to run tests, specifying any required features for the test suite. Ensure you replace `` with the actual features needed. ```bash cargo test --features ``` -------------------------------- ### Define Custom Numeric Type with Peroxide-num Source: https://github.com/axect/peroxide/blob/master/peroxide-num/README.md Example of defining a custom numeric type `SimpleNumber` that wraps an f64 and implements the `Numeric` trait from Peroxide-num. This allows it to be used with the crate's mathematical operations. Ensure all required traits like Add, Sub, Mul, Div, Neg, TrigOps, and ExpLogOps are also implemented for full functionality. ```rust #[derive(Debug, Clone, Copy, PartialOrd)] struct SimpleNumber(f64); impl PowOps for SimpleNumber { type Float = Self; fn powi(&self, n: i32) -> Self { SimpleNumber(self.0.powi(n)) } fn powf(&self, f: Self::Float) -> Self { SimpleNumber(self.0.powf(f.0)) } fn pow(&self, f: Self) -> Self { SimpleNumber(self.0.powf(f.0)) } fn sqrt(&self) -> Self { SimpleNumber(self.0.sqrt()) } } // Implement other required operations for SimpleNumber... // - Add, Sub, Mul, Div, Neg // - PowOps (implemented above) // - TrigOps // - ExpLogOps impl Numeric for SimpleNumber {} ``` -------------------------------- ### Numerical Integration with Peroxide Source: https://context7.com/axect/peroxide/llms.txt Shows how to compute definite integrals using various methods like Gauss-Legendre, Adaptive Gauss-Kronrod, and Newton-Cotes. Supports absolute and relative tolerance variants. ```rust use peroxide::fuga::*; fn main() { // Gauss-Legendre with 20 nodes let gl20 = integrate(|x| x.sin(), (0f64, std::f64::consts::PI), GaussLegendre(20)); println!("GL20: {:.10}", gl20); // ≈ 2.0000000000 // Adaptive Gauss-Kronrod G7K15 (tol=1e-10, max_iter=1000) let gk = integrate(|x| (-x.powi(2)).exp(), (0f64, 1f64), G7K15(1e-10, 1000)); println!("GK G7K15: {:.10}", gk); // ≈ 0.7468241328 // Newton-Cotes with n=10 nodes let nc = integrate(|x| x.powi(2), (0f64, 1f64), NewtonCotes(10)); println!("NC: {:.10}", nc); // ≈ 0.3333333333 // Relative-tolerance variant let gkr = integrate(|x| 1f64 / (1f64 + x.powi(2)), (0f64, 1f64), G15K31R(1e-8, 500)); println!("GK G15K31R: {:.10}", gkr); // ≈ PI/4 } ``` -------------------------------- ### Simulate Lorenz Attractor with Peroxide in Rust Source: https://github.com/axect/peroxide/blob/master/README.md Demonstrates simulating the Lorenz attractor using Peroxide's ODE solver and visualizing the results. Requires the 'plot' feature for visualization. The `?` operator is used for streamlined error handling. ```rust use peroxide::fuga::*; fn main() -> Result<(), Box> { let initial_conditions = vec![10f64, 1f64, 1f64]; let rkf45 = RKF45::new(1e-4, 0.9, 1e-6, 1e-2, 100); let basic_ode_solver = BasicODESolver::new(rkf45); let (_, y_vec) = basic_ode_solver.solve( &Lorenz, (0f64, 100f64), 1e-2, &initial_conditions, )?; let y_mat = py_matrix(y_vec); let y0 = y_mat.col(0); let y2 = y_mat.col(2); let mut plt = Plot2D::new(); plt .set_domain(y0) .insert_image(y2) .set_xlabel(r"$y_0$") .set_ylabel(r"$y_2$") .set_style(PlotStyle::Nature) .tight_layout() .set_dpi(600) .set_path("example_data/lorenz_rkf45.png") .savefig()?; Ok(()) } struct Lorenz; impl ODEProblem for Lorenz { fn rhs(&self, t: f64, y: &[f64], dy: &mut [f64]) -> anyhow::Result<()> { dy[0] = 10f64 * (y[1] - y[0]); dy[1] = 28f64 * y[0] - y[1] - y[0] * y[2]; dy[2] = -8f64 / 3f64 * y[2] + y[0] * y[1]; Ok(()) } } ``` -------------------------------- ### Writing a Matrix to a Pickle File Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Shows how to write a `Matrix` to a pickle file using the `write_pickle` method. This requires the `serde` and `serde_pickle` crates. Ensure proper error handling for file operations. ```rust extern crate peroxide; use peroxide::*; use std::fs::File; use std::io::Write; fn main () { let mut w: Box; match File::create(path) { Ok(p) => writer = Box::new(p), Err(e) => (), } let a = ml_matrix("1 2;3 4"); a.write_pickle(&mut w).expect("Can't write pickle file"); } ``` -------------------------------- ### Eigenvalue Decomposition using Jacobi Method Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Demonstrates how to compute eigenvalues and eigenvectors of a matrix using the Jacobi method. Requires the `peroxide` crate and its `fuga` module. ```rust extern crate peroxide; use peroxide::fuga::*; fn main() { let a = MATLAB::new("1 2; 2 3"); let eigen = eigen(&a, Jacobi); let (eig_val, eig_vec) = eigen.extract(); eig_val.print(); eig_vec.print(); } ``` -------------------------------- ### Root Finding with Peroxide Macros Source: https://context7.com/axect/peroxide/llms.txt Demonstrates the high-level macro API for various root-finding algorithms. Ensure the function `f` is annotated with `#[ad_function]` for the `newton!` macro. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::*; use anyhow::Result; // #[ad_function] is required for newton! macro (auto-differentiates f) #[ad_function] fn f(x: f64) -> f64 { (x - 1f64).powi(3) } fn main() -> Result<()> { // High-level macro API let root_bisect = bisection!(f, (0.0, 2.0), 100, 1e-6)?; let root_newton = newton!(f, 0.0, 100, 1e-6)?; let root_secant = secant!(f, (0.0, 2.0), 100, 1e-6)?; let root_fp = false_position!(f, (0.0, 2.0), 100, 1e-6)?; println!("bisect={:.8}, newton={:.8}", root_bisect, root_newton); assert!(f(root_bisect).abs() < 1e-6); assert!(f(root_newton).abs() < 1e-6); // Low-level trait API with explicit struct let problem = Cubic; let bisect = BisectionMethod { max_iter: 100, tol: 1e-6 }; let root = bisect.find(&problem)?; println!("Cubic root: {:?}", root); Ok(()) } struct Cubic; impl RootFindingProblem<1, 1, (f64, f64)> for Cubic { fn function(&self, x: [f64; 1]) -> Result<[f64; 1]> { Ok([(x[0] - 1f64).powi(3)]) } fn initial_guess(&self) -> (f64, f64) { (0.0, 2.0) } } ``` -------------------------------- ### Matrix Construction in Peroxide Source: https://context7.com/axect/peroxide/llms.txt Construct matrices using R-style `matrix()`, MATLAB-style `ml_matrix()`, Python-style `py_matrix()`, or the `matrix!` macro. Includes utility constructors for zeros, identity, and random matrices. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::*; fn main() { // R style: data, nrow, ncol, fill order (Row or Col) let a = matrix(c!(1,2,3,4), 2, 2, Row); // c[0] c[1] // r[0] 1 2 // r[1] 3 4 // MATLAB style let b = ml_matrix("1 2; 3 4"); // Python style (Vec>) let c = py_matrix(vec![vec![1, 2], vec![3, 4]]); // Range macro: matrix!(start;end;step, nrow, ncol, shape) let d = matrix!(1;4;1, 2, 2, Row); // Useful constructors let z = zeros(2, 2); // all-zero matrix let id = eye(3); // 3×3 identity let r = rand(2, 2); // random uniform matrix a.print(); b.print(); } ``` -------------------------------- ### Matrix Operations with Peroxide Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Demonstrates matrix addition, multiplication, and subtraction using overloaded operators for `&Matrix` in Peroxide. Ensure the `peroxide` crate is added as a dependency. ```rust extern crate peroxide; use peroxide::fuga::*; fn main() { let a = ml_matrix("1 2;3 4"); (&a + &a).print(); (&a * &a).print(); (&a - &a).print(); } ``` -------------------------------- ### Spline Interpolation with Peroxide Source: https://context7.com/axect/peroxide/llms.txt Illustrates spline interpolation using CubicSpline, CubicHermiteSpline (with Akima or Quadratic slope estimation), and BSpline. Includes evaluating splines and inspecting underlying polynomials. ```rust use peroxide::fuga::*; use std::error::Error; fn main() -> Result<(), Box> { let x = seq(0, 10, 1); // [0, 1, ..., 10] let y = x.fmap(|t| t.sin()); let cs = CubicSpline::from_nodes(&x, &y)?; let cs_akima = CubicHermiteSpline::from_nodes(&x, &y, Akima)?; let cs_quad = CubicHermiteSpline::from_nodes(&x, &y, Quadratic)?; // Inspect local polynomial on [0,1] cs.polynomial_at(0f64).print(); // e.g. -0.1523x^3 + 0.9937x // Evaluate over a dense grid let new_x = seq(4, 6, 0.1); let y_cs = cs.eval_vec(&new_x); let y_akima = cs_akima.eval_vec(&new_x); // Build a DataFrame with the results let mut df = DataFrame::new(vec![]); df.push("x", Series::new(new_x)); df.push("y_cs", Series::new(y_cs)); df.push("y_akima", Series::new(y_akima)); df.print(); // B-Spline: degree, knots, 2D control points let degree = 3; let knots = seq(0, 1, 0.25); let ctrl = vec![vec![0.0,0.0], vec![1.0,2.0], vec![2.0,-1.0], vec![3.0,1.0]]; let bspline = BSpline::clamped(degree, knots, ctrl)?; let (bx, by): (Vec, Vec) = bspline.eval_vec(&seq(0,1,0.01)).into_iter().unzip(); println!("B-Spline: {} points evaluated", bx.len()); Ok(()) } ``` -------------------------------- ### Probability Distributions in Peroxide Source: https://context7.com/axect/peroxide/llms.txt Demonstrates the usage of various probability distributions like Normal, Beta, Gamma, and Bernoulli. Includes sampling, PDF calculation, and statistical properties. For reproducible sampling, a seeded RNG is used. ```rust use peroxide::fuga::*; fn main() { // Normal(mean, std) let norm = Normal(0f64, 1f64); let samples = norm.sample(1000); norm.pdf(0f64).print(); // 0.3989... (peak of standard normal) norm.mean().print(); // 0.0 norm.var().print(); // 1.0 // Beta(alpha, beta) let beta = Beta(2.0, 5.0); beta.sample(100).print(); beta.pdf(0.3).print(); // ≈ 1.852... beta.mean().print(); // 2/(2+5) ≈ 0.2857 // Gamma(shape, scale) let gamma = Gamma(2.0, 1.0); gamma.sample(100).print(); gamma.mean().print(); // shape * scale = 2.0 // Reproducible sampling with a seeded RNG let mut rng = smallrng_from_seed(42); let bern = Bernoulli(0.3); let rep = bern.sample_with_rng(&mut rng, 20); println!("{:?}", rep); } ``` -------------------------------- ### Simple Vector Norm Calculation with Prelude Source: https://github.com/axect/peroxide/blob/master/README.md Demonstrates the straightforward usage of the `norm()` method for calculating the L2 norm of a vector using the `prelude` module. This is the default vector norm. ```rust #[macro_use] extern crate peroxide; use peroxide::prelude::*; fn main() { let a = c!(1, 2, 3); let l2 = a.norm(); // L2 is default vector norm assert_eq!(l2, 14f64.sqrt()); } ``` -------------------------------- ### Root Finding Macros Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Generic and stable root finding macros, excluding the Newton method. ```APIDOC ## Generic Root Finding Macros ### Description Provides generic and stable macros for root finding algorithms, with the exception of the Newton method. ``` -------------------------------- ### Utility Range Functions Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Introduction of utility functions for generating and zipping ranges. ```rust util::useful::gen_range ``` ```rust util::useful::zip_range ``` -------------------------------- ### Implement LogNormal distribution and fix Gamma sampling Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Introduces the LogNormal distribution with parameters mu and sigma. Also includes a fix for the sampling method of the Gamma distribution. ```rust Implement `LogNormal` distribution ``` ```rust LogNormal(mu: f64, sigma: f64) ``` ```rust Fix sampling method for `Gamma` ``` -------------------------------- ### Secant Method Root Finding Macro Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Use the `secant!` macro for root finding with the secant method. Requires an initial interval `(a,b)`. ```rust secant!(f, (a,b), max_iter, tol) ``` -------------------------------- ### Bisection Method Root Finding Macro Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Use the `bisection!` macro for root finding with the bisection method. Requires an initial interval `(a,b)`. ```rust bisection!(f, (a,b), max_iter, tol) ``` -------------------------------- ### LambertW Function Wrapper and Usage Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Defines accuracy modes and functions for Lambert W0 and W-1, and shows how to use the default precise version in the prelude. ```rust pub enum LambertWAccuracyMode { Simple, // Faster, 24 bits of accuracy Precise, // Slower, 50 bits of accuracy } pub fn lambert_w0(z: f64, mode: LambertWAccuracyMode) -> f64; pub fn lambert_wm1(z: f64, mode: LambertWAccuracyMode) -> f64; ``` ```rust use peroxide::prelude::*; fn main() { lambert_w0(1.0).print(); // Same as fuga::lambert_w0(1.0, LambertWAccuracyMode::Simple) } ``` -------------------------------- ### DataFrame I/O Operations (CSV, NetCDF, Parquet) Source: https://context7.com/axect/peroxide/llms.txt Shows how to read and write DataFrames to CSV, NetCDF, and Parquet file formats. Requires enabling specific features (e.g., `csv`, `nc`, `parquet`) and potentially external libraries for NetCDF. ```rust use peroxide::fuga::*; fn main() -> anyhow::Result<()> { let mut df = DataFrame::new(vec![]); df.push("x", Series::new(vec![1.0f64, 2.0, 3.0])); df.push("y", Series::new(vec![1.0f64, 4.0, 9.0])); // CSV (requires `csv` feature) #[cfg(feature = "csv")] { df.write_csv("data.csv")?; let df2 = DataFrame::read_csv("data.csv", ',')?; df2.print(); } // NetCDF (requires `nc` feature + libnetcdf) #[cfg(feature = "nc")] { df.write_nc("data.nc")?; let df3 = DataFrame::read_nc("data.nc")?; let x: Vec = df3["x"].to_vec(); println!("{:?}", x); } // Parquet (requires `parquet` feature) #[cfg(feature = "parquet")] { df.write_parquet("data.parquet", CompressionOptions::Snappy)?; let df4 = DataFrame::read_parquet("data.parquet")?; df4.print(); } Ok(()) } ``` -------------------------------- ### DataFrame and Series Operations in Peroxide Source: https://context7.com/axect/peroxide/llms.txt Illustrates building, manipulating, and analyzing DataFrames and Series. Covers column operations, filtering, descriptive statistics, and Series-specific methods. Requires `anyhow::Result` for error handling. ```rust extern crate peroxide; use peroxide::fuga::*; fn main() -> anyhow::Result<()> { // Build DataFrame column by column let mut df = DataFrame::new(vec![]); df.push("id", Series::new(vec![1u32, 2, 3, 4, 5])); df.push("score", Series::new(vec![88.5, 91.0, 75.3, 95.8, 82.1])); df.push("pass", Series::new(vec![true, true, false, true, true])); df.print(); // Shape info println!("rows={}, cols={}", df.nrow(), df.ncol()); println!("dtypes={:?}", df.dtypes()); // Row operations df.head(3).print(); df.tail(2).print(); df.slice(1, 3).print(); // rows 1,2,3 // Column operations df.select(&["id", "score"]).print(); let mut df2 = df.clone(); df2.rename("score", "grade"); println!("{:?}", df2.column_names()); // Filtering let high = df.filter_by("score", |s: f64| s > 85.0)?; high.print(); // Descriptive statistics (numeric columns) df.describe().print(); df.mean().print(); // Series statistics let scores: &Series = &df["score"]; println!("mean={:.2}", scores.mean()?); println!("sd={:.2}", scores.sd()?); println!("max={:?}", scores.max()?); Ok(()) } ``` -------------------------------- ### Non-Linear Regression with Optimizer Source: https://context7.com/axect/peroxide/llms.txt Demonstrates fitting a parametric model to data using Peroxide's Optimizer. Supports gradient descent and Levenberg-Marquardt methods. The model function must handle `AD` types for automatic differentiation. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::*; fn main() { let normal = Normal(0f64, 0.1f64); let noise2 = Normal(0f64, 100f64); let mut x = seq(0., 99., 1f64); x = zip_with(|a, b| (a + b).abs(), &x, &normal.sample(x.len())); let mut y = x.fmap(|t| t.powi(2)); y = zip_with(|a, b| a + b, &y, &noise2.sample(y.len())); let data = hstack!(x.clone(), y.clone()); let mut opt = Optimizer::new(data, quad); let params = opt .set_init_param(vec![1f64]) // initial exponent = 1 .set_max_iter(50) .set_method(LevenbergMarquardt) .set_lambda_init(1e-3) .set_lambda_max(1e3) .optimize(); params.print(); // should converge close to [2.0] opt.get_error().print(); // RMSE of the fit } fn quad(x: &Vec, n: Vec) -> Option> { Some(x.iter().map(|&xi| AD::from(xi).powf(n[0])).collect()) } ``` -------------------------------- ### R-like and MATLAB-like Macros for Data Structures Source: https://context7.com/axect/peroxide/llms.txt This snippet showcases Peroxide's macros that mimic R and MATLAB syntax for creating and manipulating data structures. Use `c!` for vector literals, `seq!` for sequences, and `hstack!` / `vstack!` for matrix binding. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::* fn main() -> Result<(), Box> { // c!: create Vec let a = c!(1, 2, 3, 4); let b = c!(5, 6, 7, 8); let ab = c![a; b]; // concatenate: [1..8] println!("{:?}", ab); // seq!(start, end, step) let s = seq!(0, 1, 0.25); assert_eq!(s, c!(0, 0.25, 0.5, 0.75, 1.0)); // hstack! / vstack! for matrices let m1 = ml_matrix("1 2; 3 4"); let m2 = ml_matrix("5 6; 7 8"); let h = hstack!(m1.col(0), m1.col(1), m2.col(0)); // 2×3 matrix h.print(); Ok(()) } ``` -------------------------------- ### Statistical Calculations with Peroxide Source: https://context7.com/axect/peroxide/llms.txt Demonstrates the `Statistics` trait for calculating mean, variance, standard deviation, covariance, and correlation for vectors and matrices. Also shows standalone functions for vector covariance and correlation. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::*; fn main() { let v = c!(1, 2, 3, 4, 5); v.mean().print(); // 3.0 v.var().print(); // 2.5 v.sd().print(); // 1.5811... let v2 = c!(5, 4, 3, 2, 1); cov(&v, &v2).print(); // -2.5 cor(&v, &v2).print(); // -1.0 // Matrix column-wise statistics let m = matrix(c!(1,2,3,3,2,1), 3, 2, Col); m.mean().print(); // [2, 2] m.cov().print(); // 2×2 covariance matrix m.cor().print(); // 2×2 correlation matrix } ``` -------------------------------- ### Newton's Method Root Finding Macro Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Use the `newton!` macro for root finding with Newton's method. Requires the `#[ad_function]` attribute on the function being solved. ```rust newton!(f, x0, max_iter, tol) ``` -------------------------------- ### False Position Method Root Finding Macro Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Use the `false_position!` macro for root finding with the false position method. Requires an initial interval `(a,b)`. ```rust false_position!(f, (a,b), max_iter, tol) ``` -------------------------------- ### Calculus Integration Method Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Addition of an `integrate` method to the `Calculus` module for numerical integration. ```rust structure::poly::Calculus::integrate ``` -------------------------------- ### Matrix Column Stack Utility Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Create a new matrix by stacking vectors column-wise. Returns a `Result` to handle potential concatenation errors. ```rust column_stack(&[Vec]) -> Result ``` -------------------------------- ### Add Peroxide Dependency to Cargo.toml Source: https://github.com/axect/peroxide/blob/master/peroxide-ad/README.md To use the Peroxide-ad toolbox, add the peroxide crate with version '0.30' to your project's Cargo.toml file under [dependencies]. ```toml [dependencies] peroxide = "0.30" ``` -------------------------------- ### Fix adaptive step size control exponent Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Corrects the adaptive step size control exponent for embedded Runge-Kutta methods. The `order()` method on `ButcherTableau` now provides the correct exponent, e.g., 1/3 for BS23, 1/5 for RKF45/DP45/TSIT45, and 1/8 for RKF78. ```rust Add `order()` method to `ButcherTableau` trait for correct exponent `1/(p+1)` ``` ```rust BS23: `1/3`, RKF45/DP45/TSIT45: `1/5`, RKF78: `1/8` ``` -------------------------------- ### Explicit Vector Norm Calculation with Fuga Source: https://github.com/axect/peroxide/blob/master/README.md Shows how to explicitly specify different vector norms (L1, L2, L-infinity) using the `norm()` method from the `fuga` module. This requires specifying the desired norm type. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::*; fn main() { let a = c!(1, 2, 3); let l1 = a.norm(Norm::L1); let l2 = a.norm(Norm::L2); let l_inf = a.norm(Norm::LInf); assert_eq!(l1, 6f64); assert_eq!(l2, 14f64.sqrt()); assert_eq!(l_inf, 3f64); } ``` -------------------------------- ### Using Special Mathematical Functions Source: https://context7.com/axect/peroxide/llms.txt This snippet demonstrates the usage of various special mathematical functions provided by the `special` module, including gamma, log-gamma, incomplete gamma, error functions, and Gaussian PDF. These functions are implemented in pure Rust. ```rust use peroxide::fuga::* fn main() { // Gamma and log-gamma printlnביר{:.6}", gamma(5.0)); // 24.0 (= 4!) printlnביר{:.6}", ln_gamma(100.0)); // ln(99!) // Regularized incomplete gamma P(a, x) and its inverse printlnביר{:.6}", inc_gamma(2.0, 1.0)); // ≈ 0.2642 printlnביר{:.6}", inv_inc_gamma(2.0, 0.2642)); // ≈ 1.0 // Error function and inverse printlnביר{:.6}", erf(1.0)); // ≈ 0.8427 printlnביר{:.6}", erfc(1.0)); // ≈ 0.1573 printlnביר{:.6}", inv_erf(0.8427)); // ≈ 1.0 // Gaussian PDF printlnביר{:.6}", gaussian(0.0, 0.0, 1.0)); // 0.3989... } ``` -------------------------------- ### Matrix Row Stack Utility Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Create a new matrix by stacking vectors row-wise. Returns a `Result` to handle potential concatenation errors. ```rust row_stack(&[Vec]) -> Result ``` -------------------------------- ### DataFrame Parquet Read/Write Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Implement Parquet support for DataFrames, enabling reading from and writing to Parquet files. ```rust fn write_parquet(&self, path: &str) -> Result<(), Box> ``` ```rust fn read_parquet(path: &str) -> Result> ``` -------------------------------- ### ODE Solver - RKF78 Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Implementation of the Runge-Kutta-Fehlberg 7(8) method for Ordinary Differential Equation (ODE) solving. ```APIDOC ## ODESolver::RKF78 ### Description Provides an implementation of the RKF78 method for solving ODEs. ### Method `RKF78` for `ODESolver` ``` -------------------------------- ### Rkyv Serialization Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Implementation of `rkyv` traits for serialization and deserialization of core data structures. ```APIDOC ## Rkyv Serialization ### Description Enables efficient zero-copy deserialization for `Matrix`, `Polynomial`, `Spline`, and `ODE` types using the `rkyv` crate. ### Traits Implemented - `rkyv::Archive` - `rkyv::Serialize` - `rkyv::Deserialize` ``` -------------------------------- ### Render Math in Document Body with KaTeX Source: https://github.com/axect/peroxide/blob/master/katex-header.html Include this script in your HTML to automatically render mathematical expressions using KaTeX. It configures delimiters for inline and display math. ```javascript document.addEventListener("DOMContentLoaded", function() { renderMathInElement(document.body, { delimiters: [ {left: "$$", right: "$$", display: true}, {left: "\\(", right: "\\)", display: false}, {left: "$", right: "$", display: false}, {left: "\\\[", right: "\\\]", display: true} ] }); }); ``` -------------------------------- ### Vector Functional Programming with FPVector Source: https://context7.com/axect/peroxide/llms.txt Demonstrates common functional programming operations on `Vec` using the `FPVector` trait, such as `fmap`, `reduce`, `zip_with`, and `filter`. The `parallel` feature offers a parallel variant. ```rust #[macro_use] extern crate peroxide; use peroxide::fuga::*; fn main() { let x = c!(1, 2, 3, 4, 5); // Element-wise map let y = x.fmap(|t| t.powi(2)); y.print(); // [1, 4, 9, 16, 25] // Reduce let s = x.reduce(0.0, |a, b| a + b); assert_eq!(s, 15.0); // zip_with: element-wise binary op over two vecs let z = c!(10, 20, 30, 40, 50); let w = x.zip_with(|a, b| a + b, &z); w.print(); // [11, 22, 33, 44, 55] // filter let evens = x.filter(|t| t % 2.0 == 0.0); evens.print(); // [2, 4] // linspace (function, not macro) let domain = linspace(0.0, 1.0, 5); domain.print(); // [0.0, 0.25, 0.5, 0.75, 1.0] // seq macro let s2 = seq!(0, 4, 1); s2.print(); // [0, 1, 2, 3, 4] } ``` -------------------------------- ### Fix adaptive step size control for embedded Runge-Kutta methods Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Corrects a bug in the adaptive step size control mechanism for all embedded Runge-Kutta methods. This ensures more accurate and stable time-stepping in simulations. ```rust Fixed a bug in the adaptive step size control for all embedded Runge-Kutta methods. ``` -------------------------------- ### Broyden Method for GL4 Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Implementation of the Broyden method for the GL4 solver. ```APIDOC ## GL4::Broyden ### Description Implements the Broyden method for the GL4 solver. ### Method `Broyden` for `GL4` ``` -------------------------------- ### Low-level and High-level Matrix Operations in Rust Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Demonstrates mutable column access and mapping operations on matrices. Requires unsafe blocks for direct pointer manipulation. Use `col_mut_map` for functional-style updates. ```rust fn main() { // =================================== // Low Level // =================================== let mut a = ml_matrix("1 2; 3 4"); a.print(); // c[0] c[1] // r[0] 1 2 // r[1] 3 4 unsafe { let mut p: Vec<*mut f64> = a.col_mut(1); // Mutable second column for i in 0 .. p.len() { *p[i] = i as f64; } } a.print(); // c[0] c[1] // r[0] 1 0 // r[1] 3 1 // =================================== // High Level // =================================== let mut b = ml_matrix("1 2 3; 4 5 6"); b.col_mut_map(|x| x.normalize()); b.print(); // c[0] c[1] c[2] // r[0] 0.2425 0.3714 0.4472 // r[1] 0.9701 0.9285 0.8944 } ``` -------------------------------- ### Lambert W Function Source: https://github.com/axect/peroxide/blob/master/RELEASES.md Wrapper functions for the Lambert W function, offering different accuracy modes and a default precise implementation. ```APIDOC ## Lambert W Function Wrapper ### Description Provides flexible wrappers for the `lambert_w` crate, allowing selection of accuracy modes and offering a default precise implementation for convenience. ### Accuracy Modes - `LambertWAccuracyMode::Simple`: Faster, 24 bits of accuracy. - `LambertWAccuracyMode::Precise`: Slower, 50 bits of accuracy. ### Functions - `lambert_w0(z: f64, mode: LambertWAccuracyMode) -> f64`: Computes the principal branch (W0) of the Lambert W function. - `lambert_wm1(z: f64, mode: LambertWAccuracyMode) -> f64`: Computes the secondary branch (W-1) of the Lambert W function. ### Default Usage ```rust use peroxide::prelude::*; fn main() { lambert_w0(1.0).print(); // Uses LambertWAccuracyMode::Simple by default } ``` ```