sets.py 2.0 KB

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