economy balance --region: the demo region advanced on the shipped off-screen path
EconomyRegion.Run boots the region, parks the hauler and advances every zone with Zone.AdvanceTo at each RegionClock.Span. Per seed: stations by faction and kind with their depth, facility Stall shares, held units of outputs, units made per recipe, H-region-idle and H-region-missing-link (the link set is StationKinds.FieldableKindsOf). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
33bdf92a2f
commit
26b451e1b9
4 changed files with 355 additions and 10 deletions
|
|
@ -334,6 +334,24 @@ public sealed class EconomyCommandTests
|
|||
Assert.Contains("economy report | author", output.ToString());
|
||||
}
|
||||
|
||||
// --region is a stage of its own, like --loop and --drain, with its seeds last; --hours belongs to it alone.
|
||||
[Theory]
|
||||
[InlineData("--region", "--drain")]
|
||||
[InlineData("--drain", "--region")]
|
||||
[InlineData("--region", "--loop")]
|
||||
[InlineData("--loop", "--region")]
|
||||
[InlineData("--region", "--hours")]
|
||||
[InlineData("--region", "--hours", "0")]
|
||||
[InlineData("--hours", "2")]
|
||||
[InlineData("--region", "x")]
|
||||
[InlineData("--region", "1", "--supply")]
|
||||
public void RegionStageArgs(params string[] words)
|
||||
{
|
||||
var output = new StringWriter();
|
||||
Assert.Equal(1, EconomyCommand.Run(new[] { "balance" }.Concat(words).ToArray(), output));
|
||||
Assert.Contains("balance --region [<seed>...] [--hours <sim hours>]", output.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BalanceOnTheShippedCatalogPrintsEveryLinkAndBeltRow()
|
||||
{
|
||||
|
|
|
|||
97
tests/Aetheria.Shared.Tests/EconomyRegionTests.cs
Normal file
97
tests/Aetheria.Shared.Tests/EconomyRegionTests.cs
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GameCult.Caching;
|
||||
using Xunit;
|
||||
|
||||
// The region stage of `economy balance --region` (EconomyRegion): the demo region of seed 1 booted as a run boots it and advanced by
|
||||
// RegionClock's off-screen step. The harness drives and reads; what sim time does off screen is RegionClock's and Zone.AdvanceTo's.
|
||||
public sealed class EconomyRegionTests
|
||||
{
|
||||
private static string Root => RunStartTests.FindRepoRoot();
|
||||
|
||||
private const double Hours = 2;
|
||||
|
||||
[Fact]
|
||||
public void EveryZoneAdvancesToTheHorizon()
|
||||
{
|
||||
var advanced = 0;
|
||||
var moved = false;
|
||||
var sample = EconomyRegion.Run(Root, 1, Hours, atEnd: demo =>
|
||||
{
|
||||
var zones = demo.Galaxy.Zones.Where(zone => zone.Contents != null).ToList();
|
||||
advanced = zones.Count;
|
||||
Assert.Equal(demo.Galaxy.Zones.Length, zones.Count);
|
||||
// The entrance included: Zone.AdvanceTo sets each zone's clock to the span boundary, none steps by itself.
|
||||
Assert.All(zones, zone => Assert.Equal(Hours * 3600, zone.Contents.ExactTime));
|
||||
// Something off the entrance did more than sit: a facility there stalled for a reason or has a cycle under way.
|
||||
moved = zones.Where(zone => zone != demo.Galaxy.Entrance)
|
||||
.SelectMany(zone => zone.Contents.Entities)
|
||||
.SelectMany(entity => entity.Equipment)
|
||||
.Any(unit => unit.Behaviors.OfType<Facility>().Any(facility => facility.Stall != Stall.None) || (unit.EquippableItem.Run?.Progress ?? 0) > 0);
|
||||
});
|
||||
Assert.Equal(advanced, sample.Zones);
|
||||
Assert.Equal((int) (Hours * 3600 / RegionClock.Span), sample.Spans);
|
||||
Assert.True(moved, "no facility outside the entrance zone has a Stall or a run: only the entrance advanced");
|
||||
}
|
||||
|
||||
// A station kind of a faction, taken from the stations outside the entrance that its faction can field, and every station of
|
||||
// that faction and kind taken out before the run.
|
||||
private static (string Faction, string Kind) Remove(DemoArena demo)
|
||||
{
|
||||
var stations = demo.Galaxy.Zones.Where(zone => zone != demo.Galaxy.Entrance && zone.Contents != null)
|
||||
.SelectMany(zone => zone.Contents.Entities.OfType<OrbitalEntity>().Where(e => e.Kind.IsSet() && e.Faction != null).Select(e => (zone, entity: e)))
|
||||
.ToList();
|
||||
var pick = stations.First(s => StationKinds.FieldableKindsOf(demo.Cache, s.entity.Faction).Any(kind => kind.Key.Equals(s.entity.Kind.Key))).entity;
|
||||
foreach (var (zone, entity) in stations.Where(s => s.entity.Faction == pick.Faction && s.entity.Kind.Key.Equals(pick.Kind.Key)))
|
||||
Assert.True(zone.Contents.Remove(entity));
|
||||
return (pick.Faction.Name, demo.Cache.Get(pick.Kind).Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MissingLinkIsReported()
|
||||
{
|
||||
var baseline = EconomyRegion.Run(Root, 1, 0.05);
|
||||
(string Faction, string Kind) removed = default;
|
||||
var sample = EconomyRegion.Run(Root, 1, 0.05, beforeRun: demo => removed = Remove(demo));
|
||||
Assert.DoesNotContain(removed, baseline.MissingLinks);
|
||||
// Exactly the removed link is new: the link set is read from the catalog, not from the stations left.
|
||||
Assert.Equal(new[] { removed }, sample.MissingLinks.Except(baseline.MissingLinks).ToArray());
|
||||
var named = EconomyRegion.Report(new[] { sample }).Where(fault => fault.Invariant == EconomyRegion.HMissingLink && fault.Message.Contains($"{removed.Faction} fields {removed.Kind},")).ToList();
|
||||
Assert.Single(named);
|
||||
Assert.Empty(EconomyRegion.Report(new[] { baseline }).Where(fault => fault.Message.Contains($"{removed.Faction} fields {removed.Kind},")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IdleRecipeIsReported()
|
||||
{
|
||||
var baseline = EconomyRegion.Run(Root, 1, Hours);
|
||||
// The entrance refinery handed one stack of each ore it wants: the recipes that draw them run, the rest of the region reads Inputs.
|
||||
var stored = 0;
|
||||
var fed = EconomyRegion.Run(Root, 1, Hours, beforeRun: demo =>
|
||||
{
|
||||
var station = demo.Processing;
|
||||
foreach (var ore in StationWants.Of(station).Where(key => FieldKinds.IsOre(demo.Cache, demo.Cache.Get<ItemData>(key))))
|
||||
{
|
||||
var stack = new SimpleCommodity { Data = new CultRecordRef<ItemData>(ore), Quantity = demo.Cache.Get<SimpleCommodityData>(ore).MaxStack };
|
||||
if (StationWants.Bays(station, ore).Any(bay => bay.TryStore(stack))) stored++;
|
||||
}
|
||||
});
|
||||
Assert.True(stored > 0, "the refinery took no ore");
|
||||
var ranFed = fed.Recipes.Where(recipe => recipe.Ran).Select(recipe => recipe.Output).ToList();
|
||||
Assert.NotEmpty(ranFed.Except(baseline.Recipes.Where(recipe => recipe.Ran).Select(recipe => recipe.Output)));
|
||||
var idle = EconomyRegion.Report(new[] { fed }).Where(fault => fault.Invariant == EconomyRegion.HIdle).Select(fault => fault.Record).OrderBy(record => record, StringComparer.Ordinal).ToArray();
|
||||
Assert.Equal(fed.Recipes.Where(recipe => !recipe.Ran).Select(recipe => $"seed 1 {recipe.Output}").OrderBy(record => record, StringComparer.Ordinal), idle);
|
||||
Assert.All(ranFed, output => Assert.DoesNotContain($"seed 1 {output}", idle));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PrintNamesTheRegionAndWhatItDoesNotMove()
|
||||
{
|
||||
var sample = EconomyRegion.Run(Root, 1, 0.05);
|
||||
var text = new StringWriter();
|
||||
EconomyRegion.Print(sample, text);
|
||||
Assert.Contains("Region, seed 1 (", text.ToString());
|
||||
Assert.Contains("no cargo moves between stations", text.ToString());
|
||||
}
|
||||
}
|
||||
|
|
@ -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 [<batch>...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [<seed>...]] [--cap <sim seconds>] | balance --drain [<seed>...] [--window <sim seconds>] [--horizon <sim hours>] [--supply]\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; --drain, not in the same call, adds a station block per seed: sorties to fill, the window (default 600 sim s) on screen and by spans, and the horizon (default 24 sim h) by spans; --supply tops the wanted ores up through the landing rule every 600 sim s of the horizon (a long --horizon, such as 300, shows a station whose products fill with no outflow: H-drain-saturated). A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made good (a commodity, or a design with a recipe) to the price its chain derives; with no batch it reprices alone.";
|
||||
private const string Usage = "economy report | author [<batch>...] [apply] | " + EconomyPrices.Usage + " | balance [--loop [<seed>...]] [--cap <sim seconds>] | balance --drain [<seed>...] [--window <sim seconds>] [--horizon <sim hours>] [--supply] | balance --region [<seed>...] [--hours <sim hours>]\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; --drain, not in the same call, adds a station block per seed: sorties to fill, the window (default 600 sim s) on screen and by spans, and the horizon (default 24 sim h) by spans; --supply tops the wanted ores up through the landing rule every 600 sim s of the horizon (a long --horizon, such as 300, shows a station whose products fill with no outflow: H-drain-saturated). --region, a stage of its own, boots the demo region as a run does and advances every zone, the entrance included, with Zone.AdvanceTo each RegionClock span (default 24 sim h; no zone steps, no cargo moves between stations): per seed the stations by faction and kind with their depth toward the gate, each facility's Stall shares, units held of what it makes, units made per recipe, H-region-idle for a recipe that made nothing and H-region-missing-link for a kind a faction fields that none of its stations outside the entrance zone is. A batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor. After the batches, author reprices every made good (a commodity, or a design with a recipe) to the price its chain derives; with no batch it reprices alone.";
|
||||
|
||||
public static int Run(string[] args, TextWriter output)
|
||||
{
|
||||
|
|
@ -96,9 +96,9 @@ public static class EconomyCommand
|
|||
rest.RemoveRange(at, 2);
|
||||
return true;
|
||||
}
|
||||
double cap, window, horizon;
|
||||
bool capped, windowed, horizoned;
|
||||
try { (capped, windowed, horizoned) = (Option("--cap", out cap), Option("--window", out window), Option("--horizon", out horizon)); }
|
||||
double cap, window, horizon, hours;
|
||||
bool capped, windowed, horizoned, houred;
|
||||
try { (capped, windowed, horizoned, houred) = (Option("--cap", out cap), Option("--window", out window), Option("--horizon", out horizon), Option("--hours", out hours)); }
|
||||
catch (FormatException)
|
||||
{
|
||||
output.WriteLine(Usage);
|
||||
|
|
@ -113,19 +113,21 @@ public static class EconomyCommand
|
|||
if (!capped) cap = EconomyLoop.DefaultCap;
|
||||
if (!windowed) window = EconomyDrain.DefaultWindowSeconds;
|
||||
if (!horizoned) horizon = EconomyDrain.DefaultHorizonHours;
|
||||
if (!houred) hours = EconomyRegion.DefaultHours;
|
||||
var supplied = rest.Remove("--supply");
|
||||
var loopAt = rest.IndexOf("--loop");
|
||||
var drainAt = rest.IndexOf("--drain");
|
||||
var regionAt = rest.IndexOf("--region");
|
||||
var seeds = new List<uint>();
|
||||
var flagAt = Math.Max(loopAt, drainAt);
|
||||
var flagAt = Math.Max(Math.Max(loopAt, drainAt), regionAt);
|
||||
if (flagAt >= 0)
|
||||
foreach (var word in rest.Skip(flagAt + 1))
|
||||
{
|
||||
if (!uint.TryParse(word, out var seed)) { output.WriteLine(Usage); return 1; }
|
||||
seeds.Add(seed);
|
||||
}
|
||||
// One of the two stages a call, its seeds last; each option belongs to its own stage.
|
||||
if ((flagAt >= 0 ? rest.Count - 1 - seeds.Count : rest.Count) != 0 || (loopAt >= 0 && drainAt >= 0) || (capped && loopAt < 0) || ((windowed || horizoned || supplied) && drainAt < 0))
|
||||
// One of the three stages a call, its seeds last; each option belongs to its own stage.
|
||||
if ((flagAt >= 0 ? rest.Count - 1 - seeds.Count : rest.Count) != 0 || new[] { loopAt, drainAt, regionAt }.Count(at => at >= 0) > 1 || (capped && loopAt < 0) || ((windowed || horizoned || supplied) && drainAt < 0) || (houred && regionAt < 0))
|
||||
{
|
||||
output.WriteLine(Usage);
|
||||
return 1;
|
||||
|
|
@ -137,7 +139,10 @@ public static class EconomyCommand
|
|||
List<DrainSample> drain = null;
|
||||
if (drainAt >= 0)
|
||||
drain = seedList.Select(seed => EconomyDrain.Run(db.Root, seed, window, horizon, EconomyLoop.Sorties(db.Root, seed, EconomyLoop.DefaultCap), supplied: supplied)).ToList();
|
||||
return Balance(db.Cache, settings.EconomyWageSpread, output, loop, drain);
|
||||
List<RegionSample> region = null;
|
||||
if (regionAt >= 0)
|
||||
region = seedList.Select(seed => EconomyRegion.Run(db.Root, seed, hours)).ToList();
|
||||
return Balance(db.Cache, settings.EconomyWageSpread, output, loop, drain, region);
|
||||
}
|
||||
if (args.Length > 0 && args[0] == "author")
|
||||
{
|
||||
|
|
@ -160,10 +165,10 @@ public static class EconomyCommand
|
|||
|
||||
// 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, LoopReport loop = null, IReadOnlyList<DrainSample> drain = null)
|
||||
public static int Balance(CultCache catalog, double wageSpread, TextWriter output, LoopReport loop = null, IReadOnlyList<DrainSample> drain = null, IReadOnlyList<RegionSample> region = null)
|
||||
{
|
||||
var report = EconomyBalance.Balance(catalog, wageSpread);
|
||||
var faults = report.Faults.Concat(loop?.Faults ?? new List<EconomyFault>()).Concat(drain == null ? new List<EconomyFault>() : EconomyDrain.Report(drain)).ToList();
|
||||
var faults = report.Faults.Concat(loop?.Faults ?? new List<EconomyFault>()).Concat(drain == null ? new List<EconomyFault>() : EconomyDrain.Report(drain)).Concat(region == null ? new List<EconomyFault>() : EconomyRegion.Report(region)).ToList();
|
||||
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($"{faults.Count} faults");
|
||||
|
|
@ -185,6 +190,7 @@ public static class EconomyCommand
|
|||
}
|
||||
if (loop != null) PrintLoop(loop, output);
|
||||
if (drain != null) foreach (var sample in drain) EconomyDrain.Print(sample, output);
|
||||
if (region != null) foreach (var sample in region) EconomyRegion.Print(sample, output);
|
||||
return faults.Count == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
|
|
|
|||
224
tools/AetherDb/EconomyRegion.cs
Normal file
224
tools/AetherDb/EconomyRegion.cs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GameCult.Caching;
|
||||
|
||||
// What the demo's whole region does with simulation time, on the path the game ships (ruling demo-chain-spans-the-region): the demo
|
||||
// region is booted as a run boots it (every zone generated and live), the hauler parked, and every zone, the entrance included, is
|
||||
// advanced with Zone.AdvanceTo at each multiple of RegionClock.Span up to the horizon. No zone steps and no player flies; the harness
|
||||
// drives RegionClock's off-screen step and reads what it left. Measurement only: it reads a booted scratch copy of the catalog and
|
||||
// writes none.
|
||||
//
|
||||
// The region view moves no cargo between stations (haul legs are region-haul-legs), so a station that needs a good it does not hold
|
||||
// stalls Inputs, and the report says so instead of hiding it.
|
||||
|
||||
// One facility of a station: the Stall it ended each span in, counted.
|
||||
public sealed class RegionFacility
|
||||
{
|
||||
public string Name;
|
||||
public SortedDictionary<Stall, int> Stalls = new SortedDictionary<Stall, int>();
|
||||
// The recipe outputs of this facility's run list (good names).
|
||||
public List<string> Outputs = new List<string>();
|
||||
}
|
||||
|
||||
public sealed class RegionStation
|
||||
{
|
||||
public string Zone, Name, Faction, Kind;
|
||||
public bool Entrance;
|
||||
public float Depth;
|
||||
public List<RegionFacility> Facilities = new List<RegionFacility>();
|
||||
// Units held of each good any facility here makes, at the start and at the end of the horizon.
|
||||
public SortedDictionary<string, (int Start, int End)> Held = new SortedDictionary<string, (int, int)>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
// One (faction, kind) of the region's non-entrance stations: how many, and the depth toward the gate they sit at.
|
||||
public sealed class RegionKind
|
||||
{
|
||||
public string Faction, Kind;
|
||||
public int Stations;
|
||||
public float DepthMin = float.MaxValue, DepthMax = float.MinValue;
|
||||
}
|
||||
|
||||
// One recipe of a facility the region holds: every station that holds a facility running it, the units its output rose by across
|
||||
// the spans (the most the harness can see of what was made: a unit another recipe takes in the same span is not counted), and
|
||||
// whether a cycle of it was ever seen running.
|
||||
public sealed class RegionRecipe
|
||||
{
|
||||
public string Output;
|
||||
public int Stations;
|
||||
public long Made;
|
||||
public bool Ran => Made > 0 || Started;
|
||||
public bool Started;
|
||||
}
|
||||
|
||||
public sealed class RegionSample
|
||||
{
|
||||
public uint Seed;
|
||||
public double Hours;
|
||||
public int Zones, Spans;
|
||||
public int Parked;
|
||||
public List<RegionKind> Kinds = new List<RegionKind>();
|
||||
public List<RegionStation> Stations = new List<RegionStation>();
|
||||
public List<RegionRecipe> Recipes = new List<RegionRecipe>();
|
||||
// Per faction holding a non-entrance station: the kinds it fields (StationKinds.FieldableKindsOf) that no such station of it is.
|
||||
public List<(string Faction, string Kind)> MissingLinks = new List<(string, string)>();
|
||||
}
|
||||
|
||||
public static class EconomyRegion
|
||||
{
|
||||
public const string HIdle = "H-region-idle", HMissingLink = "H-region-missing-link";
|
||||
public const double DefaultHours = 24;
|
||||
|
||||
// Boots the demo region of this seed, runs it to the horizon and reads it. beforeRun sees the booted region before any zone
|
||||
// advances (a test removes a station there); atEnd sees it after the last span.
|
||||
public static RegionSample Run(string root, uint seed, double hours, Action<DemoArena> beforeRun = null, Action<DemoArena> atEnd = null)
|
||||
{
|
||||
if (!double.IsFinite(hours) || hours <= 0) throw new ArgumentOutOfRangeException(nameof(hours), "the horizon must be a positive, finite number of sim hours");
|
||||
using var demo = EconomyLoop.Boot(root, seed, region: true);
|
||||
var catalog = demo.Cache;
|
||||
var sample = new RegionSample { Seed = seed, Hours = hours, Parked = demo.ParkHaulers() };
|
||||
beforeRun?.Invoke(demo);
|
||||
var galaxy = demo.Galaxy;
|
||||
var zones = galaxy.Zones.Where(zone => zone.Contents != null).ToArray();
|
||||
sample.Zones = zones.Length;
|
||||
|
||||
// The stations: every orbital that is some kind of station, in zone index order and entity order.
|
||||
string Good(CultRecordKey key) => catalog.Get<ItemData>(key)?.Name ?? key.Value;
|
||||
var tracked = new List<(RegionStation station, Entity entity, (EquippedItem unit, Facility facility)[] facilities, CultRecordKey[] outputs)>();
|
||||
foreach (var zone in zones)
|
||||
foreach (var entity in zone.Contents.Entities.OfType<OrbitalEntity>().Where(e => e.Kind.IsSet()))
|
||||
{
|
||||
var station = new RegionStation
|
||||
{
|
||||
Zone = zone.Name, Name = entity.Name, Entrance = zone == galaxy.Entrance,
|
||||
Faction = entity.Faction?.Name ?? "none", Kind = catalog.Get(entity.Kind)?.Name ?? entity.Kind.Key.Value,
|
||||
Depth = DemoPressure.Depth(galaxy, zone)
|
||||
};
|
||||
var facilities = entity.Equipment.SelectMany(unit => unit.Behaviors.OfType<Facility>().Select(facility => (unit, facility))).ToArray();
|
||||
var outputs = facilities.SelectMany(f => Production.RunList(catalog, f.unit.EquippableItem.Data.Key)).Select(recipe => recipe.Output.Key).Distinct().ToArray();
|
||||
foreach (var (unit, _) in facilities)
|
||||
{
|
||||
var run = Production.RunList(catalog, unit.EquippableItem.Data.Key);
|
||||
station.Facilities.Add(new RegionFacility { Name = demo.Items.GetData(unit.EquippableItem).Name, Outputs = run.Select(recipe => Good(recipe.Output.Key)).ToList() });
|
||||
foreach (var recipe in run)
|
||||
{
|
||||
var entry = sample.Recipes.FirstOrDefault(r => r.Output == Good(recipe.Output.Key));
|
||||
if (entry == null) sample.Recipes.Add(entry = new RegionRecipe { Output = Good(recipe.Output.Key) });
|
||||
entry.Stations++;
|
||||
}
|
||||
}
|
||||
var hold = new EntityHold(entity);
|
||||
foreach (var output in outputs) station.Held[Good(output)] = (hold.Held(output), 0);
|
||||
sample.Stations.Add(station);
|
||||
tracked.Add((station, entity, facilities, outputs));
|
||||
}
|
||||
|
||||
var heldLast = tracked.Select(t => t.outputs.Select(output => new EntityHold(t.entity).Held(output)).ToArray()).ToArray();
|
||||
var made = new Dictionary<string, long>(StringComparer.Ordinal);
|
||||
var started = new HashSet<string>(StringComparer.Ordinal);
|
||||
var ticks = (int) Math.Floor(hours * 3600 / RegionClock.Span + 1e-9);
|
||||
for (var tick = 1; tick <= ticks; tick++)
|
||||
{
|
||||
var time = tick * RegionClock.Span;
|
||||
foreach (var zone in zones) zone.Contents.AdvanceTo(time);
|
||||
for (var s = 0; s < tracked.Count; s++)
|
||||
{
|
||||
var (station, entity, facilities, outputs) = tracked[s];
|
||||
for (var f = 0; f < facilities.Length; f++)
|
||||
{
|
||||
var stall = facilities[f].facility.Stall;
|
||||
var tally = station.Facilities[f].Stalls;
|
||||
tally[stall] = tally.TryGetValue(stall, out var n) ? n + 1 : 1;
|
||||
var run = facilities[f].unit.EquippableItem.Run;
|
||||
if (run != null && run.Progress > 0) started.Add(Good(RecipeOutput(catalog, run)));
|
||||
}
|
||||
var hold = new EntityHold(entity);
|
||||
for (var o = 0; o < outputs.Length; o++)
|
||||
{
|
||||
var now = hold.Held(outputs[o]);
|
||||
if (now > heldLast[s][o]) made[Good(outputs[o])] = (made.TryGetValue(Good(outputs[o]), out var m) ? m : 0) + now - heldLast[s][o];
|
||||
heldLast[s][o] = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
sample.Spans = ticks;
|
||||
for (var s = 0; s < tracked.Count; s++)
|
||||
for (var o = 0; o < tracked[s].outputs.Length; o++)
|
||||
{
|
||||
var name = Good(tracked[s].outputs[o]);
|
||||
tracked[s].station.Held[name] = (tracked[s].station.Held[name].Start, heldLast[s][o]);
|
||||
}
|
||||
foreach (var recipe in sample.Recipes)
|
||||
{
|
||||
recipe.Made = made.TryGetValue(recipe.Output, out var units) ? units : 0;
|
||||
recipe.Started = started.Contains(recipe.Output);
|
||||
}
|
||||
|
||||
// Kinds by faction over the non-entrance stations: the count, and the depth range of the zones they sit in.
|
||||
var outside = sample.Stations.Where(station => !station.Entrance).ToList();
|
||||
foreach (var group in outside.GroupBy(station => (station.Faction, station.Kind)).OrderBy(g => g.Key.Faction, StringComparer.Ordinal).ThenBy(g => g.Key.Kind, StringComparer.Ordinal))
|
||||
sample.Kinds.Add(new RegionKind { Faction = group.Key.Faction, Kind = group.Key.Kind, Stations = group.Count(), DepthMin = group.Min(s => s.Depth), DepthMax = group.Max(s => s.Depth) });
|
||||
|
||||
// A faction's link set is the kinds it can field (StationKinds.FieldableKindsOf), read from the catalog and not from the
|
||||
// stations: a kind it fields that none of its non-entrance stations is, is a link the region lacks.
|
||||
var factions = zones.Where(zone => zone != galaxy.Entrance)
|
||||
.SelectMany(zone => zone.Contents.Entities.OfType<OrbitalEntity>().Where(e => e.Kind.IsSet() && e.Faction != null))
|
||||
.Select(entity => entity.Faction).Distinct().OrderBy(faction => faction.Name, StringComparer.Ordinal);
|
||||
foreach (var faction in factions)
|
||||
{
|
||||
var held = outside.Where(station => station.Faction == faction.Name).Select(station => station.Kind).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var kind in StationKinds.FieldableKindsOf(catalog, faction))
|
||||
{
|
||||
var name = catalog.Get(kind)?.Name ?? kind.Key.Value;
|
||||
if (!held.Contains(name)) sample.MissingLinks.Add((faction.Name, name));
|
||||
}
|
||||
}
|
||||
atEnd?.Invoke(demo);
|
||||
return sample;
|
||||
}
|
||||
|
||||
private static CultRecordKey RecipeOutput(CultCache catalog, FacilityRun run) => catalog.Get<RecipeData>(run.Recipe.Key)?.Output.Key ?? run.Recipe.Key;
|
||||
|
||||
// The faults of a set of samples: a recipe of a held facility that made nothing in the horizon, and a kind a faction fields that
|
||||
// none of its non-entrance stations is.
|
||||
public static List<EconomyFault> Report(IReadOnlyList<RegionSample> samples)
|
||||
{
|
||||
var faults = new List<EconomyFault>();
|
||||
foreach (var sample in samples)
|
||||
{
|
||||
foreach (var recipe in sample.Recipes.Where(r => !r.Ran))
|
||||
faults.Add(new EconomyFault(HIdle, $"seed {sample.Seed} {recipe.Output}", $"{recipe.Output} is a recipe of {recipe.Stations} facilities the region holds and none made a unit in {sample.Hours:0.##} sim h: no cycle of it ran. A station that needs a good it does not hold stalls Inputs here: this view moves no cargo (region-haul-legs)."));
|
||||
foreach (var (faction, kind) in sample.MissingLinks)
|
||||
faults.Add(new EconomyFault(HMissingLink, $"seed {sample.Seed} {faction}", $"{faction} fields {kind}, and no station of it outside the entrance zone is one: the chain has no such link."));
|
||||
}
|
||||
return faults;
|
||||
}
|
||||
|
||||
public static void Print(RegionSample sample, TextWriter output)
|
||||
{
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
output.WriteLine(string.Format(inv, "\nRegion, seed {0} ({1} zones advanced to {2:0.##} sim h in {3} spans of {4:0} s by Zone.AdvanceTo; no zone steps, no player flies; hauler parked: {5})", sample.Seed, sample.Zones, sample.Hours, sample.Spans, RegionClock.Span, sample.Parked));
|
||||
output.WriteLine(" no cargo moves between stations in this view (region-haul-legs): a station that needs a good it does not hold reads Inputs");
|
||||
output.WriteLine(" stations outside the entrance zone by faction and kind (count | depth toward the gate, min to max)");
|
||||
foreach (var kind in sample.Kinds)
|
||||
output.WriteLine(string.Format(inv, " {0} {1}: {2} | {3:0.##} to {4:0.##}", kind.Faction, kind.Kind, kind.Stations, kind.DepthMin, kind.DepthMax));
|
||||
output.WriteLine(sample.MissingLinks.Count == 0
|
||||
? " missing links: none"
|
||||
: " missing links: " + string.Join("; ", sample.MissingLinks.Select(link => $"{link.Faction} {link.Kind}")));
|
||||
foreach (var station in sample.Stations.Where(s => s.Facilities.Count > 0))
|
||||
{
|
||||
output.WriteLine($" {station.Zone} | {station.Name} ({station.Faction} {station.Kind}{(station.Entrance ? ", entrance" : "")})");
|
||||
foreach (var facility in station.Facilities)
|
||||
{
|
||||
var total = facility.Stalls.Values.Sum();
|
||||
output.WriteLine($" facility {facility.Name}: {(total == 0 ? "no spans" : string.Join(", ", facility.Stalls.Select(kv => string.Format(inv, "{0} {1:0.#}%", kv.Key, 100.0 * kv.Value / total))))}");
|
||||
}
|
||||
output.WriteLine(" held at start -> end: " + string.Join("; ", station.Held.Select(kv => $"{kv.Key} {kv.Value.Start} -> {kv.Value.End}")));
|
||||
}
|
||||
output.WriteLine(" recipes of the facilities the region holds (output | stations | units the output rose by, the most seen made | ran)");
|
||||
foreach (var recipe in sample.Recipes.OrderBy(r => r.Output, StringComparer.Ordinal))
|
||||
output.WriteLine($" {recipe.Output} | {recipe.Stations} | {recipe.Made} | {(recipe.Ran ? "yes" : "NO")}");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue