kryst 3.2.1

Krylov subspace and preconditioned iterative solvers for dense and sparse linear systems, with shared and distributed memory parallelism.
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
//! Core linear-algebra traits for kryst.

/// Matrix–vector product: y ← A x.
pub trait MatVec<V> {
    /// Compute y = A · x.
    fn matvec(&self, x: &V, y: &mut V);
}

/// Matrix–transpose–vector product: y ← Aᵗ x (A^H for complex).
pub trait MatTransVec<V> {
    /// Compute y = Aᵗ · x (or A^H · x in complex builds).
    fn mattransvec(&self, x: &V, y: &mut V);
}

// Blanket implementations of MatVec/MatTransVec for LinOp types using Vec storage.
use crate::algebra::parallel::{self, par_dot_conj_local, par_sum_abs2_local};
use crate::algebra::prelude::*;
use crate::algebra::scalar::{KrystScalar, copy_real_to_scalar_in, copy_scalar_to_real_in};
use crate::core::block::BlockVec;
use crate::error::KError;
use crate::matrix::op::LinOp;
use crate::preconditioner::LocalPreconditioner;

impl<L> MatVec<Vec<S>> for L
where
    L: LinOp<S = S> + ?Sized,
{
    fn matvec(&self, x: &Vec<S>, y: &mut Vec<S>) {
        LinOp::matvec(self, &x[..], &mut y[..]);
    }
}

impl<L> MatTransVec<Vec<S>> for L
where
    L: LinOp<S = S> + ?Sized,
{
    fn mattransvec(&self, x: &Vec<S>, y: &mut Vec<S>) {
        if !LinOp::supports_transpose(self) {
            panic!("t_matvec not supported");
        }
        LinOp::t_matvec(self, &x[..], &mut y[..]);
    }
}

#[cfg(feature = "complex")]
impl<L> MatVec<Vec<f64>> for L
where
    L: LinOp<S = f64> + ?Sized,
{
    fn matvec(&self, x: &Vec<f64>, y: &mut Vec<f64>) {
        LinOp::matvec(self, &x[..], &mut y[..]);
    }
}

#[cfg(feature = "complex")]
impl<L> MatTransVec<Vec<f64>> for L
where
    L: LinOp<S = f64> + ?Sized,
{
    fn mattransvec(&self, x: &Vec<f64>, y: &mut Vec<f64>) {
        if !LinOp::supports_transpose(self) {
            panic!("t_matvec not supported");
        }
        LinOp::t_matvec(self, &x[..], &mut y[..]);
    }
}

/// Real-valued block operator used by block Krylov variants while remaining matrix-free.
///
/// This trait is intentionally defined in terms of `f64` scalars. In complex builds the helper
/// conversions (`copy_scalar_to_real_in`) drop imaginary parts, so `apply_many`/`apply` work
/// only on the real components of the block vectors. Use this trait for real preconditioners
/// or diagnostics inside complex solvers rather than for fully complex-valued operators.
pub trait BlockOp {
    /// Apply the operator to multiple columns at once. Default implementation calls
    /// [`apply`](Self::apply) per column to remain format agnostic.
    fn apply_many(&self, x: &BlockVec, y: &mut BlockVec) -> Result<(), KError> {
        if x.ncols() != y.ncols() {
            return Err(KError::InvalidInput(format!(
                "apply_many column mismatch: {} vs {}",
                x.ncols(),
                y.ncols()
            )));
        }
        let mut x_real = vec![0.0; x.nrows()];
        let mut y_real = vec![0.0; y.nrows()];
        // In complex builds `copy_scalar_to_real_in` discards imaginary components.
        for c in 0..x.ncols() {
            copy_scalar_to_real_in(x.col(c), &mut x_real);
            copy_scalar_to_real_in(y.col(c), &mut y_real);
            self.apply(&x_real, &mut y_real)?;
            copy_real_to_scalar_in(&y_real, y.col_mut(c));
        }
        Ok(())
    }

