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

Unit 1: From a question to a reproducible measurement report

Planning reference TMP-SCI-204. This original teaching manuscript is one opening unit, not a completed semester, credential, institutional equivalent or staffed assessment service. All observations below are invented. Do not collect real samples or upload any personal data. The core measurement function reads no files, writes no files, uses no network and needs no third-party packages. The Unit 1 tests run in memory; later units preserve output in new folders you choose.

Your goal: make a small scientific computation understandable, checkable and repeatable, then say exactly what it does and does not establish. A program can run without error while answering the wrong question. A report can be reproducible while the measurement design is weak. We will make both possibilities visible.

Study route and evidence

A proposed 16 hours includes readiness and a syntax bridge (2), worked reasoning/code (4), guided work (2), independent work and corrections (3), quiz (1), project (3), and delayed transfer (1). These are unpiloted planning estimates, not credit or measured learner time. Take breaks and revisit difficult steps.

Use an existing Python 3 installation and a text editor if available. The package was executed with Python 3.12.14; that does not prove you have a usable interpreter. No install, account, paid tool or cloud notebook is required. With no interpreter, use the paper-tracing route and label all outputs predicted, not executed. That route supports conceptual outcomes; execution outcomes stay unassessed. Optional preparation is Brule's existing Python Foundations short course, especially its lessons on values, functions, loops and records. This unit is not a replacement for that course.

After study, you should be able to:

  1. Specify a question, input contract, units and missing-data policy before calculating.
  2. Derive a pooled rate and distinguish it from an average that gives each interval equal weight.
  3. Trace and run a small function, including zero, empty, missing and invalid inputs.
  4. Design checks that can reveal a wrong denominator, lost zero, changed input or failed validation.
  5. Produce a recoverable run record and revise a scientific claim when data or assumptions change.

Readiness check: attempt before consulting the key

R1. A fictional window collected 24 mL over 40 seconds. Find its rate in mL/s and mL/min. State which quantity changes when converting units.

R2. A log contains a measured volume of zero in one window and no volume observation in another. Explain why replacing both by zero changes the scientific meaning.

R3. Predict total = 8; extra = 3; total = total + extra. What value is bound to total? Is the equals sign an assertion that two old values were equal?

R4. A result file contains “0.64” and nothing else. Name four things you would need before you could interpret or rerun that result.

1. Start with the question, not a formula

Imagine a fictional demonstration collector. Each record describes one separate, nonoverlapping collection window. The observed volume is the amount collected during that window, not a cumulative meter reading. Durations are known for every scheduled window. We want: What was the volume collected per second across the windows with recorded volumes? This is a descriptive question about a supplied packet. It is not a claim about every future window, a population, or a real device.

Here is the complete worked packet:

ID Elapsed seconds Volume during the window, mL
W1 30 18
W2 90 54
W3 60 missing
W4 20 8

The text equivalent is W1: 30 seconds, 18 mL; W2: 90 seconds, 54 mL; W3: 60 seconds, volume missing; W4: 20 seconds, 8 mL. “Missing” is not a measured value and not a reason to erase the scheduled window.

An input contract states what the computation is designed to accept and what it promises. For this unit:

The model also assumes that IDs refer to distinct windows, units are correctly labelled and windows do not overlap. Our small schema has no start/end timestamps, so the program cannot verify nonoverlap. Validation of shape and allowed numbers cannot certify these scientific assumptions.

G1. Write the worked packet as four ordinary-language records. Identify which fields define the question and which assumption the program cannot check. Explain why an ID repeated for a second row should not simply be counted twice.

2. Derive the quantity before writing the loop

For W1, rate = 18/30 = 0.6 mL/s. W2 also gives 54/90 = 0.6 mL/s. W4 gives 8/20 = 0.4 mL/s. The pooled rate adds the observed volumes and divides by the corresponding observed durations:

pooled observed rate = (18 + 54 + 8) / (30 + 90 + 20) = 80/140 = 4/7 mL/s, approximately 0.571429 mL/s.

The denominator is 140 seconds, not the scheduled 200 seconds. Dividing 80 by 200 implicitly assigns no collected volume to the missing 60 seconds when interpreting it as a full-period rate. Our data do not establish that. Report the missing ID and the observed-duration coverage, 140/200 = 70%, alongside the observed rate. Coverage is a description of this packet, not an estimate of accuracy.

