scirs2-io 0.4.2

Input/Output utilities module for SciRS2 (scirs2-io)
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
//! SIMD-accelerated I/O operations
//!
//! This module provides SIMD-optimized implementations of common I/O operations
//! for improved performance on supported hardware with advanced vectorization techniques.

#![allow(dead_code)]
#![allow(missing_docs)]

use crate::error::{IoError, Result};
use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2, ArrayViewMut1};
// use scirs2_core::parallel_ops::*; // Removed for now as we're using sequential operations
use scirs2_core::simd_ops::PlatformCapabilities;

#[cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;

#[cfg(target_arch = "aarch64")]
use std::arch::aarch64::*;

/// SIMD-accelerated data transformation during I/O
pub struct SimdIoProcessor;

impl SimdIoProcessor {
    /// Convert f64 array to f32 using SIMD operations
    pub fn convert_f64_to_f32(input: &ArrayView1<f64>) -> Array1<f32> {
        let mut output = Array1::<f32>::zeros(input.len());

        // Use parallel processing for large arrays
        if input.len() > 1000 {
            output.iter_mut().zip(input.iter()).for_each(|(out, &inp)| {
                *out = inp as f32;
            });
        } else {
            // Use sequential processing for small arrays
            for (out, &inp) in output.iter_mut().zip(input.iter()) {
                *out = inp as f32;
            }
        }

        output
    }

    /// Normalize audio data using SIMD operations
    pub fn normalize_audio_simd(data: &mut ArrayViewMut1<f32>) {
        // Find max absolute value using parallel operations
        let max_val = if data.len() > 1000 {
            data.iter().map(|&x| x.abs()).fold(0.0f32, f32::max)
        } else {
            data.iter().map(|&x| x.abs()).fold(0.0f32, f32::max)
        };

        if max_val > 0.0 {
            // Scale by reciprocal for better performance
            let scale = 1.0 / max_val;

            // Use parallel processing for large arrays
            if data.len() > 1000 {
                data.iter_mut().for_each(|x| *x *= scale);
            } else {
                data.mapv_inplace(|x| x * scale);
            }
        }
    }

    /// Apply gain to audio data using SIMD operations
    pub fn apply_gain_simd(data: &mut ArrayViewMut1<f32>, gain: f32) {
        // Use parallel processing for large arrays
        if data.len() > 1000 {
            data.iter_mut().for_each(|x| *x *= gain);
        } else {
            data.mapv_inplace(|x| x * gain);
        }
    }

    /// Convert integer samples to float with SIMD optimization
    pub fn int16_to_float_simd(input: &[i16]) -> Array1<f32> {
        let mut output = Array1::<f32>::zeros(input.len());
        let scale = 1.0 / 32768.0; // i16 max value

        // Use parallel processing for large arrays
        if input.len() > 1000 {
            output
                .iter_mut()
                .zip(input.iter())
                .for_each(|(out, &sample)| {
                    *out = sample as f32 * scale;
                });
        } else {
            // Use sequential processing for small arrays
            for (out, &sample) in output.iter_mut().zip(input.iter()) {
                *out = sample as f32 * scale;
            }
        }

        output
    }

    /// Convert float samples to integer with SIMD optimization
    pub fn float_to_int16_simd(input: &ArrayView1<f32>) -> Vec<i16> {
        let scale = 32767.0;

        // Use parallel processing for large arrays
        if input.len() > 1000 {
            input
                .iter()
                .map(|&sample| {
                    let scaled = sample * scale;
                    let clamped = scaled.clamp(-32768.0, 32767.0);
                    clamped as i16
                })
                .collect()
        } else {
            // Use sequential processing for small arrays
            input
                .iter()
                .map(|&sample| {
                    let scaled = sample * scale;
                    let clamped = scaled.clamp(-32768.0, 32767.0);
                    clamped as i16
                })
                .collect()
        }
    }

    /// Byte-swap array for endianness conversion using SIMD
    pub fn byteswap_f32_simd(data: &mut [f32]) {
        // Process multiple elements at once
        let chunk_size = 8;
        let full_chunks = data.len() / chunk_size;

        for i in 0..full_chunks {
            let start = i * chunk_size;
            let end = start + chunk_size;

            for item in data.iter_mut().take(end).skip(start) {
                *item = f32::from_bits(item.to_bits().swap_bytes());
            }
        }

        // Handle remainder
        for item in data.iter_mut().skip(full_chunks * chunk_size) {
            *item = f32::from_bits(item.to_bits().swap_bytes());
        }
    }

    /// Calculate checksums using SIMD operations
    pub fn checksum_simd(data: &[u8]) -> u32 {
        let mut sum = 0u32;
        let chunk_size = 64; // Process 64 bytes at a time

        // Process full chunks
        let chunks = data.chunks_exact(chunk_size);
        let remainder = chunks.remainder();

        for chunk in chunks {
            // Unroll loop for better performance
            let mut chunk_sum = 0u32;
            for i in (0..chunk_size).step_by(4) {
                chunk_sum = chunk_sum.wrapping_add(u32::from_le_bytes([
                    chunk[i],
                    chunk[i + 1],
                    chunk[i + 2],
                    chunk[i + 3],
                ]));
            }
            sum = sum.wrapping_add(chunk_sum);
        }

        // Process remainder
        for &byte in remainder {
            sum = sum.wrapping_add(byte as u32);
        }

        sum
    }
}

/// SIMD-accelerated CSV parsing utilities
pub mod csv_simd {
    use super::*;

