Celestis-RL / src /celestis_rl /allocation.py
PureOne's picture
Release Celestis-RL v2.0.0: audited research reference
f95cbd4 verified
Raw History Blame Contribute Delete
1.23 kB
"""Optimal integer allocation of a fixed tail-draw budget for fixed heads."""
import heapq
import numpy as np
def allocate_tail_draws(variance_numerators, total_draws: int) -> np.ndarray:
"""Minimize sum_i A_i/m_i, m_i>=1 integer, sum m_i=total_draws.
A_i must be fixed before production draws (known or independent pilot).
The greedy largest marginal decrease A_i/[m_i(m_i+1)] is exact for this
separable discrete-convex problem. It does not optimize head sizes jointly.
Zero-A sites keep their mandatory one draw unless all marginal gains tie.
"""
a = np.asarray(variance_numerators, dtype=np.float64)
if a.ndim != 1 or not len(a) or not np.isfinite(a).all() or (a < 0).any():
raise ValueError("nonnegative finite 1D numerators required")
if isinstance(total_draws, bool) or not isinstance(total_draws, int) or total_draws < len(a):
raise ValueError("need at least one draw per tail")
m = np.ones(len(a), dtype=np.int64)
heap = [(-float(x)/2, i) for i, x in enumerate(a)]
heapq.heapify(heap)
for _ in range(total_draws-len(a)):
_, i = heapq.heappop(heap)
m[i] += 1
heapq.heappush(heap, (-float(a[i])/(m[i]*(m[i]+1)), i))
return m