scirs2-neural 0.3.3

Neural network building blocks module for SciRS2 (scirs2-neural) - Minimal Version
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
//! Terminal color utilities for visualization output
//!
//! This module provides utilities for adding colors to terminal output.

use std::fmt::Display;

/// ANSI color codes
#[derive(Debug, Clone, Copy)]
pub enum Color {
    /// Black color
    Black,
    /// Red color
    Red,
    /// Green color
    Green,
    /// Yellow color
    Yellow,
    /// Blue color
    Blue,
    /// Magenta color
    Magenta,
    /// Cyan color
    Cyan,
    /// White color
    White,
    /// Bright black (gray) color
    BrightBlack,
    /// Bright red color
    BrightRed,
    /// Bright green color
    BrightGreen,
    /// Bright yellow color
    BrightYellow,
    /// Bright blue color
    BrightBlue,
    /// Bright magenta color
    BrightMagenta,
    /// Bright cyan color
    BrightCyan,
    /// Bright white color
    BrightWhite,
}

impl Color {
    /// Get the ANSI foreground color code
    pub fn fg_code(&self) -> &'static str {
        match self {
            Color::Black => "\x1b[30m",
            Color::Red => "\x1b[31m",
            Color::Green => "\x1b[32m",
            Color::Yellow => "\x1b[33m",
            Color::Blue => "\x1b[34m",
            Color::Magenta => "\x1b[35m",
            Color::Cyan => "\x1b[36m",
            Color::White => "\x1b[37m",
            Color::BrightBlack => "\x1b[90m",
            Color::BrightRed => "\x1b[91m",
            Color::BrightGreen => "\x1b[92m",
            Color::BrightYellow => "\x1b[93m",
            Color::BrightBlue => "\x1b[94m",
            Color::BrightMagenta => "\x1b[95m",
            Color::BrightCyan => "\x1b[96m",
            Color::BrightWhite => "\x1b[97m",
        }
    }

    /// Get the ANSI background color code
    pub fn bg_code(&self) -> &'static str {
        match self {
            Color::Black => "\x1b[40m",
            Color::Red => "\x1b[41m",
            Color::Green => "\x1b[42m",
            Color::Yellow => "\x1b[43m",
            Color::Blue => "\x1b[44m",
            Color::Magenta => "\x1b[45m",
            Color::Cyan => "\x1b[46m",
            Color::White => "\x1b[47m",
            Color::BrightBlack => "\x1b[100m",
            Color::BrightRed => "\x1b[101m",
            Color::BrightGreen => "\x1b[102m",
            Color::BrightYellow => "\x1b[103m",
            Color::BrightBlue => "\x1b[104m",
            Color::BrightMagenta => "\x1b[105m",
            Color::BrightCyan => "\x1b[106m",
            Color::BrightWhite => "\x1b[107m",
        }
    }
}

/// ANSI text style
#[derive(Debug, Clone, Copy)]
pub enum Style {
    /// Bold text
    Bold,
    /// Italic text
    Italic,
    /// Underlined text
    Underline,
    /// Blinking text
    Blink,
    /// Inverted colors
    Reverse,
    /// Dim text
    Dim,
}

impl Style {
    /// Get the ANSI style code
    pub fn code(&self) -> &'static str {
        match self {
            Style::Bold => "\x1b[1m",
            Style::Italic => "\x1b[3m",
            Style::Underline => "\x1b[4m",
            Style::Blink => "\x1b[5m",
            Style::Reverse => "\x1b[7m",
            Style::Dim => "\x1b[2m",
        }
    }
}

/// ANSI reset code
pub const RESET: &str = "\x1b[0m";

/// Colorize text with a foreground color
#[allow(dead_code)]
pub fn colorize<T: Display>(text: T, color: Color) -> String {
    format!("{}{}{}", color.fg_code(), text, RESET)
}

/// Colorize text with a background color
#[allow(dead_code)]
pub fn colorize_bg<T: Display>(text: T, color: Color) -> String {
    format!("{}{}{}", color.bg_code(), text, RESET)
}

/// Style text with a text style
#[allow(dead_code)]
pub fn stylize<T: Display>(text: T, style: Style) -> String {
    format!("{}{}{}", style.code(), text, RESET)
}

