Files
Rail_Enterprise/tests/RailEnterprise.Tests/Balance/BalanceTests.cs
T
Alby96andClaude Opus 5.5 b0191e4b93
CI / Build e test (pull_request) Successful in 1m39s
CI / Immagine Docker (pull_request) Successful in 31s
F6: bilanciamento, correzioni della revisione
Misure del banco corrette (ADR 0025, «Correzioni della revisione»):
- O8: «trasformatori che vendono» = vendite nell'ultimo trimestre, non
  RevenueEma > 0 (la media mobile non torna a zero e contava impianti fermi
  da anni). Misurato bene il margine è positivo nel 62 % dei mesi dopo la
  taratura contro il 75 % di prima: la conclusione «logistica, non prezzo»
  non reggeva.
- O6 per partita e bene; O7 per difficoltà con la fascia allargata dalla
  volatilità del preset; O3–O5 solo sulle partite in cui il bot costruisce
  (O3 «non valutabile» se in una difficoltà non costruisce mai); O11 sulle
  IA presenti al 3° anno; O12 con gli interessi di dicembre (anno campionato
  dopo la chiusura); obiettivi del mondo su una partita per seme e
  difficoltà; mediana sui due valori centrali con un numero pari di semi.
- Verifica sui semi 4–9, mai usati nella taratura: O1 non tiene (livello 2
  al 4° anno in 3 semi su 6), O11 sì. Il test lento usa i semi 4–9.

Agente:
- il blocco in attesa della linea dei ricambi ferma solo le reti nuove e
  al più per partsDeferYears dall'apertura della rete;
- la linea dei ricambi si rimanda solo se l'utile la ripaga prima che
  finisca la dotazione del deposito (stimata dai tagliandi): con la regola
  di prima il bot competente falliva nel seme 9 di «Imprenditore»;
- il budget della compravendita vale per tutti gli affari del mese.
Una soglia minima al tasso dei prestiti per le linee urbane è stata provata
e scartata (O1 cade sul seme 3): motivazione nell'ADR.

