using System.Text.Json.Nodes; using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Core.Data; using RailEnterprise.Core.Economy; using RailEnterprise.Core.Persistence; using RailEnterprise.Core.Rail; using RailEnterprise.Core.Simulation; using RailEnterprise.Tests.Harness; using RailEnterprise.Tests.Rail; namespace RailEnterprise.Tests.Economy; /// Mercato globale (F6, ADR 0015): storico a 24 mesi, migrazione della finestra, previsione, analisi. public static class MarketOutlookTests { private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index; [Test(Description = "Una finestra allungata conserva i valori nello stesso ordine e continua a scorrere")] public static void ExtendedWindowKeepsValuesInOrder() { var window = new RollingWindow(5); for (int v = 1; v <= 8; v++) window.Add(v); var longer = window.Extended(10); Assert.Equal(10, longer.Length); Assert.Equal(5, longer.Count); for (int k = 0; k < 5; k++) Assert.Equal(8.0 - k, longer.Ago(k)); Assert.Equal(30.0, longer.Sum); longer.Add(9); Assert.Equal(6, longer.Count); Assert.Equal(9.0, longer.Ago(0)); Assert.Equal(4.0, longer.Ago(5)); Assert.Equal(39.0, longer.Sum); Assert.Throws(() => window.Extended(4)); Assert.Approx(8.5, longer.AverageOfLast(2), 1e-12); } [Test(Slow = true, Description = "Un salvataggio con lo storico dei prezzi di 360 giorni si carica con la finestra di 720 e gli stessi prezzi")] public static void OldSavesWithAShortPriceHistoryAreExtended() { var files = MemoryDataSource.Snapshot(TestData.Source); var balance = JsonNode.Parse(files["balance.json"])!; balance["market"]!["historyDays"] = 360; balance["market"]!["outlook"]!["historyMonths"] = 12; files["balance.json"] = balance.ToJsonString(); var oldData = GameData.Load(new MemoryDataSource(files)); Assert.Equal(360, oldData.Balance.Market.HistoryDays); var settings = new NewGameSettings { Seed = 1501, SizeKm = 64, DifficultyId = "imprenditore" }; var old = WorldFactory.Create(oldData, settings); old.RunDays(400); byte[] save = SaveFile.Save(old, "test"); var loaded = SaveFile.Load(TestData.Data, save); int expected = TestData.Data.Balance.Market.HistoryDays; Assert.Equal(720, expected); for (int g = 0; g < TestData.Data.GoodCount; g++) { var before = old.Market.PriceHistory[g]; var after = loaded.Market.PriceHistory[g]; Assert.Equal(expected, after.Length); Assert.Equal(before.Count, after.Count); for (int k = 0; k < before.Count; k++) Assert.Equal(before.Ago(k), after.Ago(k), $"bene {g}, {k} giorni fa"); } // la partita continua e lo storico cresce oltre i 360 giorni loaded.RunDays(30); Assert.Equal(390, loaded.Market.PriceHistory[0].Count); Assert.True(MarketOutlook.MonthlyHistory(loaded, 0, 24).Count >= 13, "storico mensile oltre l'anno"); } [Test(Slow = true, Description = "Storico mensile: un campione per mese di calendario (l'ultimo giorno) più il giorno corrente, 24 mesi")] public static void MonthlyHistoryTakesOneSamplePerMonth() { var w = TestWorlds.NoAi(1502); w.RunDays(800); w.RunTicks(5); // a metà giornata: il giorno corrente è già nello storico int dpm = w.Calendar.DaysPerMonth; int coal = GoodIndex(w, "coal"); var history = MarketOutlook.MonthlyHistory(w, coal, 24); Assert.Equal(24, history.Count); long last = MarketOutlook.LastRecordedDay(w); Assert.Equal(w.Clock.Day, last); Assert.Equal(last, history[^1].Day); Assert.Equal(w.Market.GlobalPrice[coal], history[^1].Price); for (int i = 0; i < history.Count - 1; i++) { Assert.Equal((long)dpm - 1, history[i].Day % dpm, $"campione {i} all'ultimo giorno del mese"); if (i > 0) Assert.Equal((long)dpm, history[i].Day - history[i - 1].Day); Assert.Equal(w.Market.PriceHistory[coal].Ago((int)(last - history[i].Day)), history[i].Price); } Assert.True(history[^2].Day < last && last - history[^2].Day <= dpm, "penultimo campione nel mese precedente"); // all'inizio di un giorno (prima del sistema del mercato) l'ultimo campione è quello di ieri var fresh = TestWorlds.NoAi(1503); fresh.RunDays(45); Assert.Equal(fresh.Clock.Day - 1, MarketOutlook.LastRecordedDay(fresh)); var short_ = MarketOutlook.MonthlyHistory(fresh, coal, 24); Assert.Equal(2, short_.Count); Assert.Equal(29L, short_[0].Day); Assert.Equal(44L, short_[1].Day); } [Test(Slow = true, Description = "La previsione segue la componente mondiale, è deterministica, resta entro i limiti e la banda si allarga")] public static void ForecastIsDeterministicAndWithinLimits() { var a = TestWorlds.NoAi(1504); var b = TestWorlds.NoAi(1504); a.RunDays(200); b.RunDays(200); var m = a.Data.Balance.Market; for (int g = 0; g < a.Data.GoodCount; g++) { var fa = MarketOutlook.Forecast(a, g); var fb = MarketOutlook.Forecast(b, g); Assert.SequenceEqual(fa, fb, $"previsione del bene {g}"); Assert.Equal(m.Outlook.ForecastMonths, fa.Count); double pb = a.Data.Goods[g].BasePrice; for (int i = 0; i < fa.Count; i++) { var p = fa[i]; Assert.Equal(i + 1, p.Months); Assert.InRange(p.Price, m.MinPriceFactor * pb, m.MaxPriceFactor * pb); Assert.True(p.Low <= p.Price && p.Price <= p.High, $"banda del bene {g} al mese {p.Months}"); Assert.InRange(p.Low, m.MinPriceFactor * pb, m.MaxPriceFactor * pb); Assert.InRange(p.High, m.MinPriceFactor * pb, m.MaxPriceFactor * pb); } } // uno shock positivo forte decade: il prezzo previsto scende mese dopo mese e la banda si allarga int coal = GoodIndex(a, "coal"); a.Market.GlobalPrice[coal] = a.Data.Goods[coal].BasePrice; for (int g = 0; g < a.Data.GoodCount; g++) a.Market.Shock[g] = 0; a.Market.Shock[coal] = 0.25; var forecast = MarketOutlook.Forecast(a, coal); Assert.True(forecast[^1].Price < a.Market.GlobalPrice[coal], $"previsione {forecast[^1].Price:0} sotto il prezzo attuale"); for (int i = 1; i < forecast.Count; i++) { Assert.True(forecast[i].Price < forecast[i - 1].Price, $"mese {i + 1} sotto il mese {i}"); Assert.True(forecast[i].High / forecast[i].Price > forecast[i - 1].High / forecast[i - 1].Price, "la banda si allarga"); } // lo stesso shock è l'evento in corso, con i mesi prima che scenda sotto la soglia var e = MarketOutlook.StrongestEvent(a); Assert.Equal(coal, e.Good); Assert.Equal(0.25, e.Shock); double months = m.World.ShockDecayDays * Math.Log(0.25 / m.Outlook.EventThreshold) / a.Calendar.DaysPerMonth; Assert.Approx(months, e.Months, 1e-6); a.Market.Shock[coal] = -m.Outlook.EventThreshold / 2; Assert.Equal(-1, MarketOutlook.StrongestEvent(a).Good); } [Test(Description = "Analisi del mercato su Valdoria: beni, vendite ordinate con la linea che collega, hub, indice, commercio; nessun effetto sul mondo")] public static void OutlookOnValdoria() { var f = RailFixture.Valdoria(); var w = f.W; var (mine, mill, depot) = f.BuildFreightNetwork(); int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4)); int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) })); var steel = w.Industries.First(i => i.Def.Id == "steel_mill"); // la linea senza treni non collega Assert.False(MarketOutlook.IndustryLine(w, f.Me, MarketOutlook.StationLines(w, f.Me), steel.Id).IsValid, "linea senza treni"); f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line))); w.RunDays(40); var lines = MarketOutlook.StationLines(w, f.Me); Assert.Equal(line, MarketOutlook.IndustryLine(w, f.Me, lines, steel.Id).Value); Assert.False(MarketOutlook.IndustryLine(w, CompanyId.None, MarketOutlook.StationLines(w, CompanyId.None), steel.Id).IsValid); ulong hash = StateHasher.Compute(w); var report = MarketOutlook.Build(w, f.Me); Assert.Equal(hash, StateHasher.Compute(w), "l'analisi non cambia il mondo"); Assert.Equal(w.Data.GoodCount, report.Goods.Count); Assert.Equal(w.Hubs.Count, report.Hubs.Count); int ore = GoodIndex(w, "iron_ore"); var good = report.Goods[ore]; Assert.True(good.Available); Assert.Equal(w.Market.GlobalPrice[ore], good.Price); Assert.True(good.History.Count >= 2, "storico di almeno due mesi"); Assert.True(good.SellPlaces.Count is > 0 and <= 3, $"destinazioni: {good.SellPlaces.Count}"); for (int i = 1; i < good.SellPlaces.Count; i++) Assert.True(good.SellPlaces[i - 1].Price >= good.SellPlaces[i].Price, "ordinate per prezzo"); // ogni destinazione industriale consuma il bene, con il prezzo locale dell'ADR 0004 var lp = w.Data.Balance.LocalPrice; foreach (var p in good.SellPlaces) { if (p.Kind == SellPlaceKind.Hub) { Assert.Equal(w.Hubs[p.Target].BuyPrice(good.Price), p.Price); continue; } var ind = w.Industries[p.Target]; int input = ind.InputIndexOf(ore); Assert.True(input >= 0 && !ind.Closed && ind.Level > 0, $"{ind.Name} consuma minerale"); Assert.InRange(p.Price, good.Price * (1 - lp.MaxDeviation) - 1e-9, good.Price * (1 + lp.MaxDeviation) + 1e-9); Assert.Equal(MarketOutlook.IndustryLine(w, f.Me, lines, ind.Id), p.Line); } // tutte le industrie che consumano minerale e gli hub sono candidati: il migliore è davvero il primo double best = w.Hubs.Select(h => h.BuyPrice(good.Price)).Concat(w.Industries .Where(i => !i.Closed && i.Level > 0 && i.InputIndexOf(ore) >= 0) .Select(i => Market.LocalPrice(good.Price, Core.Simulation.Systems.IndustryMath.InputCapacity(i, i.InputIndexOf(ore), w.Calendar.DaysPerMonth), i.InputStock[i.InputIndexOf(ore)], lp))) .Max(); Assert.Equal(best, good.SellPlaces[0].Price); // scorte e domanda Assert.Equal(MarketOutlook.StockUnits(w, ore), good.StockUnits); if (good.DemandMonth > 0) Assert.Approx(good.StockUnits / good.DemandMonth, good.StockMonths, 1e-9); Assert.True(good.WorldDemandMonth > 0 && good.WorldSupplyMonth > 0, "quota mondiale"); // indice materie prime: media di Pg/Pb × 100 sui beni disponibili var available = Enumerable.Range(0, w.Data.GoodCount).Where(g => w.Data.Goods[g].Era <= w.Clock.Year).ToList(); Assert.Approx(available.Average(g => w.Market.GlobalPrice[g] / w.Data.Goods[g].BasePrice) * 100, report.Index, 1e-9); foreach (var g in report.Goods.Where(g => !g.Available)) Assert.Equal(0, g.SellPlaces.Count); // hub: nessuna stazione della compagnia al porto Assert.True(report.Hubs.All(h => !h.Line.IsValid), "hub non collegati"); Assert.Equal(w.Hubs[0].MonthlyCapacity, report.Hubs[0].MonthlyCapacity); // compravendita in proprio: dal livello 2 di tiers.json var trading = report.Trading; var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading); Assert.Equal(tier.Level, trading.Level); Assert.False(trading.Unlocked); Assert.Equal(tier.Requirements.CreditRating, trading.RatingRequired); Assert.InRange(trading.Fraction, 0, 1); double worth = Math.Clamp((double)w.Player.NetWorth.Cents / tier.Requirements.NetWorth, 0, 1); double towns = Math.Clamp((double)trading.TownsConnected / tier.Requirements.ConnectedTownsOver.Count, 0, 1); Assert.Approx(Math.Min(worth, towns), trading.Fraction, 1e-12); w.Player.Tier = tier.Level; Assert.True(MarketOutlook.Trading(w, f.Me).Unlocked); Assert.Equal(1.0, MarketOutlook.Trading(w, f.Me).Fraction); } }