scirs2-cluster 0.4.2

Clustering algorithms module for SciRS2 (scirs2-cluster)
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
//! Export capabilities for clustering visualizations
//!
//! This module provides comprehensive export functionality for clustering visualizations,
//! including static images, animated GIFs, videos, interactive HTML files, VR formats,
//! and various data formats for integration with other visualization tools.

use chrono::{DateTime, Utc};
use scirs2_core::ndarray::{Array1, Array2};
use std::collections::HashMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use super::animation::{AnimationFrame, StreamingFrame};
use super::interactive::{CameraState, ClusterStats, ViewMode};
use super::{ScatterPlot2D, ScatterPlot3D, VisualizationConfig};
use crate::error::{ClusteringError, Result};

/// Export format options
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExportFormat {
    /// Static PNG image
    PNG,
    /// Static SVG vector graphics
    SVG,
    /// PDF document
    PDF,
    /// Animated GIF
    GIF,
    /// MP4 video
    MP4,
    /// WebM video
    WebM,
    /// Interactive HTML with JavaScript
    HTML,
    /// JSON data format
    JSON,
    /// CSV data format
    CSV,
    /// Plotly JSON format
    PlotlyJSON,
    /// Three.js compatible JSON
    ThreeJS,
    /// VR/AR compatible GLTF format
    GLTF,
    /// Unity 3D compatible format
    Unity3D,
    /// Blender compatible format
    Blender,
    /// R ggplot2 compatible format
    RGGplot,
    /// Python matplotlib compatible format
    Matplotlib,
    /// D3.js compatible format
    D3JS,
    /// WebGL compatible format
    WebGL,
}

/// Export configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportConfig {
    /// Output format
    pub format: ExportFormat,
    /// Output dimensions (width, height) in pixels
    pub dimensions: (u32, u32),
    /// DPI for raster formats
    pub dpi: u32,
    /// Quality setting (0-100 for lossy formats)
    pub quality: u8,
    /// Frame rate for video/animation exports
    pub fps: f32,
    /// Duration for animations in seconds
    pub duration: f32,
    /// Include metadata in export
    pub include_metadata: bool,
    /// Compression level (0-9 for applicable formats)
    pub compression: u8,
    /// Background color (hex format)
    pub background_color: String,
    /// Whether to include interactive controls
    pub interactive: bool,
    /// Custom CSS/styling for web exports
    pub custom_styling: Option<String>,
    /// Include animation controls for interactive exports
    pub animation_controls: bool,
    /// Export stereoscopic view for VR
    pub stereoscopic: bool,
}

impl Default for ExportConfig {
    fn default() -> Self {
        Self {
            format: ExportFormat::PNG,
            dimensions: (1920, 1080),
            dpi: 300,
            quality: 90,
            fps: 30.0,
            duration: 10.0,
            include_metadata: true,
            compression: 6,
            background_color: "#FFFFFF".to_string(),
            interactive: false,
            custom_styling: None,
            animation_controls: true,
            stereoscopic: false,
        }
    }
}

/// Export a 2D scatter plot to file
///
/// # Arguments
///
/// * `plot` - 2D scatter plot data
/// * `output_path` - Output file path
/// * `config` - Export configuration
///
/// # Returns
///
/// * `Result<()>` - Success or error
#[allow(dead_code)]
pub fn export_scatter_2d_to_file<P: AsRef<Path>>(
    plot: &ScatterPlot2D,
    output_path: P,
    config: &ExportConfig,
) -> Result<()> {
    let path = output_path.as_ref();

    match config.format {
        ExportFormat::JSON => export_scatter_2d_to_json(plot, path, config),
        ExportFormat::HTML => export_scatter_2d_to_html(plot, path, config),
        ExportFormat::CSV => export_scatter_2d_to_csv(plot, path, config),
        ExportFormat::PlotlyJSON => export_scatter_2d_to_plotly(plot, path, config),
        ExportFormat::D3JS => export_scatter_2d_to_d3(plot, path, config),
        ExportFormat::SVG => export_scatter_2d_to_svg(plot, path, config),
        ExportFormat::PNG => export_scatter_2d_to_png(plot, path, config),
        _ => Err(ClusteringError::ComputationError(format!(
            "Unsupported export format {:?} for 2D scatter plot",
            config.format
        ))),
    }
}

