Merge pull request #68 from Magnus167/update-docs

Enhance documentation with usage examples
This commit is contained in:
Palash Tyagi 2025-08-03 17:45:29 +01:00 committed by GitHub
commit 7d0978e5fb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 354 additions and 2 deletions

View File

@ -152,7 +152,7 @@ let zipped_matrix = a.zip(&b, |x, y| x + y);
assert_eq!(zipped_matrix.data(), &[6.0, 8.0, 10.0, 12.0]); assert_eq!(zipped_matrix.data(), &[6.0, 8.0, 10.0, 12.0]);
``` ```
### More examples ## More examples
See the [examples](./examples/) directory for some demonstrations of Rustframe's syntax and functionality. See the [examples](./examples/) directory for some demonstrations of Rustframe's syntax and functionality.
@ -191,7 +191,7 @@ cargo run --example
Each demo runs a couple of mini-scenarios showcasing the APIs. Each demo runs a couple of mini-scenarios showcasing the APIs.
### Running benchmarks ## Running benchmarks
To run the benchmarks, use: To run the benchmarks, use:

View File

@ -1,3 +1,16 @@
//! Algorithms and statistical utilities built on top of the core matrices.
//!
//! This module groups together machinelearning models and statistical helper
//! functions. For quick access to basic statistics see [`stats`](crate::compute::stats), while
//! [`models`](crate::compute::models) contains small learning algorithms.
//!
//! ```
//! use rustframe::compute::stats;
//! use rustframe::matrix::Matrix;
//!
//! let m = Matrix::from_vec(vec![1.0, 2.0, 3.0], 3, 1);
//! assert_eq!(stats::mean(&m), 2.0);
//! ```
pub mod models; pub mod models;
pub mod stats; pub mod stats;

View File