Another legitimate question is “What is the average of the three observed interval rates when each interval counts equally?” Its answer is (0.6 + 0.6 + 0.4)/3 = 8/15, about 0.533333 mL/s. It gives the 20-second interval the same influence as the 90-second interval. That is different from the original question.

The connection is useful. Write each observed rate as r_i = v_i/t_i. The pooled rate is sum(t_i * r_i) / sum(t_i). Thus each rate receives a weight proportional to its duration. It lies between the smallest and largest observed rates when durations are positive. If all durations are equal, those weights are equal and the two averages agree. Equal rates also make them agree. Agreement in one packet therefore does not prove the formulas answer the same question generally.

G2. Verify both worked rates exactly as fractions. Explain which rate is appropriate for the stated question and why multiplying the pooled rate by 60 changes its unit without changing the collected volume.

G3. Add an observed W5 with 20 seconds and zero mL. Recalculate volume, observed time, scheduled time and pooled rate. Explain why skipping W5 would be a substantive error.

An assumption changes a bound, not the missing observation

Suppose a separate, fictional design constraint establishes that the missing window's average rate was between 0 and 1 mL/s. Its volume is then between 0 and 60 mL. Across all 200 scheduled seconds, the full-packet rate is between 80/200 = 0.4 and 140/200 = 0.7 mL/s. We have not observed that rate, assigned a probability or proved the missingness harmless. The bound depends on the added constraint. Without an upper bound, the supplied data alone do not provide a finite upper bound on missing volume. Even a lower bound of zero relies on our nonnegative-volume model.

3. A small syntax bridge

Read this section before the full program if Python is new. A list such as [18, 54, 8] keeps items in order. A dictionary such as {'id': 'W1', 'elapsed_s': 30, 'volume_ml': 18} keeps named fields together. Quotes mark text; 18 is a number while '18' is text. row['elapsed_s'] retrieves a value by its field name. None is our explicit missing marker; it is neither the text 'None' nor a numerical zero.

A function begins def name(parameters):. Its indented lines form its body. Calling it supplies values for the parameters; return sends a result back. print displays something but is not a substitute for returning a usable report. for row in rows: repeats its indented block for each row, in order. if ...: selects a branch. else: selects the alternative. Keep indentation consistent; copying an expected-output line into a script is not copying code.

total_ml = total_ml + volume calculates the right side and assigns the new total. Start the accumulator before the loop; resetting it inside the loop would forget earlier rows. some_list.append(label) adds a label. label in seen_ids checks membership. set(row) obtains the dictionary's collection of keys, allowing the guard to compare it with exactly the three required names. It is not a conversion of measurement values.

type(seconds) is int is a deliberately strict test here. It excludes decimal floats, strings and Boolean values. volume is None tests our missing marker specifically. Avoid if volume: for this purpose: zero and None both behave as false in a truth test. The Boolean operators or and and evaluate only as far as needed. In type(row) is not dict or set(row) != required_keys, the second part is not attempted when the first already establishes failure.

raise ValueError('...') stops the current call and explains a contract violation. This program does not catch that error and pretend it produced a report. Its already accumulated local totals are not returned. A traceback is evidence to inspect, not a signal to erase the awkward row. The first failing guard determines which error appears; the program is not a comprehensive data-cleaning system.

4. Trace the algorithm, then execute it

The complete source is the adjacent measurement_report.py. Its main function is summarise_windows(rows). It uses these stages:

  1. Check the input container and initialize fresh totals/lists.
  2. For each row, check schema, ID, duration and volume before accumulating that row.
  3. Add duration to scheduled time. If volume is missing, record its ID. Otherwise add its ID, volume and duration to the observed totals.
  4. Divide only if observed time is positive. Return the report, keeping the exact integer totals as well as the approximate displayed rate.

After W1 the totals are 18 mL, 30 observed seconds, 30 scheduled seconds. After W2 they are 72, 120, 120. W3 changes only scheduled time to 180 and adds a missing ID. W4 produces 80, 140, 200. The loop's central invariant is: after each accepted row, volume and observed time describe precisely the observed rows processed so far, while scheduled time describes every processed row. Initially each total is zero. Each branch preserves that description. When the finite list is exhausted, it describes the whole accepted packet. This argument complements tests; it does not prove that the chosen question or real measurements are valid.

