Programming and Computation · Module 10 of 10
Files, Validation, and Reproducibility
Real work reads data from files, writes results back, and must run the same way tomorrow. This closing module covers loading a data file, validating a computed answer against a known value, and writing scripts anyone, including future you, can rerun and trust.
Readiness check
This module ties the course together. Tick only what you can do closed-notes.
- Load and summarise an array from Module 8.
- Write a function from Module 6.
- Recall computing a mean from data.
- Recall checking an answer against a known value.
- Recall why a result should be repeatable.
The core idea
A trustworthy computation reads its data from a file, validates its output against something you already know, and is written so it runs the same way every time. Loading, validating, and documenting are what turn a one-off script into engineering work you can defend.
data = np.loadtxt('tests.csv')assert abs(computed - known) < tolfixed inputs + comments = repeatableThe last step in becoming useful with code is making results that hold up. That starts with files: instead of typing numbers in, you read them from a data file, data = np.loadtxt('tests.csv'), and write results back with np.savetxt or a plain with open(...) as f block. Reading from files means the same script handles ten values or ten thousand. Next comes validation, the habit that separates engineering from guessing: whenever you compute something, compare it to a value you already trust, a hand calculation, a textbook case, or a known limit, and check they agree within a tolerance, abs(computed - known) < tol. A result that matches a reference is one you can defend; one that does not is a bug you just caught. Finally, reproducibility: a script should give the same answer when you, or a colleague, run it next month. That means writing the inputs explicitly at the top, commenting why not just what, fixing any randomness with a seed like np.random.seed(0), and keeping the data file alongside the code. Loading, validating, documenting: these three practices are why a calculation becomes something an engineer signs off on, and they carry into every numerical-methods and simulation course ahead.
The skills, taught in order
Five skills make a computation dependable.
10.1 Reading a data file
np.loadtxt('tests.csv') reads numbers from a text or CSV file into an array. For finer control, with open('tests.csv') as f: reads lines yourself. Reading from files scales from a few values to many.
10.2 Writing results
np.savetxt('out.csv', results) writes an array to a file, and a with open(..., 'w') as f: f.write(...) block writes formatted text. Saving results keeps a record you can share.
10.3 Validation against a known value
Compare every result to something trusted: assert abs(computed - known) < tol. A hand calculation, a textbook case, or a limiting value all work. Agreement builds confidence; disagreement finds bugs.
| Practice | Tool | Why it matters |
|---|---|---|
| Read data | np.loadtxt | same code for any dataset size |
| Validate | abs(a - b) < tol | catches errors, builds trust |
| Fix randomness | np.random.seed(0) | same answer every run |
Three habits that make a result you can defend.
10.4 Reproducibility
State inputs explicitly at the top, comment why not just what, seed any randomness with np.random.seed(0), and keep the data file with the code. Then the answer is the same next month.
10.5 Putting it together
A dependable script reads its data, computes, validates against a known case, and prints a labeled result, all documented. This is the shape of every calculation in the courses ahead.
Engineering connection: a validated, reproducible script is what lets an analysis be reviewed, reused, and trusted, the standard every numerical-methods, CFD, and FEM course builds on.
Worked example 1: loading a CSV and averaging
A file beam_tests.csv holds five measured deflections, one per line. Load it and report the mean.
# beam_tests.csv
3.8
4.1
4.2
4.3
4.6
import numpy as np
data = np.loadtxt('beam_tests.csv')
print('n =', len(data))
print('mean =', f'{data.mean():.2f}', 'mm')
Output:
n = 5
mean = 4.20 mm
- ProblemLoad five deflection readings from a file and average them.
- Given / findvalues 3.8, 4.1, 4.2, 4.3, 4.6 mm. Find the count and mean.
- Model
np.loadtxtreads the file;data.mean()averages the array. - Solvesum = 21.0 over 5 items, so mean = 4.20 mm.
- Check3.8 + 4.1 + 4.2 + 4.3 + 4.6 = 21.0, and 21.0 / 5 = 4.20.
- ConclusionThe same two lines handle five readings or five thousand, straight from a file.
Worked example 2: validating against a known value
Compute a cantilever's end deflection and validate it against a hand calculation of 4.05 mm. The formula is deflection = F L cubed / (3 E I).
F = 720 # end load, N
L = 1.5 # length, m
E = 200e9 # Young's modulus, Pa
I = 1.0e-6 # second moment of area, m4
deflection = F * L ** 3 / (3 * E * I) # metres
delta_mm = deflection * 1000
known = 4.05 # hand calculation, mm
print('computed =', round(delta_mm, 2), 'mm')
if abs(delta_mm - known) < 0.01:
print('validated against hand calc')
Output:
computed = 4.05 mm
validated against hand calc
- ProblemCompute a cantilever deflection and check it against a known value.
- Given / findF = 720 N, L = 1.5 m, E = 200 GPa, I = 1.0e-6. Find the deflection and validate.
- Modeldeflection = F L cubed / (3 E I); compare to the hand value within a tolerance.
- Solve720 × 3.375 / (6.0e5) = 0.00405 m = 4.05 mm, which matches 4.05.
- CheckL cubed = 3.375 and 3 E I = 6.0e5, so the ratio is 4.05e-3 m, and the tolerance check passes.
- ConclusionThe code agrees with the hand calculation, so the result can be trusted.
Misconceptions and diagnostics
| Mistake | Symptom | Diagnostic question | Correction |
|---|---|---|---|
| Hard-coding data | Rewriting code for new data | "Could this read from a file?" | Load data with np.loadtxt. |
| No validation | Wrong answers pass silently | "What known case confirms this?" | Check against a hand calc within a tolerance. |
| Unseeded randomness | Answer changes each run | "Is anything random here?" | Fix it with np.random.seed(0). |
| Undocumented inputs | Nobody can rerun it | "Are the inputs stated and commented?" | List inputs at the top with units and comments. |
Practice ladder
Load a file of numbers with np.loadtxt and print how many values it holds.
Show answer
data = np.loadtxt('file.csv'), then print(len(data)).
Compute a value and assert it is within 1 percent of a known answer.
Show answer
assert abs(computed - known) < 0.01 * known raises an error unless they agree to 1 percent.
Write a short script that reads measurements from a file, computes the mean, validates it against an expected value, and saves the result.
Show answer
Load with np.loadtxt, compute data.mean(), check abs(mean - expected) < tol, then np.savetxt the result, with inputs commented at the top.
Turn a calculation from an earlier module into a documented, reproducible script that reads its data, validates against a known case, and could be reviewed by someone else.
What good work looks like
Inputs stated with units at the top, data read from a file, a validation check against a hand calculation or textbook case, a labeled result, and comments explaining the why. A good answer is one a colleague could rerun and trust without asking you.
Working with AI, and proving it yourself
Use AI as a tutor, not a black box
Portfolio task
Publish one reproducible script: it reads data from a file, computes a result, validates against a known value, and is documented well enough for a reviewer.
Retrieval and spaced review
Closed notes. Answer out loud, then reveal.
1. How do you load numbers from a CSV?
np.loadtxt('file.csv') into an array.
2. What does validation mean here?
Checking a result against a trusted known value within a tolerance.
3. Why seed randomness?
So the script gives the same answer every run.
4. What makes a script reproducible?
Stated inputs, comments, fixed randomness, and data kept with the code.
5. Why validate at all?
An answer that matches a known case can be defended; one that does not reveals a bug.
Textbook mapping
This module follows Hans Fangohr, Introduction to Python for Computational Science and Engineering. Use these references to read further.
| Topic in this module | Where to read more |
|---|---|
| Reading and writing files | Fangohr, chapter on Input and Output, files |
| Loading data with NumPy | Fangohr, Numerical Python, loadtxt and savetxt |
| Testing and validation | Fangohr, chapter on Testing (assert and checks) |
Chapter titles refer to Fangohr's Introduction to Python for Computational Science and Engineering. Any recent version is equivalent for study. You have finished the course; return to the hub to review or move on.