defmodule TradeMachine.GMGradeV2.Pillars.RosterConstruction.PositionCoverage do @moduledoc """ Scores AVC's Position Coverage metric over the entire final roster. Each player contributes only at their listed position. The historical player feed's generic `"G"` display value is canonicalized to `"SG"` — the same conservative rule used by calibration, which avoids inventing primary-handler credit. Their contribution is the shared `TradeMachine.GMGradeV2.SkillIndexes.contribution_factor/2`, so the 800-minute experience curve and the two-way availability multiplier remain centralized. A position reaches full coverage at one contribution unit. The result's `inputs.detail` records who makes up each position's units, so a breakdown can show them without working anything out again: %{ experience_minutes: 800, positions: %{ "PG" => [%{player_id: id, name: name, amount: 1.0, season_minutes: 2100, two_way: false}, ...], ...all five positions, always present } } Each position lists every player counted there, largest amount first (roster order among equal amounts). A position's amounts sum to its `inputs.coverage_units` figure; a player with no minutes sample has no entry (he is in `fallbacks`). `season_minutes` and `two_way` are what the amount was worked out from (`SkillIndexes.contribution_basis/1`), and `experience_minutes` is the number of minutes that counts as full experience under the same model override, so `SkillIndexes.contribution_factor/2` on a player built from an entry gives back its amount. Nothing reads `detail` to compute a score. """ alias TradeMachine.GMGradeV2.Benchmark alias TradeMachine.GMGradeV2.ChallengeSnapshot alias TradeMachine.GMGradeV2.ModelVersion alias TradeMachine.GMGradeV2.Pillars.RosterConstruction.Inputs alias TradeMachine.GMGradeV2.Result.MetricResult alias TradeMachine.GMGradeV2.SkillIndexes @positions ~w(PG SG SF PF C) @average_weight 0.70 @weakest_weight 0.30 @doc "Returns the five positions in AVC's stated order." @spec positions() :: [String.t()] def positions, do: @positions @doc "Normalizes an AVC position (including legacy `G`) or raises." @spec normalize_position!(String.t() | atom()) :: String.t() def normalize_position!(position) when position in @positions, do: position def normalize_position!("G"), do: "SG" def normalize_position!(position) when is_atom(position) do position |> Atom.to_string() |> String.upcase() |> normalize_position!() end def normalize_position!(position) do raise ArgumentError, "position must be one of #{Enum.join(@positions, ", ")}, got: #{inspect(position)}" end @doc "Returns a full-precision Position Coverage metric result." @spec score(map(), ChallengeSnapshot.t()) :: MetricResult.t() def score( %{roster: roster} = scenario_state, %ChallengeSnapshot{benchmark: %Benchmark{} = benchmark} = snapshot ) when is_list(roster) do override = Inputs.model_override(scenario_state, snapshot) {units, fallbacks, entries} = coverage_units_with_entries(roster, override) position_scores = Map.new(units, fn {position, value} -> {position, position_score(value)} end) scores = Map.values(position_scores) average = Enum.sum(scores) / length(@positions) weakest = Enum.min(scores) %MetricResult{ key: :position_coverage, version: benchmark.version, score: average * @average_weight + weakest * @weakest_weight, inputs: %{ coverage_units: units, average_position_score: average, weakest_position_score: weakest, detail: %{ experience_minutes: ModelVersion.experience_minutes(override), positions: entries } }, supporting: position_scores, weights: %{average: @average_weight, weakest: @weakest_weight}, fallbacks: fallbacks, explanation: "Position Coverage gives 70% weight to the five-position average and 30% " <> "to the weakest listed position." } end @doc """ Sums player contribution factors at each listed position. Players with unknown season minutes receive no invented coverage credit and are reported as fallbacks. The legacy generic-guard value `G` uses the documented `SG` canonicalization; other positions outside AVC's PG/SG/SF/PF/C vocabulary are rejected rather than silently omitted. """ @spec coverage_units([map()], map()) :: {%{String.t() => float()}, [MetricResult.fallback()]} def coverage_units(roster, override \\ %{}) when is_list(roster) and is_map(override) do {units, fallbacks, _entries} = coverage_units_with_entries(roster, override) {units, fallbacks} end # `coverage_units/2` plus, collected in the same pass, the players behind # each position's units (largest amount first). The units are added up # exactly as before; the entries are recorded beside them and read by # nothing that scores. defp coverage_units_with_entries(roster, override) do initial = {Map.new(@positions, &{&1, 0.0}), [], Map.new(@positions, &{&1, []})} {units, fallbacks, entries} = Enum.reduce(roster, initial, fn player, {units, fallbacks, entries} -> position = player |> fetch_any!(:position) |> normalize_position!() case SkillIndexes.contribution_factor(player, override) do factor when is_number(factor) -> entry = coverage_entry(player, factor) {Map.update!(units, position, &(&1 + factor)), fallbacks, Map.update!(entries, position, &[entry | &1])} nil -> fallback = %{ input: player_identifier(player), method: :missing_contribution_factor, note: "#{player_label(player)} has no season-minutes sample, so no " <> "#{position} coverage credit was invented." } {units, [fallback | fallbacks], entries} end end) entries = Map.new(entries, fn {position, players} -> {position, players |> Enum.reverse() |> Enum.sort_by(& &1.amount, :desc)} end) {units, Enum.reverse(fallbacks), entries} end defp coverage_entry(player, amount) do basis = SkillIndexes.contribution_basis(player) %{ player_id: fetch_any(player, :id) || fetch_any(player, :player_id), name: fetch_any(player, :name), amount: amount, season_minutes: basis.season_minutes, two_way: basis.two_way } end @doc "Converts coverage units to AVC's capped 0–100 individual-position score." @spec position_score(number()) :: float() def position_score(units) when is_number(units) and units >= 0 do 100.0 * min(1.0, units) end defp fetch_any!(map, key) do case Map.get(map, key, Map.get(map, Atom.to_string(key))) do nil -> raise KeyError, key: key, term: map value -> value end end defp fetch_any(map, key), do: Map.get(map, key, Map.get(map, Atom.to_string(key))) defp player_identifier(player) do fetch_any(player, :id) || fetch_any(player, :player_id) || player_label(player) end defp player_label(player) do fetch_any(player, :name) || "Player #{inspect(player_identifier_without_label(player))}" end defp player_identifier_without_label(player) do fetch_any(player, :id) || fetch_any(player, :player_id) || "at #{fetch_any(player, :position)}" end end