economy balance: static implied-wage, derived-cost and belt report

EconomyChecks.Columns is now the one reader of a recipe's per-cycle
consumption (Productive builds its matrix over it). EconomyBalance reads
the same columns: implied wage per link, prices derived from inputs plus
labour at the median wage, H-margin and H-wage health faults (report-only,
not a batch Shape invariant), belt rows. `economy balance` prints it.
GameplaySettings.EconomyWageSpread is the one tolerance.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-26 17:52:29 +01:00
commit a2e8e89292
6 changed files with 330 additions and 12 deletions

View file

@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
// One recipe read as a chain link. Wage is the implied credits per worker-second at the authored prices; null when the link
// is unpriced (an input, filler or output at Price 0) or has no labour. Cost is the derived cost of one output unit.
public sealed class BalanceLink
{
public string Output, Name, StationKind;
public double Labour, Price, Cost;
public double? Wage;
public double? WageRatio;
}
// One ore a kind of belt holds: its share of the kind's abundance, its extraction link's wage over the median, its price and cost.
public sealed class BeltYield
{
public string Ore;
public double Share, Price, Cost;
public double? WageRatio;
}
public sealed class BeltRow
{
public string Kind;
public List<BeltYield> Yields = new List<BeltYield>();
public double Price, Cost;
}
public sealed class BalanceReport
{
public double WageReference;
public List<BalanceLink> Links;
public List<EconomyFault> Faults;
public List<BeltRow> Belts;
}
// The static economy balance: a steady-state input-output reading of the authored chain (Leontief 1936; Sraffa 1960 zero-profit
// prices under one wage; Samuelson 1951: with labour the only primary factor the cheapest filler of a role is demand-independent).
// Pure: reads the catalog, writes nothing. Its faults are report-only and never a refusal; the authored ItemData.Price stays the
// only price the game charges.
public static class EconomyBalance
{
public const string HMargin = "H-margin", HWage = "H-wage", HConverge = "H-converge";
private const int SweepCap = 10000;
public static BalanceReport Balance(CultCache catalog, double wageSpread = 2)
{
var columns = EconomyChecks.Columns(catalog);
double Price(string key) => catalog.Get<ItemData>(new CultRecordKey(key))?.Price ?? 0;
// Authored-price wage per link; the cheapest priced filler fills a role.
double? CheapestPriced(string[] fillers) => fillers.Select(Price).Where(p => p > 0).Select(p => (double?) p).Min();
var links = new List<BalanceLink>();
foreach (var c in columns)
{
var link = new BalanceLink { Output = c.Output, Name = catalog.Get(c.Recipe.Output)?.Name ?? c.Output, Labour = c.Labour, Price = Price(c.Output), StationKind = catalog.Get(c.Recipe.StationKind)?.Name ?? "no kind" };
var cost = 0.0;
var priced = link.Price > 0 && c.Labour > 0;
foreach (var (commodity, count) in c.Inputs.Concat(c.Upkeep))
{
if (count <= 0) continue;
var p = Price(commodity);
if (p <= 0) priced = false;
cost += count * p;
}
foreach (var slot in c.Slots)
{
if (slot.Count <= 0) continue;
var p = CheapestPriced(slot.Fillers);
if (p == null) priced = false;
else cost += slot.Count * p.Value;
}
if (priced) link.Wage = (c.OutputCount * link.Price - cost) / c.Labour;
links.Add(link);
}
var wages = links.Where(l => l.Wage.HasValue).Select(l => l.Wage.Value).OrderBy(w => w).ToList();
var reference = wages.Count == 0 ? 0 : wages.Count % 2 == 1 ? wages[wages.Count / 2] : (wages[wages.Count / 2 - 1] + wages[wages.Count / 2]) / 2;
foreach (var l in links) l.WageRatio = reference > 0 ? l.Wage / reference : null;
// Derived cost: value iteration from zero. A good with no recipe holds its authored price as a stand-in.
var derived = new Dictionary<string, double>(StringComparer.Ordinal);
foreach (var c in columns) derived[c.Output] = 0;
double Cost(string key) => derived.TryGetValue(key, out var v) ? v : Price(key);
var converged = false;
for (var sweep = 0; sweep < SweepCap && !converged; sweep++)
{
converged = true;
foreach (var c in columns)
{
var sum = reference * c.Labour;
foreach (var (commodity, count) in c.Inputs.Concat(c.Upkeep)) if (count > 0) sum += count * Cost(commodity);
foreach (var slot in c.Slots)
if (slot.Count > 0 && slot.Fillers.Length > 0) sum += slot.Count * slot.Fillers.Min(Cost);
var next = sum / c.OutputCount;
if (Math.Abs(next - derived[c.Output]) > 1e-12 * Math.Max(1, Math.Abs(next))) converged = false;
derived[c.Output] = next;
}
}
foreach (var l in links) l.Cost = derived[l.Output];
var faults = new List<EconomyFault>();
if (!converged) faults.Add(new EconomyFault(HConverge, "(chain)", $"Derived cost did not settle within {SweepCap} sweeps."));
foreach (var l in links.Where(l => l.Wage.HasValue))
{
if (l.Wage.Value <= 0)
faults.Add(new EconomyFault(HMargin, l.Output, $"{l.Name} sells at or below its inputs: implied wage {l.Wage.Value:0.#####} per worker-second."));
else if (reference > 0 && (l.Wage.Value < reference / wageSpread || l.Wage.Value > reference * wageSpread))
faults.Add(new EconomyFault(HWage, l.Output, $"{l.Name}: implied wage {l.Wage.Value:0.#####} is {l.WageRatio:0.##}x the median {reference:0.#####}, outside the spread of {wageSpread:0.##}."));
}
var belts = new List<BeltRow>();
foreach (var kind in catalog.GetAll<FieldKindData>().OrderBy(k => k.Name, StringComparer.Ordinal))
{
var row = new BeltRow { Kind = kind.Name };
var total = kind.Yields.Where(y => y.Abundance > 0).Sum(y => (double) y.Abundance);
foreach (var y in kind.Yields.Where(y => y.Abundance > 0 && total > 0))
{
var ore = y.Commodity.Key.Value;
var share = y.Abundance / total;
var yield = new BeltYield { Ore = ore, Share = share, Price = Price(ore), Cost = Cost(ore), WageRatio = links.FirstOrDefault(l => l.Output == ore)?.WageRatio };
row.Price += share * yield.Price;
row.Cost += share * yield.Cost;
row.Yields.Add(yield);
}
belts.Add(row);
}
return new BalanceReport { WageReference = reference, Links = links, Faults = faults, Belts = belts };
}
}

