rfann 0.1.0

A pure Rust implementation of the Fast Artificial Neural Network (FANN) library
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
//! Comprehensive error handling system for rfann
//!
//! This module provides a unified error handling framework with detailed error categories,
//! context information, and recovery mechanisms for robust neural network operations.

use crate::{NetworkError, TrainingError};
use std::error::Error;
use thiserror::Error;

/// Main error type for all rfann operations
#[derive(Error, Debug)]
pub enum RuvFannError {
    /// Network configuration and topology errors
    #[error("Network error: {category:?} - {message}")]
    Network {
        category: NetworkErrorCategory,
        message: String,
        context: Option<String>,
    },

    /// Training and learning algorithm errors
    #[error("Training error: {category:?} - {message}")]
    Training {
        category: TrainingErrorCategory,
        message: String,
        context: Option<String>,
    },

    /// Cascade correlation specific errors
    #[error("Cascade error: {category:?} - {message}")]
    Cascade {
        category: CascadeErrorCategory,
        message: String,
        context: Option<String>,
    },

    /// Data validation and format errors
    #[error("Validation error: {category:?} - {message}")]
    Validation {
        category: ValidationErrorCategory,
        message: String,
        details: Vec<String>,
    },

    /// I/O and serialization errors
    #[error("I/O error: {category:?} - {message}")]
    Io {
        category: IoErrorCategory,
        message: String,
        source: Option<Box<dyn Error + Send + Sync>>,
    },

    /// Parallel processing and concurrency errors
    #[error("Parallel processing error: {message}")]
    Parallel {
        message: String,
        thread_count: usize,
        context: Option<String>,
    },

    /// Memory allocation and management errors
    #[error("Memory error: {message}")]
    Memory {
        message: String,
        requested_bytes: Option<usize>,
        available_bytes: Option<usize>,
    },

    /// Performance and optimization errors
    #[error("Performance error: {message}")]
    Performance {
        message: String,
        metric: String,
        threshold: f64,
        actual: f64,
    },

    /// FANN compatibility errors
    #[error("FANN compatibility error: {message}")]
    Compatibility {
        message: String,
        fann_version: Option<String>,
        operation: String,
    },
}

/// Network error categories for detailed classification
#[derive(Debug, Clone, PartialEq)]
pub enum NetworkErrorCategory {
    /// Invalid network topology or structure
    Topology,
    /// Weight and bias configuration issues
    Weights,
    /// Layer configuration problems
    Layers,
    /// Neuron connection issues
    Connections,
    /// Activation function problems
    Activation,
    /// Forward propagation errors
    Propagation,
}

/// Training error categories
#[derive(Debug, Clone, PartialEq)]
pub enum TrainingErrorCategory {
    /// Learning algorithm failures
    Algorithm,
    /// Convergence problems
    Convergence,
    /// Gradient calculation issues
    Gradients,
    /// Learning rate problems
    LearningRate,
    /// Epoch and iteration errors
    Iteration,
    /// Stop criteria issues
    StopCriteria,
}

/// Cascade correlation error categories
#[derive(Debug, Clone, PartialEq)]
pub enum CascadeErrorCategory {
    /// Candidate neuron generation issues
    CandidateGeneration,
    /// Candidate training failures
    CandidateTraining,
    /// Candidate selection problems
    CandidateSelection,
    /// Network topology modification errors
    TopologyModification,
    /// Correlation calculation issues
    CorrelationCalculation,
    /// Output training problems
    OutputTraining,
}

/// Validation error categories
#[derive(Debug, Clone, PartialEq)]
pub enum ValidationErrorCategory {
    /// Input data validation
    InputData,
    /// Output data validation
    OutputData,
    /// Network configuration validation
    NetworkConfig,
    /// Training parameter validation
    TrainingParams,
    /// Cascade parameter validation
    CascadeParams,
}

/// I/O error categories
#[derive(Debug, Clone, PartialEq)]
pub enum IoErrorCategory {
    /// File reading/writing issues
    FileAccess,
    /// Serialization/deserialization problems
    Serialization,
    /// Format compatibility issues
    Format,
    /// Network export/import errors
    NetworkIo,
    /// Training data I/O problems
    DataIo,
}

/// Comprehensive error category enum for uniform handling
#[derive(Debug, Clone, PartialEq)]
pub enum ErrorCategory {
    Network(NetworkErrorCategory),
    Training(TrainingErrorCategory),
    Cascade(CascadeErrorCategory),
    Validation(ValidationErrorCategory),
    Io(IoErrorCategory),
    Parallel,
    Memory,
    Performance,
    Compatibility,
}

/// Validation error for detailed parameter checking
#[derive(Error, Debug)]
pub enum ValidationError {
    #[error("Parameter out of range: {parameter} = {value}, expected {min} <= value <= {max}")]
    OutOfRange {
        parameter: String,
        value: f64,
        min: f64,
        max: f64,
    },

    #[error("Invalid configuration: {message}")]
    InvalidConfig { message: String },

    #[error("Missing required parameter: {parameter}")]
    MissingParameter { parameter: String },

