Skip to content

Data Model

Data model for the typed-logic framework.

Overview

This module defines the core classes and structures used to represent logical constructs such as sentences, terms, predicates, and theories. It is based on the Common Logic Interchange Format (CLIF) and the Common Logic Standard (CL), with additions to make working with simple type systems easier.

Logical axioms are called sentences which organized into theories., which can be loaded into a solver.

While one of the goals of typed-logic is to be able to write logic intuitively in Python, this data model is independent of the mapping from the Python language to the logic language; it can be used independently of the python syntax.

Here is an example:

    >>> from typedlogic import Term, Forall, Implies
    >>> x = Variable('x')
    >>> y = Variable('y')
    >>> pdef = PredicateDefinition(predicate='FriendOf',
    ...                          arguments={'x': 'str', 'y': 'str'}),
    >>> theory = Theory(
    ...     name="My theory",
    ...     predicate_definitions=[pdef],
    ... )
    >>> s = Forall([x, y],
    ...            Implies(Term('friend_of', x, y),
    ...                    Term('friend_of', y, x)))
    >>> theory.add(s)

Classes

PredicateDefinition dataclass

Defines the name and arguments of a predicate.

Example:

>>> pdef = PredicateDefinition(predicate='FriendOf',
...                            arguments={'x': 'str', 'y': 'str'})

The arguments are mappings between variable names and types. You can use either base types (e.g. 'str', 'int', 'float') or custom types.

Custom types should be defined in the theory's type_definitions attribute.

>>> pdef = PredicateDefinition(predicate='FriendOf',
...                            arguments={'x': 'Person', 'y': 'Person'})
>>> theory = Theory(
...     name="My theory",
...     type_definitions={'Person': 'str'},
...     predicate_definitions=[pdef],
... )

Model:

classDiagram
class PredicateDefinition {
    +String predicate
    +Dict arguments
    +String description
    +Dict metadata
}
PredicateDefinition --> "*" PredicateDefinition : parents
Source code in src/typedlogic/datamodel.py
 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
@dataclass
class PredicateDefinition:
    """
    Defines the name and arguments of a predicate.

    Example:

        >>> pdef = PredicateDefinition(predicate='FriendOf',
        ...                            arguments={'x': 'str', 'y': 'str'})

    The arguments are mappings between variable names and types.
    You can use either base types (e.g. 'str', 'int', 'float') or custom types.

    Custom types should be defined in the theory's `type_definitions` attribute.

        >>> pdef = PredicateDefinition(predicate='FriendOf',
        ...                            arguments={'x': 'Person', 'y': 'Person'})
        >>> theory = Theory(
        ...     name="My theory",
        ...     type_definitions={'Person': 'str'},
        ...     predicate_definitions=[pdef],
        ... )

    Model:

    ```mermaid
    classDiagram
    class PredicateDefinition {
        +String predicate
        +Dict arguments
        +String description
        +Dict metadata
    }
    PredicateDefinition --> "*" PredicateDefinition : parents
    ```

    """

    predicate: str
    arguments: Dict[str, str]
    description: Optional[str] = None
    metadata: Optional[Dict[str, Any]] = None
    parents: Optional[List[str]] = None
    python_class: Optional[Type] = None

    def argument_base_type(self, arg: str) -> str:
        typ = self.arguments[arg]
        try:
            import pydantic

            if isinstance(typ, pydantic.fields.FieldInfo):
                typ = typ.annotation
        except ImportError:
            pass
        return str(typ)

    @classmethod
    def from_class(cls, python_class: Type) -> "PredicateDefinition":
        """
        Create a predicate definition from a python class

        :param predicate_class:
        :return:
        """
        return PredicateDefinition(
            predicate=python_class.__name__,
            arguments={k: v for k, v in python_class.__annotations__.items()},
        )

from_class(python_class) classmethod

Create a predicate definition from a python class

Parameters:

Name Type Description Default
predicate_class
required

Returns:

Type Description
PredicateDefinition
Source code in src/typedlogic/datamodel.py
105
106
107
108
109
110
111
112
113
114
115
116
@classmethod
def from_class(cls, python_class: Type) -> "PredicateDefinition":
    """
    Create a predicate definition from a python class

    :param predicate_class:
    :return:
    """
    return PredicateDefinition(
        predicate=python_class.__name__,
        arguments={k: v for k, v in python_class.__annotations__.items()},
    )

Variable dataclass

A variable in a logical sentence.

>>> x = Variable('x')
>>> y = Variable('y')
>>> s = Forall([x, y],
...            Implies(Term('friend_of', x, y),
...                    Term('friend_of', y, x)))

Variables can have domains (types) specified:

>>> x = Variable('x', domain='str')
>>> y = Variable('y', domain='str')
>>> z = Variable('y', domain='int')
>>> xa = Variable('xa', domain='int')
>>> ya = Variable('ya', domain='int')
>>> s = Forall([x, y, z],
...            Implies(And(Term('ParentOf', x, y),
...                        Term('Age', x, xa),
...                        Term('Age', y, ya)),
...                    Term('OlderThan', x, y)))

The domains should be either base types or defined types in the theory's `type_definitions` attribute.
Source code in src/typedlogic/datamodel.py
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
@dataclass
class Variable:
    """
    A variable in a logical sentence.

        >>> x = Variable('x')
        >>> y = Variable('y')
        >>> s = Forall([x, y],
        ...            Implies(Term('friend_of', x, y),
        ...                    Term('friend_of', y, x)))

    Variables can have domains (types) specified:

        >>> x = Variable('x', domain='str')
        >>> y = Variable('y', domain='str')
        >>> z = Variable('y', domain='int')
        >>> xa = Variable('xa', domain='int')
        >>> ya = Variable('ya', domain='int')
        >>> s = Forall([x, y, z],
        ...            Implies(And(Term('ParentOf', x, y),
        ...                        Term('Age', x, xa),
        ...                        Term('Age', y, ya)),
        ...                    Term('OlderThan', x, y)))

        The domains should be either base types or defined types in the theory's `type_definitions` attribute.

    """

    name: str
    domain: Optional[str] = None
    constraints: Optional[List[str]] = None

    def __eq__(self, other):
        return isinstance(other, Variable) and self.name == other.name

    def __str__(self):
        return "?" + self.name

    def __hash__(self):
        return hash(self.name)

    def as_sexpr(self) -> SExpression:
        sexpr = [type(self).__name__, self.name]
        if self.domain:
            return sexpr + [self.domain]
        else:
            return sexpr

    @staticmethod
    def create(names: str) -> tuple['Variable', ...]:
        return tuple(Variable(name.strip()) for name in names.split())