To run, save the supplied file unchanged in a local working folder. In a terminal opened in that folder, use python3 measurement_report.py, or the equivalent existing command on your system, such as py measurement_report.py. Do not enter this command at the >>> interpreter prompt. The file's final if __name__ == '__main__': block displays the demonstration only when run directly; importing its function for tests does not print it.

Expected display, to compare with your actual output:

Observed IDs: ['W1', 'W2', 'W4']
Missing IDs: ['W3']
Volume (mL): 80
Observed time (s): 140
Scheduled time (s): 200
Pooled observed rate (mL/s): 0.5714285714285714

Integer totals are exact for these inputs. Division produces a floating-point value; its displayed digits are a numerical representation, not measurement precision. Reporting 0.571 mL/s may be readable, but do not claim three decimal places of physical accuracy. Preserve 80/140 and the units so the computation remains interpretable. More detailed rounding-error analysis belongs in a later unit.

G4. Make a four-row trace with all three totals and the lists of IDs after each iteration. Then trace an empty list and a single missing-volume row of 15 seconds. Why must neither report an observed rate of zero?

G5. In a copy of the source, change only W1's duration to zero. Predict the error before running. Does the function return a partial report? Restore the original copy afterward, or keep the changed file clearly named as a failed case. State predicted and actual outcomes separately.

G6. Predict, then run the original source twice from a fresh terminal invocation. Record interpreter version, command, input identity and both outputs. If you cannot execute, provide two traces and state why they are not execution evidence.

5. Tests need an independent expectation

A check is useful when a wrong program could fail it. Copying a program's answer into an “expected” field merely records what it did. For the worked packet, our independent oracle is hand addition and the exact fraction 4/7. For an error case, the oracle is the contract, not a made-up numerical answer.

A minimal test plan includes ordinary data; a measured zero; an empty list; all volumes missing; a bad duration; an invalid volume; a duplicate ID; and a malformed row. Also check that input records remain unchanged. A successful run on the usual four rows alone does not exercise these cases. Use the supplied test_measurement_report.py in the same folder and run python3 -m unittest -v test_measurement_report. The standard-library suite states case names and whether each passed. You do not need to understand class syntax to run it, but you must explain the contract behind your own added test.

Some checks compare relationships rather than a single expected number. Reordering records should preserve totals and pooled rate, but the returned ID lists should follow the new order. Adding a missing row should change scheduled time and missing IDs, not the pooled observed rate. Multiplying every observed volume by three while keeping durations should triple the rate, under the same integer contract. These are metamorphic checks: deliberate transformations with predictable effects. A family of such checks can expose faults, but no finite suite proves all possible inputs correct.

I1. Use A: 10 seconds, 9 mL; B: 30 seconds, 3 mL. Find pooled and equal-interval rates. Supply a sentence for each question. Which of them is 0.5 mL/s?

I2. Give expected report totals and rate for: (a) one observed row, 12 seconds and zero mL; (b) one missing row, 12 seconds; (c) no rows. Include scheduled time and ID status, not just the rate.

I3. A replacement loop adds every duration to the denominator but ignores missing volumes. Give the smallest counterexample containing both observed and missing data. Show the wrong and right results.

I4. A developer changes the condition to if volume: and treats the else branch as missing. Give a counterexample, trace the classification error, and state a precise repair.

I5. Design three metamorphic checks for the worked packet: reversed order; an added missing window of 50 seconds; and every observed volume tripled. Give expected totals, rates and any changed list order.

I6. Someone replaces negative volumes by zero and converts the text '8' to 8 before running, without preserving the original packet. Explain two scientific/reproducibility problems. Propose a recoverable correction workflow rather than merely changing a formula.

Three short audit tasks

H1. “All 16 named tests pass, so the collector really flows at exactly 4/7 mL/s.” Identify at least three unsupported jumps.

H2. “The two reruns match, so missing W3 cannot matter.” Use the stated 0 to 1 mL/s bound to refute the claim quantitatively.

H3. “I reordered the rows and the entire output dictionary changed, so the pooled computation is nondeterministic.” Explain the relevant invariant and why the claim is too strong.

6. Build a useful run record

A run record should let a later reader distinguish what was intended, what was executed, and what the output supports. Keep the original input and source, not only a screenshot of the answer. Record:

For example, an honest report might say: “Using the supplied fictional W1–W4 packet and the original integer contract, I predicted 80 mL over 140 observed seconds, with 60 additional seconds missing. My local run produced those totals. The observed pooled rate is 4/7 mL/s. I checked zero, empty and invalid-duration cases. This describes the observed windows only. I have not established a full-period rate or a future-device prediction.” If you only traced it, replace the execution claim with that fact.

