From 4520f786407e2868855f4256a0b781252c34483e Mon Sep 17 00:00:00 2001 From: soul Date: Fri, 27 Nov 2026 06:43:01 +0100 Subject: [PATCH] economy balance --loop fix batch: every belt its own sample, AmmoOut and RigFault outcomes kept out of the rate, exact accounting pins, committed golden of base output, finite positive cap Co-Authored-By: Claude Sonnet 5.5 --- .../Aetheria.Shared.Tests/EconomyLoopTests.cs | 152 ++++++++++++++++-- .../Golden/economy-balance-base.txt | 130 +++++++++++++++ tools/AetherDb/EconomyCommand.cs | 14 +- tools/AetherDb/EconomyLoop.cs | 130 +++++++++++---- 4 files changed, 373 insertions(+), 53 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/Golden/economy-balance-base.txt diff --git a/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs index ca6264501..3af46fdd3 100644 --- a/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyLoopTests.cs @@ -8,16 +8,16 @@ using Xunit; // the H faults, on fixture catalogs whose numbers are solved by hand. The sortie itself runs on the shipped catalog. public sealed class EconomyLoopTests { - private static LoopSample Sample(uint seed, int sell, int ammo, int repair, double seconds) => - new LoopSample { Seed = seed, BeltKind = "belt", Weapons = "gun", SimSeconds = seconds, SellValue = sell, AmmoSpent = ammo, Repair = repair }; + private static LoopSample Sample(uint seed, int sell, int ammo, int repair, double seconds, LoopOutcome outcome = LoopOutcome.Capped) => + new LoopSample { Seed = seed, Belts = 1, BeltKind = "belt", Weapons = "gun", SimSeconds = seconds, SellValue = sell, AmmoSpent = ammo, Repair = repair, Outcome = outcome, Note = "why" }; private static GameplaySettings Settings(float min = 0, float max = 0, int purse = 100000) => new GameplaySettings { StartingCredits = purse, EconomyLadderMin = min, EconomyLadderMax = max }; // A gear in `hardpoint` offered at `price`, with a recipe so it is an offered design. - private static void Offer(EconomyFixture f, string id, HardpointType hardpoint, int price) + private static void Offer(EconomyFixture f, string id, HardpointType hardpoint, int price, int plates = 1) { - var key = f.Gear(id, new[] { ("Plate", 1) }); + var key = f.Gear(id, new[] { ("Plate", plates) }); f.EditItem(key, g => { g.Hardpoint = hardpoint; g.Price = price; }); } @@ -45,6 +45,38 @@ public sealed class EconomyLoopTests Offer(f, "cannon", HardpointType.Tool, 600); var report = EconomyLoop.Report(f.Cache, Settings(purse: 599), new[] { Sample(1, 1000, 0, 0, 60) }); Assert.False(Ladder(report, "Gear/Tool").Designs.Single(d => d.Key == "gear:cannon").Covered); + // A design priced exactly at the purse is covered. + report = EconomyLoop.Report(f.Cache, Settings(purse: 600), new[] { Sample(1, 1000, 0, 0, 60) }); + Assert.True(Ladder(report, "Gear/Tool").Designs.Single(d => d.Key == "gear:cannon").Covered); + } + + [Fact] + public void ABandWithOnlyOneSideFaultsOnlyThatSide() + { + using var f = EconomyFixture.Healthy(); + Offer(f, "cheap", HardpointType.Reactor, 10); + Offer(f, "dear", HardpointType.Reactor, 1000); + var samples = new[] { Sample(1, 1000, 0, 0, 60) }; + // 100x against a floor of 10 alone, and against a ceiling of 30 alone. + Assert.DoesNotContain(EconomyLoop.Report(f.Cache, Settings(10, 0), samples).Faults, x => x.Record == "Gear/Reactor"); + Assert.Contains(EconomyLoop.Report(f.Cache, Settings(0, 30), samples).Faults, x => x.Record == "Gear/Reactor"); + Assert.Contains(EconomyLoop.Report(f.Cache, Settings(200, 0), samples).Faults, x => x.Record == "Gear/Reactor"); + Assert.DoesNotContain(EconomyLoop.Report(f.Cache, Settings(0, 200), samples).Faults, x => x.Record == "Gear/Reactor"); + } + + [Fact] + public void ADerivedWidthOutsideTheBandIsAFaultAlthoughTheAuthoredOneIsInIt() + { + using var f = EconomyFixture.Healthy(); + // Authored 2x; derived from one plate against ten, 10x. + f.EditItem("commodity:ore", o => o.Price = 10); + Offer(f, "thin", HardpointType.Reactor, 100, plates: 1); + Offer(f, "thick", HardpointType.Reactor, 200, plates: 10); + var report = EconomyLoop.Report(f.Cache, Settings(1, 5), new[] { Sample(1, 1000, 0, 0, 60) }); + Assert.Equal(2, Ladder(report, "Gear/Reactor").WidthAuthored.Value, 9); + Assert.Equal(10, Ladder(report, "Gear/Reactor").WidthDerived.Value, 9); + var fault = Assert.Single(report.Faults, x => x.Invariant == EconomyLoop.HLadder); + Assert.Contains("derived", fault.Message); } [Fact] @@ -99,7 +131,32 @@ public sealed class EconomyLoopTests // Gross positive in all three; net 0, -1 and 1: only the last earns anything. var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(1, 100, 60, 40, 60), Sample(2, 100, 60, 41, 60), Sample(3, 100, 60, 39, 60) }); var faults = report.Faults.Where(x => x.Invariant == EconomyLoop.HLoop).Select(x => x.Record).OrderBy(x => x, StringComparer.Ordinal).ToArray(); - Assert.Equal(new[] { "seed 1", "seed 2" }, faults); + Assert.Equal(new[] { "seed 1 belt 1 of 1", "seed 2 belt 1 of 1" }, faults); + } + + [Fact] + public void AmmoOutAndRigFaultSortiesAreOutcomesNotIdleIncome() + { + using var f = EconomyFixture.Healthy(); + var report = EconomyLoop.Report(f.Cache, Settings(), new[] + { + Sample(1, 1000, 0, 0, 60), Sample(2, 3000, 0, 0, 60), + // Strongly negative if they were folded in; neither is a rate. + Sample(3, 10, 500, 0, 12, LoopOutcome.AmmoOut), Sample(4, 0, 0, 4, 1, LoopOutcome.RigFault) + }); + Assert.Equal(2000, report.Median, 9); + Assert.Equal(3000, report.Best, 9); + Assert.Equal(new[] { "H-ammo", "H-rig" }, report.Faults.Select(x => x.Invariant).OrderBy(x => x, StringComparer.Ordinal).ToArray()); + Assert.DoesNotContain(report.Faults, x => x.Invariant == EconomyLoop.HLoop); + } + + [Fact] + public void WithNoMeasuredSortieThereIsNoRateAndNoMinutes() + { + using var f = EconomyFixture.Healthy(); + var report = EconomyLoop.Report(f.Cache, Settings(), new[] { Sample(3, 10, 500, 0, 12, LoopOutcome.AmmoOut) }); + Assert.Equal(0, report.Median); + Assert.All(report.Ladders.SelectMany(l => l.Designs), d => Assert.Null(d.MinutesAtMedian)); } [Fact] @@ -116,31 +173,94 @@ public sealed class EconomyLoopTests Assert.Equal(plain["commodity:plate"], withDesigns["hull:skiff"], 9); } + private static string Root => RunStartTests.FindRepoRoot(); + + // The price the catalog authors for a simple commodity of that name. + private static int PriceOf(string name) + { + using var db = AetherDb.Open(); + return db.Cache.GetAll().Single(c => c.Name == name).Price; + } + [Fact] public void SortieLeavesTheCatalogAndMinesSomething() { - var root = RunStartTests.FindRepoRoot(); - var catalog = Path.Combine(root, "GameData", "Aetheria.cc"); + var catalog = Path.Combine(Root, "GameData", "Aetheria.cc"); var before = System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(catalog)); - var sample = EconomyLoop.Sortie(root, 1, 60); + var sample = EconomyLoop.Sortie(Root, 1, 0, 60); Assert.True(sample.Units > 0); Assert.True(sample.Rocks > 0); Assert.Equal(60, sample.SimSeconds, 1); + Assert.Equal(LoopOutcome.Capped, sample.Outcome); Assert.Equal(before, System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(catalog))); } + [Fact] + public void AFullHoldSortieIsPricedFromTheShipItEndedWith() + { + int ore = -1, repair = -1; + var sample = EconomyLoop.Sortie(Root, 1, 0, 300, (ship, items) => + { + ore = StationServices.OreValue(items, ship.CargoBays); + repair = StationServices.RepairCost(items, ship); + }); + Assert.Equal(LoopOutcome.Full, sample.Outcome); + Assert.True(sample.HoldFullAt > 0 && sample.HoldFullAt <= sample.SimSeconds); + Assert.True(sample.SellValue > 0); + Assert.Equal(ore, sample.SellValue); + Assert.True(sample.Repair > 0); + Assert.Equal(repair, sample.Repair); + // Laser fit: no ammunition is spent. + Assert.Equal(0, sample.AmmoSpent); + } + + [Fact] + public void ASortieThatSpendsItsStarterAmmunitionEndsAmmoOutAndPaysForIt() + { + var ammoLeft = -1; + var sample = EconomyLoop.Sortie(Root, 2, 0, 150, (ship, items) => + ammoLeft = ship.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Where(c => items.GetData(c).Name == "Ammo").Sum(c => c.Quantity)); + Assert.Equal(LoopOutcome.AmmoOut, sample.Outcome); + Assert.Equal(0, ammoLeft); + // The Cell Blaster fit starts with 3 Ammo, bought back at the catalog's price. + Assert.Equal(3 * PriceOf("Ammo"), sample.AmmoSpent); + Assert.True(sample.SimSeconds < 150); + } + + [Fact] + public void EveryBeltOfTheZoneIsItsOwnSampleAndAnUnlitOneIsARigFault() + { + var samples = EconomyLoop.Sorties(Root, 2, 5); + Assert.Equal(2, samples.Count); + Assert.All(samples, x => Assert.Equal(2, x.Belts)); + Assert.Equal(new[] { 0, 1 }, samples.Select(x => x.Belt).ToArray()); + Assert.NotEqual(samples[0].BeltKind, samples[1].BeltKind); + // Seed 2's second belt is in darkness: no rock can be targeted, and that is not income. + Assert.Equal(LoopOutcome.RigFault, samples[1].Outcome); + Assert.Equal(0, samples[1].Units); + } + + [Fact] + public void ANonFiniteOrNonPositiveCapIsRefused() + { + foreach (var cap in new[] { float.NaN, 0f, -1f, float.PositiveInfinity }) + Assert.Throws(() => EconomyLoop.Sortie(Root, 1, 0, cap)); + foreach (var word in new[] { "NaN", "0", "-1", "Infinity" }) + { + var output = new StringWriter(); + Assert.Equal(1, EconomyCommand.Run(new[] { "balance", "--loop", "1", "--cap", word }, output)); + Assert.Contains("balance [--loop", output.ToString()); + } + } + [Fact] public void BalanceWithoutLoopIsUnchanged() { - using var db = AetherDb.Open(); - var spread = AuthoredSettings.Load(db.Root).Read("GameplaySettings").EconomyWageSpread; - var expected = new StringWriter(); - var expectedCode = EconomyCommand.Balance(db.Cache, spread, expected); + // The committed output of economy balance at the commit before --loop existed, on the shipped catalog. + var golden = File.ReadAllText(Path.Combine(Root, "tests", "Aetheria.Shared.Tests", "Golden", "economy-balance-base.txt")).Replace("\r\n", "\n"); var output = new StringWriter(); - var code = EconomyCommand.Run(new[] { "balance" }, output); - Assert.Equal(expectedCode, code); - Assert.Equal(expected.ToString(), output.ToString()); - Assert.DoesNotContain("Player loop", output.ToString()); + EconomyCommand.Run(new[] { "balance" }, output); + Assert.Equal(golden, output.ToString().Replace("\r\n", "\n")); } [Fact] diff --git a/tests/Aetheria.Shared.Tests/Golden/economy-balance-base.txt b/tests/Aetheria.Shared.Tests/Golden/economy-balance-base.txt new file mode 100644 index 000000000..7bda3e2fb --- /dev/null +++ b/tests/Aetheria.Shared.Tests/Golden/economy-balance-base.txt @@ -0,0 +1,130 @@ +median implied wage 0.00722 per worker-second, spread 2, 70 links, 0 unpriced +23 faults +H-margin (6) + 0271bb97-4ce8-4d64-97c3-8bfd3f76b2c6: Light Machine Gun sells at or below its inputs: implied wage -0.03456 per worker-second. + 1b4a2bb358eb432eb1cfc0ccf3317303: Mine Launcher sells at or below its inputs: implied wage -0.00356 per worker-second. + 2fd0d88b-f565-4021-85b4-02d9eae7be58: Long Slug Rifle sells at or below its inputs: implied wage -0.01696 per worker-second. + 679fb6a1-cefb-4adc-a49c-71942602196b: Slug Rifle sells at or below its inputs: implied wage -0.02067 per worker-second. + 6af6446e40cb4cdd90d7a3fee04394d4: Flak Gun sells at or below its inputs: implied wage -0.01048 per worker-second. + d02bcf71f2c8420b878f036cd1a33bea: Point Defense Gun sells at or below its inputs: implied wage -0.029 per worker-second. +H-wage (17) + 043997a8-0661-4206-ab8a-10215ecf4efc: Regolith: implied wage 0.00071 is 0.1x the median 0.00722, outside the spread of 2. + 13116166-f0c8-43cf-a35f-8fd448bc630c: Autocannon: implied wage 0.00248 is 0.34x the median 0.00722, outside the spread of 2. + 3aa1ac05-6d55-4569-8a4b-e1c3c6e07c61: Charged Scattergun: implied wage 0.23396 is 32.39x the median 0.00722, outside the spread of 2. + 8ac84e31-f0cf-43b2-8611-3316adfa4010: Cluster Cannon: implied wage 0.03952 is 5.47x the median 0.00722, outside the spread of 2. + commodity:ammonia: Ammonia: implied wage 0.025 is 3.46x the median 0.00722, outside the spread of 2. + commodity:anorthite: Anorthite: implied wage 0.00333 is 0.46x the median 0.00722, outside the spread of 2. + commodity:brannerite: Brannerite: implied wage 0.015 is 2.08x the median 0.00722, outside the spread of 2. + commodity:columbite: Columbite: implied wage 0.03333 is 4.62x the median 0.00722, outside the spread of 2. + commodity:isoferroplatinum: Isoferroplatinum: implied wage 0.18056 is 25x the median 0.00722, outside the spread of 2. + commodity:monazite: Monazite: implied wage 0.02667 is 3.69x the median 0.00722, outside the spread of 2. + commodity:native-gold: Native Gold: implied wage 0.09722 is 13.46x the median 0.00722, outside the spread of 2. + commodity:orthoclase: Orthoclase: implied wage 0.00067 is 0.09x the median 0.00722, outside the spread of 2. + commodity:sperrylite: Sperrylite: implied wage 0.09375 is 12.98x the median 0.00722, outside the spread of 2. + commodity:sylvite: Sylvite: implied wage 0.00167 is 0.23x the median 0.00722, outside the spread of 2. + commodity:troilite: Troilite: implied wage 0.00267 is 0.37x the median 0.00722, outside the spread of 2. + commodity:uraninite: Uraninite: implied wage 0.02 is 2.77x the median 0.00722, outside the spread of 2. + commodity:wolframite: Wolframite: implied wage 0.02 is 2.77x the median 0.00722, outside the spread of 2. + +Links by wage over the median (output | station kind | labour | price | derived cost | wage | ratio) + 0271bb97-4ce8-4d64-97c3-8bfd3f76b2c6 (Light Machine Gun) | Fabrication Station | 54000 | 500 | 2154.75 | -0.03456 | -4.78x + d02bcf71f2c8420b878f036cd1a33bea (Point Defense Gun) | Fabrication Station | 54000 | 800 | 2154.75 | -0.029 | -4.02x + 679fb6a1-cefb-4adc-a49c-71942602196b (Slug Rifle) | Fabrication Station | 54000 | 1250 | 2154.75 | -0.02067 | -2.86x + 2fd0d88b-f565-4021-85b4-02d9eae7be58 (Long Slug Rifle) | Fabrication Station | 54000 | 1450 | 2154.75 | -0.01696 | -2.35x + 6af6446e40cb4cdd90d7a3fee04394d4 (Flak Gun) | Fabrication Station | 54000 | 1800 | 2154.75 | -0.01048 | -1.45x + 1b4a2bb358eb432eb1cfc0ccf3317303 (Mine Launcher) | Fabrication Station | 43200 | 1250 | 1307.13 | -0.00356 | -0.49x + commodity:orthoclase (Orthoclase) | Mining Station | 6000 | 1 | 10.83 | 0.00067 | 0.09x + 043997a8-0661-4206-ab8a-10215ecf4efc (Regolith) | Mining Station | 8400 | 1 | 10.11 | 0.00071 | 0.1x + commodity:sylvite (Sylvite) | Mining Station | 4800 | 2 | 8.67 | 0.00167 | 0.23x + 13116166-f0c8-43cf-a35f-8fd448bc630c (Autocannon) | Fabrication Station | 54000 | 2500 | 2154.75 | 0.00248 | 0.34x + commodity:troilite (Troilite) | Mining Station | 6000 | 4 | 10.83 | 0.00267 | 0.37x + commodity:anorthite (Anorthite) | Mining Station | 7200 | 6 | 13 | 0.00333 | 0.46x + commodity:magnetite (Magnetite) | Mining Station | 6000 | 6 | 10.83 | 0.004 | 0.55x + commodity:native-copper (Native Copper) | Mining Station | 6000 | 16 | 21.67 | 0.00533 | 0.74x + commodity:primer (Primer) | Munitions Works | 4800 | 9 | 10.17 | 0.00646 | 0.89x + 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 (Nickel-Iron) | Mining Station | 6000 | 10 | 10.83 | 0.00667 | 0.92x + 214fe497-cda4-4cdb-a7c4-fe656e5ff61c (Methane) | Volatiles Station | 2400 | 4 | 4.33 | 0.00667 | 0.92x + commodity:chalcopyrite (Chalcopyrite) | Mining Station | 7200 | 12 | 13 | 0.00667 | 0.92x + commodity:pentlandite (Pentlandite) | Mining Station | 7200 | 12 | 13 | 0.00667 | 0.92x + 2e08445d-c130-497c-9fb3-8d752a24e654 (Algae) | Agriculture Station | 7200 | 12 | 14.69 | 0.00708 | 0.98x + commodity:steel (Steel) | Processing Station | 12000 | 29 | 32.32 | 0.00708 | 0.98x + 3c8b2b3d-ca1a-405f-966f-c64662a64418 (Circuit Board) | Fabrication Station | 8400 | 394 | 79.44 | 0.00714 | 0.99x + commodity:iron (Iron) | Processing Station | 8400 | 36 | 46.58 | 0.00714 | 0.99x + commodity:nitrocellulose (Nitrocellulose) | Munitions Works | 12000 | 103 | 101.47 | 0.00717 | 0.99x + commodity:he-warhead (High-Explosive Warhead) | Munitions Works | 21600 | 693 | 587.08 | 0.00718 | 0.99x + commodity:titanium (Titanium) | Processing Station | 16800 | 191 | 186.33 | 0.0072 | 1x + commodity:tungsten (Tungsten) | Processing Station | 16800 | 301 | 186.33 | 0.0072 | 1x + 08c07793-bc06-48dc-adc2-c7e61ef2cb2b (Uranium) | Processing Station | 9000 | 155 | 108.33 | 0.00722 | 1x + 3085fc8a-ec0d-4f6f-a339-ea43edb573e6 (Ammo) | Munitions Works | 18000 | 181 | 183.67 | 0.00722 | 1x + 36746041-a5bd-4b95-aa18-294acaaeae62 (Gold) | Processing Station | 3600 | 726 | 78 | 0.00722 | 1x + 8776c2fd-45f6-4ca6-8ef0-5214be830182 (Diamond) | Mining Station | 14400 | 104 | 104 | 0.00722 | 1x + a8e259fc-fbf1-477a-8248-0277611f1859 (Potassium) | Processing Station | 1800 | 15 | 30.33 | 0.00722 | 1x + commodity:aluminium (Aluminium) | Processing Station | 10800 | 108 | 143 | 0.00722 | 1x + commodity:autoloader (Autoloader Mechanism) | Fabrication Station | 36000 | 1364 | 751.47 | 0.00722 | 1x + commodity:copper (Copper) | Processing Station | 14400 | 152 | 156 | 0.00722 | 1x + commodity:explosive-fill (Explosive Fill) | Munitions Works | 27000 | 160 | 146.25 | 0.00722 | 1x + commodity:fuze (Fuze) | Munitions Works | 10800 | 158 | 75.92 | 0.00722 | 1x + commodity:gun-barrel (Gun Barrel) | Fabrication Station | 36000 | 1002 | 1013.28 | 0.00722 | 1x + commodity:mine-dispenser (Mine Dispenser) | Fabrication Station | 18000 | 711 | 408.06 | 0.00722 | 1x + commodity:missiles (Missiles) | Munitions Works | 28800 | 678 | 626.42 | 0.00722 | 1x + commodity:nickel (Nickel) | Processing Station | 12600 | 131 | 134.33 | 0.00722 | 1x + commodity:nitric-acid (Nitric Acid) | Processing Station | 3600 | 31 | 25.28 | 0.00722 | 1x + commodity:platinum-group-metals (Platinum Group Metals) | Processing Station | 18000 | 1480 | 208 | 0.00722 | 1x + commodity:rare-earth-oxides (Rare Earth Oxides) | Processing Station | 32400 | 474 | 299 | 0.00722 | 1x + commodity:rocket-motor (Rocket Motor) | Munitions Works | 18000 | 455 | 457.76 | 0.00722 | 1x + commodity:niobium (Niobium) | Processing Station | 21000 | 452 | 216.67 | 0.00724 | 1x + commodity:gun-forging (Gun Forging) | Processing Station | 72000 | 638 | 649.28 | 0.00725 | 1x + commodity:mines (Mines) | Munitions Works | 18000 | 441 | 390.86 | 0.00728 | 1.01x + 0b449ae1-7eab-47e8-ac3c-2b6f6ff01f00 (Ballistic Powder) | Munitions Works | 14400 | 148 | 147.72 | 0.00729 | 1.01x + commodity:potassium-nitrate (Potassium Nitrate) | Processing Station | 1920 | 30 | 34.74 | 0.00729 | 1.01x + commodity:cellulose-pulp (Cellulose Pulp) | Processing Station | 3000 | 29 | 32.86 | 0.00733 | 1.02x + commodity:hexamine (Hexamine) | Processing Station | 3000 | 32 | 21.67 | 0.00733 | 1.02x + commodity:fragmentation-case (Fragmentation Case) | Fabrication Station | 8400 | 60 | 62.65 | 0.00738 | 1.02x + commodity:actuator (Actuator) | Fabrication Station | 9600 | 523 | 213.42 | 0.0074 | 1.02x + 3acbb2bf-19fb-4591-bef1-dc9d5dde7e7a (Water) | Volatiles Station | 2400 | 3 | 2.89 | 0.0075 | 1.04x + commodity:oxygen (Oxygen) | Processing Station | 2400 | 9 | 8.67 | 0.0075 | 1.04x + commodity:projectile (Projectile) | Fabrication Station | 2880 | 20 | 21.36 | 0.00764 | 1.06x + commodity:ilmenite (Ilmenite) | Mining Station | 7200 | 14 | 13 | 0.00778 | 1.08x + commodity:shell-casing (Shell Casing) | Fabrication Station | 2880 | 13 | 13.28 | 0.00799 | 1.11x + commodity:brannerite (Brannerite) | Mining Station | 6000 | 45 | 21.67 | 0.015 | 2.08x + commodity:uraninite (Uraninite) | Mining Station | 6000 | 60 | 21.67 | 0.02 | 2.77x + commodity:wolframite (Wolframite) | Mining Station | 6000 | 60 | 21.67 | 0.02 | 2.77x + commodity:ammonia (Ammonia) | Volatiles Station | 2400 | 15 | 4.33 | 0.025 | 3.46x + commodity:monazite (Monazite) | Mining Station | 6000 | 80 | 21.67 | 0.02667 | 3.69x + commodity:columbite (Columbite) | Mining Station | 6000 | 100 | 21.67 | 0.03333 | 4.62x + 8ac84e31-f0cf-43b2-8611-3316adfa4010 (Cluster Cannon) | Fabrication Station | 54000 | 4500 | 2154.75 | 0.03952 | 5.47x + commodity:sperrylite (Sperrylite) | Mining Station | 4800 | 450 | 34.67 | 0.09375 | 12.98x + commodity:native-gold (Native Gold) | Mining Station | 3600 | 350 | 26 | 0.09722 | 13.46x + commodity:isoferroplatinum (Isoferroplatinum) | Mining Station | 3600 | 650 | 26 | 0.18056 | 25x + 3aa1ac05-6d55-4569-8a4b-e1c3c6e07c61 (Charged Scattergun) | Fabrication Station | 54000 | 15000 | 2154.75 | 0.23396 | 32.39x + +Belts (kind: abundance-weighted price and derived cost per unit; each ore: share, extraction wage ratio, price, cost) + Basaltic: price 9.37, cost 12.35 + 043997a8-0661-4206-ab8a-10215ecf4efc 47 % | wage 0.1x | price 1 | cost 10.11 + commodity:ilmenite 14 % | wage 1.08x | price 14 | cost 13 + commodity:anorthite 19 % | wage 0.46x | price 6 | cost 13 + commodity:native-copper 3 % | wage 0.74x | price 16 | cost 21.67 + commodity:chalcopyrite 3 % | wage 0.92x | price 12 | cost 13 + commodity:orthoclase 7 % | wage 0.09x | price 1 | cost 10.83 + commodity:uraninite 1 % | wage 2.77x | price 60 | cost 21.67 + commodity:brannerite 1 % | wage 2.08x | price 45 | cost 21.67 + commodity:monazite 2 % | wage 3.69x | price 80 | cost 21.67 + commodity:columbite 1 % | wage 4.62x | price 100 | cost 21.67 + commodity:wolframite 1 % | wage 2.77x | price 60 | cost 21.67 + Carbonaceous: price 2.75, cost 10.25 + 043997a8-0661-4206-ab8a-10215ecf4efc 62 % | wage 0.1x | price 1 | cost 10.11 + commodity:magnetite 19 % | wage 0.55x | price 6 | cost 10.83 + commodity:pentlandite 6 % | wage 0.92x | price 12 | cost 13 + commodity:sylvite 12 % | wage 0.23x | price 2 | cost 8.67 + Metallic: price 28.21, cost 11.46 + 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 83 % | wage 0.92x | price 10 | cost 10.83 + commodity:troilite 13 % | wage 0.37x | price 4 | cost 10.83 + commodity:native-gold 2 % | wage 13.46x | price 350 | cost 26 + commodity:isoferroplatinum 2 % | wage 25x | price 650 | cost 26 + Stony: price 8.23, cost 10.88 + 043997a8-0661-4206-ab8a-10215ecf4efc 63 % | wage 0.1x | price 1 | cost 10.11 + commodity:troilite 16 % | wage 0.37x | price 4 | cost 10.83 + 00b5b3b2-2fc5-4adb-a1d7-c1a35d19afd3 8 % | wage 0.92x | price 10 | cost 10.83 + commodity:pentlandite 6 % | wage 0.92x | price 12 | cost 13 + commodity:chalcopyrite 5 % | wage 0.92x | price 12 | cost 13 + commodity:sperrylite 1 % | wage 12.98x | price 450 | cost 34.67 diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 1e3acf087..94b3271dd 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -71,7 +71,7 @@ public static class EconomyCommand { EconomyChecks.LRecipe, EconomyChecks.LLore, EconomyChecks.LProductive, EconomyChecks.LOneKindList, EconomyChecks.LWeights, EconomyChecks.LShape, EconomyChecks.LPrice }; // A batch is compiled code under tools/AetherDb/Economy/ and runs with the operator's authority: reviewed code, never an input. - private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [...]] [--cap ]\nbalance reads the chain and changes nothing; --loop adds the player loop (a mining sortie per seed, default seeds 1 2 3 69 97 and cap 300 sim seconds) and the offered gear ladders. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made commodity to the price its chain derives; with no batch it reprices alone."; + private const string Usage = "economy report | author [...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [...]] [--cap ]\nbalance reads the chain and changes nothing; --loop adds the player loop (a mining sortie per seed, default seeds 1 2 3 69 97, every belt of each, cap 150 sim seconds a sortie) and the offered gear ladders. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made commodity to the price its chain derives; with no batch it reprices alone."; public static int Run(string[] args, TextWriter output) { @@ -88,7 +88,7 @@ public static class EconomyCommand var rest = args.Skip(1).ToList(); var cap = EconomyLoop.DefaultCap; var capAt = rest.IndexOf("--cap"); - if (capAt >= 0 && (capAt + 1 >= rest.Count || !float.TryParse(rest[capAt + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out cap) || cap <= 0)) + if (capAt >= 0 && (capAt + 1 >= rest.Count || !float.TryParse(rest[capAt + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out cap) || !float.IsFinite(cap) || cap <= 0)) { output.WriteLine(Usage); return 1; @@ -109,7 +109,7 @@ public static class EconomyCommand } LoopReport loop = null; if (loopAt >= 0) - loop = EconomyLoop.Report(db.Cache, settings, (seeds.Count == 0 ? EconomyLoop.DefaultSeeds : seeds.ToArray()).Select(seed => EconomyLoop.Sortie(db.Root, seed, cap)).ToList()); + loop = EconomyLoop.Report(db.Cache, settings, (seeds.Count == 0 ? EconomyLoop.DefaultSeeds : seeds.ToArray()).SelectMany(seed => EconomyLoop.Sorties(db.Root, seed, cap)).ToList()); return Balance(db.Cache, settings.EconomyWageSpread, output, loop); } if (args.Length > 0 && args[0] == "author") @@ -165,11 +165,11 @@ public static class EconomyCommand private static void PrintLoop(LoopReport loop, TextWriter output) { var inv = System.Globalization.CultureInfo.InvariantCulture; - output.WriteLine("\nPlayer loop (seed | belt | weapons | rocks | sim s | hold full at | units | sell | ammo | repair | net per minute)"); + output.WriteLine("\nPlayer loop (seed belt | kind | weapons | outcome | rocks | sim s | hold full at | units | sell | ammo | repair | net per minute)"); foreach (var s in loop.Samples) - output.WriteLine(string.Format(inv, " {0} | {1} | {2} | {3} | {4:0.#} | {5} | {6} | {7} | {8} | {9} | {10:0.#}", s.Seed, s.BeltKind, s.Weapons, s.Rocks, s.SimSeconds, - s.HoldFullAt.HasValue ? s.HoldFullAt.Value.ToString("0.#", inv) + " s" : "never", s.Units, s.SellValue, s.AmmoSpent, s.Repair, s.RatePerMinute)); - output.WriteLine(string.Format(inv, " median {0:0.#} per minute, best {1:0.#} per minute, purse {2}", loop.Median, loop.Best, loop.Purse)); + output.WriteLine(string.Format(inv, " {0} {11}/{12} | {1} | {2} | {13} | {3} | {4:0.#} | {5} | {6} | {7} | {8} | {9} | {10:0.#}", s.Seed, s.BeltKind, s.Weapons, s.Rocks, s.SimSeconds, + s.HoldFullAt.HasValue ? s.HoldFullAt.Value.ToString("0.#", inv) + " s" : "never", s.Units, s.SellValue, s.AmmoSpent, s.Repair, s.RatePerMinute, s.Belt + 1, s.Belts, s.Outcome)); + output.WriteLine(string.Format(inv, " median {0:0.#} per minute, best {1:0.#} per minute over the {3} sorties that mined to a full hold or the cap; purse {2}", loop.Median, loop.Best, loop.Purse, loop.Samples.Count(s => s.Measured))); string Minutes(double? m) => m.HasValue ? m.Value.ToString("0.#", inv) : "-"; string Width(double? w) => w.HasValue ? w.Value.ToString("0.##", inv) + "x" : "-"; output.WriteLine("\nLadders (category: width authored, derived; each design: price | derived | minutes at median | minutes at best | purse covers)"); diff --git a/tools/AetherDb/EconomyLoop.cs b/tools/AetherDb/EconomyLoop.cs index 309a34173..8315c556b 100644 --- a/tools/AetherDb/EconomyLoop.cs +++ b/tools/AetherDb/EconomyLoop.cs @@ -11,11 +11,28 @@ using UniRx; // takes to afford each offered design, and the width of each offered gear ladder against a band. It measures and reports; it changes // no price, yield or purse (rulings economy-numbers-are-sim-tuned-knobs, economy-tuned-by-systemic-health). Faults are report-only. // The sortie driver teleports the ship, so it is a measuring rig that lives here and never in ServerShared. +public enum LoopOutcome +{ + // The hold filled (the first unit floated): the sortie measured what a full trip pays. + Full, + // The cap ended it with the ship still mining. + Capped, + // A stock the ship started with ran out: it cannot sustain mining. The rate is measured up to there and never enters the median. + AmmoOut, + // The rig measured nothing (no rock could be targeted, or it ran out of rocks early): never income. + RigFault +} + public sealed class LoopSample { public uint Seed; + // This sample's belt in the zone's generation order, and how many belts the zone holds. + public int Belt; + public int Belts; public string BeltKind; public string Weapons; + public LoopOutcome Outcome; + public string Note; public int Rocks; public double SimSeconds; public int Units; @@ -27,6 +44,8 @@ public sealed class LoopSample public int Net => SellValue - AmmoSpent - Repair; public double RatePerMinute => SimSeconds > 0 ? Net * 60.0 / SimSeconds : 0; + // Only a sortie that mined to a full hold or to the cap says what the loop pays. + public bool Measured => Outcome == LoopOutcome.Full || Outcome == LoopOutcome.Capped; } public sealed class LoopDesign @@ -52,6 +71,7 @@ public sealed class LoopLadder public sealed class LoopReport { public IReadOnlyList Samples; + // Over the measured samples only. public double Median; public double Best; public int Purse; @@ -61,19 +81,32 @@ public sealed class LoopReport public static class EconomyLoop { - public const string HLoop = "H-loop", HLadder = "H-ladder"; + public const string HLoop = "H-loop", HLadder = "H-ladder", HAmmo = "H-ammo", HRig = "H-rig"; public static readonly uint[] DefaultSeeds = { 1, 2, 3, 69, 97 }; - public const float DefaultCap = 300f; + // Every belt of every default seed is a sample (11 of them), so the cap is what bounds wall time. + public const float DefaultCap = 150f; private const float Step = .02f; private const float RockSeconds = 60f; + private const int AmmoCheckTicks = 10; - // One sortie in the demo run of this seed: the staged ship is held forty units off each rock of the arena's belt in index order, - // fires every weapon at it, and stops when the first unit floats (the hold is full) or at the cap. Everything it touches is its - // own: a scratch copy of the catalog, its own run store and its own ItemManager (a shared one advances its Random and gave the - // same seed different results). - public static LoopSample Sortie(string root, uint seed, float capSeconds) + // One sortie per belt of the demo run of this seed, each its own sample. + public static List Sorties(string root, uint seed, float capSeconds) { + var first = Sortie(root, seed, 0, capSeconds); + var samples = new List { first }; + for (var belt = 1; belt < first.Belts; belt++) samples.Add(Sortie(root, seed, belt, capSeconds)); + return samples; + } + + // One sortie in the demo run of this seed on one belt: the staged ship is held forty units off each rock of the belt in index + // order, fires every weapon at it, and stops when the first unit floats (the hold is full), when a starting stock runs out, or + // at the cap. Everything it touches is its own: a scratch copy of the catalog, its own run store and its own ItemManager (a + // shared one advances its Random and gave the same seed different results). atEnd, if given, sees the ship and items as the + // sample is taken, so a test can read the same state the sample was priced from. + public static LoopSample Sortie(string root, uint seed, int beltIndex, float capSeconds, Action atEnd = null) + { + if (!float.IsFinite(capSeconds) || capSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(capSeconds), "the cap must be a positive, finite number of sim seconds"); var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-loop-" + Guid.NewGuid().ToString("N"))).FullName; try { @@ -98,9 +131,23 @@ public static class EconomyLoop var player = RunStart.Stage(items, arena, scenario, startingHull, failures).Player; if (failures.Count > 0) throw new InvalidOperationException($"seed {seed}: staging failed: {string.Join("; ", failures)}"); - var belt = arena.Planets.First(body => body.Value is AsteroidBeltData); - var rocks = ((AsteroidBeltData) belt.Value).Asteroids.Length; + var belts = arena.Planets.Where(body => body.Value is AsteroidBeltData).ToList(); + if (beltIndex < 0 || beltIndex >= Math.Max(belts.Count, 1)) throw new ArgumentOutOfRangeException(nameof(beltIndex), $"seed {seed} has {belts.Count} belts"); var weapons = player.Equipment.SelectMany(item => item.Behaviors.OfType()).ToArray(); + var sample = new LoopSample + { + Seed = seed, Belt = beltIndex, Belts = belts.Count, BeltKind = "none", + Weapons = string.Join(", ", weapons.Select(w => items.GetData(w.Item.EquippableItem).Name).GroupBy(n => n).Select(g => g.Count() + "x " + g.Key)) + }; + if (belts.Count == 0) + { + sample.Outcome = LoopOutcome.RigFault; + sample.Note = "the zone holds no belt"; + return sample; + } + var belt = belts[beltIndex]; + var beltData = (AsteroidBeltData) belt.Value; + sample.BeltKind = cache.Get(beltData.Kind)?.Name ?? beltData.Kind.Key.Value; var ammoBefore = Ammunition(items, player); var units = 0; arena.CargoGained.Subscribe(gain => units += gain.Stored); @@ -109,11 +156,24 @@ public static class EconomyLoop var ticks = 0; var capTicks = (int) Math.Round(capSeconds / Step); var broken = 0; + var targeted = 0; + var ammoOut = false; int? fullTick = null; - bool Stopped() => fullTick != null || ticks >= capTicks; - void Tick(Action hold) { hold(); arena.Update(Step); ticks++; if (fullTick == null && arena.FloatingItems.Count > 0) fullTick = ticks; } + bool Stopped() => fullTick != null || ammoOut || ticks >= capTicks; + void Tick(Action hold) + { + hold(); + arena.Update(Step); + ticks++; + if (fullTick == null && arena.FloatingItems.Count > 0) fullTick = ticks; + if (ticks % AmmoCheckTicks == 0 && !ammoOut) + { + var now = Ammunition(items, player); + ammoOut = ammoBefore.Keys.Any(data => !now.ContainsKey(data)); + } + } - for (var index = 0; index < rocks && !Stopped(); index++) + for (var index = 0; index < beltData.Asteroids.Length && !Stopped(); index++) { var rock = new ChunkId(belt.Key, index); if (!arena.ChunkExists(rock)) continue; @@ -128,6 +188,7 @@ public static class EconomyLoop Tick(Hold); Tick(Hold); if (!player.SetTarget(rock)) continue; + targeted++; foreach (var weapon in weapons) weapon.Activate(); for (var spent = 0; spent < (int) Math.Round(RockSeconds / Step) && arena.ChunkExists(rock) && !Stopped(); spent++) Tick(Hold); if (!arena.ChunkExists(rock)) broken++; @@ -136,24 +197,25 @@ public static class EconomyLoop var ammoAfter = Ammunition(items, player); var spentOnAmmo = 0L; - foreach (var (data, (quantity, sample)) in ammoBefore) + foreach (var (data, (quantity, stack)) in ammoBefore) { var left = ammoAfter.TryGetValue(data, out var held) ? held.Quantity : 0; - if (quantity > left) spentOnAmmo += StationServices.BuyPrice(items, sample, quantity - left); + if (quantity > left) spentOnAmmo += StationServices.BuyPrice(items, stack, quantity - left); } - return new LoopSample - { - Seed = seed, - BeltKind = cache.Get(((AsteroidBeltData) belt.Value).Kind)?.Name ?? ((AsteroidBeltData) belt.Value).Kind.Key.Value, - Weapons = string.Join(", ", weapons.Select(w => items.GetData(w.Item.EquippableItem).Name).GroupBy(n => n).Select(g => g.Count() + "x " + g.Key)), - Rocks = broken, - SimSeconds = ticks * (double) Step, - Units = units, - HoldFullAt = fullTick == null ? null : fullTick * (double) Step, - SellValue = StationServices.OreValue(items, player.CargoBays), - AmmoSpent = (int) Math.Min(spentOnAmmo, int.MaxValue), - Repair = StationServices.RepairCost(items, player) - }; + sample.Rocks = broken; + sample.SimSeconds = ticks * (double) Step; + sample.Units = units; + sample.HoldFullAt = fullTick == null ? null : fullTick * (double) Step; + sample.SellValue = StationServices.OreValue(items, player.CargoBays); + sample.AmmoSpent = (int) Math.Min(spentOnAmmo, int.MaxValue); + sample.Repair = StationServices.RepairCost(items, player); + if (fullTick != null) sample.Outcome = LoopOutcome.Full; + else if (ammoOut) { sample.Outcome = LoopOutcome.AmmoOut; sample.Note = "a starting stock ran out"; } + else if (targeted == 0) { sample.Outcome = LoopOutcome.RigFault; sample.Note = "no rock of the belt could be targeted"; } + else if (ticks >= capTicks) sample.Outcome = LoopOutcome.Capped; + else { sample.Outcome = LoopOutcome.RigFault; sample.Note = "ran out of rocks before the cap"; } + atEnd?.Invoke(player, items); + return sample; } finally { @@ -182,7 +244,7 @@ public static class EconomyLoop // Rates, minutes to afford and ladder widths from the samples and the catalog: pure, recomputed every run, nothing stored. public static LoopReport Report(CultCache catalog, GameplaySettings settings, IReadOnlyList samples) { - var rates = samples.Select(s => s.RatePerMinute).OrderBy(r => r).ToList(); + var rates = samples.Where(s => s.Measured).Select(s => s.RatePerMinute).OrderBy(r => r).ToList(); var median = rates.Count == 0 ? 0 : rates.Count % 2 == 1 ? rates[rates.Count / 2] : (rates[rates.Count / 2 - 1] + rates[rates.Count / 2]) / 2; var best = rates.Count == 0 ? 0 : rates[rates.Count - 1]; var derived = EconomyBalance.Prices(catalog, out _, designs: true); @@ -213,8 +275,16 @@ public static class EconomyLoop }).ToList(); var faults = new List(); - foreach (var sample in samples.Where(s => s.Net <= 0)) - faults.Add(new EconomyFault(HLoop, "seed " + sample.Seed, $"the sortie nets {sample.Net} (sell {sample.SellValue}, ammunition {sample.AmmoSpent}, repair {sample.Repair}): no income.")); + foreach (var sample in samples) + { + var where = $"seed {sample.Seed} belt {sample.Belt + 1} of {sample.Belts}"; + if (sample.Outcome == LoopOutcome.AmmoOut) + faults.Add(new EconomyFault(HAmmo, where, $"the fit ran out of a starting stock after {sample.SimSeconds:0.#} s ({sample.Weapons}) and cannot sustain mining.")); + else if (sample.Outcome == LoopOutcome.RigFault) + faults.Add(new EconomyFault(HRig, where, $"the rig measured nothing: {sample.Note}.")); + else if (sample.Net <= 0) + faults.Add(new EconomyFault(HLoop, where, $"the sortie nets {sample.Net} (sell {sample.SellValue}, ammunition {sample.AmmoSpent}, repair {sample.Repair}): no income.")); + } var (min, max) = (settings.EconomyLadderMin, settings.EconomyLadderMax); if (min > 0 || max > 0) foreach (var ladder in ladders)