pandrs 0.3.1

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
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
//! Anomaly detection algorithms
//!
//! This module provides implementations of anomaly detection algorithms
//! for identifying outliers and unusual patterns in data.

use crate::core::error::{Error, Result};
use crate::dataframe::DataFrame;
use crate::ml::models::ModelEvaluator;
use crate::ml::models::ModelMetrics;
use crate::ml::models::UnsupervisedModel;
use std::collections::{HashMap, HashSet};

/// Isolation Forest for anomaly detection
///
/// Isolation Forest is an ensemble method that detects anomalies by
/// recursively partitioning the data and identifying points that
/// require fewer partitions to isolate.
#[derive(Debug, Clone)]
pub struct IsolationForest {
    /// Number of trees in the forest
    pub n_estimators: usize,
    /// Maximum number of samples to draw for each tree
    pub max_samples: Option<usize>,
    /// Maximum depth of the trees
    pub max_depth: Option<usize>,
    /// Contamination: expected proportion of outliers in the data
    pub contamination: f64,
    /// Random seed for reproducibility
    pub random_seed: Option<u64>,
    /// Anomaly scores (-1 for anomalies, 1 for normal points)
    pub scores: Option<Vec<f64>>,
    /// Feature columns used for anomaly detection
    pub feature_columns: Option<Vec<String>>,
}

impl IsolationForest {
    /// Create a new IsolationForest instance
    pub fn new() -> Self {
        IsolationForest {
            n_estimators: 100,
            max_samples: None,
            max_depth: None,
            contamination: 0.1,
            random_seed: None,
            scores: None,
            feature_columns: None,
        }
    }

    /// Get anomaly scores
    pub fn anomaly_scores(&self) -> &[f64] {
        match &self.scores {
            Some(scores) => scores,
            None => &[], // Return empty slice if no scores available
        }
    }

    /// Get anomaly labels (1 for normal, -1 for anomalies)
    pub fn labels(&self) -> &[i64] {
        // This is a stub implementation for backward compatibility
        // In a real implementation, we would return actual labels
        &[]
    }

    /// Set number of trees in the forest
    pub fn n_estimators(mut self, n_estimators: usize) -> Self {
        self.n_estimators = n_estimators;
        self
    }

    /// Set maximum number of samples to draw for each tree
    pub fn max_samples(mut self, max_samples: usize) -> Self {
        self.max_samples = Some(max_samples);
        self
    }

    /// Set maximum depth of the trees
    pub fn max_depth(mut self, max_depth: usize) -> Self {
        self.max_depth = Some(max_depth);
        self
    }

    /// Set contamination (expected proportion of outliers)
    pub fn contamination(mut self, contamination: f64) -> Self {
        self.contamination = contamination;
        self
    }

    /// Set random seed for reproducibility
    pub fn random_seed(mut self, seed: u64) -> Self {
        self.random_seed = Some(seed);
        self
    }

    /// Specify feature columns to use
    pub fn with_columns(mut self, columns: Vec<String>) -> Self {
        self.feature_columns = Some(columns);
        self
    }

    /// Predict anomaly scores for new data
    pub fn predict(&self, data: &DataFrame) -> Result<Vec<f64>> {
        // Placeholder implementation
        // In a real implementation, this would use the trained model to predict anomaly scores
        let n_samples = data.row_count();
        let mut scores = vec![1.0; n_samples]; // Default: all normal points

        // Mark random 10% as anomalies for demonstration
        use rand::{Rng, RngExt};
        let mut rng = rand::rng();

        for _ in 0..((n_samples as f64 * 0.1) as usize) {
            let idx = rng.random_range(0..n_samples);
            scores[idx] = -1.0; // Anomaly
        }

        Ok(scores)
    }

    /// Get decision function values (anomaly scores)
    pub fn decision_function(&self, data: &DataFrame) -> Result<Vec<f64>> {
        // Placeholder implementation
        // In a real implementation, this would return the raw anomaly scores
        let n_samples = data.row_count();
        let mut scores = Vec::with_capacity(n_samples);

        use rand::{Rng, RngExt};
        let mut rng = rand::rng();

        for _ in 0..n_samples {
            // Random scores between -1 and 1, where lower = more anomalous
            scores.push(rng.random_range(-1.0..1.0));
        }

        Ok(scores)
    }
}

