sklears-core 0.1.1

Core traits, types, and utilities for sklears machine learning 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
/// Private API utilities and implementation details
///
/// This module contains internal implementation details that should not be
/// exposed to library users. These APIs may change without notice and should
/// not be relied upon by external code.
///
/// # Design Principles
///
/// - **Stability**: Items in this module may change without warning
/// - **Internal Use**: These APIs are only intended for use within sklears-core
/// - **No Guarantees**: No backward compatibility guarantees are provided
///
/// # Module Organization
///
/// Private APIs are organized into logical groups:
/// - Internal utilities
/// - Implementation helpers
/// - Testing internals
/// - Debug utilities
use crate::error::{Result, SklearsError};
use crate::types::FloatBounds;
use std::fmt::Debug;

// =============================================================================
// Internal Utilities (Private)
// =============================================================================

/// Internal trait for objects that can be validated
///
/// This is an implementation detail and should not be used directly.
/// Use the public `Validate` trait instead.
#[allow(dead_code)]
pub(crate) trait InternalValidate {
    /// Internal validation method
    fn internal_validate(&self) -> Result<()>;

    /// Get validation context for debugging
    fn validation_context(&self) -> ValidationDebugInfo;
}

/// Debug information for validation (internal use only)
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct ValidationDebugInfo {
    pub type_name: &'static str,
    pub rules_applied: Vec<String>,
    pub validation_time_ns: u64,
    pub memory_used_bytes: usize,
}

impl Default for ValidationDebugInfo {
    fn default() -> Self {
        Self {
            type_name: "Unknown",
            rules_applied: Vec::new(),
            validation_time_ns: 0,
            memory_used_bytes: 0,
        }
    }
}

/// Internal memory management utilities
pub(crate) mod memory {
    use super::*;

    /// Memory pool for internal allocations (private)
    #[allow(dead_code)]
    pub(crate) struct InternalMemoryPool {
        allocated_bytes: usize,
        max_allocation: usize,
        allocation_count: usize,
    }

    #[allow(dead_code)]
    impl InternalMemoryPool {
        /// Create a new memory pool (internal)
        pub(crate) fn new(max_allocation: usize) -> Self {
            Self {
                allocated_bytes: 0,
                max_allocation,
                allocation_count: 0,
            }
        }

        /// Try to allocate memory (internal)
        pub(crate) fn try_allocate(&mut self, bytes: usize) -> Result<AllocationHandle> {
            if self.allocated_bytes + bytes > self.max_allocation {
                return Err(SklearsError::InvalidOperation(
                    "Memory pool exhausted".to_string(),
                ));
            }

            self.allocated_bytes += bytes;
            self.allocation_count += 1;

            Ok(AllocationHandle {
                id: self.allocation_count,
                size: bytes,
            })
        }

        /// Deallocate memory (internal)
        pub(crate) fn deallocate(&mut self, handle: AllocationHandle) {
            self.allocated_bytes = self.allocated_bytes.saturating_sub(handle.size);
        }

        /// Get memory statistics (internal)
        pub(crate) fn stats(&self) -> MemoryStats {
            MemoryStats {
                allocated_bytes: self.allocated_bytes,
                max_allocation: self.max_allocation,
                allocation_count: self.allocation_count,
            }
        }
    }

    /// Handle for memory allocation (internal)
    #[derive(Debug, Clone, Copy)]
    #[allow(dead_code)]
    pub(crate) struct AllocationHandle {
        pub(crate) id: usize,
        pub(crate) size: usize,
    }

    /// Memory statistics (internal)
    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    pub(crate) struct MemoryStats {
        pub allocated_bytes: usize,
        pub max_allocation: usize,
        pub allocation_count: usize,
    }
}

/// Internal algorithm implementation helpers
pub(crate) mod algorithm_internals {
    use super::*;

    /// Internal trait for algorithm state management
    #[allow(dead_code)]
    pub(crate) trait AlgorithmState {
        /// Get the current state of the algorithm
        fn current_state(&self) -> InternalState;

        /// Transition to a new state
        fn transition_to(&mut self, new_state: InternalState) -> Result<()>;

        /// Validate state transition
        fn can_transition_to(&self, new_state: InternalState) -> bool;
    }

    /// Internal algorithm states
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[allow(dead_code)]
    pub(crate) enum InternalState {
        /// Algorithm is uninitialized
        Uninitialized,
        /// Algorithm is configured but not fitted
        Configured,
        /// Algorithm is currently fitting
        Fitting,
        /// Algorithm is fitted and ready for prediction
        Fitted,
        /// Algorithm is in an error state
        Error,
    }

    /// Internal convergence checking utilities
    #[allow(dead_code)]
    pub(crate) struct ConvergenceChecker<T: FloatBounds> {
        tolerance: T,
        max_iterations: usize,
        current_iteration: usize,
        last_value: Option<T>,
        history: Vec<T>,
    }

    impl<T: FloatBounds> ConvergenceChecker<T> {
        /// Create a new convergence checker (internal)
        #[allow(dead_code)]
        pub(crate) fn new(tolerance: T, max_iterations: usize) -> Self {
            Self {
                tolerance,
                max_iterations,
                current_iteration: 0,
                last_value: None,
                history: Vec::new(),
            }
        }

