Coverage for src / cvx / linalg / det.py: 100%

15 statements  

« prev     ^ index     » next       coverage.py v7.14.0, created at 2026-05-19 05:40 +0000

1"""Matrix determinant with NaN-aware submatrix handling.""" 

2 

3from __future__ import annotations 

4 

5import numpy as np 

6 

7from .exceptions import NonSquareMatrixError 

8from .exceptions import check_and_warn_condition as _check_and_warn_condition 

9from .solve import _DEFAULT_COND_THRESHOLD 

10from .valid import valid 

11 

12_SENTINEL = float("nan") 

13 

14 

15def det( 

16 matrix: np.ndarray, 

17 cond_threshold: float = _DEFAULT_COND_THRESHOLD, 

18) -> float: 

19 """Return the determinant of a square matrix. 

20 

21 Rows and columns with non-finite diagonal entries are excluded before the 

22 computation; when no valid rows or columns remain the function returns 

23 ``nan``. When the condition number of the valid sub-matrix exceeds 

24 *cond_threshold*, an ``IllConditionedMatrixWarning`` is emitted. 

25 

26 Args: 

27 matrix: Square input matrix. 

28 cond_threshold: Condition-number threshold above which a warning is 

29 emitted. Defaults to ``1e12``. 

30 

31 Returns: 

32 The determinant of the valid sub-matrix, or ``nan`` when no valid 

33 entries exist. 

34 

35 Raises: 

36 NonSquareMatrixError: If the matrix is not square. 

37 

38 Example: 

39 >>> import numpy as np 

40 >>> from cvx.linalg import det 

41 >>> det(np.eye(3)) 

42 1.0 

43 

44 NaN-masked entries are skipped: 

45 

46 >>> matrix = np.array([[2.0, 0.0], [0.0, np.nan]]) 

47 >>> det(matrix) 

48 2.0 

49 """ 

50 if matrix.shape[0] != matrix.shape[1]: 

51 raise NonSquareMatrixError(matrix.shape[0], matrix.shape[1]) 

52 

53 mask, submatrix = valid(matrix) 

54 

55 if not mask.any(): 

56 return _SENTINEL 

57 

58 _check_and_warn_condition(submatrix, cond_threshold) 

59 return float(np.linalg.det(submatrix))