Answer architecture round 1: 3 🔴, 13 🟡; one items-table reader, a pure measuring core, shared git and round-title modules, and a hook rule for round counts
This commit is contained in:
@@ -1,119 +1,91 @@
|
||||
import dataclasses
|
||||
import re
|
||||
import statistics
|
||||
from typing import Callable
|
||||
import typing
|
||||
|
||||
from larv_review.rounds import round_counts, ROUND
|
||||
from comprehension_history import HISTORY
|
||||
from todo_table import Item, items
|
||||
from reading_cost.figures import RECORD
|
||||
from round_titles import round_counts, round_findings
|
||||
|
||||
# Least to be measured before a score's medians show: the count the reading-cost trend waits for, which no published standard sets either.
|
||||
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]
|
||||
# The plan, and the records tools append to: none of their lines are the chunk's work.
|
||||
NOT_WORK = ("todo.md", HISTORY, RECORD)
|
||||
|
||||
|
||||
@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
|
||||
"""What the merge that shipped an item measured. findings holds the 🔴 and 🟡 counts, None where a round title lacks them."""
|
||||
item: Item
|
||||
merge: str
|
||||
merged: str
|
||||
shipped_with: tuple[int, ...]
|
||||
lines: int
|
||||
files: int
|
||||
rounds: int
|
||||
red: int | None
|
||||
yellow: int | None
|
||||
rounds_past_first: int
|
||||
findings: tuple[int, int] | None
|
||||
|
||||
|
||||
# Each score, and the outcome it predicts.
|
||||
MEASURES: dict[str, tuple[str, Callable[[Outcome], int | None]]] = {
|
||||
"R": ("🔴 findings", lambda outcome: outcome.red),
|
||||
# Each score, and the outcome it predicts. Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
|
||||
MEASURES: dict[str, tuple[str, typing.Callable[[Outcome], int | None]]] = {
|
||||
"R": ("🔴 findings", lambda outcome: outcome.findings[0] if outcome.findings else None),
|
||||
"S": ("lines changed", lambda outcome: outcome.lines),
|
||||
"C": ("review rounds", lambda outcome: outcome.rounds),
|
||||
"C": ("review rounds past each pass's first", lambda outcome: outcome.rounds_past_first),
|
||||
}
|
||||
|
||||
|
||||
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 shipped(before: str, after: str) -> list[Item]:
|
||||
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
|
||||
planned, left = items(before), items(after)
|
||||
if not isinstance(planned, list) or not isinstance(left, list):
|
||||
return []
|
||||
kept = {item.id for item in left}
|
||||
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
||||
|
||||
|
||||
def split(row: str) -> list[str]:
|
||||
return [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]] if row.startswith("|") else []
|
||||
|
||||
|
||||
def shipped(before: dict[int, Guess], after: dict[int, Guess]) -> 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 <pass> round <n>:` title, which opens with `<n> 🔴, <n> 🟡`; 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 outcomes_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str]) -> list[Outcome]:
|
||||
"""What one merge measured for each item it shipped, from `git diff --numstat` against its first parent and its branch's commit titles; none where it changed nothing but the plan and the records."""
|
||||
changed = [row.split("\t", 2) for row in numstat.splitlines()]
|
||||
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
|
||||
if not work:
|
||||
return []
|
||||
# Git counts a binary file's lines as "-".
|
||||
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
|
||||
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
|
||||
ids = [item.id for item in shipped]
|
||||
return [Outcome(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles)) for item in shipped]
|
||||
|
||||
|
||||
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)
|
||||
"""The outcomes whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
|
||||
def distance(outcome: Outcome) -> float:
|
||||
shared = [name for name in given if name in outcome.item.scores]
|
||||
return sum((given[name] - outcome.item.scores[name]) ** 2 for name in shared) / len(shared)
|
||||
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."""
|
||||
"""For each score, the median outcome at each value it was guessed at, among chunks that shipped one item: a chunk measures all its 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]
|
||||
held = [(outcome.item.scores[name], value) for outcome in single if name in outcome.item.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}.")
|
||||
lines.append(f"- {name}, {what}: {len(held)} {chunks} {name} and its outcome; 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]
|
||||
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
|
||||
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} 🟡"
|
||||
scores = ", ".join(f"{name} {outcome.item.scores[name]}" for name in MEASURES if name in outcome.item.scores)
|
||||
findings = f"{outcome.findings[0]} 🔴, {outcome.findings[1]} 🟡" if outcome.findings else "findings unknown"
|
||||
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}"
|
||||
return f"- Item {outcome.item.id}, {scores}: {plural(outcome.lines, 'line')} in {plural(outcome.files, 'file')}, {plural(outcome.rounds_past_first, 'round')} past each pass's first, {findings}; merged {outcome.merged} in {outcome.merge}{together}. {outcome.item.tagline}"
|
||||
|
||||
|
||||
def plural(count: int, noun: str) -> str:
|
||||
|
||||
Reference in New Issue
Block a user