#process #distribution #motion #simulation #traits #rayon #computing

diffusionx

A Rust crate for random number/stochastic process simulation with high performance

19 releases

Uses new Rust 2024

new 0.3.7 May 6, 2025
0.3.6 May 6, 2025
0.3.5 Apr 29, 2025
0.3.1 Mar 31, 2025
0.1.4 Feb 24, 2025

#187 in Algorithms

Download history 350/week @ 2025-02-17 224/week @ 2025-02-24 420/week @ 2025-03-03 182/week @ 2025-03-10 438/week @ 2025-03-17 60/week @ 2025-03-24 128/week @ 2025-03-31 128/week @ 2025-04-07 126/week @ 2025-04-14 120/week @ 2025-04-21 120/week @ 2025-04-28

498 downloads per month

MIT/Apache

345KB
6K SLoC

DiffusionX

English | 简体中文

DiffusionX is a multi-threaded high-performance Rust library for random number generation and stochastic process simulation, designed for scientific computing and quantitative finance applications.

docs.rs crates.io License: MIT/Apache-2.0

Features

  • High Performance: Optimized for computational efficiency with multi-threading support via rayon
  • Comprehensive: Extensive collection of random distributions and stochastic processes for scientific computing
  • Extensible: Trait-based architecture enabling easy extension with custom processes and distributions
  • Well-documented: Detailed API documentation with mathematical background and usage examples
  • Type-safe: Leverages Rust's type system for compile-time safety and correctness
  • Zero-cost abstractions: Efficient abstractions with minimal runtime overhead

Visualization

DiffusionX provides built-in visualization capabilities using the plotters crate:

  • Process Trajectories: Easily visualize continuous process trajectories
  • Customizable Plots: Configure plot appearance including colors, dimensions, and line styles
  • Multiple Backends: Support for both BitMap and SVG output formats
  • Simple API: Intuitive trait-based API for visualizing simulation results

Implemented

Random Number Generation

  • Normal distribution - Gaussian random variables with specified mean and variance
  • Uniform distribution - Uniform random variables in specified ranges
  • Exponential distribution - Exponential waiting times with specified rate
  • Poisson distribution - Discrete count distribution with specified mean
  • Alpha-stable distribution - Heavy-tailed distributions with specified stability, skewness, scale, and location

Stochastic Processes

  • Brownian motion - Standard and generalized with drift and diffusion
  • Alpha-stable Lévy process - Non-Gaussian processes with heavy tails
  • Cauchy process - Lévy process with stable index 1
  • Subordinator - Time-changed processes
  • Inverse subordinator - Processes for modeling waiting times
  • Poisson process - Counting processes with independent increments
  • Fractional Brownian motion - Long-range dependent processes
  • Continuous time random walk - Jump processes with random waiting times
  • Ornstein-Uhlenbeck process - Mean-reverting processes
  • Langevin equation - Physical models with friction and noise
  • Generalized Langevin equation - Extended models with memory effects
  • Subordinated Langevin equation - Time-changed Langevin processes
  • Lévy walk - Superdiffusive processes with coupled jump lengths and waiting times
  • Birth-death process - Discrete-state processes with birth and death rates
  • Random walk - Discrete-time random walk
  • Brownian bridge - Brownian motion conditioned to hit origin at the end
  • Brownian excursion - Brownian motion conditioned to be positive and to take the value 0 at time 1
  • Brownian meander
  • Gamma process - Non-negative process with independent and stationary increments

Installation

Add the following to your Cargo.toml:

[dependencies]
diffusionx = "*"  # Replace with the latest version

Or use the following command to install:

cargo add diffusionx

Usage

Random Number Generation

use diffusionx::random::{normal, uniform, stable};

// Generate a normal random number with mean 0.0 and std 1.0
let normal_sample = normal::rand(0.0, 1.0)?;
// Generate 1000 standard normal random numbers
let std_normal_samples = normal::standard_rands(1000);

// Generate a uniform random number in range [0, 10)
let uniform_sample = uniform::range_rand(0..10)?;
// Generate 1000 uniform random numbers in range [0, 1)
let std_uniform_samples = uniform::standard_rands(1000);

// Generate 1000 standard stable random numbers
let stable_samples = stable::standard_rands(1.5, 0.5, 1000)?;

Stochastic Process Simulation