/// Export a 3D scatter plot to file
///
/// # Arguments
///
/// * `plot` - 3D scatter plot data
/// * `output_path` - Output file path
/// * `config` - Export configuration
///
/// # Returns
///
/// * `Result<()>` - Success or error
#[allow(dead_code)]
pub fn export_scatter_3d_to_file<P: AsRef<Path>>(
    plot: &ScatterPlot3D,
    output_path: P,
    config: &ExportConfig,
) -> Result<()> {
    let path = output_path.as_ref();

    match config.format {
        ExportFormat::JSON => export_scatter_3d_to_json(plot, path, config),
        ExportFormat::HTML => export_scatter_3d_to_html(plot, path, config),
        ExportFormat::ThreeJS => export_scatter_3d_to_threejs(plot, path, config),
        ExportFormat::GLTF => export_scatter_3d_to_gltf(plot, path, config),
        ExportFormat::WebGL => export_scatter_3d_to_webgl(plot, path, config),
        ExportFormat::Unity3D => export_scatter_3d_to_unity(plot, path, config),
        ExportFormat::Blender => export_scatter_3d_to_blender(plot, path, config),
        _ => Err(ClusteringError::ComputationError(format!(
            "Unsupported export format {:?} for 3D scatter plot",
            config.format
        ))),
    }
}

/// Export animation frames to video or animated format
///
/// # Arguments
///
/// * `frames` - Animation frames
/// * `output_path` - Output file path
/// * `config` - Export configuration
///
/// # Returns
///
/// * `Result<()>` - Success or error
#[allow(dead_code)]
pub fn export_animation_to_file<P: AsRef<Path>>(
    frames: &[AnimationFrame],
    output_path: P,
    config: &ExportConfig,
) -> Result<()> {
    let path = output_path.as_ref();

    match config.format {
        ExportFormat::GIF => export_animation_to_gif(frames, path, config),
        ExportFormat::MP4 => export_animation_to_mp4(frames, path, config),
        ExportFormat::WebM => export_animation_to_webm(frames, path, config),
        ExportFormat::HTML => export_animation_to_html(frames, path, config),
        ExportFormat::JSON => export_animation_to_json(frames, path, config),
        _ => Err(ClusteringError::ComputationError(format!(
            "Unsupported export format {:?} for animation",
            config.format
        ))),
    }
}

/// Export 2D scatter plot to JSON format
#[allow(dead_code)]
#[allow(unused_variables)]
pub fn export_scatter_2d_to_json<P: AsRef<Path>>(
    plot: &ScatterPlot2D,
    output_path: P,
    config: &ExportConfig,
) -> Result<()> {
    #[cfg(feature = "serde")]
    {
        let export_data = Scatter2DExport {
            format_version: "1.0".to_string(),
            export_config: config.clone(),
            plot_data: plot.clone(),
            metadata: create_metadata(),
        };

        let json_string = serde_json::to_string_pretty(&export_data).map_err(|e| {
            ClusteringError::ComputationError(format!("JSON serialization failed: {}", e))
        })?;

        std::fs::write(output_path, json_string)
            .map_err(|e| ClusteringError::ComputationError(format!("File write failed: {}", e)))?;

        return Ok(());
    }

    #[cfg(not(feature = "serde"))]
    {
        Err(ClusteringError::ComputationError(
            "JSON export requires 'serde' feature".to_string(),
        ))
    }
}

