forked from EvgSkv/logica
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavatar.py
240 lines (200 loc) · 7.58 KB
/
avatar.py
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
#!/usr/bin/python
#
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Python representation of Logica propositions, expressions and rules.
# Example usage:
# P = avatar.Predicate('P')
# T = avatar.Predicate('T')
# F = avatar.Predicate('F')
# x, y, z = avatar.Variables('x', 'y', 'z')
# Aggr = avatar.Aggregation
# print(+P(a=x, b=Aggr('List', y), c = F(x=y)) << T(x, y, z=x))
#
# Prints:
# P(a: x, b? List= y, c: F(x: y)) distinct :- T(x, y, z: x)
class LogicalTerm:
"""Proposition or expression."""
@classmethod
def FromSyntax(cls, syntax):
if 'call' in syntax:
p = Predicate(syntax['call']['predicate_name'])
positional_args = []
named_args = {}
for fv in syntax['call']['record']['field_value']:
value = cls.FromSyntax(fv['value']['expression'])
if isinstance(fv['field'], int):
positional_args[fv['field']:fv['field']] = [value]
else:
named_args[fv['field']] = value
return p(*positional_args, **named_args)
if 'literal' in syntax:
literal = syntax['literal']
if 'the_number' in literal:
number_str = literal['the_number']['number']
if '.' in number_str:
return Literal(float(number_str))
return Literal(int(number_str))
if 'the_string' in literal:
return Literal(literal['the_string']['the_string'])
if 'the_list' in literal:
return Literal([LogicalTerm.FromSyntax(e)
for e in literal['the_list']['element']])
assert False, syntax
assert False, syntax
class Literal(LogicalTerm):
def __init__(self, value):
self.value = value
def __str__(self):
def Render(x):
if isinstance(x, int) or isinstance(x, float):
return str(x)
if isinstance(x, list):
return '[%s]' % ', '.join(map(Render, x))
if isinstance(x, dict):
return '{%s}' % ', '.join('%s: %s' % (k, Render(v))
for k, v in x.items())
if isinstance(x, str):
assert '"' not in x, x
assert '\\' not in x, x
return '"%s"' % x
if isinstance(x, LogicalTerm):
return str(x)
assert False, x
return Render(self.value)
def AsJson(self):
value = self.value
if (isinstance(value, int) or
isinstance(value, float) or
isinstance(value, str)):
return value
if isinstance(value, list):
return [x.AsJson() for x in value]
if isinstance(value, dict):
return {k: v.AsJson() for k, v in value}
assert False
class PredicateCall(LogicalTerm):
def __init__(self, predicate_name,
positional_args, named_args,
distinct_denoted=None):
def Digest(x):
if (isinstance(x, int) or isinstance(x, float) or
isinstance(x, list) or isinstance(x, dict)):
return Literal(x)
return x
self.predicate_name = predicate_name
self.positional_args = list(map(Digest, positional_args))
self.named_args = {k: Digest(v) for k, v in named_args.items()}
self.names_aggregated = [name
for name in self.named_args
if isinstance(self.named_args[name], Aggregation)]
self.distinct_denoted = distinct_denoted
def __pos__(self):
return PredicateCall(self.predicate_name, self.positional_args, self.named_args,
True)
def __str__(self):
def RenderKeyValue(k, v):
if k in self.names_aggregated:
return '%s? %s= %s' % (
k, v.aggregating_operator, v.aggregated_expression
)
if isinstance(v, Variable) and k == v.name:
return '%s:' % k
return '%s: %s' % (k, v)
assert self.distinct_denoted or not self.names_aggregated, (
self.predicate_name, self.positional_args, self.named_args,
self.names_aggregated, self.distinct_denoted)
for x in list(self.positional_args) + list(self.named_args.values()):
assert isinstance(x, LogicalTerm), x
positional = ', '.join(map(str, self.positional_args))
named = ', '.join(RenderKeyValue(k, v)
for k, v in self.named_args.items())
t = filter(None, [positional, named])
distinct_str = ' distinct' if self.distinct_denoted else ''
return '%s(%s)%s' % (self.predicate_name, ', '.join(t),
distinct_str)
def __lshift__(self, body):
return Rule(self, body)
def __and__(self, other_conjunct):
if isinstance(other_conjunct, Conjunction):
return Conjunction([self] + other_conjunct.conjuncts)
return Conjunction([self, other_conjunct])
def __call__(self, *positional_args, **named_args):
new_positional_args = self.positional_args
new_positional_args[0:len(positional_args)] = positional_args
new_named_args = dict(list(self.named_args.items()) +
list(named_args.items()))
return PredicateCall(self.predicate_name,
new_positional_args, new_named_args)
class Subscript(LogicalTerm):
def __init__(self, record, field):
self.record = record
self.field = field
def __str__(self):
return '%s.%s' % (self.record, self.field)
class Rule:
def __init__(self, head: PredicateCall, body):
self.head = head
self.body = body
self.comment_before_rule : str = None
def __str__(self):
if self.comment_before_rule:
comment = '# ' + '# '.join(self.comment_before_rule.split('\n')) + '\n'
else:
comment = ''
if self.body:
return '%s%s :- %s' % (comment, self.head, self.body)
else:
return comment + str(self.head)
class Conjunction(LogicalTerm):
def __init__(self, conjuncts):
self.conjuncts = conjuncts
def __str__(self):
return '\n ' + ',\n '.join(map(str, self.conjuncts))
def __and__(self, other_conjunct):
if isinstance(other_conjunct, Conjunction):
return Conjunction(self.conjuncts + other_conjunct.conjuncts)
return Conjunction(self.conjuncts + [other_conjunct])
class Disjunction(LogicalTerm):
def __init__(self, disjuncts):
self.disjuncts = disjuncts
def __str__(self):
return '\n ' + ' |\n '.join(map(lambda x: '(%s)' % x, self.disjuncts))
def __or__(self, other_disjunct):
if isinstance(other_disjunct, Disjunction):
return Disjunction(self.disjuncts + other_disjunct.disjuncts)
return Disjunction(self.disjuncts + [other_disjunct])
class Variable(LogicalTerm):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def Variables(*variables):
return map(Variable, variables)
class Aggregation(LogicalTerm):
def __init__(self, aggregating_operator, aggregated_expression):
self.aggregating_operator = aggregating_operator
self.aggregated_expression = aggregated_expression
class Predicate:
def __init__(self, predicate_name):
self.predicate_name = predicate_name
def __call__(self, *args, **named_args):
return PredicateCall(self.predicate_name, args, named_args)
class Program:
def __init__(self, rules):
self.rules = rules
def AddRule(self, rule):
self.rules.append(rule)
def __str__(self):
return ';\n\n'.join(map(str, self.rules))