Skip to content

Commit da9f980

Browse files
[ENH] vectorize CLA _reduce_matrix using numpy advanced indexing (#693)
Replace nested loop implementation with np.ix_ based vectorized selection. Performance improvement: 10-36x speedup depending on matrix size. Benchmarks (100 iterations): - n=20: 10x faster - n=50: 18x faster - n=100: 12x faster - n=200: 34x faster - n=500: 37x faster All existing CLA tests pass with identical numerical results.
1 parent 6d837f1 commit da9f980

1 file changed

Lines changed: 18 additions & 11 deletions

File tree

pypfopt/cla.py

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -198,18 +198,25 @@ def _diff_lists(list1, list2):
198198

199199
@staticmethod
200200
def _reduce_matrix(matrix, listX, listY):
201-
# Reduce a matrix to the provided list of rows and columns
201+
"""
202+
Extract a submatrix from the given matrix using specified row and column indices.
203+
204+
Uses numpy advanced indexing with np.ix_ for vectorized selection,
205+
which is significantly faster than the previous nested loop implementation
206+
for large matrices.
207+
208+
:param matrix: input matrix to extract submatrix from
209+
:type matrix: np.ndarray
210+
:param listX: row indices to select
211+
:type listX: list
212+
:param listY: column indices to select
213+
:type listY: list
214+
:return: submatrix with selected rows and columns, or None if indices are empty
215+
:rtype: np.ndarray or None
216+
"""
202217
if len(listX) == 0 or len(listY) == 0:
203-
return
204-
matrix_ = matrix[:, listY[0] : listY[0] + 1]
205-
for i in listY[1:]:
206-
a = matrix[:, i : i + 1]
207-
matrix_ = np.append(matrix_, a, 1)
208-
matrix__ = matrix_[listX[0] : listX[0] + 1, :]
209-
for i in listX[1:]:
210-
a = matrix_[i : i + 1, :]
211-
matrix__ = np.append(matrix__, a, 0)
212-
return matrix__
218+
return None
219+
return matrix[np.ix_(listX, listY)]
213220

214221
def _purge_num_err(self, tol):
215222
# Purge violations of inequality constraints (associated with ill-conditioned cov matrix)

0 commit comments

Comments
 (0)