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

Unit 2: Decomposition, file boundaries and traceable transformations

TMP-SCI-204. This original unit follows Unit 1. It is not a new course, a live execution service or an accredited qualification. Use only the supplied fictional data and a folder you own. No network, account, installation, personal data or real experiment is required. The retained learner execution-capacity gate remains unresolved.

The question now is not just “What is the number?” It is “Can I reconstruct how this exact input became this result, without destroying the earlier evidence?” We will split a small analysis into functions, read a text file under an explicit contract, preserve an input/source snapshot and rerun the analysis in a new folder.

Preparation and route

Unit 1 introduced records, loops, missing versus zero, pooled rates, validation and honest execution records. Revisit its syntax bridge or optional RUN_GUIDE if needed. Here we teach the additional file, parser and provenance concepts before using them. Proposed workload is 16 unpiloted hours: readiness and representation (2), decomposition and worked run (4), guided practice (2), independent/audit work (3), quiz (1), project (3), delayed transfer (1). This is a study estimate, not credit or observed learner timing.

Use an existing Python 3 installation. The author executed the package with Python 3.12.14. If you cannot execute, trace the stages and design tests, clearly marking outputs predicted. Paper work supports conceptual outcomes; it cannot establish that you ran or reproduced a workflow. Do not invent a terminal record.

By the end you should be able to:

  1. Separate text parsing, scientific analysis and evidence writing into testable interfaces.
  2. Apply a precise CSV/missing-data contract and diagnose a failure at the right stage.
  3. Preserve raw input, source and outputs while refusing to overwrite an existing run.
  4. Compare byte identity, equal numerical results and valid scientific interpretation without conflating them.
  5. Reproduce a run and revise a bounded conclusion using a recoverable change record.

Readiness

R1. Unit 1's function accepts integer values and None. A file contains the characters 20, 0 and NA. Explain which are already Python integers and what must happen before the function can use them.

R2. A folder contains raw.csv and report.json. Someone edits raw.csv after the report was made. Why can the current pair no longer establish the report's exact input?

R3. A data record has a measured zero volume. State whether its time belongs in the pooled observed-rate denominator and why.

R4. A script says “complete,” but the saved output is empty. Give two things to inspect before accepting the result.

1. Representation is a contract, not a guess

A text file stores bytes. An encoding specifies how bytes represent text; this unit accepts UTF-8. A parser interprets that text as structured records. A domain validator checks whether the resulting values belong to the scientific computation's allowed domain. These stages answer different questions. Decoding a file successfully does not establish that its columns are right. Parsing a number does not establish that it is a valid duration.

The supplied file fixtures/windows.csv is:

id,elapsed_s,volume_ml
A1,20,6
A2,40,28
A3,30,NA
A4,10,0

In words: A1 records 6 mL over 20 seconds; A2 records 28 mL over 40 seconds; A3 has 30 seconds with volume missing; A4 records zero mL over 10 seconds. Every row describes a separate, nonoverlapping interval, not a cumulative meter reading.

This unit's text contract is intentionally narrow:

These rules are a chosen interchange format, not universal scientific rules. A valid observation written as 18.0 fails this particular format. That is a representation mismatch, not proof the physical quantity was invalid. Conversely, 0 parses as an integer but fails when used as a duration. Never “repair” a record until you know which contract and scientific meaning are intended.

The parser uses a CSV library rather than splitting each line at every comma. Quoted fields can contain commas or line breaks. Error messages identify logical record numbers, with the header counted as record 1; that may differ from physical line numbers when quoted fields span lines.

G1. For each volume token, state parse success/failure and resulting meaning: 0, NA, na, empty text, 006, 6.0. Then explain why an ID written as "Dock, east" needs a real CSV parser.

2. Three interfaces keep different questions separate

The companion pipeline.py has three main functions:

  1. parse_window_csv(raw) consumes bytes and returns a list of typed dictionaries. It checks encoding, CSV shape and numeric-token spelling, not all scientific-domain conditions. It performs no file operations.
  2. analyse_bytes(raw) calls the parser and then Unit 1's unchanged summarise_windows(rows). It returns a report containing the scientific result, input byte count and SHA-256 digest. It performs no file operations.
  3. run_pipeline(input_path, output_directory) reads one bounded byte snapshot, completes analysis, then creates a new output directory and writes evidence. It does not reuse an existing destination.

A pure calculation depends on its supplied values and returns a result without changing external files. Keeping parsing and analysis separate from writing allows small tests to inspect exact failures without filling the filesystem. The file stage still matters, but it is not mixed into the rate formula.

The unchanged Unit 1 module remains the single place that decides whether an integer duration is positive, an ID is duplicated, or an empty observation set has a rate. We reuse it instead of copying those rules into several implementations. If a future contract changes, the dependency and its tests must be reviewed, not silently replaced.

Python's import loads these local/standard-library definitions. It does not install anything or call a service. Path represents a filesystem location; / between a Path and a filename joins path components. with ... open(...) makes the lifetime of an open file explicit. 'rb' means read bytes; 'xb' means create a new binary file and fail if that exact path exists. The output directory is also created with existing-directory reuse disabled. These mechanisms reduce accidental overwrite in a trusted exercise folder; they are not a security boundary against malicious paths or concurrent attackers.

