1use 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)]
35pub struct LogCodec {
40 #[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)]
104pub enum LogCodecError {
106 #[error("Log does not support the dtype {0}")]
108 UnsupportedDtype(AnyArrayDType),
109 #[error("Log does not support non-positive (negative or zero) floating point data")]
112 NonPositiveData,
113 #[error("Log does not support non-finite (infinite or NaN) floating point data")]
116 NonFiniteData,
117 #[error("Log cannot decode into the provided array")]
119 MismatchedDecodeIntoArray {
120 #[from]
122 source: AnyArrayAssignError,
123 },
124}
125
126pub 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
152pub 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)]
173pub 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 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}