nabled 0.0.8

A linear algebra library written in Rust with an ndarray-first architecture.
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
//! Arrow adapters for fixed-shape tensor workflows.

use arrow_array::types::{ArrowPrimitiveType, Float64Type};
use arrow_array::{Array, FixedSizeListArray, StructArray};
use arrow_schema::Field;
use nabled_core::scalar::NabledReal;
use ndarray::{ArrayD, Ix3};
use ndarrow::NdarrowElement;
use num_complex::Complex64;
use serde::Deserialize;

use super::{
    ArrowInteropError, complex64_fixed_shape_tensor_from_owned, complex64_fixed_shape_tensor_viewd,
    complex64_matrix_from_owned, complex64_matrix_view, fixed_shape_tensor_from_owned,
    fixed_shape_tensor_viewd, fixed_size_list_from_owned, fixed_size_list_view,
    variable_shape_tensor_batch_view,
};

#[derive(Debug, Deserialize)]
struct VariableShapeTensorWireMetadata {
    #[serde(default)]
    uniform_shape: Option<Vec<Option<i32>>>,
}

fn fixed_shape_tensor_view3<'a, T>(
    field: &'a Field,
    array: &'a FixedSizeListArray,
) -> Result<ndarray::ArrayView3<'a, T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NdarrowElement,
{
    let view = fixed_shape_tensor_viewd::<T>(field, array)?;
    view.into_dimensionality::<Ix3>()
        .map_err(|error: ndarray::ShapeError| ArrowInteropError::InvalidShape(error.to_string()))
}

fn complex64_fixed_shape_tensor_view3<'a>(
    field: &'a Field,
    array: &'a FixedSizeListArray,
) -> Result<ndarray::ArrayView3<'a, Complex64>, ArrowInteropError> {
    let view = complex64_fixed_shape_tensor_viewd(field, array)?;
    view.into_dimensionality::<Ix3>()
        .map_err(|error: ndarray::ShapeError| ArrowInteropError::InvalidShape(error.to_string()))
}

fn variable_shape_uniform_shape(
    field: &Field,
) -> Result<Option<Vec<Option<i32>>>, ArrowInteropError> {
    let raw_metadata =
        field.extension_type_metadata().ok_or_else(|| ndarrow::NdarrowError::InvalidMetadata {
            message: "arrow.variable_shape_tensor metadata missing".to_owned(),
        })?;
    let metadata: VariableShapeTensorWireMetadata =
        serde_json::from_str(raw_metadata).map_err(|error| {
            ndarrow::NdarrowError::InvalidMetadata {
                message: format!("arrow.variable_shape_tensor metadata parse failed: {error}"),
            }
        })?;
    Ok(metadata.uniform_shape)
}

fn reduced_uniform_shape(mut uniform_shape: Option<Vec<Option<i32>>>) -> Option<Vec<Option<i32>>> {
    if let Some(shape) = &mut uniform_shape {
        let _ = shape.pop();
    }
    uniform_shape
}

