"""SOURCE render logic for TI-AN-02 (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_02(reg: dict) -> dict:
"""The Anime Mover (weekly) - fastest-building anime series new to the US panel in the past 13 weeks
(recency of PANEL ENTRY, not new production): share of
weekly US panel viewing as a multiple of each series' own US PANEL DEBUT week (panel-safe,
L-046 shares; debut anchored on first panel reach, never air date - late-licensed titles
otherwise have unmeasurable climbs)."""
chart_id = "TI-AN-02"
output_dir = THIS_DIR / chart_id / ROLE
conn = lib.connect_readonly()
t0 = time.time()
df = lib.run_query(conn, f"""
WITH d AS (SELECT MAX(file_date) AS d0 FROM title_metrics_daily WHERE geo_code = 'US'),
t0 AS (SELECT MIN(file_date) AS dmin FROM title_metrics_daily WHERE geo_code = 'US'),
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 >= d.d0 - %(cohort_days)s - 7
),
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}
),
deb AS ( -- US PANEL DEBUT = first day the series ever shows US panel reach
SELECT t.imdb_id, MIN(t.file_date) AS debut
FROM title_metrics_daily t JOIN lane l USING (imdb_id)
WHERE t.geo_code = 'US' AND t.reach > 0
GROUP BY t.imdb_id
),
cohort AS ( -- recent debuts only; left-censor guard keeps table-start out of "debuts"
SELECT deb.imdb_id, deb.debut FROM deb, d, t0
WHERE deb.debut >= d.d0 - %(cohort_days)s
AND deb.debut <= d.d0 - %(min_age)s
AND deb.debut > t0.dmin + 7
),
prem AS ( -- premiere-week share of panel (same-window sums: panel swings cancel, L-046)
SELECT c.imdb_id, SUM(t.reach)::numeric AS r,
(SELECT SUM(ph.total_reach) FROM metrics_panel_health ph
WHERE ph.file_date BETWEEN c.debut AND c.debut + 6)::numeric AS tot
FROM cohort c JOIN title_metrics_daily t ON t.imdb_id = c.imdb_id
WHERE t.geo_code = 'US' AND t.file_date BETWEEN c.debut AND c.debut + 6
GROUP BY c.imdb_id, c.debut
),
lat AS (
SELECT c.imdb_id, SUM(t.reach)::numeric AS r,
(SELECT SUM(ph.total_reach) FROM metrics_panel_health ph, d
WHERE ph.file_date BETWEEN d.d0 - 6 AND d.d0)::numeric AS tot
FROM cohort c JOIN title_metrics_daily t ON t.imdb_id = c.imdb_id, d
WHERE t.geo_code = 'US' AND t.file_date BETWEEN d.d0 - 6 AND d.d0
GROUP BY c.imdb_id
)
SELECT c.imdb_id, l.primary_title, l.start_year, c.debut,
10000.0 * prem.r / NULLIF(prem.tot, 0) AS debut_week_share_bps,
10000.0 * COALESCE(lat.r, 0) / NULLIF(lat.tot, 0) AS latest_week_share_bps,
(SELECT d0 FROM d) AS d0
FROM cohort c JOIN lane l USING (imdb_id)
JOIN prem ON prem.imdb_id = c.imdb_id
LEFT JOIN lat ON lat.imdb_id = c.imdb_id;
""", {"cohort_days": AN_MOVER_COHORT_DAYS, "min_age": AN_MOVER_MIN_AGE_DAYS})
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_seasonal.md"),
reg.get("pc_id", "PC-AN-02"), "No recently-premiered anime cohort in the panel")
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["debut_week_share_bps"] = df["debut_week_share_bps"].astype(float)
df["latest_week_share_bps"] = pd.to_numeric(df["latest_week_share_bps"], errors="coerce").fillna(0.0)
df["multiple_vs_debut_week"] = (df["latest_week_share_bps"]
/ df["debut_week_share_bps"].replace(0.0, np.nan))
freshness = str(df["d0"].iloc[0])
elig = df[(df["latest_week_share_bps"] >= AN_MOVER_FLOOR_BPS)
& (df["debut_week_share_bps"] > 0)
& df["multiple_vs_debut_week"].notna()].copy()
# CURRENT-week reach index within the eligible cohort (this week's biggest climber by reach =
# 100), the basis of the spotlight reach guard. Computed before selection so the headline pick
# and the data.csv share one definition.
lane_top = float(elig["latest_week_share_bps"].max()) or 1.0
elig["latest_week_lane_index"] = (elig["latest_week_share_bps"] / lane_top * 100.0).round(1)
climbers = elig[elig["multiple_vs_debut_week"] >= AN_MOVER_MIN_MULT] \
.sort_values("multiple_vs_debut_week", ascending=False).head(AN_MOVER_BARS)
if climbers.empty:
lib.needs_spec_review(output_dir, chart_id, reg.get("spec_file", "_anime_section_mock/mock_seasonal.md"),
reg.get("pc_id", "PC-AN-02"), "No measurable anime climbers above the floor this week")
write_shim(output_dir, chart_id); return {"status": "needs_spec_review"}
# Headline spotlight subject = THE TOP BAR (rebuilt 2026-06-13): this board ranks by climb speed,
# so its own #1 is the steepest climber (climbers is sorted by multiple descending; .iloc[0] is the
# bar drawn at the very top). The navy claim-accent must mark that literal top bar so navy = "the
# chart's #1" with no beat lost reconciling a highlighted lower bar. No-spotlight band excluded
# (ecchi content policy): if the steepest climber is a no-spotlight title, there is no lone hero and
# the whole rising set is framed instead (every bar green). The biggest-current-audience point is no
# longer the navy subject - it is demoted to a small neutral chip below (never navy, never competing
# with the leader=top-bar reading).
spot = climbers[~climbers["imdb_id"].isin(ANIME_NO_SPOTLIGHT)]
t1 = spot.iloc[0] if len(spot) and str(spot.iloc[0]["imdb_id"]) == str(climbers.iloc[0]["imdb_id"]) else None
hero_id = str(t1["imdb_id"]) if t1 is not None else None
# Biggest-current-audience climber among those shown (the point the navy accent USED to carry): a
# secondary, non-navy chip subject. It fires only when it adds value - i.e. when the biggest-audience
# climber is NOT the top bar (otherwise the note is redundant with the navy spotlight) and is itself a
# spotlight-eligible title clearing the reach guard. Drawn as a small neutral (muted) chip so it never
# competes with the leader=top-bar reading; the navy accent stays the chart's single relational marker.
aud_pool = climbers[~climbers["imdb_id"].isin(ANIME_NO_SPOTLIGHT)
& (climbers["latest_week_lane_index"] >= AN_MOVER_SPOTLIGHT_MIN_INDEX)] \
.sort_values("latest_week_share_bps", ascending=False)
aud = aud_pool.iloc[0] if len(aud_pool) else None
aud_id = str(aud["imdb_id"]) if (aud is not None and str(aud["imdb_id"]) != hero_id) else None
plot = climbers.sort_values("multiple_vs_debut_week").reset_index(drop=True) # biggest on top
mults = plot["multiple_vs_debut_week"].astype(float)
# DISPLAYED audience index re-anchored to the top SHOWN climber (= 100): the lane-wide anchor (the
# whole-lane reach leader) is correctly OFF this board (it builds too slowly to be a Mover), so a
# lane index never reached 100 on any drawn bar and the scale's anchor was invisible. Re-basing on
# the biggest-audience bar actually shown makes 100 a bar the reader can see, and matches the legend
# ('biggest current audience of the climbers shown'). The lane-wide index is kept in data.csv and in
# the off-board comparison, which is done on raw share so it does not depend on this display scale.
shown_top = float(plot["latest_week_share_bps"].max()) or 1.0
plot["shown_audience_index"] = (plot["latest_week_share_bps"].astype(float) / shown_top * 100.0).round(1)
reach_idx = plot["shown_audience_index"].astype(float)
ylabels = [lib.ellipsize(clean_title(t), 46) for t in plot["primary_title"]]
# Tie-safe multiple precision: bars are SORTED by the multiple, so two bars that round to the same
# 1-decimal label (e.g. 3.53 and 3.52 -> "3.5x") would hide the order that sorted them. Detect any
# such collision among the rendered set and show 2 decimals everywhere so every bar's label
# reconstructs its own rank; otherwise keep the cleaner 1-decimal form.
r1 = mults.round(1).tolist()
mult_dp = 2 if len(set(r1)) < len(r1) else 1
mult_str = [f"{m:.{mult_dp}f}x" for m in mults]
# Color contract: green = rising (the whole set IS rising). The NAVY claim-accent marks the TOP bar
# (the steepest climber = the board's own #1 by its climb-speed sort), so navy is literally the
# top-of-chart bar and the headline names that same title. If the steepest climber is a no-spotlight
# title there is no lone accent: every bar stays green and the headline frames the whole rising set.
bar_colors = [lib.NAVY if (hero_id is not None and str(i) == hero_id) else lib.GREEN
for i in plot["imdb_id"]]
fig = go.Figure()
# Each bar's outside label carries ONLY the plotted multiple (the one dimension the bar length encodes).
# The former second per-bar "audience index N" scale was REMOVED: it was a second, axis-less numeric
# rescale layered onto every label, defined circularly for the navy bar (navy IS the index-100 bar), and
# it competed with the chart's single lesson (climb speed). The biggest-current-audience-of-those-shown
# distinction now reads from ONE place - the navy claim-accent decoded by the legend - not a number on
# every bar, so the face carries a single scale and a single relational marker. (Index kept in data.csv.)
bar_text = [f" {ms}" for ms in mult_str]
# ZERO-BASED bars (Tufte lie-factor fix): length is proportional to the multiple itself - the
# old base=1.0 bars encoded (multiple - 1), so a 3.9x bar drew ~2.3x the length of a 2.3x bar.
# The dotted 1x line still marks the debut-week level inside every bar.
fig.add_trace(go.Bar(
x=mults, y=ylabels, orientation="h",
marker=dict(color=bar_colors, line=dict(width=0)),
text=bar_text, textposition="outside",
textfont=dict(size=11, color=lib.INK), cliponaxis=False, showlegend=False,
customdata=np.stack([[f"{m:.{mult_dp}f}" for m in mults], plot["debut"].astype(str),
[f"{ri:.0f}" for ri in reach_idx]], axis=-1),
hovertemplate="%{y}
this week reads %{customdata[0]}x its US panel debut week"
"
current audience index %{customdata[2]} (the biggest-audience climber shown here = 100)"
"
first seen in the panel %{customdata[1]}",
))
mx = float(mults.max())
ticks_x = list(range(0, int(np.ceil(mx)) + 1))
# right headroom: the bar label now carries ONLY the short multiple (e.g. "3.9x"), so the
# multiple-axis range needs just enough pad to clear that one token past the longest bar.
fig.update_xaxes(range=[0, mx * 1.18], tickvals=ticks_x,
ticktext=[("1x = its debut week" if t == 1 else f"{t}x") for t in ticks_x])
vline_above(fig, 1.0, color=lib.MUTED, width=1.2, dash="dot")
if t1 is None:
takeaway = "The steepest climbers among series new to the US panel in the past 13 weeks keep building week over week"
else:
hero_name = clean_title(t1["primary_title"])
# The headline names the chart's OWN #1 - the steepest climber, which is the navy TOP bar - so the
# words and the top-of-chart navy accent point at the same title and the reader reconciles nothing.
# Framed strictly on the one dimension the bars encode (climb speed off each title's own debut), the
# superlative the board's climb-speed sort actually proves. The biggest-current-audience point is no
# longer in the headline (a slower-building series can out-draw it); it rides the neutral chip below
# and the footer/sidecar. Multiple printed at the hero bar's own precision (mult_dp), so the title
# never reads "3.5x" while its bar reads "3.53x".
# PRECISION: the cohort is recency of US PANEL ENTRY (first panel-reach day within the cohort
# window), NOT new production. "new anime" implied a freshly produced show; it is now "new to the
# US panel in the past 13 weeks", which names the ACTUAL cohort window (a long-running show newly
# tracked here also qualifies) and matches the footnote's scope EXACTLY, so a strict reader can no
# longer read the looser "this season" as a fixed broadcast quarter.
takeaway = (f"{hero_name} is the fastest-climbing series new to the US panel in the past 13 weeks, building to "
f"{float(t1['multiple_vs_debut_week']):.{mult_dp}f}x its US debut week on the viewer panel")
# Subtitle is two sentences (house rule): what a bar measures, then the single caveat the chart turns on.
# "new to the US panel in the past 13 weeks" (not "recently premiered", not the looser "this season"):
# the cohort is recency of panel ENTRY, not production, and the window is named to match the footnote.
what = ("Each bar is an anime series new to the US panel in the past 13 weeks, its share of weekly US panel viewing shown "
"as a multiple of its own first week in the panel (1x = its debut-week level). A high multiple is fast "
"growth from a title's own small debut, not the largest audience, so the steepest climber is not always "
"the biggest-drawing.")
why = ("A new anime almost never opens at its peak: simulcast audiences compound as episodes land and word of "
"mouth spreads. The steepest climbers are next season's headliners, visible here weeks before they carry "
"Top 10 weight.")
cautions = ["measured on shares of panel viewing, so panel-size swings cancel out"]
if panel_degraded:
cautions.append("panel volume atypical on this date; read multiples with care")
# the display cut is DISCLOSED: more climbers can clear the floor than the board has bars
# (the old footer read as if every qualifying climber were drawn)
n_qual = int((elig["multiple_vs_debut_week"] >= AN_MOVER_MIN_MULT).sum())
shown_note = (f" · the {len(climbers)} steepest of {n_qual} qualifying climbers shown"
if n_qual > len(climbers) else "")
# reach-guard disclosure: the named subject must also clear a minimum current-week reach, so a
# huge multiple off a tiny audience cannot crown the board (base-rate fragility close-out)
guard_note = (" · the fastest climber must also clear a minimum current-week reach to be named"
if t1 is not None else "")
# Ranking-basis disclosure: this board ranks by climb SPEED, not by current audience, so a series
# drawing a larger current audience but building more slowly can sit off the board. Compared against
# the biggest current audience AMONG THE CLIMBERS SHOWN (the chip subject's reach when present, else
# the on-board max) on RAW share (scale-independent), the note fires only when such a bigger-drawing
# title actually exists off-board this week, keeping the climb-speed framing airtight and
# reconstructable from the full-cohort sidecar (e.g. the slower-building lane leader Daemons sits off).
if t1 is not None:
shown_reach_max = float(climbers["latest_week_share_bps"].astype(float).max())
higher_reach_offboard = elig[(~elig["imdb_id"].isin(set(climbers["imdb_id"])))
& (elig["latest_week_share_bps"].astype(float) > shown_reach_max)]
rank_basis_note = (" · ranked by climb speed, not current audience: a slower-building series can "
"draw a larger current audience yet sit off this board"
if len(higher_reach_offboard) else "")
else:
rank_basis_note = ""
footer = lib.assemble_footer(pc_id=reg.get("pc_id", "PC-AN-02"),
caution_labels=cautions,
freshness_date=freshness,
sources=["title_metrics_daily", "metrics_panel_health"],
extra=f"anime series new to the US panel in the past {AN_MOVER_COHORT_DAYS // 7} weeks "
f"· climbers reaching at least 0.1% of weekly panel viewing{shown_note}{guard_note}{rank_basis_note} "
f"· refreshed weekly · metrics decoded at METH-03")
fig.update_layout(**lib.layout_v2(takeaway, what, width=1180, height=640),
xaxis=lib.standard_xaxis("", showgrid=False),
yaxis=lib.standard_yaxis(showgrid=False))
if t1 is not None: # the lone navy accent must self-decode against the green field
lib.add_color_key(fig, f"■ fastest climber (the top bar) "
f"■ other rising climbers")
# Biggest-current-audience chip (neutral, non-navy): a small note INSIDE that climber's own bar
# naming the secondary fact the navy accent used to carry, only when it is a DIFFERENT title than the
# top bar. Placed inside the (long) green bar in white so it stays subordinate and never competes with
# the navy=top-bar reading; it adds no second numeric scale (it is a label, not a value).
if aud_id is not None:
aud_label = next((yl for yl, iid in zip(ylabels, plot["imdb_id"]) if str(iid) == aud_id), None)
if aud_label is not None:
aud_mult = float(plot.loc[plot["imdb_id"].astype(str) == aud_id, "multiple_vs_debut_week"].iloc[0])
fig.add_annotation(x=aud_mult / 2.0, y=aud_label, xref="x", yref="y",
text="biggest current audience of the climbers shown",
showarrow=False, xanchor="center",
font=dict(size=10, color="#FFFFFF"))
lib.add_why_and_footer(fig, why, footer)
# TI-AN display contract (founder-locked): NO cross-comparable absolute levels anywhere,
# data.csv included - the old debut/latest share-of-TOTAL-panel bps columns were exactly such
# a leak. The csv ships momentum multiples plus a WITHIN-LANE index (this cohort's biggest
# latest-week climber = 100), which supports ordering without cross-lane comparability.
# FULL COHORT shipped (every recently-premiered series, not just eligible) so a reader can
# reconstruct the "fastest climber" / "most-watched climber" superlatives end to end: each row
# carries its growth multiple, its current-week reach index, and the eligibility/render/headline
# flags that drove selection.
full = df.copy()
full_top = float(full["latest_week_share_bps"].max()) or 1.0
full["latest_week_lane_index"] = (full["latest_week_share_bps"] / full_top * 100.0).round(1)
out = full.sort_values("multiple_vs_debut_week", ascending=False, na_position="last")[
["imdb_id", "primary_title", "start_year", "debut",
"multiple_vs_debut_week", "latest_week_lane_index"]].copy()
out["primary_title"] = out["primary_title"].map(clean_title) # no spaced-hyphen in the sidecar
out = out.rename(columns={"debut": "us_panel_debut"})
out["eligible_above_floor"] = out["imdb_id"].isin(set(elig["imdb_id"]))
out["rendered"] = out["imdb_id"].isin(set(climbers["imdb_id"]))
# the on-face index uses the re-anchored SHOWN scale (biggest-audience shown climber = 100); ship it
# alongside the lane-wide index so both the chart label and the lane reference reconstruct from the csv.
_shown_map = dict(zip(plot["imdb_id"].astype(str), plot["shown_audience_index"].astype(float)))
out["shown_audience_index"] = out["imdb_id"].astype(str).map(_shown_map)
out["headline_subject"] = (out["imdb_id"].astype(str) == hero_id) if hero_id else False
out["freshness_date"] = freshness
lib.save_csv(out, output_dir)
lib.export_chart(fig, output_dir, width=1180, height=640)
what_plain = re.sub(r"?b>", "", what)
lesson = {"reader_title": takeaway, "reader_subtitle": what_plain, "claim_strength": "strong",
"rules_applied": (f"anime-lane mover anchored on US PANEL DEBUT (first panel-reach day, never air date); "
f"cohort = debut within {AN_MOVER_COHORT_DAYS}d, >= {AN_MOVER_MIN_AGE_DAYS}d old, "
f"left-censor guard; share-of-panel weekly windows (panel-safe); floor latest week "
f">= {AN_MOVER_FLOOR_BPS:.0f} bps; climbers >= {AN_MOVER_MIN_MULT}x, top {AN_MOVER_BARS} "
f"bars; ZERO-BASED bars (length = the multiple itself; dotted 1x line marks debut level); "
f"headline = the TOP BAR = the steepest climber (board's own #1 by climb-speed sort), "
f"navy claim-accent on that top bar (else, if the steepest is a no-spotlight title, "
f"set-level headline, all green); biggest-current-audience climber demoted to a neutral "
f"in-bar chip (non-navy, fires only when it differs from the top bar and clears the "
f"reach guard, lane index >= {AN_MOVER_SPOTLIGHT_MIN_INDEX:.0f}); blocklist removed "
f"{n_blocked} series; no-spotlight band barred from callouts; full cohort shipped in data.csv")}
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_seasonal.md"),
pc_id=reg.get("pc_id", "PC-AN-02"),
intended_lesson_from_spec="Weekly Anime Mover: within-lane share-of-panel climb vs US panel debut week",
rendered_lesson=lesson, row_count=len(climbers), freshness_date=freshness,
query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec,
extra={"blocklist_removed": int(n_blocked),
"no_spotlight_rendered": sorted(set(climbers["imdb_id"]) & ANIME_NO_SPOTLIGHT),
"cohort_size": int(len(df)), "eligible_above_floor": int(len(elig)),
# preview-gate aid: the H1 spotlight pick = the TOP BAR (steepest climber),
# named so the founder's pre-publish pass can band-check new-premiere titles
# the board hazard list has not seen yet
"headline_spotlight_title": (clean_title(t1["primary_title"]) if t1 is not None else None),
"headline_spotlight_imdb_id": (str(t1["imdb_id"]) if t1 is not None else None),
"headline_spotlight_basis": "top bar = steepest climber (board's own climb-speed #1)",
"headline_spotlight_multiple": (round(float(t1["multiple_vs_debut_week"]), 2) if t1 is not None else None),
# the secondary, neutral-chip subject (biggest current audience of those shown),
# named only when it differs from the top bar
"audience_chip_title": (clean_title(aud["primary_title"]) if aud_id is not None else None),
"audience_chip_imdb_id": aud_id,
"spotlight_reach_guard_index": AN_MOVER_SPOTLIGHT_MIN_INDEX})
return {"status": "ok", "rows": len(climbers)}
# Where Anime Lives (monthly platform map) constants
AN_PLAT_BARS = 7 # named platform bars; everything else rolls into one "smaller services" row
AN_PLAT_DEPART_DAYS = 60 # licensing-event chip lookback (subscription/free events only, never TVOD churn)
AN_PLAT_VAULT_MIN_OWN = 60.0 # vault chip fires when >= this % of a shelf is exclusive...
AN_PLAT_VAULT_MIN_CARRY = 3.0 # ...and the platform carries at least this % of the lane
AN_PLAT_CHIP_INSIDE_PCT = 45.0 # chips sit inside the bar when it is at least this long