Files
Rail_Enterprise/tests/RailEnterprise.Tests/Economy/EconomyTests.cs
T
Alby96andClaude Opus 5.5 3d394c01d3 F6: bilanciamento con i bot su simulate
Banco di prova ripetibile per tarare l'economia (ADR 0025, obiettivi O1–O14
scritti prima della taratura):

- railenterprise-tools balance: semi × difficoltà × bot × anni in parallelo,
  rapporto deterministico (rapporto.txt con gli obiettivi, anni/mesi/prezzi/
  esecuzioni.csv, tempi.txt); simulate --bot <id>.
- Bot giocatore (PlayerBot): l'agente delle IA con le personalità di
  ai.json → bots guida la compagnia del giocatore; pianifica per primo; non
  è salvato né nell'hash, il formato dei salvataggi non cambia.
- Le IA usano la compravendita in proprio (supera ADR 0016 §9) con una regola
  mensile deterministica e parametri in ai.json → trading.
- Agente corretto: un trasformatore è fonte solo con gli input alimentati
  (prima i bot fallivano su linee rimaste senza merce finite le scorte
  iniziali); la linea dei ricambi di una rete nuova esce dal budget iniziale
  se l'utile la ripaga entro planning.partsDeferYears.
- Dati: market.world volumeShare 0,5 → 1,0 ed elasticity 1,0 → 2,5;
  townBonus 1,8 → 3,0, townRoiFactor 0,5 → 0,35.

Matrice predefinita (72 esecuzioni da 12 anni, 533 s): obiettivi da 5 a 9
su 14; livello 2 del bot competente in «Imprenditore» al 4° anno (prima 7°),
nessun fallimento dei bot in «Apprendista» e «Imprenditore», prezzi medi tra
0,77 e 1,42 volte il base (prima 0,38–2,78). Restano aperti O7–O11.

EconomyTests.PriceRisesWhenDemandExceedsSupply: la soglia passa da 1,5 a
1,25 volte in 120 giorni perché il mondo a volume pieno ed elasticità 2,5
assorbe parte dello squilibrio (aumento misurato ~1,36). Accettazioni F2, F4
e F5 invariate e verdi; 222 test verdi.

Refs #47.

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

