-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrt-MODIFIED.py
1480 lines (1233 loc) · 51.4 KB
/
drt-MODIFIED.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
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
# Natural Language Toolkit: Discourse Representation Theory (DRT)
#
# Author: Dan Garrette <[email protected]>
#
# Copyright (C) 2001-2022 NLTK Project
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
import operator
from functools import reduce
from itertools import chain
from nltk.sem.logic import (
APP,
AbstractVariableExpression,
AllExpression,
AndExpression,
ApplicationExpression,
BinaryExpression,
BooleanExpression,
ConstantExpression,
EqualityExpression,
EventVariableExpression,
ExistsExpression,
Expression,
FunctionVariableExpression,
ImpExpression,
IndividualVariableExpression,
LambdaExpression,
LogicParser,
NegatedExpression,
OrExpression,
Tokens,
Variable,
is_eventvar,
is_funcvar,
is_indvar,
unique_variable,
)
# Import Tkinter-based modules if they are available
try:
from tkinter import Canvas, Tk
from tkinter.font import Font
from nltk.util import in_idle
except ImportError:
# No need to print a warning here, nltk.draw has already printed one.
pass
class DrtTokens(Tokens):
DRS = "DRS"
DRS_CONC = "+"
PRONOUN = "PRO"
OPEN_BRACKET = "["
CLOSE_BRACKET = "]"
COLON = ":"
PUNCT = [DRS_CONC, OPEN_BRACKET, CLOSE_BRACKET, COLON]
SYMBOLS = Tokens.SYMBOLS + PUNCT
TOKENS = Tokens.TOKENS + [DRS] + PUNCT
class DrtParser(LogicParser):
"""A lambda calculus expression parser."""
def __init__(self):
LogicParser.__init__(self)
self.operator_precedence = dict(
[(x, 1) for x in DrtTokens.LAMBDA_LIST]
+ [(x, 2) for x in DrtTokens.NOT_LIST]
+ [(APP, 3)]
+ [(x, 4) for x in DrtTokens.EQ_LIST + Tokens.NEQ_LIST]
+ [(DrtTokens.COLON, 5)]
+ [(DrtTokens.DRS_CONC, 6)]
+ [(x, 7) for x in DrtTokens.OR_LIST]
+ [(x, 8) for x in DrtTokens.IMP_LIST]
+ [(None, 9)]
)
def get_all_symbols(self):
"""This method exists to be overridden"""
return DrtTokens.SYMBOLS
def isvariable(self, tok):
return tok not in DrtTokens.TOKENS
def handle(self, tok, context):
"""This method is intended to be overridden for logics that
use different operators or expressions"""
if tok in DrtTokens.NOT_LIST:
return self.handle_negation(tok, context)
elif tok in DrtTokens.LAMBDA_LIST:
return self.handle_lambda(tok, context)
elif tok == DrtTokens.OPEN:
if self.inRange(0) and self.token(0) == DrtTokens.OPEN_BRACKET:
return self.handle_DRS(tok, context)
else:
return self.handle_open(tok, context)
elif tok.upper() == DrtTokens.DRS:
self.assertNextToken(DrtTokens.OPEN)
return self.handle_DRS(tok, context)
elif self.isvariable(tok):
if self.inRange(0) and self.token(0) == DrtTokens.COLON:
return self.handle_prop(tok, context)
else:
return self.handle_variable(tok, context)
def make_NegatedExpression(self, expression):
return DrtNegatedExpression(expression)
def handle_DRS(self, tok, context):
# a DRS
refs = self.handle_refs()
if (
self.inRange(0) and self.token(0) == DrtTokens.COMMA
): # if there is a comma (it's optional)
self.token() # swallow the comma
conds = self.handle_conds(context)
self.assertNextToken(DrtTokens.CLOSE)
return DRS(refs, conds, None)
def handle_refs(self):
self.assertNextToken(DrtTokens.OPEN_BRACKET)
refs = []
while self.inRange(0) and self.token(0) != DrtTokens.CLOSE_BRACKET:
# Support expressions like: DRS([x y],C) == DRS([x,y],C)
if refs and self.token(0) == DrtTokens.COMMA:
self.token() # swallow the comma
refs.append(self.get_next_token_variable("quantified"))
self.assertNextToken(DrtTokens.CLOSE_BRACKET)
return refs
def handle_conds(self, context):
self.assertNextToken(DrtTokens.OPEN_BRACKET)
conds = []
while self.inRange(0) and self.token(0) != DrtTokens.CLOSE_BRACKET:
# Support expressions like: DRS([x y],C) == DRS([x, y],C)
if conds and self.token(0) == DrtTokens.COMMA:
self.token() # swallow the comma
conds.append(self.process_next_expression(context))
self.assertNextToken(DrtTokens.CLOSE_BRACKET)
return conds
def handle_prop(self, tok, context):
variable = self.make_VariableExpression(tok)
self.assertNextToken(":")
drs = self.process_next_expression(DrtTokens.COLON)
return DrtProposition(variable, drs)
def make_EqualityExpression(self, first, second):
"""This method serves as a hook for other logic parsers that
have different equality expression classes"""
return DrtEqualityExpression(first, second)
def get_BooleanExpression_factory(self, tok):
"""This method serves as a hook for other logic parsers that
have different boolean operators"""
if tok == DrtTokens.DRS_CONC:
return lambda first, second: DrtConcatenation(first, second, None)
elif tok in DrtTokens.OR_LIST:
return DrtOrExpression
elif tok in DrtTokens.IMP_LIST:
def make_imp_expression(first, second):
if isinstance(first, DRS):
return DRS(first.refs, first.conds, second)
if isinstance(first, DrtConcatenation):
return DrtConcatenation(first.first, first.second, second)
raise Exception("Antecedent of implication must be a DRS")
return make_imp_expression
else:
return None
def make_BooleanExpression(self, factory, first, second):
return factory(first, second)
def make_ApplicationExpression(self, function, argument):
return DrtApplicationExpression(function, argument)
def make_VariableExpression(self, name):
return DrtVariableExpression(Variable(name))
def make_LambdaExpression(self, variables, term):
return DrtLambdaExpression(variables, term)
class DrtExpression:
"""
This is the base abstract DRT Expression from which every DRT
Expression extends.
"""
_drt_parser = DrtParser()
@classmethod
def fromstring(cls, s):
return cls._drt_parser.parse(s)
def applyto(self, other):
return DrtApplicationExpression(self, other)
def __neg__(self):
return DrtNegatedExpression(self)
def __and__(self, other):
raise NotImplementedError()
def __or__(self, other):
assert isinstance(other, DrtExpression)
return DrtOrExpression(self, other)
def __gt__(self, other):
assert isinstance(other, DrtExpression)
if isinstance(self, DRS):
return DRS(self.refs, self.conds, other)
if isinstance(self, DrtConcatenation):
return DrtConcatenation(self.first, self.second, other)
raise Exception("Antecedent of implication must be a DRS")
def equiv(self, other, prover=None):
"""
Check for logical equivalence.
Pass the expression (self <-> other) to the theorem prover.
If the prover says it is valid, then the self and other are equal.
:param other: an ``DrtExpression`` to check equality against
:param prover: a ``nltk.inference.api.Prover``
"""
assert isinstance(other, DrtExpression)
f1 = self.simplify().fol()
f2 = other.simplify().fol()
return f1.equiv(f2, prover)
@property
def type(self):
raise AttributeError(
"'%s' object has no attribute 'type'" % self.__class__.__name__
)
def typecheck(self, signature=None):
raise NotImplementedError()
def __add__(self, other):
return DrtConcatenation(self, other, None)
def get_refs(self, recursive=False):
"""
Return the set of discourse referents in this DRS.
:param recursive: bool Also find discourse referents in subterms?
:return: list of ``Variable`` objects
"""
raise NotImplementedError()
def is_pronoun_function(self):
"""Is self of the form "PRO(x)"?"""
return (
isinstance(self, DrtApplicationExpression)
and isinstance(self.function, DrtAbstractVariableExpression)
and self.function.variable.name == DrtTokens.PRONOUN
and isinstance(self.argument, DrtIndividualVariableExpression)
)
def make_EqualityExpression(self, first, second):
return DrtEqualityExpression(first, second)
def make_VariableExpression(self, variable):
return DrtVariableExpression(variable)
def resolve_anaphora(self):
return resolve_anaphora(self)
def eliminate_equality(self):
return self.visit_structured(lambda e: e.eliminate_equality(), self.__class__)
def pretty_format(self):
"""
Draw the DRS
:return: the pretty print string
"""
return "\n".join(self._pretty())
def pretty_print(self):
print(self.pretty_format())
def draw(self):
DrsDrawer(self).draw()
class DRS(DrtExpression, Expression):
"""A Discourse Representation Structure."""
def __init__(self, refs, conds, consequent=None):
"""
:param refs: list of ``DrtIndividualVariableExpression`` for the
discourse referents
:param conds: list of ``Expression`` for the conditions
"""
self.refs = refs
self.conds = conds
self.consequent = consequent
def replace(self, variable, expression, replace_bound=False, alpha_convert=True):
"""Replace all instances of variable v with expression E in self,
where v is free in self."""
if variable in self.refs:
# if a bound variable is the thing being replaced
if not replace_bound:
return self
else:
i = self.refs.index(variable)
if self.consequent:
consequent = self.consequent.replace(
variable, expression, True, alpha_convert
)
else:
consequent = None
return DRS(
self.refs[:i] + [expression.variable] + self.refs[i + 1 :],
[
cond.replace(variable, expression, True, alpha_convert)
for cond in self.conds
],
consequent,
)
else:
if alpha_convert:
# any bound variable that appears in the expression must
# be alpha converted to avoid a conflict
for ref in set(self.refs) & expression.free():
newvar = unique_variable(ref)
newvarex = DrtVariableExpression(newvar)
i = self.refs.index(ref)
if self.consequent:
consequent = self.consequent.replace(
ref, newvarex, True, alpha_convert
)
else:
consequent = None
self = DRS(
self.refs[:i] + [newvar] + self.refs[i + 1 :],
[
cond.replace(ref, newvarex, True, alpha_convert)
for cond in self.conds
],
consequent,
)
# replace in the conditions
if self.consequent:
consequent = self.consequent.replace(
variable, expression, replace_bound, alpha_convert
)
else:
consequent = None
return DRS(
self.refs,
[
cond.replace(variable, expression, replace_bound, alpha_convert)
for cond in self.conds
],
consequent,
)
def free(self):
""":see: Expression.free()"""
conds_free = reduce(operator.or_, [c.free() for c in self.conds], set())
if self.consequent:
conds_free.update(self.consequent.free())
return conds_free - set(self.refs)
def get_refs(self, recursive=False):
""":see: AbstractExpression.get_refs()"""
if recursive:
conds_refs = self.refs + list(
chain.from_iterable(c.get_refs(True) for c in self.conds)
)
if self.consequent:
conds_refs.extend(self.consequent.get_refs(True))
return conds_refs
else:
return self.refs
def visit(self, function, combinator):
""":see: Expression.visit()"""
parts = list(map(function, self.conds))
if self.consequent:
parts.append(function(self.consequent))
return combinator(parts)
def visit_structured(self, function, combinator):
""":see: Expression.visit_structured()"""
consequent = function(self.consequent) if self.consequent else None
return combinator(self.refs, list(map(function, self.conds)), consequent)
def eliminate_equality(self):
drs = self
i = 0
while i < len(drs.conds):
cond = drs.conds[i]
if (
isinstance(cond, EqualityExpression)
and isinstance(cond.first, AbstractVariableExpression)
and isinstance(cond.second, AbstractVariableExpression)
):
drs = DRS(
list(set(drs.refs) - {cond.second.variable}),
drs.conds[:i] + drs.conds[i + 1 :],
drs.consequent,
)
if cond.second.variable != cond.first.variable:
drs = drs.replace(cond.second.variable, cond.first, False, False)
i = 0
i -= 1
i += 1
conds = []
for cond in drs.conds:
new_cond = cond.eliminate_equality()
new_cond_simp = new_cond.simplify()
if (
not isinstance(new_cond_simp, DRS)
or new_cond_simp.refs
or new_cond_simp.conds
or new_cond_simp.consequent
):
conds.append(new_cond)
consequent = drs.consequent.eliminate_equality() if drs.consequent else None
return DRS(drs.refs, conds, consequent)
def fol(self):
if self.consequent:
accum = None
if self.conds:
accum = reduce(AndExpression, [c.fol() for c in self.conds])
if accum:
accum = ImpExpression(accum, self.consequent.fol())
else:
accum = self.consequent.fol()
for ref in self.refs[::-1]:
accum = AllExpression(ref, accum)
return accum
else:
if not self.conds:
raise Exception("Cannot convert DRS with no conditions to FOL.")
accum = reduce(AndExpression, [c.fol() for c in self.conds])
for ref in map(Variable, self._order_ref_strings(self.refs)[::-1]):
accum = ExistsExpression(ref, accum)
return accum
def _pretty(self):
refs_line = " ".join(self._order_ref_strings(self.refs))
cond_lines = [
cond
for cond_line in [
filter(lambda s: s.strip(), cond._pretty()) for cond in self.conds
]
for cond in cond_line
]
length = max([len(refs_line)] + list(map(len, cond_lines)))
drs = (
[
" _" + "_" * length + "_ ",
"| " + refs_line.ljust(length) + " |",
"|-" + "-" * length + "-|",
]
+ ["| " + line.ljust(length) + " |" for line in cond_lines]
+ ["|_" + "_" * length + "_|"]
)
if self.consequent:
return DrtBinaryExpression._assemble_pretty(
drs, DrtTokens.IMP, self.consequent._pretty()
)
return drs
def _order_ref_strings(self, refs):
strings = ["%s" % ref for ref in refs]
ind_vars = []
func_vars = []
event_vars = []
other_vars = []
for s in strings:
if is_indvar(s):
ind_vars.append(s)
elif is_funcvar(s):
func_vars.append(s)
elif is_eventvar(s):
event_vars.append(s)
else:
other_vars.append(s)
return (
sorted(other_vars)
+ sorted(event_vars, key=lambda v: int([v[2:], -1][len(v[2:]) == 0]))
+ sorted(func_vars, key=lambda v: (v[0], int([v[1:], -1][len(v[1:]) == 0])))
+ sorted(ind_vars, key=lambda v: (v[0], int([v[1:], -1][len(v[1:]) == 0])))
)
def __eq__(self, other):
r"""Defines equality modulo alphabetic variance.
If we are comparing \x.M and \y.N, then check equality of M and N[x/y]."""
if isinstance(other, DRS):
if len(self.refs) == len(other.refs):
converted_other = other
for (r1, r2) in zip(self.refs, converted_other.refs):
varex = self.make_VariableExpression(r1)
converted_other = converted_other.replace(r2, varex, True)
if self.consequent == converted_other.consequent and len(
self.conds
) == len(converted_other.conds):
for c1, c2 in zip(self.conds, converted_other.conds):
if not (c1 == c2):
return False
return True
return False
def __ne__(self, other):
return not self == other
__hash__ = Expression.__hash__
def __str__(self):
drs = "([{}],[{}])".format(
",".join(self._order_ref_strings(self.refs)),
", ".join("%s" % cond for cond in self.conds),
) # map(str, self.conds)))
if self.consequent:
return (
DrtTokens.OPEN
+ drs
+ " "
+ DrtTokens.IMP
+ " "
+ "%s" % self.consequent
+ DrtTokens.CLOSE
)
return drs
def DrtVariableExpression(variable):
"""
This is a factory method that instantiates and returns a subtype of
``DrtAbstractVariableExpression`` appropriate for the given variable.
"""
if is_indvar(variable.name):
return DrtIndividualVariableExpression(variable)
elif is_funcvar(variable.name):
return DrtFunctionVariableExpression(variable)
elif is_eventvar(variable.name):
return DrtEventVariableExpression(variable)
else:
return DrtConstantExpression(variable)
class DrtAbstractVariableExpression(DrtExpression, AbstractVariableExpression):
def fol(self):
return self
def get_refs(self, recursive=False):
""":see: AbstractExpression.get_refs()"""
return []
def _pretty(self):
s = "%s" % self
blank = " " * len(s)
return [blank, blank, s, blank]
def eliminate_equality(self):
return self
class DrtIndividualVariableExpression(
DrtAbstractVariableExpression, IndividualVariableExpression
):
pass
class DrtFunctionVariableExpression(
DrtAbstractVariableExpression, FunctionVariableExpression
):
pass
class DrtEventVariableExpression(
DrtIndividualVariableExpression, EventVariableExpression
):
pass
class DrtConstantExpression(DrtAbstractVariableExpression, ConstantExpression):
pass
class DrtProposition(DrtExpression, Expression):
def __init__(self, variable, drs):
self.variable = variable
self.drs = drs
def replace(self, variable, expression, replace_bound=False, alpha_convert=True):
if self.variable == variable:
assert isinstance(
expression, DrtAbstractVariableExpression
), "Can only replace a proposition label with a variable"
return DrtProposition(
expression.variable,
self.drs.replace(variable, expression, replace_bound, alpha_convert),
)
else:
return DrtProposition(
self.variable,
self.drs.replace(variable, expression, replace_bound, alpha_convert),
)
def eliminate_equality(self):
return DrtProposition(self.variable, self.drs.eliminate_equality())
def get_refs(self, recursive=False):
return self.drs.get_refs(True) if recursive else []
def __eq__(self, other):
return (
self.__class__ == other.__class__
and self.variable == other.variable
and self.drs == other.drs
)
def __ne__(self, other):
return not self == other
__hash__ = Expression.__hash__
def fol(self):
return self.drs.fol()
def _pretty(self):
drs_s = self.drs._pretty()
blank = " " * len("%s" % self.variable)
return (
[blank + " " + line for line in drs_s[:1]]
+ ["%s" % self.variable + ":" + line for line in drs_s[1:2]]
+ [blank + " " + line for line in drs_s[2:]]
)
def visit(self, function, combinator):
""":see: Expression.visit()"""
return combinator([function(self.drs)])
def visit_structured(self, function, combinator):
""":see: Expression.visit_structured()"""
return combinator(self.variable, function(self.drs))
def __str__(self):
return f"prop({self.variable}, {self.drs})"
class DrtNegatedExpression(DrtExpression, NegatedExpression):
def fol(self):
return NegatedExpression(self.term.fol())
def get_refs(self, recursive=False):
""":see: AbstractExpression.get_refs()"""
return self.term.get_refs(recursive)
def _pretty(self):
term_lines = self.term._pretty()
return (
[" " + line for line in term_lines[:2]]
+ ["__ " + line for line in term_lines[2:3]]
+ [" | " + line for line in term_lines[3:4]]
+ [" " + line for line in term_lines[4:]]
)
class DrtLambdaExpression(DrtExpression, LambdaExpression):
def alpha_convert(self, newvar):
"""Rename all occurrences of the variable introduced by this variable
binder in the expression to ``newvar``.
:param newvar: ``Variable``, for the new variable
"""
return self.__class__(
newvar,
self.term.replace(self.variable, DrtVariableExpression(newvar), True),
)
def fol(self):
return LambdaExpression(self.variable, self.term.fol())
def _pretty(self):
variables = [self.variable]
term = self.term
while term.__class__ == self.__class__:
variables.append(term.variable)
term = term.term
var_string = " ".join("%s" % v for v in variables) + DrtTokens.DOT
term_lines = term._pretty()
blank = " " * len(var_string)
return (
[" " + blank + line for line in term_lines[:1]]
+ [r" \ " + blank + line for line in term_lines[1:2]]
+ [r" /\ " + var_string + line for line in term_lines[2:3]]
+ [" " + blank + line for line in term_lines[3:]]
)
def get_refs(self, recursive=False):
""":see: AbstractExpression.get_refs()"""
return (
[self.variable] + self.term.get_refs(True) if recursive else [self.variable]
)
class DrtBinaryExpression(DrtExpression, BinaryExpression):
def get_refs(self, recursive=False):
""":see: AbstractExpression.get_refs()"""
return (
self.first.get_refs(True) + self.second.get_refs(True) if recursive else []
)
def _pretty(self):
return DrtBinaryExpression._assemble_pretty(
self._pretty_subex(self.first),
self.getOp(),
self._pretty_subex(self.second),
)
@staticmethod
def _assemble_pretty(first_lines, op, second_lines):
max_lines = max(len(first_lines), len(second_lines))
first_lines = _pad_vertically(first_lines, max_lines)
second_lines = _pad_vertically(second_lines, max_lines)
blank = " " * len(op)
first_second_lines = list(zip(first_lines, second_lines))
return (
[
" " + first_line + " " + blank + " " + second_line + " "
for first_line, second_line in first_second_lines[:2]
]
+ [
"(" + first_line + " " + op + " " + second_line + ")"
for first_line, second_line in first_second_lines[2:3]
]
+ [
" " + first_line + " " + blank + " " + second_line + " "
for first_line, second_line in first_second_lines[3:]
]
)
def _pretty_subex(self, subex):
return subex._pretty()
class DrtBooleanExpression(DrtBinaryExpression, BooleanExpression):
pass
class DrtOrExpression(DrtBooleanExpression, OrExpression):
def fol(self):
return OrExpression(self.first.fol(), self.second.fol())
def _pretty_subex(self, subex):
if isinstance(subex, DrtOrExpression):
return [line[1:-1] for line in subex._pretty()]
return DrtBooleanExpression._pretty_subex(self, subex)
class DrtEqualityExpression(DrtBinaryExpression, EqualityExpression):
def fol(self):
return EqualityExpression(self.first.fol(), self.second.fol())
class DrtConcatenation(DrtBooleanExpression):
"""DRS of the form '(DRS + DRS)'"""
def __init__(self, first, second, consequent=None):
DrtBooleanExpression.__init__(self, first, second)
self.consequent = consequent
def replace(self, variable, expression, replace_bound=False, alpha_convert=True):
"""Replace all instances of variable v with expression E in self,
where v is free in self."""
first = self.first
second = self.second
consequent = self.consequent
# If variable is bound
if variable in self.get_refs():
if replace_bound:
first = first.replace(
variable, expression, replace_bound, alpha_convert
)
second = second.replace(
variable, expression, replace_bound, alpha_convert
)
if consequent:
consequent = consequent.replace(
variable, expression, replace_bound, alpha_convert
)
else:
if alpha_convert:
# alpha convert every ref that is free in 'expression'
for ref in set(self.get_refs(True)) & expression.free():
v = DrtVariableExpression(unique_variable(ref))
first = first.replace(ref, v, True, alpha_convert)
second = second.replace(ref, v, True, alpha_convert)
if consequent:
consequent = consequent.replace(ref, v, True, alpha_convert)
first = first.replace(variable, expression, replace_bound, alpha_convert)
second = second.replace(variable, expression, replace_bound, alpha_convert)
if consequent:
consequent = consequent.replace(
variable, expression, replace_bound, alpha_convert
)
return self.__class__(first, second, consequent)
def eliminate_equality(self):
# TODO: at some point. for now, simplify.
drs = self.simplify()
assert not isinstance(drs, DrtConcatenation)
return drs.eliminate_equality()
def simplify(self):
first = self.first.simplify()
second = self.second.simplify()
consequent = self.consequent.simplify() if self.consequent else None
if isinstance(first, DRS) and isinstance(second, DRS):
# For any ref that is in both 'first' and 'second'
for ref in set(first.get_refs(True)) & set(second.get_refs(True)):
# alpha convert the ref in 'second' to prevent collision
newvar = DrtVariableExpression(unique_variable(ref))
second = second.replace(ref, newvar, True)
return DRS(first.refs + second.refs, first.conds + second.conds, consequent)
else:
return self.__class__(first, second, consequent)
def get_refs(self, recursive=False):
""":see: AbstractExpression.get_refs()"""
refs = self.first.get_refs(recursive) + self.second.get_refs(recursive)
if self.consequent and recursive:
refs.extend(self.consequent.get_refs(True))
return refs
def getOp(self):
return DrtTokens.DRS_CONC
def __eq__(self, other):
r"""Defines equality modulo alphabetic variance.
If we are comparing \x.M and \y.N, then check equality of M and N[x/y]."""
if isinstance(other, DrtConcatenation):
self_refs = self.get_refs()
other_refs = other.get_refs()
if len(self_refs) == len(other_refs):
converted_other = other
for (r1, r2) in zip(self_refs, other_refs):
varex = self.make_VariableExpression(r1)
converted_other = converted_other.replace(r2, varex, True)
return (
self.first == converted_other.first
and self.second == converted_other.second
and self.consequent == converted_other.consequent
)
return False
def __ne__(self, other):
return not self == other
__hash__ = DrtBooleanExpression.__hash__
def fol(self):
e = AndExpression(self.first.fol(), self.second.fol())
if self.consequent:
e = ImpExpression(e, self.consequent.fol())
return e
def _pretty(self):
drs = DrtBinaryExpression._assemble_pretty(
self._pretty_subex(self.first),
self.getOp(),
self._pretty_subex(self.second),
)
if self.consequent:
drs = DrtBinaryExpression._assemble_pretty(
drs, DrtTokens.IMP, self.consequent._pretty()
)
return drs
def _pretty_subex(self, subex):
if isinstance(subex, DrtConcatenation):
return [line[1:-1] for line in subex._pretty()]
return DrtBooleanExpression._pretty_subex(self, subex)
def visit(self, function, combinator):
""":see: Expression.visit()"""
if self.consequent:
return combinator(
[function(self.first), function(self.second), function(self.consequent)]
)
else:
return combinator([function(self.first), function(self.second)])
def __str__(self):
first = self._str_subex(self.first)
second = self._str_subex(self.second)
drs = Tokens.OPEN + first + " " + self.getOp() + " " + second + Tokens.CLOSE
if self.consequent:
return (
DrtTokens.OPEN
+ drs
+ " "
+ DrtTokens.IMP
+ " "
+ "%s" % self.consequent
+ DrtTokens.CLOSE
)
return drs
def _str_subex(self, subex):
s = "%s" % subex
if isinstance(subex, DrtConcatenation) and subex.consequent is None:
return s[1:-1]
return s
class DrtApplicationExpression(DrtExpression, ApplicationExpression):
def fol(self):
return ApplicationExpression(self.function.fol(), self.argument.fol())
def get_refs(self, recursive=False):
""":see: AbstractExpression.get_refs()"""
return (
self.function.get_refs(True) + self.argument.get_refs(True)
if recursive
else []
)
def _pretty(self):
function, args = self.uncurry()
function_lines = function._pretty()
args_lines = [arg._pretty() for arg in args]
max_lines = max(map(len, [function_lines] + args_lines))
function_lines = _pad_vertically(function_lines, max_lines)
args_lines = [_pad_vertically(arg_lines, max_lines) for arg_lines in args_lines]
func_args_lines = list(zip(function_lines, list(zip(*args_lines))))
return (
[
func_line + " " + " ".join(args_line) + " "
for func_line, args_line in func_args_lines[:2]
]
+ [
func_line + "(" + ",".join(args_line) + ")"
for func_line, args_line in func_args_lines[2:3]
]
+ [
func_line + " " + " ".join(args_line) + " "
for func_line, args_line in func_args_lines[3:]
]
)
# MARK This is the edited part!
def simplify(self):
function = self.function.simplify()
argument = self.argument.simplify()
if isinstance(function, LambdaExpression):
# TODO make sure this fits with the ethos of the module
alsobound = []
term = function.term
while isinstance(term, LambdaExpression):
alsobound.append(term.variable)
term = term.term
newargument = argument
for var in alsobound:
if var not in newargument.free():
newargument = newargument.replace(var,DrtVariableExpression(unique_variable(pattern=var)),replace_bound=True)
return function.term.replace(function.variable, newargument).simplify()
else:
return self.__class__(function, argument)
# MARK End of the edited part!
def _pad_vertically(lines, max_lines):
pad_line = [" " * len(lines[0])]
return lines + pad_line * (max_lines - len(lines))