TMP-SCI-204 · Planned course · Unfinished learning resource

Unit 6: Discrete-time scientific models and convergence checks

This original, fictional lab continues Units 1–5. You will construct a time-stepping model, check properties of every state, compare three grids at the same final time, and reproduce a bounded computational claim. No calculus prerequisite is assumed: the recurrence and the separate continuous reference are supplied and explained. The proposed sixteen hours are an unpiloted allowance, not credits or a measured learning time.

Execution capacity remains unresolved. Reading and paper tracing can support conceptual outcomes. They cannot establish that you ran, tested or reproduced a program. Use only an already available, suitable Python 3 interpreter with the standard library; no installation, account, API, package purchase or personal data is required. If execution is unavailable, label your work “trace only” and leave execution credit unclaimed. This unit does not provide an interpreter.

What you should be able to explain and demonstrate

  1. Express a physical story as explicit state variables, units, assumptions and a recurrence.
  2. Update coupled quantities using a single transfer calculated from the old state.
  3. Distinguish conservation, nonnegativity and approximation accuracy; check entire trajectories.
  4. Compare timestep choices without changing the final time or confusing refinement with parameter changes.
  5. Use independent formulas and edge cases to test an implementation; interpret a rounded reference cautiously.
  6. Preserve inputs, source, outputs and execution records, then report what the evidence does and does not support.

1. Preparation: time, ratios and repeated multiplication

A state is a description of the system at one time. Write A_j for the mass in container A after j steps, and B_j for the mass in B. The subscript is a counter, not multiplication. A_0 and B_0 are the initial masses. If the experiment lasts T minutes and has N equal steps, each step lasts h = T/N minutes; step j is at time jh. The states include the initial state, so N steps produce N+1 states.

A rate k measured “per minute” multiplied by h minutes gives the dimensionless fraction kh. For k = 1/2 per minute and h = 1 minute, kh = 1/2. Multiplying kh by 64 grams gives a proposed transfer of 32 grams. We do not multiply the mass by k alone and call that a complete step: k times mass has units grams per minute, not grams.

An exponent means repeated multiplication: q^3 = q × q × q; q^0 = 1. A negative q changes the sign on each multiplication. Fractions can be retained exactly instead of rounded after every step. Exact arithmetic prevents a class of rounding effects, but it does not make a fictional model physically correct or a finite timestep infinitesimal.

R1. A simulation lasts 3 minutes with 6 equal steps. Give h, the time at step 4, and the number of recorded states. Explain the units of k × h when k = 2/3 per minute.

R2. Evaluate (3/4)^2 and (-1/2)^3. Explain why a positive endpoint at step 2 does not rule out a negative state at step 1.

R3. A contains 20 g and B contains 5 g. Calculate one transfer at k = 1/4 per minute and h = 2 minutes, then the next A, B and total. Calculate the transfer before changing either state.

R4. Identify three different claims: “the recorded total stays fixed,” “the algorithm follows its stated recurrence,” and “the model predicts a real system adequately.” What evidence could support each? Which is not supplied by this fictional lab?

2. Build a model before running a loop

Our story is a closed pair of containers. Material moves from A to B; it never returns, enters from outside or leaves the pair. We treat the contents as masses in grams, not concentrations. The proportional transfer rate k is constant in time. We assume no capacity limit, delay, chemical transformation or change in rate as B fills. Those assumptions define a deliberately small model, not a general laboratory apparatus.

At the start of a step, calculate one proposed transfer:

transfer_j = k × h × A_j.

Then update both containers from that same old state:

A_(j+1) = A_j - transfer_j. B_(j+1) = B_j + transfer_j.

The transfer is only an approximation to what the supplied constant-rate continuous model would transfer over the whole interval. In the latter, A declines continuously, so the instantaneous transfer rate also declines. Holding the beginning-of-step rate fixed tends to remove too much on an admissible nonzero step. A smaller h changes that approximation. “Constant k” does not mean “constant grams transferred in every step.”

A common coding error changes A first and then recalculates the addition to B using the new A. That subtracts one transfer but adds a different one. Instead, calculate transfer = k * h * a once, then use a, b = a - transfer, b + transfer. Python evaluates the right-hand expressions before assigning the new pair. A loop that uses temporary names for the two next states is equally valid.