    /// Apply the operator to a single column.
    fn apply(&self, x: &[f64], y: &mut [f64]) -> Result<(), KError>;

    /// Apply the transpose of the operator if available.
    fn apply_t(&self, _x: &[f64], _y: &mut [f64]) -> Result<(), KError> {
        Err(KError::Unsupported("transpose not available"))
    }
}

impl<T> BlockOp for T
where
    T: LinOp<S = f64> + ?Sized,
{
    fn apply(&self, x: &[f64], y: &mut [f64]) -> Result<(), KError> {
        LinOp::try_matvec(self, x, y)
    }

    fn apply_t(&self, x: &[f64], y: &mut [f64]) -> Result<(), KError> {
        if !LinOp::supports_transpose(self) {
            return Err(KError::Unsupported(
                "LinOp::t_matvec called but transpose not supported",
            ));
        }
        LinOp::t_matvec(self, x, y);
        Ok(())
    }
}

/// Inner products & norms.
pub trait InnerProduct<V> {
    /// Associated scalar type.
    type Scalar: Copy + PartialOrd + From<f64> + Into<f64>;
    /// Compute dot(x, y) with communicator support for parallel reductions.
    fn dot(&self, x: &V, y: &V, comm: &impl crate::parallel::Comm) -> Self::Scalar;
    /// Compute ‖x‖₂ with communicator support for parallel reductions.
    fn norm(&self, x: &V, comm: &impl crate::parallel::Comm) -> Self::Scalar {
        let local_sq = self.dot(x, x, comm);
        let global_sq = comm.all_reduce_f64(local_sq.into());
        (global_sq.sqrt()).into()
    }
}

/// Uniform indexing into vectors (dense or sparse).
pub trait Indexing {
    /// Number of rows (or length for a vector).
    fn nrows(&self) -> usize;
}

/// Matrix shape trait: provides nrows/ncols for matrices and vectors.
pub trait MatShape {
    fn nrows(&self) -> usize;
    fn ncols(&self) -> usize;
}

/// Trait for extracting the sparsity pattern of a matrix row.
pub trait RowPattern {
    /// Returns the column indices of nonzeros in row i.
    fn row_indices(&self, i: usize) -> &[usize];
}

/// Trait for extracting elements from a matrix.
pub trait MatrixGet<T> {
    /// Get the element at position (i, j).
    fn get(&self, i: usize, j: usize) -> T;
}

/// Trait for extracting a submatrix by index set (for block/ASM preconditioners).
pub trait SubmatrixExtract: Sized {
    /// Stored scalar type for the matrix.
    type S;

    /// Extract a submatrix defined by row and column index sets.
    fn extract_submatrix(&self, rows: &[usize], cols: &[usize]) -> Self;

    /// Convenience helper for square sub-blocks that use the same index set.
    fn submatrix(&self, indices: &[usize]) -> Self {
        self.extract_submatrix(indices, indices)
    }
}

/// Sparse-aware matrix-vector operations for AMG and iterative solvers
pub trait MatVecOp<T> {
    /// Compute y = alpha * A * x + beta * y
    fn mat_vec(&self, alpha: T, x: &[T], beta: T, y: &mut [T]) -> Result<(), crate::error::KError>;

    /// Compute y = alpha * A^T * x + beta * y (transpose operation)
    fn mat_vec_trans(
        &self,
        alpha: T,
        x: &[T],
        beta: T,
        y: &mut [T],
    ) -> Result<(), crate::error::KError>;

    /// Get the number of rows
    fn nrows(&self) -> usize;

    /// Get the number of columns  
    fn ncols(&self) -> usize;
}

/// Sparse-aware dot product operations
pub trait DotOp<T> {
    /// Compute the dot product x^T * y
    fn dot(&self, x: &[T], y: &[T]) -> T;

    /// Compute the 2-norm of a vector
    fn norm2(&self, x: &[T]) -> T;
}

