pytmpinv 1.1.0__tar.gz → 1.1.2__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.1.0
3
+ Version: 1.1.2
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,7 +31,7 @@ The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-s
31
31
  pip install tmpinv
32
32
  ```
33
33
 
34
- ## Quick Example 1
34
+ ## Quick Example
35
35
 
36
36
  ```python
37
37
  import numpy as np
@@ -98,17 +98,10 @@ print(" NRMSE :", fmt(result.model.nrmse))
98
98
  print(" Diagnostic band (min):", fmt(np.min(result.model.x_lower)))
99
99
  print(" Diagnostic band (max):", fmt(np.max(result.model.x_upper)))
100
100
  print(" Monte Carlo t-test:")
101
- for kw, val in result.model.ttest(sample_size=30, # NRMSE_partial sample
101
+ for kw, val in result.model.ttest(sample_size=30, # NRMSE sample
102
102
  seed=seed, distribution="normal", # seed and distribution
103
103
  partial=True).items():
104
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
105
 
113
106
  # AP (TM), based on a trade matrix, with a zero diagonal and 20% of known values
114
107
 
@@ -118,6 +111,7 @@ rng = np.random.default_rng(seed)
118
111
  # sample (dataset)
119
112
  m, p = 40, 40 # matrix dimensions (m x p)
120
113
  X_true = np.abs(rng.normal(size=(m, p))) # non-negative X_true
114
+ X_true = X_true * (1 - np.eye(m, p)) # zero diagonal
121
115
  idx = rng.choice(m * p, size=max(1, int(0.2 * (m * p))), # random numbers from
122
116
  replace=False) # [0,(m * p) - 1], 20% of total
123
117
 
@@ -129,7 +123,7 @@ b_val = X_true.reshape(-1, 1)[idx] # column vector
129
123
  bounds = (0, None) # non-negativity
130
124
  result = tmpinv(
131
125
  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)
126
+ m=m, p=p, zero_diagonal=True, reduced=(20,20), # reduced models of (20, 20)
133
127
  bounds=bounds,
134
128
  r=1, # a solution without refinement
135
129
  alpha=1.0 # a unique MNBLUE estimator
@@ -170,7 +164,7 @@ print(" Diagnostic band (min):", fmt(np.min(x_lower)), "-", fmt(np.max(x_low
170
164
  print(" Diagnostic band (max):", fmt(np.min(x_upper)), "-", fmt(np.max(x_upper) ))
171
165
  print(" Monte Carlo t-test:")
172
166
  ttests = [CLSP.ttest(sample_size=30, seed=seed,
173
- distribution="normal", partial=True) for CLSP in result.model]
167
+ distribution="normal") for CLSP in result.model]
174
168
  keys = ttests[0].keys()
175
169
  for kw in keys:
176
170
  val = np.array([t[kw] for t in ttests], dtype=float)
@@ -179,91 +173,91 @@ for kw in keys:
179
173
 
180
174
  ## User Reference
181
175
 
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.
176
+ 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
177
 
184
- **TMPINV Parameters:**
178
+ **TMPINV Parameters:**
185
179
 
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.
180
+ `S` : *array_like* of shape *(m + p, m + p)*, optional
181
+ A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
182
+ - *0* enforces equality (== `b_row` or `b_col`),
183
+ - *1* enforces a lower-than-or-equal (≤) condition,
184
+ - *–1* enforces a greater-than-or-equal (≥) condition.
191
185
 
192
186
  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
187
 
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.
188
+ `M` : *array_like* of shape *(k, m * p)*, optional
189
+ 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 unique 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
190
 
197
- `b_row` : *array_like* of shape *(m,)*
191
+ `b_row` : *array_like* of shape *(m,)*
198
192
  Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
199
193
 
200
- `b_col` : *array_like* of shape *(p,)*
194
+ `b_col` : *array_like* of shape *(p,)*
201
195
  Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
202
196
 
203
- `b_val` : *array_like* of shape *(k,)*
197
+ `b_val` : *array_like* of shape *(k,)*
204
198
  Right-hand side vector of known cell values.
205
199
 
206
- `i` : *int*, default = *1*
200
+ `i` : *int*, default = *1*
207
201
  Number of row groups.
208
202
 
209
- `j` : *int*, default = *1*
203
+ `j` : *int*, default = *1*
210
204
  Number of column groups.
211
205
 
212
- `zero_diagonal` : *bool*, default = *False*
206
+ `zero_diagonal` : *bool*, default = *False*
213
207
  If *True*, enforces the zero diagonal.
214
208
 
215
- `reduced` : *tuple* of *(int, int)*, optional
209
+ `reduced` : *tuple* of *(int, int)*, optional
216
210
  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
211
 
218
212
  `symmetric` : *bool*, default = *False*
219
- If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
213
+ If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
220
214
  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
215
 
222
- `bounds` : *sequence* of *(low, high)*, optional
216
+ `bounds` : *sequence* of *(low, high)*, optional
223
217
  Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
224
218
 
225
- `replace_value` : *float* or *None*, default = *np.nan*
219
+ `replace_value` : *float* or *None*, default = *np.nan*
226
220
  Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
227
221
 
228
- `tolerance` : *float*, default = *square root of machine epsilon*
222
+ `tolerance` : *float*, default = *square root of machine epsilon*
229
223
  Convergence tolerance for bounds.
230
224
 
231
- `iteration_limit` : *int*, default = *50*
225
+ `iteration_limit` : *int*, default = *50*
232
226
  Maximum number of iterations allowed in the refinement loop.
233
227
 
234
- **CLSP Parameters:**
228
+ **CLSP Parameters:**
235
229
 
236
- `r` : *int*, default = *1*
230
+ `r` : *int*, default = *1*
237
231
  Number of refinement iterations for the pseudoinverse-based estimator.
238
232
 
239
- `Z` : *np.ndarray* or *None*
233
+ `Z` : *np.ndarray* or *None*
240
234
  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
235
 
242
- `final` : *bool*, default = *True*
236
+ `final` : *bool*, default = *True*
243
237
  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
238
 
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)
239
+ `alpha` : *float*, *list[float]* or *None*, default = *None*
240
+ Regularization parameter (weight) in the final convex program:
241
+ - `α = 0`: Lasso (L1 norm)
242
+ - `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
249
243
  - `0 < α < 1`: Elastic Net
250
244
  If a scalar float is provided, that value is used after clipping to [0, 1].
251
245
  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))
246
+ If None, α is chosen, based on an error rule: α = min(1.0, NRMSE_{α = 0} / (NRMSE_{α = 0} + NRMSE_{α = 1} + tolerance))
253
247
 
254
- `*args`, `**kwargs` : optional
248
+ `*args`, `**kwargs` : optional
255
249
  CVXPY arguments passed to the CVXPY solver.
256
250
 
257
- **Returns:**
251
+ **Returns:**
258
252
  *TMPinvResult*
259
253
 
260
- `TMPinvResult.full` : *bool*
254
+ `TMPinvResult.full` : *bool*
261
255
  Indicates if this result comes from the full (non-reduced) model.
262
256
 
263
- `TMPinvResult.model` : *CLSP* or *list* of *CLSP*
257
+ `TMPinvResult.model` : *CLSP* or *list* of *CLSP*
264
258
  A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
265
259
 
266
- `TMPinvResult.x` : *np.ndarray*
260
+ `TMPinvResult.x` : *np.ndarray*
267
261
  Final estimated solution matrix of shape *(m, p)*.
268
262
 
269
263
  ## Bibliography
@@ -8,7 +8,7 @@ The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-s
8
8
  pip install tmpinv
9
9
  ```
10
10
 
11
- ## Quick Example 1
11
+ ## Quick Example
12
12
 
13
13
  ```python
14
14
  import numpy as np
@@ -75,17 +75,10 @@ print(" NRMSE :", fmt(result.model.nrmse))
75
75
  print(" Diagnostic band (min):", fmt(np.min(result.model.x_lower)))
76
76
  print(" Diagnostic band (max):", fmt(np.max(result.model.x_upper)))
77
77
  print(" Monte Carlo t-test:")
78
- for kw, val in result.model.ttest(sample_size=30, # NRMSE_partial sample
78
+ for kw, val in result.model.ttest(sample_size=30, # NRMSE sample
79
79
  seed=seed, distribution="normal", # seed and distribution
80
80
  partial=True).items():
81
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
82
 
90
83
  # AP (TM), based on a trade matrix, with a zero diagonal and 20% of known values
91
84
 
@@ -95,6 +88,7 @@ rng = np.random.default_rng(seed)
95
88
  # sample (dataset)
96
89
  m, p = 40, 40 # matrix dimensions (m x p)
97
90
  X_true = np.abs(rng.normal(size=(m, p))) # non-negative X_true
91
+ X_true = X_true * (1 - np.eye(m, p)) # zero diagonal
98
92
  idx = rng.choice(m * p, size=max(1, int(0.2 * (m * p))), # random numbers from
99
93
  replace=False) # [0,(m * p) - 1], 20% of total
100
94
 
@@ -106,7 +100,7 @@ b_val = X_true.reshape(-1, 1)[idx] # column vector
106
100
  bounds = (0, None) # non-negativity
107
101
  result = tmpinv(
108
102
  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)
103
+ m=m, p=p, zero_diagonal=True, reduced=(20,20), # reduced models of (20, 20)
110
104
  bounds=bounds,
111
105
  r=1, # a solution without refinement
112
106
  alpha=1.0 # a unique MNBLUE estimator
@@ -147,7 +141,7 @@ print(" Diagnostic band (min):", fmt(np.min(x_lower)), "-", fmt(np.max(x_low
147
141
  print(" Diagnostic band (max):", fmt(np.min(x_upper)), "-", fmt(np.max(x_upper) ))
148
142
  print(" Monte Carlo t-test:")
149
143
  ttests = [CLSP.ttest(sample_size=30, seed=seed,
150
- distribution="normal", partial=True) for CLSP in result.model]
144
+ distribution="normal") for CLSP in result.model]
151
145
  keys = ttests[0].keys()
152
146
  for kw in keys:
153
147
  val = np.array([t[kw] for t in ttests], dtype=float)
@@ -156,91 +150,91 @@ for kw in keys:
156
150
 
157
151
  ## User Reference
158
152
 
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.
153
+ 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
154
 
161
- **TMPINV Parameters:**
155
+ **TMPINV Parameters:**
162
156
 
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.
157
+ `S` : *array_like* of shape *(m + p, m + p)*, optional
158
+ A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
159
+ - *0* enforces equality (== `b_row` or `b_col`),
160
+ - *1* enforces a lower-than-or-equal (≤) condition,
161
+ - *–1* enforces a greater-than-or-equal (≥) condition.
168
162
 
169
163
  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
164
 
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.
165
+ `M` : *array_like* of shape *(k, m * p)*, optional
166
+ 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 unique 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
167
 
174
- `b_row` : *array_like* of shape *(m,)*
168
+ `b_row` : *array_like* of shape *(m,)*
175
169
  Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
176
170
 
177
- `b_col` : *array_like* of shape *(p,)*
171
+ `b_col` : *array_like* of shape *(p,)*
178
172
  Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
179
173
 
180
- `b_val` : *array_like* of shape *(k,)*
174
+ `b_val` : *array_like* of shape *(k,)*
181
175
  Right-hand side vector of known cell values.
182
176
 
183
- `i` : *int*, default = *1*
177
+ `i` : *int*, default = *1*
184
178
  Number of row groups.
185
179
 
186
- `j` : *int*, default = *1*
180
+ `j` : *int*, default = *1*
187
181
  Number of column groups.
188
182
 
189
- `zero_diagonal` : *bool*, default = *False*
183
+ `zero_diagonal` : *bool*, default = *False*
190
184
  If *True*, enforces the zero diagonal.
191
185
 
192
- `reduced` : *tuple* of *(int, int)*, optional
186
+ `reduced` : *tuple* of *(int, int)*, optional
193
187
  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
188
 
195
189
  `symmetric` : *bool*, default = *False*
196
- If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
190
+ If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
197
191
  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
192
 
199
- `bounds` : *sequence* of *(low, high)*, optional
193
+ `bounds` : *sequence* of *(low, high)*, optional
200
194
  Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
201
195
 
202
- `replace_value` : *float* or *None*, default = *np.nan*
196
+ `replace_value` : *float* or *None*, default = *np.nan*
203
197
  Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
204
198
 
205
- `tolerance` : *float*, default = *square root of machine epsilon*
199
+ `tolerance` : *float*, default = *square root of machine epsilon*
206
200
  Convergence tolerance for bounds.
207
201
 
208
- `iteration_limit` : *int*, default = *50*
202
+ `iteration_limit` : *int*, default = *50*
209
203
  Maximum number of iterations allowed in the refinement loop.
210
204
 
211
- **CLSP Parameters:**
205
+ **CLSP Parameters:**
212
206
 
213
- `r` : *int*, default = *1*
207
+ `r` : *int*, default = *1*
214
208
  Number of refinement iterations for the pseudoinverse-based estimator.
215
209
 
216
- `Z` : *np.ndarray* or *None*
210
+ `Z` : *np.ndarray* or *None*
217
211
  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
212
 
219
- `final` : *bool*, default = *True*
213
+ `final` : *bool*, default = *True*
220
214
  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
215
 
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)
216
+ `alpha` : *float*, *list[float]* or *None*, default = *None*
217
+ Regularization parameter (weight) in the final convex program:
218
+ - `α = 0`: Lasso (L1 norm)
219
+ - `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
226
220
  - `0 < α < 1`: Elastic Net
227
221
  If a scalar float is provided, that value is used after clipping to [0, 1].
228
222
  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))
