Skip to content

FIX: Pivoting routines: Report numerical breakdown correctly - #949

Merged
mmcky merged 18 commits into
mainfrom
pivoting_refactor
Sep 9, 2026
Merged

mmcky merged 18 commits into
mainfrom
pivoting_refactor

Conversation

@oyamad

@oyamad oyamad commented Sep 6, 2026

Copy link
Copy Markdown
Member

Fixes to the pivoting routines and their callers, found while benchmarking linprog_simplex on the Netlib problems.

  • _lex_min_ratio_test: found=False was returned both when the pivot column has no positive entry and when the lexicographic tie breaking failed to single out one row; the latter was reported as "unbounded" by linprog_simplex. Return found=True with the first candidate in that case, together with a third value resolved.
  • lemke_howson and polym_lcp_solver discarded found; they now stop with converged=False on breakdown instead of returning a wrong "equilibrium".
  • lcp_lemke: require d > 0; measure ties in the initial ratio test against the minimum ratio.
  • linprog_simplex: fun = inf when unbounded; Phase 1 infeasibility test relative to the scale of b; pivot artificial variables out on the largest entry; docstring fixes.
  • Guard docstring formatting against python -OO, which made quantecon unimportable.

🤖 Generated with Claude Code (Claude Fable 5.1)

oyamad and others added 8 commits September 6, 2026 12:18
`_lex_min_ratio_test` returned `found=False` both when the pivot column
has no positive entry and when the lexicographic tie breaking failed to
single out one row among the candidates of the ratio test. The caller
`solve_tableau` treats `found=False` as "unbounded", so the second case
was reported as unbounded although the pivot column does have positive
entries. It arises when the tableau entries are large relative to the
absolute tolerance `tol_ratio_diff`, e.g. for `A_ub = [[1e14], [1e14]]`,
where the ratios in all columns tie within the tolerance.

Now `found` is True whenever the first pass finds a candidate, and if the
tie breaking leaves several rows, which are then indistinguishable within
`tol_ratio_diff`, the first of them is taken.

Add tests: a unit test of `_lex_min_ratio_test` and the linprog_simplex
example above. Add the analogous Lemke-Howson example (payoffs scaled by
1e16) as an expected failure: it also requires the tolerance to be
scale-aware, which is left for later.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`_lemke_howson_tbl` ignored the `found` flag of `_lex_min_ratio_test`
and, when the pivot column had no positive entry (up to `tol_piv`),
pivoted on a meaningless row and could return a wrong "equilibrium" with
`converged=True`. This cannot happen in exact arithmetic, and is a
numerical breakdown; now the pivoting stops and `converged=False` is
returned, so that the capping loop moves on to the next initial pivot.

Add a test of the breakdown path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Return a third value `resolved`: True if the row returned is the unique
lexico-minimum row, False if no candidate was found or if the
lexicographic passes over all the slack columns left several candidates
that tie within `tol_ratio_diff`. The latter cannot happen in exact
arithmetic, so `found and not resolved` signals a numerical breakdown.

`lemke_howson` now stops with `converged=False` in that case too: with
payoffs of order 1e15 or more all ratios tie within the tolerance, and
a wrong "equilibrium" was returned with `converged=True`. The
corresponding expected-failure test becomes a test of the reported
non-convergence. `polym_lcp_solver`, which discarded `found` as well,
now stops with `converged=False` on either kind of breakdown.
`linprog_simplex` and `lcp_lemke` keep pivoting on the first remaining
candidate, as before.

Document the preconditions of `_lex_min_ratio_test` (right hand side in
the last column, basis inverse in the slack columns) and why
`_min_ratio_test_no_tie_breaking` anchors ties to the minimum ratio.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- Raise ValueError if the covering vector d has a nonpositive entry,
  which silently flipped the sign of the artificial column.

- Derive n in `_get_solution` from `basis` rather than from the output
  buffer `z`.

- In the initial ratio test (open-coded, as the artificial column is
  negative), measure ties against the smallest ratio found so far
  instead of the last tied ratio, so that the accepted set cannot drift
  away from the minimum by chaining tolerances, in line with
  `_min_ratio_test_no_tie_breaking`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- On an unbounded exit, `fun` was the finite value of a non-optimal
  basic solution; return inf, as -inf is returned when infeasible.

- Derive L in `get_solution` from `basis` rather than from the output
  buffer `lambd`.