/// Colorize and style text
#[allow(dead_code)]
pub fn colorize_and_style<T: Display>(
    text: T,
    fg_color: Option<Color>,
    bg_color: Option<Color>,
    style: Option<Style>,
) -> String {
    let mut result = String::new();
    if let Some(fg) = fg_color {
        result.push_str(fg.fg_code());
    }
    if let Some(bg) = bg_color {
        result.push_str(bg.bg_code());
    }
    if let Some(s) = style {
        result.push_str(s.code());
    }
    result.push_str(&format!("{text}"));
    result.push_str(RESET);
    result
}

/// Detect if the terminal supports colors
///
/// This is a simple heuristic based on environment variables
#[allow(dead_code)]
pub fn supports_color() -> bool {
    if let Ok(term) = std::env::var("TERM") {
        if term == "dumb" {
            return false;
        }
    }
    if let Ok(no_color) = std::env::var("NO_COLOR") {
        if !no_color.is_empty() {
            return false;
        }
    }
    if let Ok(color) = std::env::var("FORCE_COLOR") {
        if !color.is_empty() {
            return true;
        }
    }
    // Check if running on GitHub Actions
    if std::env::var("GITHUB_ACTIONS").is_ok() {
        return true;
    }
    // Use cfg to branch platform-specific code
    #[cfg(not(target_os = "windows"))]
    {
        // Simple heuristic: assume color is supported on non-Windows platforms
        true
    }
    #[cfg(target_os = "windows")]
    {
        // On Windows, check for common terminals that support colors
        if let Ok(term) = std::env::var("TERM_PROGRAM") {
            if term == "vscode" || term == "mintty" || term == "alacritty" {
                true
            } else {
                false
            }
        } else {
            false
        }
    }
}

/// Colorization options for terminal output
pub struct ColorOptions {
    /// Whether to use colors
    pub enabled: bool,
    /// Whether to use background colors
    pub use_background: bool,
    /// Whether to use bright colors
    pub use_bright: bool,
}

impl Default for ColorOptions {
    fn default() -> Self {
        Self {
            enabled: supports_color(),
            use_background: true,
            use_bright: true,
        }
    }
}

/// Get the appropriate color based on a value's position in a range
/// Returns red for values close to 0.0, yellow for values around 0.5,
/// and green for values close to 1.0
#[allow(dead_code)]
pub fn gradient_color(value: f64, options: &ColorOptions) -> Option<Color> {
    if !options.enabled {
        return None;
    }
    if !(0.0..=1.0).contains(&value) {
        return None;
    }
    // Red -> Yellow -> Green gradient
    if value < 0.5 {
        // Red to Yellow (0.0 -> 0.5)
        if options.use_bright {
            Some(Color::BrightRed)
        } else {
            Some(Color::Red)
        }
    } else if value < 0.7 {
        // Yellow (0.5 -> 0.7)
        if options.use_bright {
            Some(Color::BrightYellow)
        } else {
            Some(Color::Yellow)
        }
    } else {
        // Green (0.7 -> 1.0)
        if options.use_bright {
            Some(Color::BrightGreen)
        } else {
            Some(Color::Green)
        }
    }
}

/// Generate a more fine-grained gradient color for heatmap visualizations
/// This provides a more detailed color spectrum for visualizing data with subtle differences
/// Returns a spectrum from cool (blues/purples) for low values to warm (reds/yellows) for high values
#[allow(dead_code)]
pub fn heatmap_gradient_color(value: f64, options: &ColorOptions) -> Option<Color> {
    if !options.enabled {
        return None;
    }
    if !(0.0..=1.0).contains(&value) {
        return None;
    }
    // More detailed gradient with 5 color stops
    if value < 0.2 {
        // Very low values (0.0 -> 0.2)
        if options.use_bright {
            Some(Color::BrightBlue)
        } else {
            Some(Color::Blue)
        }
    } else if value < 0.4 {
        // Low values (0.2 -> 0.4)
        if options.use_bright {
            Some(Color::BrightCyan)
        } else {
            Some(Color::Cyan)
        }
    } else if value < 0.6 {
        // Medium values (0.4 -> 0.6)
        if options.use_bright {
            Some(Color::BrightYellow)
        } else {
            Some(Color::Yellow)
        }
    } else if value < 0.8 {
        // High values (0.6 -> 0.8)
        if options.use_bright {
            Some(Color::BrightRed)
        } else {
            Some(Color::Red)
        }
    } else {
        // Very high values (0.8 -> 1.0)
        if options.use_bright {
            Some(Color::BrightMagenta)
        } else {
            Some(Color::Magenta)
        }
    }
}