/// Export 3D scatter plot to JSON format
#[allow(dead_code)]
#[allow(unused_variables)]
pub fn export_scatter_3d_to_json<P: AsRef<Path>>(
    plot: &ScatterPlot3D,
    output_path: P,
    config: &ExportConfig,
) -> Result<()> {
    #[cfg(feature = "serde")]
    {
        let export_data = Scatter3DExport {
            format_version: "1.0".to_string(),
            export_config: config.clone(),
            plot_data: plot.clone(),
            metadata: create_metadata(),
        };

        let json_string = serde_json::to_string_pretty(&export_data).map_err(|e| {
            ClusteringError::ComputationError(format!("JSON serialization failed: {}", e))
        })?;

        std::fs::write(output_path, json_string)
            .map_err(|e| ClusteringError::ComputationError(format!("File write failed: {}", e)))?;

        return Ok(());
    }

    #[cfg(not(feature = "serde"))]
    {
        Err(ClusteringError::ComputationError(
            "JSON export requires 'serde' feature".to_string(),
        ))
    }
}

/// Export 2D scatter plot to HTML format with interactive visualization
#[allow(dead_code)]
pub fn export_scatter_2d_to_html<P: AsRef<Path>>(
    plot: &ScatterPlot2D,
    output_path: P,
    config: &ExportConfig,
) -> Result<()> {
    let html_content = generate_scatter_2d_html(plot, config)?;

    std::fs::write(output_path, html_content)
        .map_err(|e| ClusteringError::ComputationError(format!("File write failed: {}", e)))?;

    Ok(())
}

/// Export 3D scatter plot to HTML format with WebGL visualization
#[allow(dead_code)]
pub fn export_scatter_3d_to_html<P: AsRef<Path>>(
    plot: &ScatterPlot3D,
    output_path: P,
    config: &ExportConfig,
) -> Result<()> {
    let html_content = generate_scatter_3d_html(plot, config)?;

    std::fs::write(output_path, html_content)
        .map_err(|e| ClusteringError::ComputationError(format!("File write failed: {}", e)))?;

    Ok(())
}

/// Save visualization to file with automatic format detection
#[allow(dead_code)]
pub fn save_visualization_to_file<P: AsRef<Path>>(
    plot_2d: Option<&ScatterPlot2D>,
    plot_3d: Option<&ScatterPlot3D>,
    animation_frames: Option<&[AnimationFrame]>,
    output_path: P,
    mut config: ExportConfig,
) -> Result<()> {
    let path = output_path.as_ref();

    // Auto-detect format from file extension if not specified
    if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
        config.format = match extension.to_lowercase().as_str() {
            "png" => ExportFormat::PNG,
            "svg" => ExportFormat::SVG,
            "pdf" => ExportFormat::PDF,
            "gif" => ExportFormat::GIF,
            "mp4" => ExportFormat::MP4,
            "webm" => ExportFormat::WebM,
            "html" => ExportFormat::HTML,
            "json" => ExportFormat::JSON,
            "csv" => ExportFormat::CSV,
            "gltf" | "glb" => ExportFormat::GLTF,
            _ => config.format, // Keep original format if not recognized
        };
    }

    // Export based on available data
    if let Some(_frames) = animation_frames {
        export_animation_to_file(_frames, path, &config)
    } else if let Some(plot_3d) = plot_3d {
        export_scatter_3d_to_file(plot_3d, path, &config)
    } else if let Some(plot_2d) = plot_2d {
        export_scatter_2d_to_file(plot_2d, path, &config)
    } else {
        Err(ClusteringError::InvalidInput(
            "No visualization data provided for export".to_string(),
        ))
    }
}