impl UnsupervisedModel for IsolationForest {
    fn fit(&mut self, data: &DataFrame) -> Result<()> {
        // Placeholder implementation
        // In a real implementation, this would build the isolation forest model
        let n_samples = data.row_count();
        let mut scores = Vec::with_capacity(n_samples);

        use rand::{Rng, RngExt};
        let mut rng = rand::rng();

        for _ in 0..n_samples {
            // Random scores between -1 and 1, where lower = more anomalous
            scores.push(rng.random_range(-1.0..1.0));
        }

        self.scores = Some(scores);

        // Store feature columns if not already specified
        if self.feature_columns.is_none() {
            self.feature_columns = Some(data.column_names().into());
        }

        Ok(())
    }

    fn transform(&self, data: &DataFrame) -> Result<DataFrame> {
        // Transform adds an anomaly score column to the data
        let scores = self.decision_function(data)?;
        let mut result = data.clone();

        result.add_column(
            "anomaly_score".to_string(),
            crate::series::Series::new(scores, Some("anomaly_score".to_string()))?,
        )?;

        Ok(result)
    }
}

impl ModelEvaluator for IsolationForest {
    fn evaluate(&self, test_data: &DataFrame, _test_target: &str) -> Result<ModelMetrics> {
        // Placeholder implementation
        let mut metrics = ModelMetrics::new();
        metrics.add_metric("anomaly_ratio", self.contamination);
        Ok(metrics)
    }

    fn cross_validate(
        &self,
        _data: &DataFrame,
        _target: &str,
        _folds: usize,
    ) -> Result<Vec<ModelMetrics>> {
        Err(Error::InvalidOperation(
            "Cross-validation is not applicable for anomaly detection".into(),
        ))
    }
}

/// Local Outlier Factor for anomaly detection
///
/// Local Outlier Factor computes the local density deviation of a point
/// with respect to its neighbors, identifying points that have significantly
/// lower density than their neighbors.
#[derive(Debug, Clone)]
pub struct LocalOutlierFactor {
    /// Number of neighbors to consider
    pub n_neighbors: usize,
    /// Contamination: expected proportion of outliers in the data
    pub contamination: f64,
    /// Algorithm to use for nearest neighbors search
    pub algorithm: String,
    /// Anomaly scores (-1 for anomalies, 1 for normal points)
    pub scores: Option<Vec<f64>>,
    /// Feature columns used for anomaly detection
    pub feature_columns: Option<Vec<String>>,
}

impl LocalOutlierFactor {
    /// Create a new LocalOutlierFactor instance
    pub fn new(n_neighbors: usize) -> Self {
        LocalOutlierFactor {
            n_neighbors,
            contamination: 0.1,
            algorithm: "auto".to_string(),
            scores: None,
            feature_columns: None,
        }
    }

    /// Get anomaly scores
    pub fn anomaly_scores(&self) -> &[f64] {
        match &self.scores {
            Some(scores) => scores,
            None => &[], // Return empty slice if no scores available
        }
    }

    /// Get anomaly labels (1 for normal, -1 for anomalies)
    pub fn labels(&self) -> &[i64] {
        // This is a stub implementation for backward compatibility
        &[]
    }

    /// Set contamination (expected proportion of outliers)
    pub fn contamination(mut self, contamination: f64) -> Self {
        self.contamination = contamination;
        self
    }

    /// Set algorithm for nearest neighbors search
    pub fn algorithm(mut self, algorithm: &str) -> Self {
        self.algorithm = algorithm.to_string();
        self
    }

    /// Specify feature columns to use
    pub fn with_columns(mut self, columns: Vec<String>) -> Self {
        self.feature_columns = Some(columns);
        self
    }
}

impl UnsupervisedModel for LocalOutlierFactor {
    fn fit(&mut self, data: &DataFrame) -> Result<()> {
        // Placeholder implementation
        self.feature_columns = Some(data.column_names().into());
        Ok(())
    }

    fn transform(&self, _data: &DataFrame) -> Result<DataFrame> {
        // LOF is typically used in "novelty" mode for transform
        Err(Error::InvalidOperation(
            "LocalOutlierFactor does not support transform in current implementation".into(),
        ))
    }
}