223
+ If None, α is chosen, based on an error rule: α = min(1.0, NRMSE_{α = 0} / (NRMSE_{α = 0} + NRMSE_{α = 1} + tolerance))
230
224
 
231
- `*args`, `**kwargs` : optional
225
+ `*args`, `**kwargs` : optional
232
226
  CVXPY arguments passed to the CVXPY solver.
233
227
 
234
- **Returns:**
228
+ **Returns:**
235
229
  *TMPinvResult*
236
230
 
237
- `TMPinvResult.full` : *bool*
231
+ `TMPinvResult.full` : *bool*
238
232
  Indicates if this result comes from the full (non-reduced) model.
239
233
 
240
- `TMPinvResult.model` : *CLSP* or *list* of *CLSP*
234
+ `TMPinvResult.model` : *CLSP* or *list* of *CLSP*
241
235
  A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
242
236
 
243
- `TMPinvResult.x` : *np.ndarray*
237
+ `TMPinvResult.x` : *np.ndarray*
244
238
  Final estimated solution matrix of shape *(m, p)*.
245
239
 
246
240
  ## Bibliography
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytmpinv"
3
- version = "1.1.0"
3
+ version = "1.1.2"
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.1.0
3
+ Version: 1.1.2
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,7 +31,7 @@ The **Tabular Matrix Problems via Pseudoinverse Estimation (TMPinv)** is a two-s
31
31
  pip install tmpinv
