scirs2-cluster 0.3.4

Clustering algorithms module for SciRS2 (scirs2-cluster)
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
//! Enhanced K-means clustering implementation with multiple initialization methods

use scirs2_core::ndarray::{s, Array1, Array2, ArrayView2};
use scirs2_core::numeric::{Float, FromPrimitive};
use scirs2_core::random::{rngs::StdRng, Rng, RngExt, SeedableRng};
use scirs2_core::random::{Distribution, Normal};
use std::fmt::Debug;
use std::str::FromStr;

use super::{euclidean_distance, vq};
use crate::error::{ClusteringError, Result};
use scirs2_core::validation::{clustering::*, parameters::*};

/// Initialization methods for kmeans2
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MinitMethod {
    /// Generate k centroids from a Gaussian with mean and variance estimated from the data
    Random,
    /// Choose k observations (rows) at random from data for the initial centroids
    Points,
    /// K-means++ initialization (careful seeding)
    PlusPlus,
}

impl MinitMethod {
    /// Parse a string into a MinitMethod (SciPy-compatible)
    ///
    /// # Arguments
    ///
    /// * `s` - String representation of the initialization method
    ///
    /// # Returns
    ///
    /// * The corresponding MinitMethod enum value
    ///
    /// # Errors
    ///
    /// * Returns an error if the string is not recognized
    pub fn parse_method(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "random" => Ok(MinitMethod::Random),
            "points" => Ok(MinitMethod::Points),
            "k-means++" | "kmeans++" | "plusplus" => Ok(MinitMethod::PlusPlus),
            _ => Err(ClusteringError::InvalidInput(format!(
                "Unknown initialization method: '{}'. Valid options are: 'random', 'points', 'k-means++'",
                s
            ))),
        }
    }
}

impl FromStr for MinitMethod {
    type Err = ClusteringError;

    fn from_str(s: &str) -> Result<Self> {
        Self::parse_method(s)
    }
}

/// Methods for handling empty clusters during K-means clustering
///
/// When a cluster becomes empty during the K-means iteration process,
/// this enum determines how the algorithm should respond.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingMethod {
    /// Give a warning and continue with the algorithm
    ///
    /// The algorithm will continue execution, potentially with fewer
    /// effective clusters than originally requested.
    Warn,
    /// Raise a ClusteringError and terminate the algorithm
    ///
    /// The algorithm will stop execution and return an error when
    /// an empty cluster is encountered.
    Raise,
}