    #[error("Incompatible parameters: {message}")]
    IncompatibleParams { message: String },

    #[error("Data format error: {message}")]
    DataFormat { message: String },
}

/// Error context for providing additional debugging information
#[derive(Debug, Clone)]
pub struct ErrorContext {
    pub operation: String,
    pub network_id: Option<String>,
    pub layer_index: Option<usize>,
    pub neuron_index: Option<usize>,
    pub epoch: Option<usize>,
    pub timestamp: std::time::SystemTime,
    pub additional_info: std::collections::HashMap<String, String>,
}

impl ErrorContext {
    pub fn new(operation: impl Into<String>) -> Self {
        Self {
            operation: operation.into(),
            network_id: None,
            layer_index: None,
            neuron_index: None,
            epoch: None,
            timestamp: std::time::SystemTime::now(),
            additional_info: std::collections::HashMap::new(),
        }
    }

    pub fn with_network_id(mut self, id: impl Into<String>) -> Self {
        self.network_id = Some(id.into());
        self
    }

    pub fn with_layer(mut self, index: usize) -> Self {
        self.layer_index = Some(index);
        self
    }

    pub fn with_neuron(mut self, index: usize) -> Self {
        self.neuron_index = Some(index);
        self
    }

    pub fn with_epoch(mut self, epoch: usize) -> Self {
        self.epoch = Some(epoch);
        self
    }

    pub fn with_info(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.additional_info.insert(key.into(), value.into());
        self
    }
}

/// Error recovery strategies
#[derive(Debug, Clone)]
pub enum RecoveryStrategy {
    /// Retry the operation with the same parameters
    Retry,
    /// Retry with modified parameters
    RetryWithModification(std::collections::HashMap<String, String>),
    /// Reset to a known good state
    Reset,
    /// Skip the problematic operation
    Skip,
    /// Abort the entire process
    Abort,
    /// Use fallback implementation
    Fallback(String),
}

/// Error recovery context
#[derive(Debug)]
pub struct RecoveryContext {
    pub strategy: RecoveryStrategy,
    pub max_retries: usize,
    pub current_retry: usize,
    pub fallback_available: bool,
    pub checkpoints: Vec<String>,
}

impl RecoveryContext {
    pub fn new(strategy: RecoveryStrategy) -> Self {
        Self {
            strategy,
            max_retries: 3,
            current_retry: 0,
            fallback_available: false,
            checkpoints: Vec::new(),
        }
    }

    pub fn should_retry(&self) -> bool {
        self.current_retry < self.max_retries
    }

    pub fn increment_retry(&mut self) {
        self.current_retry += 1;
    }

    pub fn reset_retry_count(&mut self) {
        self.current_retry = 0;
    }
}

/// Professional error logging and debugging facilities
pub struct ErrorLogger {
    #[cfg(feature = "logging")]
    log_level: log::Level,
    #[cfg(not(feature = "logging"))]
    log_level: u8, // Simple placeholder when log feature is disabled
    structured_logging: bool,
    performance_tracking: bool,
}

impl ErrorLogger {
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "logging")]
            log_level: log::Level::Warn,
            #[cfg(not(feature = "logging"))]
            log_level: 2, // 2 as a placeholder for Warn level
            structured_logging: true,
            performance_tracking: false,
        }
    }

    #[cfg(feature = "logging")]
    pub fn with_level(mut self, level: log::Level) -> Self {
        self.log_level = level;
        self
    }

    #[cfg(not(feature = "logging"))]
    pub fn with_level(self, _level: u8) -> Self {
        // No-op when logging is disabled
        self
    }

    pub fn with_structured_logging(mut self, enabled: bool) -> Self {
        self.structured_logging = enabled;
        self
    }

    pub fn with_performance_tracking(mut self, enabled: bool) -> Self {
        self.performance_tracking = enabled;
        self
    }

    pub fn log_error(&self, error: &RuvFannError, context: Option<&ErrorContext>) {
        if self.structured_logging {
            self.log_structured_error(error, context);
        } else {
            self.log_simple_error(error, context);
        }
    }

    fn log_structured_error(&self, error: &RuvFannError, context: Option<&ErrorContext>) {
        #[cfg(feature = "serde")]
        {
            let mut fields = serde_json::Map::new();
            fields.insert(
                "error_type".to_string(),
                serde_json::Value::String(format!("{error:?}")),
            );
            fields.insert(
                "message".to_string(),
                serde_json::Value::String(error.to_string()),
            );

            if let Some(ctx) = context {
                fields.insert(
                    "operation".to_string(),
                    serde_json::Value::String(ctx.operation.clone()),
                );
                if let Some(ref network_id) = ctx.network_id {
                    fields.insert(
                        "network_id".to_string(),
                        serde_json::Value::String(network_id.clone()),
                    );
                }
                if let Some(layer_idx) = ctx.layer_index {
                    fields.insert(
                        "layer_index".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(layer_idx)),
                    );
                }
                if let Some(neuron_idx) = ctx.neuron_index {
                    fields.insert(
                        "neuron_index".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(neuron_idx)),
                    );
                }
                if let Some(epoch) = ctx.epoch {
                    fields.insert(
                        "epoch".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(epoch)),
                    );
                }
            }

            #[cfg(feature = "logging")]
            {
                log::log!(self.log_level, "{}", serde_json::Value::Object(fields));
            }
        }

        #[cfg(not(feature = "serde"))]
        {
            // Simple fallback when serde_json is not available
            let _ = error;
            let _ = context;
        }

        #[cfg(all(feature = "logging", not(feature = "serde")))]
        log::log!(self.log_level, "Error: {}", error);
    }

    fn log_simple_error(&self, error: &RuvFannError, context: Option<&ErrorContext>) {
        let context_str = context
            .map(|c| format!(" [{}]", c.operation))
            .unwrap_or_default();

        #[cfg(feature = "logging")]
        log::log!(self.log_level, "Error{context_str}: {error}");
    }
}

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

