Coverage for src/cvx/core/parameter.py: 100%

13 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-07-22 10:34 +0000

1# Copyright (c) 2025 Jebel Quant Research 

2# 

3# Licensed under the MIT License. See the LICENSE file in the project root 

4# for the full license text. 

5"""Parameter class for risk models. 

6 

7This module provides a simple parameter class that stores a named numpy array 

8value that can be updated without reconstructing the optimization problem. 

9 

10Example: 

11 Create a parameter and update its value: 

12 

13 >>> import numpy as np 

14 >>> from cvx.core.parameter import Parameter 

15 >>> p = Parameter(shape=3, name="weights") 

16 >>> p.value 

17 array([0., 0., 0.]) 

18 >>> p.value = np.array([0.5, 0.3, 0.2]) 

19 >>> p.value 

20 array([0.5, 0.3, 0.2]) 

21 

22""" 

23 

24from __future__ import annotations 

25 

26from dataclasses import dataclass, field 

27 

28import numpy as np 

29 

30 

31@dataclass 

32class Parameter: 

33 """A named parameter holding a mutable numpy array value. 

34 

35 Parameters are used in risk models to store matrices and vectors 

36 (such as Cholesky factors, factor exposures, and bounds) that can 

37 be updated between solver calls without rebuilding the problem structure. 

38 

39 Attributes: 

40 shape: The shape of the parameter. Use an integer for 1-D parameters 

41 and a tuple for 2-D parameters. 

42 name: A human-readable name for the parameter. 

43 value: The numpy array holding the current parameter value. 

44 

45 Example: 

46 1-D parameter (e.g., lower bounds): 

47 

48 >>> import numpy as np 

49 >>> from cvx.core.parameter import Parameter 

50 >>> p = Parameter(shape=4, name="lower_assets") 

51 >>> p.value.shape 

52 (4,) 

53 >>> p.value = np.array([0.0, 0.1, 0.0, 0.2]) 

54 >>> p.value[1] 

55 np.float64(0.1) 

56 

57 2-D parameter (e.g., Cholesky factor): 

58 

59 >>> p2 = Parameter(shape=(3, 3), name="chol") 

60 >>> p2.value.shape 

61 (3, 3) 

62 >>> import numpy as np 

63 >>> p2.value = np.eye(3) 

64 >>> p2.value[0, 0] 

65 np.float64(1.0) 

66 

67 """ 

68 

69 shape: int | tuple[int, ...] 

70 """Shape of the parameter (int for 1-D, tuple for 2-D).""" 

71 

72 name: str = "" 

73 """Human-readable name for the parameter.""" 

74 

75 value: np.ndarray = field(init=False) 

76 """Current value of the parameter as a numpy array.""" 

77 

78 def __post_init__(self) -> None: 

79 """Initialise the value array to zeros.""" 

80 self.value = np.zeros(self.shape)