32
32
  ```
33
33
 
34
- ## Quick Example 1
34
+ ## Quick Example
35
35
 
36
36
  ```python
37
37
  import numpy as np
@@ -98,17 +98,10 @@ print(" NRMSE :", fmt(result.model.nrmse))
98
98
  print(" Diagnostic band (min):", fmt(np.min(result.model.x_lower)))
99
99
  print(" Diagnostic band (max):", fmt(np.max(result.model.x_upper)))
100
100
  print(" Monte Carlo t-test:")
101
- for kw, val in result.model.ttest(sample_size=30, # NRMSE_partial sample
101
+ for kw, val in result.model.ttest(sample_size=30, # NRMSE sample
102
102
  seed=seed, distribution="normal", # seed and distribution
103
103
  partial=True).items():
104
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
105
 
113
106
  # AP (TM), based on a trade matrix, with a zero diagonal and 20% of known values
114
107
 
@@ -118,6 +111,7 @@ rng = np.random.default_rng(seed)
118
111
  # sample (dataset)
119
112
  m, p = 40, 40 # matrix dimensions (m x p)
120
113
  X_true = np.abs(rng.normal(size=(m, p))) # non-negative X_true
114
+ X_true = X_true * (1 - np.eye(m, p)) # zero diagonal
121
115
  idx = rng.choice(m * p, size=max(1, int(0.2 * (m * p))), # random numbers from
122
116
  replace=False) # [0,(m * p) - 1], 20% of total
123
117
 
@@ -129,7 +123,7 @@ b_val = X_true.reshape(-1, 1)[idx] # column vector
129
123
  bounds = (0, None) # non-negativity
130
124
  result = tmpinv(
131
125
  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)
126
+ m=m, p=p, zero_diagonal=True, reduced=(20,20), # reduced models of (20, 20)
133
127
  bounds=bounds,
134
128
  r=1, # a solution without refinement
135
129
  alpha=1.0 # a unique MNBLUE estimator
@@ -170,7 +164,7 @@ print(" Diagnostic band (min):", fmt(np.min(x_lower)), "-", fmt(np.max(x_low
170
164
  print(" Diagnostic band (max):", fmt(np.min(x_upper)), "-", fmt(np.max(x_upper) ))
171
165
  print(" Monte Carlo t-test:")
172
166
  ttests = [CLSP.ttest(sample_size=30, seed=seed,
173
- distribution="normal", partial=True) for CLSP in result.model]
167
+ distribution="normal") for CLSP in result.model]
174
168
  keys = ttests[0].keys()
175
169
  for kw in keys:
176
170
  val = np.array([t[kw] for t in ttests], dtype=float)
@@ -179,91 +173,91 @@ for kw in keys:
179
173
 
180
174
  ## User Reference
181
175
 
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.
176
+ 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
177
 
184
- **TMPINV Parameters:**
178
+ **TMPINV Parameters:**
185
179
 
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.
180
+ `S` : *array_like* of shape *(m + p, m + p)*, optional
181
+ A diagonal sign slack (surplus) matrix with entries in *{0, ±1}*.
182
+ - *0* enforces equality (== `b_row` or `b_col`),
183
+ - *1* enforces a lower-than-or-equal (≤) condition,
184
+ - *–1* enforces a greater-than-or-equal (≥) condition.
191
185
 
192
186
  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
187
 
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.
188
+ `M` : *array_like* of shape *(k, m * p)*, optional
189
+ 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 unique 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
190
 
197
- `b_row` : *array_like* of shape *(m,)*
191
+ `b_row` : *array_like* of shape *(m,)*
198
192
  Right-hand side vector of row totals. Please note that both `b_row` and `b_col` must be provided.
199
193
 
200
- `b_col` : *array_like* of shape *(p,)*
194
+ `b_col` : *array_like* of shape *(p,)*
201
195
  Right-hand side vector of column totals. Please note that both `b_row` and `b_col` must be provided.
202
196
 
203
- `b_val` : *array_like* of shape *(k,)*
197
+ `b_val` : *array_like* of shape *(k,)*
204
198
  Right-hand side vector of known cell values.
205
199
 
206
- `i` : *int*, default = *1*
200
+ `i` : *int*, default = *1*
207
201
  Number of row groups.
208
202
 
209
- `j` : *int*, default = *1*
203
+ `j` : *int*, default = *1*
210
204
  Number of column groups.
211
205
 
212
- `zero_diagonal` : *bool*, default = *False*
206
+ `zero_diagonal` : *bool*, default = *False*
213
207
  If *True*, enforces the zero diagonal.
214
208
 
215
- `reduced` : *tuple* of *(int, int)*, optional
209
+ `reduced` : *tuple* of *(int, int)*, optional
216
210
  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
211
 
218
212
  `symmetric` : *bool*, default = *False*
219
- If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
213
+ If True, enforces symmetry of the estimated solution matrix as: x = 0.5 * (x + x.T)
220
214
  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
215
 
222
- `bounds` : *sequence* of *(low, high)*, optional
216
+ `bounds` : *sequence* of *(low, high)*, optional
223
217
  Bounds on cell values. If a single tuple *(low, high)* is given, it is applied to all `m` * `p` cells. Example: *(0, None)*.
224
218
 
225
- `replace_value` : *float* or *None*, default = *np.nan*
219
+ `replace_value` : *float* or *None*, default = *np.nan*
226
220
  Final replacement value for any cell in the solution matrix that violates the specified bounds by more than the given tolerance.
227
221
 
228
- `tolerance` : *float*, default = *square root of machine epsilon*
222
+ `tolerance` : *float*, default = *square root of machine epsilon*
229
223
  Convergence tolerance for bounds.
230
224
 
231
- `iteration_limit` : *int*, default = *50*
225
+ `iteration_limit` : *int*, default = *50*
232
226
  Maximum number of iterations allowed in the refinement loop.
233
227
 
234
- **CLSP Parameters:**
228
+ **CLSP Parameters:**
235
229
 
236
- `r` : *int*, default = *1*
230
+ `r` : *int*, default = *1*
237
231
  Number of refinement iterations for the pseudoinverse-based estimator.
238
232
 
239
- `Z` : *np.ndarray* or *None*
233
+ `Z` : *np.ndarray* or *None*
240
234
  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
235
 
242
- `final` : *bool*, default = *True*
236
+ `final` : *bool*, default = *True*
243
237
  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
238
 
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)
239
+ `alpha` : *float*, *list[float]* or *None*, default = *None*
240
+ Regularization parameter (weight) in the final convex program:
241
+ - `α = 0`: Lasso (L1 norm)
242
+ - `α = 1`: Tikhonov Regularization/Ridge (L2 norm)
249
243
  - `0 < α < 1`: Elastic Net
250
244
  If a scalar float is provided, that value is used after clipping to [0, 1].
251
245
  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))
