using System.Globalization; using System.Text.Json; using Anubis.Core; using Anubis.Data; using Anubis.Learning; namespace Anubis.Server; /// What the model is doing, for the badge and the sentences at the top. internal static class LearningStates { /// No model yet: the night after the first start prepares it. public const string None = "none"; public const string Observation = "observation"; public const string Active = "active"; /// Set aside on its own by the nightly check. public const string Aside = "aside"; /// Set aside by the user. public const string Manual = "manual"; } /// A band of estimates: percentages as they are read, the point at the mean estimate. public sealed record LearningBand(int From, int To, int Cases, decimal Estimated, decimal Observed) { public bool Solid => Cases >= Judge.BandMin; } internal sealed record LearningWeight(string Name, int Share, bool Rest); /// A column of the comparison between the model in charge and the one on trial. internal sealed record LearningVersion(int Version, string Trained, int Examples, int? Precision, decimal? Error, decimal? Gain, decimal? GainWithout); /// What was tried when a model was trained, the chosen one included. internal sealed record LearningAttempt(string Learner, int? Precision, decimal Error, decimal Gain, bool Chosen); public sealed record LearningWeek(DateOnly Monday, int Precision); /// A line of "Sorveglianza": is ok, warn or wait. internal sealed record LearningCheck(string State, string Text); internal sealed record LearningStory(string When, string Text); /// The model box of the Panoramica: the same state in few words. internal sealed record LearningSummary(string State, int Signals, int Needed, int? Precision, string Trained, string NextLabel, string NextCheck) { public string Sentence => State switch { LearningStates.None => "Il modello non è ancora pronto: comincia a osservare dopo la prima verifica.", LearningStates.Active => "Il modello rimpicciolisce le operazioni che giudica deboli.", LearningStates.Aside => "Il modello è messo da parte per un'anomalia: le strategie proseguono senza di lui.", LearningStates.Manual => "Hai messo da parte il modello: le strategie proseguono senza di lui.", _ => "Il modello osserva e impara, ma non decide ancora.", }; } /// /// The Apprendimento screen (SPEC 13.6, mockup 06): what the model is doing, whether its probabilities can be trusted, /// what it looks at, the model in charge against the challenger, the watch, the discoveries and the history. In demo mode /// the numbers of appendix F.7 come from the aggregates. /// internal sealed record LearningView { /// The clues named one by one; the others are "Tutto il resto". public const int NamedWeights = 9; public const int StoryRows = 12; private const string Fear = "Paura o avidità"; /// The pace is measured on the last four weeks, and needs at least one. private const int PaceDays = 28; private static readonly CultureInfo _it = CultureInfo.GetCultureInfo("it-IT"); private static readonly string[] _numbers = ["zero", "una", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici"]; public required LearningSummary Summary { get; init; } public required string Title { get; init; } public required string Text { get; init; } public string? Pace { get; init; } /// With 300 signals done, what still stops it from counting. public IReadOnlyList Missing { get; init; } = []; /// "domenica 4 ottobre, versione 3". public required string LastTraining { get; init; } public IReadOnlyList Bands { get; init; } = []; /// The sentence under the calibration chart. public string BandsText { get; init; } = ""; /// True when the bands are those of the verification on the history, because the live ones are still too few. public bool BandsFromHistory { get; init; } public IReadOnlyList Weights { get; init; } = []; public string WeightsText { get; init; } = ""; public LearningVersion? Champion { get; init; } public LearningVersion? Challenger { get; init; } /// The signals both estimated, with their outcome, and how many the next decision needs. public int Pairs { get; init; } public int PairsNeeded { get; init; } /// No strategy with capital had examples when the model in charge was trained. public bool GainOnReference { get; init; } public string TrialTitle { get; init; } = ""; public string TrialText { get; init; } = ""; /// How the model in charge was chosen, with everything that was tried. public string? Choice { get; init; } public IReadOnlyList Attempts { get; init; } = []; /// Set when the last promotion can be taken back: the version that would return. public int? UndoTo { get; init; } public bool Anomaly { get; init; } public bool Checked { get; init; } public IReadOnlyList Checks { get; init; } = []; public IReadOnlyList Weeks { get; init; } = []; public IReadOnlyList Found { get; init; } = []; public IReadOnlyList News { get; init; } = []; public IReadOnlyList Story { get; init; } = []; // ---- Panoramica --------------------------------------------------------------------------------------------- /// The few numbers of the Panoramica. public static async Task SummaryAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(shell); using var aggregates = shell.Aggregates(); if (aggregates is not null) { return DemoSummary(aggregates.RootElement.GetProperty("apprendimento")); } var services = host.Services!; var desk = new LearningDesk(services.Db, host.Clock, services.Settings); var models = await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false); var evaluated = (int)await desk.Models.EvaluatedAsync(cancellationToken).ConfigureAwait(false); var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, host.Clock.UtcNow); } private static LearningSummary Summarise(IReadOnlyList models, int evaluated, CycleState state, bool aside, DateTimeOffset now) { var champion = models.LastOrDefault(m => m.Status == ModelStatuses.Champion); var challenger = models.LastOrDefault(m => m.Status == ModelStatuses.Challenger); var last = models.LastOrDefault(m => m.Version is not null); var status = champion is null ? LearningStates.None : aside ? LearningStates.Manual : state.Aside is not null ? LearningStates.Aside : state.ActivatedAt is not null ? LearningStates.Active : LearningStates.Observation; return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : LongDay(DayOf(last.TrainedAt), now), champion is null ? "Prima verifica" : challenger is null ? "Prossimo addestramento" : "Prossima verifica dello sfidante", NextText(now, champion is not null)); } private static LearningSummary DemoSummary(JsonElement demo) => new(demo.GetProperty("stato").GetString()!, demo.GetProperty("segnali").GetInt32(), demo.GetProperty("necessari").GetInt32(), demo.GetProperty("precisione_pct").GetInt32(), demo.GetProperty("ultimo_addestramento").GetString()!, "Prossima verifica dello sfidante", demo.GetProperty("prossima_verifica").GetString()!); // ---- Page --------------------------------------------------------------------------------------------------- public static async Task LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(shell); using var aggregates = shell.Aggregates(); if (aggregates is not null) { return Demo(aggregates.RootElement.GetProperty("apprendimento")); } var services = host.Services!; var clock = host.Clock; var desk = new LearningDesk(services.Db, clock, services.Settings); var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false); var capitals = await LearningCycle.CapitalsAsync(services.Db, clock, cancellationToken).ConfigureAwait(false); var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); var found = await new DiscoveryDesk(services.Db, clock, desk.Store).LatestAsync(cancellationToken).ConfigureAwait(false); var events = await desk.Models.EventsAsync(cancellationToken).ConfigureAwait(false); return Of(snapshot, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), capitals, aside, found, events, clock.UtcNow); } /// The page from what was read, without touching the database. public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary baseRates, IReadOnlyDictionary capitals, bool aside, DiscoverySet discoveries, IReadOnlyList events, DateTimeOffset now) { ArgumentNullException.ThrowIfNull(snapshot); ArgumentNullException.ThrowIfNull(discoveries); ArgumentNullException.ThrowIfNull(events); var (champion, challenger, state) = (snapshot.Champion, snapshot.Challenger, snapshot.State); var inCharge = snapshot.InCharge; var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, now); var activation = ActivationCheck.Of(inCharge, baseRates, capitals); var last = snapshot.Models.LastOrDefault(m => m.Version is not null); var (title, text) = Words(summary, state, now); // What really happened: the weights by maturation serve the decisions, not the sentence "è andata bene". var live = Judge.Bands(inCharge); var history = !live.Any(b => b.Cases >= Judge.BandMin); var verified = Verified(champion); var bands = (history ? verified?.Bands ?? [] : live).Select(Band).ToList(); var view = new LearningView { Summary = summary, Title = title, Text = text, Pace = state.ActivatedAt is null && champion is not null ? PaceText(inCharge, now) : null, Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [], LastTraining = last is null ? "mai" : $"{LongDay(DayOf(last.TrainedAt), now)}, versione {last.Version}", Bands = bands, BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands, history ? null : activation.CalibrationError), BandsFromHistory = history && bands.Count > 0, Champion = Column(champion, now), Challenger = Column(challenger, now), Choice = champion?.Report.Reason is { Length: > 0 } reason ? reason : null, Attempts = champion is null ? [] : [ .. champion.Report.Attempts.Select(a => new LearningAttempt(LearnerNames.Label(a.Learner), Points(a.Combined.Precision), Round(a.Combined.Brier, 3), Round(a.Combined.GainWith, 2), a.Chosen)), ], UndoTo = champion?.ReplacedId is { } replaced ? snapshot.Models.FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version : null, Anomaly = state.Aside is not null, Checked = state.Health is not null, GainOnReference = champion?.Report.AllStrategiesCounted == true, Found = [.. discoveries.Found, .. discoveries.Improvements], News = discoveries.News, Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))], }; view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? []); if (champion is not null) { view = view with { Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Health.Shown(w.Precision)))], Checks = state.Health is not { } health ? [] : health.Version is { } seen && seen != champion.Version ? [new("wait", "Il modello in carica è cambiato: il primo controllo è alle 03:00. " + AlarmText(events, now))] : ChecksOf(health, snapshot, champion, verified, events, now), }; } return champion is not null && challenger is not null ? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), challenger.ThresholdDone, summary.NextCheck, champion.Version, challenger.Version) : view with { TrialTitle = champion is null ? "Nessun modello ancora." : "Nessuno sfidante in prova.", TrialText = champion is null ? "" : $"Il prossimo si addestra {At(summary.NextCheck)}, se nel frattempo ci sono casi nuovi.", }; } private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now) { const string How = "Per ogni segnale delle strategie il modello stima quanto è probabile che vada bene, poi confronta la stima con quello che succede davvero."; const string Limits = "Non potrà mai ingrandirle, né aprirne di sue."; const string Alone = "Le strategie proseguono senza di lui."; return summary.State switch { LearningStates.None => ("Non ha ancora cominciato.", $"{How} La prima verifica, {At(summary.NextCheck)}, prepara il primo modello dai dati storici; da lì parte in osservazione."), LearningStates.Active => ("Rimpicciolisce le operazioni che giudica deboli.", $"{How} Dal {DayText(DayOf(state.ActivatedAt!.Value), now)} le sue stime contano: un segnale che giudica debole compra meno, o niente. Non può mai ingrandire un'operazione, né aprirne di sue."), LearningStates.Aside => ("Per ora è messo da parte.", $"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} Torna da solo quando l'anomalia rientra{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."), LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione nuova; quelle già rimpicciolite restano così fino alla chiusura. Si riattiva da Impostazioni."), _ when summary.Signals >= summary.Needed => ("Ha visto abbastanza casi, ma non decide ancora.", $"{How} Potrà rimpicciolire le operazioni che giudica deboli solo quando le prove lo confermano. {Limits}"), _ => ("Sta imparando, ma non decide ancora.", $"{How} Quando avrà visto abbastanza casi potrà rimpicciolire le operazioni che giudica deboli. {Limits}"), }; } /// How long the missing signals take at the pace of the last four weeks. public static string? PaceText(IReadOnlyList inCharge, DateTimeOffset now) { ArgumentNullException.ThrowIfNull(inCharge); var missing = ActivationCheck.Needed - inCharge.Count; if (missing <= 0) { return null; } var today = DayOf(now); if (inCharge.Count == 0 || (today.DayNumber - inCharge.Min(e => e.Case.Label!.ClosedDay!.Value).DayNumber) is not (>= 7 and var seen)) { return "È presto per dire quanto manca."; } var days = Math.Min(PaceDays, seen); var recent = inCharge.Count(e => e.Case.Label!.ClosedDay!.Value > today.AddDays(-days)); return recent == 0 ? "Nelle ultime settimane nessun segnale si è concluso." : PaceWords(missing * days / 7.0 / recent); } /// "Al ritmo attuale, tra tre e quattro settimane." from the weeks that are missing. public static string PaceWords(double weeks) { if (weeks <= 1) { return "Al ritmo attuale, meno di una settimana."; } if (weeks > 52) { return "Al ritmo attuale, più di un anno."; } if (weeks > 12) { return string.Create(_it, $"Al ritmo attuale, circa {Math.Round(weeks / 4.345):0} mesi."); } var (low, high) = ((int)Math.Floor(weeks), (int)Math.Ceiling(weeks)); return low == high ? $"Al ritmo attuale, circa {_numbers[low]} settimane." : $"Al ritmo attuale, tra {_numbers[low]} e {_numbers[high]} settimane."; } private static List Missings(ActivationCheck check) { var missing = new List(); if (!check.Calibrated) { missing.Add(check.CalibrationError is { } error ? string.Create(_it, $"Le probabilità non sono ancora ben tarate: sbagliano in media di {error * 100:0.0} punti, il massimo è {ActivationCheck.MaxCalibrationError * 100:0}.") : $"Nessuna fascia di probabilità ha ancora {Judge.BandMin} casi."); } if (check.Funded < ActivationCheck.FundedNeeded) { missing.Add($"Servono almeno {ActivationCheck.FundedNeeded} segnali di strategie con un capitale, anche in simulazione: per ora {(check.Funded == 1 ? "è uno" : $"sono {Format.Number(check.Funded)}")}."); } else if (!check.Improves) { missing.Add("Non è ancora provato che, filtrando lui, si guadagni di più per operazione proposta: la differenza può essere caso."); } return missing; } // ---- Calibration and clues ---------------------------------------------------------------------------------- private static LearningBand Band(CalibrationBand b) => new((int)Math.Round(b.From * 100), (int)Math.Round(b.To * 100), b.Cases, Round(b.Estimated * 100, 1), Round(b.Observed * 100, 1)); /// /// The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not /// count. is the error of the criterion to start counting (11.5), when it is the judge. /// public static string BandsWords(IReadOnlyList bands, double? measured = null) { ArgumentNullException.ThrowIfNull(bands); var solid = bands.Where(b => b.Solid).ToList(); if (solid.Count == 0) { return $"Nessuna fascia ha ancora {Judge.BandMin} casi: troppo pochi per contarci."; } var error = measured is { } known ? Round(known * 100, 1) : solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases); var best = solid[^1]; var text = $"Quando stima tra il {best.From} e il {best.To}%, è andata bene il {Format.Number(best.Observed)}% delle volte: " + ((measured is { } exact ? exact < ActivationCheck.MaxCalibrationError : error < (decimal)ActivationCheck.MaxCalibrationError * 100) ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti."); var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList(); var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList(); var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases); static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : Format.Number(cases) + " casi, troppo pochi")} per contarci."; return text + (above.Count > 0 ? Few($"Sopra il {best.To}%", above.Sum(b => b.Cases)) : "") + (below.Count > 0 ? Few($"Sotto il {solid[0].From}%", below.Sum(b => b.Cases)) : "") + (between > 0 ? Few($"Nelle fasce di mezzo con meno di {Judge.BandMin} casi", between) : ""); } private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights) { var rest = weights.Skip(NamedWeights).Sum(w => w.Share); var rows = weights.Take(NamedWeights).Where(w => w.Share > 0).Select(w => new LearningWeight(w.Name, w.Share, false)).ToList(); if (rest > 0) { rows.Add(new LearningWeight("Tutto il resto", rest, true)); } var news = weights.Where(w => Clues.NewsGroups.Contains(w.Name)).Sum(w => w.Share); var fear = weights.Where(w => w.Name == Fear).Sum(w => w.Share); var text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime." : news + fear == 0 && weights.Any(w => Clues.NewsGroups.Contains(w.Name) || w.Name == Fear) ? "Notizie, paura e avidità le studia già, ma per ora non pesano." : news + fear == 0 ? $"Notizie, paura e avidità per ora non pesano: le studia solo quando almeno {Clues.MinLive} segnali dal vivo le contengono." : news == 0 ? $"Le notizie per ora non pesano; paura e avidità pesano {fear} su 100." : $"Le notizie contano, {(news + fear < 50 ? "ma meno dei prezzi" : "più dei prezzi")}: insieme a paura e avidità pesano {news + fear} su 100."; return view with { Weights = rows, WeightsText = text }; } // ---- Versions ----------------------------------------------------------------------------------------------- /// The scores of a model on the cases it had not studied, from the verification of its training. private static Scores? Verified(ModelRow? model) => model?.Report.Attempts.FirstOrDefault(a => a.Chosen)?.Combined; private static LearningVersion? Column(ModelRow? model, DateTimeOffset now) => model?.Version is not { } version ? null : Verified(model) is { Cases: > 0 } s ? new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, Points(s.Precision), Round(s.Brier, 3), Round(s.GainWith, 2), Round(s.GainWithout, 2)) : new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, null, null, null, null); /// The last threshold already judged: at the next one, passed or not, there is a decision (SPEC 11.4). private static LearningView WithTrial(LearningView view, TrialCheck check, int done, string nextCheck, int? champion, int? challenger) { var next = TrialCheck.Thresholds.FirstOrDefault(t => t > done, TrialCheck.Thresholds[^1]); var first = TrialCheck.Thresholds[0]; var text = check.Pairs switch { 0 => $"Non ha ancora casi di confronto: ne servono {first}. Fino ad allora gira in ombra accanto alla {champion}.", _ when check.Pairs < first => $"{(check.Mean > 0 ? "Sembra un po' meglio, ma ha" : "Per ora non sembra meglio, e ha")} solo {(check.Pairs == 1 ? "un caso" : check.Pairs + " casi")} di confronto su {first}: " + $"troppo pochi per escludere la fortuna. Fino ad allora gira in ombra accanto alla {champion}.", _ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. {(check.Pairs >= next ? $"Si decide {At(nextCheck)}" : $"Si decide di nuovo a {next} casi")}: " + $"prende il posto della {champion} se il vantaggio non si spiega con il caso, e dopo {TrialCheck.Thresholds[^1]} casi senza vantaggio è scartata.", }; return view with { Pairs = check.Pairs, PairsNeeded = next, TrialTitle = $"La versione {challenger} è ancora in prova.", TrialText = text }; } // ---- Watch -------------------------------------------------------------------------------------------------- private static List ChecksOf(HealthCheck health, LearningSnapshot snapshot, ModelRow champion, Scores? verified, IReadOnlyList events, DateTimeOffset now) { var known = champion.Model is { } model ? snapshot.Examples.Count(e => e.Source == CaseSources.Live && model.Strategies.Contains(e.Strategy)) : 0; var checks = new List { health.DriftingClues.Count > 0 ? new("warn", "Il mercato è diverso da quello su cui ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(_it)) : known < Health.MinCases ? new("wait", $"Se il mercato somiglia a quello su cui ha studiato si vede da {Health.MinCases} segnali: per ora sono {known}") : new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"), PrecisionCheck(health.Precision is { } p ? Health.Shown(p) : null, health.Cases, Points(verified?.Precision)), }; if (health.ErrorDrift) { checks.Add(new("warn", "I suoi errori sono aumentati negli ultimi casi")); } checks.Add(new("wait", $"Ultimo controllo {Moment(health.At, now)}. {AlarmText(events, now)}")); return checks; } private static LearningCheck PrecisionCheck(int? precision, int cases, int? expected) { if (precision is not { } seen || cases < Health.MinCases) { return new("wait", cases == 0 ? $"Nessun segnale concluso: la precisione si giudica da {Health.MinCases} casi" : $"Segnali conclusi: {cases}. La precisione si giudica da {Health.MinCases} casi"); } var against = expected is not { } e ? "" : Math.Abs(seen - e) <= 5 ? $", in linea con il {e}% atteso" : seen < e ? $", sotto il {e}% atteso" : $", sopra il {e}% atteso"; return new(seen < Health.Alarm * 100 ? "warn" : "ok", $"Precisione sugli ultimi {cases} casi: {seen}%{against}"); } private static string AlarmText(IReadOnlyList events, DateTimeOffset now) { if (events.LastOrDefault(e => e.Kind == ModelEvents.SetAside) is not { } alarm) { return "Nessun allarme finora"; } var back = events.FirstOrDefault(e => e.Kind == ModelEvents.Back && e.At >= alarm.At); var days = back is null ? 0 : Math.Max(1, (int)Math.Round((back.At - alarm.At).TotalDays)); return $"Ultimo allarme il {DayText(DayOf(alarm.At), now)}, {(back is null ? "ancora in corso" : days == 1 ? "rientrato in un giorno" : $"rientrato in {days} giorni")}"; } // ---- Demo --------------------------------------------------------------------------------------------------- private static LearningView Demo(JsonElement demo) { static decimal Amount(JsonElement e, string name) => decimal.Parse(e.GetProperty(name).GetString()!, CultureInfo.InvariantCulture); LearningVersion Version(string name) { var v = demo.GetProperty(name); return new LearningVersion(v.GetProperty("versione").GetInt32(), v.GetProperty("addestrato").GetString()!, v.GetProperty("casi").GetInt32(), v.GetProperty("precisione_pct").GetInt32(), Amount(v, "errore"), Amount(v, "guadagno"), Amount(demo, "guadagno_senza_filtro")); } var summary = DemoSummary(demo); var champion = Version("in_carica"); var challenger = Version("sfidante"); var watch = demo.GetProperty("sorveglianza"); var (title, text) = Words(summary, new CycleState(), DateTimeOffset.MinValue); var view = new LearningView { Summary = summary, Title = title, Text = text, Pace = PaceWords(demo.GetProperty("settimane_mancanti").GetDouble()), LastTraining = $"{summary.Trained}, versione {challenger.Version}", Bands = [ .. demo.GetProperty("fasce").EnumerateArray().Select(b => (From: b.GetProperty("da").GetInt32(), To: b.GetProperty("a").GetInt32(), Band: b)) .Select(b => new LearningBand(b.From, b.To, b.Band.GetProperty("casi").GetInt32(), (b.From + b.To) / 2m, b.Band.GetProperty("pct").GetInt32())), ], BandsText = demo.GetProperty("fasce_testo").GetString()!, Champion = champion, Challenger = challenger, Checked = true, Checks = [ new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"), PrecisionCheck(watch.GetProperty("precisione_pct").GetInt32(), watch.GetProperty("casi").GetInt32(), champion.Precision), new("wait", watch.GetProperty("controllo").GetString()!), ], Weeks = [.. watch.GetProperty("settimane").EnumerateArray().Select(w => new LearningWeek(DateOnly.Parse(w.GetProperty("lunedi").GetString()!, CultureInfo.InvariantCulture), w.GetProperty("pct").GetInt32()))], Found = [.. demo.GetProperty("scoperte").EnumerateArray().Select(d => new Discovery(d.GetProperty("titolo").GetString()!, d.GetProperty("dettaglio").GetString()!, d.GetProperty("casi").GetInt32()))], Story = [.. demo.GetProperty("storia").EnumerateArray().Select(s => new LearningStory(s.GetProperty("quando").GetString()!, s.GetProperty("testo").GetString()!))], }; var named = demo.GetProperty("indizi").EnumerateArray().Select(w => (w.GetProperty("nome").GetString()!, w.GetProperty("peso").GetInt32())).ToList(); return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version); } // ---- Words -------------------------------------------------------------------------------------------------- /// The night that comes: 03:00 in Rome of the next Sunday, or of the next day before the first model. private static string NextText(DateTimeOffset now, bool sunday) { var local = TimeZoneInfo.ConvertTime(now, Zones.Rome); var today = DateOnly.FromDateTime(local.DateTime); var day = local.Hour < 3 ? today : today.AddDays(1); if (sunday) { day = day.AddDays((7 - (int)day.DayOfWeek) % 7); } return Format.Day(day) + ", 03:00"; } /// "domenica 11 ottobre alle 03:00" from the short form. private static string At(string next) => next.Replace(",", " alle", StringComparison.Ordinal); /// "oggi alle 03:00", "il 4 ottobre alle 03:00". private static string Moment(DateTimeOffset at, DateTimeOffset now) { var time = TimeZoneInfo.ConvertTime(at, Zones.Rome).ToString("HH:mm", CultureInfo.InvariantCulture); return (DayOf(now).DayNumber - DayOf(at).DayNumber) switch { 0 => $"oggi alle {time}", 1 => $"ieri alle {time}", _ => $"il {DayText(DayOf(at), now)} alle {time}", }; } private static DateOnly DayOf(DateTimeOffset moment) => Zones.DayIn(moment, Zones.Rome); /// "domenica 4 ottobre", with the year when it is another one. private static string LongDay(DateOnly day, DateTimeOffset now) => Format.Day(day) + (day.Year == DayOf(now).Year ? "" : day.ToString(" yyyy", CultureInfo.InvariantCulture)); /// "4 ottobre", with the year when it is another one. private static string DayText(DateOnly day, DateTimeOffset now) => day.Year == DayOf(now).Year ? Format.LongDate(day)[..^5] : Format.LongDate(day); private static int? Points(double? share) => share is { } s ? (int)Math.Round(s * 100, MidpointRounding.AwayFromZero) : null; private static decimal Round(double value, int decimals) => Math.Round((decimal)value, decimals, MidpointRounding.AwayFromZero); }