ndhistogram/
lib.rs

1//! ndhistogram implements multi-dimensional histograms for Rust.
2//!
3//!
4//! This library aims to provide a similar feature set to the C++ library
5//! [boost-histogram](https://www.boost.org/doc/libs/1_75_0/libs/histogram)
6//! but with an idomatic pure-Rust implementation.
7//!
8//! Features include:
9//! - Histograms with any number of dimensions from 1 up to 21 dimensions.
10//! - Continuous (eg represented by a floating point number) and discrete axis (eg a category represented by a string value or enum) types that are composable (eg you may mix discrete and continuous axes).
11//! - Flexible bin values including any primitive number type, or a user-defined type.
12//! - Unweighted and weighted filling of histograms.
13//! - Flexible, user-definable axis types.
14//! - Sparse histograms to reduce the memory footprint of high bin count, mostly empty, histograms.
15//!
16//! ## Table of Contents
17//!
18//! 1. [Usage](#usage)
19//! 2. [Quick-start](#quick-start)
20//! 3. [Overview](#overview)
21//!    1. [Histogram Implementations](#histogram-implementations)
22//!    2. [Axis Implementations](#axis-implementations)
23//!    3. [Histogram Bin Values](#histogram-bin-values)
24//! 4. [How to Guide](#how-to-guide)
25//!    1. [Customize the Bin Value Type](#customize-the-bin-value-type)
26//!    2. [Create and Use a 2D Histogram](#create-and-use-a-2d-histogram)
27//!    3. [Create a Histogram with a Discrete Axis](#create-a-histogram-with-a-discrete-axis)
28//!    4. [Create a Histogram with Variable Sized Bins](#create-a-histogram-with-variable-sized-bins)
29//!    5. [Create a Histogram with a Periodic or Cyclic Axis](#create-a-histogram-with-a-periodic-or-cyclic-axis)
30//!    6. [Create a Sparse Histogram](#create-a-sparse-histogram)
31//!    7. [Merge Histograms](#merge-histograms)
32//!    8. [Iterate over Histogram Bins in Parallel](#iterate-over-histogram-bins-in-parallel)
33//! 5. [Crate Feature Flags](#crate-feature-flags)
34//! 6. [How to contribute](#how-to-contribute)
35//!
36//! ## Usage
37//!
38//! Add this to your `Cargo.toml`:
39//!
40//! ```toml
41//! [dependencies]
42//! ndhistogram = "0.10.0"
43//! ```
44//!
45//! See the [change log](https://github.com/davehadley/ndhistogram/blob/main/ndhistogram/CHANGELOG.md)
46//! for differences between releases.
47//! Please report any bugs in the [issues tracker](https://github.com/davehadley/ndhistogram/issues).
48//!
49//! ## Quick-start
50//!
51//! ```rust
52//! use ndhistogram::{Histogram, ndhistogram, axis::Uniform};
53//!
54//! # fn main() -> Result<(), ndhistogram::Error> {
55//! // create a 1D histogram with 10 equally sized bins between -5 and 5
56//! let mut hist = ndhistogram!(Uniform::new(10, -5.0, 5.0)?);
57//! // fill this histogram with a single value
58//! hist.fill(&1.0);
59//! // fill this histogram with weights
60//! hist.fill_with(&2.0, 4.0);
61//! // read the histogram values
62//! let x1 = hist.value(&1.0);
63//! let also_x1 = hist.value_at_index(7);
64//! assert_eq!(x1, also_x1);
65//! // iterate the histogram values
66//! for item in hist.iter() {
67//!     println!("{}, {}, {}", item.index, item.bin, item.value)
68//! }
69//! // print the histogram to stdout
70//! println!("{}", hist);
71//! # Ok(()) }
72//! ```
73//!
74//! ## Overview
75//!
76//! A [Histogram] is composed of two components:
77//! - The [Axes] which is a set of [Axis](axis::Axis) corresponding to each dimension of the histogram.
78//!   The [Axes] and [Axis](axis::Axis) define the binning of the histogram and are responsible for mapping from coordinate space (eg \[x,y,z\]) to an integer bin number.
79//! - The histogram bin value storage. Valid bin value types include any integer and floating number type as well as user defined types that implement [Fill], [FillWith] or [FillWithWeighted].
80//!
81//! ### Histogram Implementations
82//!
83//! - [VecHistogram]: bin values are stored in a [Vec].
84//!   Created with the [ndhistogram] macro.
85//!   This is the recommended implementation for most use cases.
86//!   However, as memory is allocated even for empty bins,
87//!   this may not be practical for very high dimension histograms.
88//! - [HashHistogram]: bin values are stored in a [HashMap](std::collections::HashMap).
89//!   Created with the [sparsehistogram] macro.
90//!   Useful for high dimension, mostly empty, histograms as empty bins
91//!   take up no memory.
92//!
93//! Alternative implementations are possible by implementing the [Histogram] trait.
94//!
95//! ### Axis Implementations
96//!
97//! - [Uniform](axis::Uniform)/[UniformNoFlow](axis::UniformNoFlow): equally sized bins in a some range with optional underflow/overflow bins.
98//! - [Variable](axis::Variable)/[VariableNoFlow](axis::VariableNoFlow): variable sized bins with optional underflow/overflow bins.
99//! - [UniformCyclic](axis::UniformCyclic)/[VariableCyclic](axis::VariableCyclic): cyclic or periodic versions of the Uniform and Variable axes.
100//! - [Category](axis::Category)/[CategoryNoFlow](axis::CategoryNoFlow): a finite set of discrete values with optional overflow bin.
101//!
102//! User defined axes types are possible by implementing the [Axis](axis::Axis) trait.
103//!
104//! ### Histogram Bin Values
105//!
106//! Histograms may be filled with values of the following types:
107//!
108//! - Primitive floating point and integer number types.
109//! - All types that implement [Fill]
110//! - All types that implement [FillWith]
111//! - All types that implement [FillWithWeighted]
112//! - All types that implement [AddAssign](std::ops::AddAssign) (as they are also [FillWith]).
113//! - All types that implement [AddAssign](std::ops::AddAssign) and [One](num_traits::One) (as they are also [Fill]).
114//!
115//! This crate defines the following bin value types:
116//!
117//! - [Sum](value::Sum) : a simple bin count that counts the number of times it has been filled.
118//! - [WeightedSum](value::WeightedSum) : as Sum but with weighted fills.
119//! - [Mean](value::Mean) : computes the mean of the values it is filled with.
120//! - [WeightedMean](value::WeightedMean) : as Mean but with weighted fills.
121//!
122//! User defined bin value types are possible by implementing the [Fill], [FillWith] or [FillWithWeighted] traits.
123//!
124//! ## How to Guide
125//!
126//! ### Customize the Bin Value Type
127//!
128//! ```rust
129//! use ndhistogram::{Histogram, ndhistogram, axis::Uniform, value::Mean};
130//! # fn main() -> Result<(), ndhistogram::Error> {
131//! // Create a histogram whose bin values are i32
132//! let mut hist = ndhistogram!(Uniform::new(10, -5.0, 5.0)?; i32);
133//! hist.fill_with(&1.0, 2);
134//! let value: Option<&i32> = hist.value(&1.0);
135//! assert_eq!(value, Some(&2));
136//!
137//! // More complex value types beyond primitives are available
138//! // "Mean" calculates the average of values it is filled with
139//! let mut hist = ndhistogram!(Uniform::new(10, -5.0, 5.0)?; Mean);
140//! hist.fill_with(&1.0, 1.0);
141//! hist.fill_with(&1.0, 3.0);
142//! assert_eq!(hist.value(&1.0).unwrap().mean(), 2.0);
143//!
144//! // for other examples see the documentation of Sum, WeightedSum and WeightedMean
145//!
146//! // user defined value types are possible by implementing
147//! // Fill, FillWith or FillWithWeighted traits
148//! # Ok(()) }
149//! ```
150//!
151//! ### Create and Use a 2D Histogram
152//!
153//! ```rust
154//! use ndhistogram::{Histogram, ndhistogram, axis::Uniform};
155//! # fn main() -> Result<(), ndhistogram::Error> {
156//! // create a 2D histogram
157//! let mut hist = ndhistogram!(Uniform::new(10, -5.0, 5.0)?, Uniform::new(10, -5.0, 5.0)?);
158//! // fill 2D histogram
159//! hist.fill(&(1.0, 2.0));
160//! // read back the histogram values
161//! let x1_y2 = hist.value(&(1.0, 2.0));
162//! // higher dimensions are possible with additional arguments to ndhistogram
163//! # Ok(()) }
164//! ```
165//!
166//! ### Create a Histogram with a Discrete Axis
167//! ```rust
168//! use ndhistogram::{Histogram, ndhistogram, axis::Category};
169//! # fn main() -> Result<(), ndhistogram::Error> {
170//! let mut hist = ndhistogram!(Category::new(vec![0, 2, 4]));
171//! hist.fill_with(&2, 42.0);
172//! hist.fill_with(&1, 128.0);
173//! assert_eq!(hist.value(&2), Some(&42.0));
174//! assert_eq!(hist.value(&1), Some(&128.0));
175//! assert_eq!(hist.value(&3), Some(&128.0));
176//! // 1 and 3 give the same answer as they are both mapped to the overflow bin
177//! // For a version with no overflow bins use CategoryNoFlow
178//!
179//! // The Category type can be any hashable type, for example string
180//! let mut hist = ndhistogram!(Category::new(vec!["Red", "Blue", "Green"]));
181//! hist.fill(&"Red");
182//! assert_eq!(hist.value(&"Red"), Some(&1.0));
183//! # Ok(()) }
184//! ```
185//!
186//! ### Create a Histogram with Variable Sized Bins
187//!
188//! ```rust
189//! use ndhistogram::{Histogram, ndhistogram, axis::Variable};
190//! # fn main() -> Result<(), ndhistogram::Error> {
191//! let mut hist = ndhistogram!(Variable::new(vec![0.0, 1.0, 3.0, 6.0])?);
192//! for x in 0..6 {
193//!     hist.fill(&f64::from(x));
194//! }
195//! assert_eq!(hist.value(&0.0), Some(&1.0));
196//! assert_eq!(hist.value(&1.0), Some(&2.0));
197//! assert_eq!(hist.value(&3.0), Some(&3.0));
198//! # Ok(()) }
199//! ```
200//!
201//! ### Create a Histogram with a Periodic or Cyclic Axis
202//!
203//! ```rust
204//! use std::f64::consts::PI;
205//! use ndhistogram::{Histogram, ndhistogram, axis::UniformCyclic};
206//! # fn main() -> Result<(), ndhistogram::Error> {
207//! let mut hist = ndhistogram!(UniformCyclic::<f64>::new(10, 0.0, 2.0*PI)?);
208//! hist.fill(&PI);
209//! hist.fill(&-PI);
210//! // +pi and -pi are mapped onto the same value
211//! assert_eq!(hist.value(&-PI), Some(&2.0));
212//! assert_eq!(hist.value(&PI), Some(&2.0));
213//! # Ok(()) }
214//! ```
215//!
216//! ### Create a Sparse Histogram
217//!
218//! ```rust
219//! use ndhistogram::{Histogram, sparsehistogram, axis::Uniform};
220//! # fn main() -> Result<(), ndhistogram::Error> {
221//! // This histogram has 1e18 bins, too many to allocate with a normal histogram
222//! let mut histogram_with_lots_of_bins = sparsehistogram!(
223//!     Uniform::new(1_000_000, -5.0, 5.0)?,
224//!     Uniform::new(1_000_000, -5.0, 5.0)?,
225//!     Uniform::new(1_000_000, -5.0, 5.0)?
226//! );
227//! histogram_with_lots_of_bins.fill(&(1.0, 2.0, 3.0));
228//! // read back the filled value
229//! assert_eq!(histogram_with_lots_of_bins.value(&(1.0, 2.0, 3.0)).unwrap(), &1.0);
230//! // unfilled bins will return None
231//! assert!(histogram_with_lots_of_bins.value(&(0.0, 0.0, 0.0)).is_none());
232//! # Ok(()) }
233//! ```
234//!
235//! ### Merge Histograms
236//!
237//! ```rust
238//! use ndhistogram::{Histogram, ndhistogram, axis::Uniform};
239//! # fn main() -> Result<(), ndhistogram::Error> {
240//! let mut hist1 = ndhistogram!(Uniform::<f64>::new(10, -5.0, 5.0)?);
241//! let mut hist2 = ndhistogram!(Uniform::<f64>::new(10, -5.0, 5.0)?);
242//! hist1.fill_with(&0.0, 2.0);
243//! hist2.fill_with(&0.0, 3.0);
244//! let combined_hist = (hist1 + &hist2).expect("Axes are compatible");
245//! # assert_eq!(combined_hist.value(&0.0).unwrap(), &5.0);
246//! # Ok(()) }
247//! ```
248//!
249//! ### Iterate over Histogram Bins in Parallel
250//!
251//! ```rust
252//! # fn main() -> Result<(), ndhistogram::Error> {
253//! #[cfg(feature = "rayon")] {
254//! use rayon::prelude::*;
255//! use ndhistogram::{Histogram, ndhistogram, axis::Uniform};
256//! let mut histogram = ndhistogram!(Uniform::<f64>::new(10, -5.0, 5.0)?);
257//! let sum: f64 = histogram.par_iter().map(|bin| bin.value).sum();
258//! // see also: par_iter_mut, par_values, par_values_mut.
259//! assert_eq!(sum, 0.0);
260//! # }
261//! # Ok(()) }
262//! ```
263//! Requires "rayon" feature enabled.
264//!
265//! ## Crate Feature Flags
266//! All cargo features of this crate are off by default.
267//! The following features can be enabled in your `Cargo.toml`:
268//!   - [serde] : enable support for histogram serialization and deserialization.
269//!   - [rayon] : enable parallel iteration over histograms.
270//!
271//! ## How to contribute
272//!
273//! If you discover a bug in this crate or a mistake in the documentation please either
274//! [open an issue](https://github.com/davehadley/ndhistogram/issues) or
275//! [submit a pull request](https://github.com/davehadley/ndhistogram/pulls).
276//!
277//! If you want to request or add a new feature please
278//! [open an issue](https://github.com/davehadley/ndhistogram/issues).
279//!
280
281#![doc(issue_tracker_base_url = "https://github.com/davehadley/ndhistogram/issues")]
282#![doc(html_root_url = "https://docs.rs/ndhistogram/0.10.0")]
283#![cfg_attr(
284    debug_assertions,
285    warn(
286        missing_debug_implementations,
287        rust_2018_idioms,
288        unreachable_pub,
289        unused_import_braces,
290    ),
291    deny(unsafe_code, macro_use_extern_crate),
292    warn(
293        missing_docs,
294        rustdoc::missing_crate_level_docs,
295        rustdoc::broken_intra_doc_links,
296    )
297)]
298
299mod axes;
300pub mod axis;
301mod histogram;
302
303pub mod value;
304
305pub use axes::Axes;
306pub use axes::AxesTuple;
307pub use histogram::fill::Fill;
308pub use histogram::fill::FillWith;
309pub use histogram::fill::FillWithWeighted;
310pub use histogram::hashhistogram::HashHistogram;
311pub use histogram::histogram::Histogram;
312pub use histogram::histogram::Item;
313pub use histogram::vechistogram::VecHistogram;
314
315/// Type alias for 1D [Histogram]s returned by [ndhistogram].
316pub type Hist1D<X, V = f64> = VecHistogram<AxesTuple<(X,)>, V>;
317
318/// Type alias for 2D [Histogram]s returned by [ndhistogram].
319pub type Hist2D<X, Y, V = f64> = VecHistogram<AxesTuple<(X, Y)>, V>;
320
321/// Type alias for 3D [Histogram]s returned by [ndhistogram].
322pub type Hist3D<X, Y, Z, V = f64> = VecHistogram<AxesTuple<(X, Y, Z)>, V>;
323
324/// Type alias for ND [Histogram]s returned by [ndhistogram].
325pub type HistND<A, V = f64> = VecHistogram<AxesTuple<A>, V>;
326
327/// Type alias for 1D [Histogram]s returned by [sparsehistogram].
328pub type SparseHist1D<X, V = f64> = HashHistogram<AxesTuple<(X,)>, V>;
329
330/// Type alias for 2D [Histogram]s returned by [sparsehistogram].
331pub type SparseHist2D<X, Y, V = f64> = HashHistogram<AxesTuple<(X, Y)>, V>;
332
333/// Type alias for 3D [Histogram]s returned by [sparsehistogram].
334pub type SparseHist3D<X, Y, Z, V = f64> = HashHistogram<AxesTuple<(X, Y, Z)>, V>;
335
336/// Type alias for ND [Histogram]s returned by [sparsehistogram].
337pub type SparseHistND<A, V = f64> = HashHistogram<AxesTuple<A>, V>;
338
339/// Provides errors that may be returned by [Histogram]s.
340pub mod error;
341
342pub use error::Error;
343
344#[macro_use]
345mod macros;