#!/usr/bin/env python
"""Build nearby_uchii_writeup/: hardlink all per-region figures (sanitized names, since
graphicx dislikes dots), generate main.tex (summary + per-region atlas), ready for pdflatex.
Regions: all <2kpc members + all curated entries (incl. revealed-excluded, appendix-flagged).
Figures per region: zoom/overview (meerkat_alma/offplane/manual/pg_ostar), SED (sed_figs),
distance profile (extinction_profiles/figs), Gaia onset (figs_gaia) when present."""
import csv
import os
import numpy as np

BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, 'nearby_uchii_writeup')
FIGD = os.path.join(OUT, 'figs')
os.makedirs(FIGD, exist_ok=True)

PG_MAP = {'M8-Hourglass': 'M8_Her36', 'M20-Trifid': 'M20_HD164492A', 'NGC6357': 'NGC6357_Pis24-1'}
ZOOM_ALIAS = {'IRAS18089-1732': 'G012.8909+00.4938B'}


def sanitize(name):
    stem, ext = os.path.splitext(name)
    return stem.replace('.', 'p').replace('+', 'P') + ext


def hardlink(src, prefix=''):
    if not os.path.exists(src):
        return None
    dst = os.path.join(FIGD, prefix + sanitize(os.path.basename(src)))
    if not os.path.exists(dst):
        try:
            os.link(src, dst)
        except OSError:
            import shutil
            shutil.copy(src, dst)
    return 'figs/' + os.path.basename(dst)


def texesc(s):
    return (s.replace('_', r'\_').replace('%', r'\%').replace('&', r'\&')
            .replace('#', r'\#').replace('^', r'\^{}').replace('~', r'\~{}'))


def load_regions():
    regs = []
    with open(os.path.join(BASE, 'master_distances.csv')) as fh:
        for r in csv.DictReader(fh):
            d = float(r['d_best'])
            L = float(r['Lbol_best'])
            if not (r['in_2kpc'] == 'True'):
                continue
            regs.append(dict(name=r['Name'], glon=float(r['GLON']), glat=float(r['GLAT']),
                             d=d, derr=float(r.get('d_err_kpc', 0) or 0), L=L,
                             typ=r['Type'], method=r['method'], ref=r['ref'],
                             conf=r['conf'], origin='RMS', note=''))
    with open(os.path.join(BASE, 'curated_nearby_sample.csv')) as fh:
        for r in csv.DictReader(fh):
            regs.append(dict(name=r['Name'], glon=float(r['GLON']), glat=float(r['GLAT']),
                             d=float(r['Dist_kpc']), derr=0.0,
                             L=float(r['Lbol']), typ=r['Type'], method=r['Dist_method'],
                             ref=r['Dist_ref'], conf='curated', origin='curated',
                             note=r['note']))
    seen, uniq = set(), []
    for r in regs:
        if r['name'] in seen:
            continue
        seen.add(r['name'])
        uniq.append(r)
    return sorted(uniq, key=lambda x: x['glon'])


def region_figs(name):
    out = {}
    for key, path in [
            ('zoom', f'meerkat_alma_figs/{ZOOM_ALIAS.get(name, name)}.png'),
            ('zoom', f'offplane_figs/{name}.png'),
            ('zoom', f'manual_figs/{name}.png'),
            ('zoom', f'pg_ostar_figs/{PG_MAP.get(name, "___none")}.png'),
            ('sed', f'sed_figs/{name}.png'),
            ('dist', f'extinction_profiles/figs/{name}.png'),
            ('gaia', f'extinction_profiles/figs_gaia/{name}.png')]:
        if key in out:
            continue
        rel = hardlink(os.path.join(BASE, path), prefix=f'{key}_')
        if rel:
            out[key] = rel
    return out


HEADER = r"""\documentclass[10pt]{article}
\usepackage[margin=1.8cm]{geometry}
\usepackage{graphicx}
\usepackage{amsmath,amssymb}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{hyperref}
\usepackage{xcolor}
\providecommand{\msun}{\ensuremath{M_\odot}}
\providecommand{\lsun}{\ensuremath{L_\odot}}
\setlength{\parindent}{0pt}
\setlength{\parskip}{4pt}
\title{The Volume-Limited ($d<2$\,kpc) Census of Ultracompact H\,{\sc ii} Regions and
$L>10^4$\,L$_\odot$ Young Stellar Objects:\\ Distances, SEDs, and Source-Scale Luminosity
Distribution}
\author{A. Ginsburg \& Claude (uchii\_2026 analysis session)}
\date{\today}
\begin{document}
\maketitle
% Human-written abstract lives in abstract.tex and is NOT regenerated by
% build_writeup.py -- edit that file (also on Overleaf) to change it.
\IfFileExists{abstract.tex}{\input{abstract}}{}
\tableofcontents
"""


