Coverage for src/cvxmarkowitz/utils/fill.py: 100%
16 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-15 05:21 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-09-15 05:21 +0000
1# Copyright 2023 Stanford University Convex Optimization Group
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Helpers to pad vectors/matrices to target shapes."""
16import numpy as np
18from cvxmarkowitz.cvxerror import CvxDataError
19from cvxmarkowitz.types import Matrix
22def fill_vector(x: Matrix, num: int) -> Matrix:
23 """Return a vector of length ``num`` holding ``x`` in its leading entries.
25 The tail is zero. This is what lets one compiled problem serve a universe
26 smaller than the one it was built for: `Bounds` pads both of its bounds
27 this way, which pins the unused tail to ``0 <= w <= 0``.
29 Padding only ever goes one way. An ``x`` longer than ``num`` does not fit
30 the compiled problem at all, so it is reported as a `CvxDataError` rather
31 than truncated silently or left to escape as the `ValueError` numpy raises
32 on the assignment below -- `CvxDataError` is the failure mode the README
33 promises for input whose shapes do not fit.
35 Raises:
36 CvxDataError: If ``x`` is longer than ``num``.
37 """
38 if len(x) > num:
39 raise CvxDataError(f"Vector of length {len(x)} does not fit a problem built for {num}") # noqa: TRY003
41 z = np.zeros(num)
42 z[: len(x)] = x
43 return z
46def fill_matrix(x: Matrix, rows: int, cols: int) -> Matrix:
47 """Return a ``rows`` x ``cols`` matrix holding ``x`` in its top-left block.
49 The counterpart of `fill_vector`; see there for why the padding is only
50 ever one-directional.
52 Raises:
53 CvxDataError: If ``x`` does not fit into ``(rows, cols)``.
54 """
55 # I had no luck with ndarray.resize()
56 (n, m) = np.shape(x)
58 if n > rows or m > cols:
59 raise CvxDataError(f"Matrix of shape {(n, m)} does not fit a problem built for {(rows, cols)}") # noqa: TRY003
61 z = np.zeros((rows, cols))
62 z[:n, :m] = x
63 return z