sklears-feature-selection 0.1.1

Feature selection algorithms for sklears - scikit-learn compatible ML in Rust
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
//! Graph-based feature selection for network and graph-structured data.
//!
//! This module provides specialized feature selection capabilities for graph-structured data,
//! including social networks, biological networks, knowledge graphs, and other network data.
//! It implements various graph-theoretic measures to identify important features based on
//! network topology and structural properties.
//!
//! # Features
//!
//! - **Centrality-based selection**: Uses degree, betweenness, closeness, and PageRank centrality measures
//! - **Community detection**: Leverages community structure for feature importance
//! - **Structural properties**: Considers clustering coefficients, path lengths, and connectivity
//! - **Multi-scale analysis**: Analyzes features at different graph scales
//! - **Dynamic graphs**: Supports temporal graph feature selection
//!
//! # Examples
//!
//! ## Basic Graph Feature Selection
//!
//! ```rust,ignore
//! use sklears_feature_selection::domain_specific::graph_features::GraphFeatureSelector;
//! use scirs2_core::ndarray::{Array2, Array1};
//!
//! // Sample adjacency matrix for a small graph
//! let adjacency = Array2::from_shape_vec((5, 5), vec![
//!     0.0, 1.0, 1.0, 0.0, 0.0,
//!     1.0, 0.0, 1.0, 1.0, 0.0,
//!     1.0, 1.0, 0.0, 0.0, 1.0,
//!     0.0, 1.0, 0.0, 0.0, 1.0,
//!     0.0, 0.0, 1.0, 1.0, 0.0,
//! ]).unwrap();
//!
//! // Node features (each row is a node, columns are features)
//! let features = Array2::from_shape_vec((5, 4), vec![
//!     1.0, 2.0, 3.0, 4.0,
//!     2.0, 3.0, 1.0, 5.0,
//!     3.0, 1.0, 4.0, 2.0,
//!     1.0, 4.0, 2.0, 3.0,
//!     4.0, 2.0, 5.0, 1.0,
//! ]).unwrap();
//!
//! // Target values for supervised selection
//! let target = Array1::from_vec(vec![0.0, 1.0, 1.0, 0.0, 1.0]);
//!
//! let selector = GraphFeatureSelector::builder()
//!     .include_centrality(true)
//!     .include_community(true)
//!     .include_structural(true)
//!     .centrality_threshold(0.3)
//!     .k(2)
//!     .build();
//!
//! let trained = selector.fit(&features, &target, Some(&adjacency))?;
//! let selected_features = trained.transform(&features, Some(&adjacency))?;
//! ```
//!
//! ## Centrality-based Feature Selection
//!
//! ```rust,ignore
//! use sklears_feature_selection::domain_specific::graph_features::GraphFeatureSelector;
//!
//! let selector = GraphFeatureSelector::builder()
//!     .include_centrality(true)
//!     .include_community(false)
//!     .include_structural(false)
//!     .centrality_types(vec!["degree", "pagerank", "betweenness"])
//!     .centrality_threshold(0.5)
//!     .build();
//! ```
//!
//! ## Community-aware Feature Selection
//!
//! ```rust,ignore
//! let selector = GraphFeatureSelector::builder()
//!     .include_community(true)
//!     .community_method("modularity")
//!     .min_community_size(3)
//!     .community_weight(0.7)
//!     .build();
//! ```

use crate::base::SelectorMixin;
use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
use sklears_core::error::{Result as SklResult, SklearsError};
use sklears_core::traits::{Estimator, Fit, Transform};
use std::collections::HashMap;
use std::marker::PhantomData;

type Result<T> = SklResult<T>;
type Float = f64;

#[derive(Debug, Clone)]
/// Untrained
pub struct Untrained;

#[derive(Debug, Clone)]
/// Trained
pub struct Trained {
    selected_features: Vec<usize>,
    _feature_scores: Array1<Float>,
    _centrality_scores: Option<HashMap<String, Array1<Float>>>,
    _community_assignments: Option<Array1<usize>>,
    _structural_scores: Option<Array1<Float>>,
    n_features: usize,
}