Adding the two update equations cancels the transfer: next A + next B = old A + old B. Starting from M = A_0 + B_0, the total should remain M. This is an invariant, a property the correct recurrence preserves. It is a powerful test because it concerns every state. It is not a sufficient test: a wrong method could conserve total while placing material in the wrong container.

G1. State the inputs, units, initial state, output horizon and four modeling assumptions for worked.json. Explain why its quantities are masses rather than concentrations.

G2. For the worked case A_0 = 64 g, B_0 = 16 g, k = 1/2 per minute, T = 2 minutes and N = 2, write all three states. Show both transfers and check the total at every state.

G3. Starting from the worked initial state with h = 1 minute, subtract the correct transfer from A, but mistakenly add k × h × the new A to B. Calculate the incorrect next pair and total. Give an assertion that catches this bug, and explain why a total-only assertion cannot detect swapping the correct A and B values.

3. A conserved quantity can still be impossible

Rearrange the A update as A_(j+1) = q × A_j, with q = 1 - kh. Thus A_j = A_0 × q^j, and B_j = M - A_j. This provides a separate endpoint oracle: compute a power directly rather than reproduce the program's step loop. An oracle derived from the same assumptions checks implementation, not those assumptions against reality.

For all nonnegative starting masses, 0 ≤ kh ≤ 1 is a sufficient condition for every step to remain nonnegative. Then 0 ≤ q ≤ 1, A never increases, and B never decreases. At kh = 1, the discrete update empties A in one step. That is allowed by this recurrence, but it is not the same as the supplied positive continuous reference at a finite time when A_0 > 0.

If kh > 1 and A_0 > 0, the very first transfer exceeds the material in A. Negative masses follow. For 1 < kh < 2, q is between -1 and 0; signs alternate while magnitudes decrease. At kh = 2, q = -1 and the magnitudes persist. For kh > 2, |q| > 1 and they grow. These comparisons describe this scalar recurrence; they are not a general stability theorem for other methods or models. The physical nonnegativity requirement is stricter than merely having |q| ≤ 1.

The companion deliberately accepts a valid numeric packet with a coarse nonphysical timestep. It keeps negative states and flags the first one. Silently replacing a negative A with zero would conceal the numerical failure and could break conservation depending on how B is handled. A valid input format does not guarantee a scientifically admissible trajectory.

For failure.json, A_0 = 8 g, B_0 = 0, k = 3 per minute, T = 1 minute and N = 2. Here h = 1/2 and q = -1/2. The states are (8,0), (-4,12), (2,6). The final pair is nonnegative and every total is 8, yet the path is physically inadmissible. Checking only the endpoint misses the problem.

There is a useful exceptional case. If A_0 = 0, A stays zero even when kh > 1. Therefore a false “positivity condition” flag describes a condition that is not guaranteed for arbitrary starts; it does not by itself assert that this particular trajectory contains a negative state. Inspect the separate observed nonnegative flag. Zero rate is another special case: both masses remain fixed and grid differences vanish.

G4. Compute q for kh = 1/2, 1, 3/2, 2 and 3. Classify the resulting A sequence for A_0 > 0. Identify which cases guarantee nonnegative mass under the model assumptions.

G5. Trace failure.json and explain how it can conserve mass, end nonnegative and still fail. Predict whether N = 4 will satisfy the positivity condition, without running the program.

G6. Derive A_N = A_0(1-kT/N)^N and B_N = M-A_N from repeated multiplication. Use it to independently check the worked N = 4 endpoint. Describe the roles of an implementation oracle and empirical observations separately.

4. Compare grids at one physical time

The companion runs N, 2N and 4N steps, always over the same duration T. The corresponding steps are h, h/2 and h/4. Do not halve h while keeping the number of steps fixed: that also halves the final time and confounds the comparison.

For worked.json, the A endpoints at 2 minutes are 16 g with 2 steps, 81/4 = 20.25 g with 4, and 5764801/262144 ≈ 21.990971 g with 8. All conserve 80 g. The absolute coarse-to-medium gap is 17/4 = 4.25 g. The medium-to-fine gap is 456385/262144 ≈ 1.740971 g. Their ratio is about 2.441. These finite observations are compatible with improving approximation. They do not prove convergence, establish a universal error bound or certify an order of accuracy from three grids.

We supply a separate ideal constant-rate continuous-model reference:

A(T) = A_0 × exp(-kT); B(T) = M - A(T).