231 lines
11 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.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Tests.Harness;
namespace RailEnterprise.Tests.Economy;
public static class EconomyTests
{
[Test(Description = "Invarianti: la somma di tutti i saldi resta zero, nessun bene nasce dal nulla")]
public static void MoneyAndGoodsInvariantsHold()
{
var w = TestWorlds.Small(101);
for (int month = 0; month < 18; month++)
{
w.RunDays(30);
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro al mese {month}");
for (int g = 0; g < w.Data.GoodCount; g++)
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} al mese {month}");
}
Assert.True(w.Goods.Produced.Sum() > 0, "qualcosa è stato prodotto");
}
[Test(Description = "I prezzi globali restano sempre entro 0,3·Pb e 3·Pb")]
public static void PricesStayWithinLimits()
{
var w = TestWorlds.Small(102, "ferro_e_sangue");
var m = w.Data.Balance.Market;
for (int day = 0; day < 3 * 360; day++)
{
w.RunDays(1);
for (int g = 0; g < w.Data.GoodCount; g++)
{
double pb = w.Data.Goods[g].BasePrice;
Assert.InRange(w.Market.GlobalPrice[g], m.MinPriceFactor * pb - 1e-6, m.MaxPriceFactor * pb + 1e-6);
}
}
}
[Test]
public static void PriceRisesWhenDemandExceedsSupply()
{
var w = TestWorlds.Small(103);
int food = w.Data.GoodIndex("food");
double before = w.Market.GlobalPrice[food];
// nessuna produzione di alimentari raggiunge il mercato: la domanda cittadina spinge il prezzo; il resto
// del mondo (volume pieno ed elasticità 2,5, ADR 0025) ne assorbe una parte, quindi la salita è più dolce
w.RunDays(120);
Assert.True(w.Market.GlobalPrice[food] > before * 1.25, $"prezzo alimentari {before} → {w.Market.GlobalPrice[food]}");
}
[Test]
public static void LocalPriceFollowsImbalanceWithinBounds()
{
var lp = TestData.Data.Balance.LocalPrice;
Assert.Approx(100.0, Market.LocalPrice(100, 10, 10, lp), 1e-9);
Assert.True(Market.LocalPrice(100, 50, 0, lp) > 130);
Assert.True(Market.LocalPrice(100, 0, 50, lp) < 70);
Assert.InRange(Market.LocalPrice(100, 1e9, 0, lp), 60, 140);
Assert.InRange(Market.LocalPrice(100, 0, 1e9, lp), 60, 140);
}
[Test]
public static void FreightAndPassengerTariffsFollowFormulas()
{
var t = TestData.Data.Balance.Tariffs;
// a prezzo base: 40 t × tariffa base × 1 × 20^0,9 centesimi
var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0);
Assert.Equal(Money.FromCentsRounded(40 * t.FreightBaseRate * DMath.Pow(20, 0.9)), freight);
// consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala
var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0);
Assert.True(late < freight && late.Cents >= freight.Cents / 2);
var staff = Tariffs.Passenger(10, 15, PaxClass.Staff, 1, 1, t, 1.0);
var worker = Tariffs.Passenger(10, 15, PaxClass.Worker, 1, 1, t, 1.0);
Assert.Approx(3.0, (double)staff.Cents / worker.Cents, 0.01, "classe personale ×3");
}
[Test(Description = "Solo le industrie servite crescono; con punteggio alto salgono di livello dopo due trimestri")]
public static void ServedIndustryWithGoodScoreUpgrades()
{
var w = TestWorlds.Small(104);
var mine = w.Industries.First(i => i.Def.Kind == IndustryKind.Primary && i.Level == 1 && !i.Closed);
var other = w.Industries.First(i => i != mine && i.Def.Kind == IndustryKind.Primary && !i.Closed);
int otherLevel = other.Level;
for (int q = 0; q < 2; q++)
{
for (int d = 0; d < 90; d++)
{
// tutta la produzione viene spedita e i posti sono coperti
mine.WorkersPresent = mine.JobsWorkers;
mine.StaffPresent = mine.JobsStaff;
mine.CovWorkers = 1;
mine.CovStaff = 1;
mine.RevenueEma = 1_000_000;
mine.CostEma = 100_000;
mine.QuarterShipped = mine.QuarterProduced;
mine.LastServedDay = w.Clock.Day; // servita da un vettore simulato
w.RunDays(1);
}
}
w.RunTicks(1); // il secondo trimestre si chiude nel primo tick del giorno 180
Assert.Equal(2, mine.Level, "livello dopo due trimestri ottimi");
Assert.Equal(otherLevel, other.Level, "un'industria non servita non cambia livello");
}
[Test(Description = "Un'industria servita ma abbandonata scende fino a 0 e chiude dopo quattro trimestri a zero")]
public static void NeglectedServedIndustryDeclinesAndCloses()
{
var w = TestWorlds.Small(105);
var ind = w.Industries.First(i => i.Def.Kind == IndustryKind.Processing && !i.Closed);
int startLevel = ind.Level;
for (int d = 0; d < 90 * (startLevel + 5) + 1; d++)
{
ind.LastServedDay = w.Clock.Day; // servita ma senza consegne né spedizioni
w.RunDays(1);
}
Assert.True(ind.Closed, $"chiusa (livello iniziale {startLevel}, ultimo punteggio {ind.LastScore:F2})");
Assert.True(w.Events.Recent.Any(e => e.Text.Contains(ind.Name, StringComparison.Ordinal) && e.Text.Contains("chiude", StringComparison.Ordinal)));
}
[Test]
public static void TownsGrowWithSatisfactionAndShrinkWithout()
{
var w = TestWorlds.Small(106);
var served = w.Towns[0];
var neglected = w.Towns[1];
int s0 = served.Population, n0 = neglected.Population;
for (int d = 0; d < 360; d++)
{
for (int g = 0; g < w.Data.GoodCount; g++)
{
int need = (int)Math.Ceiling(served.DemandToday[g]) + 1;
if (served.DemandToday[g] > 0 && served.Stock[g] < need)
{
int add = need - served.Stock[g];
served.Stock[g] += add;
w.Goods.Produced[g] += add; // consegna simulata, contabilizzata
}
}
w.RunDays(1);
}
Assert.True(served.OverallSatisfaction > 0.9, $"soddisfazione {served.OverallSatisfaction:F2}");
Assert.True(served.Population > s0, $"la città servita cresce: {s0} → {served.Population}");
Assert.True(neglected.Population < n0, $"la città trascurata cala: {n0} → {neglected.Population}");
Assert.True(served.Services >= 2);
}
[Test]
public static void LoansRespectCreditAndAccrueInterest()
{
var w = TestWorlds.Small(107);
var player = w.Player;
var credit = FinanceSystem.MaxLoan(w, player);
Assert.Equal(new Money(w.Difficulty.InitialCredit), credit);
var cash0 = player.Cash;
w.Enqueue(new TakeLoanCommand(credit + Money.FromLire(1)) { Issuer = player.Id, Seq = 1 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(100_000)) { Issuer = player.Id, Seq = 2 });
w.RunTicks(1);
var results = w.DrainResults();
Assert.Equal(CommandError.CreditLimit, results[0].Error);
Assert.True(results[1].Ok, results[1].Message);
Assert.Equal(cash0 + Money.FromLire(100_000), player.Cash);
Assert.Equal(Money.FromLire(100_000), player.Debt);
w.RunDays(31);
Assert.True(player.Debt < Money.FromLire(100_000), "la rata riduce il debito");
Assert.True(player.YearEntries[(int)LedgerEntry.Interest] < 0, "interessi pagati");
Assert.Equal(0L, w.MoneyBalanceSum());
var loanId = player.Loans[0].Id;
w.Enqueue(new RepayLoanCommand(loanId, player.Debt) { Issuer = player.Id, Seq = 3 });
w.RunTicks(1);
Assert.True(w.DrainResults()[0].Ok);
Assert.Equal(Money.Zero, player.Debt);
}
[Test]
public static void UnimplementedCommandsAreRejectedWithoutSideEffects()
{
var w = TestWorlds.Small(108);
ulong before = RailEnterprise.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults();
// al livello 1 le concessioni si rifiutano per il livello (ADR 0018), con il livello che le sblocca
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Concessions);
Assert.Equal(CommandError.TierLocked, results[0].Error);
Assert.True(results[0].Message.Contains($"livello {tier.Level}, «{tier.NameIt}»"), results[0].Message);
Assert.Equal(CommandError.UnknownCompany, results[1].Error);
Assert.Equal(before, RailEnterprise.Core.Persistence.StateHasher.Compute(w));
// sbloccate dal livello, restano un comando non ancora disponibile (F7)
w.Player.Tier = tier.Level;
before = RailEnterprise.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 11 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
Assert.Equal(CommandError.NotImplemented, w.DrainResults()[0].Error);
Assert.Equal(before, RailEnterprise.Core.Persistence.StateHasher.Compute(w));
}
[Test]
public static void WalkingWorkersStaffIndustriesNextToTowns()
{
var w = TestWorlds.Small(109);
w.RunDays(40);
var manufacturing = w.Industries.Where(i => i.Def.Kind == IndustryKind.Manufacturing && !i.Closed).ToList();
Assert.True(manufacturing.Count > 0);
Assert.True(manufacturing.Any(i => i.CovWorkers > 0.9), "almeno una manifattura con lavoratori a piedi dalla città vicina");
Assert.True(w.Commutes.All(c => c.Walking));
foreach (var town in w.Towns)
Assert.True(town.EmployedWorkers <= town.Workforce(w.Data.Balance.Town), $"{town.Name}: occupati oltre la forza lavoro");
}
[Test]
public static void DifficultyChangesStartingConditions()
{
var easy = TestWorlds.Small(110, "apprendista");
var hard = TestWorlds.Small(110, "ferro_e_sangue");
Assert.Equal(Money.FromLire(500_000), easy.Player.Cash);
Assert.Equal(Money.FromLire(100_000), hard.Player.Cash);
Assert.Equal(1 + 1, easy.Companies.Count);
Assert.Equal(1 + 5, hard.Companies.Count);
Assert.Equal(easy.Terrain.ComputeHash(), hard.Terrain.ComputeHash(), "la difficoltà non cambia la mappa");
}
}