def main():
    regs = load_regions()
    olg = hardlink(os.path.join(BASE, 'fig_olguin_LM.png'))
    tex = [HEADER]

    tex.append(r"""
\section{Summary}
This document compiles the nearby ($d<2$--3\,kpc) ultracompact H\,{\sc ii} region and massive
YSO census built from the RMS survey \citefoot{Lumsden et al. 2013} with per-source literature
distance corrections, a famous-nebula/amateur-catalog completeness audit, an off-plane
IRAS/Akari completeness check, and a 3D-extinction (Gaia + DECaPS) distance analysis.
\textbf{Current sample: $N=47$ within 2\,kpc (one marginal); $N=100$ within 3\,kpc (two
marginal)} ($L\geq10^4$\,L$_\odot$;
UC\,H\,{\sc ii} + embedded MYSO; revealed O-star regions excluded and shown in the Appendix).

\textbf{Headline result} (full uncertainty budget in \S\ref{sec:ladder}): above
$10^5$\,L$_\odot$ the volume holds embedded\,:\,extended-H\,{\sc ii}\,:\,revealed-O
populations in the ratio $1:12\!-\!13:59\!-\!71$, identically in both distance bins.
With the IMF-weighted main-sequence clock ($\langle t_{\rm
MS}(L>10^5)\rangle=4.3$\,Myr) this gives an embedded (potentially accreting) phase
$\tau_{\rm emb}=6\times10^4$\,yr $[4.3\!-\!8.9]\times10^4$ (68\%),
$[2.8\!-\!12]\times10^4$ (95\%), robust at $\tau_{\rm emb}\le1.2\times10^5$\,yr
under every classification and calibration deformation we could construct against
it. A multi-Myr accretion phase through the H\,{\sc ii} stage requires a ratio near
unity and is excluded by a factor $\gtrsim$30--70; the direct far-IR/submm reservoir
census (\S\ref{sec:ostardust}) and the SFR-based proto-O clock (\S\ref{sec:protoO})
independently agree.

\subsection{Luminosity completeness: the SED-reintegration sweep}
The census inherits RMS bolometric luminosities, which can be underestimated for
confusion-flagged sources: the prototype is IRAS 20126$+$4104 (RMS $L=3970$\,L$_\odot$ at
1.4\,kpc vs.\ literature $1.1$--$1.3\times10^4$ at the 1.64\,kpc parallax). We therefore
reintegrated SEDs for all 144 RMS sources with $2.8\times10^3 < L < 10^4$\,L$_\odot$ and
$d<3.5$\,kpc, using dedicated catalog cone-matches (2MASS, AllWISE, MSX6C, AKARI IRC+FIS,
IRAS PSC with quality flags; \texttt{sed\_recalc2.py}). Validation on 27 known members
gives median $L_{\rm int}/L_{\rm RMS} = 1.22$ with 0.22\,dex scatter; crowded fields where
the 60$''$ IRAS match grabs a brighter neighbor are identifiable by unphysical ratios
($>2.6$) and were excluded ($\sim$30 sources; recovering them requires Hi-GAL-grade
deblended photometry). Six trusted threshold-crossers survive distance re-vetting
(extinction jumps + parallaxes) and enter the sample: IRAS 20178$+$4046 (1.4\,kpc, the
one new $d<2$\,kpc member), G286.21, G318.95A, G059.78 (parallax 2.16), G188.80 (S252,
parallax 2.10), G019.61; IRAS 20126 itself lands at $8\times10^3$\,L$_\odot$ (1.64\,kpc)
--- within the method scatter of the threshold --- and is retained as a flagged marginal
member. The S235 pair, by contrast, \emph{drops out}: the Burns parallax (1.56\,kpc)
pulls its rescaled luminosity below $10^4$. Net effect: the $10^4$\,L$_\odot$ boundary is
fuzzy at the $\pm$0.2\,dex level; we estimate $\lesssim$5--10 additional members hide in
the excluded crowded-field subset, all at $L\approx1$--$2\times10^4$ --- enough to
perturb the lowest LF bin by $\sim$10--25\% but none of the high-luminosity conclusions.

The same undercounting mechanism reaches below the sweep floor. A targeted audit of the
RCW and Sharpless catalogues against the RMS survey recovered \textbf{RCW\,36} (Vela\,C,
G265.1438$+$01.4548): RMS assigned $L=670$\,L$_\odot$ because it fit a single embedded YSO
rather than the extended nebula, placing it below even the sweep's $2.8\times10^3$ floor.
Per-catalogue SED reintegration gives $L_{\rm int}\approx1.5\times10^4$\,L$_\odot$ at the
extinction-confirmed distance (Edenhofer dust wall at 944\,pc, matching the Vela\,C
distance of \citefoot{Zucker et al. 2020}, 933\,pc; RMS had used 0.7\,kpc), ionized by an
O9V$+$B1.5 pair \citefoot{Bik et al. 2022}. It is added as a revealed/borderline low-$L$
member. The audit found no other clean nearby recoveries: the remaining threshold-crossers
(Sh2-38 at $l=11.9^\circ$; two Cygnus-X sources adjacent to the DR21 ridge) all lie in
confused complexes where the IRAS aperture samples complex-wide emission, and are held as
flagged candidates pending Hi-GAL deblending.

\subsection{Distance methodology}
Every sightline was checked against three 3D dust maps (Edenhofer+2024 Gaia BP/RP cube to
1.25\,kpc; Bayestar19 for $\delta>-30^\circ$; the DECaPS southern-plane map), with jump
(cloud) distances extracted from extinction-density profiles, Bayestar posterior samples for
uncertainties, Zucker+2020 per-cloud anchors, and Gaia DR3 cluster/association distances.
Fifteen distances were revised (largest: RCW108-IR $2.0\to1.26$\,kpc; AFGL4029 $2.9\to2.2$\,kpc
= W5; G348.53 $2.84\to3.38$\,kpc = RCW122), and 19 kinematic distances were independently
confirmed within 15\%. Median distance uncertainty of the final RMS-side sample: 8\%.
VLBI maser parallaxes and Gaia cluster distances are never overridden: toward opaque clumps
optical extinction jumps trace the foreground screen only (verified 0.7--0.9$\times$ bias on
maser-anchored sightlines).

A source-by-source crossmatch with kinematically measured protostellar masses (DIHCA VII)
is deferred to Appendix~B, as it concerns individual-source systematics rather than the
population-level argument of this document.
""")

    lf = hardlink(os.path.join(BASE, 'fig_lf_deficit_2and3kpc.png'))
    als1 = hardlink(os.path.join(BASE, 'fig_als_topdown.png'))
    als2 = hardlink(os.path.join(BASE, 'fig_als_lf.png'))
    lfh = hardlink(os.path.join(BASE, 'fig_lf_hist_2and3kpc.png'))
    lfk = hardlink(os.path.join(BASE, 'fig_lf_kde_2and3kpc.png'))
    lfc = hardlink(os.path.join(BASE, 'fig_lf_counts_2and3kpc.png'))
    lfcum = hardlink(os.path.join(BASE, 'fig_lf_cumulative_2and3kpc.png'))
    if lf:
        tex.append(r"""
\section{The H\,{\sc ii}-region luminosity-function deficit: full methodology}
\label{sec:lfdeficit}

\subsection{The diagnostic}
Mottram et al.\ (2011, M11) introduced, and Padoan \& Gieles (2026, P\&G) reinterpreted, a
lifetime diagnostic built from the ratio of two luminosity functions (LFs) in the same
volume. If star formation is in steady state, every OB star of luminosity $L$ passed
through an embedded (compact-H\,{\sc ii}/MYSO) phase at approximately the same $L$, so the
number ratio at fixed $L$ measures a timescale ratio:
\begin{equation}
\frac{\phi_{\rm emb}(L)}{\phi_{\rm OB}(L)}
 \;=\; \frac{t_{\rm emb}(L)}{t_{\rm MS}(L)},
\qquad \phi(L) \equiv \frac{dN}{d\log L}\bigg|_{d<3\,{\rm kpc}} .
\label{eq:ratio}
\end{equation}
M11 read the declining ratio as a lifetime that shrinks with $L$; P\&G instead let the
star grow in mass (and hence $L$) during the phase, so the declining ratio constrains a
growth law. The two readings are degenerate in Eq.~\ref{eq:ratio} alone; they separate
when the \emph{extended} H\,{\sc ii} population and independent clocks
(\S\ref{sec:protoO}) are added. All previous applications used flux-limited samples;
here every term is evaluated in a volume-limited $d<3$\,kpc sphere with distance-vetted
members (median uncertainty 8\%; \S2), which removes the Malmquist-type corrections that
dominated earlier error budgets.

\subsection{The three populations}
\textbf{(i) Embedded census} ($N=91$): the sample of this paper --- RMS-selected
UC/compact H\,{\sc ii} regions and $L>10^4$\,L$_\odot$ MYSOs plus the curated non-RMS
additions, with the 2026 3D-extinction distance revisions applied and luminosities
rescaled as $L \propto d^2$ (\texttt{master\_distances.csv}, assembled by
\texttt{write\_sample\_lists.py}; loading logic replicated in \texttt{pg\_lf\_final.py}).

\textbf{(ii) Extended H\,{\sc ii} regions} ($N=231$ with $L\geq10^4$, $r>0.15$\,pc): the
WISE Catalog of Galactic H\,{\sc ii} Regions (Anderson et al., V2.3), restricted to
radio/H$\alpha$-confirmed ``K'' entries with catalog distances $d<3$\,kpc. The catalog's
photometry columns are unpopulated for most rows, so we performed our own 22\,$\mu$m
aperture photometry (\texttt{wise\_lf\_photometry.py}): allWISE W4 cutouts via
\texttt{hips2fits}, a circular aperture at the catalog radius $R$ (capped at 900$''$), a
background annulus at $(1.3\mbox{--}1.8)R$, and the background-subtracted, relative flux
$f_{22} = \sum (I - \tilde I_{\rm bg})\,\Omega_{\rm pix}$. Because the HiPS zeropoint is
uncertain, we calibrate \emph{self-consistently} on our own census: for the 76 sample
members with known $L_{\rm bol}$ we measured the identical quantity and fit a fixed-slope
offset,
\begin{equation}
\log L_{\rm bol} = \log\!\left(f_{22}\,d^2\right) + C, \qquad
C = {\rm median}\!\left[\log L_{\rm bol} - \log(f_{22} d^2)\right] = -2.47,
\label{eq:l22}
\end{equation}
with a robust scatter of 0.35\,dex (MAD). Compact duplicates of population (i) are removed
with a physical-radius cut $r = R\,d > 0.15$\,pc. Output:
\texttt{wise22\_photometry.csv}, \texttt{wise\_hii\_3kpc.csv}.

\textbf{(iii) OB stars} ($N=2837$ in the fitted range at $d<3$\,kpc): the Alma Luminous
Star catalogue (ALS\,II), distances from the \texttt{DistMode} Gaia column, spectral types
parsed to luminosities via a ZAMS calibration ($\log L$ from O3:5.8 to B3:3.4 for class V)
plus luminosity-class boosts ($+0.25$ for III up to $+0.7$ for I); implemented in
\texttt{pg\_lf\_final.py} (\textsc{spt\_l}, \textsc{class\_boost} tables), $\pm0.2$\,dex
per star. The class-V default is deliberate: luminosity class is a surface-gravity
diagnostic, and the zero-age main sequence is the maximum-gravity, most-compact state, so a
newly formed or recently emerged O star is expected to be a dwarf. Figure~\ref{fig:martins}
plots the \citefoot{Martins, Schaerer \& Hillier 2005, A\&A 436, 1049 --- retrieved
reproducibly from the arXiv e-print astro-ph/0503346 (\texttt{martins2005\_fetch.py}); these
calibration tables are not in VizieR} calibration by luminosity class: the dwarf (V) locus is
the lowest $L(M)$ and $Q_0(M)$ track, so defaulting an unknown-class star to V assigns the
minimum luminosity consistent with its spectral type --- the conservative, non-inflating
choice for the denominator. Two caveats temper the ZAMS-equals-V expectation: Martins fixes
$\log g_{\rm spec}=3.92$ for the dwarf sequence, whereas a true ZAMS O star has
$\log g\approx4.1$--$4.2$, so the strict zero-age floor lies $\sim$0.1--0.15\,dex below the V
track; and above $\sim$40--60\,M$_\odot$ stars leave the ZAMS on a formation-comparable
timescale and drive winds strong enough to push the class-defining lines into emission (Of /
WNh), so the most massive objects can first appear as giants/supergiants while still young.
The class assumption costs $\sim$0.24\,dex at 40\,M$_\odot$ (V/III/I $=5.53/5.72/5.77$) rising
to $\sim$0.44\,dex at 25\,M$_\odot$. Figure~\ref{fig:als} shows this population directly: the top-down view
(spiral-arm segments, the Carina and Cygnus concentrations, and the low-density inter-arm
volume around the Sun) and the fine-binned luminosity function
(\texttt{make\_als\_figs.py}). A Salpeter IMF mapped through the ZAMS $L(m)$ relation and
normalized to the lowest-luminosity bin tracks the observed LF well over
$3.5\lesssim\log L\lesssim5.3$ before falling below it at the highest luminosities, where
evolved supergiants boosted above their ZAMS luminosity accumulate; the KDE with a
bootstrap band shows the same shape free of binning artifacts. The agreement with
Salpeter normalized only at the low end is the sanity check that the ALS denominator in
Eq.~\ref{eq:ratio} carries no strong luminosity-dependent incompleteness over the fitted
range.

An independent and far larger check on the OB denominator has just become available:
\citefoot{Quintana et al. 2026, arXiv:2607.07068 --- Gaia DR3 census of OB stars within
2\,kpc, Paper I} assemble a Bayesian SED-fitted census of $N=105{,}971$ OB stars within
2\,kpc that is $>$95\% complete at all magnitudes (the only significant gap is the faint,
heavily obscured tail behind Cyg\,OB2). Because it is drawn from Gaia astrometry rather
than heterogeneous spectral-type compilations and supplies HR-diagram luminosities
directly, it corroborates our central assumption --- that the revealed-OB population, the
denominator of Eq.~\ref{eq:ratio}, is essentially complete within a few kpc --- and
independently establishes that the ``missing O-star'' problem is \emph{not} a shortfall of
\emph{revealed} O stars (those are nearly all catalogued), so any luminosity-function
deficit must reside in the embedded/forming or short-lived evolutionary phases, exactly
where our census operates. Substituting their SED luminosities for the ALS spectral-type
inversion is the natural next refinement of the denominator; on the volume we share
($r<2$\,kpc) it would remove the $\pm0.2$\,dex per-star type-to-$L$ scatter without
changing the deficit's sign.

\subsection{Process}
(1) Histogram all three populations in $\log L$ with 0.25\,dex bins over
$4.0\le\log L\le6.25$. (2) Form the ratio of Eq.~\ref{eq:ratio} with and without
population (ii) added to the numerator; propagate Poisson errors per bin,
$\sigma_r/r = (1/N_{\rm num} + 1/N_{\rm den})^{1/2}$. (3) Convert ratios to timescales
with $t_{\rm MS}(L)$ from standard tracks. (4) Repeat at both $d<2$ and $d<3$\,kpc: the
2\,kpc volume has the best-vetted distances but small counts; the 3\,kpc volume carries
the statistics. The result (Figure~\ref{fig:lf}):

\begin{center}
\small
\begin{tabular}{c|ccc|ccc|c}
\hline
 & \multicolumn{3}{c|}{$d<2$ kpc} & \multicolumn{3}{c|}{$d<3$ kpc} & \\
$\log L$ & emb & ext & $\phi_{\rm e}/\phi_{\rm OB}$ & emb & ext & $\phi_{\rm e}/\phi_{\rm OB}$ & $t_{\rm emb}$ [yr]\\
\hline
4.12 & 21 & 10 & 0.037 & 40 & 20 & 0.042 & $\sim$5.8e5\\
4.38 & 12 & 19 & 0.047 & 21 & 38 & 0.045 & $\sim$4.6e5\\
4.62 & 3 & 19 & 0.010 & 15 & 41 & 0.027 & $\sim$2.1e5\\
4.88 & 4 & 15 & 0.023 & 6 & 39 & 0.018 & $\sim$1.1e5\\
5.12 & 1 & 18 & 0.006 & 5 & 32 & 0.017 & $\sim$8.1e4\\
5.38 & 2 & 14 & 0.031 & 2 & 32 & 0.015 & $\sim$5.9e4\\
5.62 & 0 & 9 & $<$0.026 & 1 & 19 & 0.016 & ---\\
5.88 & 1 & 5 & 0.059 & 1 & 10 & 0.028 & ---\\
\hline
\end{tabular}
\end{center}
The two volumes agree bin-by-bin within Poisson errors ($t_{\rm emb}$ quotes the 3\,kpc
values; the 2\,kpc ratios scatter around them with $N\leq4$ per high-$L$ bin). The
combined-with-extended ratio rises with $L$ in both volumes (to 0.24--0.35 above
$\log L = 5.3$), so neither the deficit nor its fill-in is driven by the $2$--$3$\,kpc
shell (where kinematic distances are less certain) or by the boundary objects at
$d\approx1.9$\,kpc (W3, M17).

\subsection{Findings and interpretation}
\textbf{The deficit is real.} The embedded-to-OB ratio falls by a factor $\sim$3 from
$\log L = 4.2$ to $5.4$ in a volume-complete sample --- it is not a flux-limit artifact of
the RMS selection.
\textbf{It is filled --- overfilled --- by the extended population.} Adding the WISE
extended regions makes the combined ratio \emph{rise} with $L$: the luminous compact
H\,{\sc ii} regions are not missing, they have expanded past the compact stage. The
deficit therefore measures the compact-phase duration, not hidden stellar growth:
inverting Eq.~\ref{eq:ratio} bin by bin gives $t_{\rm emb}\propto L^{-0.55}$, i.e.\
$t_{\rm emb}\propto m^{-1.7}$ and a time-averaged accretion rate
$\langle\dot M\rangle = m/t_{\rm emb} \propto m^{2.7}$ reaching
$\sim$$10^{-3}$\,M$_\odot$\,yr$^{-1}$ at 40\,M$_\odot$
(\texttt{formation\_timescale\_vs\_mass.md}); the independent proto-O count clock of
\S\ref{sec:protoO} gives the same answer.

\subsection{Caveats}
(1) The 22\,$\mu$m-only luminosities carry 0.35\,dex scatter; Eddington bias inflates the
high-$L$ extended counts. (2) Population (ii) luminosities are region-integrated
(several OB stars per region) while population (iii) counts stars; this biases the
\emph{combined} ratio shape but not the embedded/OB deficit itself. (3) All luminosities
are isotropic ($4\pi d^2 F$); for individual edge-on sources $L_{\rm iso}$ can
underestimate $L_{\rm tot}$ by factors of several (the flashlight effect), which averages
out in LF statistics but matters for source-by-source comparisons (Appendix~B).

\subsubsection{The Carina apertures, dissected}
Carina (2.35\,kpc) is the best-characterized OB complex in the sample and illustrates the
merged-aperture problem concretely. Four WISE-catalog ``K'' entries at $285.5<l<289.5$
survive our cuts. Three are modest ($L_{22} = 3\times10^4$--$1.4\times10^5$, radii
1--4\,pc). The fourth, G287.524$-$00.735, has the catalog radius capped at our
$900''$ limit --- \textbf{10.7\,pc} at 2.46\,kpc --- and contains \emph{both} Tr\,16
(with $\eta$\,Car, 460$''$ from aperture center) \emph{and} Tr\,14 (693$''$). Its
22\,$\mu$m-calibrated luminosity is $2.5\times10^7$\,L$_\odot$, about twice the
Smith \& Brooks integrated far-IR luminosity of the whole nebula
($\sim$$1.2\times10^7$\,L$_\odot$) --- the excess reflecting our compact-aperture
calibration applied to a PDR-filled 900$''$ beam. The stellar content of that single
aperture, from the Smith (2006) census, is approximately: $\eta$\,Car itself
($L\simeq5\times10^6$, roughly half the aperture's inferred output), 3 WNH stars
($\sim$$10^6$ each), $\sim$30 O stars spanning $\log L = 4.8$--$6.2$ (including
HD\,93129A, O2\,If*), and hundreds of B stars. In LF terms this enters the numerator
\emph{once} at an off-scale luminosity ($\log L = 7.4$, above our 6.25 binning ceiling,
so it does not corrupt the plotted bins), while its $\sim$30 O stars enter the ALS
denominator \emph{individually}. The $\log L = 5.5$--$6.25$ extended bins are populated
instead by M17- and M16-class merged apertures ($L_{22}\approx10^7$ for G015.10 and
G016.99, likely $\times$2--3 inflated for the same reason). The direction of all these
biases is the same: they exaggerate the \emph{rise} of the combined ratio at high $L$,
but cannot manufacture the fill-in itself --- redistributing the merged-aperture flux
into lower bins only moves extended counts to luminosities where the fill-in is already
established. The region-vs-star bookkeeping asymmetry is the fundamental limitation of
LF-ratio diagnostics at cluster scales, and is why the direct source-by-source census of
\S\ref{sec:direct} matters.

\subsection{The count ladder and its uncertainty budget}\label{sec:ladder}
Everything in this document compresses to one dimensionless measurement, evaluated
independently in the two volume-complete bins (\texttt{ladder\_uncertainty.py}):

\begin{center}
\begin{tabular}{l|ccc|c}
\hline
 & embedded & extended H\,{\sc ii} & revealed O & O\,:\,embedded \\
\hline
$d<2$\,kpc, $L>10^5$\,L$_\odot$ & 4 & 48 & 284 & 71 \\
$d<3$\,kpc, $L>10^5$\,L$_\odot$ & 9 & 109 & 527 & 59 \\
\hline
\end{tabular}
\end{center}

The same $1:12\!-\!13:59\!-\!71$ ladder appears in both volumes --- two nearly independent
measurements agreeing at the $\sim$15\% level. In steady state the number ratio is the
lifetime ratio, so the entire argument reduces to: how uncertain is that factor
$\sim$70, and what clock does it multiply?

\paragraph{Statistical uncertainty.} Treating the 0--2 and 2--3\,kpc shells as
independent Poisson experiments with a common ratio $\rho=N_{\rm O}/N_{\rm emb}$
(embedded counts 4 and 5; O-star counts 284 and 243) and profiling out the shell
normalizations gives
\[
\rho = 69\;[49\!-\!101]~(68\%),\;[36\!-\!153]~(95\%).
\]
The dominant term is Poisson noise on the embedded count --- everything else is
subdominant. A per-source Monte Carlo that jitters every object in all three
populations by its own $\sigma_{\log L}$ (0.17\,dex protostars, 0.21\,dex OB stars,
0.39\,dex extended H\,{\sc ii}) and its own distance error, thereby including
Eddington bias across the $L=10^5$ threshold in numerator and denominator alike,
returns $\rho = 76\,[59\!-\!105]$ ($d<2$\,kpc) and $54\,[46\!-\!66]$ ($d<3$\,kpc) ---
consistent with the Poisson interval and confirming that measurement scatter does not
move the ratio.

\paragraph{Classification robustness.} The nine numerator members are listed
explicitly (W3\,IRS5, W3\,(main), M17, W33, NGC\,7538, RCW\,38, NGC\,3576,
G333.6$-$0.2, G333.1$-$0.4). Deforming the classification \emph{against} the
conclusion: promoting every extended H\,{\sc ii} region compact enough to be
plausibly miscategorized ($r<0.4$\,pc) with $L>10^5$ into the numerator adds
\textbf{zero} sources --- no such object exists in either volume; the smallest
$L>10^5$ extended regions are $\gg$1\,pc. Deforming in the other direction
(dropping the semi-revealed RCW\,38) raises the ratio to 95/66. The classification
freedom is therefore bounded: $59 \le \rho \le 95$ under every reassignment we could
construct.

\paragraph{The one anti-conservative systematic, bounded.} Our spectral-type
inversion boosts luminosity classes III/I above their ZAMS luminosity, inflating the
denominator at fixed $L$. Stripping \emph{every} class boost (counting only stars
whose ZAMS-calibration luminosity exceeds $10^5$) shrinks the denominator to
185/323 and the ratio to 46/36. That is the hardest floor we can build against
ourselves: $\rho \ge 36$.

\paragraph{The clock.} The ratio multiplies the time a star spends on the main
sequence with $L>10^5$\,L$_\odot$. Using Ekstr\"om-type lifetimes and ZAMS
luminosities with a Kroupa/Salpeter high-mass slope, the IMF-weighted mean is
$\langle t_{\rm MS}(L>10^5)\rangle = 4.3$\,Myr (individual masses span 0--6.5\,Myr;
the average is pulled down by 22--28\,M$_\odot$ stars that cross $10^5$ only late in
their main sequence). Then
\[
\tau_{\rm emb} \;=\; \frac{\langle t_{\rm MS}\rangle}{\rho}
\;=\; 6\times10^4\;{\rm yr}\;\;[4.3\!-\!8.9]\times10^4~(68\%),\;\;
[2.8\!-\!12]\times10^4~(95\%),
\]
and even at the anti-conservative floor $\rho=36$, $\tau_{\rm emb}\le1.2\times10^5$\,yr.
An accretion phase of $\sim$4\,Myr (Padoan \& Gieles) corresponds to $\rho\approx1$
and is excluded at $\gg$5$\sigma$ by counting alone.

\paragraph{Systematics ledger.} Every remaining known systematic biases
$\tau_{\rm emb}$ \emph{upward} (i.e., our numbers are upper limits):
\begin{center}
\small
\begin{tabular}{l l l}
\hline
systematic & size & direction on $\tau_{\rm emb}$ \\
\hline
embedded $L$ is protocluster-integrated & bins shift up & numerator inflated $\to$ $\tau$ over \\
41--47\% of ALS rows lack a parseable type & denominator under & $\tau$ over \\
current local OB overdensity (Quintana) & recent SFR high & numerator should be high $\to$ $\tau$ over \\
7/9 numerator members lack hot cores & --- & $\tau$ is a ceiling on \emph{accretion} time \\
RMS $|l|<10^\circ$ exclusion & $\le$10\% of denom.; numerator curated & negligible \\
class-III/I luminosity boost & $\rho\ge36$ floor & bounded above \\
$T_d$, $\kappa_\nu$ in reservoir limits & $\times$3--4 for 20--50\,K & fraction below line robust \\
\hline
\end{tabular}
\end{center}

\paragraph{Closing the ionized-accretion escape.} A remaining loophole is accretion
during the extended-H\,{\sc ii} phase from gas that carries no dust signature ---
ionized or atomic material inside the region. The Bondi rate closes it, and the
closure is fundamentally a \emph{luminosity} argument. For a 30\,M$_\odot$ star in
$8000$\,K photoionized gas ($c_s\simeq10$\,km\,s$^{-1}$) the accretion radius is
$R_B = 2GM/c_s^2 \approx 530$\,au, and at the measured interior densities of evolved
regions ($n_e \approx 10$--$100$\,cm$^{-3}$) $\dot M_B \approx 7\times10^{-10}$\,M$_\odot$/yr
--- five to six orders of magnitude short. Since $\dot M_B \propto n_e$, reaching
$10^{-4}$\,M$_\odot$/yr requires $n_e \approx 1.4\times10^7$\,cm$^{-3}$ inside
$R_B$. But an ionized flow at that density announces itself: its emission measure
is $\sim$$5\times10^{11}$\,pc\,cm$^{-6}$ --- an extreme \emph{hypercompact}
H\,{\sc ii} region, optically thick in the radio and mm-bright --- and its
recombination rate within $R_B$ alone is $n_e^2\alpha_B V \approx
1\times10^{50}$\,s$^{-1}$, more than \emph{double} the total ionizing output of
even an O3 supergiant ($Q_0 = 6\times10^{49}$\,s$^{-1}$; Martins et al.\ 2005,
Fig.~\ref{fig:martins}). The star being grown cannot keep its own accretion flow
ionized: the flow recombines, becomes neutral and dusty, and reverts to exactly
the embedded, dust-detectable configuration our reservoir census
(\S\ref{sec:ostardust}) rules out. At $10^{-3}$\,M$_\odot$/yr the requirement is
$10^{52}$\,s$^{-1}$ --- the ionizing output of an entire young massive cluster.
Because the required $Q_0$ scales as $\dot M^2$, ionized accretion at the P\&G
rates is photon-starved by 2--3 orders of magnitude no matter the stellar type:
the region either recombines (and is then an embedded source, counted in the short
rung) or the gas is genuinely at the observed $n_e\lesssim10^2$ (and then
$\dot M_B$ is negligible). There is no intermediate configuration in which
multi-Myr growth hides inside an extended H\,{\sc ii} region without either a
detectable dust reservoir or a wildly over-luminous free-free source --- and the
extended regions' measured free-free luminosities correspond to their measured
low densities. Moreover the sign is wrong throughout: photoionized gas at
$\sim$$10^4$\,K around an O star is overpressured and flows \emph{outward}
(thermal expansion, champagne flows), not inward.

\paragraph{Implied accretion rates.} The ladder converts directly into the
steady-state accretion rates it permits (\texttt{maccr\_constraint.py}). For a mass
threshold $m_1$ (mapped from the $L$ threshold via the ZAMS), steady state gives
$\dot M(m_1) = \langle m_{\rm f}-m_1\rangle_{\rm IMF}\,\rho(m_1)/\langle t_{\rm
MS}\rangle$. Scanning the threshold:

\begin{center}
\small
\begin{tabular}{ccccl}
\hline
$\log L$ & $m_1$ [M$_\odot$] & $N_{\rm emb}/N_{\rm OB}$ ($<$3\,kpc) & $\rho$ [68\%] &
$\dot M$ [M$_\odot$/yr, 68\%] \\
\hline
4.65 & 20 & 19/969 & 55 [44--70]   & $1.9\,[1.5\!-\!2.5]\times10^{-4}$ \\
4.80 & 23 & 14/803 & 63 [48--85]   & $2.6\,[2.0\!-\!3.5]\times10^{-4}$ \\
5.00 & 28 &  9/527 & 69 [49--101]  & $3.5\,[2.5\!-\!5.1]\times10^{-4}$ \\
5.20 & 34 &  4/315 & 118 [68--230] & $7.2\,[4.1\!-\!14]\times10^{-4}$ \\
5.40 & 43 &  2/180 & 224 [92--627] & $1.6\,[0.7\!-\!4.5]\times10^{-3}$ \\
\hline
\end{tabular}
\end{center}

Two readings. First, the \emph{constant-rate} fit over the whole $m>20$ climb gives
$\dot M = 1.9\times10^{-4}$\,M$_\odot$/yr (Salpeter tail; $1.2\times10^{-4}$ for a
steep $s_{\rm f}=3.35$ tail), i.e.\ 20$\rightarrow$30\,M$_\odot$ in
$\sim$5--8$\times10^4$\,yr, 20$\rightarrow$60 in $\sim$2--3$\times10^5$\,yr, and
20$\rightarrow$120 in $\sim$5--8$\times10^5$\,yr. The rate is constrained to a
factor $\sim$2 at 68\% at the low thresholds (Poisson-dominated), degrading to a
factor $\sim$3--7 above $m_1\approx35$ where the numerator holds 2--4 sources.
Second, the scan is \emph{not} flat: the implied rate rises by a factor $\sim$8
from $m_1=20$ to 43, $\dot M\propto m^{2.8}$, with the $m_1=20$ and $m_1=34$
intervals disjoint at 68\%. The data therefore prefer \emph{accelerating}
accretion --- consistent with the independent Kelvin--Helmholtz/non-relaxation
argument that $\dot M\propto m^{2.7}$ reaching $10^{-3}$\,M$_\odot$/yr at
40\,M$_\odot$ --- and any protocluster inflation of the luminous numerator only
\emph{suppresses} this trend, so the acceleration is if anything underestimated.
Integrating $\dot M\propto m^{2.8}$ normalized at the $m_1=20$ value gives a total
20$\rightarrow m_{\rm f}$ climb that \emph{converges} to
$\approx6\times10^4$\,yr for any final mass: the most massive stars finish
assembly essentially as fast as 30\,M$_\odot$ stars --- the diametric opposite of
a formation time growing as $m^{1/2}$ to Myr scales. Caveats: the thresholds are
nested (correlated Poisson draws), the IMF-tail choice moves absolute rates by a
factor $\sim$1.6, and the two highest thresholds rest on 2--4 objects; but even
the most conservative combination (lowest threshold, steep tail, 95\%-low ratio)
requires $\dot M\gtrsim8\times10^{-5}$\,M$_\odot$/yr --- two orders of magnitude
beyond the strongest Bondi rate available to a revealed star, achievable only in
the embedded, dust-rich configuration.

\subsection{The role of the extended-H\,{\sc ii} phase}\label{sec:extphase}
The extended population is not just a correction term --- it is a measured phase in its
own right. Applying Eq.~\ref{eq:ratio} to the extended regions alone,
$t_{\rm ext}(L) = (\phi_{\rm ext}/\phi_{\rm OB})\,t_{\rm MS}(L)$ gives
$t_{\rm ext} \approx 0.6$--$1.2$\,Myr across $4.4 < \log L < 5.6$, roughly independent
of luminosity (mildly rising). This matches the molecular-cloud clearing timescales
measured in nearby galaxies and simulations ($\sim$1--3\,Myr) and quantifies the
evolutionary sequence: a massive star spends $\sim$0.5--5$\times10^5$\,yr (mass-dependent,
\S2.4) in the compact/embedded phase, then $\sim$1\,Myr ionizing an expanding, extended
H\,{\sc ii} region while its natal clump disperses, then the balance of its
few-Myr main-sequence lifetime as an optically revealed field or cluster star. Two
implications. First, the extended phase is where any multi-Myr accretion window
(P\&G's hypothesis) would have to live --- the compact phase is demonstrably too short.
Second, the exciting stars of extended regions are largely optically revealed (many
already appear in ALS), so the same direct reservoir tests that we applied to compact
regions apply to them: that census is \S\ref{sec:direct}, and it finds the gas that
remains during the extended phase is not organized into accretion reservoirs at the
stars.

\medskip
\noindent\textbf{Code:} \texttt{pg\_lf\_final.py} (LFs, ratios, figure);
\texttt{wise\_lf\_photometry.py} (WISE 22\,$\mu$m photometry + calibration);
\texttt{apply\_distance\_revisions.py}, \texttt{extinction\_profiles*.py} (distance
vetting feeding the census); \texttt{olguin\_crossmatch.py} ($L$--$M_{\rm dyn}$);
\texttt{build\_ostar\_sample.py} (the $L>10^5$ extension). Full notes:
\texttt{pg\_reassessment\_2026-07.md}.
""")
        mart = hardlink(os.path.join(BASE, 'fig_martins2005.png'))
        if mart:
            tex.append(f"""
\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{mart}}}
\\caption{{The Martins, Schaerer \\& Hillier (2005) O-star calibration by luminosity class,
retrieved reproducibly from the arXiv e-print astro-ph/0503346 (\\texttt{{martins2005\\_fetch.py}};
the tables are not in VizieR). Left: $\\log L$ vs.\\ spectroscopic mass; right: H-ionizing
photon rate $\\log Q_0$ vs.\\ mass. Solid = observational $T_{{\\rm eff}}$ scale, dashed = theoretical
scale; blue V (dwarf), green III (giant), red I (supergiant). The dwarf locus is the lowest
$L(M)$ and $Q_0(M)$ track, so a class-V default for an unknown-class star is the minimum
luminosity consistent with its type. A true ZAMS star lies slightly below even the V track
($\\log g\\approx4.1$--$4.2$ vs.\\ Martins' fixed 3.92).}}\\label{{fig:martins}}
\\end{{figure}}
""")
        if als1 and als2:
            tex.append(f"""
\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.52\\linewidth]{{{als1}}}\\includegraphics[width=0.47\\linewidth]{{{als2}}}
\\caption{{The ALS\\,II OB-star population within 3\\,kpc (\\texttt{{make\\_als\\_figs.py}}).
Left: top-down Galactic-plane view, color-coded in six luminosity bins from
$\\log L = 3$--$6$. Right: fine-binned (0.1 dex) luminosity function with a Salpeter IMF
mapped through the ZAMS $L(m)$ relation and normalized to the lowest-luminosity bin
(dashed), and a KDE with 68\\% bootstrap band.}}\\label{{fig:als}}
\\end{{figure}}
""")
        alshi = hardlink(os.path.join(BASE, 'fig_als_topdown_hiL.png'))
        alsden = hardlink(os.path.join(BASE, 'fig_als_density.png'))
        alsdenlab = hardlink(os.path.join(BASE, 'fig_als_density_labeled.png'))
        if alshi and alsden:
            tex.append(f"""
The same census restricted to the luminous end and rendered as a surface density is shown in
Figs.~\\ref{{fig:alshi}} and~\\ref{{fig:alsden}}. Fig.~\\ref{{fig:alshi}} keeps only the
$\\log L\\geq5$ stars (the O-star reservoir directly comparable to our proto-O counts,
$N=527$ within 3\\,kpc), and Fig.~\\ref{{fig:alsden}} converts positions to a stars-per-kpc$^2$
surface density above $\\log L\\geq4$ and $\\geq5$. Both make plain that the local OB
population is concentrated into a few associations (Sco--Cen, the Orion and Vela clusters,
the Cygnus and Carina directions) rather than smoothly distributed, and that these same
concentrations host the volume's revealed O stars; the radially elongated features are
spectroscopic-distance smearing along the line of sight, not physical structure. This is the
denominator against which the embedded census of \\S\\ref{{sec:lfpair}} is compared: the
luminous protostars, where present, sit in or beside these same associations.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.72\\linewidth]{{{alshi}}}
\\caption{{Top-down view of the ALS\\,II census restricted to $\\log L\\geq5$ ($d<3$\\,kpc,
$N=527$), the revealed-O-star reservoir directly comparable to the proto-O counts of
\\S\\ref{{sec:protoO}}. Symbol size and color track luminosity; dotted rings are at 1, 2,
3\\,kpc.}}\\label{{fig:alshi}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{alsden}}}
\\caption{{ALS\\,II OB-star surface density (stars\\,kpc$^{{-2}}$, Gaussian-KDE of the top-down
positions normalized to the source count) within 3\\,kpc, above $\\log L\\geq4$ (left,
$N=2842$) and $\\log L\\geq5$ (right, $N=527$). White points are the individual stars; dotted
rings at 1, 2, 3\\,kpc. The population is association-dominated at both luminosity
cuts.}}\\label{{fig:alsden}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{alsdenlab}}}
\\caption{{As Fig.~\\ref{{fig:alsden}}, with the major nearby star-forming complexes and OB
associations marked at their $(l,d)$. The surface-density peaks coincide with the known
complexes --- Cygnus\\,X, Carina, M17, the inner-Galaxy NGC\\,6334/6357 and Sco\\,OB1 group,
M8/M20, W3/4/5 with Per\\,OB1, Gem\\,OB1, Cep\\,OB2, and the nearby Orion, Vela, and Rosette
clusters --- confirming that the revealed massive-star reservoir is locked into a handful of
associations rather than smoothly distributed.}}\\label{{fig:alsdenlab}}
\\end{{figure}}
""")
        tex.append(f"""
\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{lf}}}
\\caption{{Volume-limited LFs and lifetime-ratio diagnostics for $d<2$\\,kpc (top) and
$d<3$\\,kpc (bottom). Left: the embedded census, WISE extended H\\,{{\\sc ii}} regions,
and ALS OB stars. Right: the H\\,{{\\sc ii}}-to-OB ratio (Eq.~\\ref{{eq:ratio}},
$\\propto t_{{\\rm phase}}/t_{{\\rm MS}}$) with and without the extended regions. The two
volumes show the same deficit and the same fill-in.}}\\label{{fig:lf}}
\\end{{figure}}
\\clearpage
""")

    if lfh and lfk:
        tex.append(f"""
\\subsection{{Stars, extended H\\,{{\\sc ii}}, and protostars, side by side}}\\label{{sec:lfpair}}
Figures~\\ref{{fig:lfhist}} and~\\ref{{fig:lfkde}} show the diagnostic's three input
populations --- revealed OB stars, extended (WISE-catalogue) H\\,{{\\sc ii}} regions, and
embedded protostars --- overlaid in each of the two volume-complete bins, without forming the
ratio. The sample sizes are $N=46$ protostars (28 H\\,{{\\sc ii}}, 18 MYSO), 111 extended
H\\,{{\\sc ii}} regions, and 1583 ALS OB stars within 2\\,kpc; $N=98$ (56/42), 247, and 2842
within 3\\,kpc. The single marginal protostellar member of each list is excluded here, as in
Fig.~\\ref{{fig:lf}}.

The two panels are the same data seen two ways. The binned view carries small-$N$ Poisson
errors (\\citefoot{{Gehrels 1986, ApJ 303, 336 --- asymmetric Poisson confidence intervals,
valid at $N=0$}}), which is what matters where the protostellar LF runs to one or zero
counts per bin. The KDE view instead propagates the two error sources the histogram cannot
show: each Monte-Carlo realization bootstrap-resamples the catalogue (finite-sample noise)
\\emph{{and}} jitters every source by its own $\\sigma_{{\\log L}}$, so the band width is the
LF uncertainty rather than a smoothing choice. Median $\\sigma_{{\\log L}}$ is 0.17--0.18\\,dex
for the protostars (distance error propagated as $L\\propto d^2$, added in quadrature with a
0.15\\,dex SED-integration systematic), 0.21\\,dex for the OB stars (Gaia distance plus a
0.20\\,dex spectral-type-inversion scatter), and 0.39\\,dex for the extended H\\,{{\\sc ii}}
regions (0.35\\,dex $L_{{22}}$-calibration scatter plus a 20\\%\\ kinematic-distance term),
which is why their KDE band is the widest.

Three points read off the overlay. First, the protostar-to-star ratio falls with luminosity ---
$\\approx$0.05 at $\\log L=4.1$, 0.012 by $\\log L=5.3$--5.5, and zero above --- which is the
deficit of \\S\\ref{{sec:lfdeficit}} shown without the ratio machinery; the extended
H\\,{{\\sc ii}} regions sit an order of magnitude \\emph{{above}} the protostars and largely
close that gap toward the OB stars at the luminous end, which is the fill-in the ratio
diagnostic quantifies. Second, the sawtooth in
the binned OB LF (444/173/380 per bin at $\\log L=4.1/4.3/4.5$ within 2\\,kpc) is an artefact
of spectral-type discretisation piling stars onto grid values of the inversion, not
structure; the KDE's 0.21\\,dex jitter removes it, which is one reason to prefer the smoothed
view for the denominator. Third, the protostellar band becomes very wide above $\\log
L\\approx5.5$, where the counts are 0--2: the scarcity of luminous protostars is a real
feature of the census, but its \\emph{{amplitude}} there is uncertain at the factor-of-several
level, and \\S\\ref{{sec:protoO}} treats it with Poisson statistics rather than a fitted LF.
The grey band at the left of Fig.~\\ref{{fig:lfkde}} marks where the kernel leaks across the
$L\\geq10^4$\\,L$_\\odot$ selection boundary; the apparent turnover inside it is bandwidth, not
a physical rollover.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{lfh}}}
\\caption{{Classic binned view of the three populations in the volume-complete bins:
revealed OB stars (ALS, red), extended H\\,{{\\sc ii}} regions (WISE, purple), and embedded
protostars (compact H\\,{{\\sc ii}}$+$MYSO, blue),
$d<2$\\,kpc (left) and $d<3$\\,kpc (right), in 0.2\\,dex bins. Errorbars are asymmetric
Poisson intervals (Gehrels 1986); arrows are $1\\sigma$ upper limits
in empty bins interior to the occupied range.}}\\label{{fig:lfhist}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{lfk}}}
\\caption{{The same three populations as kernel-density estimates ($h=0.18$\\,dex), with the
uncertainty made explicit. Bands are the 68\\% and 95\\% ranges over 800 Monte-Carlo
realizations, each bootstrap-resampling the sample and perturbing every source by its own
$\\sigma_{{\\log L}}$ (distance $\\oplus$ SED for the protostars, distance $\\oplus$
spectral-type inversion for the stars, distance $\\oplus$ $L_{{22}}$ calibration for the
extended H\\,{{\\sc ii}} regions); the solid line is the median. Ticks along the bottom
are the individual sources. The grey band marks where the kernel leaks across the
$L\\geq10^4$\\,L$_\\odot$ cut, so the turnover there is not
physical.}}\\label{{fig:lfkde}}
\\end{{figure}}
\\clearpage
""")

    if lfc and lfcum:
        tex.append(f"""
The density-based views above are convenient for shape but awkward for the one number the
argument actually turns on: how many luminous sources of each kind the local volume
contains. Figures~\\ref{{fig:lfcounts}} and~\\ref{{fig:lfcum}} give that directly.
Fig.~\\ref{{fig:lfcounts}} is the true histogram --- counts per 0.25\\,dex bin, with the
integer on each bar --- and Fig.~\\ref{{fig:lfcum}} is the reverse-cumulative count
$N(>L)$, from which the number above any luminosity threshold is read off the curve. The
marked thresholds give, within 2\\,kpc, $N(>10^5\\,{{\\rm L}}_\\odot)=284$ revealed OB stars,
48 extended H\\,{{\\sc ii}} regions, and 4 protostars; above $10^{{5.5}}$, 54 / 16 / 1. Within
3\\,kpc: $527$ / 109 / 8 above $10^5$, and $98$ / 45 / 2 above $10^{{5.5}}$. Above
$10^6\\,{{\\rm L}}_\\odot$ there are 4--6 revealed O stars and zero protostars in either volume.
The ordering is the whole argument in one figure: the luminous population exists (hundreds of
revealed O stars), the H\\,{{\\sc ii}} regions that trace it are an order of magnitude more
numerous than the compact embedded sources at every threshold, and the embedded numerator is
the small residual --- a handful of luminous protostars --- which is the short-embedded-phase
signature quantified in \\S\\ref{{sec:protoO}} without any LF fit.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{lfc}}}
\\caption{{True histogram (counts, not density): number of sources per 0.25\\,dex luminosity
bin for revealed OB stars (red), extended H\\,{{\\sc ii}} regions (purple), and embedded
protostars (blue), $d<2$\\,kpc (left) and
$d<3$\\,kpc (right). The integer above each bar is the count in that bin.}}\\label{{fig:lfcounts}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{lfcum}}}
\\caption{{Reverse-cumulative luminosity counts $N(>L)$: the number of sources brighter than
$L$ in the volume, for revealed OB stars (red), extended H\\,{{\\sc ii}} regions (purple), and
embedded protostars (blue). Dotted lines
mark $L=10^5$ and $10^{{5.5}}$\\,L$_\\odot$; the labelled points give the count above each
threshold. Within 2\\,kpc, above $10^5$\\,L$_\\odot$: 284 OB stars, 48 extended H\\,{{\\sc ii}},
4 protostars (54 / 16 / 1 above $10^{{5.5}}$); within 3\\,kpc, 527 / 109 / 8 and 98 / 45 /
2.}}\\label{{fig:lfcum}}
\\end{{figure}}
\\clearpage
""")

    ptd = hardlink(os.path.join(BASE, 'fig_proto_topdown.png'))
    ptdhi = hardlink(os.path.join(BASE, 'fig_proto_topdown_hiL.png'))
    if ptd and ptdhi:
        tex.append(f"""
Spatially, the embedded numerator can be shown in the same top-down projection used for the
ALS denominator (Figs.~\\ref{{fig:alshi}},~\\ref{{fig:alsden}}). Figures~\\ref{{fig:ptd}}
and~\\ref{{fig:ptdhi}} plot the protostars with the matching luminosity cuts, H\\,{{\\sc ii}}
regions and MYSOs distinguished by symbol. The full $\\log L\\geq4$ sample ($N=98$ within
3\\,kpc) traces the same association directions as the OB stars, as expected if these are the
still-forming members of the same complexes. At $\\log L\\geq5$ the map is nearly empty ---
9 sources in the entire 3\\,kpc sphere, 8 of them compact H\\,{{\\sc ii}} regions and only one
a genuinely embedded MYSO --- against the 527 revealed OB stars above the same cut
(Fig.~\\ref{{fig:alshi}}). The scarcity of luminous protostars is thus not a projection or
selection accident visible only in the LF: it is directly apparent as an almost bare map,
and it is the spatial statement of the proto-O deficit quantified in \\S\\ref{{sec:protoO}}.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.72\\linewidth]{{{ptd}}}
\\caption{{Top-down view of the embedded protostellar census, $\\log L\\geq4$, $d<3$\\,kpc
($N=98$). Circles are compact H\\,{{\\sc ii}} regions, squares are MYSOs; color tracks
luminosity; dotted rings at 1, 2, 3\\,kpc. Same projection as the ALS OB map
(Fig.~\\ref{{fig:alshi}}).}}\\label{{fig:ptd}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.72\\linewidth]{{{ptdhi}}}
\\caption{{The same census restricted to $\\log L\\geq5$: only 9 sources in the entire
3\\,kpc sphere (8 compact H\\,{{\\sc ii}}, 1 MYSO), to be compared with 527 revealed OB stars
above the same cut (Fig.~\\ref{{fig:alshi}}). The near-empty map is the spatial form of the
proto-O deficit.}}\\label{{fig:ptdhi}}
\\end{{figure}}
\\clearpage
""")

    eht = hardlink(os.path.join(BASE, 'fig_exthii_topdown.png'))
    ehh = hardlink(os.path.join(BASE, 'fig_exthii_lf_hist.png'))
    ehk = hardlink(os.path.join(BASE, 'fig_exthii_lf_kde.png'))
    ehc = hardlink(os.path.join(BASE, 'fig_exthii_lf_cdf.png'))
    if eht and ehh and ehk and ehc:
        tex.append(f"""
\\subsection{{The extended H\\,{{\\sc ii}}-region population}}\\label{{sec:exthii}}
Population (ii) --- the WISE-catalogue known H\\,{{\\sc ii}} regions, mostly evolved and
physically large ($r>0.15$\\,pc), with $L$ from the self-calibrated 22\\,$\\mu$m aperture
photometry --- is the term that fills the high-luminosity deficit left by the compact
embedded census. Figures~\\ref{{fig:ehtd}}--\\ref{{fig:ehcdf}} present it in the same four
views used for the stars and protostars. Positions are decoded from the WISE names
(\\texttt{{fig\\_extended\\_hii.py}}); the calibration scatter (0.35\\,dex) plus a 20\\%\\
kinematic-distance term give a per-source $\\sigma_{{\\log L}}=0.39$\\,dex, which is why the KDE
band (Fig.~\\ref{{fig:ehkde}}) is wider than for the other populations.

The contrast with the embedded map is the point. Where the compact protostellar census has
9 sources above $10^5$\\,L$_\\odot$ within 3\\,kpc, the extended H\\,{{\\sc ii}} regions number
{{\\bf 109}} (48 within 2\\,kpc), and above $10^{{5.5}}$ there are 45 (16 within 2\\,kpc)
against the protostars' 2. The extended population is spatially broader and less
association-locked than either the compact protostars or the highest-density OB knots,
consistent with these being older regions that have had time to disperse. In the deficit
diagnostic of \\S\\ref{{sec:lfdeficit}} it is exactly this population, added to the numerator,
that raises $\\phi_{{\\rm HII}}/\\phi_{{\\rm OB}}$ at the luminous end --- the observational
statement that the luminous H\\,{{\\sc ii}} regions are present, but revealed and extended
rather than compact and embedded.

\\paragraph{{Are the OB stars inside these regions?}} As a consistency check we ask how many
ALS OB stars fall within the angular boundary (catalogue radius) of an extended H\\,{{\\sc ii}}
region (\\texttt{{assess\\_als\\_in\\_exthii.py}}: angular containment, then a distance-consistency
cut requiring the Gaia and kinematic distances to agree within a factor 1.5). Within 3\\,kpc,
241 of 4756 OB stars (5.1\\%) lie inside an extended-H\\,{{\\sc ii}} disk, 210 (4.4\\%)
distance-consistent; restricted to O-type stars the fraction triples, to 91/639 (14.2\\%
inside, 12.8\\% distance-consistent), as expected since O stars are the ionizing sources and
most B stars are not. The distance cut removes only $\\sim$13\\%\\ of the angular pairs, so
chance projection is minor. The physically interesting number is that only $\\sim$1 in 7
revealed O stars currently sits inside a catalogued extended H\\,{{\\sc ii}} region --- and that
is a \\emph{{lower}} bound, floored by the incompleteness of the WISE extended-H\\,{{\\sc ii}}
catalogue, by the deliberate exclusion of the compact ($r<0.15$\\,pc)
regions that host the youngest O stars, and by regions whose exciting star lies outside the
22\\,$\\mu$m centroid. Taken at face value it says most revealed O stars have already dispersed
or outlived their natal ionized gas, consistent with the short-embedded / fast-feedback
reading of the deficit rather than a long hidden-accretion phase.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{eht}}}
\\caption{{Top-down view of the extended (WISE-catalogue) H\\,{{\\sc ii}} regions within
3\\,kpc, above $\\log L\\geq4$ (left, $N=247$) and $\\log L\\geq5$ (right, $N=109$), colored by
luminosity. Arrow from the Sun points to the Galactic centre; dotted rings at 1, 2,
3\\,kpc.}}\\label{{fig:ehtd}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{ehh}}}
\\caption{{Extended H\\,{{\\sc ii}}-region luminosity function, counts per 0.25\\,dex bin with
Gehrels (1986) Poisson errors, $d<2$ (left) and $d<3$\\,kpc (right).}}\\label{{fig:ehhist}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{ehk}}}
\\caption{{Same population as a KDE with 68/95\\%\\ Monte-Carlo bands propagating the
per-source $\\sigma_{{\\log L}}=0.39$\\,dex (L22 calibration $\\oplus$ distance) and bootstrap
resampling.}}\\label{{fig:ehkde}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{ehc}}}
\\caption{{Reverse-cumulative counts $N(>L)$ for the extended H\\,{{\\sc ii}} regions: 48 (2\\,kpc)
/ 109 (3\\,kpc) above $10^5$\\,L$_\\odot$, 16 / 45 above $10^{{5.5}}$ --- an order of magnitude
more luminous sources than the compact embedded census.}}\\label{{fig:ehcdf}}
\\end{{figure}}
\\clearpage
""")

    odust = hardlink(os.path.join(BASE, 'fig_ostar_dust.png'))
    if odust:
        tex.append(f"""
\\subsection{{Do the revealed O stars retain an accretion reservoir?}}\\label{{sec:ostardust}}
The containment test above asks whether O stars sit inside ionized gas; the physically
decisive question for the P\\&G picture is narrower --- is there \\emph{{accretable}} material
around them at all. We test it directly by measuring the far-IR flux in each mission's beam
around every revealed ALS O star ($d<3$\\,kpc, $N=639$) and converting it to a cold-dust mass
(\\texttt{{build\\_ostar\\_fir.py}}: CDS X-Match to the IRAS PSC 60/100\\,$\\mu$m and AKARI FIS
65/90/140/160\\,$\\mu$m catalogues; $M_{{\\rm dust}}=F_\\nu d^2/\\kappa_\\nu B_\\nu(T_d)$ with
$\\kappa_\\nu=0.1(\\nu/{{\\rm THz}})^{{1.8}}$\\,cm$^2$\\,g$^{{-1}}$, $T_d=30$\\,K; 22\\,$\\mu$m is
excluded as it is the stellar Rayleigh--Jeans tail, not a mass tracer). Any matched flux is
treated as an \\emph{{upper limit}} on truly circumstellar dust, since single-dish FIR is
confused with foreground cirrus, so every point in Fig.~\\ref{{fig:ostardust}} is an upper
bound.

508 of 639 O stars (79\\%) are undetected in the FIR, with dust upper limits whose median is
0.047\\,M$_\\odot$ --- a gas reservoir (at a gas-to-dust ratio of 100) of $\\sim$5\\,M$_\\odot$,
and 503/639 lie below 0.1\\,M$_\\odot$ of dust. To sustain even $10^5$\\,yr of accretion at
$10^{{-4}}$\\,M$_\\odot$\\,yr$^{{-1}}$ requires $\\gtrsim$10\\,M$_\\odot$ of gas
($\\gtrsim$0.1\\,M$_\\odot$ dust; the dashed line in Fig.~\\ref{{fig:ostardust}}), so the large
majority of revealed O stars simply do not have the material to keep growing. The 131 with a
FIR flux nearby scatter to much larger apparent masses, but those are dominated by projected
cirrus and unrelated clouds rather than bound circumstellar gas --- upper limits, not
reservoirs. This is the beam-scale ($\\sim$0.1--1\\,pc) counterpart to the ALMA result that
individual revealed O stars (e.g.\\ Herschel\\,36) carry $<0.07$\\,M$_\\odot$ of circumstellar
dust: once an O star is optically revealed, its accretion reservoir is largely gone, which is
what a short accretion phase followed by rapid gas clearing predicts and a long
hidden-accretion phase does not.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.86\\linewidth]{{{odust}}}
\\caption{{ALS spectral-type luminosity vs.\\ circumstellar dust mass (upper limit, $T_d=30$\\,K)
in the far-IR beam around each revealed O star within 3\\,kpc. Grey: FIR non-detections
(catalogue-limit bound, $N=508$); red: an FIR flux is present, taken as an upper bound on
circumstellar dust since it is cirrus-confused ($N=131$). Top axis is the implied gas
reservoir ($100\\times$ dust). The dashed line marks the $\\sim$10\\,M$_\\odot$ gas needed to
accrete for $10^5$\\,yr at $10^{{-4}}$\\,M$_\\odot$/yr; 79\\%\\ of the O stars fall below
it.}}\\label{{fig:ostardust}}
\\end{{figure}}
\\clearpage
""")

    odhr = hardlink(os.path.join(BASE, 'fig_ostar_dust_highres.png'))
    osky = hardlink(os.path.join(BASE, 'fig_ostar_skymap.png'))
    obcirc = hardlink(os.path.join(BASE, 'fig_circ_mass_ob.png'))
    if odhr and osky:
        tex.append(f"""
The 131 with an IRAS/AKARI flux nearby are the only ones that could harbour a real reservoir,
and the single-dish $1$--$2'$ beam cannot tell circumstellar gas from cirrus. We resolve them
with higher-resolution submm/mm catalogues --- ATLASGAL 870\\,$\\mu$m (19$''$), BGPS 1.1\\,mm
(33$''$), and Hi-GAL 70--500\\,$\\mu$m --- asking whether a \\emph{{compact}} source sits on the
star (\\texttt{{scan\\_ostar\\_highres.py}}). It almost never does. Of the 58 that fall in the
full-plane Hi-GAL footprint, only 4 have a coincident compact source; the other 54 (93\\%) show
no concentrated dust and are confirmed diffuse cirrus, converting their IRAS-beam ``mass'' into
a firm non-detection of any bound reservoir (Fig.~\\ref{{fig:ostarhr}}). The 4 coincidences are
not accretion discs but massive clumps or chance projections --- dust masses of
0.26--1800\\,M$_\\odot$ (the 1800\\,M$_\\odot$ BGPS case is an entire $\\sim10^5$\\,M$_\\odot$
clump the O star is projected onto, not material bound to it), two of them with a Hi-GAL
70\\,$\\mu$m counterpart indicating an internally heated source that is forming \\emph{{other}}
stars. We nonetheless retain these 4 as an ``unembedded-but-accreting'' category --- the most
conservative bookkeeping, treating every revealed O star with any coincident compact dust as
potentially still gaining mass, even though the coincidences look like projection. Four out
of the 639 revealed O stars within 3\\,kpc ($<1\\%$) is then a hard upper bound on the revealed
population that could plausibly still be accreting. The remaining 73 FIR-flux O stars lie
outside the Hi-GAL footprint (all at $|b|>1^\\circ$, median $|b|\\approx2^\\circ$, median
$d\\approx1.7$\\,kpc; Fig.~\\ref{{fig:ostarsky}}) so they are formally uncovered, but their high
latitude makes local cirrus the natural explanation. The high-resolution view therefore
removes the apparent reservoirs almost entirely: at most 4 revealed O stars sit on a compact
dust concentration and even those are likely projected clumps, tightening the
\\S\\ref{{sec:ostardust}} conclusion from ``79\\%\\ below the reservoir line'' to ``the FIR-bright
minority are cirrus, not reservoirs.''

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.86\\linewidth]{{{odhr}}}
\\caption{{The same $L$ vs.\\ FIR-beam dust mass as Fig.~\\ref{{fig:ostardust}}, with the 131
FIR-flux O stars recoloured by their higher-resolution verdict: orange squares are resolved
into diffuse cirrus (in the Hi-GAL footprint with no compact source, $N=54$); dark circles
lack high-resolution coverage ($N=73$); red stars are the only sources with a coincident
compact ATLASGAL/BGPS/Hi-GAL source ($N=4$, all massive clumps or projections). The apparent
high-mass reservoirs at right are almost all cirrus, not bound gas.}}\\label{{fig:ostarhr}}
\\end{{figure}}

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.98\\linewidth]{{{osky}}}
\\caption{{Galactic Aitoff sky map of the 131 FIR-flux revealed O stars by high-resolution
verdict. Grey band is the Hi-GAL $|b|<1^\\circ$ footprint; the 54 cirrus-confirmed sources
(orange) lie within it, the 4 compact-submm sources (red stars) on the plane, and the 73
high-resolution-uncovered sources (blue) just outside it ($|b|\\approx1$--$15^\\circ$, all
longitudes) --- nearby, off-plane O stars where local cirrus rather than a bound reservoir is
the natural interpretation.}}\\label{{fig:ostarsky}}
\\end{{figure}}

The most systematic form of this test is a per-star, mass-matched catalogue: an upper limit on
the gas within a fixed 0.1\\,pc (20{{,}}000\\,au) aperture around \\emph{{every}} revealed star,
in three independent channels (\\texttt{{circ\\_mass\\_\\{{ionized,cold,higal,diffuse,warm,build\\}}.py}}).
Ionized gas comes from the Finkbeiner H$\\alpha$ composite (${{\\rm EM}}=2.25\\,I_R$, all beam
emission forced into a 0.1\\,pc uniform sphere); cold dust from ATLASGAL\\,870, Hi-GAL\\,350, and
an SFD all-sky diffuse backstop at $T=20$\\,K with the standard ATLASGAL opacity
($\\kappa_\\nu=0.0185(\\nu/345\\,{{\\rm GHz}})^{{1.8}}$\\,cm$^2$\\,g$^{{-1}}$ of gas); warm dust
from IRAS\\,60/AKARI\\,65--90 at $T=25$\\,K. Every channel is built to over-state the enclosed
mass, so each is a true upper limit. For the 639 O stars the median cold-gas limit is
$1.5$\\,M$_\\odot$, $632/639$ (99\\%) --- and $446/448$ above $10^5\\,{{\\rm L}}_\\odot$ --- fall
below the $\\sim$10\\,M$_\\odot$ reservoir, and only $8/639$ carry any compact submm source in the
aperture (the high-resolution winnowing above reduces these to the same 4 clump projections);
the warm and ionized limits are negligible ($0.12$ and $8\\times10^{{-4}}$\\,M$_\\odot$). Extending
the same machinery to \\emph{{all}} 6804 revealed O and B stars within 3\\,kpc
(\\texttt{{circ\\_mass\\_ob.py}}; Fig.~\\ref{{fig:obcirc}}) gives the identical null: a median cold
limit of $0.6$\\,M$_\\odot$, $6783/6804$ (100\\%) below the reservoir, and $0.7\\%$ with any
compact submm projection. No revealed massive or intermediate-mass star in the local volume
retains an accretable reservoir within 0.1\\,pc.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.99\\linewidth]{{{obcirc}}}
\\caption{{Circumstellar gas within 0.1\\,pc of the 6804 revealed O and B stars within 3\\,kpc.
Left: luminosity vs.\\ the cold-gas reservoir upper limit ($T_d=20$\\,K; O stars blue, B stars
grey), with the 46 compact-submm projections as red stars and the $\\sim$10\\,M$_\\odot$ reservoir
(dashed). Right: the cold, warm, and ionized channels, all far below the reservoir threshold.
The horizontal striping is the discrete spectral-type $L$ grid.}}\\label{{fig:obcirc}}
\\end{{figure}}
\\clearpage
""")

    tex.append(r"""
\subsection{Proto-O-star counts vs.\ the local star-formation rate}\label{sec:protoO}
The number of luminous embedded sources is a formation clock requiring no H\,{\sc ii}-region
physics: $N = {\rm SFR} \times n_{\rm IMF}(>30\,{\rm M}_\odot) \times \tau$, with
$n_{\rm IMF} = 1/600\,{\rm M}_\odot^{-1}$ (Kroupa; $L_{\rm ZAMS}>10^5\,{\rm L}_\odot
\Leftrightarrow m\gtrsim30\,{\rm M}_\odot$). The SFR within 2\,kpc is 0.015--0.05\,M$_\odot$/yr
(uniform share of the Galactic 2\,M$_\odot$/yr; local $\Sigma_{\rm SFR}$; gas + KS;
inversion of the ALS census of 125 living O2--O7 stars). A fourth, independent anchor is
now available: \citefoot{Quintana et al. 2026, arXiv:2607.07068} derive a compact-cluster
surface star-formation-rate density $\Sigma_{\rm SFR,OC}\approx600$--$920\,{\rm
M}_\odot\,{\rm Myr}^{-1}\,{\rm kpc}^{-2}$ within 2\,kpc from the Gaia OB census; integrated
over the $\pi(2\,{\rm kpc})^2$ disc this is $\approx0.008$--$0.012\,{\rm M}_\odot$/yr,
consistent with (and anchoring the low end of) our adopted range. We observe $N=4$ embedded
$L\geq10^5$ sources at $r<2$\,kpc (M17, W3\,IRS5, W3(OH), RCW38; only 1--2 are strictly
pre-ionizing) and, treating the $2<r<3$\,kpc annulus as an independent sample of comparable
area, $N=3$ (W33, NGC\,7538, NGC\,3576). The two zones give consistent clocks:
$\tau_{\rm embedded} = 4.8\times10^4$ and $2.9\times10^4$\,yr; combined
$\tau = 3.7^{+4.0}_{-2.2}\times10^4$\,yr (95\%). A growth law that keeps stars at
$m>30\,{\rm M}_\odot$ for $\sim$1\,Myr while accreting predicts $\sim$105 such objects in
the annulus alone versus 3 observed ($P=7\times10^{-41}$); even $\tau=10^5$\,yr is mildly
disfavored ($P=0.007$). The scarcity of proto-O stars is exactly what a
$\sim3\times10^4$\,yr luminous embedded phase predicts.

One caveat cuts in our favor rather than against it. \citefoot{Quintana et al. 2026,
arXiv:2607.07068} show that the local 2\,kpc is presently \emph{over}dense in OB stars: the
current core-collapse-SN waiting time ($\sim7800$\,yr, valid over the next $\sim$3\,Myr) is
about half the $\sim$15{,}150\,yr expected from the $\sim$400\,Myr temporal average, so
``we live in an era characterized by an overdensity of OB stars nearby.'' Recent massive
star formation in our sample volume has therefore been \emph{above} its long-term mean. If
anything this raises the expected number of proto-O stars relative to a steady-state SFR,
so observing only 1--2 makes the short embedded phase a \emph{conservative} inference: even
a volume caught mid-burst produces essentially no luminous proto-O stars, as a
$\sim3\times10^4$\,yr phase requires.

\section{The direct constraint: are the ionizing stars of H\,{\sc ii} regions accreting?}
\label{sec:direct}
The luminosity-function and counting arguments above are statistical. The fundamental
question raised by P\&G and by the ``missing proto-O-star'' population is direct and
physical: \emph{do massive stars ($m\gtrsim20$\,M$_\odot$) continue to accrete while on
the main sequence, i.e., while ionizing an H\,{\sc ii} region?} We tested this
source-by-source in earlier phases of this project, asking, for each ionizing star of a
compact H\,{\sc ii} region, whether a dense accretion reservoir is present \emph{at the
star's position} --- the necessary (not sufficient) condition for ongoing growth.

\subsection{Method}
Starting from the RMS-based census sub-classified with CORNISH 5\,GHz radio sizes
(102 ultracompact $\leq$0.1\,pc, 240 compact, 62 classical;
\texttt{alma\_census.py}), the 57 UC/compact H\,{\sc ii} regions with usable archival
ALMA continuum form the test sample (\texttt{UCHII\_master\_deliverable.csv};
analysis in \texttt{analyze\_census.py}). Three independent tracers were evaluated at
each ionizing-star position:
\begin{enumerate}
\item \textbf{Dust mass at the star} (ALMAGAL 1.4\,mm, free-free-subtracted using the
cm-radio flux extrapolated as $S_\nu\propto\nu^{-0.1}$): median coincident dust mass
$<1$\,M$_\odot$; a dust-dominated core at the star in \textbf{1/30} sources
(3\%, 95\% CI 0--15\%).
\item \textbf{Resolved spectral index} (ALMA-IMF B3--B6 common-beam $\alpha$ maps at the
ionizing positions): free-free-dominated in 7/8; dust-dominated in \textbf{1/8}
(12\%, CI 1--45\%). W51-IRS2 shows $\alpha=+1.51$, consistent with pure free-free ---
\emph{not} accreting-envelope emission.
\item \textbf{Hot-core line emission} (CH$_3$CN at the ionizing positions in ALMA-IMF
cubes): detected at \textbf{2/9} (22\%, CI 5--54\%), both in the most massive,
cluster-confused fields where attribution to the ionizing star is ambiguous.
\end{enumerate}

\subsection{Answer}
Combining the tracers, the fraction of compact-H\,{\sc ii} ionizing stars with any
plausible accretion reservoir is \textbf{$\sim$13--23\%} (loose to strict criteria), and
even for those the coincident dust masses ($\lesssim$1\,M$_\odot$ against
$\gtrsim$20\,M$_\odot$ stars) permit fractional growth of only a few percent. For
\emph{revealed} O stars the limits are stronger: ALMA continuum at Herschel 36 gives
$<0.067$\,M$_\odot$ at the star. Meanwhile the parent \emph{clumps} remain gas-rich
(ATLASGAL median $\sim$1260\,M$_\odot$, bound) with persistent large-scale inflow at the
H\,{\sc ii}-region stage (Wells et al.\ 2024: median
$\dot M \sim 7\times10^{-4}$\,M$_\odot$\,yr$^{-1}$, detected in 100\% of
H\,{\sc ii}-region clumps) --- but that inflow feeds the clump/protocluster, not the
already-ionizing star, whose own $\leq$0.1\,pc reservoir is cleared.

The direct answer: \textbf{at most $\sim$1--2 of every 10 massive stars in compact
H\,{\sc ii} regions could still be growing, and none of the resolved cases has enough
coincident material to grow significantly.} With \S\ref{sec:extphase} covering the
extended phase (clump-scale gas present, but exciting stars revealed, with
Herschel-36-class limits where measured), main-sequence accretion is excluded as a
significant mass-assembly channel at every H\,{\sc ii}-region stage we can test. The
P\&G deficit is an H\,{\sc ii}-region \emph{expansion} clock, not a stellar growth clock.

\medskip
\noindent\textbf{Code:} \texttt{alma\_census.py}, \texttt{analyze\_census.py},
\texttt{batch\_viz\_census.py} (per-source validation figures),
\texttt{UCHII\_master\_deliverable.csv}; full statistics in \texttt{PAPER\_DRAFT.md} and
\texttt{RESULTS.md}.
""")

    pgshell = hardlink(os.path.join(BASE, 'fig_pg_shell_ratio.png'))
    tex.append(f"""
\\section{{Reproducing and diagnosing the Padoan \\& Gieles analysis}}\\label{{sec:pgdiag}}
P\\&G (arXiv:2602.06196) fit the RMS embedded-source LF (H\\,{{\\sc ii}}$+$MYSO, $N=1800$,
$d\\le18$\\,kpc) jointly with the ALS\\,III OB-star LF (in $G_{{\\rm abs}}$, $d\\le12$\\,kpc),
each corrected by an empirical radial function $g(R)$ normalized at 3\\,kpc plus an
effective-volume completeness correction, using a five-parameter forward model (broken
power-law IMF $m_k$, $s$, $s_f$; growth law $\\alpha$, $\\tau_0$). They obtain
$\\alpha=0.48\\pm0.11$, $\\tau_0=4.15^{{+0.90}}_{{-0.63}}$\\,Myr at 60\\,M$_\\odot$, and
$m_k=18\\pm2$, $s_f=3.86$. We reproduce and test their pipeline directly
(\\texttt{{pg\\_reproduce.py}}).

\\paragraph{{Sample reproduction.}} From the same RMS catalogue we recover 1653 of their
1800 working sources (H\\,{{\\sc ii}}$+$YSO, $L>0$, $0<d\\le18$\\,kpc; the difference is
in low-$L$ bookkeeping) and the raw high-luminosity LF slope, $-1.04$ per dex, matches
their corrected-LF value ($-1.03$) --- as expected, since the bright end is nearly
volume-complete to 18\\,kpc. We are analysing the same data.

\\paragraph{{The slope constraint is degenerate.}} Their central analytic result,
$\\Delta\\beta = \\beta_{{\\rm HII}}-\\beta_{{\\rm OB}} = (\\alpha+\\delta)/\\gamma$, is
algebraically indistinguishable from a fixed-mass lifetime interpretation. Writing the
birthrate density $b(L)=\\phi_{{\\rm OB}}(L)/t_{{\\rm MS}}(L)$ and a luminosity-dependent
lifetime $t_{{\\rm HII}}\\propto L^{{x}}$ gives $\\phi_{{\\rm HII}} = b\\,t_{{\\rm HII}}$
with exactly the same slope difference for $x=\\alpha/\\gamma\\approx0.15$--0.3. The LF
\\emph{{shapes}} cannot distinguish ``stars grow through the phase'' from ``the phase
lifetime varies mildly with $L$''; every bit of the timescale information resides in the
\\emph{{relative normalization}} of the two LFs.

\\paragraph{{Their model fails at its own anchor.}} Both of their LFs are normalized to
the source density at 3\\,kpc --- precisely our volume-complete sphere. Their best-fit
model predicts, in steady state, $N_{{\\rm emb}}/N_{{\\rm OB}}(L>10^5) = 0.185$: given the
527 revealed OB stars above $10^5$\\,L$_\\odot$ within 3\\,kpc, it predicts
\\textbf{{98 luminous embedded sources where 9 exist}} ($P(N\\le9\\,|\\,\\mu=98) =
1\\times10^{{-30}}$). The environment-dependence escape ($\\tau_0$ varying with
surface density) is unavailable: 3\\,kpc \\emph{{is}} their normalization anchor.

\\paragraph{{Where the normalization comes from.}} Figure~\\ref{{fig:pgshell}} shows the
raw embedded-to-OB count ratio in heliocentric shells. A steady-state population ratio
is distance-independent; the observed ratio instead climbs monotonically from 0.014
(0--2\\,kpc) to 4.2 (9--12\\,kpc) --- a factor of $\\sim$300 --- because the mid-IR
numerator survives extinction and beam-sums whole protoclusters (the MSX beam is
$>$1\\,pc beyond 12\\,kpc) while the optically selected denominator is destroyed by
extinction. The ratio their fit requires, 0.185, is the raw value at 4--6\\,kpc ---
exactly where the RMS source counts peak --- not the value at their 3\\,kpc anchor
(0.019). The empirical $g(R)$ and effective-volume corrections, derived from the same
data they correct, cannot repair a differential two-catalogue selection effect of two
orders of magnitude; they inherit it.

\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.8\\linewidth]{{{pgshell}}}
\\caption{{Raw embedded-to-OB count ratio (RMS H\\,{{\\sc ii}}$+$MYSO over ALS OB) in
heliocentric distance shells, for $L>10^4$ (blue) and $L>10^5$\\,L$_\\odot$ (red). A
physical steady-state ratio would be flat; the $\\sim$300-fold rise is differential
selection (mid-IR vs.\\ optical; beam-summed protocluster luminosities at large $d$).
Dotted line: the volume-complete value; dashed line: the ratio required by the P\\&G
best-fit model, which matches the selection-inflated 4--6\\,kpc shells rather than the
volume-complete anchor.}}\\label{{fig:pgshell}}
\\end{{figure}}

\\paragraph{{Verdict.}} Given their sample \\emph{{and}} their corrections \\emph{{and}}
the growth-model reading of the slope difference, their conclusion follows --- we can
reproduce it. But the same sample, restricted to its volume-complete core where no
corrections are needed, yields the count ladder of \\S\\ref{{sec:ladder}} and
$\\tau_{{\\rm emb}}\\approx6\\times10^4$\\,yr. The error is not in the RMS or ALS data,
nor primarily in classification: it is (i) a two-catalogue differential-selection bias
that sets the fitted normalization, compounded by protocluster beam-summing of the
high-$L$ numerator at $d\\gtrsim4$\\,kpc, and (ii) an interpretive degeneracy in which
the slope fit appears to constrain growth but cannot, leaving the poisoned
normalization as the sole carrier of $\\tau_0$. Their revised LFs otherwise agree with
M11, i.e.\\ with our own starting point, so nothing in their data pushes back on the
conclusions of this document. Their separate claim of a field-IMF steepening above
$\\sim$18\\,M$_\\odot$ is orthogonal to the timescale question and is not contradicted
by our analysis (our ALS LF also steepens above $\\log L\\sim5.3$).
""")

    tex.append(r"""
\section{Merger pathways and explosive outflows}\label{sec:mergers}

The count ladder constrains how long stars spend luminous and embedded; it does not by
itself specify \emph{how} the mass arrives. Accretion at few$\times10^{-4}$--$10^{-3}$
\,M$_\odot$/yr fits the window (\S\ref{sec:ladder}), but stellar mergers are the
alternative worth taking seriously, in three distinct regimes.

\subsection{Direct collisions and gas-free dynamical decay}
Cluster-centric direct collisions are excluded on rates: growing massive stars by
star--star collisions within $\lesssim$1\,Myr requires stellar densities
$\sim10^{8}$\,pc$^{-3}$ (Bonnell \& Bate 2005), two to three orders of magnitude above
observed young-massive-cluster cores ($10^{5}$--$10^{6}$\,pc$^{-3}$). Gas-free decay of
non-hierarchical multiples after gas dispersal fares little better as a
\emph{formation} channel: decay predominantly ejects the light members and hardens a
binary (the Reipurth-type paradigm), with contact mergers rare per decay absent
dissipation, and post-gas cluster densities fall quickly. What gas-free dynamics
\emph{does} deliver, on 1--10\,Myr timescales, is the binary-evolution merger channel:
$\sim$70\% of O stars interact with a companion and $\sim$8--10\% of massive
main-sequence stars are merger products (Sana et al.\ 2012; de Mink et al.\ 2014;
Schneider et al.\ 2016). But these events merge components that are \emph{already}
massive --- they redistribute mass within the massive population and rejuvenate
(and possibly magnetize) the products; they do not build the top of the IMF out of
intermediate-mass stars. For the ladder, the accounting matters: main-sequence merger
products enter the revealed denominator having contributed no embedded numerator at
their final mass. If a fraction $f_{\rm merge}$ of massive stars form this way, our
$\tau_{\rm emb}$ underestimates the embedded time of the accretion-formed majority by
$1/(1-f_{\rm merge})$ --- a $\le$10\% correction at the measured $f\approx0.1$, and
even a (counterfactual) merger-dominated $f=0.9$ would stretch $\tau_{\rm emb}$ only
to $\sim$$6\times10^5$\,yr, still an order of magnitude short of the P\&G growth law.
Post-accretion mergers cannot resurrect slow accretion; they can only dilute how many
stars accrete at all.

\subsection{Gas-rich mergers during assembly: the explosive-outflow rate}
The interesting regime is mergers \emph{during} the embedded phase, where gas changes
the dynamics qualitatively --- disks, envelopes, and gas drag give capture
cross-sections that pure $N$-body dynamics never has. The binary-mediated variant
needs only $\sim10^{6}$\,pc$^{-3}$ (a close binary perturbed into merger by a third
body; Bonnell \& Bate 2005), collapse simulations transiently reach
$10^{6}$--$10^{8}$\,pc$^{-3}$ (Bonnell et al.\ 2003), and observed protocluster
centers do too: $\gtrsim$3 compact sources per $(10^3\,{\rm au})^3$ in OMC1-S and
$>$7 within $\sim$$10^3$\,au in NGC\,6334\,I(N) correspond to
$\sim$$3\times10^{7}$\,pc$^{-3}$ (Zapata et al.\ 2026, review, and references
therein).

The empirical anchor is the explosive-outflow census (Zapata et al.\ 2026,
arXiv:2607.10452): eight BN/KL-like events --- isotropic, Hubble--Lema\^itre-law
CO streamer systems with $E_{\rm kin}\sim10^{47}$--$10^{49}$\,erg and dynamical ages
of $10^{2.7}$--$10^{4}$\,yr --- interpreted as the disruption of non-hierarchical
massive protostellar systems ending in a tight ($\sim$au) binary or a merger. The
energetics match: a $15+10$\,M$_\odot$ pair brought to 1\,au releases
$2.6\times10^{48}$\,erg. Seven events within 5\,kpc and 8.6\,kyr give a Galactic
rate of one per $\sim$140\,yr (one per 80\,yr in the IRAS\,15520 analysis),
against a $>$8\,M$_\odot$ star-formation rate of one per $\sim$50\,yr and a
$>$20\,M$_\odot$ rate of one per $\sim$175\,yr: \emph{of order one explosive event
per massive star formed}. Our census checks this independently and locally: three
of the eight hosts (Orion BN/KL, G5.89$-$0.39, DR21) are members of our $d<3$\,kpc
embedded sample. With $\tau_{\rm emb}(L>10^4)\approx2.2\times10^5$\,yr from the
ladder and a $\sim$8.6\,kyr visibility window, the expected number of currently
visible events among our 96 members is $3.8k$ for $k$ events per system; the
$\ge$3 observed give $k\gtrsim0.8$ --- a lower limit, since most of the 96 have
never been searched at the required resolution. Volume-complete counting thus
confirms the rate ledger: roughly one merger-scale dynamical event per massive
system during its embedded lifetime.

\subsection{Can mergers evade the timescale argument?}
This is the one place our data leave a genuine loophole --- but not the one P\&G
need. A hybrid scenario in which mass is first assembled slowly into
\emph{intermediate-mass} protostars (8--15\,M$_\odot$, $L\sim10^{3}$--$10^{4.3}$
\,L$_\odot$ --- below our census floor, hence unconstrained by the ladder) and the
top of the IMF is then built by one or a few gas-mediated mergers is consistent
with every measurement in this document: the luminous ($>$20\,M$_\odot$) phase it
predicts is exactly as short as we measure, the post-merger object reveals quickly,
and the merger events themselves occur at the observed one-per-star rate. What the
rate cannot support is a repeated merger ladder as the \emph{dominant} channel for
the whole massive IMF ($\sim$2--3 doublings per 60\,M$_\odot$ star would need
several events per star), unless the census is incomplete by the corresponding
factor --- which its authors consider possible. What no merger variant can do is
rescue the P\&G growth law \emph{as published}: their model keeps a single star
ionizing and luminous while accreting for Myr, which the ladder, the reservoir
census, and the ionizing-photon budget independently exclude. Mergers instead
\emph{compress} the luminous phase, in the same direction as our measurements.

Discriminants between rapid-accretion and merger-assisted assembly of the top of
the IMF: (i) runaway/ejected-star and expanding-bubble signatures around the
youngest revealed O stars (BN/KL-type forensics); (ii) completion of the
explosive-outflow census over our 96-member sample --- a well-defined ALMA
program, since the sample is volume-complete and the expected yield is $\sim$4$k$
visible events; (iii) multiplicity and spin/magnetic statistics of the merger
candidates (the $\sim$10\% incidence of strongly magnetic OB stars matches the
merger-product fraction); and (iv) per-event mass budgets: energies imply
intermediate-mass pairs, so merger-built O stars should sit in clusters missing
their second-most-massive members.
""")

    tex.append(r"""
\section{Sample table ($d<2$ kpc)}
\begin{longtable}{llrrrrl}
\toprule
\# & Source & $l$ & $b$ & $d$ (kpc) & $L$ ($10^4$L$_\odot$) & dist.\ method \\
\midrule
""")
    for i, r in enumerate([r for r in regs if r['d'] < 2.0 and (r['L'] >= 1e4)], 1):
        err = f"$\\pm${r['derr']:.2f}" if r['derr'] else ''
        tex.append(f"{i} & {texesc(r['name'])} & {r['glon']:.2f} & {r['glat']:+.2f} & "
                   f"{r['d']:.2f}{err} & {r['L']/1e4:.1f} & {texesc(r['method'])} \\\\\n")
    tex.append(r"""\bottomrule
\end{longtable}
\clearpage
\section{Region atlas}
For each region: (top) wide-field + ALMA zoom showing how the luminosity divides among
individual sources; (middle) VizieR broadband SED photometry entering the luminosity
estimate; (bottom) 3D-extinction distance profiles with the adopted distance.
""")

    app = []
    for r in regs:
        figs = region_figs(r['name'])
        block = []
        excluded = 'REVEALED-EXCLUDE' in r['note']
        title = texesc(r['name'])
        block.append(f"\\subsection{{{title}}}\n")
        err = f" \\pm {r['derr']:.2f}" if r['derr'] else ''
        block.append(
            f"$l={r['glon']:.3f}$, $b={r['glat']:+.3f}$; $d={r['d']:.2f}{err}$\\,kpc "
            f"({texesc(r['method'])}; {texesc(r['ref'])}); "
            f"$L_{{\\rm bol}}={r['L']:.2e}$\\,L$_\\odot$; type: {texesc(r['typ'])}; "
            f"origin: {r['origin']}.\n\n")
        if r['note']:
            block.append(f"\\textit{{{texesc(r['note'])}}}\n\n")
        for key, cap, wid in [('zoom', 'Wide-field + zoom: luminosity distribution among sources', 0.98),
                              ('sed', 'Broadband SED (VizieR photometry)', 0.62),
                              ('dist', '3D-extinction distance profile', 0.62),
                              ('gaia', 'Gaia DR3 reddening-onset check', 0.55)]:
            if key in figs:
                block.append(
                    f"\\begin{{center}}\\includegraphics[width={wid}\\linewidth]"
                    f"{{{figs[key]}}}\\\\{{\\small {cap}}}\\end{{center}}\n")
        missing = [k for k in ('zoom', 'sed', 'dist') if k not in figs]
        if missing:
            block.append(f"\\textit{{(no {', '.join(missing)} figure available)}}\n")
        block.append('\\clearpage\n')
        if excluded:
            app.extend(block)
        else:
            tex.extend(block)

    if app:
        tex.append("\\appendix\n\\section{Revealed O-star regions (excluded from the "
                   "forming-source sample)}\n")
        tex.extend(app)
    else:
        tex.append("\\appendix\n")
    if olg:
        tex.append(f"""
\\section{{Luminosity vs.\\ dynamical mass: the DIHCA VII crossmatch}}\\label{{app:olguin}}
Cross-matching our census with kinematically measured central masses (Olguin et al.\\ 2026,
DIHCA VII; plus Orion SrcI, IRAS 16562$-$3959, and Cep A HW2) yields 15
$(M_c\\sin^2 i, L_{{\\rm bol}})$ pairs with masses rescaled to our revised distances
(\\texttt{{olguin\\_crossmatch.py}}, \\texttt{{olguin\\_crossmatch.csv}}). The high-mass
luminosity deficit reported by Olguin et al.\\ is \\textbf{{reproduced}} with our
independent luminosities: every source with $M_c\\sin^2 i \\gtrsim 12$\\,M$_\\odot$ lies at
or below the ZAMS $L(M)$ (up to $\\times$6 for IRAS 18089$-$1732), while lower-mass
condensations show the opposite (region-integrated $L$ exceeds single-star ZAMS).

We attribute the deficit primarily to a single geometric selection effect rather than to
stacked physical causes: kinematic (position--velocity) samples are edge-on-biased by
construction, and edge-on systems simultaneously (i) have $\\sin^2 i \\approx 1$ and
(ii) have isotropic luminosities that underestimate the true output by factors of
2--10, because radiation escapes through the polar cavities away from the line of sight
(the flashlight effect; Zhang \\& Tan SED-model corrections). The test case: G11.92$-$0.61
ALMAe1, the highest dynamical mass in DIHCA ($M_c\\sin^2 i = 45$\\,M$_\\odot$;
Ilee et al.\\ 2018 concur with $40\\pm5$ from Keplerian fitting), has deficit $\\times$4.8
with the isotropic RMS luminosity but $\\times$0.8 --- no deficit --- with the SOMA
radiative-transfer-corrected $L_{{\\rm tot}} = 2.4\\times10^5$\\,L$_\\odot$
(Telkamp et al.\\ 2025): a measured flashlight factor of 5.9. Orion SrcI (known
$i\\approx95^\\circ$, deficit $\\times$1.8) is qualitatively consistent. Completing the
panel for IRAS 18089, W33A, and NGC 6334I(N) requires either \\texttt{{sedcreator}} SED
fits or outflow-cavity measurements from archival DIHCA CO data (2016.1.01036.S). This
appendix is deliberately separated from the main argument: it concerns per-source
inclination systematics, whereas the census conclusions rest on statistics that average
over viewing geometry.
\\begin{{figure}}[h!]
\\centering
\\includegraphics[width=0.85\\linewidth]{{{olg}}}
\\caption{{Bolometric luminosity (our distance-revised values) vs.\\ dynamical mass
($M_c\\sin^2 i$, rescaled to our distances) for the overlap of our $<3$\\,kpc sample with
DIHCA VII and related kinematic measurements. Curves: ZAMS (Ekstr\\"om+12), equal-mass
binary, star+massive disk, and the Olguin+26 power-law fit.}}
\\end{{figure}}
""")
    tex.append('\\end{document}\n')

    body = ''.join(tex).replace(r'\citefoot', r'\footnote')
    with open(os.path.join(OUT, 'main.tex'), 'w') as fh:
        fh.write(body)
    nfig = len(os.listdir(FIGD))
    print(f'wrote {OUT}/main.tex; {nfig} figures hardlinked')


if __name__ == '__main__':
    main()