Sentence

Bases: ABC

Base class for logical sentences.

Do not use this class directly; use one of the subclasses instead.

Model:

classDiagram
Sentence <|-- Term
Sentence <|-- BooleanSentence
Sentence <|-- QuantifiedSentence
Sentence <|-- Extension
Source code in src/typedlogic/datamodel.py
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
class Sentence(ABC):
    """
    Base class for logical sentences.

    Do not use this class directly; use one of the subclasses instead.

    Model:

    ```mermaid
    classDiagram
    Sentence <|-- Term
    Sentence <|-- BooleanSentence
    Sentence <|-- QuantifiedSentence
    Sentence <|-- Extension
    ```


    """

    def __init__(self):
        self._annotations = {}

    def __and__(self, other):
        return And(self, other)

    def __or__(self, other):
        return Or(self, other)

    def __invert__(self):
        return Not(self)

    def __sub__(self):
        return NegationAsFailure(self)

    def __rshift__(self, other):
        return Implies(self, other)

    def __lshift__(self, other):
        return Implied(self, other)

    def __xor__(self, other):
        return Xor(self, other)

    def iff(self, other):
        return Iff(self, other)

    def __lt__(self, other):
        return Term(operator.lt.__name__, self, other)

    def __le__(self, other):
        return Term(operator.le.__name__, self, other)

    def __gt__(self, other):
        return Term(operator.gt.__name__, self, other)

    def __ge__(self, other):
        return Term(operator.ge.__name__, self, other)

    def __add__(self, other):
        return Term(operator.add.__name__, self, other)

    def __rmul__(self, other):
        # TODO: avoid circular import
        from typedlogic.extensions.probabilistic import Probability, That
        return Probability(self, That(other))

    @property
    def annotations(self) -> Dict[str, Any]:
        """
        Annotations for the sentence.

        Annotations are always logically silent, but can be used to store metadata or other information.

        :return:
        """
        return self._annotations or {}

    def add_annotation(self, key: str, value: Any):
        """
        Add an annotation to the sentence

        :param key:
        :param value:
        :return:
        """
        if not self._annotations:
            self._annotations = {}
        self._annotations[key] = value

    def as_sexpr(self) -> SExpression:
        raise NotImplementedError(f"type = {type(self)} // {self}")

    @property
    def arguments(self) -> List[Any]:
        raise NotImplementedError(f"type = {type(self)} // {self}")

annotations property

Annotations for the sentence.

Annotations are always logically silent, but can be used to store metadata or other information.

Returns:

Type Description
Dict[str, Any]

add_annotation(key, value)

Add an annotation to the sentence

Parameters:

Name Type Description Default
key str
required
value Any
required

Returns:

Type Description
Source code in src/typedlogic/datamodel.py
249
250
251
252
253
254
255
256
257
258
259
def add_annotation(self, key: str, value: Any):
    """
    Add an annotation to the sentence

    :param key:
    :param value:
    :return:
    """
    if not self._annotations:
        self._annotations = {}
    self._annotations[key] = value

Term

Bases: Sentence

An atomic part of a sentence.

A ground term is a term with no variables:

>>> t = Term('FriendOf', 'Alice', 'Bob')
>>> t
FriendOf(Alice, Bob)
>>> t.values
('Alice', 'Bob')
>>> t.is_ground
True

Keyword argument based initialization is also supported:

>>> t = Term('FriendOf', dict(about='Alice', friend='Bob'))
>>> t.values
('Alice', 'Bob')
>>> t.positional
False

Mappings:

  • Corresponds to AtomicSentence in Common Logic
Source code in src/typedlogic/datamodel.py
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
class Term(Sentence):
    """
    An atomic part of a sentence.

    A ground term is a term with no variables:

        >>> t = Term('FriendOf', 'Alice', 'Bob')
        >>> t
        FriendOf(Alice, Bob)
        >>> t.values
        ('Alice', 'Bob')
        >>> t.is_ground
        True

    Keyword argument based initialization is also supported:

        >>> t = Term('FriendOf', dict(about='Alice', friend='Bob'))
        >>> t.values
        ('Alice', 'Bob')
        >>> t.positional
        False

    Mappings:

     - Corresponds to AtomicSentence in Common Logic
    """

    def __init__(self, predicate: str, *args, **kwargs):
        self.predicate = predicate
        if not args:
            self.positional = None
            bindings = {}
        elif len(args) == 1 and isinstance(args[0], dict):
            bindings = args[0]
            self.positional = False
        else:
            bindings = {f"arg{i}": arg for i, arg in enumerate(args)}
            self.positional = True
        self.bindings = bindings
        self._annotations = kwargs

    @property
    def is_constant(self):
        """
        :return: True if the term is a constant (zero arguments)
        """
        return not self.bindings

    @property
    def is_ground(self):
        """
        :return: True if none of the arguments are variables
        """
        return not any(isinstance(v, Variable) for v in self.bindings.values())

    @property
    def values(self) -> Tuple[Any, ...]:
        """
        Representation of the arguments of the term as a fixed-position tuples
        :return:
        """
        return tuple([v for v in self.bindings.values()])

    @property
    def variables(self) -> List[Variable]:
        """
        :return: All of the arguments that are variables
        """
        return [v for v in self.bindings.values() if isinstance(v, Variable)]

    @property
    def variable_names(self) -> List[str]:
        return [v.name for v in self.bindings.values() if isinstance(v, Variable)]

    def make_keyword_indexed(self, keywords: List[str]):
        """
        Convert positional arguments to keyword arguments
        """
        if self.positional:
            self.bindings = {k: v for k, v in zip(keywords, self.bindings.values(), strict=False)}
            self.positional = False

    def __repr__(self):
        if not self.bindings:
            return f"{self.predicate}"
        elif self.positional:
            return f'{self.predicate}({", ".join(f"{v}" for v in self.bindings.values())})'
        else:
            return f'{self.predicate}({", ".join(f"{v}" for k, v in self.bindings.items())})'

    def __eq__(self, other):
        # return isinstance(other, Term) and self.predicate == other.predicate and self.bindings == other.bindings
        return isinstance(other, Term) and self.predicate == other.predicate and self.values == other.values

    def __hash__(self):
        return hash((self.predicate, tuple(self.values)))

    def as_sexpr(self) -> SExpression:
        return [self.predicate] + [as_sexpr(v) for v in self.bindings.values()]