/// Convert from legacy error types for backward compatibility
impl From<NetworkError> for RuvFannError {
    fn from(error: NetworkError) -> Self {
        match error {
            NetworkError::InputSizeMismatch { expected, actual } => RuvFannError::Network {
                category: NetworkErrorCategory::Topology,
                message: format!("Input size mismatch: expected {expected}, got {actual}"),
                context: None,
            },
            NetworkError::WeightCountMismatch { expected, actual } => RuvFannError::Network {
                category: NetworkErrorCategory::Weights,
                message: format!("Weight count mismatch: expected {expected}, got {actual}"),
                context: None,
            },
            NetworkError::InvalidLayerConfiguration => RuvFannError::Network {
                category: NetworkErrorCategory::Layers,
                message: "Invalid layer configuration".to_string(),
                context: None,
            },
            NetworkError::NoLayers => RuvFannError::Network {
                category: NetworkErrorCategory::Topology,
                message: "Network has no layers".to_string(),
                context: None,
            },
        }
    }
}

impl From<TrainingError> for RuvFannError {
    fn from(error: TrainingError) -> Self {
        match error {
            TrainingError::InvalidData(msg) => RuvFannError::Validation {
                category: ValidationErrorCategory::InputData,
                message: msg,
                details: vec![],
            },
            TrainingError::NetworkError(msg) => RuvFannError::Network {
                category: NetworkErrorCategory::Topology,
                message: msg,
                context: None,
            },
            TrainingError::TrainingFailed(msg) => RuvFannError::Training {
                category: TrainingErrorCategory::Algorithm,
                message: msg,
                context: None,
            },
        }
    }
}

/// Helper macros for error creation with context
#[macro_export]
macro_rules! network_error {
    ($category:expr, $msg:expr) => {
        RuvFannError::Network {
            category: $category,
            message: $msg.to_string(),
            context: None,
        }
    };
    ($category:expr, $msg:expr, $context:expr) => {
        RuvFannError::Network {
            category: $category,
            message: $msg.to_string(),
            context: Some($context.to_string()),
        }
    };
}

#[macro_export]
macro_rules! training_error {
    ($category:expr, $msg:expr) => {
        RuvFannError::Training {
            category: $category,
            message: $msg.to_string(),
            context: None,
        }
    };
    ($category:expr, $msg:expr, $context:expr) => {
        RuvFannError::Training {
            category: $category,
            message: $msg.to_string(),
            context: Some($context.to_string()),
        }
    };
}

#[macro_export]
macro_rules! cascade_error {
    ($category:expr, $msg:expr) => {
        RuvFannError::Cascade {
            category: $category,
            message: $msg.to_string(),
            context: None,
        }
    };
    ($category:expr, $msg:expr, $context:expr) => {
        RuvFannError::Cascade {
            category: $category,
            message: $msg.to_string(),
            context: Some($context.to_string()),
        }
    };
}

/// Comprehensive result type for all rfann operations
pub type RuvFannResult<T> = Result<T, RuvFannError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_creation() {
        let error = RuvFannError::Network {
            category: NetworkErrorCategory::Topology,
            message: "Test error".to_string(),
            context: None,
        };

        assert!(matches!(error, RuvFannError::Network { .. }));
    }

    #[test]
    fn test_error_context() {
        let context = ErrorContext::new("test_operation")
            .with_network_id("network_1")
            .with_layer(2)
            .with_epoch(100);

        assert_eq!(context.operation, "test_operation");
        assert_eq!(context.network_id, Some("network_1".to_string()));
        assert_eq!(context.layer_index, Some(2));
        assert_eq!(context.epoch, Some(100));
    }

    #[test]
    fn test_recovery_context() {
        let mut recovery = RecoveryContext::new(RecoveryStrategy::Retry);
        assert!(recovery.should_retry());

        recovery.max_retries = 2;
        recovery.current_retry = 2;
        assert!(!recovery.should_retry());
    }

    #[test]
    fn test_error_conversion() {
        let network_error = NetworkError::NoLayers;
        let lion_error: RuvFannError = network_error.into();

        match lion_error {
            RuvFannError::Network { category, .. } => {
                assert_eq!(category, NetworkErrorCategory::Topology);
            }
            _ => panic!("Expected Network error"),
        }
    }
}