Show what the model knows on its own screen and let the user set it aside

The Apprendimento screen says in plain words whether the model counts, how
well its probabilities hold, which clues it weighs, how the challenger is
doing and what it has learned. Thresholds, set-aside and the undo of a
promotion live in Impostazioni; anything that shrinks less with real money
asks for the phrase. The new tests also caught a wrong column name that
broke the Panoramica as soon as the first model existed.

refs #66

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 12:44:37 +01:00
1 parent 14e8a872dc
commit f69943f70a
22 files changed
+1680 -27

No files matched your search

+545
View File
@@ -0,0 +1,545 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Learning;
namespace Anubis.Server;
/// <summary>What the model is doing, for the badge and the sentences at the top.</summary>
internal static class LearningStates
{
/// <summary>No model yet: the night after the first start prepares it.</summary>
public const string None = "none";
public const string Observation = "observation";
public const string Active = "active";
/// <summary>Set aside on its own by the nightly check.</summary>
public const string Aside = "aside";
/// <summary>Set aside by the user.</summary>
public const string Manual = "manual";
}
/// <summary>A band of estimates: percentages as they are read, the point at the mean estimate.</summary>
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);
/// <summary>A column of the comparison between the model in charge and the one on trial.</summary>
internal sealed record LearningVersion(int Version, string Trained, int Examples, int? Precision, decimal? Error, decimal? Gain, decimal? GainWithout);
/// <summary>What was tried when a model was trained, the chosen one included.</summary>
internal sealed record LearningAttempt(string Learner, int? Precision, decimal Error, decimal Gain, bool Chosen);
public sealed record LearningWeek(DateOnly Monday, int Precision);
/// <summary>A line of "Sorveglianza": <paramref name="State"/> is ok, warn or wait.</summary>
internal sealed record LearningCheck(string State, string Text);
internal sealed record LearningStory(string When, string Text);
/// <summary>The model box of the Panoramica: the same state in few words.</summary>
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.",
};
}
/// <summary>
/// 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.
/// </summary>
internal sealed record LearningView
{
/// <summary>The clues named one by one; the others are "Tutto il resto".</summary>
public const int NamedWeights = 9;
public const int StoryRows = 12;
private const string Fear = "Paura o avidità";
/// <summary>The pace is measured on the last four weeks, and needs at least one.</summary>
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; }
/// <summary>With 300 signals done, what still stops it from counting.</summary>
public IReadOnlyList<string> Missing { get; init; } = [];
/// <summary>"domenica 4 ottobre, versione 3".</summary>
public required string LastTraining { get; init; }
public IReadOnlyList<LearningBand> Bands { get; init; } = [];
/// <summary>The sentence under the calibration chart.</summary>
public string BandsText { get; init; } = "";
/// <summary>True when the bands are those of the verification on the history, because the live ones are still too few.</summary>
public bool BandsFromHistory { get; init; }
public IReadOnlyList<LearningWeight> Weights { get; init; } = [];
public string WeightsText { get; init; } = "";
public LearningVersion? Champion { get; init; }
public LearningVersion? Challenger { get; init; }
/// <summary>The signals both estimated, with their outcome, and how many the next decision needs.</summary>
public int Pairs { get; init; }
public int PairsNeeded { get; init; }
public string TrialTitle { get; init; } = "";
public string TrialText { get; init; } = "";
/// <summary>How the model in charge was chosen, with everything that was tried.</summary>
public string? Choice { get; init; }
public IReadOnlyList<LearningAttempt> Attempts { get; init; } = [];
/// <summary>Set when the last promotion can be taken back: the version that would return.</summary>
public int? UndoTo { get; init; }
public bool Anomaly { get; init; }
public bool Checked { get; init; }
public IReadOnlyList<LearningCheck> Checks { get; init; } = [];
public IReadOnlyList<LearningWeek> Weeks { get; init; } = [];
public IReadOnlyList<Discovery> Found { get; init; } = [];
public IReadOnlyList<NewsImpact> News { get; init; } = [];
public IReadOnlyList<LearningStory> Story { get; init; } = [];
// ---- Panoramica ---------------------------------------------------------------------------------------------
/// <summary>The few numbers of the Panoramica.</summary>
public static async Task<LearningSummary> 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<ModelRow> 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" : Format.Day(DayOf(last.TrainedAt)),
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<LearningView> 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, desk.BaseRates, capitals, aside, found, events, clock.UtcNow);
}
/// <summary>The page from what was read, without touching the database.</summary>
public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capitals, bool aside, DiscoverySet discoveries,
IReadOnlyList<ModelEvent> 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);
var live = activation.Scores.Bands;
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" : $"{Format.Day(DayOf(last.TrainedAt))}, versione {last.Version}",
Bands = bands,
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands),
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,
Found = discoveries.Found,
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, Points(w.Precision)!.Value))],
Checks = state.Health is { } health ? 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), 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. 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}"),
};
}
/// <summary>How long the missing signals take at the pace of the last four weeks.</summary>
public static string? PaceText(IReadOnlyList<Estimate> 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);
}
/// <summary>"Al ritmo attuale, tra tre e quattro settimane." from the weeks that are missing.</summary>
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<string> Missings(ActivationCheck check)
{
var missing = new List<string>();
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.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));
/// <summary>The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not count.</summary>
public static string BandsWords(IReadOnlyList<LearningBand> bands)
{
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 = 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: " +
(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" : cases.ToString(_it) + " 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 ? $"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 -----------------------------------------------------------------------------------------------
/// <summary>The scores of a model on the cases it had not studied, from the verification of its training.</summary>
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);
private static LearningView WithTrial(LearningView view, TrialCheck check, int? champion, int? challenger)
{
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > check.Pairs, TrialCheck.Thresholds[^1]);
var first = TrialCheck.Thresholds[0];
var thresholds = string.Join(", ", TrialCheck.Thresholds.SkipLast(1)) + " e " + TrialCheck.Thresholds[^1];
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. Si decide solo quando i casi superano {thresholds}: " +
$"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<LearningCheck> ChecksOf(HealthCheck health, LearningSnapshot snapshot, ModelRow champion, Scores? verified, IReadOnlyList<ModelEvent> 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<LearningCheck>
{
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(Points(health.Precision), 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<ModelEvent> 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), champion.Version, challenger.Version);
}
// ---- Words --------------------------------------------------------------------------------------------------
/// <summary>The night that comes: 03:00 in Rome of the next Sunday, or of the next day before the first model.</summary>
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";
}
/// <summary>"domenica 11 ottobre alle 03:00" from the short form.</summary>
private static string At(string next) => next.Replace(",", " alle", StringComparison.Ordinal);
/// <summary>"oggi alle 03:00", "il 4 ottobre alle 03:00".</summary>
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);
/// <summary>"4 ottobre", with the year when it is another one.</summary>
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);
}