"""Numeric-estimation (regress) families with exact quantile targets. Every question targets 19 quantiles at taus .05,.10,...,.95, computed in closed form or by exact CDF inversion — the numeric analogue of the closed-form stochastic families. """ import math import random from statistics import NormalDist from .genbase import generate, emit, q_regress, q_choice, q_noul, validate_row rng = random.Random() TAUS = [0.05 * (i + 1) for i in range(19)] FIRST = ["Mara", "Tobias", "Priya", "Kenji", "Lucia", "Omar", "Ingrid", "Felix", "Sofia", "Dmitri", "Amara", "Jonas", "Nadia", "Pablo", "Yuki", "Elena"] CITIES = ["Berlin", "Toronto", "Osaka", "Austin", "Lyon", "Porto", "Tallinn", "Busan", "Valencia", "Denver"] COURIERS = ["ParcelFox", "QuickShip", "NordPost", "BlueBike", "DHLyft"] def _q_of_cdf(cdf_inv): return [cdf_inv(t) for t in TAUS] def _q_of_pmf(pmf): """pmf: dict value->prob. Quantile = smallest v with CDF(v) >= tau.""" items = sorted(pmf.items()) cums, s, i = [], 0.0, 0 out = [] for t in TAUS: while i < len(items) - 1 and s + items[i][1] < t - 1e-12: s += items[i][1] i += 1 out.append(float(items[i][0])) return out def gen_exp_wait(): lam = rng.choice([3, 5, 8, 12, 15, 20, 30]) # mean minutes svc = rng.choice(["support chat", "customs clearance", "delivery courier", "build pipeline", "payment settlement"]) state = (f"Operations log: {svc} completion times are exponentially " f"distributed with mean {lam} minutes. One case is in flight.") qs = [q_regress("wait", f"How many minutes until this {svc} case completes?", _q_of_cdf(lambda t: -math.log(1 - t) * lam), unit="minutes")] if rng.random() < 0.4: thr = rng.choice([5, 10, 20, 30]) qs.append(q_noul("within", f"Will it complete within {thr} minutes?", 1 - math.exp(-thr / lam))) return state, qs def gen_uniform_window(): a = rng.randint(2, 10) b = a + rng.randint(2, 20) courier = rng.choice(COURIERS) state = (f"{courier} quotes a delivery window: uniform between {a} and " f"{b} business days, anywhere in the window equally likely.") qs = [q_regress("eta", "How many business days until delivery?", _q_of_cdf(lambda t: a + t * (b - a)), unit="days")] return state, qs def gen_normal_metric(): mu = rng.choice([50, 100, 200, 500, 1000]) sigma = round(mu * rng.choice([0.05, 0.1, 0.15, 0.25]), 2) metric = rng.choice(["daily active users", "orders per day", "API latency (ms)", "warehouse stock (units)"]) city = rng.choice(CITIES) dist = NormalDist(mu, sigma) state = (f"Metrics for the {city} region: {metric} is well modeled as " f"Normal(mean={mu}, sd={sigma}).") qs = [q_regress("level", f"What value will {metric} take tomorrow?", _q_of_cdf(dist.inv_cdf), unit=metric.split("(")[-1].rstrip(")") if "(" in metric else "units")] if rng.random() < 0.4: z = rng.choice([-1.0, -0.5, 0.5, 1.0, 1.5]) thr = round(mu + z * sigma, 2) qs.append(q_noul("over", f"Will {metric} exceed {thr}?", 1 - dist.cdf(thr))) return state, qs def gen_dice_sum(): n = rng.randint(2, 5) sides = rng.choice([4, 6, 8]) # exact pmf of sum via DP pmf = {0: 1.0} for _ in range(n): nxt = {} for s, p in pmf.items(): for f in range(1, sides + 1): nxt[s + f] = nxt.get(s + f, 0.0) + p / sides pmf = nxt state = (f"{n} fair {sides}-sided dice are rolled. The quantity of " f"interest is the sum of the faces.") qs = [q_regress("sum", "What will the sum of the dice be?", _q_of_pmf(pmf), unit="points")] if rng.random() < 0.4: t = rng.randint(n + 1, n * sides - 1) p_ge = sum(p for s, p in pmf.items() if s >= t) qs.append(q_noul("ge", f"Will the sum be at least {t}?", p_ge)) return state, qs def gen_binomial_count(): n = rng.randint(5, 30) p = rng.choice([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]) item = rng.choice(["defective units in a batch", "successful signups", "on-time departures", "failed login attempts"]) state = (f"Quality log: {n} independent trials of '{item}', each with " f"probability {p:.2f} of occurring.") pmf = {k: math.comb(n, k) * p ** k * (1 - p) ** (n - k) for k in range(n + 1)} qs = [q_regress("count", f"How many '{item}' events will occur?", _q_of_pmf(pmf), unit="count")] return state, qs def gen_triangular(): a = rng.randint(10, 50) b = a + rng.randint(10, 100) m = a + rng.random() * (b - a) task = rng.choice(["the refactor task", "the migration", "the audit", "the penetration test", "the data cleanup"]) state = (f"Engineering estimate for {task}: minimum {a} hours, most " f"likely {m:.0f} hours, worst case {b} hours (triangular).") def inv(t): c = (m - a) / (b - a) if t < c: return a + math.sqrt(t * (b - a) * (m - a)) return b - math.sqrt((1 - t) * (b - a) * (b - m)) qs = [q_regress("hours", f"How many hours will {task} take?", _q_of_cdf(inv), unit="hours")] return state, qs def gen_deterministic_total(): price = rng.randint(5, 200) qty = rng.randint(1, 20) ship = rng.choice([0, 5, 10, 15]) total = price * qty + ship state = (f"Cart: unit price ${price}, quantity {qty}, flat shipping ${ship}. " f"No discounts apply.") qs = [q_regress("total", "What is the order total in dollars?", [float(total)] * 19, unit="dollars")] if rng.random() < 0.5: thr = rng.choice([100, 250, 500, 1000]) qs.append(q_noul("over", f"Is the total over ${thr}?", float(total > thr))) return state, qs def gen_mixture_delay(): p_fast = rng.choice([0.5, 0.6, 0.7, 0.8]) a1, b1 = sorted(rng.sample(range(1, 15), 2)) a2, b2 = sorted(rng.sample(range(15, 45), 2)) state = (f"A package ships via express with probability {p_fast:.2f} " f"(uniform {a1}-{b1} days) or standard otherwise " f"(uniform {a2}-{b2} days).") def cdf(x): def u(a, b): return min(1.0, max(0.0, (x - a) / (b - a))) return p_fast * u(a1, b1) + (1 - p_fast) * u(a2, b2) # invert by bisection qs_q = [] for t in TAUS: lo, hi = float(a1), float(b2) for _ in range(60): mid = (lo + hi) / 2 if cdf(mid) < t: lo = mid else: hi = mid qs_q.append((lo + hi) / 2) qs = [q_regress("eta", "How many days until the package arrives?", qs_q, unit="days")] return state, qs FAMILIES = {"exp_wait": gen_exp_wait, "uniform_window": gen_uniform_window, "normal_metric": gen_normal_metric, "dice_sum": gen_dice_sum, "binomial_count": gen_binomial_count, "triangular": gen_triangular, "deterministic_total": gen_deterministic_total, "mixture_delay": gen_mixture_delay} WEIGHTS = {"exp_wait": 0.15, "uniform_window": 0.12, "normal_metric": 0.15, "dice_sum": 0.13, "binomial_count": 0.13, "triangular": 0.12, "deterministic_total": 0.10, "mixture_delay": 0.10} def make_rows(n, seed): return generate(FAMILIES, WEIGHTS, n, seed, rng) if __name__ == "__main__": rows = make_rows(10, 0) for r in rows[:3]: validate_row(r) print(r["id"], "|", r["state"][:100]) for qid, t in r["targets"].items(): print(" ", qid, r["questions"][qid]["type"], t[:5] if isinstance(t, list) else t) print(f"{len(rows)} rows OK")