core: fix solveLP floating-point drift producing infeasible solutions 🤖🤖🤖 (#30823)

* core: fix solveLP floating-point drift producing infeasible solutions

* core(lpsolver): tighten pivot-eps comment per review (drop issue ref, note cost)

* core(lpsolver): snap cancellation noise relative to the operands

Replace the fixed 1e-12 cutoff on the whole tableau with a relative test on
the subtraction that updates it. A fixed cutoff turns legitimate small data
into zeros (right-hand sides around 1e-14 were returned as z = 0), while the
relative test removes only results that are within rounding noise of the
values being subtracted.

Add small_magnitude_data, which fails with the fixed cutoff.

* core(lpsolver): snap cancellation noise when restoring objective after Phase I

When any constraint has a negative right-hand side, initialize_simplex() runs Phase I and then rebuilds the original objective from old_c and the Phase I tableau before entering Phase II inner_simplex(). Snap cancellation noise in those updates consistently with pivot() so that exact-zero checks in Phase II are not distorted by residual rounding error.

Add negative_rhs_restore_cancellation regression test.

* core(lpsolver): compare the regression tests with their exact optima

issue_12343 has the unique optimum z = (16, 15, 0, 24)/37, objective
189/37. Compare z with it through cvtest::norm, as regression_basic does.
Checking only the status and the constraints passes for any feasible
point reported as SOLVELP_SINGLE.

Compare small_magnitude_data with its exact solution as well, and check
that the point returned by negative_rhs_restore_cancellation lies on its
optimal segment. Assert the status first in all three tests.

Inline add_snap_zero, which had one caller, and drop an example noise
magnitude from the sub_snap_zero comment that does not hold in general.

* core(lpsolver): pivot the Phase I auxiliary variable out on a nonzero entry

When Phase I ends with the auxiliary variable x0 basic at value 0,
initialize_simplex() makes it nonbasic by one degenerate pivot. It always
pivoted on the first column of x0's row, but that entry can be 0. With
cancellation noise snapped to exact zeros this happens often: the pivot
divides by 0 and solveLP returns SOLVELP_UNBOUNDED for bounded problems.
Pivot on the entry of largest magnitude instead.

Add phase1_auxiliary_basic_at_zero, which returned SOLVELP_UNBOUNDED.

* core(lpsolver): guard zero Phase I pivot row and snap v updates

* core(lpsolver): snap each restored objective coefficient once

After Phase I, each coefficient of the original objective is rebuilt as a
sum of terms. Add up each column and the absolute values of its terms, and
set the coefficient to 0 once, when it is at most 1e-12 times that
absolute sum, instead of snapping after every term.

The objective value v is never compared or returned, so its updates go
back to plain additions. The doc comment of initialize_simplex() now
lists SOLVELP_LOST.
This commit is contained in:
Rahul Kumar
2026-11-17 11:06:58 +05:30
committed by GitHub
parent ecb072401a
commit 0ced618c14
2 changed files with 97 additions and 12 deletions

View File

@@ -41,6 +41,7 @@
#include "precomp.hpp"
#include <climits>
#include <algorithm>
#include <cmath>
#define dprintf(x)
#define print_matrix(x)
@@ -78,7 +79,8 @@ static void print_simplex_state(const Mat& c,const Mat& b,double v,const std::ve
*both b and c should be one column bigger than corresponding b and c of linear problem and the leftmost column will be used internally
by this procedure - it should not be cleaned before the call to procedure and may contain mess after
it also initializes N and B and does not make any assumptions about their init values
* @return SOLVELP_UNFEASIBLE if problem is unfeasible, 0 if feasible.
* @return SOLVELP_UNFEASIBLE if problem is unfeasible, SOLVELP_LOST if the auxiliary variable of Phase I
cannot be pivoted out of the basis, 0 if feasible.
*/
static int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B,vector<unsigned int>& indexToRow);
static inline void pivot(Mat_<double>& c,Mat_<double>& b,double& v,vector<int>& N,vector<int>& B,int leaving_index,
@@ -119,13 +121,13 @@ int solveLP(InputArray Func_, InputArray Constr_, OutputArray z_, double constr_
vector<int> N,B;
vector<unsigned int> indexToRow;
if(initialize_simplex(bigC,bigB,v,N,B,indexToRow)==SOLVELP_UNFEASIBLE){
return SOLVELP_UNFEASIBLE;
int res=initialize_simplex(bigC,bigB,v,N,B,indexToRow);
if(res!=0){
return res;
}
Mat_<double> c=bigC.colRange(1,bigC.cols),
b=bigB.colRange(1,bigB.cols);
int res=0;
if((res=inner_simplex(c,b,v,N,B,indexToRow))==SOLVELP_UNBOUNDED){
return SOLVELP_UNBOUNDED;
}
@@ -162,6 +164,19 @@ int solveLP(InputArray Func, InputArray Constr, OutputArray z)
return solveLP(Func, Constr, z, 1e-12);
}
// Returns x, or exactly 0 when x is only rounding noise: |x| <= 1e-12*scale, where scale is the
// magnitude of the terms x was computed from. The simplex logic compares tableau entries with
// exactly 0, so the noise that a cancellation leaves behind would be taken as a real value.
// The threshold is relative, so it does not depend on the scale of the problem.
static inline double snap_zero(double x,double scale){
return std::abs(x)<=1e-12*scale?0.0:x;
}
// Returns a-b, snapped to 0 relative to the operands.
static inline double sub_snap_zero(double a,double b){
return snap_zero(a-b,std::max(std::abs(a),std::abs(b)));
}
static int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B,vector<unsigned int>& indexToRow){
N.resize(c.cols);
N[0]=0;
@@ -224,7 +239,17 @@ static int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<
if(b(iterator_offset,b.cols-1)>0){
return SOLVELP_UNFEASIBLE;
}
pivot(c,b,v,N,B,iterator_offset,0,indexToRow);
// x0 is basic at 0: pivot it out on the largest entry of its row, since a given entry may be 0.
int entering_index=0;
for(int j=1;j<b.cols-1;j++){
if(std::abs(b(iterator_offset,j))>std::abs(b(iterator_offset,entering_index))){
entering_index=j;
}
}
if(b(iterator_offset,entering_index)==0){
return SOLVELP_LOST;
}
pivot(c,b,v,N,B,iterator_offset,entering_index,indexToRow);
}
vector<int>::iterator iterator;
@@ -241,22 +266,32 @@ static int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<
print_simplex_state(c,b,v,N,B);
//start from 1, because we ignore x_0
//each coefficient is a sum of terms: snap it once, relative to the sum of their absolute values
c=0;
v=0;
Mat_<double> abs_sum(1,c.cols,0.0);
for(int I=1;I<old_c.cols;I++){
if(indexToRow[I]<nsize){
dprintf(("I=%d from nonbasic\n",I));
int iterator_offset=indexToRow[I];
c(0,iterator_offset)+=old_c(0,I);
abs_sum(0,iterator_offset)+=std::abs(old_c(0,I));
print_matrix(c);
}else{
dprintf(("I=%d from basic\n",I));
int iterator_offset=indexToRow[I]-nsize;
c-=old_c(0,I)*b.row(iterator_offset).colRange(0,b.cols-1);
for(int j=0;j<c.cols;j++){
double term=old_c(0,I)*b(iterator_offset,j);
c(0,j)-=term;
abs_sum(0,j)+=std::abs(term);
}
v+=old_c(0,I)*b(iterator_offset,b.cols-1);
print_matrix(c);
}
}
for(int j=0;j<c.cols;j++){
c(0,j)=snap_zero(c(0,j),abs_sum(0,j));
}
dprintf(("after restore\n"));
print_simplex_state(c,b,v,N,B);
@@ -349,7 +384,7 @@ static inline void pivot(Mat_<double>& c,Mat_<double>& b,double& v,vector<int>&
if(j==entering_index){
b(i,j)=-coef*b(leaving_index,j);
}else{
b(i,j)-=(coef*b(leaving_index,j));
b(i,j)=sub_snap_zero(b(i,j),coef*b(leaving_index,j));
}
}
}
@@ -361,7 +396,7 @@ static inline void pivot(Mat_<double>& c,Mat_<double>& b,double& v,vector<int>&
if(i==entering_index){
c(0,i)=-Coef*b(leaving_index,i);
}else{
c(0,i)-=Coef*b(leaving_index,i);
c(0,i)=sub_snap_zero(c(0,i),Coef*b(leaving_index,i));
}
}
dprintf(("v was %g\n",v));

View File

@@ -151,8 +151,8 @@ TEST(Core_LPSolver, issue_12337)
EXPECT_ANY_THROW(Mat1b z_8u; cv::solveLP(A, B, z_8u));
}
// NOTE: Test parameters found experimentally to get numerically inaccurate result.
// The test behaviour may change after algorithm tuning and may removed.
// Degenerate problem: the first ratio test is a three-way tie.
// The optimum is unique: z = (16, 15, 0, 24) / 37, objective 189 / 37.
TEST(Core_LPSolver, issue_12343)
{
Mat A = (cv::Mat_<double>(4, 1) << 3., 3., 3., 4.);
@@ -161,8 +161,58 @@ TEST(Core_LPSolver, issue_12343)
4., 4., 0., 1., 4.,
4., 0., 4., 1., 4.);
Mat z;
int result = cv::solveLP(A, B, z);
EXPECT_EQ(SOLVELP_LOST, result);
ASSERT_EQ(SOLVELP_SINGLE, cv::solveLP(A, B, z));
Mat etalon_z = cv::Mat_<double>({4, 1}, {16. / 37, 15. / 37, 0., 24. / 37});
ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12);
}
// Cormen's example #1 from regression_basic with the right-hand side scaled by 1e-14.
// The solution scales with the data: nothing may be treated as zero because it is small.
TEST(Core_LPSolver, small_magnitude_data)
{
const double scale = 1e-14;
Mat A = cv::Mat_<double>({3, 1}, {3, 1, 2});
Mat B = cv::Mat_<double>({3, 4}, {1, 1, 3, 30 * scale,
2, 2, 5, 24 * scale,
4, 1, 2, 36 * scale});
Mat z;
ASSERT_EQ(SOLVELP_SINGLE, cv::solveLP(A, B, z));
Mat etalon_z = cv::Mat_<double>({3, 1}, {8 * scale, 4 * scale, 0});
ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12 * scale);
}
// A negative right-hand side makes solveLP start with Phase I. The objective is parallel to
// the first constraint, so the optimal points are z = (t, 3 - 3t) for 0 <= t <= 0.9.
TEST(Core_LPSolver, negative_rhs_restore_cancellation)
{
Mat A = cv::Mat_<double>({2, 1}, {-3., -1.});
Mat B = cv::Mat_<double>({3, 3}, {
-3., -1., -3.,
-2., -4., -3.,
1., 2., 6.
});
Mat z;
ASSERT_EQ(SOLVELP_MULTI, cv::solveLP(A, B, z));
ASSERT_EQ(2, z.rows);
const double t = z.at<double>(0);
EXPECT_GE(t, -1e-12);
EXPECT_LE(t, 0.9 + 1e-12);
EXPECT_NEAR(3 - 3 * t, z.at<double>(1), 1e-12);
}
// x1 must be 0 and x2 >= 2/3, so the optimum is unique: z = (0, 2/3), objective -8/3.
// Phase I ends with its auxiliary variable basic at 0 and a 0 in the first column of its row.
TEST(Core_LPSolver, phase1_auxiliary_basic_at_zero)
{
Mat A = cv::Mat_<double>({2, 1}, {1., -4.});
Mat B = cv::Mat_<double>({2, 3}, {
-4., -3., -2.,
2., 0., 0.
});
Mat z;
ASSERT_EQ(SOLVELP_SINGLE, cv::solveLP(A, B, z));
Mat etalon_z = cv::Mat_<double>({2, 1}, {0., 2. / 3});
ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12);
}
}} // namespace