Skip to main content

numcodecs_log/
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-log
10//! [crates.io]: https://crates.io/crates/numcodecs-log
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-log
13//! [docs.rs]: https://docs.rs/numcodecs-log/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_log
17//!
18//! `$\ln(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/// Log codec which calculates `$c = \ln(x)$` on encoding and `$d = {e}^{c}$`
36/// on decoding.
37///
38/// The codec only supports finite positive floating point numbers.
39pub struct LogCodec {
40    /// The codec's encoding format version. Do not provide this parameter explicitly.
41    #[serde(default, rename = "_version")]
42    pub version: StaticCodecVersion<1, 0, 0>,
43}
44
45impl Codec for LogCodec {
46    type Error = LogCodecError;
47
48    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
49        match data {
50            AnyCowArray::F32(data) => Ok(AnyArray::F32(ln(data)?)),
51            AnyCowArray::F64(data) => Ok(AnyArray::F64(ln(data)?)),
52            encoded => Err(LogCodecError::UnsupportedDtype(encoded.dtype())),
53        }
54    }
55
56    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
57        match encoded {
58            AnyCowArray::F32(encoded) => Ok(AnyArray::F32(exp(encoded)?)),
59            AnyCowArray::F64(encoded) => Ok(AnyArray::F64(exp(encoded)?)),
60            encoded => Err(LogCodecError::UnsupportedDtype(encoded.dtype())),
61        }
62    }
63
64    fn decode_into(
65        &self,
66        encoded: AnyArrayView,
67        decoded: AnyArrayViewMut,
68    ) -> Result<(), Self::Error> {
69        match (encoded, decoded) {
70            (AnyArrayView::F32(encoded), AnyArrayViewMut::F32(decoded)) => {
71                exp_into(encoded, decoded)
72            }
73            (AnyArrayView::F64(encoded), AnyArrayViewMut::F64(decoded)) => {
74                exp_into(encoded, decoded)
75            }
76            (encoded @ (AnyArrayView::F32(_) | AnyArrayView::F64(_)), decoded) => {
77                Err(LogCodecError::MismatchedDecodeIntoArray {
78                    source: AnyArrayAssignError::DTypeMismatch {
79                        src: encoded.dtype(),
80                        dst: decoded.dtype(),
81                    },
82                })
83            }
84            (encoded, _decoded) => Err(LogCodecError::UnsupportedDtype(encoded.dtype())),
85        }
86    }
87}
88
89impl StaticCodec for LogCodec {
90    const CODEC_ID: &'static str = "log.rs";
91
92    type Config<'de> = Self;
93
94    fn from_config(config: Self::Config<'_>) -> Self {
95        config
96    }
97
98    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
99        StaticCodecConfig::from(self)
100    }
101}
102
103#[derive(Debug, Error)]
104/// Errors that may occur when applying the [`LogCodec`].
105pub enum LogCodecError {
106    /// [`LogCodec`] does not support the dtype
107    #[error("Log does not support the dtype {0}")]
108    UnsupportedDtype(AnyArrayDType),
109    /// [`LogCodec`] does not support non-positive (negative or zero) floating
110    /// point data
111    #[error("Log does not support non-positive (negative or zero) floating point data")]
112    NonPositiveData,
113    /// [`LogCodec`] does not support non-finite (infinite or NaN) floating
114    /// point data
115    #[error("Log does not support non-finite (infinite or NaN) floating point data")]
116    NonFiniteData,
117    /// [`LogCodec`] cannot decode into the provided array
118    #[error("Log cannot decode into the provided array")]
119    MismatchedDecodeIntoArray {
120        /// The source of the error
121        #[from]
122        source: AnyArrayAssignError,
123    },
124}
125
126/// Compute `$\ln(x)$` over the elements of the input `data` array.
127///
128/// # Errors
129///
130/// Errors with
131/// - [`LogCodecError::NonPositiveData`] if any data element is non-positive
132///   (negative or zero)
133/// - [`LogCodecError::NonFiniteData`] if any data element is non-finite
134///   (infinite or NaN)
135pub fn ln<T: Float + Signed, S: Data<Elem = T>, D: Dimension>(
136    data: ArrayBase<S, D>,
137) -> Result<Array<T, D>, LogCodecError> {
138    if !Zip::from(&data).all(T::is_positive) {
139        return Err(LogCodecError::NonPositiveData);
140    }
141
142    if !Zip::from(&data).all(|x| x.is_finite()) {
143        return Err(LogCodecError::NonFiniteData);
144    }
145
146    let mut data = data.into_owned();
147    data.mapv_inplace(T::ln);
148
149    Ok(data)
150}
151
152/// Compute `${e}^{x}$` over the elements of the input `data` array.
153///
154/// # Errors
155///
156/// Errors with
157/// - [`LogCodecError::NonFiniteData`] if any data element is non-finite
158///   (infinite or NaN)
159pub fn exp<T: Float, S: Data<Elem = T>, D: Dimension>(
160    data: ArrayBase<S, D>,
161) -> Result<Array<T, D>, LogCodecError> {
162    if !Zip::from(&data).all(|x| x.is_finite()) {
163        return Err(LogCodecError::NonFiniteData);
164    }
165
166    let mut data = data.into_owned();
167    data.mapv_inplace(T::exp);
168
169    Ok(data)
170}
171
172#[expect(clippy::needless_pass_by_value)]
173/// Compute `${e}^{x}$` over the elements of the input `data` array and write
174/// them into the `out`put array.
175///
176/// # Errors
177///
178/// Errors with
179/// - [`LogCodecError::NonFiniteData`] if any data element is non-finite
180///   (infinite or NaN)
181/// - [`LogCodecError::MismatchedDecodeIntoArray`] if the `data` array's shape
182///   does not match the `out`put array's shape
183pub fn exp_into<T: Float, D: Dimension>(
184    data: ArrayView<T, D>,
185    mut out: ArrayViewMut<T, D>,
186) -> Result<(), LogCodecError> {
187    if data.shape() != out.shape() {
188        return Err(LogCodecError::MismatchedDecodeIntoArray {
189            source: AnyArrayAssignError::ShapeMismatch {
190                src: data.shape().to_vec(),
191                dst: out.shape().to_vec(),
192            },
193        });
194    }
195
196    if !Zip::from(&data).all(|x| x.is_finite()) {
197        return Err(LogCodecError::NonFiniteData);
198    }
199
200    // iteration must occur in synchronised (standard) order
201    for (d, o) in data.iter().zip(out.iter_mut()) {
202        *o = T::exp(*d);
203    }
204
205    Ok(())
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn roundtrip() -> Result<(), LogCodecError> {
214        let data = (1..1000).map(f64::from).collect::<Vec<_>>();
215        let data = Array::from_vec(data);
216
217        let encoded = ln(data.view())?;
218
219        for (r, e) in data.iter().zip(encoded.iter()) {
220            assert_eq!((*r).ln().to_bits(), (*e).to_bits());
221        }
222
223        let decoded = exp(encoded)?;
224
225        for (r, d) in data.iter().zip(decoded.iter()) {
226            assert!(((*r) - (*d)).abs() < 1e-12);
227        }
228
229        Ok(())
230    }
231}