Coverage for src / cvx / core / parameter.py: 100%
13 statements
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-13 06:46 +0000
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-13 06:46 +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"""Parameter class for risk models.
16This module provides a simple parameter class that stores a named numpy array
17value that can be updated without reconstructing the optimization problem.
19Example:
20 Create a parameter and update its value:
22 >>> import numpy as np
23 >>> from cvx.core.parameter import Parameter
24 >>> p = Parameter(shape=3, name="weights")
25 >>> p.value
26 array([0., 0., 0.])
27 >>> p.value = np.array([0.5, 0.3, 0.2])
28 >>> p.value
29 array([0.5, 0.3, 0.2])
31"""
33from __future__ import annotations
35from dataclasses import dataclass, field
37import numpy as np
40@dataclass
41class Parameter:
42 """A named parameter holding a mutable numpy array value.
44 Parameters are used in risk models to store matrices and vectors
45 (such as Cholesky factors, factor exposures, and bounds) that can
46 be updated between solver calls without rebuilding the problem structure.
48 Attributes:
49 shape: The shape of the parameter. Use an integer for 1-D parameters
50 and a tuple for 2-D parameters.
51 name: A human-readable name for the parameter.
52 value: The numpy array holding the current parameter value.
54 Example:
55 1-D parameter (e.g., lower bounds):
57 >>> import numpy as np
58 >>> from cvx.core.parameter import Parameter
59 >>> p = Parameter(shape=4, name="lower_assets")
60 >>> p.value.shape
61 (4,)
62 >>> p.value = np.array([0.0, 0.1, 0.0, 0.2])
63 >>> p.value[1]
64 np.float64(0.1)
66 2-D parameter (e.g., Cholesky factor):
68 >>> p2 = Parameter(shape=(3, 3), name="chol")
69 >>> p2.value.shape
70 (3, 3)
71 >>> import numpy as np
72 >>> p2.value = np.eye(3)
73 >>> p2.value[0, 0]
74 np.float64(1.0)
76 """
78 shape: int | tuple[int, ...]
79 """Shape of the parameter (int for 1-D, tuple for 2-D)."""
81 name: str = ""
82 """Human-readable name for the parameter."""
84 value: np.ndarray = field(init=False)
85 """Current value of the parameter as a numpy array."""
87 def __post_init__(self) -> None:
88 """Initialise the value array to zeros."""
89 self.value = np.zeros(self.shape)