tensorlogic_ir/lib.rs
1//! # TensorLogic IR
2//!
3//! **Engine-agnostic Abstract Syntax Tree & Intermediate Representation for TensorLogic**
4//!
5//! **Version**: 0.1.0-alpha.1 | **Status**: Production Ready
6//!
7//! This crate provides the core data structures and operations for representing logic-as-tensor
8//! computations in the TensorLogic framework. It serves as the foundational layer that all other
9//! TensorLogic components build upon.
10//!
11//! ## Overview
12//!
13//! TensorLogic IR enables the compilation of logical rules (predicates, quantifiers, implications)
14//! into **tensor equations (einsum graphs)** with a minimal DSL + IR. This approach allows for:
15//!
16//! - Neural, symbolic, and probabilistic models within a unified tensor computation framework
17//! - Engine-agnostic representation that can be executed on different backends
18//! - Static analysis and optimization of logical expressions before execution
19//! - Type-safe construction and validation of logical expressions
20//!
21//! ## Core Components
22//!
23//! ### Terms ([`Term`])
24//! Variables and constants that appear in logical expressions:
25//! - **Variables**: Free or bound variables (e.g., `x`, `y`, `Person`)
26//! - **Constants**: Concrete values (e.g., `alice`, `bob`, `42`)
27//! - **Typed terms**: Terms with explicit type annotations
28//!
29//! ### Logical Expressions ([`TLExpr`])
30//! The DSL for expressing logical rules:
31//! - **Predicates**: Atomic propositions like `Person(x)` or `knows(alice, bob)`
32//! - **Logical connectives**: AND (∧), OR (∨), NOT (¬), Implication (→)
33//! - **Quantifiers**: Existential (∃) and Universal (∀) with domain constraints
34//! - **Arithmetic**: Addition, subtraction, multiplication, division
35//! - **Comparisons**: Equality, less than, greater than, etc.
36//! - **Control flow**: If-then-else conditionals
37//!
38//! ### Tensor Computation Graphs ([`EinsumGraph`])
39//! The compiled IR representing tensor operations:
40//! - **Tensors**: Named tensor values with indices
41//! - **Nodes**: Operations on tensors (einsum, element-wise, reductions)
42//! - **Outputs**: Designated output tensors
43//! - **Validation**: Comprehensive graph validation and error checking
44//!
45//! ## Features
46//!
47//! ### Type System
48//! - Static type checking with [`PredicateSignature`] and [`TypeAnnotation`]
49//! - Arity validation ensures consistent predicate usage
50//! - Type inference and compatibility checking
51//!
52//! ### Domain Constraints
53//! - Domain management via [`DomainRegistry`] and [`DomainInfo`]
54//! - Built-in domains: Bool, Int, Real, Nat, Probability
55//! - Custom finite and infinite domains
56//! - Domain validation for quantified variables
57//!
58//! ### Metadata & Provenance
59//! - Source location tracking with [`SourceLocation`] and [`SourceSpan`]
60//! - Provenance information via [`Provenance`] for rule tracking
61//! - Custom metadata support for nodes and expressions
62//!
63//! ### Serialization
64//! - Full serde support for JSON and binary formats
65//! - Versioned serialization with [`VersionedExpr`] and [`VersionedGraph`]
66//! - Backward compatibility checking
67//!
68//! ### Analysis & Utilities
69//! - Free variable analysis
70//! - Predicate extraction and counting
71//! - Graph statistics with [`GraphStats`]
72//! - Expression statistics with [`ExprStats`]
73//! - Pretty printing and DOT export for visualization
74//! - Expression and graph diffing with [`diff_exprs`] and [`diff_graphs`]
75//!
76//! ## Quick Start
77//!
78//! ### Creating Logical Expressions
79//!
80//! ```rust
81//! use tensorlogic_ir::{TLExpr, Term};
82//!
83//! // Simple predicate: Person(x)
84//! let person = TLExpr::pred("Person", vec![Term::var("x")]);
85//!
86//! // Logical rule: ∀x. Person(x) → Mortal(x)
87//! let mortal = TLExpr::pred("Mortal", vec![Term::var("x")]);
88//! let rule = TLExpr::forall("x", "Entity", TLExpr::imply(person, mortal));
89//!
90//! // Verify no free variables (all bound by quantifier)
91//! assert!(rule.free_vars().is_empty());
92//! ```
93//!
94//! ### Building Computation Graphs
95//!
96//! ```rust
97//! use tensorlogic_ir::{EinsumGraph, EinsumNode};
98//!
99//! let mut graph = EinsumGraph::new();
100//!
101//! // Matrix multiplication: C = A @ B
102//! let a = graph.add_tensor("A");
103//! let b = graph.add_tensor("B");
104//! let c = graph.add_tensor("C");
105//!
106//! graph.add_node(EinsumNode::einsum("ik,kj->ij", vec![a, b], vec![c])).unwrap();
107//! graph.add_output(c).unwrap();
108//!
109//! // Validate the graph
110//! assert!(graph.validate().is_ok());
111//! ```
112//!
113//! ### Domain Management
114//!
115//! ```rust
116//! use tensorlogic_ir::{DomainRegistry, DomainInfo, TLExpr, Term};
117//!
118//! // Create registry with built-in domains
119//! let mut registry = DomainRegistry::with_builtins();
120//!
121//! // Add custom domain
122//! registry.register(DomainInfo::finite("Person", 100)).unwrap();
123//!
124//! // Create and validate expression
125//! let expr = TLExpr::exists("x", "Person", TLExpr::pred("P", vec![Term::var("x")]));
126//! assert!(expr.validate_domains(®istry).is_ok());
127//! ```
128//!
129//! ## Examples
130//!
131//! See the `examples/` directory for comprehensive demonstrations:
132//! - `00_basic_expressions`: Simple predicates and logical connectives
133//! - `01_quantifiers`: Existential and universal quantifiers
134//! - `02_arithmetic`: Arithmetic and comparison operations
135//! - `03_graph_construction`: Building computation graphs
136//! - `05_serialization`: JSON and binary serialization
137//! - `06_visualization`: Pretty printing and DOT export
138//!
139//! ## Architecture
140//!
141//! The crate is organized into focused modules:
142//! - **term**: Variables, constants, and type annotations
143//! - **expr**: Logical expressions and builders
144//! - **graph**: Tensor computation graphs and nodes
145//! - **domain**: Domain constraints and validation
146//! - **signature**: Type signatures for predicates
147//! - **metadata**: Provenance and source tracking
148//! - **[`serialization`]**: Versioned JSON/binary formats
149//! - **[`util`]**: Pretty printing and statistics
150//! - **[`diff`]**: Expression and graph comparison
151//! - **error**: Comprehensive error types
152//!
153//! ## Logic-to-Tensor Mapping
154//!
155//! | Logic Operation | Tensor Equivalent | Notes |
156//! |----------------|-------------------|-------|
157//! | `AND(a, b)` | `a * b` | Hadamard product (element-wise) |
158//! | `OR(a, b)` | `max(a, b)` | Or soft variant (configurable) |
159//! | `NOT(a)` | `1 - a` | Complement operation |
160//! | `∃x. P(x)` | `sum(P, axis=x)` | Or `max` for hard quantification |
161//! | `∀x. P(x)` | `NOT(∃x. NOT(P(x)))` | Dual of existential |
162//! | `a → b` | `ReLU(b - a)` | Soft implication |
163//!
164//! ## Performance
165//!
166//! - **Lazy validation**: Operations are validated only when explicitly requested
167//! - **Zero-copy indices**: Graph operations use tensor indices instead of cloning
168//! - **Incremental building**: Graphs can be built step-by-step efficiently
169//! - **Property tests**: 30 randomized tests ensure correctness
170//! - **Benchmarks**: 40+ performance tests measure all operations
171//!
172//! ## See Also
173//!
174//! - **tensorlogic-compiler**: Compiles TLExpr → EinsumGraph
175//! - **tensorlogic-infer**: Execution and autodiff traits
176//! - **tensorlogic-scirs-backend**: SciRS2-powered runtime execution
177//! - **tensorlogic-adapters**: Symbol tables and axis metadata
178
179pub mod diff;
180mod display;
181mod domain;
182mod error;
183mod expr;
184pub mod fuzzing;
185mod graph;
186mod metadata;
187pub mod serialization;
188mod signature;
189mod term;
190pub mod util;
191
192#[cfg(test)]
193mod tests;
194
195pub use diff::{diff_exprs, diff_graphs, ExprDiff, GraphDiff, NodeDiff};
196pub use domain::{DomainInfo, DomainRegistry, DomainType};
197pub use error::IrError;
198pub use expr::ac_matching::{
199 ac_equivalent, flatten_ac, normalize_ac, ACOperator, ACPattern, Multiset,
200};
201pub use expr::advanced_analysis::{ComplexityMetrics, OperatorCounts, PatternAnalysis};
202pub use expr::advanced_rewriting::{
203 AdvancedRewriteSystem, ConditionalRule, RewriteConfig, RewriteStats, RewriteStrategy,
204 RulePriority,
205};
206pub use expr::confluence::{
207 are_joinable, normalize, ConfluenceChecker, ConfluenceReport, CriticalPair,
208};
209pub use expr::defuzzification::{
210 bisector, centroid, defuzzify, largest_of_maximum, mean_of_maximum, smallest_of_maximum,
211 weighted_average, DefuzzificationMethod, FuzzySet, SingletonFuzzySet,
212};
213pub use expr::distributive_laws::{apply_distributive_laws, DistributiveStrategy};
214pub use expr::ltl_ctl_utilities::{
215 apply_advanced_ltl_equivalences, classify_temporal_formula, compute_temporal_complexity,
216 decompose_safety_liveness, extract_state_predicates, extract_temporal_subformulas,
217 identify_temporal_pattern, is_temporal, is_temporal_nnf, TemporalClass, TemporalComplexity,
218 TemporalPattern,
219};
220pub use expr::modal_axioms::{
221 apply_axiom_k, apply_axiom_t, extract_modal_subformulas, is_modal_free, is_theorem_in_system,
222 modal_depth, normalize_s5, verify_axiom_4, verify_axiom_5, verify_axiom_b, verify_axiom_d,
223 verify_axiom_k, verify_axiom_t, ModalSystem,
224};
225pub use expr::modal_equivalences::apply_modal_equivalences;
226pub use expr::normal_forms::{is_cnf, is_dnf, to_cnf, to_dnf, to_nnf};
227pub use expr::optimization::{
228 algebraic_simplify, constant_fold, optimize_expr, propagate_constants,
229};
230pub use expr::optimization_pipeline::{
231 OptimizationLevel, OptimizationMetrics, OptimizationPass, OptimizationPipeline, PipelineConfig,
232};
233pub use expr::probabilistic_reasoning::{
234 compute_tight_bounds, extract_probabilistic_semantics, mln_probability,
235 propagate_probabilities, CredalSet, ProbabilityInterval,
236};
237pub use expr::rewriting::{Pattern, RewriteRule, RewriteSystem};
238pub use expr::strategy_selector::{auto_optimize, ExpressionProfile, StrategySelector};
239pub use expr::temporal_equivalences::apply_temporal_equivalences;
240pub use expr::{
241 AggregateOp, FuzzyImplicationKind, FuzzyNegationKind, TCoNormKind, TLExpr, TNormKind,
242};
243pub use graph::cost_model::{
244 auto_annotate_costs, estimate_graph_cost, estimate_operation_cost, CostSummary, GraphCostModel,
245 OperationCost,
246};
247pub use graph::{
248 are_graphs_equivalent, canonical_hash, canonicalize_graph, export_to_dot,
249 export_to_dot_with_options, validate_graph, DotExportOptions, EinsumGraph, EinsumNode,
250 GraphValidationStats, OpType, ValidationError, ValidationErrorKind, ValidationReport,
251 ValidationWarning, ValidationWarningKind,
252};
253pub use metadata::{Metadata, Provenance, SourceLocation, SourceSpan};
254pub use serialization::{VersionedExpr, VersionedGraph, FORMAT_VERSION};
255pub use signature::{PredicateSignature, SignatureRegistry};
256pub use term::{Term, TypeAnnotation};
257pub use util::{pretty_print_expr, pretty_print_graph, ExprStats, GraphStats};