pytmpinv 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pytmpinv-1.0.0/LICENSE +7 -0
- pytmpinv-1.0.0/PKG-INFO +167 -0
- pytmpinv-1.0.0/README.md +144 -0
- pytmpinv-1.0.0/pyproject.toml +42 -0
- pytmpinv-1.0.0/pytmpinv.egg-info/PKG-INFO +167 -0
- pytmpinv-1.0.0/pytmpinv.egg-info/SOURCES.txt +10 -0
- pytmpinv-1.0.0/pytmpinv.egg-info/dependency_links.txt +1 -0
- pytmpinv-1.0.0/pytmpinv.egg-info/requires.txt +2 -0
- pytmpinv-1.0.0/pytmpinv.egg-info/top_level.txt +1 -0
- pytmpinv-1.0.0/setup.cfg +4 -0
- pytmpinv-1.0.0/tmpinv/__init__.py +8 -0
- pytmpinv-1.0.0/tmpinv/tmpinv.py +310 -0
pytmpinv-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2021 econcz
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
pytmpinv-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytmpinv
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Tabular Matrix Problems via Pseudoinverse Estimation
|
|
5
|
+
Author-email: The Economist <29724411+econcz@users.noreply.github.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/econcz/pytmpinv
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/econcz/pytmpinv/issues
|
|
9
|
+
Keywords: tabular-matrix-problems,convex-optimization,least-squares,generalized-inverse,regularization
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: numpy>=1.24
|
|
21
|
+
Requires-Dist: pyclsp>=1.1.2
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Tabular Matrix Problems via Pseudoinverse Estimation
|
|
25
|
+
|
|
26
|
+
The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-stage estimation method that reformulates structured table-based systems — such as allocation problems, transaction matrices, and input–output tables — as structured least-squares problems. Based on the [Convex Least Squares Programming (CLSP)](https://pypi.org/project/pyclsp/ "Convex Least Squares Programming") framework, TMPinv solves systems with row and column constraints, block structure, and optionally reduced dimensionality by (1) constructing a canonical constraint form and applying a pseudoinverse-based projection, followed by (2) a convex-programming refinement stage to improve fit, coherence, and regularization (e.g., via Lasso, Ridge, or Elastic Net).
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install tmpinv
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Example
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import numpy as np
|
|
38
|
+
from tmpinv import tmpinv
|
|
39
|
+
|
|
40
|
+
# Define a 10×10 matrix with consistent row and column sums
|
|
41
|
+
X_true = np.array([
|
|
42
|
+
[ 0, 4, 6, 8, 7, 10, 9, 5, 6, 13],
|
|
43
|
+
[ 6, 0, 9, 6, 5, 4, 13, 10, 8, 8],
|
|
44
|
+
[ 7, 10, 0, 12, 11, 5, 4, 3, 10, 10],
|
|
45
|
+
[11, 12, 5, 0, 12, 13, 4, 2, 4, 10],
|
|
46
|
+
[13, 5, 11, 11, 0, 3, 11, 6, 12, 5],
|
|
47
|
+
[ 4, 12, 13, 4, 11, 0, 3, 3, 4, 10],
|
|
48
|
+
[ 6, 9, 4, 13, 4, 13, 0, 12, 3, 11],
|
|
49
|
+
[10, 6, 11, 5, 12, 4, 10, 0, 13, 4],
|
|
50
|
+
[12, 13, 5, 14, 4, 11, 4, 13, 0, 9],
|
|
51
|
+
[ 5, 6, 12, 12, 10, 3, 13, 4, 11, 0]
|
|
52
|
+
], dtype=np.float64)
|
|
53
|
+
|
|
54
|
+
# Get row and column sums
|
|
55
|
+
b_row = X_true.sum(axis=1)
|
|
56
|
+
b_col = X_true.sum(axis=0)
|
|
57
|
+
|
|
58
|
+
# Get known values
|
|
59
|
+
M = np.eye(100)[[1, 2, 3, 4, 5]]
|
|
60
|
+
b_val = X_true[0, [1, 2, 3, 4, 5]]
|
|
61
|
+
|
|
62
|
+
# Run bounded tmpinv
|
|
63
|
+
result = tmpinv(
|
|
64
|
+
M=M,
|
|
65
|
+
b_row=b_row,
|
|
66
|
+
b_col=b_col,
|
|
67
|
+
b_val=b_val,
|
|
68
|
+
zero_diagonal=True,
|
|
69
|
+
bounds=(0, 15),
|
|
70
|
+
replace_value=0
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# Reshape result and display checks
|
|
74
|
+
print("Estimated matrix:\n", np.round(result.x, 2))
|
|
75
|
+
print("\nRow sums: ", np.round(result.x.sum(axis=1), 2))
|
|
76
|
+
print("Column sums:", np.round(result.x.sum(axis=0), 2))
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## User Reference
|
|
80
|
+
|
|
81
|
+
For comprehensive information on the estimator’s capabilities, advanced configuration options, and implementation details, please refer to the [pyclsp module](https://pypi.org/project/pyclsp/ "Convex Least Squares Programming"), on which TMPinv is based.
|
|
82
|
+
|
|
83
|
+
**TMPINV Parameters:**
|
|
84
|
+
|
|
85
|
+
`S` : *array_like* of shape *(m + p, m + p)*, optional
|
|
86
|
+
A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
|
|
87
|
+
- *0* enforces equality (== `b_row` or `b_col`),
|
|
88
|
+
- *1* enforces a lower-than-or-equal (≤) condition,
|
|
89
|
+
- *–1* enforces a greater-than-or-equal (≥) condition.
|
|
90
|
+
|
|
91
|
+
The first `m` diagonal entries correspond to row constraints, and the remaining `p` to column constraints. Please note that, in the reduced model, `S` is ignored: slack behavior is derived implicitly from block-wise marginal totals.
|
|
92
|
+
|
|
93
|
+
`M` : *array_like* of shape *(k, m * p)*, optional
|
|
94
|
+
A model matrix with entries in *{0, 1}*. Each row defines a linear restriction on the flattened solution matrix. The corresponding right-hand side values must be provided in `b_val`. This block is used to encode known cell values. Please note that, in the reduced model, `M` must be a row subset of an identity matrix (i.e., diagonal-only). Arbitrary or non-diagonal model matrices cannot be mapped to reduced blocks, making the model infeasible.
|
|
95
|
+
|
|
96
|
+
`b_row` : *array_like* of shape *(m,)*
|
|
97
|
+
Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
|
|
98
|
+
|
|
99
|
+
`b_col` : *array_like* of shape *(p,)*
|
|
100
|
+
Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
|
|
101
|
+
|
|
102
|
+
`b_val` : *array_like* of shape *(k,)*
|
|
103
|
+
Right-hand side vector of known cell values.
|
|
104
|
+
|
|
105
|
+
`i` : *int*, default = *1*
|
|
106
|
+
Number of row groups.
|
|
107
|
+
|
|
108
|
+
`j` : *int*, default = *1*
|
|
109
|
+
Number of column groups.
|
|
110
|
+
|
|
111
|
+
`zero_diagonal` : *bool*, default = *False*
|
|
112
|
+
If *True*, enforces the zero diagonal.
|
|
113
|
+
|
|
114
|
+
`reduced` : *tuple* of *(int, int)*, optional
|
|
115
|
+
Dimensions of the reduced problem. If specified, the problem is estimated as a set of reduced problems constructed from contiguous submatrices of the original table. For example, `reduced` = *(6, 6)* implies *5×5* data blocks with *1* slack row and *1* slack column each (edge blocks may be smaller).
|
|
116
|
+
|
|
117
|
+
`bounds` : *sequence* of *(low, high)*, optional
|
|
118
|
+
Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
|
|
119
|
+
|
|
120
|
+
`replace_value` : *float* or *None*, default = *np.nan*
|
|
121
|
+
Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
|
|
122
|
+
|
|
123
|
+
`tolerance` : *float*, default = *square root of machine epsilon*
|
|
124
|
+
Convergence tolerance for bounds.
|
|
125
|
+
|
|
126
|
+
`iteration_limit` : *int*, default = *50*
|
|
127
|
+
Maximum number of iterations allowed in the refinement loop.
|
|
128
|
+
|
|
129
|
+
**CLSP Parameters:**
|
|
130
|
+
|
|
131
|
+
`r` : *int*, default = *1*
|
|
132
|
+
Number of refinement iterations for the pseudoinverse-based estimator.
|
|
133
|
+
|
|
134
|
+
`Z` : *np.ndarray* or *None*
|
|
135
|
+
A symmetric idempotent matrix (projector) defining the subspace for Bott–Duffin pseudoinversion. If *None*, the identity matrix is used, reducing the Bott–Duffin inverse to the Moore–Penrose case.
|
|
136
|
+
|
|
137
|
+
`final` : *bool*, default = *True*
|
|
138
|
+
If *True*, a convex programming problem is solved to refine `zhat`. The resulting solution `z` minimizes a weighted L1/L2 norm around `zhat` subject to `Az = b`.
|
|
139
|
+
|
|
140
|
+
`alpha` : *float*, default = *1.0*
|
|
141
|
+
Regularization parameter (weight) in the final convex program:
|
|
142
|
+
- `α = 0`: Lasso (L1 norm)
|
|
143
|
+
- `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
|
|
144
|
+
- `0 < α < 1`: Elastic Net
|
|
145
|
+
|
|
146
|
+
`*args`, `**kwargs` : optional
|
|
147
|
+
CVXPY arguments passed to the CVXPY solver.
|
|
148
|
+
|
|
149
|
+
**Returns:**
|
|
150
|
+
*TMPinvResult*
|
|
151
|
+
|
|
152
|
+
`TMPinvResult.full` : *bool*
|
|
153
|
+
Indicates if this result comes from the full (non-reduced) model.
|
|
154
|
+
|
|
155
|
+
`TMPinvResult.model` : *CLSP* or *list* of *CLSP*
|
|
156
|
+
A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
|
|
157
|
+
|
|
158
|
+
`TMPinvResult.x` : *np.ndarray*
|
|
159
|
+
Final estimated solution matrix of shape *(m, p)*.
|
|
160
|
+
|
|
161
|
+
## Bibliography
|
|
162
|
+
|
|
163
|
+
To be added.
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
MIT License — see the [LICENSE](LICENSE) file.
|
pytmpinv-1.0.0/README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# Tabular Matrix Problems via Pseudoinverse Estimation
|
|
2
|
+
|
|
3
|
+
The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-stage estimation method that reformulates structured table-based systems — such as allocation problems, transaction matrices, and input–output tables — as structured least-squares problems. Based on the [Convex Least Squares Programming (CLSP)](https://pypi.org/project/pyclsp/ "Convex Least Squares Programming") framework, TMPinv solves systems with row and column constraints, block structure, and optionally reduced dimensionality by (1) constructing a canonical constraint form and applying a pseudoinverse-based projection, followed by (2) a convex-programming refinement stage to improve fit, coherence, and regularization (e.g., via Lasso, Ridge, or Elastic Net).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install tmpinv
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Example
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import numpy as np
|
|
15
|
+
from tmpinv import tmpinv
|
|
16
|
+
|
|
17
|
+
# Define a 10×10 matrix with consistent row and column sums
|
|
18
|
+
X_true = np.array([
|
|
19
|
+
[ 0, 4, 6, 8, 7, 10, 9, 5, 6, 13],
|
|
20
|
+
[ 6, 0, 9, 6, 5, 4, 13, 10, 8, 8],
|
|
21
|
+
[ 7, 10, 0, 12, 11, 5, 4, 3, 10, 10],
|
|
22
|
+
[11, 12, 5, 0, 12, 13, 4, 2, 4, 10],
|
|
23
|
+
[13, 5, 11, 11, 0, 3, 11, 6, 12, 5],
|
|
24
|
+
[ 4, 12, 13, 4, 11, 0, 3, 3, 4, 10],
|
|
25
|
+
[ 6, 9, 4, 13, 4, 13, 0, 12, 3, 11],
|
|
26
|
+
[10, 6, 11, 5, 12, 4, 10, 0, 13, 4],
|
|
27
|
+
[12, 13, 5, 14, 4, 11, 4, 13, 0, 9],
|
|
28
|
+
[ 5, 6, 12, 12, 10, 3, 13, 4, 11, 0]
|
|
29
|
+
], dtype=np.float64)
|
|
30
|
+
|
|
31
|
+
# Get row and column sums
|
|
32
|
+
b_row = X_true.sum(axis=1)
|
|
33
|
+
b_col = X_true.sum(axis=0)
|
|
34
|
+
|
|
35
|
+
# Get known values
|
|
36
|
+
M = np.eye(100)[[1, 2, 3, 4, 5]]
|
|
37
|
+
b_val = X_true[0, [1, 2, 3, 4, 5]]
|
|
38
|
+
|
|
39
|
+
# Run bounded tmpinv
|
|
40
|
+
result = tmpinv(
|
|
41
|
+
M=M,
|
|
42
|
+
b_row=b_row,
|
|
43
|
+
b_col=b_col,
|
|
44
|
+
b_val=b_val,
|
|
45
|
+
zero_diagonal=True,
|
|
46
|
+
bounds=(0, 15),
|
|
47
|
+
replace_value=0
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Reshape result and display checks
|
|
51
|
+
print("Estimated matrix:\n", np.round(result.x, 2))
|
|
52
|
+
print("\nRow sums: ", np.round(result.x.sum(axis=1), 2))
|
|
53
|
+
print("Column sums:", np.round(result.x.sum(axis=0), 2))
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## User Reference
|
|
57
|
+
|
|
58
|
+
For comprehensive information on the estimator’s capabilities, advanced configuration options, and implementation details, please refer to the [pyclsp module](https://pypi.org/project/pyclsp/ "Convex Least Squares Programming"), on which TMPinv is based.
|
|
59
|
+
|
|
60
|
+
**TMPINV Parameters:**
|
|
61
|
+
|
|
62
|
+
`S` : *array_like* of shape *(m + p, m + p)*, optional
|
|
63
|
+
A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
|
|
64
|
+
- *0* enforces equality (== `b_row` or `b_col`),
|
|
65
|
+
- *1* enforces a lower-than-or-equal (≤) condition,
|
|
66
|
+
- *–1* enforces a greater-than-or-equal (≥) condition.
|
|
67
|
+
|
|
68
|
+
The first `m` diagonal entries correspond to row constraints, and the remaining `p` to column constraints. Please note that, in the reduced model, `S` is ignored: slack behavior is derived implicitly from block-wise marginal totals.
|
|
69
|
+
|
|
70
|
+
`M` : *array_like* of shape *(k, m * p)*, optional
|
|
71
|
+
A model matrix with entries in *{0, 1}*. Each row defines a linear restriction on the flattened solution matrix. The corresponding right-hand side values must be provided in `b_val`. This block is used to encode known cell values. Please note that, in the reduced model, `M` must be a row subset of an identity matrix (i.e., diagonal-only). Arbitrary or non-diagonal model matrices cannot be mapped to reduced blocks, making the model infeasible.
|
|
72
|
+
|
|
73
|
+
`b_row` : *array_like* of shape *(m,)*
|
|
74
|
+
Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
|
|
75
|
+
|
|
76
|
+
`b_col` : *array_like* of shape *(p,)*
|
|
77
|
+
Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
|
|
78
|
+
|
|
79
|
+
`b_val` : *array_like* of shape *(k,)*
|
|
80
|
+
Right-hand side vector of known cell values.
|
|
81
|
+
|
|
82
|
+
`i` : *int*, default = *1*
|
|
83
|
+
Number of row groups.
|
|
84
|
+
|
|
85
|
+
`j` : *int*, default = *1*
|
|
86
|
+
Number of column groups.
|
|
87
|
+
|
|
88
|
+
`zero_diagonal` : *bool*, default = *False*
|
|
89
|
+
If *True*, enforces the zero diagonal.
|
|
90
|
+
|
|
91
|
+
`reduced` : *tuple* of *(int, int)*, optional
|
|
92
|
+
Dimensions of the reduced problem. If specified, the problem is estimated as a set of reduced problems constructed from contiguous submatrices of the original table. For example, `reduced` = *(6, 6)* implies *5×5* data blocks with *1* slack row and *1* slack column each (edge blocks may be smaller).
|
|
93
|
+
|
|
94
|
+
`bounds` : *sequence* of *(low, high)*, optional
|
|
95
|
+
Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
|
|
96
|
+
|
|
97
|
+
`replace_value` : *float* or *None*, default = *np.nan*
|
|
98
|
+
Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
|
|
99
|
+
|
|
100
|
+
`tolerance` : *float*, default = *square root of machine epsilon*
|
|
101
|
+
Convergence tolerance for bounds.
|
|
102
|
+
|
|
103
|
+
`iteration_limit` : *int*, default = *50*
|
|
104
|
+
Maximum number of iterations allowed in the refinement loop.
|
|
105
|
+
|
|
106
|
+
**CLSP Parameters:**
|
|
107
|
+
|
|
108
|
+
`r` : *int*, default = *1*
|
|
109
|
+
Number of refinement iterations for the pseudoinverse-based estimator.
|
|
110
|
+
|
|
111
|
+
`Z` : *np.ndarray* or *None*
|
|
112
|
+
A symmetric idempotent matrix (projector) defining the subspace for Bott–Duffin pseudoinversion. If *None*, the identity matrix is used, reducing the Bott–Duffin inverse to the Moore–Penrose case.
|
|
113
|
+
|
|
114
|
+
`final` : *bool*, default = *True*
|
|
115
|
+
If *True*, a convex programming problem is solved to refine `zhat`. The resulting solution `z` minimizes a weighted L1/L2 norm around `zhat` subject to `Az = b`.
|
|
116
|
+
|
|
117
|
+
`alpha` : *float*, default = *1.0*
|
|
118
|
+
Regularization parameter (weight) in the final convex program:
|
|
119
|
+
- `α = 0`: Lasso (L1 norm)
|
|
120
|
+
- `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
|
|
121
|
+
- `0 < α < 1`: Elastic Net
|
|
122
|
+
|
|
123
|
+
`*args`, `**kwargs` : optional
|
|
124
|
+
CVXPY arguments passed to the CVXPY solver.
|
|
125
|
+
|
|
126
|
+
**Returns:**
|
|
127
|
+
*TMPinvResult*
|
|
128
|
+
|
|
129
|
+
`TMPinvResult.full` : *bool*
|
|
130
|
+
Indicates if this result comes from the full (non-reduced) model.
|
|
131
|
+
|
|
132
|
+
`TMPinvResult.model` : *CLSP* or *list* of *CLSP*
|
|
133
|
+
A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
|
|
134
|
+
|
|
135
|
+
`TMPinvResult.x` : *np.ndarray*
|
|
136
|
+
Final estimated solution matrix of shape *(m, p)*.
|
|
137
|
+
|
|
138
|
+
## Bibliography
|
|
139
|
+
|
|
140
|
+
To be added.
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
MIT License — see the [LICENSE](LICENSE) file.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pytmpinv"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Tabular Matrix Problems via Pseudoinverse Estimation"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [
|
|
10
|
+
{ name = "The Economist", email = "29724411+econcz@users.noreply.github.com" }
|
|
11
|
+
]
|
|
12
|
+
keywords = [
|
|
13
|
+
"tabular-matrix-problems",
|
|
14
|
+
"convex-optimization",
|
|
15
|
+
"least-squares",
|
|
16
|
+
"generalized-inverse",
|
|
17
|
+
"regularization"
|
|
18
|
+
]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Operating System :: OS Independent",
|
|
25
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
26
|
+
"Topic :: Scientific/Engineering :: Information Analysis"
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"numpy>=1.24",
|
|
30
|
+
"pyclsp>=1.1.2"
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://github.com/econcz/pytmpinv"
|
|
35
|
+
"Bug Tracker" = "https://github.com/econcz/pytmpinv/issues"
|
|
36
|
+
|
|
37
|
+
[build-system]
|
|
38
|
+
requires = ["setuptools>=77", "wheel"]
|
|
39
|
+
build-backend = "setuptools.build_meta"
|
|
40
|
+
|
|
41
|
+
[tool.setuptools]
|
|
42
|
+
packages = ["tmpinv"]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytmpinv
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Tabular Matrix Problems via Pseudoinverse Estimation
|
|
5
|
+
Author-email: The Economist <29724411+econcz@users.noreply.github.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/econcz/pytmpinv
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/econcz/pytmpinv/issues
|
|
9
|
+
Keywords: tabular-matrix-problems,convex-optimization,least-squares,generalized-inverse,regularization
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: numpy>=1.24
|
|
21
|
+
Requires-Dist: pyclsp>=1.1.2
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Tabular Matrix Problems via Pseudoinverse Estimation
|
|
25
|
+
|
|
26
|
+
The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-stage estimation method that reformulates structured table-based systems — such as allocation problems, transaction matrices, and input–output tables — as structured least-squares problems. Based on the [Convex Least Squares Programming (CLSP)](https://pypi.org/project/pyclsp/ "Convex Least Squares Programming") framework, TMPinv solves systems with row and column constraints, block structure, and optionally reduced dimensionality by (1) constructing a canonical constraint form and applying a pseudoinverse-based projection, followed by (2) a convex-programming refinement stage to improve fit, coherence, and regularization (e.g., via Lasso, Ridge, or Elastic Net).
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install tmpinv
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Example
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import numpy as np
|
|
38
|
+
from tmpinv import tmpinv
|
|
39
|
+
|
|
40
|
+
# Define a 10×10 matrix with consistent row and column sums
|
|
41
|
+
X_true = np.array([
|
|
42
|
+
[ 0, 4, 6, 8, 7, 10, 9, 5, 6, 13],
|
|
43
|
+
[ 6, 0, 9, 6, 5, 4, 13, 10, 8, 8],
|
|
44
|
+
[ 7, 10, 0, 12, 11, 5, 4, 3, 10, 10],
|
|
45
|
+
[11, 12, 5, 0, 12, 13, 4, 2, 4, 10],
|
|
46
|
+
[13, 5, 11, 11, 0, 3, 11, 6, 12, 5],
|
|
47
|
+
[ 4, 12, 13, 4, 11, 0, 3, 3, 4, 10],
|
|
48
|
+
[ 6, 9, 4, 13, 4, 13, 0, 12, 3, 11],
|
|
49
|
+
[10, 6, 11, 5, 12, 4, 10, 0, 13, 4],
|
|
50
|
+
[12, 13, 5, 14, 4, 11, 4, 13, 0, 9],
|
|
51
|
+
[ 5, 6, 12, 12, 10, 3, 13, 4, 11, 0]
|
|
52
|
+
], dtype=np.float64)
|
|
53
|
+
|
|
54
|
+
# Get row and column sums
|
|
55
|
+
b_row = X_true.sum(axis=1)
|
|
56
|
+
b_col = X_true.sum(axis=0)
|
|
57
|
+
|
|
58
|
+
# Get known values
|
|
59
|
+
M = np.eye(100)[[1, 2, 3, 4, 5]]
|
|
60
|
+
b_val = X_true[0, [1, 2, 3, 4, 5]]
|
|
61
|
+
|
|
62
|
+
# Run bounded tmpinv
|
|
63
|
+
result = tmpinv(
|
|
64
|
+
M=M,
|
|
65
|
+
b_row=b_row,
|
|
66
|
+
b_col=b_col,
|
|
67
|
+
b_val=b_val,
|
|
68
|
+
zero_diagonal=True,
|
|
69
|
+
bounds=(0, 15),
|
|
70
|
+
replace_value=0
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# Reshape result and display checks
|
|
74
|
+
print("Estimated matrix:\n", np.round(result.x, 2))
|
|
75
|
+
print("\nRow sums: ", np.round(result.x.sum(axis=1), 2))
|
|
76
|
+
print("Column sums:", np.round(result.x.sum(axis=0), 2))
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## User Reference
|
|
80
|
+
|
|
81
|
+
For comprehensive information on the estimator’s capabilities, advanced configuration options, and implementation details, please refer to the [pyclsp module](https://pypi.org/project/pyclsp/ "Convex Least Squares Programming"), on which TMPinv is based.
|
|
82
|
+
|
|
83
|
+
**TMPINV Parameters:**
|
|
84
|
+
|
|
85
|
+
`S` : *array_like* of shape *(m + p, m + p)*, optional
|
|
86
|
+
A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
|
|
87
|
+
- *0* enforces equality (== `b_row` or `b_col`),
|
|
88
|
+
- *1* enforces a lower-than-or-equal (≤) condition,
|
|
89
|
+
- *–1* enforces a greater-than-or-equal (≥) condition.
|
|
90
|
+
|
|
91
|
+
The first `m` diagonal entries correspond to row constraints, and the remaining `p` to column constraints. Please note that, in the reduced model, `S` is ignored: slack behavior is derived implicitly from block-wise marginal totals.
|
|
92
|
+
|
|
93
|
+
`M` : *array_like* of shape *(k, m * p)*, optional
|
|
94
|
+
A model matrix with entries in *{0, 1}*. Each row defines a linear restriction on the flattened solution matrix. The corresponding right-hand side values must be provided in `b_val`. This block is used to encode known cell values. Please note that, in the reduced model, `M` must be a row subset of an identity matrix (i.e., diagonal-only). Arbitrary or non-diagonal model matrices cannot be mapped to reduced blocks, making the model infeasible.
|
|
95
|
+
|
|
96
|
+
`b_row` : *array_like* of shape *(m,)*
|
|
97
|
+
Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
|
|
98
|
+
|
|
99
|
+
`b_col` : *array_like* of shape *(p,)*
|
|
100
|
+
Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
|
|
101
|
+
|
|
102
|
+
`b_val` : *array_like* of shape *(k,)*
|
|
103
|
+
Right-hand side vector of known cell values.
|
|
104
|
+
|
|
105
|
+
`i` : *int*, default = *1*
|
|
106
|
+
Number of row groups.
|
|
107
|
+
|
|
108
|
+
`j` : *int*, default = *1*
|
|
109
|
+
Number of column groups.
|
|
110
|
+
|
|
111
|
+
`zero_diagonal` : *bool*, default = *False*
|
|
112
|
+
If *True*, enforces the zero diagonal.
|
|
113
|
+
|
|
114
|
+
`reduced` : *tuple* of *(int, int)*, optional
|
|
115
|
+
Dimensions of the reduced problem. If specified, the problem is estimated as a set of reduced problems constructed from contiguous submatrices of the original table. For example, `reduced` = *(6, 6)* implies *5×5* data blocks with *1* slack row and *1* slack column each (edge blocks may be smaller).
|
|
116
|
+
|
|
117
|
+
`bounds` : *sequence* of *(low, high)*, optional
|
|
118
|
+
Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
|
|
119
|
+
|
|
120
|
+
`replace_value` : *float* or *None*, default = *np.nan*
|
|
121
|
+
Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
|
|
122
|
+
|
|
123
|
+
`tolerance` : *float*, default = *square root of machine epsilon*
|
|
124
|
+
Convergence tolerance for bounds.
|
|
125
|
+
|
|
126
|
+
`iteration_limit` : *int*, default = *50*
|
|
127
|
+
Maximum number of iterations allowed in the refinement loop.
|
|
128
|
+
|
|
129
|
+
**CLSP Parameters:**
|
|
130
|
+
|
|
131
|
+
`r` : *int*, default = *1*
|
|
132
|
+
Number of refinement iterations for the pseudoinverse-based estimator.
|
|
133
|
+
|
|
134
|
+
`Z` : *np.ndarray* or *None*
|
|
135
|
+
A symmetric idempotent matrix (projector) defining the subspace for Bott–Duffin pseudoinversion. If *None*, the identity matrix is used, reducing the Bott–Duffin inverse to the Moore–Penrose case.
|
|
136
|
+
|
|
137
|
+
`final` : *bool*, default = *True*
|
|
138
|
+
If *True*, a convex programming problem is solved to refine `zhat`. The resulting solution `z` minimizes a weighted L1/L2 norm around `zhat` subject to `Az = b`.
|
|
139
|
+
|
|
140
|
+
`alpha` : *float*, default = *1.0*
|
|
141
|
+
Regularization parameter (weight) in the final convex program:
|
|
142
|
+
- `α = 0`: Lasso (L1 norm)
|
|
143
|
+
- `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
|
|
144
|
+
- `0 < α < 1`: Elastic Net
|
|
145
|
+
|
|
146
|
+
`*args`, `**kwargs` : optional
|
|
147
|
+
CVXPY arguments passed to the CVXPY solver.
|
|
148
|
+
|
|
149
|
+
**Returns:**
|
|
150
|
+
*TMPinvResult*
|
|
151
|
+
|
|
152
|
+
`TMPinvResult.full` : *bool*
|
|
153
|
+
Indicates if this result comes from the full (non-reduced) model.
|
|
154
|
+
|
|
155
|
+
`TMPinvResult.model` : *CLSP* or *list* of *CLSP*
|
|
156
|
+
A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
|
|
157
|
+
|
|
158
|
+
`TMPinvResult.x` : *np.ndarray*
|
|
159
|
+
Final estimated solution matrix of shape *(m, p)*.
|
|
160
|
+
|
|
161
|
+
## Bibliography
|
|
162
|
+
|
|
163
|
+
To be added.
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
MIT License — see the [LICENSE](LICENSE) file.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tmpinv
|
pytmpinv-1.0.0/setup.cfg
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from math import ceil
|
|
3
|
+
from typing import Sequence
|
|
4
|
+
from collections.abc import Sequence as sq
|
|
5
|
+
from clsp import CLSP
|
|
6
|
+
|
|
7
|
+
class TMPinvInputError(Exception):
|
|
8
|
+
"""
|
|
9
|
+
Exception class for TMPinv-related input errors.
|
|
10
|
+
|
|
11
|
+
Represents internal failures in Tabular Matrix Problems via Pseudoinverse
|
|
12
|
+
Estimation routines due to malformed or missing input. Supports structured
|
|
13
|
+
messaging and optional diagnostic augmentation.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
message : str, optional
|
|
18
|
+
Description of the error. Defaults to a generic TMPinv message.
|
|
19
|
+
|
|
20
|
+
code : int or str, optional
|
|
21
|
+
Optional error code or identifier for downstream handling.
|
|
22
|
+
|
|
23
|
+
Attributes
|
|
24
|
+
----------
|
|
25
|
+
message : str
|
|
26
|
+
Human-readable error message.
|
|
27
|
+
|
|
28
|
+
code : int or str
|
|
29
|
+
Optional error code for custom handling or debugging.
|
|
30
|
+
|
|
31
|
+
Usage
|
|
32
|
+
-----
|
|
33
|
+
raise TMPinvInputError("Both b_row and b_col must be provided", code=201)
|
|
34
|
+
"""
|
|
35
|
+
def __init__(self, message: str = "An error occurred in TMPinv",
|
|
36
|
+
code: int | str | None = None):
|
|
37
|
+
self.message = message
|
|
38
|
+
self.code = code
|
|
39
|
+
full_message = f"{message} (Code: {code})" if code is not None \
|
|
40
|
+
else message
|
|
41
|
+
super().__init__(full_message)
|
|
42
|
+
|
|
43
|
+
def __str__(self) -> str:
|
|
44
|
+
return self.message if self.code is None \
|
|
45
|
+
else f"{self.message} [Code: {self.code}]"
|
|
46
|
+
|
|
47
|
+
def as_dict(self) -> dict:
|
|
48
|
+
"""
|
|
49
|
+
Return the error as a dictionary for structured logging or JSON output.
|
|
50
|
+
"""
|
|
51
|
+
return {"error": self.message, "code": self.code}
|
|
52
|
+
|
|
53
|
+
class TMPinvResult:
|
|
54
|
+
"""
|
|
55
|
+
Result container for TMPinv estimation.
|
|
56
|
+
|
|
57
|
+
Attributes
|
|
58
|
+
----------
|
|
59
|
+
full : bool
|
|
60
|
+
Indicates if this result comes from the full (non-reduced) model.
|
|
61
|
+
|
|
62
|
+
model : CLSP or list of CLSP
|
|
63
|
+
A single CLSP object in the full model, or a list of CLSP objects
|
|
64
|
+
for each reduced block in the reduced model.
|
|
65
|
+
|
|
66
|
+
x : np.ndarray
|
|
67
|
+
Final estimated solution matrix of shape (m, p).
|
|
68
|
+
"""
|
|
69
|
+
def __init__(self, full: bool, model, x: np.ndarray):
|
|
70
|
+
self.full = full
|
|
71
|
+
self.model = model
|
|
72
|
+
self.x = x
|
|
73
|
+
|
|
74
|
+
def TMPinvSolve(
|
|
75
|
+
S: Sequence[Sequence[float]] | None = None,
|
|
76
|
+
M: Sequence[Sequence[float]] | None = None,
|
|
77
|
+
b_row: Sequence[float] | None = None,
|
|
78
|
+
b_col: Sequence[float] | None = None,
|
|
79
|
+
b_val: Sequence[float] | None = None,
|
|
80
|
+
i: int = 1,
|
|
81
|
+
j: int = 1,
|
|
82
|
+
zero_diagonal: bool = False,
|
|
83
|
+
reduced: tuple[int, int] | None = None,
|
|
84
|
+
*args, **kwargs
|
|
85
|
+
) -> TMPinvResult:
|
|
86
|
+
"""
|
|
87
|
+
Solve a tabular matrix estimation problem via Convex Least Squares
|
|
88
|
+
Programming (CLSP).
|
|
89
|
+
|
|
90
|
+
Parameters
|
|
91
|
+
----------
|
|
92
|
+
S : array_like of shape (m + p, m + p), optional
|
|
93
|
+
A diagonal sign slack (surplus) matrix with entries in {0, ±1}.
|
|
94
|
+
- 0 enforces equality (== b_row or b_col),
|
|
95
|
+
- 1 enforces a lower-than-or-equal (≤) condition,
|
|
96
|
+
- –1 enforces a greater-than-or-equal (≥) condition.
|
|
97
|
+
The first `m` diagonal entries correspond to row constraints,
|
|
98
|
+
and the remaining `p` to column constraints.
|
|
99
|
+
M : array_like of shape (k, m * p), optional
|
|
100
|
+
A model matrix with entries in {0, 1}. Each row defines a linear
|
|
101
|
+
restriction on the flattened solution matrix. The corresponding
|
|
102
|
+
right-hand side values must be provided in `b_val`. This block is
|
|
103
|
+
used to encode known cell values.
|
|
104
|
+
b_row : array_like of shape (m,)
|
|
105
|
+
Right-hand side vector of row totals.
|
|
106
|
+
b_col : array_like of shape (p,)
|
|
107
|
+
Right-hand side vector of column totals.
|
|
108
|
+
b_val : array_like of shape (k,)
|
|
109
|
+
Right-hand side vector of known cell values.
|
|
110
|
+
i : int, default = 1
|
|
111
|
+
Number of row groups.
|
|
112
|
+
j : int, default = 1
|
|
113
|
+
Number of column groups.
|
|
114
|
+
zero_diagonal : bool, default = False
|
|
115
|
+
If True, enforces the zero diagonal.
|
|
116
|
+
reduced : tuple of (int, int), optional
|
|
117
|
+
Dimensions of the reduced problem.
|
|
118
|
+
If specified, the problem is estimated as a set of reduced problems
|
|
119
|
+
constructed from contiguous submatrices of the original table.
|
|
120
|
+
For example, reduced = (6, 6) implies 5×5 data blocks with 1 slack
|
|
121
|
+
row and 1 slack column each (edge blocks may be smaller).
|
|
122
|
+
|
|
123
|
+
Returns
|
|
124
|
+
-------
|
|
125
|
+
TMPinvResult
|
|
126
|
+
An object containing the fitted CLSP model(s) and the solution
|
|
127
|
+
matrix `x`.
|
|
128
|
+
|
|
129
|
+
Notes
|
|
130
|
+
----
|
|
131
|
+
In the reduced model, `S` is ignored. Slack behavior is derived implicitly
|
|
132
|
+
from block-wise marginal totals. Likewise, `M` must be a row subset of an
|
|
133
|
+
identity matrix (i.e., diagonal-only). Arbitrary or non-diagonal model
|
|
134
|
+
matrices cannot be mapped to reduced blocks, making the model infeasible.
|
|
135
|
+
"""
|
|
136
|
+
# (m), (p) Process the parameters, assert conformity, and get dimensions
|
|
137
|
+
if b_row is None or b_col is None:
|
|
138
|
+
raise TMPinvInputError("Both b_row and b_col must be provided.")
|
|
139
|
+
if len(b_row) < 2 or len(b_col) < 2:
|
|
140
|
+
raise TMPinvInputError("Minimum length for b_row and b_col is 2.")
|
|
141
|
+
if not np.isfinite(b_row).all() or not np.isfinite(b_col).all():
|
|
142
|
+
raise TMPinvInputError("b_row and b_col must not contain inf or NaN.")
|
|
143
|
+
b_row = np.asarray(b_row, dtype=np.float64).reshape(-1, 1)
|
|
144
|
+
b_col = np.asarray(b_col, dtype=np.float64).reshape(-1, 1)
|
|
145
|
+
m = b_row.shape[0]
|
|
146
|
+
p = b_col.shape[0]
|
|
147
|
+
if M is not None:
|
|
148
|
+
M = np.asarray(M, dtype=np.float64)
|
|
149
|
+
if M.ndim == 1:
|
|
150
|
+
M = M.reshape(1, -1)
|
|
151
|
+
if M.shape[1] != m * p:
|
|
152
|
+
raise TMPinvInputError(f"M must have exactly {m * p} columns.")
|
|
153
|
+
if b_val is not None:
|
|
154
|
+
if not np.isfinite(b_val).all():
|
|
155
|
+
raise TMPinvInputError("b_val must not contain inf or NaN.")
|
|
156
|
+
b_val = np.asarray(b_val, dtype=np.float64).reshape(-1, 1)
|
|
157
|
+
if M is not None and b_val is not None:
|
|
158
|
+
if M.shape[0] != b_val.shape[0]:
|
|
159
|
+
raise TMPinvInputError(f"M and b_val must have the same number "
|
|
160
|
+
f"of rows: "
|
|
161
|
+
f"{M.shape[0]} vs {b_val.shape[0]}")
|
|
162
|
+
|
|
163
|
+
# perform full estimation and return the result
|
|
164
|
+
if reduced is None:
|
|
165
|
+
result = TMPinvResult(True, None, np.empty((m, p), dtype=float))
|
|
166
|
+
b_blocks = [b_row, b_col]
|
|
167
|
+
if b_val is not None:
|
|
168
|
+
b_blocks.append(b_val)
|
|
169
|
+
b = np.vstack(b_blocks)
|
|
170
|
+
result.model = CLSP().solve(problem='ap', b=b, S=S, M=M,
|
|
171
|
+
m=m,
|
|
172
|
+
p=p,
|
|
173
|
+
i=i,
|
|
174
|
+
j=j,
|
|
175
|
+
zero_diagonal=zero_diagonal,
|
|
176
|
+
*args, **kwargs)
|
|
177
|
+
result.x = result.model.x
|
|
178
|
+
|
|
179
|
+
# perform reduced estimation and return the result
|
|
180
|
+
else:
|
|
181
|
+
if reduced[0] < 3 or reduced[1] < 3:
|
|
182
|
+
raise TMPinvInputError("Each reduced block must be at least "
|
|
183
|
+
"(3, 3) to allow a solvable CLSP submatrix "
|
|
184
|
+
"with a slack (surplus) structure.")
|
|
185
|
+
result = TMPinvResult(False, [], np.empty((m, p), dtype=float))
|
|
186
|
+
m_subset = reduced[0] - 1
|
|
187
|
+
p_subset = reduced[1] - 1
|
|
188
|
+
if M is not None:
|
|
189
|
+
if not all(np.count_nonzero(row) == 1 and
|
|
190
|
+
np.all((row == 0) | (row == 1)) for row in M):
|
|
191
|
+
raise TMPinvInputError("M must be a row subset of the identity "
|
|
192
|
+
"matrix in the reduced model.")
|
|
193
|
+
M = (np.abs(np.sign(M)) * b_val).sum(axis=0).reshape(m, p)
|
|
194
|
+
for row_block in range(ceil(m / m_subset)):
|
|
195
|
+
for col_block in range(ceil(p / p_subset)):
|
|
196
|
+
m_start = row_block * m_subset
|
|
197
|
+
m_end = min(m_start + m_subset, m)
|
|
198
|
+
p_start = col_block * p_subset
|
|
199
|
+
p_end = min(p_start + p_subset, p)
|
|
200
|
+
S = np.ones(((m_end - m_start) + (p_end - p_start), 1))
|
|
201
|
+
b_blocks = [b_row[m_start:m_end].reshape(-1, 1),
|
|
202
|
+
b_col[p_start:p_end].reshape(-1, 1)]
|
|
203
|
+
M_subset, b_val_subset = None, None
|
|
204
|
+
if M is not None:
|
|
205
|
+
M_subset = np.diag(np.sign(M[m_start:m_end,
|
|
206
|
+
p_start:p_end]).flatten())
|
|
207
|
+
b_val_subset = M[m_start:m_end,
|
|
208
|
+
p_start:p_end].reshape(-1, 1)
|
|
209
|
+
if np.any(M_subset): # drop zero rows
|
|
210
|
+
nonzero_rows = np.diag(M_subset) != 0
|
|
211
|
+
M_subset = M_subset[nonzero_rows]
|
|
212
|
+
b_val_subset = b_val_subset[nonzero_rows].reshape(-1, 1)
|
|
213
|
+
b_blocks.append(b_val_subset)
|
|
214
|
+
else:
|
|
215
|
+
M_subset, b_val_subset = None, None
|
|
216
|
+
b = np.vstack(b_blocks)
|
|
217
|
+
tmp = CLSP().solve(problem='ap', b=b, S=S, M=M_subset,
|
|
218
|
+
m=m_end - m_start,
|
|
219
|
+
p=p_end - p_start,
|
|
220
|
+
i=i,
|
|
221
|
+
j=j,
|
|
222
|
+
zero_diagonal=False,
|
|
223
|
+
*args, **kwargs)
|
|
224
|
+
result.model.append(tmp)
|
|
225
|
+
result.x[m_start:m_end, p_start:p_end] = tmp.x
|
|
226
|
+
|
|
227
|
+
return result
|
|
228
|
+
|
|
229
|
+
def tmpinv(
|
|
230
|
+
bounds: list[tuple[float | None, float | None]] | \
|
|
231
|
+
tuple[float | None, float | None] | None = None,
|
|
232
|
+
replace_value: float | None = np.nan,
|
|
233
|
+
tolerance: float = np.sqrt(np.finfo(float).eps),
|
|
234
|
+
iteration_limit: int = 50,
|
|
235
|
+
*args, **kwargs
|
|
236
|
+
) -> TMPinvResult:
|
|
237
|
+
"""
|
|
238
|
+
Solve a tabular matrix estimation problem via Convex Least Squares
|
|
239
|
+
Programming (CLSP) with bound-constrained iterative refinement.
|
|
240
|
+
|
|
241
|
+
Parameters
|
|
242
|
+
----------
|
|
243
|
+
bounds : sequence of (low, high), optional
|
|
244
|
+
Bounds on cell values. If a single tuple (low, high) is given, it
|
|
245
|
+
is applied to all m * p cells. Example: (0, None).
|
|
246
|
+
replace_value : float or None, default = np.nan
|
|
247
|
+
Final replacement value for any cell in the solution matrix that
|
|
248
|
+
violates the specified bounds by more than the given tolerance.
|
|
249
|
+
tolerance : float, optional
|
|
250
|
+
Convergence tolerance for bounds. Default is the square root of
|
|
251
|
+
machine epsilon.
|
|
252
|
+
iteration_limit : int, default = 50
|
|
253
|
+
Maximum number of iterations allowed in the refinement loop.
|
|
254
|
+
*args, **kwargs : additional arguments
|
|
255
|
+
Passed directly to TMPinvSolver().
|
|
256
|
+
|
|
257
|
+
Returns
|
|
258
|
+
-------
|
|
259
|
+
TMPinvResult
|
|
260
|
+
An object containing the fitted CLSP model(s) and the solution
|
|
261
|
+
matrix `x`.
|
|
262
|
+
"""
|
|
263
|
+
# (n_cells) Perform initial estimation and get cell count
|
|
264
|
+
result = TMPinvSolve(*args, **kwargs)
|
|
265
|
+
n_cells = result.x.shape[0] * result.x.shape[1]
|
|
266
|
+
if bounds is None:
|
|
267
|
+
bounds = (None, None)
|
|
268
|
+
if isinstance(bounds, tuple):
|
|
269
|
+
bounds = [bounds] * n_cells # replicate (low, high)
|
|
270
|
+
elif isinstance(bounds, sq): # normalize bounds
|
|
271
|
+
if len(bounds) > 1 and len(bounds) != n_cells:
|
|
272
|
+
raise TMPinvInputError(f"Bounds length {len(bounds)} does not "
|
|
273
|
+
f"match number of variables {n_cells}.")
|
|
274
|
+
elif len(bounds) == 1:
|
|
275
|
+
bounds = bounds * n_cells # replicate (low, high)
|
|
276
|
+
if all(l is None and h is None for l, h in bounds):
|
|
277
|
+
return result # finish if unbounded
|
|
278
|
+
if any((l is not None and l < 0) or
|
|
279
|
+
(h is not None and h < 0) for l, h in bounds):
|
|
280
|
+
raise TMPinvInputError("Negative lower or upper bounds are not "
|
|
281
|
+
"allowed in tabular matrix programs.")
|
|
282
|
+
|
|
283
|
+
# (result) Perform bound-constrained iterative refinement
|
|
284
|
+
for _ in range(iteration_limit):
|
|
285
|
+
M_idx, b_val = [], []
|
|
286
|
+
x = result.x.reshape(-1, 1)
|
|
287
|
+
for i, (v, (l, h)) in enumerate(zip(x, bounds)):
|
|
288
|
+
if ((l is not None and v < l - tolerance) or \
|
|
289
|
+
(h is not None and v > h + tolerance)):
|
|
290
|
+
continue # skip out-of-bounds
|
|
291
|
+
M_idx.append(i)
|
|
292
|
+
b_val.append(float(v.item()))
|
|
293
|
+
if len(M_idx) < n_cells:
|
|
294
|
+
M = np.eye(n_cells, dtype=np.float64)[M_idx]
|
|
295
|
+
result = TMPinvSolve(M=M, b_val=b_val,
|
|
296
|
+
*args, **{k: v for k, v in kwargs.items()
|
|
297
|
+
if k not in {"M", "b_val"}})
|
|
298
|
+
else:
|
|
299
|
+
break
|
|
300
|
+
|
|
301
|
+
# (result) Replace out-of-bound values with `replace_value`
|
|
302
|
+
x = result.x.reshape(-1, 1)
|
|
303
|
+
x_lb = np.array([l if l is not None else -np.inf
|
|
304
|
+
for l, _ in bounds]).reshape(-1, 1)
|
|
305
|
+
x_ub = np.array([h if h is not None else np.inf
|
|
306
|
+
for _, h in bounds]).reshape(-1, 1)
|
|
307
|
+
x[(x < x_lb - tolerance) | (x > x_ub + tolerance)] = replace_value
|
|
308
|
+
result.x = x.reshape(result.x.shape)
|
|
309
|
+
|
|
310
|
+
return result
|