Skip to main content

ad_core_rs/
ndarray.rs

1use crate::attributes::NDAttributeList;
2use crate::codec::Codec;
3use crate::error::{ADError, ADResult};
4use crate::timestamp::EpicsTimestamp;
5
6/// NDArray data types matching areaDetector NDDataType_t.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8#[repr(u8)]
9pub enum NDDataType {
10    Int8 = 0,
11    UInt8 = 1,
12    Int16 = 2,
13    UInt16 = 3,
14    Int32 = 4,
15    UInt32 = 5,
16    Int64 = 6,
17    UInt64 = 7,
18    Float32 = 8,
19    Float64 = 9,
20}
21
22impl NDDataType {
23    pub fn element_size(&self) -> usize {
24        match self {
25            Self::Int8 | Self::UInt8 => 1,
26            Self::Int16 | Self::UInt16 => 2,
27            Self::Int32 | Self::UInt32 | Self::Float32 => 4,
28            Self::Int64 | Self::UInt64 | Self::Float64 => 8,
29        }
30    }
31
32    pub fn from_ordinal(v: u8) -> Option<Self> {
33        match v {
34            0 => Some(Self::Int8),
35            1 => Some(Self::UInt8),
36            2 => Some(Self::Int16),
37            3 => Some(Self::UInt16),
38            4 => Some(Self::Int32),
39            5 => Some(Self::UInt32),
40            6 => Some(Self::Int64),
41            7 => Some(Self::UInt64),
42            8 => Some(Self::Float32),
43            9 => Some(Self::Float64),
44            _ => None,
45        }
46    }
47}
48
49/// Typed buffer for NDArray data.
50#[derive(Debug, Clone)]
51pub enum NDDataBuffer {
52    I8(Vec<i8>),
53    U8(Vec<u8>),
54    I16(Vec<i16>),
55    U16(Vec<u16>),
56    I32(Vec<i32>),
57    U32(Vec<u32>),
58    I64(Vec<i64>),
59    U64(Vec<u64>),
60    F32(Vec<f32>),
61    F64(Vec<f64>),
62}
63
64impl NDDataBuffer {
65    pub fn zeros(data_type: NDDataType, count: usize) -> Self {
66        match data_type {
67            NDDataType::Int8 => Self::I8(vec![0; count]),
68            NDDataType::UInt8 => Self::U8(vec![0; count]),
69            NDDataType::Int16 => Self::I16(vec![0; count]),
70            NDDataType::UInt16 => Self::U16(vec![0; count]),
71            NDDataType::Int32 => Self::I32(vec![0; count]),
72            NDDataType::UInt32 => Self::U32(vec![0; count]),
73            NDDataType::Int64 => Self::I64(vec![0; count]),
74            NDDataType::UInt64 => Self::U64(vec![0; count]),
75            NDDataType::Float32 => Self::F32(vec![0.0; count]),
76            NDDataType::Float64 => Self::F64(vec![0.0; count]),
77        }
78    }
79
80    pub fn data_type(&self) -> NDDataType {
81        match self {
82            Self::I8(_) => NDDataType::Int8,
83            Self::U8(_) => NDDataType::UInt8,
84            Self::I16(_) => NDDataType::Int16,
85            Self::U16(_) => NDDataType::UInt16,
86            Self::I32(_) => NDDataType::Int32,
87            Self::U32(_) => NDDataType::UInt32,
88            Self::I64(_) => NDDataType::Int64,
89            Self::U64(_) => NDDataType::UInt64,
90            Self::F32(_) => NDDataType::Float32,
91            Self::F64(_) => NDDataType::Float64,
92        }
93    }
94
95    pub fn len(&self) -> usize {
96        match self {
97            Self::I8(v) => v.len(),
98            Self::U8(v) => v.len(),
99            Self::I16(v) => v.len(),
100            Self::U16(v) => v.len(),
101            Self::I32(v) => v.len(),
102            Self::U32(v) => v.len(),
103            Self::I64(v) => v.len(),
104            Self::U64(v) => v.len(),
105            Self::F32(v) => v.len(),
106            Self::F64(v) => v.len(),
107        }
108    }
109
110    pub fn is_empty(&self) -> bool {
111        self.len() == 0
112    }
113
114    pub fn total_bytes(&self) -> usize {
115        self.len() * self.data_type().element_size()
116    }
117
118    /// Capacity of the underlying Vec in bytes.
119    pub fn capacity_bytes(&self) -> usize {
120        let cap = match self {
121            Self::I8(v) => v.capacity(),
122            Self::U8(v) => v.capacity(),
123            Self::I16(v) => v.capacity(),
124            Self::U16(v) => v.capacity(),
125            Self::I32(v) => v.capacity(),
126            Self::U32(v) => v.capacity(),
127            Self::I64(v) => v.capacity(),
128            Self::U64(v) => v.capacity(),
129            Self::F32(v) => v.capacity(),
130            Self::F64(v) => v.capacity(),
131        };
132        cap * self.data_type().element_size()
133    }
134
135    /// Resize the buffer, zeroing new elements if growing.
136    pub fn resize(&mut self, new_len: usize) {
137        match self {
138            Self::I8(v) => v.resize(new_len, 0),
139            Self::U8(v) => v.resize(new_len, 0),
140            Self::I16(v) => v.resize(new_len, 0),
141            Self::U16(v) => v.resize(new_len, 0),
142            Self::I32(v) => v.resize(new_len, 0),
143            Self::U32(v) => v.resize(new_len, 0),
144            Self::I64(v) => v.resize(new_len, 0),
145            Self::U64(v) => v.resize(new_len, 0),
146            Self::F32(v) => v.resize(new_len, 0.0),
147            Self::F64(v) => v.resize(new_len, 0.0),
148        }
149    }
150
151    /// View the underlying data as a byte slice.
152    pub fn as_u8_slice(&self) -> &[u8] {
153        match self {
154            Self::I8(v) => unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len()) },
155            Self::U8(v) => v.as_slice(),
156            Self::I16(v) => unsafe {
157                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2)
158            },
159            Self::U16(v) => unsafe {
160                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2)
161            },
162            Self::I32(v) => unsafe {
163                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 4)
164            },
165            Self::U32(v) => unsafe {
166                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 4)
167            },
168            Self::I64(v) => unsafe {
169                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 8)
170            },
171            Self::U64(v) => unsafe {
172                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 8)
173            },
174            Self::F32(v) => unsafe {
175                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 4)
176            },
177            Self::F64(v) => unsafe {
178                std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 8)
179            },
180        }
181    }
182
183    /// Get element at index as f64.
184    pub fn get_as_f64(&self, index: usize) -> Option<f64> {
185        match self {
186            Self::I8(v) => v.get(index).map(|&x| x as f64),
187            Self::U8(v) => v.get(index).map(|&x| x as f64),
188            Self::I16(v) => v.get(index).map(|&x| x as f64),
189            Self::U16(v) => v.get(index).map(|&x| x as f64),
190            Self::I32(v) => v.get(index).map(|&x| x as f64),
191            Self::U32(v) => v.get(index).map(|&x| x as f64),
192            Self::I64(v) => v.get(index).map(|&x| x as f64),
193            Self::U64(v) => v.get(index).map(|&x| x as f64),
194            Self::F32(v) => v.get(index).map(|&x| x as f64),
195            Self::F64(v) => v.get(index).copied(),
196        }
197    }
198
199    /// Set element at index from f64 value.
200    pub fn set_from_f64(&mut self, index: usize, value: f64) {
201        match self {
202            Self::I8(v) => {
203                if let Some(e) = v.get_mut(index) {
204                    *e = value as i8;
205                }
206            }
207            Self::U8(v) => {
208                if let Some(e) = v.get_mut(index) {
209                    *e = value as u8;
210                }
211            }
212            Self::I16(v) => {
213                if let Some(e) = v.get_mut(index) {
214                    *e = value as i16;
215                }
216            }
217            Self::U16(v) => {
218                if let Some(e) = v.get_mut(index) {
219                    *e = value as u16;
220                }
221            }
222            Self::I32(v) => {
223                if let Some(e) = v.get_mut(index) {
224                    *e = value as i32;
225                }
226            }
227            Self::U32(v) => {
228                if let Some(e) = v.get_mut(index) {
229                    *e = value as u32;
230                }
231            }
232            Self::I64(v) => {
233                if let Some(e) = v.get_mut(index) {
234                    *e = value as i64;
235                }
236            }
237            Self::U64(v) => {
238                if let Some(e) = v.get_mut(index) {
239                    *e = value as u64;
240                }
241            }
242            Self::F32(v) => {
243                if let Some(e) = v.get_mut(index) {
244                    *e = value as f32;
245                }
246            }
247            Self::F64(v) => {
248                if let Some(e) = v.get_mut(index) {
249                    *e = value;
250                }
251            }
252        }
253    }
254}
255
256/// A single dimension of an NDArray.
257#[derive(Debug, Clone)]
258pub struct NDDimension {
259    pub size: usize,
260    pub offset: usize,
261    pub binning: usize,
262    pub reverse: bool,
263}
264
265impl NDDimension {
266    pub fn new(size: usize) -> Self {
267        Self {
268            size,
269            offset: 0,
270            binning: 1,
271            reverse: false,
272        }
273    }
274}
275
276/// Computed info about an NDArray's layout.
277#[derive(Debug, Clone)]
278pub struct NDArrayInfo {
279    pub total_bytes: usize,
280    pub bytes_per_element: usize,
281    pub num_elements: usize,
282    pub x_size: usize,
283    pub y_size: usize,
284    pub color_size: usize,
285}
286
287/// N-dimensional array with typed data buffer.
288#[derive(Debug, Clone)]
289pub struct NDArray {
290    pub unique_id: i32,
291    pub timestamp: EpicsTimestamp,
292    pub dims: Vec<NDDimension>,
293    pub data: NDDataBuffer,
294    pub attributes: NDAttributeList,
295    pub codec: Option<Codec>,
296}
297
298impl NDArray {
299    /// Create a new NDArray with zeroed buffer matching dimensions.
300    pub fn new(dims: Vec<NDDimension>, data_type: NDDataType) -> Self {
301        let num_elements: usize = dims.iter().map(|d| d.size).product();
302        Self {
303            unique_id: 0,
304            timestamp: EpicsTimestamp::default(),
305            dims,
306            data: NDDataBuffer::zeros(data_type, num_elements),
307            attributes: NDAttributeList::new(),
308            codec: None,
309        }
310    }
311
312    /// Compute layout info for this array.
313    pub fn info(&self) -> NDArrayInfo {
314        let bytes_per_element = self.data.data_type().element_size();
315        let num_elements = self.data.len();
316        let total_bytes = num_elements * bytes_per_element;
317
318        let ndims = self.dims.len();
319        let (x_size, y_size, color_size) = match ndims {
320            0 => (0, 0, 0),
321            1 => (self.dims[0].size, 1, 1),
322            2 => (self.dims[0].size, self.dims[1].size, 1),
323            _ => {
324                // 3D: interpret as color image
325                // NDColorMode convention: dim[0]=color for RGB1
326                (self.dims[1].size, self.dims[2].size, self.dims[0].size)
327            }
328        };
329
330        NDArrayInfo {
331            total_bytes,
332            bytes_per_element,
333            num_elements,
334            x_size,
335            y_size,
336            color_size,
337        }
338    }
339
340    /// Validate that buffer length matches dimension product.
341    pub fn validate(&self) -> ADResult<()> {
342        let expected: usize = if self.dims.is_empty() {
343            0
344        } else {
345            self.dims.iter().map(|d| d.size).product()
346        };
347        if self.data.len() != expected {
348            return Err(ADError::BufferSizeMismatch {
349                expected,
350                actual: self.data.len(),
351            });
352        }
353        Ok(())
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn test_element_size_all_types() {
363        assert_eq!(NDDataType::Int8.element_size(), 1);
364        assert_eq!(NDDataType::UInt8.element_size(), 1);
365        assert_eq!(NDDataType::Int16.element_size(), 2);
366        assert_eq!(NDDataType::UInt16.element_size(), 2);
367        assert_eq!(NDDataType::Int32.element_size(), 4);
368        assert_eq!(NDDataType::UInt32.element_size(), 4);
369        assert_eq!(NDDataType::Int64.element_size(), 8);
370        assert_eq!(NDDataType::UInt64.element_size(), 8);
371        assert_eq!(NDDataType::Float32.element_size(), 4);
372        assert_eq!(NDDataType::Float64.element_size(), 8);
373    }
374
375    #[test]
376    fn test_from_ordinal_roundtrip() {
377        for i in 0..10u8 {
378            let dt = NDDataType::from_ordinal(i).unwrap();
379            assert_eq!(dt as u8, i);
380        }
381        assert!(NDDataType::from_ordinal(10).is_none());
382    }
383
384    #[test]
385    fn test_buffer_zeros_type_and_len() {
386        let buf = NDDataBuffer::zeros(NDDataType::UInt16, 100);
387        assert_eq!(buf.data_type(), NDDataType::UInt16);
388        assert_eq!(buf.len(), 100);
389        assert_eq!(buf.total_bytes(), 200);
390    }
391
392    #[test]
393    fn test_buffer_zeros_all_types() {
394        for i in 0..10u8 {
395            let dt = NDDataType::from_ordinal(i).unwrap();
396            let buf = NDDataBuffer::zeros(dt, 10);
397            assert_eq!(buf.data_type(), dt);
398            assert_eq!(buf.len(), 10);
399            assert_eq!(buf.total_bytes(), 10 * dt.element_size());
400        }
401    }
402
403    #[test]
404    fn test_buffer_as_u8_slice() {
405        let buf = NDDataBuffer::U8(vec![1, 2, 3]);
406        assert_eq!(buf.as_u8_slice(), &[1, 2, 3]);
407    }
408
409    #[test]
410    fn test_ndarray_new_allocates() {
411        let dims = vec![NDDimension::new(256), NDDimension::new(256)];
412        let arr = NDArray::new(dims, NDDataType::UInt8);
413        assert_eq!(arr.data.len(), 256 * 256);
414        assert_eq!(arr.data.data_type(), NDDataType::UInt8);
415    }
416
417    #[test]
418    fn test_ndarray_validate_ok() {
419        let dims = vec![NDDimension::new(10), NDDimension::new(20)];
420        let arr = NDArray::new(dims, NDDataType::Float64);
421        arr.validate().unwrap();
422    }
423
424    #[test]
425    fn test_ndarray_validate_mismatch() {
426        let mut arr = NDArray::new(
427            vec![NDDimension::new(10), NDDimension::new(20)],
428            NDDataType::UInt8,
429        );
430        arr.data = NDDataBuffer::U8(vec![0; 100]);
431        assert!(arr.validate().is_err());
432    }
433
434    #[test]
435    fn test_ndarray_info_2d_mono() {
436        let dims = vec![NDDimension::new(640), NDDimension::new(480)];
437        let arr = NDArray::new(dims, NDDataType::UInt16);
438        let info = arr.info();
439        assert_eq!(info.x_size, 640);
440        assert_eq!(info.y_size, 480);
441        assert_eq!(info.color_size, 1);
442        assert_eq!(info.num_elements, 640 * 480);
443        assert_eq!(info.bytes_per_element, 2);
444        assert_eq!(info.total_bytes, 640 * 480 * 2);
445    }
446
447    #[test]
448    fn test_ndarray_info_3d_rgb() {
449        let dims = vec![
450            NDDimension::new(3),
451            NDDimension::new(640),
452            NDDimension::new(480),
453        ];
454        let arr = NDArray::new(dims, NDDataType::UInt8);
455        let info = arr.info();
456        assert_eq!(info.color_size, 3);
457        assert_eq!(info.x_size, 640);
458        assert_eq!(info.y_size, 480);
459        assert_eq!(info.num_elements, 3 * 640 * 480);
460    }
461
462    #[test]
463    fn test_ndarray_info_1d() {
464        let dims = vec![NDDimension::new(1024)];
465        let arr = NDArray::new(dims, NDDataType::Float64);
466        let info = arr.info();
467        assert_eq!(info.x_size, 1024);
468        assert_eq!(info.y_size, 1);
469        assert_eq!(info.color_size, 1);
470    }
471
472    #[test]
473    fn test_buffer_is_empty() {
474        let buf = NDDataBuffer::zeros(NDDataType::UInt8, 0);
475        assert!(buf.is_empty());
476        let buf2 = NDDataBuffer::zeros(NDDataType::UInt8, 1);
477        assert!(!buf2.is_empty());
478    }
479
480    #[test]
481    fn test_codec_field_preserved() {
482        let mut arr = NDArray::new(vec![NDDimension::new(10)], NDDataType::UInt8);
483        arr.codec = Some(Codec {
484            name: crate::codec::CodecName::JPEG,
485            compressed_size: 42,
486        });
487        let cloned = arr.clone();
488        assert_eq!(cloned.codec.as_ref().unwrap().compressed_size, 42);
489    }
490}