Coverage for /usr/lib/python3/dist-packages/sympy/matrices/expressions/companion.py: 33%

30 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-14 15:55 +0200

1from sympy.core.singleton import S 

2from sympy.core.sympify import _sympify 

3from sympy.polys.polytools import Poly 

4 

5from .matexpr import MatrixExpr 

6 

7 

8class CompanionMatrix(MatrixExpr): 

9 """A symbolic companion matrix of a polynomial. 

10 

11 Examples 

12 ======== 

13 

14 >>> from sympy import Poly, Symbol, symbols 

15 >>> from sympy.matrices.expressions import CompanionMatrix 

16 >>> x = Symbol('x') 

17 >>> c0, c1, c2, c3, c4 = symbols('c0:5') 

18 >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) 

19 >>> CompanionMatrix(p) 

20 CompanionMatrix(Poly(x**5 + c4*x**4 + c3*x**3 + c2*x**2 + c1*x + c0, 

21 x, domain='ZZ[c0,c1,c2,c3,c4]')) 

22 """ 

23 def __new__(cls, poly): 

24 poly = _sympify(poly) 

25 if not isinstance(poly, Poly): 

26 raise ValueError("{} must be a Poly instance.".format(poly)) 

27 if not poly.is_monic: 

28 raise ValueError("{} must be a monic polynomial.".format(poly)) 

29 if not poly.is_univariate: 

30 raise ValueError( 

31 "{} must be a univariate polynomial.".format(poly)) 

32 if not poly.degree() >= 1: 

33 raise ValueError( 

34 "{} must have degree not less than 1.".format(poly)) 

35 

36 return super().__new__(cls, poly) 

37 

38 

39 @property 

40 def shape(self): 

41 poly = self.args[0] 

42 size = poly.degree() 

43 return size, size 

44 

45 

46 def _entry(self, i, j): 

47 if j == self.cols - 1: 

48 return -self.args[0].all_coeffs()[-1 - i] 

49 elif i == j + 1: 

50 return S.One 

51 return S.Zero 

52 

53 

54 def as_explicit(self): 

55 from sympy.matrices.immutable import ImmutableDenseMatrix 

56 return ImmutableDenseMatrix.companion(self.args[0])