pytmpinv 2.0.0__tar.gz → 2.6.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: 2.0.0
3
+ Version: 2.6.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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytmpinv"
3
- version = "2.0.0"
3
+ version = "2.6.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: 2.0.0
3
+ Version: 2.6.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
@@ -1,4 +1,4 @@
1
- __version__ = "2.0.0"
1
+ __version__ = "2.6.0"
2
2
 
3
3
  from .tmpinv import tmpinv
4
4
 
@@ -40,11 +40,11 @@ class TMPinvInputError(Exception):
40
40
  full_message = f"{message} (Code: {code})" if code is not None \
41
41
  else message
42
42
  super().__init__(full_message)
43
-
43
+
44
44
  def __str__(self) -> str:
45
45
  return self.message if self.code is None \
46
46
  else f"{self.message} [Code: {self.code}]"
47
-
47
+
48
48
  def as_dict(self) -> dict:
49
49
  """
50
50
  Return the error as a dictionary for structured logging or JSON output.
@@ -172,10 +172,10 @@ def TMPinvSolve(
172
172
  raise TMPinvInputError("Both b_row and b_col must be provided.")
173
173
  if len(b_row) < 2 or len(b_col) < 2:
174
174
  raise TMPinvInputError("Minimum length for b_row and b_col is 2.")
175
- if not np.isfinite(b_row).all() or not np.isfinite(b_col).all():
176
- raise TMPinvInputError("b_row and b_col must not contain inf or NaN.")
177
175
  b_row = np.asarray(b_row, dtype=np.float64).reshape(-1, 1)
178
176
  b_col = np.asarray(b_col, dtype=np.float64).reshape(-1, 1)
177
+ if not np.isfinite(b_row).all() or not np.isfinite(b_col).all():
178
+ raise TMPinvInputError("b_row and b_col must not contain inf or NaN.")
179
179
  m = b_row.shape[0] * i
180
180
  p = b_col.shape[0] * j
181
181
  if S is not None:
@@ -269,8 +269,8 @@ def TMPinvSolve(
269
269
  X_true = np.full((1*m, p), np.nan, dtype=np.float64)
270
270
  for idx, row in enumerate(M):
271
271
  col = np.argmax(row)
272
- r, c = divmod(col, p) # M has m * p columns
273
- X_true[r, c] = b_val.ravel()[idx]
272
+ r, c = col % m, col // m # M has m * p columns
273
+ X_true[r, c] = b_val.ravel(order='F')[idx]
274
274
  if kwargs.get("b_lim") is not None:
275
275
  X_lim = np.full((2*m, p), np.nan, dtype=np.float64)
276
276
  l_idx = (lambda x: kwargs["b_lim"].shape[0] if not x.size else
@@ -278,13 +278,13 @@ def TMPinvSolve(
278
278
  if l_idx > 0: # upper bounds
279
279
  for idx, row in enumerate(kwargs["C_lim"][:l_idx,:]):
280
280
  col = np.argmax(row)
281
- r, c = divmod(col, p)
282
- X_lim[ r, c] = kwargs["b_lim"].ravel()[ idx]
281
+ r, c = col % m, col // m
282
+ X_lim[ r, c] = kwargs["b_lim"].ravel(order='F')[ idx]
283
283
  if l_idx < kwargs["b_lim"].shape[0]: # lower bounds
284
284
  for idx, row in enumerate(kwargs["C_lim"][l_idx:,:]):
285
285
  col = np.argmax(row)
286
- r, c = divmod(col, p)
287
- X_lim[m+r, c] = kwargs["b_lim"].ravel()[l_idx+idx]
286
+ r, c = col % m, col // m
287
+ X_lim[m+r, c] = kwargs["b_lim"].ravel(order='F')[l_idx+idx]
288
288
  if S is not None and np.any(S[: S.shape[0] if kwargs.get("b_lim")
289
289
  is None else -kwargs["b_lim"].shape[0],:] != 0):
290
290
  warnings.warn("User-provided S is ignored in the reduced model.",
@@ -297,22 +297,16 @@ def TMPinvSolve(
297
297
  p_start = col_block * p_subset
298
298
  p_end = min(p_start + p_subset, p)
299
299
  C_subset = None
300
- S_subset = np.eye((m_end - m_start) + (p_end - p_start))
300
+ S_subset = np.eye((m_end - m_start) + (p_end - p_start),
301
+ dtype=np.float64)
301
302
  b_subset = [b_row[m_start:m_end].reshape(-1, 1),
302
303
  b_col[p_start:p_end].reshape(-1, 1)]
303
304
  M_subset = None
304
- if M is not None:
305
- subset = X_true[m_start:m_end, p_start:p_end].ravel()
306
- non_empty = ~np.isnan(subset)
307
- if non_empty.any():
308
- b_subset.append(subset[non_empty].reshape(-1, 1))
309
- M_subset = np.eye(subset.size,
310
- dtype=np.float64)[non_empty,:]
311
305
  if kwargs.get("b_lim") is not None:
312
306
  subset = np.vstack([
313
307
  X_lim[ m_start: m_end, p_start:p_end],
314
308
  X_lim[m+m_start:m+m_end, p_start:p_end]
315
- ]).ravel()
309
+ ]).ravel(order='F')
316
310
  non_empty = ~np.isnan(subset)
317
311
  if non_empty.any():
318
312
  b_subset.append(subset[non_empty].reshape(-1, 1))
@@ -332,6 +326,16 @@ def TMPinvSolve(
332
326
  np.hstack([np.zeros((S.shape[0],
333
327
  S_subset.shape[1])),
334
328
  S]) ])
329
+ S_subset = S_subset[:, ~np.all(S_subset == 0, axis=0)]
330
+ if M is not None:
331
+ subset = X_true[m_start:m_end, p_start:p_end].ravel(
332
+ order='F'
333
+ )
334
+ non_empty = ~np.isnan(subset)
335
+ if non_empty.any():
336
+ b_subset.append(subset[non_empty].reshape(-1, 1))
337
+ M_subset = np.eye(subset.size,
338
+ dtype=np.float64)[non_empty,:]
335
339
  tmp = CLSP().solve(*args,
336
340
  problem='ap', b=np.vstack(b_subset),
337
341
  C=C_subset,
@@ -389,10 +393,13 @@ def tmpinv(
389
393
  An object containing the fitted CLSP model(s) and the solution
390
394
  matrix `x`.
391
395
  """