The function exp(x) is the exponential function; exp(0) = 1, and exp(-x) is positive and decreases as nonnegative x increases. You may use the supplied value without deriving calculus. This reference represents the limiting continuous story rather than a step update. The program evaluates it with Decimal at 50-digit working precision. Inputs and arithmetic involved in that calculation can still be rounded. It is not a certified interval enclosing the mathematical value.

For worked.json, the rounded reference A is approximately 23.544284 g. Absolute endpoint differences are about 7.544284 g, 3.294284 g and 1.553314 g. Even an exact match with this reference would be agreement with an idealized model, not measurement of a real apparatus. Separate three questions: did the code implement the recurrence, did the discrete approximation approach the chosen reference, and does that reference describe the intended physical system?

When a fine gap is zero, the companion reports the gap ratio as null, meaning undefined. It does not divide by zero, report infinity automatically or claim perfect scientific accuracy. Zero rate and zero initial A legitimately produce zero gaps. Different grids might also agree at a quantity that fails to expose an error. Always inspect model assumptions and test more than one diagnostic.

5. Use the companion without erasing evidence

The files are transfer_model.py, test_transfer_model.py and four JSON fixtures. From this unit's folder, an example command is:

python3 -B transfer_model.py fixtures/worked.json worked-run

If your existing installation calls Python python, use its verified Python 3 command instead. Do not install software to satisfy this example. -B avoids bytecode cache files. The destination must be a new directory whose parent already exists. Quotes around paths are needed if your shell path contains spaces. Read the Unit 1 run guide if opening a terminal or identifying a working directory is unfamiliar.

The five fields are exactly a0_g, b0_g, k_per_min, duration_min and base_steps. The first four use unsigned integer or fraction strings such as "64", "1/2" or "0". Decimal spelling "0.5", spaces, negative values, leading zeros, scientific notation and denominator zero are rejected. Written denominators may not exceed 1000 and strings may not exceed 24 characters. Initial masses are 0–1000 g each, k is 0–10 per minute, and duration is positive and at most 100 minutes. base_steps is a JSON integer 1–64, not a string, decimal or boolean. The derived grids therefore have at most 256 steps. JSON bytes are limited to 64 KiB; duplicate object keys and nonfinite constants are rejected. These bounds make the educational workload finite, not a hostile-input security guarantee.

A successful run writes input.json with the original bytes, a snapshot of transfer_model.py, report.json, a linear summary.txt and finally run.json. The summary names every time/state, total, condition and failure flag without relying on a graph or colour. Fractions in report.json are strings; null is used for an undefined gap ratio. Use labels and units when reading the long rational values aloud or in your report.

The manifest records interpreter information, invocation, original path arguments and SHA-256 hashes of the four payloads. To regard an output as complete, parse run.json, confirm status complete, confirm the expected files exist and recompute every listed hash. A directory, a printed completion message or a status word alone is not enough. Hashes detect changed bytes, not authorship, scientific validity or malicious tampering by someone who can rewrite both files and hashes.

Reproduce using the saved source and saved input into another new directory, for example python3 -B worked-run/transfer_model.py worked-run/input.json replay-run. Compare report.json and summary.txt. Manifests legitimately differ because invocation and destination differ; byte equality of every manifest is not a success requirement. Preserve a note explaining whether you executed or only predicted this procedure.

The runner refuses an existing destination. A failure while writing can leave a partial directory, possibly even a partial run.json. Preserve it for diagnosis. Do not relabel it complete or silently overwrite it. Correct the cause and choose a fresh directory. This is recoverable evidence retention, not transactional or atomic output, durable-storage assurance or a guarantee against a concurrent source edit. Review the actual snapshot when reproducibility matters.

I1. Run the worked fixture if possible, otherwise trace it. Independently check all three endpoint pairs using powers and the total. Record the two gaps and explain why they are not error bounds.

I2. In a copy of worked.json, set k_per_min to "0". Predict all endpoints and the gap ratio before running. Explain what the observation can and cannot establish.

I3. In a copy of failure.json, set a0_g to "0". Predict the coarse positivity-condition flag, observed nonnegative flag and endpoint. Explain why the two flags need not agree.

I4. Check q = -1 and q = -2 with A_0 = 1, B_0 = 0, T = 2 and N = 2, using k = 2 and k = 3 respectively. Show all states, not just the endpoints. Contrast bounded oscillation, growing oscillation and physical admissibility.