/// Implementation for sparse CSR matrices over the crate scalar.
impl MatVecOp<S> for crate::matrix::sparse::CsrMatrix<S> {
    fn mat_vec(&self, alpha: S, x: &[S], beta: S, y: &mut [S]) -> Result<(), crate::error::KError> {
        if x.len() != self.ncols() || y.len() != self.nrows() {
            return Err(crate::error::KError::InvalidInput(
                "Matrix-vector dimension mismatch".to_string(),
            ));
        }

        let rp = self.row_ptr();
        let cj = self.col_idx();
        let vv = self.values();

        #[cfg(debug_assertions)]
        {
            assert_eq!(rp.len(), self.nrows() + 1);
            assert!(rp.windows(2).all(|w| w[0] <= w[1]));
            let nnz = *rp.last().unwrap();
            assert_eq!(cj.len(), nnz);
            assert_eq!(vv.len(), nnz);
        }

        if alpha == S::zero() {
            if beta == S::zero() {
                for v in y.iter_mut() {
                    *v = S::zero();
                }
            } else if beta != S::one() {
                for v in y.iter_mut() {
                    *v = beta * *v;
                }
            }
            return Ok(());
        }

        let m = self.nrows();
        if beta == S::zero() {
            for i in 0..m {
                let rs = rp[i];
                let re = rp[i + 1];
                let mut acc = S::zero();
                for p in rs..re {
                    let j = cj[p];
                    acc = vv[p].mul_add(x[j], acc);
                }
                y[i] = alpha * acc;
            }
        } else if beta == S::one() {
            for i in 0..m {
                let rs = rp[i];
                let re = rp[i + 1];
                let mut acc = S::zero();
                for p in rs..re {
                    let j = cj[p];
                    acc = vv[p].mul_add(x[j], acc);
                }
                y[i] = y[i] + alpha * acc;
            }
        } else {
            for i in 0..m {
                let rs = rp[i];
                let re = rp[i + 1];
                let mut acc = S::zero();
                for p in rs..re {
                    let j = cj[p];
                    acc = vv[p].mul_add(x[j], acc);
                }
                y[i] = alpha * acc + beta * y[i];
            }
        }

        Ok(())
    }

    fn mat_vec_trans(
        &self,
        alpha: S,
        x: &[S],
        beta: S,
        y: &mut [S],
    ) -> Result<(), crate::error::KError> {
        if x.len() != self.nrows() || y.len() != self.ncols() {
            return Err(crate::error::KError::InvalidInput(
                "Matrix-vector dimension mismatch".to_string(),
            ));
        }

        let rp = self.row_ptr();
        let cj = self.col_idx();
        let vv = self.values();

        if alpha == S::zero() {
            if beta == S::zero() {
                for v in y.iter_mut() {
                    *v = S::zero();
                }
            } else {
                for v in y.iter_mut() {
                    *v = beta * *v;
                }
            }
            return Ok(());
        }

        if beta == S::zero() {
            for v in y.iter_mut() {
                *v = S::zero();
            }
        } else if beta != S::one() {
            for v in y.iter_mut() {
                *v = beta * *v;
            }
        }

        let m = self.nrows();
        for i in 0..m {
            let xi = x[i];
            if xi == S::zero() {
                continue;
            }
            let start = rp[i];
            let end = rp[i + 1];
            for k in start..end {
                let j = cj[k];
                y[j] = y[j] + alpha * vv[k] * xi;
            }
        }

        Ok(())
    }

    fn nrows(&self) -> usize {
        self.nrows()
    }
    fn ncols(&self) -> usize {
        self.ncols()
    }
}

