oxirs-samm 0.2.4

Semantic Aspect Meta Model (SAMM) implementation for OxiRS
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
//! Graph Visualization for SAMM Models
//!
//! This module provides visualization capabilities for SAMM model dependency graphs.
//! It supports generating DOT format files that can be rendered using Graphviz, and
//! optionally can render directly to SVG/PNG if the `graphviz` feature is enabled.
//!
//! # Features
//!
//! - **DOT Format Generation**: Create Graphviz DOT files for model graphs
//! - **Customizable Styles**: Choose between compact, detailed, or hierarchical layouts
//! - **Color Coding**: Different colors for aspects, properties, and characteristics
//! - **Optional Rendering**: Generate SVG/PNG images with the `graphviz` feature
//!
//! # Examples
//!
//! ```rust
//! use oxirs_samm::graph_analytics::{ModelGraph, VisualizationStyle};
//! use oxirs_samm::metamodel::Aspect;
//!
//! # fn example(aspect: &Aspect) -> Result<(), Box<dyn std::error::Error>> {
//! // Build graph
//! let graph = ModelGraph::from_aspect(aspect)?;
//!
//! // Generate DOT format
//! let dot = graph.to_dot(VisualizationStyle::Detailed)?;
//! std::fs::write("model.dot", dot)?;
//!
//! // Render to SVG (requires 'graphviz' feature)
//! #[cfg(feature = "graphviz")]
//! graph.render_svg("model.svg", VisualizationStyle::Hierarchical)?;
//! # Ok(())
//! # }
//! ```

use crate::error::{Result, SammError};
use crate::graph_analytics::ModelGraph;
use std::fmt::Write as FmtWrite;

/// Visualization style for graph rendering
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VisualizationStyle {
    /// Compact layout - minimal labels, optimized for overview
    Compact,
    /// Detailed layout - full URNs and metadata
    #[default]
    Detailed,
    /// Hierarchical layout - top-down tree structure
    Hierarchical,
}

/// Color scheme for graph elements
#[derive(Debug, Clone)]
pub struct ColorScheme {
    /// Color for aspect nodes
    pub aspect_color: String,
    /// Color for property nodes
    pub property_color: String,
    /// Color for characteristic nodes
    pub characteristic_color: String,
    /// Color for edges
    pub edge_color: String,
}

impl Default for ColorScheme {
    fn default() -> Self {
        Self {
            aspect_color: "#E8F4F8".to_string(),         // Light blue
            property_color: "#FFF4E6".to_string(),       // Light orange
            characteristic_color: "#F0F0F0".to_string(), // Light gray
            edge_color: "#666666".to_string(),           // Dark gray
        }
    }
}

