Files
DSP_Mods/UXAssist/Production/TwoPhaseSimplex.cs
T
soarqin f0773ffb9b fix(production): correct blueprint power and planner edge cases
Read the Advanced Mining Machine speed stored with station settings in prebuild
and blueprint captures, and count charging power nodes such as Satellite
Substations at their idle draw. Skip recipes that consume their own product when
choosing an item's default recipe, so Refined Oil uses Plasma Refining instead
of Reforming Refine.

Run each planner recipe in one proliferation mode and report conflicting
explicit modes, keep material flows for recipe types the catalog does not know,
and attribute receiver warnings to their recipe. Compare simplex ratio ties
relatively and drive out near-zero artificials without amplifying residuals.
Bound the steady-state reduction so lossless cycles cannot stall blueprint
descriptions, and choose power units after rounding.

Remove redundant code: share the numeric and flow helpers, and drop the unused
IsExcessIntermediate threshold, legacy constructor and Capture overloads, the
multi-field updater, and the unused proliferator source table.
2026-10-25 22:01:05 +08:00

229 lines
9.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading;
namespace UXAssist.Production;
internal enum LinearSolveStatus
{
Optimal,
Infeasible,
Unbounded,
IterationLimit,
Cancelled
}
internal sealed class LinearSolveResult
{
internal LinearSolveStatus Status { get; }
internal double[] Values { get; }
internal LinearSolveResult(LinearSolveStatus status, double[] values = null)
{
Status = status;
Values = values;
}
}
internal static class TwoPhaseSimplex
{
private const double PivotTolerance = 1e-10;
private const double ReducedTolerance = 1e-8;
private const double RatioTieTolerance = 1e-9;
internal static LinearSolveResult Solve(double[,] coefficients, double[] rightHandSide,
IReadOnlyList<double[]> objectives, int iterationBudget, CancellationToken cancellation)
{
var rowCount = rightHandSide.Length;
var columnCount = coefficients.GetLength(1);
if (coefficients.GetLength(0) != rowCount || iterationBudget <= 0)
throw new ArgumentException("The linear system or iteration budget is invalid.");
foreach (var objective in objectives)
{
if (objective.Length != columnCount)
throw new ArgumentException("An objective has an incorrect number of columns.");
}
if (rowCount == 0)
return new LinearSolveResult(LinearSolveStatus.Optimal, new double[columnCount]);
// Optimal values scale linearly with the right-hand side; normalize it so tolerances do not depend on rates.
var rightHandScale = 0.0;
foreach (var value in rightHandSide)
{
if (double.IsNaN(value) || double.IsInfinity(value))
throw new ArgumentException("The right-hand side contains a non-finite number.");
rightHandScale = Math.Max(rightHandScale, Math.Abs(value));
}
if (rightHandScale == 0) rightHandScale = 1;
var width = columnCount + rowCount;
var tableau = new double[rowCount, width + 1];
var basis = new int[rowCount];
var isBasic = new bool[width];
for (var row = 0; row < rowCount; row++)
{
var scale = 0.0;
for (var column = 0; column < columnCount; column++)
{
if (double.IsNaN(coefficients[row, column]) || double.IsInfinity(coefficients[row, column]))
throw new ArgumentException("The constraint matrix contains a non-finite number.");
scale = Math.Max(scale, Math.Abs(coefficients[row, column]));
}
var rightHand = rightHandSide[row] / rightHandScale;
if (scale == 0)
{
if (Math.Abs(rightHand) > PivotTolerance)
return new LinearSolveResult(LinearSolveStatus.Infeasible);
scale = 1;
}
var sign = rightHand < 0 ? -1 : 1;
for (var column = 0; column < columnCount; column++)
tableau[row, column] = sign * coefficients[row, column] / scale;
tableau[row, columnCount + row] = 1;
tableau[row, width] = sign * rightHand / scale;
basis[row] = columnCount + row;
isBasic[columnCount + row] = true;
}
var artificialObjective = new double[width];
for (var row = 0; row < rowCount; row++) artificialObjective[columnCount + row] = 1;
var iterations = 0;
var firstStatus = Optimize(tableau, basis, isBasic, artificialObjective, Array.Empty<double[]>(),
columnCount, ref iterations, iterationBudget, cancellation);
if (firstStatus != LinearSolveStatus.Optimal)
return new LinearSolveResult(firstStatus == LinearSolveStatus.Unbounded
? LinearSolveStatus.Infeasible : firstStatus);
for (var row = 0; row < rowCount; row++)
{
if (basis[row] < columnCount) continue;
if (Math.Abs(tableau[row, width]) > ReducedTolerance)
return new LinearSolveResult(LinearSolveStatus.Infeasible);
// The remaining artificial counts as zero. Pivot it out on its largest coefficient at exactly zero so a
// tiny residual divided by a tiny coefficient cannot move the other rows.
var pivotColumn = -1;
for (var column = 0; column < columnCount; column++)
{
if (isBasic[column] || Math.Abs(tableau[row, column]) <= PivotTolerance) continue;
if (pivotColumn < 0 || Math.Abs(tableau[row, column]) > Math.Abs(tableau[row, pivotColumn]))
pivotColumn = column;
}
if (pivotColumn < 0) continue;
tableau[row, width] = 0;
Pivot(tableau, basis, isBasic, row, pivotColumn);
}
var optimizedObjectives = new List<double[]>();
foreach (var objective in objectives)
{
var costs = new double[width];
Array.Copy(objective, costs, columnCount);
var status = Optimize(tableau, basis, isBasic, costs, optimizedObjectives, columnCount,
ref iterations, iterationBudget, cancellation);
if (status != LinearSolveStatus.Optimal) return new LinearSolveResult(status);
optimizedObjectives.Add(costs);
}
var values = new double[columnCount];
for (var row = 0; row < rowCount; row++)
{
if (basis[row] < columnCount)
values[basis[row]] = Math.Max(0, tableau[row, width]) * rightHandScale;
}
return new LinearSolveResult(LinearSolveStatus.Optimal, values);
}
private static LinearSolveStatus Optimize(double[,] tableau, int[] basis, bool[] isBasic, double[] costs,
IReadOnlyList<double[]> previousCosts, int enteringLimit, ref int iterations, int budget,
CancellationToken cancellation)
{
var rowCount = basis.Length;
var rightColumn = tableau.GetLength(1) - 1;
while (true)
{
if (cancellation.IsCancellationRequested) return LinearSolveStatus.Cancelled;
var entering = -1;
for (var column = 0; column < enteringLimit; column++)
{
if (isBasic[column] || ReducedCost(tableau, basis, costs, column) >= -ReducedTolerance)
continue;
var preservesPrevious = true;
foreach (var previous in previousCosts)
{
if (Math.Abs(ReducedCost(tableau, basis, previous, column)) <= ReducedTolerance) continue;
preservesPrevious = false;
break;
}
if (preservesPrevious)
{
entering = column;
break;
}
}
if (entering < 0) return LinearSolveStatus.Optimal;
if (iterations >= budget) return LinearSolveStatus.IterationLimit;
var leaving = -1;
var minRatio = double.PositiveInfinity;
for (var row = 0; row < rowCount; row++)
{
var coefficient = tableau[row, entering];
if (coefficient <= PivotTolerance) continue;
var ratio = Math.Max(0, tableau[row, rightColumn]) / coefficient;
// Ties are relative: an absolute tolerance would merge distinct small ratios and leave a row infeasible.
var tie = leaving < 0 ? 0 : RatioTieTolerance * Math.Max(ratio, minRatio);
if (ratio < minRatio - tie ||
Math.Abs(ratio - minRatio) <= tie && (leaving < 0 || basis[row] < basis[leaving]))
{
minRatio = ratio;
leaving = row;
}
}
if (leaving < 0) return LinearSolveStatus.Unbounded;
Pivot(tableau, basis, isBasic, leaving, entering);
iterations++;
}
}
private static double ReducedCost(double[,] tableau, int[] basis, double[] costs, int column)
{
var reduced = costs[column];
for (var row = 0; row < basis.Length; row++)
reduced -= costs[basis[row]] * tableau[row, column];
return reduced;
}
private static void Pivot(double[,] tableau, int[] basis, bool[] isBasic, int pivotRow, int pivotColumn)
{
var rowCount = basis.Length;
var width = tableau.GetLength(1);
var divisor = tableau[pivotRow, pivotColumn];
for (var column = 0; column < width; column++)
tableau[pivotRow, column] /= divisor;
for (var row = 0; row < rowCount; row++)
{
if (row == pivotRow) continue;
var factor = tableau[row, pivotColumn];
if (factor == 0) continue;
for (var column = 0; column < width; column++)
tableau[row, column] -= factor * tableau[pivotRow, column];
tableau[row, pivotColumn] = 0;
}
tableau[pivotRow, pivotColumn] = 1;
isBasic[basis[pivotRow]] = false;
isBasic[pivotColumn] = true;
basis[pivotRow] = pivotColumn;
}
}