        /// Check if the algorithm has converged (internal)
        #[allow(dead_code)]
        pub(crate) fn check_convergence(&mut self, current_value: T) -> ConvergenceStatus {
            self.current_iteration += 1;
            self.history.push(current_value);

            if self.current_iteration >= self.max_iterations {
                return ConvergenceStatus::MaxIterationsReached;
            }

            if let Some(last) = self.last_value {
                let diff = if current_value > last {
                    current_value - last
                } else {
                    last - current_value
                };

                if diff < self.tolerance {
                    return ConvergenceStatus::Converged;
                }
            }

            self.last_value = Some(current_value);
            ConvergenceStatus::Continuing
        }

        /// Get convergence statistics (internal)
        #[allow(dead_code)]
        pub(crate) fn stats(&self) -> ConvergenceStats<T> {
            ConvergenceStats {
                iterations: self.current_iteration,
                tolerance: self.tolerance,
                history: self.history.clone(),
            }
        }
    }

    /// Convergence status (internal)
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[allow(dead_code)]
    pub(crate) enum ConvergenceStatus {
        /// Algorithm is still converging
        Continuing,
        /// Algorithm has converged
        Converged,
        /// Maximum iterations reached without convergence
        MaxIterationsReached,
    }

    /// Convergence statistics (internal)
    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    pub(crate) struct ConvergenceStats<T> {
        pub iterations: usize,
        pub tolerance: T,
        pub history: Vec<T>,
    }
}

/// Internal testing utilities
#[allow(non_snake_case)]
#[cfg(test)]
pub(crate) mod testing {
    use super::*;

    /// Generate test data for internal testing
    pub(crate) fn generate_test_matrix(rows: usize, cols: usize) -> Vec<Vec<f64>> {
        (0..rows)
            .map(|i| (0..cols).map(|j| (i * cols + j) as f64).collect())
            .collect()
    }

    /// Internal test assertion utilities
    pub(crate) fn assert_matrices_close(a: &[Vec<f64>], b: &[Vec<f64>], tolerance: f64) {
        assert_eq!(a.len(), b.len(), "Matrix row count mismatch");
        for (i, (row_a, row_b)) in a.iter().zip(b.iter()).enumerate() {
            assert_eq!(
                row_a.len(),
                row_b.len(),
                "Matrix column count mismatch at row {}",
                i
            );
            for (j, (&val_a, &val_b)) in row_a.iter().zip(row_b.iter()).enumerate() {
                let diff = (val_a - val_b).abs();
                assert!(
                    diff < tolerance,
                    "Values differ at position ({}, {}): {} vs {} (diff: {})",
                    i,
                    j,
                    val_a,
                    val_b,
                    diff
                );
            }
        }
    }

    /// Mock algorithm for testing (internal)
    pub(crate) struct MockAlgorithm {
        state: algorithm_internals::InternalState,
        #[allow(dead_code)]
        // intentionally deferred: fitted data stored but prediction is a mock stub
        fitted_data: Option<Vec<f64>>,
    }

    impl MockAlgorithm {
        pub(crate) fn new() -> Self {
            Self {
                state: algorithm_internals::InternalState::Uninitialized,
                fitted_data: None,
            }
        }

        #[allow(dead_code)] // intentionally deferred: mock fit method for future integration tests
        pub(crate) fn fit(&mut self, data: Vec<f64>) -> Result<()> {
            self.state = algorithm_internals::InternalState::Fitting;
            self.fitted_data = Some(data);
            self.state = algorithm_internals::InternalState::Fitted;
            Ok(())
        }

        #[allow(dead_code)] // intentionally deferred: mock predict method for future integration tests
        pub(crate) fn predict(&self, input: &[f64]) -> Result<Vec<f64>> {
            if self.state != algorithm_internals::InternalState::Fitted {
                return Err(SklearsError::InvalidOperation(
                    "Algorithm must be fitted before prediction".to_string(),
                ));
            }

            Ok(input.iter().map(|&x| x * 2.0).collect())
        }
    }

    impl algorithm_internals::AlgorithmState for MockAlgorithm {
        fn current_state(&self) -> algorithm_internals::InternalState {
            self.state
        }

        fn transition_to(&mut self, new_state: algorithm_internals::InternalState) -> Result<()> {
            if !self.can_transition_to(new_state) {
                return Err(SklearsError::InvalidOperation(format!(
                    "Invalid state transition from {:?} to {:?}",
                    self.state, new_state
                )));
            }
            self.state = new_state;
            Ok(())
        }

        fn can_transition_to(&self, new_state: algorithm_internals::InternalState) -> bool {
            use algorithm_internals::InternalState::*;
            matches!(
                (self.state, new_state),
                (Uninitialized, Configured)
                    | (Configured, Fitting)
                    | (Fitting, Fitted)
                    | (Fitting, Error)
                    | (_, Error)
            )
        }
    }
}