impl ModelGraph {
    /// Generate DOT format representation of the graph
    ///
    /// Creates a Graphviz DOT file that can be rendered using `dot` command or
    /// online tools like GraphvizOnline.
    ///
    /// # Arguments
    ///
    /// * `style` - Visualization style to use
    ///
    /// # Returns
    ///
    /// DOT format string
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxirs_samm::graph_analytics::{ModelGraph, VisualizationStyle};
    ///
    /// # fn example(graph: &ModelGraph) -> Result<(), Box<dyn std::error::Error>> {
    /// let dot = graph.to_dot(VisualizationStyle::Detailed)?;
    /// std::fs::write("model.dot", dot)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_dot(&self, style: VisualizationStyle) -> Result<String> {
        self.to_dot_with_colors(style, ColorScheme::default())
    }

    /// Generate DOT format with custom color scheme
    ///
    /// # Arguments
    ///
    /// * `style` - Visualization style to use
    /// * `colors` - Custom color scheme
    ///
    /// # Returns
    ///
    /// DOT format string
    pub fn to_dot_with_colors(
        &self,
        style: VisualizationStyle,
        colors: ColorScheme,
    ) -> Result<String> {
        let mut dot = String::new();

        // DOT file header
        writeln!(dot, "digraph SAMM_Model {{")
            .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;
        writeln!(dot, "  // Generated by OxiRS SAMM")
            .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;
        writeln!(
            dot,
            "  rankdir={}; // Layout direction",
            if style == VisualizationStyle::Hierarchical {
                "TB"
            } else {
                "LR"
            }
        )
        .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;
        writeln!(dot, "  node [shape=box, style=filled, fontname=\"Arial\"];")
            .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;
        writeln!(dot, "  edge [color=\"{}\"];", colors.edge_color)
            .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;
        writeln!(dot).map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;

        // Add nodes with colors based on type
        for name in self.nodes() {
            let (color, shape, label) = self.get_node_attributes(name, style, &colors);
            writeln!(
                dot,
                "  \"{}\" [fillcolor=\"{}\", shape={}, label=\"{}\"];",
                name, color, shape, label
            )
            .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;
        }

        writeln!(dot).map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;

        // Add edges
        for (src, tgt) in self.edges() {
            writeln!(dot, "  \"{}\" -> \"{}\";", src, tgt)
                .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;
        }

        writeln!(dot, "}}")
            .map_err(|e| SammError::GraphError(format!("Failed to write DOT: {}", e)))?;

        Ok(dot)
    }

    /// Get node attributes (color, shape, label) based on node type
    fn get_node_attributes(
        &self,
        name: &str,
        style: VisualizationStyle,
        colors: &ColorScheme,
    ) -> (String, &'static str, String) {
        // Determine node type based on naming patterns
        let (color, shape) = if name.contains("Aspect") {
            (colors.aspect_color.clone(), "box")
        } else if name.contains("Characteristic") || name.contains("Char") {
            (colors.characteristic_color.clone(), "ellipse")
        } else {
            // Assume property
            (colors.property_color.clone(), "rectangle")
        };

        // Generate label based on style
        let label = match style {
            VisualizationStyle::Compact => {
                // Just the short name
                name.to_string()
            }
            VisualizationStyle::Detailed => {
                // Full name with type indicator
                name.to_string()
            }
            VisualizationStyle::Hierarchical => {
                // Name with indentation hints
                name.to_string()
            }
        };

        (color, shape, label)
    }

    /// Render graph to SVG file (requires `graphviz` feature)
    ///
    /// This method directly renders the graph to an SVG file using the Graphviz library.
    ///
    /// # Arguments
    ///
    /// * `output_path` - Path to output SVG file
    /// * `style` - Visualization style to use
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "graphviz")]
    /// # {
    /// use oxirs_samm::graph_analytics::{ModelGraph, VisualizationStyle};
    ///
    /// # fn example(graph: &ModelGraph) -> Result<(), Box<dyn std::error::Error>> {
    /// graph.render_svg("model.svg", VisualizationStyle::Hierarchical)?;
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    #[cfg(feature = "graphviz")]
    pub fn render_svg(&self, output_path: &str, style: VisualizationStyle) -> Result<()> {
        use graphviz_rust::cmd::{CommandArg, Format};
        use graphviz_rust::exec;
        use graphviz_rust::parse;
        use graphviz_rust::printer::PrinterContext;

        let dot_string = self.to_dot(style)?;

        // Parse DOT string
        let graph = parse(&dot_string)
            .map_err(|e| SammError::GraphError(format!("Failed to parse DOT: {:?}", e)))?;

        // Render to SVG
        let svg = exec(
            graph,
            &mut PrinterContext::default(),
            vec![CommandArg::Format(Format::Svg)],
        )
        .map_err(|e| SammError::GraphError(format!("Failed to render SVG: {:?}", e)))?;

        // Write to file
        std::fs::write(output_path, svg)
            .map_err(|e| SammError::GraphError(format!("Failed to write SVG: {}", e)))?;

        Ok(())
    }

    /// Render graph to PNG file (requires `graphviz` feature)
    ///
    /// This method directly renders the graph to a PNG file using the Graphviz library.
    ///
    /// # Arguments
    ///
    /// * `output_path` - Path to output PNG file
    /// * `style` - Visualization style to use
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "graphviz")]
    /// # {
    /// use oxirs_samm::graph_analytics::{ModelGraph, VisualizationStyle};
    ///
    /// # fn example(graph: &ModelGraph) -> Result<(), Box<dyn std::error::Error>> {
    /// graph.render_png("model.png", VisualizationStyle::Compact)?;
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    #[cfg(feature = "graphviz")]
    pub fn render_png(&self, output_path: &str, style: VisualizationStyle) -> Result<()> {
        use graphviz_rust::cmd::{CommandArg, Format};
        use graphviz_rust::exec;
        use graphviz_rust::parse;
        use graphviz_rust::printer::PrinterContext;

        let dot_string = self.to_dot(style)?;

        // Parse DOT string
        let graph = parse(&dot_string)
            .map_err(|e| SammError::GraphError(format!("Failed to parse DOT: {:?}", e)))?;

        // Render to PNG
        let png = exec(
            graph,
            &mut PrinterContext::default(),
            vec![CommandArg::Format(Format::Png)],
        )
        .map_err(|e| SammError::GraphError(format!("Failed to render PNG: {:?}", e)))?;

        // Write to file
        std::fs::write(output_path, png)
            .map_err(|e| SammError::GraphError(format!("Failed to write PNG: {}", e)))?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metamodel::{Aspect, Characteristic, CharacteristicKind, Property};

    fn create_test_aspect() -> Aspect {
        let mut aspect = Aspect::new("urn:samm:test:1.0.0#TestAspect".to_string());

        // Add properties
        for i in 1..=3 {
            let characteristic = Characteristic {
                metadata: crate::metamodel::ElementMetadata::new(format!(
                    "urn:samm:test:1.0.0#Char{}",
                    i
                )),
                data_type: Some("string".to_string()),
                kind: CharacteristicKind::Trait,
                constraints: vec![],
            };

            let property = Property::new(format!("urn:samm:test:1.0.0#Property{}", i))
                .with_characteristic(characteristic);

            aspect.add_property(property);
        }

        aspect
    }

    #[test]
    fn test_dot_generation_compact() {
        let aspect = create_test_aspect();
        let graph = ModelGraph::from_aspect(&aspect).expect("conversion should succeed");

        let dot = graph
            .to_dot(VisualizationStyle::Compact)
            .expect("operation should succeed");

        // Verify DOT structure
        assert!(dot.contains("digraph SAMM_Model"));
        assert!(dot.contains("TestAspect"));
        assert!(dot.contains("Property1"));
        assert!(dot.contains("Char1"));
    }

    #[test]
    fn test_dot_generation_detailed() {
        let aspect = create_test_aspect();
        let graph = ModelGraph::from_aspect(&aspect).expect("conversion should succeed");

        let dot = graph
            .to_dot(VisualizationStyle::Detailed)
            .expect("operation should succeed");

        // Verify DOT structure
        assert!(dot.contains("digraph SAMM_Model"));
        assert!(dot.contains("fillcolor"));
        assert!(dot.contains("->"));
    }

    #[test]
    fn test_dot_generation_hierarchical() {
        let aspect = create_test_aspect();
        let graph = ModelGraph::from_aspect(&aspect).expect("conversion should succeed");

        let dot = graph
            .to_dot(VisualizationStyle::Hierarchical)
            .expect("operation should succeed");

        // Verify hierarchical layout
        assert!(dot.contains("rankdir=TB"));
    }

    #[test]
    fn test_custom_colors() {
        let aspect = create_test_aspect();
        let graph = ModelGraph::from_aspect(&aspect).expect("conversion should succeed");

        let colors = ColorScheme {
            aspect_color: "#FF0000".to_string(),
            property_color: "#00FF00".to_string(),
            characteristic_color: "#0000FF".to_string(),
            edge_color: "#000000".to_string(),
        };

        let dot = graph
            .to_dot_with_colors(VisualizationStyle::Detailed, colors)
            .expect("operation should succeed");

        // Verify custom colors are used
        assert!(dot.contains("#FF0000") || dot.contains("#00FF00") || dot.contains("#0000FF"));
    }

    #[test]
    fn test_node_attributes() {
        let aspect = create_test_aspect();
        let graph = ModelGraph::from_aspect(&aspect).expect("conversion should succeed");
        let colors = ColorScheme::default();

        // Test aspect node
        let (color, shape, _label) =
            graph.get_node_attributes("TestAspect", VisualizationStyle::Detailed, &colors);
        assert_eq!(color, colors.aspect_color);
        assert_eq!(shape, "box");

        // Test characteristic node
        let (color, shape, _label) =
            graph.get_node_attributes("Char1", VisualizationStyle::Detailed, &colors);
        assert_eq!(color, colors.characteristic_color);
        assert_eq!(shape, "ellipse");

        // Test property node
        let (color, shape, _label) =
            graph.get_node_attributes("Property1", VisualizationStyle::Detailed, &colors);
        assert_eq!(color, colors.property_color);
        assert_eq!(shape, "rectangle");
    }
}