#[cfg(feature = "backend-faer")]
impl MatVecOp<S> for faer::Mat<S> {
    fn mat_vec(&self, alpha: S, x: &[S], beta: S, y: &mut [S]) -> Result<(), crate::error::KError> {
        if x.len() != self.ncols() || y.len() != self.nrows() {
            return Err(crate::error::KError::InvalidInput(
                "Matrix-vector dimension mismatch".into(),
            ));
        }

        if beta == S::zero() {
            for value in y.iter_mut() {
                *value = S::zero();
            }
        } else if beta != S::one() {
            for value in y.iter_mut() {
                *value *= beta;
            }
        }

        let m = self.nrows();
        let n = self.ncols();
        for i in 0..m {
            let mut acc = S::zero();
            for j in 0..n {
                acc = self[(i, j)].mul_add(x[j], acc);
            }
            y[i] += alpha * acc;
        }
        Ok(())
    }

    fn mat_vec_trans(
        &self,
        alpha: S,
        x: &[S],
        beta: S,
        y: &mut [S],
    ) -> Result<(), crate::error::KError> {
        if x.len() != self.nrows() || y.len() != self.ncols() {
            return Err(crate::error::KError::InvalidInput(
                "Matrix-vector dimension mismatch".into(),
            ));
        }

        if beta == S::zero() {
            for value in y.iter_mut() {
                *value = S::zero();
            }
        } else if beta != S::one() {
            for value in y.iter_mut() {
                *value *= beta;
            }
        }

        let m = self.nrows();
        let n = self.ncols();
        for j in 0..n {
            let mut acc = S::zero();
            for i in 0..m {
                acc = self[(i, j)].mul_add(x[i], acc);
            }
            y[j] += alpha * acc;
        }
        Ok(())
    }

    fn nrows(&self) -> usize {
        self.nrows()
    }

    fn ncols(&self) -> usize {
        self.ncols()
    }
}

/// Standard dot product implementation
pub struct StandardDotOp;

impl DotOp<S> for StandardDotOp {
    fn dot(&self, x: &[S], y: &[S]) -> S {
        par_dot_conj_local(x, y)
    }

    fn norm2(&self, x: &[S]) -> S {
        S::from_real(par_sum_abs2_local(x).sqrt())
    }
}

#[cfg(feature = "complex")]
impl DotOp<f64> for StandardDotOp {
    fn dot(&self, x: &[f64], y: &[f64]) -> f64 {
        x.iter().zip(y.iter()).map(|(a, b)| a * b).sum()
    }

    fn norm2(&self, x: &[f64]) -> f64 {
        self.dot(x, x).sqrt()
    }
}

/// Unified kernel trait for local vs distributed operations
/// Provides a consistent interface for AMG operations that can work
/// both in single-process (local) and multi-process (MPI) scenarios
pub trait KernelOp<T: KrystScalar> {
    /// The communicator type for this kernel (e.g., UniverseComm for MPI, () for local)
    type Comm: crate::parallel::Comm;

    /// Matrix-vector product with communicator support: y = alpha * A * x + beta * y
    fn kernel_mat_vec(
        &self,
        matrix: &dyn MatVecOp<T>,
        alpha: T,
        x: &[T],
        beta: T,
        y: &mut [T],
        comm: &Self::Comm,
    ) -> Result<(), crate::error::KError>;

    /// Transpose matrix-vector product: y = alpha * A^T * x + beta * y (A^H for complex).
    fn kernel_mat_vec_trans(
        &self,
        matrix: &dyn MatVecOp<T>,
        alpha: T,
        x: &[T],
        beta: T,
        y: &mut [T],
        comm: &Self::Comm,
    ) -> Result<(), crate::error::KError>;

    /// Global dot product with reduction across processes
    fn kernel_dot(&self, x: &[T], y: &[T], comm: &Self::Comm) -> T;

    /// Global norm computation with reduction
    fn kernel_norm2(&self, x: &[T], comm: &Self::Comm) -> T;

    /// Vector operations: y = alpha * x + beta * y
    fn kernel_axpby(&self, alpha: T, x: &[T], beta: T, y: &mut [T]);

