From 0ced618c140f31d8a2caaf999437c41dd32a554e Mon Sep 17 00:00:00 2001 From: Rahul Kumar <55033230+pctablet505@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:06:58 +0530 Subject: [PATCH] =?UTF-8?q?core:=20fix=20solveLP=20floating-point=20drift?= =?UTF-8?q?=20producing=20infeasible=20solutions=20=F0=9F=A4=96?= =?UTF-8?q?=F0=9F=A4=96=F0=9F=A4=96=20(#30823)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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. --- modules/core/src/lpsolver.cpp | 51 +++++++++++++++++++++---- modules/core/test/test_lpsolver.cpp | 58 +++++++++++++++++++++++++++-- 2 files changed, 97 insertions(+), 12 deletions(-) diff --git a/modules/core/src/lpsolver.cpp b/modules/core/src/lpsolver.cpp index b09fb0128b..3e09b5ca91 100644 --- a/modules/core/src/lpsolver.cpp +++ b/modules/core/src/lpsolver.cpp @@ -41,6 +41,7 @@ #include "precomp.hpp" #include #include +#include #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_& c, Mat_& b,double& v,vector& N,vector& B,vector& indexToRow); static inline void pivot(Mat_& c,Mat_& b,double& v,vector& N,vector& B,int leaving_index, @@ -119,13 +121,13 @@ int solveLP(InputArray Func_, InputArray Constr_, OutputArray z_, double constr_ vector N,B; vector 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_ 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_& c, Mat_& b,double& v,vector& N,vector& B,vector& indexToRow){ N.resize(c.cols); N[0]=0; @@ -224,7 +239,17 @@ static int initialize_simplex(Mat_& c, Mat_& 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;jstd::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::iterator iterator; @@ -241,22 +266,32 @@ static int initialize_simplex(Mat_& c, Mat_& 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_ abs_sum(1,c.cols,0.0); for(int I=1;I& c,Mat_& b,double& v,vector& 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_& c,Mat_& b,double& v,vector& 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)); diff --git a/modules/core/test/test_lpsolver.cpp b/modules/core/test/test_lpsolver.cpp index b46dc7ef79..af15eeddf4 100644 --- a/modules/core/test/test_lpsolver.cpp +++ b/modules/core/test/test_lpsolver.cpp @@ -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_(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_({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_({3, 1}, {3, 1, 2}); + Mat B = cv::Mat_({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_({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_({2, 1}, {-3., -1.}); + Mat B = cv::Mat_({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(0); + EXPECT_GE(t, -1e-12); + EXPECT_LE(t, 0.9 + 1e-12); + EXPECT_NEAR(3 - 3 * t, z.at(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_({2, 1}, {1., -4.}); + Mat B = cv::Mat_({2, 3}, { + -4., -3., -2., + 2., 0., 0. + }); + Mat z; + ASSERT_EQ(SOLVELP_SINGLE, cv::solveLP(A, B, z)); + Mat etalon_z = cv::Mat_({2, 1}, {0., 2. / 3}); + ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12); } }} // namespace