-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpytensorlogic.pyi
More file actions
1394 lines (1124 loc) · 38.4 KB
/
pytensorlogic.pyi
File metadata and controls
1394 lines (1124 loc) · 38.4 KB
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Type stubs for tensorlogic_py module.
This file provides type hints for IDE support and static type checking.
"""
from typing import Dict, List, Optional
import numpy as np
import numpy.typing as npt
# Version
__version__: str
# Core Types
class Term:
"""A term in a logical expression (variable or constant)."""
def name(self) -> str: ...
def is_var(self) -> bool: ...
def is_const(self) -> bool: ...
class TLExpr:
"""A logical expression."""
...
class EinsumGraph:
"""A compiled tensor computation graph."""
def stats(self) -> Dict[str, int]: ...
# Adapter Types
class DomainInfo: ...
class PredicateInfo: ...
class SymbolTable: ...
class CompilerContext: ...
class CompilationConfig: ...
# Provenance Types
class SourceLocation:
"""Source code location information."""
def __init__(self, file: str, line: int, column: int) -> None: ...
@property
def file(self) -> str: ...
@property
def line(self) -> int: ...
@property
def column(self) -> int: ...
class SourceSpan:
"""Source code span from start to end location."""
def __init__(self, start: SourceLocation, end: SourceLocation) -> None: ...
@property
def start(self) -> SourceLocation: ...
@property
def end(self) -> SourceLocation: ...
class Provenance:
"""Provenance information tracking origin of IR nodes."""
def __init__(self) -> None: ...
@property
def rule_id(self) -> Optional[str]: ...
@property
def source_file(self) -> Optional[str]: ...
@property
def span(self) -> Optional[SourceSpan]: ...
def set_rule_id(self, rule_id: str) -> None: ...
def set_source_file(self, source_file: str) -> None: ...
def set_span(self, span: SourceSpan) -> None: ...
def add_attribute(self, key: str, value: str) -> None: ...
def get_attribute(self, key: str) -> Optional[str]: ...
def get_attributes(self) -> Dict[str, str]: ...
class ProvenanceTracker:
"""Provenance tracker for RDF and tensor computation mappings."""
def __init__(self, enable_rdfstar: bool = False) -> None: ...
def track_entity(self, entity_iri: str, tensor_idx: int) -> None: ...
def track_shape(self, shape_iri: str, rule_expr: str, node_idx: int) -> None: ...
def get_entity(self, tensor_idx: int) -> Optional[str]: ...
def get_tensor(self, entity_iri: str) -> Optional[int]: ...
def track_inferred_triple(
self,
subject: str,
predicate: str,
object: str,
rule_id: Optional[str] = None,
confidence: Optional[float] = None
) -> None: ...
def get_entity_mappings(self) -> Dict[str, int]: ...
def get_shape_mappings(self) -> Dict[str, str]: ...
def to_rdf_star(self) -> List[str]: ...
def to_rdfstar_turtle(self) -> str: ...
def to_json(self) -> str: ...
@staticmethod
def from_json(json: str) -> "ProvenanceTracker": ...
def get_high_confidence_inferences(self, min_confidence: float = 0.8) -> List[Dict[str, any]]: ...
# Backend Types
class Backend:
"""Backend selection for execution.
Available backends:
- AUTO: Automatically select the best available backend
- SCIRS2_CPU: SciRS2 backend with CPU execution
- SCIRS2_GPU: SciRS2 backend with GPU execution (requires 'gpu' feature)
"""
AUTO: "Backend"
SCIRS2_CPU: "Backend"
SCIRS2_GPU: "Backend"
class BackendCapabilities:
"""Backend capability information.
Provides details about a backend's supported features, devices, and data types.
"""
@property
def name(self) -> str:
"""Get the backend name."""
...
@property
def version(self) -> str:
"""Get the backend version."""
...
@property
def devices(self) -> List[str]:
"""Get list of supported device types."""
...
@property
def dtypes(self) -> List[str]:
"""Get list of supported data types."""
...
@property
def features(self) -> List[str]:
"""Get list of supported features."""
...
@property
def max_dims(self) -> int:
"""Get maximum number of tensor dimensions supported."""
...
def supports_device(self, device: str) -> bool:
"""Check if a specific device type is supported."""
...
def supports_dtype(self, dtype: str) -> bool:
"""Check if a specific data type is supported."""
...
def supports_feature(self, feature: str) -> bool:
"""Check if a specific feature is supported."""
...
def summary(self) -> str:
"""Get a human-readable summary of capabilities."""
...
def to_dict(self) -> Dict[str, any]:
"""Get capabilities as a dictionary."""
...
# Term Constructors
def var(name: str) -> Term: ...
def const(name: str) -> Term: ...
# Expression Constructors
def pred(name: str, args: List[Term]) -> TLExpr: ...
def and_expr(left: TLExpr, right: TLExpr) -> TLExpr: ...
def or_expr(left: TLExpr, right: TLExpr) -> TLExpr: ...
def not_expr(expr: TLExpr) -> TLExpr: ...
def exists(var: str, domain: str, body: TLExpr) -> TLExpr: ...
def forall(var: str, domain: str, body: TLExpr) -> TLExpr: ...
def imply(left: TLExpr, right: TLExpr) -> TLExpr: ...
def constant(value: float) -> TLExpr: ...
# Arithmetic
def add(left: TLExpr, right: TLExpr) -> TLExpr: ...
def sub(left: TLExpr, right: TLExpr) -> TLExpr: ...
def mul(left: TLExpr, right: TLExpr) -> TLExpr: ...
def div(left: TLExpr, right: TLExpr) -> TLExpr: ...
# Comparison
def eq(left: TLExpr, right: TLExpr) -> TLExpr: ...
def lt(left: TLExpr, right: TLExpr) -> TLExpr: ...
def gt(left: TLExpr, right: TLExpr) -> TLExpr: ...
def lte(left: TLExpr, right: TLExpr) -> TLExpr: ...
def gte(left: TLExpr, right: TLExpr) -> TLExpr: ...
# Conditional
def if_then_else(cond: TLExpr, then_expr: TLExpr, else_expr: TLExpr) -> TLExpr: ...
# Compilation
def compile(expr: TLExpr) -> EinsumGraph: ...
def compile_with_config(expr: TLExpr, config: CompilationConfig) -> EinsumGraph: ...
# Execution
def execute(
graph: EinsumGraph,
inputs: Dict[str, npt.NDArray[np.float64]],
backend: Backend | None = None
) -> Dict[str, npt.NDArray[np.float64]]:
"""Execute a compiled graph with given inputs.
Args:
graph: The compiled EinsumGraph to execute
inputs: Dictionary mapping input names to NumPy arrays
backend: Optional backend selection (defaults to Auto, which selects SciRS2CPU)
Returns:
Dictionary mapping output names to NumPy arrays
Raises:
RuntimeError: If execution fails or backend is not available
"""
...
# Adapter Constructors
def domain_info(name: str, cardinality: int) -> DomainInfo: ...
def predicate_info(name: str, domains: List[str]) -> PredicateInfo: ...
def symbol_table() -> SymbolTable: ...
def compiler_context() -> CompilerContext: ...
# Backend Functions
def get_backend_capabilities(backend: Backend | None = None) -> BackendCapabilities:
"""Get capabilities for a specific backend.
Args:
backend: The backend to query (defaults to Auto)
Returns:
BackendCapabilities: Detailed capability information
Raises:
RuntimeError: If the backend is not available
"""
...
def list_available_backends() -> Dict[str, bool]:
"""List all available backends.
Returns:
Dictionary mapping backend names to their availability status
"""
...
def get_default_backend() -> Backend:
"""Get the default backend for this system.
Returns:
Backend: The default backend (currently SciRS2CPU)
"""
...
def get_system_info() -> Dict[str, any]:
"""Get detailed system and backend information.
Returns:
Dictionary with system and backend information including:
- tensorlogic_version: TensorLogic version
- rust_version: Rust compiler version
- default_backend: Default backend name
- backend_version: Backend version
- available_backends: Dict of available backends
- cpu_capabilities: CPU backend capabilities
"""
...
# Provenance Functions
def get_provenance(graph: EinsumGraph) -> List[Optional[Provenance]]:
"""Get provenance information from an einsum graph.
Extracts provenance metadata from all nodes in the graph.
Args:
graph: EinsumGraph to extract provenance from
Returns:
List of provenance records for each node (None if node has no provenance)
"""
...
def get_metadata(graph: EinsumGraph) -> List[Optional[Dict[str, any]]]:
"""Get metadata from an einsum graph.
Extracts all metadata (names, spans, provenance, attributes) from graph nodes.
Args:
graph: EinsumGraph to extract metadata from
Returns:
List of metadata dictionaries for each node (None if node has no metadata)
"""
...
def provenance_tracker(enable_rdfstar: bool = False) -> ProvenanceTracker:
"""Create a provenance tracker.
Helper function to create a new provenance tracker.
Args:
enable_rdfstar: Enable RDF* support (default: False)
Returns:
ProvenanceTracker: New provenance tracker
"""
...
# Training API Types
class LossFunction:
"""Loss function for training neural-symbolic models."""
def __init__(self, loss_type: str) -> None: ...
@property
def loss_type(self) -> str: ...
def __call__(
self,
predictions: npt.NDArray[np.float64],
targets: npt.NDArray[np.float64]
) -> float: ...
class Optimizer:
"""Optimizer for updating model parameters during training."""
def __init__(
self,
optimizer_type: str,
learning_rate: float = 0.01,
config: Optional[Dict[str, float]] = None
) -> None: ...
@property
def optimizer_type(self) -> str: ...
@property
def learning_rate(self) -> float: ...
@learning_rate.setter
def learning_rate(self, lr: float) -> None: ...
class Callback:
"""Callback for monitoring and controlling training."""
def __init__(
self,
callback_type: str,
config: Optional[Dict[str, float]] = None
) -> None: ...
@property
def callback_type(self) -> str: ...
class TrainingHistory:
"""Training history containing loss and metrics over epochs."""
def __init__(self) -> None: ...
@property
def train_losses(self) -> List[float]: ...
@property
def val_losses(self) -> List[float]: ...
def add_train_loss(self, loss: float) -> None: ...
def add_val_loss(self, loss: float) -> None: ...
def add_metric(self, name: str, value: float) -> None: ...
def get_metric(self, name: str) -> Optional[List[float]]: ...
def num_epochs(self) -> int: ...
def best_train_loss(self) -> Optional[tuple[int, float]]: ...
def best_val_loss(self) -> Optional[tuple[int, float]]: ...
class Trainer:
"""High-level trainer for neural-symbolic models."""
def __init__(
self,
graph: EinsumGraph,
loss_fn: LossFunction,
optimizer: Optimizer,
output_name: str = "result",
callbacks: Optional[List[Callback]] = None
) -> None: ...
def fit(
self,
train_inputs: Dict[str, npt.NDArray[np.float64]],
train_targets: npt.NDArray[np.float64],
epochs: int = 10,
validation_data: Optional[tuple[Dict[str, npt.NDArray[np.float64]], npt.NDArray[np.float64]]] = None,
verbose: int = 1
) -> TrainingHistory:
"""Train the model on data."""
...
def evaluate(
self,
inputs: Dict[str, npt.NDArray[np.float64]],
targets: npt.NDArray[np.float64]
) -> float:
"""Evaluate model on data without training."""
...
def predict(
self,
inputs: Dict[str, npt.NDArray[np.float64]]
) -> npt.NDArray[np.float64]:
"""Make predictions on new data."""
...
def get_history(self) -> TrainingHistory:
"""Get training history."""
...
# Loss Functions
def mse_loss() -> LossFunction:
"""Create a Mean Squared Error (MSE) loss function."""
...
def bce_loss() -> LossFunction:
"""Create a Binary Cross-Entropy (BCE) loss function."""
...
def cross_entropy_loss() -> LossFunction:
"""Create a Cross-Entropy loss function."""
...
# Optimizers
def sgd(learning_rate: float = 0.01, momentum: float = 0.0) -> Optimizer:
"""Create a Stochastic Gradient Descent (SGD) optimizer."""
...
def adam(
learning_rate: float = 0.001,
beta1: float = 0.9,
beta2: float = 0.999,
epsilon: float = 1e-8
) -> Optimizer:
"""Create an Adam optimizer."""
...
def rmsprop(
learning_rate: float = 0.01,
alpha: float = 0.99,
epsilon: float = 1e-8
) -> Optimizer:
"""Create an RMSprop optimizer."""
...
# Callbacks
def early_stopping(patience: float = 5.0, min_delta: float = 0.0001) -> Callback:
"""Create an EarlyStopping callback."""
...
def model_checkpoint(save_best_only: float = 1.0) -> Callback:
"""Create a ModelCheckpoint callback."""
...
def logger(verbose: float = 1.0) -> Callback:
"""Create a Logger callback."""
...
# Training Functions
def fit(
expr: TLExpr,
train_inputs: Dict[str, npt.NDArray[np.float64]],
train_targets: npt.NDArray[np.float64],
loss_fn: Optional[LossFunction] = None,
optimizer: Optional[Optimizer] = None,
epochs: int = 10,
config: Optional[CompilationConfig] = None
) -> tuple[EinsumGraph, TrainingHistory]:
"""Train a model with a simple API.
Convenience function for training without explicitly creating a Trainer.
Args:
expr: TensorLogic expression to train
train_inputs: Training input data
train_targets: Training target values
loss_fn: Loss function (default: MSE)
optimizer: Optimizer (default: Adam with lr=0.001)
epochs: Number of training epochs (default: 10)
config: Optional compilation configuration
Returns:
Tuple of (trained_graph, training_history)
"""
...
# ============================================================================
# Model Persistence
# ============================================================================
class ModelPackage:
"""Container for saving and loading complete TensorLogic models.
Supports multiple serialization formats:
- JSON: Human-readable, cross-platform
- Binary: Compact, efficient (bincode)
- Pickle: Python-native serialization
Example:
>>> package = tl.model_package()
>>> package.add_metadata("author", "Alice")
>>> package.save_json("model.json")
>>> loaded = tl.ModelPackage.load_json("model.json")
"""
def __init__(self) -> None:
"""Create a new empty model package."""
...
@property
def graph(self) -> Optional[str]:
"""Serialized einsum graph."""
...
@graph.setter
def graph(self, value: Optional[str]) -> None: ...
@property
def config(self) -> Optional[str]:
"""Serialized compilation configuration."""
...
@config.setter
def config(self, value: Optional[str]) -> None: ...
@property
def symbol_table(self) -> Optional[str]:
"""Serialized symbol table."""
...
@symbol_table.setter
def symbol_table(self, value: Optional[str]) -> None: ...
@property
def compiler_context(self) -> Optional[str]:
"""Serialized compiler context."""
...
@compiler_context.setter
def compiler_context(self, value: Optional[str]) -> None: ...
@property
def parameters(self) -> Optional[Dict[str, bytes]]:
"""Training parameters (tensor data)."""
...
@parameters.setter
def parameters(self, value: Optional[Dict[str, bytes]]) -> None: ...
@property
def metadata(self) -> Dict[str, str]:
"""Metadata key-value pairs."""
...
@metadata.setter
def metadata(self, value: Dict[str, str]) -> None: ...
def add_metadata(self, key: str, value: str) -> None:
"""Add a metadata key-value pair.
Args:
key: Metadata key
value: Metadata value
"""
...
def get_metadata(self, key: str) -> Optional[str]:
"""Get metadata value by key.
Args:
key: Metadata key
Returns:
Metadata value or None if not found
"""
...
def save_json(self, path: str) -> None:
"""Save package to JSON file.
Args:
path: File path to save to
Example:
>>> package.save_json("model.json")
"""
...
@staticmethod
def load_json(path: str) -> "ModelPackage":
"""Load package from JSON file.
Args:
path: File path to load from
Returns:
Loaded ModelPackage
Example:
>>> package = ModelPackage.load_json("model.json")
"""
...
def save_binary(self, path: str) -> None:
"""Save package to binary file (bincode format).
Args:
path: File path to save to
Example:
>>> package.save_binary("model.bin")
"""
...
@staticmethod
def load_binary(path: str) -> "ModelPackage":
"""Load package from binary file.
Args:
path: File path to load from
Returns:
Loaded ModelPackage
Example:
>>> package = ModelPackage.load_binary("model.bin")
"""
...
def to_json(self) -> str:
"""Convert package to JSON string.
Returns:
JSON representation
"""
...
@staticmethod
def from_json(json: str) -> "ModelPackage":
"""Create package from JSON string.
Args:
json: JSON string
Returns:
ModelPackage instance
"""
...
def to_bytes(self) -> bytes:
"""Convert package to binary bytes (for pickle support).
Returns:
Binary representation
"""
...
@staticmethod
def from_bytes(data: bytes) -> "ModelPackage":
"""Create package from binary bytes.
Args:
data: Binary bytes
Returns:
ModelPackage instance
"""
...
# Persistence Functions
def model_package() -> ModelPackage:
"""Create a new model package.
Returns:
Empty ModelPackage instance
Example:
>>> package = tl.model_package()
>>> package.add_metadata("author", "John Doe")
"""
...
def save_model(
graph: EinsumGraph,
path: str,
format: str = "json"
) -> None:
"""Save a compiled graph to file.
Args:
graph: EinsumGraph to save
path: File path to save to
format: Format to use ("json" or "binary", default: "json")
Example:
>>> graph = tl.compile(expr)
>>> tl.save_model(graph, "model.json")
>>> tl.save_model(graph, "model.bin", format="binary")
"""
...
def load_model(
path: str,
format: Optional[str] = None
) -> EinsumGraph:
"""Load a compiled graph from file.
Args:
path: File path to load from
format: Format to use (default: auto-detect from extension)
Returns:
Loaded EinsumGraph
Example:
>>> graph = tl.load_model("model.json")
>>> graph = tl.load_model("model.bin", format="binary")
"""
...
def save_full_model(
graph: EinsumGraph,
path: str,
config: Optional[CompilationConfig] = None,
symbol_table: Optional[SymbolTable] = None,
compiler_context: Optional[CompilerContext] = None,
metadata: Optional[Dict[str, str]] = None,
format: str = "json"
) -> None:
"""Save a complete model with all components.
Args:
graph: EinsumGraph to save
path: File path to save to
config: Optional compilation configuration
symbol_table: Optional symbol table
compiler_context: Optional compiler context
metadata: Optional metadata dictionary
format: Format to use ("json" or "binary", default: "json")
Example:
>>> tl.save_full_model(
... graph,
... "model.json",
... config=config,
... symbol_table=sym_table,
... metadata={"description": "My model", "version": "1.0"}
... )
"""
...
def load_full_model(
path: str,
format: Optional[str] = None
) -> Dict[str, any]:
"""Load a complete model with all components.
Args:
path: File path to load from
format: Format to use (default: auto-detect from extension)
Returns:
Dictionary with keys:
- 'graph': EinsumGraph
- 'config': CompilationConfig (if saved)
- 'symbol_table': SymbolTable (if saved)
- 'metadata': Dict[str, str]
Example:
>>> model = tl.load_full_model("model.json")
>>> graph = model['graph']
>>> config = model.get('config')
>>> metadata = model['metadata']
"""
...
# ============================================================================
# Rule Builder DSL - Python-native syntax for defining logic rules
# ============================================================================
class Var:
"""Variable wrapper with domain binding for DSL.
Enables Python-native syntax for building logic expressions with
operator overloading: & (AND), | (OR), ~ (NOT), >> (IMPLY)
Example:
>>> x = tl.Var("x", domain="Person")
>>> y = tl.Var("y", domain="Person")
>>> knows = tl.PredicateBuilder("knows", arity=2)
>>> expr = knows(x, y) & knows(y, x) # Mutual knowledge
"""
def __init__(self, name: str, domain: Optional[str] = None) -> None:
"""Create a variable.
Args:
name: Variable name
domain: Optional domain name for type checking
"""
...
@property
def name(self) -> str:
"""Get variable name."""
...
@property
def domain(self) -> Optional[str]:
"""Get variable domain."""
...
def to_term(self) -> Term:
"""Convert to PyTerm for internal use."""
...
def to_expr(self) -> TLExpr:
"""Get the underlying TLExpr representation."""
...
class PredicateBuilder:
"""Predicate builder for function-call syntax.
Enables defining predicates that can be called with variables
to produce TLExpr instances, with automatic arity and domain validation.
Example:
>>> knows = tl.PredicateBuilder("knows", arity=2, domains=["Person", "Person"])
>>> x = tl.Var("x", domain="Person")
>>> y = tl.Var("y", domain="Person")
>>> expr = knows(x, y) # Creates a predicate expression
"""
def __init__(
self,
name: str,
arity: Optional[int] = None,
domains: Optional[List[str]] = None
) -> None:
"""Create a predicate builder.
Args:
name: Predicate name
arity: Number of arguments (for validation)
domains: Domain names for each argument (for validation)
"""
...
@property
def name(self) -> str:
"""Get predicate name."""
...
@property
def arity(self) -> Optional[int]:
"""Get predicate arity."""
...
@property
def domains(self) -> Optional[List[str]]:
"""Get argument domains."""
...
def __call__(self, *args) -> TLExpr:
"""Call predicate with arguments to create a TLExpr.
Args:
*args: Variables, constants, or Terms
Returns:
TLExpr representing the predicate application
Raises:
ValueError: If arity doesn't match
TypeError: If domains don't match
"""
...
def to_predicate_info(self) -> PredicateInfo:
"""Get predicate metadata as PredicateInfo."""
...
class RuleBuilder:
"""Rule builder context manager for collecting and compiling rules.
Provides a high-level DSL for defining multiple rules and compiling
them together into execution graphs. Manages symbol tables and
domain/predicate metadata.
Example:
>>> with tl.RuleBuilder() as rb:
... x, y, z = rb.vars("x", "y", "z", domain="Person")
... knows = rb.pred("knows", arity=2)
... rule1 = (knows(x, y) & knows(y, z)) >> knows(x, z)
... rb.add_rule(rule1, name="transitivity")
... graph = rb.compile()
"""
def __init__(self, config: Optional[CompilationConfig] = None) -> None:
"""Create a rule builder.
Args:
config: Optional compilation configuration
"""
...
def __enter__(self) -> "RuleBuilder":
"""Enter context manager."""
...
def __exit__(self, exc_type, exc_value, traceback) -> bool:
"""Exit context manager."""
...
def vars(self, *names: str, domain: Optional[str] = None):
"""Create variables with optional domain.
Args:
*names: Variable names
domain: Optional domain name for all variables
Returns:
Single Var or tuple of Vars
Example:
>>> rb = tl.RuleBuilder()
>>> x = rb.vars("x", domain="Person")
>>> x, y, z = rb.vars("x", "y", "z", domain="Person")
"""
...
def pred(
self,
name: str,
arity: Optional[int] = None,
domains: Optional[List[str]] = None
) -> PredicateBuilder:
"""Create a predicate builder.
Args:
name: Predicate name
arity: Number of arguments (optional)
domains: Domain names for each argument (optional)
Returns:
PredicateBuilder instance
Example:
>>> rb = tl.RuleBuilder()
>>> knows = rb.pred("knows", arity=2, domains=["Person", "Person"])
"""
...
def add_domain(
self,
name: str,
cardinality: int,
description: Optional[str] = None,
elements: Optional[List[str]] = None
) -> None:
"""Add a domain to the symbol table.
Args:
name: Domain name
cardinality: Number of elements
description: Optional description
elements: Optional list of element names
Example:
>>> rb = tl.RuleBuilder()
>>> rb.add_domain("Person", cardinality=10, description="People")
"""
...
def add_rule(self, expr: TLExpr, name: Optional[str] = None) -> None:
"""Add a rule to the builder.
Args:
expr: TLExpr representing the rule
name: Optional name for the rule (default: rule_N)
Example:
>>> rb = tl.RuleBuilder()
>>> x, y = rb.vars("x", "y")
>>> knows = rb.pred("knows")
>>> rule = knows(x, y) >> knows(y, x)
>>> rb.add_rule(rule, name="symmetry")
"""
...
def get_rules(self) -> List[tuple]:
"""Get all defined rules.
Returns:
List of (name, expr) tuples
"""
...
def get_symbol_table(self) -> SymbolTable:
"""Get the symbol table.
Returns:
SymbolTable instance
"""
...
def compile(self, config: Optional[CompilationConfig] = None) -> EinsumGraph:
"""Compile all rules into a single execution graph.