I5. Produce a saved-source replay into a fresh directory. Verify all manifest-listed hashes, compare the two report/summary pairs, run the 15 named tests with python3 -B -m unittest discover -v, and record exact commands/results. If tracing, specify expected checks without claiming execution. Try an existing destination only after preserving its evidence; confirm refusal and unchanged files.

I6. Double both initial masses in worked.json, keeping k, T and N fixed. Predict A, B, total, absolute refinement gaps and gap ratio. Explain what changes if instead only B_0 increases by 5 g. Distinguish these parameter changes from grid refinement.

6. Audit a claim, not just a number

H1. A report says “our total was conserved, so the simulation is physically valid.” Use failure.json as a concrete counterexample and write a defensible replacement claim.

H2. A colleague halves h, keeps N fixed, and calls the new endpoint a finer approximation at the same time. Diagnose the comparison. Give the corrected pair of choices and name a quantity held constant in a refinement study.

H3. A report says “three decreasing gaps prove convergence and the 50-digit reference proves real-world accuracy.” Identify two unsupported inferences and propose one numerical follow-up and one empirical follow-up. Do not promise that this package supplies real data.

7. Formative quiz: a changed initial state

Use quiz.json: A_0 = 81 g, B_0 = 9 g, k = 1 per minute, T = 1 minute and N = 2. The quiz totals 30 formative points, six per question. It is not a calibrated course grade.

Q1. Compute h, q, all coarse-grid states and the conserved total. Explain the old-state transfer rule. [6]

Q2. Compute the A and B endpoints for 4 and 8 steps with the power oracle. Give the coarse-to-medium and medium-to-fine gaps and identify their units. [6]

Q3. Compare the three A endpoints with the supplied rounded continuous reference, approximately 29.798235 g. State what the trend supports and two claims it does not support. [6]

Q4. A proposed file uses k_per_min = "1.0" and base_steps = true. Explain both refusals, give accepted equivalent values, and identify a scientifically nonphysical packet that the format validator should still accept for diagnosis. [6]

Q5. Describe and, if possible, perform an actual quiz run and saved-source replay. State the completion/hash checks, meaningful output comparison and partial-failure response. One of six points requires actual evidenced execution; a trace-only answer can earn at most five. [6]

8. Formative project: a longer, slower transfer

Use project.json: A_0 = 48 g, B_0 = 12 g, k = 1/4 per minute, T = 4 minutes and N = 2. Submit a concise report, the original packet, any clearly named changed packet, and recoverable run evidence if available. Each question is worth eight points, for 40 formative points; do not combine this automatically with the quiz into a course grade.

P1. Write a model contract, calculate all coarse states and all three endpoint pairs independently, and check conservation and nonnegativity over every grid. State the units and assumptions. [8]

P2. Execute the base project and an actual saved-source replay, run the tests, verify manifests and compare outputs. Explain why the path-dependent manifests need not match. Five points require actual execution/reproduction/hash evidence; a trace-only plan can earn at most three. [8]

P3. In a separate copied packet, halve k to "1/8" without changing T or N. Predict and check all A endpoints, compare them with the base project at matching grids, and explain why changing k is parameter sensitivity rather than convergence evidence. [8]

P4. Compare the base project grids with the rounded reference approximately 17.658213 g. Report exact gaps, approximate reference differences and a cautious conclusion. Discuss why mass conservation and a smaller fine gap are jointly useful but insufficient. [8]

P5. Deliver a readable scientific limitations note: explain a possible failed assumption, distinguish code checking from empirical validation, identify a concrete next measurement/design check, and describe a recovery procedure for an interrupted output. Mark execution status honestly. [8]

9. Delayed transfer, without copying the old schema blindly

D1. After a break, consider material that can also return from B to A at rate r. Write simultaneous old-state transfers and updates for both directions. Give a sufficient timestep condition for nonnegative states for all nonnegative starts, and explain which total is preserved. Does the current five-field runner implement this model?

D2. Now imagine A and B report concentrations in grams per litre and their volumes differ. Explain why adding concentrations is not total mass. Give a two-container numerical example, identify the extra information a new model needs, and state why the current mass-only output must not be relabeled as concentration output.

Use the explained key only after making a genuine attempt. Correct the reasoning, not just the final number. The last two tasks deliberately change the model; unsupported fields or semantic relabeling are not valid extensions of this companion.