From b20fef69c8c679b2e3ef7bb9a33f591ffdeea38c Mon Sep 17 00:00:00 2001 From: Vitalii Kozlovskyi Date: Sun, 23 Apr 2017 01:45:31 +0300 Subject: [PATCH 1/2] Add Range merging. --- pso/q.py | 244 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 145 insertions(+), 99 deletions(-) diff --git a/pso/q.py b/pso/q.py index 909dd70..7142d51 100644 --- a/pso/q.py +++ b/pso/q.py @@ -16,35 +16,19 @@ from functools import wraps from collections.abc import Iterable from collections import namedtuple +import ipdb -class Range(namedtuple('Range', ['fr', 'to', 'fr_incl', 'to_incl'])): - - @classmethod - def from_dict(cls, d): - if Condition.GE in d: - fr, fr_incl = d[Condition.GE], True - else: - fr, fr_incl = d[Condition.GT], False - - if Condition.LE in d: - to, to_incl = d[Condition.LE], True - else: - to, to_incl = d[Condition.LT], False - return cls(fr, to, fr_incl, to_incl) +class _NoValue: + """ + To check when value is explicitly None or False + """ + @staticmethod + def __bool__(): + return False - def to_dict(self): - d = {} - d[Condition.GE if self.fr_incl else Condition.GT] = self.fr - d[Condition.LE if self.to_incl else Condition.LT] = self.to - return d - @classmethod - def from_range(cls, r): - """ - Ability to use Python's standart range object - """ - cls(r.start, r.end, True, False) +NoValue = _NoValue() class Operator: @@ -74,6 +58,83 @@ class Condition: ] +class Range(namedtuple('Range', ['fr', 'to', 'fr_incl', 'to_incl'])): + + def __new__(cls, fr=NoValue, to=NoValue, fr_incl=False, to_incl=False): + return super(Range, cls).__new__(cls, fr, to, fr_incl, to_incl) + + def _check_overlap(self, other): + # ipdb.set_trace(context=50) + if self.to and other.fr: + incl = (self.to_incl or other.fr_incl) + if other.fr > self.to or (other.fr == self.to and not incl): + return False + + if self.fr and other.to: + incl = (self.fr_incl or other.to_incl) + if self.fr > other.to or (self.fr == other.to and not incl): + return False + + return True + + @staticmethod + def _merge(func, v1, v2): + if v1[0] and v2[0]: + return func(v1, v2) + else: + return v1 if v1[0] else v2 + + def merge(self, other, operator): + if operator is Operator.OR: + return self.__or__(other) + else: + return self.__and__(other) + + def __and__(self, other): + """ + Merge range with AND operator + """ + # ipdb.set_trace(context=50) + if not self._check_overlap(other): + raise ValueError("Can not merge non overlapped ranges") + + fr, fr_incl = self._merge( + max, (self.fr, not self.fr_incl), (other.fr, not other.fr_incl)) + fr_incl = not fr_incl + + to, to_incl = self._merge( + min, (self.to, self.to_incl), (other.to, other.to_incl)) + + return Range(fr, to, fr_incl, to_incl) + + def __or__(self, other): + """ + Merge range with AND operator + """ + if not self._check_overlap(other): + raise ValueError("Can not merge non overlapped ranges") + + fr, fr_incl = self._merge( + min, (self.fr, not self.fr_incl), (other.fr, not other.fr_incl)) + fr_incl = not fr_incl + + to, to_incl = self._merge( + max, (self.to, self.to_incl), (other.to, other.to_incl)) + + return Range(fr, to, fr_incl, to_incl) + + @classmethod + def from_range(cls, r): + """ + Ability to use Python's standart range object + + Model.field_name == range(0, 100) -> {0 TO 100} + Model.field_name == range(0, 100, True) -> [0 TO 100] + """ + include = (True, True) if r.step is True else (False, False) + cls(r.start, r.end, *include) + + def unpack_magic(method): """ Method decorator used to unpack Iterable items, @@ -93,64 +154,42 @@ def unpack(self, value): return unpack -class NoValue: - """ - To check when value is explicitly None or False - """ - - class QComparisonMixin(): """QComparisonMixin - defines comparsion magic for Q objects""" - _CONFLICT_MERGE_MAP = { - (Condition.LT, Operator.AND): min, - (Condition.LE, Operator.AND): min, - (Condition.GT, Operator.AND): max, - (Condition.GE, Operator.AND): max, - - (Condition.LT, Operator.OR): max, - (Condition.LE, Operator.OR): max, - (Condition.GT, Operator.OR): min, - (Condition.GE, Operator.OR): min, - } - - def _merge_range_condition(self): + def _merge_ranges(self): + # ipdb.set_trace(context=50) if self.is_leaf or not self.is_field: - return - - qrange = {} - childs = [] - # TODO boost check - for q in self.childs: - if q.is_leaf and q.operation in RANGE_CONDITIONS: - old = qrange.get(q.operation) - value = q.value - if old: - value = self._CONFLICT_MERGE_MAP[(q.operation, self.operator)](old, value) # noqa - qrange[q.operation] = value - if q.is_leaf and q.operation == Condition.RANGE: - for op, new in q.value.to_dict().items(): - old = qrange.get(op) - qrange[op] = self._CONFLICT_MERGE_MAP[(q.operation, self.operator)](old, value) # noqa - else: - childs.append(q) - if qrange: - if len(qrange) > 2: - "TODO " - # Merge - childs.append(Q( - operation=Condition.RANGE, - value=Range.from_dict(qrange) - )) - return self._replace(childs=childs) + return self + childs = list(self.childs) + ranges = filter(lambda x: x.operation is Condition.RANGE, childs) + previous = None + + for q in sorted(ranges, key=lambda x: (x.value.fr is not NoValue, x.value.fr, x.value.to is NoValue, x.value.to)): + try: + # TODO predefine 'previos' + childs.append( + q._replace(value=previous.value.merge(q.value, self.operator)) + ) + childs.remove(q) + childs.remove(previous) + except: + continue + finally: + previous = q + return self._replace(childs=tuple(childs)) @unpack_magic def __lt__(self, value): - return self._make_q_operation(Condition.LT, value) + return self\ + ._make_q_operation(Condition.RANGE, Range(to=value, to_incl=False))\ + ._merge_ranges() @unpack_magic def __le__(self, value): - return self._make_q_operation(Condition.LE, value) + return self\ + ._make_q_operation(Condition.RANGE, Range(to=value, to_incl=True))\ + ._merge_ranges() @unpack_magic def __eq__(self, value): @@ -162,11 +201,17 @@ def __ne__(self, value): @unpack_magic def __gt__(self, value): - return self._make_q_operation(Condition.GT, value) + return self\ + ._make_q_operation(Condition.RANGE, Range(fr=value, fr_incl=False))\ + ._merge_ranges() @unpack_magic def __ge__(self, value): - return self._make_q_operation(Condition.GE, value) + print(value) + print(Range(10, 20, False, False)) + return self\ + ._make_q_operation(Condition.RANGE, Range(fr=value, fr_incl=True))\ + ._merge_ranges() def __contains__(self, value): """To use reverse in operator as contains operation @@ -338,27 +383,6 @@ def __invert__(self): self.inverted = not self.inverted return self - def _merge_condition(self, other, operator=Operator.AND): - if not isinstance(other, Q): - return NotImplemented - - childs = [] - same_invertion = self.inverted == other.inverted - - if self.qtype == Q.AGGREGATION\ - and self.operator == operator and same_invertion: - childs.extend(list(self.childs)) - else: - childs.append(self) - - if other.qtype == Q.AGGREGATION\ - and other.operator == operator and same_invertion: - childs.extend(list(other.childs)) - else: - childs.append(other) - - return Q(operator, childs=tuple(childs)) - def __and__(self, other): return self._merge_condition(other, Operator.AND) @@ -368,7 +392,6 @@ def __or__(self, other): class Q(QComparisonMixin, QShiftContainsMixin, QNumericBoostMixin, BaseQ): - # TODO: rewrite to use namedtuple def _make_q_operation(self, operation, value): print(self, operation, value) if self.is_leaf: @@ -380,13 +403,36 @@ def _make_q_operation(self, operation, value): self._replace(field=None), Q(operation=operation, value=value) ) - ) + )._merge_ranges() # Add operation to existing Q object return self._replace(operation=operation, value=value) # TODO: maybe check all childs field ... and in some case append elif self.is_field: q = Q(operation=operation, value=value) - return self._replace(field=self.is_field, child=self.childs + (q)) + return self._replace(field=self.is_field, child=self.childs + (q))._merge_ranges() else: raise ValueError( 'Can not use comparsion of complex Q with multuple fields') + + def _merge_condition(self, other, operator=Operator.AND): + if not isinstance(other, Q): + return NotImplemented + + childs = [] + same_invertion = self.inverted == other.inverted + + if self.qtype == Q.AGGREGATION\ + and self.operator == operator and same_invertion: + childs.extend(list(self.childs)) + else: + childs.append(self) + + if other.qtype == Q.AGGREGATION\ + and other.operator == operator and same_invertion: + childs.extend(list(other.childs)) + else: + childs.append(other) + + childs = self._merge_ranges(childs) + + return Q(operator, childs=tuple(childs))._merge_ranges() From fbf56526a88c06133eb9c2a320faafa7320a142c Mon Sep 17 00:00:00 2001 From: Vitalii Kozlovskyi Date: Sun, 23 Apr 2017 02:41:26 +0300 Subject: [PATCH 2/2] Add tests. Fix bugs. --- pso/q.py | 2 +- tests/test_range.py | 56 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 tests/test_range.py diff --git a/pso/q.py b/pso/q.py index 7142d51..950f321 100644 --- a/pso/q.py +++ b/pso/q.py @@ -132,7 +132,7 @@ def from_range(cls, r): Model.field_name == range(0, 100, True) -> [0 TO 100] """ include = (True, True) if r.step is True else (False, False) - cls(r.start, r.end, *include) + return cls(r.start, r.stop, *include) def unpack_magic(method): diff --git a/tests/test_range.py b/tests/test_range.py new file mode 100644 index 0000000..6fb4953 --- /dev/null +++ b/tests/test_range.py @@ -0,0 +1,56 @@ +import unittest +from pso.q import Range +from pso.q import NoValue + + +r1 = Range(-99, 10, True, True) +r2 = Range(-10, 99, True, True) +r3 = Range(10, 15, False, False) +r4 = Range(15, 17, True, False) +r5 = Range(15, 17, False, False) +r6 = Range(fr=-10, fr_incl=True) +r7 = Range(fr=10) +r8 = Range(to=-10, to_incl=True) +r9 = Range(to=10, to_incl=True) + + +class TestRangeMerge(unittest.TestCase): + + def test_010_create_range(t): + "Range creating" + t.assertEqual(Range(-1, 10), (-1, 10, False, False)) + t.assertEqual(Range(fr=99, fr_incl=True), (99, NoValue, True, False)) + t.assertEqual(Range(to=99, to_incl=True), (NoValue, 99, False, True)) + + def test_020_create_range_from_native(t): + "Range from native python range()" + t.assertEqual(Range.from_range(range(0, 10)), (0, 10, False, False)) + t.assertEqual( + Range.from_range(range(0, 10, True)), (0, 10, True, True)) + + def test_030_overlap_detection(t): + "Overlap detection" + t.assertTrue(r1._check_overlap(r2), msg="Fatal. No overlap detection") + t.assertTrue(r3._check_overlap(r4), msg="Equal and inclusive") + t.assertTrue(r3._check_overlap(r1), msg="Equal and inclusive") + t.assertFalse(r3._check_overlap(r5), msg="Equal, but exclusive") + t.assertFalse(r1._check_overlap(r4), msg="Equal, but exclusive") + t.assertFalse(r1._check_overlap(r4), msg="Without any overlap.") + + def test_040_test_overlap_or_merge(t): + "Merging overlapped Ranges with OR (Union)" + t.assertEqual(r1 | r2, Range(-99, 99, True, True)) + t.assertEqual(r1 | r3, Range(-99, 15, True, False)) + t.assertEqual(r3 | r4, Range(10, 17, False, False)) + t.assertEqual(r6 | r7, Range(-10, NoValue, True, False)) + + # BUG with NoValue. + t.assertEqual(r6 | r9, Range(-10, 10, True, True)) + + def test_050_test_overlap_and_merge(t): + "Merging overlapped Ranges with AND (Intersection)" + t.assertEqual(r1 & r2, Range(-10, 10, True, True)) + t.assertEqual(r4 & r5, r5) + + # Here, works fine. + t.assertEqual(r6 | r9, Range(-10, 10, True, True))