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 AsinhCodec {
50 pub linear_width: f64,
53 #[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)]
122pub enum AsinhCodecError {
124 #[error("Asinh does not support the dtype {0}")]
126 UnsupportedDtype(AnyArrayDType),
127 #[error("Asinh does not support non-finite (infinite or NaN) floating point data")]
130 NonFiniteData,
131 #[error("Asinh cannot decode into the provided array")]
133 MismatchedDecodeIntoArray {
134 #[from]
136 source: AnyArrayAssignError,
137 },
138}
139
140pub 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
162pub 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)]
185pub 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 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}