numrs2 0.3.0

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
use crate::array::Array;
use crate::error::{NumRs2Error, Result};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::Path;
use std::str::FromStr;

pub mod npy_npz;
pub mod text;

// Optional I/O format modules (feature-gated)
#[cfg(feature = "bson")]
pub mod bson_format;
#[cfg(feature = "matlab")]
pub mod matlab;
#[cfg(feature = "messagepack")]
pub mod messagepack;
#[cfg(feature = "netcdf")]
pub mod netcdf;
#[cfg(feature = "parquet")]
pub mod parquet;

pub use npy_npz::*;
pub use text::*;

// Re-export format-specific modules when features are enabled
#[cfg(feature = "bson")]
pub use bson_format::{from_bson_document, from_bson_file, to_bson_document, to_bson_file};
#[cfg(feature = "matlab")]
pub use matlab::{read_mat, write_mat};
#[cfg(feature = "messagepack")]
pub use messagepack::{
    from_messagepack, from_messagepack_bytes, to_messagepack, to_messagepack_bytes,
};
#[cfg(feature = "netcdf")]
pub use netcdf::{read_netcdf, write_netcdf};
#[cfg(feature = "parquet")]
pub use parquet::{read_parquet, write_parquet};

/// Module for input/output operations with NumRS arrays.
///
/// This module provides functionality for:
/// 1. Serializing/deserializing arrays to/from various formats
/// 2. Reading and writing arrays from/to files
/// 3. Converting between arrays and other data formats
///    
/// Internal representation of an Array for serialization
#[derive(Serialize, Deserialize)]
struct SerializedArray<T> {
    shape: Vec<usize>,
    data: Vec<T>,
}

/// Enum representing different serialization formats
#[derive(Clone, Copy, Debug)]
pub enum SerializeFormat {
    /// JSON format
    Json,
    /// CSV format
    Csv,
    /// Binary format (using oxicode)
    Binary,
    /// NumPy NPY format (*.npy)
    Npy,
    /// NumPy NPZ format (zipped NPY files, *.npz)
    Npz,
    /// Python pickle format (*.pkl)
    Pickle,
    /// Apache Parquet format (*.parquet) - requires "parquet" feature
    #[cfg(feature = "parquet")]
    Parquet,
    /// MessagePack format (*.msgpack) - requires "messagepack" feature
    #[cfg(feature = "messagepack")]
    MessagePack,
    /// BSON format (*.bson) - requires "bson" feature
    #[cfg(feature = "bson")]
    Bson,
    /// NetCDF-3 format (*.nc) - requires "netcdf" feature
    #[cfg(feature = "netcdf")]
    NetCdf,
    /// MATLAB .mat format (*.mat) - requires "matlab" feature
    #[cfg(feature = "matlab")]
    Matlab,
}