    /// Copy operation: y = x
    fn kernel_copy(&self, x: &[T], y: &mut [T]);

    /// Scale operation: x = alpha * x
    fn kernel_scale(&self, alpha: T, x: &mut [T]);

    /// Apply a local preconditioner: y = M^{-1} x.
    fn kernel_apply_preconditioner<P>(
        &self,
        preconditioner: &P,
        x: &[T],
        y: &mut [T],
        _comm: &Self::Comm,
    ) -> Result<(), crate::error::KError>
    where
        P: LocalPreconditioner<T>,
    {
        let (m, n) = preconditioner.dims();
        if (m != 0 && x.len() != m) || (n != 0 && y.len() != n) {
            return Err(crate::error::KError::InvalidInput(format!(
                "Preconditioner dimension mismatch: dims=({m}, {n}), x.len()={}, y.len()={}",
                x.len(),
                y.len()
            )));
        }

        preconditioner.apply_local(x, y)
    }
}

/// Local (single-process) kernel implementation
pub struct LocalKernel;

impl KernelOp<S> for LocalKernel {
    type Comm = crate::parallel::NoComm;

    fn kernel_mat_vec(
        &self,
        matrix: &dyn MatVecOp<S>,
        alpha: S,
        x: &[S],
        beta: S,
        y: &mut [S],
        _comm: &Self::Comm,
    ) -> Result<(), crate::error::KError> {
        // For local operations, no communication needed
        matrix.mat_vec(alpha, x, beta, y)
    }

    fn kernel_mat_vec_trans(
        &self,
        matrix: &dyn MatVecOp<S>,
        alpha: S,
        x: &[S],
        beta: S,
        y: &mut [S],
        _comm: &Self::Comm,
    ) -> Result<(), crate::error::KError> {
        matrix.mat_vec_trans(alpha, x, beta, y)
    }

    fn kernel_dot(&self, x: &[S], y: &[S], _comm: &Self::Comm) -> S {
        par_dot_conj_local(x, y)
    }

    fn kernel_norm2(&self, x: &[S], _comm: &Self::Comm) -> S {
        let norm_sq = par_sum_abs2_local(x);
        S::from_real(norm_sq.sqrt())
    }

    fn kernel_axpby(&self, alpha: S, x: &[S], beta: S, y: &mut [S]) {
        parallel::par_axpby(x, alpha, y, beta);
    }

    fn kernel_copy(&self, x: &[S], y: &mut [S]) {
        parallel::par_copy(x, y);
    }

    fn kernel_scale(&self, alpha: S, x: &mut [S]) {
        parallel::par_scale(alpha, x);
    }
}

/// Distributed (MPI) kernel implementation for future use
/// Currently a placeholder that delegates to local operations
#[cfg(feature = "mpi")]
pub struct DistributedKernel;

#[cfg(feature = "mpi")]
impl KernelOp<S> for DistributedKernel {
    type Comm = crate::parallel::UniverseComm;

    fn kernel_mat_vec(
        &self,
        matrix: &dyn MatVecOp<S>,
        alpha: S,
        x: &[S],
        beta: S,
        y: &mut [S],
        comm: &Self::Comm,
    ) -> Result<(), crate::error::KError> {
        let mut local = vec![S::zero(); y.len()];
        matrix.mat_vec(alpha, x, S::zero(), &mut local)?;
        comm.allreduce_sum_scalars(&mut local);

        if beta == S::zero() {
            parallel::par_copy(&local, y);
        } else {
            parallel::par_axpby(&local, S::one(), y, beta);
        }

        Ok(())
    }

    fn kernel_mat_vec_trans(
        &self,
        matrix: &dyn MatVecOp<S>,
        alpha: S,
        x: &[S],
        beta: S,
        y: &mut [S],
        comm: &Self::Comm,
    ) -> Result<(), crate::error::KError> {
        let mut local = vec![S::zero(); y.len()];
        matrix.mat_vec_trans(alpha, x, S::zero(), &mut local)?;
        comm.allreduce_sum_scalars(&mut local);

        if beta == S::zero() {
            parallel::par_copy(&local, y);
        } else {
            parallel::par_axpby(&local, S::one(), y, beta);
        }

        Ok(())
    }