is_constant property

Returns:

Type Description

True if the term is a constant (zero arguments)

is_ground property

Returns:

Type Description

True if none of the arguments are variables

values property

Representation of the arguments of the term as a fixed-position tuples

Returns:

Type Description
Tuple[Any, ...]

variables property

Returns:

Type Description
List[Variable]

All of the arguments that are variables

make_keyword_indexed(keywords)

Convert positional arguments to keyword arguments

Source code in src/typedlogic/datamodel.py
365
366
367
368
369
370
371
def make_keyword_indexed(self, keywords: List[str]):
    """
    Convert positional arguments to keyword arguments
    """
    if self.positional:
        self.bindings = {k: v for k, v in zip(keywords, self.bindings.values(), strict=False)}
        self.positional = False

TermBag

Bases: Sentence

A bag of terms.

Example (using keyword arguments):

>>> tb = TermBag('Distance', {'start': ['London', 'Paris', 'Tokyo'], 'end': ['Paris', 'Tokyo', 'New York'], 'miles': [344, 9561, 10838]})
>>> tb
Distance(London, Paris, 344), Distance(Paris, Tokyo, 9561), Distance(Tokyo, New York, 10838)

Example (using positional arguments):

>>> tb = TermBag('Distance', ['London', 'Paris', 'Tokyo'], ['Paris', 'Tokyo', 'New York'], [344, 9561, 10838])
>>> tb
Distance(London, Paris, 344), Distance(Paris, Tokyo, 9561), Distance(Tokyo, New York, 10838)
Source code in src/typedlogic/datamodel.py
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
class TermBag(Sentence):
    """
    A bag of terms.

    Example (using keyword arguments):

        >>> tb = TermBag('Distance', {'start': ['London', 'Paris', 'Tokyo'], 'end': ['Paris', 'Tokyo', 'New York'], 'miles': [344, 9561, 10838]})
        >>> tb
        Distance(London, Paris, 344), Distance(Paris, Tokyo, 9561), Distance(Tokyo, New York, 10838)

    Example (using positional arguments):

        >>> tb = TermBag('Distance', ['London', 'Paris', 'Tokyo'], ['Paris', 'Tokyo', 'New York'], [344, 9561, 10838])
        >>> tb
        Distance(London, Paris, 344), Distance(Paris, Tokyo, 9561), Distance(Tokyo, New York, 10838)

    """

    def __init__(self, predicate: str, *args, **kwargs):
        self.predicate = predicate
        bindings: Dict[str, List[Any]]
        if not args:
            self.positional = None
            bindings = {}
        elif len(args) == 1 and isinstance(args[0], dict):
            bindings = args[0]
            self.positional = False
        else:
            bindings = {f"arg{i}": arg for i, arg in enumerate(args)}
            self.positional = True
        self.bindings = bindings
        self._annotations = kwargs
        self._validate()

    def _validate(self):
        if not self.predicate:
            raise ValueError("No predicate provided")
        if not self.bindings:
            raise ValueError("No bindings provided")
        if not all(isinstance(v, List) for v in self.bindings.values()):
            raise ValueError("All bindings must be collections")

    @property
    def values(self) -> Tuple[List[Any], ...]:
        """
        Representation of the arguments of the term as a fixed-position tuples

        :return:
        """
        return tuple([v for v in self.bindings.values()])

    def make_keyword_indexed(self, keywords: List[str]):
        """
        Convert positional arguments to keyword arguments
        """
        if self.positional:
            self.bindings = {k: v for k, v in zip(keywords, self.bindings.values(), strict=False)}
            self.positional = False
        self._validate()

    def __repr__(self):
        terms = self.as_terms()
        return ", ".join(repr(t) for t in terms)

    def __eq__(self, other):
        # return isinstance(other, Term) and self.predicate == other.predicate and self.bindings == other.bindings
        return isinstance(other, TermBag) and self.predicate == other.predicate and self.values == other.values

    def __hash__(self):
        return hash((self.predicate, tuple(self.values)))

    def as_terms(self) -> List[Term]:
        tuples = zip(*self.values)
        return [Term(self.predicate, *tuple) for tuple in tuples]

    def as_sexpr(self) -> SExpressionTerm:
        return [t.as_sexpr() for t in self.as_terms()]

values property

Representation of the arguments of the term as a fixed-position tuples

Returns:

Type Description
Tuple[List[Any], ...]

make_keyword_indexed(keywords)

Convert positional arguments to keyword arguments

Source code in src/typedlogic/datamodel.py
443
444
445
446
447
448
449
450
def make_keyword_indexed(self, keywords: List[str]):
    """
    Convert positional arguments to keyword arguments
    """
    if self.positional:
        self.bindings = {k: v for k, v in zip(keywords, self.bindings.values(), strict=False)}
        self.positional = False
    self._validate()

Extension

Bases: Sentence, ABC

Use this abstract class for framework-specific extensions.