Dati: limiti espliciti negli schemi per ai.json → planning e
balance.json → market.world, più due controlli del validatore.
Test: determinismo con più mondi in parallelo (anche con compravendita),
limiti degli schemi. ADR e STATE: 24 esecuzioni (non 72), tempi, legame
non monotono tra elasticità e accettazione F4 (un'unità di margine), tabella
prima / dopo / verifica rifatta con le misure nuove.

Matrice predefinita: 7 su 13 obiettivi (prima della taratura 4 su 13);
semi 4–9: 7 su 13. 244 test verdi (222 senza i lenti), client compilato.

Refs #47.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:00:11 +01:00

135 lines
8.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Ai;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tools.Balance;
using static RailEnterprise.Tests.Rail.RailFixture;
namespace RailEnterprise.Tests.Balance;
/// <summary>Banco di bilanciamento con i bot giocatore e compravendita delle IA (F6, issue #47, ADR 0025).</summary>
public static class BalanceTests
{
/// <summary>Esegue la matrice con un thread e con più thread e confronta testo, CSV e hash di ogni esecuzione.</summary>
private static List<BalanceRun> SameReportWithThreads(BalanceOptions o, int threads)
{
var a = BalanceBench.Run(TestData.Data, o with { Threads = 1 });
var b = BalanceBench.Run(TestData.Data, o with { Threads = threads });
Assert.Equal(BalanceReport.Text(TestData.Data, o, a), BalanceReport.Text(TestData.Data, o, b));
Assert.Equal(BalanceReport.YearsCsv(a), BalanceReport.YearsCsv(b));
Assert.Equal(BalanceReport.MonthsCsv(TestData.Data, a), BalanceReport.MonthsCsv(TestData.Data, b));
Assert.Equal(BalanceReport.PricesCsv(TestData.Data, a), BalanceReport.PricesCsv(TestData.Data, b));
Assert.Equal(BalanceReport.RunsCsv(TestData.Data, a), BalanceReport.RunsCsv(TestData.Data, b));
Assert.Equal(a.Count, b.Count);
for (int i = 0; i < a.Count; i++)
{
Assert.Equal(a[i].FinalHash, b[i].FinalHash, $"hash dell'esecuzione {i}");
Assert.True(a[i].InvariantsOk, $"invarianti di denaro e merci dell'esecuzione {i}");
}
return a;
}
[Test(Description = "Il banco è deterministico: stesso seme, stesso rapporto (testo, CSV e hash) con uno o due mondi in parallelo")]
public static void SameSeedGivesTheSameReport()
{
var o = new BalanceOptions { Seeds = [5, 6], Difficulties = ["imprenditore"], Bots = ["bot_competent"], Years = 2, SizeKm = 64 };
var runs = SameReportWithThreads(o, threads: 2);
Assert.True(runs.All(r => r.BotCommands > 0), "il bot ha giocato");
Assert.True(runs.All(r => r.Months.Count == 24), "24 mesi per esecuzione");
}
[Test(Slow = true, Description = "Il banco resta deterministico con più mondi in parallelo anche quando bot e IA arrivano al livello 2 e commerciano (ADR 0025)")]
public static void ParallelRunsWithTradingGiveTheSameReport()
{
// 128 km: nel seme 4 in «Apprendista» il bot arriva al livello 2 nel primo anno e commercia
var o = new BalanceOptions { Seeds = [4, 5], Difficulties = ["apprendista", "imprenditore"], Bots = ["bot_competent"], Years = 3 };
var runs = SameReportWithThreads(o, threads: 4);
long trades = runs.Sum(r => r.BotTrades + r.AiTrades);
Console.WriteLine($" livello 2 del bot agli anni {string.Join(", ", runs.Select(r => r.BotTierYear[1]))}; affari di bot e IA {trades}");
Assert.True(runs.Any(r => r.BotTierYear[1] > 0), "almeno un bot sblocca la compravendita");
Assert.True(trades > 0, "la compravendita delle IA e dei bot è stata esercitata");
}
[Test(Slow = true, Description = "Banco ridotto sui semi di verifica 4–9, non usati nella taratura (ADR 0025): in «Imprenditore» il bot competente non fallisce, paga interessi entro il 20 % dei ricavi, pochi rifiuti, invarianti; almeno un bot al livello 2 entro il 6° anno")]
public static void BenchMeetsTheMainGoals()
{
var o = new BalanceOptions { Seeds = [4, 5, 6, 7, 8, 9], Difficulties = ["imprenditore"], Bots = ["bot_competent"], Years = 6 };
var runs = BalanceBench.Run(TestData.Data, o);
var goals = BalanceReport.Goals(TestData.Data, runs);
foreach (var g in goals) Console.WriteLine($" {(g.Met is null ? "—" : g.Met.Value ? "sì" : "NO")} {g.Id} {g.Text}: {g.Measured}");
foreach (var id in new[] { "O5", "O12", "O13", "O14" })
{
var g = goals.Single(x => x.Id == id);
Assert.True(g.Met == true, $"{g.Id} {g.Text}: {g.Measured}");
}
// O1 non è raggiunto sui semi di verifica (ADR 0025: livello 2 al 4° anno in 3 semi su 6, poi all'8°,
// al 10° o mai): il test ne controlla solo il crollo
Assert.True(runs.Any(r => r.BotTierYear[1] > 0), $"nessun bot al livello 2 in {o.Years} anni: {goals.Single(x => x.Id == "O1").Measured}");
}
[Test(Description = "Il bot guida la compagnia del giocatore con i comandi, non entra nel salvataggio e il mondo resta deterministico")]
public static void BotDrivesThePlayerAndIsNotSaved()
{
static World Make()
{
var w = TestWorlds.Small(11);
w.PlayerBot = PlayerBot.Create(w, "bot_competent");
return w;
}
var a = Make();
var b = Make();
a.RunYears(1);
b.RunYears(1);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
Assert.True(a.PlayerBot!.State.Issued > 0, "il bot emette comandi");
Assert.True(a.Network.Stations.Any(s => s.Owner == a.Player.Id), "stazioni del giocatore costruite dal bot");
Assert.True(a.PlayerBot.State.RejectedShare <= a.Data.Ai.Planning.MaxRejectedShare, $"rifiutati {a.PlayerBot.State.Rejected} su {a.PlayerBot.State.Issued}");
Assert.Equal(a.Companies.Count(c => !c.IsPlayer), a.AiStates.Count);
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(a, "test"));
Assert.True(loaded.PlayerBot is null, "il bot non è salvato");
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(loaded));
Assert.Throws<ArgumentException>(() => PlayerBot.Create(a, "expansive"));
}
[Test(Description = "Compravendita delle IA (ADR 0016 §9): con il produttore pieno e il consumatore a secco nello stesso bacino l'agente compra e vende, senza comandi rifiutati")]
public static void AgentTradesWhenTheMarginPays()
{
var f = Valdoria();
var w = f.W;
// stazione tra l'acciaieria e la fabbrica di attrezzi: produttore e consumatore dell'acciaio nello stesso bacino
int hub = f.Ok(new BuildStationCommand(K(11.7, 3.7), 2, "Acciaierie"));
var station = w.Network.Stations[hub];
var mill = w.Industries.First(i => i.Def.Id == "steel_mill");
var tools = w.Industries.First(i => i.Def.Id == "tool_factory");
Assert.True(station.Industries.Contains(mill.Id) && station.Industries.Contains(tools.Id), "bacino con acciaieria e fabbrica");
w.Player.Tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading).Level;
int steel = w.Data.Goods.First(g => g.Id == "steel").Index;
int cap = IndustryMath.OutputCapacity(mill, 0, w.Calendar.DaysPerMonth);
w.Goods.Produced[steel] += cap - mill.OutputStock[0];
mill.OutputStock[0] = cap;
int input = tools.InputIndexOf(steel);
w.Goods.Decayed[steel] += tools.InputStock[input];
tools.InputStock[input] = 0;
var q = TradingMath.Quote(w, station, steel);
Assert.True((q.SellPrice - q.BuyPrice) / q.BuyPrice > w.Data.Ai.Trading.MinMargin, $"margine atteso: compra {q.BuyPrice:0}, vende {q.SellPrice:0}");
w.PlayerBot = PlayerBot.Create(w, "bot_competent");
long millCash = mill.Cash.Cents, toolsCash = tools.Cash.Cents;
w.RunDays(w.Calendar.DaysPerMonth + 1);
long trading = w.Player.YearEntries[(int)LedgerEntry.Trading];
Assert.True(mill.Cash.Cents > millCash, "l'acciaieria ha venduto acciaio alla compagnia");
Assert.True(tools.Cash.Cents < toolsCash, "la fabbrica di attrezzi ha comprato l'acciaio");
Assert.True(trading > 0, $"utile della compravendita: {trading} centesimi");
Assert.Equal(0, station.StockOf(steel), "rivenduto subito alla fabbrica");
Assert.Equal(0L, w.PlayerBot.State.Rejected, "nessun comando rifiutato");
Assert.Equal(0L, w.MoneyBalanceSum());
for (int g = 0; g < w.Data.GoodCount; g++)
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
}
}