tensorlogic-adapters 0.1.0

Symbol tables, axis metadata, and domain masks for TensorLogic
Documentation
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
//! Predicate composition system for defining predicates in terms of others.
//!
//! This module provides a system for composing predicates from other predicates,
//! enabling:
//! - Macro-like predicate expansion
//! - Predicate templates with parameters
//! - Derived predicates based on existing ones
//! - Complex predicate definitions through composition

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tensorlogic_ir::TLExpr;

use crate::error::AdapterError;

/// A composable predicate definition that can be expanded.
///
/// Composite predicates are defined in terms of other predicates and can
/// include parameters that are substituted during expansion.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CompositePredicate {
    /// Name of this composite predicate
    pub name: String,
    /// Parameter names (e.g., ["x", "y"])
    pub parameters: Vec<String>,
    /// The body expression defining this predicate
    pub body: PredicateBody,
    /// Optional description
    pub description: Option<String>,
}

/// The body of a composite predicate.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum PredicateBody {
    /// A TensorLogic expression
    Expression(Box<TLExpr>),
    /// Reference to another composite predicate
    Reference { name: String, args: Vec<String> },
    /// Conjunction of multiple predicates
    And(Vec<PredicateBody>),
    /// Disjunction of multiple predicates
    Or(Vec<PredicateBody>),
    /// Negation
    Not(Box<PredicateBody>),
}

/// A registry of composite predicates for lookup and expansion.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct CompositeRegistry {
    predicates: HashMap<String, CompositePredicate>,
}

impl CompositePredicate {
    /// Creates a new composite predicate.
    pub fn new(name: impl Into<String>, parameters: Vec<String>, body: PredicateBody) -> Self {
        CompositePredicate {
            name: name.into(),
            parameters,
            body,
            description: None,
        }
    }

    /// Sets the description for this composite predicate.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Returns the arity (number of parameters) of this predicate.
    pub fn arity(&self) -> usize {
        self.parameters.len()
    }

    /// Validates that this composite predicate is well-formed.
    pub fn validate(&self) -> Result<(), AdapterError> {
        // Check that all parameters are unique
        let mut seen = std::collections::HashSet::new();
        for param in &self.parameters {
            if !seen.insert(param) {
                return Err(AdapterError::InvalidParametricType(format!(
                    "Duplicate parameter '{}' in predicate '{}'",
                    param, self.name
                )));
            }
        }

        // Validate the body
        self.body.validate(&self.parameters)?;

        Ok(())
    }

    /// Expands this composite predicate with the given arguments.
    ///
    /// Substitutes all parameter occurrences in the body with the provided arguments.
    pub fn expand(&self, args: &[String]) -> Result<PredicateBody, AdapterError> {
        if args.len() != self.parameters.len() {
            return Err(AdapterError::ArityMismatch {
                name: self.name.clone(),
                expected: self.parameters.len(),
                found: args.len(),
            });
        }

        // Create substitution map
        let mut substitutions = HashMap::new();
        for (param, arg) in self.parameters.iter().zip(args.iter()) {
            substitutions.insert(param.clone(), arg.clone());
        }

        self.body.substitute(&substitutions)
    }
}

impl PredicateBody {
    /// Validates that this predicate body is well-formed.
    fn validate(&self, parameters: &[String]) -> Result<(), AdapterError> {
        match self {
            PredicateBody::Expression(_) => Ok(()), // TLExpr validation handled elsewhere
            PredicateBody::Reference { args, .. } => {
                // Check that all args reference valid parameters
                for arg in args {
                    if !parameters.contains(arg) && !arg.starts_with('_') {
                        return Err(AdapterError::UnboundVariable(arg.clone()));
                    }
                }
                Ok(())
            }
            PredicateBody::And(bodies) | PredicateBody::Or(bodies) => {
                for body in bodies {
                    body.validate(parameters)?;
                }
                Ok(())
            }
            PredicateBody::Not(body) => body.validate(parameters),
        }
    }

