"""SOURCE render logic for TI-DP-05 (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_DP_05(reg: dict) -> dict: """Baseline Percentile Distribution - BL percentile distribution at latest snapshot.""" chart_id = "TI-DP-05" output_dir = THIS_DIR / chart_id / ROLE conn = lib.connect_readonly() t0 = time.time() df = lib.run_query(conn, """ WITH latest AS (SELECT MAX(file_date) AS file_date FROM title_metrics_daily) SELECT t.imdb_id, t.bl::numeric AS bl, PERCENT_RANK() OVER (ORDER BY t.bl::numeric) AS bl_pct, l.file_date AS freshness_date FROM title_metrics_daily t JOIN latest l USING (file_date) WHERE t.bl IS NOT NULL AND t.di IS NOT NULL AND t.geo_code = 'US'; """) q_sec = time.time() - t0 df = lib.drop_demand_orphans(df, conn) # hide in-theaters / not-yet-streaming demand-orphans conn.close() if df.empty: lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "No BL rows") return {"status": "needs_spec_review"} freshness = str(df["freshness_date"].iloc[0]) bl = df["bl"].astype(float) # Strip zeros for log binning bl_pos = bl[bl > 0] q1, med, q3 = bl.quantile([0.25, 0.5, 0.75]) p99 = float(bl.quantile(0.99)) q1, med, q3 = float(q1), float(med), float(q3) pct_under_10 = (bl < 10).mean() # Integer-aligned EQUAL-WIDTH bins below 10 (baselines are near-integers there; fine log bins # leave a comb of alternating tall/empty bars, and unequal low-end widths like [5,7] print a # fake dip-then-rise), log-spaced above. log_max = np.log10(bl_pos.max()) edges = np.unique(np.concatenate([np.arange(1, 11), np.logspace(1, log_max, 20)])) counts, _ = np.histogram(bl_pos, bins=edges) centers = np.sqrt(edges[:-1] * edges[1:]) # geometric center widths = edges[1:] - edges[:-1] n_zero = int((bl <= 0).sum()) # Concentration the user intuited: top 1% of titles' share of total baseline demand bl_desc = bl.sort_values(ascending=False) top1_share = bl_desc.head(max(1, len(bl)//100)).sum() / bl.sum() fig = go.Figure() fig.add_trace(go.Bar(x=centers, y=counts, width=widths, marker=dict(color=lib.BLUE, line=dict(width=0.5, color="white")), showlegend=False, hovertemplate="baseline around %{x:.0f}
%{y} titles")) title_lesson = (f"A handful of titles carry the catalog: the typical title's everyday demand is just {med:.0f} points " f"on our demand scale, while the top 1% sit above {p99:.0f}") what = ("Baseline demand = a title's normal, everyday demand level between spikes, in Demand Score points. This shows how many titles " "sit at each level - most cluster low, a thin tail runs very high.") why = (f"Your intuition is right: it's a power-law catalog. The top 1% of titles alone account for {top1_share:.0%} of all baseline demand, " "while the bulk of the library ticks along quietly. That's why a few franchises carry a service - and why losing one hurts.") zero_note = f" · {n_zero:,} zero-baseline titles not drawn" if n_zero > 0 else "" fig.update_layout(**lib.layout_v2(title_lesson, what, width=1180, height=620), yaxis=lib.standard_yaxis("Number of titles", minor=dict(ticks="", showgrid=False)), bargap=0, ) lib.set_log_axis(fig, "x", "A title's baseline (everyday) demand, in Demand Score points (log scale)", tickvals=[1, 3, 10, 30, 100, 300, 1000], ticktext=["1", "3", "10", "30", "100", "300", "1,000"]) # Both markers drawn as DATA-coordinate lines through the full bar height: shape-based ref # lines on this log axis land at the wrong x (raw-vs-log10 quirk) and fade behind the bars. y_top = float(counts.max()) * 1.02 for v, label in [(med, "typical (median) title"), (p99, "top 1%")]: data_refline(fig, x=v, lo=0, hi=y_top) fig.add_annotation(x=np.log10(v), y=1.0, yref="paper", xref="x", text=f"{label}
{v:.0f}", showarrow=False, yanchor="bottom", font=dict(size=10, color=lib.MUTED)) lib.add_why_and_footer(fig, why, lib.assemble_footer("PC-DP-07", [], freshness, ["title_metrics_daily"], f"{len(df):,} active titles · log scale on x-axis · equal 1-point bins up to 10, " f"wider log-spaced bins above (so bar heights step up at 10){zero_note}")) lesson = {"reader_title": title_lesson, "reader_subtitle": what, "claim_strength": "strong", "rules_applied": f"log-x; median={med:.0f}, top1%={top1_share:.0%}"} hist_csv = pd.DataFrame({"bin_low": edges[:-1], "bin_high": edges[1:], "n_titles": counts}) lib.save_csv(hist_csv, output_dir) pd.DataFrame([{"median_baseline": med, "p99_baseline": p99, "top1_share_of_baseline": round(float(top1_share), 4), "n_active_titles": len(df), "n_zero_baseline": n_zero}]).to_csv(output_dir / "stats.csv", index=False) lib.export_chart(fig, output_dir, width=1180, height=620) lib.write_lesson_design(output_dir, chart_id, f"# {chart_id}\n\n{title_lesson}\n\n{what}\n") write_shim(output_dir, chart_id) lib.write_manifest(output_dir, chart_id, "ok", reg["spec_file"], pc_id="PC-DP-07", intended_lesson_from_spec="Distribution of BL across active universe", rendered_lesson=lesson, row_count=len(df), freshness_date=freshness, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec) return {"status": "ok", "rows": len(df)}