impl<T: Clone + Serialize> Array<T> {
    /// Serialize the array to a string in the specified format
    ///
    /// # Arguments
    ///
    /// * `format` - The format to serialize to
    ///
    /// # Returns
    ///
    /// A Result containing the serialized string or an error
    ///
    /// # Examples
    ///
    /// ```
    /// use numrs2::prelude::*;
    /// use numrs2::io::SerializeFormat;
    ///
    /// let array = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);
    /// let json = array.to_string(SerializeFormat::Json).expect("Failed to serialize to JSON");
    /// ```
    pub fn to_string(&self, format: SerializeFormat) -> Result<String> {
        let serialized = SerializedArray {
            shape: self.shape(),
            data: self.to_vec(),
        };

        match format {
            SerializeFormat::Json => serde_json::to_string(&serialized).map_err(|e| {
                NumRs2Error::SerializationError(format!("JSON serialization error: {}", e))
            }),
            SerializeFormat::Csv => {
                // For CSV, we'll just write the flattened data as there's no standard
                // for multidimensional arrays in CSV
                let mut writer = csv::Writer::from_writer(vec![]);
                let data = self.to_vec();
                writer.serialize(&data).map_err(|e| {
                    NumRs2Error::SerializationError(format!("CSV serialization error: {}", e))
                })?;

                let csv_bytes = writer.into_inner().map_err(|e| {
                    NumRs2Error::SerializationError(format!("CSV serialization error: {}", e))
                })?;

                String::from_utf8(csv_bytes).map_err(|e| {
                    NumRs2Error::SerializationError(format!("CSV serialization error: {}", e))
                })
            }
            SerializeFormat::Binary => Err(NumRs2Error::SerializationError(
                "Binary serialization to string not supported".to_string(),
            )),
            SerializeFormat::Npy => Err(NumRs2Error::SerializationError(
                "NPY format serialization to string not supported".to_string(),
            )),
            SerializeFormat::Npz => Err(NumRs2Error::SerializationError(
                "NPZ format serialization to string not supported".to_string(),
            )),
            SerializeFormat::Pickle => Err(NumRs2Error::SerializationError(
                "Pickle format serialization to string not supported (use to_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "parquet")]
            SerializeFormat::Parquet => Err(NumRs2Error::SerializationError(
                "Parquet format serialization to string not supported (use to_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "messagepack")]
            SerializeFormat::MessagePack => Err(NumRs2Error::SerializationError(
                "MessagePack format serialization to string not supported (use to_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "bson")]
            SerializeFormat::Bson => Err(NumRs2Error::SerializationError(
                "BSON format serialization to string not supported (use to_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "netcdf")]
            SerializeFormat::NetCdf => Err(NumRs2Error::SerializationError(
                "NetCDF format serialization to string not supported (use to_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "matlab")]
            SerializeFormat::Matlab => Err(NumRs2Error::SerializationError(
                "MATLAB format serialization to string not supported (use to_file instead)"
                    .to_string(),
            )),
        }
    }

    /// Serialize the array to a file in the specified format
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the file
    /// * `format` - The format to serialize to
    ///
    /// # Returns
    ///
    /// A Result indicating success or an error
    ///
    /// # Examples
    ///
    /// ```
    /// use numrs2::prelude::*;
    /// use numrs2::io::SerializeFormat;
    /// use std::path::Path;
    ///
    /// let array = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);
    /// // Uncomment to actually write to file:
    /// // array.to_file(Path::new("array.json"), SerializeFormat::Json).expect("Failed to write to file");
    /// ```
    pub fn to_file<P: AsRef<Path>>(&self, path: P, format: SerializeFormat) -> Result<()> {
        let file = File::create(path)
            .map_err(|e| NumRs2Error::IOError(format!("Failed to create file: {}", e)))?;
        let mut writer = BufWriter::new(file);

        let serialized = SerializedArray {
            shape: self.shape(),
            data: self.to_vec(),
        };

        match format {
            SerializeFormat::Json => {
                let json = serde_json::to_string(&serialized).map_err(|e| {
                    NumRs2Error::SerializationError(format!("JSON serialization error: {}", e))
                })?;
                writer
                    .write_all(json.as_bytes())
                    .map_err(|e| NumRs2Error::IOError(format!("Failed to write to file: {}", e)))?;
            }
            SerializeFormat::Csv => {
                let mut csv_writer = csv::Writer::from_writer(writer);
                for row in self.to_row_vectors()? {
                    csv_writer.serialize(row).map_err(|e| {
                        NumRs2Error::SerializationError(format!("CSV serialization error: {}", e))
                    })?;
                }
                csv_writer.flush().map_err(|e| {
                    NumRs2Error::IOError(format!("Failed to flush CSV writer: {}", e))
                })?;
            }
            SerializeFormat::Binary => {
                // oxicode API uses encode_to_std_write with a configuration.
                let config = oxicode::config::standard();
                oxicode::serde::encode_into_std_write(&serialized, &mut writer, config).map_err(
                    |e| {
                        NumRs2Error::SerializationError(format!(
                            "Binary serialization error: {}",
                            e
                        ))
                    },
                )?;
            }
            SerializeFormat::Npy | SerializeFormat::Npz => {
                // Delegate to the NPY/NPZ module
                npy_npz::serialize_to_file(self, &mut writer, format)?;
            }
            SerializeFormat::Pickle => {
                serde_pickle::to_writer(&mut writer, &serialized, serde_pickle::SerOptions::new())
                    .map_err(|e| {
                        NumRs2Error::SerializationError(format!(
                            "Pickle serialization error: {}",
                            e
                        ))
                    })?;
            }
            #[cfg(feature = "parquet")]
            SerializeFormat::Parquet => {
                return Err(NumRs2Error::SerializationError(
                    "Parquet format not yet implemented for Array serialization".to_string(),
                ));
            }
            #[cfg(feature = "messagepack")]
            SerializeFormat::MessagePack => {
                let bytes = to_messagepack_bytes(self)?;
                writer
                    .write_all(&bytes)
                    .map_err(|e| NumRs2Error::IOError(format!("Failed to write to file: {}", e)))?;
            }
            #[cfg(feature = "bson")]
            SerializeFormat::Bson => {
                return Err(NumRs2Error::SerializationError(
                    "BSON format: use to_bson_file() function instead".to_string(),
                ));
            }
            #[cfg(feature = "netcdf")]
            SerializeFormat::NetCdf => {
                return Err(NumRs2Error::SerializationError(
                    "NetCDF format: use write_netcdf() function instead".to_string(),
                ));
            }
            #[cfg(feature = "matlab")]
            SerializeFormat::Matlab => {
                return Err(NumRs2Error::SerializationError(
                    "MATLAB format: use write_mat() function instead".to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Convert the array to a vector of row vectors (for CSV export)
    ///
    /// # Returns
    ///
    /// A Result containing the rows or an error
    ///
    /// # Examples
    ///
    /// ```
    /// use numrs2::prelude::*;
    ///
    /// let array = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);
    /// let rows = array.to_row_vectors().expect("Failed to convert to row vectors");
    /// assert_eq!(rows, vec![vec![1, 2], vec![3, 4]]);
    /// ```
    pub fn to_row_vectors(&self) -> Result<Vec<Vec<T>>> {
        if self.ndim() == 1 {
            // For 1D arrays, return a single row
            return Ok(vec![self.to_vec()]);
        } else if self.ndim() == 2 {
            let shape = self.shape();
            let rows = shape[0];
            let cols = shape[1];
            let data = self.to_vec();

            let mut result = Vec::with_capacity(rows);
            for i in 0..rows {
                let mut row = Vec::with_capacity(cols);
                for j in 0..cols {
                    let idx = i * cols + j;
                    row.push(data[idx].clone());
                }
                result.push(row);
            }
            return Ok(result);
        }

        // For higher dimensional arrays, flatten to 2D first
        Err(NumRs2Error::DimensionMismatch(
            "Cannot convert arrays with more than 2 dimensions to CSV rows".to_string(),
        ))
    }
}

impl<T: Clone + for<'a> Deserialize<'a> + std::str::FromStr> Array<T>
where
    <T as FromStr>::Err: std::fmt::Debug,
{
    /// Deserialize an array from a string
    ///
    /// # Arguments
    ///
    /// * `s` - The string to deserialize from
    /// * `format` - The format of the string
    ///
    /// # Returns
    ///
    /// A Result containing the deserialized array or an error
    ///
    /// # Examples
    ///
    /// ```
    /// use numrs2::prelude::*;
    /// use numrs2::io::SerializeFormat;
    ///
    /// let json = r#"{"shape":[2,2],"data":[1,2,3,4]}"#;
    /// let array = Array::<i32>::from_string(json, SerializeFormat::Json).expect("Failed to deserialize from JSON");
    /// assert_eq!(array.shape(), vec![2, 2]);
    /// assert_eq!(array.to_vec(), vec![1, 2, 3, 4]);
    /// ```
    pub fn from_string(s: &str, format: SerializeFormat) -> Result<Self> {
        match format {
            SerializeFormat::Json => {
                let serialized: SerializedArray<T> = serde_json::from_str(s).map_err(|e| {
                    NumRs2Error::DeserializationError(format!("JSON deserialization error: {}", e))
                })?;

                Ok(Array::from_vec(serialized.data).reshape(&serialized.shape))
            }
            SerializeFormat::Csv => {
                let mut reader = csv::ReaderBuilder::new()
                    .has_headers(false)
                    .from_reader(s.as_bytes());
                let mut data = Vec::new();

                for result in reader.records() {
                    let record = result.map_err(|e| {
                        NumRs2Error::DeserializationError(format!("CSV reading error: {}", e))
                    })?;

                    for field in record.iter() {
                        let value = field.parse::<T>().map_err(|_| {
                            NumRs2Error::DeserializationError(format!(
                                "Failed to parse CSV field: {}",
                                field
                            ))
                        })?;
                        data.push(value);
                    }
                }

                // For CSV, we assume 1D array since we don't have shape information
                Ok(Array::from_vec(data))
            }
            SerializeFormat::Binary => Err(NumRs2Error::DeserializationError(
                "Binary deserialization from string not supported".to_string(),
            )),
            SerializeFormat::Npy => Err(NumRs2Error::DeserializationError(
                "NPY format deserialization from string not supported".to_string(),
            )),
            SerializeFormat::Npz => Err(NumRs2Error::DeserializationError(
                "NPZ format deserialization from string not supported".to_string(),
            )),
            SerializeFormat::Pickle => Err(NumRs2Error::DeserializationError(
                "Pickle format deserialization from string not supported (use from_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "parquet")]
            SerializeFormat::Parquet => Err(NumRs2Error::DeserializationError(
                "Parquet format deserialization from string not supported (use from_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "messagepack")]
            SerializeFormat::MessagePack => Err(NumRs2Error::DeserializationError(
                "MessagePack format deserialization from string not supported (use from_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "bson")]
            SerializeFormat::Bson => Err(NumRs2Error::DeserializationError(
                "BSON format deserialization from string not supported (use from_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "netcdf")]
            SerializeFormat::NetCdf => Err(NumRs2Error::DeserializationError(
                "NetCDF format deserialization from string not supported (use from_file instead)"
                    .to_string(),
            )),
            #[cfg(feature = "matlab")]
            SerializeFormat::Matlab => Err(NumRs2Error::DeserializationError(
                "MATLAB format deserialization from string not supported (use from_file instead)"
                    .to_string(),
            )),
        }
    }

    /// Deserialize an array from a file
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the file
    /// * `format` - The format of the file
    ///
    /// # Returns
    ///
    /// A Result containing the deserialized array or an error
    ///
    /// # Examples
    ///
    /// ```
    /// use numrs2::prelude::*;
    /// use numrs2::io::SerializeFormat;
    /// use std::path::Path;
    ///
    /// // Uncomment to actually read from file:
    /// // let array = Array::<i32>::from_file(Path::new("array.json"), SerializeFormat::Json).expect("Failed to read from file");
    /// ```
    pub fn from_file<P: AsRef<Path>>(path: P, format: SerializeFormat) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| NumRs2Error::IOError(format!("Failed to open file: {}", e)))?;
        let reader = BufReader::new(file);

        match format {
            SerializeFormat::Json => {
                let serialized: SerializedArray<T> =
                    serde_json::from_reader(reader).map_err(|e| {
                        NumRs2Error::DeserializationError(format!(
                            "JSON deserialization error: {}",
                            e
                        ))
                    })?;

                Ok(Array::from_vec(serialized.data).reshape(&serialized.shape))
            }
            SerializeFormat::Csv => {
                let mut csv_reader = csv::ReaderBuilder::new()
                    .has_headers(false)
                    .from_reader(reader);
                // Read all rows first to determine shape
                let mut all_rows: Vec<Vec<T>> = Vec::new();

                for result in csv_reader.records() {
                    let record = result.map_err(|e| {
                        NumRs2Error::DeserializationError(format!("CSV reading error: {}", e))
                    })?;

                    // Parse each field in the record
                    let mut row = Vec::new();
                    for field in record.iter() {
                        let value = field.parse::<T>().map_err(|_| {
                            NumRs2Error::DeserializationError(format!(
                                "Failed to parse CSV field: {}",
                                field
                            ))
                        })?;
                        row.push(value);
                    }
                    all_rows.push(row);
                }

                if all_rows.is_empty() {
                    return Err(NumRs2Error::DeserializationError(
                        "CSV file contained no data".to_string(),
                    ));
                }

                // Check if all rows have the same length
                let row_length = all_rows[0].len();
                for (i, row) in all_rows.iter().enumerate().skip(1) {
                    if row.len() != row_length {
                        return Err(NumRs2Error::DeserializationError(
                            format!("CSV file has inconsistent row lengths: row 0 has length {}, row {} has length {}", 
                                    row_length, i, row.len())
                        ));
                    }
                }

                // Store the rows count before moving the data
                let rows_count = all_rows.len();

                // Flatten the rows into a single vector
                let mut data = Vec::with_capacity(rows_count * row_length);
                for row in all_rows {
                    data.extend(row);
                }

                // Create a 2D array with the appropriate shape
                Ok(Array::from_vec(data).reshape(&[rows_count, row_length]))
            }
            SerializeFormat::Binary => {
                let config = oxicode::config::standard();
                let mut reader = reader; // make mutable for API
                let (serialized, _len): (SerializedArray<T>, usize) =
                    oxicode::serde::decode_from_std_read(&mut reader, config).map_err(|e| {
                        NumRs2Error::DeserializationError(format!(
                            "Binary deserialization error: {}",
                            e
                        ))
                    })?;

                Ok(Array::from_vec(serialized.data).reshape(&serialized.shape))
            }
            SerializeFormat::Npy | SerializeFormat::Npz => {
                // Delegate to the NPY/NPZ module for these formats
                npy_npz::deserialize_from_file(reader, format)
            }
            SerializeFormat::Pickle => {
                let serialized: SerializedArray<T> =
                    serde_pickle::from_reader(reader, serde_pickle::DeOptions::new()).map_err(
                        |e| {
                            NumRs2Error::DeserializationError(format!(
                                "Pickle deserialization error: {}",
                                e
                            ))
                        },
                    )?;

                Ok(Array::from_vec(serialized.data).reshape(&serialized.shape))
            }
            #[cfg(feature = "parquet")]
            SerializeFormat::Parquet => Err(NumRs2Error::DeserializationError(
                "Parquet format not yet implemented for Array deserialization".to_string(),
            )),
            #[cfg(feature = "messagepack")]
            SerializeFormat::MessagePack => {
                use std::io::Read;
                let mut bytes = Vec::new();
                let mut reader = reader;
                reader
                    .read_to_end(&mut bytes)
                    .map_err(|e| NumRs2Error::IOError(format!("Failed to read file: {}", e)))?;
                from_messagepack_bytes(&bytes)
            }
            #[cfg(feature = "bson")]
            SerializeFormat::Bson => Err(NumRs2Error::DeserializationError(
                "BSON format: use from_bson_file() function instead".to_string(),
            )),
            #[cfg(feature = "netcdf")]
            SerializeFormat::NetCdf => Err(NumRs2Error::DeserializationError(
                "NetCDF format: use read_netcdf() function instead".to_string(),
            )),
            #[cfg(feature = "matlab")]
            SerializeFormat::Matlab => Err(NumRs2Error::DeserializationError(
                "MATLAB format: use read_mat() function instead".to_string(),
            )),
        }
    }
}

// Conversion functions for standard Rust data structures

/// Convert a Vec to an Array
///
/// # Arguments
///
/// * `vec` - The vector to convert
/// * `shape` - Optional shape for the resulting array. If not provided, a 1D array is created.
///
/// # Returns
///
/// A new Array containing the vector's data
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::io::vec_to_array;
///
/// let vec = vec![1, 2, 3, 4];
/// let array = vec_to_array(vec, Some(&[2, 2])).expect("Failed to convert vec to array");
/// assert_eq!(array.shape(), vec![2, 2]);
/// ```
pub fn vec_to_array<T: Clone>(vec: Vec<T>, shape: Option<&[usize]>) -> Result<Array<T>> {
    let array = Array::from_vec(vec);
    match shape {
        Some(shape) => Ok(array.reshape(shape)),
        None => Ok(array),
    }
}

/// Convert a 2D Vec (`Vec<Vec<T>>`) to an Array
///
/// # Arguments
///
/// * `vec` - The 2D vector to convert
///
/// # Returns
///
/// A new 2D Array containing the vector's data
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::io::vec2d_to_array;
///
/// let vec = vec![vec![1, 2], vec![3, 4]];
/// let array = vec2d_to_array(vec).expect("Failed to convert 2D vec to array");
/// assert_eq!(array.shape(), vec![2, 2]);
/// ```
pub fn vec2d_to_array<T: Clone>(vec: Vec<Vec<T>>) -> Result<Array<T>> {
    if vec.is_empty() {
        return Ok(Array::from_vec(Vec::new()));
    }

    let rows = vec.len();
    let cols = vec[0].len();

    // Check that all rows have the same length
    for (i, row) in vec.iter().enumerate() {
        if row.len() != cols {
            return Err(NumRs2Error::DimensionMismatch(format!(
                "Row 0 has length {}, but row {} has length {}",
                cols,
                i,
                row.len()
            )));
        }
    }

    // Flatten the 2D vector into a 1D vector
    let mut data = Vec::with_capacity(rows * cols);
    for row in vec {
        data.extend(row);
    }

    // Create a 2D array with the appropriate shape
    Ok(Array::from_vec(data).reshape(&[rows, cols]))
}

/// Convert an Array to a 2D Vec (`Vec<Vec<T>>`)
///
/// # Arguments
///
/// * `array` - The array to convert
///
/// # Returns
///
/// A 2D vector containing the array's data
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::io::array_to_vec2d;
///
/// let array = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);
/// let vec = array_to_vec2d(&array).expect("Failed to convert array to 2D vec");
/// assert_eq!(vec, vec![vec![1, 2], vec![3, 4]]);
/// ```
pub fn array_to_vec2d<T: Clone>(array: &Array<T>) -> Result<Vec<Vec<T>>> {
    if array.ndim() != 2 {
        return Err(NumRs2Error::DimensionMismatch(format!(
            "Expected 2D array, got {}D",
            array.ndim()
        )));
    }

    let shape = array.shape();
    let rows = shape[0];
    let cols = shape[1];
    let data = array.to_vec();

    let mut result = Vec::with_capacity(rows);
    for i in 0..rows {
        let mut row = Vec::with_capacity(cols);
        for j in 0..cols {
            let idx = i * cols + j;
            row.push(data[idx].clone());
        }
        result.push(row);
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_json_serialization() {
        let array = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);
        let json = array
            .to_string(SerializeFormat::Json)
            .expect("Failed to serialize to JSON");
        let expected = r#"{"shape":[2,2],"data":[1,2,3,4]}"#;
        assert_eq!(json, expected);

        let deserialized = Array::<i32>::from_string(&json, SerializeFormat::Json)
            .expect("Failed to deserialize from JSON");
        assert_eq!(deserialized.shape(), vec![2, 2]);
        assert_eq!(deserialized.to_vec(), vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_vec_to_array() {
        let vec = vec![1, 2, 3, 4];
        let array = vec_to_array(vec, Some(&[2, 2])).expect("Failed to convert vec to array");
        assert_eq!(array.shape(), vec![2, 2]);
        assert_eq!(array.to_vec(), vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_vec2d_to_array() {
        let vec = vec![vec![1, 2], vec![3, 4]];
        let array = vec2d_to_array(vec).expect("Failed to convert 2D vec to array");
        assert_eq!(array.shape(), vec![2, 2]);
        assert_eq!(array.to_vec(), vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_array_to_vec2d() {
        let array = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);
        let vec = array_to_vec2d(&array).expect("Failed to convert array to 2D vec");
        assert_eq!(vec, vec![vec![1, 2], vec![3, 4]]);
    }

    #[test]
    fn test_csv_serialization() {
        let array = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);
        let rows = array
            .to_row_vectors()
            .expect("Failed to convert to row vectors");
        assert_eq!(rows, vec![vec![1, 2], vec![3, 4]]);
    }
}