- Fix the docstring of `_pivot_col` (skip_aux is False in Phase 1 and
  True in Phase 2, the opposite of what was stated) and of `b_signs`
  (b may be zero).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`__doc__` is None under `python -OO`, and `__doc__.format(...)` at
import time raised AttributeError, making `quantecon` unimportable.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e of b

The residual of the Phase 1 objective (the sum of the artificial
variables) was compared with `fea_tol` in absolute terms, so a feasible
problem with right hand sides of order 1e5 and a roundoff residual of
1e-5 was declared infeasible (Netlib FFFFF800). Compare it with
`fea_tol` times the initial value of the Phase 1 objective, the sum of
|b|, if larger than 1. Pivoting is unaffected: on the Netlib problems of
the benchmark, only FFFFF800 changes, from "infeasible" to solved.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ntry

After Phase 1, an artificial variable still basic at level zero was
pivoted out on the first entry of its row exceeding `tol_piv`, which can
be a small pivot. Pivot on the largest entry of the row instead.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new covering-vector validation is bypassed when the LCP has a trivial solution.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Improves numerical-breakdown reporting and robustness across simplex, LCP, and game-theory pivoting routines.

Changes:

  • Distinguishes unresolved ties from missing pivots.
  • Improves solver failure outputs and numerical scaling.
  • Adds regression and workspace tests.
File summaries
File Description
quantecon/optimize/pivoting.py Extends lexicographic ratio-test results.
quantecon/optimize/linprog_simplex.py Improves failure values and Phase 1 handling.
quantecon/optimize/lcp_lemke.py Adds covering-vector validation and ratio fixes.
quantecon/game_theory/lemke_howson.py Reports pivot breakdown as non-convergence.
quantecon/game_theory/howson_lcp.py Stops polymatrix solving on breakdown.
quantecon/optimize/tests/test_pivoting.py Tests ratio-test outcomes.
quantecon/optimize/tests/test_linprog_simplex.py Tests numerical and workspace behavior.
quantecon/optimize/tests/test_lcp_lemke.py Tests validation and workspaces.
quantecon/game_theory/tests/test_lemke_howson.py Tests breakdown reporting.
Review details
  • Files reviewed: 9/9 changed files
  • Comments generated: 1
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread quantecon/optimize/lcp_lemke.py Resolved
@coveralls

coveralls commented Sep 6, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 90.828% (+0.05%) from 90.78% — pivoting_refactor into main

oyamad and others added 4 commits September 6, 2026 16:39
The check `d > 0` was bypassed when q is nonnegative, where the function
returns z = 0 before looking at d. Validate a supplied d up front, so that
an invalid covering vector is rejected on every instance, as in
QuantEcon.jl.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- A Phase 1 exit with no admissible pivot was reported as status 3
  ("unbounded") with `fun = inf`, although the auxiliary problem is
  bounded, so that it can only be a numerical breakdown (e.g. rows with
  coefficients at `tol_piv`). Report it as the new status 4, "Numerical
  difficulties encountered", with `fun` as for any Phase 1 failure;
  `fun = inf` is reserved for Phase 2 unboundedness.

- An unresolved tie in the lexico-minimum ratio test was followed by a
  pivot on an arbitrary candidate; the rows of the basis inverse are
  never identical, so it means that the tolerance could not separate
  distinct rows. Stop with status 4 in either phase, as `lcp_lemke` does
  with its status 3.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