    /// Substitutes parameters with concrete arguments.
    fn substitute(
        &self,
        substitutions: &HashMap<String, String>,
    ) -> Result<PredicateBody, AdapterError> {
        match self {
            PredicateBody::Expression(expr) => {
                // For now, return as-is. Full expression substitution would require
                // walking the TLExpr tree and replacing variable names.
                Ok(PredicateBody::Expression(expr.clone()))
            }
            PredicateBody::Reference { name, args } => {
                let new_args = args
                    .iter()
                    .map(|arg| {
                        substitutions
                            .get(arg)
                            .cloned()
                            .unwrap_or_else(|| arg.clone())
                    })
                    .collect();
                Ok(PredicateBody::Reference {
                    name: name.clone(),
                    args: new_args,
                })
            }
            PredicateBody::And(bodies) => {
                let new_bodies: Result<Vec<_>, _> =
                    bodies.iter().map(|b| b.substitute(substitutions)).collect();
                Ok(PredicateBody::And(new_bodies?))
            }
            PredicateBody::Or(bodies) => {
                let new_bodies: Result<Vec<_>, _> =
                    bodies.iter().map(|b| b.substitute(substitutions)).collect();
                Ok(PredicateBody::Or(new_bodies?))
            }
            PredicateBody::Not(body) => Ok(PredicateBody::Not(Box::new(
                body.substitute(substitutions)?,
            ))),
        }
    }
}

impl CompositeRegistry {
    /// Creates a new empty composite registry.
    pub fn new() -> Self {
        CompositeRegistry::default()
    }

    /// Registers a composite predicate.
    pub fn register(&mut self, predicate: CompositePredicate) -> Result<(), AdapterError> {
        predicate.validate()?;
        self.predicates.insert(predicate.name.clone(), predicate);
        Ok(())
    }

    /// Gets a composite predicate by name.
    pub fn get(&self, name: &str) -> Option<&CompositePredicate> {
        self.predicates.get(name)
    }

    /// Checks if a predicate is registered.
    pub fn contains(&self, name: &str) -> bool {
        self.predicates.contains_key(name)
    }

    /// Expands a composite predicate with the given arguments.
    pub fn expand(&self, name: &str, args: &[String]) -> Result<PredicateBody, AdapterError> {
        let predicate = self
            .get(name)
            .ok_or_else(|| AdapterError::PredicateNotFound(name.to_string()))?;

        predicate.expand(args)
    }

    /// Returns the number of registered composite predicates.
    pub fn len(&self) -> usize {
        self.predicates.len()
    }

    /// Checks if the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.predicates.is_empty()
    }

    /// Lists all registered predicate names.
    pub fn list_predicates(&self) -> Vec<String> {
        self.predicates.keys().cloned().collect()
    }
}

/// A template for creating multiple similar predicates.
///
/// Templates allow defining patterns for predicates that can be instantiated
/// with different domains or properties.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PredicateTemplate {
    /// Template name
    pub name: String,
    /// Type parameters (e.g., ["T", "U"])
    pub type_params: Vec<String>,
    /// Value parameters (e.g., ["relation"])
    pub value_params: Vec<String>,
    /// The body defining how to construct the predicate
    pub body: PredicateBody,
}

impl PredicateTemplate {
    /// Creates a new predicate template.
    pub fn new(
        name: impl Into<String>,
        type_params: Vec<String>,
        value_params: Vec<String>,
        body: PredicateBody,
    ) -> Self {
        PredicateTemplate {
            name: name.into(),
            type_params,
            value_params,
            body,
        }
    }

