Akahsizrr commited on
Commit
2bea5bf
·
verified ·
1 Parent(s): abc4372

Upload alea/gen_numeric.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. alea/gen_numeric.py +206 -0
alea/gen_numeric.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Numeric-estimation (regress) families with exact quantile targets.
2
+
3
+ Every question targets 19 quantiles at taus .05,.10,...,.95, computed in
4
+ closed form or by exact CDF inversion — the numeric analogue of the
5
+ closed-form stochastic families.
6
+ """
7
+ import math
8
+ import random
9
+ from statistics import NormalDist
10
+
11
+ from .genbase import generate, emit, q_regress, q_choice, q_noul, validate_row
12
+
13
+ rng = random.Random()
14
+
15
+ TAUS = [0.05 * (i + 1) for i in range(19)]
16
+
17
+ FIRST = ["Mara", "Tobias", "Priya", "Kenji", "Lucia", "Omar", "Ingrid", "Felix",
18
+ "Sofia", "Dmitri", "Amara", "Jonas", "Nadia", "Pablo", "Yuki", "Elena"]
19
+ CITIES = ["Berlin", "Toronto", "Osaka", "Austin", "Lyon", "Porto", "Tallinn",
20
+ "Busan", "Valencia", "Denver"]
21
+ COURIERS = ["ParcelFox", "QuickShip", "NordPost", "BlueBike", "DHLyft"]
22
+
23
+
24
+ def _q_of_cdf(cdf_inv):
25
+ return [cdf_inv(t) for t in TAUS]
26
+
27
+
28
+ def _q_of_pmf(pmf):
29
+ """pmf: dict value->prob. Quantile = smallest v with CDF(v) >= tau."""
30
+ items = sorted(pmf.items())
31
+ cums, s, i = [], 0.0, 0
32
+ out = []
33
+ for t in TAUS:
34
+ while i < len(items) - 1 and s + items[i][1] < t - 1e-12:
35
+ s += items[i][1]
36
+ i += 1
37
+ out.append(float(items[i][0]))
38
+ return out
39
+
40
+
41
+ def gen_exp_wait():
42
+ lam = rng.choice([3, 5, 8, 12, 15, 20, 30]) # mean minutes
43
+ svc = rng.choice(["support chat", "customs clearance", "delivery courier",
44
+ "build pipeline", "payment settlement"])
45
+ state = (f"Operations log: {svc} completion times are exponentially "
46
+ f"distributed with mean {lam} minutes. One case is in flight.")
47
+ qs = [q_regress("wait", f"How many minutes until this {svc} case completes?",
48
+ _q_of_cdf(lambda t: -math.log(1 - t) * lam), unit="minutes")]
49
+ if rng.random() < 0.4:
50
+ thr = rng.choice([5, 10, 20, 30])
51
+ qs.append(q_noul("within", f"Will it complete within {thr} minutes?",
52
+ 1 - math.exp(-thr / lam)))
53
+ return state, qs
54
+
55
+
56
+ def gen_uniform_window():
57
+ a = rng.randint(2, 10)
58
+ b = a + rng.randint(2, 20)
59
+ courier = rng.choice(COURIERS)
60
+ state = (f"{courier} quotes a delivery window: uniform between {a} and "
61
+ f"{b} business days, anywhere in the window equally likely.")
62
+ qs = [q_regress("eta", "How many business days until delivery?",
63
+ _q_of_cdf(lambda t: a + t * (b - a)), unit="days")]
64
+ return state, qs
65
+
66
+
67
+ def gen_normal_metric():
68
+ mu = rng.choice([50, 100, 200, 500, 1000])
69
+ sigma = round(mu * rng.choice([0.05, 0.1, 0.15, 0.25]), 2)
70
+ metric = rng.choice(["daily active users", "orders per day",
71
+ "API latency (ms)", "warehouse stock (units)"])
72
+ city = rng.choice(CITIES)
73
+ dist = NormalDist(mu, sigma)
74
+ state = (f"Metrics for the {city} region: {metric} is well modeled as "
75
+ f"Normal(mean={mu}, sd={sigma}).")
76
+ qs = [q_regress("level", f"What value will {metric} take tomorrow?",
77
+ _q_of_cdf(dist.inv_cdf), unit=metric.split("(")[-1].rstrip(")")
78
+ if "(" in metric else "units")]
79
+ if rng.random() < 0.4:
80
+ z = rng.choice([-1.0, -0.5, 0.5, 1.0, 1.5])
81
+ thr = round(mu + z * sigma, 2)
82
+ qs.append(q_noul("over", f"Will {metric} exceed {thr}?",
83
+ 1 - dist.cdf(thr)))
84
+ return state, qs
85
+
86
+
87
+ def gen_dice_sum():
88
+ n = rng.randint(2, 5)
89
+ sides = rng.choice([4, 6, 8])
90
+ # exact pmf of sum via DP
91
+ pmf = {0: 1.0}
92
+ for _ in range(n):
93
+ nxt = {}
94
+ for s, p in pmf.items():
95
+ for f in range(1, sides + 1):
96
+ nxt[s + f] = nxt.get(s + f, 0.0) + p / sides
97
+ pmf = nxt
98
+ state = (f"{n} fair {sides}-sided dice are rolled. The quantity of "
99
+ f"interest is the sum of the faces.")
100
+ qs = [q_regress("sum", "What will the sum of the dice be?",
101
+ _q_of_pmf(pmf), unit="points")]
102
+ if rng.random() < 0.4:
103
+ t = rng.randint(n + 1, n * sides - 1)
104
+ p_ge = sum(p for s, p in pmf.items() if s >= t)
105
+ qs.append(q_noul("ge", f"Will the sum be at least {t}?", p_ge))
106
+ return state, qs
107
+
108
+
109
+ def gen_binomial_count():
110
+ n = rng.randint(5, 30)
111
+ p = rng.choice([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
112
+ item = rng.choice(["defective units in a batch", "successful signups",
113
+ "on-time departures", "failed login attempts"])
114
+ state = (f"Quality log: {n} independent trials of '{item}', each with "
115
+ f"probability {p:.2f} of occurring.")
116
+ pmf = {k: math.comb(n, k) * p ** k * (1 - p) ** (n - k) for k in range(n + 1)}
117
+ qs = [q_regress("count", f"How many '{item}' events will occur?",
118
+ _q_of_pmf(pmf), unit="count")]
119
+ return state, qs
120
+
121
+
122
+ def gen_triangular():
123
+ a = rng.randint(10, 50)
124
+ b = a + rng.randint(10, 100)
125
+ m = a + rng.random() * (b - a)
126
+ task = rng.choice(["the refactor task", "the migration", "the audit",
127
+ "the penetration test", "the data cleanup"])
128
+ state = (f"Engineering estimate for {task}: minimum {a} hours, most "
129
+ f"likely {m:.0f} hours, worst case {b} hours (triangular).")
130
+ def inv(t):
131
+ c = (m - a) / (b - a)
132
+ if t < c:
133
+ return a + math.sqrt(t * (b - a) * (m - a))
134
+ return b - math.sqrt((1 - t) * (b - a) * (b - m))
135
+ qs = [q_regress("hours", f"How many hours will {task} take?",
136
+ _q_of_cdf(inv), unit="hours")]
137
+ return state, qs
138
+
139
+
140
+ def gen_deterministic_total():
141
+ price = rng.randint(5, 200)
142
+ qty = rng.randint(1, 20)
143
+ ship = rng.choice([0, 5, 10, 15])
144
+ total = price * qty + ship
145
+ state = (f"Cart: unit price ${price}, quantity {qty}, flat shipping ${ship}. "
146
+ f"No discounts apply.")
147
+ qs = [q_regress("total", "What is the order total in dollars?",
148
+ [float(total)] * 19, unit="dollars")]
149
+ if rng.random() < 0.5:
150
+ thr = rng.choice([100, 250, 500, 1000])
151
+ qs.append(q_noul("over", f"Is the total over ${thr}?",
152
+ float(total > thr)))
153
+ return state, qs
154
+
155
+
156
+ def gen_mixture_delay():
157
+ p_fast = rng.choice([0.5, 0.6, 0.7, 0.8])
158
+ a1, b1 = sorted(rng.sample(range(1, 15), 2))
159
+ a2, b2 = sorted(rng.sample(range(15, 45), 2))
160
+ state = (f"A package ships via express with probability {p_fast:.2f} "
161
+ f"(uniform {a1}-{b1} days) or standard otherwise "
162
+ f"(uniform {a2}-{b2} days).")
163
+ def cdf(x):
164
+ def u(a, b):
165
+ return min(1.0, max(0.0, (x - a) / (b - a)))
166
+ return p_fast * u(a1, b1) + (1 - p_fast) * u(a2, b2)
167
+ # invert by bisection
168
+ qs_q = []
169
+ for t in TAUS:
170
+ lo, hi = float(a1), float(b2)
171
+ for _ in range(60):
172
+ mid = (lo + hi) / 2
173
+ if cdf(mid) < t:
174
+ lo = mid
175
+ else:
176
+ hi = mid
177
+ qs_q.append((lo + hi) / 2)
178
+ qs = [q_regress("eta", "How many days until the package arrives?", qs_q,
179
+ unit="days")]
180
+ return state, qs
181
+
182
+
183
+ FAMILIES = {"exp_wait": gen_exp_wait, "uniform_window": gen_uniform_window,
184
+ "normal_metric": gen_normal_metric, "dice_sum": gen_dice_sum,
185
+ "binomial_count": gen_binomial_count,
186
+ "triangular": gen_triangular,
187
+ "deterministic_total": gen_deterministic_total,
188
+ "mixture_delay": gen_mixture_delay}
189
+ WEIGHTS = {"exp_wait": 0.15, "uniform_window": 0.12, "normal_metric": 0.15,
190
+ "dice_sum": 0.13, "binomial_count": 0.13, "triangular": 0.12,
191
+ "deterministic_total": 0.10, "mixture_delay": 0.10}
192
+
193
+
194
+ def make_rows(n, seed):
195
+ return generate(FAMILIES, WEIGHTS, n, seed, rng)
196
+
197
+
198
+ if __name__ == "__main__":
199
+ rows = make_rows(10, 0)
200
+ for r in rows[:3]:
201
+ validate_row(r)
202
+ print(r["id"], "|", r["state"][:100])
203
+ for qid, t in r["targets"].items():
204
+ print(" ", qid, r["questions"][qid]["type"],
205
+ t[:5] if isinstance(t, list) else t)
206
+ print(f"{len(rows)} rows OK")