    fn kernel_dot(&self, x: &[S], y: &[S], comm: &Self::Comm) -> S {
        let local_dot = par_dot_conj_local(x, y);
        comm.allreduce_sum_scalar(local_dot)
    }

    fn kernel_norm2(&self, x: &[S], comm: &Self::Comm) -> S {
        let local_sq = par_sum_abs2_local(x);
        let global_sq = comm.allreduce_sum_real(local_sq);
        S::from_real(global_sq.sqrt())
    }

    fn kernel_axpby(&self, alpha: S, x: &[S], beta: S, y: &mut [S]) {
        parallel::par_axpby(x, alpha, y, beta);
    }

    fn kernel_copy(&self, x: &[S], y: &mut [S]) {
        parallel::par_copy(x, y);
    }

    fn kernel_scale(&self, alpha: S, x: &mut [S]) {
        parallel::par_scale(alpha, x);
    }
}

/// Unified AMG kernel trait to eliminate code duplication between local and MPI variants
pub trait AmgKernel {
    /// Associated communicator type
    type Comm: crate::parallel::Comm;

    /// Matrix-vector multiplication with alpha/beta scaling
    fn matvec<M>(
        &self,
        alpha: S,
        a: &M,
        x: &[S],
        beta: S,
        y: &mut [S],
        comm: &Self::Comm,
    ) -> Result<(), crate::error::KError>
    where
        M: MatVecOp<S>;

    /// Global dot product with communicator reduction
    fn dot(&self, x: &[S], y: &[S], comm: &Self::Comm) -> S;

    /// Global norm with communicator reduction
    fn norm(&self, x: &[S], comm: &Self::Comm) -> S {
        S::from_real(self.dot(x, x, comm).abs().sqrt())
    }

    /// Vector scaling: x = alpha * x
    fn scale(&self, alpha: S, x: &mut [S]);

    /// Vector copy: y = x
    fn copy(&self, x: &[S], y: &mut [S]);

    /// AXPY operation: y = alpha * x + y
    fn axpy(&self, alpha: S, x: &[S], y: &mut [S]);

    /// Apply a local preconditioner: y = M^{-1} x.
    fn apply_preconditioner<P>(
        &self,
        preconditioner: &P,
        x: &[S],
        y: &mut [S],
        _comm: &Self::Comm,
    ) -> Result<(), crate::error::KError>
    where
        P: LocalPreconditioner<S>,
    {
        let (m, n) = preconditioner.dims();
        if (m != 0 && x.len() != m) || (n != 0 && y.len() != n) {
            return Err(crate::error::KError::InvalidInput(format!(
                "Preconditioner dimension mismatch: dims=({m}, {n}), x.len()={}, y.len()={}",
                x.len(),
                y.len()
            )));
        }

        preconditioner.apply_local(x, y)
    }
}

/// Local (single-process) AMG kernel implementation
pub struct LocalAmgKernel;

impl LocalAmgKernel {
    pub fn new() -> Self {
        Self
    }
}

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

impl AmgKernel for LocalAmgKernel {
    type Comm = crate::parallel::NoComm;

    fn matvec<M>(
        &self,
        alpha: S,
        a: &M,
        x: &[S],
        beta: S,
        y: &mut [S],
        _comm: &Self::Comm,
    ) -> Result<(), crate::error::KError>
    where
        M: MatVecOp<S>,
    {
        a.mat_vec(alpha, x, beta, y)
    }

    fn dot(&self, x: &[S], y: &[S], _comm: &Self::Comm) -> S {
        par_dot_conj_local(x, y)
    }

