aprender-core 0.29.3

Next-generation machine learning library in pure Rust
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
//! Metrics tracking for CITL performance analysis.
//!
//! Provides comprehensive tracking of fix attempts, pattern usage,
//! compilation times, and convergence rates.

use std::collections::HashMap;
use std::fmt::Write as _;
use std::time::{Duration, Instant};

/// Comprehensive metrics tracker for CITL operations.
///
/// Tracks fix attempt success rates, pattern usage, compilation times,
/// error frequencies, and convergence statistics.
#[derive(Debug)]
pub struct MetricsTracker {
    /// Fix attempt metrics
    fix_attempts: FixAttemptMetrics,
    /// Pattern usage metrics
    pattern_usage: PatternUsageMetrics,
    /// Compilation time metrics
    compilation_times: CompilationTimeMetrics,
    /// Error frequency metrics
    error_frequencies: ErrorFrequencyMetrics,
    /// Convergence metrics
    convergence: ConvergenceMetrics,
    /// Session start time
    session_start: Instant,
}

impl MetricsTracker {
    /// Create a new metrics tracker.
    #[must_use]
    pub fn new() -> Self {
        Self {
            fix_attempts: FixAttemptMetrics::new(),
            pattern_usage: PatternUsageMetrics::new(),
            compilation_times: CompilationTimeMetrics::new(),
            error_frequencies: ErrorFrequencyMetrics::new(),
            convergence: ConvergenceMetrics::new(),
            session_start: Instant::now(),
        }
    }

    /// Record a fix attempt result.
    pub fn record_fix_attempt(&mut self, success: bool, error_code: &str) {
        self.fix_attempts.record(success);
        self.error_frequencies.record(error_code);
    }

    /// Record pattern usage.
    pub fn record_pattern_use(&mut self, pattern_id: usize, success: bool) {
        self.pattern_usage.record(pattern_id, success);
    }

    /// Record compilation time.
    pub fn record_compilation_time(&mut self, duration: Duration) {
        self.compilation_times.record(duration);
    }

    /// Record fix convergence (number of iterations to fix).
    pub fn record_convergence(&mut self, iterations: usize, success: bool) {
        self.convergence.record(iterations, success);
    }

    /// Get fix attempt metrics.
    #[must_use]
    pub fn fix_attempts(&self) -> &FixAttemptMetrics {
        &self.fix_attempts
    }

    /// Get pattern usage metrics.
    #[must_use]
    pub fn pattern_usage(&self) -> &PatternUsageMetrics {
        &self.pattern_usage
    }

    /// Get compilation time metrics.
    #[must_use]
    pub fn compilation_times(&self) -> &CompilationTimeMetrics {
        &self.compilation_times
    }

    /// Get error frequency metrics.
    #[must_use]
    pub fn error_frequencies(&self) -> &ErrorFrequencyMetrics {
        &self.error_frequencies
    }

    /// Get convergence metrics.
    #[must_use]
    pub fn convergence(&self) -> &ConvergenceMetrics {
        &self.convergence
    }

    /// Get session duration.
    #[must_use]
    pub fn session_duration(&self) -> Duration {
        self.session_start.elapsed()
    }

    /// Get a summary of all metrics.
    #[must_use]
    pub fn summary(&self) -> MetricsSummary {
        MetricsSummary {
            total_fix_attempts: self.fix_attempts.total(),
            fix_success_rate: self.fix_attempts.success_rate(),
            total_compilations: self.compilation_times.count(),
            avg_compilation_time_ms: self.compilation_times.average_ms(),
            most_common_errors: self.error_frequencies.top_n(5),
            avg_iterations_to_fix: self.convergence.average_iterations(),
            convergence_rate: self.convergence.success_rate(),
            session_duration: self.session_duration(),
        }
    }

    /// Reset all metrics.
    pub fn reset(&mut self) {
        self.fix_attempts = FixAttemptMetrics::new();
        self.pattern_usage = PatternUsageMetrics::new();
        self.compilation_times = CompilationTimeMetrics::new();
        self.error_frequencies = ErrorFrequencyMetrics::new();
        self.convergence = ConvergenceMetrics::new();
        self.session_start = Instant::now();
    }
}

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

/// Metrics for fix attempts.
#[derive(Debug, Clone)]
pub struct FixAttemptMetrics {
    /// Number of successful fixes
    successes: u64,
    /// Number of failed fixes
    failures: u64,
}

impl FixAttemptMetrics {
    /// Create new fix attempt metrics.
    #[must_use]
    pub fn new() -> Self {
        Self {
            successes: 0,
            failures: 0,
        }
    }

    /// Record a fix attempt.
    pub fn record(&mut self, success: bool) {
        if success {
            self.successes += 1;
        } else {
            self.failures += 1;
        }
    }

    /// Get total attempts.
    #[must_use]
    pub fn total(&self) -> u64 {
        self.successes + self.failures
    }

    /// Get success rate (0.0 to 1.0).
    #[must_use]
    pub fn success_rate(&self) -> f64 {
        let total = self.total();
        if total == 0 {
            0.0
        } else {
            self.successes as f64 / total as f64
        }
    }

    /// Get success count.
    #[must_use]
    pub fn successes(&self) -> u64 {
        self.successes
    }

    /// Get failure count.
    #[must_use]
    pub fn failures(&self) -> u64 {
        self.failures
    }
}

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