fn collect_variable_shape_real_rows<T, F>(
    field: &Field,
    array: &StructArray,
    uniform_shape: Option<Vec<Option<i32>>>,
    mut op: F,
) -> Result<(Field, StructArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
    F: FnMut(&ndarray::ArrayViewD<'_, T::Native>) -> Result<ArrayD<T::Native>, ArrowInteropError>,
{
    let batch = variable_shape_tensor_batch_view::<T>(field, array)?;
    let mut outputs = Vec::with_capacity(batch.len());
    for row in 0..batch.len() {
        let tensor_view = batch.row(row)?.as_array_viewd()?;
        outputs.push(op(&tensor_view)?);
    }
    Ok(ndarrow::arrays_to_variable_shape_tensor(field.name(), outputs, uniform_shape)?)
}

fn collect_variable_shape_complex_rows<F>(
    field: &Field,
    array: &StructArray,
    uniform_shape: Option<Vec<Option<i32>>>,
    mut op: F,
) -> Result<(Field, StructArray), ArrowInteropError>
where
    F: FnMut(&ndarray::ArrayViewD<'_, Complex64>) -> Result<ArrayD<Complex64>, ArrowInteropError>,
{
    let mut outputs = Vec::with_capacity(array.len());
    for row in ndarrow::complex64_variable_shape_tensor_iter(field, array)? {
        let (_, tensor_view) = row?;
        outputs.push(op(&tensor_view)?);
    }
    Ok(ndarrow::arrays_complex64_to_variable_shape_tensor(field.name(), outputs, uniform_shape)?)
}

fn collect_variable_shape_complex_norm_rows<F>(
    field: &Field,
    array: &StructArray,
    uniform_shape: Option<Vec<Option<i32>>>,
    mut op: F,
) -> Result<(Field, StructArray), ArrowInteropError>
where
    F: FnMut(&ndarray::ArrayViewD<'_, Complex64>) -> Result<ArrayD<f64>, ArrowInteropError>,
{
    let mut outputs = Vec::with_capacity(array.len());
    for row in ndarrow::complex64_variable_shape_tensor_iter(field, array)? {
        let (_, tensor_view) = row?;
        outputs.push(op(&tensor_view)?);
    }
    Ok(ndarrow::arrays_to_variable_shape_tensor(field.name(), outputs, uniform_shape)?)
}

/// Arrow-facing rank-3 CP-ALS result paired with convergence diagnostics.
pub type ArrowCpAls3WithReport<T> =
    (crate::linalg::tensor::CpAls3Result<T>, crate::linalg::tensor::CpAlsReport<T>);

/// Arrow-facing N-D CP-ALS result paired with convergence diagnostics.
pub type ArrowCpAlsNdWithReport<T> =
    (crate::linalg::tensor::CpAlsNdResult<T>, crate::linalg::tensor::CpAlsReport<T>);

/// Sum over the last axis of a canonical `arrow.fixed_shape_tensor` batch.
///
/// `field` and `array` must come from the same fixed-shape tensor column. The returned field keeps
/// the input field name and carries updated fixed-shape tensor metadata.
///
/// # Errors
/// Returns an error when the input field/array do not represent a valid fixed-shape tensor batch,
/// contain nulls, or the tensor reduction fails.
pub fn sum_last_axis<T>(
    field: &Field,
    array: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    let output = crate::linalg::tensor::sum_last_axis_view(&tensor_view)?;
    fixed_shape_tensor_from_owned::<T>(field.name(), output)
}

/// Compute L2 norms over the last axis of a fixed-shape tensor batch.
///
/// # Errors
/// Returns an error when the input field/array do not represent a valid fixed-shape tensor batch,
/// contain nulls, or the tensor reduction fails.
pub fn l2_norm_last_axis<T>(
    field: &Field,
    array: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    let output = crate::linalg::tensor::l2_norm_last_axis_view(&tensor_view)?;
    fixed_shape_tensor_from_owned::<T>(field.name(), output)
}

/// Normalize a fixed-shape tensor batch over the last axis.
///
/// # Errors
/// Returns an error when the input field/array do not represent a valid fixed-shape tensor batch,
/// contain nulls, or the tensor normalization fails.
pub fn normalize_last_axis<T>(
    field: &Field,
    array: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    let output = crate::linalg::tensor::normalize_last_axis_view(&tensor_view)?;
    fixed_shape_tensor_from_owned::<T>(field.name(), output)
}

/// Compute batched dot products over the last axis of two fixed-shape tensor batches.
///
/// # Errors
/// Returns an error when inputs do not represent valid fixed-shape tensors, contain nulls, or
/// dimensions are incompatible.
pub fn batched_dot_last_axis<T>(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let left_view = fixed_shape_tensor_viewd::<T>(left_field, left)?;
    let right_view = fixed_shape_tensor_viewd::<T>(right_field, right)?;
    let output = crate::linalg::tensor::batched_dot_last_axis_view(&left_view, &right_view)?;
    fixed_shape_tensor_from_owned::<T>(left_field.name(), output)
}

/// Permute the axes of a fixed-shape tensor batch.
///
/// # Errors
/// Returns an error when the input does not represent a valid fixed-shape tensor batch, contains
/// nulls, or the permutation is invalid.
pub fn permute_axes<T>(
    field: &Field,
    array: &FixedSizeListArray,
    permutation: &[usize],
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    let output = crate::linalg::tensor::permute_axes_view(&tensor_view, permutation)?;
    fixed_shape_tensor_from_owned::<T>(field.name(), output)
}

/// Contract two fixed-shape tensors along explicit axis sets.
///
/// # Errors
/// Returns an error when either input is invalid, contains nulls, or contraction axes are
/// incompatible.
pub fn contract_axes<T>(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
    left_axes: &[usize],
    right_axes: &[usize],
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let left_view = fixed_shape_tensor_viewd::<T>(left_field, left)?;
    let right_view = fixed_shape_tensor_viewd::<T>(right_field, right)?;
    let output =
        crate::linalg::tensor::contract_axes_view(&left_view, &right_view, left_axes, right_axes)?;
    fixed_shape_tensor_from_owned::<T>(left_field.name(), output)
}

/// Perform N-D batched matrix multiplication over the last two axes of fixed-shape tensors.
///
/// # Errors
/// Returns an error when either input is invalid, contains nulls, or dimensions are incompatible.
pub fn batched_matmul_last_two<T>(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let left_view = fixed_shape_tensor_viewd::<T>(left_field, left)?;
    let right_view = fixed_shape_tensor_viewd::<T>(right_field, right)?;
    let output = crate::linalg::tensor::batched_matmul_last_two_view(&left_view, &right_view)?;
    fixed_shape_tensor_from_owned::<T>(left_field.name(), output)
}

/// Compute batched cube-matrix vector products from fixed-shape tensor / Arrow dense inputs.
///
/// `cube` is interpreted as rank-3 `(batch, rows, cols)` tensor data and `vectors` as `(batch,
/// cols)` dense matrix data.
///
/// # Errors
/// Returns an error when inputs are invalid, contain nulls, or dimensions are incompatible.
pub fn cube_matvec<T>(
    cube_field: &Field,
    cube: &FixedSizeListArray,
    vectors: &FixedSizeListArray,
) -> Result<FixedSizeListArray, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let cube_view = fixed_shape_tensor_view3::<T>(cube_field, cube)?;
    let vectors_view = fixed_size_list_view::<T>(vectors)?;
    let output = crate::linalg::tensor::cube_matvec_view(&cube_view, &vectors_view)?;
    fixed_size_list_from_owned::<T>(output)
}

/// Compute batched cube matrix-matrix products from two rank-3 fixed-shape tensors.
///
/// # Errors
/// Returns an error when inputs are invalid, contain nulls, or dimensions are incompatible.
pub fn cube_matmat<T>(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let left_view = fixed_shape_tensor_view3::<T>(left_field, left)?;
    let right_view = fixed_shape_tensor_view3::<T>(right_field, right)?;
    let output = crate::linalg::tensor::cube_matmat_view(&left_view, &right_view)?;
    fixed_shape_tensor_from_owned::<T>(left_field.name(), output.into_dyn())
}

/// Flatten a rank-3 tensor batch into a dense matrix.
///
/// # Errors
/// Returns an error when the input is not rank-3, contains nulls, or flattening fails.
pub fn flatten_cubes<T>(
    field: &Field,
    array: &FixedSizeListArray,
) -> Result<FixedSizeListArray, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let cube_view = fixed_shape_tensor_view3::<T>(field, array)?;
    let output = crate::linalg::tensor::flatten_cubes_view(&cube_view)?;
    fixed_size_list_from_owned::<T>(output)
}

/// Sum over the last axis of a canonical `arrow.variable_shape_tensor` batch.
///
/// # Errors
/// Returns an error when the input field/array do not represent a valid variable-shape tensor
/// batch, contain nulls, or the tensor reduction fails.
pub fn sum_last_axis_variable<T>(
    field: &Field,
    array: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement + Default,
{
    let uniform_shape = reduced_uniform_shape(variable_shape_uniform_shape(field)?);
    collect_variable_shape_real_rows::<T, _>(field, array, uniform_shape, |tensor_view| {
        Ok(crate::linalg::tensor::sum_last_axis_view(tensor_view)?)
    })
}

/// Compute L2 norms over the last axis of a variable-shape tensor batch.
///
/// # Errors
/// Returns an error when the input field/array do not represent a valid variable-shape tensor
/// batch, contain nulls, or the tensor reduction fails.
pub fn l2_norm_last_axis_variable<T>(
    field: &Field,
    array: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let uniform_shape = reduced_uniform_shape(variable_shape_uniform_shape(field)?);
    collect_variable_shape_real_rows::<T, _>(field, array, uniform_shape, |tensor_view| {
        Ok(crate::linalg::tensor::l2_norm_last_axis_view(tensor_view)?)
    })
}

/// Normalize a variable-shape tensor batch over the last axis.
///
/// # Errors
/// Returns an error when the input field/array do not represent a valid variable-shape tensor
/// batch, contain nulls, or normalization fails.
pub fn normalize_last_axis_variable<T>(
    field: &Field,
    array: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let uniform_shape = variable_shape_uniform_shape(field)?;
    collect_variable_shape_real_rows::<T, _>(field, array, uniform_shape, |tensor_view| {
        Ok(crate::linalg::tensor::normalize_last_axis_view(tensor_view)?)
    })
}

/// Compute batched dot products over the last axis of two variable-shape tensor batches.
///
/// # Errors
/// Returns an error when inputs do not represent valid variable-shape tensors, contain nulls, or
/// dimensions are incompatible.
pub fn batched_dot_last_axis_variable<T>(
    left_field: &Field,
    left: &StructArray,
    right_field: &Field,
    right: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    if left.len() != right.len() {
        return Err(ArrowInteropError::InvalidShape(format!(
            "variable-shape tensor batch row count mismatch: {} vs {}",
            left.len(),
            right.len()
        )));
    }

    let uniform_shape = reduced_uniform_shape(variable_shape_uniform_shape(left_field)?);
    let left_batch = variable_shape_tensor_batch_view::<T>(left_field, left)?;
    let right_batch = variable_shape_tensor_batch_view::<T>(right_field, right)?;
    let mut outputs = Vec::with_capacity(left_batch.len());
    for row in 0..left_batch.len() {
        let left_view = left_batch.row(row)?.as_array_viewd()?;
        let right_view = right_batch.row(row)?.as_array_viewd()?;
        outputs.push(crate::linalg::tensor::batched_dot_last_axis_view(&left_view, &right_view)?);
    }
    Ok(ndarrow::arrays_to_variable_shape_tensor(left_field.name(), outputs, uniform_shape)?)
}

/// Sum over the last axis of a complex fixed-shape tensor batch.
///
/// # Errors
/// Returns an error when the tensor metadata is invalid, contains nulls, or the reduction fails.
pub fn sum_last_axis_complex(
    field: &Field,
    array: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let tensor_view = complex64_fixed_shape_tensor_viewd(field, array)?;
    let output = crate::linalg::tensor::sum_last_axis_complex_view(&tensor_view)?;
    complex64_fixed_shape_tensor_from_owned(field.name(), output)
}

/// Sum over the last axis of a complex variable-shape tensor batch.
///
/// # Errors
/// Returns an error when the tensor metadata is invalid, contains nulls, or the reduction fails.
pub fn sum_last_axis_variable_complex(
    field: &Field,
    array: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError> {
    let uniform_shape = reduced_uniform_shape(variable_shape_uniform_shape(field)?);
    collect_variable_shape_complex_rows(field, array, uniform_shape, |tensor_view| {
        Ok(crate::linalg::tensor::sum_last_axis_complex_view(tensor_view)?)
    })
}

/// Compute L2 norms over the last axis of a complex fixed-shape tensor batch.
///
/// # Errors
/// Returns an error when the tensor metadata is invalid, contains nulls, or the reduction fails.
pub fn l2_norm_last_axis_complex(
    field: &Field,
    array: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let tensor_view = complex64_fixed_shape_tensor_viewd(field, array)?;
    let output = crate::linalg::tensor::l2_norm_last_axis_complex_view(&tensor_view)?;
    fixed_shape_tensor_from_owned::<Float64Type>(field.name(), output)
}

/// Compute L2 norms over the last axis of a complex variable-shape tensor batch.
///
/// # Errors
/// Returns an error when the tensor metadata is invalid, contains nulls, or the reduction fails.
pub fn l2_norm_last_axis_variable_complex(
    field: &Field,
    array: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError> {
    let uniform_shape = reduced_uniform_shape(variable_shape_uniform_shape(field)?);
    collect_variable_shape_complex_norm_rows(field, array, uniform_shape, |tensor_view| {
        Ok(crate::linalg::tensor::l2_norm_last_axis_complex_view(tensor_view)?)
    })
}

/// Normalize a complex fixed-shape tensor batch over the last axis.
///
/// # Errors
/// Returns an error when the tensor metadata is invalid, contains nulls, or normalization fails.
pub fn normalize_last_axis_complex(
    field: &Field,
    array: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let tensor_view = complex64_fixed_shape_tensor_viewd(field, array)?;
    let output = crate::linalg::tensor::normalize_last_axis_complex_view(&tensor_view)?;
    complex64_fixed_shape_tensor_from_owned(field.name(), output)
}

/// Normalize a complex variable-shape tensor batch over the last axis.
///
/// # Errors
/// Returns an error when the tensor metadata is invalid, contains nulls, or normalization fails.
pub fn normalize_last_axis_variable_complex(
    field: &Field,
    array: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError> {
    let uniform_shape = variable_shape_uniform_shape(field)?;
    collect_variable_shape_complex_rows(field, array, uniform_shape, |tensor_view| {
        Ok(crate::linalg::tensor::normalize_last_axis_complex_view(tensor_view)?)
    })
}

/// Compute batched complex dot products over the last axis of two fixed-shape tensor batches.
///
/// # Errors
/// Returns an error when either tensor is invalid, contains nulls, or shapes are incompatible.
pub fn batched_dot_last_axis_complex(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let left_view = complex64_fixed_shape_tensor_viewd(left_field, left)?;
    let right_view = complex64_fixed_shape_tensor_viewd(right_field, right)?;
    let output =
        crate::linalg::tensor::batched_dot_last_axis_complex_view(&left_view, &right_view)?;
    complex64_fixed_shape_tensor_from_owned(left_field.name(), output)
}

/// Compute batched complex dot products over the last axis of two variable-shape tensor batches.
///
/// # Errors
/// Returns an error when either tensor is invalid, contains nulls, or shapes are incompatible.
pub fn batched_dot_last_axis_variable_complex(
    left_field: &Field,
    left: &StructArray,
    right_field: &Field,
    right: &StructArray,
) -> Result<(Field, StructArray), ArrowInteropError> {
    if left.len() != right.len() {
        return Err(ArrowInteropError::InvalidShape(format!(
            "variable-shape tensor batch row count mismatch: {} vs {}",
            left.len(),
            right.len()
        )));
    }

    let uniform_shape = reduced_uniform_shape(variable_shape_uniform_shape(left_field)?);
    let mut outputs = Vec::with_capacity(left.len());
    let mut right_iter = ndarrow::complex64_variable_shape_tensor_iter(right_field, right)?;
    for left_row in ndarrow::complex64_variable_shape_tensor_iter(left_field, left)? {
        let (_, left_view) = left_row?;
        let (_, right_view) = right_iter.next().ok_or_else(|| {
            ArrowInteropError::InvalidShape(
                "variable-shape tensor batch iterator ended early".to_owned(),
            )
        })??;
        outputs.push(crate::linalg::tensor::batched_dot_last_axis_complex_view(
            &left_view,
            &right_view,
        )?);
    }
    Ok(ndarrow::arrays_complex64_to_variable_shape_tensor(
        left_field.name(),
        outputs,
        uniform_shape,
    )?)
}

/// Permute the axes of a complex fixed-shape tensor batch.
///
/// # Errors
/// Returns an error when the tensor is invalid, contains nulls, or the permutation is invalid.
pub fn permute_axes_complex(
    field: &Field,
    array: &FixedSizeListArray,
    permutation: &[usize],
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let tensor_view = complex64_fixed_shape_tensor_viewd(field, array)?;
    let output = crate::linalg::tensor::permute_axes_complex_view(&tensor_view, permutation)?;
    complex64_fixed_shape_tensor_from_owned(field.name(), output)
}

/// Contract two complex fixed-shape tensors along explicit axis sets.
///
/// # Errors
/// Returns an error when either tensor is invalid, contains nulls, or contraction axes mismatch.
pub fn contract_axes_complex(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
    left_axes: &[usize],
    right_axes: &[usize],
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let left_view = complex64_fixed_shape_tensor_viewd(left_field, left)?;
    let right_view = complex64_fixed_shape_tensor_viewd(right_field, right)?;
    let output = crate::linalg::tensor::contract_axes_complex_view(
        &left_view,
        &right_view,
        left_axes,
        right_axes,
    )?;
    complex64_fixed_shape_tensor_from_owned(left_field.name(), output)
}

/// Perform N-D batched complex matrix multiplication over the last two axes.
///
/// # Errors
/// Returns an error when either tensor is invalid, contains nulls, or dimensions mismatch.
pub fn batched_matmul_last_two_complex(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let left_view = complex64_fixed_shape_tensor_viewd(left_field, left)?;
    let right_view = complex64_fixed_shape_tensor_viewd(right_field, right)?;
    let output =
        crate::linalg::tensor::batched_matmul_last_two_complex_view(&left_view, &right_view)?;
    complex64_fixed_shape_tensor_from_owned(left_field.name(), output)
}

/// Compute batched complex cube-matrix vector products from Arrow inputs.
///
/// # Errors
/// Returns an error when inputs are invalid, contain nulls, or dimensions mismatch.
pub fn cube_matvec_complex(
    cube_field: &Field,
    cube: &FixedSizeListArray,
    vectors: &FixedSizeListArray,
) -> Result<FixedSizeListArray, ArrowInteropError> {
    let cube_view = complex64_fixed_shape_tensor_view3(cube_field, cube)?;
    let vectors_view = complex64_matrix_view(vectors)?;
    let output = crate::linalg::tensor::cube_matvec_complex_view(&cube_view, &vectors_view)?;
    complex64_matrix_from_owned(output)
}

/// Compute batched complex cube matrix-matrix products from Arrow inputs.
///
/// # Errors
/// Returns an error when inputs are invalid, contain nulls, or dimensions mismatch.
pub fn cube_matmat_complex(
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let left_view = complex64_fixed_shape_tensor_view3(left_field, left)?;
    let right_view = complex64_fixed_shape_tensor_view3(right_field, right)?;
    let output = crate::linalg::tensor::cube_matmat_complex_view(&left_view, &right_view)?;
    complex64_fixed_shape_tensor_from_owned(left_field.name(), output.into_dyn())
}

/// Evaluate two-operand Einstein summation over real fixed-shape tensors.
///
/// # Errors
/// Returns an error when expression syntax is invalid or the tensor shapes mismatch.
pub fn einsum<T>(
    expression: &str,
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let left_view = fixed_shape_tensor_viewd::<T>(left_field, left)?;
    let right_view = fixed_shape_tensor_viewd::<T>(right_field, right)?;
    let output = crate::linalg::tensor::einsum_view(expression, &left_view, &right_view)?;
    fixed_shape_tensor_from_owned::<T>(left_field.name(), output)
}

/// Evaluate two-operand Einstein summation over complex fixed-shape tensors.
///
/// # Errors
/// Returns an error when expression syntax is invalid or the tensor shapes mismatch.
pub fn einsum_complex(
    expression: &str,
    left_field: &Field,
    left: &FixedSizeListArray,
    right_field: &Field,
    right: &FixedSizeListArray,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError> {
    let left_view = complex64_fixed_shape_tensor_viewd(left_field, left)?;
    let right_view = complex64_fixed_shape_tensor_viewd(right_field, right)?;
    let output = crate::linalg::tensor::einsum_complex_view(expression, &left_view, &right_view)?;
    complex64_fixed_shape_tensor_from_owned(left_field.name(), output)
}

/// Compute rank-`R` CP decomposition for a rank-3 tensor from Arrow fixed-shape tensor input.
///
/// # Errors
/// Returns an error when the tensor is not rank-3, contains nulls, or ALS fails.
pub fn cp_als3<T>(
    field: &Field,
    array: &FixedSizeListArray,
    rank: usize,
    config: &crate::linalg::tensor::CpAlsConfig<T::Native>,
) -> Result<crate::linalg::tensor::CpAls3Result<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: crate::linalg::tensor::CpAlsScalar + NdarrowElement,
{
    let cube_view = fixed_shape_tensor_view3::<T>(field, array)?;
    Ok(crate::linalg::tensor::cp_als3_view(&cube_view, rank, config)?)
}

/// Compute rank-`R` CP decomposition plus diagnostics for a rank-3 Arrow tensor input.
///
/// # Errors
/// Returns an error when the tensor is not rank-3, contains nulls, or ALS fails.
pub fn cp_als3_with_report<T>(
    field: &Field,
    array: &FixedSizeListArray,
    rank: usize,
    config: &crate::linalg::tensor::CpAlsConfig<T::Native>,
) -> Result<ArrowCpAls3WithReport<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: crate::linalg::tensor::CpAlsScalar + NdarrowElement,
{
    let cube_view = fixed_shape_tensor_view3::<T>(field, array)?;
    Ok(crate::linalg::tensor::cp_als3_view_with_report(&cube_view, rank, config)?)
}

/// Compute reconstruction diagnostics for a rank-3 CP decomposition against an Arrow tensor.
///
/// # Errors
/// Returns an error when the tensor is not rank-3, contains nulls, or dimensions mismatch.
pub fn cp_als3_diagnostics<T>(
    field: &Field,
    array: &FixedSizeListArray,
    result: &crate::linalg::tensor::CpAls3Result<T::Native>,
) -> Result<crate::linalg::tensor::CpErrorMetrics<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let cube_view = fixed_shape_tensor_view3::<T>(field, array)?;
    Ok(crate::linalg::tensor::cp_als3_diagnostics_view(&cube_view, result)?)
}

/// Reconstruct a rank-3 tensor from CP factors into Arrow fixed-shape tensor form.
///
/// # Errors
/// Returns an error when factor dimensions are incompatible.
pub fn cp_als3_reconstruct<T>(
    field_name: &str,
    result: &crate::linalg::tensor::CpAls3Result<T::Native>,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let output = crate::linalg::tensor::cp_als3_reconstruct(result)?;
    fixed_shape_tensor_from_owned::<T>(field_name, output.into_dyn())
}

/// Compute rank-`R` CP decomposition for an `N`-D tensor from Arrow fixed-shape tensor input.
///
/// # Errors
/// Returns an error when the tensor is invalid, contains nulls, or ALS fails.
pub fn cp_als_nd<T>(
    field: &Field,
    array: &FixedSizeListArray,
    rank: usize,
    config: &crate::linalg::tensor::CpAlsConfig<T::Native>,
) -> Result<crate::linalg::tensor::CpAlsNdResult<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: crate::linalg::tensor::CpAlsScalar + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    Ok(crate::linalg::tensor::cp_als_nd_view(&tensor_view, rank, config)?)
}

/// Compute rank-`R` CP decomposition plus diagnostics for an `N`-D Arrow tensor input.
///
/// # Errors
/// Returns an error when the tensor is invalid, contains nulls, or ALS fails.
pub fn cp_als_nd_with_report<T>(
    field: &Field,
    array: &FixedSizeListArray,
    rank: usize,
    config: &crate::linalg::tensor::CpAlsConfig<T::Native>,
) -> Result<ArrowCpAlsNdWithReport<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: crate::linalg::tensor::CpAlsScalar + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    Ok(crate::linalg::tensor::cp_als_nd_view_with_report(&tensor_view, rank, config)?)
}

/// Compute reconstruction diagnostics for an `N`-D CP decomposition against an Arrow tensor.
///
/// # Errors
/// Returns an error when the tensor is invalid, contains nulls, or dimensions mismatch.
pub fn cp_als_nd_diagnostics<T>(
    field: &Field,
    array: &FixedSizeListArray,
    result: &crate::linalg::tensor::CpAlsNdResult<T::Native>,
) -> Result<crate::linalg::tensor::CpErrorMetrics<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    Ok(crate::linalg::tensor::cp_als_nd_diagnostics_view(&tensor_view, result)?)
}

/// Reconstruct an `N`-D tensor from CP factors into Arrow fixed-shape tensor form.
///
/// # Errors
/// Returns an error when factor dimensions are incompatible.
pub fn cp_als_nd_reconstruct<T>(
    field_name: &str,
    result: &crate::linalg::tensor::CpAlsNdResult<T::Native>,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let output = crate::linalg::tensor::cp_als_nd_reconstruct(result)?;
    fixed_shape_tensor_from_owned::<T>(field_name, output)
}

/// Compute rank-truncated `N`-D HOSVD from Arrow fixed-shape tensor input.
///
/// # Errors
/// Returns an error when the tensor is invalid, contains nulls, or factorization fails.
pub fn hosvd_nd<T>(
    field: &Field,
    array: &FixedSizeListArray,
    ranks: &[usize],
) -> Result<crate::linalg::tensor::HosvdNdResult<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: crate::linalg::tensor::HosvdNdScalar + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    Ok(crate::linalg::tensor::hosvd_nd_view(&tensor_view, ranks)?)
}

/// Compute rank-truncated `N`-D Tucker decomposition via HOOI from Arrow tensor input.
///
/// # Errors
/// Returns an error when the tensor is invalid, contains nulls, or factorization fails.
pub fn hooi_nd<T>(
    field: &Field,
    array: &FixedSizeListArray,
    ranks: &[usize],
    config: &crate::linalg::tensor::HooiConfig<T::Native>,
) -> Result<crate::linalg::tensor::HosvdNdResult<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: crate::linalg::tensor::HooiNdScalar + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    Ok(crate::linalg::tensor::hooi_nd_view(&tensor_view, ranks, config)?)
}

/// Project an Arrow tensor into a Tucker core using ndarray-native factor matrices.
///
/// # Errors
/// Returns an error when tensor/factor dimensions are incompatible.
pub fn tucker_project<T>(
    field: &Field,
    array: &FixedSizeListArray,
    factors: &[ndarray::Array2<T::Native>],
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    let output = crate::linalg::tensor::tucker_project_view(&tensor_view, factors)?;
    fixed_shape_tensor_from_owned::<T>(field.name(), output)
}

/// Expand a Tucker core from Arrow into the original tensor space.
///
/// # Errors
/// Returns an error when core/factor dimensions are incompatible.
pub fn tucker_expand<T>(
    field: &Field,
    array: &FixedSizeListArray,
    factors: &[ndarray::Array2<T::Native>],
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    let output = crate::linalg::tensor::tucker_expand_view(&tensor_view, factors)?;
    fixed_shape_tensor_from_owned::<T>(field.name(), output)
}

/// Reconstruct an `N`-D tensor from an ndarray-native HOSVD/Tucker result.
///
/// # Errors
/// Returns an error when factor dimensions are incompatible.
pub fn hosvd_nd_reconstruct<T>(
    field_name: &str,
    result: &crate::linalg::tensor::HosvdNdResult<T::Native>,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let output = crate::linalg::tensor::hosvd_nd_reconstruct(result)?;
    fixed_shape_tensor_from_owned::<T>(field_name, output)
}

/// Compute Tensor-Train decomposition from Arrow fixed-shape tensor input.
///
/// # Errors
/// Returns an error when the tensor is invalid, contains nulls, or decomposition fails.
pub fn tt_svd<T>(
    field: &Field,
    array: &FixedSizeListArray,
    config: &crate::linalg::tensor::TtSvdConfig<T::Native>,
) -> Result<crate::linalg::tensor::TensorTrainResult<T::Native>, ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: crate::linalg::tensor::TtSvdScalar + NdarrowElement,
{
    let tensor_view = fixed_shape_tensor_viewd::<T>(field, array)?;
    Ok(crate::linalg::tensor::tt_svd_view(&tensor_view, config)?)
}

/// Left-orthogonalize a Tensor-Train result.
///
/// # Errors
/// Returns an error when TT core dimensions are incompatible.
pub fn tt_orthogonalize_left<T: crate::linalg::tensor::TtSvdScalar>(
    result: &crate::linalg::tensor::TensorTrainResult<T>,
) -> Result<crate::linalg::tensor::TensorTrainResult<T>, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_orthogonalize_left(result)?)
}

