interval_membership.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from sympy.core.logic import fuzzy_and, fuzzy_or, fuzzy_not, fuzzy_xor
  2. class intervalMembership:
  3. """Represents a boolean expression returned by the comparison of
  4. the interval object.
  5. Parameters
  6. ==========
  7. (a, b) : (bool, bool)
  8. The first value determines the comparison as follows:
  9. - True: If the comparison is True throughout the intervals.
  10. - False: If the comparison is False throughout the intervals.
  11. - None: If the comparison is True for some part of the intervals.
  12. The second value is determined as follows:
  13. - True: If both the intervals in comparison are valid.
  14. - False: If at least one of the intervals is False, else
  15. - None
  16. """
  17. def __init__(self, a, b):
  18. self._wrapped = (a, b)
  19. def __getitem__(self, i):
  20. try:
  21. return self._wrapped[i]
  22. except IndexError:
  23. raise IndexError(
  24. "{} must be a valid indexing for the 2-tuple."
  25. .format(i))
  26. def __len__(self):
  27. return 2
  28. def __iter__(self):
  29. return iter(self._wrapped)
  30. def __str__(self):
  31. return "intervalMembership({}, {})".format(*self)
  32. __repr__ = __str__
  33. def __and__(self, other):
  34. if not isinstance(other, intervalMembership):
  35. raise ValueError(
  36. "The comparison is not supported for {}.".format(other))
  37. a1, b1 = self
  38. a2, b2 = other
  39. return intervalMembership(fuzzy_and([a1, a2]), fuzzy_and([b1, b2]))
  40. def __or__(self, other):
  41. if not isinstance(other, intervalMembership):
  42. raise ValueError(
  43. "The comparison is not supported for {}.".format(other))
  44. a1, b1 = self
  45. a2, b2 = other
  46. return intervalMembership(fuzzy_or([a1, a2]), fuzzy_and([b1, b2]))
  47. def __invert__(self):
  48. a, b = self
  49. return intervalMembership(fuzzy_not(a), b)
  50. def __xor__(self, other):
  51. if not isinstance(other, intervalMembership):
  52. raise ValueError(
  53. "The comparison is not supported for {}.".format(other))
  54. a1, b1 = self
  55. a2, b2 = other
  56. return intervalMembership(fuzzy_xor([a1, a2]), fuzzy_and([b1, b2]))
  57. def __eq__(self, other):
  58. return self._wrapped == other
  59. def __ne__(self, other):
  60. return self._wrapped != other