CultMath BoundedLeastSquares: Validate names the invalid input; Solve's validation has one owner

Adds BoundedLeastSquaresInput and BoundedLeastSquares.Validate (tolerance, bounds, matrix, target; first failure).
Solve calls it and its inline tolerance, bounds and A^T b finiteness checks are deleted. Untested at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-10 19:24:59 +02:00
commit 004d8bb78a
2 changed files with 211 additions and 15 deletions

View file

@ -11,10 +11,29 @@ public enum BoundedLeastSquaresStatus
/// <summary>The iteration cap was reached. <c>x</c> holds the last feasible iterate, which is never worse than the clamped start.</summary>
IterationLimit,
/// <summary>The input broke the contract; nothing was solved and <c>x</c> is exactly as passed.</summary>
/// <summary>The input broke the contract; nothing was solved and <c>x</c> is exactly as passed. <see cref="BoundedLeastSquares.Validate"/> names which input.</summary>
InvalidInput,
}
/// <summary>Which input of <see cref="BoundedLeastSquares"/> breaks its contract; the first failure in the order of the members.</summary>
public enum BoundedLeastSquaresInput
{
/// <summary>Every input meets the contract; <c>Solve</c> will not return <see cref="BoundedLeastSquaresStatus.InvalidInput"/>.</summary>
Valid,
/// <summary>The KKT tolerance is not finite and greater than zero.</summary>
InvalidTolerance,
/// <summary>Some <c>lo</c> or <c>hi</c> is NaN, <c>lo[j] &gt; hi[j]</c>, <c>lo[j]</c> is <c>+Inf</c> or <c>hi[j]</c> is <c>-Inf</c>.</summary>
InvalidBounds,
/// <summary>Some entry of <c>a</c> is NaN or infinite.</summary>
NonFiniteMatrix,
/// <summary>Some entry of <c>b</c> is NaN or infinite.</summary>
NonFiniteTarget,
}
/// <summary>
/// Dense bounded least squares: <c>min ||A x - b||^2</c> subject to <c>lo &lt;= x &lt;= hi</c>, for small problems
/// (tens of rows and columns). C#-only, like the intercept helpers in <see cref="math"/>; there is no HLSL mirror.
@ -58,7 +77,9 @@ public enum BoundedLeastSquaresStatus
/// <see cref="BoundedLeastSquaresStatus.InvalidInput"/> without throwing, with <c>iterations</c> 0 and
/// <c>x</c> exactly as passed. A NaN or infinite warm start is legal: it is clamped into the box (an infinite
/// result on an unbounded side becomes 0 clamped to the box). Spans shorter than the stated dimensions are a
/// caller bug and throw <see cref="ArgumentException"/>.
/// caller bug and throw <see cref="ArgumentException"/>. <see cref="Validate"/> reports which input broke the
/// contract, and <c>Solve</c> returns <c>InvalidInput</c> exactly when it does not return
/// <see cref="BoundedLeastSquaresInput.Valid"/>.
/// </para>
/// </remarks>
public static class BoundedLeastSquares
@ -75,6 +96,44 @@ public static class BoundedLeastSquares
/// <summary>Floats of caller-supplied workspace needed for <paramref name="n"/> columns.</summary>
public static int WorkspaceLength(int n) => 2 * (2 * n * n + 6 * n) + 3 * n;
/// <summary>
/// Checks the inputs of <c>Solve</c> against its contract and names the first one that breaks it, in the order
/// tolerance, bounds, matrix, target. <c>Solve</c> calls this and returns
/// <see cref="BoundedLeastSquaresStatus.InvalidInput"/> for any result but <see cref="BoundedLeastSquaresInput.Valid"/>.
/// It reads its arguments only, allocates nothing and does not throw for a bad value.
/// </summary>
/// <param name="m">Rows of <paramref name="a"/>.</param>
/// <param name="n">Columns of <paramref name="a"/>, and length of <paramref name="lo"/> and <paramref name="hi"/>.</param>
/// <param name="a">Row-major <c>m * n</c> matrix.</param>
/// <param name="b">Length <c>m</c> target. With <c>n = 0</c> there is no unknown and <paramref name="b"/> is not read.</param>
/// <param name="lo">Lower bounds.</param>
/// <param name="hi">Upper bounds.</param>
/// <param name="kktRelativeTolerance">The tolerance <c>Solve</c> will be given.</param>
/// <exception cref="ArgumentException">A span is shorter than the stated dimensions, or <paramref name="m"/> or <paramref name="n"/> is negative: a caller bug, not an invalid input.</exception>
public static BoundedLeastSquaresInput Validate(
int m, int n,
ReadOnlySpan<float> a, ReadOnlySpan<float> b,
ReadOnlySpan<float> lo, ReadOnlySpan<float> hi,
double kktRelativeTolerance = DefaultKktRelativeTolerance)
{
if (m < 0 || n < 0 || a.Length < m * n || b.Length < m || lo.Length < n || hi.Length < n)
throw new ArgumentException("BoundedLeastSquares: span shorter than the stated dimensions.");
if (!(kktRelativeTolerance > 0.0) || double.IsPositiveInfinity(kktRelativeTolerance))
return BoundedLeastSquaresInput.InvalidTolerance;
for (var j = 0; j < n; j++)
if (!(lo[j] <= hi[j]) || float.IsPositiveInfinity(lo[j]) || float.IsNegativeInfinity(hi[j]))
return BoundedLeastSquaresInput.InvalidBounds;
for (var i = 0; i < m * n; i++)
if (!float.IsFinite(a[i]))
return BoundedLeastSquaresInput.NonFiniteMatrix;
if (n > 0)
for (var r = 0; r < m; r++)
if (!float.IsFinite(b[r]))
return BoundedLeastSquaresInput.NonFiniteTarget;
return BoundedLeastSquaresInput.Valid;
}
/// <summary>
/// Minimises <c>||A x - b||^2</c> subject to <c>lo &lt;= x &lt;= hi</c>. <paramref name="x"/> is the warm start
/// on entry (clamped to the box first) and the result on exit.
@ -124,9 +183,11 @@ public static class BoundedLeastSquares
double kktRelativeTolerance,
int maxIterations = DefaultMaxIterations)
{
if (m < 0 || n < 0 || a.Length < m * n || b.Length < m || lo.Length < n || hi.Length < n
|| x.Length < n || workspace.Length < WorkspaceLength(n))
if (n < 0 || x.Length < n || workspace.Length < WorkspaceLength(n))
throw new ArgumentException("BoundedLeastSquares: span shorter than the stated dimensions.");
iterations = 0;
if (Validate(m, n, a, b, lo, hi, kktRelativeTolerance) != BoundedLeastSquaresInput.Valid)
return BoundedLeastSquaresStatus.InvalidInput;
// Double-precision vectors and matrices first, then the integer flags, all carved from the caller's floats.
var doubleCount = 2 * n * n + 6 * n;
@ -145,22 +206,11 @@ public static class BoundedLeastSquares
var freeIndex = Take(ref ints, n);
var dependent = Take(ref ints, n);
iterations = 0;
if (!(kktRelativeTolerance > 0.0) || double.IsPositiveInfinity(kktRelativeTolerance))
return BoundedLeastSquaresStatus.InvalidInput;
for (var j = 0; j < n; j++)
if (!(lo[j] <= hi[j]) || float.IsPositiveInfinity(lo[j]) || float.IsNegativeInfinity(hi[j]))
return BoundedLeastSquaresStatus.InvalidInput;
// A float is never large enough to overflow a double product or a sum of tens of them, so a non-finite
// A^T b entry is exactly a non-finite entry of A or b (NaN and infinity never cancel to a finite value).
for (var j = 0; j < n; j++)
{
var sb = 0.0;
for (var r = 0; r < m; r++)
sb += (double)a[r * n + j] * b[r];
if (!double.IsFinite(sb))
return BoundedLeastSquaresStatus.InvalidInput;
atb[j] = sb;
for (var k = 0; k <= j; k++)
{