Skip to main content

Crate tensorlogic_oxirs_bridge

Crate tensorlogic_oxirs_bridge 

Source
Expand description

OxiRS Bridge: RDF*/SHACL/GraphQL → TensorLogic Integration

Version: 0.1.0 | Status: Production Ready

This crate provides comprehensive bidirectional integration between RDF knowledge graphs and TensorLogic’s tensor-based logical reasoning system. It enables semantic web data to be compiled into tensor operations while preserving provenance and validation semantics.

§Overview

The bridge connects five key components:

  1. Schema Import: RDF/OWL schemas → TensorLogic SymbolTable
  2. Constraint Compilation: SHACL shapes → TensorLogic TLExpr rules
  3. Provenance Tracking: RDF entities ↔ tensor indices with RDF* metadata
  4. Validation: SHACL-compliant validation reports from tensor outputs
  5. GraphQL Integration: GraphQL schemas → TensorLogic domains/predicates

§Quick Start

use tensorlogic_oxirs_bridge::SchemaAnalyzer;
use anyhow::Result;

fn main() -> Result<()> {
    // Define an RDF schema
    let turtle = r#"
        @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
        @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
        @prefix ex: <http://example.org/> .

        ex:Person a rdfs:Class ;
                  rdfs:label "Person" .

        ex:knows a rdf:Property ;
                 rdfs:domain ex:Person ;
                 rdfs:range ex:Person .
    "#;

    // Parse and analyze the schema
    let mut analyzer = SchemaAnalyzer::new();
    analyzer.load_turtle(turtle)?;
    analyzer.analyze()?;

    // Convert to TensorLogic symbol table
    let symbol_table = analyzer.to_symbol_table()?;
    println!("Converted {} classes and {} properties",
             symbol_table.domains.len(),
             symbol_table.predicates.len());
    Ok(())
}

§Key Features

§RDF/OWL Schema Support

  • RDFS: Classes, properties, subclass/subproperty hierarchies
  • OWL: Class expressions, property characteristics, restrictions
  • RDFS Inference: Automatic entailment and materialization
  • Formats: Turtle, N-Triples, JSON-LD

§SHACL Validation

  • Constraint Types: 15+ SHACL constraint types (minCount, pattern, datatype, etc.)
  • Logical Operators: sh:and, sh:or, sh:not, sh:xone
  • Validation Reports: Full SHACL-compliant reports with severity levels
  • Export: Turtle and JSON export formats

§SPARQL 1.1 Query Support

  • Query Types: SELECT, ASK, DESCRIBE, CONSTRUCT
  • Graph Patterns: OPTIONAL (left-outer join), UNION (disjunction)
  • Filters: Comparison operators, BOUND, isIRI, isLiteral, regex
  • Solution Modifiers: DISTINCT, LIMIT, OFFSET, ORDER BY
  • Compilation: Full compilation to TensorLogic expressions

§Performance Features

  • Triple Indexing: O(1) lookups by subject/predicate/object
  • Caching: In-memory and file-based caching (10-50x speedup)
  • Metadata: Multilingual label preservation and quality checking

§Provenance & Tracking

  • RDF Support*: Statement-level metadata with quoted triples
  • Bidirectional Mapping: Entities ↔ tensor indices
  • Confidence Tracking: Confidence scores for inferred statements
  • Rule Attribution: Track which rules produced which results

§Architecture

┌─────────────────────────────────────────────────────────────┐
│                     Input Formats                            │
│  Turtle │ N-Triples │ JSON-LD │ GraphQL │ SHACL              │
└────────────┬────────────────────────────────────────────────┘
             │
             ▼
┌─────────────────────────────────────────────────────────────┐
│                  SchemaAnalyzer                              │
│  • Parse RDF triples                                         │
│  • Extract classes & properties                              │
│  • Build indexes (optional)                                  │
│  • Preserve metadata (optional)                              │
└────────────┬────────────────────────────────────────────────┘
             │
             ▼
