using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace RynthCore.Plugin.RynthThreads.Threads; /// /// One modifier's rate in a set of presses (a component's, a combination's, ...), with its rate /// in the other presses for comparison. /// internal sealed class Odds { /// The modifier's name, or for any "<Material> Affinity". public string Modifier = string.Empty; /// Presses in the set that had it, of . public int Hits, N; /// False for the All presses row: nothing to compare with. public bool Compared; /// The other presses (without the component, ...) that had it, of ; 0 = no data. public int OtherHits, OtherN; /// One-sided Fisher exact p: chance of a rate this much higher here if the set made no difference. public double P = 1; /// Clearly higher here than in the other presses (Fisher p < 0.05 or the 95% intervals apart). public bool MoreLikely; /// Its numbers in these presses ("x1.38 to x1.52"). public string Values = string.Empty; /// For the Affinity group: presses per material, most first. public List<(string Material, int Hits)> Split = new(); public double Rate => N == 0 ? 0 : (double)Hits / N; public double? OtherRate => OtherN == 0 ? null : (double)OtherHits / OtherN; public bool IsGroup => Modifier == PressInference.AffinityGroup; } internal enum GroupKind { All, Component, Combination, NoComponents } /// (fragment level, result level, entries) and how many presses gave it. internal readonly record struct ResultCount(int? FragmentLevel, int? ResultLevel, int? Entries, int Count); /// A set of presses: All presses, one component's, one exact combination's, or those with no component. internal sealed class GroupReport { public string Name = string.Empty; public GroupKind Kind; /// The components (one for a component row, several for a combination, none otherwise). public List Members = new(); public int Presses; public double AvgModifiers; public int MinModifiers, MaxModifiers; /// Most common first. public List Results = new(); /// Every modifier seen in these presses, likeliest first. public List Odds = new(); /// What the comparison column is: "without", "other presses", "with components", or "". public string OtherLabel => Kind switch { GroupKind.Component => "without", GroupKind.Combination => "other presses", GroupKind.NoComponents => "with components", _ => string.Empty, }; public Odds? Find(string modifier) => Odds.FirstOrDefault(o => o.Modifier.Equals(modifier, StringComparison.OrdinalIgnoreCase)); } internal sealed class ModifierReport { /// The modifier's name, or . public string Name = string.Empty; public bool IsGroup; public string Example = string.Empty; /// "reward" (loot, salvage), "harder" (monster health, damage, numbers) or "" when the text doesn't say plainly. public string Tag = string.Empty; /// Its rate over all usable presses. public Odds Overall = new(); /// Its rate in presses with no components (against presses with some); null when there are none. public Odds? NoComponents; /// Its rate with each component and combination (0% included), likeliest first. public List<(GroupReport Group, Odds Odds)> ByGroup = new(); public string Values = string.Empty; /// (fragment level, presses, values), lowest level first; level null = unknown. public List<(int? Level, int Count, string Values)> ByLevel = new(); public int Seen => Overall.Hits; } internal sealed class ThreadsReport { public int Total, Usable, Incomplete, Characters; /// Every usable press (the baseline); null when there are none. public GroupReport? All; public List Components = new(); /// Exact combinations of two or more components. public List Combinations = new(); /// Presses with no components (the plain random draw); null when there are none. public GroupReport? NoComponents; public List Modifiers = new(); public GroupReport? Component(string name) => Components.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); public GroupReport? Combination(string name) => Combinations.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); public ModifierReport? Modifier(string name) => Modifiers.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } /// /// The odds of each modifier from the recorded presses. On DreamWeave a component gives a chance of /// each modifier, not a fixed one, so for every set of presses (All presses, each component, each /// exact combination of components, no components) this counts how often each modifier came: /// hits/N, with a 95% Wilson interval, against its rate in the presses outside the set. /// /// Only finished presses with their gem block count (Press.Usable); a finished press without a /// "Components selected" line counts as one with no components. Every gem carries one /// "<Material> Affinity": those are counted together as the Affinity group, with the split by /// material. /// /// "More likely with X": the rate with X is above the rate without and either the one-sided Fisher /// exact p is under 0.05 or the two 95% intervals don't overlap. "Always ... so far" only for 100% /// over at least 10 presses. /// internal static class PressInference { public const string AffinityGroup = "Affinity"; private const string AffinitySuffix = " Affinity"; private const double Z = 1.96; /// Intervals are shown below this many presses. public const int IntervalBelow = 50; public const int AlwaysAtLeast = 10; public static ThreadsReport Build(IReadOnlyList all) { var report = new ThreadsReport { Total = all.Count }; var used = new List(); var characters = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (Press p in all) { if (p.Character.Length > 0) characters.Add(p.Character); if (!p.Complete) report.Incomplete++; if (p.Usable) used.Add(p); } report.Usable = used.Count; report.Characters = characters.Count; if (used.Count == 0) return report; List components = Distinct(used.SelectMany(p => p.Components)); List keys = Distinct(used.SelectMany(Keys)); report.All = Group("All presses", GroupKind.All, new List(), used, used); foreach (string c in components) report.Components.Add(Group(c, GroupKind.Component, new List { c }, used, used.Where(p => p.HasComponent(c)).ToList())); SortGroups(report.Components); foreach (var g in used.Where(p => p.Components.Count > 1).GroupBy(ComboKey, StringComparer.OrdinalIgnoreCase)) { List members = g.First().Components.OrderBy(x => x, StringComparer.OrdinalIgnoreCase).ToList(); report.Combinations.Add(Group(string.Join(" + ", members), GroupKind.Combination, members, used, g.ToList())); } SortGroups(report.Combinations); List plain = used.Where(p => p.Components.Count == 0).ToList(); if (plain.Count > 0) report.NoComponents = Group("No components", GroupKind.NoComponents, new List(), used, plain); foreach (string k in keys) { List with = used.Where(p => Has(p, k)).ToList(); var mr = new ModifierReport { Name = k, IsGroup = k == AffinityGroup, Example = Find(with[^1], k)!.Description, Overall = Count(k, used, null), Values = Values(with, k), }; mr.Tag = Tag(mr.Example); if (report.NoComponents != null) mr.NoComponents = Count(k, plain, used.Where(p => p.Components.Count > 0).ToList()); foreach (GroupReport gr in report.Components.Concat(report.Combinations)) mr.ByGroup.Add((gr, gr.Find(k) ?? Count(k, Members(used, gr), Others(used, gr)))); mr.ByGroup.Sort((a, b) => { int byOdds = CompareOdds(a.Odds, b.Odds); return byOdds != 0 ? byOdds : string.Compare(a.Group.Name, b.Group.Name, StringComparison.OrdinalIgnoreCase); }); foreach (var g in with.GroupBy(p => p.FragmentLevel).OrderBy(g => g.Key ?? int.MaxValue)) mr.ByLevel.Add((g.Key, g.Count(), Values(g, k))); report.Modifiers.Add(mr); } report.Modifiers.Sort((a, b) => b.Seen != a.Seen ? b.Seen.CompareTo(a.Seen) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); return report; } // ── Groups ────────────────────────────────────────────────────────────── private static GroupReport Group(string name, GroupKind kind, List members, List used, List set) { var g = new GroupReport { Name = name, Kind = kind, Members = members, Presses = set.Count }; if (set.Count == 0) return g; g.AvgModifiers = set.Average(p => (double)p.Modifiers.Count); g.MinModifiers = set.Min(p => p.Modifiers.Count); g.MaxModifiers = set.Max(p => p.Modifiers.Count); g.Results = set.GroupBy(p => (p.FragmentLevel, p.ResultLevel, p.Entries)) .Select(x => new ResultCount(x.Key.FragmentLevel, x.Key.ResultLevel, x.Key.Entries, x.Count())) .OrderByDescending(r => r.Count).ThenBy(r => r.ResultLevel ?? int.MaxValue).ThenBy(r => r.Entries ?? int.MaxValue) .ToList(); List? others = kind == GroupKind.All ? null : Others(used, g, set); foreach (string k in Distinct(set.SelectMany(Keys))) g.Odds.Add(Count(k, set, others)); g.Odds.Sort(CompareOdds); return g; } private static void SortGroups(List groups) => groups.Sort((a, b) => b.Presses != a.Presses ? b.Presses.CompareTo(a.Presses) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); /// The presses a component or combination row covers. private static List Members(List used, GroupReport g) => g.Kind switch { GroupKind.Component => used.Where(p => p.HasComponent(g.Members[0])).ToList(), GroupKind.Combination => used.Where(p => ComboKey(p).Equals(ComboKey(g.Members), StringComparison.OrdinalIgnoreCase)).ToList(), GroupKind.NoComponents => used.Where(p => p.Components.Count == 0).ToList(), _ => used, }; /// The presses a row is compared with: without the component, not this combination, with components. private static List Others(List used, GroupReport g, List? set = null) { var inSet = new HashSet(set ?? Members(used, g)); return used.Where(p => !inSet.Contains(p)).ToList(); } private static string ComboKey(Press p) => ComboKey(p.Components); private static string ComboKey(IEnumerable components) => string.Join("\n", components.Select(c => c.ToLowerInvariant()).OrderBy(c => c, StringComparer.Ordinal)); /// Likeliest first; then more presses; then by name. private static int CompareOdds(Odds a, Odds b) { if (a.Rate != b.Rate) return b.Rate.CompareTo(a.Rate); if (a.Hits != b.Hits) return b.Hits.CompareTo(a.Hits); return string.Compare(a.Modifier, b.Modifier, StringComparison.OrdinalIgnoreCase); } /// Modifier in , against (null = no comparison). internal static Odds Count(string k, List set, List? others) { var o = new Odds { Modifier = k, N = set.Count, Compared = others != null }; foreach (Press p in set) if (Has(p, k)) o.Hits++; if (others != null) { o.OtherN = others.Count; foreach (Press p in others) if (Has(p, k)) o.OtherHits++; if (o.OtherN > 0 && o.N > 0) { o.P = FisherGreater(o.Hits, o.N, o.OtherHits, o.OtherN); bool apart = Wilson(o.Hits, o.N).Low > Wilson(o.OtherHits, o.OtherN).High; o.MoreLikely = o.Rate > o.OtherRate!.Value && (o.P < 0.05 || apart); } } o.Values = Values(set, k); if (k == AffinityGroup) { var split = new Dictionary(StringComparer.OrdinalIgnoreCase); var names = new List(); foreach (Press p in set) foreach (string mat in p.Modifiers.Select(m => Material(m.Name)).OfType().Distinct(StringComparer.OrdinalIgnoreCase)) { if (!split.ContainsKey(mat)) { split[mat] = 0; names.Add(mat); } split[mat]++; } o.Split = names.Select(n => (n, split[n])) .OrderByDescending(x => x.Item2).ThenBy(x => x.n, StringComparer.OrdinalIgnoreCase).ToList(); } return o; } // ── Modifier keys (the Affinity group) ────────────────────────────────── /// "Amethyst" for "Amethyst Affinity", else null. internal static string? Material(string modifier) => modifier.Length > AffinitySuffix.Length && modifier.EndsWith(AffinitySuffix, StringComparison.OrdinalIgnoreCase) ? modifier.Substring(0, modifier.Length - AffinitySuffix.Length).Trim() : null; /// The name the counts use: for any affinity, else the modifier's own. internal static string Key(string modifier) => Material(modifier) != null ? AffinityGroup : modifier; private static IEnumerable Keys(Press p) => p.Modifiers.Select(m => Key(m.Name)); private static bool Has(Press p, string k) => Find(p, k) != null; private static GemModifier? Find(Press p, string k) { if (k != AffinityGroup) return p.FindModifier(k); foreach (GemModifier m in p.Modifiers) if (Material(m.Name) != null) return m; return null; } /// "Affinity (any)" for the group, else the name. internal static string Display(string k) => k == AffinityGroup ? "Affinity (any)" : k; // ── Statistics ────────────────────────────────────────────────────────── /// 95% Wilson score interval for of . internal static (double Low, double High) Wilson(int hits, int n) { if (n <= 0) return (0, 1); double p = (double)hits / n, z2 = Z * Z; double denom = 1 + z2 / n; double centre = (p + z2 / (2 * n)) / denom; double half = Z * Math.Sqrt(p * (1 - p) / n + z2 / (4.0 * n * n)) / denom; return (Math.Max(0, centre - half), Math.Min(1, centre + half)); } /// /// One-sided Fisher exact test: the chance of or more hits in a set of /// when + hits are spread at random /// over the + presses. /// internal static double FisherGreater(int a, int n, int c, int m) { int total = n + m, hits = a + c; if (total == 0) return 1; double logAll = LogChoose(total, n), sum = 0; for (int x = a; x <= Math.Min(n, hits); x++) { if (hits - x > m) continue; sum += Math.Exp(LogChoose(hits, x) + LogChoose(total - hits, n - x) - logAll); } return Math.Min(1, sum); } private static double LogChoose(int n, int k) { if (k < 0 || k > n) return double.NegativeInfinity; double r = 0; for (int i = 1; i <= k; i++) r += Math.Log(n - k + i) - Math.Log(i); return r; } // ── Text ──────────────────────────────────────────────────────────────── private static string Pct(double v) => Math.Round(v * 100).ToString("0", CultureInfo.InvariantCulture); /// "75% (3/4, 30-95%)"; the interval only below presses. internal static string OddsText(Odds o) { if (o.N == 0) return "no data"; if (o.N >= IntervalBelow) return $"{Pct(o.Rate)}% ({o.Hits}/{o.N})"; var (lo, hi) = Wilson(o.Hits, o.N); return $"{Pct(o.Rate)}% ({o.Hits}/{o.N}, {Pct(lo)}-{Pct(hi)}%)"; } /// "without: 20% (1/5)", "without: no data", or "" when not compared. internal static string OtherText(Odds o, string label) { if (!o.Compared || label.Length == 0) return string.Empty; return o.OtherN == 0 ? label + ": no data" : $"{label}: {Pct(o.OtherRate!.Value)}% ({o.OtherHits}/{o.OtherN})"; } /// "more likely with Lead Scarab", "always with Lead Scarab so far" (100% over 10+), or "". internal static string LikelyText(Odds o, GroupReport g) { if (!o.MoreLikely) return string.Empty; string who = g.Kind == GroupKind.NoComponents ? "no components" : g.Name; return o.Hits == o.N && o.N >= AlwaysAtLeast ? $"always with {who} so far" : $"more likely with {who}"; } /// "Amethyst 1, Iron 1" for the Affinity group's split, else "". internal static string SplitText(Odds o) => string.Join(", ", o.Split.Select(s => $"{s.Material} {s.Hits}")); /// "5.25 modifiers per press (5-6)". internal static string ModifiersText(GroupReport g) { string avg = g.AvgModifiers.ToString("0.##", CultureInfo.InvariantCulture); string range = g.MinModifiers == g.MaxModifiers ? "" : $" ({g.MinModifiers}-{g.MaxModifiers})"; return $"{avg} modifiers per press{range}"; } /// "L185 -> 175, 3 entries: 4" per result, most common first. internal static string ResultsText(GroupReport g) => string.Join("; ", g.Results.Select(r => $"L{N(r.FragmentLevel)} -> {N(r.ResultLevel)}, {N(r.Entries)} entries: {r.Count}")); private static string N(int? v) => v?.ToString(CultureInfo.InvariantCulture) ?? "?"; private static List Distinct(IEnumerable names) { var list = new List(); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string n in names) if (n.Length > 0 && seen.Add(n)) list.Add(n); list.Sort(StringComparer.OrdinalIgnoreCase); return list; } /// /// The modifier's numbers across presses, position by position: "x1.38 to x1.52, 12%". Empty /// when it has none. /// internal static string Values(IEnumerable presses, string k) { var ranges = new List<(string Kind, double Min, double Max)>(); foreach (Press p in presses) { GemModifier? gm = Find(p, k); if (gm == null) continue; for (int i = 0; i < gm.Numbers.Count; i++) { ModNumber n = gm.Numbers[i]; if (i >= ranges.Count) ranges.Add((n.Kind, n.Value, n.Value)); else ranges[i] = (ranges[i].Kind, Math.Min(ranges[i].Min, n.Value), Math.Max(ranges[i].Max, n.Value)); } } var sb = new StringBuilder(); foreach (var (kind, min, max) in ranges) { if (sb.Length > 0) sb.Append(", "); sb.Append(Format(kind, min)); if (max != min) sb.Append(" to ").Append(Format(kind, max)); } return sb.ToString(); } internal static string Format(string kind, double v) { string s = v.ToString("0.##", CultureInfo.InvariantCulture); return kind switch { ModNumber.Mult => "x" + s, ModNumber.Pct => s + "%", ModNumber.Plus => v >= 0 ? "+" + s : s, _ => s, }; } /// "reward" or "harder" when the description says so plainly, else "". internal static string Tag(string description) { string d = description.ToLowerInvariant(); bool reward = d.Contains("loot") || d.Contains("salvage") || d.Contains("drop"); bool harder = d.Contains("monsters have") || d.Contains("more monsters") || d.Contains("monsters attack") || d.Contains("boss attacks") || d.Contains("hitting harder"); return reward == harder ? string.Empty : reward ? "reward" : "harder"; } }