An example of this is the Fact class which subclasses Extension, and is intended to be subclassed by domain-specific classes representing predicate definitions, whose instances map to terms.

Source code in src/typedlogic/datamodel.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
class Extension(Sentence, ABC):
    """
    Use this abstract class for framework-specific extensions.

    An example of this is the `Fact` class which subclasses Extension, and is intended to be
    subclassed by domain-specific classes representing predicate definitions, whose instances
    map to terms.
    """

    @abstractmethod
    def to_model_object(self) -> Sentence:
        """
        Convert the extension to a standard model object.

        :return:
        """
        pass

    def as_sexpr(self) -> List[Any]:
        return self.to_model_object().as_sexpr()

    @property
    def arguments(self) -> List[Any]:
        return self.to_model_object().arguments

to_model_object() abstractmethod

Convert the extension to a standard model object.

Returns:

Type Description
Sentence
Source code in src/typedlogic/datamodel.py
480
481
482
483
484
485
486
487
@abstractmethod
def to_model_object(self) -> Sentence:
    """
    Convert the extension to a standard model object.

    :return:
    """
    pass

BooleanSentence dataclass

Bases: Sentence, ABC

Base class for sentences that are boolean expressions

Corresponds to BooleanSentence in CL

classDiagram
BooleanSentence <|-- And
BooleanSentence <|-- Or
BooleanSentence <|-- Not
BooleanSentence <|-- Xor
BooleanSentence <|-- ExactlyOne
BooleanSentence <|-- Implication
BooleanSentence <|-- Implied
BooleanSentence <|-- Iff
BooleanSentence <|-- NegationAsFailure
BooleanSentence --> "*" Sentence : operands
Source code in src/typedlogic/datamodel.py
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
@dataclass
class BooleanSentence(Sentence, ABC):
    """
    Base class for sentences that are boolean expressions

    Corresponds to BooleanSentence in CL

    ```mermaid
    classDiagram
    BooleanSentence <|-- And
    BooleanSentence <|-- Or
    BooleanSentence <|-- Not
    BooleanSentence <|-- Xor
    BooleanSentence <|-- ExactlyOne
    BooleanSentence <|-- Implication
    BooleanSentence <|-- Implied
    BooleanSentence <|-- Iff
    BooleanSentence <|-- NegationAsFailure
    BooleanSentence --> "*" Sentence : operands
    ```

    """

    operands: Tuple[Sentence, ...] = field(default_factory=tuple)
    # operands: Tuple[Union[Sentence, bool], ...] = field(default_factory=tuple)

    def __init__(self, *operands, **kwargs):
        def _as_sentence(s: Union[Sentence, bool]) -> Sentence:
            if isinstance(s, Sentence):
                return s
            elif isinstance(s, bool):
                return And() if s else Or()
            else:
                raise TypeError(f"Expected Sentence or bool, got {type(s)}")
        self.operands = tuple([_as_sentence(s) for s in operands])
        self._annotations = kwargs

    def __eq__(self, other):
        return isinstance(other, type(self)) and self.operands == other.operands

    def as_sexpr(self) -> SExpression:
        return [type(self).__name__] + [as_sexpr(op) for op in self.operands]

    @property
    def arguments(self) -> List[Any]:
        return list(self.operands)

And dataclass

Bases: BooleanSentence

A conjunction of sentences.

>>> x = Variable('x')
>>> y = Variable('y')
>>> s = And(Term('friend_of', x, y), Term('friend_of', y, x))

You can also use syntactic sugar:

>>> s = Term('friend_of', x, y) & Term('friend_of', y, x)

Note however that precedence rules for & are different from and.

In the context of a pylog program, you can also use and:

assert FriendOf(x, y) & FriendOf(y, x)

As in CL, And() means True

Source code in src/typedlogic/datamodel.py
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
@dataclass
class And(BooleanSentence):
    """
    A conjunction of sentences.

        >>> x = Variable('x')
        >>> y = Variable('y')
        >>> s = And(Term('friend_of', x, y), Term('friend_of', y, x))

    You can also use syntactic sugar:

        >>> s = Term('friend_of', x, y) & Term('friend_of', y, x)

    Note however that precedence rules for `&` are different from `and`.

    In the context of a pylog program, you can also use `and`:

    ```assert FriendOf(x, y) & FriendOf(y, x)```

    As in CL, ``And()`` means True
    """

    def __init__(self, *operands, **kwargs):
        super().__init__(*operands, **kwargs)

    def __str__(self):
        return f'({") & (".join(str(op) for op in self.operands)})'

    def __repr__(self):
        return f'And({", ".join(repr(op) for op in self.operands)})'

Or dataclass

Bases: BooleanSentence

A disjunction of sentences.

>>> x = Variable('x')
>>> y = Variable('y')
>>> s = Or(Term('friend_of', x, y), Term('friend_of', y, x))
>>> s.operands[0]
friend_of(?x, ?y)

You can also use syntactic sugar:

>>> s = Term('friend_of', x, y) | Term('friend_of', y, x)

Note however that precedence rules for | are different from or.

In the context of a pylog program, you can also use or:

assert FriendOf(x, y) | FriendOf(y, x)

As in CL, Or() means False

Source code in src/typedlogic/datamodel.py
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
@dataclass
class Or(BooleanSentence):
    """
    A disjunction of sentences.

        >>> x = Variable('x')
        >>> y = Variable('y')
        >>> s = Or(Term('friend_of', x, y), Term('friend_of', y, x))
        >>> s.operands[0]
        friend_of(?x, ?y)

    You can also use syntactic sugar:

        >>> s = Term('friend_of', x, y) | Term('friend_of', y, x)

    Note however that precedence rules for `|` are different from `or`.

    In the context of a pylog program, you can also use `or`:

    ```assert FriendOf(x, y) | FriendOf(y, x)```

    As in CL, ``Or()`` means False
    """

    def __init__(self, *operands, **kwargs):
        super().__init__(*operands, **kwargs)

    def __str__(self):
        return f'({") | (".join(str(op) for op in self.operands)})'

    def __repr__(self):
        return f'Or({", ".join(repr(op) for op in self.operands)})'