Here computational reproducibility means obtaining consistent results with the same data, code and stated computational conditions. It is distinct from investigating the same scientific question with newly collected data. Terminology varies across fields, so name what you actually did. Neither matching reruns nor fresh data automatically establish the validity or generality of an inference. The reference at the end explains this convention.

7. Changed-data quiz: 30 formative points

Use this new packet, without looking at its answers: A: 20 seconds, 12 mL; B: 80 seconds, 64 mL; C: 40 seconds, missing; D: 20 seconds, zero mL. All five questions are worth 6 points. Written, typed or clearly structured spoken reasoning is acceptable. Execution credit requires an actual run record; never substitute a trace without labelling it.

Q1. List observed/missing IDs, both time totals, volume and pooled rate as an exact fraction with units.

Q2. Calculate the equal-interval mean rate. Explain quantitatively why it differs from Q1, and state the question each answers.

Q3. Construct a one-row valid-zero test and a one-row invalid-duration test. State expected outcomes and how the pair detects two different failures.

Q4. An analyst reports 76/160 as the observed pooled rate. Diagnose the denominator, calculate observed-duration coverage, and state the full-packet rate bounds if the missing average rate is known only to lie between 0 and 0.5 mL/s.

Q5. Write a 100–150-word audit note naming the question, a reproducible computational procedure, an independent check and a limitation. State honestly whether you executed or only traced. A planned run may earn planning credit but not completed-execution credit.

8. Integrative project: a revision with consequences, 40 formative points

Use this fictional packet of separate windows: S1: 25 seconds, 10 mL; S2: 75 seconds, 45 mL; S3: 50 seconds, missing; S4: 50 seconds, zero mL; S5: 50 seconds, 40 mL. A fictional comparison target is 0.5 mL/s. This is not a regulatory or safety threshold.

P1 (8 points). Write the contract and create an input file/script or paper representation. Derive totals, coverage, pooled rate and equal-interval mean before execution. Explain any disagreement between the two means.

P2 (8 points). Run the supplied function with the new records and preserve a run record. Add or describe three discriminating checks: a zero, a malformed record and an unchanged-input check. Report results, including any failures. Without an interpreter, provide a trace and test design, clearly marking execution evidence absent.

P3 (8 points). A later analyst guarantees only that S3's missing average rate was between 0 and 0.8 mL/s. Derive the full-packet rate interval. Decide whether the observed-only rate meets the target, whether the full-packet rate is known to meet it, and how much S3 volume is needed to meet it exactly. Separate deductions from assumptions.

P4 (8 points). Investigate two alternative updates to the original packet. Update A adds S6: 50 seconds, 25 mL; S3 remains missing. Update B instead fills S3 with 20 mL and adds no S6. For each, calculate the observed rate and coverage, preserve the original and identify exactly what changed. Do not accumulate the updates accidentally.

P5 (8 points). Deliver a 200–300-word report that answers the original and revised questions, explains at least one rejected shortcut, names evidence and uncertainty, and proposes a concrete next check. Include a change log and label execution status accurately. If an error was found, show the previous claim and corrected claim, not only a polished final result.

Self-mark against the key only after attempting all parts. Revise weak reasoning in a different section or document. A score is formative feedback, not certification of competence, and an unexecuted project cannot be described as verified computational performance.

9. Delayed transfer and retrieval

Return after a break, ideally on a later day. No reminder or account setup is required.

D1. A different fictional instrument reports cumulative counts at elapsed times: at 0 seconds, 0 counts; at 10 seconds, 4 counts; at 30 seconds, 16 counts; at 60 seconds, 34 counts. Explain why treating 4, 16 and 34 as interval counts would be wrong. Derive three interval records, pooled count rate and equal-interval mean. Describe which field names/units and contract statements must change before reusing the volume program. No actual modification is required.

D2. Without reopening the worked code, write five checks or pieces of evidence you would require before trusting a new computational report. Include one test that could pass even when the scientific interpretation is wrong, and explain the gap. Then compare with your earlier audit note and record one improvement.

Reference notes

All packets, tasks, rubrics and code here are original. These optional primary references support language semantics and terminology, not endorsement or validation of this bespoke unit. Links checked 4 November 2026; local execution used Python 3.12.14, not whatever version a documentation banner may later show.