    fn scale(&self, alpha: S, x: &mut [S]) {
        parallel::par_scale(alpha, x);
    }

    fn copy(&self, x: &[S], y: &mut [S]) {
        parallel::par_copy(x, y);
    }

    fn axpy(&self, alpha: S, x: &[S], y: &mut [S]) {
        parallel::par_axpy(x, alpha, y);
    }
}

#[cfg(feature = "mpi")]
/// Distributed (MPI) AMG kernel implementation
pub struct DistributedAmgKernel;

#[cfg(feature = "mpi")]
impl DistributedAmgKernel {
    pub fn new() -> Self {
        Self
    }
}

#[cfg(feature = "mpi")]
impl Default for DistributedAmgKernel {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "mpi")]
impl AmgKernel for DistributedAmgKernel {
    type Comm = crate::parallel::UniverseComm;

    fn matvec<M>(
        &self,
        alpha: S,
        a: &M,
        x: &[S],
        beta: S,
        y: &mut [S],
        comm: &Self::Comm,
    ) -> Result<(), crate::error::KError>
    where
        M: MatVecOp<S>,
    {
        let mut local = vec![S::zero(); y.len()];
        a.mat_vec(alpha, x, S::zero(), &mut local)?;
        comm.allreduce_sum_scalars(&mut local);

        if beta == S::zero() {
            parallel::par_copy(&local, y);
        } else {
            parallel::par_axpby(&local, S::one(), y, beta);
        }

        Ok(())
    }

    fn dot(&self, x: &[S], y: &[S], comm: &Self::Comm) -> S {
        let local_dot = par_dot_conj_local(x, y);
        comm.allreduce_sum_scalar(local_dot)
    }

    fn scale(&self, alpha: S, x: &mut [S]) {
        parallel::par_scale(alpha, x);
    }

    fn copy(&self, x: &[S], y: &mut [S]) {
        parallel::par_copy(x, y);
    }