Not dataclass

Bases: BooleanSentence

A complement of a sentence

>>> x = Variable('x')
>>> y = Variable('y')
>>> s = Not(Term('friend_of', x, y))
>>> s.negated
friend_of(?x, ?y)

You can also use syntactic sugar:

>>> s = ~Term('friend_of', x, y)

In the context of a pylog program, you can also use not:

assert not FriendOf(x, y)

This SHOULD be interpreted as strict negation, not as failure.

Source code in src/typedlogic/datamodel.py
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
@dataclass
class Not(BooleanSentence):
    """
    A complement of a sentence

        >>> x = Variable('x')
        >>> y = Variable('y')
        >>> s = Not(Term('friend_of', x, y))
        >>> s.negated
        friend_of(?x, ?y)

    You can also use syntactic sugar:

        >>> s = ~Term('friend_of', x, y)

    In the context of a pylog program, you can also use `not`:

    ```assert not FriendOf(x, y)```

    This SHOULD be interpreted as strict negation, not as failure.
    """

    def __init__(self, operand, **kwargs):
        super().__init__(operand, **kwargs)

    def __str__(self):
        return f"~{self.operands[0]}"

    def __repr__(self):
        return f"Not({repr(self.operands[0])})"

    @property
    def negated(self) -> Sentence:
        """
        The negated sentence
        :return: Sentence
        """
        return self.operands[0]

negated property

The negated sentence

Returns:

Type Description
Sentence

Sentence

Xor

Bases: BooleanSentence

An exclusive or of sentences

Source code in src/typedlogic/datamodel.py
671
672
673
674
675
676
677
class Xor(BooleanSentence):
    """
    An exclusive or of sentences
    """

    def __init__(self, left, right, **kwargs):
        super().__init__(left, right, **kwargs)

ExactlyOne dataclass

Bases: BooleanSentence

Exactly one of the sentences is true

>>> x = Variable('x')
>>> s = ExactlyOne(Term('likes', x, "root beer"), Term('likes', x, "marmite"))
Source code in src/typedlogic/datamodel.py
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
@dataclass
class ExactlyOne(BooleanSentence):
    """
    Exactly one of the sentences is true

        >>> x = Variable('x')
        >>> s = ExactlyOne(Term('likes', x, "root beer"), Term('likes', x, "marmite"))

    """

    def __init__(self, *operands, **kwargs):
        super().__init__(*operands, **kwargs)

    def __str__(self):
        return f'({") x| (".join(str(op) for op in self.operands)})'

    def __repr__(self):
        return f'ExactlyOne({", ".join(repr(op) for op in self.operands)})'

Implication dataclass

Bases: BooleanSentence, ABC

An abstract grouping of sentences with an implication operator.

classDiagram
Implication <|-- Implies
Implication <|-- Implied
Implication <|-- Iff
Source code in src/typedlogic/datamodel.py
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
@dataclass
class Implication(BooleanSentence, ABC):
    """
    An abstract grouping of sentences with an implication operator.

    ```mermaid
    classDiagram
    Implication <|-- Implies
    Implication <|-- Implied
    Implication <|-- Iff
    ```

    """

    def __init__(self, left, right, **kwargs):
        super().__init__(left, right, **kwargs)

    @property
    def symbol(self):
        raise NotImplementedError

    def __str__(self):
        return f"({self.operands[0]} {self.symbol} {self.operands[1]})"

    def __repr__(self):
        return f"{type(self).__name__}({repr(self.operands[0])}, {repr(self.operands[1])})"

Implies dataclass

Bases: Implication

An if-then implication.

Corresponds to Implication in CommonLogic

>>> x = Variable('x')
>>> s = Iff(Term('likes', x, "root beer"), ~Term('likes', x, "marmite"))

You can also use syntactic sugar:

>>> s = Term('likes', x, "root beer") >> ~Term('likes', x, "marmite")
Source code in src/typedlogic/datamodel.py
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
@dataclass
class Implies(Implication):
    """
    An if-then implication.

    Corresponds to Implication in CommonLogic

        >>> x = Variable('x')
        >>> s = Iff(Term('likes', x, "root beer"), ~Term('likes', x, "marmite"))

    You can also use syntactic sugar:

        >>> s = Term('likes', x, "root beer") >> ~Term('likes', x, "marmite")

    """

    def __init__(self, antecedent, consequent, **kwargs):
        super().__init__(antecedent, consequent, **kwargs)

    @property
    def symbol(self):
        return "->"

    @property
    def antecedent(self):
        return self.operands[0]

    @property
    def consequent(self):
        return self.operands[1]

    def __str__(self):
        return f"({self.operands[0]} -> {self.operands[1]})"

    def __repr__(self):
        return f"Implies({repr(self.operands[0])}, {repr(self.operands[1])})"

Implied dataclass

Bases: Implication

An implication of the form consequent <- antecedent

Inverse of Implies

Source code in src/typedlogic/datamodel.py
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
@dataclass
class Implied(Implication):
    """
    An implication of the form consequent <- antecedent

    Inverse of `Implies`
    """

    def __init__(self, consequent, antecedent, **kwargs):
        super().__init__(consequent, antecedent, **kwargs)

    @property
    def symbol(self):
        return "<-"

    @property
    def antecedent(self):
        return self.operands[1]

    @property
    def consequent(self):
        return self.operands[0]

    def __str__(self):
        return f"({self.operands[0]} <- {self.operands[1]})"

    def __repr__(self):
        return f"Implied({repr(self.operands[0])}, {repr(self.operands[1])})"

Iff dataclass

Bases: Implication

An equivalence of sentences

Corresponds to Biconditional in CommonLogic.