392
- # (n_cells) Perform initial estimation and get cell count
393
- result = TMPinvSolve(*args, tolerance=tolerance,
394
- iteration_limit=iteration_limit, **kwargs)
395
- n_cells = result.x.shape[0] * result.x.shape[1]
396
+ # (n_cells) Get cell count from keyword arguments
397
+ if kwargs.get("b_row") is None or kwargs.get("b_col") is None:
398
+ raise TMPinvInputError("Both b_row and b_col must be provided.")
399
+ if len(kwargs.get("b_row")) < 2 or len(kwargs.get("b_col")) < 2:
400
+ raise TMPinvInputError("Minimum length for b_row and b_col is 2.")
401
+ n_cells = (len(kwargs.get("b_row")) * kwargs.get("i", 1) *
402
+ len(kwargs.get("b_col")) * kwargs.get("j", 1))
396
403
  if bounds is None:
397
404
  bounds = (None, None)
398
405
  if isinstance(bounds, tuple):
@@ -403,8 +410,6 @@ def tmpinv(
403
410
  f"match number of variables {n_cells}.")
404
411
  elif len(bounds) == 1:
405
412
  bounds = bounds * n_cells # replicate (low, high)
406
- if all(l is None and h is None for l, h in bounds):
407
- return result # finish if unbounded
408
413
 
409
414
  # (result) Perform bound-constrained iterative refinement
410
415
  kw = {k: v for k, v in kwargs.items() if k not in {"b_lim", "b_val",
@@ -430,30 +435,33 @@ def tmpinv(
430
435
  finite_rows]),
431
436
  :] == 0, axis=0) # reduce S width
432
437
  for _ in range(iteration_limit):
433
- M_idx, b_val = [], []
434
- x = result.x.reshape(-1, 1)
435
- for i, (v, (l, h)) in enumerate(zip(x, bounds)):
436
- v = float(v.item())
437
- if ((l is not None and v < l - tolerance) or \
438
- (h is not None and v > h + tolerance)):
439
- continue # skip out-of-bounds
440
- M_idx.append(i)
441
- b_val.append(v)
442
- if len(M_idx) < n_cells:
443
- M = np.eye(n_cells, dtype=np.float64)[M_idx]
444
- result = TMPinvSolve(*args, b_lim=(b_lim[finite_rows, :]),
445
- b_val=b_val,
446
- C_lim=(C_lim[finite_rows, :]),
447
- S=(S[np.concatenate([
448
- np.ones(S.shape[0] -
449
- b_lim.shape[0],
450
- dtype=bool),
451
- finite_rows]),
452
- :])[:,nonzero_cols],
453
- M=M, tolerance=tolerance,
454
- iteration_limit=iteration_limit, **kw)
438
+ if _ > 0:
439
+ M_idx, b_val = [], []
440
+ x = result.x.reshape(-1, 1)
441
+ for i, (v, (l, h)) in enumerate(zip(x, bounds)):
442
+ v = float(v.item())
443
+ if ((l is not None and v < l - tolerance) or \
444
+ (h is not None and v > h + tolerance)):
445
+ continue # skip out-of-bounds
446
+ M_idx.append(i)
447
+ b_val.append(v)
448
+ if len(M_idx) < n_cells:
449
+ M = np.eye(n_cells, dtype=np.float64)[M_idx]
450
+ else:
451
+ break
455
452
  else:
456
- break
453
+ M, b_val = kwargs.get("M"), kwargs.get("b_val")
454
+ result = TMPinvSolve(*args, b_lim=(b_lim[finite_rows, :]),
455
+ b_val=b_val,
456
+ C_lim=(C_lim[finite_rows, :]),
457
+ S=(S[np.concatenate([
458
+ np.ones(S.shape[0] -
459
+ b_lim.shape[0],
460
+ dtype=bool),
461
+ finite_rows]),
462
+ :])[:,nonzero_cols],
463
+ M=M, tolerance=tolerance,
464
+ iteration_limit=iteration_limit, **kw)
457
465
 
458
466
  # (result) Replace out-of-bound values with `replace_value`
459
467
  x = result.x.reshape(-1, 1)
File without changes
File without changes
File without changes