Coverage for cvxrisk/linalg/valid.py: 100%
7 statements
« prev ^ index » next coverage.py v7.8.2, created at 2025-06-18 11:11 +0000
« prev ^ index » next coverage.py v7.8.2, created at 2025-06-18 11:11 +0000
1"""Matrix validation utilities for handling non-finite values."""
3# Copyright 2023 Stanford University Convex Optimization Group
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16from __future__ import annotations
18import numpy as np
21def valid(matrix: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
22 """Extract the valid subset of a matrix by removing rows/columns with non-finite values.
24 This function identifies rows and columns in a matrix that contain non-finite values
25 (NaN or infinity) on the diagonal and removes them, returning both the indicator
26 vector and the resulting valid submatrix.
28 Args:
29 matrix: An n x n matrix to be validated
31 Returns:
32 A tuple containing:
33 - Boolean vector indicating which rows/columns are valid
34 - The valid submatrix with invalid rows/columns removed
36 Raises:
37 AssertionError: If the input matrix is not square
39 """
40 # make sure matrix is quadratic
41 if matrix.shape[0] != matrix.shape[1]:
42 raise AssertionError
44 v = np.isfinite(np.diag(matrix))
45 return v, matrix[:, v][v]