G2. Classify the stage that rejects each input: (a) invalid UTF-8; (b) an extra fourth column; (c) volume 2.5; (d) duration 0; (e) duplicate ID; (f) an existing output directory. Explain why the rate formula should not be responsible for all six.

3. Work the analysis independently

The observed windows A1, A2 and A4 contain 6+28+0 = 34 mL over 20+40+10 = 70 seconds. Scheduled time is 100 seconds. The pooled observed rate is 34/70 = 17/35 mL/s, approximately 0.4857142857142857; observed-duration coverage is 70%. The three individual observed rates are 3/10, 7/10 and 0. Their equal-interval mean is 1/3 mL/s, which answers a different question.

The output uses JSON, a text representation of structured values. JSON's null corresponds to Python None here. JSON numbers are not written in quotation marks, while keys and string values are. The report's schema version is a label for this report format, not a timestamp or a claim of scientific validity. The supplied serializer sorts keys and uses a fixed indentation/newline format, making repeated reports comparable under the checked code/environment.

The report also contains the input's byte count and SHA-256 digest, a deterministic fingerprint of the exact byte sequence. Changing line endings can change the digest while preserving parsed values. A matching digest is useful practical evidence of byte consistency, but it is not proof that measurements are true, a trusted signature, or an independent review. A digest without the original bytes cannot reconstruct the input.

G3. Derive the worked totals, coverage and both means. Predict what changes if the same file is saved with Windows-style CRLF line endings instead of LF: parsed values, numerical result, input digest and complete report bytes. Do not assume all four have the same answer.

4. Run once into a new folder

Keep pipeline.py, measurement_report.py and test_pipeline.py together in the package folder, with the supplied fixtures subfolder. Open a terminal in that package folder. First record your existing interpreter version with python3 --version, or py --version if that is your verified command. Use the same command prefix throughout. If it is unavailable, keep the tracing route; no installation is required.

Run:

python3 pipeline.py fixtures/windows.csv my-run-001

The destination my-run-001 must not already exist, and its parent must exist. Choose a different new name if you already have work there. On success the script prints:

Completed new run: my-run-001
Pooled observed rate (mL/s): 0.4857142857142857

The new folder contains five files:

The code reads/validates input and reads its source companions before creating the destination. Therefore a parsing/domain error creates no output directory. Once writing starts, a disk or permission failure can leave a partial new directory. This deliberately simple teaching workflow is not an atomic multi-file transaction and does not automatically delete evidence or retry into that directory. Inspect the error and use a new destination for a justified retry.

The mere existence of run.json is insufficient: a write could be interrupted, or a file could be changed later. It must parse as a complete JSON record, say complete, and its listed digests must match the files. For a known file in your own run folder, a separate Python check can compute hashlib.sha256(Path('my-run-001/input.csv').read_bytes()).hexdigest() after import hashlib and from pathlib import Path. Compare that result with the matching entry under files in run.json, and repeat for the two source files and report. Use the four known filenames rather than following unfamiliar paths in an untrusted manifest. Even then, byte consistency is not scientific validation. Work in an owned, trusted exercise folder and do not edit source files during a run. No adversarial filesystem or crash-durability guarantee is claimed.

G4. Execute the worked run, or trace it. List the expected five files and explain what evidence each preserves. Try the same command again only against your own completed practice run, predict the existing-directory refusal, and record what happened. Do not remove the original output to make the retry pass.

5. Reproduce from preserved evidence

To reproduce the completed run using its source and input snapshots, run from the original package folder:

python3 my-run-001/pipeline.py my-run-001/input.csv my-run-002

Again, the destination must be new. The copied pipeline loads its neighbouring copied measurement module. With identical input bytes, source and checked execution conditions, the report.json files should match byte-for-byte. The run.json records normally differ because the input/output command arguments differ. Equal scientific results do not require every provenance field to be identical.

A simple comparison script, saved separately beside the two run folders, is:

from pathlib import Path
first = Path('my-run-001/report.json').read_bytes()
second = Path('my-run-002/report.json').read_bytes()
print(first == second)

It prints True for the checked repeat. This script only reads the two specified files. Matching them alone does not verify every source/input digest, nor does it establish that the selected analysis is scientifically appropriate. It is one deliberately narrow test.

Run the companion suite with python3 -m unittest -v test_pipeline. It checks representation failures, domain failures, preserved input/source copies, overwrite refusal, a simulated partial-write failure and repeatable report bytes. A test is strongest when its expectation was obtained independently of the code under test. Run logs from the author are examples of evidence, not proof that you ran the suite.

G5. Reproduce from the preserved first run into a second new folder and compare report bytes. Explain one expected difference in the two run.json records. State separately whether you executed the rerun or only predicted its result.

6. Independent practice

I1. File A uses A,01,02 and file B uses A,1,2, with the correct identical header. Predict parsed values, observed rate, raw-byte equality, digest equality and complete-report equality. Which comparisons answer a scientific question and which answer an identity question?