>>> x = Variable('x')
>>> s = Iff(Term('likes', x, "jaffa cakes"), Term('likes', x, "marmite"))
Source code in src/typedlogic/datamodel.py
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
@dataclass
class Iff(Implication):
    """
    An equivalence of sentences

    Corresponds to Biconditional in CommonLogic.

        >>> x = Variable('x')
        >>> s = Iff(Term('likes', x, "jaffa cakes"), Term('likes', x, "marmite"))

    """

    def __init__(self, left, right, **kwargs):
        super().__init__(left, right, **kwargs)

    @property
    def symbol(self):
        return "<->"

    @property
    def left(self):
        return self.operands[0]

    @property
    def right(self):
        return self.operands[1]

    def __str__(self):
        return f"({self.operands[0]} <-> {self.operands[1]})"

    def __repr__(self):
        return f"Iff({repr(self.operands[0])}, {repr(self.operands[1])})"

NegationAsFailure dataclass

Bases: BooleanSentence

A negated sentence, interpreted via negation as failure semantics.

Source code in src/typedlogic/datamodel.py
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
@dataclass
class NegationAsFailure(BooleanSentence):
    """
    A negated sentence, interpreted via negation as failure semantics.
    """

    def __init__(self, operand, **kwargs):
        super().__init__(operand, **kwargs)

    def __str__(self):
        return f"NegationAsFailure{self.operands[0]}"

    def __repr__(self):
        return f"NegationAsFailure({repr(self.operands[0])})"

    @property
    def negated(self):
        return self.operands[0]

QuantifiedSentence dataclass

Bases: Sentence, ABC

A sentence with a logical quantifier.

classDiagram
QuantifiedSentence <|-- Forall
QuantifiedSentence <|-- Exists
QuantifiedSentence --> "*" Variable : variables
Source code in src/typedlogic/datamodel.py
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
@dataclass
class QuantifiedSentence(Sentence, ABC):
    """
    A sentence with a logical quantifier.

    ```mermaid
    classDiagram
    QuantifiedSentence <|-- Forall
    QuantifiedSentence <|-- Exists
    QuantifiedSentence --> "*" Variable : variables
    ```

    """

    variables: List[Variable]
    sentence: Sentence
    _annotations: Optional[Dict[str, Any]] = None

    @property
    def quantifier(self) -> str:
        raise NotImplementedError

    def _bindings_str(self) -> str:
        return ", ".join(f"{v.name}: {v.domain}" for v in self.variables)

    def __hash__(self):
        return hash((self.quantifier, tuple(self.variables), self.sentence))

    def as_sexpr(self) -> SExpression:
        return [type(self).__name__, [v.as_sexpr() for v in self.variables], self.sentence.as_sexpr()]

    @property
    def arguments(self) -> List[Any]:
        return [self.variables, self.sentence]

Forall dataclass

Bases: QuantifiedSentence

Universal quantifier.

>>> x = Variable('x')
>>> y = Variable('y')
>>> s = Forall([x, y], Implies(Term('friend_of', x, y), Term('friend_of', y, x)))
Source code in src/typedlogic/datamodel.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
@dataclass
class Forall(QuantifiedSentence):
    """
    Universal quantifier.

        >>> x = Variable('x')
        >>> y = Variable('y')
        >>> s = Forall([x, y], Implies(Term('friend_of', x, y), Term('friend_of', y, x)))

    """

    @property
    def quantifier(self) -> str:
        return "all"

    def __str__(self):
        return f"∀{self._bindings_str()} : {self.sentence}"

    def __repr__(self):
        return f"Forall([{self._bindings_str()}] : {repr(self.sentence)})"

Exists dataclass

Bases: QuantifiedSentence

Existential quantifier.

>>> x = Variable('x')
>>> y = Variable('y')
>>> s = ~Exists([x, y], And(Term('friend_of', x, y), Term('enemy_of', x, y)))
Source code in src/typedlogic/datamodel.py
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
@dataclass
class Exists(QuantifiedSentence):
    """
    Existential quantifier.

        >>> x = Variable('x')
        >>> y = Variable('y')
        >>> s = ~Exists([x, y], And(Term('friend_of', x, y), Term('enemy_of', x, y)))

    """

    @property
    def quantifier(self) -> str:
        return "exists"

    def __str__(self):
        return f"∃{self.sentence}"

    def __repr__(self):
        return f"Exists({self._bindings_str()} : {repr(self.sentence)})"

    def __hash__(self):
        return hash((self.quantifier, self._bindings_str(), self.sentence))

CardinalityConstraint dataclass

Bases: Term

A constraint on the cardinality of a set of terms.

Example:

>>> h = Variable("h")
>>> f = Variable("f")
>>> hp = Term("has_part", h, f)
>>> s = Forall([h], CardinalityConstraint(Term("has_part", h, f), Term("has_part", h, f), 5, 5))
Source code in src/typedlogic/datamodel.py
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
@dataclass
class CardinalityConstraint(Term):
    """
    A constraint on the cardinality of a set of terms.

    Example:

        >>> h = Variable("h")
        >>> f = Variable("f")
        >>> hp = Term("has_part", h, f)
        >>> s = Forall([h], CardinalityConstraint(Term("has_part", h, f), Term("has_part", h, f), 5, 5))

    """

    def __init__(self, template: Optional[Sentence], conditions: Sentence, minimum_number: Optional[int] = None, maximum_number: Optional[int] = None):
        """
        Initialize a CardinalityConstraint.

        :param template: The template sentence that defines the terms.
        :param conditions: The conditions that the terms must satisfy.
        :param minimum_number: The minimum number of terms that must satisfy the conditions.
        :param maximum_number: The maximum number of terms that can satisfy the conditions.
        """
        if not template:
            template = conditions
        super().__init__("CardinalityConstraint",
                         dict(template=template, conditions=conditions,
                              minimum_number=minimum_number, maximum_number=maximum_number))

    # TODO: decide on general strategy for extending Terms

    #template: Sentence
    #conditions: Sentence
    #minimum_number: Optional[int] = None
    #maximum_number: Optional[int] = None

    @property
    def template(self):
        return self.bindings.get("template")

    @property
    def conditions(self):
        return self.bindings.get("conditions")

    @property
    def minimum_number(self) -> Optional[int]:
        return self.bindings.get("minimum_number")

    @property
    def maximum_number(self) -> Optional[int]:
        return self.bindings.get("maximum_number")

    def __str__(self):
        return f"{self.minimum_number} <= {{ {self.template} : {self.conditions} }} <= {self.maximum_number}"

    def __repr__(self):
        return f"CardinalityConstraint({self.template}, {self.conditions}, {self.minimum_number}, {self.maximum_number})"

    def __hash__(self):
        return hash((self.template, self.conditions, str(self.maximum_number), str(self.minimum_number)))

