Skip to main content

tensorlogic_oxirs_bridge/
lib.rs

1//! OxiRS Bridge: RDF*/SHACL/GraphQL → TensorLogic Integration
2//!
3//! **Version**: 0.1.0-beta.1 | **Status**: Production Ready
4//!
5//! This crate provides comprehensive bidirectional integration between RDF knowledge graphs
6//! and TensorLogic's tensor-based logical reasoning system. It enables semantic web data
7//! to be compiled into tensor operations while preserving provenance and validation semantics.
8//!
9//! # Overview
10//!
11//! The bridge connects five key components:
12//!
13//! 1. **Schema Import**: RDF/OWL schemas → TensorLogic [`SymbolTable`](tensorlogic_adapters::SymbolTable)
14//! 2. **Constraint Compilation**: SHACL shapes → TensorLogic [`TLExpr`](tensorlogic_ir::TLExpr) rules
15//! 3. **Provenance Tracking**: RDF entities ↔ tensor indices with RDF* metadata
16//! 4. **Validation**: SHACL-compliant validation reports from tensor outputs
17//! 5. **GraphQL Integration**: GraphQL schemas → TensorLogic domains/predicates
18//!
19//! # Quick Start
20//!
21//! ```
22//! use tensorlogic_oxirs_bridge::SchemaAnalyzer;
23//! use anyhow::Result;
24//!
25//! fn main() -> Result<()> {
26//!     // Define an RDF schema
27//!     let turtle = r#"
28//!         @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
29//!         @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
30//!         @prefix ex: <http://example.org/> .
31//!
32//!         ex:Person a rdfs:Class ;
33//!                   rdfs:label "Person" .
34//!
35//!         ex:knows a rdf:Property ;
36//!                  rdfs:domain ex:Person ;
37//!                  rdfs:range ex:Person .
38//!     "#;
39//!
40//!     // Parse and analyze the schema
41//!     let mut analyzer = SchemaAnalyzer::new();
42//!     analyzer.load_turtle(turtle)?;
43//!     analyzer.analyze()?;
44//!
45//!     // Convert to TensorLogic symbol table
46//!     let symbol_table = analyzer.to_symbol_table()?;
47//!     println!("Converted {} classes and {} properties",
48//!              symbol_table.domains.len(),
49//!              symbol_table.predicates.len());
50//!     Ok(())
51//! }
52//! ```
53//!
54//! # Key Features
55//!
56//! ## RDF/OWL Schema Support
57//!
58//! - **RDFS**: Classes, properties, subclass/subproperty hierarchies
59//! - **OWL**: Class expressions, property characteristics, restrictions
60//! - **RDFS Inference**: Automatic entailment and materialization
61//! - **Formats**: Turtle, N-Triples, JSON-LD
62//!
63//! ### SHACL Validation
64//! - **Constraint Types**: 15+ SHACL constraint types (minCount, pattern, datatype, etc.)
65//! - **Logical Operators**: sh:and, sh:or, sh:not, sh:xone
66//! - **Validation Reports**: Full SHACL-compliant reports with severity levels
67//! - **Export**: Turtle and JSON export formats
68//!
69//! ### SPARQL 1.1 Query Support
70//! - **Query Types**: SELECT, ASK, DESCRIBE, CONSTRUCT
71//! - **Graph Patterns**: OPTIONAL (left-outer join), UNION (disjunction)
72//! - **Filters**: Comparison operators, BOUND, isIRI, isLiteral, regex
73//! - **Solution Modifiers**: DISTINCT, LIMIT, OFFSET, ORDER BY
74//! - **Compilation**: Full compilation to TensorLogic expressions
75//!
76//! ## Performance Features
77//!
78//! - **Triple Indexing**: O(1) lookups by subject/predicate/object
79//! - **Caching**: In-memory and file-based caching (10-50x speedup)
80//! - **Metadata**: Multilingual label preservation and quality checking
81//!
82//! ## Provenance & Tracking
83//!
84//! - **RDF* Support**: Statement-level metadata with quoted triples
85//! - **Bidirectional Mapping**: Entities ↔ tensor indices
86//! - **Confidence Tracking**: Confidence scores for inferred statements
87//! - **Rule Attribution**: Track which rules produced which results
88//!
89//! # Architecture
90//!
91//! ```text
92//! ┌─────────────────────────────────────────────────────────────┐
93//! │                     Input Formats                            │
94//! │  Turtle │ N-Triples │ JSON-LD │ GraphQL │ SHACL              │
95//! └────────────┬────────────────────────────────────────────────┘
96//!              │
97//!              ▼
98//! ┌─────────────────────────────────────────────────────────────┐
99//! │                  SchemaAnalyzer                              │
100//! │  • Parse RDF triples                                         │
101//! │  • Extract classes & properties                              │
102//! │  • Build indexes (optional)                                  │
103//! │  • Preserve metadata (optional)                              │
104//! └────────────┬────────────────────────────────────────────────┘
105//!              │
106//!              ▼
107//! ┌─────────────────────────────────────────────────────────────┐
108//! │                  SymbolTable                                 │
109//! │  • Domains (from classes)                                    │
110//! │  • Predicates (from properties)                              │
111//! │  • Axis metadata                                             │
112//! └────────────┬────────────────────────────────────────────────┘
113//!              │
114//!              ▼
115//! ┌─────────────────────────────────────────────────────────────┐
116//! │              TensorLogic Compiler                            │
117//! │  • TLExpr (logical expressions)                              │
118//! │  • Tensor operations                                         │
119//! │  • Provenance tracking                                       │
120//! └─────────────────────────────────────────────────────────────┘
121//! ```
122//!
123//! # Examples
124//!
125//! ## With Performance Features
126//!
127//! ```
128//! use tensorlogic_oxirs_bridge::SchemaAnalyzer;
129//! use anyhow::Result;
130//!
131//! fn main() -> Result<()> {
132//!     // Enable indexing and metadata preservation
133//!     let mut analyzer = SchemaAnalyzer::new()
134//!         .with_indexing()
135//!         .with_metadata();
136//!
137//!     analyzer.load_turtle(r#"
138//!         @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
139//!         @prefix ex: <http://example.org/> .
140//!
141//!         ex:Person rdfs:label "Person"@en, "Personne"@fr .
142//!     "#)?;
143//!
144//!     // Fast indexed lookup
145//!     if let Some(index) = analyzer.index() {
146//!         let triples = index.find_by_subject("http://example.org/Person");
147//!         println!("Found {} triples", triples.len());
148//!     }
149//!
150//!     // Multilingual metadata
151//!     if let Some(metadata) = analyzer.metadata() {
152//!         if let Some(meta) = metadata.get("http://example.org/Person") {
153//!             println!("EN: {}", meta.get_label(Some("en")).unwrap_or("N/A"));
154//!             println!("FR: {}", meta.get_label(Some("fr")).unwrap_or("N/A"));
155//!         }
156//!     }
157//!     Ok(())
158//! }
159//! ```
160//!
161//! ## SHACL Validation
162//!
163//! ```
164//! use tensorlogic_oxirs_bridge::{ShaclConverter, SchemaAnalyzer};
165//! use tensorlogic_adapters::SymbolTable;
166//! use anyhow::Result;
167//!
168//! fn main() -> Result<()> {
169//!     let shacl = r#"
170//!         @prefix sh: <http://www.w3.org/ns/shacl#> .
171//!         @prefix ex: <http://example.org/> .
172//!         @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
173//!
174//!         ex:PersonShape a sh:NodeShape ;
175//!             sh:targetClass ex:Person ;
176//!             sh:property [
177//!                 sh:path ex:name ;
178//!                 sh:minCount 1 ;
179//!                 sh:datatype xsd:string ;
180//!             ] .
181//!     "#;
182//!
183//!     let symbol_table = SymbolTable::new();
184//!     let mut converter = ShaclConverter::new(symbol_table);
185//!     converter.parse_shapes(shacl)?;
186//!
187//!     println!("Parsed SHACL shapes successfully");
188//!     Ok(())
189//! }
190//! ```
191//!
192//! ## Caching for Performance
193//!
194//! ```
195//! use tensorlogic_oxirs_bridge::{SchemaCache, SchemaAnalyzer};
196//! use anyhow::Result;
197//!
198//! fn main() -> Result<()> {
199//!     let mut cache = SchemaCache::new();
200//!     let turtle = "@prefix ex: <http://example.org/> .";
201//!
202//!     // First access - cache miss
203//!     let table = if let Some(cached) = cache.get_symbol_table(turtle) {
204//!         cached
205//!     } else {
206//!         let mut analyzer = SchemaAnalyzer::new();
207//!         analyzer.load_turtle(turtle)?;
208//!         analyzer.analyze()?;
209//!         let table = analyzer.to_symbol_table()?;
210//!         cache.put_symbol_table(turtle, table.clone());
211//!         table
212//!     };
213//!
214//!     // Second access - cache hit (20-50x faster!)
215//!     assert!(cache.get_symbol_table(turtle).is_some());
216//!     Ok(())
217//! }
218//! ```
219//!
220//! # Module Organization
221//!
222//! - [`schema`] - Core RDF schema parsing and analysis
223//!   - [`cache`](schema::cache) - Caching for performance
224//!   - [`index`](schema::index) - Triple indexing for fast lookups
225//!   - [`metadata`](schema::metadata) - Multilingual metadata management
226//!   - [`owl`](schema::owl) - OWL ontology support
227//!   - [`inference`](schema::inference) - RDFS inference engine
228//! - [`shacl`] - SHACL constraint compilation and validation
229//! - [`rdfstar`] - RDF* provenance tracking
230//! - [`graphql`] - GraphQL schema integration
231//! - [`sparql`] - SPARQL 1.1 query compilation (SELECT/ASK/DESCRIBE/CONSTRUCT + OPTIONAL/UNION)
232//!
233//! # See Also
234//!
235//! - [Examples directory](https://github.com/cool-japan/tensorlogic/tree/main/crates/tensorlogic-oxirs-bridge/examples) - Comprehensive examples
236//! - [TensorLogic project](https://github.com/cool-japan/tensorlogic) - Main project repository
237//! - [OxiRS](https://github.com/cool-japan/oxirs) - Full RDF/SPARQL support
238//!
239//! # Implementation Note
240//!
241//! This is a **lightweight implementation** using only `oxrdf` and `oxttl` for RDF parsing.
242//! For full SPARQL query execution, federation, and advanced RDF features, use the `oxirs-core` crate.
243
244mod compilation;
245mod error;
246pub mod graphql;
247pub mod knowledge_embeddings;
248pub mod oxirs_executor;
249pub mod oxirs_graphql;
250mod provenance;
251pub mod rdfstar;
252pub mod schema;
253pub mod shacl;
254pub mod sparql;
255
256#[cfg(test)]
257mod rdfstar_tests;
258#[cfg(test)]
259mod tests;
260
261pub use compilation::compile_rules;
262pub use error::{BridgeError, ParseLocation};
263pub use graphql::{DirectiveValue, GraphQLConverter, GraphQLDirective};
264pub use knowledge_embeddings::{
265    cosine_similarity, euclidean_distance, EmbeddingConfig, EmbeddingModel, KGTriple,
266    KnowledgeEmbeddings,
267};
268pub use oxirs_executor::{OxirsSparqlExecutor, QueryResults, QueryValue, TripleResult};
269pub use oxirs_graphql::{GraphQLField, GraphQLObjectType, GraphQLType, OxirsGraphQLBridge};
270pub use provenance::ProvenanceTracker;
271pub use rdfstar::{
272    MetadataBuilder, ProvenanceStats, QuotedTriple, RdfStarProvenanceStore, StatementMetadata,
273};
274pub use schema::{
275    cache::{CacheStats, PersistentCache, SchemaCache},
276    index::{IndexStats, TripleIndex},
277    inference::{InferenceStats, RdfsInferenceEngine},
278    jsonld::JsonLdContext,
279    metadata::{EntityMetadata, LangString, MetadataStats, MetadataStore},
280    nquads::{NQuadsProcessor, Quad},
281    owl::{OwlClassInfo, OwlPropertyCharacteristics, OwlPropertyInfo, OwlRestriction},
282    streaming::{StreamAnalyzer, StreamStats, StreamingRdfLoader},
283    ClassInfo, PropertyInfo, SchemaAnalyzer,
284};
285pub use shacl::{
286    validation::{ShaclValidator, ValidationReport, ValidationResult, ValidationSeverity},
287    ShaclConverter,
288};
289pub use sparql::{
290    AggregateFunction, FilterCondition, PatternElement, SelectElement, SparqlCompiler, SparqlQuery,
291    TriplePattern,
292};