rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
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
//! 可視化ユーティリティ
//! Visualization utilities

use crate::error::RusTorchResult; // RusTorchError,
use std::fs;
use std::path::Path;

/// プロット形式
/// Plot formats
#[derive(Debug, Clone, PartialEq)]
pub enum PlotFormat {
    /// SVG形式
    Svg,
    /// PNG形式(将来の実装用)
    Png,
    /// PDF形式(将来の実装用)
    Pdf,
    /// HTML形式
    Html,
    /// DOT形式
    Dot,
}

impl PlotFormat {
    /// ファイル拡張子を取得
    /// Get file extension
    pub fn extension(&self) -> &'static str {
        match self {
            PlotFormat::Svg => "svg",
            PlotFormat::Png => "png",
            PlotFormat::Pdf => "pdf",
            PlotFormat::Html => "html",
            PlotFormat::Dot => "dot",
        }
    }

    /// MIME タイプを取得
    /// Get MIME type
    pub fn mime_type(&self) -> &'static str {
        match self {
            PlotFormat::Svg => "image/svg+xml",
            PlotFormat::Png => "image/png",
            PlotFormat::Pdf => "application/pdf",
            PlotFormat::Html => "text/html",
            PlotFormat::Dot => "text/vnd.graphviz",
        }
    }
}

/// プロットをファイルに保存
/// Save plot to file
pub fn save_plot<P: AsRef<Path>>(content: &str, path: P, format: PlotFormat) -> RusTorchResult<()> {
    let file_path = path.as_ref();

    // ディレクトリが存在しない場合は作成
    if let Some(parent) = file_path.parent() {
        fs::create_dir_all(parent)?;
    }

    match format {
        PlotFormat::Html => {
            let html_content = wrap_in_html(content, format)?;
            fs::write(file_path, html_content)?;
        }
        _ => {
            fs::write(file_path, content)?;
        }
    }

    Ok(())
}

/// HTMLファイルにSVGを埋め込み
/// Embed SVG in HTML file
pub fn wrap_in_html(svg_content: &str, format: PlotFormat) -> RusTorchResult<String> {
    match format {
        PlotFormat::Html => Ok(format!(
            r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RusTorch Visualization</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }}
        h1 {{
            color: #333;
            margin-bottom: 20px;
        }}
        .plot-container {{
            display: inline-block;
            margin: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #fafafa;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>RusTorch Visualization</h1>
        <div class="plot-container">
            {}
        </div>
        <p style="color: #666; font-size: 12px; margin-top: 20px;">
            Generated by RusTorch v0.3.5
        </p>
    </div>
</body>
</html>"#,
            svg_content
        )),
        _ => Err(crate::error::RusTorchError::visualization(
            "Invalid format for HTML wrapping",
        )),
    }
}

/// 複数のプロットを一つのHTMLファイルにまとめる
/// Combine multiple plots into a single HTML file
pub fn create_dashboard(plots: Vec<(&str, &str)>) -> RusTorchResult<String> {
    let mut plot_sections = String::new();

    for (i, (title, svg_content)) in plots.iter().enumerate() {
        plot_sections.push_str(&format!(
            r#"
        <div class="plot-section">
            <h2>{}. {}</h2>
            <div class="plot-container">
                {}
            </div>
        </div>"#,
            i + 1,
            title,
            svg_content
        ));
    }

    Ok(format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RusTorch Visualization Dashboard</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 30px;
            text-align: center;
        }}
        .header h1 {{
            margin: 0;
            font-size: 2.5em;
            font-weight: 300;
        }}
        .header p {{
            margin: 10px 0 0 0;
            opacity: 0.9;
        }}
        .dashboard {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
        }}
        .plot-section {{
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }}
        .plot-section h2 {{
            background-color: #f8f9fa;
            margin: 0;
            padding: 15px 20px;
            color: #333;
            border-bottom: 1px solid #e9ecef;
            font-size: 1.2em;
        }}
        .plot-container {{
            padding: 20px;
            text-align: center;
        }}
        .footer {{
            text-align: center;
            margin-top: 40px;
            padding: 20px;
            color: #666;
            font-size: 14px;
            background-color: white;
            border-radius: 8px;
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>RusTorch Visualization Dashboard</h1>
        <p>Comprehensive visualization of training progress and model analysis</p>
    </div>
    
    <div class="dashboard">
        {}
    </div>
    
    <div class="footer">
        Generated by RusTorch v0.3.5 • {} plots
    </div>
</body>
</html>"#,
        plot_sections,
        plots.len()
    ))
}

/// カラーパレットユーティリティ
/// Color palette utilities
pub struct ColorPalette;

