Rstats crates.io GitHub last commit Actions Status

Statistics, Information Measures, Vector Algebra, Linear Algebra, Cholesky Matrix Decomposition, Mahalanobis Distance, Householder QR Decomposition, Multidimensional Data Analysis, Geometric Median, Convex Hull, Machine Learning ...

Usage

Insert Rstats = "^1" in the Cargo.toml file, under [dependencies].

Use in your source files any of the following structs, as and when needed:

rust use Rstats::{RE,TriangMat,Mstats,MinMax,Med};

and any of the following traits:

rust use Rstats::{Stats,Vecg,Vecu8,MutVecg,VecVec,VecVecg};

The latest (nightly) version is always available in the github repository Rstats. Sometimes it may be in some details a little ahead of the crates.io release versions.

It is highly recommended to read and run tests.rs from the github repository as examples of usage. To run all the tests, use a single thread in order to print the results in the right order:

bash cargo test --release -- --test-threads=1 --nocapture --color always

Alternatively, just to get a quick idea of the methods provided and their usage, you can now read the output produced by an automated test run. There are test logs for each new push to this repository. Unclick the latest (top) one, then Rstats and then Run cargo test ... The badge at the top of this document lights up green when all the tests have passed and clicking it gets you to these logs as well.

Introduction

Rstats has a small footprint. Nonetheless the best methods are implemented, primarily with Data Analysis and Machine Learning in mind. They include multidimensional nd analysis, i.e. characterising sets of n points in space of d dimensions.

Several branches of mathematics: statistics, information theory, set theory and linear algebra are combined in this one consistent crate, based on the abstraction that they all operate on the same data objects (here Rust Vecs). The only difference being that an ordering of their components is sometimes assumed (in linear algebra, set theory) and sometimes it is not (in statistics, information theory, set theory).

Rstats begins with basic statistical measures, information measures, vector algebra and linear algebra. These provide self-contained tools for the multidimensional algorithms but are also useful in their own right.

Non analytical statistics is preferred, whereby the 'random variables' are replaced by vectors of real data. Probabilities densities and other parameters are always obtained from the data, not from some assumed distributions.

Linear algebra uses by default Vec<Vec<T>>: a generic data structure capable of representing irregular matrices. Also, struct TriangMat is defined and used for symmetric and triangular matrices (for efficiency reasons).

Our treatment of multidimensional sets of points is constructed from the first principles. Some original concepts, not found elsewhere, are introduced and implemented here:

Zero median vectors are generally preferable to the commonly used zero mean vectors.

In n dimensions, many authors 'cheat' by using quasi medians (1-d medians along each axis). Quasi medians are a poor start to stable characterisation of multidimensional data. In a highly dimensional space, they are also much slower to compute than our gm.

Specifically, all such 1d measures are sensitive to the choice of axis and thus are affected by rotation.

In contrast, analyses based on the true geometric median (gm) are axis (rotation) independent. Also, they are more stable, as medians have a 50% breakdown point (the maximum possible). They are computed here by methods gmedian and its weighted version wgmedian, in traits vecvec and vecvecg respectively.

Additional Documentation

For more detailed comments, plus some examples, see docs.rs. You may have to unclick the 'implementations on foreign types' somewhere near the bottom of the page (as these traits are implemented directly over 'out of this crate' Rust Vec type).

Terminology

Including some new definitions for sets of nd points, i.e. n points in d dimensional space

Implementation

The main constituent parts of Rstats are its traits. The selection of traits (to use) is primarily determined by the types of objects handled. These are mostly vectors of arbitrary length/dimensionality (d). The main traits are implementing methods applicable to:

In other words, the traits and their methods operate on arguments of their required categories. In classical statistical terminology, the main categories correspond to the number of 'random variables'.

Vec<Vec<T>> type is used for full rectangular matrices (could also be irregular), whereas TriangMat struct is used specifically for symmetric and triangular matrices (to save memory).

The vectors' end types (of the actual data) are mostly generic: usually some numeric type. End type f64 is mostly used for the computed results.

Errors

Rstats crate produces custom errors RError:

rust pub enum RError<T> where T:Sized+Debug { /// Insufficient data NoDataError(T), /// Wrong kind/size of data DataError(T), /// Invalid result, such as prevented division by zero ArithError(T), /// Other error converted to RError OtherError(T) } Each of its enum variants also carries a generic payload T. Most commonly this will be a String message giving more helpful explanation, e.g.:

rust if dif <= 0_f64 { return Err(RError::ArithError(format!( "cholesky needs a positive definite matrix {}", dif ))); };

format!(...) is used to insert values of variables to the payload String, as shown. These potential errors are returned and can then be automatically converted (with ?) to users' own errors. Some such conversions are implemented at the bottom of errors.rs file and used in tests.rs.

There is a type alias shortening return declarations to, e.g.: Result<Vec<f64>,RE>, where

rust pub type RE = RError<String>;

Structs

struct MStats

holds the central tendency of 1d data, e.g. some kind of mean or median, and its dispersion measure, e.g. standard deviation or MAD.

struct TriangMat

holds lower/upper triangular symmetric/non-symmetric matrix in compact form that avoids zeros and duplications. Beyond the usual conversion to full matrix form, a number of (the best) Linear Algebra methods are implemented directly on TriangMag, in module triangmag.rs, such as:

Also, there are some methods implemented for VecVecg that produce TriangMat, specifically the covariance/comedience calculations: covar,wcovar,comed and wcomed. Their results will be typically used by mahalanobis.

Auxiliary Functions

Trait Stats

One dimensional statistical measures implemented for all numeric end types.

Its methods operate on one slice of generic data and take no arguments. For example, s.amean() returns the arithmetic mean of the data in slice s. These methods are checked and will report RError(s), such as an empty input. This means you have to apply ? to their results to pass the errors up, or explicitly match them to take recovery actions, depending on the variant.

Included in this trait are:

Note that fast implementation of 1d medians is as of version 1.1.0 in crate medians.

Trait Vecg

Generic vector algebra operations between two slices &[T], &[U] of any length (dimensionality). It may be necessary to invoke some using the 'turbofish' ::<type> syntax to indicate the type U of the supplied argument, e.g.:
datavec.methodname::<f64>(arg)
This is because Rust is currently incapable of inferring the type ('the inference bug').

The simpler methods of this trait are sometimes unchecked (for speed), so some caution with data is advisable.

Trait MutVecg

A select few of the Stats and Vecg methods (e.g. mutable vector addition, subtraction and multiplication) are reimplemented under this trait, so that they can mutate self in-place. This is more efficient and convenient in some circumstances, such as in vector iterative methods.

Trait Vecu8

Some vector algebra as above that can be more efficient when the end type happens to be u8 (bytes). These methods have u8 appended to their names to avoid confusion with Vecg methods. These specific algorithms are different to their generic equivalents in Vecg.

Trait VecVec

Relationships between n vectors (in d dimensions). This general data domain is denoted here as (nd). It is in nd where the main original contribution of this library lies. True geometric median (gm) is found by fast and stable iteration, using improved Weiszfeld's algorithm gmedian. This algorithm solves Weiszfeld's convergence and stability problems in the neighbourhoods of existing set points. Its variant pmedian iterates point-by-point, which gives even better convergence.

Trait VecVecg

Methods which take an additional generic vector argument, such as a vector of weights for computing weighted geometric medians (where each point has its own weight). Matrices multiplications.

Appendix: Recent Releases