/// Enhanced K-means clustering algorithm compatible with SciPy's kmeans2
///
/// # Arguments
///
/// * `data` - Input data (n_samples × n_features) or pre-computed centroids if minit is None
/// * `k` - Number of clusters or initial centroids array
/// * `iter` - Number of iterations
/// * `thresh` - Convergence threshold (not used yet)
/// * `minit` - Initialization method (None if k is a centroid array)
/// * `missing` - Method to handle empty clusters
/// * `check_finite` - Whether to check input validity
/// * `randomseed` - Optional random seed
///
/// # Returns
///
/// * Tuple of (centroids, labels) where:
///   - centroids: Array of shape (k × n_features)
///   - labels: Array of shape (n_samples,) with cluster assignments
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub fn kmeans2<F>(
    data: ArrayView2<F>,
    k: usize,
    iter: Option<usize>,
    thresh: Option<F>,
    minit: Option<MinitMethod>,
    missing: Option<MissingMethod>,
    check_finite: Option<bool>,
    randomseed: Option<u64>,
) -> Result<(Array2<F>, Array1<usize>)>
where
    F: Float + FromPrimitive + Debug + std::iter::Sum + std::fmt::Display,
{
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];
    let iterations = iter.unwrap_or(10);
    let threshold = thresh.unwrap_or(F::from(1e-5).expect("Failed to convert constant to float"));
    let missing_method = missing.unwrap_or(MissingMethod::Warn);
    let check_finite_flag = check_finite.unwrap_or(true);

    // Use unified validation
    validate_clustering_data(&data, "K-means", check_finite_flag, Some(k))
        .map_err(|e| ClusteringError::InvalidInput(format!("K-means: {}", e)))?;

    check_n_clusters_bounds(&data, k, "K-means")
        .map_err(|e| ClusteringError::InvalidInput(format!("{}", e)))?;

    check_iteration_params(iterations, threshold, "K-means")
        .map_err(|e| ClusteringError::InvalidInput(format!("{}", e)))?;

    // Initialize centroids
    let init_method = minit.unwrap_or(MinitMethod::PlusPlus); // Default to k-means++
    let mut centroids = match init_method {
        MinitMethod::Random => krandinit(data, k, randomseed)?,
        MinitMethod::Points => kpoints(data, k, randomseed)?,
        MinitMethod::PlusPlus => kmeans_plus_plus(data, k, randomseed)?,
    };

    let mut labels;

    // Run K-means iterations
    for _iteration in 0..iterations {
        // Store previous centroids for convergence check
        let prev_centroids = centroids.clone();

        // Assign samples to nearest centroid
        let (new_labels, _distances) = vq(data, centroids.view())?;
        labels = new_labels;

        // Compute new centroids
        let mut new_centroids = Array2::zeros((k, n_features));
        let mut counts = Array1::zeros(k);

        for i in 0..n_samples {
            let cluster = labels[i];
            let point = data.slice(s![i, ..]);

            for j in 0..n_features {
                new_centroids[[cluster, j]] = new_centroids[[cluster, j]] + point[j];
            }

            counts[cluster] += 1;
        }

        // Handle empty clusters
        for i in 0..k {
            if counts[i] == 0 {
                match missing_method {
                    MissingMethod::Warn => {
                        eprintln!("One of the clusters is empty. Re-run kmeans with a different initialization.");
                        // Find point furthest from its centroid
                        let mut max_dist = F::zero();
                        let mut far_idx = 0;

                        for j in 0..n_samples {
                            let cluster_j = labels[j];
                            let dist = euclidean_distance(
                                data.slice(s![j, ..]),
                                centroids.slice(s![cluster_j, ..]),
                            );
                            if dist > max_dist {
                                max_dist = dist;
                                far_idx = j;
                            }
                        }

                        // Move this point to the empty cluster
                        for j in 0..n_features {
                            new_centroids[[i, j]] = data[[far_idx, j]];
                        }
                        counts[i] = 1;
                    }
                    MissingMethod::Raise => {
                        return Err(ClusteringError::EmptyCluster(
                            "One of the clusters is empty. Re-run kmeans with a different initialization.".to_string()
                        ));
                    }
                }
            } else {
                // Normalize by the number of points in the cluster
                for j in 0..n_features {
                    new_centroids[[i, j]] = new_centroids[[i, j]]
                        / F::from(counts[i]).expect("Failed to convert to float");
                }
            }
        }

        centroids = new_centroids;

        // Check for convergence
        let mut max_centroid_shift = F::zero();
        for i in 0..k {
            for j in 0..n_features {
                let shift = (centroids[[i, j]] - prev_centroids[[i, j]]).abs();
                if shift > max_centroid_shift {
                    max_centroid_shift = shift;
                }
            }
        }

        // If convergence reached, break early
        if max_centroid_shift < threshold {
            break;
        }
    }

    // Final assignment
    let (final_labels, _distances) = vq(data, centroids.view())?;

    Ok((centroids, final_labels))
}