    fn axpy(&self, alpha: S, x: &[S], y: &mut [S]) {
        parallel::par_axpy(x, alpha, y);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::matrix::sparse::CsrMatrix;
    use crate::parallel::NoComm;

    // Simple test to verify traits can be imported and used
    #[test]
    fn test_traits_exist() {
        // This test just verifies that all traits compile and can be referenced
        // More comprehensive tests would require mock implementations

        // Test that trait bounds can be specified
        fn _test_matvec_bound<T, V>(_: &T)
        where
            T: MatVec<V>,
        {
        }
        fn _test_mattransvec_bound<T, V>(_: &T)
        where
            T: MatTransVec<V>,
        {
        }
        fn _test_inner_product_bound<T, V>(_: &T)
        where
            T: InnerProduct<V>,
        {
        }
        fn _test_indexing_bound<T>(_: &T)
        where
            T: Indexing,
        {
        }
        fn _test_mat_shape_bound<T>(_: &T)
        where
            T: MatShape,
        {
        }
        fn _test_row_pattern_bound<T>(_: &T)
        where
            T: RowPattern,
        {
        }
        fn _test_matrix_get_bound<T, U>(_: &T)
        where
            T: MatrixGet<U>,
        {
        }
        fn _test_submatrix_extract_bound<T>(_: &T)
        where
            T: SubmatrixExtract,
        {
        }

        // All traits should compile
        assert!(true);
    }

    #[test]
    fn test_inner_product_scalar_trait_bounds() {
        // Test that the associated Scalar type has the required bounds
        fn _check_scalar_bounds<T: Copy + PartialOrd + From<f64> + Into<f64>>() {}

        // Use the real partner of S for bound checking
        _check_scalar_bounds::<R>();

        assert!(true);
    }

    #[test]
    fn test_trait_names_and_methods() {
        // Verify method names exist by checking trait signatures
        trait TestMatVec<V> {
            fn matvec(&self, x: &V, y: &mut V);
        }

        trait TestMatTransVec<V> {
            fn mattransvec(&self, x: &V, y: &mut V);
        }

        trait TestInnerProduct<V> {
            type Scalar: Copy;
            fn dot(&self, x: &V, y: &V, _comm: &impl crate::parallel::Comm) -> Self::Scalar;
        }
        struct Dummy;

        impl TestMatVec<Vec<S>> for Dummy {
            fn matvec(&self, _x: &Vec<S>, _y: &mut Vec<S>) {}
        }

        impl TestMatTransVec<Vec<S>> for Dummy {
            fn mattransvec(&self, _x: &Vec<S>, _y: &mut Vec<S>) {}
        }

        impl TestInnerProduct<Vec<S>> for Dummy {
            type Scalar = S;
            fn dot(
                &self,
                _x: &Vec<S>,
                _y: &Vec<S>,
                _comm: &impl crate::parallel::Comm,
            ) -> Self::Scalar {
                S::zero()
            }
        }

        fn _use_traits<
            T: TestMatVec<Vec<S>> + TestMatTransVec<Vec<S>> + TestInnerProduct<Vec<S>>,
        >() {
        }
        _use_traits::<Dummy>();

        let dummy = Dummy;
        let comm = crate::parallel::NoComm;
        let v = vec![S::zero(); 1];
        let mut y = vec![S::zero(); 1];
        dummy.matvec(&v, &mut y);
        dummy.mattransvec(&v, &mut y);
        let _ = dummy.dot(&v, &v, &comm);

        // All method signatures should compile without panicking.
    }

    #[test]
    fn csr_matvec_happy_path() {
        // 2x3 CSR: row_ptr=[0,2,3], col_idx=[0,2,1], val=[1,4,5]
        // A = [1 0 4; 0 5 0]
        let a = CsrMatrix::from_csr(
            2,
            3,
            vec![0, 2, 3],
            vec![0, 2, 1],
            vec![S::from_real(1.0), S::from_real(4.0), S::from_real(5.0)],
        );
        let x = [S::from_real(10.0), S::from_real(20.0), S::from_real(30.0)];
        let mut y = [S::zero(); 2];
        MatVecOp::mat_vec(&a, S::one(), &x, S::zero(), &mut y).unwrap();
        let expected = [S::from_real(130.0), S::from_real(100.0)];
        for (got, target) in y.iter().zip(expected.iter()) {
            assert!(((*got) - *target).abs() < 1e-12);
        }
        // with scaling
        let mut y2 = [S::from_real(1.0), S::from_real(2.0)];
        MatVecOp::mat_vec(&a, S::from_real(2.0), &x, S::from_real(3.0), &mut y2).unwrap();
        // 2*A*x + 3*y0
        let expect0 = S::from_real(2.0 * 130.0 + 3.0 * 1.0);
        let expect1 = S::from_real(2.0 * 100.0 + 3.0 * 2.0);
        assert!((y2[0] - expect0).abs() < 1e-12);
        assert!((y2[1] - expect1).abs() < 1e-12);
    }

    struct DummyPc;

    impl LocalPreconditioner for DummyPc {
        fn dims(&self) -> (usize, usize) {
            (2, 2)
        }

        fn apply_local(&self, x: &[S], y: &mut [S]) -> Result<(), KError> {
            y.copy_from_slice(x);
            Ok(())
        }
    }

    #[test]
    fn kernel_apply_preconditioner_respects_dims() {
        let pc = DummyPc;
        let kernel = LocalKernel;
        let comm = NoComm;

        let mut y = vec![S::zero(); 2];
        kernel
            .kernel_apply_preconditioner(&pc, &[S::one(), S::from_real(2.0)], &mut y, &comm)
            .unwrap();
        assert_eq!(y, vec![S::one(), S::from_real(2.0)]);

        let err = kernel.kernel_apply_preconditioner(&pc, &[S::one()], &mut y, &comm);
        assert!(matches!(err, Err(KError::InvalidInput(_))));
    }
}