┌─────────────────────────────────────────────────────────────┐
│                  SymbolTable                                 │
│  • Domains (from classes)                                    │
│  • Predicates (from properties)                              │
│  • Axis metadata                                             │
└────────────┬────────────────────────────────────────────────┘
             │
             ▼
┌─────────────────────────────────────────────────────────────┐
│              TensorLogic Compiler                            │
│  • TLExpr (logical expressions)                              │
│  • Tensor operations                                         │
│  • Provenance tracking                                       │
└─────────────────────────────────────────────────────────────┘

§Examples

§With Performance Features

use tensorlogic_oxirs_bridge::SchemaAnalyzer;
use anyhow::Result;

fn main() -> Result<()> {
    // Enable indexing and metadata preservation
    let mut analyzer = SchemaAnalyzer::new()
        .with_indexing()
        .with_metadata();

    analyzer.load_turtle(r#"
        @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
        @prefix ex: <http://example.org/> .

        ex:Person rdfs:label "Person"@en, "Personne"@fr .
    "#)?;

    // Fast indexed lookup
    if let Some(index) = analyzer.index() {
        let triples = index.find_by_subject("http://example.org/Person");
        println!("Found {} triples", triples.len());
    }

    // Multilingual metadata
    if let Some(metadata) = analyzer.metadata() {
        if let Some(meta) = metadata.get("http://example.org/Person") {
            println!("EN: {}", meta.get_label(Some("en")).unwrap_or("N/A"));
            println!("FR: {}", meta.get_label(Some("fr")).unwrap_or("N/A"));
        }
    }
    Ok(())
}

§SHACL Validation

use tensorlogic_oxirs_bridge::{ShaclConverter, SchemaAnalyzer};
use tensorlogic_adapters::SymbolTable;
use anyhow::Result;

fn main() -> Result<()> {
    let shacl = r#"
        @prefix sh: <http://www.w3.org/ns/shacl#> .
        @prefix ex: <http://example.org/> .
        @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

        ex:PersonShape a sh:NodeShape ;
            sh:targetClass ex:Person ;
            sh:property [
                sh:path ex:name ;
                sh:minCount 1 ;
                sh:datatype xsd:string ;
            ] .
    "#;

    let symbol_table = SymbolTable::new();
    let mut converter = ShaclConverter::new(symbol_table);
    converter.parse_shapes(shacl)?;

    println!("Parsed SHACL shapes successfully");
    Ok(())
}

§Caching for Performance

use tensorlogic_oxirs_bridge::{SchemaCache, SchemaAnalyzer};
use anyhow::Result;

fn main() -> Result<()> {
    let mut cache = SchemaCache::new();
    let turtle = "@prefix ex: <http://example.org/> .";

    // First access - cache miss
    let table = if let Some(cached) = cache.get_symbol_table(turtle) {
        cached
    } else {
        let mut analyzer = SchemaAnalyzer::new();
        analyzer.load_turtle(turtle)?;
        analyzer.analyze()?;
        let table = analyzer.to_symbol_table()?;
        cache.put_symbol_table(turtle, table.clone());
        table
    };

    // Second access - cache hit (20-50x faster!)
    assert!(cache.get_symbol_table(turtle).is_some());
    Ok(())
}

§Module Organization

  • schema - Core RDF schema parsing and analysis
    • cache - Caching for performance
    • index - Triple indexing for fast lookups
    • metadata - Multilingual metadata management
    • owl - OWL ontology support
    • inference - RDFS inference engine
  • shacl - SHACL constraint compilation and validation
  • rdfstar - RDF* provenance tracking
  • graphql - GraphQL schema integration
  • sparql - SPARQL 1.1 query compilation (SELECT/ASK/DESCRIBE/CONSTRUCT + OPTIONAL/UNION)

§See Also

§Implementation Note

This is a lightweight implementation using only oxrdf and oxttl for RDF parsing. For full SPARQL query execution, federation, and advanced RDF features, use the oxirs-core crate.

Re-exports§

pub use blank_node::BlankNodeManager;
pub use execute_validate::ExecutionResult;
pub use execute_validate::ExecutionStats;
pub use execute_validate::ExecutionTensor;
pub use execute_validate::ValidationExecutor;
pub use execute_validate::ValidationExecutorConfig;
pub use execute_validate::ValidationExecutorError;
pub use graph_stats::connected_components;
pub use graph_stats::predicate_statistics;
pub use graph_stats::DegreeDistribution;
pub use graph_stats::GraphStats;
pub use graph_stats::PredicateStats;
pub use graphql::DirectiveValue;
pub use graphql::GraphQLConverter;
pub use graphql::GraphQLDirective;
pub use json_ld::build_entity_node;
pub use json_ld::context_from_expr;
pub use json_ld::context_from_predicates;
pub use json_ld::expr_to_json_ld_node;
pub use json_ld::standard_prefixes_context;
pub use json_ld::validate_document;
pub use json_ld::ContextTerm as TlContextTerm;
pub use json_ld::JsonLdError as TlJsonLdError;
pub use json_ld::JsonLdValue;
pub use json_ld::TlJsonLdContext;
pub use json_ld::TlJsonLdDocument;
pub use json_ld::TlJsonLdNode;
pub use knowledge_embeddings::cosine_similarity;
pub use knowledge_embeddings::euclidean_distance;
pub use knowledge_embeddings::EmbeddingConfig;
pub use knowledge_embeddings::EmbeddingModel;
pub use knowledge_embeddings::KGTriple;
pub use knowledge_embeddings::KnowledgeEmbeddings;
pub use ontology_diff::compare_symbol_tables;
pub use ontology_diff::DiffEntry;
pub use ontology_diff::OntologyDiff;
pub use oxirs_executor::OxirsSparqlExecutor;
pub use oxirs_executor::QueryResults;
pub use oxirs_executor::QueryValue;
pub use oxirs_executor::TripleResult;
pub use oxirs_graphql::GraphQLField;
pub use oxirs_graphql::GraphQLObjectType;
pub use oxirs_graphql::GraphQLType;
pub use oxirs_graphql::OxirsGraphQLBridge;
pub use property_path::PathError;
pub use property_path::PropertyPath;
pub use property_path::PropertyPathExpander;
pub use property_path::TripleStore;
pub use quad_store::QuadStore;
pub use rdf_bulk_io::BulkFormat;
pub use rdf_bulk_io::BulkIoError;
pub use rdf_bulk_io::BulkIoStats;
pub use rdf_bulk_io::NamespaceRegistry;
pub use rdf_bulk_io::RdfBulkExporter;
pub use rdf_bulk_io::RdfBulkImporter;
pub use rdf_bulk_io::RdfTriple;
pub use rdfstar::MetadataBuilder;
pub use rdfstar::ProvenanceStats;
pub use rdfstar::QuotedTriple;
pub use rdfstar::RdfStarProvenanceStore;
pub use rdfstar::StatementMetadata;
pub use schema::cache::CacheStats;
pub use schema::cache::PersistentCache;
pub use schema::cache::SchemaCache;
pub use schema::index::IndexStats;
pub use schema::index::TripleIndex;
pub use schema::inference::InferenceStats;
pub use schema::inference::RdfsInferenceEngine;
pub use schema::jsonld::JsonLdContext;
pub use schema::metadata::EntityMetadata;
pub use schema::metadata::LangString;
pub use schema::metadata::MetadataStats;
pub use schema::metadata::MetadataStore;
pub use schema::nquads::NQuadsProcessor;
pub use schema::nquads::Quad;
pub use schema::owl::OwlClassInfo;
pub use schema::owl::OwlPropertyCharacteristics;
pub use schema::owl::OwlPropertyInfo;
pub use schema::owl::OwlRestriction;
pub use schema::streaming::StreamAnalyzer;
pub use schema::streaming::StreamStats;
pub use schema::streaming::StreamingRdfLoader;
pub use schema::ClassInfo;
pub use schema::PropertyInfo;
pub use schema::SchemaAnalyzer;
pub use shacl::validation::ShaclValidator;
pub use shacl::validation::ValidationReport;
pub use shacl::validation::ValidationResult;
pub use shacl::validation::ValidationSeverity;
pub use shacl::ReportExportError;
pub use shacl::ShaclConverter;
pub use shacl::ShaclReportExporter;
pub use shacl::ShaclReportFormat;
pub use sparql::AggregateFunction;
pub use sparql::BindExpr;
pub use sparql::FilterCondition;
pub use sparql::GraphPattern;
pub use sparql::PatternElement;
pub use sparql::SelectElement;
pub use sparql::SparqlCompiler;
pub use sparql::SparqlQuery;
pub use sparql::TriplePattern;
pub use sparql_builder::validate_variable_name;
pub use sparql_builder::AskQuery;
pub use sparql_builder::BuilderTriplePattern;
pub use sparql_builder::OrderDirection;
pub use sparql_builder::SelectQuery;
pub use sparql_builder::SparqlBuilderError;
pub use sparql_builder::SparqlFilter;
pub use sparql_builder::SparqlLiteral;
pub use sparql_builder::SparqlTerm;
pub use sparql_builder::WhereClause;
pub use sparql_builder::WhereClauseItem;
pub use sparql_gen::expr_to_sparql;
pub use sparql_gen::render_filter as sparql_gen_render_filter;
pub use sparql_gen::render_pattern as sparql_gen_render_pattern;
pub use sparql_gen::GraphPattern as SparqlGenGraphPattern;
pub use sparql_gen::SparqlExpr as SparqlGenExpr;
pub use sparql_gen::SparqlFilter as SparqlGenFilter;
pub use sparql_gen::SparqlGenConfig;
pub use sparql_gen::SparqlGenError;
pub use sparql_gen::SparqlQuery as SparqlGenQuery;
pub use sparql_gen::SparqlTerm as SparqlGenTerm;
pub use sparql_gen::TriplePattern as SparqlGenTriplePattern;
pub use turtle_export::TurtleExporter;
pub use validation_warnings::SchemaWarning;
pub use validation_warnings::SchemaWarningAnalyzer;
pub use validation_warnings::SchemaWarningKind;

Modules§

blank_node
Blank-node management: mint stable IRIs for anonymous RDF nodes.
execute_validate
Compile-execute-validate pipeline tying together TensorLogic rules and RDF.
graph_stats
RDF graph statistics and structural analysis.
graphql
GraphQL schema integration for TensorLogic
json_ld
JSON-LD context generation and document building for TensorLogic knowledge graph serialization.
knowledge_embeddings
Knowledge graph embeddings for TensorLogic integration.
ontology_diff
Ontology diff: compare two SymbolTables and report differences.
oxirs_executor
OxiRS SPARQL execution integration.
oxirs_graphql
GraphQL integration for RDF knowledge graphs.
property_path
SPARQL 1.1 property path query support.
quad_store
Multi-named-graph storage with per-graph query API.
rdf_bulk_io
RDF Bulk Import/Export for tensorlogic-oxirs-bridge
rdfstar
RDF* (RDF-star) support for statement-level metadata and provenance tracking.
schema
RDF schema analysis and conversion to TensorLogic types.
shacl
SHACL constraint parsing and conversion to TensorLogic rules.
sparql
Advanced SPARQL query compilation to TensorLogic operations
sparql_builder
Programmatic SPARQL query builder — a fluent builder API that constructs SPARQL query strings without requiring manual string formatting.
sparql_gen
SPARQL query generation from TLExpr logic expressions.
turtle_export
Turtle (.ttl) export for TensorLogic SymbolTable.
validation_warnings
Schema quality warnings for RDF/OWL schemas loaded into SchemaAnalyzer.

Structs§

ParseLocation
Parse location information for better error reporting
ProvenanceTracker
Provenance tracker: maps RDF entities to tensor computation graph

Enums§

BridgeError

Functions§

compile_rules
Compile multiple TLExpr rules into a single execution plan