sets.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from sympy.core.assumptions import check_assumptions
  2. from sympy.core.logic import fuzzy_and
  3. from sympy.core.sympify import _sympify
  4. from sympy.sets.sets import Set
  5. from .matexpr import MatrixExpr
  6. class MatrixSet(Set):
  7. """
  8. MatrixSet represents the set of matrices with ``shape = (n, m)`` over the
  9. given set.
  10. Examples
  11. ========
  12. >>> from sympy.matrices import MatrixSet
  13. >>> from sympy import S, I, Matrix
  14. >>> M = MatrixSet(2, 2, set=S.Reals)
  15. >>> X = Matrix([[1, 2], [3, 4]])
  16. >>> X in M
  17. True
  18. >>> X = Matrix([[1, 2], [I, 4]])
  19. >>> X in M
  20. False
  21. """
  22. is_empty = False
  23. def __new__(cls, n, m, set):
  24. n, m, set = _sympify(n), _sympify(m), _sympify(set)
  25. cls._check_dim(n)
  26. cls._check_dim(m)
  27. if not isinstance(set, Set):
  28. raise TypeError("{} should be an instance of Set.".format(set))
  29. return Set.__new__(cls, n, m, set)
  30. @property
  31. def shape(self):
  32. return self.args[:2]
  33. @property
  34. def set(self):
  35. return self.args[2]
  36. def _contains(self, other):
  37. if not isinstance(other, MatrixExpr):
  38. raise TypeError("{} should be an instance of MatrixExpr.".format(other))
  39. if other.shape != self.shape:
  40. are_symbolic = any(_sympify(x).is_Symbol for x in other.shape + self.shape)
  41. if are_symbolic:
  42. return None
  43. return False
  44. return fuzzy_and(self.set.contains(x) for x in other)
  45. @classmethod
  46. def _check_dim(cls, dim):
  47. """Helper function to check invalid matrix dimensions"""
  48. ok = check_assumptions(dim, integer=True, nonnegative=True)
  49. if ok is False:
  50. raise ValueError(
  51. "The dimension specification {} should be "
  52. "a nonnegative integer.".format(dim))