246
+ If None, α is chosen, based on an error rule: α = min(1.0, NRMSE_{α = 0} / (NRMSE_{α = 0} + NRMSE_{α = 1} + tolerance))
253
247
 
254
- `*args`, `**kwargs` : optional
248
+ `*args`, `**kwargs` : optional
255
249
  CVXPY arguments passed to the CVXPY solver.
256
250
 
257
- **Returns:**
251
+ **Returns:**
258
252
  *TMPinvResult*
259
253
 
260
- `TMPinvResult.full` : *bool*
254
+ `TMPinvResult.full` : *bool*
261
255
  Indicates if this result comes from the full (non-reduced) model.
262
256
 
263
- `TMPinvResult.model` : *CLSP* or *list* of *CLSP*
257
+ `TMPinvResult.model` : *CLSP* or *list* of *CLSP*
264
258
  A single CLSP object in the full model, or a list of CLSP objects for each reduced block in the reduced model.
265
259
 
266
- `TMPinvResult.x` : *np.ndarray*
260
+ `TMPinvResult.x` : *np.ndarray*
267
261
  Final estimated solution matrix of shape *(m, p)*.
268
262
 
269
263
  ## Bibliography
@@ -1,4 +1,4 @@
1
- __version__ = "1.1.0"
1
+ __version__ = "1.1.2"
2
2
 
