-
Notifications
You must be signed in to change notification settings - Fork 2
/
comparisons.py
422 lines (360 loc) · 15.4 KB
/
comparisons.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
from __future__ import annotations
from abc import ABC
import functools
from itertools import permutations, zip_longest
import logging
from typing import Callable, Dict, Iterator, List, Optional
logger = logging.getLogger(__name__)
class Comparable(ABC):
generic: bool = False
def consistent_with(
self, other: Optional[Comparable], context: Optional[ContextRegister] = None
) -> bool:
"""
Check if self and other can be non-contradictory.
:returns:
a bool indicating whether there's at least one way to
match the :attr:`context_factors` of ``self`` and ``other``,
such that they fit the relationship ``comparison``.
"""
if other is None:
return True
return any(
explanation is not None
for explanation in self.explanations_consistent_with(other, context)
)
def _context_registers(
self,
other: Optional[Factor],
comparison: Callable,
context: Optional[ContextRegister] = None,
) -> Iterator[ContextRegister]:
r"""
Search for ways to match :attr:`context_factors` of ``self`` and ``other``.
:yields:
all valid ways to make matches between
corresponding :class:`Factor`\s.
"""
if context is None:
context = ContextRegister()
if other is None:
yield context
elif self.generic or other.generic:
if context.get(self) is None or (context.get(self) == other):
yield ContextRegister({self: other})
else:
yield from self.context_factors.ordered_comparison(
other=other.context_factors, operation=comparison, context=context
)
def contradicts(
self, other: Optional[Comparable], context: Optional[ContextRegister] = None
) -> bool:
"""
Test whether ``self`` implies the absence of ``other``.
:returns:
``True`` if self and other can't both be true at
the same time. Otherwise returns ``False``.
"""
if other is None:
return False
return any(
explanation is not None
for explanation in self.explanations_contradiction(other, context)
)
@property
def generic_factors(self) -> List[Comparable]:
r"""
:class:`.Factor`\s that can be replaced without changing ``self``\s meaning.
:returns:
a :class:`list` made from a :class:`dict` with ``self``\'s
generic :class:`.Factor`\s as keys and ``None`` as values,
so that the keys can be matched to another object's
``generic_factors`` to perform an equality test.
"""
return []
def implied_by(
self, other: Optional[Comparable], context: Optional[ContextRegister] = None
):
"""Test whether ``other`` implies ``self``."""
if other is None:
return False
return any(
register is not None
for register in self.explanations_implied_by(other, context=context)
)
def implies(
self, other: Optional[Comparable], context: Optional[ContextRegister] = None
) -> bool:
"""Test whether ``self`` implies ``other``."""
if other is None:
return True
return any(
register is not None
for register in self.explanations_implication(other, context=context)
)
def implies_same_context(self, other) -> bool:
same_context = ContextRegister({key: key for key in self.generic_factors})
return self.implies(other, context=same_context)
def means(
self, other: Optional[Comparable], context: Optional[ContextRegister] = None
) -> bool:
r"""
Test whether ``self`` and ``other`` have identical meanings.
:returns:
whether ``other`` is another :class:`Factor`
with the same meaning as ``self``. Not the same as an
equality comparison with the ``==`` symbol, which simply
converts ``self``\'s and ``other``\'s fields to tuples
and compares them.
"""
if other is None:
return False
return any(
explanation is not None
for explanation in self.explanations_same_meaning(other, context=context)
)
def means_same_context(self, other) -> bool:
same_context = ContextRegister({key: key for key in self.generic_factors})
return self.means(other, context=same_context)
def possible_contexts(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Iterator[ContextRegister]:
r"""
Get permutations of generic Factor assignments not ruled out by the known context.
:param other:
another :class:`.Comparable` object with generic :class:`.Factor`\s
:yields: all possible ContextRegisters linking the two :class:`.Comparable`\s
"""
context = context or ContextRegister()
context = ContextRegister(context)
unused_self = [
factor for factor in self.generic_factors if factor not in context.keys()
]
unused_other = [
factor for factor in other.generic_factors if factor not in context.values()
]
if not (unused_self and unused_other):
yield context
else:
for permutation in permutations(unused_other):
incoming = ContextRegister(zip_longest(unused_self, permutation))
yield context.merged_with(incoming)
def __or__(self, other: Comparable):
return self.union(other)
def explanations_union(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Iterator[ContextRegister]:
context = context or ContextRegister()
for partial in self.partial_explanations_union(other, context):
for guess in self.possible_contexts(other, partial):
answer = self.union_from_explanation(other, guess)
if answer:
yield guess
def union(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Optional[Comparable]:
context = context or ContextRegister()
explanations = self.explanations_union(other, context)
try:
explanation = next(explanations)
except StopIteration:
return None
return self.union_from_explanation(other, explanation)
def update_context_register(
self,
other: Optional[Comparable],
register: ContextRegister,
comparison: Callable,
) -> Iterator[ContextRegister]:
r"""
Find ways to update ``self_mapping`` to allow relationship ``comparison``.
:param other:
another :class:`Comparable` being compared to ``self``
:param register:
keys representing :class:`Comparable`\s from ``self``'s context and
values representing :class:`Comparable`\s in ``other``'s context.
:param comparison:
a function defining the comparison that must be ``True``
between ``self`` and ``other``. Could be :meth:`Comparable.means` or
:meth:`Comparable.__ge__`.
:yields:
every way that ``self_mapping`` can be updated to be consistent
with ``self`` and ``other`` having the relationship
``comparison``.
"""
if other and not isinstance(other, Comparable):
raise TypeError
if not isinstance(register, ContextRegister):
register = ContextRegister(register)
for incoming_register in self._context_registers(other, comparison):
for new_register_variation in self._registers_for_interchangeable_context(
incoming_register
):
register_or_none = register.merged_with(new_register_variation)
if register_or_none is not None:
yield register_or_none
def explain_same_meaning(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Optional[ContextRegister]:
"""Get one explanation of why self and other have the same meaning."""
explanations = self.explanations_same_meaning(other, context=context)
try:
explanation = next(explanations)
except StopIteration:
return None
return explanation
def explain_consistent_with(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Optional[ContextRegister]:
"""Get one explanation of why self and other need not contradict."""
explanations = self.explanations_consistent_with(other, context=context)
try:
explanation = next(explanations)
except StopIteration:
return None
return explanation
def explain_contradiction(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Optional[ContextRegister]:
"""Get one explanation of why self and other contradict."""
explanations = self.explanations_contradiction(other, context=context)
try:
explanation = next(explanations)
except StopIteration:
return None
return explanation
def explain_implication(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Optional[ContextRegister]:
"""Get one explanation of why self implies other."""
explanations = self.explanations_implication(other, context=context)
try:
explanation = next(explanations)
except StopIteration:
return None
return explanation
def explain_implied_by(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Optional[ContextRegister]:
"""Get one explanation of why self implies other."""
explanations = self.explanations_implied_by(other, context=context)
try:
explanation = next(explanations)
except StopIteration:
return None
return explanation
def explanations_consistent_with(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Iterator[ContextRegister]:
raise NotImplementedError
def explanations_contradiction(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Iterator[ContextRegister]:
raise NotImplementedError
def explanations_implication(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Iterator[ContextRegister]:
raise NotImplementedError
def explanations_implied_by(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Iterator[ContextRegister]:
context = context or ContextRegister()
yield from (
register.reversed()
for register in other.explanations_implication(
self, context=context.reversed()
)
)
def explanations_same_meaning(
self, other: Comparable, context: Optional[ContextRegister] = None
) -> Iterator[ContextRegister]:
raise NotImplementedError
class ContextRegister(Dict[Comparable, Comparable]):
r"""
A mapping of corresponding :class:`Factor`\s from two different contexts.
When :class:`Factor`\s are matched in a ContextRegister, it indicates
that their relationship can be described by a comparison function
like :func:`means`, :meth:`Factor.implies`, or :meth:`Factor.consistent_with`\.
"""
def __repr__(self) -> str:
return "ContextRegister({})".format(super().__repr__())
def __str__(self) -> str:
item_names = [f"{str(k)} -> {str(v)}" for k, v in self.items()]
items = ", ".join(item_names)
return f"ContextRegister({items})"
@property
def prose(self) -> str:
"""Make statement matching analagous context factors of self and other."""
similies = [
f'{key} {"are" if key.__dict__.get("plural") is True else "is"} like {value}'
for key, value in self.items()
]
if len(similies) > 1:
similies[-2:] = [", and ".join(similies[-2:])]
return ", ".join(similies)
def replace_keys(self, replacements: ContextRegister) -> ContextRegister:
"""Construct new :class:`ContextRegister` by replacing keys."""
values = self.values()
keys = [replacements.get(factor) or factor for factor in self.keys()]
return ContextRegister(zip(keys, values))
def reversed(self):
"""Swap keys for values and vice versa."""
return ContextRegister({v: k for k, v in self.items()})
def merged_with(
self, incoming_mapping: ContextRegister
) -> Optional[ContextRegister]:
r"""
Create a new merged :class:`ContextRegister`\.
:param incoming_mapping:
an incoming mapping of :class:`Factor`\s
from ``self`` to :class:`Factor`\s.
:returns:
``None`` if the same :class:`Factor` in one mapping
appears to match to two different :class:`Factor`\s in the other.
Otherwise returns an updated :class:`ContextRegister` of matches.
"""
self_mapping = ContextRegister(self.items())
for in_key, in_value in incoming_mapping.items():
if in_value:
if self_mapping.get(in_key) and self_mapping.get(in_key) != in_value:
logger.debug(
f"{in_key} already in mapping with value "
+ f"{self_mapping[in_key]}, not {in_value}"
)
return None
self_mapping[in_key] = in_value
if list(self_mapping.values()).count(in_value) > 1:
logger.debug("%s assigned to two different keys", in_value)
return None
return self_mapping
def use_likely_context(func: Callable):
r"""
Find contexts most likely to have been intended for comparing Comparable.
When such contexts are found, first tries calling the decorated comparison method
using those contexts. Only if no answer is found using the likely contexts
will the decorated method be called with no comparison method specified.
:param left:
a :class:`.Comparable` that is being compared to another
:class:`.Comparable`\, to create a new :class:`.Comparable`
using the context of the left :class:`.Comparable`\.
:param right:
a :class:`.Comparable` that is being compared but that will have its context
overwritten in the newly-created object.
:param context:
a :class:`.ContextRegister` identifying any known pairs of corresponding
context :class:`.Factor`\s between the two :class:`.Comparable`\s being
compared.
:returns:
a generator yielding :class:`.ContextRegister`\s based on the most "likely"
context that yields any :class:`.ContextRegister`\s at all.
"""
@functools.wraps(func)
def wrapper(
left: Comparable, right: Comparable, context: Optional[ContextRegister] = None
) -> Optional[Comparable]:
for likely_context in left.likely_contexts(right, context):
answer = func(left, right, likely_context)
if answer is not None:
return answer
return None
return wrapper