This original fictional lab asks how a program can produce varying trial outcomes while leaving a reproducible record. You will build a simple probability model, audit its raw draws, distinguish restarting from continuing a random stream, and explain what repeated synthetic trials cannot tell us about the world. Probability preparation is included here; no advanced probability prerequisite is silently assumed. Twelve proposed hours are an unpiloted planning allowance, not credit or measured learning time.
Execution capacity remains unresolved. Use an existing suitable Python 3 interpreter and its standard library only. No new software installation, account, API, paid package or personal data is required. If you cannot run the companion, use the printed draws for conceptual work, label it “trace only,” and do not claim execution points. Author execution does not supply you with an interpreter. The companion's pseudorandom generator is not suitable for passwords, security tokens, gambling decisions or cryptography.
Learning targets
- Define a trial, event, probability, complement and an independence assumption.
- Translate a rational success probability into an exact integer threshold rule.
- Separate theoretical expectation from the observed average and range of a finite synthetic record.
- Explain seed, local generator state, restart, checkpoint continuation and draw order.
- Preserve inputs, raw draws, source, state and environment evidence; reproduce a bounded run when execution is available.
- Audit selective seed reporting and changed-model assumptions without treating simulation as empirical validation.
1. Probability preparation: what is the model claiming?
A trial is one specified opportunity for an outcome. Our fictional detector trial has two outcomes, called success and failure. “Success” is only the label 1 and “failure” the label 0; neither is a real device observation or a judgment of a person's performance. The probability p is a model number between 0 and 1. Its complement, the failure probability, is 1-p. A probability of 1/4 says that success has one quarter of the ideal model's probability, not that each group of four must contain exactly one success.
For a simple equally likely model with four integer labels 0,1,2,3, designate label 0 as success. One of four labels is successful. More generally, for probability p=a/d, choose an integer x from 0 through d-1 and record success if x<a. There are a successful labels, so the intended probability is a/d. The strict less-than sign matters: x≤a would include a+1 labels except at a boundary. This construction avoids converting the threshold to a rounded binary fraction.
Independent trials mean, in the ideal probability model, that knowing earlier outcomes does not change the probability of a later one. Equal probability means the same p applies to each trial. These are assumptions of the fictional detector model, not conclusions obtained from setting a seed. If a detector wears out, components share a disturbance, or successful objects are removed from a finite supply, the assumptions may fail.
A batch contains n trials. Its success count is the sum of the 0/1 outcomes, and its success rate is that count divided by n. The theoretical expected count is n×p. One way to understand this is to average each 0/1 indicator over its model possibilities: its average is p; adding n such averages gives np. This expected value may be fractional even though an individual count is an integer. The formula for the expected count needs the same marginal p for each trial; independence is an additional assumption that affects the pattern of variation and joint events.
For two independent p=1/2 trials, the sequences failure–failure, failure–success, success–failure and success–success each have probability 1/4. Their success counts are 0,1,1,2. The expected count is (0+1+1+2)/4=1. This does not predict that the next batch has exactly one success. For independent p=1/4 trials, the probability of two successes is (1/4)(1/4)=1/16. Multiplying probabilities this way requires the stated independence condition; it is not a rule for every pair of events.
R1. For p=2/5, give the failure probability and successful integer labels in the range 0–4. Explain why a five-trial batch need not have exactly two successes.
R2. For the outcome sequence 1,0,1,1,0, calculate count and rate. If the model p is 1/2, give the expected count and explain why it differs from this observed count.
R3. List all four equally likely outcome sequences for two independent p=1/2 trials. Calculate the probabilities of zero, exactly one and two successes, and the expected count.
R4. A colleague says that any repeated experiment is independent. Describe a concrete shared-cause or depletion example in which that assumption fails, and identify what extra evidence or model change would be needed.
2. A deterministic generator can support a simulation
The companion creates one local random.Random(seed) instance. A pseudorandom generator is a deterministic state machine: its internal state and the next requested operation determine what happens next. The seed initializes that state. Given a compatible implementation, the same seed and the same sequence of calls recreate the same sequence. This is useful for diagnosis, but deterministic replay is not evidence that real observations would repeat or that every finite sequence has exactly the expected proportions.
Use a local generator rather than the module's shared global instance. A local instance keeps unrelated calls elsewhere from consuming your stream. Do not reseed inside the trial loop or at each batch. That would repeatedly restart the sequence and could make supposedly fresh batches identical. Distinct seeds are useful recorded cases, but different seeds do not guarantee different summaries or mathematically independent streams. Consecutive seed numbers have no scientific ranking: seed 24 is not “more random” or “better” than seed 23.
A generator state is a snapshot of its current position, not merely the original seed. The companion retains the initial state, a checkpoint after the first floor(batch_count/2) complete batches, and the final state. For six batches of four trials, the checkpoint is after 12 draws. Restoring it and making the same remaining calls should reproduce the last 12 draws and final state. Reseeding with the original seed instead reproduces the first 12 draws.
State replay also depends on the kind and order of calls. Calling randrange(4) once to print a “debug example” consumes part of the stream; later results can change. Changing the denominator changes the requested draw operation. Equivalent probabilities such as 1/2 and 2/4 define the same ideal success probability, but the implementations request different integer ranges and need not return identical seeded outcomes. The state record binds the original denominator, batch shape and seed; the replay helper rejects a changed draw contract.
The saved Python state uses JSON integers and lists, not executable object deserialization. The supported restore format is specifically version-3 Random state with a 625-integer vector and no Gaussian cache. These details are implementation-specific. The original raw draws are therefore important evidence even if a future Python version cannot reproduce or restore exactly the same stream. Record interpreter and implementation, not just the seed. A valid state shape does not authenticate its origin or prove that it arose from the stated seed.
3. Work through a complete record
worked.json sets p=1/4, n=4 trials per batch, six batches and seed 17. The observed Python 3.12.14 record has these integer draws, grouped by batch:
- Batch 1: 3,2,2,2.
- Batch 2: 1,2,0,0.
- Batch 3: 1,3,3,2.
- Batch 4: 2,3,1,0.
- Batch 5: 1,1,1,1.
- Batch 6: 2,0,0,2.
Success means x<1, so only zero succeeds. Counts are 0,2,0,1,0,2; rates are 0,1/2,0,1/4,0,1/2. The total is five successes in 24 trials, giving pooled rate 5/24. The observed mean count is 5/6, while the theoretical expected count is 4×1/4=1. Both statements can be true. The observed batch range is 0 to 2; this describes the six recorded batches, not a confidence interval, a guaranteed future range or the full model support. A four-trial batch can in principle contain 0,1,2,3 or 4 successes when 0<p<1 under the independent model.
Because all batches have equal size n, the mean of their rates equals the pooled rate: adding counts/n and dividing by the batch count is the same as total successes/(n×batch count). This equality would not generally hold if batch sizes differed. Keep counts, denominators and units visible rather than averaging whichever percentages are easiest to copy.
More synthetic trials can help investigate the model's behavior, but adding trials does not guarantee that each new cumulative proportion gets closer to p. A run may move closer, farther away and closer again. The program does not calculate inferential uncertainty, estimate a real detector's p or test a real-world hypothesis. Its theoretical p is supplied, not learned from these generated outcomes.
G1. State the worked packet's inputs, trial meaning and assumptions. Explain what is supplied and what is generated; do not call generated draws measured data.
G2. Convert every worked batch to 0/1 outcomes, count successes and verify total, pooled rate, mean count and observed range. Explain why a batch containing no successes is not automatically a bug.
G3. Recalculate the worked counts for the incorrect rule x≤1. Identify exactly which extra integer label is accepted and how this changes the intended probability. Give a boundary test that rejects this implementation.
G4. Explain why 5/6 observed mean successes does not contradict theoretical expectation 1. Distinguish observed range 0–2 from possible count range 0–4 and from an uncertainty interval.
G5. Identify the checkpoint after batch 3. Write the expected remaining raw draws and counts after correct restoration. Contrast this with the first three batches returned by reseeding at 17.
G6. Explain why one local stream across all six batches is preferable to resetting seed 17 before each batch. Predict the six batch counts under that incorrect reset procedure using the printed first batch.
4. Run, verify, reproduce and recover
The supplied files are simulation_records.py, test_simulation_records.py and three JSON fixtures. Use an existing suitable Python 3 command from the unit folder, for example:
python3 -B simulation_records.py fixtures/worked.json worked-run
Use the Unit 1 run guide if identifying a terminal, folder or existing interpreter is unfamiliar. If your verified Python 3 command is python, substitute it. Do not install software to complete this unit. -B avoids bytecode cache files. The output directory must be new and its parent must already exist.
The exact five integer fields are success_numerator, success_denominator, batch_size, batch_count and seed. The denominator is 1–1000; the numerator is 0–denominator inclusive. Batch size is 1–100; batch count is 2–40, ensuring a nonempty halfway checkpoint and a remaining suffix. The seed is 0–4294967295. Booleans, numeric strings, decimal-valued JSON numbers, extra fields and missing fields are rejected. JSON input is limited to 64 KiB; duplicate keys and nonfinite constants are rejected. These are bounded educational contracts, not a security certification for hostile files.
At p=0 or p=1, success outcomes are certain under the model. The program still consumes and saves one integer draw per trial. This consistent call pattern makes changes to the numerator comparable while the denominator, seed and batch shape stay fixed. With the same raw draws, increasing the numerator cannot turn an existing success into a failure. These paired scenarios intentionally share draws; they must not be described as independent simulation samples.
A successful run saves the original input.json bytes, source snapshot simulation_records.py, report.json, a linear summary.txt, states.json and finally run.json. The report includes raw draws, 0/1 outcomes, counts, exact fraction rates, expected and observed summaries, and the result of an actual checkpoint suffix/final-state check. The text summary gives each batch's numbers and labels, so no graph, colour or hover interaction is required.
To verify completion, parse run.json, confirm its complete status, require all five expected payload files, and recompute their SHA-256 hashes. A directory, a printed success message or the presence of a manifest alone is insufficient. Hashes detect changed bytes but do not authenticate authorship or scientific validity. A person who can replace both data and hashes can conceal tampering; this unit is not a secure-signature system.
Run the saved source and saved input into another new folder:
python3 -B worked-run/simulation_records.py worked-run/input.json replay-run
Compare report.json, summary.txt and states.json under the same recorded interpreter. The manifests can differ because invocation and destination paths differ. If an interpreter change leads to different draws, preserve both runs and diagnose the compatibility change instead of editing one to match. Seed replay is a claim about a recorded computation and environment, not a universal promise across future versions.
For a separate state-continuation check, in an existing Python session in the unit folder:
import json
import simulation_records as lab
from pathlib import Path
p = json.loads(Path('worked-run/input.json').read_text())
s = json.loads(Path('worked-run/states.json').read_text())
r = json.loads(Path('worked-run/report.json').read_text())
suffix, final = lab.replay_checkpoint(p, s)
print(suffix == r['draws'][s['checkpoint_draw_count']:])
print(final == s['final'])
Both printed values should be True for an unchanged compatible run. This checks continuation, not randomness quality. Do not load arbitrary pickle files as a shortcut. The replay helper validates a narrow JSON state shape and draw contract; it does not prove state provenance.
Failures can leave partial output, including a partial manifest. Preserve that directory, diagnose the cause and choose a fresh destination. The runner never silently overwrites an existing destination. This is recoverable evidence retention, not atomic storage or protection against simultaneous source edits. Never turn a predicted trace into “execution evidence” by filling in missing files manually.
I1. Recompute the worked report directly from saved or printed draws, without trusting its summaries. Then run all 17 tests with python3 -B -m unittest discover -v if possible. Separate arithmetic evidence from execution evidence.
I2. Predict outcomes and expected/observed summaries for numerator 0 and numerator 4 with the worked denominator unchanged. Check that 24 draws are still consumed, even though the outcomes no longer vary.
I3. Make a separate worked packet with numerator 2 and all other fields unchanged. Predict all six counts from the existing draws. Explain why this comparison shares random inputs and why the counts cannot decrease.
I4. Perform a saved-source replay and the independent state-continuation snippet when possible. Verify hashes and meaningful output equality. Explain what would happen if you restarted from the seed instead, or changed the denominator before restoring the checkpoint.
I5. Compare this proposed algorithm with the specification: “seed once; before each batch, draw one unused debug number; then draw the four recorded trials.” Does it reproduce the same record? What must be documented or changed? Explain why an ignored value is still a consumed draw.
I6. Compare probabilities represented as 1/2 and 2/4 under the same seed. Explain why they describe the same ideal probability but need not produce the same seeded outcomes. State which input/output records are needed to audit the difference without accusing a correct implementation of failure.
5. Audit what the simulation is being used to claim
H1. A researcher tries seeds 0–99, retains only the one with the highest success rate, and labels it a typical run. Identify the selection problem and propose a transparent reporting plan chosen before looking at results.
H2. A colleague duplicates one successful seeded run 20 times and says the repeated output is 20 independent samples. Explain what the duplicates actually demonstrate and what they do not add.
H3. A report says “the simulated rate is 5/24, so the real detector's success probability is exactly 5/24.” Explain the direction of the model, missing empirical evidence and a concrete next step for evaluating a real detector.
6. Formative quiz: a fair synthetic event
quiz.json uses numerator 1, denominator 2, batch size 3, batch count 4 and seed 7. The recorded draws are grouped as [1,0,1], [0,0,0], [1,0,0], [0,0,1]. These printed draws support a trace if execution is unavailable. The quiz totals 30 formative points, six per question; it is not a calibrated grade.
Q1. Convert the draws to outcomes and counts. Give batch rates, total successes, pooled rate and mean success count. [6]
Q2. Calculate the theoretical expected count per batch and compare it with the observed mean. Explain why both are meaningful and why neither fixes the next batch's count. [6]
Q3. Identify the checkpoint draw count and correct continuation sequence. Explain how seed restart differs and why calling an extra random operation can change later results. [6]
Q4. Explain why success_denominator=0 and seed=true are invalid. Give a valid boundary probability packet, and describe its certain outcomes without claiming the generator stops consuming draws. [6]
Q5. Describe and, if possible, execute a complete quiz run and saved-source replay. Verify files/hashes, compare meaningful output and state the partial-failure procedure. One of six points requires actual evidenced execution; trace-only maximum is five. [6]
7. Formative project: paired inputs and changed seeds
project.json uses p=2/3, batch size 5, eight batches and seed 23. The recorded batches are:
- 1,0,0,2,1
- 1,1,2,1,0
- 2,0,1,1,0
- 0,2,1,0,0
- 0,2,1,1,0
- 2,2,2,1,1
- 0,0,0,2,1
- 2,0,2,0,2
Keep the original packet. Name each changed packet separately. Submit a readable report and actual evidence only if you have it. Each question is worth eight points, totaling 40 formative points.
P1. State the model contract and assumptions; audit all base counts, pooled rate, observed mean, expected count and observed range from the raw draws. [8]
P2. Execute the base run, saved-source replay, checkpoint continuation and 17 tests. Verify all manifests/payload hashes and compare meaningful output. Five points require actual execution evidence; a trace-only plan can earn at most three. [8]
P3. Change only the numerator from 2 to 1. Reuse the printed base draws to predict all eight counts, total and pooled rate. Explain the paired comparison and state what has changed in the model versus the random stream. [8]
P4. Change only the base packet's seed to 24. A recorded compatible run has batch counts 3,3,3,3,3,3,3,4. Compute its total, pooled rate and mean count. Compare with seed 23 without selecting a winner; explain why a changed seed does not alter theoretical p. [8]
P5. Write a limitations and recovery note distinguishing deterministic replay, ideal model assumptions and real-world validation. Propose an honest seed-reporting rule, a concrete empirical check and a response to interrupted output. [8]
8. Delayed transfer: the same mean can hide a different model
D1. A finite box holds two good and two bad components. Draw two without replacement. Work out the probabilities of zero, one and two good components, and the expected count. Compare with two independent p=1/2 trials. Does the existing runner implement depletion?
D2. Two recorded batches have sizes 1 and 9, with success counts 1 and 0. Compute the pooled success rate and the unweighted mean of batch rates. Explain the different weighting and why the current equal-batch schema cannot represent this dataset unchanged.
Attempt each task before opening the explained key. Correct the reasoning rather than copying only the numbers. These changed contexts are deliberately outside the current companion's contract.