/// SciPy-compatible K-means clustering with string-based parameters
///
/// This function provides an interface compatible with SciPy's kmeans2,
/// accepting string-based initialization methods.
///
/// # Arguments
///
/// * `data` - Input data (n_samples × n_features)
/// * `k` - Number of clusters
/// * `iter` - Number of iterations
/// * `thresh` - Convergence threshold
/// * `minit` - Initialization method as string ('random', 'points', 'k-means++')
/// * `missing` - Method to handle empty clusters ('warn', 'raise')
/// * `check_finite` - Whether to check input validity
/// * `randomseed` - Optional random seed
///
/// # Returns
///
/// * Tuple of (centroids, labels) where:
///   - centroids: Array of shape (k × n_features)
///   - labels: Array of shape (n_samples,) with cluster assignments
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_cluster::vq::kmeans2_str;
///
/// let data = Array2::from_shape_vec((6, 2), vec![
///     1.0, 1.0, 1.1, 1.1, 0.9, 0.9,
///     8.0, 8.0, 8.1, 8.1, 7.9, 7.9,
/// ]).expect("Operation failed");
///
/// let (centroids, labels) = kmeans2_str(
///     data.view(), 2, Some(20), Some(1e-5), Some("k-means++"),
///     Some("warn"), Some(true), Some(42)
/// ).expect("Operation failed");
/// ```
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub fn kmeans2_str<F>(
    data: ArrayView2<F>,
    k: usize,
    iter: Option<usize>,
    thresh: Option<F>,
    minit: Option<&str>,
    missing: Option<&str>,
    check_finite: Option<bool>,
    randomseed: Option<u64>,
) -> Result<(Array2<F>, Array1<usize>)>
where
    F: Float + FromPrimitive + Debug + std::iter::Sum + std::fmt::Display,
{
    // Parse string parameters
    let minit_method = if let Some(method_str) = minit {
        Some(MinitMethod::from_str(method_str)?)
    } else {
        Some(MinitMethod::PlusPlus) // Default to k-means++ like SciPy
    };

    let missing_method = if let Some(missing_str) = missing {
        match missing_str.to_lowercase().as_str() {
            "warn" => Some(MissingMethod::Warn),
            "raise" => Some(MissingMethod::Raise),
            _ => {
                return Err(ClusteringError::InvalidInput(format!(
                    "Unknown missing method: '{}'. Valid options are: 'warn', 'raise'",
                    missing_str
                )))
            }
        }
    } else {
        Some(MissingMethod::Warn) // Default to warn like SciPy
    };

    // Call the main kmeans2 function
    kmeans2(
        data,
        k,
        iter,
        thresh,
        minit_method,
        missing_method,
        check_finite,
        randomseed,
    )
}

/// Random initialization: generate k centroids from a Gaussian with mean and
/// variance estimated from the data
#[allow(dead_code)]
fn krandinit<F>(data: ArrayView2<F>, k: usize, randomseed: Option<u64>) -> Result<Array2<F>>
where
    F: Float + FromPrimitive + Debug + std::iter::Sum,
{
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];

    // Calculate mean and variance for each feature
    let mut means = Array1::<F>::zeros(n_features);
    let mut vars = Array1::<F>::zeros(n_features);

    for j in 0..n_features {
        let mut sum = F::zero();
        for i in 0..n_samples {
            sum = sum + data[[i, j]];
        }
        means[j] = sum / F::from(n_samples).expect("Failed to convert to float");

        let mut var_sum = F::zero();
        for i in 0..n_samples {
            let diff = data[[i, j]] - means[j];
            var_sum = var_sum + diff * diff;
        }
        vars[j] = var_sum / F::from(n_samples).expect("Failed to convert to float");
    }

    // Generate random centroids from Gaussian distribution
    let mut centroids = Array2::<F>::zeros((k, n_features));

    let mut rng: Box<dyn Rng> = if let Some(_seed) = randomseed {
        Box::new(StdRng::seed_from_u64(_seed))
    } else {
        Box::new(scirs2_core::random::rng())
    };

    for i in 0..k {
        for j in 0..n_features {
            // Convert to f64 for normal distribution
            let mean = means[j].to_f64().expect("Operation failed");
            let std = vars[j].sqrt().to_f64().expect("Operation failed");

            if std > 0.0 {
                let normal = Normal::new(mean, std).expect("Operation failed");
                let value = normal.sample(&mut rng);
                centroids[[i, j]] = F::from(value).expect("Failed to convert to float");
            } else {
                centroids[[i, j]] = means[j];
            }
        }
    }

    Ok(centroids)
}

