teqo-backup/src/utilities/territory/territoryIntraCaptureBenchmark.ts
Francisco Ignácio Fontoura Solla 2b3d688be3 Simplify E12+ Metropolitano peers extraction.
Centralize sub-row slug helper, drop one-line filter wrappers, and scope E12 sub-row rollups to the Metropolitano region inputs.
2026-07-29 08:24:19 -03:00

76 lines
2.5 KiB
TypeScript

/**
* E12 — intra-TI capture benchmark (T4) for municipality detail.
*
* Pure over the committed TSE artifact + `municipalityCatalog` (client-safe).
* Peers share the same Território de Identidade (`catalogPeersForSlug`).
*/
import { getMunicipalityFederalBaseline } from '@/lib/bahiaElectionAggregates'
import { medianOf } from '@/lib/median'
import { catalogPeersForSlug } from '@/lib/metropolitanoTerritoryPeers'
import { captureRate } from '@/utilities/municipality/municipalityPotential'
type TerritoryCaptureBeacon = {
slug: string
name: string
captureRate: number
}
export type MunicipalityIntraTerritoryCaptureBenchmark = {
/** This municipality's 2022 capture rate, or null without a field ceiling. */
captureRate: number | null
/** Median capture among peers in the same TI (or Metropolitano sub-group). */
medianCapture: number | null
/**
* `captureRate / medianCapture` when both exist — how many times above/below
* the TI median (T4).
*/
ratioToMedian: number | null
/** Peer with the highest capture in the group (learning reference, not a scoreboard). */
beacon: TerritoryCaptureBeacon | null
}
const benchmarkBySlug = new Map<string, MunicipalityIntraTerritoryCaptureBenchmark>()
export const getMunicipalityIntraTerritoryCaptureBenchmark = (
slug: string,
): MunicipalityIntraTerritoryCaptureBenchmark => {
const cached = benchmarkBySlug.get(slug)
if (cached) return cached
const peers = catalogPeersForSlug(slug)
const rates: Array<{ slug: string; name: string; rate: number }> = []
for (const peer of peers) {
const baseline = getMunicipalityFederalBaseline(peer.slug)
const rate = captureRate(baseline)
if (rate == null) continue
rates.push({ slug: peer.slug, name: peer.name, rate })
}
const baseline = getMunicipalityFederalBaseline(slug)
const municipalityCapture = captureRate(baseline)
const medianCapture = medianOf(rates.map((entry) => entry.rate))
let beacon: TerritoryCaptureBeacon | null = null
for (const entry of rates) {
if (!beacon || entry.rate > beacon.captureRate) {
beacon = { slug: entry.slug, name: entry.name, captureRate: entry.rate }
}
}
const ratioToMedian =
municipalityCapture != null && medianCapture != null && medianCapture > 0
? municipalityCapture / medianCapture
: null
const result: MunicipalityIntraTerritoryCaptureBenchmark = {
captureRate: municipalityCapture,
medianCapture,
ratioToMedian,
beacon,
}
benchmarkBySlug.set(slug, result)
return result
}