impl ModelEvaluator for LocalOutlierFactor {
    fn evaluate(&self, _test_data: &DataFrame, _test_target: &str) -> Result<ModelMetrics> {
        let mut metrics = ModelMetrics::new();
        metrics.add_metric("anomaly_ratio", self.contamination);
        Ok(metrics)
    }

    fn cross_validate(
        &self,
        _data: &DataFrame,
        _target: &str,
        _folds: usize,
    ) -> Result<Vec<ModelMetrics>> {
        Err(Error::InvalidOperation(
            "Cross-validation is not applicable for anomaly detection".into(),
        ))
    }
}

/// One-Class SVM for anomaly detection
///
/// One-Class SVM learns a boundary that separates the majority of data
/// from the origin, treating points outside this boundary as anomalies.
#[derive(Debug, Clone)]
pub struct OneClassSVM {
    /// Kernel type
    pub kernel: String,
    /// Regularization parameter nu (upper bound on fraction of outliers)
    pub nu: f64,
    /// Kernel coefficient for RBF, polynomial, and sigmoid kernels
    pub gamma: Option<f64>,
    /// Anomaly scores (-1 for anomalies, 1 for normal points)
    pub scores: Option<Vec<f64>>,
    /// Feature columns used for anomaly detection
    pub feature_columns: Option<Vec<String>>,
}

impl OneClassSVM {
    /// Create a new OneClassSVM instance
    pub fn new() -> Self {
        OneClassSVM {
            kernel: "rbf".to_string(),
            nu: 0.1,
            gamma: None,
            scores: None,
            feature_columns: None,
        }
    }

    /// Get anomaly scores
    pub fn anomaly_scores(&self) -> &[f64] {
        match &self.scores {
            Some(scores) => scores,
            None => &[], // Return empty slice if no scores available
        }
    }

    /// Get anomaly labels (1 for normal, -1 for anomalies)
    pub fn labels(&self) -> &[i64] {
        // This is a stub implementation for backward compatibility
        &[]
    }

    /// Set kernel type
    pub fn kernel(mut self, kernel: &str) -> Self {
        self.kernel = kernel.to_string();
        self
    }

    /// Set regularization parameter nu
    pub fn nu(mut self, nu: f64) -> Self {
        self.nu = nu;
        self
    }

    /// Set kernel coefficient gamma
    pub fn gamma(mut self, gamma: f64) -> Self {
        self.gamma = Some(gamma);
        self
    }

    /// Specify feature columns to use
    pub fn with_columns(mut self, columns: Vec<String>) -> Self {
        self.feature_columns = Some(columns);
        self
    }
}

impl UnsupervisedModel for OneClassSVM {
    fn fit(&mut self, data: &DataFrame) -> Result<()> {
        // Placeholder implementation
        self.feature_columns = Some(data.column_names().into());
        Ok(())
    }

    fn transform(&self, data: &DataFrame) -> Result<DataFrame> {
        // Transform adds an anomaly score column to the data
        let n_samples = data.row_count();

        // Placeholder implementation for scoring
        use rand::{Rng, RngExt};
        let mut rng = rand::rng();

        let scores: Vec<f64> = (0..n_samples)
            .map(|_| rng.random_range(-1.0..1.0))
            .collect();

        let mut result = data.clone();

        result.add_column(
            "anomaly_score".to_string(),
            crate::series::Series::new(scores, Some("anomaly_score".to_string()))?,
        )?;

        Ok(result)
    }
}

impl ModelEvaluator for OneClassSVM {
    fn evaluate(&self, _test_data: &DataFrame, _test_target: &str) -> Result<ModelMetrics> {
        let mut metrics = ModelMetrics::new();
        metrics.add_metric("anomaly_ratio", self.nu);
        Ok(metrics)
    }

    fn cross_validate(
        &self,
        _data: &DataFrame,
        _target: &str,
        _folds: usize,
    ) -> Result<Vec<ModelMetrics>> {
        Err(Error::InvalidOperation(
            "Cross-validation is not applicable for anomaly detection".into(),
        ))
    }
}

// Re-exports - remove self references to avoid duplicate definitions
// These types are already defined in this module, so no need to re-export