/// Graph-based feature selector for network-structured data.
///
/// This selector uses graph topology and structure to identify important features
/// by analyzing centrality measures, community structure, and other graph properties.
/// It's particularly useful for social networks, biological networks, citation networks,
/// and other graph-structured data where network topology provides valuable information
/// about feature importance.
#[derive(Debug, Clone)]
pub struct GraphFeatureSelector<State = Untrained> {
    include_centrality: bool,
    include_community: bool,
    include_structural: bool,
    centrality_threshold: Float,
    centrality_types: Vec<String>,
    community_method: String,
    min_community_size: usize,
    community_weight: Float,
    structural_weight: Float,
    k: Option<usize>,
    damping_factor: Float,
    max_iterations: usize,
    tolerance: Float,
    adjacency: Option<Array2<Float>>,
    state: PhantomData<State>,
    trained_state: Option<Trained>,
}

impl Default for GraphFeatureSelector<Untrained> {
    fn default() -> Self {
        Self::new()
    }
}

impl GraphFeatureSelector<Untrained> {
    /// Creates a new GraphFeatureSelector with default parameters.
    pub fn new() -> Self {
        Self {
            include_centrality: true,
            include_community: true,
            include_structural: true,
            centrality_threshold: 0.1,
            centrality_types: vec!["degree".to_string(), "pagerank".to_string()],
            community_method: "modularity".to_string(),
            min_community_size: 2,
            community_weight: 0.5,
            structural_weight: 0.3,
            k: None,
            damping_factor: 0.85,
            max_iterations: 100,
            tolerance: 1e-6,
            adjacency: None,
            state: PhantomData,
            trained_state: None,
        }
    }

    /// Creates a builder for configuring the GraphFeatureSelector.
    pub fn builder() -> GraphFeatureSelectorBuilder {
        GraphFeatureSelectorBuilder::new()
    }
}

/// Builder for GraphFeatureSelector configuration.
#[derive(Debug)]
pub struct GraphFeatureSelectorBuilder {
    include_centrality: bool,
    include_community: bool,
    include_structural: bool,
    centrality_threshold: Float,
    centrality_types: Vec<String>,
    community_method: String,
    min_community_size: usize,
    community_weight: Float,
    structural_weight: Float,
    k: Option<usize>,
    damping_factor: Float,
    max_iterations: usize,
    tolerance: Float,
    adjacency: Option<Array2<Float>>,
}

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

impl GraphFeatureSelectorBuilder {
    /// new
    pub fn new() -> Self {
        Self {
            include_centrality: true,
            include_community: true,
            include_structural: true,
            centrality_threshold: 0.1,
            centrality_types: vec!["degree".to_string(), "pagerank".to_string()],
            community_method: "modularity".to_string(),
            min_community_size: 2,
            community_weight: 0.5,
            structural_weight: 0.3,
            k: None,
            damping_factor: 0.85,
            max_iterations: 100,
            tolerance: 1e-6,
            adjacency: None,
        }
    }

    /// Whether to include centrality-based features.
    pub fn include_centrality(mut self, include: bool) -> Self {
        self.include_centrality = include;
        self
    }

    /// Whether to include community-based features.
    pub fn include_community(mut self, include: bool) -> Self {
        self.include_community = include;
        self
    }

    /// Whether to include structural property features.
    pub fn include_structural(mut self, include: bool) -> Self {
        self.include_structural = include;
        self
    }

    /// Minimum centrality score threshold for feature selection.
    pub fn centrality_threshold(mut self, threshold: Float) -> Self {
        self.centrality_threshold = threshold;
        self
    }