__init__(template, conditions, minimum_number=None, maximum_number=None)

Initialize a CardinalityConstraint.

Parameters:

Name Type Description Default
template Optional[Sentence]

The template sentence that defines the terms.

required
conditions Sentence

The conditions that the terms must satisfy.

required
minimum_number Optional[int]

The minimum number of terms that must satisfy the conditions.

None
maximum_number Optional[int]

The maximum number of terms that can satisfy the conditions.

None
Source code in src/typedlogic/datamodel.py
953
954
955
956
957
958
959
960
961
962
963
964
965
966
def __init__(self, template: Optional[Sentence], conditions: Sentence, minimum_number: Optional[int] = None, maximum_number: Optional[int] = None):
    """
    Initialize a CardinalityConstraint.

    :param template: The template sentence that defines the terms.
    :param conditions: The conditions that the terms must satisfy.
    :param minimum_number: The minimum number of terms that must satisfy the conditions.
    :param maximum_number: The maximum number of terms that can satisfy the conditions.
    """
    if not template:
        template = conditions
    super().__init__("CardinalityConstraint",
                     dict(template=template, conditions=conditions,
                          minimum_number=minimum_number, maximum_number=maximum_number))

SentenceGroup dataclass

A logical grouping of related sentences with common documentation.

One way to collect these is via a decorated python function.