/// Generate table cell content with appropriate color based on value
#[allow(dead_code)]
pub fn colored_metric_cell<T: Display>(
    value: T,
    normalized_value: f64,
    options: &ColorOptions,
) -> String {
    if !options.enabled {
        return format!("{value}");
    }
    if let Some(color) = gradient_color(normalized_value, options) {
        colorize(value, color)
    } else {
        format!("{value}")
    }
}

/// Generate a heatmap cell with color gradient for confusion matrix
#[allow(dead_code)]
pub fn heatmap_cell<T: Display>(
    _value: T,
    normalized_value: f64,
    options: &ColorOptions,
) -> String {
    if !options.enabled {
        return format!("{_value}");
    }
    if let Some(color) = heatmap_gradient_color(normalized_value, options) {
        // For higher values, use bold to emphasize importance
        if normalized_value > 0.7 {
            colorize(stylize(_value, Style::Bold), color)
        } else {
            colorize(_value, color)
        }
    } else {
        format!("{_value}")
    }
}

/// Build a color legend for confusion matrix or other visualizations
#[allow(dead_code)]
pub fn color_legend(options: &ColorOptions) -> Option<String> {
    if !options.enabled {
        return None;
    }
    let mut legend = String::from("Color Legend: ");
    let low_color = if options.use_bright {
        Color::BrightRed
    } else {
        Color::Red
    };
    let mid_color = if options.use_bright {
        Color::BrightYellow
    } else {
        Color::Yellow
    };
    let high_color = if options.use_bright {
        Color::BrightGreen
    } else {
        Color::Green
    };
    legend.push_str(&format!("{} Low (0.0-0.5) ", colorize("", low_color)));
    legend.push_str(&format!("{} Medium (0.5-0.7) ", colorize("", mid_color)));
    legend.push_str(&format!("{} High (0.7-1.0)", colorize("", high_color)));
    Some(legend)
}

/// Build a detailed heatmap color legend
#[allow(dead_code)]
pub fn heatmap_color_legend(options: &ColorOptions) -> Option<String> {
    if !options.enabled {
        return None;
    }
    let mut legend = String::from("Heatmap Legend: ");
    let colors = [
        (
            if options.use_bright {
                Color::BrightBlue
            } else {
                Color::Blue
            },
            "Very Low (0.0-0.2)",
        ),
        (
            if options.use_bright {
                Color::BrightCyan
            } else {
                Color::Cyan
            },
            "Low (0.2-0.4)",
        ),
        (
            if options.use_bright {
                Color::BrightYellow
            } else {
                Color::Yellow
            },
            "Medium (0.4-0.6)",
        ),
        (
            if options.use_bright {
                Color::BrightRed
            } else {
                Color::Red
            },
            "High (0.6-0.8)",
        ),
        (
            if options.use_bright {
                Color::BrightMagenta
            } else {
                Color::Magenta
            },
            "Very High (0.8-1.0)",
        ),
    ];
    for (i, (color, label)) in colors.iter().enumerate() {
        if i > 0 {
            legend.push(' ');
        }
        legend.push_str(&format!("{} {}", colorize("", *color), label));
    }
    Some(legend)
}

/// Helper function to conditionally create a string with ANSI coloring for terminal output
#[allow(dead_code)]
pub fn colored_string<T: Display>(
    content: T,
    color: Option<Color>,
    style: Option<Style>,
) -> String {
    match (color, style) {
        (Some(c), Some(s)) => colorize_and_style(content, Some(c), None, Some(s)),
        (Some(c), None) => colorize(content, c),
        (None, Some(s)) => stylize(content, s),
        (None, None) => content.to_string(),
    }
}