"""SOURCE render logic for TI-AN-01 (REFERENCE ONLY).
This is the exact function from our pipeline. It is DB-coupled — you cannot run it without our database.
The query result it produces is materialized for you in data.csv, and the rendered output is figure.json
(load that to display the chart). This file is provided so you can understand / re-theme the logic.
"""
def render_TI_AN_01(reg: dict) -> dict:
"""The Anime 10 (weekly board) - the biggest anime series in US homes, ranked within-lane
(reach_7d x cred, K_ANIME) and displayed Billboard-style: rank, Anime Pulse Index (#1 = 100),
weekly movement chip, weeks-on-board, amber NEW chip for debuts. No absolute scores ship."""
chart_id = "TI-AN-01"
output_dir = THIS_DIR / chart_id / ROLE
conn = lib.connect_readonly()
t0 = time.time()
# One pass: per-(title, week) trailing-7d avg reach for AN_WEEKS disjoint weekly windows,
# board-universe flag (reach > 0 on each window's anchor day), and lane cred votes.
df = lib.run_query(conn, f"""
WITH d AS (SELECT MAX(file_date) AS d0 FROM title_metrics_daily WHERE geo_code = 'US'),
wk AS (SELECT generate_series(0, %(weeks)s - 1) AS w),
uni AS (
SELECT DISTINCT t.imdb_id
FROM title_metrics_daily t, d
WHERE t.geo_code = 'US' AND t.reach > 0
AND t.file_date BETWEEN d.d0 - (7 * %(weeks)s - 1) AND d.d0
),
lane AS (
SELECT b.imdb_id, b.primary_title, b.start_year
FROM uni u JOIN categorization_imdb_title_basics b USING (imdb_id), d
WHERE b.title_type IN ('tvSeries','tvMiniSeries') AND {_AN_LANE_WHERE}
),
votes AS (
SELECT l.imdb_id,
COALESCE(NULLIF((SELECT MAX(r.num_votes) FROM categorization_imdb_ratings r
WHERE r.imdb_id = l.imdb_id), 0)::numeric,
42 * NULLIF((SELECT MAX(m.tmdb_votes) FROM categorization_metadata m
WHERE m.imdb_id = l.imdb_id), 0)::numeric) AS v
FROM lane l
)
SELECT t.imdb_id, l.primary_title, l.start_year, w.w,
AVG(t.reach)::numeric AS reach_7d,
BOOL_OR(t.file_date = d.d0 - 7 * w.w AND t.reach > 0) AS on_anchor,
MAX(v.v)::numeric AS v, MAX(d.d0) AS d0
FROM title_metrics_daily t
JOIN lane l ON l.imdb_id = t.imdb_id
LEFT JOIN votes v ON v.imdb_id = t.imdb_id
CROSS JOIN wk w CROSS JOIN d
WHERE t.geo_code = 'US'
AND t.file_date BETWEEN d.d0 - 7 * w.w - 6 AND d.d0 - 7 * w.w
GROUP BY t.imdb_id, l.primary_title, l.start_year, w.w;
""", {"weeks": AN_WEEKS})
ph = lib.run_query(conn, """SELECT degraded FROM metrics_panel_health
WHERE file_date = (SELECT MAX(file_date) FROM title_metrics_daily
WHERE geo_code = 'US');""")
panel_degraded = bool(ph["degraded"].iloc[0]) if len(ph) else False
q_sec = time.time() - t0
conn.close()
if df.empty:
lib.needs_spec_review(output_dir, chart_id, reg.get("spec_file", "_anime_section_mock/mock_board.md"),
reg.get("pc_id", "PC-AN-01"), "No anime-lane weekly data")
write_shim(output_dir, chart_id); return {"status": "needs_spec_review"}
n_blocked = df.loc[df["imdb_id"].isin(ANIME_SOURCE_BLOCKLIST), "imdb_id"].nunique()
df = df[~df["imdb_id"].isin(ANIME_SOURCE_BLOCKLIST)].copy() # content policy (see constant)
df["reach_7d"] = df["reach_7d"].astype(float)
df["v"] = pd.to_numeric(df["v"], errors="coerce")
df["w"] = df["w"].astype(int)
df["score"] = df["reach_7d"] * df["v"] / (df["v"] + K_ANIME) # internal only - never ships
freshness = str(df["d0"].iloc[0])
# Board per week: universe = reach > 0 on that week's anchor day; NULL-cred excluded
# from ranked slots (board-faithful).
ranked = df[df["on_anchor"].astype(bool) & df["v"].notna()].copy()
ranked["lane_rank"] = ranked.groupby("w")["score"].rank(ascending=False, method="first").astype(int)
cur = ranked[ranked["w"] == 0].sort_values("lane_rank").head(AN_BOARD_SLOTS).copy()
if cur.empty:
lib.needs_spec_review(output_dir, chart_id, reg.get("spec_file", "_anime_section_mock/mock_board.md"),
reg.get("pc_id", "PC-AN-01"), "Anime lane empty at the current anchor week")
write_shim(output_dir, chart_id); return {"status": "needs_spec_review"}
cur["pulse_index"] = 100.0 * cur["score"] / float(cur["score"].max())
prev_rank = ranked[ranked["w"] == 1].set_index("imdb_id")["lane_rank"]
cur["prev_rank"] = cur["imdb_id"].map(prev_rank)
# NEAR-TIE GUARD at the top of the board: a within-lane index is a relative reach x cred figure, so a
# sub-1-point gap between #1 and #2 is within noise and must NOT be sold as a clean rank change. When
# the top two round to the same whole index, the headline discloses the dead heat instead of asserting
# a decisive #1, and an on-chart note flags it next to the leaders. (The index is shown to whole
# numbers, not one decimal, so the face never implies a precision the noise cannot support.)
cur_sorted_idx = cur.sort_values("pulse_index", ascending=False)["pulse_index"].tolist()
top_near_tie = len(cur_sorted_idx) >= 2 and round(cur_sorted_idx[0]) == round(cur_sorted_idx[1])
# Tenure + debut from the board re-runs themselves: consecutive weekly top-10 finishes
# counting back from this week; debut = on board now and in NO earlier computed week.
onboard_weeks = ranked[ranked["lane_rank"] <= AN_BOARD_SLOTS].groupby("imdb_id")["w"].agg(set)
def _streak(iid):
got = onboard_weeks.get(iid, set())
s = 0
while s in got:
s += 1
return s
cur["weeks_on_board"] = cur["imdb_id"].map(_streak).astype(int)
cur["debut"] = cur["imdb_id"].map(lambda i: len(onboard_weeks.get(i, set()) - {0}) == 0)
# Transparency count (no silent exclusions): lane series in the raw-reach top-10 that the
# corroboration weighting keeps lower or off the board. Count only - the no-spotlight
# content band means names stay off annotation copy by rule.
raw_top = df[(df["w"] == 0) & df["on_anchor"].astype(bool)].nlargest(AN_BOARD_SLOTS, "reach_7d")
board_ids = set(cur["imdb_id"])
pend_n = int(sum((iid not in board_ids) and (pd.isna(v) or (v / (v + K_ANIME)) < 0.5)
for iid, v in zip(raw_top["imdb_id"], raw_top["v"])))
plot = cur.sort_values("lane_rank", ascending=False).reset_index(drop=True) # 10..1 -> #1 on top
ticks, texts, colors, chips = [], [], [], {}
for _, r in plot.iterrows():
rk = int(r["lane_rank"]); title = clean_title(r["primary_title"])
debut = bool(r["debut"])
ch, cc = _an_chip(rk, r["prev_rank"], debut)
chips[r["imdb_id"]] = ch
is_lead = rk == 1
ticks.append(f"{rk}. {title}" if (is_lead or debut) else f"{rk}. {title}")
wk = int(r["weeks_on_board"])
if debut or wk <= 0:
tenure = ""
else:
wk_txt = f"{AN_WEEKS}+" if wk >= AN_WEEKS else str(wk) # history window caps tenure
tenure = f" · {wk_txt} wk{'s' if wk != 1 else ''}"
texts.append(f"{r['pulse_index']:.0f} {ch}{tenure}")
# Color contract: NAVY = leader ONLY, PALE_BLUE = the field. A debut keeps the pale field
# fill (a full amber bar would out-weigh the navy leader); the amber NEW chip in the outside
# label is the debut signal, so amber marks the debut without a bar-length verdict.
colors.append(lib.NAVY if is_lead else lib.PALE_BLUE)
fig = go.Figure()
fig.add_trace(go.Bar(
x=plot["pulse_index"].astype(float), y=ticks, orientation="h",
marker=dict(color=colors, line=dict(width=0)),
text=texts, textposition="outside", textfont=dict(size=11, color=lib.MUTED),
cliponaxis=False, showlegend=False,
hovertemplate="%{y}
Anime Pulse Index %{x:.0f} (this week's #1 = 100)",
))
fig.update_xaxes(range=[0, 132]) # index tops out at 100; room for chip + tenure text
# Hairline tick at the 100 ceiling so the #1 bar reads as visibly the longest even in a near-tie
# (e.g. #1=100.0 vs #2=99.9): the leader's navy bar alone reaches the line, the field stops short.
vline_above(fig, 100.0, color=lib.MUTED, width=1.0, dash="dot")
# LABEL the 100 line (AN-01 fix): an unexplained dotted vertical element leaves a strict reader to
# infer its meaning. A small muted label at the top of the line names it as the index ceiling
# (this week's #1 = 100), matching the subtitle's index definition and the hover text. Anchored at
# the line's top end inside the plot, left of the line, so it never strikes the leaders' value labels.
fig.add_annotation(x=100.0, y=1.0, xref="x", yref="paper", text="100 = this week's #1",
showarrow=False, xanchor="right", xshift=-3, yanchor="bottom",
font=dict(size=9.5, color=lib.MUTED))
# Rule-based takeaway, no-spotlight aware: leader streak > leadership change > debut > steady.
lead = cur.iloc[0]
lead_ok = lead["imdb_id"] not in ANIME_NO_SPOTLIGHT
rank1_weeks = ranked[ranked["lane_rank"] == 1].groupby("imdb_id")["w"].agg(set)
lw = rank1_weeks.get(lead["imdb_id"], set())
streak1 = 0
while streak1 in lw:
streak1 += 1
faller = cur[(cur["prev_rank"] == 1) & (cur["lane_rank"] > 1)
& ~cur["imdb_id"].isin(ANIME_NO_SPOTLIGHT)]
debuts = cur[cur["debut"] & ~cur["imdb_id"].isin(ANIME_NO_SPOTLIGHT)].sort_values("lane_rank")
lead_name = clean_title(lead["primary_title"])
runner = cur.sort_values("lane_rank").iloc[1] if len(cur) >= 2 else None
if not lead_ok:
takeaway = "This week's anime Top 10 on the US viewer panel, every series indexed to the board's #1"
elif top_near_tie and runner is not None and (runner["imdb_id"] not in ANIME_NO_SPOTLIGHT):
# Dead heat at the top: disclose it as a TIE and do NOT crown a directional winner. Both round
# to index 100, so a "{lead} a hair ahead" headline would assert an order the shown numbers (and
# data.csv, which also ships 100/100) cannot reconstruct - the sub-100-cap precision behind the
# rank is not disclosed, so the only honest headline is that the two are level this week. This
# keeps the title in agreement with the on-chart near-tie note (no title-vs-annotation conflict).
runner_name = clean_title(runner["primary_title"])
takeaway = (f"{lead_name} and {runner_name} are level atop the US anime board this week, "
f"tied at the top of the index")
else:
if streak1 >= AN_WEEKS:
lead_part = f"{lead_name} has held #1 on the US anime board all {AN_WEEKS}+ weeks we track"
elif streak1 >= 2:
lead_part = f"{lead_name} runs its {_ordinal(streak1)} straight week at #1 on the US anime board"
elif pd.notna(lead["prev_rank"]) and int(lead["prev_rank"]) != 1:
lead_part = f"{lead_name} takes #1 on the US anime board"
else:
lead_part = f"{lead_name} tops the US anime board this week"
if streak1 < 2 and pd.notna(lead["prev_rank"]) and int(lead["prev_rank"]) != 1 and len(faller):
f0 = faller.iloc[0]
takeaway = f"{lead_part}, while {clean_title(f0['primary_title'])} slips from the top spot to #{int(f0['lane_rank'])}"
elif len(debuts):
d0r = debuts.iloc[0]
takeaway = f"{lead_part}, while {clean_title(d0r['primary_title'])} debuts at #{int(d0r['lane_rank'])}"
else:
takeaway = lead_part
# Which special chips actually appear on THIS week's board drives the legend AND the WHY copy, so
# the legend never defines a marker the reader cannot find and the WHY never points at an absent chip.
has_new = bool(len(cur[cur["debut"]]))
has_back = any(chips.get(i) == "BACK" for i in cur["imdb_id"])
what = ("The 10 top-ranked anime series on the US viewer panel this week, ranked on panel viewing weighted by outside "
"corroboration (not audience size alone) and shown as the Anime Pulse Index (this week's #1 = 100). Row "
"tags: the move since last week (green climbed, red slipped, grey held), then straight weeks on the board")
if has_new:
what += "; an amber NEW chip = a first week on the board"
if has_back:
what += "; a grey BACK chip = re-entered the board after a week off"
what += "."
# WHY closes on whichever breakout marker is actually present this week (NEW preferred; else BACK);
# if neither is on the board it stays on the durable-leader point alone, so it never references a
# chip the reader will hunt for and not find.
why = ("Anime audiences are among streaming's most devoted, yet general charts bury the lane behind one or two "
"franchise names. A dedicated board shows the full pecking order: a multi-week run at #1 marks real "
"franchise weight")
if has_new:
why += ", and a NEW chip is a season breakout worth catching early."
elif has_back:
why += ", and a BACK chip flags a series climbing back into contention."
else:
why += "."
cautions = ["the index compares anime series only against each other, never across boards"]
if panel_degraded:
cautions.append("panel volume atypical on this date; rankings use a 7-day basis")
# Tenure-cap gloss: a tenure of 'AN_WEEKS+' means on the board for every week we track, so the
# '+' is explained and the capped number is unambiguous (only shown when a row is actually capped).
tenure_gloss = (f" · {AN_WEEKS}+ wks = on the board every week we track"
if (cur["weeks_on_board"] >= AN_WEEKS).any() else "")
footer = drop_census(lib.assemble_footer(pc_id=reg.get("pc_id", "PC-AN-01"),
caution_labels=cautions,
freshness_date=freshness,
sources=["title_metrics_daily", "categorization_imdb_genres",
"categorization_imdb_ratings", "categorization_platforms_available"],
extra="current and ongoing Japanese-language anime series · excludes adaptations of "
f"adult-only source media{tenure_gloss} · refreshed weekly · metrics decoded at METH-03"))
fig.update_layout(**lib.layout_v2(takeaway, what, width=1180, height=720),
xaxis=lib.standard_xaxis("", showticklabels=False, showgrid=False),
yaxis=lib.standard_yaxis(showgrid=False))
# Near-tie flag ON THE FACE: a sub-1-point index gap is within noise, so the reader is told the top
# is effectively level. Placed in the LOWER-right open space (the short low-rank bars leave it clear)
# so it never collides with the leaders' value labels, while still reading as a top-of-board caveat.
# The text is WORD-WRAPPED to a narrow column (founder overlap fix 2026-06-19): the previous
# single-line notes ran the full plot width and overlapped the low-rank bars' value labels and the
# 100-index dotted ceiling. Wrapped, each note stays a compact block in the clear lower-right corner.
note_y = 0.30
if top_near_tie and lead_ok:
_nt_txt, _nt_lines = lib._wrap(
"Top of board: #1 and #2 both round to 100 on the index, effectively level. The rank order is "
"a sub-point edge too small to show, not a visible gap; the movement chips report last week's "
"rank change, not this week's margin.", width=46)
fig.add_annotation(xref="paper", yref="paper", x=0.985, y=note_y, xanchor="right", yanchor="top",
showarrow=False, align="right",
text=_nt_txt,
font=dict(size=10, color=lib.MUTED), bgcolor="rgba(255,255,255,0.9)")
# drop the next note below this one by its rendered height (line count), so the two stack
# without overlapping each other
note_y -= 0.05 + 0.035 * _nt_lines
lib.add_why_and_footer(fig, why, footer)
# Sidecar obeys the founder display rule: ranks / index / movement / tenure only -
# reach, scores and cred never ship (nothing dividable against a main-board Demand Score).
out = cur[["lane_rank", "imdb_id", "primary_title", "start_year"]].copy()
out["primary_title"] = out["primary_title"].map(clean_title) # no spaced-hyphen in the sidecar
out["anime_pulse_index"] = cur["pulse_index"].round(0).astype(int) # whole numbers, matching the face (no false precision)
out["movement"] = cur["imdb_id"].map(chips)
out["weeks_on_board"] = cur["weeks_on_board"]
out["tenure_capped_at_window"] = cur["weeks_on_board"] >= AN_WEEKS
out["debut"] = cur["debut"]
out["freshness_date"] = freshness
lib.save_csv(out, output_dir)
lib.export_chart(fig, output_dir, width=1180, height=720)
what_plain = re.sub(r"?b>", "", what)
lesson = {"reader_title": takeaway, "reader_subtitle": what_plain, "claim_strength": "strong",
"rules_applied": (f"board-faithful anime lane (override > multi-genre Animation + Japanese language); "
f"recurrent rule (end_year 0 = ongoing); SOFTENED streaming gate (confirmed non-streaming "
f"only); rank basis reach_7d x cred(K_anime={int(K_ANIME)}), NULL-cred excluded; "
f"source blocklist removed {n_blocked} series; {AN_WEEKS} weekly board re-runs drive "
f"movement chips + weeks-on-board; index-only display (no absolute scores ship)")}
lib.write_lesson_design(output_dir, chart_id, f"# {chart_id}\n\n{takeaway}\n\n{what_plain}\n")
write_shim(output_dir, chart_id)
lib.write_manifest(output_dir, chart_id, "ok", reg.get("spec_file", "_anime_section_mock/mock_board.md"),
pc_id=reg.get("pc_id", "PC-AN-01"),
intended_lesson_from_spec="Weekly Anime 10: within-lane board with movement + tenure, index-only display",
rendered_lesson=lesson, row_count=len(cur), freshness_date=freshness,
query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec,
extra={"blocklist_removed": int(n_blocked),
"no_spotlight_on_board": sorted(set(cur["imdb_id"]) & ANIME_NO_SPOTLIGHT)})
return {"status": "ok", "rows": len(cur)}
# The Anime Mover board constants (interpolated into BOTH the logic and rules_applied)
AN_MOVER_COHORT_DAYS = 91 # cohort = series whose US panel debut is within ~13 weeks
AN_MOVER_MIN_AGE_DAYS = 13 # debut + premiere week must not overlap the latest week
AN_MOVER_FLOOR_BPS = 10.0 # latest-week share floor (noise gate, mock-validated)
AN_MOVER_MIN_MULT = 1.1 # only genuine climbers take a bar
AN_MOVER_BARS = 8
# Spotlight reach guard: a title may be the headline subject only if its CURRENT-week reach reaches
# at least this within-cohort index (this week's biggest climber by reach = 100). A multiple is a
# growth rate off a title's own debut, so a tiny title can post a huge multiple off a tiny base; the
# guard stops a small-reach title (e.g. 50.6) being crowned over a large-reach one (e.g. 92.3) as
# "fastest climber". Below the guard the headline frames the whole set with no single-title spotlight.
AN_MOVER_SPOTLIGHT_MIN_INDEX = 50.0