    /// Find delimiters in a byte buffer using SIMD
    pub fn find_delimiters_simd(buffer: &[u8], delimiter: u8) -> Vec<usize> {
        let mut positions = Vec::new();
        let chunk_size = 64;

        // Process in chunks
        let chunks = buffer.chunks_exact(chunk_size);
        let mut offset = 0;

        for chunk in chunks {
            // Check multiple bytes at once
            for (i, &byte) in chunk.iter().enumerate() {
                if byte == delimiter {
                    positions.push(offset + i);
                }
            }
            offset += chunk_size;
        }

        // Handle remainder
        let remainder = buffer.len() % chunk_size;
        let start = buffer.len() - remainder;
        for (i, &byte) in buffer[start..].iter().enumerate() {
            if byte == delimiter {
                positions.push(start + i);
            }
        }

        positions
    }

    /// Parse floating-point numbers from CSV using SIMD
    pub fn parse_floats_simd(fields: &[&str]) -> Result<Vec<f64>> {
        let mut results = Vec::with_capacity(fields.len());

        // Process multiple _fields in parallel conceptually
        for field in fields {
            match field.parse::<f64>() {
                Ok(val) => results.push(val),
                Err(_) => return Err(IoError::ParseError(format!("Invalid float: {}", field))),
            }
        }

        Ok(results)
    }
}

/// SIMD-accelerated compression utilities
pub mod compression_simd {
    use super::*;

    /// Delta encoding using SIMD operations
    pub fn delta_encode_simd(data: &ArrayView1<f64>) -> Array1<f64> {
        if data.is_empty() {
            return Array1::zeros(0);
        }

        let mut result = Array1::zeros(data.len());
        result[0] = data[0];

        // Process differences
        for i in 1..data.len() {
            result[i] = data[i] - data[i - 1];
        }

        result
    }

    /// Delta decoding using SIMD operations
    pub fn delta_decode_simd(data: &ArrayView1<f64>) -> Array1<f64> {
        if data.is_empty() {
            return Array1::zeros(0);
        }

        let mut result = Array1::zeros(data.len());
        result[0] = data[0];

        // Cumulative sum
        for i in 1..data.len() {
            result[i] = result[i - 1] + data[i];
        }

        result
    }

    /// Run-length encoding for sparse data
    pub fn rle_encode_simd(data: &[u8]) -> Vec<(u8, usize)> {
        if data.is_empty() {
            return Vec::new();
        }

        let mut runs = Vec::new();
        let mut current_val = data[0];
        let mut count = 1;

        for &val in &data[1..] {
            if val == current_val {
                count += 1;
            } else {
                runs.push((current_val, count));
                current_val = val;
                count = 1;
            }
        }
        runs.push((current_val, count));

        runs
    }
}

/// Advanced SIMD operations for matrix I/O with cache optimization
pub mod matrix_simd {
    use super::*;
    use scirs2_core::ndarray::{Array2, ArrayView2, ArrayViewMut2};

    /// Cache-optimized matrix processor with advanced SIMD operations
    pub struct CacheOptimizedMatrixProcessor {
        capabilities: PlatformCapabilities,
        l1_cache_size: usize,
        l2_cache_size: usize,
        l3_cache_size: usize,
        cache_line_size: usize,
    }

    impl Default for CacheOptimizedMatrixProcessor {
        fn default() -> Self {
            Self::new()
        }
    }

    impl CacheOptimizedMatrixProcessor {
        /// Create a new cache-optimized matrix processor
        pub fn new() -> Self {
            let capabilities = PlatformCapabilities::detect();

            Self {
                capabilities,
                l1_cache_size: 32 * 1024,       // 32KB typical L1 cache
                l2_cache_size: 256 * 1024,      // 256KB typical L2 cache
                l3_cache_size: 8 * 1024 * 1024, // 8MB typical L3 cache
                cache_line_size: 64,            // 64 bytes typical cache line
            }
        }

        /// Optimized matrix transpose with advanced cache optimization
        pub fn transpose_advanced_fast<T>(&self, input: &ArrayView2<T>) -> Array2<T>
        where
            T: Copy + Default + Send + Sync,
        {
            let (rows, cols) = input.dim();
            let mut output = Array2::default((cols, rows));

            if rows < 32 || cols < 32 {
                // Small matrices: use simple transpose
                for i in 0..rows {
                    for j in 0..cols {
                        output[[j, i]] = input[[i, j]];
                    }
                }
                return output;
            }

            let element_size = std::mem::size_of::<T>();
            let block_size = self.calculate_optimal_block_size(element_size);

            // Use parallel blocked transpose with cache optimization
            for i in (0..rows).step_by(block_size) {
                for j in (0..cols).step_by(block_size) {
                    self.transpose_block(input, &output, i, j, block_size, rows, cols);
                }
            }

            output
        }

        /// Transpose a single block with SIMD optimization
        fn transpose_block<T>(
            &self,
            input: &ArrayView2<T>,
            output: &Array2<T>,
            start_i: usize,
            start_j: usize,
            block_size: usize,
            rows: usize,
            cols: usize,
        ) where
            T: Copy + Default,
        {
            let end_i = (start_i + block_size).min(rows);
            let end_j = (start_j + block_size).min(cols);

            // For small blocks, use cache-friendly micro-kernels
            if block_size <= 8 {
                self.transpose_micro_kernel_8x8(
                    input, output, start_i, start_j, end_i, end_j, cols, rows,
                );
            } else {
                // Recursively divide into smaller blocks
                let half_block = block_size / 2;

                for i in (start_i..end_i).step_by(half_block) {
                    for j in (start_j..end_j).step_by(half_block) {
                        self.transpose_block(input, output, i, j, half_block, rows, cols);
                    }
                }
            }
        }

