File size: 1,231 Bytes
f95cbd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""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