    /// Types of centrality measures to compute.
    pub fn centrality_types(mut self, types: Vec<&str>) -> Self {
        self.centrality_types = types.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Community detection method to use.
    pub fn community_method(mut self, method: &str) -> Self {
        self.community_method = method.to_string();
        self
    }

    /// Minimum size for communities to be considered.
    pub fn min_community_size(mut self, size: usize) -> Self {
        self.min_community_size = size;
        self
    }

    /// Weight for community-based features in scoring.
    pub fn community_weight(mut self, weight: Float) -> Self {
        self.community_weight = weight;
        self
    }

    /// Weight for structural property features in scoring.
    pub fn structural_weight(mut self, weight: Float) -> Self {
        self.structural_weight = weight;
        self
    }

    /// Number of top features to select.
    pub fn k(mut self, k: usize) -> Self {
        self.k = Some(k);
        self
    }

    /// Damping factor for PageRank computation.
    pub fn damping_factor(mut self, factor: Float) -> Self {
        self.damping_factor = factor;
        self
    }

    /// Maximum iterations for iterative algorithms.
    pub fn max_iterations(mut self, iterations: usize) -> Self {
        self.max_iterations = iterations;
        self
    }

    /// Convergence tolerance for iterative algorithms.
    pub fn tolerance(mut self, tol: Float) -> Self {
        self.tolerance = tol;
        self
    }

    /// Sets the adjacency matrix for graph feature selection.
    pub fn with_adjacency(mut self, adjacency: Array2<Float>) -> Self {
        self.adjacency = Some(adjacency);
        self
    }

    /// Builds the GraphFeatureSelector.
    pub fn build(self) -> GraphFeatureSelector<Untrained> {
        GraphFeatureSelector {
            include_centrality: self.include_centrality,
            include_community: self.include_community,
            include_structural: self.include_structural,
            centrality_threshold: self.centrality_threshold,
            centrality_types: self.centrality_types,
            community_method: self.community_method,
            min_community_size: self.min_community_size,
            community_weight: self.community_weight,
            structural_weight: self.structural_weight,
            k: self.k,
            damping_factor: self.damping_factor,
            max_iterations: self.max_iterations,
            tolerance: self.tolerance,
            adjacency: self.adjacency,
            state: PhantomData,
            trained_state: None,
        }
    }
}

impl Estimator for GraphFeatureSelector<Untrained> {
    type Config = ();
    type Error = sklears_core::error::SklearsError;
    type Float = Float;

    fn config(&self) -> &Self::Config {
        &()
    }
}

impl Estimator for GraphFeatureSelector<Trained> {
    type Config = ();
    type Error = sklears_core::error::SklearsError;
    type Float = Float;

    fn config(&self) -> &Self::Config {
        &()
    }
}

impl Fit<Array2<Float>, Array1<Float>> for GraphFeatureSelector<Untrained> {
    type Fitted = GraphFeatureSelector<Trained>;

