vowl-wasm 0.2.0

VOWL ontology visualisation engine in Rust/WASM: OWL parsing, force-directed layout (Barnes-Hut, SIMD), and rendering data for web explorers. A clean-room reimplementation of the WebVOWL visual notation.
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
//! OWL ontology parser implementation

use super::ClassOntologyMetadata;
use super::*;
use crate::{Result, VowlError};
use serde_json::Value;
use std::collections::HashMap;

/// Standard OWL ontology parser
pub struct StandardParser {
    /// Parser configuration
    config: ParserConfig,
}

/// Parser configuration options
#[derive(Debug, Clone)]
pub struct ParserConfig {
    /// Validate IRI format
    pub validate_iris: bool,

    /// Allow empty labels
    pub allow_empty_labels: bool,

    /// Maximum classes to parse (0 = unlimited)
    pub max_classes: usize,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            validate_iris: true,
            allow_empty_labels: false,
            max_classes: 0,
        }
    }
}

impl StandardParser {
    /// Create a new parser with default configuration
    pub fn new() -> Self {
        Self {
            config: ParserConfig::default(),
        }
    }

    /// Create a parser with custom configuration
    pub fn with_config(config: ParserConfig) -> Self {
        Self { config }
    }

    /// Parse class nodes from JSON value
    fn parse_classes(&self, json: &Value) -> Result<Vec<ClassNode>> {
        let classes_array = json
            .get("class")
            .or_else(|| json.get("classes"))
            .and_then(|v| v.as_array())
            .ok_or_else(|| VowlError::ParseError("Missing 'class' array".to_string()))?;

        let mut classes = Vec::new();

        for (idx, class_json) in classes_array.iter().enumerate() {
            if self.config.max_classes > 0 && idx >= self.config.max_classes {
                break;
            }

            let class = self.parse_class_node(class_json)?;
            classes.push(class);
        }

        Ok(classes)
    }

    /// Parse a single class node
    fn parse_class_node(&self, json: &Value) -> Result<ClassNode> {
        let id = json
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| VowlError::ParseError("Missing class id".to_string()))?
            .to_string();

