Skip to main content

qualia_core_db/modalities/logic/owl/
shacl_convert.rs

1//! OWL → SHACL conversion for QualiaDB ontology alignment.
2//!
3//! RadLex and DICOM healthcare vocabularies arrive as OWL (RDF/XML or Turtle/N3).
4//! The Webizen Sentinel consumes **SHACL**, not OWL classifiers directly. This module
5//! lowers OWL axioms into `sh:NodeShape` graphs while preserving the agency invariant:
6//! **`q42:Principal` may have `q42:Thing` possessions but is not itself a Thing.**
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::fs::{self, File};
10use std::io::{BufReader, Write};
11use std::path::Path;
12
13use quick_xml::events::Event;
14use quick_xml::Reader;
15use rio_api::model::Triple;
16use rio_api::parser::TriplesParser;
17use rio_turtle::TurtleParser;
18
19const OWL_CLASS: &str = "http://www.w3.org/2002/07/owl#Class";
20const OWL_DATATYPE_PROPERTY: &str = "http://www.w3.org/2002/07/owl#DatatypeProperty";
21const OWL_OBJECT_PROPERTY: &str = "http://www.w3.org/2002/07/owl#ObjectProperty";
22const OWL_EQUIVALENT_CLASS: &str = "http://www.w3.org/2002/07/owl#equivalentClass";
23const OWL_EQUIVALENT_PROPERTY: &str = "http://www.w3.org/2002/07/owl#equivalentProperty";
24const RDFS_DOMAIN: &str = "http://www.w3.org/2000/01/rdf-schema#domain";
25const RDFS_RANGE: &str = "http://www.w3.org/2000/01/rdf-schema#range";
26const RDFS_LABEL: &str = "http://www.w3.org/2000/01/rdf-schema#label";
27const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
28
29/// Prefixes emitted on every generated shapes file.
30pub const SHAPE_PREFIXES: &str = r#"@prefix sh: <http://www.w3.org/ns/shacl#> .
31@prefix owl: <http://www.w3.org/2002/07/owl#> .
32@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
33@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
34@prefix q42: <https://ns.webcivics.net/> .
35@prefix hc: <http://purl.org/healthcarevocab/v1#> .
36@prefix radlex: <http://www.radlex.org/RID/> .
37"#;
38
39#[derive(Debug, Default, Clone)]
40struct OwlClass {
41    labels: Vec<String>,
42    equivalent: Option<String>,
43}
44
45#[derive(Debug, Default, Clone)]
46struct OwlProperty {
47    labels: Vec<String>,
48    kinds: BTreeSet<String>,
49    domains: BTreeSet<String>,
50    ranges: BTreeSet<String>,
51    equivalent: Option<String>,
52}
53
54#[derive(Debug, Default)]
55pub struct HealthcareOwlModel {
56    classes: BTreeMap<String, OwlClass>,
57    properties: BTreeMap<String, OwlProperty>,
58}
59
60#[derive(Debug, Clone)]
61pub struct RadlexRelation {
62    pub subject_rid: String,
63    pub predicate_local: String,
64    pub object_rid: String,
65}
66
67#[derive(Debug, PartialEq, Eq)]
68pub enum OwlToShaclError {
69    Io(String),
70    Parse(String),
71    EmptyInput,
72}
73
74impl std::fmt::Display for OwlToShaclError {
75    /// Human-readable error text (`IO error: …`, `parse error: …`,
76    /// `no triples or relations parsed`).
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        match self {
79            Self::Io(msg) => write!(f, "IO error: {msg}"),
80            Self::Parse(msg) => write!(f, "parse error: {msg}"),
81            Self::EmptyInput => write!(f, "no triples or relations parsed"),
82        }
83    }
84}
85
86impl std::error::Error for OwlToShaclError {}
87
88/// True for blank/anonymous node spellings (`_:…`, `[…`) that cannot
89/// be named subjects in emitted SHACL.
90fn is_blank_or_anon(subject: &str) -> bool {
91    subject.starts_with("_:") || subject.starts_with('[')
92}
93
94/// Fragment after the last `#` or `/` (or the whole URI when neither
95/// is present).
96fn local_name(uri: &str) -> String {
97    uri.rsplit(['#', '/']).next().unwrap_or(uri).to_string()
98}
99
100/// Shape name for a class/property URI — namespaced `hc:`/`radlex:` for
101/// the known vocabularies, `ex:` otherwise.
102fn shape_name_for_uri(uri: &str) -> String {
103    let local = local_name(uri);
104    if uri.contains("healthcarevocab") {
105        format!("hc:{local}Shape")
106    } else if uri.contains("radlex.org") {
107        format!("radlex:{local}Shape")
108    } else {
109        format!("ex:{local}Shape")
110    }
111}
112
113/// Compact `hc:`/`radlex:`/`q42:` CURIE for the known vocab prefixes;
114/// `<uri>` bracket form for anything else.
115fn curie_for_uri(uri: &str) -> String {
116    if let Some(tag) = uri.strip_prefix("http://purl.org/healthcarevocab/v1#") {
117        return format!("hc:{tag}");
118    }
119    if let Some(tag) = uri.strip_prefix("http://www.radlex.org/RID/") {
120        return format!("radlex:{tag}");
121    }
122    if uri.starts_with("https://ns.webcivics.net/") {
123        let tag = uri.trim_start_matches("https://ns.webcivics.net/");
124        return format!("q42:{tag}");
125    }
126    format!("<{uri}>")
127}
128
129/// Map an XSD datatype URI to its CURIE (`xsd:date`, `xsd:integer`,
130/// `xsd:decimal`, `xsd:boolean`, …); `None` for unrecognized ranges so
131/// the caller can emit the full URI instead.
132fn xsd_from_range(range: &str) -> Option<&'static str> {
133    match range {
134        "http://www.w3.org/2001/XMLSchema#date" => Some("xsd:date"),
135        "http://www.w3.org/2001/XMLSchema#dateTime" => Some("xsd:dateTime"),
136        "http://www.w3.org/2001/XMLSchema#long" | "http://www.w3.org/2001/XMLSchema#integer" => {
137            Some("xsd:integer")
138        }
139        "http://www.w3.org/2001/XMLSchema#double"
140        | "http://www.w3.org/2001/XMLSchema#decimal"
141        | "http://www.w3.org/2001/XMLSchema#float" => Some("xsd:decimal"),
142        "http://www.w3.org/2001/XMLSchema#boolean" => Some("xsd:boolean"),
143        _ => None,
144    }
145}
146
147/// Fold one parsed `(s, p, o)` triple into `model`: registers classes
148/// and datatype/object properties on `rdf:type`, labels on
149/// `rdfs:label`, and `owl:equivalentClass`/`equivalentProperty` links.
150/// Unrecognized predicates are ignored.
151fn ingest_owl_triple(model: &mut HealthcareOwlModel, s: String, p: String, o: String) {
152    if p == RDF_TYPE {
153        if o == OWL_CLASS {
154            model.classes.entry(s).or_default();
155        } else if o == OWL_DATATYPE_PROPERTY || o == OWL_OBJECT_PROPERTY {
156            model.properties.entry(s).or_default().kinds.insert(o);
157        }
158    } else if p == RDFS_LABEL {
159        if let Some(class) = model.classes.get_mut(&s) {
160            class.labels.push(o.trim_matches('"').to_string());
161        } else if let Some(prop) = model.properties.get_mut(&s) {
162            prop.labels.push(o.trim_matches('"').to_string());
163        }
164    } else if p == OWL_EQUIVALENT_CLASS {
165        model.classes.entry(s).or_default().equivalent = Some(o);
166    } else if p == OWL_EQUIVALENT_PROPERTY {
167        model.properties.entry(s).or_default().equivalent = Some(o);
168    } else if p == RDFS_DOMAIN {
169        model.properties.entry(s).or_default().domains.insert(o);
170    } else if p == RDFS_RANGE {
171        model.properties.entry(s).or_default().ranges.insert(o);
172    }
173}
174
175/// Parse Turtle healthcare vocabulary.
176pub fn parse_healthcare_owl_turtle(path: &Path) -> Result<HealthcareOwlModel, OwlToShaclError> {
177    let bytes = fs::read(path).map_err(|e| OwlToShaclError::Io(e.to_string()))?;
178    let sanitized = trim_incomplete_turtle_tail(&bytes);
179    let mut model = HealthcareOwlModel::default();
180    let mut on_triple = |t: Triple| -> Result<(), std::io::Error> {
181        ingest_owl_triple(
182            &mut model,
183            t.subject.to_string(),
184            t.predicate.to_string(),
185            t.object.to_string(),
186        );
187        Ok(())
188    };
189    let cursor = std::io::Cursor::new(sanitized);
190    let mut parser = TurtleParser::new(cursor, None);
191    if let Err(e) = parser.parse_all(&mut on_triple) {
192        if model.classes.is_empty() && model.properties.is_empty() {
193            return Err(OwlToShaclError::Parse(format!("{e}")));
194        }
195    }
196    if model.classes.is_empty() && model.properties.is_empty() {
197        return Err(OwlToShaclError::EmptyInput);
198    }
199    Ok(model)
200}
201
202/// Parse `.n3` healthcare excerpt (OWL in Notation3/Turtle syntax; tolerates truncated exports).
203pub fn parse_healthcare_owl_n3(path: &Path) -> Result<HealthcareOwlModel, OwlToShaclError> {
204    let text = std::fs::read_to_string(path).map_err(|e| OwlToShaclError::Io(e.to_string()))?;
205    let mut model = HealthcareOwlModel::default();
206    let mut parser = crate::modalities::logic::n3_parser::N3Parser::new(&text);
207    let result = parser.parse_all(|event| {
208        if let crate::modalities::logic::n3_parser::N3Event::StaticTriple(triple) = event {
209            let subject = term_uri(&triple.subject);
210            let predicate = term_uri(&triple.predicate);
211            let object = term_uri(&triple.object);
212            ingest_owl_triple(&mut model, subject, predicate, object);
213        }
214        Ok(())
215    });
216    if result.is_err() && model.classes.is_empty() && model.properties.is_empty() {
217        return parse_healthcare_owl_turtle(path);
218    }
219    if model.classes.is_empty() && model.properties.is_empty() {
220        return Err(OwlToShaclError::EmptyInput);
221    }
222    Ok(model)
223}
224
225/// Line-oriented parser for healthcare vocab exports (handles truncated tails and `unionOf` domains).
226pub fn parse_healthcare_owl_lines(path: &Path) -> Result<HealthcareOwlModel, OwlToShaclError> {
227    let bytes = fs::read(path).map_err(|e| OwlToShaclError::Io(e.to_string()))?;
228    let sanitized = trim_incomplete_turtle_tail(&bytes);
229    let text = String::from_utf8_lossy(&sanitized).into_owned();
230    let mut model = HealthcareOwlModel::default();
231    let mut current_subject: Option<String> = None;
232
233    for raw in text.lines() {
234        let line = raw.trim();
235        if line.is_empty() {
236            continue;
237        }
238        if line.starts_with('@') {
239            continue;
240        }
241        if line.starts_with('<')
242            && line.ends_with('>')
243            && !line.contains(';')
244            && !line.contains(' ')
245        {
246            current_subject = Some(line.trim_matches(|c| c == '<' || c == '>').to_string());
247            continue;
248        }
249        let Some(subject) = current_subject.clone() else {
250            continue;
251        };
252        if let Some(kind) = line.strip_prefix("a ") {
253            let kind = kind.trim().trim_end_matches(';').trim();
254            let expanded = match kind {
255                "owl:Class" => OWL_CLASS.to_string(),
256                "owl:DatatypeProperty" => OWL_DATATYPE_PROPERTY.to_string(),
257                "owl:ObjectProperty" => OWL_OBJECT_PROPERTY.to_string(),
258                other if other.starts_with("http") => other.to_string(),
259                _ => continue,
260            };
261            ingest_owl_triple(&mut model, subject, RDF_TYPE.to_string(), expanded);
262        } else if line.strip_prefix("rdfs:label").is_some() {
263            if let Some(value) = extract_turtle_string_literal(line) {
264                ingest_owl_triple(&mut model, subject, RDFS_LABEL.to_string(), value);
265            }
266        } else if line.contains("owl:equivalentClass") {
267            if let Some(uri) = extract_first_uri(line) {
268                ingest_owl_triple(&mut model, subject, OWL_EQUIVALENT_CLASS.to_string(), uri);
269            }
270        } else if line.contains("owl:equivalentProperty") {
271            if let Some(uri) = extract_first_uri(line) {
272                ingest_owl_triple(
273                    &mut model,
274                    subject,
275                    OWL_EQUIVALENT_PROPERTY.to_string(),
276                    uri,
277                );
278            }
279        } else if line.contains("rdfs:domain") {
280            if let Some(uri) = extract_first_uri(line) {
281                ingest_owl_triple(&mut model, subject, RDFS_DOMAIN.to_string(), uri);
282            }
283        } else if line.contains("rdfs:range") {
284            if let Some(uri) = extract_first_uri(line) {
285                ingest_owl_triple(&mut model, subject, RDFS_RANGE.to_string(), uri);
286            }
287        } else if line.ends_with('.') && !line.starts_with('<') {
288            current_subject = None;
289        }
290    }
291
292    if model.classes.is_empty() && model.properties.is_empty() {
293        return Err(OwlToShaclError::EmptyInput);
294    }
295    Ok(model)
296}
297
298/// First `<…>` bracket URI on a line, or `None` when no complete pair
299/// exists (used by the line-oriented N3 fallback parser).
300fn extract_first_uri(line: &str) -> Option<String> {
301    let start = line.find('<')? + 1;
302    let end = line[start..].find('>')? + start;
303    Some(line[start..end].to_string())
304}
305
306/// First `"…"` string literal on a line, or `None` (no escape handling —
307/// the line-oriented fallback only needs simple literals).
308fn extract_turtle_string_literal(line: &str) -> Option<String> {
309    let start = line.find('"')? + 1;
310    let rest = &line[start..];
311    let end = rest.find('"')?;
312    Some(rest[..end].to_string())
313}
314
315/// Parse healthcare OWL from `.n3` or `.ttl`.
316pub fn parse_healthcare_owl(path: &Path) -> Result<HealthcareOwlModel, OwlToShaclError> {
317    parse_healthcare_owl_lines(path)
318        .or_else(|_| parse_healthcare_owl_turtle(path))
319        .or_else(|_| parse_healthcare_owl_n3(path))
320}
321
322/// Unwrap any `n3_parser::Term` variant to its string payload — Uri,
323/// Variable, Literal, and Formula all carry their surface form.
324fn term_uri(term: &crate::modalities::logic::n3_parser::Term) -> String {
325    match term {
326        crate::modalities::logic::n3_parser::Term::Uri(s) => s.to_string(),
327        crate::modalities::logic::n3_parser::Term::Variable(s) => s.to_string(),
328        crate::modalities::logic::n3_parser::Term::Literal(s) => s.to_string(),
329        crate::modalities::logic::n3_parser::Term::Formula(s) => s.to_string(),
330    }
331}
332
333/// Drop a truncated final subject line (common in partial DICOM OWL exports).
334fn trim_incomplete_turtle_tail(bytes: &[u8]) -> Vec<u8> {
335    let text = String::from_utf8_lossy(bytes);
336    if text.trim_end().ends_with('.') {
337        return bytes.to_vec();
338    }
339    let mut lines: Vec<&str> = text.lines().collect();
340    while let Some(last) = lines.last() {
341        if last.trim().starts_with('<') && !last.trim().ends_with('.') {
342            lines.pop();
343        } else {
344            break;
345        }
346    }
347    let mut out = lines.join("\n");
348    if !out.ends_with('\n') {
349        out.push('\n');
350    }
351    out.into_bytes()
352}
353
354/// Emit SHACL node shapes for healthcare IE.* classes and DICOM-tag properties.
355pub fn healthcare_owl_to_shacl_ttl(model: &HealthcareOwlModel) -> String {
356    let mut out = String::from(SHAPE_PREFIXES);
357    out.push_str("\n# Generated from healthcare OWL — DICOM tag alignment\n\n");
358
359    for (class_uri, class) in &model.classes {
360        if is_blank_or_anon(class_uri) {
361            continue;
362        }
363        let local = local_name(class_uri);
364        if !local.starts_with("IE.") && !local.starts_with("SequenceItem.") {
365            continue;
366        }
367        let shape = shape_name_for_uri(class_uri);
368        let target = curie_for_uri(class_uri);
369        out.push_str(&format!(
370            "{shape} a sh:NodeShape ;\n    sh:targetClass {target}"
371        ));
372        if let Some(label) = class.labels.first() {
373            out.push_str(&format!(" ;\n    rdfs:label \"{label}\""));
374        }
375        if let Some(eq) = &class.equivalent {
376            out.push_str(&format!(
377                " ;\n    sh:property [ sh:path owl:equivalentClass ; sh:hasValue {} ]",
378                curie_for_uri(eq)
379            ));
380        }
381        out.push_str(" .\n\n");
382    }
383
384    let mut by_domain: BTreeMap<String, Vec<(String, OwlProperty)>> = BTreeMap::new();
385    for (prop_uri, prop) in &model.properties {
386        if is_blank_or_anon(prop_uri) {
387            continue;
388        }
389        let domains: Vec<String> = if prop.domains.is_empty() {
390            vec!["http://purl.org/healthcarevocab/v1#IE.Image".to_string()]
391        } else {
392            prop.domains.iter().cloned().collect()
393        };
394        for domain in domains {
395            if is_blank_or_anon(&domain) {
396                continue;
397            }
398            by_domain
399                .entry(domain)
400                .or_default()
401                .push((prop_uri.clone(), prop.clone()));
402        }
403    }
404
405    for (domain_uri, props) in by_domain {
406        let domain_local = local_name(&domain_uri);
407        if !domain_local.starts_with("IE.") {
408            continue;
409        }
410        let shape = format!("hc:{domain_local}PropertyShape");
411        let target = curie_for_uri(&domain_uri);
412        out.push_str(&format!(
413            "{shape} a sh:NodeShape ;\n    sh:targetClass {target}"
414        ));
415        for (prop_uri, prop) in props {
416            let path = curie_for_uri(&prop_uri);
417            out.push_str(" ;\n    sh:property [");
418            out.push_str(&format!("\n        sh:path {path}"));
419            if let Some(label) = prop.labels.first() {
420                out.push_str(&format!(" ;\n        sh:name \"{label}\""));
421            }
422            if let Some(eq) = &prop.equivalent {
423                out.push_str(&format!(
424                    " ;\n        sh:qualifiedValueShape [ sh:hasValue {} ]",
425                    curie_for_uri(eq)
426                ));
427            }
428            if prop.kinds.contains(OWL_DATATYPE_PROPERTY) {
429                if let Some(range) = prop.ranges.iter().next() {
430                    if let Some(dt) = xsd_from_range(range) {
431                        out.push_str(&format!(" ;\n        sh:datatype {dt}"));
432                    } else if *range == "http://www.w3.org/2000/01/rdf-schema#Literal" {
433                        out.push_str(" ;\n        sh:datatype xsd:string");
434                    }
435                }
436            } else if prop.kinds.contains(OWL_OBJECT_PROPERTY) {
437                out.push_str(" ;\n        sh:nodeKind sh:BlankNodeOrIRI");
438            }
439            out.push_str("\n    ]");
440        }
441        out.push_str(" .\n\n");
442    }
443
444    out.push_str(
445        "# Principal may reference imaging entities but is not an IE.* class.\n\
446q42:PrincipalImagingLinkShape a sh:NodeShape ;\n\
447    sh:targetClass q42:Principal ;\n\
448    sh:property [\n\
449        sh:path q42:hasImagingStudy ;\n\
450        sh:class hc:IE.Study ;\n\
451        sh:minCount 0 ;\n\
452        sh:message \"Imaging studies are possessions of the Principal, not the Principal itself.\" ;\n\
453    ] ;\n\
454    sh:property [\n\
455        sh:path q42:hasDicomSeries ;\n\
456        sh:class hc:IE.Series ;\n\
457        sh:minCount 0 ;\n\
458    ] .\n\n",
459    );
460
461    out
462}
463
464/// Stream-parse RadLex Pun OWL (RDF/XML) relation axioms (`RID:Part_Of`, `RID:Has_Part`, …).
465pub fn parse_radlex_relations_xml(
466    path: &Path,
467    max_relations: usize,
468) -> Result<Vec<RadlexRelation>, OwlToShaclError> {
469    let file = File::open(path).map_err(|e| OwlToShaclError::Io(e.to_string()))?;
470    let mut reader = Reader::from_reader(BufReader::new(file));
471    reader.config_mut().trim_text(true);
472
473    let mut relations = Vec::new();
474    let mut buf = Vec::new();
475    let mut current_subject: Option<String> = None;
476    let mut in_description = false;
477
478    loop {
479        match reader.read_event_into(&mut buf) {
480            Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
481                let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
482                if name == "rdf:Description" || name.ends_with("Description") {
483                    in_description = true;
484                    current_subject = None;
485                    for attr in e.attributes().flatten() {
486                        let key = String::from_utf8_lossy(attr.key.as_ref()).to_string();
487                        if key.ends_with("about") {
488                            current_subject =
489                                Some(String::from_utf8_lossy(&attr.value).to_string());
490                        }
491                    }
492                } else if in_description {
493                    if let Some(subject) = current_subject.clone() {
494                        if let Some(pred_local) = name.strip_prefix("RID:") {
495                            for attr in e.attributes().flatten() {
496                                let key = String::from_utf8_lossy(attr.key.as_ref()).to_string();
497                                if key.ends_with("resource") {
498                                    let object = String::from_utf8_lossy(&attr.value).to_string();
499                                    relations.push(RadlexRelation {
500                                        subject_rid: subject.clone(),
501                                        predicate_local: pred_local.to_string(),
502                                        object_rid: object,
503                                    });
504                                    if relations.len() >= max_relations {
505                                        return Ok(relations);
506                                    }
507                                }
508                            }
509                        }
510                    }
511                }
512            }
513            Ok(Event::End(e)) => {
514                let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
515                if name == "rdf:Description" || name.ends_with("Description") {
516                    in_description = false;
517                    current_subject = None;
518                }
519            }
520            Ok(Event::Eof) => break,
521            Err(e) => return Err(OwlToShaclError::Parse(format!("{e}"))),
522            _ => {}
523        }
524        buf.clear();
525    }
526
527    if relations.is_empty() {
528        return Err(OwlToShaclError::EmptyInput);
529    }
530    Ok(relations)
531}
532
533/// Group RadLex relations by subject RID and emit SHACL node shapes.
534pub fn radlex_relations_to_shacl_ttl(relations: &[RadlexRelation], max_shapes: usize) -> String {
535    let mut grouped: BTreeMap<String, Vec<RadlexRelation>> = BTreeMap::new();
536    for rel in relations {
537        grouped
538            .entry(rel.subject_rid.clone())
539            .or_default()
540            .push(rel.clone());
541    }
542
543    let mut out = String::from(SHAPE_PREFIXES);
544    out.push_str(
545        "\n# Generated from RadLex OWL — anatomical possession graph (Things, not Principals)\n\n",
546    );
547    out.push_str(
548        "radlex:AnatomicalEntity a owl:Class ;\n\
549    rdfs:subClassOf q42:Thing ;\n\
550    rdfs:comment \"RadLex RID tokens are clinical Things a Principal may have findings about.\" .\n\n",
551    );
552
553    for (idx, (subject, rels)) in grouped.iter().enumerate() {
554        if idx >= max_shapes {
555            out.push_str(&format!(
556                "# ... truncated ({max_shapes} shapes shown; increase max_shapes for full export)\n"
557            ));
558            break;
559        }
560        let rid_local = local_name(subject);
561        let shape = format!("radlex:{rid_local}Shape");
562        let target = curie_for_uri(subject);
563        out.push_str(&format!(
564            "{shape} a sh:NodeShape ;\n    sh:targetClass {target} ;\n    sh:class radlex:AnatomicalEntity"
565        ));
566        for rel in rels {
567            let pred = format!("radlex:{}", rel.predicate_local);
568            let obj = curie_for_uri(&rel.object_rid);
569            out.push_str(&format!(
570                " ;\n    sh:property [ sh:path {pred} ; sh:hasValue {obj} ]"
571            ));
572        }
573        out.push_str(" .\n\n");
574    }
575
576    out.push_str(
577        "q42:PrincipalRadLexFindingShape a sh:NodeShape ;\n\
578    sh:targetClass q42:Principal ;\n\
579    sh:property [\n\
580        sh:path q42:hasFinding ;\n\
581        sh:class radlex:AnatomicalEntity ;\n\
582        sh:minCount 0 ;\n\
583        sh:message \"RadLex findings attach to a Principal; the Principal is not an anatomical entity.\" ;\n\
584    ] .\n\n",
585    );
586
587    out
588}
589
590/// Write agency baseline + converted ontologies to an output directory.
591pub fn write_anatomy_shape_bundle(
592    healthcare_owl: Option<&Path>,
593    radlex_owl: Option<&Path>,
594    out_dir: &Path,
595    radlex_max_shapes: usize,
596    radlex_max_relations: usize,
597) -> Result<Vec<String>, OwlToShaclError> {
598    fs::create_dir_all(out_dir).map_err(|e| OwlToShaclError::Io(e.to_string()))?;
599    let mut written = Vec::new();
600
601    let agency_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("shapes/qualia-agency.shacl.ttl");
602    let agency_dst = out_dir.join("qualia-agency.shacl.ttl");
603    fs::copy(&agency_src, &agency_dst).map_err(|e| OwlToShaclError::Io(e.to_string()))?;
604    written.push(agency_dst.display().to_string());
605
606    if let Some(path) = healthcare_owl {
607        let model = parse_healthcare_owl(path)?;
608        let ttl = healthcare_owl_to_shacl_ttl(&model);
609        let dst = out_dir.join("dicom-healthcare.shacl.ttl");
610        write_text(&dst, &ttl)?;
611        written.push(dst.display().to_string());
612    }
613
614    if let Some(path) = radlex_owl {
615        let relations = parse_radlex_relations_xml(path, radlex_max_relations)?;
616        let ttl = radlex_relations_to_shacl_ttl(&relations, radlex_max_shapes);
617        let dst = out_dir.join("radlex-anatomy.shacl.ttl");
618        write_text(&dst, &ttl)?;
619        written.push(dst.display().to_string());
620    }
621
622    Ok(written)
623}
624
625/// Write `content` to `path` verbatim (create/truncate), mapping I/O
626/// failures to `OwlToShaclError::Io`.
627fn write_text(path: &Path, content: &str) -> Result<(), OwlToShaclError> {
628    let mut f = File::create(path).map_err(|e| OwlToShaclError::Io(e.to_string()))?;
629    f.write_all(content.as_bytes())
630        .map_err(|e| OwlToShaclError::Io(e.to_string()))
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    fn fixture_healthcare() -> Option<std::path::PathBuf> {
638        let manifest = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
639        for candidate in [
640            manifest.join("../../app-development/2015-01-11.n3"),
641            std::path::PathBuf::from("app-development/2015-01-11.n3"),
642        ] {
643            if candidate.is_file() {
644                return candidate.canonicalize().ok().or(Some(candidate));
645            }
646        }
647        None
648    }
649
650    fn fixture_radlex() -> Option<std::path::PathBuf> {
651        let manifest = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
652        for candidate in [
653            manifest.join("../../app-development/PunRadLex_Owl4.3/PunRadLex4.3.owl"),
654            std::path::PathBuf::from("app-development/PunRadLex_Owl4.3/PunRadLex4.3.owl"),
655        ] {
656            if candidate.is_file() {
657                return candidate.canonicalize().ok().or(Some(candidate));
658            }
659        }
660        None
661    }
662
663    #[test]
664    fn healthcare_owl_parses_and_emits_ie_shapes() {
665        let Some(path) = fixture_healthcare() else {
666            eprintln!("skip: 2015-01-11.n3 not present");
667            return;
668        };
669        let model = parse_healthcare_owl(&path).expect("parse healthcare owl");
670        assert!(!model.classes.is_empty());
671        assert!(!model.properties.is_empty());
672        let ttl = healthcare_owl_to_shacl_ttl(&model);
673        assert!(ttl.contains("hc:IE.ImagePropertyShape"));
674        assert!(ttl.contains("q42:PrincipalImagingLinkShape"));
675        assert!(ttl.contains("sh:targetClass q42:Principal"));
676    }
677
678    #[test]
679    fn radlex_xml_parses_part_of_relations() {
680        let Some(path) = fixture_radlex() else {
681            eprintln!("skip: PunRadLex4.3.owl not present");
682            return;
683        };
684        let rels = parse_radlex_relations_xml(&path, 64).expect("parse radlex");
685        assert!(!rels.is_empty());
686        assert!(rels.iter().any(|r| r.predicate_local == "Part_Of"));
687        let ttl = radlex_relations_to_shacl_ttl(&rels, 8);
688        assert!(ttl.contains("radlex:AnatomicalEntity"));
689        assert!(ttl.contains("q42:PrincipalRadLexFindingShape"));
690        assert!(ttl.contains("sh:targetClass q42:Principal"));
691    }
692
693    #[test]
694    fn agency_shape_file_exists() {
695        let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
696            .join("shapes/qualia-agency.shacl.ttl");
697        let text = fs::read_to_string(p).unwrap();
698        assert!(text.contains("q42:PrincipalShape"));
699        assert!(text.contains("sh:not"));
700        assert!(text.contains("q42:hasCondition"));
701    }
702
703    /// Regression guard for the human-centric PRIMITIVE: a natural person must be
704    /// grounded in RDFS (rdfs:Class), never in OWL (owl:Class) — because under OWL
705    /// semantics every owl:Class individual is implicitly an owl:Thing, which reduces
706    /// a person to a "thing". This invariant was reverted once by a careless agent and
707    /// only caught by manual inspection; this test stops that recurring silently.
708    #[test]
709    fn principal_is_rdfs_grounded_not_owl_thing() {
710        let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
711            .join("shapes/qualia-agency.shacl.ttl");
712        let text = fs::read_to_string(p).unwrap();
713
714        // The Principal (and the native q42 classes) MUST be rdfs:Class, never owl:Class.
715        assert!(
716            text.contains("q42:Principal a rdfs:Class"),
717            "q42:Principal must be grounded as rdfs:Class (a natural person is not an owl:Thing)"
718        );
719        assert!(
720            !text.contains("q42:Principal a owl:Class"),
721            "q42:Principal must NOT be declared a owl:Class — that re-imports owl:Thing semantics"
722        );
723
724        // owl: may appear ONLY as a guard target (sh:not owl:Thing), never as a person's type.
725        assert!(
726            text.contains("A Principal must not be typed as owl:Thing"),
727            "the sh:not owl:Thing dignity guard must remain"
728        );
729
730        // The native vocabulary uses rdf:Property, not owl:ObjectProperty.
731        assert!(
732            !text.contains("a owl:ObjectProperty"),
733            "native possession relations must be rdf:Property, not owl:ObjectProperty"
734        );
735    }
736
737    /// The `.q42` format lexicon must register SHACL (`sh`) as a first-class prefix —
738    /// SHACL is the enforcement layer for the human-centric primitive, so the format
739    /// must be able to name it (it was previously omitted while owl: was registered).
740    #[test]
741    fn q42_lexicon_registers_shacl_prefix() {
742        let ctx = crate::q42_lexicon::Q42Context::new();
743        assert_eq!(
744            ctx.vocabulary.get("sh").map(String::as_str),
745            Some("http://www.w3.org/ns/shacl#"),
746            "q42 context must register the SHACL (sh:) namespace"
747        );
748        assert_eq!(
749            ctx.vocabulary.get("hcai").map(String::as_str),
750            Some("http://www.w3.org/ns/hcai#"),
751            "q42 context must register the human-centric (hcai:) namespace"
752        );
753    }
754}