3
3
  from .tmpinv import tmpinv
4
4
 
@@ -137,8 +137,8 @@ def TMPinvSolve(
137
137
  Notes
138
138
  ----
139
139
  In the reduced model, `S` is ignored. Slack behavior is derived implicitly
140
- from block-wise marginal totals. Likewise, `M` must be a row subset of an
141
- identity matrix (i.e., diagonal-only). Arbitrary or non-diagonal model
140
+ from block-wise marginal totals. Likewise, `M` must be a unique row subset
141
+ of an identity matrix (i.e., diagonal-only). Arbitrary or non-diagonal model
142
142
  matrices cannot be mapped to reduced blocks, making the model infeasible.
143
143
  """
144
144
  # (m), (p) Process the parameters, assert conformity, and get dimensions
@@ -193,12 +193,14 @@ def TMPinvSolve(
193
193
  b_blocks.append(b_val)
194
194
  b = np.vstack(b_blocks)
195
195
  result.model = CLSP().solve(*args,
196
- problem='ap', b=b, S=S, M=M,
197
- m=m,
198
- p=p,
199
- i=i,
200
- j=j,
201
- zero_diagonal=zero_diagonal,
196
+ problem='ap', b=b,
197
+ S=S,
198
+ M=M,
199
+ m=m,
200
+ p=p,
201
+ i=i,
202
+ j=j,
203
+ zero_diagonal=zero_diagonal,
202
204
  **kw)
203
205
  result.x = result.model.x
204
206
 
@@ -219,16 +221,22 @@ def TMPinvSolve(
219
221
  M, idx = np.unique(M_diag.copy() if M is None or M.size == 0
220
222
  else np.vstack([M, M_diag]),
221
223
  axis=0, return_index=True)
222
- b_val = (b_diag.copy() if b_val is None or b_val.size == 0
224
+ b_val = (b_diag.copy() if b_val is None or b_val.size == 0
223
225
  else np.vstack([b_val, b_diag])
224
- )[idx.reshape(-1)]
226
+ )[idx.reshape(-1)]
225
227
  del M_diag, b_diag, idx
228
+
226
229
  if M is not None:
227
- if not all(np.count_nonzero(row) == 1 and
228
- np.all((row == 0) | (row == 1)) for row in M):
229
- raise TMPinvInputError("M must be a row subset of the identity "
230
- "matrix in the reduced model.")
231
- M = (np.abs(np.sign(M)) * b_val).sum(axis=0).reshape(m, p)
230
+ if not ((np.isclose(M, 0) | np.isclose(M, 1)).all() and
231
+ (np.isclose(M, 1).sum(axis=1) == 1).all() and
232
+ (np.isclose(M, 1).sum(axis=0) <= 1).all()):
233
+ raise TMPinvInputError("M must be a unique row subset of the "
234
+ "identity matrix in the reduced model.")
235
+ X_true = np.full((m, p), np.nan, dtype=np.float64)
236
+ for idx, row in enumerate(M):
237
+ col = np.argmax(row)
238
+ r, c = divmod(col, p) # M has m * p columns
239
+ X_true[r, c] = b_val.ravel()[idx]
232
240
  if S is not None:
233
241
  warnings.warn("User-provided S is ignored in the reduced model.",
234
242
  UserWarning)
@@ -238,30 +246,26 @@ def TMPinvSolve(
238
246
  m_end = min(m_start + m_subset, m)
239
247
  p_start = col_block * p_subset
240
248
  p_end = min(p_start + p_subset, p)
241
- S = np.ones(((m_end - m_start) + (p_end - p_start), 1))
242
- b_blocks = [b_row[m_start:m_end].reshape(-1, 1),
249
+ S_subset = np.ones(((m_end - m_start) + (p_end - p_start), 1))
250
+ b_subset = [b_row[m_start:m_end].reshape(-1, 1),
243
251
  b_col[p_start:p_end].reshape(-1, 1)]
244
- M_subset, b_val_subset = None, None
245
- if M is not None:
246
- M_subset = np.diag(np.sign(M[m_start:m_end,
247
- p_start:p_end]).flatten())
248
- b_val_subset = M[m_start:m_end,
249
- p_start:p_end].reshape(-1, 1)
250
- if np.any(M_subset): # drop zero rows
251
- nonzero_rows = np.diag(M_subset) != 0
252
- M_subset = M_subset[nonzero_rows]
253
- b_val_subset = b_val_subset[nonzero_rows].reshape(-1, 1)
254
- b_blocks.append(b_val_subset)
255
- else:
256
- M_subset, b_val_subset = None, None
257
- b = np.vstack(b_blocks)
252
+ M_subset = None
253
+ if M is not None:
254
+ subset = X_true[m_start:m_end, p_start:p_end].ravel()
255
+ non_empty = ~np.isnan(subset)
256
+ if non_empty.any():
257
+ M_subset = np.eye(subset.size,
258
+ dtype=np.float64)[non_empty]
259
+ b_subset.append(subset[non_empty].reshape(-1, 1))
258
260
  tmp = CLSP().solve(*args,
259
- problem='ap', b=b, S=S, M=M_subset,
260
- m=m_end - m_start,
261
- p=p_end - p_start,
262
- i=i,
263
- j=j,
264
- zero_diagonal=False,
261
+ problem='ap', b=np.vstack(b_subset),
262
+ S=S_subset,
263
+ M=M_subset,
264
+ m=m_end - m_start,
265
+ p=p_end - p_start,
266
+ i=i,
267
+ j=j,
268
+ zero_diagonal=False,
265
269
  **kw)
266
270
  result.model.append(tmp)
267
271
  result.x[m_start:m_end, p_start:p_end] = tmp.x
File without changes
File without changes