impl ColorPalette {
    /// 質的データ用のカテゴリカルカラーパレット
    /// Categorical color palette for qualitative data
    pub fn categorical() -> Vec<String> {
        vec![
            "#1f77b4".to_string(), // blue
            "#ff7f0e".to_string(), // orange
            "#2ca02c".to_string(), // green
            "#d62728".to_string(), // red
            "#9467bd".to_string(), // purple
            "#8c564b".to_string(), // brown
            "#e377c2".to_string(), // pink
            "#7f7f7f".to_string(), // gray
            "#bcbd22".to_string(), // olive
            "#17becf".to_string(), // cyan
        ]
    }

    /// シーケンシャルカラーパレット(青系)
    /// Sequential color palette (blues)
    pub fn sequential_blues() -> Vec<String> {
        vec![
            "#f7fbff".to_string(),
            "#deebf7".to_string(),
            "#c6dbef".to_string(),
            "#9ecae1".to_string(),
            "#6baed6".to_string(),
            "#4292c6".to_string(),
            "#2171b5".to_string(),
            "#08519c".to_string(),
            "#08306b".to_string(),
        ]
    }

    /// 発散カラーパレット(赤-青)
    /// Diverging color palette (red-blue)
    pub fn diverging_red_blue() -> Vec<String> {
        vec![
            "#67001f".to_string(),
            "#b2182b".to_string(),
            "#d6604d".to_string(),
            "#f4a582".to_string(),
            "#fddbc7".to_string(),
            "#f7f7f7".to_string(),
            "#d1e5f0".to_string(),
            "#92c5de".to_string(),
            "#4393c3".to_string(),
            "#2166ac".to_string(),
            "#053061".to_string(),
        ]
    }

    /// インデックスに基づいてカテゴリカル色を取得
    /// Get categorical color by index
    pub fn get_categorical_color(index: usize) -> String {
        let colors = Self::categorical();
        colors[index % colors.len()].clone()
    }

    /// 値に基づいてシーケンシャル色を取得
    /// Get sequential color by value
    pub fn get_sequential_color(value: f32) -> String {
        let colors = Self::sequential_blues();
        let clamped_value = value.clamp(0.0, 1.0);
        let index = (clamped_value * (colors.len() - 1) as f32).round() as usize;
        colors[index].clone()
    }
}

/// フォーマット変換ユーティリティ
/// Format conversion utilities
pub fn export_format(
    content: &str,
    from_format: PlotFormat,
    to_format: PlotFormat,
) -> RusTorchResult<String> {
    match (&from_format, &to_format) {
        (PlotFormat::Svg, PlotFormat::Html) => wrap_in_html(content, PlotFormat::Html),
        (PlotFormat::Dot, PlotFormat::Svg) => {
            // DOT to SVG conversion would require Graphviz
            Err(crate::error::RusTorchError::visualization(
                "DOT to SVG conversion requires Graphviz",
            ))
        }
        (from, to) if from == to => Ok(content.to_string()),
        _ => Err(crate::error::RusTorchError::visualization(format!(
            "Conversion from {:?} to {:?} is not supported",
            from_format, to_format
        ))),
    }
}

/// SVGサイズ調整ユーティリティ
/// SVG size adjustment utilities
pub fn resize_svg(svg_content: &str, new_width: u32, new_height: u32) -> RusTorchResult<String> {
    // 簡単なSVGサイズ変更(正規表現を使わない実装)
    if let Some(start) = svg_content.find("<svg") {
        if let Some(end) = svg_content[start..].find(">") {
            let svg_tag_end = start + end + 1;

            // 新しいSVGタグを作成
            let new_svg_tag = format!(
                r#"<svg width="{}" height="{}" xmlns="http://www.w3.org/2000/svg">"#,
                new_width, new_height
            );

            let mut result = String::new();
            result.push_str(&svg_content[..start]);
            result.push_str(&new_svg_tag);
            result.push_str(&svg_content[svg_tag_end..]);

            Ok(result)
        } else {
            Err(crate::error::RusTorchError::plotting_error(
                "Invalid SVG format",
            ))
        }
    } else {
        Err(crate::error::RusTorchError::plotting_error(
            "No SVG tag found",
        ))
    }
}

/// プロット統計情報
/// Plot statistics
#[derive(Debug, Clone)]
pub struct PlotStatistics {
    /// 総要素数
    /// Total elements
    pub total_elements: usize,
    /// SVGファイルサイズ(バイト)
    /// SVG file size in bytes
    pub file_size_bytes: usize,
    /// プロット生成時間(ミリ秒)
    /// Plot generation time in milliseconds
    pub generation_time_ms: u64,
}

impl PlotStatistics {
    /// 新しい統計情報を作成
    /// Create new statistics
    pub fn new(content: &str, generation_time_ms: u64) -> Self {
        Self {
            total_elements: Self::count_svg_elements(content),
            file_size_bytes: content.len(),
            generation_time_ms,
        }
    }

    /// SVG要素数をカウント
    /// Count SVG elements
    fn count_svg_elements(content: &str) -> usize {
        let elements = [
            "<rect", "<circle", "<ellipse", "<line", "<path", "<text", "<polygon",
        ];
        elements
            .iter()
            .map(|element| content.matches(element).count())
            .sum()
    }