use diffusionx::simulation::{prelude::*, continuous::Bm};

// Create standard Brownian motion object
let bm = Bm::default();
// Create trajectory with duration 1.0
let traj = bm.duration(1.0)?;
// Simulate Brownian motion trajectory with time step 0.01
let (times, positions) = traj.simulate(0.01)?;

// Calculate first-order raw moment with 1000 particles and time step 0.01
let mean = traj.raw_moment(1, 1000, 0.01)?;
// Calculate second-order central moment with 1000 particles and time step 0.01
let msd = traj.central_moment(2, 1000, 0.01)?;

// Calculate first passage time of Brownian motion with boundaries at -1.0 and 1.0
let fpt = bm.fpt(0.01, (-1.0, 1.0), 1000)?;

Visualization Example

use diffusionx::{
    simulation::{continuous::Bm, prelude::*},
};

// Create Brownian motion trajectory
let bm = Bm::default();
let traj = bm.duration(10.0)?;

// Configure and create visualization
let config = PlotConfigBuilder::default()
.time_step(0.01)
.output_path("brownian_motion.png")
.caption("Brownian Motion Trajectory")
.x_label("t")
.y_label("B")
.legend("bm")
.size((800, 600))
.backend(PlotterBackend::BitMap)
.build()?;

// Generate plot
traj.plot(&config)?;

Architecture and Extensibility

DiffusionX is designed with a trait-based system for high extensibility and performance:

Core Traits

  • ContinuousProcess: Base trait for continuous stochastic processes
  • PointProcess: Base trait for point processes
  • DiscreteProcess: Base trait for discrete stochastic processes
  • Moment: Trait for statistical moments calculation, including raw and central moments
  • Visualize: Trait for plotting process trajectories

Functional Distribution Simulation

DiffusionX provides powerful functional distribution simulation for stochastic processes:

  1. First Passage Time (FPT): Calculate when a process first reaches a specified boundary

    // For a Brownian motion process
    let bm = Bm::default();
    // Calculate first passage time with time step 0.01,
    // boundaries at -1.0 and 1.0, and 1000 particles
    let fpt = bm.fpt(0.01, (-1.0, 1.0), 1000)?;
    
  2. Occupation Time: Measure time spent by a process in a specified region

    // For a Brownian motion process
    let bm = Bm::default();
    let traj = bm.duration(10.0)?;
    // Calculate time spent in region [0.0, 2.0] with time step 0.01
    let occupation = traj.occupation_time(0.01, (0.0, 2.0))?;
    

Extending with Custom Processes

  1. Adding a New Continuous Process:

    #[derive(Clone)]
    struct MyProcess {
        // Your parameters
        // Should be `Send + Sync` for parallel computation
    }
    
    impl ContinuousProcess for MyProcess {
        fn simulate(&self, duration: impl Into<f64>, time_step: f64) -> XResult<(Vec<f64>, Vec<f64>)> {
            // Implement your simulation logic
            todo!()
        }
    }
    
  2. Automatic Feature Acquisition:

    • Implementing ContinuousProcess trait automatically provides ContinuousTrajectoryTrait functionality
    • ContinuousTrajectory provides access to the Moment trait functionality
    • Built-in support for moment statistics calculation

Example:

let myprocess = MyProcess::default();
let traj = myprocess.duration(10)?;
// Calculate mean with 1000 particles and time step 0.01
let mean = traj.raw_moment(1, 1000, 0.01)?;
  1. Parallel Computing Support:

    • Automatic parallel computation for moment calculations using Rayon
    • Default parallel strategy for statistical calculations
    • Configurable parallelism for optimal performance
  2. Visualization Support:

    • Easy trajectory visualization with minimal code
    • Highly customizable plot configuration

Example:

// Visualize a Brownian motion trajectory
use diffusionx::visualize::{PlotConfigBuilder, Visualize};

let bm = Bm::default().duration(10)?;
let config = PlotConfigBuilder::default()
.title("Brownian Motion")
.output_path("brownian_motion.png")
.build()?;

bm.plot(&config)?; // Generates a plot with the specified configuration

Benchmark

The related content can be found in the Benchmark section of py-diffusionx.

License

This project is dual-licensed under:

You can choose to use either license.

Dependencies

~5.5–8.5MB
~156K SLoC