An unresolved tie in the lexico-minimum ratio test was followed by a
pivot on an arbitrary candidate, which could end in a wrong "solution"
reported as success (e.g. with entries of order 1e14, where the ratios
tie within `tol_ratio_diff`). Stop with `success=False` and the new
status 3, "Numerical difficulties encountered"; `found=False` remains
secondary ray termination (status 2).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`_lemke_howson_tbl` stopped with `converged=False` on breakdown, which
`_lemke_howson_capping` took for a capped run and answered by retrying
with the next initial pivot, even when capping was not requested; the
result could then hide the breakdown of the requested path, reporting
`converged=True` from a different initial pivot. Return a third value
`breakdown` from `_lemke_howson_tbl`, and try another initial pivot on
breakdown only when capping was explicitly enabled. Adjust the caller in
`_compute_fp`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
oyamad and others added 4 commits September 6, 2026 17:28
Chained near-ties in q / d, observed through the basis workspace after
the initial pivot only (max_iter=1): the artificial variable must enter
at the row tied with the minimum, not drift to the next one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The reference ratio for ties was updated only when a ratio was smaller
by more than `tol_ratio_diff`, so a slightly smaller ratio left the
reference stale, and a later ratio within the tolerance of the stale
reference but more than a tolerance above the true minimum was accepted
as a candidate. Determine the minimum in a first pass, then keep the
rows whose ratio is within the tolerance of it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The reference ratio was updated only when a ratio was smaller by more
than `tol_ratio_diff`, so a later ratio within the tolerance of a stale
reference could be chosen although more than a tolerance above the
minimum. Update the reference on every strictly smaller ratio.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
When the Lemke-Howson pivoting on the imitation game broke down, the
partially pivoted tableaux were read as an equilibrium, and the next
iterate was formed from a vector that is not a mixed action (e.g. all
zeros). Stop the iteration instead, return the last iterate with
`converged=False`, and warn with a specific message rather than the
"max_iter attained" one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@quantecon-services quantecon-services left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks so much for this, @oyamad! This is a really careful piece of work. Separating "no positive entry" from "tie not broken" in _lex_min_ratio_test fixes a whole family of silent wrong answers in one go, and the commit-by-commit history made it a pleasure to review.