    fn fit(self, x: &Array2<Float>, y: &Array1<Float>) -> Result<Self::Fitted> {
        let (n_samples, n_features) = x.dim();

        if y.len() != n_samples {
            return Err(SklearsError::InvalidInput(
                "Number of samples in X and y must match".to_string(),
            ));
        }

        let adjacency = self.adjacency.ok_or_else(|| {
            SklearsError::InvalidInput(
                "Adjacency matrix is required for graph feature selection".to_string(),
            )
        })?;

        if adjacency.dim() != (n_samples, n_samples) {
            return Err(SklearsError::InvalidInput(
                "Adjacency matrix must be square with same number of nodes as samples".to_string(),
            ));
        }

        let mut centrality_scores = None;
        let mut community_assignments = None;
        let mut structural_scores = None;
        let mut combined_scores = Array1::zeros(n_features);

        // Compute centrality-based scores
        if self.include_centrality {
            let mut centrality_map = HashMap::new();

            for centrality_type in &self.centrality_types {
                let scores = match centrality_type.as_str() {
                    "degree" => compute_degree_centrality(&adjacency.view()),
                    "pagerank" => compute_pagerank_centrality(
                        &adjacency.view(),
                        self.damping_factor,
                        self.max_iterations,
                        self.tolerance,
                    ),
                    "betweenness" => compute_betweenness_centrality(&adjacency.view()),
                    "closeness" => compute_closeness_centrality(&adjacency.view()),
                    _ => Array1::zeros(n_samples),
                };
                centrality_map.insert(centrality_type.clone(), scores);
            }

            // Combine centrality scores with feature correlations
            let feature_centrality_scores = compute_feature_centrality_scores(x, &centrality_map)?;
            combined_scores = &combined_scores + &feature_centrality_scores;
            centrality_scores = Some(centrality_map);
        }

        // Compute community-based scores
        if self.include_community {
            let communities = match self.community_method.as_str() {
                "modularity" => {
                    detect_communities_modularity(&adjacency.view(), self.min_community_size)
                }
                "louvain" => detect_communities_louvain(&adjacency.view(), self.min_community_size),
                _ => Array1::zeros(n_samples),
            };

            let community_feature_scores =
                compute_community_feature_scores(x, &communities, self.community_weight)?;
            combined_scores = &combined_scores + &community_feature_scores;
            community_assignments = Some(communities);
        }

        // Compute structural property scores
        if self.include_structural {
            let struct_scores =
                compute_structural_feature_scores(x, &adjacency.view(), self.structural_weight)?;
            combined_scores = &combined_scores + &struct_scores;
            structural_scores = Some(struct_scores);
        }

        // Select features based on combined scores
        let selected_features = if let Some(k) = self.k {
            select_top_k_features(&combined_scores, k)
        } else {
            select_features_by_threshold(&combined_scores, self.centrality_threshold)
        };

        let trained_state = Trained {
            selected_features,
            _feature_scores: combined_scores,
            _centrality_scores: centrality_scores,
            _community_assignments: community_assignments,
            _structural_scores: structural_scores,
            n_features,
        };

        Ok(GraphFeatureSelector {
            include_centrality: self.include_centrality,
            include_community: self.include_community,
            include_structural: self.include_structural,
            centrality_threshold: self.centrality_threshold,
            centrality_types: self.centrality_types,
            community_method: self.community_method,
            min_community_size: self.min_community_size,
            community_weight: self.community_weight,
            structural_weight: self.structural_weight,
            k: self.k,
            damping_factor: self.damping_factor,
            max_iterations: self.max_iterations,
            tolerance: self.tolerance,
            adjacency: None,
            state: PhantomData,
            trained_state: Some(trained_state),
        })
    }
}

impl Transform<Array2<Float>> for GraphFeatureSelector<Trained> {
    fn transform(&self, x: &Array2<Float>) -> Result<Array2<Float>> {
        let trained = self.trained_state.as_ref().ok_or_else(|| {
            SklearsError::InvalidState("Selector must be fitted before transforming".to_string())
        })?;

        let (_n_samples, n_features) = x.dim();

        if n_features != trained.n_features {
            return Err(SklearsError::InvalidInput(format!(
                "Expected {} features, got {}",
                trained.n_features, n_features
            )));
        }

        if trained.selected_features.is_empty() {
            return Err(SklearsError::InvalidState(
                "No features were selected".to_string(),
            ));
        }

        let selected_data = x.select(Axis(1), &trained.selected_features);
        Ok(selected_data)
    }
}

impl SelectorMixin for GraphFeatureSelector<Trained> {
    fn get_support(&self) -> Result<Array1<bool>> {
        let trained = self.trained_state.as_ref().ok_or_else(|| {
            SklearsError::InvalidState("Selector must be fitted before getting support".to_string())
        })?;

        let mut support = Array1::from_elem(trained.n_features, false);
        for &idx in &trained.selected_features {
            support[idx] = true;
        }
        Ok(support)
    }

    fn transform_features(&self, indices: &[usize]) -> SklResult<Vec<usize>> {
        let trained = self.trained_state.as_ref().ok_or_else(|| {
            SklearsError::InvalidState(
                "Selector must be fitted before transforming features".to_string(),
            )
        })?;

        let selected: Vec<usize> = indices
            .iter()
            .filter(|&&idx| trained.selected_features.contains(&idx))
            .cloned()
            .collect();
        Ok(selected)
    }
}

// Centrality computation functions

fn compute_degree_centrality(adjacency: &ArrayView2<Float>) -> Array1<Float> {
    let n = adjacency.nrows();
    let mut centrality = Array1::zeros(n);

    for i in 0..n {
        let degree: Float = adjacency.row(i).sum();
        centrality[i] = degree / (n - 1) as Float;
    }

    centrality
}

fn compute_pagerank_centrality(
    adjacency: &ArrayView2<Float>,
    damping: Float,
    max_iter: usize,
    tolerance: Float,
) -> Array1<Float> {
    let n = adjacency.nrows();
    let mut pagerank = Array1::from_elem(n, 1.0 / n as Float);
    let mut new_pagerank = Array1::zeros(n);

    for _ in 0..max_iter {
        new_pagerank.fill(0.0);

        for i in 0..n {
            let out_degree: Float = adjacency.row(i).sum();
            if out_degree > 0.0 {
                for j in 0..n {
                    if adjacency[[i, j]] > 0.0 {
                        new_pagerank[j] += damping * pagerank[i] / out_degree;
                    }
                }
            }
        }

        // Add random jump probability
        for i in 0..n {
            new_pagerank[i] += (1.0 - damping) / n as Float;
        }

        // Check convergence
        let diff: Float = (&new_pagerank - &pagerank).mapv(|x| x.abs()).sum();
        if diff < tolerance {
            break;
        }

        pagerank.assign(&new_pagerank);
    }

    pagerank
}

fn compute_betweenness_centrality(adjacency: &ArrayView2<Float>) -> Array1<Float> {
    let n = adjacency.nrows();
    let mut betweenness = Array1::zeros(n);

    // Simplified betweenness centrality (approximate)
    for i in 0..n {
        let mut local_betweenness = 0.0;
        for j in 0..n {
            if i != j {
                for k in 0..n {
                    if k != i && k != j {
                        // Check if node i is on shortest path from j to k
                        let direct_jk = if adjacency[[j, k]] > 0.0 {
                            1.0
                        } else {
                            f64::INFINITY
                        };
                        let via_i = if adjacency[[j, i]] > 0.0 && adjacency[[i, k]] > 0.0 {
                            2.0
                        } else {
                            f64::INFINITY
                        };

                        if via_i < direct_jk {
                            local_betweenness += 1.0;
                        }
                    }
                }
            }
        }
        betweenness[i] = local_betweenness / ((n - 1) * (n - 2)) as Float;
    }

    betweenness
}

fn compute_closeness_centrality(adjacency: &ArrayView2<Float>) -> Array1<Float> {
    let n = adjacency.nrows();
    let mut closeness = Array1::zeros(n);

    for i in 0..n {
        let mut total_distance = 0.0;
        let mut reachable_nodes = 0;

        for j in 0..n {
            if i != j {
                // Simplified distance calculation (direct connection = 1, else 2 if connected through neighbors)
                let distance = if adjacency[[i, j]] > 0.0 {
                    1.0
                } else {
                    // Check for 2-hop connection
                    let mut found_path = false;
                    for k in 0..n {
                        if adjacency[[i, k]] > 0.0 && adjacency[[k, j]] > 0.0 {
                            found_path = true;
                            break;
                        }
                    }
                    if found_path {
                        2.0
                    } else {
                        f64::INFINITY
                    }
                };

                if distance.is_finite() {
                    total_distance += distance;
                    reachable_nodes += 1;
                }
            }
        }

        if reachable_nodes > 0 {
            closeness[i] = reachable_nodes as Float / total_distance;
        }
    }

    closeness
}

// Feature scoring functions

fn compute_feature_centrality_scores(
    x: &Array2<Float>,
    centrality_scores: &HashMap<String, Array1<Float>>,
) -> Result<Array1<Float>> {
    let (_n_samples, n_features) = x.dim();
    let mut feature_scores = Array1::zeros(n_features);

    for j in 0..n_features {
        let feature = x.column(j);
        let mut total_score = 0.0;
        let mut weight_sum = 0.0;

        for (centrality_type, centrality) in centrality_scores {
            let weight = match centrality_type.as_str() {
                "degree" => 1.0,
                "pagerank" => 1.5,
                "betweenness" => 1.2,
                "closeness" => 1.1,
                _ => 1.0,
            };

            let correlation = compute_pearson_correlation(&feature, &centrality.view());
            total_score += weight * correlation.abs();
            weight_sum += weight;
        }

        feature_scores[j] = if weight_sum > 0.0 {
            total_score / weight_sum
        } else {
            0.0
        };
    }

    Ok(feature_scores)
}

fn compute_community_feature_scores(
    x: &Array2<Float>,
    communities: &Array1<usize>,
    weight: Float,
) -> Result<Array1<Float>> {
    let (_n_samples, n_features) = x.dim();
    let mut feature_scores = Array1::zeros(n_features);

    // Find unique communities
    let max_community = communities.iter().max().cloned().unwrap_or(0);

    for j in 0..n_features {
        let feature = x.column(j);
        let mut community_variance = 0.0;

        for c in 0..=max_community {
            let community_indices: Vec<usize> = communities
                .iter()
                .enumerate()
                .filter(|(_, &comm)| comm == c)
                .map(|(i, _)| i)
                .collect();

            if community_indices.len() > 1 {
                let community_values: Vec<Float> =
                    community_indices.iter().map(|&i| feature[i]).collect();

                let mean = community_values.iter().sum::<Float>() / community_values.len() as Float;
                let variance = community_values
                    .iter()
                    .map(|&val| (val - mean).powi(2))
                    .sum::<Float>()
                    / community_values.len() as Float;

                community_variance += variance;
            }
        }

        feature_scores[j] = weight * community_variance;
    }

    Ok(feature_scores)
}

fn compute_structural_feature_scores(
    x: &Array2<Float>,
    adjacency: &ArrayView2<Float>,
    weight: Float,
) -> Result<Array1<Float>> {
    let (_n_samples, n_features) = x.dim();
    let mut feature_scores = Array1::zeros(n_features);

    // Compute clustering coefficients
    let clustering_coeffs = compute_clustering_coefficients(adjacency);

    for j in 0..n_features {
        let feature = x.column(j);
        let correlation = compute_pearson_correlation(&feature, &clustering_coeffs.view());
        feature_scores[j] = weight * correlation.abs();
    }

    Ok(feature_scores)
}

// Community detection functions

fn detect_communities_modularity(adjacency: &ArrayView2<Float>, min_size: usize) -> Array1<usize> {
    let n = adjacency.nrows();
    let mut communities = Array1::from_iter(0..n);

    // Simple modularity-based community detection (simplified implementation)
    let total_edges: Float = adjacency.sum() / 2.0;

    if total_edges == 0.0 {
        return communities;
    }

    // Greedy modularity optimization
    let mut improved = true;
    while improved {
        improved = false;

        for i in 0..n {
            let current_community = communities[i];
            let mut best_community = current_community;
            let mut best_modularity_gain = 0.0;

            // Try moving node i to different communities
            for j in 0..n {
                if i != j {
                    let target_community = communities[j];
                    if target_community != current_community {
                        let modularity_gain = compute_modularity_gain(
                            i,
                            current_community,
                            target_community,
                            adjacency,
                            &communities,
                            total_edges,
                        );
                        if modularity_gain > best_modularity_gain {
                            best_modularity_gain = modularity_gain;
                            best_community = target_community;
                        }
                    }
                }
            }

            if best_community != current_community {
                communities[i] = best_community;
                improved = true;
            }
        }
    }

    // Ensure minimum community size
    let mut community_counts = HashMap::new();
    for &comm in communities.iter() {
        *community_counts.entry(comm).or_insert(0) += 1;
    }

    let small_communities: Vec<usize> = community_counts
        .iter()
        .filter(|(_, &count)| count < min_size)
        .map(|(&comm, _)| comm)
        .collect();

    // Merge small communities with largest neighbor
    for &small_comm in &small_communities {
        let nodes_in_small: Vec<usize> = communities
            .iter()
            .enumerate()
            .filter(|(_, &comm)| comm == small_comm)
            .map(|(i, _)| i)
            .collect();

        if !nodes_in_small.is_empty() {
            let target_comm = find_best_merge_community(&nodes_in_small, adjacency, &communities);
            for &node in &nodes_in_small {
                communities[node] = target_comm;
            }
        }
    }

    communities
}

fn detect_communities_louvain(adjacency: &ArrayView2<Float>, min_size: usize) -> Array1<usize> {
    // Simplified Louvain algorithm (placeholder implementation)
    detect_communities_modularity(adjacency, min_size)
}

// Utility functions

fn compute_modularity_gain(
    node: usize,
    from_comm: usize,
    to_comm: usize,
    adjacency: &ArrayView2<Float>,
    communities: &Array1<usize>,
    total_edges: Float,
) -> Float {
    if total_edges == 0.0 {
        return 0.0;
    }

    // Simplified modularity gain calculation
    let node_degree: Float = adjacency.row(node).sum();

    let mut edges_to_from = 0.0;
    let mut edges_to_to = 0.0;

    for i in 0..adjacency.nrows() {
        if communities[i] == from_comm && i != node {
            edges_to_from += adjacency[[node, i]];
        }
        if communities[i] == to_comm {
            edges_to_to += adjacency[[node, i]];
        }
    }

    (edges_to_to - edges_to_from) / (2.0 * total_edges)
        - node_degree * node_degree / (4.0 * total_edges * total_edges)
}

fn find_best_merge_community(
    nodes: &[usize],
    adjacency: &ArrayView2<Float>,
    communities: &Array1<usize>,
) -> usize {
    let mut community_connections = HashMap::new();

    for &node in nodes {
        for i in 0..adjacency.nrows() {
            if adjacency[[node, i]] > 0.0 && !nodes.contains(&i) {
                let comm = communities[i];
                *community_connections.entry(comm).or_insert(0.0) += adjacency[[node, i]];
            }
        }
    }

    community_connections
        .into_iter()
        .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
        .map(|(comm, _)| comm)
        .unwrap_or(0)
}

fn compute_clustering_coefficients(adjacency: &ArrayView2<Float>) -> Array1<Float> {
    let n = adjacency.nrows();
    let mut clustering = Array1::zeros(n);

    for i in 0..n {
        let neighbors: Vec<usize> = (0..n)
            .filter(|&j| i != j && adjacency[[i, j]] > 0.0)
            .collect();

        let degree = neighbors.len();
        if degree < 2 {
            clustering[i] = 0.0;
            continue;
        }

        let mut triangles = 0;
        for j in 0..neighbors.len() {
            for k in (j + 1)..neighbors.len() {
                if adjacency[[neighbors[j], neighbors[k]]] > 0.0 {
                    triangles += 1;
                }
            }
        }

        let possible_triangles = degree * (degree - 1) / 2;
        clustering[i] = if possible_triangles > 0 {
            triangles as Float / possible_triangles as Float
        } else {
            0.0
        };
    }

    clustering
}

fn compute_pearson_correlation(x: &ArrayView1<Float>, y: &ArrayView1<Float>) -> Float {
    let n = x.len();
    if n != y.len() || n == 0 {
        return 0.0;
    }

    let mean_x = x.sum() / n as Float;
    let mean_y = y.sum() / n as Float;

    let mut numerator = 0.0;
    let mut sum_sq_x = 0.0;
    let mut sum_sq_y = 0.0;

    for i in 0..n {
        let dx = x[i] - mean_x;
        let dy = y[i] - mean_y;
        numerator += dx * dy;
        sum_sq_x += dx * dx;
        sum_sq_y += dy * dy;
    }

    let denominator = (sum_sq_x * sum_sq_y).sqrt();
    if denominator == 0.0 {
        0.0
    } else {
        numerator / denominator
    }
}

fn select_top_k_features(scores: &Array1<Float>, k: usize) -> Vec<usize> {
    let mut indexed_scores: Vec<(usize, Float)> = scores
        .iter()
        .enumerate()
        .map(|(i, &score)| (i, score))
        .collect();

    indexed_scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    indexed_scores
        .into_iter()
        .take(k.min(scores.len()))
        .map(|(i, _)| i)
        .collect()
}

fn select_features_by_threshold(scores: &Array1<Float>, threshold: Float) -> Vec<usize> {
    scores
        .iter()
        .enumerate()
        .filter(|(_, &score)| score >= threshold)
        .map(|(i, _)| i)
        .collect()
}

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