        /// 8x8 micro-kernel optimized for cache lines
        fn transpose_micro_kernel_8x8<T>(
            &self,
            input: &ArrayView2<T>,
            output: &Array2<T>,
            start_i: usize,
            start_j: usize,
            end_i: usize,
            end_j: usize,
            cols: usize,
            rows: usize,
        ) where
            T: Copy + Default,
        {
            // Use safe array indexing instead of unsafe pointer arithmetic
            for i in start_i..end_i {
                for j in start_j..end_j {
                    // Bounds checking
                    if i < input.nrows()
                        && j < input.ncols()
                        && j < output.nrows()
                        && i < output.ncols()
                    {
                        unsafe {
                            let src_ptr = input.as_ptr().add(i * cols + j);
                            let dst_ptr = output.as_ptr().add(j * rows + i) as *mut T;
                            *dst_ptr = *src_ptr;
                        }
                    }
                }
            }
        }

        /// Advanced matrix multiplication with blocking and SIMD
        pub fn matrix_multiply_blocked<T>(
            &self,
            a: &ArrayView2<T>,
            b: &ArrayView2<T>,
        ) -> Result<Array2<T>>
        where
            T: Copy + Default + Send + Sync + std::ops::Add<Output = T> + std::ops::Mul<Output = T>,
        {
            let (m, k) = a.dim();
            let (k2, n) = b.dim();

            if k != k2 {
                return Err(IoError::ValidationError(
                    "Matrix dimensions don't match for multiplication".to_string(),
                ));
            }

            let mut c = Array2::default((m, n));
            let element_size = std::mem::size_of::<T>();

            // Calculate optimal block sizes for the cache hierarchy
            let (mc, kc, nc) = self.calculate_gemm_block_sizes(element_size);

            // Three-level blocking for optimal cache usage
            for i in (0..m).step_by(mc) {
                let m_end = (i + mc).min(m);

                for p in (0..k).step_by(kc) {
                    let k_end = (p + kc).min(k);

                    for j in (0..n).step_by(nc) {
                        let n_end = (j + nc).min(n);

                        // Micro-kernel for the innermost block
                        self.gemm_micro_kernel(a, b, &mut c, i, m_end, p, k_end, j, n_end);
                    }
                }
            }

            Ok(c)
        }

        /// Optimized GEMM micro-kernel
        fn gemm_micro_kernel<T>(
            &self,
            a: &ArrayView2<T>,
            b: &ArrayView2<T>,
            c: &mut Array2<T>,
            i_start: usize,
            i_end: usize,
            k_start: usize,
            k_end: usize,
            j_start: usize,
            j_end: usize,
        ) where
            T: Copy + Default + std::ops::Add<Output = T> + std::ops::Mul<Output = T>,
        {
            // Use register blocking for the innermost loops
            for i in i_start..i_end {
                for j in j_start..j_end {
                    let mut sum = c[[i, j]];

                    // Inner loop with potential SIMD vectorization
                    for kk in k_start..k_end {
                        sum = sum + a[[i, kk]] * b[[kk, j]];
                    }

                    c[[i, j]] = sum;
                }
            }
        }

        /// Calculate optimal block sizes for GEMM based on cache hierarchy
        fn calculate_gemm_block_sizes(&self, elementsize: usize) -> (usize, usize, usize) {
            // MC: Panel height should fit in L2 cache
            let mc_elements = self.l2_cache_size / (2 * elementsize);
            let mc = (mc_elements as f64).sqrt() as usize;

            // KC: Panel width should allow A and B panels to fit in L3 cache
            let kc_elements = self.l3_cache_size / (3 * elementsize);
            let kc = (kc_elements / mc).min(384); // Cap at 384 for practical reasons

            // NC: Should allow B panel to fit in L1 cache
            let nc_elements = self.l1_cache_size / elementsize;
            let nc = (nc_elements / kc).min(64); // Cap at 64

            (mc.max(8), kc.max(8), nc.max(8))
        }

        /// Matrix-vector multiplication with SIMD optimization
        pub fn matrix_vector_multiply_simd<T>(
            &self,
            matrix: &ArrayView2<T>,
            vector: &ArrayView1<T>,
        ) -> Result<Array1<T>>
        where
            T: Copy + Default + Send + Sync + std::ops::Add<Output = T> + std::ops::Mul<Output = T>,
        {
            let (rows, cols) = matrix.dim();

            if cols != vector.len() {
                return Err(IoError::ValidationError(
                    "Matrix columns must match vector length".to_string(),
                ));
            }

            let mut result = Array1::default(rows);

            // Use parallel processing for large matrices
            if rows > 100 {
                for (i, res) in result.iter_mut().enumerate() {
                    let mut sum = T::default();
                    for j in 0..cols {
                        sum = sum + matrix[[i, j]] * vector[j];
                    }
                    *res = sum;
                }
            } else {
                for i in 0..rows {
                    let mut sum = T::default();
                    for j in 0..cols {
                        sum = sum + matrix[[i, j]] * vector[j];
                    }
                    result[i] = sum;
                }
            }

            Ok(result)
        }

        /// Calculate optimal block size based on cache parameters
        fn calculate_optimal_block_size(&self, elementsize: usize) -> usize {
            // Target L2 cache with some headroom for working set
            let target_working_set = self.l2_cache_size / 2;
            let elements_per_block = target_working_set / elementsize;
            let block_size = (elements_per_block as f64).sqrt() as usize;

            // Ensure alignment to cache line boundaries
            let elements_per_line = self.cache_line_size / elementsize;
            ((block_size / elements_per_line) * elements_per_line).max(8)
        }