/// Metrics for pattern usage.
#[derive(Debug, Clone)]
pub struct PatternUsageMetrics {
    /// Usage counts by pattern ID
    usage_counts: HashMap<usize, u64>,
    /// Success counts by pattern ID
    success_counts: HashMap<usize, u64>,
}

impl PatternUsageMetrics {
    /// Create new pattern usage metrics.
    #[must_use]
    pub fn new() -> Self {
        Self {
            usage_counts: HashMap::new(),
            success_counts: HashMap::new(),
        }
    }

    /// Record pattern usage.
    pub fn record(&mut self, pattern_id: usize, success: bool) {
        *self.usage_counts.entry(pattern_id).or_insert(0) += 1;
        if success {
            *self.success_counts.entry(pattern_id).or_insert(0) += 1;
        }
    }

    /// Get usage count for a pattern.
    #[must_use]
    pub fn usage_count(&self, pattern_id: usize) -> u64 {
        *self.usage_counts.get(&pattern_id).unwrap_or(&0)
    }

    /// Get success rate for a pattern.
    #[must_use]
    pub fn pattern_success_rate(&self, pattern_id: usize) -> f64 {
        let usage = self.usage_count(pattern_id);
        if usage == 0 {
            0.0
        } else {
            let successes = *self.success_counts.get(&pattern_id).unwrap_or(&0);
            successes as f64 / usage as f64
        }
    }

    /// Get total patterns used.
    #[must_use]
    pub fn total_patterns_used(&self) -> usize {
        self.usage_counts.len()
    }

    /// Get most used patterns.
    #[must_use]
    pub fn most_used(&self, n: usize) -> Vec<(usize, u64)> {
        let mut counts: Vec<_> = self.usage_counts.iter().map(|(&k, &v)| (k, v)).collect();
        counts.sort_by(|a, b| b.1.cmp(&a.1));
        counts.truncate(n);
        counts
    }
}

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

/// Metrics for compilation times.
#[derive(Debug, Clone)]
pub struct CompilationTimeMetrics {
    /// Total compilation time
    total_time: Duration,
    /// Number of compilations
    count: u64,
    /// Minimum compilation time
    min_time: Option<Duration>,
    /// Maximum compilation time
    max_time: Option<Duration>,
}

impl CompilationTimeMetrics {
    /// Create new compilation time metrics.
    #[must_use]
    pub fn new() -> Self {
        Self {
            total_time: Duration::ZERO,
            count: 0,
            min_time: None,
            max_time: None,
        }
    }

    /// Record a compilation time.
    pub fn record(&mut self, duration: Duration) {
        self.total_time += duration;
        self.count += 1;

        match self.min_time {
            None => self.min_time = Some(duration),
            Some(min) if duration < min => self.min_time = Some(duration),
            _ => {}
        }

        match self.max_time {
            None => self.max_time = Some(duration),
            Some(max) if duration > max => self.max_time = Some(duration),
            _ => {}
        }
    }

    /// Get compilation count.
    #[must_use]
    pub fn count(&self) -> u64 {
        self.count
    }

    /// Get average compilation time in milliseconds.
    #[must_use]
    pub fn average_ms(&self) -> f64 {
        if self.count == 0 {
            0.0
        } else {
            self.total_time.as_millis() as f64 / self.count as f64
        }
    }

    /// Get total compilation time.
    #[must_use]
    pub fn total_time(&self) -> Duration {
        self.total_time
    }

    /// Get minimum compilation time.
    #[must_use]
    pub fn min_time(&self) -> Option<Duration> {
        self.min_time
    }

    /// Get maximum compilation time.
    #[must_use]
    pub fn max_time(&self) -> Option<Duration> {
        self.max_time
    }
}

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

/// Metrics for error frequencies.
#[derive(Debug, Clone)]
pub struct ErrorFrequencyMetrics {
    /// Error counts by error code
    error_counts: HashMap<String, u64>,
}

impl ErrorFrequencyMetrics {
    /// Create new error frequency metrics.
    #[must_use]
    pub fn new() -> Self {
        Self {
            error_counts: HashMap::new(),
        }
    }

    /// Record an error.
    pub fn record(&mut self, error_code: &str) {
        *self.error_counts.entry(error_code.to_string()).or_insert(0) += 1;
    }

    /// Get count for an error code.
    #[must_use]
    pub fn count(&self, error_code: &str) -> u64 {
        *self.error_counts.get(error_code).unwrap_or(&0)
    }

    /// Get total errors.
    #[must_use]
    pub fn total(&self) -> u64 {
        self.error_counts.values().sum()
    }

    /// Get number of unique error types.
    #[must_use]
    pub fn unique_errors(&self) -> usize {
        self.error_counts.len()
    }

    /// Get top N most common errors.
    #[must_use]
    pub fn top_n(&self, n: usize) -> Vec<(String, u64)> {
        let mut counts: Vec<_> = self
            .error_counts
            .iter()
            .map(|(k, &v)| (k.clone(), v))
            .collect();
        counts.sort_by(|a, b| b.1.cmp(&a.1));
        counts.truncate(n);
        counts
    }
}

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

/// Metrics for convergence (iterations to fix).
#[derive(Debug, Clone)]
pub struct ConvergenceMetrics {
    /// Total iterations across all fix attempts
    total_iterations: u64,
    /// Number of successful fixes
    successful_fixes: u64,
    /// Number of failed fixes
    failed_fixes: u64,
    /// Histogram of iterations to fix
    iteration_histogram: HashMap<usize, u64>,
}

include!("metrics_summary.rs");
include!("metrics_tests.rs");