What I checked

  • Pulled the branch and ran the affected suites locally (pivoting, linprog_simplex, lcp_lemke, lemke_howson, howson_lcp, polymatrix_game, compute_fp): 74 passed, and the CI flake8 selects are clean.
  • Reproduced every item in the description on main and confirmed it is fixed here:
    • the duplicated-row LP (A_ub = [[1e14], [1e14]]) that main reports as "unbounded" now returns status 4;
    • an unbounded Phase 2 exit now reports fun = inf instead of a finite non-optimal value;
    • the 1e15-scale game that main "solves" with a non-equilibrium and converged=True now reports converged=False;
    • the 2e14 LCP goes from status 2 (ray termination) to the more accurate status 3;
    • the imitation game stops with the specific breakdown warning after 6 evaluations, where main runs to max_iter after 20 and warns about that instead;
    • python -OO -c "import quantecon" fails on main and works here.
  • Ran a small sweep of 30 random 4x4 games per payoff scale, validating each answer against the equivalent unit-scale game (so that the absolute tolerance in is_nash doesn't flatter tiny payoffs). The branch mostly turns silent wrong answers into explicit failures; the only place it gives up answers that main had right is the 1e12 scale (20 valid before, 18 after):
payoff scale main: converged / valid NE this PR: converged / valid NE
1e-12 30 / 3 0 / 0
1e-10 30 / 13 30 / 13
1 30 / 30 30 / 30
1e12 30 / 20 20 / 18
1e15 30 / 3 0 / 0

One thing I'd love your eyes on

The relative Phase 1 infeasibility test (fea_tol * sum|b|) is a good idea for FFFFF800, but as written it can let a genuinely infeasible problem through when one constraint has a large right-hand side and the contradiction sits in a small one:

A_eq = np.array([[1., 0.], [0., 1.], [0., 1.]])
b_eq = np.array([1e6, 0., 0.9])          # x2 = 0 and x2 = 0.9
res = linprog_simplex(np.array([-1., -1.]), A_eq=A_eq, b_eq=b_eq)
# this PR: success=True,  status=0, x=[1e6, 0]
# main:    success=False, status=2

The residual 0.9 sits below fea_tol * (1e6 + 0.9) ≈ 1.0, the artificial variable of the third row stays basic at level 0.9 with an all-zero row in the x columns (so the pivot-out loop never touches it), and Phase 2 proceeds as if the problem were feasible.

One fix that seems to work well is to keep the total test and additionally check each artificial variable that is still basic against the scale of its own constraint, using the |b| values from the initial tableau:

    b_scale = max(1., tableau[-1, -1])
    b_abs = tableau[:L, -1].copy()  # |b_k| per constraint, before Phase 1
    success, status, num_iter_1 = \
        solve_tableau(tableau, basis, max_iter, skip_aux=False,
                      piv_options=piv_options)
    ...
    if tableau[-1, -1] > piv_options.fea_tol * b_scale:  # Infeasible
        ...
    for i in range(L):
        if basis[i] >= nm:  # Artificial variable k still basic
            k = basis[i] - nm
            if tableau[i, -1] > piv_options.fea_tol * max(1., b_abs[k]):
                success = False
                status = 2
                return success, status, num_iter_1

I tried this in a scratch copy: it rejects the example above, still solves the 1e5-scale case in TestLinprogSimplexPhase1Scale, and all 20 tests in test_linprog_simplex.py pass. The one caveat is that a roundoff residual landing in a row with a small |b_k| would now be flagged, so it would be worth re-running the Netlib benchmark with it. Very happy to help with that if useful!

Small nits

I left three inline notes: an unreachable branch in linprog_simplex, a pointer to the tolerance line above, and a test comment that describes the intermediate state of the branch rather than main. One more that I couldn't attach inline because the line isn't in the diff: the polym_lcp_solver docstring (line 71) still says the result is an equilibrium "if not stopped early by reaching max_iter"; breakdown is now a second early exit worth a mention there.

Ideas for follow-ups (definitely not for this PR!)

  • Scale normalization in _initialize_tableaux. Equilibria are invariant to positive affine transformations of each player's payoffs, and the setup already shifts payoffs to be positive. Dividing by the maximum payoff as well would make the absolute tolerances effectively relative. The table above suggests the unit scale is the only one that is reliably right today (see the 1e-10 row, where both branches return wrong answers with converged=True). I think this might be a very cheap way to get the "scale-aware tolerance" mentioned in the first commit message.
  • A RuntimeWarning on non-convergence in lemke_howson / polym_lcp_solver. With the default full_output=False, a caller still receives the vector read from the partially pivoted tableaux (all zeros in the new tests) with no signal at all. A warning like the one in compute_fixed_point would make the new breakdown reporting visible to everyone, not only full_output=True users.
  • x and lambd on Phase 1 failure. They come back as allocated by np.empty, so callers can see values like 6e151 next to fun = -inf. Zeroing them (or a note in the docstring) would round out the new failure-output conventions nicely.

Thanks again! This is a big improvement in how honestly the pivoting routines report what happened, and I learned a lot reading it.


Generated by Claude Code

Comment thread quantecon/optimize/linprog_simplex.py Resolved
Comment thread quantecon/optimize/linprog_simplex.py Resolved
oyamad and others added 2 commits September 8, 2026 12:45
…sibility

The Phase 1 residual was compared with `fea_tol` times the sum of |b|
only, so a violation of a constraint with a small right hand side could
hide under the scale of the others (e.g. x2 = 0 and x2 = 0.9 next to
x1 = 1e6 was accepted as feasible). The artificial variable of a
constraint enters that constraint only, so its level after Phase 1 is
the residual of the constraint: test each one still basic against
`fea_tol` times the scale of its own right hand side, in addition to the
total. On the Netlib problems of the benchmark nothing changes.

Drop a branch on the Phase 1 failure path made unreachable by the
mapping of status 3 to 4 in `solve_phase_1`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@oyamad

oyamad commented Sep 8, 2026

Copy link
Copy Markdown
Member Author
  • The mixed-scale infeasibility: correct, and the diagnosis is exact. The artificial variable of a constraint enters that constraint only, so its level after Phase 1 is the residual of the constraint; ecc31df tests each artificial variable still basic against fea_tol times the scale of its own right hand side, in addition to the total, with the example above as a test. On the Netlib problems of the benchmark (51 problems, default tolerances) nothing changes: same 40 solved, FFFFF800 included, and no problem declared infeasible.
  • The unreachable branch is removed in the same commit.
  • The test comment is reworded (also in the Julia port, FIX: Pivoting routines: Report numerical breakdown correctly QuantEcon.jl#406), and the polym_lcp_solver docstring now mentions breakdown as a second early exit (bb28dbe).

On the follow-ups: agreed that they are for separate PRs. Payoff normalization in _initialize_tableaux was considered here and deferred, as it changes what the tolerances mean; the 1e-10 row of the sweep is a good argument for revisiting it. The warning on non-convergence in the game solvers is worth a discussion of its own.

🤖 Generated with Claude Code (Claude Fable 5.1)

@mmcky

mmcky commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

thanks @oyamad. Merging.

@mmcky
mmcky merged commit 25e2a65 into main Sep 9, 2026
14 checks passed
@mmcky
mmcky deleted the pivoting_refactor branch September 9, 2026 00:30
mmcky added a commit that referenced this pull request Sep 9, 2026
Catches the @-operator migration up to main (#831, #937, #947, #949).
Conflict in quantecon/tests/test_matrix_eqn.py: #831 appended
test_solve_discrete_riccati_system_beta_ge_one_failure_message directly
after the assert this branch rewrote to the @ operator. Kept both sides.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants