pytmpinv 4.0.0__tar.gz → 5.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/). Earlier versions are listed as published on PyPI, with their release dates; changes made between two releases are listed under the later one.
4
+
5
+ ## [5.0.0] – 2026-11-23
6
+
7
+ Version 5.0.0 adapts TMPinv to pyclsp 5.0.0, which enforces bounds on the unknowns exactly. The preparation of version 5.0.0 — code changes, tests and documentation — was assisted by Claude (Anthropic), an AI assistant.
8
+
9
+ ### Added
10
+
11
+ - `zero_diagonal="exact"` in `tmpinv()`: sets the bounds of the diagonal cells to (0, 0), so that the diagonal is exactly zero (in the full and in the reduced model); a *TMPinvInputError* is raised if the bounds of a diagonal cell exclude 0 or for another string. `zero_diagonal=True` keeps its meaning (soft model rows x_kk = 0).
12
+ - `bounds` and `slack_sign` parameters of `TMPinvSolve()`: the cell bounds (one pair per cell, as normalized by `tmpinv()`) are passed to `CLSP.solve(bounds=...)`, block-wise in the reduced model; `slack_sign` restricts the slacks of `S` to be ≥ 0 (ignored in the reduced model).
13
+ - `sweep_limit` parameter of `TMPinvSolve()` (default 100, also accepted by `tmpinv()` as a keyword argument): the maximum number of block sweeps of the reduced model; a *RuntimeWarning* is issued if the sweeps do not converge within it, and a *TMPinvInputError* if it is < 1.
14
+ - `TMPinvResult.sweeps`: the number of block sweeps of the reduced model (*None* in the full model).
15
+ - `TMPinvResult.replaced`: boolean m × p mask of the cells set to `replace_value` (an optional fourth argument of `TMPinvResult()`, all *False* by default).
16
+ - Pass-through of all options of `CLSP.solve()` via keyword arguments, documented: `r`, `Z`, `rcond`, `final`, `alpha`, `scale`, `slack_sign` and CVXPY solver arguments (e.g. `solver=`); `tolerance` and `iteration_limit` are passed to CLSP.
17
+ - Bounds given as *np.nan* or ±*np.inf* denote an unbounded side (like *None*); bounds as an array of shape (m·p, 2) and as a tuple of pairs are accepted; malformed bounds (wrong length or shape, non-numeric values, low > high, low = +inf, high = −inf) raise a *TMPinvInputError*.
18
+ - Validation in the reduced model: grouped totals (`i` or `j` > 1) raise a *TMPinvInputError* instead of failing in CLSP.
19
+ - Test suite `tests/test_tmpinv.py` (29 tests; references computed with numpy, scipy and CLSP, including the equivalence of the bounded first step with scipy's BVLS on the canonical system; runs under pytest or as a script, against the installed package with `TMPINV_TEST_INSTALLED=1`, with a pyclsp source tree from `CLSP_SRC`).
20
+ - CI: a `test` job (Python 3.11 and 3.12) in the PyPI workflow, on which the release build depends, and a `tests.yml` workflow (push and pull request; Python 3.11, 3.12 and 3.13) that builds the wheel and runs the tests against the installed wheel. Both install pyclsp ≥ 5.0.0 from PyPI.
21
+ - Full MIT license text in `LICENSE` (previously only the title line).
22
+ - `CHANGELOG.md`; README sections on how TMPinv works (problem types, canonical form, bounds, Step 2, zero diagonal and symmetry, reduced models, `replace_value`), seven runnable examples with their output, an extended parameter reference, warnings and troubleshooting, limitations, and citation. The README links to `CHANGELOG.md` and `LICENSE` on GitHub (so that the links also work on PyPI), and the project URLs include the changelog.
23
+
24
+ ### Changed
25
+
26
+ - Requires numpy ≥ 2.0, the minimum of cvxpy ≥ 1.8.1 (the declared numpy ≥ 1.24 could not be installed together with it); the README notes the spurious *RuntimeWarning*s of the NumPy 2.0 and 2.1 wheels on macOS. Error messages end with a period ("M and b_val must have the same number of rows: … vs ….", and through pyclsp 5.0.0). Found in an external review.
27
+ - Bounds are enforced exactly by CLSP: by bounded-variable least squares (verified by the KKT conditions, with a scipy BVLS fallback) in Step 1 and as constraints in Step 2. Out-of-bound values can no longer occur in a CLSP estimate, also in the reduced model.
28
+ - `replace_value` applies only to the cells of a full or block model whose bounded Step 1 did not converge (`model.status["step1"]` starting with *'not converged'*) and to the cells that violate their bounds by more than `tolerance` after the symmetrization (`symmetric=True` with asymmetric bounds). *None* now means "no replacement". With `symmetric=True`, the replaced cells are mirrored, so that `result.x` stays symmetric.
29
+ - `S` is validated against the number of totals, `len(b_row)` + `len(b_col)` (previously m + p plus the internal bound rows), and its slacks are signed by default (`slack_sign=True` when `S` is supplied), so that S_kk = +1/−1 makes a total a "≤"/"≥" condition on its feasible side, as documented.
30
+ - Reduced model: the full problem is solved by block-coordinate (Gauss–Seidel) sweeps. Each block is fitted by CLSP with the other blocks fixed, i.e. with the row and column totals minus the current sums of the other blocks, its known values and its bounds (as CLSP bounds instead of additional constraint rows), without slacks; the sweeps start from the minimum-norm table of the totals (with the known values, clipped to the bounds) and stop when the largest change of a cell is below `tolerance` · max(1, max |x|). They converge toward a least-squares fit of the full problem (not necessarily the minimum-norm one); a sweep costs one CLSP fit per block. `result.model` holds the block fits of the last sweep, and `replaced` refers to them; `S` and `slack_sign` are ignored.
31
+ - `alpha` is a single value in [0, 1] and *None* means α = 1 (pyclsp 5.0.0); `rcond` is a cutoff on the singular values of A·Z (pyclsp 5.0.0); the defaults of `final`, `rcond` and `scale` are those of pyclsp.
32
+ - `result.x` is a copy of the CLSP estimate when cells are replaced, so that `result.model.x` keeps the unreplaced estimate.
33
+ - Docstrings and README describe the totals, known values and soft zero-diagonal rows as least-squares rows, the exact enforcement of the bounds, the meaning of Step 2, and the block sweeps of the reduced model.
34
+ - Requires Python ≥ 3.11 and pyclsp ≥ 5.0.0; classifiers for Python 3.11, 3.12 and 3.13; version 5.0.0 in `pyproject.toml` and `tmpinv/__init__.py`.
35
+
36
+ ### Fixed
37
+
38
+ - README: on PyPI, the placeholder of the status templates *'fallback: \<reason\>'* and *'not converged: \<reason\>'* was removed as an HTML tag (it is now escaped). Found in an external review.
39
+ - Through pyclsp 5.0.0: with SciPy 1.13 (within the supported range), a table whose cells are all fixed by `bounds` (e.g. `bounds=(0, 0)`) raised an untyped *ValueError* ("Internal work array size computation failed: -10"); it now returns the fixed cells. The α = 1 polish no longer accepts a point with a larger objective than the verified solver solution. Found in an external review.
40
+ - A list or object array that contains itself (`b_row = [1]; b_row.append(b_row)`) was walked forever by the check of masked entries and dates; it now raises a *TMPinvInputError* ("b_row must not contain itself (a cyclic list or array)."), while a list repeated without a cycle is accepted. `sweep_limit` of the reduced model was converted with `int()`, which gave 1 for 1.9, `"1"` and *True* and raised a *TypeError*, *ValueError* or *OverflowError* for a function, a list, *nan* or *inf*; it now must be a positive whole number (a *TMPinvInputError* "sweep_limit must be a positive whole number.", which replaces "sweep_limit must be at least 1."). It is still ignored in the full model. Found in an external review.
41
+ - A masked total inside a list (`b_row=[np.ma.array([99, 2], mask=[1, 0])]`) was used with its hidden value, and dates inside a list or an object array became days since 1970; the checks now apply at any depth of lists, tuples and object arrays of `b_row`, `b_col`, `S`, `M` and `b_val`. A conversion method that raises an exception (e.g. `__array__`) now raises a *TMPinvInputError* ("b_row could not be converted to a numeric array (…).") with the original exception as its `__cause__`, instead of that exception. Found in an external review.
42
+ - `tolerance=None` raised a *TypeError* in the bound check of `replace_value` (and `tolerance="a"` a *ValueError* in the reduced model), an `S` without columns (`np.empty((4, 0))`) NumPy's *ValueError* in `max()`, a masked total (*np.ma*) was used with its hidden value (a masked 99 as 99), and dates (*datetime64*, *timedelta64*) became their days or seconds since 1970. `tolerance=None` is now the default, an invalid `tolerance` raises the *CLSPError* of pyclsp in both models, an `S` without columns is `S=None`, and masked entries and dates in `b_row`, `b_col`, `S`, `M` and `b_val` raise a *TMPinvInputError* ("b_row must not contain masked (missing) values.", "b_row must be numeric, not a date or time (convert it to numbers explicitly)."). Through pyclsp 5.0.0, an array of solvers raises a *CLSPError* instead of NumPy's *ValueError*, and Step 2 stays in the subspace of `Z`. Found in an external review.
43
+ - Totals of more than one dimension were flattened (`b_row=np.zeros((2, 2, 2))` gave an 8 × 2 table), `i=1e300` raised NumPy's *OverflowError* and `zero_diagonal=10**400` a *TypeError* in `np.isnan`; they now raise a *TMPinvInputError* ("b_row must be a vector (or a matrix of one row or column), got shape (2, 2, 2).", "i and j are too large: the table would have more than … cells.", "zero_diagonal must be True, False or 'exact'."). Through pyclsp 5.0.0, the bound tolerance of Step 1 and the equality rows of Step 2 follow the units of `A` as well as those of `b` (a general problem in units of 10⁹ or 10⁶ changed the estimate; tables, whose `A` is of 0/1, were not affected), and the Lasso example of the README (α = 0, a non-unique minimizer) now returns another solution with the same objective. Found in an external review.
44
+ - `summary(i=…)` (and `summarize()`) converted the block index with `int()` before checking it: a function, a list or a complex number raised a *TypeError*, *np.nan* a *ValueError* and *np.inf* an *OverflowError*, and *True* was accepted as the index 1; `i` must now be a whole number in 0..len(model)−1 that is not a boolean (else a *TMPinvInputError*, checked without a conversion to float, which overflowed for `Fraction(10**400, 1)`; found in a further rerun), and the message gives the range ("i must be in 0..5 for reduced model.", previously "0..6-1"). `display` must be *True*, *False*, 0 or 1 (else a *TMPinvInputError* "display must be True or False."; through pyclsp 5.0.0, an array raised NumPy's *ValueError* and *"no"* printed the summary). Found in a rerun of an external stress test.
45
+ - Through pyclsp 5.0.0, a `tolerance` given as a `fractions.Fraction` is stored as a *float* (it raised NumPy's *TypeError* in the fit).
46
+ - Through pyclsp 5.0.0: bounds that no Step 2 minimizer can reach (e.g. an upper bound of 10¹²) are no longer passed to the solver, whose accuracy they degraded, and α = 0 is solved with CLARABEL instead of ECOS, which was inaccurate on columns of order 10⁻⁶; the Lasso table of the README (non-unique minimizer) now equals the one of the rtmpinv README. Found in a rerun of an external stress test.
47
+ - Through pyclsp 5.0.0, a boolean `alpha` raises a *CLSPError* (as in rtmpinv), and so do nested, zero-dimensional or boolean candidates `alphas` of `result.model.cv_alpha()`, previously flattened or read as 1.0; the README notes that the effect of 0 < α < 1 depends on the units of the table (see the limitations of pyclsp).
48
+ - Integers too large for a float (10⁴⁰⁰) for `replace_value`, `i` or `j` raised an *OverflowError* or *TypeError*; they now raise a *TMPinvInputError*. Through pyclsp 5.0.0, Step 2 also checks its equality error in the units of z (see the pyclsp changelog). Found in an external stress test.
49
+ - `symmetric="no"` was truthy and symmetrized the table (rtmpinv: not symmetrized); a scalar `S` raised an *IndexError*; complex totals were made real. They now raise a *TMPinvInputError* ("symmetric must be True or False.", "S must be a 2-D array.", "b_row must be real, not complex."). Through pyclsp 5.0.0, complex, empty or malformed inputs and diagnostic arguments raise a *CLSPError*. Found in a fourth external review.
50
+ - Through pyclsp 5.0.0: the bound tolerances of Steps 1 and 2 and the residual-sign cutoff of `r` > 1 follow the scale of the problem, so that tables in small units give the same estimate, and the KKT check of the bounded Step 1 is weighted by the column lengths (see the pyclsp changelog); the README Lasso example (α = 0) returns another of the equally optimal tables, and the README prints the weighted `kkt_error`.
51
+ - Non-numeric `b_row`, `b_col`, `S`, `M` or `b_val` raised numpy's *ValueError* or *TypeError*, a non-numeric `replace_value` a *ValueError* after the estimation, and a non-numeric or fractional `reduced` a *ValueError* or was truncated by `int()`; they now raise a *TMPinvInputError* ("b_row must be a numeric array (not ragged).", "replace_value must be None or a number.", "reduced must be a pair of whole numbers (rows, columns), each ≥ 3."). A scalar `b_row` or `b_col` (e.g. `float("inf")`) raised a *TypeError* from `len()`; it is now a vector of length 1 and raises "Minimum length for b_row and b_col is 2.". Found in external reviews.
52
+ - Empty `bounds` (`[]`, `()` or an array of shape (0, 2)) raised a numpy broadcasting *ValueError* (an *IndexError* with `zero_diagonal="exact"`); they now raise a *TMPinvInputError* ("Bounds length 0 does not match number of variables …."), as in rtmpinv 3.0.0.
53
+ - Through pyclsp 5.0.0: bounded estimates of tables in small units (e.g. totals of order 10⁻⁴) could stop at a bound, and `rcond=np.nan` returned a zero table; see the pyclsp changelog.
54
+ - `i` and `j` were used unchecked, so that, e.g., `i=1.9` raised an unrelated *TypeError*; they must now be positive whole numbers ("i must be a positive whole number."), and the block index of `summary()`/`summarize()` must be whole, as in rtmpinv 3.0.0.
55
+ - `S` was rejected for grouped totals (`i`, `j` > 1), since the expected number of rows was computed from the dimensions of the table instead of the number of totals.
56
+ - A tuple of bound pairs was treated as a single (low, high) pair.
57
+ - The reduced model with grouped totals sliced `b_row`/`b_col` by the cell indices and failed in CLSP (now rejected with a *TMPinvInputError*).
58
+ - The reduced model did not reproduce the totals: every block was fitted independently with one slack per total, so that the assembled table overshot the totals (40 × 40 table with `reduced=(20, 20)`: row sums 1.9 to 2.7 times the row totals, R² ≈ −4.2, vs. R² = 0.28 for the full model). With the block sweeps, the totals are reproduced (relative error 2·10⁻⁹, R² = 0.27; README, Example 5).
59
+
60
+ - `zero_diagonal=True` with a known diagonal cell in `M` silently removed the soft row x_kk = 0, since the rows were merged by their coefficients only (in pyclsp and in the reduced model): 2 × 2 totals of 2 with x₁₁ = 3 gave [[2, 0.5], [0.5, 1]] (squared residual 7) instead of the least-squares table [[1.2, 1.1], [1.1, 0.6]] (5.4). All rows are now kept; the reduced model accepts repeated cells in `M` and passes every row of a cell to its block with its own value (as in the full model, so that ρ, the NRMSE and the refinement with `r` > 1 refer to the supplied rows; a one-block reduced model equals the full model).
61
+ - README: the error table quoted "M and b_val must have the same number of rows." for the actual "M and b_val must have the same number of rows: … vs ….". Found in an external review.
62
+ - README: `tolerance` was said to set the verification tolerance of the second step; it sets its bound tolerance sqrt(`tolerance`)·s_u, while the equality rows are verified against sqrt(`tolerance`)·f (as in the pyclsp README). Found in an external review.
63
+
64
+ ### Removed
65
+
66
+ - The iterative bound-handling heuristic of `tmpinv()` (freezing the in-bound cells as known values in `M`, re-solving up to `iteration_limit` times, and replacing the remaining out-of-bound cells by `replace_value`).
67
+ - The internal keyword arguments `b_lim` and `C_lim` of `TMPinvSolve()` (bounds as constraint rows with slacks), and the bound rows and slack columns built for each block of the reduced model.
68
+ - The block slacks of the reduced model (one slack per block-wise total, `S` = I), replaced by the block sweeps.
69
+ - Support for Python 3.10.
70
+
71
+ ### Breaking
72
+
73
+ - pyclsp ≥ 5.0.0, Python ≥ 3.11 and numpy ≥ 2.0 are required.
74
+ - Estimates with `bounds` differ from 4.0.0: they are exact bounded least-squares estimates (Step 1) and, with `final=True`, the bounded table selected by α (Step 2), instead of the result of the heuristic.
75
+ - `replace_value` has a new scope (non-converged fits and bound violations after the symmetrization), and `replace_value=None` keeps the estimate instead of producing *NaN*.
76
+ - `alpha` lists and the NRMSE rule for `alpha=None` are removed in pyclsp 5.0.0: a list, tuple or array raises a *CLSPError*, and *None* means α = 1. A float `rcond` has a different effective cutoff (pyclsp 5.0.0).
77
+ - `TMPinvSolve()` no longer accepts `b_lim`/`C_lim`; it takes normalized `bounds` (one pair per cell) and `slack_sign`.
78
+ - `S` must have `len(b_row)` + `len(b_col)` rows, and its slacks are signed by default (`slack_sign=False` restores free slacks).
79
+ - The reduced model is estimated by block-coordinate sweeps (different estimates, no block slacks, `slack_sign` ignored, `result.model` from the last sweep) and rejects grouped totals.
80
+ - `zero_diagonal` must be a bool, a number or *'exact'*: any other value raises a *TMPinvInputError* ("zero_diagonal must be True, False or 'exact'."); before, *None* was accepted and acted as *False*, and a list such as `[1]` acted as *True*.
81
+ - `zero_diagonal=True` no longer drops the row x_kk = 0 of a known diagonal cell, and `M` with repeated cells is accepted in the reduced model (estimates differ in these cases).
82
+
83
+ ## [4.0.0] – 2026-06-06
84
+
85
+ - Bug fixes.
86
+ - Requires pyclsp ≥ 4.0.0.
87
+
88
+ ## [2.0.0] – 2026-04-21
89
+
90
+ - Cross-platform condition-number tolerance in CLSP (`cond_tolerance`).
91
+ - Requires pyclsp ≥ 3.0.0 (pyclsp 3.x is not on PyPI; the first release that satisfies it is 4.0.0).
92
+
93
+ ## [1.6.0] – 2026-01-29
94
+
95
+ - Better boundary handling in the reduced model.
96
+
97
+ ## [1.4.2] – 2025-12-31
98
+
99
+ - `TMPinvResult.summary()` and refreshed README.
100
+ - GitHub Actions workflow for PyPI publishing.
101
+ - Requires pyclsp ≥ 1.8.0.
102
+
103
+ ## [1.3.2] – 2025-11-06
104
+
105
+ - README update.
106
+
107
+ ## [1.3.0] – 2025-10-25
108
+
109
+ - Improved bound handling via the CLSP design matrix.
110
+
111
+ ## [1.2.0] – 2025-09-19
112
+
113
+ - Input checks, zero diagonal, and symmetric flag.
114
+
115
+ ## [1.0.0] – 2025-08-23 [YANKED]
116
+
117
+ - Initial release.
pytmpinv-5.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ilya Bolotov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.