F6: bilanciamento, correzioni della revisione
CI / Build e test (pull_request) Successful in 1m39s
CI / Immagine Docker (pull_request) Successful in 31s

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 18:00:11 +01:00
1 parent 67a3dd05f9
commit b0191e4b93
11 files changed
+790 -188

No files matched your search

@@ -277,8 +277,11 @@ public static class DataValidator
Unique("ai.json", d.Ai.Personalities.Select(p => p.Id).Concat(d.Ai.Bots.Select(p => p.Id)), errors);
if (d.Ai.Trading.MinMargin <= 2 * d.Ai.Trading.PriceSlack)
Err("ai.json", "trading.minMargin deve superare il doppio di trading.priceSlack (ogni unità scambiata resta in margine)");
if (d.Ai.Planning.PartsDeferYears < 0)
Err("ai.json", "planning.partsDeferYears non può essere negativo");
// i limiti dei singoli valori di taratura (planning, market.world) sono negli schemi (ADR 0025)
if (d.Ai.Planning.CandidateMinDistanceKm >= d.Ai.Planning.CandidateMaxDistanceKm)
Err("ai.json", "planning.candidateMinDistanceKm deve essere minore di candidateMaxDistanceKm");
if (d.Balance.Market.World.ShockMin > d.Balance.Market.World.ShockMax)
Err("balance.json", "market.world.shockMin non può superare shockMax");
Unique("contracts.json", d.Contracts.Templates.Select(t => t.Id), errors);
foreach (var t in d.Contracts.Templates)
{
@@ -27,7 +27,8 @@ internal sealed class AiAgent
private readonly AiPlanningParams _plan;
private readonly AiMarketParams _mk;
private readonly GridPath _path;
// un deposito in esercizio aspetta la sua linea dei ricambi e la cassa non basta ancora: niente reti nuove
// un deposito in esercizio aspetta la sua linea dei ricambi e la cassa non basta ancora: questo mese
// niente reti nuove (nuovi depositi), le linee che usano un deposito esistente restano possibili
private bool _partsPending;
public AiAgent(World w, WorldContext ctx, AiState s, GridPath path, AiPersonalityDef? personality = null)
@@ -271,7 +272,11 @@ internal sealed class AiAgent
RenewFleet();
StockMarket();
BuyIndustries();
if (!EnsurePartsSupply() && !_partsPending) NewProject();
if (!EnsurePartsSupply())
{
if (_partsPending) _s.PartsBlockedMonths++;
NewProject();
}
Trade();
}
@@ -354,7 +359,9 @@ internal sealed class AiAgent
string good = _w.Data.Goods[d.Good].Id;
long maxPrice = (long)Math.Ceiling(d.BuyPrice * (1 + t.PriceSlack));
if (FreeCash() < maxPrice) break;
int units = d.Units;
// il budget del mese (cashShare della cassa oltre la riserva) vale per tutti gli affari insieme
int units = (int)Math.Min(d.Units, budget / maxPrice);
if (units <= 0) continue;
if (d.To.Id == d.From.Id)
{
// un affare precedente può aver riempito un compratore comune a due stazioni vicine
@@ -367,10 +374,13 @@ internal sealed class AiAgent
if (units <= 0) continue;
}
int before = d.From.StockOf(d.Good);
long cashBefore = _c.Cash.Cents;
if (!Do(new BuyGoodsCommand(d.From.Id, good, units, new Money(maxPrice))).Ok) continue;
budget -= cashBefore - _c.Cash.Cents;
int bought = d.From.StockOf(d.Good) - before;
if (bought <= 0) continue;
done++;
_s.Trades++;
if (d.To.Id == d.From.Id)
Do(new SellGoodsCommand(d.From.Id, good, bought, new Money((long)Math.Floor(d.SellPrice * (1 - t.PriceSlack)))));
else
@@ -480,7 +490,14 @@ internal sealed class AiAgent
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: linea dei ricambi per {depot.Name}: {km:0.0} km, capitale {new Money(proposal.Capital)} (budget {new Money(budget)})");
if (proposal.Capital > budget)
{
_partsPending = true;
// si risparmia per la linea (niente depositi nuovi) solo entro planning.partsDeferYears
// dall'apertura della rete; poi l'agente torna a espandersi come prima (ADR 0025)
long opened = long.MaxValue;
foreach (var p in _s.Projects)
{
if (p.Depot == depot.Id && p.StartDay < opened) opened = p.StartDay;
}
if (opened != long.MaxValue && _ctx.Day - opened <= _plan.PartsDeferYears * _w.Calendar.DaysPerYear) _partsPending = true;
return false;
}
Execute(proposal, depot.Id);
@@ -824,9 +841,13 @@ internal sealed class AiAgent
// la linea dei ricambi entra nel ROI ma si costruisce dopo (EnsurePartsSupply): il deposito parte con la
// sua dotazione di ricambi e la linea si paga con i primi ricavi (ADR 0025)
if (proposal.Capital - proposal.DeferredCapital > budget) continue;
// un deposito aspetta la sua linea dei ricambi: niente reti nuove finché la cassa non basta
if (_partsPending && !proposal.ExistingDepot.IsValid) continue;
// ROI sul capitale investito, come nella guida (gli interessi sono una scelta di finanziamento)
double roi = proposal.Roi;
bool townProject = cand.SourceIsTown || cand.DestIsTown;
// le linee urbane che servono al livello passano con una soglia ridotta, anche sotto il tasso dei prestiti:
// il loro valore è lo sblocco del livello, che il ROI non misura (ADR 0025)
double threshold = townProject && NeedTowns() ? _p.RoiThreshold * _plan.TownRoiFactor : _p.RoiThreshold;
if (roi < threshold) continue;
if (best is null || proposal.Roi > best.Roi) best = proposal;
@@ -1226,8 +1247,17 @@ internal sealed class AiAgent
+ (existingB.IsValid ? 0 : _plan.Platforms * sp.UpkeepPerPlatformPerYear)
+ (existingDepot.IsValid ? 0 : sp.DepotUpkeepPerYear["small"])
+ km * _plan.TrackUpkeepPerKmPerYear;
// la linea dei ricambi si rimanda solo se l'utile della linea la ripaga presto (ADR 0025)
if (deferred > (revenue - costs) * _plan.PartsDeferYears) deferred = 0;
// la linea dei ricambi si rimanda solo se l'utile della linea la ripaga prima che finisca la dotazione
// iniziale del deposito (tagliandi dei treni previsti con la politica della personalità), e comunque
// entro planning.partsDeferYears (ADR 0025)
if (deferred > 0)
{
var mt = _w.Data.Maintenance;
double servicesPerYear = _w.Calendar.DaysPerYear / (mt.Intervals.ServiceDays * mt.Policy(_p.MaintenancePolicy).IntervalFactor);
double partsPerYear = trains * (1 + cars) * servicesPerYear * mt.Intervention("service").SpareParts;
double stockYears = partsPerYear <= 0 ? _plan.PartsDeferYears : mt.Depots.InitialSpareParts / partsPerYear;
if (deferred > (revenue - costs) * Math.Min(_plan.PartsDeferYears, stockYears)) deferred = 0;
}
return new Proposal
{
Candidate = cand, PosA = posA.Value, PosB = posB.Value, ExistingA = existingA, ExistingB = existingB,
@@ -59,6 +59,14 @@ public sealed class AiState
/// <summary>Ultimo giorno in cui l'IA ha sciolto uno stallo (uno ogni tanto, non a cascata).</summary>
public long LastGridlockDay { get; set; } = -1_000_000;
/// <summary>
/// Diagnostica del banco di bilanciamento (ADR 0025), né salvata né nell'hash: mesi in cui l'agente non
/// ha aperto reti nuove perché un deposito aspettava la sua linea dei ricambi, e affari di compravendita
/// conclusi (acquisti riusciti).
/// </summary>
public long PartsBlockedMonths { get; set; }
public long Trades { get; set; }
/// <summary>Quota dei comandi rifiutati sul totale emesso.</summary>
public double RejectedShare => Issued == 0 ? 0 : (double)Rejected / Issued;
}
@@ -50,6 +50,8 @@ public sealed class BalanceRun
public int AiBankrupt { get; set; }
/// <summary>IA con almeno una linea in esercizio alla fine del terzo anno.</summary>
public int AiActiveByYear3 { get; set; }
/// <summary>IA presenti alla fine del terzo anno (denominatore di O11), −1 se la partita è più corta.</summary>
public int AiAtYear3 { get; set; } = -1;
public int BestAiTier { get; set; }
/// <summary>Anno di gioco in cui la prima IA ha raggiunto il livello 2, 0 se mai.</summary>
public int AiTier2Year { get; set; }
@@ -64,6 +66,12 @@ public sealed class BalanceRun
public long BotRejected { get; set; }
public long AiCommands { get; set; }
public long AiRejected { get; set; }
/// <summary>Mesi senza reti nuove perché un deposito aspettava la linea dei ricambi (bot, somma delle IA).</summary>
public long BotPartsBlockedMonths { get; set; }
public long AiPartsBlockedMonths { get; set; }
/// <summary>Affari di compravendita conclusi dal bot e dalle IA.</summary>
public long BotTrades { get; set; }
public long AiTrades { get; set; }
public ulong FinalHash { get; set; }
public bool InvariantsOk { get; set; }
/// <summary>Durata in millisecondi (non entra nel rapporto deterministico).</summary>
@@ -122,13 +130,38 @@ public static class BalanceBench
int months = w.Calendar.MonthsPerYear;
int dpm = w.Calendar.DaysPerMonth;
var levels = w.Industries.Select(i => i.Level).ToArray();
// ultimo giorno con vendite di ogni industria (−1 se mai): il margine dei trasformatori «che vendono»
// si misura su chi ha venduto nell'ultimo trimestre (O8)
var lastSale = new List<long>();
var lastEma = new List<double>();
double alpha = Ema.Alpha(data.Balance.Industry.MarginWindowDays);
void Day()
{
w.RunDays(1);
long today = w.Clock.Day - 1;
for (int i = 0; i < w.Industries.Count; i++)
{
if (i >= lastSale.Count)
{
lastSale.Add(-1);
lastEma.Add(0);
}
// vendite del giorno ricavate dalla media mobile: RevenueEma = prima + α·(vendite − prima)
double ema = w.Industries[i].RevenueEma;
double sales = lastEma[i] + (ema - lastEma[i]) / alpha;
if (sales >= MinDailySalesCents) lastSale[i] = today;
lastEma[i] = ema;
}
}
int carried = 0;
for (int y = 0; y < years; y++)
{
int year = w.Clock.Year;
for (int m = 0; m < months; m++)
{
w.RunDays(dpm);
var month = SampleMonth(w, y * months + m);
for (int d = carried; d < dpm; d++) Day();
carried = 0;
var month = SampleMonth(w, y * months + m, lastSale);
run.Months.Add(month);
run.ServedIndustryMonths += month.ServedIndustries;
for (int i = 0; i < w.Industries.Count; i++)
@@ -142,9 +175,16 @@ public static class BalanceBench
if (levels.Length < w.Industries.Count) levels = [.. levels, .. w.Industries.Skip(levels.Length).Select(i => i.Level)];
w.Events.Drain();
}
// il bilancio dell'anno si chiude al primo giorno del successivo: le voci dell'anno sono ancora in YearEntries
// il bilancio dell'anno si chiude al primo tick dell'anno dopo, che registra ancora rate e interessi di
// dicembre: si campiona dopo quel giorno, dall'anno chiuso (LastYearEntries)
Day();
carried = 1;
SampleYear(w, run, y + 1, year);
if (y + 1 == 3) run.AiActiveByYear3 = w.AiStates.Count(s => !w.Company(s.Company).Defunct && s.Projects.Any(p => p.Stage == AiProjectStage.Running));
if (y + 1 == 3)
{
run.AiActiveByYear3 = w.AiStates.Count(s => !w.Company(s.Company).Defunct && s.Projects.Any(p => p.Stage == AiProjectStage.Running));
run.AiAtYear3 = w.AiStates.Count;
}
}
var player = w.Player;
run.BotTierYear = new int[data.Tiers.Tiers.Count];
@@ -167,16 +207,23 @@ public static class BalanceBench
{
run.BotCommands = pb.State.Issued;
run.BotRejected = pb.State.Rejected;
run.BotPartsBlockedMonths = pb.State.PartsBlockedMonths;
run.BotTrades = pb.State.Trades;
}
run.AiCommands = w.AiStates.Sum(s => s.Issued);
run.AiRejected = w.AiStates.Sum(s => s.Rejected);
run.AiPartsBlockedMonths = w.AiStates.Sum(s => s.PartsBlockedMonths);
run.AiTrades = w.AiStates.Sum(s => s.Trades);
run.FinalHash = w.LastStateHash;
run.InvariantsOk = w.MoneyBalanceSum() == 0 && Enumerable.Range(0, data.GoodCount).All(g => w.TotalStock(g) == w.Goods.ExpectedStock(g));
run.ElapsedMs = clock.ElapsedMilliseconds;
return run;
}
private static MonthRow SampleMonth(World w, int monthIndex)
/// <summary>Vendite giornaliere minime (centesimi) perché un giorno conti come giorno con vendite (soglia del banco).</summary>
public const double MinDailySalesCents = 1;
private static MonthRow SampleMonth(World w, int monthIndex, List<long> lastSale)
{
var data = w.Data;
int year = w.Clock.Year;
@@ -194,6 +241,7 @@ public static class BalanceBench
foreach (var ind in w.Industries)
{
if (ind.Closed || ind.Level <= 0) continue;
long sold = ind.Id.Value < lastSale.Count ? lastSale[ind.Id.Value] : -1;
open++;
eff += ind.Efficiency;
ci += ind.CovInput;
@@ -209,9 +257,10 @@ public static class BalanceBench
transformers++;
margin += ind.Margin;
if (ind.Margin < 0) negative++;
// trasformatori che vendono (ritiri dei vettori o trasporto locale): senza vendite il margine è −1
// per costruzione, qualunque siano i prezzi
if (ind.RevenueEma > 0)
// trasformatori che vendono (ritiri dei vettori o trasporto locale) nell'ultimo trimestre: senza vendite
// il margine tende a −1 per costruzione, qualunque siano i prezzi; RevenueEma > 0 non basta (una media
// mobile esponenziale non torna più a zero dopo la prima vendita)
if (sold >= 0 && day - sold <= window)
{
served++;
servedMargin += ind.Margin;
@@ -243,8 +292,8 @@ public static class BalanceBench
string personality = c.IsPlayer ? w.PlayerBot?.Personality.Id ?? NoBot : c.AiPersonality ?? "";
run.YearRows.Add(new CompanyYearRow(
yearIndex, year, c.Name, c.IsPlayer, personality, c.Tier, c.NetWorth.Cents, c.Rating.ToString(),
c.Cash.Cents, c.Debt.Cents, -c.YearEntries[(int)LedgerEntry.Interest], Company.TransportRevenue(c.YearEntries),
Company.OperatingProfit(c.YearEntries), trains, lines, c.Bankrupt, c.Defunct));
c.Cash.Cents, c.Debt.Cents, -c.LastYearEntries[(int)LedgerEntry.Interest], Company.TransportRevenue(c.LastYearEntries),
Company.OperatingProfit(c.LastYearEntries), trains, lines, c.Bankrupt, c.Defunct));
}
}
}
+161 -56
View File
@@ -33,19 +33,31 @@ public static class BalanceReport
public const double RejectedShareMax = 0.05;
/// <summary>Mediana degli anni (0 = mai, contato come oltre la fine) come testo.</summary>
/// <summary>Con un numero pari di semi la mediana sono i due valori centrali («4–8»).</summary>
private static string MedianYear(IEnumerable<int> years, int horizon)
{
var list = years.Select(y => y == 0 ? horizon + 1 : y).OrderBy(y => y).ToList();
if (list.Count == 0) return "–";
int m = list[(list.Count - 1) / 2];
return m > horizon ? "mai" : m.ToString(It);
var (lo, hi) = MedianYearValue(years);
if (lo == int.MinValue) return "–";
string Y(int y) => y == int.MaxValue || y > horizon ? "mai" : y.ToString(It);
return lo == hi ? Y(lo) : $"{Y(lo)}–{Y(hi)}";
}
/// <summary>Mediana degli anni con «mai» oltre ogni soglia (un obiettivo mancato non passa per caso).</summary>
private static int MedianYearValue(IEnumerable<int> years, int horizon)
/// <summary>
/// I due valori centrali degli anni (uguali con un numero dispari di semi), con «mai» oltre ogni soglia:
/// un obiettivo sulla mediana vale solo se vale per entrambi, così un obiettivo mancato non passa per caso.
/// </summary>
private static (int Lo, int Hi) MedianYearValue(IEnumerable<int> years)
{
var list = years.Select(y => y == 0 ? int.MaxValue : y).OrderBy(y => y).ToList();
return list.Count == 0 ? int.MaxValue : list[(list.Count - 1) / 2];
if (list.Count == 0) return (int.MinValue, int.MinValue);
return (list[(list.Count - 1) / 2], list[list.Count / 2]);
}
/// <summary>Quanti anni stanno nella fascia [from, to], come «3 su 6».</summary>
private static string InBand(IEnumerable<int> years, int from, int to)
{
var list = years.ToList();
return $"{list.Count(y => y >= from && y <= to)} su {list.Count} nella fascia";
}
private static long Median(IEnumerable<long> values)
@@ -68,97 +80,147 @@ public static class BalanceReport
var normal = Of(NormalDifficulty, CompetentBot);
if (normal.Count > 0)
{
int m = MedianYearValue(normal.Select(r => r.BotTierYear[1]), horizon);
var years = normal.Select(r => r.BotTierYear[1]).ToList();
var (lo, hi) = MedianYearValue(years);
goals.Add(new GoalResult("O1", $"bot competente in «Imprenditore»: livello 2 tra il {Tier2FromYear}° e il {Tier2ToYear}° anno (mediana)",
$"mediana {MedianYear(normal.Select(r => r.BotTierYear[1]), horizon)} (anni: {string.Join(", ", normal.Select(r => r.BotTierYear[1] == 0 ? "mai" : r.BotTierYear[1].ToString(It)))})",
m >= Tier2FromYear && m <= Tier2ToYear));
$"mediana {MedianYear(years, horizon)} (anni: {string.Join(", ", years.Select(y => y == 0 ? "mai" : y.ToString(It)))}; {InBand(years, Tier2FromYear, Tier2ToYear)})",
lo >= Tier2FromYear && hi <= Tier2ToYear));
}
else goals.Add(new GoalResult("O1", "bot competente in «Imprenditore»: livello 2 tra il 3° e il 6° anno", "non eseguito", null));
var easy = Of(EasyDifficulty, CompetentBot);
if (easy.Count > 0)
{
int m = MedianYearValue(easy.Select(r => r.BotTierYear[1]), horizon);
var years = easy.Select(r => r.BotTierYear[1]).ToList();
var (_, hi) = MedianYearValue(years);
goals.Add(new GoalResult("O2", $"bot competente in «Apprendista»: livello 2 entro il {EasyTier2ByYear}° anno (mediana)",
$"mediana {MedianYear(easy.Select(r => r.BotTierYear[1]), horizon)}", m <= EasyTier2ByYear));
$"mediana {MedianYear(years, horizon)} (anni: {string.Join(", ", years.Select(y => y == 0 ? "mai" : y.ToString(It)))}; {InBand(years, 1, EasyTier2ByYear)})", hi <= EasyTier2ByYear));
}
else goals.Add(new GoalResult("O2", "bot competente in «Apprendista»: livello 2 entro il 5° anno", "non eseguito", null));
// la difficoltà conta: patrimonio finale mediano del bot competente non crescente con la difficoltà
// la difficoltà conta: patrimonio finale mediano del bot competente non crescente con la difficoltà.
// Si contano solo le partite in cui il bot ha giocato (almeno una linea in esercizio): un bot fermo
// chiude con il capitale iniziale, che decresce con la difficoltà, e l'obiettivo passerebbe da solo.
var order = data.Difficulty.Presets.Select(p => p.Id).Where(d => Of(d, CompetentBot).Count > 0).ToList();
if (order.Count >= 2)
{
var worth = order.Select(d => Median(Of(d, CompetentBot).Select(r => FinalBot(r)?.NetWorthCents ?? 0))).ToList();
bool ok = true;
for (int i = 1; i < worth.Count; i++) ok &= worth[i] <= worth[i - 1];
goals.Add(new GoalResult("O3", "bot competente: patrimonio finale mediano non crescente con la difficoltà",
string.Join(" ≥ ", order.Zip(worth, (d, v) => $"{d} {Lire(v)}")), ok));
var idle = order.Where(d => !Of(d, CompetentBot).Any(Played)).ToList();
var worth = order.Select(d => Median(Of(d, CompetentBot).Where(Played).Select(r => FinalBot(r)?.NetWorthCents ?? 0))).ToList();
string measured = string.Join(" ≥ ", order.Zip(worth, (d, v) => idle.Contains(d) ? $"{d} senza partite giocate" : $"{d} {Lire(v)}"));
if (idle.Count > 0)
{
goals.Add(new GoalResult("O3", "bot competente: patrimonio finale mediano non crescente con la difficoltà",
$"non valutabile: il bot non costruisce in {string.Join(", ", idle)} ({measured})", null));
}
else
{
bool ok = true;
for (int i = 1; i < worth.Count; i++) ok &= worth[i] <= worth[i - 1];
goals.Add(new GoalResult("O3", "bot competente: patrimonio finale mediano non crescente con la difficoltà", measured, ok));
}
}
else goals.Add(new GoalResult("O3", "patrimonio decrescente con la difficoltà", "servono almeno due difficoltà", null));
var prudent = runs.Where(r => r.Bot == PrudentBot && (r.Difficulty == EasyDifficulty || r.Difficulty == NormalDifficulty)).ToList();
goals.Add(prudent.Count == 0
? new GoalResult("O4", "nessun fallimento del bot prudente in «Apprendista» e «Imprenditore»", "non eseguito", null)
: new GoalResult("O4", "nessun fallimento del bot prudente in «Apprendista» e «Imprenditore»",
$"{prudent.Count(r => r.BotBankrupt || r.GameOver)} su {prudent.Count}", prudent.All(r => !r.BotBankrupt && !r.GameOver)));
goals.Add(Bankruptcies("O4", "nessun fallimento del bot prudente in «Apprendista» e «Imprenditore»",
runs.Where(r => r.Bot == PrudentBot && (r.Difficulty == EasyDifficulty || r.Difficulty == NormalDifficulty)).ToList()));
goals.Add(Bankruptcies("O5", "nessun fallimento del bot competente in «Apprendista» e «Imprenditore»",
runs.Where(r => r.Bot == CompetentBot && (r.Difficulty == EasyDifficulty || r.Difficulty == NormalDifficulty)).ToList()));
var competentEasy = runs.Where(r => r.Bot == CompetentBot && (r.Difficulty == EasyDifficulty || r.Difficulty == NormalDifficulty)).ToList();
goals.Add(competentEasy.Count == 0
? new GoalResult("O5", "nessun fallimento del bot competente in «Apprendista» e «Imprenditore»", "non eseguito", null)
: new GoalResult("O5", "nessun fallimento del bot competente in «Apprendista» e «Imprenditore»",
$"{competentEasy.Count(r => r.BotBankrupt || r.GameOver)} su {competentEasy.Count}", competentEasy.All(r => !r.BotBankrupt && !r.GameOver)));
// obiettivi del mondo (O6–O11): una partita per seme e difficoltà, perché le partite dei due bot con
// lo stesso seme condividono mappa e IA e, se il bot non gioca, sono quasi lo stesso mondo
var world = WorldRuns(runs);
string n = $"{world.Count} partite distinte";
// prezzi
// prezzi: media di ogni bene in ogni partita (O6) e mesi-bene nella fascia della difficoltà (O7)
int goods = data.GoodCount;
int inBand = 0, total = 0;
double worstMeanLow = double.MaxValue, worstMeanHigh = double.MinValue;
string lowGood = "", highGood = "";
double worstLow = double.MaxValue, worstHigh = double.MinValue, pooledLow = double.MaxValue, pooledHigh = double.MinValue;
string lowAt = "", highAt = "", pooledLowGood = "", pooledHighGood = "";
int outOfBand = 0, pairs = 0;
for (int g = 0; g < goods; g++)
{
var values = runs.SelectMany(r => r.Months).Select(m => m.PriceRatio[g]).Where(v => !double.IsNaN(v)).ToList();
if (values.Count == 0) continue;
total += values.Count;
inBand += values.Count(v => v >= PriceLow && v <= PriceHigh);
double mean = values.Average();
if (mean < worstMeanLow) (worstMeanLow, lowGood) = (mean, data.Goods[g].Id);
if (mean > worstMeanHigh) (worstMeanHigh, highGood) = (mean, data.Goods[g].Id);
var all = new List<double>();
foreach (var r in world)
{
var v = r.Months.Select(m => m.PriceRatio[g]).Where(x => !double.IsNaN(x)).ToList();
if (v.Count == 0) continue;
all.AddRange(v);
double mean = v.Average();
pairs++;
if (mean < PriceLow || mean > PriceHigh) outOfBand++;
if (mean < worstLow) (worstLow, lowAt) = (mean, $"{data.Goods[g].Id} (seme {r.Seed}, {r.Difficulty})");
if (mean > worstHigh) (worstHigh, highAt) = (mean, $"{data.Goods[g].Id} (seme {r.Seed}, {r.Difficulty})");
}
if (all.Count == 0) continue;
double pooled = all.Average();
if (pooled < pooledLow) (pooledLow, pooledLowGood) = (pooled, data.Goods[g].Id);
if (pooled > pooledHigh) (pooledHigh, pooledHighGood) = (pooled, data.Goods[g].Id);
}
if (total > 0)
if (pairs > 0)
{
goals.Add(new GoalResult("O6", $"media di ogni bene entro {Dec(PriceLow)}–{Dec(PriceHigh)} volte il base",
$"più bassa {lowGood} {Dec(worstMeanLow, "0.00")}, più alta {highGood} {Dec(worstMeanHigh, "0.00")}",
worstMeanLow >= PriceLow && worstMeanHigh <= PriceHigh));
double share = (double)inBand / total;
goals.Add(new GoalResult("O7", $"almeno il {Dec(PriceMonthsInBand * 100)} % dei mesi-bene entro {Dec(PriceLow)}–{Dec(PriceHigh)} volte il base",
Pct(share), share >= PriceMonthsInBand));
goals.Add(new GoalResult("O6", $"media di ogni bene in ogni partita entro {Dec(PriceLow)}–{Dec(PriceHigh)} volte il base",
$"peggiori: più bassa {lowAt} {Dec(worstLow, "0.00")}, più alta {highAt} {Dec(worstHigh, "0.00")}; {outOfBand} su {pairs} medie partita-bene fuori; " +
$"sull'insieme delle partite {pooledLowGood} {Dec(pooledLow, "0.00")} – {pooledHighGood} {Dec(pooledHigh, "0.00")} ({n})",
outOfBand == 0));
int inBand = 0, total = 0;
bool everyDifficulty = true;
var perDifficulty = new List<string>();
foreach (var preset in data.Difficulty.Presets)
{
var set = world.Where(r => r.Difficulty == preset.Id).ToList();
if (set.Count == 0) continue;
var (low, high) = PriceBand(preset.MarketVolatilityMultiplier);
int dIn = 0, dTotal = 0;
foreach (var r in set)
{
foreach (var m in r.Months)
{
foreach (double v in m.PriceRatio)
{
if (double.IsNaN(v)) continue;
dTotal++;
if (v >= low && v <= high) dIn++;
}
}
}
inBand += dIn;
total += dTotal;
if (dTotal > 0 && (double)dIn / dTotal < PriceMonthsInBand) everyDifficulty = false;
perDifficulty.Add($"{preset.Id} {Pct(dTotal == 0 ? double.NaN : (double)dIn / dTotal)} in {Dec(low, "0.00")}–{Dec(high, "0.00")}");
}
double share = total == 0 ? 0 : (double)inBand / total;
goals.Add(new GoalResult("O7", $"in ogni difficoltà almeno il {Dec(PriceMonthsInBand * 100)} % dei mesi-bene entro {Dec(PriceLow)}–{Dec(PriceHigh)} volte il base (fascia allargata dalla volatilità della difficoltà)",
$"{string.Join("; ", perDifficulty)}; tutte insieme {Pct(share)}", everyDifficulty));
}
// margini dei trasformatori che vendono (quelli senza vendite hanno margine −1 per costruzione)
var served = runs.SelectMany(r => r.Months).Where(m => !double.IsNaN(m.SellingTransformerMargin)).ToList();
// margini dei trasformatori che hanno venduto nell'ultimo trimestre (gli altri hanno margine −1 per costruzione)
var served = world.SelectMany(r => r.Months).Where(m => !double.IsNaN(m.SellingTransformerMargin)).ToList();
if (served.Count > 0)
{
double share = (double)served.Count(m => m.SellingTransformerMargin > 0) / served.Count;
goals.Add(new GoalResult("O8", $"margine medio dei trasformatori che vendono positivo in almeno il {Dec(TransformerPositiveMonths * 100)} % dei mesi",
$"{Pct(share)} (margine medio {Dec(served.Average(m => m.SellingTransformerMargin), "0.000")})", share >= TransformerPositiveMonths));
$"{Pct(share)} (margine medio {Dec(served.Average(m => m.SellingTransformerMargin), "0.000")}, {Dec(served.Average(m => m.SellingTransformers), "0.0")} trasformatori che vendono al mese)", share >= TransformerPositiveMonths));
}
else goals.Add(new GoalResult("O8", "margine dei trasformatori che vendono positivo", "nessun trasformatore vende", null));
var servedEff = runs.SelectMany(r => r.Months.Skip(r.Months.Count / 2)).Where(m => !double.IsNaN(m.ServedEfficiency)).ToList();
var servedEff = world.SelectMany(r => r.Months.Skip(r.Months.Count / 2)).Where(m => !double.IsNaN(m.ServedEfficiency)).ToList();
if (servedEff.Count > 0)
{
double eff = servedEff.Average(m => m.ServedEfficiency);
goals.Add(new GoalResult("O9", $"efficienza media delle industrie servite almeno {Dec(ServedEfficiencyMin)} (seconda metà)", Dec(eff, "0.000"), eff >= ServedEfficiencyMin));
}
var normalAll = runs.Where(r => r.Difficulty == NormalDifficulty && r.Bot != BalanceBench.NoBot).ToList();
var normalAll = world.Where(r => r.Difficulty == NormalDifficulty && r.Bot != BalanceBench.NoBot).ToList();
if (normalAll.Count > 0)
{
double growth = normalAll.Average(r => AnnualGrowth(r));
goals.Add(new GoalResult("O10", $"popolazione in «Imprenditore» (con bot): crescita media annua almeno {Pct(PopulationGrowthMin)}", Pct(growth), growth >= PopulationGrowthMin));
}
int ais = runs.Sum(r => r.AiCompanies), active = runs.Sum(r => r.AiActiveByYear3);
if (ais > 0)
// IA attive entro il 3° anno su quelle presenti allora (i concorrenti nati dopo non contano)
var year3 = world.Where(r => r.AiAtYear3 >= 0).ToList();
int ais = year3.Sum(r => r.AiAtYear3), active = year3.Sum(r => r.AiActiveByYear3);
if (year3.Count == 0) goals.Add(new GoalResult("O11", "IA con una linea in esercizio entro il 3° anno", "non eseguito (partite più corte di 3 anni)", null));
else if (ais > 0)
{
double share = (double)active / ais;
goals.Add(new GoalResult("O11", $"almeno il {Dec(AiActiveShareMin * 100)} % delle IA con una linea in esercizio entro il 3° anno", $"{active} su {ais} ({Pct(share)})", share >= AiActiveShareMin));
@@ -186,6 +248,47 @@ public static class BalanceReport
private static CompanyYearRow? FinalBot(BalanceRun r) => r.YearRows.LastOrDefault(y => y.IsBot);
/// <summary>Il bot ha giocato: almeno una linea in esercizio alla fine di un anno (gli obiettivi O3–O5 contano solo queste partite).</summary>
public static bool Played(BalanceRun r) => r.YearRows.Any(y => y.IsBot && y.RunningLines > 0);
/// <summary>Fallimenti del bot sulle partite giocate; quelle senza linee si dichiarano e non contano.</summary>
private static GoalResult Bankruptcies(string id, string text, List<BalanceRun> set)
{
if (set.Count == 0) return new GoalResult(id, text, "non eseguito", null);
var played = set.Where(Played).ToList();
int idle = set.Count - played.Count;
string idleText = idle == 0 ? "" : $" ({idle} senza linee, non contate)";
if (played.Count == 0) return new GoalResult(id, text, $"non valutabile: il bot non costruisce in nessuna delle {set.Count} partite", null);
int failed = played.Count(r => r.BotBankrupt || r.GameOver);
return new GoalResult(id, text, $"{failed} su {played.Count}{idleText}", failed == 0);
}
/// <summary>
/// Una partita per seme e difficoltà per gli obiettivi del mondo: quella del bot competente se c'è,
/// altrimenti la prima del piano.
/// </summary>
public static List<BalanceRun> WorldRuns(List<BalanceRun> runs)
{
var list = new List<BalanceRun>();
foreach (var r in runs)
{
int k = list.FindIndex(x => x.Seed == r.Seed && x.Difficulty == r.Difficulty);
if (k < 0) list.Add(r);
else if (r.Bot == CompetentBot && list[k].Bot != CompetentBot) list[k] = r;
}
return list;
}
/// <summary>
/// Fascia dei prezzi di O7 per la difficoltà: 0,7–1,6 volte il base, allargata in proporzione alla
/// volatilità del mercato quando la difficoltà la moltiplica (sezione 7: A e shock × 1,3 o × 1,6).
/// </summary>
public static (double Low, double High) PriceBand(double volatility)
{
double v = Math.Max(1, volatility);
return (1 - (1 - PriceLow) * v, 1 + (PriceHigh - 1) * v);
}
/// <summary>Crescita media annua composta della popolazione complessiva.</summary>
public static double AnnualGrowth(BalanceRun r) =>
r.PopulationStart <= 0 || r.Years <= 0 ? 0 : Core.Common.DMath.Pow((double)r.PopulationEnd / r.PopulationStart, 1.0 / r.Years) - 1;
@@ -223,8 +326,9 @@ public static class BalanceReport
sb.AppendLine($" bot alla fine: livello {string.Join("/", finals.Select(f => f.Tier))}, patrimonio mediano {Lire(Median(finals.Select(f => f.NetWorthCents)))}, rating {string.Join("/", finals.Select(f => f.Rating))}, treni {string.Join("/", finals.Select(f => f.Trains))}");
sb.AppendLine($" bot fallito: {set.Count(r => r.BotBankrupt)}, fine partita: {set.Count(r => r.GameOver)}; interessi pagati (mediana del totale) {Lire(Median(set.Select(r => r.YearRows.Where(y => y.IsBot).Sum(y => y.InterestCents))))}");
sb.AppendLine($" livello per anno (prima esecuzione): {string.Join(" ", set[0].YearRows.Where(y => y.IsBot).Select(y => y.Tier))}");
sb.AppendLine($" bot con almeno una linea: {set.Count(Played)} su {set.Count}; mesi senza reti nuove in attesa dei ricambi {string.Join("/", set.Select(r => r.BotPartsBlockedMonths))}; affari di compravendita {string.Join("/", set.Select(r => r.BotTrades))}");
}
sb.AppendLine($" IA: {set.Sum(r => r.AiCompanies)} compagnie, fallite {set.Sum(r => r.AiBankrupt)}, attive al 3° anno {set.Sum(r => r.AiActiveByYear3)}, livello massimo {string.Join("/", set.Select(r => r.BestAiTier))}, primo livello 2 di un'IA all'anno {MedianYear(set.Select(r => r.AiTier2Year), horizon)} (mediana)");
sb.AppendLine($" IA: {set.Sum(r => r.AiCompanies)} compagnie, fallite {set.Sum(r => r.AiBankrupt)}, attive al 3° anno {set.Sum(r => r.AiActiveByYear3)} su {set.Sum(r => Math.Max(0, r.AiAtYear3))}, mesi senza reti nuove in attesa dei ricambi {set.Sum(r => r.AiPartsBlockedMonths)}, affari {set.Sum(r => r.AiTrades)}, livello massimo {string.Join("/", set.Select(r => r.BestAiTier))}, primo livello 2 di un'IA all'anno {MedianYear(set.Select(r => r.AiTier2Year), horizon)} (mediana)");
var months = set.SelectMany(r => r.Months).ToList();
var served = months.Where(m => !double.IsNaN(m.SellingTransformerMargin)).ToList();
sb.AppendLine($" trasformatori: margine medio {Dec(months.Average(m => m.TransformerMargin), "0.000")} (quota in perdita {Pct(months.Average(m => m.TransformerNegativeShare))}); che vendono {Dec(served.Count == 0 ? double.NaN : served.Average(m => m.SellingTransformerMargin), "0.000")}, mesi positivi {Pct(served.Count == 0 ? double.NaN : (double)served.Count(m => m.SellingTransformerMargin > 0) / served.Count)}");
@@ -313,7 +417,7 @@ public static class BalanceReport
{
var sb = new StringBuilder("seme;difficoltà;bot;anni;");
sb.Append(string.Join(';', Enumerable.Range(2, data.Tiers.Tiers.Count - 1).Select(t => $"anno livello {t}")));
sb.AppendLine(";bot fallito;fine partita;IA;IA fallite;IA attive al 3° anno;livello massimo IA;anno livello 2 IA;ampliamenti industrie;mesi-industria serviti;livello massimo industrie;popolazione iniziale;popolazione finale;comandi bot;rifiutati bot;comandi IA;rifiutati IA;invarianti;hash finale");
sb.AppendLine(";bot fallito;fine partita;IA;IA fallite;IA attive al 3° anno;livello massimo IA;anno livello 2 IA;ampliamenti industrie;mesi-industria serviti;livello massimo industrie;popolazione iniziale;popolazione finale;comandi bot;rifiutati bot;comandi IA;rifiutati IA;IA al 3° anno;mesi bloccati ricambi bot;mesi bloccati ricambi IA;affari bot;affari IA;invarianti;hash finale");
foreach (var r in runs)
{
sb.Append(string.Join(';', r.Seed.ToString(It), r.Difficulty, r.Bot, r.Years.ToString(It)));
@@ -321,7 +425,8 @@ public static class BalanceReport
sb.Append(string.Join(';', r.BotTierYear.Skip(1).Select(y => y.ToString(It))));
sb.AppendLine(";" + string.Join(';', r.BotBankrupt ? "sì" : "no", r.GameOver ? "sì" : "no", r.AiCompanies.ToString(It), r.AiBankrupt.ToString(It),
r.AiActiveByYear3.ToString(It), r.BestAiTier.ToString(It), r.AiTier2Year.ToString(It), r.LevelUps.ToString(It), r.ServedIndustryMonths.ToString(It), r.MaxIndustryLevel.ToString(It), r.PopulationStart.ToString(It), r.PopulationEnd.ToString(It),
r.BotCommands.ToString(It), r.BotRejected.ToString(It), r.AiCommands.ToString(It), r.AiRejected.ToString(It), r.InvariantsOk ? "ok" : "ROTTI", r.FinalHash.ToString("x16", It)));
r.BotCommands.ToString(It), r.BotRejected.ToString(It), r.AiCommands.ToString(It), r.AiRejected.ToString(It),
r.AiAtYear3.ToString(It), r.BotPartsBlockedMonths.ToString(It), r.AiPartsBlockedMonths.ToString(It), r.BotTrades.ToString(It), r.AiTrades.ToString(It), r.InvariantsOk ? "ok" : "ROTTI", r.FinalHash.ToString("x16", It)));
}
return sb.ToString();
}