I2. A colleague accepts an empty volume field as missing while our parser requires NA. Give an explicit one-row counterexample. Explain why silently changing our parser alters a contract even if that particular record's final rate would be absent either way.

I3. Design four tests that isolate different boundaries: wrong header order, an ASCII integer outside the duration range, duplicate ID, and existing output folder. State whether failure should occur before any new output is created and what existing evidence must remain untouched.

I4. Simulate a failure after input.csv is written but before report.json completes, using reasoning rather than deliberately exhausting storage. What can you infer about the folder? What must you not claim? Propose a recoverable next step.

I5. Someone changes A3's NA to 0 and reruns into a new folder. Calculate the new pooled rate and coverage. Explain why the successful run and new digest do not justify that scientific substitution.

I6. Describe a change that preserves numerical totals but changes input bytes, and a different change that preserves raw input but changes source bytes. For each, say what can and cannot be concluded if the final numerical result is unchanged.

Audit the shortcuts

H1. “A matching SHA-256 proves the data came from the instrument and are correct.” Identify two distinct overclaims.

H2. “The parser accepts all rows, so there can be no duplicated observation or overlapping time.” Explain a case that passes our shape/domain rules yet violates the interval model.

H3. “A failed output write means I should delete the whole raw-data folder and try again.” Explain why this is neither necessary nor justified, and give a narrower recovery plan.

7. Changed-data quiz: 30 formative points

Use this new CSV packet: B1 records 3 mL over 12 seconds; B2 records 36 mL over 48 seconds; B3 has 20 seconds with volume NA; B4 records zero mL over 20 seconds. All questions are worth 6 points.

Q1. Write the exact CSV header and four records. Derive volume, observed/scheduled time, pooled rate and coverage before execution.

Q2. Replace B2's volume token by 36.0 in a separate copy. Identify the failing stage and expected output-folder behavior. What evidence would be needed before rewriting it as 36 rather than merely forcing it through?

Q3. A saved first run is valid. Explain how to reproduce it into a second folder using its preserved sources/input, which output should match exactly, and which provenance field can legitimately differ.

Q4. A person verifies only that run.json exists and displays complete. Give a three-step stronger inspection and one scientific assumption that still is not checked.

Q5. Prepare a 100–150-word run note with question/units, input/source identity, prediction, actual execution or explicit trace status, a discriminating test and a limitation. Preserve real output if you executed. Do not use the author's output as your own.

8. Integrative project: a recoverable revision, 40 formative points

New fictional intervals: C1: 15 seconds, 9 mL; C2: 45 seconds, 18 mL; C3: 30 seconds, NA; C4: 10 seconds, zero mL; C5: 20 seconds, 12 mL. No real samples are required.

P1 (8 points). Create the CSV input under the stated contract, preserve it unchanged and derive expected totals, pooled rate and coverage. Describe the parse/analysis/write interfaces and what each can reject.

P2 (8 points). Execute into a new folder, preserve the complete five-file result, reproduce using its snapshots and compare report bytes. Run or design the provided tests. Identify actual executed evidence separately from plans or traces.

P3 (8 points). Compare two alternative, explicitly supplied corrections to the original packet. Revision A fills C3 with 6 mL, keeping all durations. Revision B instead changes C2's duration from 45 to 60 seconds, leaving C3 missing and adding no other changes. For each, derive rate and coverage, create a separate input/version, and explain the direction of the rate change. Do not combine revisions.

P4 (8 points). Audit a colleague's claim: “I used scheduled time for the observed rate, then edited the old report to fix it; the same filename means the evidence is preserved.” Calculate the original erroneous rate, explain both mistakes and specify a non-destructive corrected workflow. Include the minimum evidence needed to distinguish a completed run from partial files.

P5 (8 points). Write a 200–300-word report that names the original result, both alternative revisions, one rejected shortcut, the execution/provenance evidence and a concrete remaining scientific limitation. Add a concise change log. A correct number without recoverable method does not meet the project's purpose.

These are separate formative marks, not a semester grade or certification. Paper-only work can earn conceptual marks but leaves execution outcomes outstanding. Use the key for feedback after attempting the task, then preserve corrections rather than replacing your first attempt invisibly.

9. Delayed transfer

D1. A different fictional instrument uses ND to mean an interval volume is at least zero but strictly below 5 mL. This is a censored observation, not the missing token NA. One interval has 10 mL over 10 seconds; a second has ND over 20 seconds. Explain why the old parser should reject ND, why changing it silently to NA or zero loses information, and derive the possible full-period rate interval. Describe a revised representation, without implementing it.

D2. You receive a folder with a report, code digest and input digest but no input or source copies. The report number matches yours. Explain what reproduction is still impossible, what matching results establish, and what exact additional artifacts you would request. Do not contact anyone or transmit files for this exercise.

Optional primary references

The scenarios, scripts, tasks and rubrics are original. These links support Python behavior, not endorsement, course equivalence or validation of the scientific model. Checked 4 November 2026; author execution used Python 3.12.14.