/// Right-orthogonalize a Tensor-Train result.
///
/// # Errors
/// Returns an error when TT core dimensions are incompatible.
pub fn tt_orthogonalize_right<T: crate::linalg::tensor::TtSvdScalar>(
    result: &crate::linalg::tensor::TensorTrainResult<T>,
) -> Result<crate::linalg::tensor::TensorTrainResult<T>, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_orthogonalize_right(result)?)
}

/// Round/compress a Tensor-Train result.
///
/// # Errors
/// Returns an error when TT core dimensions or configuration are invalid.
pub fn tt_round<T: crate::linalg::tensor::TtSvdScalar>(
    result: &crate::linalg::tensor::TensorTrainResult<T>,
    config: &crate::linalg::tensor::TtRoundConfig<T>,
) -> Result<crate::linalg::tensor::TensorTrainResult<T>, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_round(result, config)?)
}

/// Compute inner product of two Tensor-Train tensors.
///
/// # Errors
/// Returns an error when TT core dimensions are incompatible or shapes mismatch.
pub fn tt_inner<T: NabledReal>(
    left: &crate::linalg::tensor::TensorTrainResult<T>,
    right: &crate::linalg::tensor::TensorTrainResult<T>,
) -> Result<T, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_inner(left, right)?)
}

/// Compute Frobenius norm of a Tensor-Train tensor.
///
/// # Errors
/// Returns an error when TT core dimensions are incompatible.
pub fn tt_norm<T: NabledReal>(
    result: &crate::linalg::tensor::TensorTrainResult<T>,
) -> Result<T, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_norm(result)?)
}

