Skip to main content

ggen_core/domain/graph/
visualize.rs

1//! Domain logic for RDF graph visualization
2//!
3//! This module provides graph visualization capabilities including:
4//! - DOT format generation for Graphviz
5//! - SVG/PNG rendering (via external tools)
6//! - JSON export for web-based visualization
7//! - Interactive graph exploration
8
9use crate::utils::error::Result;
10use crate::Graph;
11use serde::{Deserialize, Serialize};
12use std::path::{Path, PathBuf};
13use std::str::FromStr;
14
15/// Visualization format options
16#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
17pub enum VisualizeFormat {
18    /// Graphviz DOT format
19    Dot,
20    /// SVG vector graphics
21    Svg,
22    /// PNG raster graphics
23    Png,
24    /// JSON for D3.js or other web viz
25    Json,
26}
27
28impl FromStr for VisualizeFormat {
29    type Err = crate::utils::error::Error;
30
31    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
32        match s.to_lowercase().as_str() {
33            "dot" => Ok(Self::Dot),
34            "svg" => Ok(Self::Svg),
35            "png" => Ok(Self::Png),
36            "json" => Ok(Self::Json),
37            _ => Err(crate::utils::error::Error::new(&format!(
38                "Unsupported format: {}. Use dot, svg, png, or json",
39                s
40            ))),
41        }
42    }
43}
44
45impl VisualizeFormat {
46    pub fn extension(&self) -> &str {
47        match self {
48            Self::Dot => "dot",
49            Self::Svg => "svg",
50            Self::Png => "png",
51            Self::Json => "json",
52        }
53    }
54}
55
56/// Visualization options
57#[derive(Debug, Clone, Default, Serialize, Deserialize)]
58pub struct VisualizeOptions {
59    pub format: Option<VisualizeFormat>,
60    pub output_path: Option<PathBuf>,
61    pub include_labels: bool,
62    pub max_depth: Option<usize>,
63    pub subject_filter: Option<String>,
64    pub layout_engine: LayoutEngine,
65}
66
67#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
68pub enum LayoutEngine {
69    #[default]
70    /// Hierarchical layout (top-to-bottom)
71    Dot,
72    /// Radial layout
73    Neato,
74    /// Force-directed layout
75    Fdp,
76    /// Circular layout
77    Circo,
78}
79
80impl VisualizeOptions {
81    pub fn new() -> Self {
82        Self::default()
83    }
84
85    pub fn with_format(mut self, format: VisualizeFormat) -> Self {
86        self.format = Some(format);
87        self
88    }
89
90    pub fn with_output(mut self, path: PathBuf) -> Self {
91        self.output_path = Some(path);
92        self
93    }
94
95    pub fn with_labels(mut self) -> Self {
96        self.include_labels = true;
97        self
98    }
99
100    pub fn with_max_depth(mut self, depth: usize) -> Self {
101        self.max_depth = Some(depth);
102        self
103    }
104
105    pub fn with_subject_filter(mut self, filter: impl Into<String>) -> Self {
106        self.subject_filter = Some(filter.into());
107        self
108    }
109
110    pub fn with_layout(mut self, engine: LayoutEngine) -> Self {
111        self.layout_engine = engine;
112        self
113    }
114}
115
116/// Visualization result statistics
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct VisualizeStats {
119    pub nodes_rendered: usize,
120    pub edges_rendered: usize,
121    pub output_path: Option<PathBuf>,
122    pub format: String,
123}
124
125/// CLI Arguments for visualize command
126#[derive(Debug, Clone, Default, serde::Deserialize)]
127pub struct VisualizeInput {
128    /// Input RDF file to visualize
129    pub input: PathBuf,
130
131    /// Output file path
132    pub output: Option<PathBuf>,
133
134    /// Visualization format (dot, svg, png, json)
135    pub format: String,
136
137    /// Include RDF labels in visualization
138    #[serde(default)]
139    pub labels: bool,
140
141    /// Maximum depth for graph traversal
142    pub max_depth: Option<usize>,
143
144    /// Filter to specific subject IRI
145    pub subject: Option<String>,
146}
147
148/// Visualize an RDF graph
149///
150/// Real implementation using ggen-core Graph APIs
151pub async fn visualize_graph(
152    graph_path: &Path, options: &VisualizeOptions,
153) -> Result<VisualizeStats> {
154    use std::fs;
155
156    // Load graph from file
157    let graph = if graph_path.exists() {
158        Graph::load_from_file(graph_path)
159            .map_err(|e| crate::utils::error::Error::new(&format!("Failed to load graph: {}", e)))?
160    } else {
161        return Err(crate::utils::error::Error::new(&format!(
162            "Graph file not found: {}",
163            graph_path.display()
164        )));
165    };
166
167    // Determine output format
168    let format = options.format.unwrap_or(VisualizeFormat::Dot);
169
170    // Extract nodes and edges from graph
171    let nodes = extract_nodes(&graph, options)?;
172    let edges = extract_edges(&graph, options)?;
173
174    // Determine output path
175    let output_path = if let Some(ref path) = options.output_path {
176        Some(path.clone())
177    } else {
178        let extension = format.extension();
179        Some(graph_path.with_extension(extension))
180    };
181
182    // Generate visualization based on format
183    let content = match format {
184        VisualizeFormat::Dot => generate_dot(&nodes, &edges, options.include_labels),
185        VisualizeFormat::Json => generate_json(&nodes, &edges)?,
186        VisualizeFormat::Svg | VisualizeFormat::Png => {
187            // For SVG/PNG, generate DOT first (would need external tool to convert)
188            generate_dot(&nodes, &edges, options.include_labels)
189        }
190    };
191
192    // Write output file
193    if let Some(ref path) = output_path {
194        fs::write(path, content).map_err(|e| {
195            crate::utils::error::Error::new(&format!("Failed to write visualization: {}", e))
196        })?;
197    }
198
199    let stats = VisualizeStats {
200        nodes_rendered: nodes.len(),
201        edges_rendered: edges.len(),
202        output_path: output_path.clone(),
203        format: format!("{:?}", format),
204    };
205
206    Ok(stats)
207}
208
209/// Extract nodes (subjects) from graph
210fn extract_nodes(graph: &Graph, options: &VisualizeOptions) -> Result<Vec<(String, String)>> {
211    let mut nodes = Vec::new();
212    let mut seen = std::collections::HashSet::new();
213
214    // Query all subjects
215    let query = if let Some(ref filter) = options.subject_filter {
216        format!(
217            "SELECT DISTINCT ?s WHERE {{ ?s ?p ?o FILTER(strstarts(str(?s), \"{}\")) }}",
218            filter
219        )
220    } else {
221        "SELECT DISTINCT ?s WHERE { ?s ?p ?o }".to_string()
222    };
223
224    let results = graph
225        .query(&query)
226        .map_err(|e| crate::utils::error::Error::new(&format!("Failed to query graph: {}", e)))?;
227
228    if let oxigraph::sparql::QueryResults::Solutions(solutions) = results {
229        for solution in solutions {
230            let solution = solution.map_err(|e| {
231                crate::utils::error::Error::new(&format!("Query solution error: {}", e))
232            })?;
233            if let Some(term) = solution.get("s") {
234                let node_id = term.to_string();
235                if !seen.contains(&node_id) {
236                    seen.insert(node_id.clone());
237                    let label = if options.include_labels {
238                        extract_label(graph, &node_id)?
239                    } else {
240                        node_id.clone()
241                    };
242                    nodes.push((node_id, label));
243                }
244            }
245        }
246    }
247
248    Ok(nodes)
249}
250
251/// Extract edges (triples) from graph
252fn extract_edges(
253    graph: &Graph, options: &VisualizeOptions,
254) -> Result<Vec<(String, String, String)>> {
255    let mut edges = Vec::new();
256
257    let query = if let Some(ref filter) = options.subject_filter {
258        format!(
259            "SELECT ?s ?p ?o WHERE {{ ?s ?p ?o FILTER(strstarts(str(?s), \"{}\")) }}",
260            filter
261        )
262    } else {
263        "SELECT ?s ?p ?o WHERE { ?s ?p ?o }".to_string()
264    };
265
266    let results = graph
267        .query(&query)
268        .map_err(|e| crate::utils::error::Error::new(&format!("Failed to query graph: {}", e)))?;
269
270    if let oxigraph::sparql::QueryResults::Solutions(solutions) = results {
271        for solution in solutions {
272            let solution = solution.map_err(|e| {
273                crate::utils::error::Error::new(&format!("Query solution error: {}", e))
274            })?;
275            if let (Some(s), Some(p), Some(o)) =
276                (solution.get("s"), solution.get("p"), solution.get("o"))
277            {
278                edges.push((s.to_string(), p.to_string(), o.to_string()));
279            }
280        }
281    }
282
283    Ok(edges)
284}
285
286/// Extract label for a node (try rdfs:label or use IRI)
287fn extract_label(graph: &Graph, node_id: &str) -> Result<String> {
288    let query = format!(
289        "SELECT ?label WHERE {{ <{}> <http://www.w3.org/2000/01/rdf-schema#label> ?label }}",
290        node_id
291    );
292
293    let results = graph
294        .query(&query)
295        .map_err(|e| crate::utils::error::Error::new(&format!("Failed to query label: {}", e)))?;
296
297    if let oxigraph::sparql::QueryResults::Solutions(solutions) = results {
298        for solution in solutions {
299            let solution = solution.map_err(|e| {
300                crate::utils::error::Error::new(&format!("Query solution error: {}", e))
301            })?;
302            if let Some(label) = solution.get("label") {
303                return Ok(label.to_string());
304            }
305        }
306    }
307
308    // Fallback to node ID (shortened if IRI)
309    Ok(node_id
310        .split('/')
311        .next_back()
312        .unwrap_or(node_id)
313        .to_string())
314}
315
316/// Generate DOT format representation
317pub fn generate_dot(
318    nodes: &[(String, String)], edges: &[(String, String, String)], include_labels: bool,
319) -> String {
320    let mut dot = String::from("digraph RDF {\n");
321    dot.push_str("  rankdir=TB;\n");
322    dot.push_str("  node [shape=box, style=rounded];\n\n");
323
324    // Add nodes
325    for (id, label) in nodes {
326        if include_labels {
327            dot.push_str(&format!("  \"{}\" [label=\"{}\"];\n", id, label));
328        } else {
329            dot.push_str(&format!("  \"{}\";\n", id));
330        }
331    }
332
333    dot.push('\n');
334
335    // Add edges
336    for (from, to, predicate) in edges {
337        if include_labels {
338            dot.push_str(&format!(
339                "  \"{}\" -> \"{}\" [label=\"{}\"];\n",
340                from, to, predicate
341            ));
342        } else {
343            dot.push_str(&format!("  \"{}\" -> \"{}\";\n", from, to));
344        }
345    }
346
347    dot.push_str("}\n");
348    dot
349}
350
351/// Generate JSON format for web visualization
352pub fn generate_json(
353    nodes: &[(String, String)], edges: &[(String, String, String)],
354) -> Result<String> {
355    let node_objects: Vec<_> = nodes
356        .iter()
357        .map(|(id, label)| serde_json::json!({ "id": id, "label": label }))
358        .collect();
359
360    let edge_objects: Vec<_> = edges
361        .iter()
362        .map(|(from, to, predicate)| {
363            serde_json::json!({
364                "source": from,
365                "target": to,
366                "label": predicate
367            })
368        })
369        .collect();
370
371    let graph = serde_json::json!({
372        "nodes": node_objects,
373        "edges": edge_objects
374    });
375
376    serde_json::to_string_pretty(&graph)
377        .map_err(|e| crate::utils::error::Error::new(&format!("JSON serialization failed: {}", e)))
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn test_visualize_format_from_str() {
386        assert!(matches!(
387            VisualizeFormat::from_str("dot").unwrap(),
388            VisualizeFormat::Dot
389        ));
390        assert!(matches!(
391            VisualizeFormat::from_str("svg").unwrap(),
392            VisualizeFormat::Svg
393        ));
394        assert!(matches!(
395            VisualizeFormat::from_str("png").unwrap(),
396            VisualizeFormat::Png
397        ));
398        assert!(matches!(
399            VisualizeFormat::from_str("json").unwrap(),
400            VisualizeFormat::Json
401        ));
402        assert!(VisualizeFormat::from_str("invalid").is_err());
403    }
404
405    #[test]
406    fn test_visualize_options_builder() {
407        let options = VisualizeOptions::new()
408            .with_format(VisualizeFormat::Svg)
409            .with_output(PathBuf::from("output.svg"))
410            .with_labels()
411            .with_max_depth(3)
412            .with_subject_filter("http://example.com/*");
413
414        assert!(matches!(options.format, Some(VisualizeFormat::Svg)));
415        assert!(options.include_labels);
416        assert_eq!(options.max_depth, Some(3));
417        assert!(options.subject_filter.is_some());
418    }
419
420    #[test]
421    fn test_generate_dot_basic() {
422        let nodes = vec![
423            ("n1".to_string(), "Node 1".to_string()),
424            ("n2".to_string(), "Node 2".to_string()),
425        ];
426        let edges = vec![("n1".to_string(), "n2".to_string(), "connects".to_string())];
427
428        let dot = generate_dot(&nodes, &edges, true);
429
430        assert!(dot.contains("digraph RDF"));
431        assert!(dot.contains("n1"));
432        assert!(dot.contains("n2"));
433        assert!(dot.contains("connects"));
434    }
435
436    #[test]
437    fn test_generate_dot_no_labels() {
438        let nodes = vec![("n1".to_string(), "Label".to_string())];
439        let edges = vec![];
440
441        let dot = generate_dot(&nodes, &edges, false);
442
443        assert!(dot.contains("\"n1\""));
444        assert!(!dot.contains("Label"));
445    }
446
447    #[test]
448    fn test_generate_json() {
449        let nodes = vec![
450            ("n1".to_string(), "Node 1".to_string()),
451            ("n2".to_string(), "Node 2".to_string()),
452        ];
453        let edges = vec![("n1".to_string(), "n2".to_string(), "rel".to_string())];
454
455        let json = generate_json(&nodes, &edges).unwrap();
456
457        assert!(json.contains("\"nodes\""));
458        assert!(json.contains("\"edges\""));
459        assert!(json.contains("\"n1\""));
460        assert!(json.contains("\"rel\""));
461    }
462
463    #[test]
464    fn test_format_extensions() {
465        assert_eq!(VisualizeFormat::Dot.extension(), "dot");
466        assert_eq!(VisualizeFormat::Svg.extension(), "svg");
467        assert_eq!(VisualizeFormat::Png.extension(), "png");
468        assert_eq!(VisualizeFormat::Json.extension(), "json");
469    }
470}
471
472/// Visualize output for CLI
473#[derive(Debug, Clone, serde::Serialize)]
474pub struct VisualizeOutput {
475    pub nodes_rendered: usize,
476    pub edges_rendered: usize,
477    pub output_path: String,
478    pub format: String,
479}
480
481/// Execute visualize operation - domain logic entry point
482///
483/// This is the main entry point for the visualize command from CLI
484pub async fn execute_visualize(input: VisualizeInput) -> Result<VisualizeOutput> {
485    // Parse format
486    let format = VisualizeFormat::from_str(&input.format)?;
487
488    // Create visualize options
489    let mut options = VisualizeOptions::new().with_format(format).with_output(
490        input.output.clone().unwrap_or_else(|| {
491            let mut path = input.input.clone();
492            path.set_extension(format.extension());
493            path
494        }),
495    );
496
497    // Apply labels if requested
498    if input.labels {
499        options = options.with_labels();
500    }
501
502    // Apply optional settings
503    let options = if let Some(depth) = input.max_depth {
504        options.with_max_depth(depth)
505    } else {
506        options
507    };
508
509    let options = if let Some(ref subject) = input.subject {
510        options.with_subject_filter(subject.clone())
511    } else {
512        options
513    };
514
515    // Perform the actual visualization
516    let stats = visualize_graph(&input.input, &options).await?;
517
518    Ok(VisualizeOutput {
519        nodes_rendered: stats.nodes_rendered,
520        edges_rendered: stats.edges_rendered,
521        output_path: stats
522            .output_path
523            .as_ref()
524            .map(|p| p.to_string_lossy().to_string())
525            .unwrap_or_default(),
526        format: stats.format,
527    })
528}
529
530/// CLI run function - bridges sync CLI to async domain logic
531pub async fn run(args: &VisualizeInput) -> Result<()> {
532    let output = execute_visualize(args.clone()).await?;
533
534    crate::alert_success!(
535        "Visualized {} nodes and {} edges to {}",
536        output.nodes_rendered,
537        output.edges_rendered,
538        output.output_path
539    );
540    crate::alert_info!("   Format: {}", output.format);
541
542    Ok(())
543}