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
//! Domain product types for cross-domain reasoning.
//!
//! Product types allow combining multiple domains into composite types,
//! enabling predicates over tuples of values from different domains.
//!
//! # Examples
//!
//! ```rust
//! use tensorlogic_adapters::ProductDomain;
//!
//! // Create Person × Location product
//! let product = ProductDomain::new(vec!["Person".to_string(), "Location".to_string()]);
//! assert_eq!(product.components(), &["Person", "Location"]);
//!
//! // Nested product: (Person × Location) × Time
//! let nested = ProductDomain::new(vec![
//! product.to_string(),
//! "Time".to_string()
//! ]);
//! ```
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::{AdapterError, DomainInfo, SymbolTable};
/// A product domain representing a tuple of component domains.
///
/// Product domains enable cross-domain reasoning by creating composite types
/// from multiple base domains. The cardinality of a product domain is the
/// product of its component cardinalities.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::new(vec![
/// "Person".to_string(),
/// "Location".to_string()
/// ]);
///
/// assert_eq!(product.arity(), 2);
/// assert_eq!(product.to_string(), "Person × Location");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProductDomain {
/// Component domains in the product.
components: Vec<String>,
}
impl ProductDomain {
/// Create a new product domain from component domains.
///
/// # Panics
///
/// Panics if `components` has fewer than 2 elements.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::new(vec!["A".to_string(), "B".to_string()]);
/// assert_eq!(product.arity(), 2);
/// ```
pub fn new(components: Vec<String>) -> Self {
assert!(
components.len() >= 2,
"Product domain must have at least 2 components"
);
Self { components }
}
/// Create a binary product domain (A × B).
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::binary("Person", "Location");
/// assert_eq!(product.to_string(), "Person × Location");
/// ```
pub fn binary(a: impl Into<String>, b: impl Into<String>) -> Self {
Self::new(vec![a.into(), b.into()])
}
/// Create a ternary product domain (A × B × C).
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::ternary("Person", "Location", "Time");
/// assert_eq!(product.to_string(), "Person × Location × Time");
/// ```
pub fn ternary(a: impl Into<String>, b: impl Into<String>, c: impl Into<String>) -> Self {
Self::new(vec![a.into(), b.into(), c.into()])
}
/// Get the component domains.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::binary("A", "B");
/// assert_eq!(product.components(), &["A", "B"]);
/// ```
pub fn components(&self) -> &[String] {
&self.components
}
/// Get the arity (number of components) of this product.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::ternary("A", "B", "C");
/// assert_eq!(product.arity(), 3);
/// ```
pub fn arity(&self) -> usize {
self.components.len()
}
/// Compute the cardinality of this product domain.
///
/// Returns the product of component cardinalities, or an error if
/// any component domain is not found in the symbol table.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::{SymbolTable, DomainInfo, ProductDomain};
///
/// let mut table = SymbolTable::new();
/// table.add_domain(DomainInfo::new("A", 10)).expect("unwrap");
/// table.add_domain(DomainInfo::new("B", 20)).expect("unwrap");
///
/// let product = ProductDomain::binary("A", "B");
/// assert_eq!(product.cardinality(&table).expect("unwrap"), 200);
/// ```
pub fn cardinality(&self, table: &SymbolTable) -> Result<usize, AdapterError> {
let mut result = 1_usize;
for component in &self.components {
let domain = table
.get_domain(component)
.ok_or_else(|| AdapterError::UnknownDomain(component.clone()))?;
result = result.checked_mul(domain.cardinality).ok_or_else(|| {
AdapterError::InvalidCardinality(format!(
"Cardinality overflow in product domain: {}",
self
))
})?;
}
Ok(result)
}
/// Check if all component domains exist in the symbol table.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::{SymbolTable, DomainInfo, ProductDomain};
///
/// let mut table = SymbolTable::new();
/// table.add_domain(DomainInfo::new("A", 10)).expect("unwrap");
/// table.add_domain(DomainInfo::new("B", 20)).expect("unwrap");
///
/// let product = ProductDomain::binary("A", "B");
/// assert!(product.validate(&table).is_ok());
///
/// let invalid = ProductDomain::binary("A", "Unknown");
/// assert!(invalid.validate(&table).is_err());
/// ```
pub fn validate(&self, table: &SymbolTable) -> Result<(), AdapterError> {
for component in &self.components {
if table.get_domain(component).is_none() {
return Err(AdapterError::UnknownDomain(component.clone()));
}
}
Ok(())
}
/// Project to a specific component by index.
///
/// Returns the domain name of the component at the given index.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::ternary("A", "B", "C");
/// assert_eq!(product.project(0), Some("A"));
/// assert_eq!(product.project(1), Some("B"));
/// assert_eq!(product.project(2), Some("C"));
/// assert_eq!(product.project(3), None);
/// ```
pub fn project(&self, index: usize) -> Option<&str> {
self.components.get(index).map(|s| s.as_str())
}
/// Get a subproduct by slicing component indices.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let product = ProductDomain::new(vec![
/// "A".to_string(),
/// "B".to_string(),
/// "C".to_string(),
/// "D".to_string()
/// ]);
///
/// // Get middle two components (B × C)
/// let sub = product.slice(1, 3).expect("unwrap");
/// assert_eq!(sub.components(), &["B", "C"]);
/// ```
pub fn slice(&self, start: usize, end: usize) -> Result<ProductDomain, AdapterError> {
if start >= end || end > self.components.len() {
return Err(AdapterError::InvalidOperation(format!(
"Invalid slice indices: {}..{} for product of arity {}",
start,
end,
self.components.len()
)));
}
let components = self.components[start..end].to_vec();
Ok(ProductDomain::new(components))
}
/// Extend this product with additional components.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::ProductDomain;
///
/// let mut product = ProductDomain::binary("A", "B");
/// product.extend(vec!["C".to_string(), "D".to_string()]);
/// assert_eq!(product.arity(), 4);
/// ```
pub fn extend(&mut self, mut additional: Vec<String>) {
self.components.append(&mut additional);
}
}
impl fmt::Display for ProductDomain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.components.join(" × "))
}
}
impl From<Vec<String>> for ProductDomain {
fn from(components: Vec<String>) -> Self {
Self::new(components)
}
}
/// Extension trait for SymbolTable to support product domains.
pub trait ProductDomainExt {
/// Add a product domain to the symbol table.
///
/// The product domain's cardinality is computed from its components.
///
/// # Examples
///
/// ```rust
/// use tensorlogic_adapters::{SymbolTable, DomainInfo, ProductDomain, ProductDomainExt};
///
/// let mut table = SymbolTable::new();
/// table.add_domain(DomainInfo::new("Person", 100)).expect("unwrap");
/// table.add_domain(DomainInfo::new("Location", 50)).expect("unwrap");
///
/// let product = ProductDomain::binary("Person", "Location");
/// table.add_product_domain("PersonAtLocation", product).expect("unwrap");
///
/// let domain = table.get_domain("PersonAtLocation").expect("unwrap");
/// assert_eq!(domain.cardinality, 5000);
/// ```
fn add_product_domain(
&mut self,
name: impl Into<String>,
product: ProductDomain,
) -> Result<(), AdapterError>;
/// Get a product domain by name.
///
/// Returns `None` if the domain doesn't exist or is not a product domain.
fn get_product_domain(&self, name: &str) -> Option<&ProductDomain>;
/// List all product domains in the symbol table.
fn list_product_domains(&self) -> Vec<(&str, &ProductDomain)>;
}
impl ProductDomainExt for SymbolTable {
fn add_product_domain(
&mut self,
name: impl Into<String>,
product: ProductDomain,
) -> Result<(), AdapterError> {
let name = name.into();
// Validate that all component domains exist
product.validate(self)?;
// Compute cardinality
let cardinality = product.cardinality(self)?;
// Create domain info with product type metadata
let mut domain_info = DomainInfo::new(&name, cardinality);
domain_info.description = Some(format!("Product domain: {}", product));
// Store product domain metadata (we'll use a custom attribute)
if let Some(ref mut meta) = domain_info.metadata {
let components_json = serde_json::to_string(&product.components).map_err(|e| {
AdapterError::InvalidOperation(format!(
"Failed to serialize product components: {}",
e
))
})?;
meta.set_attribute("product_components", &components_json);
}
self.add_domain(domain_info)
.map_err(|_| AdapterError::DuplicateDomain(name.clone()))?;
Ok(())
}
fn get_product_domain(&self, name: &str) -> Option<&ProductDomain> {
// This is a simplified implementation
// In a real implementation, we'd store ProductDomain instances separately
// For now, we return None as a placeholder
let _domain = self.get_domain(name)?;
None
}
fn list_product_domains(&self) -> Vec<(&str, &ProductDomain)> {
// Simplified implementation
Vec::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_binary_product() {
let product = ProductDomain::binary("A", "B");
assert_eq!(product.arity(), 2);
assert_eq!(product.components(), &["A", "B"]);
assert_eq!(product.to_string(), "A × B");
}
#[test]
fn test_ternary_product() {
let product = ProductDomain::ternary("A", "B", "C");
assert_eq!(product.arity(), 3);
assert_eq!(product.to_string(), "A × B × C");
}
#[test]
fn test_cardinality() {
let mut table = SymbolTable::new();
table.add_domain(DomainInfo::new("A", 10)).expect("unwrap");
table.add_domain(DomainInfo::new("B", 20)).expect("unwrap");
table.add_domain(DomainInfo::new("C", 5)).expect("unwrap");
let product = ProductDomain::ternary("A", "B", "C");
assert_eq!(product.cardinality(&table).expect("unwrap"), 1000);
}
#[test]
fn test_validate_success() {
let mut table = SymbolTable::new();
table.add_domain(DomainInfo::new("A", 10)).expect("unwrap");
table.add_domain(DomainInfo::new("B", 20)).expect("unwrap");
let product = ProductDomain::binary("A", "B");
assert!(product.validate(&table).is_ok());
}
#[test]
fn test_validate_unknown_domain() {
let mut table = SymbolTable::new();
table.add_domain(DomainInfo::new("A", 10)).expect("unwrap");
let product = ProductDomain::binary("A", "Unknown");
assert!(product.validate(&table).is_err());
}
#[test]
fn test_project() {
let product = ProductDomain::ternary("A", "B", "C");
assert_eq!(product.project(0), Some("A"));
assert_eq!(product.project(1), Some("B"));
assert_eq!(product.project(2), Some("C"));
assert_eq!(product.project(3), None);
}
#[test]
fn test_slice() {
let product = ProductDomain::new(vec![
"A".to_string(),
"B".to_string(),
"C".to_string(),
"D".to_string(),
]);
let sub = product.slice(1, 3).expect("unwrap");
assert_eq!(sub.components(), &["B", "C"]);
assert_eq!(sub.to_string(), "B × C");
}
#[test]
fn test_slice_invalid() {
let product = ProductDomain::binary("A", "B");
assert!(product.slice(0, 3).is_err());
assert!(product.slice(2, 1).is_err());
}
#[test]
fn test_extend() {
let mut product = ProductDomain::binary("A", "B");
product.extend(vec!["C".to_string(), "D".to_string()]);
assert_eq!(product.arity(), 4);
assert_eq!(product.to_string(), "A × B × C × D");
}
#[test]
fn test_add_product_domain() {
let mut table = SymbolTable::new();
table
.add_domain(DomainInfo::new("Person", 100))
.expect("unwrap");
table
.add_domain(DomainInfo::new("Location", 50))
.expect("unwrap");
let product = ProductDomain::binary("Person", "Location");
table
.add_product_domain("PersonAtLocation", product)
.expect("unwrap");
let domain = table.get_domain("PersonAtLocation").expect("unwrap");
assert_eq!(domain.cardinality, 5000);
assert!(domain
.description
.as_ref()
.expect("unwrap")
.contains("Product domain"));
}
#[test]
#[should_panic(expected = "Product domain must have at least 2 components")]
fn test_invalid_single_component() {
ProductDomain::new(vec!["A".to_string()]);
}
#[test]
fn test_nested_product() {
let mut table = SymbolTable::new();
table.add_domain(DomainInfo::new("A", 10)).expect("unwrap");
table.add_domain(DomainInfo::new("B", 20)).expect("unwrap");
table.add_domain(DomainInfo::new("C", 5)).expect("unwrap");
// Create (A × B)
let ab = ProductDomain::binary("A", "B");
table.add_product_domain("AB", ab).expect("unwrap");
// Create (AB × C)
let abc = ProductDomain::binary("AB", "C");
assert_eq!(abc.cardinality(&table).expect("unwrap"), 1000);
}
#[test]
fn test_display() {
let product = ProductDomain::new(vec![
"Person".to_string(),
"Location".to_string(),
"Time".to_string(),
]);
assert_eq!(format!("{}", product), "Person × Location × Time");
}
#[test]
fn test_from_vec() {
let components = vec!["A".to_string(), "B".to_string()];
let product: ProductDomain = components.into();
assert_eq!(product.arity(), 2);
}
}