```mermaid classDiagram class SentenceGroup { +String name +SentenceGroupType group_type +String docstring +Dict annotations } SentenceGroup --> "*" Sentence : sentences

Source code in src/typedlogic/datamodel.py
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
@dataclass
class SentenceGroup:
    """
    A logical grouping of related sentences with common documentation.

    One way to collect these is via a decorated python function.

    ```mermaid
    classDiagram
    class SentenceGroup {
        +String name
        +SentenceGroupType group_type
        +String docstring
        +Dict annotations
    }
    SentenceGroup --> "*" Sentence : sentences

    """

    name: str
    group_type: Optional[SentenceGroupType] = None
    docstring: Optional[str] = None
    sentences: Optional[List[Sentence]] = None
    _annotations: Optional[Dict[str, Any]] = None

Theory dataclass

A collection of predicate definitions and sentences.

Analogous to a Text in CommonLogic.

classDiagram
class Theory {
    +String name
    +Dict constants
    +Dict type_definitions
    +List predicate_definitions
    +List sentence_groups
    +List ground_terms
    +Dict annotations
}
Theory --> "*" DefinedType : type_definitions
Theory --> "*" PredicateDefinition : predicate_definitions
Theory --> "*" Term : ground_terms
Theory --> "*" SentenceGroup : sentence_groups
Source code in src/typedlogic/datamodel.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
@dataclass
class Theory:
    """
    A collection of predicate definitions and sentences.

    Analogous to a Text in CommonLogic.

    ```mermaid
    classDiagram
    class Theory {
        +String name
        +Dict constants
        +Dict type_definitions
        +List predicate_definitions
        +List sentence_groups
        +List ground_terms
        +Dict annotations
    }
    Theory --> "*" DefinedType : type_definitions
    Theory --> "*" PredicateDefinition : predicate_definitions
    Theory --> "*" Term : ground_terms
    Theory --> "*" SentenceGroup : sentence_groups
    ```

    """

    name: Optional[str] = None
    constants: Dict[str, Any] = field(default_factory=dict)
    type_definitions: Dict[str, DefinedType] = field(default_factory=dict)
    predicate_definitions: List[PredicateDefinition] = field(default_factory=list)
    sentence_groups: List[SentenceGroup] = field(default_factory=list)
    ground_terms: List[Term] = field(default_factory=list)
    _annotations: Optional[Dict[str, Any]] = None
    source_module_name: Optional[str] = None

    @property
    def predicate_definition_map(self) -> Mapping[str, PredicateDefinition]:
        return {pd.predicate: pd for pd in self.predicate_definitions}

    @property
    def sentences(self) -> List[Sentence]:
        """
        Return all sentences in the theory

        :return:
        """
        if self.sentence_groups:
            return [s for sg in self.sentence_groups for s in sg.sentences or []]
        return []

    @property
    def goals(self) -> List[Sentence]:
        """
        Return all goal sentences in the theory

        :return:
        """
        return [
            s
            for sg in self.sentence_groups or []
            if sg.group_type == SentenceGroupType.GOAL
            for s in sg.sentences or []
        ]

    def add(self, sentence: Sentence):
        """
        Add a sentence to the theory

        :param sentence:
        :return:
        """
        if isinstance(sentence, Extension):
            sentence = sentence.to_model_object()
        if isinstance(sentence, TermBag):
            for t in sentence.as_terms():
                self.add(t)
            return
        if not self.sentence_groups:
            self.sentence_groups = []
        self.sentence_groups.append(SentenceGroup(name="Sentences", sentences=[sentence]))

    def extend(self, sentences: Iterable[Sentence]):
        """
        Add a list of sentences to the theory

        :param sentences:
        :return:
        """
        for s in sentences:
            self.add(s)

    def remove(self, sentence: Sentence, strict=False):
        """
        Remove a sentence to the theory

        :param sentence:
        :param strict:
        :return:
        """
        if isinstance(sentence, Extension):
            sentence = sentence.to_model_object()
        if not self.sentence_groups:
            if strict:
                raise ValueError("No sentences to remove from")
            return
        n = 0
        for sg in self.sentence_groups:
            if sg.sentences and sentence in sg.sentences:
                sg.sentences.remove(sentence)
                n += 1
        if n != 1 and strict:
            raise ValueError(f"Removed {n} sentences")

    def unroll_type(self, typ: DefinedType) -> List[str]:
        """
        Unroll a defined type into its components

        :param typ:
        :return:
        """
        if isinstance(typ, str):
            if typ in self.type_definitions:
                return self.unroll_type(self.type_definitions[typ])
            return [typ]
        if isinstance(typ, list):
            ts = []
            for t in typ:
                ts.extend(self.unroll_type(t))
            return ts
        raise ValueError(f"Unknown type {typ}")

sentences property

Return all sentences in the theory

Returns:

Type Description
List[Sentence]

goals property

Return all goal sentences in the theory

Returns:

Type Description
List[Sentence]

add(sentence)

Add a sentence to the theory

Parameters:

Name Type Description Default
sentence Sentence
required

Returns:

Type Description
Source code in src/typedlogic/datamodel.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def add(self, sentence: Sentence):
    """
    Add a sentence to the theory

    :param sentence:
    :return:
    """
    if isinstance(sentence, Extension):
        sentence = sentence.to_model_object()
    if isinstance(sentence, TermBag):
        for t in sentence.as_terms():
            self.add(t)
        return
    if not self.sentence_groups:
        self.sentence_groups = []
    self.sentence_groups.append(SentenceGroup(name="Sentences", sentences=[sentence]))

extend(sentences)

Add a list of sentences to the theory

Parameters:

Name Type Description Default
sentences Iterable[Sentence]
required

Returns:

Type Description
Source code in src/typedlogic/datamodel.py
1118
1119
1120
1121
1122
1123
1124
1125
1126
def extend(self, sentences: Iterable[Sentence]):
    """
    Add a list of sentences to the theory

    :param sentences:
    :return:
    """
    for s in sentences:
        self.add(s)

remove(sentence, strict=False)

Remove a sentence to the theory

Parameters:

Name Type Description Default
sentence Sentence
required
strict
False

Returns:

Type Description
Source code in src/typedlogic/datamodel.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
def remove(self, sentence: Sentence, strict=False):
    """
    Remove a sentence to the theory

    :param sentence:
    :param strict:
    :return:
    """
    if isinstance(sentence, Extension):
        sentence = sentence.to_model_object()
    if not self.sentence_groups:
        if strict:
            raise ValueError("No sentences to remove from")
        return
    n = 0
    for sg in self.sentence_groups:
        if sg.sentences and sentence in sg.sentences:
            sg.sentences.remove(sentence)
            n += 1
    if n != 1 and strict:
        raise ValueError(f"Removed {n} sentences")

unroll_type(typ)

Unroll a defined type into its components

Parameters:

Name Type Description Default
typ DefinedType
required

Returns:

Type Description
List[str]
Source code in src/typedlogic/datamodel.py
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
def unroll_type(self, typ: DefinedType) -> List[str]:
    """
    Unroll a defined type into its components

    :param typ:
    :return:
    """
    if isinstance(typ, str):
        if typ in self.type_definitions:
            return self.unroll_type(self.type_definitions[typ])
        return [typ]
    if isinstance(typ, list):
        ts = []
        for t in typ:
            ts.extend(self.unroll_type(t))
        return ts
    raise ValueError(f"Unknown type {typ}")

NotInProfileError

Bases: ValueError

Raised when a sentence is not in some profile

Source code in src/typedlogic/datamodel.py
1225
1226
1227
1228
1229
1230
class NotInProfileError(ValueError):
    """
    Raised when a sentence is not in some profile
    """

    pass

term(predicate, *args, **kwargs)

Create a term object.

Parameters:

Name Type Description Default
predicate Union[str, Type[Extension], Extension]
required
args
()
kwargs
{}

Returns:

Type Description
Term

Term object

Source code in src/typedlogic/datamodel.py
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def term(predicate: Union[str, Type[Extension], Extension], *args, **kwargs) -> Term:
    """
    Create a term object.

    :param predicate:
    :param args:
    :param kwargs:
    :return: Term object
    """
    if isinstance(predicate, Extension):
        s = predicate.to_model_object()
        if isinstance(s, Term):
            return s
        else:
            raise ValueError(f"Cannot convert {predicate} to a Term")
    if isinstance(predicate, type):
        predicate = predicate.__name__
    return Term(predicate, *args, **kwargs)

not_provable(predicate)

Function for Negation as Failure

Source code in src/typedlogic/datamodel.py
851
852
853
def not_provable(predicate):
    """Function for Negation as Failure"""
    return NegationAsFailure(predicate)

from_object(obj)

Convert a dictionary representation of a sentence or theory back to the original object.

Example:

>>> from_object({"type": "Term", "arguments": ["FriendOf", "Alice", "Bob"]})
FriendOf(Alice, Bob)

Parameters:

Name Type Description Default
obj Any
required

Returns:

Type Description
Any
Source code in src/typedlogic/datamodel.py
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
def from_object(obj: Any) -> Any:
    """
    Convert a dictionary representation of a sentence or theory back to the original object.

    Example:

        >>> from_object({"type": "Term", "arguments": ["FriendOf", "Alice", "Bob"]})
        FriendOf(Alice, Bob)

    :param obj:
    :return:
    """
    if isinstance(obj, dict):
        # type designation
        if "type" in obj:
            cls = globals()[obj["type"]]
            if cls in (PredicateDefinition, Theory, SentenceGroup):
                return cls(**{k: from_object(v) for k, v in obj.items() if k != "type"})
            else:
                args = obj.get("arguments", [])
                if issubclass(cls, Term) and cls != Term:
                    args = args[1:]  # skip the predicate name for Term subclasses
                args_tr = [from_object(x) for x in args]
                return cls(*args_tr)
        else:
            return obj
    if isinstance(obj, list):
        return [from_object(x) for x in obj]
    return obj