@ -1,3 +1,15 @@
//! Common activation functions used in neural networks.
//!
//! Functions operate element-wise on [`Matrix`] values.
//!
//! ```
//! use rustframe::compute::models::activations::sigmoid;
//! use rustframe::matrix::Matrix;
//!
//! let x = Matrix::from_vec(vec![0.0], 1, 1);
//! let y = sigmoid(&x);
//! assert!((y.get(0,0) - 0.5).abs() < 1e-6);
//! ```
use crate::matrix::{Matrix, SeriesOps}; use crate::matrix::{Matrix, SeriesOps};
pub fn sigmoid(x: &Matrix<f64>) -> Matrix<f64> { pub fn sigmoid(x: &Matrix<f64>) -> Matrix<f64> {

View File

@ -1,3 +1,30 @@
//! A minimal dense neural network implementation for educational purposes.
//!
//! Layers operate on [`Matrix`] values and support ReLU and Sigmoid
//! activations. This is not meant to be a performant deeplearning framework
//! but rather a small example of how the surrounding matrix utilities can be
//! composed.
//!
//! ```
//! use rustframe::compute::models::dense_nn::{ActivationKind, DenseNN, DenseNNConfig, InitializerKind, LossKind};
//! use rustframe::matrix::Matrix;
//!
//! // Tiny network with one input and one output neuron.
//! let config = DenseNNConfig {
//! input_size: 1,
//! hidden_layers: vec![],
//! output_size: 1,
//! activations: vec![ActivationKind::Relu],
//! initializer: InitializerKind::Uniform(0.5),
//! loss: LossKind::MSE,
//! learning_rate: 0.1,
//! epochs: 1,
//! };
//! let mut nn = DenseNN::new(config);
//! let x = Matrix::from_vec(vec![1.0, 2.0], 2, 1);
//! let y = Matrix::from_vec(vec![2.0, 3.0], 2, 1);
//! nn.train(&x, &y);
//! ```
use crate::compute::models::activations::{drelu, relu, sigmoid}; use crate::compute::models::activations::{drelu, relu, sigmoid};
use crate::matrix::{Matrix, SeriesOps}; use crate::matrix::{Matrix, SeriesOps};
use crate::random::prelude::*; use crate::random::prelude::*;

View File

@ -1,3 +1,16 @@
//! Gaussian Naive Bayes classifier for dense matrices.
//!
//! ```
//! use rustframe::compute::models::gaussian_nb::GaussianNB;
//! use rustframe::matrix::Matrix;
//!
//! let x = Matrix::from_vec(vec![1.0, 2.0, 1.0, 2.0], 2, 2); // two samples
//! let y = Matrix::from_vec(vec![0.0, 1.0], 2, 1);
//! let mut model = GaussianNB::new(1e-9, false);
//! model.fit(&x, &y);
//! let preds = model.predict(&x);
//! assert_eq!(preds.rows(), 2);
//! ```
use crate::matrix::Matrix; use crate::matrix::Matrix;
use std::collections::HashMap; use std::collections::HashMap;

View File

@ -1,3 +1,14 @@
//! Simple k-means clustering working on [`Matrix`] data.
//!
//! ```
//! use rustframe::compute::models::k_means::KMeans;
//! use rustframe::matrix::Matrix;
//!
//! let data = Matrix::from_vec(vec![1.0, 1.0, 5.0, 5.0], 2, 2);
//! let (model, labels) = KMeans::fit(&data, 2, 10, 1e-4);
//! assert_eq!(model.centroids.rows(), 2);
//! assert_eq!(labels.len(), 2);
//! ```
use crate::compute::stats::mean_vertical; use crate::compute::stats::mean_vertical;
use crate::matrix::Matrix; use crate::matrix::Matrix;
use crate::random::prelude::*; use crate::random::prelude::*;

View File

@ -1,3 +1,16 @@
//! Ordinary least squares linear regression.
//!
//! ```
//! use rustframe::compute::models::linreg::LinReg;
//! use rustframe::matrix::Matrix;
//!
//! let x = Matrix::from_vec(vec![1.0, 2.0, 3.0, 4.0], 4, 1);
//! let y = Matrix::from_vec(vec![2.0, 3.0, 4.0, 5.0], 4, 1);
//! let mut model = LinReg::new(1);
//! model.fit(&x, &y, 0.01, 100);
//! let preds = model.predict(&x);
//! assert_eq!(preds.rows(), 4);
//! ```
use crate::matrix::{Matrix, SeriesOps}; use crate::matrix::{Matrix, SeriesOps};
pub struct LinReg { pub struct LinReg {

View File

@ -1,3 +1,16 @@
//! Binary logistic regression classifier.
//!
//! ```
//! use rustframe::compute::models::logreg::LogReg;
//! use rustframe::matrix::Matrix;
//!
//! let x = Matrix::from_vec(vec![1.0, 2.0, 3.0, 4.0], 4, 1);
//! let y = Matrix::from_vec(vec![0.0, 0.0, 1.0, 1.0], 4, 1);
//! let mut model = LogReg::new(1);
//! model.fit(&x, &y, 0.1, 100);
//! let preds = model.predict(&x);
//! assert_eq!(preds[(0,0)], 0.0);
//! ```
use crate::compute::models::activations::sigmoid; use crate::compute::models::activations::sigmoid;
use crate::matrix::{Matrix, SeriesOps}; use crate::matrix::{Matrix, SeriesOps};

View File

@ -1,3 +1,19 @@
//! Lightweight machinelearning models built on matrices.
//!
//! Models are intentionally minimal and operate on the [`Matrix`](crate::matrix::Matrix) type for
//! inputs and parameters.
//!
//! ```
//! use rustframe::compute::models::linreg::LinReg;
//! use rustframe::matrix::Matrix;
//!
//! let x = Matrix::from_vec(vec![1.0, 2.0, 3.0, 4.0], 4, 1);
//! let y = Matrix::from_vec(vec![2.0, 3.0, 4.0, 5.0], 4, 1);
//! let mut model = LinReg::new(1);
//! model.fit(&x, &y, 0.01, 1000);
//! let preds = model.predict(&x);
//! assert_eq!(preds.rows(), 4);
//! ```
pub mod activations; pub mod activations;
pub mod dense_nn; pub mod dense_nn;
pub mod gaussian_nb; pub mod gaussian_nb;

View File

@ -1,3 +1,14 @@
//! Principal Component Analysis using covariance matrices.
//!
//! ```
//! use rustframe::compute::models::pca::PCA;
//! use rustframe::matrix::Matrix;
//!
//! let data = Matrix::from_rows_vec(vec![1.0, 1.0, 2.0, 2.0], 2, 2);
//! let pca = PCA::fit(&data, 1, 0);
//! let projected = pca.transform(&data);
//! assert_eq!(projected.cols(), 1);
//! ```
use crate::compute::stats::correlation::covariance_matrix; use crate::compute::stats::correlation::covariance_matrix;
use crate::compute::stats::descriptive::mean_vertical; use crate::compute::stats::descriptive::mean_vertical;
use crate::matrix::{Axis, Matrix, SeriesOps}; use crate::matrix::{Axis, Matrix, SeriesOps};

View File

@ -1,3 +1,16 @@
//! Covariance and correlation helpers.
//!
//! This module provides routines for measuring the relationship between
//! columns or rows of matrices.
//!
//! ```
//! use rustframe::compute::stats::correlation;
//! use rustframe::matrix::Matrix;
//!
//! let x = Matrix::from_vec(vec![1.0, 2.0, 3.0, 4.0], 2, 2);
//! let cov = correlation::covariance(&x, &x);
//! assert!((cov - 1.25).abs() < 1e-8);
//! ```
use crate::compute::stats::{mean, mean_horizontal, mean_vertical, stddev}; use crate::compute::stats::{mean, mean_horizontal, mean_vertical, stddev};
use crate::matrix::{Axis, Matrix, SeriesOps}; use crate::matrix::{Axis, Matrix, SeriesOps};

View File

@ -1,3 +1,15 @@
//! Descriptive statistics for matrices.
//!
//! Provides means, variances, medians and other aggregations computed either
//! across the whole matrix or along a specific axis.
//!
//! ```
//! use rustframe::compute::stats::descriptive;
//! use rustframe::matrix::Matrix;
//!
//! let m = Matrix::from_vec(vec![1.0, 2.0, 3.0, 4.0], 2, 2);
//! assert_eq!(descriptive::mean(&m), 2.5);
//! ```
use crate::matrix::{Axis, Matrix, SeriesOps}; use crate::matrix::{Axis, Matrix, SeriesOps};
pub fn mean(x: &Matrix<f64>) -> f64 { pub fn mean(x: &Matrix<f64>) -> f64 {

View File

@ -1,3 +1,16 @@
//! Probability distribution functions applied element-wise to matrices.
//!
//! Includes approximations for the normal, uniform and gamma distributions as
//! well as the error function.
//!
//! ```
//! use rustframe::compute::stats::distributions;
//! use rustframe::matrix::Matrix;
//!
//! let x = Matrix::from_vec(vec![0.0], 1, 1);
//! let pdf = distributions::normal_pdf(x.clone(), 0.0, 1.0);
//! assert!((pdf.get(0,0) - 0.3989).abs() < 1e-3);
//! ```
use crate::matrix::{Matrix, SeriesOps}; use crate::matrix::{Matrix, SeriesOps};
use std::f64::consts::PI; use std::f64::consts::PI;

View File

@ -1,3 +1,14 @@
//! Basic inferential statistics such as ttests and chisquare tests.
//!
//! ```
//! use rustframe::compute::stats::inferential;
//! use rustframe::matrix::Matrix;
//!
//! let a = Matrix::from_vec(vec![1.0, 2.0], 2, 1);
//! let b = Matrix::from_vec(vec![1.1, 1.9], 2, 1);
//! let (t, _p) = inferential::t_test(&a, &b);
//! assert!(t.abs() < 1.0);
//! ```
use crate::matrix::{Matrix, SeriesOps}; use crate::matrix::{Matrix, SeriesOps};
use crate::compute::stats::{gamma_cdf, mean, sample_variance}; use crate::compute::stats::{gamma_cdf, mean, sample_variance};

View File

@ -1,3 +1,16 @@
//! Statistical routines for matrices.
//!
//! Functions are grouped into submodules for descriptive statistics,
//! correlations, probability distributions and basic inferential tests.
//!
//! ```
//! use rustframe::compute::stats;
//! use rustframe::matrix::Matrix;
//!
//! let m = Matrix::from_vec(vec![1.0, 2.0, 3.0, 4.0], 2, 2);
//! let cov = stats::covariance(&m, &m);
//! assert!((cov - 1.25).abs() < 1e-8);
//! ```
pub mod correlation; pub mod correlation;
pub mod descriptive; pub mod descriptive;
pub mod distributions; pub mod distributions;

View File

@ -1,3 +1,19 @@
//! Core data-frame structures such as [`Frame`] and [`RowIndex`].
//!
//! The [`Frame`] type stores column-labelled data with an optional row index
//! and builds upon the [`crate::matrix::Matrix`] type.
//!
//! # Examples
//!
//! ```
//! use rustframe::frame::{Frame, RowIndex};
//! use rustframe::matrix::Matrix;
//!
//! let data = Matrix::from_cols(vec![vec![1, 2], vec![3, 4]]);
//! let frame = Frame::new(data, vec!["L", "R"], Some(RowIndex::Int(vec![10, 20])));
//! assert_eq!(frame.columns(), &["L", "R"]);
//! assert_eq!(frame.index(), &RowIndex::Int(vec![10, 20]));
//! ```
use crate::matrix::Matrix; use crate::matrix::Matrix;
use chrono::NaiveDate; use chrono::NaiveDate;
use std::collections::HashMap; use std::collections::HashMap;

View File

@ -1,3 +1,21 @@
//! High-level interface for working with columnar data and row indices.
//!
//! The [`Frame`](crate::frame::Frame) type combines a matrix with column labels and a typed row
//! index, similar to data frames in other data-analysis libraries.
//!
//! # Examples
//!
//! ```
//! use rustframe::frame::{Frame, RowIndex};
//! use rustframe::matrix::Matrix;
//!
//! // Build a frame from two columns labelled "A" and "B".
//! let data = Matrix::from_cols(vec![vec![1.0, 2.0], vec![3.0, 4.0]]);
//! let frame = Frame::new(data, vec!["A", "B"], None);
//!
//! assert_eq!(frame["A"], vec![1.0, 2.0]);
//! assert_eq!(frame.index(), &RowIndex::Range(0..2));
//! ```
pub mod base; pub mod base;
pub mod ops; pub mod ops;

View File

@ -1,3 +1,16 @@
//! Trait implementations that allow [`Frame`] to reuse matrix operations.
//!
//! These modules forward numeric and boolean aggregation methods from the
//! underlying [`Matrix`](crate::matrix::Matrix) type so that they can be called
//! directly on a [`Frame`].
//!
//! ```
//! use rustframe::frame::Frame;
//! use rustframe::matrix::{Matrix, SeriesOps};
//!
//! let frame = Frame::new(Matrix::from_cols(vec![vec![1.0, 2.0]]), vec!["A"], None);
//! assert_eq!(frame.sum_vertical(), vec![3.0]);
//! ```
use crate::frame::Frame; use crate::frame::Frame;
use crate::matrix::{Axis, BoolMatrix, BoolOps, FloatMatrix, SeriesOps}; use crate::matrix::{Axis, BoolMatrix, BoolOps, FloatMatrix, SeriesOps};

View File

@ -1,3 +1,14 @@
//! Logical reductions for boolean matrices.
//!
//! The [`BoolOps`] trait mirrors common boolean aggregations such as `any` and
//! `all` over rows or columns of a [`BoolMatrix`].
//!
//! ```
//! use rustframe::matrix::{BoolMatrix, BoolOps};
//!
//! let m = BoolMatrix::from_vec(vec![true, false], 2, 1);
//! assert!(m.any());
//! ```
use crate::matrix::{Axis, BoolMatrix}; use crate::matrix::{Axis, BoolMatrix};
/// Boolean operations on `Matrix<bool>` /// Boolean operations on `Matrix<bool>`

View File

@ -1,3 +1,18 @@
//! Core matrix types and operations.
//!
//! The [`Matrix`](crate::matrix::Matrix) struct provides a simple columnmajor 2D array with a
//! suite of numeric helpers. Additional traits like [`SeriesOps`](crate::matrix::SeriesOps) and
//! [`BoolOps`](crate::matrix::BoolOps) extend functionality for common statistics and logical reductions.
//!
//! # Examples
//!
//! ```
//! use rustframe::matrix::Matrix;
//!
//! let m = Matrix::from_cols(vec![vec![1, 2], vec![3, 4]]);
//! assert_eq!(m.shape(), (2, 2));
//! assert_eq!(m[(0,1)], 3);
//! ```
pub mod boolops; pub mod boolops;
pub mod mat; pub mod mat;
pub mod seriesops; pub mod seriesops;

View File

@ -1,3 +1,14 @@
//! Numeric reductions and transformations over matrix axes.
//!
//! [`SeriesOps`] provides methods like [`SeriesOps::sum_vertical`] or
//! [`SeriesOps::map`] that operate on [`FloatMatrix`] values.
//!
//! ```
//! use rustframe::matrix::{Matrix, SeriesOps};
//!
//! let m = Matrix::from_cols(vec![vec![1.0, 2.0], vec![3.0, 4.0]]);
//! assert_eq!(m.sum_horizontal(), vec![4.0, 6.0]);
//! ```
use crate::matrix::{Axis, BoolMatrix, FloatMatrix}; use crate::matrix::{Axis, BoolMatrix, FloatMatrix};
/// "Series-like" helpers that work along a single axis. /// "Series-like" helpers that work along a single axis.

View File

@ -1,3 +1,13 @@
//! Cryptographically secure random number generator.
//!
//! On Unix systems this reads from `/dev/urandom`; on Windows it uses the
//! system's preferred CNG provider.
//!
//! ```
//! use rustframe::random::{crypto_rng, Rng};
//! let mut rng = crypto_rng();
//! let _v = rng.next_u64();
//! ```
#[cfg(unix)] #[cfg(unix)]
use std::{fs::File, io::Read}; use std::{fs::File, io::Read};

View File

@ -1,3 +1,18 @@
//! Random number generation utilities.
//!
//! Provides both a simple pseudo-random generator [`Prng`](crate::random::Prng) and a
//! cryptographically secure alternative [`CryptoRng`](crate::random::CryptoRng). The
//! [`SliceRandom`](crate::random::SliceRandom) trait offers shuffling of slices using any RNG
//! implementing [`Rng`](crate::random::Rng).
//!
//! ```
//! use rustframe::random::{rng, SliceRandom};
//!
//! let mut rng = rng();
//! let mut data = [1, 2, 3, 4];
//! data.shuffle(&mut rng);
//! assert_eq!(data.len(), 4);
//! ```
pub mod crypto; pub mod crypto;
pub mod prng; pub mod prng;
pub mod random_core; pub mod random_core;

View File

@ -1,3 +1,11 @@
//! A tiny XorShift64-based pseudo random number generator.
//!
//! ```
//! use rustframe::random::{rng, Rng};
//! let mut rng = rng();
//! let x = rng.next_u64();
//! assert!(x >= 0);
//! ```
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use crate::random::Rng; use crate::random::Rng;

View File

@ -1,3 +1,11 @@
//! Core traits for random number generators and sampling ranges.
//!
//! ```
//! use rustframe::random::{rng, Rng};
//! let mut r = rng();
//! let value: f64 = r.random_range(0.0..1.0);
//! assert!(value >= 0.0 && value < 1.0);
//! ```
use std::f64::consts::PI; use std::f64::consts::PI;
use std::ops::Range; use std::ops::Range;

View File

@ -1,3 +1,11 @@
//! Extensions for shuffling slices with a random number generator.
//!
//! ```
//! use rustframe::random::{rng, SliceRandom};
//! let mut data = [1, 2, 3];
//! data.shuffle(&mut rng());
//! assert_eq!(data.len(), 3);
//! ```
use crate::random::Rng; use crate::random::Rng;
/// Trait for randomizing slices. /// Trait for randomizing slices.

View File

@ -1,3 +1,10 @@
//! Generation and manipulation of calendar date sequences.
//!
//! ```
//! use rustframe::utils::dateutils::dates::{DateFreq, DatesList};
//! let list = DatesList::new("2024-01-01".into(), "2024-01-03".into(), DateFreq::Daily);
//! assert_eq!(list.count().unwrap(), 3);
//! ```
use chrono::{Datelike, Duration, NaiveDate, Weekday}; use chrono::{Datelike, Duration, NaiveDate, Weekday};
use std::collections::HashMap; use std::collections::HashMap;
use std::error::Error; use std::error::Error;

View File

@ -1,3 +1,13 @@
//! Generators for sequences of calendar and business dates.
//!
//! See [`dates`] for all-day calendars and [`bdates`] for business-day aware
//! variants.
//!
//! ```
//! use rustframe::utils::dateutils::{DatesList, DateFreq};
//! let list = DatesList::new("2024-01-01".into(), "2024-01-02".into(), DateFreq::Daily);
//! assert_eq!(list.count().unwrap(), 2);
//! ```
pub mod bdates; pub mod bdates;
pub mod dates; pub mod dates;

View File

@ -1,3 +1,14 @@
//! Assorted helper utilities.
//!
//! Currently this module exposes date generation utilities in [`dateutils`](crate::utils::dateutils),
//! including calendar and business date sequences.
//!
//! ```
//! use rustframe::utils::DatesList;
//! use rustframe::utils::DateFreq;
//! let dates = DatesList::new("2024-01-01".into(), "2024-01-03".into(), DateFreq::Daily);
//! assert_eq!(dates.count().unwrap(), 3);
//! ```
pub mod dateutils; pub mod dateutils;
pub use dateutils::{BDateFreq, BDatesGenerator, BDatesList}; pub use dateutils::{BDateFreq, BDatesGenerator, BDatesList};