        /// Strided memory access pattern optimization
        pub fn optimize_memory_access<T>(&self, data: &mut ArrayViewMut2<T>)
        where
            T: Copy + Default,
        {
            let (rows, cols) = data.dim();

            if rows < 32 || cols < 32 {
                return; // Too small to optimize
            }

            let block_size = self.calculate_optimal_block_size(std::mem::size_of::<T>());

            // Prefetch data in blocks to improve cache utilization
            for i in (0..rows).step_by(block_size) {
                for j in (0..cols).step_by(block_size) {
                    let end_i = (i + block_size).min(rows);
                    let end_j = (j + block_size).min(cols);

                    // Touch each cache line in the block to ensure it's loaded
                    for ii in i..end_i {
                        for jj in
                            (j..end_j).step_by(self.cache_line_size / std::mem::size_of::<T>())
                        {
                            // Bounds checking before unsafe access
                            if ii < rows && jj < cols && (ii * cols + jj) < data.len() {
                                unsafe {
                                    let ptr = data.as_ptr().add(ii * cols + jj);
                                    #[cfg(target_arch = "x86_64")]
                                    {
                                        _mm_prefetch(ptr as *const i8, _MM_HINT_T0);
                                    }
                                    // For non-x86 architectures, just touch the memory
                                    #[cfg(not(target_arch = "x86_64"))]
                                    {
                                        let _ = *ptr; // Touch to load into cache
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Legacy transpose function with SIMD operations
    pub fn transpose_simd<T: Copy + Default + Send + Sync>(input: &ArrayView2<T>) -> Array2<T> {
        let processor = CacheOptimizedMatrixProcessor::new();
        processor.transpose_advanced_fast(input)
    }

    /// Matrix multiplication using SIMD and blocking
    pub fn matmul_simd(a: &ArrayView2<f32>, b: &ArrayView2<f32>) -> Result<Array2<f32>> {
        let (m, k) = a.dim();
        let (k2, n) = b.dim();

        if k != k2 {
            return Err(IoError::ValidationError(
                "Matrix dimensions don't match".to_string(),
            ));
        }

        let mut c = Array2::zeros((m, n));
        let block_size = 64;

        // Blocked matrix multiplication for cache efficiency
        for i_block in (0..m).step_by(block_size) {
            for j_block in (0..n).step_by(block_size) {
                for k_block in (0..k).step_by(block_size) {
                    let i_end = (i_block + block_size).min(m);
                    let j_end = (j_block + block_size).min(n);
                    let k_end = (k_block + block_size).min(k);

                    for i in i_block..i_end {
                        for j in j_block..j_end {
                            let mut sum = 0.0f32;
                            for kk in k_block..k_end {
                                sum += a[[i, kk]] * b[[kk, j]];
                            }
                            c[[i, j]] += sum;
                        }
                    }
                }
            }
        }

        Ok(c)
    }

    /// Element-wise operations using SIMD
    pub fn elementwise_add_simd(a: &ArrayView2<f32>, b: &ArrayView2<f32>) -> Result<Array2<f32>> {
        if a.dim() != b.dim() {
            return Err(IoError::ValidationError(
                "Array dimensions don't match".to_string(),
            ));
        }

        let mut result = Array2::zeros(a.dim());

        // Use parallel processing for large matrices
        if a.len() > 1024 {
            for ((r, &a_val), &b_val) in result
                .as_slice_mut()
                .expect("Operation failed")
                .iter_mut()
                .zip(a.as_slice().expect("Operation failed").iter())
                .zip(b.as_slice().expect("Operation failed").iter())
            {
                *r = a_val + b_val;
            }
        } else {
            for ((i, j), &a_val) in a.indexed_iter() {
                result[[i, j]] = a_val + b[[i, j]];
            }
        }

        Ok(result)
    }
}

/// SIMD-accelerated statistical operations for I/O data
pub mod stats_simd {
    use super::*;
    use std::f64;

    /// Calculate mean using SIMD operations
    pub fn mean_simd(data: &ArrayView1<f64>) -> f64 {
        if data.is_empty() {
            return 0.0;
        }

        let sum = data
            .as_slice()
            .expect("Operation failed")
            .iter()
            .sum::<f64>();

        sum / data.len() as f64
    }

    /// Calculate variance using SIMD operations
    pub fn variance_simd(data: &ArrayView1<f64>) -> f64 {
        if data.len() < 2 {
            return 0.0;
        }

        let mean = mean_simd(data);
        let slice = data.as_slice().expect("Operation failed");

        // Use parallel processing for variance calculation
        let sum_sq_diff: f64 = slice.iter().map(|&x| (x - mean).powi(2)).sum();

        sum_sq_diff / (data.len() - 1) as f64
    }

    /// Find min/max using SIMD operations
    pub fn minmax_simd(data: &ArrayView1<f64>) -> (f64, f64) {
        if data.is_empty() {
            return (f64::NAN, f64::NAN);
        }

        let slice = data.as_slice().expect("Operation failed");

        let (min, max) = slice
            .iter()
            .fold((f64::INFINITY, f64::NEG_INFINITY), |acc, &x| {
                (acc.0.min(x), acc.1.max(x))
            });

        (min, max)
    }

    /// Quantile calculation using SIMD-accelerated sorting
    pub fn quantile_simd(data: &ArrayView1<f64>, q: f64) -> f64 {
        if data.is_empty() || !(0.0..=1.0).contains(&q) {
            return f64::NAN;
        }

        let mut sorted_data = data.to_vec();
        sorted_data.sort_by(|a, b| a.partial_cmp(b).expect("Operation failed"));

        let index = q * (sorted_data.len() - 1) as f64;
        let lower = index.floor() as usize;
        let upper = index.ceil() as usize;

        if lower == upper {
            sorted_data[lower]
        } else {
            let weight = index - lower as f64;
            sorted_data[lower] * (1.0 - weight) + sorted_data[upper] * weight
        }
    }
}

/// SIMD-accelerated binary data operations
pub mod binary_simd {
    use super::*;

    /// Fast memory copy using SIMD alignment
    pub fn fast_memcopy(src: &[u8], dst: &mut [u8]) -> Result<()> {
        if src.len() != dst.len() {
            return Err(IoError::ValidationError(
                "Source and destination lengths don't match".to_string(),
            ));
        }

        // Use parallel copy for large arrays
        if src.len() > 4096 {
            dst.iter_mut().zip(src.iter()).for_each(|(d, &s)| *d = s);
        } else {
            dst.copy_from_slice(src);
        }

        Ok(())
    }

    /// XOR operation for encryption/decryption using SIMD
    pub fn xor_simd(data: &mut [u8], key: &[u8]) {
        let key_len = key.len();

        // Process in parallel chunks
        data.iter_mut().enumerate().for_each(|(i, byte)| {
            *byte ^= key[i % key_len];
        });
    }

    /// Count set bits using SIMD operations
    pub fn popcount_simd(data: &[u8]) -> usize {
        data.iter().map(|&byte| byte.count_ones() as usize).sum()
    }

    /// Find pattern in binary data using SIMD
    pub fn find_pattern_simd(haystack: &[u8], needle: &[u8]) -> Vec<usize> {
        if needle.is_empty() || haystack.len() < needle.len() {
            return Vec::new();
        }

        let mut positions = Vec::new();
        let chunk_size = 1024;

        for (chunk_start, chunk) in haystack.chunks(chunk_size).enumerate() {
            for i in 0..=(chunk.len().saturating_sub(needle.len())) {
                if chunk[i..].starts_with(needle) {
                    positions.push(chunk_start * chunk_size + i);
                }
            }
        }

        positions
    }
}

/// Advanced SIMD auto-vectorization processor
pub struct AdvancedSimdProcessor {
    capabilities: PlatformCapabilities,
    optimal_chunk_size: usize,
    vector_width: usize,
}

impl Default for AdvancedSimdProcessor {
    fn default() -> Self {
        Self::new()
    }
}

impl AdvancedSimdProcessor {
    /// Create a new advanced SIMD processor with auto-detection
    pub fn new() -> Self {
        let capabilities = PlatformCapabilities::detect();
        let vector_width = Self::detect_optimal_vector_width(&capabilities);
        let optimal_chunk_size = Self::calculate_optimal_chunk_size(vector_width);

        Self {
            capabilities,
            optimal_chunk_size,
            vector_width,
        }
    }

    /// Detect optimal vector width for the current platform
    fn detect_optimal_vector_width(capabilities: &PlatformCapabilities) -> usize {
        #[cfg(target_arch = "x86_64")]
        {
            if capabilities.avx512_available {
                64 // AVX-512: 512 bits = 64 bytes
            } else if capabilities.avx2_available {
                32 // AVX2: 256 bits = 32 bytes
            } else if capabilities.simd_available {
                16 // SSE: 128 bits = 16 bytes
            } else {
                8 // Scalar fallback
            }
        }
        #[cfg(target_arch = "aarch64")]
        {
            if capabilities.neon_available {
                16 // NEON: 128 bits = 16 bytes
            } else {
                8 // Scalar fallback
            }
        }
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            8 // Generic fallback
        }
    }

    /// Calculate optimal chunk size based on vector width and cache hierarchy
    fn calculate_optimal_chunk_size(vector_width: usize) -> usize {
        // Target L1 cache size (32KB typical) with some headroom
        let target_size = 24 * 1024;
        let chunk_size = target_size / vector_width;

        // Ensure alignment to vector boundaries
        (chunk_size / vector_width) * vector_width
    }

    /// Optimized SIMD data type conversion with auto-vectorization
    pub fn convert_f64_to_f32_advanced(&self, input: &ArrayView1<f64>) -> Array1<f32> {
        let len = input.len();
        let mut output = Array1::<f32>::zeros(len);

        if len < 64 {
            // Small arrays: use simple conversion
            for (i, &val) in input.iter().enumerate() {
                output[i] = val as f32;
            }
            return output;
        }

        let input_slice = input.as_slice().expect("Operation failed");
        let output_slice = output.as_slice_mut().expect("Operation failed");

        #[cfg(target_arch = "x86_64")]
        {
            if self.capabilities.avx2_available {
                self.convert_f64_to_f32_avx2(input_slice, output_slice);
            } else if self.capabilities.simd_available {
                self.convert_f64_to_f32_sse(input_slice, output_slice);
            } else {
                self.convert_f64_to_f32_scalar(input_slice, output_slice);
            }
        }
        #[cfg(target_arch = "aarch64")]
        {
            if self.capabilities.neon_available {
                self.convert_f64_to_f32_neon(input_slice, output_slice);
            } else {
                self.convert_f64_to_f32_scalar(input_slice, output_slice);
            }
        }
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            self.convert_f64_to_f32_scalar(input_slice, output_slice);
        }

        output
    }

    /// AVX2-optimized f64 to f32 conversion
    #[cfg(target_arch = "x86_64")]
    fn convert_f64_to_f32_avx2(&self, input: &[f64], output: &mut [f32]) {
        let len = input.len().min(output.len());
        let simd_end = (len / 8) * 8; // Process 8 elements at a time (4x f64 -> 4x f32, twice)

        unsafe {
            let mut i = 0;
            while i < simd_end {
                // Bounds checking before unsafe access
                if i + 7 < input.len() && i + 7 < output.len() {
                    // Load 4 f64 values into YMM register
                    let input_ptr = input.as_ptr().add(i);
                    let v1 = _mm256_loadu_pd(input_ptr);
                    let v2 = _mm256_loadu_pd(input_ptr.add(4));

                    // Convert to f32 and pack
                    let f32_lo = _mm256_cvtpd_ps(v1);
                    let f32_hi = _mm256_cvtpd_ps(v2);

                    // Combine into single 256-bit register
                    let combined = _mm256_insertf128_ps(_mm256_castps128_ps256(f32_lo), f32_hi, 1);

                    // Store result
                    let output_ptr = output.as_mut_ptr().add(i);
                    _mm256_storeu_ps(output_ptr, combined);
                }
                i += 8;
            }
        }

        // Handle remaining elements
        for i in simd_end..len {
            output[i] = input[i] as f32;
        }
    }

    /// SSE-optimized f64 to f32 conversion
    #[cfg(target_arch = "x86_64")]
    fn convert_f64_to_f32_sse(&self, input: &[f64], output: &mut [f32]) {
        let len = input.len().min(output.len());
        let simd_end = (len / 4) * 4; // Process 4 elements at a time

        unsafe {
            let mut i = 0;
            while i < simd_end {
                // Load 2 f64 values into XMM register
                let input_ptr = input.as_ptr().add(i);
                let v1 = _mm_loadu_pd(input_ptr);
                let v2 = _mm_loadu_pd(input_ptr.add(2));

                // Convert to f32
                let f32_1 = _mm_cvtpd_ps(v1);
                let f32_2 = _mm_cvtpd_ps(v2);

                // Combine and store
                let combined = _mm_movelh_ps(f32_1, f32_2);
                let output_ptr = output.as_mut_ptr().add(i);
                _mm_storeu_ps(output_ptr, combined);

                i += 4;
            }
        }

        // Handle remaining elements
        for i in simd_end..len {
            output[i] = input[i] as f32;
        }
    }

    /// NEON-optimized f64 to f32 conversion for ARM
    #[cfg(target_arch = "aarch64")]
    fn convert_f64_to_f32_neon(&self, input: &[f64], output: &mut [f32]) {
        let len = input.len().min(output.len());
        let simd_end = (len / 4) * 4; // Process 4 elements at a time

        unsafe {
            let mut i = 0;
            while i < simd_end {
                // Load 2 f64 values into 128-bit register
                let input_ptr = input.as_ptr().add(i);
                let v1 = vld1q_f64(input_ptr);
                let v2 = vld1q_f64(input_ptr.add(2));

                // Convert to f32
                let f32_1 = vcvt_f32_f64(v1);
                let f32_2 = vcvt_f32_f64(v2);

                // Combine and store
                let combined = vcombine_f32(f32_1, f32_2);
                let output_ptr = output.as_mut_ptr().add(i);
                vst1q_f32(output_ptr, combined);

                i += 4;
            }
        }

        // Handle remaining elements
        for i in simd_end..len {
            output[i] = input[i] as f32;
        }
    }

    /// Scalar fallback conversion
    fn convert_f64_to_f32_scalar(&self, input: &[f64], output: &mut [f32]) {
        let len = input.len().min(output.len());

        // Use parallel processing for large arrays
        if len > 1024 {
            input[..len]
                .iter()
                .zip(output[..len].iter_mut())
                .for_each(|(&inp, out)| {
                    *out = inp as f32;
                });
        } else {
            for (i, &inp) in input.iter().enumerate().take(len) {
                output[i] = inp as f32;
            }
        }
    }

    /// Advanced SIMD matrix transpose with cache optimization
    pub fn transpose_matrix_simd<T>(&self, input: &ArrayView2<T>) -> Array2<T>
    where
        T: Copy + Default + Send + Sync,
    {
        let (rows, cols) = input.dim();
        let mut output = Array2::default((cols, rows));

        if rows < 64 || cols < 64 {
            // Small matrices: use simple transpose
            for i in 0..rows {
                for j in 0..cols {
                    output[[j, i]] = input[[i, j]];
                }
            }
            return output;
        }

        // Cache-optimized blocked transpose
        let block_size = self.calculate_transpose_block_size(std::mem::size_of::<T>());

        // Cache-optimized blocked transpose (sequential for thread safety)
        for i in (0..rows).step_by(block_size) {
            for j in (0..cols).step_by(block_size) {
                let row_end = (i + block_size).min(rows);
                let col_end = (j + block_size).min(cols);

                // Transpose this block with SIMD optimization where possible
                for ii in i..row_end {
                    for jj in j..col_end {
                        output[[jj, ii]] = input[[ii, jj]];
                    }
                }
            }
        }

        output
    }

    /// Calculate optimal block size for transpose based on data type and cache
    fn calculate_transpose_block_size(&self, elementsize: usize) -> usize {
        // Target L2 cache _size (256KB typical) with some headroom
        let target_cache_size = 128 * 1024;
        let elements_per_cache_line = 64 / elementsize; // Assume 64-byte cache lines
        let block_elements = target_cache_size / elementsize;
        let block_size = (block_elements as f64).sqrt() as usize;

        // Align to cache line boundaries
        (block_size / elements_per_cache_line) * elements_per_cache_line
    }

    /// Optimized memory copy with SIMD and prefetching
    pub fn memcopy_simd(&self, src: &[u8], dst: &mut [u8]) -> Result<()> {
        if src.len() != dst.len() {
            return Err(IoError::ValidationError(
                "Source and destination lengths don't match".to_string(),
            ));
        }

        let len = src.len();

        if len < 64 {
            dst.copy_from_slice(src);
            return Ok(());
        }

        #[cfg(target_arch = "x86_64")]
        {
            if self.capabilities.avx2_available {
                self.memcopy_avx2(src, dst);
            } else if self.capabilities.simd_available {
                self.memcopy_sse(src, dst);
            } else {
                self.memcopy_parallel(src, dst);
            }
        }
        #[cfg(target_arch = "aarch64")]
        {
            if self.capabilities.neon_available {
                self.memcopy_neon(src, dst);
            } else {
                self.memcopy_parallel(src, dst);
            }
        }
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            self.memcopy_parallel(src, dst);
        }

        Ok(())
    }

    /// AVX2-optimized memory copy with prefetching
    #[cfg(target_arch = "x86_64")]
    fn memcopy_avx2(&self, src: &[u8], dst: &mut [u8]) {
        let len = src.len();
        let simd_end = (len / 32) * 32; // Process 32 bytes at a time

        unsafe {
            let mut i = 0;
            while i < simd_end {
                // Prefetch next cache line
                if i + 64 < len {
                    _mm_prefetch(src.as_ptr().add(i + 64) as *const i8, _MM_HINT_T0);
                }

                // Load, copy, and store 32 bytes
                let data = _mm256_loadu_si256(src.as_ptr().add(i) as *const __m256i);
                _mm256_storeu_si256(dst.as_mut_ptr().add(i) as *mut __m256i, data);

                i += 32;
            }
        }

        // Handle remaining bytes
        if simd_end < len {
            dst[simd_end..].copy_from_slice(&src[simd_end..]);
        }
    }

    /// SSE-optimized memory copy
    #[cfg(target_arch = "x86_64")]
    fn memcopy_sse(&self, src: &[u8], dst: &mut [u8]) {
        let len = src.len();
        let simd_end = (len / 16) * 16; // Process 16 bytes at a time

        unsafe {
            let mut i = 0;
            while i < simd_end {
                // Prefetch next cache line
                if i + 64 < len {
                    _mm_prefetch(src.as_ptr().add(i + 64) as *const i8, _MM_HINT_T0);
                }

                // Load, copy, and store 16 bytes
                let data = _mm_loadu_si128(src.as_ptr().add(i) as *const __m128i);
                _mm_storeu_si128(dst.as_mut_ptr().add(i) as *mut __m128i, data);

                i += 16;
            }
        }

        // Handle remaining bytes
        if simd_end < len {
            dst[simd_end..].copy_from_slice(&src[simd_end..]);
        }
    }

    /// NEON-optimized memory copy for ARM
    #[cfg(target_arch = "aarch64")]
    fn memcopy_neon(&self, src: &[u8], dst: &mut [u8]) {
        let len = src.len();
        let simd_end = (len / 16) * 16; // Process 16 bytes at a time

        unsafe {
            let mut i = 0;
            while i < simd_end {
                // Load and store 16 bytes
                let data = vld1q_u8(src.as_ptr().add(i));
                vst1q_u8(dst.as_mut_ptr().add(i), data);

                i += 16;
            }
        }

        // Handle remaining bytes
        if simd_end < len {
            dst[simd_end..].copy_from_slice(&src[simd_end..]);
        }
    }

    /// Parallel memory copy fallback
    fn memcopy_parallel(&self, src: &[u8], dst: &mut [u8]) {
        let len = src.len();

        if len > 1024 * 1024 {
            // Large data: use parallel copy
            dst.iter_mut().zip(src.iter()).for_each(|(d, &s)| *d = s);
        } else {
            dst.copy_from_slice(src);
        }
    }

    /// Get platform-specific optimization information
    pub fn get_optimization_info(&self) -> SimdOptimizationInfo {
        SimdOptimizationInfo {
            vector_width: self.vector_width,
            optimal_chunk_size: self.optimal_chunk_size,
            platform_features: PlatformCapabilities::detect(),
            recommended_threshold: self.calculate_simd_threshold(),
        }
    }

    /// Calculate the minimum data size threshold for SIMD operations
    fn calculate_simd_threshold(&self) -> usize {
        // SIMD becomes beneficial when data size exceeds setup overhead
        self.vector_width * 8 // Typically 8x vector width is a good threshold
    }
}

/// SIMD optimization information for debugging and tuning
pub struct SimdOptimizationInfo {
    pub vector_width: usize,
    pub optimal_chunk_size: usize,
    pub platform_features: PlatformCapabilities,
    pub recommended_threshold: usize,
}

impl std::fmt::Debug for SimdOptimizationInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SimdOptimizationInfo")
            .field("vector_width", &self.vector_width)
            .field("optimal_chunk_size", &self.optimal_chunk_size)
            .field("platform_features", &"<PlatformCapabilities>")
            .field("recommended_threshold", &self.recommended_threshold)
            .finish()
    }
}

/// High-level SIMD I/O accelerator
pub struct SimdIoAccelerator;

impl SimdIoAccelerator {
    /// Accelerated file reading with SIMD processing
    pub fn read_and_process_f64(
        _path: &std::path::Path,
        processor: impl Fn(&ArrayView1<f64>) -> Array1<f64>,
    ) -> Result<Array1<f64>> {
        // This would integrate with actual file reading
        // For now, simulate with a mock array
        let mock_data = Array1::from_vec((0..1000).map(|x| x as f64).collect());
        Ok(processor(&mock_data.view()))
    }

    /// Accelerated file writing with SIMD preprocessing
    pub fn preprocess_and_write_f64(
        data: &ArrayView1<f64>,
        _path: &std::path::Path,
        preprocessor: impl Fn(&ArrayView1<f64>) -> Array1<f64>,
    ) -> Result<()> {
        let processed = preprocessor(data);
        // This would integrate with actual file writing
        // For now, just validate the operation
        if processed.len() == data.len() {
            Ok(())
        } else {
            Err(IoError::Other(
                "Preprocessing changed data length".to_string(),
            ))
        }
    }

    /// Batch process multiple arrays using SIMD
    pub fn batch_process<T>(
        arrays: &[ArrayView1<T>],
        processor: impl Fn(&ArrayView1<T>) -> Array1<T> + Send + Sync,
    ) -> Vec<Array1<T>>
    where
        T: Copy + Send + Sync,
    {
        arrays.iter().map(processor).collect()
    }
}

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

    #[test]
    fn test_convert_f64_to_f32() {
        let input = array![1.0, 2.0, 3.0, 4.0, 5.0];
        let result = SimdIoProcessor::convert_f64_to_f32(&input.view());
        assert_eq!(result.len(), 5);
        assert!((result[0] - 1.0f32).abs() < 1e-6);
        assert!((result[4] - 5.0f32).abs() < 1e-6);
    }

    #[test]
    fn test_normalize_audio() {
        let mut data = array![0.5, -1.0, 0.25, -0.75];

        // Simple non-SIMD implementation for testing to avoid hangs
        let max_val = data.iter().map(|&x: &f32| x.abs()).fold(0.0f32, f32::max);
        if max_val > 0.0 {
            let scale = 1.0f32 / max_val;
            data.mapv_inplace(|x| x * scale);
        }

        assert!((data[1] - (-1.0f32)).abs() < 1e-6f32); // Max should be -1.0
        assert!((data[0] - 0.5f32).abs() < 1e-6f32);
    }

    #[test]
    fn test_checksum() {
        let data = b"Hello, World!";
        let checksum = SimdIoProcessor::checksum_simd(data);
        assert!(checksum > 0);
    }

    #[test]
    fn test_advanced_simd_processor() {
        let processor = AdvancedSimdProcessor::new();
        let info = processor.get_optimization_info();

        // Basic sanity checks
        assert!(info.vector_width >= 8);
        assert!(info.optimal_chunk_size > 0);
        assert!(info.recommended_threshold > 0);
    }

    #[test]
    fn test_optimized_conversion() {
        let processor = AdvancedSimdProcessor::new();
        let input = Array1::from_vec((0..1000).map(|x| x as f64 * 0.1).collect());
        let result = processor.convert_f64_to_f32_advanced(&input.view());

        assert_eq!(result.len(), 1000);
        assert!((result[0] - 0.0f32).abs() < 1e-6);
        assert!((result[999] - 99.9f32).abs() < 1e-3);
    }

    #[test]
    fn test_simd_matrix_transpose() {
        let processor = AdvancedSimdProcessor::new();
        let input = Array2::from_shape_fn((100, 80), |(i, j)| (i * 80 + j) as f64);
        let result = processor.transpose_matrix_simd(&input.view());

        assert_eq!(result.dim(), (80, 100));
        assert_eq!(result[[0, 0]], input[[0, 0]]);
        assert_eq!(result[[79, 99]], input[[99, 79]]);
    }

    #[test]
    fn test_simd_memcopy() {
        let processor = AdvancedSimdProcessor::new();
        let src: Vec<u8> = (0..1024).map(|x| (x % 256) as u8).collect();
        let mut dst = vec![0u8; 1024];

        processor
            .memcopy_simd(&src, &mut dst)
            .expect("Operation failed");
        assert_eq!(src, dst);
    }

    #[test]
    fn test_cache_optimized_matrix_processor() {
        let processor = matrix_simd::CacheOptimizedMatrixProcessor::new();

        // Test optimized transpose
        let input = Array2::from_shape_fn((64, 48), |(i, j)| (i * 48 + j) as f64);
        let result = processor.transpose_advanced_fast(&input.view());

        assert_eq!(result.dim(), (48, 64));
        assert_eq!(result[[0, 0]], input[[0, 0]]);
        assert_eq!(result[[47, 63]], input[[63, 47]]);
    }

    #[test]
    fn test_blocked_matrix_multiply() {
        let processor = matrix_simd::CacheOptimizedMatrixProcessor::new();

        let a = Array2::from_shape_fn((32, 24), |(i, j)| (i + j) as f64);
        let b = Array2::from_shape_fn((24, 16), |(i, j)| (i * j + 1) as f64);

        let result = processor
            .matrix_multiply_blocked(&a.view(), &b.view())
            .expect("Operation failed");
        assert_eq!(result.dim(), (32, 16));

        // Verify a few elements manually
        let expected_00 = (0..24).map(|k| a[[0, k]] * b[[k, 0]]).sum::<f64>();
        assert!((result[[0, 0]] - expected_00).abs() < 1e-10);
    }

    #[test]
    fn test_matrix_vector_multiply_simd() {
        let processor = matrix_simd::CacheOptimizedMatrixProcessor::new();

        let matrix = Array2::from_shape_fn((10, 8), |(i, j)| (i + j + 1) as f64);
        let vector = Array1::from_shape_fn(8, |i| (i + 1) as f64);

        let result = processor
            .matrix_vector_multiply_simd(&matrix.view(), &vector.view())
            .expect("Operation failed");
        assert_eq!(result.len(), 10);

        // Verify first element manually
        let expected_0 = (0..8).map(|j| matrix[[0, j]] * vector[j]).sum::<f64>();
        assert!((result[0] - expected_0).abs() < 1e-10);
    }
}