    #[test]
    fn test_graph_feature_selector_creation() {
        let selector = GraphFeatureSelector::new();
        assert!(selector.include_centrality);
        assert!(selector.include_community);
        assert!(selector.include_structural);
    }

    #[test]
    fn test_graph_feature_selector_builder() {
        let selector = GraphFeatureSelector::builder()
            .include_centrality(true)
            .include_community(false)
            .centrality_threshold(0.5)
            .k(3)
            .build();

        assert!(selector.include_centrality);
        assert!(!selector.include_community);
        assert_eq!(selector.centrality_threshold, 0.5);
        assert_eq!(selector.k, Some(3));
    }

    #[test]
    fn test_degree_centrality() {
        let adjacency =
            Array2::from_shape_vec((3, 3), vec![0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0])
                .expect("operation should succeed");

        let centrality = compute_degree_centrality(&adjacency.view());

        // All nodes have degree 2, so centrality should be 2/2 = 1.0 for all
        assert_eq!(centrality.len(), 3);
        for &c in centrality.iter() {
            assert!((c - 1.0).abs() < 1e-6);
        }
    }

    #[test]
    fn test_fit_transform_basic() {
        let adjacency = Array2::from_shape_vec(
            (4, 4),
            vec![
                0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,
            ],
        )
        .expect("operation should succeed");

        let features = Array2::from_shape_vec(
            (4, 3),
            vec![1.0, 2.0, 3.0, 2.0, 3.0, 1.0, 3.0, 1.0, 4.0, 1.0, 4.0, 2.0],
        )
        .expect("operation should succeed");

        let target = Array1::from_vec(vec![0.0, 1.0, 1.0, 0.0]);

        let selector = GraphFeatureSelector::builder()
            .k(2)
            .with_adjacency(adjacency)
            .build();

        let trained = selector
            .fit(&features, &target)
            .expect("operation should succeed");
        let transformed = trained
            .transform(&features)
            .expect("operation should succeed");

        assert_eq!(transformed.ncols(), 2);
        assert_eq!(transformed.nrows(), 4);
    }