View file

@ -315,6 +315,35 @@ public static class EconomyChecks
return deepest + 1;
}
// One recipe's consumption per cycle, unscaled: the one reader of what a recipe takes, for Productive's matrix and EconomyBalance.
// Labour is Workforce x Cycle worker-seconds; Slots are the role slots (a role recipe's design roles, or the recipe's RoleInputs)
// with every commodity that fills the role.
internal sealed class Column
{
public string Output;
public RecipeData Recipe;
public bool IsCommodity;
public int OutputCount;
public double Labour;
public List<(string Commodity, int Count)> Inputs;
public List<(string Commodity, int Count)> Upkeep;
public List<(string Role, int Count, string[] Fillers)> Slots;
}
// Every recipe whose output exists, produces something and has a finite cycle, ordered by output key.
internal static List<Column> Columns(CultCache catalog) =>
AllRecipes(catalog).Where(p => catalog.Get(p.Recipe.Output) != null && p.Recipe.OutputCount > 0 && float.IsFinite(p.Recipe.Cycle)).Select(p => new Column
{
Output = p.Recipe.Output.Key.Value,
Recipe = p.Recipe,
IsCommodity = Recipes.IsCommodity(catalog.Get(p.Recipe.Output)),
OutputCount = p.Recipe.OutputCount,
Labour = p.Recipe.Workforce * (double) p.Recipe.Cycle,
Inputs = p.Recipe.Inputs.Select(i => (i.Commodity.Key.Value, i.Count)).ToList(),
Upkeep = p.Recipe.Upkeep.Select(i => (i.Commodity.Key.Value, i.Count)).ToList(),
Slots = Recipes.RoleInputsOf(catalog, p.Recipe).Select(r => (r.Name, r.Count, Recipes.Fillers(catalog, r.Name).Select(k => k.Value).ToArray())).ToList()
}).ToList();
// Hawkins-Simon over commodities plus one labour good, at the worst single filler of every role slot (a recipe's role inputs): the spectral radius
// of the requirements matrix stays below one however the roles are filled. The worst fill is the spectral simplex
// (Nesterov and Protasov 2013) on the matrix nudged strictly positive, then the radius of the chosen matrix is taken exactly.
@ -323,8 +352,8 @@ public static class EconomyChecks
load = load ?? new EconomyLoad();
if (!(load.InputFactor >= 1) || !(load.WorkforceFactor >= 1) || !(load.UpkeepFactor >= 1))
throw new ArgumentException("Setting factors are at least 1.", nameof(load));
var columns = AllRecipes(catalog).Where(p => Recipes.IsCommodity(catalog.Get(p.Recipe.Output)) && p.Recipe.OutputCount > 0 && float.IsFinite(p.Recipe.Cycle)).ToList();
var names = columns.Select(p => p.Recipe.Output.Key.Value).ToList();
var columns = Columns(catalog).Where(c => c.IsCommodity).ToList();
var names = columns.Select(c => c.Output).ToList();
var index = new Dictionary<string, int>(StringComparer.Ordinal);
for (var i = 0; i < names.Count; i++) index[names[i]] = i;
var n = names.Count + 1;
@ -333,16 +362,16 @@ public static class EconomyChecks
var slots = new List<(int Column, double Amount, int[] Fillers)>();
for (var j = 0; j < columns.Count; j++)
{
var recipe = columns[j].Recipe;
foreach (var input in recipe.Inputs)
if (index.TryGetValue(input.Commodity.Key.Value, out var row) && input.Count > 0) fixedTerms[row, j] += input.Count * load.InputFactor / recipe.OutputCount;
foreach (var upkeep in recipe.Upkeep)
if (index.TryGetValue(upkeep.Commodity.Key.Value, out var row) && upkeep.Count > 0) fixedTerms[row, j] += upkeep.Count * load.UpkeepFactor / recipe.OutputCount;
fixedTerms[labour, j] = recipe.Workforce * (double) recipe.Cycle * load.WorkforceFactor / recipe.OutputCount;
foreach (var role in Recipes.RoleInputsOf(catalog, recipe))
var column = columns[j];
foreach (var input in column.Inputs)
if (index.TryGetValue(input.Commodity, out var row) && input.Count > 0) fixedTerms[row, j] += input.Count * load.InputFactor / column.OutputCount;
foreach (var upkeep in column.Upkeep)
if (index.TryGetValue(upkeep.Commodity, out var row) && upkeep.Count > 0) fixedTerms[row, j] += upkeep.Count * load.UpkeepFactor / column.OutputCount;
fixedTerms[labour, j] = column.Labour * load.WorkforceFactor / column.OutputCount;
foreach (var slot in column.Slots)
{
var fillers = Recipes.Fillers(catalog, role.Name).Where(k => index.ContainsKey(k.Value)).Select(k => index[k.Value]).ToArray();
if (fillers.Length > 0 && role.Count > 0) slots.Add((j, role.Count * load.InputFactor / recipe.OutputCount, fillers));
var fillers = slot.Fillers.Where(k => index.ContainsKey(k)).Select(k => index[k]).ToArray();
if (fillers.Length > 0 && slot.Count > 0) slots.Add((j, slot.Count * load.InputFactor / column.OutputCount, fillers));
}
}
foreach (var need in load.LabourNeeds)