    /// Instantiates this template with concrete types and values.
    pub fn instantiate(
        &self,
        type_args: &[String],
        value_args: &[String],
    ) -> Result<CompositePredicate, AdapterError> {
        if type_args.len() != self.type_params.len() {
            return Err(AdapterError::ArityMismatch {
                name: format!("{}[type params]", self.name),
                expected: self.type_params.len(),
                found: type_args.len(),
            });
        }

        if value_args.len() != self.value_params.len() {
            return Err(AdapterError::ArityMismatch {
                name: format!("{}[value params]", self.name),
                expected: self.value_params.len(),
                found: value_args.len(),
            });
        }

        // Create substitution map
        let mut substitutions = HashMap::new();
        for (param, arg) in self.type_params.iter().zip(type_args.iter()) {
            substitutions.insert(param.clone(), arg.clone());
        }
        for (param, arg) in self.value_params.iter().zip(value_args.iter()) {
            substitutions.insert(param.clone(), arg.clone());
        }

        // Generate instance name
        let instance_name = format!("{}<{}>", self.name, type_args.join(", "));

        // Substitute in body
        let instance_body = self.body.substitute(&substitutions)?;

        Ok(CompositePredicate {
            name: instance_name,
            parameters: value_args.to_vec(),
            body: instance_body,
            description: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_composite_predicate_creation() {
        let pred = CompositePredicate::new(
            "friend",
            vec!["x".to_string(), "y".to_string()],
            PredicateBody::Reference {
                name: "knows".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
        );

        assert_eq!(pred.name, "friend");
        assert_eq!(pred.arity(), 2);
    }

    #[test]
    fn test_composite_predicate_validation() {
        let valid = CompositePredicate::new(
            "test",
            vec!["x".to_string(), "y".to_string()],
            PredicateBody::Reference {
                name: "knows".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
        );
        assert!(valid.validate().is_ok());

        let invalid = CompositePredicate::new(
            "test",
            vec!["x".to_string(), "x".to_string()], // Duplicate parameter
            PredicateBody::Reference {
                name: "knows".to_string(),
                args: vec!["x".to_string()],
            },
        );
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn test_composite_registry() {
        let mut registry = CompositeRegistry::new();

        let pred = CompositePredicate::new(
            "friend",
            vec!["x".to_string(), "y".to_string()],
            PredicateBody::Reference {
                name: "knows".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
        );

        registry.register(pred).expect("unwrap");
        assert!(registry.contains("friend"));
        assert_eq!(registry.len(), 1);
    }

    #[test]
    fn test_predicate_expansion() {
        let pred = CompositePredicate::new(
            "friend",
            vec!["x".to_string(), "y".to_string()],
            PredicateBody::Reference {
                name: "knows".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
        );

        let expanded = pred
            .expand(&["alice".to_string(), "bob".to_string()])
            .expect("unwrap");

        match expanded {
            PredicateBody::Reference { name, args } => {
                assert_eq!(name, "knows");
                assert_eq!(args, vec!["alice".to_string(), "bob".to_string()]);
            }
            _ => panic!("Expected Reference"),
        }
    }

    #[test]
    fn test_predicate_template() {
        let template = PredicateTemplate::new(
            "related",
            vec!["T".to_string()],
            vec!["x".to_string(), "y".to_string()],
            PredicateBody::Reference {
                name: "connected".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
        );

        let instance = template
            .instantiate(&["Person".to_string()], &["a".to_string(), "b".to_string()])
            .expect("unwrap");

        assert_eq!(instance.name, "related<Person>");
        assert_eq!(instance.parameters, vec!["a".to_string(), "b".to_string()]);
    }

    #[test]
    fn test_composite_and() {
        let body = PredicateBody::And(vec![
            PredicateBody::Reference {
                name: "knows".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
            PredicateBody::Reference {
                name: "trusts".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
        ]);

        let pred = CompositePredicate::new("friend", vec!["x".to_string(), "y".to_string()], body);

        assert!(pred.validate().is_ok());
    }

    #[test]
    fn test_composite_or() {
        let body = PredicateBody::Or(vec![
            PredicateBody::Reference {
                name: "colleague".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
            PredicateBody::Reference {
                name: "friend".to_string(),
                args: vec!["x".to_string(), "y".to_string()],
            },
        ]);

        let pred =
            CompositePredicate::new("connected", vec!["x".to_string(), "y".to_string()], body);

        assert!(pred.validate().is_ok());
    }

    #[test]
    fn test_composite_not() {
        let body = PredicateBody::Not(Box::new(PredicateBody::Reference {
            name: "enemy".to_string(),
            args: vec!["x".to_string(), "y".to_string()],
        }));

        let pred =
            CompositePredicate::new("not_enemy", vec!["x".to_string(), "y".to_string()], body);

        assert!(pred.validate().is_ok());
    }
}