pytmpinv 1.0.4__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.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytmpinv
3
- Version: 1.0.4
3
+ Version: 1.1.0
4
4
  Summary: Tabular Matrix Problems via Pseudoinverse Estimation
5
5
  Author-email: The Economist <29724411+econcz@users.noreply.github.com>
6
6
  License-Expression: MIT
@@ -31,49 +31,150 @@ The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-s
31
31
  pip install tmpinv
32
32
  ```
33
33
 
34
- ## Quick Example
34
+ ## Quick Example 1
35
35
 
36
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
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
63
59
  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))
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))}")
77
178
  ```
78
179
 
79
180
  ## User Reference
@@ -116,7 +217,7 @@ Dimensions of the reduced problem. If specified, the problem is estimated as a s
116
217
 
117
218
  `symmetric` : *bool*, default = *False*
118
219
  If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
119
- Symmetrization can slightly alter row/column totals. For exact symmetry under all constraints, add explicit symmetry constraints to M in a full-model solve instead of using this flag.
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.
120
221
 
121
222
  `bounds` : *sequence* of *(low, high)*, optional
122
223
  Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
@@ -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.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytmpinv"
3
- version = "1.0.4"
3
+ version = "1.1.0"
4
4
  description = "Tabular Matrix Problems via Pseudoinverse Estimation"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytmpinv
3
- Version: 1.0.4
3
+ Version: 1.1.0
4
4
  Summary: Tabular Matrix Problems via Pseudoinverse Estimation
5
5
  Author-email: The Economist <29724411+econcz@users.noreply.github.com>
6
6
  License-Expression: MIT
@@ -31,49 +31,150 @@ The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-s
31
31
  pip install tmpinv
32
32
  ```
33
33
 
34
- ## Quick Example
34
+ ## Quick Example 1
35
35
 
36
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
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
63
59
  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))
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))}")
77
178
  ```
78
179
 
79
180
  ## User Reference
@@ -116,7 +217,7 @@ Dimensions of the reduced problem. If specified, the problem is estimated as a s
116
217
 
117
218
  `symmetric` : *bool*, default = *False*
118
219
  If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
119
- Symmetrization can slightly alter row/column totals. For exact symmetry under all constraints, add explicit symmetry constraints to M in a full-model solve instead of using this flag.
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.
120
221
 
121
222
  `bounds` : *sequence* of *(low, high)*, optional
122
223
  Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
@@ -1,4 +1,4 @@
1
- __version__ = "1.0.4"
1
+ __version__ = "1.1.0"
2
2
 
3
3
  from .tmpinv import tmpinv
4
4
 
@@ -124,9 +124,9 @@ def TMPinvSolve(
124
124
  symmetric : bool, default = False
125
125
  If True, enforces symmetry of the estimated solution matrix as:
126
126
  x = 0.5 * (x + x.T)
127
- Symmetrization can slightly alter row/column totals. For exact symmetry
128
- under all constraints, add explicit symmetry constraints to M in a
129
- full-model solve instead of using this flag.
127
+ Applies to TMPinvResult.x only. For TMPinvResult.model symmetry,
128
+ add explicit symmetry constraints to M in a full-model solve instead
129
+ of using this flag.
130
130
 
131
131
  Returns
132
132
  -------
pytmpinv-1.0.4/README.md DELETED
@@ -1,151 +0,0 @@
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
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
- `symmetric` : *bool*, default = *False*
95
- If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
96
- Symmetrization can slightly alter row/column totals. For exact symmetry under all constraints, add explicit symmetry constraints to M in a full-model solve instead of using this flag.
97
-
98
- `bounds` : *sequence* of *(low, high)*, optional
99
- Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
100
-
101
- `replace_value` : *float* or *None*, default = *np.nan*
102
- Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
103
-
104
- `tolerance` : *float*, default = *square root of machine epsilon*
105
- Convergence tolerance for bounds.
106
-
107
- `iteration_limit` : *int*, default = *50*
108
- Maximum number of iterations allowed in the refinement loop.
109
-
110
- **CLSP Parameters:**
111
-
112
- `r` : *int*, default = *1*
113
- Number of refinement iterations for the pseudoinverse-based estimator.
114
-
115
- `Z` : *np.ndarray* or *None*
116
- 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.
117
-
118
- `final` : *bool*, default = *True*
119
- 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`.
120
-
121
- `alpha` : *float*, *list[float]* or *None*, default = *None*
122
- Regularization parameter (weight) in the final convex program:
123
- - `α = 0`: Lasso (L1 norm)
124
- - `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
125
- - `0 < α < 1`: Elastic Net
126
- If a scalar float is provided, that value is used after clipping to [0, 1].
127
- If a list/iterable of floats is provided, each candidate is evaluated via a full solve, and the α with the smallest NRMSE is selected.
128
- If None, α is chosen, based on an error rule: α = min(1.0, NRMSE_{α = 0} / (NRMSE_{α = 0} + NRMSE_{α = 1} + tolerance))
129
-
130
- `*args`, `**kwargs` : optional
131
- CVXPY arguments passed to the CVXPY solver.
132
-
133
- **Returns:**
134
- *TMPinvResult*
135
-
136
- `TMPinvResult.full` : *bool*
137
- Indicates if this result comes from the full (non-reduced) model.
138
-
139
- `TMPinvResult.model` : *CLSP* or *list* of *CLSP*
140
- A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
141
-
142
- `TMPinvResult.x` : *np.ndarray*
143
- Final estimated solution matrix of shape *(m, p)*.
144
-
145
- ## Bibliography
146
-
147
- To be added.
148
-
149
- ## License
150
-
151
- MIT License — see the [LICENSE](LICENSE) file.
File without changes
File without changes