View file

@ -189,6 +189,8 @@ public class GameplaySettings
// What a station charges to restore worn gear, as a fraction of the price of the wear.
public float RepairFraction = .25f;
public int StartingCredits = 150000;
// A tuning tolerance, not a price: `economy balance` flags a chain link whose implied wage falls outside [median / k, median x k].
public float EconomyWageSpread = 2;
public float DurabilityQualityExponent = 2;
public float DurabilityQualityMin = 2;
public float DurabilityQualityMax = .25f;

View file

@ -0,0 +1,122 @@
using System;
using System.Linq;
using GameCult.Caching;
using Xunit;
// The static economy balance (EconomyBalance): implied wage per chain link, prices derived from inputs and labour, the report-only
// health faults. Fixture chains are hand-solved; the shipped catalog test asserts reach, never a fault count (faults are tuning state).
public sealed class EconomyBalanceTests
{
private static void Price(EconomyFixture f, string key, int price)
{
var item = f.Cache.Get<ItemData>(new CultRecordKey(key));
item.Price = price;
f.Cache.Upsert(item.GetType(), item, new CultRecordKey(key));
}
private static void Labour(EconomyFixture f, string key, int workforce, float cycle) =>
f.EditRecipe(key, r => { r.Workforce = workforce; r.Cycle = cycle; r.OutputCount = Math.Max(1, r.OutputCount); });
// ore (labour 20, price 50) -> bar (2 per cycle from 3 ore, labour 10, price 80) -> part (2 bars, labour 4, price 200), all times scale.
// Wages 2.5, 1, 10: median 2.5. Derived cost at 2.5: ore 50, bar (3 x 50 + 2.5 x 10) / 2 = 87.5, part 2 x 87.5 + 2.5 x 4 = 185.
private static EconomyFixture Chain(int scale = 1)
{
var f = new EconomyFixture();
f.Good("ore", workforce: 2, cycle: 10);
f.Good("bar", inputs: new[] { ("ore", 3) }, outputCount: 2, workforce: 2, cycle: 5);
f.Good("part", inputs: new[] { ("bar", 2) }, workforce: 1, cycle: 4);
Price(f, "commodity:ore", 50 * scale);
Price(f, "commodity:bar", 80 * scale);
Price(f, "commodity:part", 200 * scale);
return f;
}
private static BalanceLink Link(BalanceReport r, string key) => r.Links.Single(l => l.Output == key);
[Fact]
public void ALinkSellingBelowItsInputsIsAMarginFault()
{
using var f = new EconomyFixture();
f.Good("ore", workforce: 1, cycle: 1);
f.Good("bar", inputs: new[] { ("ore", 2) }, workforce: 1, cycle: 1);
Price(f, "commodity:ore", 10);
Price(f, "commodity:bar", 5);
var report = EconomyBalance.Balance(f.Cache);
var fault = Assert.Single(report.Faults, x => x.Invariant == EconomyBalance.HMargin);
Assert.Equal("commodity:bar", fault.Record);
Assert.Equal(-15, Link(report, "commodity:bar").Wage.Value, 9);
}
[Fact]
public void TheCheaperFillerSetsTheDerivedCost()
{
using var f = new EconomyFixture();
f.Good("ore", workforce: 1, cycle: 1);
// The dearer filler sorts first, so a first-filler pick and a max both read it.
f.Good("a-dear", inputs: new[] { ("ore", 3) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1);
f.Good("z-cheap", inputs: new[] { ("ore", 1) }, fills: new[] { "Plate" }, workforce: 1, cycle: 1);
var gear = f.Gear("laser", new[] { ("Plate", 1) });
Labour(f, gear, 1, 1);
Price(f, "commodity:ore", 10);
Price(f, "commodity:a-dear", 40);
Price(f, "commodity:z-cheap", 30);
f.EditItem<GearData>(gear, g => g.Price = 100);
// Wages 10, 10, 20, 70: median 15. C: ore 15, a-dear 60, z-cheap 30, laser min(60, 30) + 15 = 45.
var report = EconomyBalance.Balance(f.Cache);
Assert.Equal(15, report.WageReference, 9);
Assert.Equal(45, Link(report, gear).Cost, 9);
}
[Fact]
public void DerivedCostMatchesTheHandSolvedChain()
{
using var f = Chain();
var report = EconomyBalance.Balance(f.Cache);
Assert.Equal(2.5, report.WageReference, 9);
Assert.Equal(50, Link(report, "commodity:ore").Cost, 9);
Assert.Equal(87.5, Link(report, "commodity:bar").Cost, 9);
Assert.Equal(185, Link(report, "commodity:part").Cost, 9);
}
[Fact]
public void ScalingEveryPriceScalesTheWageAndNoFault()
{
using var one = Chain();
using var hundred = Chain(100);
var a = EconomyBalance.Balance(one.Cache);
var b = EconomyBalance.Balance(hundred.Cache);
Assert.NotEmpty(a.Faults);
Assert.Equal(a.WageReference * 100, b.WageReference, 7);
Assert.Equal(a.Faults.Select(x => x.Invariant + x.Record), b.Faults.Select(x => x.Invariant + x.Record));
foreach (var link in a.Links) Assert.Equal(link.WageRatio.Value, Link(b, link.Output).WageRatio.Value, 9);
}
[Fact]
public void AnUnpricedLinkHasNoWage()
{
using var f = new EconomyFixture();
f.Good("ore", workforce: 1, cycle: 1);
f.Good("bar", inputs: new[] { ("ore", 1) }, workforce: 1, cycle: 1);
f.Good("tin", workforce: 1, cycle: 1);
Price(f, "commodity:bar", 80);
Price(f, "commodity:tin", 7);
var report = EconomyBalance.Balance(f.Cache);
Assert.Null(Link(report, "commodity:ore").Wage);
Assert.Null(Link(report, "commodity:bar").Wage);
Assert.Equal(7, report.WageReference, 9);
Assert.Empty(report.Faults);
}
[Fact]
public void ShippedCatalogBalanceListsTheMaterializedChain()
{
using var cache = RestoredHullsTests.OpenCatalog();
var report = EconomyBalance.Balance(cache);
var expected = cache.GetAll<RecipeData>().Count(r => cache.Get(r.Output) != null && r.OutputCount > 0 && float.IsFinite(r.Cycle));
Assert.Equal(expected, report.Links.Count);
Assert.Contains(report.Links, l => l.Output == "commodity:steel");
var guns = cache.GetAll<RecipeData>().Where(r => Recipes.IsRoleRecipe(cache, r) && !Recipes.IsCommodity(cache.Get(r.Output))).Select(r => r.Output.Key.Value).ToArray();
Assert.True(guns.Length >= 9);
Assert.All(guns, g => Assert.Contains(report.Links, l => l.Output == g));
}
}

View file

@ -73,6 +73,12 @@ public static class EconomyCommand
return Report(db.Cache, output);
}
if (args.Length > 0 && args[0] == "prices") return EconomyPrices.Run(args.Skip(1).ToArray(), output);
if (args.Length > 0 && args[0] == "balance")
{
using var db = AetherDb.Open();
var spread = AuthoredSettings.Load(db.Root).Read<GameplaySettings>("GameplaySettings").EconomyWageSpread;
return Balance(db.Cache, spread, output);
}
if (args.Length > 1 && args[0] == "author")
{
var apply = args.Contains("apply");
@ -92,6 +98,33 @@ public static class EconomyCommand
return 1;
}
// The static balance: the median implied wage, the H faults, one line per chain link by wage over the median, then the belts.
// Report-only: nothing here is a Shape invariant. Exit 1 when any fault.
public static int Balance(CultCache catalog, double wageSpread, TextWriter output)
{
var report = EconomyBalance.Balance(catalog, wageSpread);
var inv = System.Globalization.CultureInfo.InvariantCulture;
output.WriteLine($"median implied wage {report.WageReference.ToString("0.#####", inv)} per worker-second, spread {wageSpread.ToString(inv)}, {report.Links.Count} links, {report.Links.Count(l => l.Wage == null)} unpriced");
output.WriteLine($"{report.Faults.Count} faults");
foreach (var group in report.Faults.GroupBy(f => f.Invariant).OrderBy(g => g.Key, StringComparer.Ordinal))
{
output.WriteLine($"{group.Key} ({group.Count()})");
foreach (var fault in group) output.WriteLine($" {fault.Record}: {fault.Message}");
}
output.WriteLine("\nLinks by wage over the median (output | station kind | labour | price | derived cost | wage | ratio)");
foreach (var l in report.Links.OrderBy(l => l.WageRatio ?? double.PositiveInfinity).ThenBy(l => l.Output, StringComparer.Ordinal))
output.WriteLine(string.Format(inv, " {0} ({7}) | {1} | {2:0.#} | {3:0.##} | {4:0.##} | {5} | {6}", l.Output, l.StationKind, l.Labour, l.Price, l.Cost,
l.Wage.HasValue ? l.Wage.Value.ToString("0.#####", inv) : "unpriced", l.WageRatio.HasValue ? l.WageRatio.Value.ToString("0.##", inv) + "x" : "-"));
output.WriteLine("\nBelts (kind: abundance-weighted price and derived cost per unit; each ore: share, extraction wage ratio, price, cost)");
foreach (var belt in report.Belts)
{
output.WriteLine(string.Format(inv, " {0}: price {1:0.##}, cost {2:0.##}", belt.Kind, belt.Price, belt.Cost));
foreach (var y in belt.Yields)
output.WriteLine(string.Format(inv, " {0} {1:P0} | wage {2} | price {3:0.##} | cost {4:0.##}", y.Ore, y.Share, y.WageRatio.HasValue ? y.WageRatio.Value.ToString("0.##", inv) + "x" : "-", y.Price, y.Cost));
}
return report.Faults.Count == 0 ? 0 : 1;
}
// Faults grouped by invariant, then one line per good with its depth, then one line per recipe. Fails on any fault.
public static int Report(CultCache catalog, TextWriter output)
{

View file

@ -81,7 +81,7 @@ public static class Program
case "auto-guns": return AutoGunsCatalog.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out);
case "doctrine-catalog": return DoctrineCatalog.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out);
default:
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], loadout-commit <name> <hull product> [<x>,<y>,<rotation>,<design>[@<product>]]... [--group <i>,<j>...]... [--replace] [--boss-of <faction>], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], range-falloff [apply] [--effective <fraction>] [--end <multiplier>], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], launch-suppressor [apply], pirates-faction [apply], verse-grammar [apply], generic-designs [apply], sensor-stat-set [apply], inspection-scanner [apply], minor-power-factions [apply], place-names [apply], product-lines weapons|minor-powers|gear|tiers [apply], doctrine-catalog [apply], auto-guns [apply], assembly-from-maker [apply], station-kinds [hull \"<name>\" <kind>] [apply], economy report|prices|author <batch>... [apply]");
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], loadout-commit <name> <hull product> [<x>,<y>,<rotation>,<design>[@<product>]]... [--group <i>,<j>...]... [--replace] [--boss-of <faction>], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], range-falloff [apply] [--effective <fraction>] [--end <multiplier>], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], launch-suppressor [apply], pirates-faction [apply], verse-grammar [apply], generic-designs [apply], sensor-stat-set [apply], inspection-scanner [apply], minor-power-factions [apply], place-names [apply], product-lines weapons|minor-powers|gear|tiers [apply], doctrine-catalog [apply], auto-guns [apply], assembly-from-maker [apply], station-kinds [hull \"<name>\" <kind>] [apply], economy report|prices|author <batch>... [apply]|balance");
return 1;
}
}