Akahsizrr commited on
Commit
0888f6f
·
verified ·
1 Parent(s): 266fdd8

Upload alea/gen_stoch.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. alea/gen_stoch.py +647 -0
alea/gen_stoch.py ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rich stochastic-event generators with exact closed-form ground truth.
2
+
3
+ Calibration-critical module: every target is the exact conditional
4
+ distribution, computed internally with fractions.Fraction and emitted as
5
+ floats. Families: cards, bayesian_update, markov_chain, order_stats,
6
+ conditional_joint, binomial_tail, first_success, coupon,
7
+ multi_choice_stoch, and multi_probe (shared-state multi-question rows).
8
+ """
9
+
10
+ import math
11
+ import random
12
+ from fractions import Fraction
13
+
14
+ from alea.genbase import (generate, emit, q_choice, q_noul, q_score,
15
+ validate_row, write_jsonl)
16
+
17
+ rng = random.Random()
18
+
19
+ SUITS = ("hearts", "diamonds", "clubs", "spades")
20
+ SUIT_SG = {"hearts": "heart", "diamonds": "diamond",
21
+ "clubs": "club", "spades": "spade"}
22
+ COLORS = ["red", "blue", "green", "black", "white", "amber", "violet", "gray"]
23
+ FIRST = ["Mara", "Tobias", "Priya", "Kenji", "Lucia", "Omar", "Ingrid",
24
+ "Felix", "Sofia", "Dmitri", "Amara", "Jonas", "Nadia", "Pablo"]
25
+ RANKS = ["ace", "2", "3", "4", "5", "6", "7", "8", "9", "10",
26
+ "jack", "queen", "king"]
27
+
28
+
29
+ def _p_str(p):
30
+ """Render an exact per-trial probability unambiguously in state text."""
31
+ if (p * 100).denominator == 1:
32
+ return f"probability {float(p):.2f}"
33
+ return f"probability {p.numerator} in {p.denominator}"
34
+
35
+
36
+ # ---------- cards ----------
37
+
38
+ _ONE_DRAW = [
39
+ "A standard deck of 52 playing cards is shuffled thoroughly and one "
40
+ "card is drawn uniformly at random.",
41
+ "From a well-shuffled standard 52-card deck, a dealer draws a single "
42
+ "card at random.",
43
+ "A spectator picks one card at random from a freshly shuffled "
44
+ "standard deck of 52 cards.",
45
+ ]
46
+
47
+ _TWO_DRAW = [
48
+ "A standard deck of 52 playing cards is shuffled thoroughly. Two "
49
+ "cards are drawn one at a time without replacement.",
50
+ "From a well-shuffled standard 52-card deck, a dealer deals two "
51
+ "cards in sequence without replacement.",
52
+ "Two cards are drawn at random, one after the other and without "
53
+ "replacement, from a standard 52-card deck.",
54
+ ]
55
+
56
+
57
+ def gen_cards():
58
+ if rng.random() < 0.4:
59
+ state = rng.choice(_TWO_DRAW)
60
+ kind = rng.choice(["pair", "same_suit", "both_suit",
61
+ "at_least_ace", "both_face", "ace_count",
62
+ "color_cmp"])
63
+ if kind == "pair":
64
+ # whatever the first card is, 3 of the remaining 51 match its rank
65
+ q = q_noul("pair", "Will the two cards have the same rank "
66
+ "(a pair)?", Fraction(3, 51))
67
+ elif kind == "same_suit":
68
+ q = q_noul("suit", "Will both cards be of the same suit?",
69
+ Fraction(12, 51))
70
+ elif kind == "both_suit":
71
+ s = rng.choice(SUITS)
72
+ q = q_noul("suit", f"Will both cards be {s}?",
73
+ Fraction(13, 52) * Fraction(12, 51))
74
+ elif kind == "at_least_ace":
75
+ p = 1 - Fraction(48, 52) * Fraction(47, 51)
76
+ q = q_noul("ace", "Will at least one of the two cards be an "
77
+ "ace?", p)
78
+ elif kind == "both_face":
79
+ q = q_noul("face", "Will both cards be face cards (jack, "
80
+ "queen or king)?",
81
+ Fraction(12, 52) * Fraction(11, 51))
82
+ elif kind == "ace_count":
83
+ denom = 52 * 51
84
+ dist = [float(Fraction(48 * 47, denom)),
85
+ float(Fraction(2 * 4 * 48, denom)),
86
+ float(Fraction(4 * 3, denom))]
87
+ q = q_choice("aces", "How many of the two cards are aces?",
88
+ ["Neither card is an ace.",
89
+ "Exactly one card is an ace.",
90
+ "Both cards are aces."], dist)
91
+ else:
92
+ same_c = Fraction(26 * 25, 52 * 51)
93
+ dist = [float(same_c), float(same_c),
94
+ float(1 - 2 * same_c)]
95
+ q = q_choice("colors", "How do the two cards compare in "
96
+ "color?", ["Both cards are red.",
97
+ "Both cards are black.",
98
+ "The cards are different colors."],
99
+ dist)
100
+ return state, [q]
101
+
102
+ state = rng.choice(_ONE_DRAW)
103
+ kind = rng.choice(["suit", "face", "ace", "specific", "red",
104
+ "color_choice", "suit_choice", "rank_choice"])
105
+ if kind == "suit":
106
+ s = rng.choice(SUITS)
107
+ q = q_noul("card", f"Is the drawn card a {SUIT_SG[s]}?",
108
+ Fraction(1, 4))
109
+ elif kind == "face":
110
+ q = q_noul("card", "Is the drawn card a face card (jack, queen "
111
+ "or king)?", Fraction(12, 52))
112
+ elif kind == "ace":
113
+ q = q_noul("card", "Is the drawn card an ace?", Fraction(4, 52))
114
+ elif kind == "specific":
115
+ q = q_noul("card", f"Is the drawn card the {rng.choice(RANKS)} "
116
+ f"of {rng.choice(SUITS)}?", Fraction(1, 52))
117
+ elif kind == "red":
118
+ q = q_noul("card", "Is the drawn card red (hearts or diamonds)?",
119
+ Fraction(1, 2))
120
+ elif kind == "color_choice":
121
+ q = q_choice("card", "What color is the drawn card?",
122
+ ["The card is red (hearts or diamonds).",
123
+ "The card is black (clubs or spades)."],
124
+ [0.5, 0.5])
125
+ elif kind == "suit_choice":
126
+ q = q_choice("card", "Which suit is the drawn card?",
127
+ [f"The card is a {SUIT_SG[s]}." for s in SUITS],
128
+ [0.25] * 4)
129
+ else:
130
+ q = q_choice("card", "What kind of card is drawn?",
131
+ ["The card is an ace.",
132
+ "The card is a face card (jack, queen or king).",
133
+ "The card is a number card (2 through 10)."],
134
+ [float(Fraction(4, 52)), float(Fraction(12, 52)),
135
+ float(Fraction(36, 52))])
136
+ return state, [q]
137
+
138
+
139
+ # ---------- bayesian_update ----------
140
+
141
+ def _posterior(prev, sens, spec):
142
+ """Exact P(condition | positive); args are integer percents."""
143
+ pv, se, sp = (Fraction(prev, 100), Fraction(sens, 100),
144
+ Fraction(spec, 100))
145
+ num = se * pv
146
+ return num / (num + (1 - sp) * (1 - pv))
147
+
148
+
149
+ def gen_bayesian_update():
150
+ scen = rng.choice(["medical", "spam", "defect", "fraud"])
151
+ if scen == "medical":
152
+ prev = rng.choice([1, 2, 5, 10])
153
+ elif scen == "fraud":
154
+ prev = rng.choice([1, 2, 5])
155
+ else:
156
+ prev = rng.choice([2, 5, 10, 20, 40])
157
+ sens = rng.choice([80, 85, 90, 95, 99])
158
+ spec = rng.choice([80, 90, 95, 98, 99])
159
+ post = _posterior(prev, sens, spec)
160
+ if scen == "medical":
161
+ cond = rng.choice(["a rare infection", "the condition",
162
+ "a viral disease"])
163
+ state = (f"A screening test for {cond} is given to the general "
164
+ f"population, where the prevalence is {prev}%. The test "
165
+ f"has sensitivity {sens}% (it detects {sens}% of true "
166
+ f"cases) and specificity {spec}% (it falsely flags "
167
+ f"{100 - spec}% of healthy people). "
168
+ f"{rng.choice(FIRST)} tests positive.")
169
+ pos = "The person has the condition."
170
+ neg = "The person does not have the condition."
171
+ instr = "Given the positive test, does the person have the condition?"
172
+ elif scen == "spam":
173
+ state = (f"An email filter flags spam. {prev}% of incoming mail "
174
+ f"is spam. The filter catches {sens}% of spam messages "
175
+ f"and falsely flags {100 - spec}% of legitimate mail. "
176
+ f"A message has just been flagged as spam.")
177
+ pos = "The message is spam."
178
+ neg = "The message is legitimate."
179
+ instr = "Is the flagged message actually spam?"
180
+ elif scen == "defect":
181
+ state = (f"A vision system inspects parts on an assembly line. "
182
+ f"{prev}% of parts have a defect. The system detects "
183
+ f"{sens}% of defective parts and raises false alarms "
184
+ f"on {100 - spec}% of good parts. A part has just been "
185
+ f"flagged.")
186
+ pos = "The part is defective."
187
+ neg = "The part is good."
188
+ instr = "Is the flagged part actually defective?"
189
+ else:
190
+ state = (f"A fraud detector monitors card transactions. {prev}% "
191
+ f"of all transactions are fraudulent. The detector "
192
+ f"catches {sens}% of fraudulent transactions but also "
193
+ f"flags {100 - spec}% of legitimate ones. A transaction "
194
+ f"has just been flagged.")
195
+ pos = "The transaction is fraudulent."
196
+ neg = "The transaction is legitimate."
197
+ instr = "Is the flagged transaction actually fraudulent?"
198
+ if rng.random() < 0.5:
199
+ return state, [q_noul("post", instr, post)]
200
+ pair = [(pos, post), (neg, 1 - post)]
201
+ if rng.random() < 0.5:
202
+ pair.reverse()
203
+ return state, [q_choice("post", "Which is the case?",
204
+ [t for t, _ in pair],
205
+ [float(p) for _, p in pair])]
206
+
207
+
208
+ # ---------- markov_chain ----------
209
+
210
+ def gen_markov_chain():
211
+ a = rng.choice([50, 60, 70, 80, 90]) # P(A -> A), percent
212
+ b = rng.choice([20, 30, 40, 50, 60]) # P(B -> A), percent
213
+ k = rng.choice([2, 3, 4])
214
+ start = rng.choice([0, 1])
215
+ scen = rng.choice(["weather", "server", "plant", "commute"])
216
+ if scen == "weather":
217
+ A, B, unit = "sunny", "rainy", "day"
218
+ state = (f"Weather follows a two-state pattern: a sunny day is "
219
+ f"followed by another sunny day with probability {a}%, "
220
+ f"and a rainy day is followed by a sunny day with "
221
+ f"probability {b}%. Today (day 0) is "
222
+ f"{'sunny' if start == 0 else 'rainy'}.")
223
+ instr = f"Will it be sunny on day {k}?"
224
+ elif scen == "server":
225
+ A, B, unit = "up", "down", "day"
226
+ state = (f"A server is either 'up' or 'down' each day. An up "
227
+ f"day is followed by another up day with probability "
228
+ f"{a}%; a down day is followed by an up day with "
229
+ f"probability {b}%. Today (day 0) the server is "
230
+ f"{'up' if start == 0 else 'down'}.")
231
+ instr = f"Will the server be up on day {k}?"
232
+ elif scen == "plant":
233
+ A, B, unit = "healthy", "wilted", "day"
234
+ state = (f"A greenhouse plant is either healthy or wilted each "
235
+ f"morning. A healthy morning is followed by another "
236
+ f"healthy morning with probability {a}%; a wilted "
237
+ f"morning is followed by a healthy morning with "
238
+ f"probability {b}%. This morning (day 0) the plant is "
239
+ f"{'healthy' if start == 0 else 'wilted'}.")
240
+ instr = f"Will the plant be healthy on day {k}?"
241
+ else:
242
+ A, B, unit = "on time", "delayed", "morning"
243
+ state = (f"{rng.choice(FIRST)}'s commute is either on time or "
244
+ f"delayed each morning. An on-time morning is followed "
245
+ f"by another on-time morning with probability {a}%; a "
246
+ f"delayed morning is followed by an on-time morning "
247
+ f"with probability {b}%. This morning (morning 0) the "
248
+ f"commute was {'on time' if start == 0 else 'delayed'}.")
249
+ instr = f"Will the commute be on time on morning {k}?"
250
+ pa, pb = Fraction(a, 100), Fraction(b, 100)
251
+ d = [Fraction(1), Fraction(0)] if start == 0 else [Fraction(0), Fraction(1)]
252
+ for _ in range(k):
253
+ d = [d[0] * pa + d[1] * pb, d[0] * (1 - pa) + d[1] * (1 - pb)]
254
+ if rng.random() < 0.5:
255
+ return state, [q_noul("mk", instr, d[0])]
256
+ return state, [q_choice("mk", f"What will the state be on {unit} {k}?",
257
+ [f"It is {A}.", f"It is {B}."],
258
+ [float(d[0]), float(d[1])])]
259
+
260
+
261
+ # ---------- order_stats ----------
262
+
263
+ def gen_order_stats():
264
+ n = rng.randint(2, 5)
265
+ s = rng.choice([4, 6, 8, 10, 12, 20])
266
+ state = rng.choice([
267
+ f"{n} fair {s}-sided dice are rolled.",
268
+ f"A player rolls {n} identical {s}-sided dice.",
269
+ f"{n} fair dice with {s} faces each are tossed together.",
270
+ ])
271
+ kinds = ["max_eq", "min_ge", "atleast_gt", "max_le"]
272
+ if s <= 8:
273
+ kinds += ["score_max", "score_max"]
274
+ kind = rng.choice(kinds)
275
+ if kind == "max_eq":
276
+ k = rng.randint(1, s)
277
+ p = Fraction(k ** n - (k - 1) ** n, s ** n)
278
+ q = q_noul("max", f"Will the highest die show exactly {k}?", p)
279
+ elif kind == "min_ge":
280
+ t = rng.randint(2, s)
281
+ p = Fraction((s - t + 1) ** n, s ** n)
282
+ q = q_noul("min", f"Will every die show {t} or more?", p)
283
+ elif kind == "atleast_gt":
284
+ t = rng.randint(1, s - 1)
285
+ p = 1 - Fraction(t ** n, s ** n)
286
+ q = q_noul("any", f"Will at least one die show more than {t}?", p)
287
+ elif kind == "max_le":
288
+ t = rng.randint(2, s)
289
+ p = Fraction(t ** n, s ** n)
290
+ q = q_noul("max", f"Will the highest die show {t} or less?", p)
291
+ else:
292
+ levels = [f"The highest die shows {k}." for k in range(1, s + 1)]
293
+ dist = [float(Fraction(k ** n - (k - 1) ** n, s ** n))
294
+ for k in range(1, s + 1)]
295
+ q = q_score("max", "What will the highest single die show?",
296
+ levels, dist)
297
+ return state, [q]
298
+
299
+
300
+ # ---------- conditional_joint ----------
301
+
302
+ _JOINT_SCEN = [
303
+ dict(rows=["Line 1", "Line 2", "Line 3"], cols=["pass", "fail"],
304
+ noun="parts", sing="part", col_word="result",
305
+ intro="A factory quality log records", row_noun="line"),
306
+ dict(rows=["treatment A", "treatment B"], cols=["recovered", "unchanged"],
307
+ noun="patients", sing="patient", col_word="outcome",
308
+ intro="A clinic tracked", row_noun="treatment group"),
309
+ dict(rows=["engineering", "sales", "support"], cols=["remote", "on-site"],
310
+ noun="employees", sing="employee", col_word="location",
311
+ intro="An HR survey of", row_noun="department"),
312
+ ]
313
+
314
+
315
+ def gen_conditional_joint():
316
+ sc = rng.choice(_JOINT_SCEN)
317
+ rows_l, cols_l = sc["rows"], sc["cols"]
318
+ cells = {(i, j): rng.randint(5, 50)
319
+ for i in range(len(rows_l)) for j in range(len(cols_l))}
320
+ total = sum(cells.values())
321
+ parts = "; ".join(
322
+ f"{rows_l[i]}: " + ", ".join(
323
+ f"{cells[(i, j)]} {cols_l[j]}" for j in range(len(cols_l)))
324
+ for i in range(len(rows_l)))
325
+ state = (f"{sc['intro']} {total} {sc['noun']}: {parts}. One "
326
+ f"{sc['sing']} is chosen uniformly at random from the "
327
+ f"{total}.")
328
+ mode = rng.choice(["row_noul", "col_noul", "row_choice",
329
+ "col_choice"])
330
+ if mode == "row_noul":
331
+ i = rng.randrange(len(rows_l))
332
+ j = rng.randrange(len(cols_l))
333
+ rs = sum(cells[(i, jj)] for jj in range(len(cols_l)))
334
+ q = q_noul("cond", f"Given the {sc['sing']} is from {rows_l[i]}, "
335
+ f"is its {sc['col_word']} '{cols_l[j]}'?",
336
+ Fraction(cells[(i, j)], rs))
337
+ elif mode == "col_noul":
338
+ j = rng.randrange(len(cols_l))
339
+ i = rng.randrange(len(rows_l))
340
+ cs = sum(cells[(ii, j)] for ii in range(len(rows_l)))
341
+ q = q_noul("cond", f"Given the {sc['sing']}'s {sc['col_word']} "
342
+ f"is '{cols_l[j]}', is it from {rows_l[i]}?",
343
+ Fraction(cells[(i, j)], cs))
344
+ elif mode == "row_choice":
345
+ i = rng.randrange(len(rows_l))
346
+ rs = sum(cells[(i, jj)] for jj in range(len(cols_l)))
347
+ dist = [float(Fraction(cells[(i, jj)], rs))
348
+ for jj in range(len(cols_l))]
349
+ q = q_choice("cond",
350
+ f"The {sc['sing']} is from {rows_l[i]}. What is "
351
+ f"its {sc['col_word']}?",
352
+ [f"Its {sc['col_word']} is '{c}'." for c in cols_l],
353
+ dist)
354
+ else:
355
+ j = rng.randrange(len(cols_l))
356
+ cs = sum(cells[(ii, j)] for ii in range(len(rows_l)))
357
+ dist = [float(Fraction(cells[(ii, j)], cs))
358
+ for ii in range(len(rows_l))]
359
+ q = q_choice("cond",
360
+ f"The {sc['sing']}'s {sc['col_word']} is "
361
+ f"'{cols_l[j]}'. Which {sc['row_noun']} is it from?",
362
+ [f"It is from {r}." for r in rows_l], dist)
363
+ return state, [q]
364
+
365
+
366
+ # ---------- binomial_tail ----------
367
+
368
+ def _binom_tail(n, p, k):
369
+ return sum(math.comb(n, i) * p ** i * (1 - p) ** (n - i)
370
+ for i in range(k, n + 1))
371
+
372
+
373
+ def gen_binomial_tail():
374
+ scen = rng.choice(["freethrow", "defect", "quiz", "packet"])
375
+ if scen == "freethrow":
376
+ p = rng.choice([Fraction(1, 2), Fraction(3, 5),
377
+ Fraction(7, 10), Fraction(4, 5)])
378
+ n = rng.randint(6, 10)
379
+ k = rng.randint(max(2, n - 4), n)
380
+ nm = rng.choice(FIRST)
381
+ state = (f"{nm} is a basketball player who makes each free "
382
+ f"throw with {_p_str(p)}, independently. {nm} takes "
383
+ f"{n} free throws.")
384
+ instr = f"Will {nm} make at least {k} of the {n} free throws?"
385
+ stem = f"How many of the {n} free throws go in?"
386
+ elif scen == "defect":
387
+ p = rng.choice([Fraction(1, 20), Fraction(1, 10), Fraction(1, 5)])
388
+ n = rng.randint(8, 15)
389
+ k = rng.randint(1, 3)
390
+ state = (f"A machine produces a defective part with {_p_str(p)} "
391
+ f"each cycle, independently. A batch of {n} parts is "
392
+ f"inspected.")
393
+ instr = (f"Will the batch contain at least {k} defective "
394
+ f"part{'s' if k > 1 else ''}?")
395
+ stem = "How many defective parts does the batch contain?"
396
+ elif scen == "quiz":
397
+ p = Fraction(1, 4)
398
+ n = rng.randint(5, 8)
399
+ k = rng.randint(2, n - 1)
400
+ state = (f"A quiz has {n} multiple-choice questions with 4 "
401
+ f"options each. {rng.choice(FIRST)} guesses uniformly "
402
+ f"at random on every question.")
403
+ instr = f"Will they get at least {k} of the {n} questions right?"
404
+ stem = "How many questions do they get right?"
405
+ else:
406
+ p = rng.choice([Fraction(9, 10), Fraction(19, 20)])
407
+ n = rng.randint(4, 8)
408
+ k = rng.randint(n - 2, n)
409
+ state = (f"Each data packet sent over a link arrives with "
410
+ f"{_p_str(p)}, independently of the others. {n} "
411
+ f"packets are sent.")
412
+ instr = f"Will at least {k} of the {n} packets arrive?"
413
+ stem = f"How many of the {n} packets arrive?"
414
+ tail = _binom_tail(n, p, k)
415
+ if rng.random() < 0.45:
416
+ return state, [q_choice("tail", stem,
417
+ [f"At least {k}.", f"Fewer than {k}."],
418
+ [float(tail), float(1 - tail)])]
419
+ return state, [q_noul("tail", instr, tail)]
420
+
421
+
422
+ # ---------- first_success ----------
423
+
424
+ def gen_first_success():
425
+ scen = rng.choice(["bullseye", "sale", "defect", "crash", "hire"])
426
+ p = rng.choice([Fraction(1, 10), Fraction(1, 6), Fraction(1, 5),
427
+ Fraction(1, 4), Fraction(3, 10), Fraction(2, 5),
428
+ Fraction(1, 2)])
429
+ k = rng.randint(2, 8)
430
+ p_first = 1 - (1 - p) ** k
431
+ if scen == "bullseye":
432
+ state = (f"{rng.choice(FIRST)} throws darts; each throw hits "
433
+ f"the bullseye with {_p_str(p)}, independently. They "
434
+ f"throw {k} darts.")
435
+ instr = f"Will at least one of the {k} darts hit the bullseye?"
436
+ elif scen == "sale":
437
+ state = (f"A salesperson closes each call with {_p_str(p)}, "
438
+ f"independently. They make {k} calls today.")
439
+ instr = f"Will they close at least one sale within the {k} calls?"
440
+ elif scen == "defect":
441
+ state = (f"Each item on a line is defective with {_p_str(p)}, "
442
+ f"independently. {k} items are checked in sequence.")
443
+ instr = (f"Will a defective item appear within the {k} checked "
444
+ f"items?")
445
+ elif scen == "crash":
446
+ state = (f"A flaky test crashes on each run with {_p_str(p)}, "
447
+ f"independently. The test is run {k} times.")
448
+ instr = f"Will the test crash at least once in the {k} runs?"
449
+ else:
450
+ state = (f"Each interviewed candidate accepts the job offer "
451
+ f"with {_p_str(p)}, independently. {k} candidates are "
452
+ f"interviewed.")
453
+ instr = f"Will at least one of the {k} candidates accept?"
454
+ if rng.random() < 0.4:
455
+ return state, [q_choice("first",
456
+ "What happens across the trials?",
457
+ [f"A success occurs within the {k} "
458
+ f"trials.",
459
+ f"No success occurs in the {k} "
460
+ f"trials."],
461
+ [float(p_first), float(1 - p_first)])]
462
+ return state, [q_noul("first", instr, p_first)]
463
+
464
+
465
+ # ---------- coupon ----------
466
+
467
+ def gen_coupon():
468
+ scen = rng.choice(["cereal", "sticker", "loot", "vending"])
469
+ m = rng.randint(3, 5)
470
+ n = rng.randint(m, m + 8)
471
+ t0 = rng.randint(1, m)
472
+ if scen == "cereal":
473
+ state = (f"Each box of cereal contains one of {m} prize types, "
474
+ f"each type equally likely. {rng.choice(FIRST)} buys "
475
+ f"{n} boxes.")
476
+ unit = "boxes"
477
+ elif scen == "sticker":
478
+ state = (f"Each sticker pack contains one of {m} sticker "
479
+ f"designs, each design equally likely. "
480
+ f"{rng.choice(FIRST)} buys {n} packs.")
481
+ unit = "packs"
482
+ elif scen == "loot":
483
+ state = (f"A game loot box drops one of {m} item types, each "
484
+ f"equally likely. A player opens {n} loot boxes.")
485
+ unit = "loot boxes"
486
+ else:
487
+ state = (f"A vending machine dispenses one of {m} toy types at "
488
+ f"random, each equally likely. A child gets {n} toys.")
489
+ unit = "toys"
490
+ kind = rng.choice(["all", "specific", "missing"])
491
+ if kind == "all":
492
+ # inclusion-exclusion over the m types
493
+ p = sum(Fraction((-1) ** j) * math.comb(m, j) * (m - j) ** n
494
+ for j in range(m)) / m ** n
495
+ instr = f"Will they collect all {m} types in the {n} {unit}?"
496
+ if rng.random() < 0.45:
497
+ return state, [q_choice(
498
+ "coupon", "What does the collection look like after the "
499
+ f"{n} {unit}?",
500
+ [f"All {m} types were collected.",
501
+ "At least one type is still missing."],
502
+ [float(p), float(1 - p)])]
503
+ elif kind == "specific":
504
+ p = 1 - Fraction((m - 1) ** n, m ** n)
505
+ instr = (f"Will at least one of the {n} {unit} contain type "
506
+ f"{t0}?")
507
+ if rng.random() < 0.45:
508
+ return state, [q_choice(
509
+ "coupon", f"What happens with type {t0} across the {n} "
510
+ f"{unit}?",
511
+ [f"Type {t0} appears at least once.",
512
+ f"Type {t0} never appears."],
513
+ [float(p), float(1 - p)])]
514
+ else:
515
+ p = Fraction((m - 1) ** n, m ** n)
516
+ instr = f"Will type {t0} still be missing after the {n} {unit}?"
517
+ return state, [q_noul("coupon", instr, p)]
518
+
519
+
520
+ # ---------- multi_choice_stoch ----------
521
+
522
+ def gen_multi_choice_stoch():
523
+ variant = rng.choice(["dice_buckets", "two_cards", "coins", "wheel"])
524
+ if variant == "dice_buckets":
525
+ s1, s2 = rng.choice([(6, 6), (8, 8), (6, 4), (4, 4), (10, 10)])
526
+ counts = {}
527
+ for a_ in range(1, s1 + 1):
528
+ for b_ in range(1, s2 + 1):
529
+ counts[a_ + b_] = counts.get(a_ + b_, 0) + 1
530
+ total = s1 * s2
531
+ lo, hi = min(counts), max(counts)
532
+ nb = rng.choice([3, 4])
533
+ cuts = sorted(rng.sample(range(lo + 1, hi), nb - 1))
534
+ edges = [lo - 1] + cuts + [hi]
535
+ opts, dist = [], []
536
+ for e_lo, e_hi in zip(edges[:-1], edges[1:]):
537
+ c = sum(v for s_, v in counts.items() if e_lo < s_ <= e_hi)
538
+ label = (f"The total is {e_lo + 1}" if e_lo + 1 == e_hi
539
+ else f"The total is {e_lo + 1} to {e_hi}")
540
+ opts.append(label + ".")
541
+ dist.append(float(Fraction(c, total)))
542
+ state = rng.choice([
543
+ f"Two fair dice are rolled: one {s1}-sided and one "
544
+ f"{s2}-sided. Their results are added.",
545
+ f"A {s1}-sided die and a {s2}-sided die, both fair, are "
546
+ f"rolled and summed.",
547
+ ])
548
+ q = q_choice("sum", "Into which range does the total fall?",
549
+ opts, dist)
550
+ elif variant == "two_cards":
551
+ state = rng.choice(_TWO_DRAW)
552
+ same_color = Fraction(26 * 25, 52 * 51)
553
+ mixed = 1 - 2 * same_color
554
+ q = q_choice("colors", "How do the two cards compare in color?",
555
+ ["Both cards are red.", "Both cards are black.",
556
+ "The cards are different colors."],
557
+ [float(same_color), float(same_color), float(mixed)])
558
+ elif variant == "coins":
559
+ n = rng.choice([3, 4, 5])
560
+ state = rng.choice([
561
+ f"{n} fair coins are flipped at once.",
562
+ f"{rng.choice(FIRST)} flips {n} fair coins.",
563
+ ])
564
+ opts = [f"Exactly {k} coin{'s' if k != 1 else ''} land "
565
+ f"{'heads' if k != 1 else 'heads'}." for k in range(n + 1)]
566
+ dist = [float(Fraction(math.comb(n, k), 2 ** n))
567
+ for k in range(n + 1)]
568
+ q = q_choice("heads", "How many coins land heads?", opts, dist)
569
+ else:
570
+ cols = rng.sample(COLORS, 3)
571
+ segs = [rng.randint(1, 6) for _ in cols]
572
+ tot = sum(segs)
573
+ state = (f"A spinner is divided into {tot} equal sectors: " +
574
+ ", ".join(f"{s_} {c}" for s_, c in zip(segs, cols)) +
575
+ ". It is spun once.")
576
+ q = q_choice("spin", "Which color does the spinner land on?",
577
+ [f"The spinner lands on {c}." for c in cols],
578
+ [s_ / tot for s_ in segs])
579
+ return state, [q]
580
+
581
+
582
+ # ---------- multi_probe (shared-state multi-question) ----------
583
+
584
+ def gen_multi_probe():
585
+ cols = rng.sample(COLORS, rng.choice([2, 3]))
586
+ counts = {c: rng.randint(2, 9) for c in cols}
587
+ total = sum(counts.values())
588
+ listing = ", ".join(f"{counts[c]} {c}" for c in cols)
589
+ rep = rng.random() < 0.3
590
+ how = "with" if rep else "without"
591
+ state = (f"An urn contains {listing} balls ({total} total). Two "
592
+ f"balls are drawn one at a time {how} replacement.")
593
+ c0 = rng.choice(cols)
594
+ qs = [q_noul("first", f"Is the first ball drawn {c0}?",
595
+ Fraction(counts[c0], total))]
596
+ if rep:
597
+ p_same = sum(Fraction(v * v) for v in counts.values()) \
598
+ / (total * total)
599
+ else:
600
+ p_same = sum(Fraction(v * (v - 1)) for v in counts.values()) \
601
+ / (total * (total - 1))
602
+ qs.append(q_noul("same", "Are both drawn balls the same color?",
603
+ p_same))
604
+ if rng.random() < 0.75:
605
+ if rep:
606
+ dist = [float(Fraction(counts[c], total)) for c in cols]
607
+ else:
608
+ dist = [float(Fraction(counts[c] - (1 if c == c0 else 0),
609
+ total - 1)) for c in cols]
610
+ qs.append(q_choice(
611
+ "second",
612
+ f"The first ball is {c0}. Which color is the second ball?",
613
+ [f"The second ball is {c}." for c in cols], dist))
614
+ return state, qs
615
+
616
+
617
+ FAMILIES = {
618
+ "cards": gen_cards,
619
+ "bayesian_update": gen_bayesian_update,
620
+ "markov_chain": gen_markov_chain,
621
+ "order_stats": gen_order_stats,
622
+ "conditional_joint": gen_conditional_joint,
623
+ "binomial_tail": gen_binomial_tail,
624
+ "first_success": gen_first_success,
625
+ "coupon": gen_coupon,
626
+ "multi_choice_stoch": gen_multi_choice_stoch,
627
+ "multi_probe": gen_multi_probe,
628
+ }
629
+
630
+ WEIGHTS = {
631
+ "cards": 0.12, "bayesian_update": 0.12, "markov_chain": 0.10,
632
+ "order_stats": 0.10, "conditional_joint": 0.10,
633
+ "binomial_tail": 0.12, "first_success": 0.08, "coupon": 0.08,
634
+ "multi_choice_stoch": 0.10, "multi_probe": 0.08,
635
+ }
636
+
637
+
638
+ def make_rows(n, seed):
639
+ return generate(FAMILIES, WEIGHTS, n, seed, rng)
640
+
641
+
642
+ if __name__ == "__main__":
643
+ rows = make_rows(10, 0)
644
+ for r in rows[:3]:
645
+ validate_row(r)
646
+ print(r["id"], "|", r["state"][:100])
647
+ print(f"{len(rows)} rows OK")