Skip to main content

numcodecs_uniform_noise/
lib.rs

1//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io] [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
2//!
3//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/numcodecs-rs/ci.yml?branch=main
4//! [workflow]: https://github.com/juntyr/numcodecs-rs/actions/workflows/ci.yml?query=branch%3Amain
5//!
6//! [MSRV]: https://img.shields.io/badge/MSRV-1.88.0-blue
7//! [repo]: https://github.com/juntyr/numcodecs-rs
8//!
9//! [Latest Version]: https://img.shields.io/crates/v/numcodecs-uniform-noise
10//! [crates.io]: https://crates.io/crates/numcodecs-uniform-noise
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-uniform-noise
13//! [docs.rs]: https://docs.rs/numcodecs-uniform-noise/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_uniform_noise
17//!
18//! Uniform noise codec implementation for the [`numcodecs`] API.
19
20use std::hash::{Hash, Hasher};
21
22use ndarray::{Array, ArrayBase, Data, Dimension};
23use num_traits::Float;
24use numcodecs::{
25    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
26    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
27};
28use rand::{
29    SeedableRng,
30    distr::{Distribution, Open01},
31};
32use schemars::JsonSchema;
33use serde::{Deserialize, Serialize};
34use thiserror::Error;
35use wyhash::{WyHash, WyRng};
36
37#[cfg(test)]
38use ::serde_json as _;
39
40#[derive(Clone, Serialize, Deserialize, JsonSchema)]
41#[serde(deny_unknown_fields)]
42/// Codec that adds `seed`ed `$\text{U}(-0.5 \cdot scale, 0.5 \cdot scale)$`
43/// uniform noise of the given `scale` during encoding and passes through the
44/// input unchanged during decoding.
45///
46/// This codec first hashes the input array data and shape to then seed a
47/// pseudo-random number generator that generates the uniform noise. Therefore,
48/// passing in the same input with the same `seed` will produce the same noise
49/// and thus the same encoded output.
50pub struct UniformNoiseCodec {
51    /// Scale of the uniform noise, which is sampled from
52    /// `$\text{U}(-0.5 \cdot scale, 0.5 \cdot scale)$`
53    pub scale: f64,
54    /// Seed for the random noise generator
55    pub seed: u64,
56    /// The codec's encoding format version. Do not provide this parameter explicitly.
57    #[serde(default, rename = "_version")]
58    pub version: StaticCodecVersion<1, 0, 0>,
59}
60
61impl Codec for UniformNoiseCodec {
62    type Error = UniformNoiseCodecError;
63
64    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
65        match data {
66            #[expect(clippy::cast_possible_truncation)]
67            AnyCowArray::F32(data) => Ok(AnyArray::F32(add_uniform_noise(
68                data,
69                self.scale as f32,
70                self.seed,
71            ))),
72            AnyCowArray::F64(data) => Ok(AnyArray::F64(add_uniform_noise(
73                data, self.scale, self.seed,
74            ))),
75            encoded => Err(UniformNoiseCodecError::UnsupportedDtype(encoded.dtype())),
76        }
77    }
78
79    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
80        match encoded {
81            AnyCowArray::F32(encoded) => Ok(AnyArray::F32(encoded.into_owned())),
82            AnyCowArray::F64(encoded) => Ok(AnyArray::F64(encoded.into_owned())),
83            encoded => Err(UniformNoiseCodecError::UnsupportedDtype(encoded.dtype())),
84        }
85    }
86
87    fn decode_into(
88        &self,
89        encoded: AnyArrayView,
90        mut decoded: AnyArrayViewMut,
91    ) -> Result<(), Self::Error> {
92        if !matches!(encoded.dtype(), AnyArrayDType::F32 | AnyArrayDType::F64) {
93            return Err(UniformNoiseCodecError::UnsupportedDtype(encoded.dtype()));
94        }
95
96        Ok(decoded.assign(&encoded)?)
97    }
98}
99
100impl StaticCodec for UniformNoiseCodec {
101    const CODEC_ID: &'static str = "uniform-noise.rs";
102
103    type Config<'de> = Self;
104
105    fn from_config(config: Self::Config<'_>) -> Self {
106        config
107    }
108
109    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
110        StaticCodecConfig::from(self)
111    }
112}
113
114#[derive(Debug, Error)]
115/// Errors that may occur when applying the [`UniformNoiseCodec`].
116pub enum UniformNoiseCodecError {
117    /// [`UniformNoiseCodec`] does not support the dtype
118    #[error("UniformNoise does not support the dtype {0}")]
119    UnsupportedDtype(AnyArrayDType),
120    /// [`UniformNoiseCodec`] cannot decode into the provided array
121    #[error("UniformNoise cannot decode into the provided array")]
122    MismatchedDecodeIntoArray {
123        /// The source of the error
124        #[from]
125        source: AnyArrayAssignError,
126    },
127}
128
129/// Adds `$\text{U}(-0.5 \cdot scale, 0.5 \cdot scale)$` uniform random noise
130/// to the input `data`.
131///
132/// This function first hashes the input and its shape to then seed a pseudo-
133/// random number generator that generates the uniform noise. Therefore,
134/// passing in the same input with the same `seed` will produce the same noise
135/// and thus the same output.
136#[must_use]
137pub fn add_uniform_noise<T: FloatExt, S: Data<Elem = T>, D: Dimension>(
138    data: ArrayBase<S, D>,
139    scale: T,
140    seed: u64,
141) -> Array<T, D>
142where
143    Open01: Distribution<T>,
144{
145    let mut hasher = WyHash::with_seed(seed);
146    // hashing the shape provides a prefix for the flattened data
147    data.shape().hash(&mut hasher);
148    // the data must be visited in a defined order
149    data.iter().copied().for_each(|x| x.hash_bits(&mut hasher));
150    let seed = hasher.finish();
151
152    let mut rng: WyRng = WyRng::seed_from_u64(seed);
153
154    let mut encoded = data.into_owned();
155
156    // the data must be visited in a defined order
157    for x in &mut encoded {
158        // x = U(0,1)*scale + (scale*-0.5 + x)
159        // --- is equivalent to ---
160        // x += U(-scale/2, +scale/2)
161        *x = Open01
162            .sample(&mut rng)
163            .mul_add(scale, scale.mul_add(T::NEG_HALF, *x));
164    }
165
166    encoded
167}
168
169/// Floating point types
170pub trait FloatExt: Float {
171    /// -0.5
172    const NEG_HALF: Self;
173
174    /// Hash the binary representation of the floating point value
175    fn hash_bits<H: Hasher>(self, hasher: &mut H);
176}
177
178impl FloatExt for f32 {
179    const NEG_HALF: Self = -0.5;
180
181    fn hash_bits<H: Hasher>(self, hasher: &mut H) {
182        hasher.write_u32(self.to_bits());
183    }
184}
185
186impl FloatExt for f64 {
187    const NEG_HALF: Self = -0.5;
188
189    fn hash_bits<H: Hasher>(self, hasher: &mut H) {
190        hasher.write_u64(self.to_bits());
191    }
192}