/// Points initialization: choose k observations (rows) at random from data
#[allow(dead_code)]
fn kpoints<F>(data: ArrayView2<F>, k: usize, randomseed: Option<u64>) -> Result<Array2<F>>
where
    F: Float + FromPrimitive + Debug,
{
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];

    let mut rng: Box<dyn Rng> = if let Some(_seed) = randomseed {
        Box::new(StdRng::seed_from_u64(_seed))
    } else {
        Box::new(scirs2_core::random::rng())
    };

    // Choose k random indices without replacement
    let mut indices: Vec<usize> = (0..n_samples).collect();

    // Shuffle and take first k
    for i in 0..k {
        let j = rng.random_range(i..n_samples);
        indices.swap(i, j);
    }

    // Extract centroids from _data
    let mut centroids = Array2::zeros((k, n_features));
    for i in 0..k {
        let idx = indices[i];
        for j in 0..n_features {
            centroids[[i, j]] = data[[idx, j]];
        }
    }

    Ok(centroids)
}

/// K-means++ initialization
#[allow(dead_code)]
fn kmeans_plus_plus<F>(data: ArrayView2<F>, k: usize, randomseed: Option<u64>) -> Result<Array2<F>>
where
    F: Float + FromPrimitive + Debug + std::iter::Sum,
{
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];

    let mut rng: Box<dyn Rng> = if let Some(_seed) = randomseed {
        Box::new(StdRng::seed_from_u64(_seed))
    } else {
        Box::new(scirs2_core::random::rng())
    };

    let mut centroids = Array2::zeros((k, n_features));

    // Choose first centroid randomly
    let first_idx = rng.random_range(0..n_samples);
    for j in 0..n_features {
        centroids[[0, j]] = data[[first_idx, j]];
    }

    // Choose remaining centroids
    for i in 1..k {
        // Calculate squared distances to nearest centroid
        let mut distances = Array1::<F>::zeros(n_samples);

        for j in 0..n_samples {
            let mut min_dist = F::infinity();
            for c in 0..i {
                let dist = euclidean_distance(data.slice(s![j, ..]), centroids.slice(s![c, ..]));
                if dist < min_dist {
                    min_dist = dist;
                }
            }
            distances[j] = min_dist * min_dist;
        }

        // Calculate probabilities
        let total = distances.iter().fold(F::zero(), |a, &b| a + b);
        let mut probabilities = Array1::<F>::zeros(n_samples);
        for j in 0..n_samples {
            probabilities[j] = distances[j] / total;
        }

        // Choose next centroid based on weighted probability
        let mut cumsum = F::zero();
        let r = F::from(rng.random::<f64>()).expect("Operation failed");
        let mut next_idx = n_samples - 1;

        for j in 0..n_samples {
            cumsum = cumsum + probabilities[j];
            if cumsum > r {
                next_idx = j;
                break;
            }
        }

        // Add chosen centroid
        for j in 0..n_features {
            centroids[[i, j]] = data[[next_idx, j]];
        }
    }

    Ok(centroids)
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use scirs2_core::ndarray::{array, Array2};

    #[test]
    fn test_kmeans2_basic_functionality() {
        let data = array![
            [1.0, 1.0],
            [1.5, 1.5],
            [0.8, 0.9],
            [8.0, 8.0],
            [8.2, 8.1],
            [7.8, 7.9],
        ];

        let (centroids, labels) = kmeans2(
            data.view(),
            2,
            Some(50),
            Some(1e-6),
            Some(MinitMethod::PlusPlus),
            Some(MissingMethod::Warn),
            Some(true),
            Some(42),
        )
        .expect("Test: operation failed");

        // Should have 2 centroids
        assert_eq!(centroids.shape(), [2, 2]);

        // Should have labels for all 6 points
        assert_eq!(labels.len(), 6);

        // All labels should be 0 or 1
        assert!(labels.iter().all(|&l| l == 0 || l == 1));

        // Should have points from both clusters
        let unique_labels: std::collections::HashSet<_> = labels.iter().cloned().collect();
        assert_eq!(unique_labels.len(), 2);
    }

    #[test]
    fn test_kmeans2_parameter_validation() {
        let data = array![[1.0, 1.0], [2.0, 2.0]];

        // Test k=0 (invalid)
        let result = kmeans2(
            data.view(),
            0,
            None,
            None,
            Some(MinitMethod::Random),
            None,
            None,
            None,
        );
        assert!(result.is_err());

        // Test k > n_samples (invalid)
        let result = kmeans2(
            data.view(),
            5,
            None,
            None,
            Some(MinitMethod::Random),
            None,
            None,
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_kmeans2_initialization_methods() {
        let data = array![
            [1.0, 1.0],
            [1.5, 1.5],
            [0.8, 0.9],
            [8.0, 8.0],
            [8.2, 8.1],
            [7.8, 7.9],
        ];

        let methods = vec![
            MinitMethod::Random,
            MinitMethod::Points,
            MinitMethod::PlusPlus,
        ];

        for method in methods {
            let result = kmeans2(
                data.view(),
                2,
                Some(10),
                None,
                Some(method),
                Some(MissingMethod::Warn),
                None,
                Some(42),
            );

            assert!(result.is_ok(), "Failed with method: {:?}", method);
            let (centroids, labels) = result.expect("Test: operation failed");
            assert_eq!(centroids.shape(), [2, 2]);
            assert_eq!(labels.len(), 6);
        }
    }

    #[test]
    fn test_kmeans2_reproducibility_with_seed() {
        let data = array![
            [1.0, 1.0],
            [1.5, 1.5],
            [0.8, 0.9],
            [8.0, 8.0],
            [8.2, 8.1],
            [7.8, 7.9],
        ];

        let (centroids1, labels1) = kmeans2(
            data.view(),
            2,
            Some(10),
            None,
            Some(MinitMethod::Random),
            None,
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        let (centroids2, labels2) = kmeans2(
            data.view(),
            2,
            Some(10),
            None,
            Some(MinitMethod::Random),
            None,
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        // With same seed, results should be identical
        assert_eq!(labels1, labels2);

        // Centroids should be very close (allowing for floating point precision)
        for i in 0..centroids1.shape()[0] {
            for j in 0..centroids1.shape()[1] {
                assert_abs_diff_eq!(centroids1[[i, j]], centroids2[[i, j]], epsilon = 1e-10);
            }
        }
    }

    #[test]
    fn test_kmeans2_single_cluster() {
        let data = array![[1.0, 1.0], [1.1, 1.1], [0.9, 0.9],];

        let (centroids, labels) = kmeans2(
            data.view(),
            1,
            Some(10),
            None,
            Some(MinitMethod::Points),
            None,
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        // Should have 1 centroid
        assert_eq!(centroids.shape(), [1, 2]);

        // All labels should be 0
        assert!(labels.iter().all(|&l| l == 0));
    }

    #[test]
    fn test_kmeans2_identical_points() {
        let data = array![[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0],];

        let (centroids, labels) = kmeans2(
            data.view(),
            2,
            Some(10),
            None,
            Some(MinitMethod::Points),
            Some(MissingMethod::Warn),
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        // Should still produce valid results
        assert_eq!(centroids.shape(), [2, 2]);
        assert_eq!(labels.len(), 4);

        // All labels should be valid (0 or 1)
        assert!(labels.iter().all(|&l| l == 0 || l == 1));
    }

    #[test]
    fn test_kmeans2_missing_method_warn() {
        // Create data that might lead to empty clusters
        let data = array![[0.0, 0.0], [0.1, 0.1], [10.0, 10.0],];

        let result = kmeans2(
            data.view(),
            2,
            Some(5),
            None,
            Some(MinitMethod::Random),
            Some(MissingMethod::Warn),
            None,
            Some(123),
        );

        // Should succeed with warning
        assert!(result.is_ok());
    }

    #[test]
    fn test_kmeans2_convergence_behavior() {
        // Create well-separated clusters
        let data = array![
            [1.0, 1.0],
            [1.1, 1.1],
            [0.9, 0.9],
            [10.0, 10.0],
            [10.1, 10.1],
            [9.9, 9.9],
        ];

        // Test with different iteration counts
        let (centroids_few_) = kmeans2(
            data.view(),
            2,
            Some(1),
            None,
            Some(MinitMethod::PlusPlus),
            None,
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        let (centroids_many_) = kmeans2(
            data.view(),
            2,
            Some(100),
            None,
            Some(MinitMethod::PlusPlus),
            None,
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        // Results should be valid for both
        assert_eq!(centroids_few_.0.shape(), [2, 2]);
        assert_eq!(centroids_many_.0.shape(), [2, 2]);
    }

    #[test]
    fn test_kmeans2_high_k() {
        let data = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0], [5.0, 5.0],];

        // Test with k equal to number of points
        let (centroids, labels) = kmeans2(
            data.view(),
            5,
            Some(10),
            None,
            Some(MinitMethod::Points),
            None,
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        assert_eq!(centroids.shape(), [5, 2]);
        assert_eq!(labels.len(), 5);

        // Each point should be its own cluster
        let unique_labels: std::collections::HashSet<_> = labels.iter().cloned().collect();
        assert_eq!(unique_labels.len(), 5);
    }

    #[test]
    fn test_kmeans2_different_thresholds() {
        let data = array![[1.0, 1.0], [1.5, 1.5], [8.0, 8.0], [8.5, 8.5],];

        // Test with different convergence thresholds
        let result1 = kmeans2(
            data.view(),
            2,
            Some(100),
            Some(1e-10), // Very strict
            Some(MinitMethod::PlusPlus),
            None,
            None,
            Some(42),
        );

        let result2 = kmeans2(
            data.view(),
            2,
            Some(100),
            Some(1e-1), // Very loose
            Some(MinitMethod::PlusPlus),
            None,
            None,
            Some(42),
        );

        assert!(result1.is_ok());
        assert!(result2.is_ok());
    }

    #[test]
    fn test_kmeans2_convergence_threshold() {
        // Test early convergence with well-separated clusters
        let data = array![
            [1.0, 1.0],
            [1.1, 1.1],
            [0.9, 0.9],
            [10.0, 10.0],
            [10.1, 10.1],
            [9.9, 9.9],
        ];

        // With a tight threshold, should converge quickly
        let result1 = kmeans2(
            data.view(),
            2,
            Some(100),   // Allow many iterations
            Some(1e-10), // Very strict threshold - should converge quickly
            Some(MinitMethod::PlusPlus),
            None,
            None,
            Some(42),
        );

        assert!(result1.is_ok());
        let (centroids1, labels1) = result1.expect("Test: operation failed");
        assert_eq!(centroids1.shape(), [2, 2]);
        assert_eq!(labels1.len(), 6);

        // With a loose threshold, should also work
        let result2 = kmeans2(
            data.view(),
            2,
            Some(100),
            Some(1e-1), // Very loose threshold
            Some(MinitMethod::PlusPlus),
            None,
            None,
            Some(42),
        );

        assert!(result2.is_ok());
        let (centroids2, labels2) = result2.expect("Test: operation failed");
        assert_eq!(centroids2.shape(), [2, 2]);
        assert_eq!(labels2.len(), 6);
    }

    #[test]
    fn test_kmeans2_check_finite() {
        // Test with finite data (should work)
        let data = array![[1.0, 2.0], [1.5, 1.5], [8.0, 8.0],];

        let result = kmeans2(
            data.view(),
            2,
            Some(10),
            None,
            Some(MinitMethod::Random),
            None,
            Some(true), // check_finite = true
            Some(42),
        );
        assert!(result.is_ok());

        // Test with check_finite disabled (should also work with finite data)
        let result = kmeans2(
            data.view(),
            2,
            Some(10),
            None,
            Some(MinitMethod::Random),
            None,
            Some(false), // check_finite = false
            Some(42),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_kmeans2_large_dataset() {
        // Generate a larger dataset for stress testing
        let mut data = Array2::zeros((100, 3));

        // Create 3 clusters
        for i in 0..100 {
            let cluster = i % 3;
            match cluster {
                0 => {
                    data[[i, 0]] = 1.0 + (i as f64) * 0.01;
                    data[[i, 1]] = 1.0 + (i as f64) * 0.01;
                    data[[i, 2]] = 1.0 + (i as f64) * 0.01;
                }
                1 => {
                    data[[i, 0]] = 5.0 + (i as f64) * 0.01;
                    data[[i, 1]] = 5.0 + (i as f64) * 0.01;
                    data[[i, 2]] = 5.0 + (i as f64) * 0.01;
                }
                2 => {
                    data[[i, 0]] = 10.0 + (i as f64) * 0.01;
                    data[[i, 1]] = 10.0 + (i as f64) * 0.01;
                    data[[i, 2]] = 10.0 + (i as f64) * 0.01;
                }
                _ => unreachable!(),
            }
        }

        let (centroids, labels) = kmeans2(
            data.view(),
            3,
            Some(50),
            None,
            Some(MinitMethod::PlusPlus),
            None,
            None,
            Some(42),
        )
        .expect("Test: operation failed");

        assert_eq!(centroids.shape(), [3, 3]);
        assert_eq!(labels.len(), 100);

        // Should find 3 clusters
        let unique_labels: std::collections::HashSet<_> = labels.iter().cloned().collect();
        assert_eq!(unique_labels.len(), 3);
    }

    // Tests for string-based parameter support
    use super::kmeans2_str;

    #[test]
    fn test_kmeans2_str_basic_functionality() {
        let data = array![
            [1.0, 1.0],
            [1.5, 1.5],
            [0.8, 0.9],
            [8.0, 8.0],
            [8.2, 8.1],
            [7.8, 7.9],
        ];

        let (centroids, labels) = kmeans2_str(
            data.view(),
            2,
            Some(50),
            Some(1e-6),
            Some("k-means++"),
            Some("warn"),
            Some(true),
            Some(42),
        )
        .expect("Test: operation failed");

        assert_eq!(centroids.shape(), [2, 2]);
        assert_eq!(labels.len(), 6);
        assert!(labels.iter().all(|&l| l == 0 || l == 1));

        let unique_labels: std::collections::HashSet<_> = labels.iter().cloned().collect();
        assert_eq!(unique_labels.len(), 2);
    }

    #[test]
    fn test_kmeans2_str_all_init_methods() {
        let data = array![
            [1.0, 1.0],
            [1.5, 1.5],
            [0.8, 0.9],
            [8.0, 8.0],
            [8.2, 8.1],
            [7.8, 7.9],
        ];

        let methods = vec!["random", "points", "k-means++", "kmeans++", "plusplus"];

        for method in methods {
            let result = kmeans2_str(
                data.view(),
                2,
                Some(10),
                None,
                Some(method),
                Some("warn"),
                None,
                Some(42),
            );

            assert!(result.is_ok(), "Failed with method: '{}'", method);
            let (centroids, labels) = result.expect("Test: operation failed");
            assert_eq!(centroids.shape(), [2, 2]);
            assert_eq!(labels.len(), 6);
        }
    }

    #[test]
    fn test_kmeans2_str_case_insensitive() {
        let data = array![[1.0, 1.0], [2.0, 2.0], [8.0, 8.0], [9.0, 9.0],];

        // Test case insensitive method names
        let methods = vec![
            "RANDOM",
            "Random",
            "random",
            "POINTS",
            "Points",
            "points",
            "K-MEANS++",
            "K-Means++",
            "k-means++",
        ];

        for method in methods {
            let result = kmeans2_str(
                data.view(),
                2,
                Some(10),
                None,
                Some(method),
                Some("warn"),
                None,
                Some(42),
            );

            assert!(result.is_ok(), "Failed with method: '{}'", method);
        }
    }

    #[test]
    fn test_kmeans2_str_missing_methods() {
        let data = array![[1.0, 1.0], [2.0, 2.0], [8.0, 8.0],];

        // Test different missing methods
        let missing_methods = vec!["warn", "raise", "WARN", "RAISE"];

        for missing_method in missing_methods {
            let result = kmeans2_str(
                data.view(),
                2,
                Some(5),
                None,
                Some("points"),
                Some(missing_method),
                None,
                Some(42),
            );

            assert!(
                result.is_ok(),
                "Failed with missing method: '{}'",
                missing_method
            );
        }
    }

    #[test]
    fn test_kmeans2_str_invalid_method() {
        let data = array![[1.0, 1.0], [2.0, 2.0]];

        // Test invalid initialization method
        let result = kmeans2_str(
            data.view(),
            2,
            Some(10),
            None,
            Some("invalid_method"),
            Some("warn"),
            None,
            None,
        );

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Unknown initialization method"));
    }

    #[test]
    fn test_kmeans2_str_invalid_missing_method() {
        let data = array![[1.0, 1.0], [2.0, 2.0]];

        // Test invalid missing method
        let result = kmeans2_str(
            data.view(),
            2,
            Some(10),
            None,
            Some("points"),
            Some("invalid_missing"),
            None,
            None,
        );

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Unknown missing method"));
    }

    #[test]
    fn test_kmeans2_str_defaults() {
        let data = array![[1.0, 1.0], [1.5, 1.5], [8.0, 8.0], [8.5, 8.5],];

        // Test with all None parameters (should use defaults)
        let result = kmeans2_str(
            data.view(),
            2,
            Some(10),
            None,
            None, // Should default to k-means++
            None, // Should default to warn
            None,
            Some(42),
        );

        assert!(result.is_ok());
        let (centroids, labels) = result.expect("Test: operation failed");
        assert_eq!(centroids.shape(), [2, 2]);
        assert_eq!(labels.len(), 4);
    }

    #[test]
    fn test_kmeans2_str_equivalence_with_enum() {
        let data = array![
            [1.0, 1.0],
            [1.5, 1.5],
            [0.8, 0.9],
            [8.0, 8.0],
            [8.2, 8.1],
            [7.8, 7.9],
        ];

        // Test that string version produces same results as enum version
        let (centroids_enum, labels_enum) = kmeans2(
            data.view(),
            2,
            Some(50),
            Some(1e-6),
            Some(MinitMethod::PlusPlus),
            Some(MissingMethod::Warn),
            Some(true),
            Some(42),
        )
        .expect("Test: operation failed");

        let (centroids_str, labels_str) = kmeans2_str(
            data.view(),
            2,
            Some(50),
            Some(1e-6),
            Some("k-means++"),
            Some("warn"),
            Some(true),
            Some(42),
        )
        .expect("Test: operation failed");

        // Results should be identical
        assert_eq!(labels_enum, labels_str);

        for i in 0..centroids_enum.shape()[0] {
            for j in 0..centroids_enum.shape()[1] {
                assert_abs_diff_eq!(
                    centroids_enum[[i, j]],
                    centroids_str[[i, j]],
                    epsilon = 1e-10
                );
            }
        }
    }

    #[test]
    fn test_minit_method_from_str() {
        // Test MinitMethod::from_str function directly
        assert_eq!(
            MinitMethod::from_str("random").expect("Operation failed"),
            MinitMethod::Random
        );
        assert_eq!(
            MinitMethod::from_str("RANDOM").expect("Operation failed"),
            MinitMethod::Random
        );
        assert_eq!(
            MinitMethod::from_str("points").expect("Operation failed"),
            MinitMethod::Points
        );
        assert_eq!(
            MinitMethod::from_str("POINTS").expect("Operation failed"),
            MinitMethod::Points
        );
        assert_eq!(
            MinitMethod::from_str("k-means++").expect("Operation failed"),
            MinitMethod::PlusPlus
        );
        assert_eq!(
            MinitMethod::from_str("kmeans++").expect("Operation failed"),
            MinitMethod::PlusPlus
        );
        assert_eq!(
            MinitMethod::from_str("plusplus").expect("Operation failed"),
            MinitMethod::PlusPlus
        );
        assert_eq!(
            MinitMethod::from_str("K-MEANS++").expect("Operation failed"),
            MinitMethod::PlusPlus
        );

        // Test invalid method
        assert!(MinitMethod::from_str("invalid").is_err());
    }
}