pytmpinv 1.0.3__tar.gz → 1.1.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.
Potentially problematic release.
This version of pytmpinv might be problematic. Click here for more details.
- pytmpinv-1.1.0/PKG-INFO +275 -0
- pytmpinv-1.1.0/README.md +252 -0
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/pyproject.toml +1 -1
- pytmpinv-1.1.0/pytmpinv.egg-info/PKG-INFO +275 -0
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/tmpinv/__init__.py +1 -1
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/tmpinv/tmpinv.py +23 -1
- pytmpinv-1.0.3/PKG-INFO +0 -170
- pytmpinv-1.0.3/README.md +0 -147
- pytmpinv-1.0.3/pytmpinv.egg-info/PKG-INFO +0 -170
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/LICENSE +0 -0
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/pytmpinv.egg-info/SOURCES.txt +0 -0
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/pytmpinv.egg-info/dependency_links.txt +0 -0
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/pytmpinv.egg-info/requires.txt +0 -0
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/pytmpinv.egg-info/top_level.txt +0 -0
- {pytmpinv-1.0.3 → pytmpinv-1.1.0}/setup.cfg +0 -0
pytmpinv-1.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytmpinv
|
|
3
|
+
Version: 1.1.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). All calculations are performed in numpy.float64 precision.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install tmpinv
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Example 1
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import numpy as np
|
|
38
|
+
from tmpinv import tmpinv
|
|
39
|
+
import matplotlib.pyplot as plt
|
|
40
|
+
|
|
41
|
+
# AP (TM), based on a symmetric input-output table, with 10% of known values
|
|
42
|
+
|
|
43
|
+
seed = 123456789
|
|
44
|
+
rng = np.random.default_rng(seed)
|
|
45
|
+
|
|
46
|
+
# sample (dataset)
|
|
47
|
+
m, p = 20, 20 # matrix dimensions (m x p)
|
|
48
|
+
X_true = np.abs(rng.normal(size=(m, p))) # symmetric non-negative X_true
|
|
49
|
+
X_true = (X_true + X_true.T) / 2.0
|
|
50
|
+
idx = rng.choice(m * p, size=max(1, int(0.1 * (m * p))), # random numbers from
|
|
51
|
+
replace=False) # [0,(m * p) - 1], 10% of total
|
|
52
|
+
|
|
53
|
+
# model
|
|
54
|
+
M = np.eye(m * p)[idx,:] # unit matrix
|
|
55
|
+
b_row = X_true.sum(axis=1) # row sums (length m)
|
|
56
|
+
b_col = X_true.sum(axis=0) # column sums (length p)
|
|
57
|
+
b_val = X_true.reshape(-1, 1)[idx] # column vector
|
|
58
|
+
bounds = (0, None) # non-negativity
|
|
59
|
+
result = tmpinv(
|
|
60
|
+
M=M, b_row=b_row, b_col=b_col, b_val=b_val,
|
|
61
|
+
m=m, p=p, bounds=bounds, symmetric=True,
|
|
62
|
+
r=1, # a solution without refinement
|
|
63
|
+
alpha=1.0 # a unique MNBLUE estimator
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# helpers
|
|
67
|
+
def fmt(v):
|
|
68
|
+
v = float(v)
|
|
69
|
+
return f"{v:.4e}" if abs(v) >= 1e6 or (v != 0 and abs(v) < 1e-4) else f"{v:.6f}"
|
|
70
|
+
|
|
71
|
+
# results
|
|
72
|
+
print("true X:")
|
|
73
|
+
print(np.round(np.asarray(X_true), 4))
|
|
74
|
+
print("X_hat:")
|
|
75
|
+
print(np.round(result.x, 4))
|
|
76
|
+
|
|
77
|
+
print("\nNumerical stability:")
|
|
78
|
+
print(" kappaC :", fmt(result.model.kappaC))
|
|
79
|
+
print(" kappaB :", fmt(result.model.kappaB))
|
|
80
|
+
print(" kappaA :", fmt(result.model.kappaA))
|
|
81
|
+
corr = result.model.corr()
|
|
82
|
+
plt.figure(figsize=(8, 4))
|
|
83
|
+
plt.grid(True, linestyle="--", alpha=0.6)
|
|
84
|
+
plt.bar(range(len(corr["rmsa_i"])), corr["rmsa_i"])
|
|
85
|
+
plt.xlabel("Constraint index")
|
|
86
|
+
plt.ylabel("dRMSA (row deletion effect)")
|
|
87
|
+
plt.title(f"CLSP Correlogram (Total RMSA = {result.model.rmsa:.2f})")
|
|
88
|
+
plt.tight_layout()
|
|
89
|
+
plt.show()
|
|
90
|
+
|
|
91
|
+
print("\nGoodness-of-fit:")
|
|
92
|
+
x_true = X_true.flatten()
|
|
93
|
+
x_hat = result.x.flatten()
|
|
94
|
+
ss_res = np.sum((x_true - x_hat) ** 2)
|
|
95
|
+
ss_tot = np.sum((x_true - np.mean(x_true)) ** 2)
|
|
96
|
+
print(" R2_user_defined :", fmt(1 - ss_res / ss_tot))
|
|
97
|
+
print(" NRMSE :", fmt(result.model.nrmse))
|
|
98
|
+
print(" Diagnostic band (min):", fmt(np.min(result.model.x_lower)))
|
|
99
|
+
print(" Diagnostic band (max):", fmt(np.max(result.model.x_upper)))
|
|
100
|
+
print(" Monte Carlo t-test:")
|
|
101
|
+
for kw, val in result.model.ttest(sample_size=30, # NRMSE_partial sample
|
|
102
|
+
seed=seed, distribution="normal", # seed and distribution
|
|
103
|
+
partial=True).items():
|
|
104
|
+
print(f" {kw}: {float(val):.6f}")
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Quick Example 2
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
import numpy as np
|
|
111
|
+
from tmpinv import tmpinv
|
|
112
|
+
|
|
113
|
+
# AP (TM), based on a trade matrix, with a zero diagonal and 20% of known values
|
|
114
|
+
|
|
115
|
+
seed = 123456789
|
|
116
|
+
rng = np.random.default_rng(seed)
|
|
117
|
+
|
|
118
|
+
# sample (dataset)
|
|
119
|
+
m, p = 40, 40 # matrix dimensions (m x p)
|
|
120
|
+
X_true = np.abs(rng.normal(size=(m, p))) # non-negative X_true
|
|
121
|
+
idx = rng.choice(m * p, size=max(1, int(0.2 * (m * p))), # random numbers from
|
|
122
|
+
replace=False) # [0,(m * p) - 1], 20% of total
|
|
123
|
+
|
|
124
|
+
# model
|
|
125
|
+
M = np.eye(m * p)[idx,:] # unit matrix
|
|
126
|
+
b_row = X_true.sum(axis=1) # row sums (length m)
|
|
127
|
+
b_col = X_true.sum(axis=0) # column sums (length p)
|
|
128
|
+
b_val = X_true.reshape(-1, 1)[idx] # column vector
|
|
129
|
+
bounds = (0, None) # non-negativity
|
|
130
|
+
result = tmpinv(
|
|
131
|
+
M=M, b_row=b_row, b_col=b_col, b_val=b_val,
|
|
132
|
+
m=m, p=p, zero_diagonal=True, reduced=(10,10), # reduced models of (10, 10)
|
|
133
|
+
bounds=bounds,
|
|
134
|
+
r=1, # a solution without refinement
|
|
135
|
+
alpha=1.0 # a unique MNBLUE estimator
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# helpers
|
|
139
|
+
def fmt(v):
|
|
140
|
+
v = float(v)
|
|
141
|
+
return f"{v:.4e}" if abs(v) >= 1e6 or (v != 0 and abs(v) < 1e-4) else f"{v:.6f}"
|
|
142
|
+
|
|
143
|
+
# results
|
|
144
|
+
print("true X:")
|
|
145
|
+
print(np.round(np.asarray(X_true), 4))
|
|
146
|
+
print("X_hat:")
|
|
147
|
+
print(np.round(result.x, 4))
|
|
148
|
+
|
|
149
|
+
print("\nNumerical stability (min-max across models):")
|
|
150
|
+
kappaC = np.array([CLSP.kappaC for CLSP in result.model])
|
|
151
|
+
kappaB = np.array([CLSP.kappaB for CLSP in result.model])
|
|
152
|
+
kappaA = np.array([CLSP.kappaA for CLSP in result.model])
|
|
153
|
+
print(" kappaC :", fmt(np.min(kappaC)), "-", fmt(np.max(kappaC)))
|
|
154
|
+
print(" kappaB :", fmt(np.min(kappaB)), "-", fmt(np.max(kappaB)))
|
|
155
|
+
print(" kappaA :", fmt(np.min(kappaA)), "-", fmt(np.max(kappaA)))
|
|
156
|
+
|
|
157
|
+
print("\nGoodness-of-fit (min-max across models):")
|
|
158
|
+
x_true = X_true.flatten()
|
|
159
|
+
x_hat = result.x.flatten()
|
|
160
|
+
mask = np.isfinite(x_true) & np.isfinite(x_hat)
|
|
161
|
+
if mask.any():
|
|
162
|
+
ss_res = np.sum((x_true[mask] - x_hat[mask])**2)
|
|
163
|
+
ss_tot = np.sum((x_true[mask] - np.mean(x_true[mask]))**2)
|
|
164
|
+
nrmse = np.array( [CLSP.nrmse for CLSP in result.model])
|
|
165
|
+
x_lower = np.concatenate([np.array(CLSP.x_lower).reshape(-1) for CLSP in result.model])
|
|
166
|
+
x_upper = np.concatenate([np.array(CLSP.x_upper).reshape(-1) for CLSP in result.model])
|
|
167
|
+
print(" R2_user_defined :", fmt(1 - ss_res / ss_tot ))
|
|
168
|
+
print(" NRMSE :", fmt(np.min(nrmse)), "-", fmt(np.max(nrmse) ))
|
|
169
|
+
print(" Diagnostic band (min):", fmt(np.min(x_lower)), "-", fmt(np.max(x_lower) ))
|
|
170
|
+
print(" Diagnostic band (max):", fmt(np.min(x_upper)), "-", fmt(np.max(x_upper) ))
|
|
171
|
+
print(" Monte Carlo t-test:")
|
|
172
|
+
ttests = [CLSP.ttest(sample_size=30, seed=seed,
|
|
173
|
+
distribution="normal", partial=True) for CLSP in result.model]
|
|
174
|
+
keys = ttests[0].keys()
|
|
175
|
+
for kw in keys:
|
|
176
|
+
val = np.array([t[kw] for t in ttests], dtype=float)
|
|
177
|
+
print(f" {kw}: {fmt(np.min(val))} - {fmt(np.max(val))}")
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## User Reference
|
|
181
|
+
|
|
182
|
+
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.
|
|
183
|
+
|
|
184
|
+
**TMPINV Parameters:**
|
|
185
|
+
|
|
186
|
+
`S` : *array_like* of shape *(m + p, m + p)*, optional
|
|
187
|
+
A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
|
|
188
|
+
- *0* enforces equality (== `b_row` or `b_col`),
|
|
189
|
+
- *1* enforces a lower-than-or-equal (≤) condition,
|
|
190
|
+
- *–1* enforces a greater-than-or-equal (≥) condition.
|
|
191
|
+
|
|
192
|
+
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.
|
|
193
|
+
|
|
194
|
+
`M` : *array_like* of shape *(k, m * p)*, optional
|
|
195
|
+
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.
|
|
196
|
+
|
|
197
|
+
`b_row` : *array_like* of shape *(m,)*
|
|
198
|
+
Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
|
|
199
|
+
|
|
200
|
+
`b_col` : *array_like* of shape *(p,)*
|
|
201
|
+
Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
|
|
202
|
+
|
|
203
|
+
`b_val` : *array_like* of shape *(k,)*
|
|
204
|
+
Right-hand side vector of known cell values.
|
|
205
|
+
|
|
206
|
+
`i` : *int*, default = *1*
|
|
207
|
+
Number of row groups.
|
|
208
|
+
|
|
209
|
+
`j` : *int*, default = *1*
|
|
210
|
+
Number of column groups.
|
|
211
|
+
|
|
212
|
+
`zero_diagonal` : *bool*, default = *False*
|
|
213
|
+
If *True*, enforces the zero diagonal.
|
|
214
|
+
|
|
215
|
+
`reduced` : *tuple* of *(int, int)*, optional
|
|
216
|
+
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).
|
|
217
|
+
|
|
218
|
+
`symmetric` : *bool*, default = *False*
|
|
219
|
+
If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
|
|
220
|
+
Applies to TMPinvResult.x only. For TMPinvResult.model symmetry, add explicit symmetry constraints to M in a full-model solve instead of using this flag.
|
|
221
|
+
|
|
222
|
+
`bounds` : *sequence* of *(low, high)*, optional
|
|
223
|
+
Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
|
|
224
|
+
|
|
225
|
+
`replace_value` : *float* or *None*, default = *np.nan*
|
|
226
|
+
Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
|
|
227
|
+
|
|
228
|
+
`tolerance` : *float*, default = *square root of machine epsilon*
|
|
229
|
+
Convergence tolerance for bounds.
|
|
230
|
+
|
|
231
|
+
`iteration_limit` : *int*, default = *50*
|
|
232
|
+
Maximum number of iterations allowed in the refinement loop.
|
|
233
|
+
|
|
234
|
+
**CLSP Parameters:**
|
|
235
|
+
|
|
236
|
+
`r` : *int*, default = *1*
|
|
237
|
+
Number of refinement iterations for the pseudoinverse-based estimator.
|
|
238
|
+
|
|
239
|
+
`Z` : *np.ndarray* or *None*
|
|
240
|
+
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.
|
|
241
|
+
|
|
242
|
+
`final` : *bool*, default = *True*
|
|
243
|
+
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`.
|
|
244
|
+
|
|
245
|
+
`alpha` : *float*, *list[float]* or *None*, default = *None*
|
|
246
|
+
Regularization parameter (weight) in the final convex program:
|
|
247
|
+
- `α = 0`: Lasso (L1 norm)
|
|
248
|
+
- `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
|
|
249
|
+
- `0 < α < 1`: Elastic Net
|
|
250
|
+
If a scalar float is provided, that value is used after clipping to [0, 1].
|
|
251
|
+
If a list/iterable of floats is provided, each candidate is evaluated via a full solve, and the α with the smallest NRMSE is selected.
|
|
252
|
+
If None, α is chosen, based on an error rule: α = min(1.0, NRMSE_{α = 0} / (NRMSE_{α = 0} + NRMSE_{α = 1} + tolerance))
|
|
253
|
+
|
|
254
|
+
`*args`, `**kwargs` : optional
|
|
255
|
+
CVXPY arguments passed to the CVXPY solver.
|
|
256
|
+
|
|
257
|
+
**Returns:**
|
|
258
|
+
*TMPinvResult*
|
|
259
|
+
|
|
260
|
+
`TMPinvResult.full` : *bool*
|
|
261
|
+
Indicates if this result comes from the full (non-reduced) model.
|
|
262
|
+
|
|
263
|
+
`TMPinvResult.model` : *CLSP* or *list* of *CLSP*
|
|
264
|
+
A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
|
|
265
|
+
|
|
266
|
+
`TMPinvResult.x` : *np.ndarray*
|
|
267
|
+
Final estimated solution matrix of shape *(m, p)*.
|
|
268
|
+
|
|
269
|
+
## Bibliography
|
|
270
|
+
|
|
271
|
+
To be added.
|
|
272
|
+
|
|
273
|
+
## License
|
|
274
|
+
|
|
275
|
+
MIT License — see the [LICENSE](LICENSE) file.
|
pytmpinv-1.1.0/README.md
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
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). All calculations are performed in numpy.float64 precision.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install tmpinv
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Example 1
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import numpy as np
|
|
15
|
+
from tmpinv import tmpinv
|
|
16
|
+
import matplotlib.pyplot as plt
|
|
17
|
+
|
|
18
|
+
# AP (TM), based on a symmetric input-output table, with 10% of known values
|
|
19
|
+
|
|
20
|
+
seed = 123456789
|
|
21
|
+
rng = np.random.default_rng(seed)
|
|
22
|
+
|
|
23
|
+
# sample (dataset)
|
|
24
|
+
m, p = 20, 20 # matrix dimensions (m x p)
|
|
25
|
+
X_true = np.abs(rng.normal(size=(m, p))) # symmetric non-negative X_true
|
|
26
|
+
X_true = (X_true + X_true.T) / 2.0
|
|
27
|
+
idx = rng.choice(m * p, size=max(1, int(0.1 * (m * p))), # random numbers from
|
|
28
|
+
replace=False) # [0,(m * p) - 1], 10% of total
|
|
29
|
+
|
|
30
|
+
# model
|
|
31
|
+
M = np.eye(m * p)[idx,:] # unit matrix
|
|
32
|
+
b_row = X_true.sum(axis=1) # row sums (length m)
|
|
33
|
+
b_col = X_true.sum(axis=0) # column sums (length p)
|
|
34
|
+
b_val = X_true.reshape(-1, 1)[idx] # column vector
|
|
35
|
+
bounds = (0, None) # non-negativity
|
|
36
|
+
result = tmpinv(
|
|
37
|
+
M=M, b_row=b_row, b_col=b_col, b_val=b_val,
|
|
38
|
+
m=m, p=p, bounds=bounds, symmetric=True,
|
|
39
|
+
r=1, # a solution without refinement
|
|
40
|
+
alpha=1.0 # a unique MNBLUE estimator
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# helpers
|
|
44
|
+
def fmt(v):
|
|
45
|
+
v = float(v)
|
|
46
|
+
return f"{v:.4e}" if abs(v) >= 1e6 or (v != 0 and abs(v) < 1e-4) else f"{v:.6f}"
|
|
47
|
+
|
|
48
|
+
# results
|
|
49
|
+
print("true X:")
|
|
50
|
+
print(np.round(np.asarray(X_true), 4))
|
|
51
|
+
print("X_hat:")
|
|
52
|
+
print(np.round(result.x, 4))
|
|
53
|
+
|
|
54
|
+
print("\nNumerical stability:")
|
|
55
|
+
print(" kappaC :", fmt(result.model.kappaC))
|
|
56
|
+
print(" kappaB :", fmt(result.model.kappaB))
|
|
57
|
+
print(" kappaA :", fmt(result.model.kappaA))
|
|
58
|
+
corr = result.model.corr()
|
|
59
|
+
plt.figure(figsize=(8, 4))
|
|
60
|
+
plt.grid(True, linestyle="--", alpha=0.6)
|
|
61
|
+
plt.bar(range(len(corr["rmsa_i"])), corr["rmsa_i"])
|
|
62
|
+
plt.xlabel("Constraint index")
|
|
63
|
+
plt.ylabel("dRMSA (row deletion effect)")
|
|
64
|
+
plt.title(f"CLSP Correlogram (Total RMSA = {result.model.rmsa:.2f})")
|
|
65
|
+
plt.tight_layout()
|
|
66
|
+
plt.show()
|
|
67
|
+
|
|
68
|
+
print("\nGoodness-of-fit:")
|
|
69
|
+
x_true = X_true.flatten()
|
|
70
|
+
x_hat = result.x.flatten()
|
|
71
|
+
ss_res = np.sum((x_true - x_hat) ** 2)
|
|
72
|
+
ss_tot = np.sum((x_true - np.mean(x_true)) ** 2)
|
|
73
|
+
print(" R2_user_defined :", fmt(1 - ss_res / ss_tot))
|
|
74
|
+
print(" NRMSE :", fmt(result.model.nrmse))
|
|
75
|
+
print(" Diagnostic band (min):", fmt(np.min(result.model.x_lower)))
|
|
76
|
+
print(" Diagnostic band (max):", fmt(np.max(result.model.x_upper)))
|
|
77
|
+
print(" Monte Carlo t-test:")
|
|
78
|
+
for kw, val in result.model.ttest(sample_size=30, # NRMSE_partial sample
|
|
79
|
+
seed=seed, distribution="normal", # seed and distribution
|
|
80
|
+
partial=True).items():
|
|
81
|
+
print(f" {kw}: {float(val):.6f}")
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Quick Example 2
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import numpy as np
|
|
88
|
+
from tmpinv import tmpinv
|
|
89
|
+
|
|
90
|
+
# AP (TM), based on a trade matrix, with a zero diagonal and 20% of known values
|
|
91
|
+
|
|
92
|
+
seed = 123456789
|
|
93
|
+
rng = np.random.default_rng(seed)
|
|
94
|
+
|
|
95
|
+
# sample (dataset)
|
|
96
|
+
m, p = 40, 40 # matrix dimensions (m x p)
|
|
97
|
+
X_true = np.abs(rng.normal(size=(m, p))) # non-negative X_true
|
|
98
|
+
idx = rng.choice(m * p, size=max(1, int(0.2 * (m * p))), # random numbers from
|
|
99
|
+
replace=False) # [0,(m * p) - 1], 20% of total
|
|
100
|
+
|
|
101
|
+
# model
|
|
102
|
+
M = np.eye(m * p)[idx,:] # unit matrix
|
|
103
|
+
b_row = X_true.sum(axis=1) # row sums (length m)
|
|
104
|
+
b_col = X_true.sum(axis=0) # column sums (length p)
|
|
105
|
+
b_val = X_true.reshape(-1, 1)[idx] # column vector
|
|
106
|
+
bounds = (0, None) # non-negativity
|
|
107
|
+
result = tmpinv(
|
|
108
|
+
M=M, b_row=b_row, b_col=b_col, b_val=b_val,
|
|
109
|
+
m=m, p=p, zero_diagonal=True, reduced=(10,10), # reduced models of (10, 10)
|
|
110
|
+
bounds=bounds,
|
|
111
|
+
r=1, # a solution without refinement
|
|
112
|
+
alpha=1.0 # a unique MNBLUE estimator
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
# helpers
|
|
116
|
+
def fmt(v):
|
|
117
|
+
v = float(v)
|
|
118
|
+
return f"{v:.4e}" if abs(v) >= 1e6 or (v != 0 and abs(v) < 1e-4) else f"{v:.6f}"
|
|
119
|
+
|
|
120
|
+
# results
|
|
121
|
+
print("true X:")
|
|
122
|
+
print(np.round(np.asarray(X_true), 4))
|
|
123
|
+
print("X_hat:")
|
|
124
|
+
print(np.round(result.x, 4))
|
|
125
|
+
|
|
126
|
+
print("\nNumerical stability (min-max across models):")
|
|
127
|
+
kappaC = np.array([CLSP.kappaC for CLSP in result.model])
|
|
128
|
+
kappaB = np.array([CLSP.kappaB for CLSP in result.model])
|
|
129
|
+
kappaA = np.array([CLSP.kappaA for CLSP in result.model])
|
|
130
|
+
print(" kappaC :", fmt(np.min(kappaC)), "-", fmt(np.max(kappaC)))
|
|
131
|
+
print(" kappaB :", fmt(np.min(kappaB)), "-", fmt(np.max(kappaB)))
|
|
132
|
+
print(" kappaA :", fmt(np.min(kappaA)), "-", fmt(np.max(kappaA)))
|
|
133
|
+
|
|
134
|
+
print("\nGoodness-of-fit (min-max across models):")
|
|
135
|
+
x_true = X_true.flatten()
|
|
136
|
+
x_hat = result.x.flatten()
|
|
137
|
+
mask = np.isfinite(x_true) & np.isfinite(x_hat)
|
|
138
|
+
if mask.any():
|
|
139
|
+
ss_res = np.sum((x_true[mask] - x_hat[mask])**2)
|
|
140
|
+
ss_tot = np.sum((x_true[mask] - np.mean(x_true[mask]))**2)
|
|
141
|
+
nrmse = np.array( [CLSP.nrmse for CLSP in result.model])
|
|
142
|
+
x_lower = np.concatenate([np.array(CLSP.x_lower).reshape(-1) for CLSP in result.model])
|
|
143
|
+
x_upper = np.concatenate([np.array(CLSP.x_upper).reshape(-1) for CLSP in result.model])
|
|
144
|
+
print(" R2_user_defined :", fmt(1 - ss_res / ss_tot ))
|
|
145
|
+
print(" NRMSE :", fmt(np.min(nrmse)), "-", fmt(np.max(nrmse) ))
|
|
146
|
+
print(" Diagnostic band (min):", fmt(np.min(x_lower)), "-", fmt(np.max(x_lower) ))
|
|
147
|
+
print(" Diagnostic band (max):", fmt(np.min(x_upper)), "-", fmt(np.max(x_upper) ))
|
|
148
|
+
print(" Monte Carlo t-test:")
|
|
149
|
+
ttests = [CLSP.ttest(sample_size=30, seed=seed,
|
|
150
|
+
distribution="normal", partial=True) for CLSP in result.model]
|
|
151
|
+
keys = ttests[0].keys()
|
|
152
|
+
for kw in keys:
|
|
153
|
+
val = np.array([t[kw] for t in ttests], dtype=float)
|
|
154
|
+
print(f" {kw}: {fmt(np.min(val))} - {fmt(np.max(val))}")
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## User Reference
|
|
158
|
+
|
|
159
|
+
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.
|
|
160
|
+
|
|
161
|
+
**TMPINV Parameters:**
|
|
162
|
+
|
|
163
|
+
`S` : *array_like* of shape *(m + p, m + p)*, optional
|
|
164
|
+
A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
|
|
165
|
+
- *0* enforces equality (== `b_row` or `b_col`),
|
|
166
|
+
- *1* enforces a lower-than-or-equal (≤) condition,
|
|
167
|
+
- *–1* enforces a greater-than-or-equal (≥) condition.
|
|
168
|
+
|
|
169
|
+
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.
|
|
170
|
+
|
|
171
|
+
`M` : *array_like* of shape *(k, m * p)*, optional
|
|
172
|
+
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.
|
|
173
|
+
|
|
174
|
+
`b_row` : *array_like* of shape *(m,)*
|
|
175
|
+
Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
|
|
176
|
+
|
|
177
|
+
`b_col` : *array_like* of shape *(p,)*
|
|
178
|
+
Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
|
|
179
|
+
|
|
180
|
+
`b_val` : *array_like* of shape *(k,)*
|
|
181
|
+
Right-hand side vector of known cell values.
|
|
182
|
+
|
|
183
|
+
`i` : *int*, default = *1*
|
|
184
|
+
Number of row groups.
|
|
185
|
+
|
|
186
|
+
`j` : *int*, default = *1*
|
|
187
|
+
Number of column groups.
|
|
188
|
+
|
|
189
|
+
`zero_diagonal` : *bool*, default = *False*
|
|
190
|
+
If *True*, enforces the zero diagonal.
|
|
191
|
+
|
|
192
|
+
`reduced` : *tuple* of *(int, int)*, optional
|
|
193
|
+
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).
|
|
194
|
+
|
|
195
|
+
`symmetric` : *bool*, default = *False*
|
|
196
|
+
If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
|
|
197
|
+
Applies to TMPinvResult.x only. For TMPinvResult.model symmetry, add explicit symmetry constraints to M in a full-model solve instead of using this flag.
|
|
198
|
+
|
|
199
|
+
`bounds` : *sequence* of *(low, high)*, optional
|
|
200
|
+
Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
|
|
201
|
+
|
|
202
|
+
`replace_value` : *float* or *None*, default = *np.nan*
|
|
203
|
+
Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
|
|
204
|
+
|
|
205
|
+
`tolerance` : *float*, default = *square root of machine epsilon*
|
|
206
|
+
Convergence tolerance for bounds.
|
|
207
|
+
|
|
208
|
+
`iteration_limit` : *int*, default = *50*
|
|
209
|
+
Maximum number of iterations allowed in the refinement loop.
|
|
210
|
+
|
|
211
|
+
**CLSP Parameters:**
|
|
212
|
+
|
|
213
|
+
`r` : *int*, default = *1*
|
|
214
|
+
Number of refinement iterations for the pseudoinverse-based estimator.
|
|
215
|
+
|
|
216
|
+
`Z` : *np.ndarray* or *None*
|
|
217
|
+
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.
|
|
218
|
+
|
|
219
|
+
`final` : *bool*, default = *True*
|
|
220
|
+
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`.
|
|
221
|
+
|
|
222
|
+
`alpha` : *float*, *list[float]* or *None*, default = *None*
|
|
223
|
+
Regularization parameter (weight) in the final convex program:
|
|
224
|
+
- `α = 0`: Lasso (L1 norm)
|
|
225
|
+
- `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
|
|
226
|
+
- `0 < α < 1`: Elastic Net
|
|
227
|
+
If a scalar float is provided, that value is used after clipping to [0, 1].
|
|
228
|
+
If a list/iterable of floats is provided, each candidate is evaluated via a full solve, and the α with the smallest NRMSE is selected.
|
|
229
|
+
If None, α is chosen, based on an error rule: α = min(1.0, NRMSE_{α = 0} / (NRMSE_{α = 0} + NRMSE_{α = 1} + tolerance))
|
|
230
|
+
|
|
231
|
+
`*args`, `**kwargs` : optional
|
|
232
|
+
CVXPY arguments passed to the CVXPY solver.
|
|
233
|
+
|
|
234
|
+
**Returns:**
|
|
235
|
+
*TMPinvResult*
|
|
236
|
+
|
|
237
|
+
`TMPinvResult.full` : *bool*
|
|
238
|
+
Indicates if this result comes from the full (non-reduced) model.
|
|
239
|
+
|
|
240
|
+
`TMPinvResult.model` : *CLSP* or *list* of *CLSP*
|
|
241
|
+
A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
|
|
242
|
+
|
|
243
|
+
`TMPinvResult.x` : *np.ndarray*
|
|
244
|
+
Final estimated solution matrix of shape *(m, p)*.
|
|
245
|
+
|
|
246
|
+
## Bibliography
|
|
247
|
+
|
|
248
|
+
To be added.
|
|
249
|
+
|
|
250
|
+
## License
|
|
251
|
+
|
|
252
|
+
MIT License — see the [LICENSE](LICENSE) file.
|