    /// 統計情報をフォーマット
    /// Format statistics
    pub fn format(&self) -> String {
        format!(
            "Elements: {}, Size: {} bytes, Generation: {}ms",
            self.total_elements, self.file_size_bytes, self.generation_time_ms
        )
    }
}

/// ファイル名生成ユーティリティ
/// Filename generation utilities
pub fn generate_filename(base_name: &str, format: PlotFormat, timestamp: bool) -> String {
    let mut filename = base_name.to_string();

    if timestamp {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        filename.push_str(&format!("_{}", now));
    }

    filename.push('.');
    filename.push_str(format.extension());

    filename
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_plot_format_extension() {
        assert_eq!(PlotFormat::Svg.extension(), "svg");
        assert_eq!(PlotFormat::Png.extension(), "png");
        assert_eq!(PlotFormat::Html.extension(), "html");
        assert_eq!(PlotFormat::Dot.extension(), "dot");
    }

    #[test]
    fn test_plot_format_mime_type() {
        assert_eq!(PlotFormat::Svg.mime_type(), "image/svg+xml");
        assert_eq!(PlotFormat::Html.mime_type(), "text/html");
    }

    #[test]
    fn test_color_palette_categorical() {
        let colors = ColorPalette::categorical();
        assert!(!colors.is_empty());
        assert!(colors[0].starts_with('#'));
        assert_eq!(colors.len(), 10);
    }

    #[test]
    fn test_get_categorical_color() {
        let color1 = ColorPalette::get_categorical_color(0);
        let color2 = ColorPalette::get_categorical_color(1);
        assert_ne!(color1, color2);

        // インデックスが範囲外の場合のテスト
        let color_overflow = ColorPalette::get_categorical_color(100);
        let colors = ColorPalette::categorical();
        assert_eq!(color_overflow, colors[100 % colors.len()]);
    }

    #[test]
    fn test_sequential_color() {
        let color_min = ColorPalette::get_sequential_color(0.0);
        let color_max = ColorPalette::get_sequential_color(1.0);
        let color_mid = ColorPalette::get_sequential_color(0.5);

        assert_ne!(color_min, color_max);
        assert_ne!(color_min, color_mid);
        assert_ne!(color_max, color_mid);
    }

    #[test]
    fn test_wrap_in_html() {
        let svg = r#"<svg><rect x="0" y="0" width="100" height="100"/></svg>"#;
        let html = wrap_in_html(svg, PlotFormat::Html).unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("RusTorch Visualization"));
        assert!(html.contains(svg));
    }

    #[test]
    fn test_create_dashboard() {
        let plots = vec![
            (
                "Training Loss",
                r#"<svg><rect x="0" y="0" width="100" height="100"/></svg>"#,
            ),
            ("Accuracy", r#"<svg><circle cx="50" cy="50" r="25"/></svg>"#),
        ];

        let dashboard = create_dashboard(plots).unwrap();

        assert!(dashboard.contains("Training Loss"));
        assert!(dashboard.contains("Accuracy"));
        assert!(dashboard.contains("dashboard"));
    }

    #[test]
    fn test_plot_statistics() {
        let svg_content = r#"<svg><rect x="0" y="0"/><circle cx="50" cy="50"/></svg>"#;
        let stats = PlotStatistics::new(svg_content, 100);

        assert_eq!(stats.total_elements, 2); // rect + circle
        assert_eq!(stats.file_size_bytes, svg_content.len());
        assert_eq!(stats.generation_time_ms, 100);
    }

    #[test]
    fn test_generate_filename() {
        let filename = generate_filename("test_plot", PlotFormat::Svg, false);
        assert_eq!(filename, "test_plot.svg");

        let filename_with_timestamp = generate_filename("test_plot", PlotFormat::Html, true);
        assert!(filename_with_timestamp.starts_with("test_plot_"));
        assert!(filename_with_timestamp.ends_with(".html"));
    }

    #[test]
    fn test_save_plot() -> std::io::Result<()> {
        let dir = tempdir()?;
        let file_path = dir.path().join("test.svg");

        let svg_content = r#"<svg><rect x="0" y="0" width="100" height="100"/></svg>"#;
        save_plot(svg_content, &file_path, PlotFormat::Svg).unwrap();

        let saved_content = fs::read_to_string(&file_path)?;
        assert_eq!(saved_content, svg_content);

        Ok(())
    }

    #[test]
    fn test_resize_svg() {
        let original_svg = r#"<svg width="400" height="300" xmlns="http://www.w3.org/2000/svg"><rect x="0" y="0" width="100" height="100"/></svg>"#;
        let resized_svg = resize_svg(original_svg, 800, 600).unwrap();

        assert!(resized_svg.contains("width=\"800\""));
        assert!(resized_svg.contains("height=\"600\""));
        assert!(resized_svg.contains("rect"));
    }
}