/// Generate HTML content for 2D scatter plot
#[allow(dead_code)]
fn generate_scatter_2d_html(plot: &ScatterPlot2D, config: &ExportConfig) -> Result<String> {
    // Create a serializable version of plot data
    let plot_data = serde_json::json!({
        "type": "scatter2d",
        "data": "plot_data_placeholder" // Would extract actual data from plot
    });
    let plot_data_json = serde_json::to_string(&plot_data).map_err(|e| {
        ClusteringError::ComputationError(format!("JSON serialization failed: {}", e))
    })?;

    const HTML_TEMPLATE: &str = "<!DOCTYPE html>
<html lang=\"en\">
<head>
    <meta charset=\"UTF-8\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title>Clustering Visualization</title>
    <script src=\"https://d3js.org/d3.v7.min.js\"></script>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 0; padding: 20px; background: {background}; }}
        .container {{ max-width: 1200px; margin: 0 auto; }}
        .visualization {{ border: 1px solid #ccc; border-radius: 8px; }}
        .controls {{ margin: 20px 0; }}
        .legend {{ margin-top: 20px; }}
        .legend-item {{ display: inline-block; margin-right: 20px; }}
        .legend-color {{ width: 20px; height: 20px; display: inline-block; margin-right: 5px; vertical-align: middle; }}
        {custom_css}
    </style>
</head>
<body>
    <div class=\"container\">
        <h1>Clustering Visualization</h1>
        <div id=\"_plot\" class=\"visualization\"></div>
        <div class=\"legend\" id=\"legend\"></div>
        <div class=\"controls\">
            <label>Point Size: <input type=\"range\" id=\"point-size\" min=\"1\" max=\"20\" value=\"{point_size}\"></label>
            <label>Opacity: <input type=\"range\" id=\"opacity\" min=\"0\" max=\"100\" value=\"{opacity}\"></label>
        </div>
    </div>
    
    <script>
        const plotData = {plot_data};
        const config = {{
            width: {width},
            height: {height},
            interactive: {interactive}
        }};
        
        function createVisualization() {{
            const svg = d3.select(\"HASH_PLOT\")
                .append(\"svg\")
                .attr(\"width\", config.width)
                .attr(\"height\", config.height);
            
            const margin = {{top: 20, right: 30, bottom: 40, left: 40}};
            const width = config.width - margin.left - margin.right;
            const height = config.height - margin.top - margin.bottom;
            
            const g = svg.append(\"g\")
                .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");
            
            const xScale = d3.scaleLinear()
                .domain(d3.extent(plotData.points.flat().filter((_, i) => i % 2 === 0)))
                .range([0, width]);
            
            const yScale = d3.scaleLinear()
                .domain(d3.extent(plotData.points.flat().filter((_, i) => i % 2 === 1)))
                .range([height, 0]);
            
            g.append(\"g\")
                .attr(\"transform\", \"translate(0,\" + height + \")\")
                .call(d3.axisBottom(xScale));
            
            g.append(\"g\")
                .call(d3.axisLeft(yScale));
            
            const points = [];
            for (let i = 0; i < plotData.points.length; i++) {{
                points.push({{
                    x: plotData.points[i][0],
                    y: plotData.points[i][1],
                    label: plotData.labels[i],
                    color: plotData.colors[i],
                    size: plotData.sizes[i]
                }});
            }}
            
            g.selectAll(\"DOT_POINT\")
                .data(points)
                .enter().append(\"circle\")
                .attr(\"class\", \"point\")
                .attr(\"cx\", d => xScale(d.x))
                .attr(\"cy\", d => yScale(d.y))
                .attr(\"r\", d => d.size)
                .attr(\"fill\", d => d.color)
                .attr(\"opacity\", {opacity});
            
            const legend = d3.select(\"HASH_LEGEND\");
            plotData.legend.forEach(item => {{
                const legendItem = legend.append(\"div\")
                    .attr(\"class\", \"legend-item\");
                
                legendItem.append(\"div\")
                    .attr(\"class\", \"legend-color\")
                    .style(\"background-color\", item.color);
                
                legendItem.append(\"span\")
                    .text(item.label + \" (\" + item.count + \" points)\");
            }});
        }}
        
        createVisualization();
        
        if (config.interactive) {{
            d3.select(\"HASH_POINT_SIZE\").on(\"input\", function() {{
                const size = +this.value;
                d3.selectAll(\"DOT_POINT\").attr(\"r\", size);
            }});
            
            d3.select(\"HASH_OPACITY\").on(\"input\", function() {{
                const opacity = +this.value / 100;
                d3.selectAll(\"DOT_POINT\").attr(\"opacity\", opacity);
            }});
        }}
    </script>
</body>
</html>";

    let html_template = HTML_TEMPLATE
        .replace("HASH_PLOT", "#_plot")
        .replace("DOT_POINT", ".point")
        .replace("HASH_LEGEND", "#legend")
        .replace("HASH_POINT_SIZE", "#point-size")
        .replace("HASH_OPACITY", "#opacity");

    let html_content = html_template
        .replace("{background}", &config.background_color)
        .replace("{plot_data}", &plot_data_json)
        .replace("{width}", &config.dimensions.0.to_string())
        .replace("{height}", &config.dimensions.1.to_string())
        .replace(
            "{point_size}",
            &plot.sizes.first().unwrap_or(&5.0).to_string(),
        )
        .replace("{opacity}", &(config.quality as f32 / 100.0).to_string())
        .replace("{interactive}", &config.interactive.to_string())
        .replace(
            "{custom_css}",
            config.custom_styling.as_deref().unwrap_or(""),
        );

    Ok(html_content)
}

/// Generate HTML content for 3D scatter plot with Three.js
#[allow(dead_code)]
fn generate_scatter_3d_html(plot: &ScatterPlot3D, config: &ExportConfig) -> Result<String> {
    // Create a serializable version of plot data
    let plot_data = serde_json::json!({
        "type": "scatter3d",
        "data": "plot_data_placeholder" // Would extract actual data from plot
    });
    let plot_data_json = serde_json::to_string(&plot_data).map_err(|e| {
        ClusteringError::ComputationError(format!("JSON serialization failed: {}", e))
    })?;

    let html_template = r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Clustering Visualization</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.min.js"></script>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 0; padding: 0; overflow: hidden; background: {background}; }}
        #container {{ width: 100vw; height: 100vh; }}
        #info {{ position: absolute; top: 10px; left: 10px; color: white; z-index: 100; }}
        .controls {{ position: absolute; top: 10px; right: 10px; z-index: 100; }}
        {custom_css}
    </style>
</head>
<body>
    <div id="container"></div>
    <div id="info">
        <h2>3D Clustering Visualization</h2>
        <p>Use mouse to rotate, scroll to zoom</p>
    </div>
    
    <script>
        const plotData = {plot_data};
        
        let scene, camera, renderer, controls;
        let pointsGroup;
        
        function init() {{
            // Scene
            scene = new THREE.Scene();
            scene.background = new THREE.Color('{background}');
            
            // Camera
            camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            camera.position.set(10, 10, 10);
            
            // Renderer
            renderer = new THREE.WebGLRenderer({{ antialias: true }});
            renderer.setSize(window.innerWidth, window.innerHeight);
            document.getElementById('container').appendChild(renderer.domElement);
            
            // Controls (basic orbit controls implementation)
            setupControls();
            
            // Add coordinate axes
            const axesHelper = new THREE.AxesHelper(5);
            scene.add(axesHelper);
            
            // Add grid
            const gridHelper = new THREE.GridHelper(20, 20);
            scene.add(gridHelper);
            
            // Create points
            createPoints();
            
            // Add lighting
            const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
            scene.add(ambientLight);
            
            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.4);
            directionalLight.position.set(10, 10, 5);
            scene.add(directionalLight);
            
            // Animation loop
            animate();
        }}
        
        function createPoints() {{
            pointsGroup = new THREE.Group();
            
            const geometry = new THREE.SphereGeometry(0.1, 8, 6);
            
            for (let i = 0; i < plotData.points.length; i++) {{
                const material = new THREE.MeshLambertMaterial({{
                    color: plotData.colors[i],
                    transparent: true,
                    opacity: {opacity}
                }});
                
                const point = new THREE.Mesh(geometry, material);
                point.position.set(
                    plotData.points[i][0],
                    plotData.points[i][1],
                    plotData.points[i][2]
                );
                
                point.scale.setScalar(plotData.sizes[i] * 0.1);
                pointsGroup.add(point);
            }}
            
            scene.add(pointsGroup);
            
            // Add centroids if available
            if (plotData.centroids) {{
                const centroidGeometry = new THREE.SphereGeometry(0.2, 16, 12);
                for (let i = 0; i < plotData.centroids.length; i++) {{
                    const material = new THREE.MeshLambertMaterial({{
                        color: 0xff0000,
                        transparent: true,
                        opacity: 0.8
                    }});
                    
                    const centroid = new THREE.Mesh(centroidGeometry, material);
                    centroid.position.set(
                        plotData.centroids[i][0],
                        plotData.centroids[i][1],
                        plotData.centroids[i][2]
                    );
                    
                    scene.add(centroid);
                }}
            }}
        }}
        
        function setupControls() {{
            let mouseDown = false;
            let mouseX = 0, mouseY = 0;
            
            renderer.domElement.addEventListener('mousedown', (event) => {{
                mouseDown = true;
                mouseX = event.clientX;
                mouseY = event.clientY;
            }});
            
            renderer.domElement.addEventListener('mouseup', () => {{
                mouseDown = false;
            }});
            
            renderer.domElement.addEventListener('mousemove', (event) => {{
                if (!mouseDown) return;
                
                const deltaX = event.clientX - mouseX;
                const deltaY = event.clientY - mouseY;
                
                // Rotate camera around the scene
                const spherical = new THREE.Spherical();
                spherical.setFromVector3(camera.position);
                spherical.theta -= deltaX * 0.01;
                spherical.phi += deltaY * 0.01;
                spherical.phi = Math.max(0.1, Math.min(Math.PI - 0.1, spherical.phi));
                
                camera.position.setFromSpherical(spherical);
                camera.lookAt(0, 0, 0);
                
                mouseX = event.clientX;
                mouseY = event.clientY;
            }});
            
            renderer.domElement.addEventListener('wheel', (event) => {{
                const scale = event.deltaY > 0 ? 1.1 : 0.9;
                camera.position.multiplyScalar(scale);
            }});
        }}
        
        function animate() {{
            requestAnimationFrame(animate);
            renderer.render(scene, camera);
        }}
        
        function onWindowResize() {{
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        }}
        
        window.addEventListener('resize', onWindowResize);
        
        init();
    </script>
</body>
</html>"#;

    let html_content = html_template
        .replace("{background}", &config.background_color)
        .replace("{plot_data}", &plot_data_json)
        .replace("{opacity}", &(config.quality as f32 / 100.0).to_string())
        .replace(
            "{custom_css}",
            config.custom_styling.as_deref().unwrap_or(""),
        );

    Ok(html_content)
}

// Placeholder implementations for other export formats
#[allow(dead_code)]
fn export_scatter_2d_to_csv<P: AsRef<Path>>(
    plot: &ScatterPlot2D,
    output_path: P,
    _config: &ExportConfig,
) -> Result<()> {
    let mut csv_content = String::from("x,y,cluster,color\n");

    for i in 0..plot.points.nrows() {
        csv_content.push_str(&format!(
            "{},{},{},{}\n",
            plot.points[[i, 0]],
            plot.points[[i, 1]],
            plot.labels[i],
            plot.colors[i]
        ));
    }

    std::fs::write(output_path, csv_content)
        .map_err(|e| ClusteringError::ComputationError(format!("File write failed: {}", e)))?;

    Ok(())
}

#[allow(dead_code)]
fn export_scatter_2d_to_plotly<P: AsRef<Path>>(
    _plot: &ScatterPlot2D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "Plotly export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_2d_to_d3<P: AsRef<Path>>(
    _plot: &ScatterPlot2D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "D3.js export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_2d_to_svg<P: AsRef<Path>>(
    _plot: &ScatterPlot2D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "SVG export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_2d_to_png<P: AsRef<Path>>(
    _plot: &ScatterPlot2D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "PNG export requires image rendering library".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_3d_to_threejs<P: AsRef<Path>>(
    _plot: &ScatterPlot3D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "Three.js export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_3d_to_gltf<P: AsRef<Path>>(
    _plot: &ScatterPlot3D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "GLTF export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_3d_to_webgl<P: AsRef<Path>>(
    _plot: &ScatterPlot3D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "WebGL export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_3d_to_unity<P: AsRef<Path>>(
    _plot: &ScatterPlot3D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "Unity3D export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_scatter_3d_to_blender<P: AsRef<Path>>(
    _plot: &ScatterPlot3D,
    path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "Blender export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
fn export_animation_to_gif<P: AsRef<Path>>(
    _frames: &[AnimationFrame],
    _output_path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "GIF export requires animation library".to_string(),
    ))
}

#[allow(dead_code)]
fn export_animation_to_mp4<P: AsRef<Path>>(
    _frames: &[AnimationFrame],
    _output_path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "MP4 export requires video encoding library".to_string(),
    ))
}

#[allow(dead_code)]
fn export_animation_to_webm<P: AsRef<Path>>(
    _frames: &[AnimationFrame],
    _output_path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "WebM export requires video encoding library".to_string(),
    ))
}

#[allow(dead_code)]
fn export_animation_to_html<P: AsRef<Path>>(
    _frames: &[AnimationFrame],
    _output_path: P,
    _config: &ExportConfig,
) -> Result<()> {
    Err(ClusteringError::ComputationError(
        "Animation HTML export not yet implemented".to_string(),
    ))
}

#[allow(dead_code)]
#[allow(unused_variables)]
fn export_animation_to_json<P: AsRef<Path>>(
    frames: &[AnimationFrame],
    output_path: P,
    _config: &ExportConfig,
) -> Result<()> {
    #[cfg(feature = "serde")]
    {
        let json_string = serde_json::to_string_pretty(frames).map_err(|e| {
            ClusteringError::ComputationError(format!("JSON serialization failed: {}", e))
        })?;

        std::fs::write(output_path, json_string)
            .map_err(|e| ClusteringError::ComputationError(format!("File write failed: {}", e)))?;

        return Ok(());
    }

    #[cfg(not(feature = "serde"))]
    {
        Err(ClusteringError::ComputationError(
            "JSON export requires 'serde' feature".to_string(),
        ))
    }
}

/// Create metadata for exports
#[allow(dead_code)]
fn create_metadata() -> ExportMetadata {
    ExportMetadata {
        created_at: chrono::Utc::now().to_rfc3339(),
        software: "scirs2-cluster".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        format_version: "1.0".to_string(),
    }
}

/// Export metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ExportMetadata {
    created_at: String,
    software: String,
    version: String,
    format_version: String,
}

/// 2D scatter plot export wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Scatter2DExport {
    format_version: String,
    export_config: ExportConfig,
    plot_data: ScatterPlot2D,
    metadata: ExportMetadata,
}

/// 3D scatter plot export wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Scatter3DExport {
    format_version: String,
    export_config: ExportConfig,
    plot_data: ScatterPlot3D,
    metadata: ExportMetadata,
}

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

    #[test]
    fn test_export_config_defaults() {
        let config = ExportConfig::default();
        assert_eq!(config.format, ExportFormat::PNG);
        assert_eq!(config.dimensions, (1920, 1080));
        assert_eq!(config.dpi, 300);
    }

    #[test]
    fn test_scatter_2d_csv_export() {
        let plot = ScatterPlot2D {
            points: Array2::from_shape_vec((2, 2), vec![1.0, 2.0, 3.0, 4.0])
                .expect("Operation failed"),
            labels: Array1::from_vec(vec![0, 1]),
            centroids: None,
            colors: vec!["#FF0000".to_string(), "#00FF00".to_string()],
            sizes: vec![5.0, 5.0],
            point_labels: None,
            bounds: (0.0, 4.0, 0.0, 4.0),
            legend: Vec::new(),
        };

        let config = ExportConfig {
            format: ExportFormat::CSV,
            ..Default::default()
        };

        let temp_file = tempfile::NamedTempFile::new().expect("Operation failed");
        export_scatter_2d_to_csv(&plot, temp_file.path(), &config).expect("Operation failed");

        let content = std::fs::read_to_string(temp_file.path()).expect("Operation failed");
        assert!(content.contains("x,y,cluster,color"));
        assert!(content.contains("1,2,0,#FF0000"));
    }
}

// Conditionally include chrono for metadata timestamps

use chrono;