Skip to main content

numcodecs_asinh/
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-asinh
10//! [crates.io]: https://crates.io/crates/numcodecs-asinh
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-asinh
13//! [docs.rs]: https://docs.rs/numcodecs-asinh/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_asinh
17//!
18//! `$\text{asinh(x)}$` codec implementation for the [`numcodecs`] API.
19
20use ndarray::{Array, ArrayBase, ArrayView, ArrayViewMut, Data, Dimension, Zip};
21use num_traits::{Float, Signed};
22use numcodecs::{
23    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
24    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
25};
26use schemars::JsonSchema;
27use serde::{Deserialize, Serialize};
28use thiserror::Error;
29
30#[cfg(test)]
31use ::serde_json as _;
32
33#[derive(Clone, Serialize, Deserialize, JsonSchema)]
34#[serde(deny_unknown_fields)]
35/// Asinh codec, which applies a quasi-logarithmic transformation on encoding.
36///
37/// For values close to zero that are within the codec's `linear_width`, the
38/// transform is close to linear. For values of larger magnitudes, the
39/// transform is asymptotically logarithmic. Unlike a logarithmic transform,
40/// this codec supports all finite values, including negative values and zero.
41///
42/// In detail, the codec calculates
43/// `$c = w \cdot \text{asinh}\left( \frac{x}{w} \right)$`
44/// on encoding and
45/// `$d = w \cdot \text{sinh}\left( \frac{c}{w} \right)$`
46/// on decoding, where `$w$` is the codec's `linear_width`.
47///
48/// The codec only supports finite floating point numbers.
49pub struct AsinhCodec {
50    /// The width of the close-to-zero input value range where the transform is
51    /// nearly linear
52    pub linear_width: f64,
53    /// The codec's encoding format version. Do not provide this parameter explicitly.
54    #[serde(default, rename = "_version")]
55    pub version: StaticCodecVersion<1, 0, 0>,
56}
57
58impl Codec for AsinhCodec {
59    type Error = AsinhCodecError;
60
61    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
62        match data {
63            #[expect(clippy::cast_possible_truncation)]
64            AnyCowArray::F32(data) => Ok(AnyArray::F32(asinh(data, self.linear_width as f32)?)),
65            AnyCowArray::F64(data) => Ok(AnyArray::F64(asinh(data, self.linear_width)?)),
66            encoded => Err(AsinhCodecError::UnsupportedDtype(encoded.dtype())),
67        }
68    }
69
70    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
71        match encoded {
72            #[expect(clippy::cast_possible_truncation)]
73            AnyCowArray::F32(encoded) => {
74                Ok(AnyArray::F32(sinh(encoded, self.linear_width as f32)?))
75            }
76            AnyCowArray::F64(encoded) => Ok(AnyArray::F64(sinh(encoded, self.linear_width)?)),
77            encoded => Err(AsinhCodecError::UnsupportedDtype(encoded.dtype())),
78        }
79    }
80
81    fn decode_into(
82        &self,
83        encoded: AnyArrayView,
84        decoded: AnyArrayViewMut,
85    ) -> Result<(), Self::Error> {
86        match (encoded, decoded) {
87            #[expect(clippy::cast_possible_truncation)]
88            (AnyArrayView::F32(encoded), AnyArrayViewMut::F32(decoded)) => {
89                sinh_into(encoded, decoded, self.linear_width as f32)
90            }
91            (AnyArrayView::F64(encoded), AnyArrayViewMut::F64(decoded)) => {
92                sinh_into(encoded, decoded, self.linear_width)
93            }
94            (encoded @ (AnyArrayView::F32(_) | AnyArrayView::F64(_)), decoded) => {
95                Err(AsinhCodecError::MismatchedDecodeIntoArray {
96                    source: AnyArrayAssignError::DTypeMismatch {
97                        src: encoded.dtype(),
98                        dst: decoded.dtype(),
99                    },
100                })
101            }
102            (encoded, _decoded) => Err(AsinhCodecError::UnsupportedDtype(encoded.dtype())),
103        }
104    }
105}
106
107impl StaticCodec for AsinhCodec {
108    const CODEC_ID: &'static str = "asinh.rs";
109
110    type Config<'de> = Self;
111
112    fn from_config(config: Self::Config<'_>) -> Self {
113        config
114    }
115
116    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
117        StaticCodecConfig::from(self)
118    }
119}
120
121#[derive(Debug, Error)]
122/// Errors that may occur when applying the [`AsinhCodec`].
123pub enum AsinhCodecError {
124    /// [`AsinhCodec`] does not support the dtype
125    #[error("Asinh does not support the dtype {0}")]
126    UnsupportedDtype(AnyArrayDType),
127    /// [`AsinhCodec`] does not support non-finite (infinite or NaN) floating
128    /// point data
129    #[error("Asinh does not support non-finite (infinite or NaN) floating point data")]
130    NonFiniteData,
131    /// [`AsinhCodec`] cannot decode into the provided array
132    #[error("Asinh cannot decode into the provided array")]
133    MismatchedDecodeIntoArray {
134        /// The source of the error
135        #[from]
136        source: AnyArrayAssignError,
137    },
138}
139
140/// Compute `$w \cdot \text{asinh}\left( \frac{x}{w} \right)$` over the
141/// elements of the input `data` array.
142///
143/// # Errors
144///
145/// Errors with
146/// - [`AsinhCodecError::NonFiniteData`] if any data element is non-finite
147///   (infinite or NaN)
148pub fn asinh<T: Float + Signed, S: Data<Elem = T>, D: Dimension>(
149    data: ArrayBase<S, D>,
150    linear_width: T,
151) -> Result<Array<T, D>, AsinhCodecError> {
152    if !Zip::from(&data).all(|x| x.is_finite()) {
153        return Err(AsinhCodecError::NonFiniteData);
154    }
155
156    let mut data = data.into_owned();
157    data.mapv_inplace(|x| (x / linear_width).asinh() * linear_width);
158
159    Ok(data)
160}
161
162/// Compute `$w \cdot \text{sinh}\left( \frac{x}{w} \right)$` over the
163/// elements of the input `data` array.
164///
165/// # Errors
166///
167/// Errors with
168/// - [`AsinhCodecError::NonFiniteData`] if any data element is non-finite
169///   (infinite or NaN)
170pub fn sinh<T: Float, S: Data<Elem = T>, D: Dimension>(
171    data: ArrayBase<S, D>,
172    linear_width: T,
173) -> Result<Array<T, D>, AsinhCodecError> {
174    if !Zip::from(&data).all(|x| x.is_finite()) {
175        return Err(AsinhCodecError::NonFiniteData);
176    }
177
178    let mut data = data.into_owned();
179    data.mapv_inplace(|x| (x / linear_width).sinh() * linear_width);
180
181    Ok(data)
182}
183
184#[expect(clippy::needless_pass_by_value)]
185/// Compute `$w \cdot \text{sinh}\left( \frac{x}{w} \right)$` over the
186/// elements of the input `data` array and write them into the `out`put array.
187///
188/// # Errors
189///
190/// Errors with
191/// - [`AsinhCodecError::NonFiniteData`] if any data element is non-finite
192///   (infinite or NaN)
193/// - [`AsinhCodecError::MismatchedDecodeIntoArray`] if the `data` array's shape
194///   does not match the `out`put array's shape
195pub fn sinh_into<T: Float, D: Dimension>(
196    data: ArrayView<T, D>,
197    mut out: ArrayViewMut<T, D>,
198    linear_width: T,
199) -> Result<(), AsinhCodecError> {
200    if data.shape() != out.shape() {
201        return Err(AsinhCodecError::MismatchedDecodeIntoArray {
202            source: AnyArrayAssignError::ShapeMismatch {
203                src: data.shape().to_vec(),
204                dst: out.shape().to_vec(),
205            },
206        });
207    }
208
209    if !Zip::from(&data).all(|x| x.is_finite()) {
210        return Err(AsinhCodecError::NonFiniteData);
211    }
212
213    // iteration must occur in synchronised (standard) order
214    for (d, o) in data.iter().zip(out.iter_mut()) {
215        *o = ((*d) / linear_width).sinh() * linear_width;
216    }
217
218    Ok(())
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn roundtrip() -> Result<(), AsinhCodecError> {
227        let data = (-1000..1000).map(f64::from).collect::<Vec<_>>();
228        let data = Array::from_vec(data);
229
230        let encoded = asinh(data.view(), 1.0)?;
231
232        for (r, e) in data.iter().zip(encoded.iter()) {
233            assert_eq!((*r).asinh().to_bits(), (*e).to_bits());
234        }
235
236        let decoded = sinh(encoded, 1.0)?;
237
238        for (r, d) in data.iter().zip(decoded.iter()) {
239            assert!(((*r) - (*d)).abs() < 1e-12);
240        }
241
242        Ok(())
243    }
244
245    #[test]
246    fn roundtrip_widths() -> Result<(), AsinhCodecError> {
247        let data = (-1000..1000).map(f64::from).collect::<Vec<_>>();
248        let data = Array::from_vec(data);
249
250        for linear_width in [-100.0, -10.0, -1.0, -0.1, 0.1, 1.0, 10.0, 100.0] {
251            let encoded = asinh(data.view(), linear_width)?;
252            let decoded = sinh(encoded, linear_width)?;
253
254            for (r, d) in data.iter().zip(decoded.iter()) {
255                assert!(((*r) - (*d)).abs() < 1e-12);
256            }
257        }
258
259        Ok(())
260    }
261}