/// Add two Tensor-Train tensors.
///
/// # Errors
/// Returns an error when TT core dimensions are incompatible or shapes mismatch.
pub fn tt_add<T: NabledReal>(
    left: &crate::linalg::tensor::TensorTrainResult<T>,
    right: &crate::linalg::tensor::TensorTrainResult<T>,
) -> Result<crate::linalg::tensor::TensorTrainResult<T>, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_add(left, right)?)
}

/// Compute elementwise Hadamard product of two Tensor-Train tensors.
///
/// # Errors
/// Returns an error when TT core dimensions are incompatible or shapes mismatch.
pub fn tt_hadamard<T: NabledReal>(
    left: &crate::linalg::tensor::TensorTrainResult<T>,
    right: &crate::linalg::tensor::TensorTrainResult<T>,
) -> Result<crate::linalg::tensor::TensorTrainResult<T>, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_hadamard(left, right)?)
}

/// Compute Hadamard product followed by TT rank-rounding.
///
/// # Errors
/// Returns an error when TT core dimensions/configuration are invalid.
pub fn tt_hadamard_round<T: crate::linalg::tensor::TtSvdScalar>(
    left: &crate::linalg::tensor::TensorTrainResult<T>,
    right: &crate::linalg::tensor::TensorTrainResult<T>,
    config: &crate::linalg::tensor::TtRoundConfig<T>,
) -> Result<crate::linalg::tensor::TensorTrainResult<T>, ArrowInteropError> {
    Ok(crate::linalg::tensor::tt_hadamard_round(left, right, config)?)
}

/// Reconstruct an `N`-D tensor from Tensor-Train cores into Arrow fixed-shape tensor form.
///
/// # Errors
/// Returns an error when TT core dimensions are incompatible.
pub fn tt_svd_reconstruct<T>(
    field_name: &str,
    result: &crate::linalg::tensor::TensorTrainResult<T::Native>,
) -> Result<(Field, FixedSizeListArray), ArrowInteropError>
where
    T: ArrowPrimitiveType,
    T::Native: NabledReal + NdarrowElement,
{
    let output = crate::linalg::tensor::tt_svd_reconstruct(result)?;
    fixed_shape_tensor_from_owned::<T>(field_name, output)
}