assassinlike commited on
Commit
6ebc2a7
·
verified ·
1 Parent(s): f540d5d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__init__.py +34 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/__init__.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/api.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/chart.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/combinator.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/lexicon.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/logic.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/api.py +358 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/chart.py +480 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/combinator.py +339 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/lexicon.py +338 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/logic.py +60 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__init__.py +529 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/europarl_raw.py +56 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/util.py +154 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__init__.py +24 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/__init__.cpython-310.pyc +0 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/api.cpython-310.pyc +0 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/discourse.cpython-310.pyc +0 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/mace.cpython-310.pyc +0 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/nonmonotonic.cpython-310.pyc +0 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/prover9.cpython-310.pyc +0 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/resolution.cpython-310.pyc +0 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/tableau.cpython-310.pyc +0 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/api.py +614 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/discourse.py +651 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/mace.py +383 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/nonmonotonic.py +561 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/prover9.py +508 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/resolution.py +759 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/tableau.py +712 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__init__.py +102 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/__init__.cpython-310.pyc +0 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/api.cpython-310.pyc +0 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/bllip.cpython-310.pyc +0 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/chart.cpython-310.pyc +0 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/corenlp.cpython-310.pyc +0 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/dependencygraph.cpython-310.pyc +0 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/earleychart.cpython-310.pyc +0 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/evaluate.cpython-310.pyc +0 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/featurechart.cpython-310.pyc +0 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/generate.cpython-310.pyc +0 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/malt.cpython-310.pyc +0 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/nonprojectivedependencyparser.cpython-310.pyc +0 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/pchart.cpython-310.pyc +0 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/projectivedependencyparser.cpython-310.pyc +0 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/recursivedescent.cpython-310.pyc +0 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/shiftreduce.cpython-310.pyc +0 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/stanford.cpython-310.pyc +0 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/transitionparser.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Combinatory Categorial Grammar
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Graeme Gange <ggange@csse.unimelb.edu.au>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+
8
+ """
9
+ Combinatory Categorial Grammar.
10
+
11
+ For more information see nltk/doc/contrib/ccg/ccg.pdf
12
+ """
13
+
14
+ from nltk.ccg.chart import CCGChart, CCGChartParser, CCGEdge, CCGLeafEdge
15
+ from nltk.ccg.combinator import (
16
+ BackwardApplication,
17
+ BackwardBx,
18
+ BackwardCombinator,
19
+ BackwardComposition,
20
+ BackwardSx,
21
+ BackwardT,
22
+ DirectedBinaryCombinator,
23
+ ForwardApplication,
24
+ ForwardCombinator,
25
+ ForwardComposition,
26
+ ForwardSubstitution,
27
+ ForwardT,
28
+ UndirectedBinaryCombinator,
29
+ UndirectedComposition,
30
+ UndirectedFunctionApplication,
31
+ UndirectedSubstitution,
32
+ UndirectedTypeRaise,
33
+ )
34
+ from nltk.ccg.lexicon import CCGLexicon
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (976 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/api.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/chart.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/combinator.cpython-310.pyc ADDED
Binary file (9.18 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/lexicon.cpython-310.pyc ADDED
Binary file (7.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/__pycache__/logic.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/api.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: CCG Categories
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Graeme Gange <ggange@csse.unimelb.edu.au>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+
8
+ from abc import ABCMeta, abstractmethod
9
+ from functools import total_ordering
10
+
11
+ from nltk.internals import raise_unorderable_types
12
+
13
+
14
+ @total_ordering
15
+ class AbstractCCGCategory(metaclass=ABCMeta):
16
+ """
17
+ Interface for categories in combinatory grammars.
18
+ """
19
+
20
+ @abstractmethod
21
+ def is_primitive(self):
22
+ """
23
+ Returns true if the category is primitive.
24
+ """
25
+
26
+ @abstractmethod
27
+ def is_function(self):
28
+ """
29
+ Returns true if the category is a function application.
30
+ """
31
+
32
+ @abstractmethod
33
+ def is_var(self):
34
+ """
35
+ Returns true if the category is a variable.
36
+ """
37
+
38
+ @abstractmethod
39
+ def substitute(self, substitutions):
40
+ """
41
+ Takes a set of (var, category) substitutions, and replaces every
42
+ occurrence of the variable with the corresponding category.
43
+ """
44
+
45
+ @abstractmethod
46
+ def can_unify(self, other):
47
+ """
48
+ Determines whether two categories can be unified.
49
+ - Returns None if they cannot be unified
50
+ - Returns a list of necessary substitutions if they can.
51
+ """
52
+
53
+ # Utility functions: comparison, strings and hashing.
54
+ @abstractmethod
55
+ def __str__(self):
56
+ pass
57
+
58
+ def __eq__(self, other):
59
+ return (
60
+ self.__class__ is other.__class__
61
+ and self._comparison_key == other._comparison_key
62
+ )
63
+
64
+ def __ne__(self, other):
65
+ return not self == other
66
+
67
+ def __lt__(self, other):
68
+ if not isinstance(other, AbstractCCGCategory):
69
+ raise_unorderable_types("<", self, other)
70
+ if self.__class__ is other.__class__:
71
+ return self._comparison_key < other._comparison_key
72
+ else:
73
+ return self.__class__.__name__ < other.__class__.__name__
74
+
75
+ def __hash__(self):
76
+ try:
77
+ return self._hash
78
+ except AttributeError:
79
+ self._hash = hash(self._comparison_key)
80
+ return self._hash
81
+
82
+
83
+ class CCGVar(AbstractCCGCategory):
84
+ """
85
+ Class representing a variable CCG category.
86
+ Used for conjunctions (and possibly type-raising, if implemented as a
87
+ unary rule).
88
+ """
89
+
90
+ _maxID = 0
91
+
92
+ def __init__(self, prim_only=False):
93
+ """Initialize a variable (selects a new identifier)
94
+
95
+ :param prim_only: a boolean that determines whether the variable is
96
+ restricted to primitives
97
+ :type prim_only: bool
98
+ """
99
+ self._id = self.new_id()
100
+ self._prim_only = prim_only
101
+ self._comparison_key = self._id
102
+
103
+ @classmethod
104
+ def new_id(cls):
105
+ """
106
+ A class method allowing generation of unique variable identifiers.
107
+ """
108
+ cls._maxID = cls._maxID + 1
109
+ return cls._maxID - 1
110
+
111
+ @classmethod
112
+ def reset_id(cls):
113
+ cls._maxID = 0
114
+
115
+ def is_primitive(self):
116
+ return False
117
+
118
+ def is_function(self):
119
+ return False
120
+
121
+ def is_var(self):
122
+ return True
123
+
124
+ def substitute(self, substitutions):
125
+ """If there is a substitution corresponding to this variable,
126
+ return the substituted category.
127
+ """
128
+ for (var, cat) in substitutions:
129
+ if var == self:
130
+ return cat
131
+ return self
132
+
133
+ def can_unify(self, other):
134
+ """If the variable can be replaced with other
135
+ a substitution is returned.
136
+ """
137
+ if other.is_primitive() or not self._prim_only:
138
+ return [(self, other)]
139
+ return None
140
+
141
+ def id(self):
142
+ return self._id
143
+
144
+ def __str__(self):
145
+ return "_var" + str(self._id)
146
+
147
+
148
+ @total_ordering
149
+ class Direction:
150
+ """
151
+ Class representing the direction of a function application.
152
+ Also contains maintains information as to which combinators
153
+ may be used with the category.
154
+ """
155
+
156
+ def __init__(self, dir, restrictions):
157
+ self._dir = dir
158
+ self._restrs = restrictions
159
+ self._comparison_key = (dir, tuple(restrictions))
160
+
161
+ # Testing the application direction
162
+ def is_forward(self):
163
+ return self._dir == "/"
164
+
165
+ def is_backward(self):
166
+ return self._dir == "\\"
167
+
168
+ def dir(self):
169
+ return self._dir
170
+
171
+ def restrs(self):
172
+ """A list of restrictions on the combinators.
173
+ '.' denotes that permuting operations are disallowed
174
+ ',' denotes that function composition is disallowed
175
+ '_' denotes that the direction has variable restrictions.
176
+ (This is redundant in the current implementation of type-raising)
177
+ """
178
+ return self._restrs
179
+
180
+ def is_variable(self):
181
+ return self._restrs == "_"
182
+
183
+ # Unification and substitution of variable directions.
184
+ # Used only if type-raising is implemented as a unary rule, as it
185
+ # must inherit restrictions from the argument category.
186
+ def can_unify(self, other):
187
+ if other.is_variable():
188
+ return [("_", self.restrs())]
189
+ elif self.is_variable():
190
+ return [("_", other.restrs())]
191
+ else:
192
+ if self.restrs() == other.restrs():
193
+ return []
194
+ return None
195
+
196
+ def substitute(self, subs):
197
+ if not self.is_variable():
198
+ return self
199
+
200
+ for (var, restrs) in subs:
201
+ if var == "_":
202
+ return Direction(self._dir, restrs)
203
+ return self
204
+
205
+ # Testing permitted combinators
206
+ def can_compose(self):
207
+ return "," not in self._restrs
208
+
209
+ def can_cross(self):
210
+ return "." not in self._restrs
211
+
212
+ def __eq__(self, other):
213
+ return (
214
+ self.__class__ is other.__class__
215
+ and self._comparison_key == other._comparison_key
216
+ )
217
+
218
+ def __ne__(self, other):
219
+ return not self == other
220
+
221
+ def __lt__(self, other):
222
+ if not isinstance(other, Direction):
223
+ raise_unorderable_types("<", self, other)
224
+ if self.__class__ is other.__class__:
225
+ return self._comparison_key < other._comparison_key
226
+ else:
227
+ return self.__class__.__name__ < other.__class__.__name__
228
+
229
+ def __hash__(self):
230
+ try:
231
+ return self._hash
232
+ except AttributeError:
233
+ self._hash = hash(self._comparison_key)
234
+ return self._hash
235
+
236
+ def __str__(self):
237
+ r_str = ""
238
+ for r in self._restrs:
239
+ r_str = r_str + "%s" % r
240
+ return f"{self._dir}{r_str}"
241
+
242
+ # The negation operator reverses the direction of the application
243
+ def __neg__(self):
244
+ if self._dir == "/":
245
+ return Direction("\\", self._restrs)
246
+ else:
247
+ return Direction("/", self._restrs)
248
+
249
+
250
+ class PrimitiveCategory(AbstractCCGCategory):
251
+ """
252
+ Class representing primitive categories.
253
+ Takes a string representation of the category, and a
254
+ list of strings specifying the morphological subcategories.
255
+ """
256
+
257
+ def __init__(self, categ, restrictions=[]):
258
+ self._categ = categ
259
+ self._restrs = restrictions
260
+ self._comparison_key = (categ, tuple(restrictions))
261
+
262
+ def is_primitive(self):
263
+ return True
264
+
265
+ def is_function(self):
266
+ return False
267
+
268
+ def is_var(self):
269
+ return False
270
+
271
+ def restrs(self):
272
+ return self._restrs
273
+
274
+ def categ(self):
275
+ return self._categ
276
+
277
+ # Substitution does nothing to a primitive category
278
+ def substitute(self, subs):
279
+ return self
280
+
281
+ # A primitive can be unified with a class of the same
282
+ # base category, given that the other category shares all
283
+ # of its subclasses, or with a variable.
284
+ def can_unify(self, other):
285
+ if not other.is_primitive():
286
+ return None
287
+ if other.is_var():
288
+ return [(other, self)]
289
+ if other.categ() == self.categ():
290
+ for restr in self._restrs:
291
+ if restr not in other.restrs():
292
+ return None
293
+ return []
294
+ return None
295
+
296
+ def __str__(self):
297
+ if self._restrs == []:
298
+ return "%s" % self._categ
299
+ restrictions = "[%s]" % ",".join(repr(r) for r in self._restrs)
300
+ return f"{self._categ}{restrictions}"
301
+
302
+
303
+ class FunctionalCategory(AbstractCCGCategory):
304
+ """
305
+ Class that represents a function application category.
306
+ Consists of argument and result categories, together with
307
+ an application direction.
308
+ """
309
+
310
+ def __init__(self, res, arg, dir):
311
+ self._res = res
312
+ self._arg = arg
313
+ self._dir = dir
314
+ self._comparison_key = (arg, dir, res)
315
+
316
+ def is_primitive(self):
317
+ return False
318
+
319
+ def is_function(self):
320
+ return True
321
+
322
+ def is_var(self):
323
+ return False
324
+
325
+ # Substitution returns the category consisting of the
326
+ # substitution applied to each of its constituents.
327
+ def substitute(self, subs):
328
+ sub_res = self._res.substitute(subs)
329
+ sub_dir = self._dir.substitute(subs)
330
+ sub_arg = self._arg.substitute(subs)
331
+ return FunctionalCategory(sub_res, sub_arg, self._dir)
332
+
333
+ # A function can unify with another function, so long as its
334
+ # constituents can unify, or with an unrestricted variable.
335
+ def can_unify(self, other):
336
+ if other.is_var():
337
+ return [(other, self)]
338
+ if other.is_function():
339
+ sa = self._res.can_unify(other.res())
340
+ sd = self._dir.can_unify(other.dir())
341
+ if sa is not None and sd is not None:
342
+ sb = self._arg.substitute(sa).can_unify(other.arg().substitute(sa))
343
+ if sb is not None:
344
+ return sa + sb
345
+ return None
346
+
347
+ # Constituent accessors
348
+ def arg(self):
349
+ return self._arg
350
+
351
+ def res(self):
352
+ return self._res
353
+
354
+ def dir(self):
355
+ return self._dir
356
+
357
+ def __str__(self):
358
+ return f"({self._res}{self._dir}{self._arg})"
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/chart.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Combinatory Categorial Grammar
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Graeme Gange <ggange@csse.unimelb.edu.au>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+
8
+ """
9
+ The lexicon is constructed by calling
10
+ ``lexicon.fromstring(<lexicon string>)``.
11
+
12
+ In order to construct a parser, you also need a rule set.
13
+ The standard English rules are provided in chart as
14
+ ``chart.DefaultRuleSet``.
15
+
16
+ The parser can then be constructed by calling, for example:
17
+ ``parser = chart.CCGChartParser(<lexicon>, <ruleset>)``
18
+
19
+ Parsing is then performed by running
20
+ ``parser.parse(<sentence>.split())``.
21
+
22
+ While this returns a list of trees, the default representation
23
+ of the produced trees is not very enlightening, particularly
24
+ given that it uses the same tree class as the CFG parsers.
25
+ It is probably better to call:
26
+ ``chart.printCCGDerivation(<parse tree extracted from list>)``
27
+ which should print a nice representation of the derivation.
28
+
29
+ This entire process is shown far more clearly in the demonstration:
30
+ python chart.py
31
+ """
32
+
33
+ import itertools
34
+
35
+ from nltk.ccg.combinator import *
36
+ from nltk.ccg.combinator import (
37
+ BackwardApplication,
38
+ BackwardBx,
39
+ BackwardComposition,
40
+ BackwardSx,
41
+ BackwardT,
42
+ ForwardApplication,
43
+ ForwardComposition,
44
+ ForwardSubstitution,
45
+ ForwardT,
46
+ )
47
+ from nltk.ccg.lexicon import Token, fromstring
48
+ from nltk.ccg.logic import *
49
+ from nltk.parse import ParserI
50
+ from nltk.parse.chart import AbstractChartRule, Chart, EdgeI
51
+ from nltk.sem.logic import *
52
+ from nltk.tree import Tree
53
+
54
+
55
+ # Based on the EdgeI class from NLTK.
56
+ # A number of the properties of the EdgeI interface don't
57
+ # transfer well to CCGs, however.
58
+ class CCGEdge(EdgeI):
59
+ def __init__(self, span, categ, rule):
60
+ self._span = span
61
+ self._categ = categ
62
+ self._rule = rule
63
+ self._comparison_key = (span, categ, rule)
64
+
65
+ # Accessors
66
+ def lhs(self):
67
+ return self._categ
68
+
69
+ def span(self):
70
+ return self._span
71
+
72
+ def start(self):
73
+ return self._span[0]
74
+
75
+ def end(self):
76
+ return self._span[1]
77
+
78
+ def length(self):
79
+ return self._span[1] - self.span[0]
80
+
81
+ def rhs(self):
82
+ return ()
83
+
84
+ def dot(self):
85
+ return 0
86
+
87
+ def is_complete(self):
88
+ return True
89
+
90
+ def is_incomplete(self):
91
+ return False
92
+
93
+ def nextsym(self):
94
+ return None
95
+
96
+ def categ(self):
97
+ return self._categ
98
+
99
+ def rule(self):
100
+ return self._rule
101
+
102
+
103
+ class CCGLeafEdge(EdgeI):
104
+ """
105
+ Class representing leaf edges in a CCG derivation.
106
+ """
107
+
108
+ def __init__(self, pos, token, leaf):
109
+ self._pos = pos
110
+ self._token = token
111
+ self._leaf = leaf
112
+ self._comparison_key = (pos, token.categ(), leaf)
113
+
114
+ # Accessors
115
+ def lhs(self):
116
+ return self._token.categ()
117
+
118
+ def span(self):
119
+ return (self._pos, self._pos + 1)
120
+
121
+ def start(self):
122
+ return self._pos
123
+
124
+ def end(self):
125
+ return self._pos + 1
126
+
127
+ def length(self):
128
+ return 1
129
+
130
+ def rhs(self):
131
+ return self._leaf
132
+
133
+ def dot(self):
134
+ return 0
135
+
136
+ def is_complete(self):
137
+ return True
138
+
139
+ def is_incomplete(self):
140
+ return False
141
+
142
+ def nextsym(self):
143
+ return None
144
+
145
+ def token(self):
146
+ return self._token
147
+
148
+ def categ(self):
149
+ return self._token.categ()
150
+
151
+ def leaf(self):
152
+ return self._leaf
153
+
154
+
155
+ class BinaryCombinatorRule(AbstractChartRule):
156
+ """
157
+ Class implementing application of a binary combinator to a chart.
158
+ Takes the directed combinator to apply.
159
+ """
160
+
161
+ NUMEDGES = 2
162
+
163
+ def __init__(self, combinator):
164
+ self._combinator = combinator
165
+
166
+ # Apply a combinator
167
+ def apply(self, chart, grammar, left_edge, right_edge):
168
+ # The left & right edges must be touching.
169
+ if not (left_edge.end() == right_edge.start()):
170
+ return
171
+
172
+ # Check if the two edges are permitted to combine.
173
+ # If so, generate the corresponding edge.
174
+ if self._combinator.can_combine(left_edge.categ(), right_edge.categ()):
175
+ for res in self._combinator.combine(left_edge.categ(), right_edge.categ()):
176
+ new_edge = CCGEdge(
177
+ span=(left_edge.start(), right_edge.end()),
178
+ categ=res,
179
+ rule=self._combinator,
180
+ )
181
+ if chart.insert(new_edge, (left_edge, right_edge)):
182
+ yield new_edge
183
+
184
+ # The representation of the combinator (for printing derivations)
185
+ def __str__(self):
186
+ return "%s" % self._combinator
187
+
188
+
189
+ # Type-raising must be handled slightly differently to the other rules, as the
190
+ # resulting rules only span a single edge, rather than both edges.
191
+
192
+
193
+ class ForwardTypeRaiseRule(AbstractChartRule):
194
+ """
195
+ Class for applying forward type raising
196
+ """
197
+
198
+ NUMEDGES = 2
199
+
200
+ def __init__(self):
201
+ self._combinator = ForwardT
202
+
203
+ def apply(self, chart, grammar, left_edge, right_edge):
204
+ if not (left_edge.end() == right_edge.start()):
205
+ return
206
+
207
+ for res in self._combinator.combine(left_edge.categ(), right_edge.categ()):
208
+ new_edge = CCGEdge(span=left_edge.span(), categ=res, rule=self._combinator)
209
+ if chart.insert(new_edge, (left_edge,)):
210
+ yield new_edge
211
+
212
+ def __str__(self):
213
+ return "%s" % self._combinator
214
+
215
+
216
+ class BackwardTypeRaiseRule(AbstractChartRule):
217
+ """
218
+ Class for applying backward type raising.
219
+ """
220
+
221
+ NUMEDGES = 2
222
+
223
+ def __init__(self):
224
+ self._combinator = BackwardT
225
+
226
+ def apply(self, chart, grammar, left_edge, right_edge):
227
+ if not (left_edge.end() == right_edge.start()):
228
+ return
229
+
230
+ for res in self._combinator.combine(left_edge.categ(), right_edge.categ()):
231
+ new_edge = CCGEdge(span=right_edge.span(), categ=res, rule=self._combinator)
232
+ if chart.insert(new_edge, (right_edge,)):
233
+ yield new_edge
234
+
235
+ def __str__(self):
236
+ return "%s" % self._combinator
237
+
238
+
239
+ # Common sets of combinators used for English derivations.
240
+ ApplicationRuleSet = [
241
+ BinaryCombinatorRule(ForwardApplication),
242
+ BinaryCombinatorRule(BackwardApplication),
243
+ ]
244
+ CompositionRuleSet = [
245
+ BinaryCombinatorRule(ForwardComposition),
246
+ BinaryCombinatorRule(BackwardComposition),
247
+ BinaryCombinatorRule(BackwardBx),
248
+ ]
249
+ SubstitutionRuleSet = [
250
+ BinaryCombinatorRule(ForwardSubstitution),
251
+ BinaryCombinatorRule(BackwardSx),
252
+ ]
253
+ TypeRaiseRuleSet = [ForwardTypeRaiseRule(), BackwardTypeRaiseRule()]
254
+
255
+ # The standard English rule set.
256
+ DefaultRuleSet = (
257
+ ApplicationRuleSet + CompositionRuleSet + SubstitutionRuleSet + TypeRaiseRuleSet
258
+ )
259
+
260
+
261
+ class CCGChartParser(ParserI):
262
+ """
263
+ Chart parser for CCGs.
264
+ Based largely on the ChartParser class from NLTK.
265
+ """
266
+
267
+ def __init__(self, lexicon, rules, trace=0):
268
+ self._lexicon = lexicon
269
+ self._rules = rules
270
+ self._trace = trace
271
+
272
+ def lexicon(self):
273
+ return self._lexicon
274
+
275
+ # Implements the CYK algorithm
276
+ def parse(self, tokens):
277
+ tokens = list(tokens)
278
+ chart = CCGChart(list(tokens))
279
+ lex = self._lexicon
280
+
281
+ # Initialize leaf edges.
282
+ for index in range(chart.num_leaves()):
283
+ for token in lex.categories(chart.leaf(index)):
284
+ new_edge = CCGLeafEdge(index, token, chart.leaf(index))
285
+ chart.insert(new_edge, ())
286
+
287
+ # Select a span for the new edges
288
+ for span in range(2, chart.num_leaves() + 1):
289
+ for start in range(0, chart.num_leaves() - span + 1):
290
+ # Try all possible pairs of edges that could generate
291
+ # an edge for that span
292
+ for part in range(1, span):
293
+ lstart = start
294
+ mid = start + part
295
+ rend = start + span
296
+
297
+ for left in chart.select(span=(lstart, mid)):
298
+ for right in chart.select(span=(mid, rend)):
299
+ # Generate all possible combinations of the two edges
300
+ for rule in self._rules:
301
+ edges_added_by_rule = 0
302
+ for newedge in rule.apply(chart, lex, left, right):
303
+ edges_added_by_rule += 1
304
+
305
+ # Output the resulting parses
306
+ return chart.parses(lex.start())
307
+
308
+
309
+ class CCGChart(Chart):
310
+ def __init__(self, tokens):
311
+ Chart.__init__(self, tokens)
312
+
313
+ # Constructs the trees for a given parse. Unfortnunately, the parse trees need to be
314
+ # constructed slightly differently to those in the default Chart class, so it has to
315
+ # be reimplemented
316
+ def _trees(self, edge, complete, memo, tree_class):
317
+ assert complete, "CCGChart cannot build incomplete trees"
318
+
319
+ if edge in memo:
320
+ return memo[edge]
321
+
322
+ if isinstance(edge, CCGLeafEdge):
323
+ word = tree_class(edge.token(), [self._tokens[edge.start()]])
324
+ leaf = tree_class((edge.token(), "Leaf"), [word])
325
+ memo[edge] = [leaf]
326
+ return [leaf]
327
+
328
+ memo[edge] = []
329
+ trees = []
330
+
331
+ for cpl in self.child_pointer_lists(edge):
332
+ child_choices = [self._trees(cp, complete, memo, tree_class) for cp in cpl]
333
+ for children in itertools.product(*child_choices):
334
+ lhs = (
335
+ Token(
336
+ self._tokens[edge.start() : edge.end()],
337
+ edge.lhs(),
338
+ compute_semantics(children, edge),
339
+ ),
340
+ str(edge.rule()),
341
+ )
342
+ trees.append(tree_class(lhs, children))
343
+
344
+ memo[edge] = trees
345
+ return trees
346
+
347
+
348
+ def compute_semantics(children, edge):
349
+ if children[0].label()[0].semantics() is None:
350
+ return None
351
+
352
+ if len(children) == 2:
353
+ if isinstance(edge.rule(), BackwardCombinator):
354
+ children = [children[1], children[0]]
355
+
356
+ combinator = edge.rule()._combinator
357
+ function = children[0].label()[0].semantics()
358
+ argument = children[1].label()[0].semantics()
359
+
360
+ if isinstance(combinator, UndirectedFunctionApplication):
361
+ return compute_function_semantics(function, argument)
362
+ elif isinstance(combinator, UndirectedComposition):
363
+ return compute_composition_semantics(function, argument)
364
+ elif isinstance(combinator, UndirectedSubstitution):
365
+ return compute_substitution_semantics(function, argument)
366
+ else:
367
+ raise AssertionError("Unsupported combinator '" + combinator + "'")
368
+ else:
369
+ return compute_type_raised_semantics(children[0].label()[0].semantics())
370
+
371
+
372
+ # --------
373
+ # Displaying derivations
374
+ # --------
375
+ def printCCGDerivation(tree):
376
+ # Get the leaves and initial categories
377
+ leafcats = tree.pos()
378
+ leafstr = ""
379
+ catstr = ""
380
+
381
+ # Construct a string with both the leaf word and corresponding
382
+ # category aligned.
383
+ for (leaf, cat) in leafcats:
384
+ str_cat = "%s" % cat
385
+ nextlen = 2 + max(len(leaf), len(str_cat))
386
+ lcatlen = (nextlen - len(str_cat)) // 2
387
+ rcatlen = lcatlen + (nextlen - len(str_cat)) % 2
388
+ catstr += " " * lcatlen + str_cat + " " * rcatlen
389
+ lleaflen = (nextlen - len(leaf)) // 2
390
+ rleaflen = lleaflen + (nextlen - len(leaf)) % 2
391
+ leafstr += " " * lleaflen + leaf + " " * rleaflen
392
+ print(leafstr.rstrip())
393
+ print(catstr.rstrip())
394
+
395
+ # Display the derivation steps
396
+ printCCGTree(0, tree)
397
+
398
+
399
+ # Prints the sequence of derivation steps.
400
+ def printCCGTree(lwidth, tree):
401
+ rwidth = lwidth
402
+
403
+ # Is a leaf (word).
404
+ # Increment the span by the space occupied by the leaf.
405
+ if not isinstance(tree, Tree):
406
+ return 2 + lwidth + len(tree)
407
+
408
+ # Find the width of the current derivation step
409
+ for child in tree:
410
+ rwidth = max(rwidth, printCCGTree(rwidth, child))
411
+
412
+ # Is a leaf node.
413
+ # Don't print anything, but account for the space occupied.
414
+ if not isinstance(tree.label(), tuple):
415
+ return max(
416
+ rwidth, 2 + lwidth + len("%s" % tree.label()), 2 + lwidth + len(tree[0])
417
+ )
418
+
419
+ (token, op) = tree.label()
420
+
421
+ if op == "Leaf":
422
+ return rwidth
423
+
424
+ # Pad to the left with spaces, followed by a sequence of '-'
425
+ # and the derivation rule.
426
+ print(lwidth * " " + (rwidth - lwidth) * "-" + "%s" % op)
427
+ # Print the resulting category on a new line.
428
+ str_res = "%s" % (token.categ())
429
+ if token.semantics() is not None:
430
+ str_res += " {" + str(token.semantics()) + "}"
431
+ respadlen = (rwidth - lwidth - len(str_res)) // 2 + lwidth
432
+ print(respadlen * " " + str_res)
433
+ return rwidth
434
+
435
+
436
+ ### Demonstration code
437
+
438
+ # Construct the lexicon
439
+ lex = fromstring(
440
+ """
441
+ :- S, NP, N, VP # Primitive categories, S is the target primitive
442
+
443
+ Det :: NP/N # Family of words
444
+ Pro :: NP
445
+ TV :: VP/NP
446
+ Modal :: (S\\NP)/VP # Backslashes need to be escaped
447
+
448
+ I => Pro # Word -> Category mapping
449
+ you => Pro
450
+
451
+ the => Det
452
+
453
+ # Variables have the special keyword 'var'
454
+ # '.' prevents permutation
455
+ # ',' prevents composition
456
+ and => var\\.,var/.,var
457
+
458
+ which => (N\\N)/(S/NP)
459
+
460
+ will => Modal # Categories can be either explicit, or families.
461
+ might => Modal
462
+
463
+ cook => TV
464
+ eat => TV
465
+
466
+ mushrooms => N
467
+ parsnips => N
468
+ bacon => N
469
+ """
470
+ )
471
+
472
+
473
+ def demo():
474
+ parser = CCGChartParser(lex, DefaultRuleSet)
475
+ for parse in parser.parse("I might cook and eat the bacon".split()):
476
+ printCCGDerivation(parse)
477
+
478
+
479
+ if __name__ == "__main__":
480
+ demo()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/combinator.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Combinatory Categorial Grammar
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Graeme Gange <ggange@csse.unimelb.edu.au>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+ """
8
+ CCG Combinators
9
+ """
10
+
11
+ from abc import ABCMeta, abstractmethod
12
+
13
+ from nltk.ccg.api import FunctionalCategory
14
+
15
+
16
+ class UndirectedBinaryCombinator(metaclass=ABCMeta):
17
+ """
18
+ Abstract class for representing a binary combinator.
19
+ Merely defines functions for checking if the function and argument
20
+ are able to be combined, and what the resulting category is.
21
+
22
+ Note that as no assumptions are made as to direction, the unrestricted
23
+ combinators can perform all backward, forward and crossed variations
24
+ of the combinators; these restrictions must be added in the rule
25
+ class.
26
+ """
27
+
28
+ @abstractmethod
29
+ def can_combine(self, function, argument):
30
+ pass
31
+
32
+ @abstractmethod
33
+ def combine(self, function, argument):
34
+ pass
35
+
36
+
37
+ class DirectedBinaryCombinator(metaclass=ABCMeta):
38
+ """
39
+ Wrapper for the undirected binary combinator.
40
+ It takes left and right categories, and decides which is to be
41
+ the function, and which the argument.
42
+ It then decides whether or not they can be combined.
43
+ """
44
+
45
+ @abstractmethod
46
+ def can_combine(self, left, right):
47
+ pass
48
+
49
+ @abstractmethod
50
+ def combine(self, left, right):
51
+ pass
52
+
53
+
54
+ class ForwardCombinator(DirectedBinaryCombinator):
55
+ """
56
+ Class representing combinators where the primary functor is on the left.
57
+
58
+ Takes an undirected combinator, and a predicate which adds constraints
59
+ restricting the cases in which it may apply.
60
+ """
61
+
62
+ def __init__(self, combinator, predicate, suffix=""):
63
+ self._combinator = combinator
64
+ self._predicate = predicate
65
+ self._suffix = suffix
66
+
67
+ def can_combine(self, left, right):
68
+ return self._combinator.can_combine(left, right) and self._predicate(
69
+ left, right
70
+ )
71
+
72
+ def combine(self, left, right):
73
+ yield from self._combinator.combine(left, right)
74
+
75
+ def __str__(self):
76
+ return f">{self._combinator}{self._suffix}"
77
+
78
+
79
+ class BackwardCombinator(DirectedBinaryCombinator):
80
+ """
81
+ The backward equivalent of the ForwardCombinator class.
82
+ """
83
+
84
+ def __init__(self, combinator, predicate, suffix=""):
85
+ self._combinator = combinator
86
+ self._predicate = predicate
87
+ self._suffix = suffix
88
+
89
+ def can_combine(self, left, right):
90
+ return self._combinator.can_combine(right, left) and self._predicate(
91
+ left, right
92
+ )
93
+
94
+ def combine(self, left, right):
95
+ yield from self._combinator.combine(right, left)
96
+
97
+ def __str__(self):
98
+ return f"<{self._combinator}{self._suffix}"
99
+
100
+
101
+ class UndirectedFunctionApplication(UndirectedBinaryCombinator):
102
+ """
103
+ Class representing function application.
104
+ Implements rules of the form:
105
+ X/Y Y -> X (>)
106
+ And the corresponding backwards application rule
107
+ """
108
+
109
+ def can_combine(self, function, argument):
110
+ if not function.is_function():
111
+ return False
112
+
113
+ return not function.arg().can_unify(argument) is None
114
+
115
+ def combine(self, function, argument):
116
+ if not function.is_function():
117
+ return
118
+
119
+ subs = function.arg().can_unify(argument)
120
+ if subs is None:
121
+ return
122
+
123
+ yield function.res().substitute(subs)
124
+
125
+ def __str__(self):
126
+ return ""
127
+
128
+
129
+ # Predicates for function application.
130
+
131
+ # Ensures the left functor takes an argument on the right
132
+ def forwardOnly(left, right):
133
+ return left.dir().is_forward()
134
+
135
+
136
+ # Ensures the right functor takes an argument on the left
137
+ def backwardOnly(left, right):
138
+ return right.dir().is_backward()
139
+
140
+
141
+ # Application combinator instances
142
+ ForwardApplication = ForwardCombinator(UndirectedFunctionApplication(), forwardOnly)
143
+ BackwardApplication = BackwardCombinator(UndirectedFunctionApplication(), backwardOnly)
144
+
145
+
146
+ class UndirectedComposition(UndirectedBinaryCombinator):
147
+ """
148
+ Functional composition (harmonic) combinator.
149
+ Implements rules of the form
150
+ X/Y Y/Z -> X/Z (B>)
151
+ And the corresponding backwards and crossed variations.
152
+ """
153
+
154
+ def can_combine(self, function, argument):
155
+ # Can only combine two functions, and both functions must
156
+ # allow composition.
157
+ if not (function.is_function() and argument.is_function()):
158
+ return False
159
+ if function.dir().can_compose() and argument.dir().can_compose():
160
+ return not function.arg().can_unify(argument.res()) is None
161
+ return False
162
+
163
+ def combine(self, function, argument):
164
+ if not (function.is_function() and argument.is_function()):
165
+ return
166
+ if function.dir().can_compose() and argument.dir().can_compose():
167
+ subs = function.arg().can_unify(argument.res())
168
+ if subs is not None:
169
+ yield FunctionalCategory(
170
+ function.res().substitute(subs),
171
+ argument.arg().substitute(subs),
172
+ argument.dir(),
173
+ )
174
+
175
+ def __str__(self):
176
+ return "B"
177
+
178
+
179
+ # Predicates for restricting application of straight composition.
180
+ def bothForward(left, right):
181
+ return left.dir().is_forward() and right.dir().is_forward()
182
+
183
+
184
+ def bothBackward(left, right):
185
+ return left.dir().is_backward() and right.dir().is_backward()
186
+
187
+
188
+ # Predicates for crossed composition
189
+ def crossedDirs(left, right):
190
+ return left.dir().is_forward() and right.dir().is_backward()
191
+
192
+
193
+ def backwardBxConstraint(left, right):
194
+ # The functors must be crossed inwards
195
+ if not crossedDirs(left, right):
196
+ return False
197
+ # Permuting combinators must be allowed
198
+ if not left.dir().can_cross() and right.dir().can_cross():
199
+ return False
200
+ # The resulting argument category is restricted to be primitive
201
+ return left.arg().is_primitive()
202
+
203
+
204
+ # Straight composition combinators
205
+ ForwardComposition = ForwardCombinator(UndirectedComposition(), forwardOnly)
206
+ BackwardComposition = BackwardCombinator(UndirectedComposition(), backwardOnly)
207
+
208
+ # Backward crossed composition
209
+ BackwardBx = BackwardCombinator(
210
+ UndirectedComposition(), backwardBxConstraint, suffix="x"
211
+ )
212
+
213
+
214
+ class UndirectedSubstitution(UndirectedBinaryCombinator):
215
+ r"""
216
+ Substitution (permutation) combinator.
217
+ Implements rules of the form
218
+ Y/Z (X\Y)/Z -> X/Z (<Sx)
219
+ And other variations.
220
+ """
221
+
222
+ def can_combine(self, function, argument):
223
+ if function.is_primitive() or argument.is_primitive():
224
+ return False
225
+
226
+ # These could potentially be moved to the predicates, as the
227
+ # constraints may not be general to all languages.
228
+ if function.res().is_primitive():
229
+ return False
230
+ if not function.arg().is_primitive():
231
+ return False
232
+
233
+ if not (function.dir().can_compose() and argument.dir().can_compose()):
234
+ return False
235
+ return (function.res().arg() == argument.res()) and (
236
+ function.arg() == argument.arg()
237
+ )
238
+
239
+ def combine(self, function, argument):
240
+ if self.can_combine(function, argument):
241
+ yield FunctionalCategory(
242
+ function.res().res(), argument.arg(), argument.dir()
243
+ )
244
+
245
+ def __str__(self):
246
+ return "S"
247
+
248
+
249
+ # Predicate for forward substitution
250
+ def forwardSConstraint(left, right):
251
+ if not bothForward(left, right):
252
+ return False
253
+ return left.res().dir().is_forward() and left.arg().is_primitive()
254
+
255
+
256
+ # Predicate for backward crossed substitution
257
+ def backwardSxConstraint(left, right):
258
+ if not left.dir().can_cross() and right.dir().can_cross():
259
+ return False
260
+ if not bothForward(left, right):
261
+ return False
262
+ return right.res().dir().is_backward() and right.arg().is_primitive()
263
+
264
+
265
+ # Instances of substitution combinators
266
+ ForwardSubstitution = ForwardCombinator(UndirectedSubstitution(), forwardSConstraint)
267
+ BackwardSx = BackwardCombinator(UndirectedSubstitution(), backwardSxConstraint, "x")
268
+
269
+
270
+ # Retrieves the left-most functional category.
271
+ # ie, (N\N)/(S/NP) => N\N
272
+ def innermostFunction(categ):
273
+ while categ.res().is_function():
274
+ categ = categ.res()
275
+ return categ
276
+
277
+
278
+ class UndirectedTypeRaise(UndirectedBinaryCombinator):
279
+ """
280
+ Undirected combinator for type raising.
281
+ """
282
+
283
+ def can_combine(self, function, arg):
284
+ # The argument must be a function.
285
+ # The restriction that arg.res() must be a function
286
+ # merely reduces redundant type-raising; if arg.res() is
287
+ # primitive, we have:
288
+ # X Y\X =>(<T) Y/(Y\X) Y\X =>(>) Y
289
+ # which is equivalent to
290
+ # X Y\X =>(<) Y
291
+ if not (arg.is_function() and arg.res().is_function()):
292
+ return False
293
+
294
+ arg = innermostFunction(arg)
295
+
296
+ # left, arg_categ are undefined!
297
+ subs = left.can_unify(arg_categ.arg())
298
+ if subs is not None:
299
+ return True
300
+ return False
301
+
302
+ def combine(self, function, arg):
303
+ if not (
304
+ function.is_primitive() and arg.is_function() and arg.res().is_function()
305
+ ):
306
+ return
307
+
308
+ # Type-raising matches only the innermost application.
309
+ arg = innermostFunction(arg)
310
+
311
+ subs = function.can_unify(arg.arg())
312
+ if subs is not None:
313
+ xcat = arg.res().substitute(subs)
314
+ yield FunctionalCategory(
315
+ xcat, FunctionalCategory(xcat, function, arg.dir()), -(arg.dir())
316
+ )
317
+
318
+ def __str__(self):
319
+ return "T"
320
+
321
+
322
+ # Predicates for type-raising
323
+ # The direction of the innermost category must be towards
324
+ # the primary functor.
325
+ # The restriction that the variable must be primitive is not
326
+ # common to all versions of CCGs; some authors have other restrictions.
327
+ def forwardTConstraint(left, right):
328
+ arg = innermostFunction(right)
329
+ return arg.dir().is_backward() and arg.res().is_primitive()
330
+
331
+
332
+ def backwardTConstraint(left, right):
333
+ arg = innermostFunction(left)
334
+ return arg.dir().is_forward() and arg.res().is_primitive()
335
+
336
+
337
+ # Instances of type-raising combinators
338
+ ForwardT = ForwardCombinator(UndirectedTypeRaise(), forwardTConstraint)
339
+ BackwardT = BackwardCombinator(UndirectedTypeRaise(), backwardTConstraint)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/lexicon.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Combinatory Categorial Grammar
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Graeme Gange <ggange@csse.unimelb.edu.au>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+ """
8
+ CCG Lexicons
9
+ """
10
+
11
+ import re
12
+ from collections import defaultdict
13
+
14
+ from nltk.ccg.api import CCGVar, Direction, FunctionalCategory, PrimitiveCategory
15
+ from nltk.internals import deprecated
16
+ from nltk.sem.logic import Expression
17
+
18
+ # ------------
19
+ # Regular expressions used for parsing components of the lexicon
20
+ # ------------
21
+
22
+ # Parses a primitive category and subscripts
23
+ PRIM_RE = re.compile(r"""([A-Za-z]+)(\[[A-Za-z,]+\])?""")
24
+
25
+ # Separates the next primitive category from the remainder of the
26
+ # string
27
+ NEXTPRIM_RE = re.compile(r"""([A-Za-z]+(?:\[[A-Za-z,]+\])?)(.*)""")
28
+
29
+ # Separates the next application operator from the remainder
30
+ APP_RE = re.compile(r"""([\\/])([.,]?)([.,]?)(.*)""")
31
+
32
+ # Parses the definition of the right-hand side (rhs) of either a word or a family
33
+ LEX_RE = re.compile(r"""([\S_]+)\s*(::|[-=]+>)\s*(.+)""", re.UNICODE)
34
+
35
+ # Parses the right hand side that contains category and maybe semantic predicate
36
+ RHS_RE = re.compile(r"""([^{}]*[^ {}])\s*(\{[^}]+\})?""", re.UNICODE)
37
+
38
+ # Parses the semantic predicate
39
+ SEMANTICS_RE = re.compile(r"""\{([^}]+)\}""", re.UNICODE)
40
+
41
+ # Strips comments from a line
42
+ COMMENTS_RE = re.compile("""([^#]*)(?:#.*)?""")
43
+
44
+
45
+ class Token:
46
+ """
47
+ Class representing a token.
48
+
49
+ token => category {semantics}
50
+ e.g. eat => S\\var[pl]/var {\\x y.eat(x,y)}
51
+
52
+ * `token` (string)
53
+ * `categ` (string)
54
+ * `semantics` (Expression)
55
+ """
56
+
57
+ def __init__(self, token, categ, semantics=None):
58
+ self._token = token
59
+ self._categ = categ
60
+ self._semantics = semantics
61
+
62
+ def categ(self):
63
+ return self._categ
64
+
65
+ def semantics(self):
66
+ return self._semantics
67
+
68
+ def __str__(self):
69
+ semantics_str = ""
70
+ if self._semantics is not None:
71
+ semantics_str = " {" + str(self._semantics) + "}"
72
+ return "" + str(self._categ) + semantics_str
73
+
74
+ def __cmp__(self, other):
75
+ if not isinstance(other, Token):
76
+ return -1
77
+ return cmp((self._categ, self._semantics), other.categ(), other.semantics())
78
+
79
+
80
+ class CCGLexicon:
81
+ """
82
+ Class representing a lexicon for CCG grammars.
83
+
84
+ * `primitives`: The list of primitive categories for the lexicon
85
+ * `families`: Families of categories
86
+ * `entries`: A mapping of words to possible categories
87
+ """
88
+
89
+ def __init__(self, start, primitives, families, entries):
90
+ self._start = PrimitiveCategory(start)
91
+ self._primitives = primitives
92
+ self._families = families
93
+ self._entries = entries
94
+
95
+ def categories(self, word):
96
+ """
97
+ Returns all the possible categories for a word
98
+ """
99
+ return self._entries[word]
100
+
101
+ def start(self):
102
+ """
103
+ Return the target category for the parser
104
+ """
105
+ return self._start
106
+
107
+ def __str__(self):
108
+ """
109
+ String representation of the lexicon. Used for debugging.
110
+ """
111
+ string = ""
112
+ first = True
113
+ for ident in sorted(self._entries):
114
+ if not first:
115
+ string = string + "\n"
116
+ string = string + ident + " => "
117
+
118
+ first = True
119
+ for cat in self._entries[ident]:
120
+ if not first:
121
+ string = string + " | "
122
+ else:
123
+ first = False
124
+ string = string + "%s" % cat
125
+ return string
126
+
127
+
128
+ # -----------
129
+ # Parsing lexicons
130
+ # -----------
131
+
132
+
133
+ def matchBrackets(string):
134
+ """
135
+ Separate the contents matching the first set of brackets from the rest of
136
+ the input.
137
+ """
138
+ rest = string[1:]
139
+ inside = "("
140
+
141
+ while rest != "" and not rest.startswith(")"):
142
+ if rest.startswith("("):
143
+ (part, rest) = matchBrackets(rest)
144
+ inside = inside + part
145
+ else:
146
+ inside = inside + rest[0]
147
+ rest = rest[1:]
148
+ if rest.startswith(")"):
149
+ return (inside + ")", rest[1:])
150
+ raise AssertionError("Unmatched bracket in string '" + string + "'")
151
+
152
+
153
+ def nextCategory(string):
154
+ """
155
+ Separate the string for the next portion of the category from the rest
156
+ of the string
157
+ """
158
+ if string.startswith("("):
159
+ return matchBrackets(string)
160
+ return NEXTPRIM_RE.match(string).groups()
161
+
162
+
163
+ def parseApplication(app):
164
+ """
165
+ Parse an application operator
166
+ """
167
+ return Direction(app[0], app[1:])
168
+
169
+
170
+ def parseSubscripts(subscr):
171
+ """
172
+ Parse the subscripts for a primitive category
173
+ """
174
+ if subscr:
175
+ return subscr[1:-1].split(",")
176
+ return []
177
+
178
+
179
+ def parsePrimitiveCategory(chunks, primitives, families, var):
180
+ """
181
+ Parse a primitive category
182
+
183
+ If the primitive is the special category 'var', replace it with the
184
+ correct `CCGVar`.
185
+ """
186
+ if chunks[0] == "var":
187
+ if chunks[1] is None:
188
+ if var is None:
189
+ var = CCGVar()
190
+ return (var, var)
191
+
192
+ catstr = chunks[0]
193
+ if catstr in families:
194
+ (cat, cvar) = families[catstr]
195
+ if var is None:
196
+ var = cvar
197
+ else:
198
+ cat = cat.substitute([(cvar, var)])
199
+ return (cat, var)
200
+
201
+ if catstr in primitives:
202
+ subscrs = parseSubscripts(chunks[1])
203
+ return (PrimitiveCategory(catstr, subscrs), var)
204
+ raise AssertionError(
205
+ "String '" + catstr + "' is neither a family nor primitive category."
206
+ )
207
+
208
+
209
+ def augParseCategory(line, primitives, families, var=None):
210
+ """
211
+ Parse a string representing a category, and returns a tuple with
212
+ (possibly) the CCG variable for the category
213
+ """
214
+ (cat_string, rest) = nextCategory(line)
215
+
216
+ if cat_string.startswith("("):
217
+ (res, var) = augParseCategory(cat_string[1:-1], primitives, families, var)
218
+
219
+ else:
220
+ (res, var) = parsePrimitiveCategory(
221
+ PRIM_RE.match(cat_string).groups(), primitives, families, var
222
+ )
223
+
224
+ while rest != "":
225
+ app = APP_RE.match(rest).groups()
226
+ direction = parseApplication(app[0:3])
227
+ rest = app[3]
228
+
229
+ (cat_string, rest) = nextCategory(rest)
230
+ if cat_string.startswith("("):
231
+ (arg, var) = augParseCategory(cat_string[1:-1], primitives, families, var)
232
+ else:
233
+ (arg, var) = parsePrimitiveCategory(
234
+ PRIM_RE.match(cat_string).groups(), primitives, families, var
235
+ )
236
+ res = FunctionalCategory(res, arg, direction)
237
+
238
+ return (res, var)
239
+
240
+
241
+ def fromstring(lex_str, include_semantics=False):
242
+ """
243
+ Convert string representation into a lexicon for CCGs.
244
+ """
245
+ CCGVar.reset_id()
246
+ primitives = []
247
+ families = {}
248
+ entries = defaultdict(list)
249
+ for line in lex_str.splitlines():
250
+ # Strip comments and leading/trailing whitespace.
251
+ line = COMMENTS_RE.match(line).groups()[0].strip()
252
+ if line == "":
253
+ continue
254
+
255
+ if line.startswith(":-"):
256
+ # A line of primitive categories.
257
+ # The first one is the target category
258
+ # ie, :- S, N, NP, VP
259
+ primitives = primitives + [
260
+ prim.strip() for prim in line[2:].strip().split(",")
261
+ ]
262
+ else:
263
+ # Either a family definition, or a word definition
264
+ (ident, sep, rhs) = LEX_RE.match(line).groups()
265
+ (catstr, semantics_str) = RHS_RE.match(rhs).groups()
266
+ (cat, var) = augParseCategory(catstr, primitives, families)
267
+
268
+ if sep == "::":
269
+ # Family definition
270
+ # ie, Det :: NP/N
271
+ families[ident] = (cat, var)
272
+ else:
273
+ semantics = None
274
+ if include_semantics is True:
275
+ if semantics_str is None:
276
+ raise AssertionError(
277
+ line
278
+ + " must contain semantics because include_semantics is set to True"
279
+ )
280
+ else:
281
+ semantics = Expression.fromstring(
282
+ SEMANTICS_RE.match(semantics_str).groups()[0]
283
+ )
284
+ # Word definition
285
+ # ie, which => (N\N)/(S/NP)
286
+ entries[ident].append(Token(ident, cat, semantics))
287
+ return CCGLexicon(primitives[0], primitives, families, entries)
288
+
289
+
290
+ @deprecated("Use fromstring() instead.")
291
+ def parseLexicon(lex_str):
292
+ return fromstring(lex_str)
293
+
294
+
295
+ openccg_tinytiny = fromstring(
296
+ """
297
+ # Rather minimal lexicon based on the openccg `tinytiny' grammar.
298
+ # Only incorporates a subset of the morphological subcategories, however.
299
+ :- S,NP,N # Primitive categories
300
+ Det :: NP/N # Determiners
301
+ Pro :: NP
302
+ IntransVsg :: S\\NP[sg] # Tensed intransitive verbs (singular)
303
+ IntransVpl :: S\\NP[pl] # Plural
304
+ TransVsg :: S\\NP[sg]/NP # Tensed transitive verbs (singular)
305
+ TransVpl :: S\\NP[pl]/NP # Plural
306
+
307
+ the => NP[sg]/N[sg]
308
+ the => NP[pl]/N[pl]
309
+
310
+ I => Pro
311
+ me => Pro
312
+ we => Pro
313
+ us => Pro
314
+
315
+ book => N[sg]
316
+ books => N[pl]
317
+
318
+ peach => N[sg]
319
+ peaches => N[pl]
320
+
321
+ policeman => N[sg]
322
+ policemen => N[pl]
323
+
324
+ boy => N[sg]
325
+ boys => N[pl]
326
+
327
+ sleep => IntransVsg
328
+ sleep => IntransVpl
329
+
330
+ eat => IntransVpl
331
+ eat => TransVpl
332
+ eats => IntransVsg
333
+ eats => TransVsg
334
+
335
+ see => TransVpl
336
+ sees => TransVsg
337
+ """
338
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/ccg/logic.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Combinatory Categorial Grammar
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Tanin Na Nakorn (@tanin)
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+ """
8
+ Helper functions for CCG semantics computation
9
+ """
10
+
11
+ from nltk.sem.logic import *
12
+
13
+
14
+ def compute_type_raised_semantics(semantics):
15
+ core = semantics
16
+ parent = None
17
+ while isinstance(core, LambdaExpression):
18
+ parent = core
19
+ core = core.term
20
+
21
+ var = Variable("F")
22
+ while var in core.free():
23
+ var = unique_variable(pattern=var)
24
+ core = ApplicationExpression(FunctionVariableExpression(var), core)
25
+
26
+ if parent is not None:
27
+ parent.term = core
28
+ else:
29
+ semantics = core
30
+
31
+ return LambdaExpression(var, semantics)
32
+
33
+
34
+ def compute_function_semantics(function, argument):
35
+ return ApplicationExpression(function, argument).simplify()
36
+
37
+
38
+ def compute_composition_semantics(function, argument):
39
+ assert isinstance(argument, LambdaExpression), (
40
+ "`" + str(argument) + "` must be a lambda expression"
41
+ )
42
+ return LambdaExpression(
43
+ argument.variable, ApplicationExpression(function, argument.term).simplify()
44
+ )
45
+
46
+
47
+ def compute_substitution_semantics(function, argument):
48
+ assert isinstance(function, LambdaExpression) and isinstance(
49
+ function.term, LambdaExpression
50
+ ), ("`" + str(function) + "` must be a lambda expression with 2 arguments")
51
+ assert isinstance(argument, LambdaExpression), (
52
+ "`" + str(argument) + "` must be a lambda expression"
53
+ )
54
+
55
+ new_argument = ApplicationExpression(
56
+ argument, VariableExpression(function.variable)
57
+ ).simplify()
58
+ new_term = ApplicationExpression(function.term, new_argument).simplify()
59
+
60
+ return LambdaExpression(function.variable, new_term)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__init__.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Corpus Readers
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Edward Loper <edloper@gmail.com>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+
8
+ # TODO this docstring isn't up-to-date!
9
+ """
10
+ NLTK corpus readers. The modules in this package provide functions
11
+ that can be used to read corpus files in a variety of formats. These
12
+ functions can be used to read both the corpus files that are
13
+ distributed in the NLTK corpus package, and corpus files that are part
14
+ of external corpora.
15
+
16
+ Available Corpora
17
+ =================
18
+
19
+ Please see https://www.nltk.org/nltk_data/ for a complete list.
20
+ Install corpora using nltk.download().
21
+
22
+ Corpus Reader Functions
23
+ =======================
24
+ Each corpus module defines one or more "corpus reader functions",
25
+ which can be used to read documents from that corpus. These functions
26
+ take an argument, ``item``, which is used to indicate which document
27
+ should be read from the corpus:
28
+
29
+ - If ``item`` is one of the unique identifiers listed in the corpus
30
+ module's ``items`` variable, then the corresponding document will
31
+ be loaded from the NLTK corpus package.
32
+ - If ``item`` is a filename, then that file will be read.
33
+
34
+ Additionally, corpus reader functions can be given lists of item
35
+ names; in which case, they will return a concatenation of the
36
+ corresponding documents.
37
+
38
+ Corpus reader functions are named based on the type of information
39
+ they return. Some common examples, and their return types, are:
40
+
41
+ - words(): list of str
42
+ - sents(): list of (list of str)
43
+ - paras(): list of (list of (list of str))
44
+ - tagged_words(): list of (str,str) tuple
45
+ - tagged_sents(): list of (list of (str,str))
46
+ - tagged_paras(): list of (list of (list of (str,str)))
47
+ - chunked_sents(): list of (Tree w/ (str,str) leaves)
48
+ - parsed_sents(): list of (Tree with str leaves)
49
+ - parsed_paras(): list of (list of (Tree with str leaves))
50
+ - xml(): A single xml ElementTree
51
+ - raw(): unprocessed corpus contents
52
+
53
+ For example, to read a list of the words in the Brown Corpus, use
54
+ ``nltk.corpus.brown.words()``:
55
+
56
+ >>> from nltk.corpus import brown
57
+ >>> print(", ".join(brown.words())) # doctest: +ELLIPSIS
58
+ The, Fulton, County, Grand, Jury, said, ...
59
+
60
+ """
61
+
62
+ import re
63
+
64
+ from nltk.corpus.reader import *
65
+ from nltk.corpus.util import LazyCorpusLoader
66
+ from nltk.tokenize import RegexpTokenizer
67
+
68
+ abc: PlaintextCorpusReader = LazyCorpusLoader(
69
+ "abc",
70
+ PlaintextCorpusReader,
71
+ r"(?!\.).*\.txt",
72
+ encoding=[("science", "latin_1"), ("rural", "utf8")],
73
+ )
74
+ alpino: AlpinoCorpusReader = LazyCorpusLoader(
75
+ "alpino", AlpinoCorpusReader, tagset="alpino"
76
+ )
77
+ bcp47: BCP47CorpusReader = LazyCorpusLoader(
78
+ "bcp47", BCP47CorpusReader, r"(cldr|iana)/*"
79
+ )
80
+ brown: CategorizedTaggedCorpusReader = LazyCorpusLoader(
81
+ "brown",
82
+ CategorizedTaggedCorpusReader,
83
+ r"c[a-z]\d\d",
84
+ cat_file="cats.txt",
85
+ tagset="brown",
86
+ encoding="ascii",
87
+ )
88
+ cess_cat: BracketParseCorpusReader = LazyCorpusLoader(
89
+ "cess_cat",
90
+ BracketParseCorpusReader,
91
+ r"(?!\.).*\.tbf",
92
+ tagset="unknown",
93
+ encoding="ISO-8859-15",
94
+ )
95
+ cess_esp: BracketParseCorpusReader = LazyCorpusLoader(
96
+ "cess_esp",
97
+ BracketParseCorpusReader,
98
+ r"(?!\.).*\.tbf",
99
+ tagset="unknown",
100
+ encoding="ISO-8859-15",
101
+ )
102
+ cmudict: CMUDictCorpusReader = LazyCorpusLoader(
103
+ "cmudict", CMUDictCorpusReader, ["cmudict"]
104
+ )
105
+ comtrans: AlignedCorpusReader = LazyCorpusLoader(
106
+ "comtrans", AlignedCorpusReader, r"(?!\.).*\.txt"
107
+ )
108
+ comparative_sentences: ComparativeSentencesCorpusReader = LazyCorpusLoader(
109
+ "comparative_sentences",
110
+ ComparativeSentencesCorpusReader,
111
+ r"labeledSentences\.txt",
112
+ encoding="latin-1",
113
+ )
114
+ conll2000: ConllChunkCorpusReader = LazyCorpusLoader(
115
+ "conll2000",
116
+ ConllChunkCorpusReader,
117
+ ["train.txt", "test.txt"],
118
+ ("NP", "VP", "PP"),
119
+ tagset="wsj",
120
+ encoding="ascii",
121
+ )
122
+ conll2002: ConllChunkCorpusReader = LazyCorpusLoader(
123
+ "conll2002",
124
+ ConllChunkCorpusReader,
125
+ r".*\.(test|train).*",
126
+ ("LOC", "PER", "ORG", "MISC"),
127
+ encoding="utf-8",
128
+ )
129
+ conll2007: DependencyCorpusReader = LazyCorpusLoader(
130
+ "conll2007",
131
+ DependencyCorpusReader,
132
+ r".*\.(test|train).*",
133
+ encoding=[("eus", "ISO-8859-2"), ("esp", "utf8")],
134
+ )
135
+ crubadan: CrubadanCorpusReader = LazyCorpusLoader(
136
+ "crubadan", CrubadanCorpusReader, r".*\.txt"
137
+ )
138
+ dependency_treebank: DependencyCorpusReader = LazyCorpusLoader(
139
+ "dependency_treebank", DependencyCorpusReader, r".*\.dp", encoding="ascii"
140
+ )
141
+ extended_omw: CorpusReader = LazyCorpusLoader(
142
+ "extended_omw", CorpusReader, r".*/wn-[a-z\-]*\.tab", encoding="utf8"
143
+ )
144
+ floresta: BracketParseCorpusReader = LazyCorpusLoader(
145
+ "floresta",
146
+ BracketParseCorpusReader,
147
+ r"(?!\.).*\.ptb",
148
+ "#",
149
+ tagset="unknown",
150
+ encoding="ISO-8859-15",
151
+ )
152
+ framenet15: FramenetCorpusReader = LazyCorpusLoader(
153
+ "framenet_v15",
154
+ FramenetCorpusReader,
155
+ [
156
+ "frRelation.xml",
157
+ "frameIndex.xml",
158
+ "fulltextIndex.xml",
159
+ "luIndex.xml",
160
+ "semTypes.xml",
161
+ ],
162
+ )
163
+ framenet: FramenetCorpusReader = LazyCorpusLoader(
164
+ "framenet_v17",
165
+ FramenetCorpusReader,
166
+ [
167
+ "frRelation.xml",
168
+ "frameIndex.xml",
169
+ "fulltextIndex.xml",
170
+ "luIndex.xml",
171
+ "semTypes.xml",
172
+ ],
173
+ )
174
+ gazetteers: WordListCorpusReader = LazyCorpusLoader(
175
+ "gazetteers", WordListCorpusReader, r"(?!LICENSE|\.).*\.txt", encoding="ISO-8859-2"
176
+ )
177
+ genesis: PlaintextCorpusReader = LazyCorpusLoader(
178
+ "genesis",
179
+ PlaintextCorpusReader,
180
+ r"(?!\.).*\.txt",
181
+ encoding=[
182
+ ("finnish|french|german", "latin_1"),
183
+ ("swedish", "cp865"),
184
+ (".*", "utf_8"),
185
+ ],
186
+ )
187
+ gutenberg: PlaintextCorpusReader = LazyCorpusLoader(
188
+ "gutenberg", PlaintextCorpusReader, r"(?!\.).*\.txt", encoding="latin1"
189
+ )
190
+ ieer: IEERCorpusReader = LazyCorpusLoader("ieer", IEERCorpusReader, r"(?!README|\.).*")
191
+ inaugural: PlaintextCorpusReader = LazyCorpusLoader(
192
+ "inaugural", PlaintextCorpusReader, r"(?!\.).*\.txt", encoding="latin1"
193
+ )
194
+ # [XX] This should probably just use TaggedCorpusReader:
195
+ indian: IndianCorpusReader = LazyCorpusLoader(
196
+ "indian", IndianCorpusReader, r"(?!\.).*\.pos", tagset="unknown", encoding="utf8"
197
+ )
198
+
199
+ jeita: ChasenCorpusReader = LazyCorpusLoader(
200
+ "jeita", ChasenCorpusReader, r".*\.chasen", encoding="utf-8"
201
+ )
202
+ knbc: KNBCorpusReader = LazyCorpusLoader(
203
+ "knbc/corpus1", KNBCorpusReader, r".*/KN.*", encoding="euc-jp"
204
+ )
205
+ lin_thesaurus: LinThesaurusCorpusReader = LazyCorpusLoader(
206
+ "lin_thesaurus", LinThesaurusCorpusReader, r".*\.lsp"
207
+ )
208
+ mac_morpho: MacMorphoCorpusReader = LazyCorpusLoader(
209
+ "mac_morpho",
210
+ MacMorphoCorpusReader,
211
+ r"(?!\.).*\.txt",
212
+ tagset="unknown",
213
+ encoding="latin-1",
214
+ )
215
+ machado: PortugueseCategorizedPlaintextCorpusReader = LazyCorpusLoader(
216
+ "machado",
217
+ PortugueseCategorizedPlaintextCorpusReader,
218
+ r"(?!\.).*\.txt",
219
+ cat_pattern=r"([a-z]*)/.*",
220
+ encoding="latin-1",
221
+ )
222
+ masc_tagged: CategorizedTaggedCorpusReader = LazyCorpusLoader(
223
+ "masc_tagged",
224
+ CategorizedTaggedCorpusReader,
225
+ r"(spoken|written)/.*\.txt",
226
+ cat_file="categories.txt",
227
+ tagset="wsj",
228
+ encoding="utf-8",
229
+ sep="_",
230
+ )
231
+ movie_reviews: CategorizedPlaintextCorpusReader = LazyCorpusLoader(
232
+ "movie_reviews",
233
+ CategorizedPlaintextCorpusReader,
234
+ r"(?!\.).*\.txt",
235
+ cat_pattern=r"(neg|pos)/.*",
236
+ encoding="ascii",
237
+ )
238
+ multext_east: MTECorpusReader = LazyCorpusLoader(
239
+ "mte_teip5", MTECorpusReader, r"(oana).*\.xml", encoding="utf-8"
240
+ )
241
+ names: WordListCorpusReader = LazyCorpusLoader(
242
+ "names", WordListCorpusReader, r"(?!\.).*\.txt", encoding="ascii"
243
+ )
244
+ nps_chat: NPSChatCorpusReader = LazyCorpusLoader(
245
+ "nps_chat", NPSChatCorpusReader, r"(?!README|\.).*\.xml", tagset="wsj"
246
+ )
247
+ opinion_lexicon: OpinionLexiconCorpusReader = LazyCorpusLoader(
248
+ "opinion_lexicon",
249
+ OpinionLexiconCorpusReader,
250
+ r"(\w+)\-words\.txt",
251
+ encoding="ISO-8859-2",
252
+ )
253
+ ppattach: PPAttachmentCorpusReader = LazyCorpusLoader(
254
+ "ppattach", PPAttachmentCorpusReader, ["training", "test", "devset"]
255
+ )
256
+ product_reviews_1: ReviewsCorpusReader = LazyCorpusLoader(
257
+ "product_reviews_1", ReviewsCorpusReader, r"^(?!Readme).*\.txt", encoding="utf8"
258
+ )
259
+ product_reviews_2: ReviewsCorpusReader = LazyCorpusLoader(
260
+ "product_reviews_2", ReviewsCorpusReader, r"^(?!Readme).*\.txt", encoding="utf8"
261
+ )
262
+ pros_cons: ProsConsCorpusReader = LazyCorpusLoader(
263
+ "pros_cons",
264
+ ProsConsCorpusReader,
265
+ r"Integrated(Cons|Pros)\.txt",
266
+ cat_pattern=r"Integrated(Cons|Pros)\.txt",
267
+ encoding="ISO-8859-2",
268
+ )
269
+ ptb: CategorizedBracketParseCorpusReader = (
270
+ LazyCorpusLoader( # Penn Treebank v3: WSJ and Brown portions
271
+ "ptb",
272
+ CategorizedBracketParseCorpusReader,
273
+ r"(WSJ/\d\d/WSJ_\d\d|BROWN/C[A-Z]/C[A-Z])\d\d.MRG",
274
+ cat_file="allcats.txt",
275
+ tagset="wsj",
276
+ )
277
+ )
278
+ qc: StringCategoryCorpusReader = LazyCorpusLoader(
279
+ "qc", StringCategoryCorpusReader, ["train.txt", "test.txt"], encoding="ISO-8859-2"
280
+ )
281
+ reuters: CategorizedPlaintextCorpusReader = LazyCorpusLoader(
282
+ "reuters",
283
+ CategorizedPlaintextCorpusReader,
284
+ "(training|test).*",
285
+ cat_file="cats.txt",
286
+ encoding="ISO-8859-2",
287
+ )
288
+ rte: RTECorpusReader = LazyCorpusLoader("rte", RTECorpusReader, r"(?!\.).*\.xml")
289
+ senseval: SensevalCorpusReader = LazyCorpusLoader(
290
+ "senseval", SensevalCorpusReader, r"(?!\.).*\.pos"
291
+ )
292
+ sentence_polarity: CategorizedSentencesCorpusReader = LazyCorpusLoader(
293
+ "sentence_polarity",
294
+ CategorizedSentencesCorpusReader,
295
+ r"rt-polarity\.(neg|pos)",
296
+ cat_pattern=r"rt-polarity\.(neg|pos)",
297
+ encoding="utf-8",
298
+ )
299
+ sentiwordnet: SentiWordNetCorpusReader = LazyCorpusLoader(
300
+ "sentiwordnet", SentiWordNetCorpusReader, "SentiWordNet_3.0.0.txt", encoding="utf-8"
301
+ )
302
+ shakespeare: XMLCorpusReader = LazyCorpusLoader(
303
+ "shakespeare", XMLCorpusReader, r"(?!\.).*\.xml"
304
+ )
305
+ sinica_treebank: SinicaTreebankCorpusReader = LazyCorpusLoader(
306
+ "sinica_treebank",
307
+ SinicaTreebankCorpusReader,
308
+ ["parsed"],
309
+ tagset="unknown",
310
+ encoding="utf-8",
311
+ )
312
+ state_union: PlaintextCorpusReader = LazyCorpusLoader(
313
+ "state_union", PlaintextCorpusReader, r"(?!\.).*\.txt", encoding="ISO-8859-2"
314
+ )
315
+ stopwords: WordListCorpusReader = LazyCorpusLoader(
316
+ "stopwords", WordListCorpusReader, r"(?!README|\.).*", encoding="utf8"
317
+ )
318
+ subjectivity: CategorizedSentencesCorpusReader = LazyCorpusLoader(
319
+ "subjectivity",
320
+ CategorizedSentencesCorpusReader,
321
+ r"(quote.tok.gt9|plot.tok.gt9)\.5000",
322
+ cat_map={"quote.tok.gt9.5000": ["subj"], "plot.tok.gt9.5000": ["obj"]},
323
+ encoding="latin-1",
324
+ )
325
+ swadesh: SwadeshCorpusReader = LazyCorpusLoader(
326
+ "swadesh", SwadeshCorpusReader, r"(?!README|\.).*", encoding="utf8"
327
+ )
328
+ swadesh110: PanlexSwadeshCorpusReader = LazyCorpusLoader(
329
+ "panlex_swadesh", PanlexSwadeshCorpusReader, r"swadesh110/.*\.txt", encoding="utf8"
330
+ )
331
+ swadesh207: PanlexSwadeshCorpusReader = LazyCorpusLoader(
332
+ "panlex_swadesh", PanlexSwadeshCorpusReader, r"swadesh207/.*\.txt", encoding="utf8"
333
+ )
334
+ switchboard: SwitchboardCorpusReader = LazyCorpusLoader(
335
+ "switchboard", SwitchboardCorpusReader, tagset="wsj"
336
+ )
337
+ timit: TimitCorpusReader = LazyCorpusLoader("timit", TimitCorpusReader)
338
+ timit_tagged: TimitTaggedCorpusReader = LazyCorpusLoader(
339
+ "timit", TimitTaggedCorpusReader, r".+\.tags", tagset="wsj", encoding="ascii"
340
+ )
341
+ toolbox: ToolboxCorpusReader = LazyCorpusLoader(
342
+ "toolbox", ToolboxCorpusReader, r"(?!.*(README|\.)).*\.(dic|txt)"
343
+ )
344
+ treebank: BracketParseCorpusReader = LazyCorpusLoader(
345
+ "treebank/combined",
346
+ BracketParseCorpusReader,
347
+ r"wsj_.*\.mrg",
348
+ tagset="wsj",
349
+ encoding="ascii",
350
+ )
351
+ treebank_chunk: ChunkedCorpusReader = LazyCorpusLoader(
352
+ "treebank/tagged",
353
+ ChunkedCorpusReader,
354
+ r"wsj_.*\.pos",
355
+ sent_tokenizer=RegexpTokenizer(r"(?<=/\.)\s*(?![^\[]*\])", gaps=True),
356
+ para_block_reader=tagged_treebank_para_block_reader,
357
+ tagset="wsj",
358
+ encoding="ascii",
359
+ )
360
+ treebank_raw: PlaintextCorpusReader = LazyCorpusLoader(
361
+ "treebank/raw", PlaintextCorpusReader, r"wsj_.*", encoding="ISO-8859-2"
362
+ )
363
+ twitter_samples: TwitterCorpusReader = LazyCorpusLoader(
364
+ "twitter_samples", TwitterCorpusReader, r".*\.json"
365
+ )
366
+ udhr: UdhrCorpusReader = LazyCorpusLoader("udhr", UdhrCorpusReader)
367
+ udhr2: PlaintextCorpusReader = LazyCorpusLoader(
368
+ "udhr2", PlaintextCorpusReader, r".*\.txt", encoding="utf8"
369
+ )
370
+ universal_treebanks: ConllCorpusReader = LazyCorpusLoader(
371
+ "universal_treebanks_v20",
372
+ ConllCorpusReader,
373
+ r".*\.conll",
374
+ columntypes=(
375
+ "ignore",
376
+ "words",
377
+ "ignore",
378
+ "ignore",
379
+ "pos",
380
+ "ignore",
381
+ "ignore",
382
+ "ignore",
383
+ "ignore",
384
+ "ignore",
385
+ ),
386
+ )
387
+ verbnet: VerbnetCorpusReader = LazyCorpusLoader(
388
+ "verbnet", VerbnetCorpusReader, r"(?!\.).*\.xml"
389
+ )
390
+ webtext: PlaintextCorpusReader = LazyCorpusLoader(
391
+ "webtext", PlaintextCorpusReader, r"(?!README|\.).*\.txt", encoding="ISO-8859-2"
392
+ )
393
+ wordnet: WordNetCorpusReader = LazyCorpusLoader(
394
+ "wordnet",
395
+ WordNetCorpusReader,
396
+ LazyCorpusLoader("omw-1.4", CorpusReader, r".*/wn-data-.*\.tab", encoding="utf8"),
397
+ )
398
+ wordnet31: WordNetCorpusReader = LazyCorpusLoader(
399
+ "wordnet31",
400
+ WordNetCorpusReader,
401
+ LazyCorpusLoader("omw-1.4", CorpusReader, r".*/wn-data-.*\.tab", encoding="utf8"),
402
+ )
403
+ wordnet2021: WordNetCorpusReader = LazyCorpusLoader(
404
+ "wordnet2021",
405
+ WordNetCorpusReader,
406
+ LazyCorpusLoader("omw-1.4", CorpusReader, r".*/wn-data-.*\.tab", encoding="utf8"),
407
+ )
408
+ wordnet_ic: WordNetICCorpusReader = LazyCorpusLoader(
409
+ "wordnet_ic", WordNetICCorpusReader, r".*\.dat"
410
+ )
411
+ words: WordListCorpusReader = LazyCorpusLoader(
412
+ "words", WordListCorpusReader, r"(?!README|\.).*", encoding="ascii"
413
+ )
414
+
415
+ # defined after treebank
416
+ propbank: PropbankCorpusReader = LazyCorpusLoader(
417
+ "propbank",
418
+ PropbankCorpusReader,
419
+ "prop.txt",
420
+ r"frames/.*\.xml",
421
+ "verbs.txt",
422
+ lambda filename: re.sub(r"^wsj/\d\d/", "", filename),
423
+ treebank,
424
+ ) # Must be defined *after* treebank corpus.
425
+ nombank: NombankCorpusReader = LazyCorpusLoader(
426
+ "nombank.1.0",
427
+ NombankCorpusReader,
428
+ "nombank.1.0",
429
+ r"frames/.*\.xml",
430
+ "nombank.1.0.words",
431
+ lambda filename: re.sub(r"^wsj/\d\d/", "", filename),
432
+ treebank,
433
+ ) # Must be defined *after* treebank corpus.
434
+ propbank_ptb: PropbankCorpusReader = LazyCorpusLoader(
435
+ "propbank",
436
+ PropbankCorpusReader,
437
+ "prop.txt",
438
+ r"frames/.*\.xml",
439
+ "verbs.txt",
440
+ lambda filename: filename.upper(),
441
+ ptb,
442
+ ) # Must be defined *after* ptb corpus.
443
+ nombank_ptb: NombankCorpusReader = LazyCorpusLoader(
444
+ "nombank.1.0",
445
+ NombankCorpusReader,
446
+ "nombank.1.0",
447
+ r"frames/.*\.xml",
448
+ "nombank.1.0.words",
449
+ lambda filename: filename.upper(),
450
+ ptb,
451
+ ) # Must be defined *after* ptb corpus.
452
+ semcor: SemcorCorpusReader = LazyCorpusLoader(
453
+ "semcor", SemcorCorpusReader, r"brown./tagfiles/br-.*\.xml", wordnet
454
+ ) # Must be defined *after* wordnet corpus.
455
+
456
+ nonbreaking_prefixes: NonbreakingPrefixesCorpusReader = LazyCorpusLoader(
457
+ "nonbreaking_prefixes",
458
+ NonbreakingPrefixesCorpusReader,
459
+ r"(?!README|\.).*",
460
+ encoding="utf8",
461
+ )
462
+ perluniprops: UnicharsCorpusReader = LazyCorpusLoader(
463
+ "perluniprops",
464
+ UnicharsCorpusReader,
465
+ r"(?!README|\.).*",
466
+ nltk_data_subdir="misc",
467
+ encoding="utf8",
468
+ )
469
+
470
+ # mwa_ppdb = LazyCorpusLoader(
471
+ # 'mwa_ppdb', MWAPPDBCorpusReader, r'(?!README|\.).*', nltk_data_subdir='misc', encoding='utf8')
472
+
473
+ # See https://github.com/nltk/nltk/issues/1579
474
+ # and https://github.com/nltk/nltk/issues/1716
475
+ #
476
+ # pl196x = LazyCorpusLoader(
477
+ # 'pl196x', Pl196xCorpusReader, r'[a-z]-.*\.xml',
478
+ # cat_file='cats.txt', textid_file='textids.txt', encoding='utf8')
479
+ #
480
+ # ipipan = LazyCorpusLoader(
481
+ # 'ipipan', IPIPANCorpusReader, r'(?!\.).*morph\.xml')
482
+ #
483
+ # nkjp = LazyCorpusLoader(
484
+ # 'nkjp', NKJPCorpusReader, r'', encoding='utf8')
485
+ #
486
+ # panlex_lite = LazyCorpusLoader(
487
+ # 'panlex_lite', PanLexLiteCorpusReader)
488
+ #
489
+ # ycoe = LazyCorpusLoader(
490
+ # 'ycoe', YCOECorpusReader)
491
+ #
492
+ # corpus not available with NLTK; these lines caused help(nltk.corpus) to break
493
+ # hebrew_treebank = LazyCorpusLoader(
494
+ # 'hebrew_treebank', BracketParseCorpusReader, r'.*\.txt')
495
+
496
+ # FIXME: override any imported demo from various corpora, see https://github.com/nltk/nltk/issues/2116
497
+ def demo():
498
+ # This is out-of-date:
499
+ abc.demo()
500
+ brown.demo()
501
+ # chat80.demo()
502
+ cmudict.demo()
503
+ conll2000.demo()
504
+ conll2002.demo()
505
+ genesis.demo()
506
+ gutenberg.demo()
507
+ ieer.demo()
508
+ inaugural.demo()
509
+ indian.demo()
510
+ names.demo()
511
+ ppattach.demo()
512
+ senseval.demo()
513
+ shakespeare.demo()
514
+ sinica_treebank.demo()
515
+ state_union.demo()
516
+ stopwords.demo()
517
+ timit.demo()
518
+ toolbox.demo()
519
+ treebank.demo()
520
+ udhr.demo()
521
+ webtext.demo()
522
+ words.demo()
523
+
524
+
525
+ # ycoe.demo()
526
+
527
+ if __name__ == "__main__":
528
+ # demo()
529
+ pass
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/europarl_raw.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Europarl Corpus Readers
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Nitin Madnani <nmadnani@umiacs.umd.edu>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+
8
+ import re
9
+
10
+ from nltk.corpus.reader import *
11
+ from nltk.corpus.util import LazyCorpusLoader
12
+
13
+ # Create a new corpus reader instance for each European language
14
+ danish: EuroparlCorpusReader = LazyCorpusLoader(
15
+ "europarl_raw/danish", EuroparlCorpusReader, r"ep-.*\.da", encoding="utf-8"
16
+ )
17
+
18
+ dutch: EuroparlCorpusReader = LazyCorpusLoader(
19
+ "europarl_raw/dutch", EuroparlCorpusReader, r"ep-.*\.nl", encoding="utf-8"
20
+ )
21
+
22
+ english: EuroparlCorpusReader = LazyCorpusLoader(
23
+ "europarl_raw/english", EuroparlCorpusReader, r"ep-.*\.en", encoding="utf-8"
24
+ )
25
+
26
+ finnish: EuroparlCorpusReader = LazyCorpusLoader(
27
+ "europarl_raw/finnish", EuroparlCorpusReader, r"ep-.*\.fi", encoding="utf-8"
28
+ )
29
+
30
+ french: EuroparlCorpusReader = LazyCorpusLoader(
31
+ "europarl_raw/french", EuroparlCorpusReader, r"ep-.*\.fr", encoding="utf-8"
32
+ )
33
+
34
+ german: EuroparlCorpusReader = LazyCorpusLoader(
35
+ "europarl_raw/german", EuroparlCorpusReader, r"ep-.*\.de", encoding="utf-8"
36
+ )
37
+
38
+ greek: EuroparlCorpusReader = LazyCorpusLoader(
39
+ "europarl_raw/greek", EuroparlCorpusReader, r"ep-.*\.el", encoding="utf-8"
40
+ )
41
+
42
+ italian: EuroparlCorpusReader = LazyCorpusLoader(
43
+ "europarl_raw/italian", EuroparlCorpusReader, r"ep-.*\.it", encoding="utf-8"
44
+ )
45
+
46
+ portuguese: EuroparlCorpusReader = LazyCorpusLoader(
47
+ "europarl_raw/portuguese", EuroparlCorpusReader, r"ep-.*\.pt", encoding="utf-8"
48
+ )
49
+
50
+ spanish: EuroparlCorpusReader = LazyCorpusLoader(
51
+ "europarl_raw/spanish", EuroparlCorpusReader, r"ep-.*\.es", encoding="utf-8"
52
+ )
53
+
54
+ swedish: EuroparlCorpusReader = LazyCorpusLoader(
55
+ "europarl_raw/swedish", EuroparlCorpusReader, r"ep-.*\.sv", encoding="utf-8"
56
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/util.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Corpus Reader Utility Functions
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Edward Loper <edloper@gmail.com>
5
+ # URL: <https://www.nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+
8
+ ######################################################################
9
+ # { Lazy Corpus Loader
10
+ ######################################################################
11
+
12
+ import gc
13
+ import re
14
+
15
+ import nltk
16
+
17
+ TRY_ZIPFILE_FIRST = False
18
+
19
+
20
+ class LazyCorpusLoader:
21
+ """
22
+ To see the API documentation for this lazily loaded corpus, first
23
+ run corpus.ensure_loaded(), and then run help(this_corpus).
24
+
25
+ LazyCorpusLoader is a proxy object which is used to stand in for a
26
+ corpus object before the corpus is loaded. This allows NLTK to
27
+ create an object for each corpus, but defer the costs associated
28
+ with loading those corpora until the first time that they're
29
+ actually accessed.
30
+
31
+ The first time this object is accessed in any way, it will load
32
+ the corresponding corpus, and transform itself into that corpus
33
+ (by modifying its own ``__class__`` and ``__dict__`` attributes).
34
+
35
+ If the corpus can not be found, then accessing this object will
36
+ raise an exception, displaying installation instructions for the
37
+ NLTK data package. Once they've properly installed the data
38
+ package (or modified ``nltk.data.path`` to point to its location),
39
+ they can then use the corpus object without restarting python.
40
+
41
+ :param name: The name of the corpus
42
+ :type name: str
43
+ :param reader_cls: The specific CorpusReader class, e.g. PlaintextCorpusReader, WordListCorpusReader
44
+ :type reader: nltk.corpus.reader.api.CorpusReader
45
+ :param nltk_data_subdir: The subdirectory where the corpus is stored.
46
+ :type nltk_data_subdir: str
47
+ :param `*args`: Any other non-keywords arguments that `reader_cls` might need.
48
+ :param `**kwargs`: Any other keywords arguments that `reader_cls` might need.
49
+ """
50
+
51
+ def __init__(self, name, reader_cls, *args, **kwargs):
52
+ from nltk.corpus.reader.api import CorpusReader
53
+
54
+ assert issubclass(reader_cls, CorpusReader)
55
+ self.__name = self.__name__ = name
56
+ self.__reader_cls = reader_cls
57
+ # If nltk_data_subdir is set explicitly
58
+ if "nltk_data_subdir" in kwargs:
59
+ # Use the specified subdirectory path
60
+ self.subdir = kwargs["nltk_data_subdir"]
61
+ # Pops the `nltk_data_subdir` argument, we don't need it anymore.
62
+ kwargs.pop("nltk_data_subdir", None)
63
+ else: # Otherwise use 'nltk_data/corpora'
64
+ self.subdir = "corpora"
65
+ self.__args = args
66
+ self.__kwargs = kwargs
67
+
68
+ def __load(self):
69
+ # Find the corpus root directory.
70
+ zip_name = re.sub(r"(([^/]+)(/.*)?)", r"\2.zip/\1/", self.__name)
71
+ if TRY_ZIPFILE_FIRST:
72
+ try:
73
+ root = nltk.data.find(f"{self.subdir}/{zip_name}")
74
+ except LookupError as e:
75
+ try:
76
+ root = nltk.data.find(f"{self.subdir}/{self.__name}")
77
+ except LookupError:
78
+ raise e
79
+ else:
80
+ try:
81
+ root = nltk.data.find(f"{self.subdir}/{self.__name}")
82
+ except LookupError as e:
83
+ try:
84
+ root = nltk.data.find(f"{self.subdir}/{zip_name}")
85
+ except LookupError:
86
+ raise e
87
+
88
+ # Load the corpus.
89
+ corpus = self.__reader_cls(root, *self.__args, **self.__kwargs)
90
+
91
+ # This is where the magic happens! Transform ourselves into
92
+ # the corpus by modifying our own __dict__ and __class__ to
93
+ # match that of the corpus.
94
+
95
+ args, kwargs = self.__args, self.__kwargs
96
+ name, reader_cls = self.__name, self.__reader_cls
97
+
98
+ self.__dict__ = corpus.__dict__
99
+ self.__class__ = corpus.__class__
100
+
101
+ # _unload support: assign __dict__ and __class__ back, then do GC.
102
+ # after reassigning __dict__ there shouldn't be any references to
103
+ # corpus data so the memory should be deallocated after gc.collect()
104
+ def _unload(self):
105
+ lazy_reader = LazyCorpusLoader(name, reader_cls, *args, **kwargs)
106
+ self.__dict__ = lazy_reader.__dict__
107
+ self.__class__ = lazy_reader.__class__
108
+ gc.collect()
109
+
110
+ self._unload = _make_bound_method(_unload, self)
111
+
112
+ def __getattr__(self, attr):
113
+
114
+ # Fix for inspect.isclass under Python 2.6
115
+ # (see https://bugs.python.org/issue1225107).
116
+ # Without this fix tests may take extra 1.5GB RAM
117
+ # because all corpora gets loaded during test collection.
118
+ if attr == "__bases__":
119
+ raise AttributeError("LazyCorpusLoader object has no attribute '__bases__'")
120
+
121
+ self.__load()
122
+ # This looks circular, but its not, since __load() changes our
123
+ # __class__ to something new:
124
+ return getattr(self, attr)
125
+
126
+ def __repr__(self):
127
+ return "<{} in {!r} (not loaded yet)>".format(
128
+ self.__reader_cls.__name__,
129
+ ".../corpora/" + self.__name,
130
+ )
131
+
132
+ def _unload(self):
133
+ # If an exception occurs during corpus loading then
134
+ # '_unload' method may be unattached, so __getattr__ can be called;
135
+ # we shouldn't trigger corpus loading again in this case.
136
+ pass
137
+
138
+
139
+ def _make_bound_method(func, self):
140
+ """
141
+ Magic for creating bound methods (used for _unload).
142
+ """
143
+
144
+ class Foo:
145
+ def meth(self):
146
+ pass
147
+
148
+ f = Foo()
149
+ bound_method = type(f.meth)
150
+
151
+ try:
152
+ return bound_method(func, self, self.__class__)
153
+ except TypeError: # python3
154
+ return bound_method(func, self)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Inference
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Dan Garrette <dhgarrette@gmail.com>
5
+ # Ewan Klein <ewan@inf.ed.ac.uk>
6
+ #
7
+ # URL: <https://www.nltk.org/>
8
+ # For license information, see LICENSE.TXT
9
+
10
+ """
11
+ Classes and interfaces for theorem proving and model building.
12
+ """
13
+
14
+ from nltk.inference.api import ParallelProverBuilder, ParallelProverBuilderCommand
15
+ from nltk.inference.discourse import (
16
+ CfgReadingCommand,
17
+ DiscourseTester,
18
+ DrtGlueReadingCommand,
19
+ ReadingCommand,
20
+ )
21
+ from nltk.inference.mace import Mace, MaceCommand
22
+ from nltk.inference.prover9 import Prover9, Prover9Command
23
+ from nltk.inference.resolution import ResolutionProver, ResolutionProverCommand
24
+ from nltk.inference.tableau import TableauProver, TableauProverCommand
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (861 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/api.cpython-310.pyc ADDED
Binary file (19.1 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/discourse.cpython-310.pyc ADDED
Binary file (20.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/mace.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/nonmonotonic.cpython-310.pyc ADDED
Binary file (16.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/prover9.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/resolution.cpython-310.pyc ADDED
Binary file (21.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/__pycache__/tableau.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/api.py ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Classifier Interface
2
+ #
3
+ # Author: Ewan Klein <ewan@inf.ed.ac.uk>
4
+ # Dan Garrette <dhgarrette@gmail.com>
5
+ #
6
+ # URL: <https://www.nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+
9
+ """
10
+ Interfaces and base classes for theorem provers and model builders.
11
+
12
+ ``Prover`` is a standard interface for a theorem prover which tries to prove a goal from a
13
+ list of assumptions.
14
+
15
+ ``ModelBuilder`` is a standard interface for a model builder. Given just a set of assumptions.
16
+ the model builder tries to build a model for the assumptions. Given a set of assumptions and a
17
+ goal *G*, the model builder tries to find a counter-model, in the sense of a model that will satisfy
18
+ the assumptions plus the negation of *G*.
19
+ """
20
+
21
+ import threading
22
+ import time
23
+ from abc import ABCMeta, abstractmethod
24
+
25
+
26
+ class Prover(metaclass=ABCMeta):
27
+ """
28
+ Interface for trying to prove a goal from assumptions. Both the goal and
29
+ the assumptions are constrained to be formulas of ``logic.Expression``.
30
+ """
31
+
32
+ def prove(self, goal=None, assumptions=None, verbose=False):
33
+ """
34
+ :return: Whether the proof was successful or not.
35
+ :rtype: bool
36
+ """
37
+ return self._prove(goal, assumptions, verbose)[0]
38
+
39
+ @abstractmethod
40
+ def _prove(self, goal=None, assumptions=None, verbose=False):
41
+ """
42
+ :return: Whether the proof was successful or not, along with the proof
43
+ :rtype: tuple: (bool, str)
44
+ """
45
+
46
+
47
+ class ModelBuilder(metaclass=ABCMeta):
48
+ """
49
+ Interface for trying to build a model of set of formulas.
50
+ Open formulas are assumed to be universally quantified.
51
+ Both the goal and the assumptions are constrained to be formulas
52
+ of ``logic.Expression``.
53
+ """
54
+
55
+ def build_model(self, goal=None, assumptions=None, verbose=False):
56
+ """
57
+ Perform the actual model building.
58
+ :return: Whether a model was generated
59
+ :rtype: bool
60
+ """
61
+ return self._build_model(goal, assumptions, verbose)[0]
62
+
63
+ @abstractmethod
64
+ def _build_model(self, goal=None, assumptions=None, verbose=False):
65
+ """
66
+ Perform the actual model building.
67
+ :return: Whether a model was generated, and the model itself
68
+ :rtype: tuple(bool, sem.Valuation)
69
+ """
70
+
71
+
72
+ class TheoremToolCommand(metaclass=ABCMeta):
73
+ """
74
+ This class holds a goal and a list of assumptions to be used in proving
75
+ or model building.
76
+ """
77
+
78
+ @abstractmethod
79
+ def add_assumptions(self, new_assumptions):
80
+ """
81
+ Add new assumptions to the assumption list.
82
+
83
+ :param new_assumptions: new assumptions
84
+ :type new_assumptions: list(sem.Expression)
85
+ """
86
+
87
+ @abstractmethod
88
+ def retract_assumptions(self, retracted, debug=False):
89
+ """
90
+ Retract assumptions from the assumption list.
91
+
92
+ :param debug: If True, give warning when ``retracted`` is not present on
93
+ assumptions list.
94
+ :type debug: bool
95
+ :param retracted: assumptions to be retracted
96
+ :type retracted: list(sem.Expression)
97
+ """
98
+
99
+ @abstractmethod
100
+ def assumptions(self):
101
+ """
102
+ List the current assumptions.
103
+
104
+ :return: list of ``Expression``
105
+ """
106
+
107
+ @abstractmethod
108
+ def goal(self):
109
+ """
110
+ Return the goal
111
+
112
+ :return: ``Expression``
113
+ """
114
+
115
+ @abstractmethod
116
+ def print_assumptions(self):
117
+ """
118
+ Print the list of the current assumptions.
119
+ """
120
+
121
+
122
+ class ProverCommand(TheoremToolCommand):
123
+ """
124
+ This class holds a ``Prover``, a goal, and a list of assumptions. When
125
+ prove() is called, the ``Prover`` is executed with the goal and assumptions.
126
+ """
127
+
128
+ @abstractmethod
129
+ def prove(self, verbose=False):
130
+ """
131
+ Perform the actual proof.
132
+ """
133
+
134
+ @abstractmethod
135
+ def proof(self, simplify=True):
136
+ """
137
+ Return the proof string
138
+ :param simplify: bool simplify the proof?
139
+ :return: str
140
+ """
141
+
142
+ @abstractmethod
143
+ def get_prover(self):
144
+ """
145
+ Return the prover object
146
+ :return: ``Prover``
147
+ """
148
+
149
+
150
+ class ModelBuilderCommand(TheoremToolCommand):
151
+ """
152
+ This class holds a ``ModelBuilder``, a goal, and a list of assumptions.
153
+ When build_model() is called, the ``ModelBuilder`` is executed with the goal
154
+ and assumptions.
155
+ """
156
+
157
+ @abstractmethod
158
+ def build_model(self, verbose=False):
159
+ """
160
+ Perform the actual model building.
161
+ :return: A model if one is generated; None otherwise.
162
+ :rtype: sem.Valuation
163
+ """
164
+
165
+ @abstractmethod
166
+ def model(self, format=None):
167
+ """
168
+ Return a string representation of the model
169
+
170
+ :param simplify: bool simplify the proof?
171
+ :return: str
172
+ """
173
+
174
+ @abstractmethod
175
+ def get_model_builder(self):
176
+ """
177
+ Return the model builder object
178
+ :return: ``ModelBuilder``
179
+ """
180
+
181
+
182
+ class BaseTheoremToolCommand(TheoremToolCommand):
183
+ """
184
+ This class holds a goal and a list of assumptions to be used in proving
185
+ or model building.
186
+ """
187
+
188
+ def __init__(self, goal=None, assumptions=None):
189
+ """
190
+ :param goal: Input expression to prove
191
+ :type goal: sem.Expression
192
+ :param assumptions: Input expressions to use as assumptions in
193
+ the proof.
194
+ :type assumptions: list(sem.Expression)
195
+ """
196
+ self._goal = goal
197
+
198
+ if not assumptions:
199
+ self._assumptions = []
200
+ else:
201
+ self._assumptions = list(assumptions)
202
+
203
+ self._result = None
204
+ """A holder for the result, to prevent unnecessary re-proving"""
205
+
206
+ def add_assumptions(self, new_assumptions):
207
+ """
208
+ Add new assumptions to the assumption list.
209
+
210
+ :param new_assumptions: new assumptions
211
+ :type new_assumptions: list(sem.Expression)
212
+ """
213
+ self._assumptions.extend(new_assumptions)
214
+ self._result = None
215
+
216
+ def retract_assumptions(self, retracted, debug=False):
217
+ """
218
+ Retract assumptions from the assumption list.
219
+
220
+ :param debug: If True, give warning when ``retracted`` is not present on
221
+ assumptions list.
222
+ :type debug: bool
223
+ :param retracted: assumptions to be retracted
224
+ :type retracted: list(sem.Expression)
225
+ """
226
+ retracted = set(retracted)
227
+ result_list = list(filter(lambda a: a not in retracted, self._assumptions))
228
+ if debug and result_list == self._assumptions:
229
+ print(Warning("Assumptions list has not been changed:"))
230
+ self.print_assumptions()
231
+
232
+ self._assumptions = result_list
233
+
234
+ self._result = None
235
+
236
+ def assumptions(self):
237
+ """
238
+ List the current assumptions.
239
+
240
+ :return: list of ``Expression``
241
+ """
242
+ return self._assumptions
243
+
244
+ def goal(self):
245
+ """
246
+ Return the goal
247
+
248
+ :return: ``Expression``
249
+ """
250
+ return self._goal
251
+
252
+ def print_assumptions(self):
253
+ """
254
+ Print the list of the current assumptions.
255
+ """
256
+ for a in self.assumptions():
257
+ print(a)
258
+
259
+
260
+ class BaseProverCommand(BaseTheoremToolCommand, ProverCommand):
261
+ """
262
+ This class holds a ``Prover``, a goal, and a list of assumptions. When
263
+ prove() is called, the ``Prover`` is executed with the goal and assumptions.
264
+ """
265
+
266
+ def __init__(self, prover, goal=None, assumptions=None):
267
+ """
268
+ :param prover: The theorem tool to execute with the assumptions
269
+ :type prover: Prover
270
+ :see: ``BaseTheoremToolCommand``
271
+ """
272
+ self._prover = prover
273
+ """The theorem tool to execute with the assumptions"""
274
+
275
+ BaseTheoremToolCommand.__init__(self, goal, assumptions)
276
+
277
+ self._proof = None
278
+
279
+ def prove(self, verbose=False):
280
+ """
281
+ Perform the actual proof. Store the result to prevent unnecessary
282
+ re-proving.
283
+ """
284
+ if self._result is None:
285
+ self._result, self._proof = self._prover._prove(
286
+ self.goal(), self.assumptions(), verbose
287
+ )
288
+ return self._result
289
+
290
+ def proof(self, simplify=True):
291
+ """
292
+ Return the proof string
293
+ :param simplify: bool simplify the proof?
294
+ :return: str
295
+ """
296
+ if self._result is None:
297
+ raise LookupError("You have to call prove() first to get a proof!")
298
+ else:
299
+ return self.decorate_proof(self._proof, simplify)
300
+
301
+ def decorate_proof(self, proof_string, simplify=True):
302
+ """
303
+ Modify and return the proof string
304
+ :param proof_string: str the proof to decorate
305
+ :param simplify: bool simplify the proof?
306
+ :return: str
307
+ """
308
+ return proof_string
309
+
310
+ def get_prover(self):
311
+ return self._prover
312
+
313
+
314
+ class BaseModelBuilderCommand(BaseTheoremToolCommand, ModelBuilderCommand):
315
+ """
316
+ This class holds a ``ModelBuilder``, a goal, and a list of assumptions. When
317
+ build_model() is called, the ``ModelBuilder`` is executed with the goal and
318
+ assumptions.
319
+ """
320
+
321
+ def __init__(self, modelbuilder, goal=None, assumptions=None):
322
+ """
323
+ :param modelbuilder: The theorem tool to execute with the assumptions
324
+ :type modelbuilder: ModelBuilder
325
+ :see: ``BaseTheoremToolCommand``
326
+ """
327
+ self._modelbuilder = modelbuilder
328
+ """The theorem tool to execute with the assumptions"""
329
+
330
+ BaseTheoremToolCommand.__init__(self, goal, assumptions)
331
+
332
+ self._model = None
333
+
334
+ def build_model(self, verbose=False):
335
+ """
336
+ Attempt to build a model. Store the result to prevent unnecessary
337
+ re-building.
338
+ """
339
+ if self._result is None:
340
+ self._result, self._model = self._modelbuilder._build_model(
341
+ self.goal(), self.assumptions(), verbose
342
+ )
343
+ return self._result
344
+
345
+ def model(self, format=None):
346
+ """
347
+ Return a string representation of the model
348
+
349
+ :param simplify: bool simplify the proof?
350
+ :return: str
351
+ """
352
+ if self._result is None:
353
+ raise LookupError("You have to call build_model() first to " "get a model!")
354
+ else:
355
+ return self._decorate_model(self._model, format)
356
+
357
+ def _decorate_model(self, valuation_str, format=None):
358
+ """
359
+ :param valuation_str: str with the model builder's output
360
+ :param format: str indicating the format for displaying
361
+ :return: str
362
+ """
363
+ return valuation_str
364
+
365
+ def get_model_builder(self):
366
+ return self._modelbuilder
367
+
368
+
369
+ class TheoremToolCommandDecorator(TheoremToolCommand):
370
+ """
371
+ A base decorator for the ``ProverCommandDecorator`` and
372
+ ``ModelBuilderCommandDecorator`` classes from which decorators can extend.
373
+ """
374
+
375
+ def __init__(self, command):
376
+ """
377
+ :param command: ``TheoremToolCommand`` to decorate
378
+ """
379
+ self._command = command
380
+
381
+ # The decorator has its own versions of 'result' different from the
382
+ # underlying command
383
+ self._result = None
384
+
385
+ def assumptions(self):
386
+ return self._command.assumptions()
387
+
388
+ def goal(self):
389
+ return self._command.goal()
390
+
391
+ def add_assumptions(self, new_assumptions):
392
+ self._command.add_assumptions(new_assumptions)
393
+ self._result = None
394
+
395
+ def retract_assumptions(self, retracted, debug=False):
396
+ self._command.retract_assumptions(retracted, debug)
397
+ self._result = None
398
+
399
+ def print_assumptions(self):
400
+ self._command.print_assumptions()
401
+
402
+
403
+ class ProverCommandDecorator(TheoremToolCommandDecorator, ProverCommand):
404
+ """
405
+ A base decorator for the ``ProverCommand`` class from which other
406
+ prover command decorators can extend.
407
+ """
408
+
409
+ def __init__(self, proverCommand):
410
+ """
411
+ :param proverCommand: ``ProverCommand`` to decorate
412
+ """
413
+ TheoremToolCommandDecorator.__init__(self, proverCommand)
414
+
415
+ # The decorator has its own versions of 'result' and 'proof'
416
+ # because they may be different from the underlying command
417
+ self._proof = None
418
+
419
+ def prove(self, verbose=False):
420
+ if self._result is None:
421
+ prover = self.get_prover()
422
+ self._result, self._proof = prover._prove(
423
+ self.goal(), self.assumptions(), verbose
424
+ )
425
+ return self._result
426
+
427
+ def proof(self, simplify=True):
428
+ """
429
+ Return the proof string
430
+ :param simplify: bool simplify the proof?
431
+ :return: str
432
+ """
433
+ if self._result is None:
434
+ raise LookupError("You have to call prove() first to get a proof!")
435
+ else:
436
+ return self.decorate_proof(self._proof, simplify)
437
+
438
+ def decorate_proof(self, proof_string, simplify=True):
439
+ """
440
+ Modify and return the proof string
441
+ :param proof_string: str the proof to decorate
442
+ :param simplify: bool simplify the proof?
443
+ :return: str
444
+ """
445
+ return self._command.decorate_proof(proof_string, simplify)
446
+
447
+ def get_prover(self):
448
+ return self._command.get_prover()
449
+
450
+
451
+ class ModelBuilderCommandDecorator(TheoremToolCommandDecorator, ModelBuilderCommand):
452
+ """
453
+ A base decorator for the ``ModelBuilderCommand`` class from which other
454
+ prover command decorators can extend.
455
+ """
456
+
457
+ def __init__(self, modelBuilderCommand):
458
+ """
459
+ :param modelBuilderCommand: ``ModelBuilderCommand`` to decorate
460
+ """
461
+ TheoremToolCommandDecorator.__init__(self, modelBuilderCommand)
462
+
463
+ # The decorator has its own versions of 'result' and 'valuation'
464
+ # because they may be different from the underlying command
465
+ self._model = None
466
+
467
+ def build_model(self, verbose=False):
468
+ """
469
+ Attempt to build a model. Store the result to prevent unnecessary
470
+ re-building.
471
+ """
472
+ if self._result is None:
473
+ modelbuilder = self.get_model_builder()
474
+ self._result, self._model = modelbuilder._build_model(
475
+ self.goal(), self.assumptions(), verbose
476
+ )
477
+ return self._result
478
+
479
+ def model(self, format=None):
480
+ """
481
+ Return a string representation of the model
482
+
483
+ :param simplify: bool simplify the proof?
484
+ :return: str
485
+ """
486
+ if self._result is None:
487
+ raise LookupError("You have to call build_model() first to " "get a model!")
488
+ else:
489
+ return self._decorate_model(self._model, format)
490
+
491
+ def _decorate_model(self, valuation_str, format=None):
492
+ """
493
+ Modify and return the proof string
494
+ :param valuation_str: str with the model builder's output
495
+ :param format: str indicating the format for displaying
496
+ :return: str
497
+ """
498
+ return self._command._decorate_model(valuation_str, format)
499
+
500
+ def get_model_builder(self):
501
+ return self._command.get_prover()
502
+
503
+
504
+ class ParallelProverBuilder(Prover, ModelBuilder):
505
+ """
506
+ This class stores both a prover and a model builder and when either
507
+ prove() or build_model() is called, then both theorem tools are run in
508
+ parallel. Whichever finishes first, the prover or the model builder, is the
509
+ result that will be used.
510
+ """
511
+
512
+ def __init__(self, prover, modelbuilder):
513
+ self._prover = prover
514
+ self._modelbuilder = modelbuilder
515
+
516
+ def _prove(self, goal=None, assumptions=None, verbose=False):
517
+ return self._run(goal, assumptions, verbose), ""
518
+
519
+ def _build_model(self, goal=None, assumptions=None, verbose=False):
520
+ return not self._run(goal, assumptions, verbose), ""
521
+
522
+ def _run(self, goal, assumptions, verbose):
523
+ # Set up two thread, Prover and ModelBuilder to run in parallel
524
+ tp_thread = TheoremToolThread(
525
+ lambda: self._prover.prove(goal, assumptions, verbose), verbose, "TP"
526
+ )
527
+ mb_thread = TheoremToolThread(
528
+ lambda: self._modelbuilder.build_model(goal, assumptions, verbose),
529
+ verbose,
530
+ "MB",
531
+ )
532
+
533
+ tp_thread.start()
534
+ mb_thread.start()
535
+
536
+ while tp_thread.is_alive() and mb_thread.is_alive():
537
+ # wait until either the prover or the model builder is done
538
+ pass
539
+
540
+ if tp_thread.result is not None:
541
+ return tp_thread.result
542
+ elif mb_thread.result is not None:
543
+ return not mb_thread.result
544
+ else:
545
+ return None
546
+
547
+
548
+ class ParallelProverBuilderCommand(BaseProverCommand, BaseModelBuilderCommand):
549
+ """
550
+ This command stores both a prover and a model builder and when either
551
+ prove() or build_model() is called, then both theorem tools are run in
552
+ parallel. Whichever finishes first, the prover or the model builder, is the
553
+ result that will be used.
554
+
555
+ Because the theorem prover result is the opposite of the model builder
556
+ result, we will treat self._result as meaning "proof found/no model found".
557
+ """
558
+
559
+ def __init__(self, prover, modelbuilder, goal=None, assumptions=None):
560
+ BaseProverCommand.__init__(self, prover, goal, assumptions)
561
+ BaseModelBuilderCommand.__init__(self, modelbuilder, goal, assumptions)
562
+
563
+ def prove(self, verbose=False):
564
+ return self._run(verbose)
565
+
566
+ def build_model(self, verbose=False):
567
+ return not self._run(verbose)
568
+
569
+ def _run(self, verbose):
570
+ # Set up two thread, Prover and ModelBuilder to run in parallel
571
+ tp_thread = TheoremToolThread(
572
+ lambda: BaseProverCommand.prove(self, verbose), verbose, "TP"
573
+ )
574
+ mb_thread = TheoremToolThread(
575
+ lambda: BaseModelBuilderCommand.build_model(self, verbose), verbose, "MB"
576
+ )
577
+
578
+ tp_thread.start()
579
+ mb_thread.start()
580
+
581
+ while tp_thread.is_alive() and mb_thread.is_alive():
582
+ # wait until either the prover or the model builder is done
583
+ pass
584
+
585
+ if tp_thread.result is not None:
586
+ self._result = tp_thread.result
587
+ elif mb_thread.result is not None:
588
+ self._result = not mb_thread.result
589
+ return self._result
590
+
591
+
592
+ class TheoremToolThread(threading.Thread):
593
+ def __init__(self, command, verbose, name=None):
594
+ threading.Thread.__init__(self)
595
+ self._command = command
596
+ self._result = None
597
+ self._verbose = verbose
598
+ self._name = name
599
+
600
+ def run(self):
601
+ try:
602
+ self._result = self._command()
603
+ if self._verbose:
604
+ print(
605
+ "Thread %s finished with result %s at %s"
606
+ % (self._name, self._result, time.localtime(time.time()))
607
+ )
608
+ except Exception as e:
609
+ print(e)
610
+ print("Thread %s completed abnormally" % (self._name))
611
+
612
+ @property
613
+ def result(self):
614
+ return self._result
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/discourse.py ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Discourse Processing
2
+ #
3
+ # Author: Ewan Klein <ewan@inf.ed.ac.uk>
4
+ # Dan Garrette <dhgarrette@gmail.com>
5
+ #
6
+ # URL: <https://www.nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+
9
+ r"""
10
+ Module for incrementally developing simple discourses, and checking for semantic ambiguity,
11
+ consistency and informativeness.
12
+
13
+ Many of the ideas are based on the CURT family of programs of Blackburn and Bos
14
+ (see http://homepages.inf.ed.ac.uk/jbos/comsem/book1.html).
15
+
16
+ Consistency checking is carried out by using the ``mace`` module to call the Mace4 model builder.
17
+ Informativeness checking is carried out with a call to ``Prover.prove()`` from
18
+ the ``inference`` module.
19
+
20
+ ``DiscourseTester`` is a constructor for discourses.
21
+ The basic data structure is a list of sentences, stored as ``self._sentences``. Each sentence in the list
22
+ is assigned a "sentence ID" (``sid``) of the form ``s``\ *i*. For example::
23
+
24
+ s0: A boxer walks
25
+ s1: Every boxer chases a girl
26
+
27
+ Each sentence can be ambiguous between a number of readings, each of which receives a
28
+ "reading ID" (``rid``) of the form ``s``\ *i* -``r``\ *j*. For example::
29
+
30
+ s0 readings:
31
+
32
+ s0-r1: some x.(boxer(x) & walk(x))
33
+ s0-r0: some x.(boxerdog(x) & walk(x))
34
+
35
+ A "thread" is a list of readings, represented as a list of ``rid``\ s.
36
+ Each thread receives a "thread ID" (``tid``) of the form ``d``\ *i*.
37
+ For example::
38
+
39
+ d0: ['s0-r0', 's1-r0']
40
+
41
+ The set of all threads for a discourse is the Cartesian product of all the readings of the sequences of sentences.
42
+ (This is not intended to scale beyond very short discourses!) The method ``readings(filter=True)`` will only show
43
+ those threads which are consistent (taking into account any background assumptions).
44
+ """
45
+
46
+ import os
47
+ from abc import ABCMeta, abstractmethod
48
+ from functools import reduce
49
+ from operator import add, and_
50
+
51
+ from nltk.data import show_cfg
52
+ from nltk.inference.mace import MaceCommand
53
+ from nltk.inference.prover9 import Prover9Command
54
+ from nltk.parse import load_parser
55
+ from nltk.parse.malt import MaltParser
56
+ from nltk.sem.drt import AnaphoraResolutionException, resolve_anaphora
57
+ from nltk.sem.glue import DrtGlue
58
+ from nltk.sem.logic import Expression
59
+ from nltk.tag import RegexpTagger
60
+
61
+
62
+ class ReadingCommand(metaclass=ABCMeta):
63
+ @abstractmethod
64
+ def parse_to_readings(self, sentence):
65
+ """
66
+ :param sentence: the sentence to read
67
+ :type sentence: str
68
+ """
69
+
70
+ def process_thread(self, sentence_readings):
71
+ """
72
+ This method should be used to handle dependencies between readings such
73
+ as resolving anaphora.
74
+
75
+ :param sentence_readings: readings to process
76
+ :type sentence_readings: list(Expression)
77
+ :return: the list of readings after processing
78
+ :rtype: list(Expression)
79
+ """
80
+ return sentence_readings
81
+
82
+ @abstractmethod
83
+ def combine_readings(self, readings):
84
+ """
85
+ :param readings: readings to combine
86
+ :type readings: list(Expression)
87
+ :return: one combined reading
88
+ :rtype: Expression
89
+ """
90
+
91
+ @abstractmethod
92
+ def to_fol(self, expression):
93
+ """
94
+ Convert this expression into a First-Order Logic expression.
95
+
96
+ :param expression: an expression
97
+ :type expression: Expression
98
+ :return: a FOL version of the input expression
99
+ :rtype: Expression
100
+ """
101
+
102
+
103
+ class CfgReadingCommand(ReadingCommand):
104
+ def __init__(self, gramfile=None):
105
+ """
106
+ :param gramfile: name of file where grammar can be loaded
107
+ :type gramfile: str
108
+ """
109
+ self._gramfile = (
110
+ gramfile if gramfile else "grammars/book_grammars/discourse.fcfg"
111
+ )
112
+ self._parser = load_parser(self._gramfile)
113
+
114
+ def parse_to_readings(self, sentence):
115
+ """:see: ReadingCommand.parse_to_readings()"""
116
+ from nltk.sem import root_semrep
117
+
118
+ tokens = sentence.split()
119
+ trees = self._parser.parse(tokens)
120
+ return [root_semrep(tree) for tree in trees]
121
+
122
+ def combine_readings(self, readings):
123
+ """:see: ReadingCommand.combine_readings()"""
124
+ return reduce(and_, readings)
125
+
126
+ def to_fol(self, expression):
127
+ """:see: ReadingCommand.to_fol()"""
128
+ return expression
129
+
130
+
131
+ class DrtGlueReadingCommand(ReadingCommand):
132
+ def __init__(self, semtype_file=None, remove_duplicates=False, depparser=None):
133
+ """
134
+ :param semtype_file: name of file where grammar can be loaded
135
+ :param remove_duplicates: should duplicates be removed?
136
+ :param depparser: the dependency parser
137
+ """
138
+ if semtype_file is None:
139
+ semtype_file = os.path.join(
140
+ "grammars", "sample_grammars", "drt_glue.semtype"
141
+ )
142
+ self._glue = DrtGlue(
143
+ semtype_file=semtype_file,
144
+ remove_duplicates=remove_duplicates,
145
+ depparser=depparser,
146
+ )
147
+
148
+ def parse_to_readings(self, sentence):
149
+ """:see: ReadingCommand.parse_to_readings()"""
150
+ return self._glue.parse_to_meaning(sentence)
151
+
152
+ def process_thread(self, sentence_readings):
153
+ """:see: ReadingCommand.process_thread()"""
154
+ try:
155
+ return [self.combine_readings(sentence_readings)]
156
+ except AnaphoraResolutionException:
157
+ return []
158
+
159
+ def combine_readings(self, readings):
160
+ """:see: ReadingCommand.combine_readings()"""
161
+ thread_reading = reduce(add, readings)
162
+ return resolve_anaphora(thread_reading.simplify())
163
+
164
+ def to_fol(self, expression):
165
+ """:see: ReadingCommand.to_fol()"""
166
+ return expression.fol()
167
+
168
+
169
+ class DiscourseTester:
170
+ """
171
+ Check properties of an ongoing discourse.
172
+ """
173
+
174
+ def __init__(self, input, reading_command=None, background=None):
175
+ """
176
+ Initialize a ``DiscourseTester``.
177
+
178
+ :param input: the discourse sentences
179
+ :type input: list of str
180
+ :param background: Formulas which express background assumptions
181
+ :type background: list(Expression)
182
+ """
183
+ self._input = input
184
+ self._sentences = {"s%s" % i: sent for i, sent in enumerate(input)}
185
+ self._models = None
186
+ self._readings = {}
187
+ self._reading_command = (
188
+ reading_command if reading_command else CfgReadingCommand()
189
+ )
190
+ self._threads = {}
191
+ self._filtered_threads = {}
192
+ if background is not None:
193
+ from nltk.sem.logic import Expression
194
+
195
+ for e in background:
196
+ assert isinstance(e, Expression)
197
+ self._background = background
198
+ else:
199
+ self._background = []
200
+
201
+ ###############################
202
+ # Sentences
203
+ ###############################
204
+
205
+ def sentences(self):
206
+ """
207
+ Display the list of sentences in the current discourse.
208
+ """
209
+ for id in sorted(self._sentences):
210
+ print(f"{id}: {self._sentences[id]}")
211
+
212
+ def add_sentence(self, sentence, informchk=False, consistchk=False):
213
+ """
214
+ Add a sentence to the current discourse.
215
+
216
+ Updates ``self._input`` and ``self._sentences``.
217
+ :param sentence: An input sentence
218
+ :type sentence: str
219
+ :param informchk: if ``True``, check that the result of adding the sentence is thread-informative. Updates ``self._readings``.
220
+ :param consistchk: if ``True``, check that the result of adding the sentence is thread-consistent. Updates ``self._readings``.
221
+
222
+ """
223
+ # check whether the new sentence is informative (i.e. not entailed by the previous discourse)
224
+ if informchk:
225
+ self.readings(verbose=False)
226
+ for tid in sorted(self._threads):
227
+ assumptions = [reading for (rid, reading) in self.expand_threads(tid)]
228
+ assumptions += self._background
229
+ for sent_reading in self._get_readings(sentence):
230
+ tp = Prover9Command(goal=sent_reading, assumptions=assumptions)
231
+ if tp.prove():
232
+ print(
233
+ "Sentence '%s' under reading '%s':"
234
+ % (sentence, str(sent_reading))
235
+ )
236
+ print("Not informative relative to thread '%s'" % tid)
237
+
238
+ self._input.append(sentence)
239
+ self._sentences = {"s%s" % i: sent for i, sent in enumerate(self._input)}
240
+ # check whether adding the new sentence to the discourse preserves consistency (i.e. a model can be found for the combined set of
241
+ # of assumptions
242
+ if consistchk:
243
+ self.readings(verbose=False)
244
+ self.models(show=False)
245
+
246
+ def retract_sentence(self, sentence, verbose=True):
247
+ """
248
+ Remove a sentence from the current discourse.
249
+
250
+ Updates ``self._input``, ``self._sentences`` and ``self._readings``.
251
+ :param sentence: An input sentence
252
+ :type sentence: str
253
+ :param verbose: If ``True``, report on the updated list of sentences.
254
+ """
255
+ try:
256
+ self._input.remove(sentence)
257
+ except ValueError:
258
+ print(
259
+ "Retraction failed. The sentence '%s' is not part of the current discourse:"
260
+ % sentence
261
+ )
262
+ self.sentences()
263
+ return None
264
+ self._sentences = {"s%s" % i: sent for i, sent in enumerate(self._input)}
265
+ self.readings(verbose=False)
266
+ if verbose:
267
+ print("Current sentences are ")
268
+ self.sentences()
269
+
270
+ def grammar(self):
271
+ """
272
+ Print out the grammar in use for parsing input sentences
273
+ """
274
+ show_cfg(self._reading_command._gramfile)
275
+
276
+ ###############################
277
+ # Readings and Threads
278
+ ###############################
279
+
280
+ def _get_readings(self, sentence):
281
+ """
282
+ Build a list of semantic readings for a sentence.
283
+
284
+ :rtype: list(Expression)
285
+ """
286
+ return self._reading_command.parse_to_readings(sentence)
287
+
288
+ def _construct_readings(self):
289
+ """
290
+ Use ``self._sentences`` to construct a value for ``self._readings``.
291
+ """
292
+ # re-initialize self._readings in case we have retracted a sentence
293
+ self._readings = {}
294
+ for sid in sorted(self._sentences):
295
+ sentence = self._sentences[sid]
296
+ readings = self._get_readings(sentence)
297
+ self._readings[sid] = {
298
+ f"{sid}-r{rid}": reading.simplify()
299
+ for rid, reading in enumerate(sorted(readings, key=str))
300
+ }
301
+
302
+ def _construct_threads(self):
303
+ """
304
+ Use ``self._readings`` to construct a value for ``self._threads``
305
+ and use the model builder to construct a value for ``self._filtered_threads``
306
+ """
307
+ thread_list = [[]]
308
+ for sid in sorted(self._readings):
309
+ thread_list = self.multiply(thread_list, sorted(self._readings[sid]))
310
+ self._threads = {"d%s" % tid: thread for tid, thread in enumerate(thread_list)}
311
+ # re-initialize the filtered threads
312
+ self._filtered_threads = {}
313
+ # keep the same ids, but only include threads which get models
314
+ consistency_checked = self._check_consistency(self._threads)
315
+ for (tid, thread) in self._threads.items():
316
+ if (tid, True) in consistency_checked:
317
+ self._filtered_threads[tid] = thread
318
+
319
+ def _show_readings(self, sentence=None):
320
+ """
321
+ Print out the readings for the discourse (or a single sentence).
322
+ """
323
+ if sentence is not None:
324
+ print("The sentence '%s' has these readings:" % sentence)
325
+ for r in [str(reading) for reading in (self._get_readings(sentence))]:
326
+ print(" %s" % r)
327
+ else:
328
+ for sid in sorted(self._readings):
329
+ print()
330
+ print("%s readings:" % sid)
331
+ print() #'-' * 30
332
+ for rid in sorted(self._readings[sid]):
333
+ lf = self._readings[sid][rid]
334
+ print(f"{rid}: {lf.normalize()}")
335
+
336
+ def _show_threads(self, filter=False, show_thread_readings=False):
337
+ """
338
+ Print out the value of ``self._threads`` or ``self._filtered_hreads``
339
+ """
340
+ threads = self._filtered_threads if filter else self._threads
341
+ for tid in sorted(threads):
342
+ if show_thread_readings:
343
+ readings = [
344
+ self._readings[rid.split("-")[0]][rid] for rid in self._threads[tid]
345
+ ]
346
+ try:
347
+ thread_reading = (
348
+ ": %s"
349
+ % self._reading_command.combine_readings(readings).normalize()
350
+ )
351
+ except Exception as e:
352
+ thread_reading = ": INVALID: %s" % e.__class__.__name__
353
+ else:
354
+ thread_reading = ""
355
+
356
+ print("%s:" % tid, self._threads[tid], thread_reading)
357
+
358
+ def readings(
359
+ self,
360
+ sentence=None,
361
+ threaded=False,
362
+ verbose=True,
363
+ filter=False,
364
+ show_thread_readings=False,
365
+ ):
366
+ """
367
+ Construct and show the readings of the discourse (or of a single sentence).
368
+
369
+ :param sentence: test just this sentence
370
+ :type sentence: str
371
+ :param threaded: if ``True``, print out each thread ID and the corresponding thread.
372
+ :param filter: if ``True``, only print out consistent thread IDs and threads.
373
+ """
374
+ self._construct_readings()
375
+ self._construct_threads()
376
+
377
+ # if we are filtering or showing thread readings, show threads
378
+ if filter or show_thread_readings:
379
+ threaded = True
380
+
381
+ if verbose:
382
+ if not threaded:
383
+ self._show_readings(sentence=sentence)
384
+ else:
385
+ self._show_threads(
386
+ filter=filter, show_thread_readings=show_thread_readings
387
+ )
388
+
389
+ def expand_threads(self, thread_id, threads=None):
390
+ """
391
+ Given a thread ID, find the list of ``logic.Expression`` objects corresponding to the reading IDs in that thread.
392
+
393
+ :param thread_id: thread ID
394
+ :type thread_id: str
395
+ :param threads: a mapping from thread IDs to lists of reading IDs
396
+ :type threads: dict
397
+ :return: A list of pairs ``(rid, reading)`` where reading is the ``logic.Expression`` associated with a reading ID
398
+ :rtype: list of tuple
399
+ """
400
+ if threads is None:
401
+ threads = self._threads
402
+ return [
403
+ (rid, self._readings[sid][rid])
404
+ for rid in threads[thread_id]
405
+ for sid in rid.split("-")[:1]
406
+ ]
407
+
408
+ ###############################
409
+ # Models and Background
410
+ ###############################
411
+
412
+ def _check_consistency(self, threads, show=False, verbose=False):
413
+ results = []
414
+ for tid in sorted(threads):
415
+ assumptions = [
416
+ reading for (rid, reading) in self.expand_threads(tid, threads=threads)
417
+ ]
418
+ assumptions = list(
419
+ map(
420
+ self._reading_command.to_fol,
421
+ self._reading_command.process_thread(assumptions),
422
+ )
423
+ )
424
+ if assumptions:
425
+ assumptions += self._background
426
+ # if Mace4 finds a model, it always seems to find it quickly
427
+ mb = MaceCommand(None, assumptions, max_models=20)
428
+ modelfound = mb.build_model()
429
+ else:
430
+ modelfound = False
431
+ results.append((tid, modelfound))
432
+ if show:
433
+ spacer(80)
434
+ print("Model for Discourse Thread %s" % tid)
435
+ spacer(80)
436
+ if verbose:
437
+ for a in assumptions:
438
+ print(a)
439
+ spacer(80)
440
+ if modelfound:
441
+ print(mb.model(format="cooked"))
442
+ else:
443
+ print("No model found!\n")
444
+ return results
445
+
446
+ def models(self, thread_id=None, show=True, verbose=False):
447
+ """
448
+ Call Mace4 to build a model for each current discourse thread.
449
+
450
+ :param thread_id: thread ID
451
+ :type thread_id: str
452
+ :param show: If ``True``, display the model that has been found.
453
+ """
454
+ self._construct_readings()
455
+ self._construct_threads()
456
+ threads = {thread_id: self._threads[thread_id]} if thread_id else self._threads
457
+
458
+ for (tid, modelfound) in self._check_consistency(
459
+ threads, show=show, verbose=verbose
460
+ ):
461
+ idlist = [rid for rid in threads[tid]]
462
+
463
+ if not modelfound:
464
+ print(f"Inconsistent discourse: {tid} {idlist}:")
465
+ for rid, reading in self.expand_threads(tid):
466
+ print(f" {rid}: {reading.normalize()}")
467
+ print()
468
+ else:
469
+ print(f"Consistent discourse: {tid} {idlist}:")
470
+ for rid, reading in self.expand_threads(tid):
471
+ print(f" {rid}: {reading.normalize()}")
472
+ print()
473
+
474
+ def add_background(self, background, verbose=False):
475
+ """
476
+ Add a list of background assumptions for reasoning about the discourse.
477
+
478
+ When called, this method also updates the discourse model's set of readings and threads.
479
+ :param background: Formulas which contain background information
480
+ :type background: list(Expression)
481
+ """
482
+ from nltk.sem.logic import Expression
483
+
484
+ for (count, e) in enumerate(background):
485
+ assert isinstance(e, Expression)
486
+ if verbose:
487
+ print("Adding assumption %s to background" % count)
488
+ self._background.append(e)
489
+
490
+ # update the state
491
+ self._construct_readings()
492
+ self._construct_threads()
493
+
494
+ def background(self):
495
+ """
496
+ Show the current background assumptions.
497
+ """
498
+ for e in self._background:
499
+ print(str(e))
500
+
501
+ ###############################
502
+ # Misc
503
+ ###############################
504
+
505
+ @staticmethod
506
+ def multiply(discourse, readings):
507
+ """
508
+ Multiply every thread in ``discourse`` by every reading in ``readings``.
509
+
510
+ Given discourse = [['A'], ['B']], readings = ['a', 'b', 'c'] , returns
511
+ [['A', 'a'], ['A', 'b'], ['A', 'c'], ['B', 'a'], ['B', 'b'], ['B', 'c']]
512
+
513
+ :param discourse: the current list of readings
514
+ :type discourse: list of lists
515
+ :param readings: an additional list of readings
516
+ :type readings: list(Expression)
517
+ :rtype: A list of lists
518
+ """
519
+ result = []
520
+ for sublist in discourse:
521
+ for r in readings:
522
+ new = []
523
+ new += sublist
524
+ new.append(r)
525
+ result.append(new)
526
+ return result
527
+
528
+
529
+ def load_fol(s):
530
+ """
531
+ Temporarily duplicated from ``nltk.sem.util``.
532
+ Convert a file of first order formulas into a list of ``Expression`` objects.
533
+
534
+ :param s: the contents of the file
535
+ :type s: str
536
+ :return: a list of parsed formulas.
537
+ :rtype: list(Expression)
538
+ """
539
+ statements = []
540
+ for linenum, line in enumerate(s.splitlines()):
541
+ line = line.strip()
542
+ if line.startswith("#") or line == "":
543
+ continue
544
+ try:
545
+ statements.append(Expression.fromstring(line))
546
+ except Exception as e:
547
+ raise ValueError(f"Unable to parse line {linenum}: {line}") from e
548
+ return statements
549
+
550
+
551
+ ###############################
552
+ # Demo
553
+ ###############################
554
+ def discourse_demo(reading_command=None):
555
+ """
556
+ Illustrate the various methods of ``DiscourseTester``
557
+ """
558
+ dt = DiscourseTester(
559
+ ["A boxer walks", "Every boxer chases a girl"], reading_command
560
+ )
561
+ dt.models()
562
+ print()
563
+ # dt.grammar()
564
+ print()
565
+ dt.sentences()
566
+ print()
567
+ dt.readings()
568
+ print()
569
+ dt.readings(threaded=True)
570
+ print()
571
+ dt.models("d1")
572
+ dt.add_sentence("John is a boxer")
573
+ print()
574
+ dt.sentences()
575
+ print()
576
+ dt.readings(threaded=True)
577
+ print()
578
+ dt = DiscourseTester(
579
+ ["A student dances", "Every student is a person"], reading_command
580
+ )
581
+ print()
582
+ dt.add_sentence("No person dances", consistchk=True)
583
+ print()
584
+ dt.readings()
585
+ print()
586
+ dt.retract_sentence("No person dances", verbose=True)
587
+ print()
588
+ dt.models()
589
+ print()
590
+ dt.readings("A person dances")
591
+ print()
592
+ dt.add_sentence("A person dances", informchk=True)
593
+ dt = DiscourseTester(
594
+ ["Vincent is a boxer", "Fido is a boxer", "Vincent is married", "Fido barks"],
595
+ reading_command,
596
+ )
597
+ dt.readings(filter=True)
598
+ import nltk.data
599
+
600
+ background_file = os.path.join("grammars", "book_grammars", "background.fol")
601
+ background = nltk.data.load(background_file)
602
+
603
+ print()
604
+ dt.add_background(background, verbose=False)
605
+ dt.background()
606
+ print()
607
+ dt.readings(filter=True)
608
+ print()
609
+ dt.models()
610
+
611
+
612
+ def drt_discourse_demo(reading_command=None):
613
+ """
614
+ Illustrate the various methods of ``DiscourseTester``
615
+ """
616
+ dt = DiscourseTester(["every dog chases a boy", "he runs"], reading_command)
617
+ dt.models()
618
+ print()
619
+ dt.sentences()
620
+ print()
621
+ dt.readings()
622
+ print()
623
+ dt.readings(show_thread_readings=True)
624
+ print()
625
+ dt.readings(filter=True, show_thread_readings=True)
626
+
627
+
628
+ def spacer(num=30):
629
+ print("-" * num)
630
+
631
+
632
+ def demo():
633
+ discourse_demo()
634
+
635
+ tagger = RegexpTagger(
636
+ [
637
+ ("^(chases|runs)$", "VB"),
638
+ ("^(a)$", "ex_quant"),
639
+ ("^(every)$", "univ_quant"),
640
+ ("^(dog|boy)$", "NN"),
641
+ ("^(he)$", "PRP"),
642
+ ]
643
+ )
644
+ depparser = MaltParser(tagger=tagger)
645
+ drt_discourse_demo(
646
+ DrtGlueReadingCommand(remove_duplicates=False, depparser=depparser)
647
+ )
648
+
649
+
650
+ if __name__ == "__main__":
651
+ demo()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/mace.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Interface to the Mace4 Model Builder
2
+ #
3
+ # Author: Dan Garrette <dhgarrette@gmail.com>
4
+ # Ewan Klein <ewan@inf.ed.ac.uk>
5
+
6
+ # URL: <https://www.nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+
9
+ """
10
+ A model builder that makes use of the external 'Mace4' package.
11
+ """
12
+
13
+ import os
14
+ import tempfile
15
+
16
+ from nltk.inference.api import BaseModelBuilderCommand, ModelBuilder
17
+ from nltk.inference.prover9 import Prover9CommandParent, Prover9Parent
18
+ from nltk.sem import Expression, Valuation
19
+ from nltk.sem.logic import is_indvar
20
+
21
+
22
+ class MaceCommand(Prover9CommandParent, BaseModelBuilderCommand):
23
+ """
24
+ A ``MaceCommand`` specific to the ``Mace`` model builder. It contains
25
+ a print_assumptions() method that is used to print the list
26
+ of assumptions in multiple formats.
27
+ """
28
+
29
+ _interpformat_bin = None
30
+
31
+ def __init__(self, goal=None, assumptions=None, max_models=500, model_builder=None):
32
+ """
33
+ :param goal: Input expression to prove
34
+ :type goal: sem.Expression
35
+ :param assumptions: Input expressions to use as assumptions in
36
+ the proof.
37
+ :type assumptions: list(sem.Expression)
38
+ :param max_models: The maximum number of models that Mace will try before
39
+ simply returning false. (Use 0 for no maximum.)
40
+ :type max_models: int
41
+ """
42
+ if model_builder is not None:
43
+ assert isinstance(model_builder, Mace)
44
+ else:
45
+ model_builder = Mace(max_models)
46
+
47
+ BaseModelBuilderCommand.__init__(self, model_builder, goal, assumptions)
48
+
49
+ @property
50
+ def valuation(mbc):
51
+ return mbc.model("valuation")
52
+
53
+ def _convert2val(self, valuation_str):
54
+ """
55
+ Transform the output file into an NLTK-style Valuation.
56
+
57
+ :return: A model if one is generated; None otherwise.
58
+ :rtype: sem.Valuation
59
+ """
60
+ valuation_standard_format = self._transform_output(valuation_str, "standard")
61
+
62
+ val = []
63
+ for line in valuation_standard_format.splitlines(False):
64
+ l = line.strip()
65
+
66
+ if l.startswith("interpretation"):
67
+ # find the number of entities in the model
68
+ num_entities = int(l[l.index("(") + 1 : l.index(",")].strip())
69
+
70
+ elif l.startswith("function") and l.find("_") == -1:
71
+ # replace the integer identifier with a corresponding alphabetic character
72
+ name = l[l.index("(") + 1 : l.index(",")].strip()
73
+ if is_indvar(name):
74
+ name = name.upper()
75
+ value = int(l[l.index("[") + 1 : l.index("]")].strip())
76
+ val.append((name, MaceCommand._make_model_var(value)))
77
+
78
+ elif l.startswith("relation"):
79
+ l = l[l.index("(") + 1 :]
80
+ if "(" in l:
81
+ # relation is not nullary
82
+ name = l[: l.index("(")].strip()
83
+ values = [
84
+ int(v.strip())
85
+ for v in l[l.index("[") + 1 : l.index("]")].split(",")
86
+ ]
87
+ val.append(
88
+ (name, MaceCommand._make_relation_set(num_entities, values))
89
+ )
90
+ else:
91
+ # relation is nullary
92
+ name = l[: l.index(",")].strip()
93
+ value = int(l[l.index("[") + 1 : l.index("]")].strip())
94
+ val.append((name, value == 1))
95
+
96
+ return Valuation(val)
97
+
98
+ @staticmethod
99
+ def _make_relation_set(num_entities, values):
100
+ """
101
+ Convert a Mace4-style relation table into a dictionary.
102
+
103
+ :param num_entities: the number of entities in the model; determines the row length in the table.
104
+ :type num_entities: int
105
+ :param values: a list of 1's and 0's that represent whether a relation holds in a Mace4 model.
106
+ :type values: list of int
107
+ """
108
+ r = set()
109
+ for position in [pos for (pos, v) in enumerate(values) if v == 1]:
110
+ r.add(
111
+ tuple(MaceCommand._make_relation_tuple(position, values, num_entities))
112
+ )
113
+ return r
114
+
115
+ @staticmethod
116
+ def _make_relation_tuple(position, values, num_entities):
117
+ if len(values) == 1:
118
+ return []
119
+ else:
120
+ sublist_size = len(values) // num_entities
121
+ sublist_start = position // sublist_size
122
+ sublist_position = int(position % sublist_size)
123
+
124
+ sublist = values[
125
+ sublist_start * sublist_size : (sublist_start + 1) * sublist_size
126
+ ]
127
+ return [
128
+ MaceCommand._make_model_var(sublist_start)
129
+ ] + MaceCommand._make_relation_tuple(
130
+ sublist_position, sublist, num_entities
131
+ )
132
+
133
+ @staticmethod
134
+ def _make_model_var(value):
135
+ """
136
+ Pick an alphabetic character as identifier for an entity in the model.
137
+
138
+ :param value: where to index into the list of characters
139
+ :type value: int
140
+ """
141
+ letter = [
142
+ "a",
143
+ "b",
144
+ "c",
145
+ "d",
146
+ "e",
147
+ "f",
148
+ "g",
149
+ "h",
150
+ "i",
151
+ "j",
152
+ "k",
153
+ "l",
154
+ "m",
155
+ "n",
156
+ "o",
157
+ "p",
158
+ "q",
159
+ "r",
160
+ "s",
161
+ "t",
162
+ "u",
163
+ "v",
164
+ "w",
165
+ "x",
166
+ "y",
167
+ "z",
168
+ ][value]
169
+ num = value // 26
170
+ return letter + str(num) if num > 0 else letter
171
+
172
+ def _decorate_model(self, valuation_str, format):
173
+ """
174
+ Print out a Mace4 model using any Mace4 ``interpformat`` format.
175
+ See https://www.cs.unm.edu/~mccune/mace4/manual/ for details.
176
+
177
+ :param valuation_str: str with the model builder's output
178
+ :param format: str indicating the format for displaying
179
+ models. Defaults to 'standard' format.
180
+ :return: str
181
+ """
182
+ if not format:
183
+ return valuation_str
184
+ elif format == "valuation":
185
+ return self._convert2val(valuation_str)
186
+ else:
187
+ return self._transform_output(valuation_str, format)
188
+
189
+ def _transform_output(self, valuation_str, format):
190
+ """
191
+ Transform the output file into any Mace4 ``interpformat`` format.
192
+
193
+ :param format: Output format for displaying models.
194
+ :type format: str
195
+ """
196
+ if format in [
197
+ "standard",
198
+ "standard2",
199
+ "portable",
200
+ "tabular",
201
+ "raw",
202
+ "cooked",
203
+ "xml",
204
+ "tex",
205
+ ]:
206
+ return self._call_interpformat(valuation_str, [format])[0]
207
+ else:
208
+ raise LookupError("The specified format does not exist")
209
+
210
+ def _call_interpformat(self, input_str, args=[], verbose=False):
211
+ """
212
+ Call the ``interpformat`` binary with the given input.
213
+
214
+ :param input_str: A string whose contents are used as stdin.
215
+ :param args: A list of command-line arguments.
216
+ :return: A tuple (stdout, returncode)
217
+ :see: ``config_prover9``
218
+ """
219
+ if self._interpformat_bin is None:
220
+ self._interpformat_bin = self._modelbuilder._find_binary(
221
+ "interpformat", verbose
222
+ )
223
+
224
+ return self._modelbuilder._call(
225
+ input_str, self._interpformat_bin, args, verbose
226
+ )
227
+
228
+
229
+ class Mace(Prover9Parent, ModelBuilder):
230
+ _mace4_bin = None
231
+
232
+ def __init__(self, end_size=500):
233
+ self._end_size = end_size
234
+ """The maximum model size that Mace will try before
235
+ simply returning false. (Use -1 for no maximum.)"""
236
+
237
+ def _build_model(self, goal=None, assumptions=None, verbose=False):
238
+ """
239
+ Use Mace4 to build a first order model.
240
+
241
+ :return: ``True`` if a model was found (i.e. Mace returns value of 0),
242
+ else ``False``
243
+ """
244
+ if not assumptions:
245
+ assumptions = []
246
+
247
+ stdout, returncode = self._call_mace4(
248
+ self.prover9_input(goal, assumptions), verbose=verbose
249
+ )
250
+ return (returncode == 0, stdout)
251
+
252
+ def _call_mace4(self, input_str, args=[], verbose=False):
253
+ """
254
+ Call the ``mace4`` binary with the given input.
255
+
256
+ :param input_str: A string whose contents are used as stdin.
257
+ :param args: A list of command-line arguments.
258
+ :return: A tuple (stdout, returncode)
259
+ :see: ``config_prover9``
260
+ """
261
+ if self._mace4_bin is None:
262
+ self._mace4_bin = self._find_binary("mace4", verbose)
263
+
264
+ updated_input_str = ""
265
+ if self._end_size > 0:
266
+ updated_input_str += "assign(end_size, %d).\n\n" % self._end_size
267
+ updated_input_str += input_str
268
+
269
+ return self._call(updated_input_str, self._mace4_bin, args, verbose)
270
+
271
+
272
+ def spacer(num=30):
273
+ print("-" * num)
274
+
275
+
276
+ def decode_result(found):
277
+ """
278
+ Decode the result of model_found()
279
+
280
+ :param found: The output of model_found()
281
+ :type found: bool
282
+ """
283
+ return {True: "Countermodel found", False: "No countermodel found", None: "None"}[
284
+ found
285
+ ]
286
+
287
+
288
+ def test_model_found(arguments):
289
+ """
290
+ Try some proofs and exhibit the results.
291
+ """
292
+ for (goal, assumptions) in arguments:
293
+ g = Expression.fromstring(goal)
294
+ alist = [lp.parse(a) for a in assumptions]
295
+ m = MaceCommand(g, assumptions=alist, max_models=50)
296
+ found = m.build_model()
297
+ for a in alist:
298
+ print(" %s" % a)
299
+ print(f"|- {g}: {decode_result(found)}\n")
300
+
301
+
302
+ def test_build_model(arguments):
303
+ """
304
+ Try to build a ``nltk.sem.Valuation``.
305
+ """
306
+ g = Expression.fromstring("all x.man(x)")
307
+ alist = [
308
+ Expression.fromstring(a)
309
+ for a in [
310
+ "man(John)",
311
+ "man(Socrates)",
312
+ "man(Bill)",
313
+ "some x.(-(x = John) & man(x) & sees(John,x))",
314
+ "some x.(-(x = Bill) & man(x))",
315
+ "all x.some y.(man(x) -> gives(Socrates,x,y))",
316
+ ]
317
+ ]
318
+
319
+ m = MaceCommand(g, assumptions=alist)
320
+ m.build_model()
321
+ spacer()
322
+ print("Assumptions and Goal")
323
+ spacer()
324
+ for a in alist:
325
+ print(" %s" % a)
326
+ print(f"|- {g}: {decode_result(m.build_model())}\n")
327
+ spacer()
328
+ # print(m.model('standard'))
329
+ # print(m.model('cooked'))
330
+ print("Valuation")
331
+ spacer()
332
+ print(m.valuation, "\n")
333
+
334
+
335
+ def test_transform_output(argument_pair):
336
+ """
337
+ Transform the model into various Mace4 ``interpformat`` formats.
338
+ """
339
+ g = Expression.fromstring(argument_pair[0])
340
+ alist = [lp.parse(a) for a in argument_pair[1]]
341
+ m = MaceCommand(g, assumptions=alist)
342
+ m.build_model()
343
+ for a in alist:
344
+ print(" %s" % a)
345
+ print(f"|- {g}: {m.build_model()}\n")
346
+ for format in ["standard", "portable", "xml", "cooked"]:
347
+ spacer()
348
+ print("Using '%s' format" % format)
349
+ spacer()
350
+ print(m.model(format=format))
351
+
352
+
353
+ def test_make_relation_set():
354
+ print(
355
+ MaceCommand._make_relation_set(num_entities=3, values=[1, 0, 1])
356
+ == {("c",), ("a",)}
357
+ )
358
+ print(
359
+ MaceCommand._make_relation_set(
360
+ num_entities=3, values=[0, 0, 0, 0, 0, 0, 1, 0, 0]
361
+ )
362
+ == {("c", "a")}
363
+ )
364
+ print(
365
+ MaceCommand._make_relation_set(num_entities=2, values=[0, 0, 1, 0, 0, 0, 1, 0])
366
+ == {("a", "b", "a"), ("b", "b", "a")}
367
+ )
368
+
369
+
370
+ arguments = [
371
+ ("mortal(Socrates)", ["all x.(man(x) -> mortal(x))", "man(Socrates)"]),
372
+ ("(not mortal(Socrates))", ["all x.(man(x) -> mortal(x))", "man(Socrates)"]),
373
+ ]
374
+
375
+
376
+ def demo():
377
+ test_model_found(arguments)
378
+ test_build_model(arguments)
379
+ test_transform_output(arguments[1])
380
+
381
+
382
+ if __name__ == "__main__":
383
+ demo()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/nonmonotonic.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Nonmonotonic Reasoning
2
+ #
3
+ # Author: Daniel H. Garrette <dhgarrette@gmail.com>
4
+ #
5
+ # Copyright (C) 2001-2023 NLTK Project
6
+ # URL: <https://www.nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+
9
+ """
10
+ A module to perform nonmonotonic reasoning. The ideas and demonstrations in
11
+ this module are based on "Logical Foundations of Artificial Intelligence" by
12
+ Michael R. Genesereth and Nils J. Nilsson.
13
+ """
14
+
15
+ from collections import defaultdict
16
+ from functools import reduce
17
+
18
+ from nltk.inference.api import Prover, ProverCommandDecorator
19
+ from nltk.inference.prover9 import Prover9, Prover9Command
20
+ from nltk.sem.logic import (
21
+ AbstractVariableExpression,
22
+ AllExpression,
23
+ AndExpression,
24
+ ApplicationExpression,
25
+ BooleanExpression,
26
+ EqualityExpression,
27
+ ExistsExpression,
28
+ Expression,
29
+ ImpExpression,
30
+ NegatedExpression,
31
+ Variable,
32
+ VariableExpression,
33
+ operator,
34
+ unique_variable,
35
+ )
36
+
37
+
38
+ class ProverParseError(Exception):
39
+ pass
40
+
41
+
42
+ def get_domain(goal, assumptions):
43
+ if goal is None:
44
+ all_expressions = assumptions
45
+ else:
46
+ all_expressions = assumptions + [-goal]
47
+ return reduce(operator.or_, (a.constants() for a in all_expressions), set())
48
+
49
+
50
+ class ClosedDomainProver(ProverCommandDecorator):
51
+ """
52
+ This is a prover decorator that adds domain closure assumptions before
53
+ proving.
54
+ """
55
+
56
+ def assumptions(self):
57
+ assumptions = [a for a in self._command.assumptions()]
58
+ goal = self._command.goal()
59
+ domain = get_domain(goal, assumptions)
60
+ return [self.replace_quants(ex, domain) for ex in assumptions]
61
+
62
+ def goal(self):
63
+ goal = self._command.goal()
64
+ domain = get_domain(goal, self._command.assumptions())
65
+ return self.replace_quants(goal, domain)
66
+
67
+ def replace_quants(self, ex, domain):
68
+ """
69
+ Apply the closed domain assumption to the expression
70
+
71
+ - Domain = union([e.free()|e.constants() for e in all_expressions])
72
+ - translate "exists x.P" to "(z=d1 | z=d2 | ... ) & P.replace(x,z)" OR
73
+ "P.replace(x, d1) | P.replace(x, d2) | ..."
74
+ - translate "all x.P" to "P.replace(x, d1) & P.replace(x, d2) & ..."
75
+
76
+ :param ex: ``Expression``
77
+ :param domain: set of {Variable}s
78
+ :return: ``Expression``
79
+ """
80
+ if isinstance(ex, AllExpression):
81
+ conjuncts = [
82
+ ex.term.replace(ex.variable, VariableExpression(d)) for d in domain
83
+ ]
84
+ conjuncts = [self.replace_quants(c, domain) for c in conjuncts]
85
+ return reduce(lambda x, y: x & y, conjuncts)
86
+ elif isinstance(ex, BooleanExpression):
87
+ return ex.__class__(
88
+ self.replace_quants(ex.first, domain),
89
+ self.replace_quants(ex.second, domain),
90
+ )
91
+ elif isinstance(ex, NegatedExpression):
92
+ return -self.replace_quants(ex.term, domain)
93
+ elif isinstance(ex, ExistsExpression):
94
+ disjuncts = [
95
+ ex.term.replace(ex.variable, VariableExpression(d)) for d in domain
96
+ ]
97
+ disjuncts = [self.replace_quants(d, domain) for d in disjuncts]
98
+ return reduce(lambda x, y: x | y, disjuncts)
99
+ else:
100
+ return ex
101
+
102
+
103
+ class UniqueNamesProver(ProverCommandDecorator):
104
+ """
105
+ This is a prover decorator that adds unique names assumptions before
106
+ proving.
107
+ """
108
+
109
+ def assumptions(self):
110
+ """
111
+ - Domain = union([e.free()|e.constants() for e in all_expressions])
112
+ - if "d1 = d2" cannot be proven from the premises, then add "d1 != d2"
113
+ """
114
+ assumptions = self._command.assumptions()
115
+
116
+ domain = list(get_domain(self._command.goal(), assumptions))
117
+
118
+ # build a dictionary of obvious equalities
119
+ eq_sets = SetHolder()
120
+ for a in assumptions:
121
+ if isinstance(a, EqualityExpression):
122
+ av = a.first.variable
123
+ bv = a.second.variable
124
+ # put 'a' and 'b' in the same set
125
+ eq_sets[av].add(bv)
126
+
127
+ new_assumptions = []
128
+ for i, a in enumerate(domain):
129
+ for b in domain[i + 1 :]:
130
+ # if a and b are not already in the same equality set
131
+ if b not in eq_sets[a]:
132
+ newEqEx = EqualityExpression(
133
+ VariableExpression(a), VariableExpression(b)
134
+ )
135
+ if Prover9().prove(newEqEx, assumptions):
136
+ # we can prove that the names are the same entity.
137
+ # remember that they are equal so we don't re-check.
138
+ eq_sets[a].add(b)
139
+ else:
140
+ # we can't prove it, so assume unique names
141
+ new_assumptions.append(-newEqEx)
142
+
143
+ return assumptions + new_assumptions
144
+
145
+
146
+ class SetHolder(list):
147
+ """
148
+ A list of sets of Variables.
149
+ """
150
+
151
+ def __getitem__(self, item):
152
+ """
153
+ :param item: ``Variable``
154
+ :return: the set containing 'item'
155
+ """
156
+ assert isinstance(item, Variable)
157
+ for s in self:
158
+ if item in s:
159
+ return s
160
+ # item is not found in any existing set. so create a new set
161
+ new = {item}
162
+ self.append(new)
163
+ return new
164
+
165
+
166
+ class ClosedWorldProver(ProverCommandDecorator):
167
+ """
168
+ This is a prover decorator that completes predicates before proving.
169
+
170
+ If the assumptions contain "P(A)", then "all x.(P(x) -> (x=A))" is the completion of "P".
171
+ If the assumptions contain "all x.(ostrich(x) -> bird(x))", then "all x.(bird(x) -> ostrich(x))" is the completion of "bird".
172
+ If the assumptions don't contain anything that are "P", then "all x.-P(x)" is the completion of "P".
173
+
174
+ walk(Socrates)
175
+ Socrates != Bill
176
+ + all x.(walk(x) -> (x=Socrates))
177
+ ----------------
178
+ -walk(Bill)
179
+
180
+ see(Socrates, John)
181
+ see(John, Mary)
182
+ Socrates != John
183
+ John != Mary
184
+ + all x.all y.(see(x,y) -> ((x=Socrates & y=John) | (x=John & y=Mary)))
185
+ ----------------
186
+ -see(Socrates, Mary)
187
+
188
+ all x.(ostrich(x) -> bird(x))
189
+ bird(Tweety)
190
+ -ostrich(Sam)
191
+ Sam != Tweety
192
+ + all x.(bird(x) -> (ostrich(x) | x=Tweety))
193
+ + all x.-ostrich(x)
194
+ -------------------
195
+ -bird(Sam)
196
+ """
197
+
198
+ def assumptions(self):
199
+ assumptions = self._command.assumptions()
200
+
201
+ predicates = self._make_predicate_dict(assumptions)
202
+
203
+ new_assumptions = []
204
+ for p in predicates:
205
+ predHolder = predicates[p]
206
+ new_sig = self._make_unique_signature(predHolder)
207
+ new_sig_exs = [VariableExpression(v) for v in new_sig]
208
+
209
+ disjuncts = []
210
+
211
+ # Turn the signatures into disjuncts
212
+ for sig in predHolder.signatures:
213
+ equality_exs = []
214
+ for v1, v2 in zip(new_sig_exs, sig):
215
+ equality_exs.append(EqualityExpression(v1, v2))
216
+ disjuncts.append(reduce(lambda x, y: x & y, equality_exs))
217
+
218
+ # Turn the properties into disjuncts
219
+ for prop in predHolder.properties:
220
+ # replace variables from the signature with new sig variables
221
+ bindings = {}
222
+ for v1, v2 in zip(new_sig_exs, prop[0]):
223
+ bindings[v2] = v1
224
+ disjuncts.append(prop[1].substitute_bindings(bindings))
225
+
226
+ # make the assumption
227
+ if disjuncts:
228
+ # disjuncts exist, so make an implication
229
+ antecedent = self._make_antecedent(p, new_sig)
230
+ consequent = reduce(lambda x, y: x | y, disjuncts)
231
+ accum = ImpExpression(antecedent, consequent)
232
+ else:
233
+ # nothing has property 'p'
234
+ accum = NegatedExpression(self._make_antecedent(p, new_sig))
235
+
236
+ # quantify the implication
237
+ for new_sig_var in new_sig[::-1]:
238
+ accum = AllExpression(new_sig_var, accum)
239
+ new_assumptions.append(accum)
240
+
241
+ return assumptions + new_assumptions
242
+
243
+ def _make_unique_signature(self, predHolder):
244
+ """
245
+ This method figures out how many arguments the predicate takes and
246
+ returns a tuple containing that number of unique variables.
247
+ """
248
+ return tuple(unique_variable() for i in range(predHolder.signature_len))
249
+
250
+ def _make_antecedent(self, predicate, signature):
251
+ """
252
+ Return an application expression with 'predicate' as the predicate
253
+ and 'signature' as the list of arguments.
254
+ """
255
+ antecedent = predicate
256
+ for v in signature:
257
+ antecedent = antecedent(VariableExpression(v))
258
+ return antecedent
259
+
260
+ def _make_predicate_dict(self, assumptions):
261
+ """
262
+ Create a dictionary of predicates from the assumptions.
263
+
264
+ :param assumptions: a list of ``Expression``s
265
+ :return: dict mapping ``AbstractVariableExpression`` to ``PredHolder``
266
+ """
267
+ predicates = defaultdict(PredHolder)
268
+ for a in assumptions:
269
+ self._map_predicates(a, predicates)
270
+ return predicates
271
+
272
+ def _map_predicates(self, expression, predDict):
273
+ if isinstance(expression, ApplicationExpression):
274
+ func, args = expression.uncurry()
275
+ if isinstance(func, AbstractVariableExpression):
276
+ predDict[func].append_sig(tuple(args))
277
+ elif isinstance(expression, AndExpression):
278
+ self._map_predicates(expression.first, predDict)
279
+ self._map_predicates(expression.second, predDict)
280
+ elif isinstance(expression, AllExpression):
281
+ # collect all the universally quantified variables
282
+ sig = [expression.variable]
283
+ term = expression.term
284
+ while isinstance(term, AllExpression):
285
+ sig.append(term.variable)
286
+ term = term.term
287
+ if isinstance(term, ImpExpression):
288
+ if isinstance(term.first, ApplicationExpression) and isinstance(
289
+ term.second, ApplicationExpression
290
+ ):
291
+ func1, args1 = term.first.uncurry()
292
+ func2, args2 = term.second.uncurry()
293
+ if (
294
+ isinstance(func1, AbstractVariableExpression)
295
+ and isinstance(func2, AbstractVariableExpression)
296
+ and sig == [v.variable for v in args1]
297
+ and sig == [v.variable for v in args2]
298
+ ):
299
+ predDict[func2].append_prop((tuple(sig), term.first))
300
+ predDict[func1].validate_sig_len(sig)
301
+
302
+
303
+ class PredHolder:
304
+ """
305
+ This class will be used by a dictionary that will store information
306
+ about predicates to be used by the ``ClosedWorldProver``.
307
+
308
+ The 'signatures' property is a list of tuples defining signatures for
309
+ which the predicate is true. For instance, 'see(john, mary)' would be
310
+ result in the signature '(john,mary)' for 'see'.
311
+
312
+ The second element of the pair is a list of pairs such that the first
313
+ element of the pair is a tuple of variables and the second element is an
314
+ expression of those variables that makes the predicate true. For instance,
315
+ 'all x.all y.(see(x,y) -> know(x,y))' would result in "((x,y),('see(x,y)'))"
316
+ for 'know'.
317
+ """
318
+
319
+ def __init__(self):
320
+ self.signatures = []
321
+ self.properties = []
322
+ self.signature_len = None
323
+
324
+ def append_sig(self, new_sig):
325
+ self.validate_sig_len(new_sig)
326
+ self.signatures.append(new_sig)
327
+
328
+ def append_prop(self, new_prop):
329
+ self.validate_sig_len(new_prop[0])
330
+ self.properties.append(new_prop)
331
+
332
+ def validate_sig_len(self, new_sig):
333
+ if self.signature_len is None:
334
+ self.signature_len = len(new_sig)
335
+ elif self.signature_len != len(new_sig):
336
+ raise Exception("Signature lengths do not match")
337
+
338
+ def __str__(self):
339
+ return f"({self.signatures},{self.properties},{self.signature_len})"
340
+
341
+ def __repr__(self):
342
+ return "%s" % self
343
+
344
+
345
+ def closed_domain_demo():
346
+ lexpr = Expression.fromstring
347
+
348
+ p1 = lexpr(r"exists x.walk(x)")
349
+ p2 = lexpr(r"man(Socrates)")
350
+ c = lexpr(r"walk(Socrates)")
351
+ prover = Prover9Command(c, [p1, p2])
352
+ print(prover.prove())
353
+ cdp = ClosedDomainProver(prover)
354
+ print("assumptions:")
355
+ for a in cdp.assumptions():
356
+ print(" ", a)
357
+ print("goal:", cdp.goal())
358
+ print(cdp.prove())
359
+
360
+ p1 = lexpr(r"exists x.walk(x)")
361
+ p2 = lexpr(r"man(Socrates)")
362
+ p3 = lexpr(r"-walk(Bill)")
363
+ c = lexpr(r"walk(Socrates)")
364
+ prover = Prover9Command(c, [p1, p2, p3])
365
+ print(prover.prove())
366
+ cdp = ClosedDomainProver(prover)
367
+ print("assumptions:")
368
+ for a in cdp.assumptions():
369
+ print(" ", a)
370
+ print("goal:", cdp.goal())
371
+ print(cdp.prove())
372
+
373
+ p1 = lexpr(r"exists x.walk(x)")
374
+ p2 = lexpr(r"man(Socrates)")
375
+ p3 = lexpr(r"-walk(Bill)")
376
+ c = lexpr(r"walk(Socrates)")
377
+ prover = Prover9Command(c, [p1, p2, p3])
378
+ print(prover.prove())
379
+ cdp = ClosedDomainProver(prover)
380
+ print("assumptions:")
381
+ for a in cdp.assumptions():
382
+ print(" ", a)
383
+ print("goal:", cdp.goal())
384
+ print(cdp.prove())
385
+
386
+ p1 = lexpr(r"walk(Socrates)")
387
+ p2 = lexpr(r"walk(Bill)")
388
+ c = lexpr(r"all x.walk(x)")
389
+ prover = Prover9Command(c, [p1, p2])
390
+ print(prover.prove())
391
+ cdp = ClosedDomainProver(prover)
392
+ print("assumptions:")
393
+ for a in cdp.assumptions():
394
+ print(" ", a)
395
+ print("goal:", cdp.goal())
396
+ print(cdp.prove())
397
+
398
+ p1 = lexpr(r"girl(mary)")
399
+ p2 = lexpr(r"dog(rover)")
400
+ p3 = lexpr(r"all x.(girl(x) -> -dog(x))")
401
+ p4 = lexpr(r"all x.(dog(x) -> -girl(x))")
402
+ p5 = lexpr(r"chase(mary, rover)")
403
+ c = lexpr(r"exists y.(dog(y) & all x.(girl(x) -> chase(x,y)))")
404
+ prover = Prover9Command(c, [p1, p2, p3, p4, p5])
405
+ print(prover.prove())
406
+ cdp = ClosedDomainProver(prover)
407
+ print("assumptions:")
408
+ for a in cdp.assumptions():
409
+ print(" ", a)
410
+ print("goal:", cdp.goal())
411
+ print(cdp.prove())
412
+
413
+
414
+ def unique_names_demo():
415
+ lexpr = Expression.fromstring
416
+
417
+ p1 = lexpr(r"man(Socrates)")
418
+ p2 = lexpr(r"man(Bill)")
419
+ c = lexpr(r"exists x.exists y.(x != y)")
420
+ prover = Prover9Command(c, [p1, p2])
421
+ print(prover.prove())
422
+ unp = UniqueNamesProver(prover)
423
+ print("assumptions:")
424
+ for a in unp.assumptions():
425
+ print(" ", a)
426
+ print("goal:", unp.goal())
427
+ print(unp.prove())
428
+
429
+ p1 = lexpr(r"all x.(walk(x) -> (x = Socrates))")
430
+ p2 = lexpr(r"Bill = William")
431
+ p3 = lexpr(r"Bill = Billy")
432
+ c = lexpr(r"-walk(William)")
433
+ prover = Prover9Command(c, [p1, p2, p3])
434
+ print(prover.prove())
435
+ unp = UniqueNamesProver(prover)
436
+ print("assumptions:")
437
+ for a in unp.assumptions():
438
+ print(" ", a)
439
+ print("goal:", unp.goal())
440
+ print(unp.prove())
441
+
442
+
443
+ def closed_world_demo():
444
+ lexpr = Expression.fromstring
445
+
446
+ p1 = lexpr(r"walk(Socrates)")
447
+ p2 = lexpr(r"(Socrates != Bill)")
448
+ c = lexpr(r"-walk(Bill)")
449
+ prover = Prover9Command(c, [p1, p2])
450
+ print(prover.prove())
451
+ cwp = ClosedWorldProver(prover)
452
+ print("assumptions:")
453
+ for a in cwp.assumptions():
454
+ print(" ", a)
455
+ print("goal:", cwp.goal())
456
+ print(cwp.prove())
457
+
458
+ p1 = lexpr(r"see(Socrates, John)")
459
+ p2 = lexpr(r"see(John, Mary)")
460
+ p3 = lexpr(r"(Socrates != John)")
461
+ p4 = lexpr(r"(John != Mary)")
462
+ c = lexpr(r"-see(Socrates, Mary)")
463
+ prover = Prover9Command(c, [p1, p2, p3, p4])
464
+ print(prover.prove())
465
+ cwp = ClosedWorldProver(prover)
466
+ print("assumptions:")
467
+ for a in cwp.assumptions():
468
+ print(" ", a)
469
+ print("goal:", cwp.goal())
470
+ print(cwp.prove())
471
+
472
+ p1 = lexpr(r"all x.(ostrich(x) -> bird(x))")
473
+ p2 = lexpr(r"bird(Tweety)")
474
+ p3 = lexpr(r"-ostrich(Sam)")
475
+ p4 = lexpr(r"Sam != Tweety")
476
+ c = lexpr(r"-bird(Sam)")
477
+ prover = Prover9Command(c, [p1, p2, p3, p4])
478
+ print(prover.prove())
479
+ cwp = ClosedWorldProver(prover)
480
+ print("assumptions:")
481
+ for a in cwp.assumptions():
482
+ print(" ", a)
483
+ print("goal:", cwp.goal())
484
+ print(cwp.prove())
485
+
486
+
487
+ def combination_prover_demo():
488
+ lexpr = Expression.fromstring
489
+
490
+ p1 = lexpr(r"see(Socrates, John)")
491
+ p2 = lexpr(r"see(John, Mary)")
492
+ c = lexpr(r"-see(Socrates, Mary)")
493
+ prover = Prover9Command(c, [p1, p2])
494
+ print(prover.prove())
495
+ command = ClosedDomainProver(UniqueNamesProver(ClosedWorldProver(prover)))
496
+ for a in command.assumptions():
497
+ print(a)
498
+ print(command.prove())
499
+
500
+
501
+ def default_reasoning_demo():
502
+ lexpr = Expression.fromstring
503
+
504
+ premises = []
505
+
506
+ # define taxonomy
507
+ premises.append(lexpr(r"all x.(elephant(x) -> animal(x))"))
508
+ premises.append(lexpr(r"all x.(bird(x) -> animal(x))"))
509
+ premises.append(lexpr(r"all x.(dove(x) -> bird(x))"))
510
+ premises.append(lexpr(r"all x.(ostrich(x) -> bird(x))"))
511
+ premises.append(lexpr(r"all x.(flying_ostrich(x) -> ostrich(x))"))
512
+
513
+ # default properties
514
+ premises.append(
515
+ lexpr(r"all x.((animal(x) & -Ab1(x)) -> -fly(x))")
516
+ ) # normal animals don't fly
517
+ premises.append(
518
+ lexpr(r"all x.((bird(x) & -Ab2(x)) -> fly(x))")
519
+ ) # normal birds fly
520
+ premises.append(
521
+ lexpr(r"all x.((ostrich(x) & -Ab3(x)) -> -fly(x))")
522
+ ) # normal ostriches don't fly
523
+
524
+ # specify abnormal entities
525
+ premises.append(lexpr(r"all x.(bird(x) -> Ab1(x))")) # flight
526
+ premises.append(lexpr(r"all x.(ostrich(x) -> Ab2(x))")) # non-flying bird
527
+ premises.append(lexpr(r"all x.(flying_ostrich(x) -> Ab3(x))")) # flying ostrich
528
+
529
+ # define entities
530
+ premises.append(lexpr(r"elephant(E)"))
531
+ premises.append(lexpr(r"dove(D)"))
532
+ premises.append(lexpr(r"ostrich(O)"))
533
+
534
+ # print the assumptions
535
+ prover = Prover9Command(None, premises)
536
+ command = UniqueNamesProver(ClosedWorldProver(prover))
537
+ for a in command.assumptions():
538
+ print(a)
539
+
540
+ print_proof("-fly(E)", premises)
541
+ print_proof("fly(D)", premises)
542
+ print_proof("-fly(O)", premises)
543
+
544
+
545
+ def print_proof(goal, premises):
546
+ lexpr = Expression.fromstring
547
+ prover = Prover9Command(lexpr(goal), premises)
548
+ command = UniqueNamesProver(ClosedWorldProver(prover))
549
+ print(goal, prover.prove(), command.prove())
550
+
551
+
552
+ def demo():
553
+ closed_domain_demo()
554
+ unique_names_demo()
555
+ closed_world_demo()
556
+ combination_prover_demo()
557
+ default_reasoning_demo()
558
+
559
+
560
+ if __name__ == "__main__":
561
+ demo()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/prover9.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Interface to the Prover9 Theorem Prover
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Dan Garrette <dhgarrette@gmail.com>
5
+ # Ewan Klein <ewan@inf.ed.ac.uk>
6
+ #
7
+ # URL: <https://www.nltk.org/>
8
+ # For license information, see LICENSE.TXT
9
+ """
10
+ A theorem prover that makes use of the external 'Prover9' package.
11
+ """
12
+
13
+ import os
14
+ import subprocess
15
+
16
+ import nltk
17
+ from nltk.inference.api import BaseProverCommand, Prover
18
+ from nltk.sem.logic import (
19
+ AllExpression,
20
+ AndExpression,
21
+ EqualityExpression,
22
+ ExistsExpression,
23
+ Expression,
24
+ IffExpression,
25
+ ImpExpression,
26
+ NegatedExpression,
27
+ OrExpression,
28
+ )
29
+
30
+ #
31
+ # Following is not yet used. Return code for 2 actually realized as 512.
32
+ #
33
+ p9_return_codes = {
34
+ 0: True,
35
+ 1: "(FATAL)", # A fatal error occurred (user's syntax error).
36
+ 2: False, # (SOS_EMPTY) Prover9 ran out of things to do
37
+ # (sos list exhausted).
38
+ 3: "(MAX_MEGS)", # The max_megs (memory limit) parameter was exceeded.
39
+ 4: "(MAX_SECONDS)", # The max_seconds parameter was exceeded.
40
+ 5: "(MAX_GIVEN)", # The max_given parameter was exceeded.
41
+ 6: "(MAX_KEPT)", # The max_kept parameter was exceeded.
42
+ 7: "(ACTION)", # A Prover9 action terminated the search.
43
+ 101: "(SIGSEGV)", # Prover9 crashed, most probably due to a bug.
44
+ }
45
+
46
+
47
+ class Prover9CommandParent:
48
+ """
49
+ A common base class used by both ``Prover9Command`` and ``MaceCommand``,
50
+ which is responsible for maintaining a goal and a set of assumptions,
51
+ and generating prover9-style input files from them.
52
+ """
53
+
54
+ def print_assumptions(self, output_format="nltk"):
55
+ """
56
+ Print the list of the current assumptions.
57
+ """
58
+ if output_format.lower() == "nltk":
59
+ for a in self.assumptions():
60
+ print(a)
61
+ elif output_format.lower() == "prover9":
62
+ for a in convert_to_prover9(self.assumptions()):
63
+ print(a)
64
+ else:
65
+ raise NameError(
66
+ "Unrecognized value for 'output_format': %s" % output_format
67
+ )
68
+
69
+
70
+ class Prover9Command(Prover9CommandParent, BaseProverCommand):
71
+ """
72
+ A ``ProverCommand`` specific to the ``Prover9`` prover. It contains
73
+ the a print_assumptions() method that is used to print the list
74
+ of assumptions in multiple formats.
75
+ """
76
+
77
+ def __init__(self, goal=None, assumptions=None, timeout=60, prover=None):
78
+ """
79
+ :param goal: Input expression to prove
80
+ :type goal: sem.Expression
81
+ :param assumptions: Input expressions to use as assumptions in
82
+ the proof.
83
+ :type assumptions: list(sem.Expression)
84
+ :param timeout: number of seconds before timeout; set to 0 for
85
+ no timeout.
86
+ :type timeout: int
87
+ :param prover: a prover. If not set, one will be created.
88
+ :type prover: Prover9
89
+ """
90
+ if not assumptions:
91
+ assumptions = []
92
+
93
+ if prover is not None:
94
+ assert isinstance(prover, Prover9)
95
+ else:
96
+ prover = Prover9(timeout)
97
+
98
+ BaseProverCommand.__init__(self, prover, goal, assumptions)
99
+
100
+ def decorate_proof(self, proof_string, simplify=True):
101
+ """
102
+ :see BaseProverCommand.decorate_proof()
103
+ """
104
+ if simplify:
105
+ return self._prover._call_prooftrans(proof_string, ["striplabels"])[
106
+ 0
107
+ ].rstrip()
108
+ else:
109
+ return proof_string.rstrip()
110
+
111
+
112
+ class Prover9Parent:
113
+ """
114
+ A common class extended by both ``Prover9`` and ``Mace <mace.Mace>``.
115
+ It contains the functionality required to convert NLTK-style
116
+ expressions into Prover9-style expressions.
117
+ """
118
+
119
+ _binary_location = None
120
+
121
+ def config_prover9(self, binary_location, verbose=False):
122
+ if binary_location is None:
123
+ self._binary_location = None
124
+ self._prover9_bin = None
125
+ else:
126
+ name = "prover9"
127
+ self._prover9_bin = nltk.internals.find_binary(
128
+ name,
129
+ path_to_bin=binary_location,
130
+ env_vars=["PROVER9"],
131
+ url="https://www.cs.unm.edu/~mccune/prover9/",
132
+ binary_names=[name, name + ".exe"],
133
+ verbose=verbose,
134
+ )
135
+ self._binary_location = self._prover9_bin.rsplit(os.path.sep, 1)
136
+
137
+ def prover9_input(self, goal, assumptions):
138
+ """
139
+ :return: The input string that should be provided to the
140
+ prover9 binary. This string is formed based on the goal,
141
+ assumptions, and timeout value of this object.
142
+ """
143
+ s = ""
144
+
145
+ if assumptions:
146
+ s += "formulas(assumptions).\n"
147
+ for p9_assumption in convert_to_prover9(assumptions):
148
+ s += " %s.\n" % p9_assumption
149
+ s += "end_of_list.\n\n"
150
+
151
+ if goal:
152
+ s += "formulas(goals).\n"
153
+ s += " %s.\n" % convert_to_prover9(goal)
154
+ s += "end_of_list.\n\n"
155
+
156
+ return s
157
+
158
+ def binary_locations(self):
159
+ """
160
+ A list of directories that should be searched for the prover9
161
+ executables. This list is used by ``config_prover9`` when searching
162
+ for the prover9 executables.
163
+ """
164
+ return [
165
+ "/usr/local/bin/prover9",
166
+ "/usr/local/bin/prover9/bin",
167
+ "/usr/local/bin",
168
+ "/usr/bin",
169
+ "/usr/local/prover9",
170
+ "/usr/local/share/prover9",
171
+ ]
172
+
173
+ def _find_binary(self, name, verbose=False):
174
+ binary_locations = self.binary_locations()
175
+ if self._binary_location is not None:
176
+ binary_locations += [self._binary_location]
177
+ return nltk.internals.find_binary(
178
+ name,
179
+ searchpath=binary_locations,
180
+ env_vars=["PROVER9"],
181
+ url="https://www.cs.unm.edu/~mccune/prover9/",
182
+ binary_names=[name, name + ".exe"],
183
+ verbose=verbose,
184
+ )
185
+
186
+ def _call(self, input_str, binary, args=[], verbose=False):
187
+ """
188
+ Call the binary with the given input.
189
+
190
+ :param input_str: A string whose contents are used as stdin.
191
+ :param binary: The location of the binary to call
192
+ :param args: A list of command-line arguments.
193
+ :return: A tuple (stdout, returncode)
194
+ :see: ``config_prover9``
195
+ """
196
+ if verbose:
197
+ print("Calling:", binary)
198
+ print("Args:", args)
199
+ print("Input:\n", input_str, "\n")
200
+
201
+ # Call prover9 via a subprocess
202
+ cmd = [binary] + args
203
+ try:
204
+ input_str = input_str.encode("utf8")
205
+ except AttributeError:
206
+ pass
207
+ p = subprocess.Popen(
208
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE
209
+ )
210
+ (stdout, stderr) = p.communicate(input=input_str)
211
+
212
+ if verbose:
213
+ print("Return code:", p.returncode)
214
+ if stdout:
215
+ print("stdout:\n", stdout, "\n")
216
+ if stderr:
217
+ print("stderr:\n", stderr, "\n")
218
+
219
+ return (stdout.decode("utf-8"), p.returncode)
220
+
221
+
222
+ def convert_to_prover9(input):
223
+ """
224
+ Convert a ``logic.Expression`` to Prover9 format.
225
+ """
226
+ if isinstance(input, list):
227
+ result = []
228
+ for s in input:
229
+ try:
230
+ result.append(_convert_to_prover9(s.simplify()))
231
+ except:
232
+ print("input %s cannot be converted to Prover9 input syntax" % input)
233
+ raise
234
+ return result
235
+ else:
236
+ try:
237
+ return _convert_to_prover9(input.simplify())
238
+ except:
239
+ print("input %s cannot be converted to Prover9 input syntax" % input)
240
+ raise
241
+
242
+
243
+ def _convert_to_prover9(expression):
244
+ """
245
+ Convert ``logic.Expression`` to Prover9 formatted string.
246
+ """
247
+ if isinstance(expression, ExistsExpression):
248
+ return (
249
+ "exists "
250
+ + str(expression.variable)
251
+ + " "
252
+ + _convert_to_prover9(expression.term)
253
+ )
254
+ elif isinstance(expression, AllExpression):
255
+ return (
256
+ "all "
257
+ + str(expression.variable)
258
+ + " "
259
+ + _convert_to_prover9(expression.term)
260
+ )
261
+ elif isinstance(expression, NegatedExpression):
262
+ return "-(" + _convert_to_prover9(expression.term) + ")"
263
+ elif isinstance(expression, AndExpression):
264
+ return (
265
+ "("
266
+ + _convert_to_prover9(expression.first)
267
+ + " & "
268
+ + _convert_to_prover9(expression.second)
269
+ + ")"
270
+ )
271
+ elif isinstance(expression, OrExpression):
272
+ return (
273
+ "("
274
+ + _convert_to_prover9(expression.first)
275
+ + " | "
276
+ + _convert_to_prover9(expression.second)
277
+ + ")"
278
+ )
279
+ elif isinstance(expression, ImpExpression):
280
+ return (
281
+ "("
282
+ + _convert_to_prover9(expression.first)
283
+ + " -> "
284
+ + _convert_to_prover9(expression.second)
285
+ + ")"
286
+ )
287
+ elif isinstance(expression, IffExpression):
288
+ return (
289
+ "("
290
+ + _convert_to_prover9(expression.first)
291
+ + " <-> "
292
+ + _convert_to_prover9(expression.second)
293
+ + ")"
294
+ )
295
+ elif isinstance(expression, EqualityExpression):
296
+ return (
297
+ "("
298
+ + _convert_to_prover9(expression.first)
299
+ + " = "
300
+ + _convert_to_prover9(expression.second)
301
+ + ")"
302
+ )
303
+ else:
304
+ return str(expression)
305
+
306
+
307
+ class Prover9(Prover9Parent, Prover):
308
+ _prover9_bin = None
309
+ _prooftrans_bin = None
310
+
311
+ def __init__(self, timeout=60):
312
+ self._timeout = timeout
313
+ """The timeout value for prover9. If a proof can not be found
314
+ in this amount of time, then prover9 will return false.
315
+ (Use 0 for no timeout.)"""
316
+
317
+ def _prove(self, goal=None, assumptions=None, verbose=False):
318
+ """
319
+ Use Prover9 to prove a theorem.
320
+ :return: A pair whose first element is a boolean indicating if the
321
+ proof was successful (i.e. returns value of 0) and whose second element
322
+ is the output of the prover.
323
+ """
324
+ if not assumptions:
325
+ assumptions = []
326
+
327
+ stdout, returncode = self._call_prover9(
328
+ self.prover9_input(goal, assumptions), verbose=verbose
329
+ )
330
+ return (returncode == 0, stdout)
331
+
332
+ def prover9_input(self, goal, assumptions):
333
+ """
334
+ :see: Prover9Parent.prover9_input
335
+ """
336
+ s = "clear(auto_denials).\n" # only one proof required
337
+ return s + Prover9Parent.prover9_input(self, goal, assumptions)
338
+
339
+ def _call_prover9(self, input_str, args=[], verbose=False):
340
+ """
341
+ Call the ``prover9`` binary with the given input.
342
+
343
+ :param input_str: A string whose contents are used as stdin.
344
+ :param args: A list of command-line arguments.
345
+ :return: A tuple (stdout, returncode)
346
+ :see: ``config_prover9``
347
+ """
348
+ if self._prover9_bin is None:
349
+ self._prover9_bin = self._find_binary("prover9", verbose)
350
+
351
+ updated_input_str = ""
352
+ if self._timeout > 0:
353
+ updated_input_str += "assign(max_seconds, %d).\n\n" % self._timeout
354
+ updated_input_str += input_str
355
+
356
+ stdout, returncode = self._call(
357
+ updated_input_str, self._prover9_bin, args, verbose
358
+ )
359
+
360
+ if returncode not in [0, 2]:
361
+ errormsgprefix = "%%ERROR:"
362
+ if errormsgprefix in stdout:
363
+ msgstart = stdout.index(errormsgprefix)
364
+ errormsg = stdout[msgstart:].strip()
365
+ else:
366
+ errormsg = None
367
+ if returncode in [3, 4, 5, 6]:
368
+ raise Prover9LimitExceededException(returncode, errormsg)
369
+ else:
370
+ raise Prover9FatalException(returncode, errormsg)
371
+
372
+ return stdout, returncode
373
+
374
+ def _call_prooftrans(self, input_str, args=[], verbose=False):
375
+ """
376
+ Call the ``prooftrans`` binary with the given input.
377
+
378
+ :param input_str: A string whose contents are used as stdin.
379
+ :param args: A list of command-line arguments.
380
+ :return: A tuple (stdout, returncode)
381
+ :see: ``config_prover9``
382
+ """
383
+ if self._prooftrans_bin is None:
384
+ self._prooftrans_bin = self._find_binary("prooftrans", verbose)
385
+
386
+ return self._call(input_str, self._prooftrans_bin, args, verbose)
387
+
388
+
389
+ class Prover9Exception(Exception):
390
+ def __init__(self, returncode, message):
391
+ msg = p9_return_codes[returncode]
392
+ if message:
393
+ msg += "\n%s" % message
394
+ Exception.__init__(self, msg)
395
+
396
+
397
+ class Prover9FatalException(Prover9Exception):
398
+ pass
399
+
400
+
401
+ class Prover9LimitExceededException(Prover9Exception):
402
+ pass
403
+
404
+
405
+ ######################################################################
406
+ # { Tests and Demos
407
+ ######################################################################
408
+
409
+
410
+ def test_config():
411
+
412
+ a = Expression.fromstring("(walk(j) & sing(j))")
413
+ g = Expression.fromstring("walk(j)")
414
+ p = Prover9Command(g, assumptions=[a])
415
+ p._executable_path = None
416
+ p.prover9_search = []
417
+ p.prove()
418
+ # config_prover9('/usr/local/bin')
419
+ print(p.prove())
420
+ print(p.proof())
421
+
422
+
423
+ def test_convert_to_prover9(expr):
424
+ """
425
+ Test that parsing works OK.
426
+ """
427
+ for t in expr:
428
+ e = Expression.fromstring(t)
429
+ print(convert_to_prover9(e))
430
+
431
+
432
+ def test_prove(arguments):
433
+ """
434
+ Try some proofs and exhibit the results.
435
+ """
436
+ for (goal, assumptions) in arguments:
437
+ g = Expression.fromstring(goal)
438
+ alist = [Expression.fromstring(a) for a in assumptions]
439
+ p = Prover9Command(g, assumptions=alist).prove()
440
+ for a in alist:
441
+ print(" %s" % a)
442
+ print(f"|- {g}: {p}\n")
443
+
444
+
445
+ arguments = [
446
+ ("(man(x) <-> (not (not man(x))))", []),
447
+ ("(not (man(x) & (not man(x))))", []),
448
+ ("(man(x) | (not man(x)))", []),
449
+ ("(man(x) & (not man(x)))", []),
450
+ ("(man(x) -> man(x))", []),
451
+ ("(not (man(x) & (not man(x))))", []),
452
+ ("(man(x) | (not man(x)))", []),
453
+ ("(man(x) -> man(x))", []),
454
+ ("(man(x) <-> man(x))", []),
455
+ ("(not (man(x) <-> (not man(x))))", []),
456
+ ("mortal(Socrates)", ["all x.(man(x) -> mortal(x))", "man(Socrates)"]),
457
+ ("((all x.(man(x) -> walks(x)) & man(Socrates)) -> some y.walks(y))", []),
458
+ ("(all x.man(x) -> all x.man(x))", []),
459
+ ("some x.all y.sees(x,y)", []),
460
+ (
461
+ "some e3.(walk(e3) & subj(e3, mary))",
462
+ [
463
+ "some e1.(see(e1) & subj(e1, john) & some e2.(pred(e1, e2) & walk(e2) & subj(e2, mary)))"
464
+ ],
465
+ ),
466
+ (
467
+ "some x e1.(see(e1) & subj(e1, x) & some e2.(pred(e1, e2) & walk(e2) & subj(e2, mary)))",
468
+ [
469
+ "some e1.(see(e1) & subj(e1, john) & some e2.(pred(e1, e2) & walk(e2) & subj(e2, mary)))"
470
+ ],
471
+ ),
472
+ ]
473
+
474
+ expressions = [
475
+ r"some x y.sees(x,y)",
476
+ r"some x.(man(x) & walks(x))",
477
+ r"\x.(man(x) & walks(x))",
478
+ r"\x y.sees(x,y)",
479
+ r"walks(john)",
480
+ r"\x.big(x, \y.mouse(y))",
481
+ r"(walks(x) & (runs(x) & (threes(x) & fours(x))))",
482
+ r"(walks(x) -> runs(x))",
483
+ r"some x.(PRO(x) & sees(John, x))",
484
+ r"some x.(man(x) & (not walks(x)))",
485
+ r"all x.(man(x) -> walks(x))",
486
+ ]
487
+
488
+
489
+ def spacer(num=45):
490
+ print("-" * num)
491
+
492
+
493
+ def demo():
494
+ print("Testing configuration")
495
+ spacer()
496
+ test_config()
497
+ print()
498
+ print("Testing conversion to Prover9 format")
499
+ spacer()
500
+ test_convert_to_prover9(expressions)
501
+ print()
502
+ print("Testing proofs")
503
+ spacer()
504
+ test_prove(arguments)
505
+
506
+
507
+ if __name__ == "__main__":
508
+ demo()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/resolution.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: First-order Resolution-based Theorem Prover
2
+ #
3
+ # Author: Dan Garrette <dhgarrette@gmail.com>
4
+ #
5
+ # Copyright (C) 2001-2023 NLTK Project
6
+ # URL: <https://www.nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+
9
+ """
10
+ Module for a resolution-based First Order theorem prover.
11
+ """
12
+
13
+ import operator
14
+ from collections import defaultdict
15
+ from functools import reduce
16
+
17
+ from nltk.inference.api import BaseProverCommand, Prover
18
+ from nltk.sem import skolemize
19
+ from nltk.sem.logic import (
20
+ AndExpression,
21
+ ApplicationExpression,
22
+ EqualityExpression,
23
+ Expression,
24
+ IndividualVariableExpression,
25
+ NegatedExpression,
26
+ OrExpression,
27
+ Variable,
28
+ VariableExpression,
29
+ is_indvar,
30
+ unique_variable,
31
+ )
32
+
33
+
34
+ class ProverParseError(Exception):
35
+ pass
36
+
37
+
38
+ class ResolutionProver(Prover):
39
+ ANSWER_KEY = "ANSWER"
40
+ _assume_false = True
41
+
42
+ def _prove(self, goal=None, assumptions=None, verbose=False):
43
+ """
44
+ :param goal: Input expression to prove
45
+ :type goal: sem.Expression
46
+ :param assumptions: Input expressions to use as assumptions in the proof
47
+ :type assumptions: list(sem.Expression)
48
+ """
49
+ if not assumptions:
50
+ assumptions = []
51
+
52
+ result = None
53
+ try:
54
+ clauses = []
55
+ if goal:
56
+ clauses.extend(clausify(-goal))
57
+ for a in assumptions:
58
+ clauses.extend(clausify(a))
59
+ result, clauses = self._attempt_proof(clauses)
60
+ if verbose:
61
+ print(ResolutionProverCommand._decorate_clauses(clauses))
62
+ except RuntimeError as e:
63
+ if self._assume_false and str(e).startswith(
64
+ "maximum recursion depth exceeded"
65
+ ):
66
+ result = False
67
+ clauses = []
68
+ else:
69
+ if verbose:
70
+ print(e)
71
+ else:
72
+ raise e
73
+ return (result, clauses)
74
+
75
+ def _attempt_proof(self, clauses):
76
+ # map indices to lists of indices, to store attempted unifications
77
+ tried = defaultdict(list)
78
+
79
+ i = 0
80
+ while i < len(clauses):
81
+ if not clauses[i].is_tautology():
82
+ # since we try clauses in order, we should start after the last
83
+ # index tried
84
+ if tried[i]:
85
+ j = tried[i][-1] + 1
86
+ else:
87
+ j = i + 1 # nothing tried yet for 'i', so start with the next
88
+
89
+ while j < len(clauses):
90
+ # don't: 1) unify a clause with itself,
91
+ # 2) use tautologies
92
+ if i != j and j and not clauses[j].is_tautology():
93
+ tried[i].append(j)
94
+ newclauses = clauses[i].unify(clauses[j])
95
+ if newclauses:
96
+ for newclause in newclauses:
97
+ newclause._parents = (i + 1, j + 1)
98
+ clauses.append(newclause)
99
+ if not len(newclause): # if there's an empty clause
100
+ return (True, clauses)
101
+ i = -1 # since we added a new clause, restart from the top
102
+ break
103
+ j += 1
104
+ i += 1
105
+ return (False, clauses)
106
+
107
+
108
+ class ResolutionProverCommand(BaseProverCommand):
109
+ def __init__(self, goal=None, assumptions=None, prover=None):
110
+ """
111
+ :param goal: Input expression to prove
112
+ :type goal: sem.Expression
113
+ :param assumptions: Input expressions to use as assumptions in
114
+ the proof.
115
+ :type assumptions: list(sem.Expression)
116
+ """
117
+ if prover is not None:
118
+ assert isinstance(prover, ResolutionProver)
119
+ else:
120
+ prover = ResolutionProver()
121
+
122
+ BaseProverCommand.__init__(self, prover, goal, assumptions)
123
+ self._clauses = None
124
+
125
+ def prove(self, verbose=False):
126
+ """
127
+ Perform the actual proof. Store the result to prevent unnecessary
128
+ re-proving.
129
+ """
130
+ if self._result is None:
131
+ self._result, clauses = self._prover._prove(
132
+ self.goal(), self.assumptions(), verbose
133
+ )
134
+ self._clauses = clauses
135
+ self._proof = ResolutionProverCommand._decorate_clauses(clauses)
136
+ return self._result
137
+
138
+ def find_answers(self, verbose=False):
139
+ self.prove(verbose)
140
+
141
+ answers = set()
142
+ answer_ex = VariableExpression(Variable(ResolutionProver.ANSWER_KEY))
143
+ for clause in self._clauses:
144
+ for term in clause:
145
+ if (
146
+ isinstance(term, ApplicationExpression)
147
+ and term.function == answer_ex
148
+ and not isinstance(term.argument, IndividualVariableExpression)
149
+ ):
150
+ answers.add(term.argument)
151
+ return answers
152
+
153
+ @staticmethod
154
+ def _decorate_clauses(clauses):
155
+ """
156
+ Decorate the proof output.
157
+ """
158
+ out = ""
159
+ max_clause_len = max(len(str(clause)) for clause in clauses)
160
+ max_seq_len = len(str(len(clauses)))
161
+ for i in range(len(clauses)):
162
+ parents = "A"
163
+ taut = ""
164
+ if clauses[i].is_tautology():
165
+ taut = "Tautology"
166
+ if clauses[i]._parents:
167
+ parents = str(clauses[i]._parents)
168
+ parents = " " * (max_clause_len - len(str(clauses[i])) + 1) + parents
169
+ seq = " " * (max_seq_len - len(str(i + 1))) + str(i + 1)
170
+ out += f"[{seq}] {clauses[i]} {parents} {taut}\n"
171
+ return out
172
+
173
+
174
+ class Clause(list):
175
+ def __init__(self, data):
176
+ list.__init__(self, data)
177
+ self._is_tautology = None
178
+ self._parents = None
179
+
180
+ def unify(self, other, bindings=None, used=None, skipped=None, debug=False):
181
+ """
182
+ Attempt to unify this Clause with the other, returning a list of
183
+ resulting, unified, Clauses.
184
+
185
+ :param other: ``Clause`` with which to unify
186
+ :param bindings: ``BindingDict`` containing bindings that should be used
187
+ during the unification
188
+ :param used: tuple of two lists of atoms. The first lists the
189
+ atoms from 'self' that were successfully unified with atoms from
190
+ 'other'. The second lists the atoms from 'other' that were successfully
191
+ unified with atoms from 'self'.
192
+ :param skipped: tuple of two ``Clause`` objects. The first is a list of all
193
+ the atoms from the 'self' Clause that have not been unified with
194
+ anything on the path. The second is same thing for the 'other' Clause.
195
+ :param debug: bool indicating whether debug statements should print
196
+ :return: list containing all the resulting ``Clause`` objects that could be
197
+ obtained by unification
198
+ """
199
+ if bindings is None:
200
+ bindings = BindingDict()
201
+ if used is None:
202
+ used = ([], [])
203
+ if skipped is None:
204
+ skipped = ([], [])
205
+ if isinstance(debug, bool):
206
+ debug = DebugObject(debug)
207
+
208
+ newclauses = _iterate_first(
209
+ self, other, bindings, used, skipped, _complete_unify_path, debug
210
+ )
211
+
212
+ # remove subsumed clauses. make a list of all indices of subsumed
213
+ # clauses, and then remove them from the list
214
+ subsumed = []
215
+ for i, c1 in enumerate(newclauses):
216
+ if i not in subsumed:
217
+ for j, c2 in enumerate(newclauses):
218
+ if i != j and j not in subsumed and c1.subsumes(c2):
219
+ subsumed.append(j)
220
+ result = []
221
+ for i in range(len(newclauses)):
222
+ if i not in subsumed:
223
+ result.append(newclauses[i])
224
+
225
+ return result
226
+
227
+ def isSubsetOf(self, other):
228
+ """
229
+ Return True iff every term in 'self' is a term in 'other'.
230
+
231
+ :param other: ``Clause``
232
+ :return: bool
233
+ """
234
+ for a in self:
235
+ if a not in other:
236
+ return False
237
+ return True
238
+
239
+ def subsumes(self, other):
240
+ """
241
+ Return True iff 'self' subsumes 'other', this is, if there is a
242
+ substitution such that every term in 'self' can be unified with a term
243
+ in 'other'.
244
+
245
+ :param other: ``Clause``
246
+ :return: bool
247
+ """
248
+ negatedother = []
249
+ for atom in other:
250
+ if isinstance(atom, NegatedExpression):
251
+ negatedother.append(atom.term)
252
+ else:
253
+ negatedother.append(-atom)
254
+
255
+ negatedotherClause = Clause(negatedother)
256
+
257
+ bindings = BindingDict()
258
+ used = ([], [])
259
+ skipped = ([], [])
260
+ debug = DebugObject(False)
261
+
262
+ return (
263
+ len(
264
+ _iterate_first(
265
+ self,
266
+ negatedotherClause,
267
+ bindings,
268
+ used,
269
+ skipped,
270
+ _subsumes_finalize,
271
+ debug,
272
+ )
273
+ )
274
+ > 0
275
+ )
276
+
277
+ def __getslice__(self, start, end):
278
+ return Clause(list.__getslice__(self, start, end))
279
+
280
+ def __sub__(self, other):
281
+ return Clause([a for a in self if a not in other])
282
+
283
+ def __add__(self, other):
284
+ return Clause(list.__add__(self, other))
285
+
286
+ def is_tautology(self):
287
+ """
288
+ Self is a tautology if it contains ground terms P and -P. The ground
289
+ term, P, must be an exact match, ie, not using unification.
290
+ """
291
+ if self._is_tautology is not None:
292
+ return self._is_tautology
293
+ for i, a in enumerate(self):
294
+ if not isinstance(a, EqualityExpression):
295
+ j = len(self) - 1
296
+ while j > i:
297
+ b = self[j]
298
+ if isinstance(a, NegatedExpression):
299
+ if a.term == b:
300
+ self._is_tautology = True
301
+ return True
302
+ elif isinstance(b, NegatedExpression):
303
+ if a == b.term:
304
+ self._is_tautology = True
305
+ return True
306
+ j -= 1
307
+ self._is_tautology = False
308
+ return False
309
+
310
+ def free(self):
311
+ return reduce(operator.or_, ((atom.free() | atom.constants()) for atom in self))
312
+
313
+ def replace(self, variable, expression):
314
+ """
315
+ Replace every instance of variable with expression across every atom
316
+ in the clause
317
+
318
+ :param variable: ``Variable``
319
+ :param expression: ``Expression``
320
+ """
321
+ return Clause([atom.replace(variable, expression) for atom in self])
322
+
323
+ def substitute_bindings(self, bindings):
324
+ """
325
+ Replace every binding
326
+
327
+ :param bindings: A list of tuples mapping Variable Expressions to the
328
+ Expressions to which they are bound.
329
+ :return: ``Clause``
330
+ """
331
+ return Clause([atom.substitute_bindings(bindings) for atom in self])
332
+
333
+ def __str__(self):
334
+ return "{" + ", ".join("%s" % item for item in self) + "}"
335
+
336
+ def __repr__(self):
337
+ return "%s" % self
338
+
339
+
340
+ def _iterate_first(first, second, bindings, used, skipped, finalize_method, debug):
341
+ """
342
+ This method facilitates movement through the terms of 'self'
343
+ """
344
+ debug.line(f"unify({first},{second}) {bindings}")
345
+
346
+ if not len(first) or not len(second): # if no more recursions can be performed
347
+ return finalize_method(first, second, bindings, used, skipped, debug)
348
+ else:
349
+ # explore this 'self' atom
350
+ result = _iterate_second(
351
+ first, second, bindings, used, skipped, finalize_method, debug + 1
352
+ )
353
+
354
+ # skip this possible 'self' atom
355
+ newskipped = (skipped[0] + [first[0]], skipped[1])
356
+ result += _iterate_first(
357
+ first[1:], second, bindings, used, newskipped, finalize_method, debug + 1
358
+ )
359
+
360
+ try:
361
+ newbindings, newused, unused = _unify_terms(
362
+ first[0], second[0], bindings, used
363
+ )
364
+ # Unification found, so progress with this line of unification
365
+ # put skipped and unused terms back into play for later unification.
366
+ newfirst = first[1:] + skipped[0] + unused[0]
367
+ newsecond = second[1:] + skipped[1] + unused[1]
368
+ result += _iterate_first(
369
+ newfirst,
370
+ newsecond,
371
+ newbindings,
372
+ newused,
373
+ ([], []),
374
+ finalize_method,
375
+ debug + 1,
376
+ )
377
+ except BindingException:
378
+ # the atoms could not be unified,
379
+ pass
380
+
381
+ return result
382
+
383
+
384
+ def _iterate_second(first, second, bindings, used, skipped, finalize_method, debug):
385
+ """
386
+ This method facilitates movement through the terms of 'other'
387
+ """
388
+ debug.line(f"unify({first},{second}) {bindings}")
389
+
390
+ if not len(first) or not len(second): # if no more recursions can be performed
391
+ return finalize_method(first, second, bindings, used, skipped, debug)
392
+ else:
393
+ # skip this possible pairing and move to the next
394
+ newskipped = (skipped[0], skipped[1] + [second[0]])
395
+ result = _iterate_second(
396
+ first, second[1:], bindings, used, newskipped, finalize_method, debug + 1
397
+ )
398
+
399
+ try:
400
+ newbindings, newused, unused = _unify_terms(
401
+ first[0], second[0], bindings, used
402
+ )
403
+ # Unification found, so progress with this line of unification
404
+ # put skipped and unused terms back into play for later unification.
405
+ newfirst = first[1:] + skipped[0] + unused[0]
406
+ newsecond = second[1:] + skipped[1] + unused[1]
407
+ result += _iterate_second(
408
+ newfirst,
409
+ newsecond,
410
+ newbindings,
411
+ newused,
412
+ ([], []),
413
+ finalize_method,
414
+ debug + 1,
415
+ )
416
+ except BindingException:
417
+ # the atoms could not be unified,
418
+ pass
419
+
420
+ return result
421
+
422
+
423
+ def _unify_terms(a, b, bindings=None, used=None):
424
+ """
425
+ This method attempts to unify two terms. Two expressions are unifiable
426
+ if there exists a substitution function S such that S(a) == S(-b).
427
+
428
+ :param a: ``Expression``
429
+ :param b: ``Expression``
430
+ :param bindings: ``BindingDict`` a starting set of bindings with which
431
+ the unification must be consistent
432
+ :return: ``BindingDict`` A dictionary of the bindings required to unify
433
+ :raise ``BindingException``: If the terms cannot be unified
434
+ """
435
+ assert isinstance(a, Expression)
436
+ assert isinstance(b, Expression)
437
+
438
+ if bindings is None:
439
+ bindings = BindingDict()
440
+ if used is None:
441
+ used = ([], [])
442
+
443
+ # Use resolution
444
+ if isinstance(a, NegatedExpression) and isinstance(b, ApplicationExpression):
445
+ newbindings = most_general_unification(a.term, b, bindings)
446
+ newused = (used[0] + [a], used[1] + [b])
447
+ unused = ([], [])
448
+ elif isinstance(a, ApplicationExpression) and isinstance(b, NegatedExpression):
449
+ newbindings = most_general_unification(a, b.term, bindings)
450
+ newused = (used[0] + [a], used[1] + [b])
451
+ unused = ([], [])
452
+
453
+ # Use demodulation
454
+ elif isinstance(a, EqualityExpression):
455
+ newbindings = BindingDict([(a.first.variable, a.second)])
456
+ newused = (used[0] + [a], used[1])
457
+ unused = ([], [b])
458
+ elif isinstance(b, EqualityExpression):
459
+ newbindings = BindingDict([(b.first.variable, b.second)])
460
+ newused = (used[0], used[1] + [b])
461
+ unused = ([a], [])
462
+
463
+ else:
464
+ raise BindingException((a, b))
465
+
466
+ return newbindings, newused, unused
467
+
468
+
469
+ def _complete_unify_path(first, second, bindings, used, skipped, debug):
470
+ if used[0] or used[1]: # if bindings were made along the path
471
+ newclause = Clause(skipped[0] + skipped[1] + first + second)
472
+ debug.line(" -> New Clause: %s" % newclause)
473
+ return [newclause.substitute_bindings(bindings)]
474
+ else: # no bindings made means no unification occurred. so no result
475
+ debug.line(" -> End")
476
+ return []
477
+
478
+
479
+ def _subsumes_finalize(first, second, bindings, used, skipped, debug):
480
+ if not len(skipped[0]) and not len(first):
481
+ # If there are no skipped terms and no terms left in 'first', then
482
+ # all of the terms in the original 'self' were unified with terms
483
+ # in 'other'. Therefore, there exists a binding (this one) such that
484
+ # every term in self can be unified with a term in other, which
485
+ # is the definition of subsumption.
486
+ return [True]
487
+ else:
488
+ return []
489
+
490
+
491
+ def clausify(expression):
492
+ """
493
+ Skolemize, clausify, and standardize the variables apart.
494
+ """
495
+ clause_list = []
496
+ for clause in _clausify(skolemize(expression)):
497
+ for free in clause.free():
498
+ if is_indvar(free.name):
499
+ newvar = VariableExpression(unique_variable())
500
+ clause = clause.replace(free, newvar)
501
+ clause_list.append(clause)
502
+ return clause_list
503
+
504
+
505
+ def _clausify(expression):
506
+ """
507
+ :param expression: a skolemized expression in CNF
508
+ """
509
+ if isinstance(expression, AndExpression):
510
+ return _clausify(expression.first) + _clausify(expression.second)
511
+ elif isinstance(expression, OrExpression):
512
+ first = _clausify(expression.first)
513
+ second = _clausify(expression.second)
514
+ assert len(first) == 1
515
+ assert len(second) == 1
516
+ return [first[0] + second[0]]
517
+ elif isinstance(expression, EqualityExpression):
518
+ return [Clause([expression])]
519
+ elif isinstance(expression, ApplicationExpression):
520
+ return [Clause([expression])]
521
+ elif isinstance(expression, NegatedExpression):
522
+ if isinstance(expression.term, ApplicationExpression):
523
+ return [Clause([expression])]
524
+ elif isinstance(expression.term, EqualityExpression):
525
+ return [Clause([expression])]
526
+ raise ProverParseError()
527
+
528
+
529
+ class BindingDict:
530
+ def __init__(self, binding_list=None):
531
+ """
532
+ :param binding_list: list of (``AbstractVariableExpression``, ``AtomicExpression``) to initialize the dictionary
533
+ """
534
+ self.d = {}
535
+
536
+ if binding_list:
537
+ for (v, b) in binding_list:
538
+ self[v] = b
539
+
540
+ def __setitem__(self, variable, binding):
541
+ """
542
+ A binding is consistent with the dict if its variable is not already bound, OR if its
543
+ variable is already bound to its argument.
544
+
545
+ :param variable: ``Variable`` The variable to bind
546
+ :param binding: ``Expression`` The atomic to which 'variable' should be bound
547
+ :raise BindingException: If the variable cannot be bound in this dictionary
548
+ """
549
+ assert isinstance(variable, Variable)
550
+ assert isinstance(binding, Expression)
551
+
552
+ try:
553
+ existing = self[variable]
554
+ except KeyError:
555
+ existing = None
556
+
557
+ if not existing or binding == existing:
558
+ self.d[variable] = binding
559
+ elif isinstance(binding, IndividualVariableExpression):
560
+ # Since variable is already bound, try to bind binding to variable
561
+ try:
562
+ existing = self[binding.variable]
563
+ except KeyError:
564
+ existing = None
565
+
566
+ binding2 = VariableExpression(variable)
567
+
568
+ if not existing or binding2 == existing:
569
+ self.d[binding.variable] = binding2
570
+ else:
571
+ raise BindingException(
572
+ "Variable %s already bound to another " "value" % (variable)
573
+ )
574
+ else:
575
+ raise BindingException(
576
+ "Variable %s already bound to another " "value" % (variable)
577
+ )
578
+
579
+ def __getitem__(self, variable):
580
+ """
581
+ Return the expression to which 'variable' is bound
582
+ """
583
+ assert isinstance(variable, Variable)
584
+
585
+ intermediate = self.d[variable]
586
+ while intermediate:
587
+ try:
588
+ intermediate = self.d[intermediate]
589
+ except KeyError:
590
+ return intermediate
591
+
592
+ def __contains__(self, item):
593
+ return item in self.d
594
+
595
+ def __add__(self, other):
596
+ """
597
+ :param other: ``BindingDict`` The dict with which to combine self
598
+ :return: ``BindingDict`` A new dict containing all the elements of both parameters
599
+ :raise BindingException: If the parameter dictionaries are not consistent with each other
600
+ """
601
+ try:
602
+ combined = BindingDict()
603
+ for v in self.d:
604
+ combined[v] = self.d[v]
605
+ for v in other.d:
606
+ combined[v] = other.d[v]
607
+ return combined
608
+ except BindingException as e:
609
+ raise BindingException(
610
+ "Attempting to add two contradicting "
611
+ "BindingDicts: '%s' and '%s'" % (self, other)
612
+ ) from e
613
+
614
+ def __len__(self):
615
+ return len(self.d)
616
+
617
+ def __str__(self):
618
+ data_str = ", ".join(f"{v}: {self.d[v]}" for v in sorted(self.d.keys()))
619
+ return "{" + data_str + "}"
620
+
621
+ def __repr__(self):
622
+ return "%s" % self
623
+
624
+
625
+ def most_general_unification(a, b, bindings=None):
626
+ """
627
+ Find the most general unification of the two given expressions
628
+
629
+ :param a: ``Expression``
630
+ :param b: ``Expression``
631
+ :param bindings: ``BindingDict`` a starting set of bindings with which the
632
+ unification must be consistent
633
+ :return: a list of bindings
634
+ :raise BindingException: if the Expressions cannot be unified
635
+ """
636
+ if bindings is None:
637
+ bindings = BindingDict()
638
+
639
+ if a == b:
640
+ return bindings
641
+ elif isinstance(a, IndividualVariableExpression):
642
+ return _mgu_var(a, b, bindings)
643
+ elif isinstance(b, IndividualVariableExpression):
644
+ return _mgu_var(b, a, bindings)
645
+ elif isinstance(a, ApplicationExpression) and isinstance(b, ApplicationExpression):
646
+ return most_general_unification(
647
+ a.function, b.function, bindings
648
+ ) + most_general_unification(a.argument, b.argument, bindings)
649
+ raise BindingException((a, b))
650
+
651
+
652
+ def _mgu_var(var, expression, bindings):
653
+ if var.variable in expression.free() | expression.constants():
654
+ raise BindingException((var, expression))
655
+ else:
656
+ return BindingDict([(var.variable, expression)]) + bindings
657
+
658
+
659
+ class BindingException(Exception):
660
+ def __init__(self, arg):
661
+ if isinstance(arg, tuple):
662
+ Exception.__init__(self, "'%s' cannot be bound to '%s'" % arg)
663
+ else:
664
+ Exception.__init__(self, arg)
665
+
666
+
667
+ class UnificationException(Exception):
668
+ def __init__(self, a, b):
669
+ Exception.__init__(self, f"'{a}' cannot unify with '{b}'")
670
+
671
+
672
+ class DebugObject:
673
+ def __init__(self, enabled=True, indent=0):
674
+ self.enabled = enabled
675
+ self.indent = indent
676
+
677
+ def __add__(self, i):
678
+ return DebugObject(self.enabled, self.indent + i)
679
+
680
+ def line(self, line):
681
+ if self.enabled:
682
+ print(" " * self.indent + line)
683
+
684
+
685
+ def testResolutionProver():
686
+ resolution_test(r"man(x)")
687
+ resolution_test(r"(man(x) -> man(x))")
688
+ resolution_test(r"(man(x) -> --man(x))")
689
+ resolution_test(r"-(man(x) and -man(x))")
690
+ resolution_test(r"(man(x) or -man(x))")
691
+ resolution_test(r"(man(x) -> man(x))")
692
+ resolution_test(r"-(man(x) and -man(x))")
693
+ resolution_test(r"(man(x) or -man(x))")
694
+ resolution_test(r"(man(x) -> man(x))")
695
+ resolution_test(r"(man(x) iff man(x))")
696
+ resolution_test(r"-(man(x) iff -man(x))")
697
+ resolution_test("all x.man(x)")
698
+ resolution_test("-all x.some y.F(x,y) & some x.all y.(-F(x,y))")
699
+ resolution_test("some x.all y.sees(x,y)")
700
+
701
+ p1 = Expression.fromstring(r"all x.(man(x) -> mortal(x))")
702
+ p2 = Expression.fromstring(r"man(Socrates)")
703
+ c = Expression.fromstring(r"mortal(Socrates)")
704
+ print(f"{p1}, {p2} |- {c}: {ResolutionProver().prove(c, [p1, p2])}")
705
+
706
+ p1 = Expression.fromstring(r"all x.(man(x) -> walks(x))")
707
+ p2 = Expression.fromstring(r"man(John)")
708
+ c = Expression.fromstring(r"some y.walks(y)")
709
+ print(f"{p1}, {p2} |- {c}: {ResolutionProver().prove(c, [p1, p2])}")
710
+
711
+ p = Expression.fromstring(r"some e1.some e2.(believe(e1,john,e2) & walk(e2,mary))")
712
+ c = Expression.fromstring(r"some e0.walk(e0,mary)")
713
+ print(f"{p} |- {c}: {ResolutionProver().prove(c, [p])}")
714
+
715
+
716
+ def resolution_test(e):
717
+ f = Expression.fromstring(e)
718
+ t = ResolutionProver().prove(f)
719
+ print(f"|- {f}: {t}")
720
+
721
+
722
+ def test_clausify():
723
+ lexpr = Expression.fromstring
724
+
725
+ print(clausify(lexpr("P(x) | Q(x)")))
726
+ print(clausify(lexpr("(P(x) & Q(x)) | R(x)")))
727
+ print(clausify(lexpr("P(x) | (Q(x) & R(x))")))
728
+ print(clausify(lexpr("(P(x) & Q(x)) | (R(x) & S(x))")))
729
+
730
+ print(clausify(lexpr("P(x) | Q(x) | R(x)")))
731
+ print(clausify(lexpr("P(x) | (Q(x) & R(x)) | S(x)")))
732
+
733
+ print(clausify(lexpr("exists x.P(x) | Q(x)")))
734
+
735
+ print(clausify(lexpr("-(-P(x) & Q(x))")))
736
+ print(clausify(lexpr("P(x) <-> Q(x)")))
737
+ print(clausify(lexpr("-(P(x) <-> Q(x))")))
738
+ print(clausify(lexpr("-(all x.P(x))")))
739
+ print(clausify(lexpr("-(some x.P(x))")))
740
+
741
+ print(clausify(lexpr("some x.P(x)")))
742
+ print(clausify(lexpr("some x.all y.P(x,y)")))
743
+ print(clausify(lexpr("all y.some x.P(x,y)")))
744
+ print(clausify(lexpr("all z.all y.some x.P(x,y,z)")))
745
+ print(clausify(lexpr("all x.(all y.P(x,y) -> -all y.(Q(x,y) -> R(x,y)))")))
746
+
747
+
748
+ def demo():
749
+ test_clausify()
750
+ print()
751
+ testResolutionProver()
752
+ print()
753
+
754
+ p = Expression.fromstring("man(x)")
755
+ print(ResolutionProverCommand(p, [p]).prove())
756
+
757
+
758
+ if __name__ == "__main__":
759
+ demo()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/inference/tableau.py ADDED
@@ -0,0 +1,712 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: First-Order Tableau Theorem Prover
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Dan Garrette <dhgarrette@gmail.com>
5
+ #
6
+ # URL: <https://www.nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+
9
+ """
10
+ Module for a tableau-based First Order theorem prover.
11
+ """
12
+
13
+ from nltk.inference.api import BaseProverCommand, Prover
14
+ from nltk.internals import Counter
15
+ from nltk.sem.logic import (
16
+ AbstractVariableExpression,
17
+ AllExpression,
18
+ AndExpression,
19
+ ApplicationExpression,
20
+ EqualityExpression,
21
+ ExistsExpression,
22
+ Expression,
23
+ FunctionVariableExpression,
24
+ IffExpression,
25
+ ImpExpression,
26
+ LambdaExpression,
27
+ NegatedExpression,
28
+ OrExpression,
29
+ Variable,
30
+ VariableExpression,
31
+ unique_variable,
32
+ )
33
+
34
+ _counter = Counter()
35
+
36
+
37
+ class ProverParseError(Exception):
38
+ pass
39
+
40
+
41
+ class TableauProver(Prover):
42
+ _assume_false = False
43
+
44
+ def _prove(self, goal=None, assumptions=None, verbose=False):
45
+ if not assumptions:
46
+ assumptions = []
47
+
48
+ result = None
49
+ try:
50
+ agenda = Agenda()
51
+ if goal:
52
+ agenda.put(-goal)
53
+ agenda.put_all(assumptions)
54
+ debugger = Debug(verbose)
55
+ result = self._attempt_proof(agenda, set(), set(), debugger)
56
+ except RuntimeError as e:
57
+ if self._assume_false and str(e).startswith(
58
+ "maximum recursion depth exceeded"
59
+ ):
60
+ result = False
61
+ else:
62
+ if verbose:
63
+ print(e)
64
+ else:
65
+ raise e
66
+ return (result, "\n".join(debugger.lines))
67
+
68
+ def _attempt_proof(self, agenda, accessible_vars, atoms, debug):
69
+ (current, context), category = agenda.pop_first()
70
+
71
+ # if there's nothing left in the agenda, and we haven't closed the path
72
+ if not current:
73
+ debug.line("AGENDA EMPTY")
74
+ return False
75
+
76
+ proof_method = {
77
+ Categories.ATOM: self._attempt_proof_atom,
78
+ Categories.PROP: self._attempt_proof_prop,
79
+ Categories.N_ATOM: self._attempt_proof_n_atom,
80
+ Categories.N_PROP: self._attempt_proof_n_prop,
81
+ Categories.APP: self._attempt_proof_app,
82
+ Categories.N_APP: self._attempt_proof_n_app,
83
+ Categories.N_EQ: self._attempt_proof_n_eq,
84
+ Categories.D_NEG: self._attempt_proof_d_neg,
85
+ Categories.N_ALL: self._attempt_proof_n_all,
86
+ Categories.N_EXISTS: self._attempt_proof_n_some,
87
+ Categories.AND: self._attempt_proof_and,
88
+ Categories.N_OR: self._attempt_proof_n_or,
89
+ Categories.N_IMP: self._attempt_proof_n_imp,
90
+ Categories.OR: self._attempt_proof_or,
91
+ Categories.IMP: self._attempt_proof_imp,
92
+ Categories.N_AND: self._attempt_proof_n_and,
93
+ Categories.IFF: self._attempt_proof_iff,
94
+ Categories.N_IFF: self._attempt_proof_n_iff,
95
+ Categories.EQ: self._attempt_proof_eq,
96
+ Categories.EXISTS: self._attempt_proof_some,
97
+ Categories.ALL: self._attempt_proof_all,
98
+ }[category]
99
+
100
+ debug.line((current, context))
101
+ return proof_method(current, context, agenda, accessible_vars, atoms, debug)
102
+
103
+ def _attempt_proof_atom(
104
+ self, current, context, agenda, accessible_vars, atoms, debug
105
+ ):
106
+ # Check if the branch is closed. Return 'True' if it is
107
+ if (current, True) in atoms:
108
+ debug.line("CLOSED", 1)
109
+ return True
110
+
111
+ if context:
112
+ if isinstance(context.term, NegatedExpression):
113
+ current = current.negate()
114
+ agenda.put(context(current).simplify())
115
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
116
+ else:
117
+ # mark all AllExpressions as 'not exhausted' into the agenda since we are (potentially) adding new accessible vars
118
+ agenda.mark_alls_fresh()
119
+ return self._attempt_proof(
120
+ agenda,
121
+ accessible_vars | set(current.args),
122
+ atoms | {(current, False)},
123
+ debug + 1,
124
+ )
125
+
126
+ def _attempt_proof_n_atom(
127
+ self, current, context, agenda, accessible_vars, atoms, debug
128
+ ):
129
+ # Check if the branch is closed. Return 'True' if it is
130
+ if (current.term, False) in atoms:
131
+ debug.line("CLOSED", 1)
132
+ return True
133
+
134
+ if context:
135
+ if isinstance(context.term, NegatedExpression):
136
+ current = current.negate()
137
+ agenda.put(context(current).simplify())
138
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
139
+ else:
140
+ # mark all AllExpressions as 'not exhausted' into the agenda since we are (potentially) adding new accessible vars
141
+ agenda.mark_alls_fresh()
142
+ return self._attempt_proof(
143
+ agenda,
144
+ accessible_vars | set(current.term.args),
145
+ atoms | {(current.term, True)},
146
+ debug + 1,
147
+ )
148
+
149
+ def _attempt_proof_prop(
150
+ self, current, context, agenda, accessible_vars, atoms, debug
151
+ ):
152
+ # Check if the branch is closed. Return 'True' if it is
153
+ if (current, True) in atoms:
154
+ debug.line("CLOSED", 1)
155
+ return True
156
+
157
+ # mark all AllExpressions as 'not exhausted' into the agenda since we are (potentially) adding new accessible vars
158
+ agenda.mark_alls_fresh()
159
+ return self._attempt_proof(
160
+ agenda, accessible_vars, atoms | {(current, False)}, debug + 1
161
+ )
162
+
163
+ def _attempt_proof_n_prop(
164
+ self, current, context, agenda, accessible_vars, atoms, debug
165
+ ):
166
+ # Check if the branch is closed. Return 'True' if it is
167
+ if (current.term, False) in atoms:
168
+ debug.line("CLOSED", 1)
169
+ return True
170
+
171
+ # mark all AllExpressions as 'not exhausted' into the agenda since we are (potentially) adding new accessible vars
172
+ agenda.mark_alls_fresh()
173
+ return self._attempt_proof(
174
+ agenda, accessible_vars, atoms | {(current.term, True)}, debug + 1
175
+ )
176
+
177
+ def _attempt_proof_app(
178
+ self, current, context, agenda, accessible_vars, atoms, debug
179
+ ):
180
+ f, args = current.uncurry()
181
+ for i, arg in enumerate(args):
182
+ if not TableauProver.is_atom(arg):
183
+ ctx = f
184
+ nv = Variable("X%s" % _counter.get())
185
+ for j, a in enumerate(args):
186
+ ctx = ctx(VariableExpression(nv)) if i == j else ctx(a)
187
+ if context:
188
+ ctx = context(ctx).simplify()
189
+ ctx = LambdaExpression(nv, ctx)
190
+ agenda.put(arg, ctx)
191
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
192
+ raise Exception("If this method is called, there must be a non-atomic argument")
193
+
194
+ def _attempt_proof_n_app(
195
+ self, current, context, agenda, accessible_vars, atoms, debug
196
+ ):
197
+ f, args = current.term.uncurry()
198
+ for i, arg in enumerate(args):
199
+ if not TableauProver.is_atom(arg):
200
+ ctx = f
201
+ nv = Variable("X%s" % _counter.get())
202
+ for j, a in enumerate(args):
203
+ ctx = ctx(VariableExpression(nv)) if i == j else ctx(a)
204
+ if context:
205
+ # combine new context with existing
206
+ ctx = context(ctx).simplify()
207
+ ctx = LambdaExpression(nv, -ctx)
208
+ agenda.put(-arg, ctx)
209
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
210
+ raise Exception("If this method is called, there must be a non-atomic argument")
211
+
212
+ def _attempt_proof_n_eq(
213
+ self, current, context, agenda, accessible_vars, atoms, debug
214
+ ):
215
+ ###########################################################################
216
+ # Since 'current' is of type '~(a=b)', the path is closed if 'a' == 'b'
217
+ ###########################################################################
218
+ if current.term.first == current.term.second:
219
+ debug.line("CLOSED", 1)
220
+ return True
221
+
222
+ agenda[Categories.N_EQ].add((current, context))
223
+ current._exhausted = True
224
+ return self._attempt_proof(
225
+ agenda,
226
+ accessible_vars | {current.term.first, current.term.second},
227
+ atoms,
228
+ debug + 1,
229
+ )
230
+
231
+ def _attempt_proof_d_neg(
232
+ self, current, context, agenda, accessible_vars, atoms, debug
233
+ ):
234
+ agenda.put(current.term.term, context)
235
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
236
+
237
+ def _attempt_proof_n_all(
238
+ self, current, context, agenda, accessible_vars, atoms, debug
239
+ ):
240
+ agenda[Categories.EXISTS].add(
241
+ (ExistsExpression(current.term.variable, -current.term.term), context)
242
+ )
243
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
244
+
245
+ def _attempt_proof_n_some(
246
+ self, current, context, agenda, accessible_vars, atoms, debug
247
+ ):
248
+ agenda[Categories.ALL].add(
249
+ (AllExpression(current.term.variable, -current.term.term), context)
250
+ )
251
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
252
+
253
+ def _attempt_proof_and(
254
+ self, current, context, agenda, accessible_vars, atoms, debug
255
+ ):
256
+ agenda.put(current.first, context)
257
+ agenda.put(current.second, context)
258
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
259
+
260
+ def _attempt_proof_n_or(
261
+ self, current, context, agenda, accessible_vars, atoms, debug
262
+ ):
263
+ agenda.put(-current.term.first, context)
264
+ agenda.put(-current.term.second, context)
265
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
266
+
267
+ def _attempt_proof_n_imp(
268
+ self, current, context, agenda, accessible_vars, atoms, debug
269
+ ):
270
+ agenda.put(current.term.first, context)
271
+ agenda.put(-current.term.second, context)
272
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
273
+
274
+ def _attempt_proof_or(
275
+ self, current, context, agenda, accessible_vars, atoms, debug
276
+ ):
277
+ new_agenda = agenda.clone()
278
+ agenda.put(current.first, context)
279
+ new_agenda.put(current.second, context)
280
+ return self._attempt_proof(
281
+ agenda, accessible_vars, atoms, debug + 1
282
+ ) and self._attempt_proof(new_agenda, accessible_vars, atoms, debug + 1)
283
+
284
+ def _attempt_proof_imp(
285
+ self, current, context, agenda, accessible_vars, atoms, debug
286
+ ):
287
+ new_agenda = agenda.clone()
288
+ agenda.put(-current.first, context)
289
+ new_agenda.put(current.second, context)
290
+ return self._attempt_proof(
291
+ agenda, accessible_vars, atoms, debug + 1
292
+ ) and self._attempt_proof(new_agenda, accessible_vars, atoms, debug + 1)
293
+
294
+ def _attempt_proof_n_and(
295
+ self, current, context, agenda, accessible_vars, atoms, debug
296
+ ):
297
+ new_agenda = agenda.clone()
298
+ agenda.put(-current.term.first, context)
299
+ new_agenda.put(-current.term.second, context)
300
+ return self._attempt_proof(
301
+ agenda, accessible_vars, atoms, debug + 1
302
+ ) and self._attempt_proof(new_agenda, accessible_vars, atoms, debug + 1)
303
+
304
+ def _attempt_proof_iff(
305
+ self, current, context, agenda, accessible_vars, atoms, debug
306
+ ):
307
+ new_agenda = agenda.clone()
308
+ agenda.put(current.first, context)
309
+ agenda.put(current.second, context)
310
+ new_agenda.put(-current.first, context)
311
+ new_agenda.put(-current.second, context)
312
+ return self._attempt_proof(
313
+ agenda, accessible_vars, atoms, debug + 1
314
+ ) and self._attempt_proof(new_agenda, accessible_vars, atoms, debug + 1)
315
+
316
+ def _attempt_proof_n_iff(
317
+ self, current, context, agenda, accessible_vars, atoms, debug
318
+ ):
319
+ new_agenda = agenda.clone()
320
+ agenda.put(current.term.first, context)
321
+ agenda.put(-current.term.second, context)
322
+ new_agenda.put(-current.term.first, context)
323
+ new_agenda.put(current.term.second, context)
324
+ return self._attempt_proof(
325
+ agenda, accessible_vars, atoms, debug + 1
326
+ ) and self._attempt_proof(new_agenda, accessible_vars, atoms, debug + 1)
327
+
328
+ def _attempt_proof_eq(
329
+ self, current, context, agenda, accessible_vars, atoms, debug
330
+ ):
331
+ #########################################################################
332
+ # Since 'current' is of the form '(a = b)', replace ALL free instances
333
+ # of 'a' with 'b'
334
+ #########################################################################
335
+ agenda.put_atoms(atoms)
336
+ agenda.replace_all(current.first, current.second)
337
+ accessible_vars.discard(current.first)
338
+ agenda.mark_neqs_fresh()
339
+ return self._attempt_proof(agenda, accessible_vars, set(), debug + 1)
340
+
341
+ def _attempt_proof_some(
342
+ self, current, context, agenda, accessible_vars, atoms, debug
343
+ ):
344
+ new_unique_variable = VariableExpression(unique_variable())
345
+ agenda.put(current.term.replace(current.variable, new_unique_variable), context)
346
+ agenda.mark_alls_fresh()
347
+ return self._attempt_proof(
348
+ agenda, accessible_vars | {new_unique_variable}, atoms, debug + 1
349
+ )
350
+
351
+ def _attempt_proof_all(
352
+ self, current, context, agenda, accessible_vars, atoms, debug
353
+ ):
354
+ try:
355
+ current._used_vars
356
+ except AttributeError:
357
+ current._used_vars = set()
358
+
359
+ # if there are accessible_vars on the path
360
+ if accessible_vars:
361
+ # get the set of bound variables that have not be used by this AllExpression
362
+ bv_available = accessible_vars - current._used_vars
363
+
364
+ if bv_available:
365
+ variable_to_use = list(bv_available)[0]
366
+ debug.line("--> Using '%s'" % variable_to_use, 2)
367
+ current._used_vars |= {variable_to_use}
368
+ agenda.put(
369
+ current.term.replace(current.variable, variable_to_use), context
370
+ )
371
+ agenda[Categories.ALL].add((current, context))
372
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
373
+
374
+ else:
375
+ # no more available variables to substitute
376
+ debug.line("--> Variables Exhausted", 2)
377
+ current._exhausted = True
378
+ agenda[Categories.ALL].add((current, context))
379
+ return self._attempt_proof(agenda, accessible_vars, atoms, debug + 1)
380
+
381
+ else:
382
+ new_unique_variable = VariableExpression(unique_variable())
383
+ debug.line("--> Using '%s'" % new_unique_variable, 2)
384
+ current._used_vars |= {new_unique_variable}
385
+ agenda.put(
386
+ current.term.replace(current.variable, new_unique_variable), context
387
+ )
388
+ agenda[Categories.ALL].add((current, context))
389
+ agenda.mark_alls_fresh()
390
+ return self._attempt_proof(
391
+ agenda, accessible_vars | {new_unique_variable}, atoms, debug + 1
392
+ )
393
+
394
+ @staticmethod
395
+ def is_atom(e):
396
+ if isinstance(e, NegatedExpression):
397
+ e = e.term
398
+
399
+ if isinstance(e, ApplicationExpression):
400
+ for arg in e.args:
401
+ if not TableauProver.is_atom(arg):
402
+ return False
403
+ return True
404
+ elif isinstance(e, AbstractVariableExpression) or isinstance(
405
+ e, LambdaExpression
406
+ ):
407
+ return True
408
+ else:
409
+ return False
410
+
411
+
412
+ class TableauProverCommand(BaseProverCommand):
413
+ def __init__(self, goal=None, assumptions=None, prover=None):
414
+ """
415
+ :param goal: Input expression to prove
416
+ :type goal: sem.Expression
417
+ :param assumptions: Input expressions to use as assumptions in
418
+ the proof.
419
+ :type assumptions: list(sem.Expression)
420
+ """
421
+ if prover is not None:
422
+ assert isinstance(prover, TableauProver)
423
+ else:
424
+ prover = TableauProver()
425
+
426
+ BaseProverCommand.__init__(self, prover, goal, assumptions)
427
+
428
+
429
+ class Agenda:
430
+ def __init__(self):
431
+ self.sets = tuple(set() for i in range(21))
432
+
433
+ def clone(self):
434
+ new_agenda = Agenda()
435
+ set_list = [s.copy() for s in self.sets]
436
+
437
+ new_allExs = set()
438
+ for allEx, _ in set_list[Categories.ALL]:
439
+ new_allEx = AllExpression(allEx.variable, allEx.term)
440
+ try:
441
+ new_allEx._used_vars = {used for used in allEx._used_vars}
442
+ except AttributeError:
443
+ new_allEx._used_vars = set()
444
+ new_allExs.add((new_allEx, None))
445
+ set_list[Categories.ALL] = new_allExs
446
+
447
+ set_list[Categories.N_EQ] = {
448
+ (NegatedExpression(n_eq.term), ctx)
449
+ for (n_eq, ctx) in set_list[Categories.N_EQ]
450
+ }
451
+
452
+ new_agenda.sets = tuple(set_list)
453
+ return new_agenda
454
+
455
+ def __getitem__(self, index):
456
+ return self.sets[index]
457
+
458
+ def put(self, expression, context=None):
459
+ if isinstance(expression, AllExpression):
460
+ ex_to_add = AllExpression(expression.variable, expression.term)
461
+ try:
462
+ ex_to_add._used_vars = {used for used in expression._used_vars}
463
+ except AttributeError:
464
+ ex_to_add._used_vars = set()
465
+ else:
466
+ ex_to_add = expression
467
+ self.sets[self._categorize_expression(ex_to_add)].add((ex_to_add, context))
468
+
469
+ def put_all(self, expressions):
470
+ for expression in expressions:
471
+ self.put(expression)
472
+
473
+ def put_atoms(self, atoms):
474
+ for atom, neg in atoms:
475
+ if neg:
476
+ self[Categories.N_ATOM].add((-atom, None))
477
+ else:
478
+ self[Categories.ATOM].add((atom, None))
479
+
480
+ def pop_first(self):
481
+ """Pop the first expression that appears in the agenda"""
482
+ for i, s in enumerate(self.sets):
483
+ if s:
484
+ if i in [Categories.N_EQ, Categories.ALL]:
485
+ for ex in s:
486
+ try:
487
+ if not ex[0]._exhausted:
488
+ s.remove(ex)
489
+ return (ex, i)
490
+ except AttributeError:
491
+ s.remove(ex)
492
+ return (ex, i)
493
+ else:
494
+ return (s.pop(), i)
495
+ return ((None, None), None)
496
+
497
+ def replace_all(self, old, new):
498
+ for s in self.sets:
499
+ for ex, ctx in s:
500
+ ex.replace(old.variable, new)
501
+ if ctx is not None:
502
+ ctx.replace(old.variable, new)
503
+
504
+ def mark_alls_fresh(self):
505
+ for u, _ in self.sets[Categories.ALL]:
506
+ u._exhausted = False
507
+
508
+ def mark_neqs_fresh(self):
509
+ for neq, _ in self.sets[Categories.N_EQ]:
510
+ neq._exhausted = False
511
+
512
+ def _categorize_expression(self, current):
513
+ if isinstance(current, NegatedExpression):
514
+ return self._categorize_NegatedExpression(current)
515
+ elif isinstance(current, FunctionVariableExpression):
516
+ return Categories.PROP
517
+ elif TableauProver.is_atom(current):
518
+ return Categories.ATOM
519
+ elif isinstance(current, AllExpression):
520
+ return Categories.ALL
521
+ elif isinstance(current, AndExpression):
522
+ return Categories.AND
523
+ elif isinstance(current, OrExpression):
524
+ return Categories.OR
525
+ elif isinstance(current, ImpExpression):
526
+ return Categories.IMP
527
+ elif isinstance(current, IffExpression):
528
+ return Categories.IFF
529
+ elif isinstance(current, EqualityExpression):
530
+ return Categories.EQ
531
+ elif isinstance(current, ExistsExpression):
532
+ return Categories.EXISTS
533
+ elif isinstance(current, ApplicationExpression):
534
+ return Categories.APP
535
+ else:
536
+ raise ProverParseError("cannot categorize %s" % current.__class__.__name__)
537
+
538
+ def _categorize_NegatedExpression(self, current):
539
+ negated = current.term
540
+
541
+ if isinstance(negated, NegatedExpression):
542
+ return Categories.D_NEG
543
+ elif isinstance(negated, FunctionVariableExpression):
544
+ return Categories.N_PROP
545
+ elif TableauProver.is_atom(negated):
546
+ return Categories.N_ATOM
547
+ elif isinstance(negated, AllExpression):
548
+ return Categories.N_ALL
549
+ elif isinstance(negated, AndExpression):
550
+ return Categories.N_AND
551
+ elif isinstance(negated, OrExpression):
552
+ return Categories.N_OR
553
+ elif isinstance(negated, ImpExpression):
554
+ return Categories.N_IMP
555
+ elif isinstance(negated, IffExpression):
556
+ return Categories.N_IFF
557
+ elif isinstance(negated, EqualityExpression):
558
+ return Categories.N_EQ
559
+ elif isinstance(negated, ExistsExpression):
560
+ return Categories.N_EXISTS
561
+ elif isinstance(negated, ApplicationExpression):
562
+ return Categories.N_APP
563
+ else:
564
+ raise ProverParseError("cannot categorize %s" % negated.__class__.__name__)
565
+
566
+
567
+ class Debug:
568
+ def __init__(self, verbose, indent=0, lines=None):
569
+ self.verbose = verbose
570
+ self.indent = indent
571
+
572
+ if not lines:
573
+ lines = []
574
+ self.lines = lines
575
+
576
+ def __add__(self, increment):
577
+ return Debug(self.verbose, self.indent + 1, self.lines)
578
+
579
+ def line(self, data, indent=0):
580
+ if isinstance(data, tuple):
581
+ ex, ctx = data
582
+ if ctx:
583
+ data = f"{ex}, {ctx}"
584
+ else:
585
+ data = "%s" % ex
586
+
587
+ if isinstance(ex, AllExpression):
588
+ try:
589
+ used_vars = "[%s]" % (
590
+ ",".join("%s" % ve.variable.name for ve in ex._used_vars)
591
+ )
592
+ data += ": %s" % used_vars
593
+ except AttributeError:
594
+ data += ": []"
595
+
596
+ newline = "{}{}".format(" " * (self.indent + indent), data)
597
+ self.lines.append(newline)
598
+
599
+ if self.verbose:
600
+ print(newline)
601
+
602
+
603
+ class Categories:
604
+ ATOM = 0
605
+ PROP = 1
606
+ N_ATOM = 2
607
+ N_PROP = 3
608
+ APP = 4
609
+ N_APP = 5
610
+ N_EQ = 6
611
+ D_NEG = 7
612
+ N_ALL = 8
613
+ N_EXISTS = 9
614
+ AND = 10
615
+ N_OR = 11
616
+ N_IMP = 12
617
+ OR = 13
618
+ IMP = 14
619
+ N_AND = 15
620
+ IFF = 16
621
+ N_IFF = 17
622
+ EQ = 18
623
+ EXISTS = 19
624
+ ALL = 20
625
+
626
+
627
+ def testTableauProver():
628
+ tableau_test("P | -P")
629
+ tableau_test("P & -P")
630
+ tableau_test("Q", ["P", "(P -> Q)"])
631
+ tableau_test("man(x)")
632
+ tableau_test("(man(x) -> man(x))")
633
+ tableau_test("(man(x) -> --man(x))")
634
+ tableau_test("-(man(x) and -man(x))")
635
+ tableau_test("(man(x) or -man(x))")
636
+ tableau_test("(man(x) -> man(x))")
637
+ tableau_test("-(man(x) and -man(x))")
638
+ tableau_test("(man(x) or -man(x))")
639
+ tableau_test("(man(x) -> man(x))")
640
+ tableau_test("(man(x) iff man(x))")
641
+ tableau_test("-(man(x) iff -man(x))")
642
+ tableau_test("all x.man(x)")
643
+ tableau_test("all x.all y.((x = y) -> (y = x))")
644
+ tableau_test("all x.all y.all z.(((x = y) & (y = z)) -> (x = z))")
645
+ # tableau_test('-all x.some y.F(x,y) & some x.all y.(-F(x,y))')
646
+ # tableau_test('some x.all y.sees(x,y)')
647
+
648
+ p1 = "all x.(man(x) -> mortal(x))"
649
+ p2 = "man(Socrates)"
650
+ c = "mortal(Socrates)"
651
+ tableau_test(c, [p1, p2])
652
+
653
+ p1 = "all x.(man(x) -> walks(x))"
654
+ p2 = "man(John)"
655
+ c = "some y.walks(y)"
656
+ tableau_test(c, [p1, p2])
657
+
658
+ p = "((x = y) & walks(y))"
659
+ c = "walks(x)"
660
+ tableau_test(c, [p])
661
+
662
+ p = "((x = y) & ((y = z) & (z = w)))"
663
+ c = "(x = w)"
664
+ tableau_test(c, [p])
665
+
666
+ p = "some e1.some e2.(believe(e1,john,e2) & walk(e2,mary))"
667
+ c = "some e0.walk(e0,mary)"
668
+ tableau_test(c, [p])
669
+
670
+ c = "(exists x.exists z3.((x = Mary) & ((z3 = John) & sees(z3,x))) <-> exists x.exists z4.((x = John) & ((z4 = Mary) & sees(x,z4))))"
671
+ tableau_test(c)
672
+
673
+
674
+ # p = 'some e1.some e2.((believe e1 john e2) and (walk e2 mary))'
675
+ # c = 'some x.some e3.some e4.((believe e3 x e4) and (walk e4 mary))'
676
+ # tableau_test(c, [p])
677
+
678
+
679
+ def testHigherOrderTableauProver():
680
+ tableau_test("believe(j, -lie(b))", ["believe(j, -lie(b) & -cheat(b))"])
681
+ tableau_test("believe(j, lie(b) & cheat(b))", ["believe(j, lie(b))"])
682
+ tableau_test(
683
+ "believe(j, lie(b))", ["lie(b)"]
684
+ ) # how do we capture that John believes all things that are true
685
+ tableau_test(
686
+ "believe(j, know(b, cheat(b)))",
687
+ ["believe(j, know(b, lie(b)) & know(b, steals(b) & cheat(b)))"],
688
+ )
689
+ tableau_test("P(Q(y), R(y) & R(z))", ["P(Q(x) & Q(y), R(y) & R(z))"])
690
+
691
+ tableau_test("believe(j, cheat(b) & lie(b))", ["believe(j, lie(b) & cheat(b))"])
692
+ tableau_test("believe(j, -cheat(b) & -lie(b))", ["believe(j, -lie(b) & -cheat(b))"])
693
+
694
+
695
+ def tableau_test(c, ps=None, verbose=False):
696
+ pc = Expression.fromstring(c)
697
+ pps = [Expression.fromstring(p) for p in ps] if ps else []
698
+ if not ps:
699
+ ps = []
700
+ print(
701
+ "%s |- %s: %s"
702
+ % (", ".join(ps), pc, TableauProver().prove(pc, pps, verbose=verbose))
703
+ )
704
+
705
+
706
+ def demo():
707
+ testTableauProver()
708
+ testHigherOrderTableauProver()
709
+
710
+
711
+ if __name__ == "__main__":
712
+ demo()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__init__.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Natural Language Toolkit: Parsers
2
+ #
3
+ # Copyright (C) 2001-2023 NLTK Project
4
+ # Author: Steven Bird <stevenbird1@gmail.com>
5
+ # Edward Loper <edloper@gmail.com>
6
+ # URL: <https://www.nltk.org/>
7
+ # For license information, see LICENSE.TXT
8
+ #
9
+
10
+ """
11
+ NLTK Parsers
12
+
13
+ Classes and interfaces for producing tree structures that represent
14
+ the internal organization of a text. This task is known as "parsing"
15
+ the text, and the resulting tree structures are called the text's
16
+ "parses". Typically, the text is a single sentence, and the tree
17
+ structure represents the syntactic structure of the sentence.
18
+ However, parsers can also be used in other domains. For example,
19
+ parsers can be used to derive the morphological structure of the
20
+ morphemes that make up a word, or to derive the discourse structure
21
+ for a set of utterances.
22
+
23
+ Sometimes, a single piece of text can be represented by more than one
24
+ tree structure. Texts represented by more than one tree structure are
25
+ called "ambiguous" texts. Note that there are actually two ways in
26
+ which a text can be ambiguous:
27
+
28
+ - The text has multiple correct parses.
29
+ - There is not enough information to decide which of several
30
+ candidate parses is correct.
31
+
32
+ However, the parser module does *not* distinguish these two types of
33
+ ambiguity.
34
+
35
+ The parser module defines ``ParserI``, a standard interface for parsing
36
+ texts; and two simple implementations of that interface,
37
+ ``ShiftReduceParser`` and ``RecursiveDescentParser``. It also contains
38
+ three sub-modules for specialized kinds of parsing:
39
+
40
+ - ``nltk.parser.chart`` defines chart parsing, which uses dynamic
41
+ programming to efficiently parse texts.
42
+ - ``nltk.parser.probabilistic`` defines probabilistic parsing, which
43
+ associates a probability with each parse.
44
+ """
45
+
46
+ from nltk.parse.api import ParserI
47
+ from nltk.parse.bllip import BllipParser
48
+ from nltk.parse.chart import (
49
+ BottomUpChartParser,
50
+ BottomUpLeftCornerChartParser,
51
+ ChartParser,
52
+ LeftCornerChartParser,
53
+ SteppingChartParser,
54
+ TopDownChartParser,
55
+ )
56
+ from nltk.parse.corenlp import CoreNLPDependencyParser, CoreNLPParser
57
+ from nltk.parse.dependencygraph import DependencyGraph
58
+ from nltk.parse.earleychart import (
59
+ EarleyChartParser,
60
+ FeatureEarleyChartParser,
61
+ FeatureIncrementalBottomUpChartParser,
62
+ FeatureIncrementalBottomUpLeftCornerChartParser,
63
+ FeatureIncrementalChartParser,
64
+ FeatureIncrementalTopDownChartParser,
65
+ IncrementalBottomUpChartParser,
66
+ IncrementalBottomUpLeftCornerChartParser,
67
+ IncrementalChartParser,
68
+ IncrementalLeftCornerChartParser,
69
+ IncrementalTopDownChartParser,
70
+ )
71
+ from nltk.parse.evaluate import DependencyEvaluator
72
+ from nltk.parse.featurechart import (
73
+ FeatureBottomUpChartParser,
74
+ FeatureBottomUpLeftCornerChartParser,
75
+ FeatureChartParser,
76
+ FeatureTopDownChartParser,
77
+ )
78
+ from nltk.parse.malt import MaltParser
79
+ from nltk.parse.nonprojectivedependencyparser import (
80
+ NaiveBayesDependencyScorer,
81
+ NonprojectiveDependencyParser,
82
+ ProbabilisticNonprojectiveParser,
83
+ )
84
+ from nltk.parse.pchart import (
85
+ BottomUpProbabilisticChartParser,
86
+ InsideChartParser,
87
+ LongestChartParser,
88
+ RandomChartParser,
89
+ UnsortedChartParser,
90
+ )
91
+ from nltk.parse.projectivedependencyparser import (
92
+ ProbabilisticProjectiveDependencyParser,
93
+ ProjectiveDependencyParser,
94
+ )
95
+ from nltk.parse.recursivedescent import (
96
+ RecursiveDescentParser,
97
+ SteppingRecursiveDescentParser,
98
+ )
99
+ from nltk.parse.shiftreduce import ShiftReduceParser, SteppingShiftReduceParser
100
+ from nltk.parse.transitionparser import TransitionParser
101
+ from nltk.parse.util import TestGrammar, extract_test_sentences, load_parser
102
+ from nltk.parse.viterbi import ViterbiParser
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.94 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/api.cpython-310.pyc ADDED
Binary file (2.65 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/bllip.cpython-310.pyc ADDED
Binary file (7.16 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/chart.cpython-310.pyc ADDED
Binary file (54 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/corenlp.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/dependencygraph.cpython-310.pyc ADDED
Binary file (29.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/earleychart.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/evaluate.cpython-310.pyc ADDED
Binary file (4.05 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/featurechart.cpython-310.pyc ADDED
Binary file (18.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/generate.cpython-310.pyc ADDED
Binary file (2.15 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/malt.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/nonprojectivedependencyparser.cpython-310.pyc ADDED
Binary file (21.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/pchart.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/projectivedependencyparser.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/recursivedescent.cpython-310.pyc ADDED
Binary file (23.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/shiftreduce.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/stanford.cpython-310.pyc ADDED
Binary file (17.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/parse/__pycache__/transitionparser.cpython-310.pyc ADDED
Binary file (21.3 kB). View file