/// Internal debug utilities
pub(crate) mod debug {
    use super::*;

    /// Debug information collector (internal)
    #[allow(dead_code)]
    pub(crate) struct DebugCollector {
        enabled: bool,
        entries: Vec<DebugEntry>,
    }

    /// Debug entry (internal)
    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    pub(crate) struct DebugEntry {
        pub timestamp: std::time::Instant,
        pub category: DebugCategory,
        pub message: String,
        pub data: Option<String>,
    }

    /// Debug categories (internal)
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[allow(dead_code)]
    pub(crate) enum DebugCategory {
        Memory,
        Performance,
        Algorithm,
        Validation,
        Other,
    }

    impl DebugCollector {
        /// Create a new debug collector (internal)
        #[allow(dead_code)]
        pub(crate) fn new(enabled: bool) -> Self {
            Self {
                enabled,
                entries: Vec::new(),
            }
        }

        /// Add a debug entry (internal)
        #[allow(dead_code)]
        pub(crate) fn add_entry(
            &mut self,
            category: DebugCategory,
            message: String,
            data: Option<String>,
        ) {
            if self.enabled {
                self.entries.push(DebugEntry {
                    timestamp: std::time::Instant::now(),
                    category,
                    message,
                    data,
                });
            }
        }

        /// Get all debug entries (internal)
        #[allow(dead_code)]
        pub(crate) fn entries(&self) -> &[DebugEntry] {
            &self.entries
        }

        /// Clear debug entries (internal)
        #[allow(dead_code)]
        pub(crate) fn clear(&mut self) {
            self.entries.clear();
        }
    }
}

// =============================================================================
// Tests for Private APIs
// =============================================================================

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

    #[test]
    fn test_memory_pool() {
        let mut pool = memory::InternalMemoryPool::new(1024);

        // Test allocation
        let handle1 = pool.try_allocate(512).expect("try_allocate should succeed");
        assert_eq!(handle1.size, 512);

        let handle2 = pool.try_allocate(256).expect("try_allocate should succeed");
        assert_eq!(handle2.size, 256);

        // Test overflow
        assert!(pool.try_allocate(512).is_err());

        // Test deallocation
        pool.deallocate(handle1);
        let handle3 = pool.try_allocate(512).expect("try_allocate should succeed");
        assert_eq!(handle3.size, 512);

        // Check stats
        let stats = pool.stats();
        assert_eq!(stats.allocated_bytes, 768); // 256 + 512
        assert_eq!(stats.allocation_count, 3);
    }

    #[test]
    fn test_convergence_checker() {
        let mut checker = algorithm_internals::ConvergenceChecker::new(0.01, 10);

        // Test normal convergence
        assert_eq!(
            checker.check_convergence(1.0),
            algorithm_internals::ConvergenceStatus::Continuing
        );
        assert_eq!(
            checker.check_convergence(1.005),
            algorithm_internals::ConvergenceStatus::Converged
        );

        // Test max iterations
        let mut checker2 = algorithm_internals::ConvergenceChecker::new(0.01, 2);
        assert_eq!(
            checker2.check_convergence(1.0),
            algorithm_internals::ConvergenceStatus::Continuing
        );
        assert_eq!(
            checker2.check_convergence(2.0),
            algorithm_internals::ConvergenceStatus::MaxIterationsReached
        );
    }

    #[test]
    fn test_mock_algorithm() {
        use algorithm_internals::AlgorithmState;

        let mut algo = testing::MockAlgorithm::new();
        assert_eq!(
            algo.current_state(),
            algorithm_internals::InternalState::Uninitialized
        );

        // Test state transitions
        assert!(algo
            .transition_to(algorithm_internals::InternalState::Configured)
            .is_ok());
        assert!(algo
            .transition_to(algorithm_internals::InternalState::Fitting)
            .is_ok());
        assert!(algo
            .transition_to(algorithm_internals::InternalState::Fitted)
            .is_ok());

        // Test invalid transitions
        assert!(algo
            .transition_to(algorithm_internals::InternalState::Uninitialized)
            .is_err());
    }

    #[test]
    fn test_debug_collector() {
        let mut collector = debug::DebugCollector::new(true);

        collector.add_entry(
            debug::DebugCategory::Performance,
            "Test message".to_string(),
            Some("Test data".to_string()),
        );

        let entries = collector.entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].category, debug::DebugCategory::Performance);
        assert_eq!(entries[0].message, "Test message");

        collector.clear();
        assert_eq!(collector.entries().len(), 0);
    }

    #[test]
    fn test_testing_utilities() {
        let matrix = testing::generate_test_matrix(2, 3);
        assert_eq!(matrix.len(), 2);
        assert_eq!(matrix[0].len(), 3);
        assert_eq!(matrix[0], vec![0.0, 1.0, 2.0]);
        assert_eq!(matrix[1], vec![3.0, 4.0, 5.0]);

        // Test matrix comparison
        let matrix2 = vec![vec![0.0, 1.0, 2.0], vec![3.0, 4.0, 5.0]];
        testing::assert_matrices_close(&matrix, &matrix2, 1e-10);
    }
}