        let iri = json
            .get("iri")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| id.clone());

        let label = json
            .get("label")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| id.clone());

        if !self.config.allow_empty_labels && label.is_empty() {
            return Err(VowlError::ParseError(format!(
                "Empty label for class: {}",
                id
            )));
        }

        let class_type = self.determine_class_type(json)?;

        let equivalent = json
            .get("equivalent")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_default();

        let attributes = self.parse_class_attributes(json)?;
        let ontology_meta = self.parse_ontology_metadata(json);

        Ok(ClassNode {
            id,
            iri,
            label,
            class_type,
            equivalent,
            attributes,
            ontology_meta,
        })
    }

    /// Determine class type from JSON, including set operators
    fn determine_class_type(&self, json: &Value) -> Result<String> {
        let type_str = json
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("owl:Class");

        // Normalize set operator types to standard OWL format
        let class_type = match type_str {
            "owl:unionOf" | "unionOf" => "owl:unionOf",
            "owl:intersectionOf" | "intersectionOf" => "owl:intersectionOf",
            "owl:complementOf" | "complementOf" => "owl:complementOf",
            "owl:disjointUnionOf" | "disjointUnionOf" => "owl:disjointUnionOf",
            _ => type_str,
        };

        Ok(class_type.to_string())
    }

    /// Parse class attributes
    fn parse_class_attributes(&self, json: &Value) -> Result<ClassAttributes> {
        let external = json
            .get("external")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let individuals = json
            .get("individuals")
            .and_then(|v| v.as_u64())
            .map(|n| n as usize);

        let mut properties = HashMap::new();
        if let Some(attrs) = json.get("attributes").and_then(|v| v.as_object()) {
            for (key, value) in attrs {
                if let Some(s) = value.as_str() {
                    properties.insert(key.clone(), s.to_string());
                } else if let Some(val_str) = value
                    .to_string()
                    .strip_prefix('"')
                    .and_then(|s| s.strip_suffix('"'))
                {
                    properties.insert(key.clone(), val_str.to_string());
                }
            }
        }

        Ok(ClassAttributes {
            external,
            individuals,
            properties,
        })
    }

    /// Parse class ontology metadata from attributes
    fn parse_ontology_metadata(&self, json: &Value) -> Option<ClassOntologyMetadata> {
        // Check if attributes exist
        let attrs = json
            .get("attributes")
            .or_else(|| json.get("classAttribute"))?;

        let attrs_obj = attrs.as_object()?;

        // Extract metadata fields from attributes
        let term_id = json
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let preferred_term = attrs_obj
            .get("preferredTerm")
            .or_else(|| attrs_obj.get("preferred_term"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let domain = attrs_obj
            .get("domain")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let maturity = attrs_obj
            .get("maturity")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let status = attrs_obj
            .get("status")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let authority_score = attrs_obj
            .get("authorityScore")
            .or_else(|| attrs_obj.get("authority_score"))
            .and_then(|v| v.as_f64())
            .map(|f| f as f32);

        // Only create metadata if we have at least one field
        if preferred_term.is_some()
            || domain.is_some()
            || maturity.is_some()
            || status.is_some()
            || authority_score.is_some()
        {
            Some(ClassOntologyMetadata {
                term_id,
                preferred_term,
                domain,
                maturity,
                status,
                authority_score,
            })
        } else {
            None
        }
    }

    /// Parse properties from JSON value
    fn parse_properties(&self, json: &Value) -> Result<Vec<Property>> {
        let properties_array = json
            .get("property")
            .or_else(|| json.get("properties"))
            .and_then(|v| v.as_array())
            .ok_or_else(|| VowlError::ParseError("Missing 'property' array".to_string()))?;

        properties_array
            .iter()
            .map(|prop_json| self.parse_property(prop_json))
            .collect()
    }

    /// Parse a single property
    fn parse_property(&self, json: &Value) -> Result<Property> {
        let id = json
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| VowlError::ParseError("Missing property id".to_string()))?
            .to_string();

        let iri = json
            .get("iri")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| id.clone());

        let label = json
            .get("label")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| id.clone());

        let property_type = self.parse_property_type(json)?;

        let domain = json
            .get("domain")
            .and_then(|v| v.as_str())
            .ok_or_else(|| VowlError::ParseError(format!("Missing domain for property: {}", id)))?
            .to_string();

        let range = json
            .get("range")
            .and_then(|v| v.as_str())
            .ok_or_else(|| VowlError::ParseError(format!("Missing range for property: {}", id)))?
            .to_string();

        let characteristics = self.parse_property_characteristics(json)?;

        // Parse Phase 11 relationship fields
        let inverse_of = json
            .get("inverseOf")
            .or_else(|| json.get("inverse_of"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let equivalent_to = json
            .get("equivalentProperty")
            .or_else(|| json.get("equivalent_to"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_default();

        let disjoint_with = json
            .get("disjointWith")
            .or_else(|| json.get("disjoint_with"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_default();

        Ok(Property {
            id,
            iri,
            label,
            property_type,
            domain,
            range,
            characteristics,
            inverse_of,
            equivalent_to,
            disjoint_with,
        })
    }

    /// Parse property type
    fn parse_property_type(&self, json: &Value) -> Result<PropertyType> {
        let type_str = json
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("owl:ObjectProperty");

        Ok(match type_str {
            "owl:ObjectProperty" => PropertyType::ObjectProperty,
            "owl:DatatypeProperty" => PropertyType::DatatypeProperty,
            "owl:AnnotationProperty" => PropertyType::AnnotationProperty,
            other => PropertyType::SpecialProperty(other.to_string()),
        })
    }

    /// Parse property characteristics
    fn parse_property_characteristics(&self, json: &Value) -> Result<PropertyCharacteristics> {
        let functional = json
            .get("functional")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let inverse_functional = json
            .get("inverseFunctional")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let transitive = json
            .get("transitive")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let symmetric = json
            .get("symmetric")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let cardinality = self.parse_cardinality(json)?;

        Ok(PropertyCharacteristics {
            functional,
            inverse_functional,
            transitive,
            symmetric,
            cardinality,
        })
    }

    /// Parse cardinality constraints
    fn parse_cardinality(&self, json: &Value) -> Result<Option<Cardinality>> {
        let cardinality = json.get("cardinality");
        if cardinality.is_none() {
            return Ok(None);
        }

        let min = json
            .get("minCardinality")
            .and_then(|v| v.as_u64())
            .map(|n| n as u32);

        let max = json
            .get("maxCardinality")
            .and_then(|v| v.as_u64())
            .map(|n| n as u32);

        let exact = json
            .get("cardinality")
            .and_then(|v| v.as_u64())
            .map(|n| n as u32);

        if min.is_some() || max.is_some() || exact.is_some() {
            Ok(Some(Cardinality { min, max, exact }))
        } else {
            Ok(None)
        }
    }

    /// Parse namespaces from JSON value
    fn parse_namespaces(&self, json: &Value) -> Result<Vec<Namespace>> {
        let namespace_obj = json.get("namespace").or_else(|| json.get("namespaces"));

        if let Some(ns) = namespace_obj {
            if let Some(obj) = ns.as_object() {
                return Ok(obj
                    .iter()
                    .map(|(prefix, iri)| Namespace {
                        prefix: prefix.clone(),
                        iri: iri.as_str().unwrap_or("").to_string(),
                    })
                    .collect());
            }
        }

        Ok(vec![])
    }

    /// Parse ontology metadata
    fn parse_metadata(&self, json: &Value) -> Result<OntologyMetadata> {
        let header = json.get("header");

        let iri = header
            .and_then(|h| h.get("iri"))
            .and_then(|v| v.as_str())
            .unwrap_or("http://example.org/ontology")
            .to_string();

        let version = header
            .and_then(|h| h.get("version"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let title = header
            .and_then(|h| h.get("title"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let description = header
            .and_then(|h| h.get("description"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        Ok(OntologyMetadata {
            iri,
            version,
            title,
            description,
        })
    }
}

impl OntologyParser for StandardParser {
    fn parse(&self, json: &str) -> Result<OntologyData> {
        let value: Value = serde_json::from_str(json)?;

        let metadata = self.parse_metadata(&value)?;
        let classes = self.parse_classes(&value)?;
        let properties = self.parse_properties(&value)?;
        let namespaces = self.parse_namespaces(&value)?;

        Ok(OntologyData {
            metadata,
            classes,
            properties,
            namespaces,
        })
    }

    fn validate(&self, data: &OntologyData) -> Result<()> {
        // Validate that all property domains and ranges reference valid classes
        let class_ids: HashMap<_, _> = data.classes.iter().map(|c| (&c.id, ())).collect();

        for prop in &data.properties {
            if !class_ids.contains_key(&prop.domain) {
                return Err(VowlError::InvalidData(format!(
                    "Property '{}' references unknown domain class: {}",
                    prop.id, prop.domain
                )));
            }

            // Range might be a datatype, so we're more lenient
            if !class_ids.contains_key(&prop.range) && !prop.range.starts_with("xsd:") {
                // Only warn for non-datatype ranges
                eprintln!(
                    "Warning: Property '{}' references possibly unknown range: {}",
                    prop.id, prop.range
                );
            }
        }

        Ok(())
    }
}

impl Default for StandardParser {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parse_simple_ontology() {
        let json = r#"
        {
            "header": {
                "iri": "http://example.org/test",
                "title": "Test Ontology",
                "version": "1.0"
            },
            "namespace": {
                "owl": "http://www.w3.org/2002/07/owl#"
            },
            "class": [
                {
                    "id": "class1",
                    "iri": "http://example.org/Class1",
                    "label": "Class 1",
                    "type": "owl:Class"
                }
            ],
            "property": [
                {
                    "id": "prop1",
                    "iri": "http://example.org/prop1",
                    "label": "Property 1",
                    "type": "owl:ObjectProperty",
                    "domain": "class1",
                    "range": "class1"
                }
            ]
        }
        "#;

        let parser = StandardParser::new();
        let result = parser.parse(json);

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data.classes.len(), 1);
        assert_eq!(data.properties.len(), 1);
        assert_eq!(data.metadata.title, Some("Test Ontology".to_string()));
    }

    #[test]
    fn test_parse_class_with_attributes() {
        let json = r#"
        {
            "class": [
                {
                    "id": "class1",
                    "label": "Class 1",
                    "external": true,
                    "individuals": 42
                }
            ],
            "property": []
        }
        "#;

        let parser = StandardParser::new();
        let result = parser.parse(json);

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data.classes.len(), 1);
        assert!(data.classes[0].attributes.external);
        assert_eq!(data.classes[0].attributes.individuals, Some(42));
    }

    #[test]
    fn test_validate_invalid_domain() {
        let data = OntologyData {
            metadata: OntologyMetadata {
                iri: "test".to_string(),
                version: None,
                title: None,
                description: None,
            },
            classes: vec![ClassNode {
                id: "class1".to_string(),
                iri: "test".to_string(),
                label: "Test".to_string(),
                class_type: "owl:Class".to_string(),
                equivalent: vec![],
                attributes: ClassAttributes::default(),
                ontology_meta: None,
            }],
            properties: vec![Property {
                id: "prop1".to_string(),
                iri: "test".to_string(),
                label: "Test".to_string(),
                property_type: PropertyType::ObjectProperty,
                domain: "invalid_class".to_string(),
                range: "class1".to_string(),
                characteristics: PropertyCharacteristics::default(),
                inverse_of: None,
                equivalent_to: vec![],
                disjoint_with: vec![],
            }],
            namespaces: vec![],
        };

        let parser = StandardParser::new();
        let result = parser.validate(&data);

        assert!(result.is_err());
    }

    #[test]
    fn test_parser_config() {
        let config = ParserConfig {
            validate_iris: false,
            allow_empty_labels: true,
            max_classes: 10,
        };

        let parser = StandardParser::with_config(config.clone());
        assert!(!parser.config.validate_iris);
        assert!(parser.config.allow_empty_labels);
        assert_eq!(parser.config.max_classes, 10);
    }

    #[test]
    fn test_parse_set_operators() {
        let json = r#"
        {
            "class": [
                {
                    "id": "union1",
                    "label": "Union of A and B",
                    "type": "owl:unionOf"
                },
                {
                    "id": "intersection1",
                    "label": "Intersection of C and D",
                    "type": "owl:intersectionOf"
                },
                {
                    "id": "complement1",
                    "label": "Complement of E",
                    "type": "owl:complementOf"
                },
                {
                    "id": "disjoint1",
                    "label": "Disjoint Union of F and G",
                    "type": "owl:disjointUnionOf"
                }
            ],
            "property": []
        }
        "#;

        let parser = StandardParser::new();
        let result = parser.parse(json);

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data.classes.len(), 4);

        assert_eq!(data.classes[0].class_type, "owl:unionOf");
        assert_eq!(data.classes[1].class_type, "owl:intersectionOf");
        assert_eq!(data.classes[2].class_type, "owl:complementOf");
        assert_eq!(data.classes[3].class_type, "owl:disjointUnionOf");
    }
}