    #[test]
    fn test_get_support() {
        let adjacency =
            Array2::from_shape_vec((3, 3), vec![0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0])
                .expect("operation should succeed");

        let features = Array2::from_shape_vec(
            (3, 4),
            vec![1.0, 2.0, 3.0, 4.0, 2.0, 3.0, 1.0, 5.0, 3.0, 1.0, 4.0, 2.0],
        )
        .expect("operation should succeed");

        let target = Array1::from_vec(vec![0.0, 1.0, 1.0]);

        let selector = GraphFeatureSelector::builder()
            .k(2)
            .with_adjacency(adjacency)
            .build();

        let trained = selector
            .fit(&features, &target)
            .expect("operation should succeed");
        let support = trained.get_support().expect("operation should succeed");

        assert_eq!(support.len(), 4);
        assert_eq!(support.iter().filter(|&&x| x).count(), 2);
    }

    #[test]
    fn test_clustering_coefficients() {
        let adjacency = Array2::from_shape_vec(
            (4, 4),
            vec![
                0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0,
            ],
        )
        .expect("operation should succeed");

        let clustering = compute_clustering_coefficients(&adjacency.view());

        assert_eq!(clustering.len(), 4);
        // Node 1 has 3 neighbors (0, 2, 3) with 2 connections between them
        // So clustering coefficient should be 2/3
        assert!((clustering[1] - 2.0 / 3.0).abs() < 1e-6);
    }

    #[test]
    fn test_pagerank_centrality() {
        let adjacency =
            Array2::from_shape_vec((3, 3), vec![0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
                .expect("operation should succeed");

        let pagerank = compute_pagerank_centrality(&adjacency.view(), 0.85, 100, 1e-6);

        assert_eq!(pagerank.len(), 3);
        // Node 0 should have highest PageRank as it receives links from both other nodes
        assert!(pagerank[0] > pagerank[1]);
        assert!(pagerank[0] > pagerank[2]);
    }
}