import dataclasses import re import statistics from typing import Callable from larv_review.rounds import round_counts, ROUND ENOUGH = 10 FINDINGS = re.compile(r"([0-9]+) 🔴, ([0-9]+) 🟡(;|$)") @dataclasses.dataclass(frozen=True) class Guess: """An item's tagline and its R, S and C as the plan held them, C only where the plan scored one.""" id: int tagline: str scores: dict[str, int] @dataclasses.dataclass(frozen=True) class Outcome: """What the merge that shipped an item measured; the findings are unknown where a round title lacks their counts.""" guess: Guess merge: str merged: str shipped_with: tuple[int, ...] lines: int files: int rounds: int red: int | None yellow: int | None # Each score, and the outcome it predicts. MEASURES: dict[str, tuple[str, Callable[[Outcome], int | None]]] = { "R": ("🔴 findings", lambda outcome: outcome.red), "S": ("lines changed", lambda outcome: outcome.lines), "C": ("review rounds", lambda outcome: outcome.rounds), } def guesses(todo: str) -> dict[int, Guess] | None: """Each item of a todo.md's items table by ID, from any shape of table with ID, Item, R and S columns; None without such a table. A row it cannot read is left out.""" lines = todo.splitlines() for index, line in enumerate(lines): header = split(line) if {"ID", "Item", "R", "S"} <= set(header): break else: return None found = {} for row in lines[index + 2:]: if not row.startswith("|"): break named = dict(zip(header, split(row))) if len(split(row)) != len(header) or not all(re.fullmatch(r"[0-9]+", named.get(name, "0")) for name in ("ID", "R", "S", "C")): continue scores: dict[str, int] = {name: int(named[name]) for name in ("R", "S", "C") if name in named} found[int(named["ID"])] = Guess(int(named["ID"]), named["Item"], scores) return found def split(row: str) -> list[str]: return [cell.strip() for cell in re.split(r"(? list[Guess]: return [guess for id_, guess in sorted(before.items()) if id_ not in after] def round_findings(titles: list[str]) -> tuple[int, int] | None: """The 🔴 and 🟡 findings summed over each `Answer round :` title, which opens with ` 🔴, 🟡`; None where a round title does not, or no title is a round.""" counts = [] for title in titles: if named := ROUND.match(title): found = FINDINGS.match(title[named.end():].lstrip()) if not found: return None counts.append((int(found.group(1)), int(found.group(2)))) return (sum(red for red, _ in counts), sum(yellow for _, yellow in counts)) if counts else None def rounds(titles: list[str]) -> int: return sum(round_counts(titles).values()) def nearest(outcomes: list[Outcome], given: dict[str, int], count: int = 5) -> list[Outcome]: """The outcomes whose guesses sit closest to the given scores, newest first among equals; C counts only where both hold one.""" def distance(outcome: Outcome) -> int: return sum((value - outcome.guess.scores[name]) ** 2 for name, value in given.items() if name in outcome.guess.scores) newest_first = sorted(outcomes, key=lambda outcome: outcome.merged, reverse=True) return sorted(newest_first, key=distance)[:count] def report(outcomes: list[Outcome]) -> list[str]: """For each score, the median outcome of each value it was guessed at, among chunks that shipped one item; a chunk measures several items at once.""" single = [outcome for outcome in outcomes if not outcome.shipped_with] lines = [] for name, (what, measure) in MEASURES.items(): held = [(outcome.guess.scores[name], value) for outcome in single if name in outcome.guess.scores and (value := measure(outcome)) is not None] if len(held) < ENOUGH: chunks = "chunk that shipped one item records" if len(held) == 1 else "chunks that shipped one item record" lines.append(f"- {name}, {what}: {len(held)} {chunks} {name} and {what}; the report needs {ENOUGH}.") continue values = sorted({guess for guess, _ in held}) medians = [(guess, [value for at, value in held if at == guess]) for guess in values] lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians)) return lines def render(outcome: Outcome) -> str: scores = ", ".join(f"{name} {value}" for name, value in outcome.guess.scores.items()) findings = "findings unknown" if outcome.red is None else f"{outcome.red} 🔴, {outcome.yellow} 🟡" others = outcome.shipped_with together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else "" return f"- Item {outcome.guess.id}, {scores}: {plural(outcome.lines, 'line')} in {plural(outcome.files, 'file')}, {plural(outcome.rounds, 'review round')}, {findings}; merged {outcome.merged} in {outcome.merge}{together}. {outcome.guess.tagline}" def plural(count: int, noun: str) -> str: return f"{count} {noun}{'' if count == 1 else 's'}"