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.

01

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.
0 or 1 weak itemsContinue with this module.
2 weak itemsRevisit arrays in Module 8.
3 or more weak itemsRevisit functions in Module 6.
02

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 = repeatable

The 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 skill works when: the script reads its data, checks its output against a known case, and reruns identically.
The skill breaks down when: numbers are hard-coded, nothing is validated, or hidden randomness changes the answer each run.
The concept. Read data, compute, then validate against a known value. Explicit inputs and comments make the run repeatable.
03

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.

PracticeToolWhy it matters
Read datanp.loadtxtsame code for any dataset size
Validateabs(a - b) < tolcatches errors, builds trust
Fix randomnessnp.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.

04

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
  1. ProblemLoad five deflection readings from a file and average them.
  2. Given / findvalues 3.8, 4.1, 4.2, 4.3, 4.6 mm. Find the count and mean.
  3. Modelnp.loadtxt reads the file; data.mean() averages the array.
  4. Solvesum = 21.0 over 5 items, so mean = 4.20 mm.
  5. Check3.8 + 4.1 + 4.2 + 4.3 + 4.6 = 21.0, and 21.0 / 5 = 4.20.
  6. ConclusionThe same two lines handle five readings or five thousand, straight from a file.
Result. mean deflection 4.20 mm from the file.
05

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
  1. ProblemCompute a cantilever deflection and check it against a known value.
  2. Given / findF = 720 N, L = 1.5 m, E = 200 GPa, I = 1.0e-6. Find the deflection and validate.
  3. Modeldeflection = F L cubed / (3 E I); compare to the hand value within a tolerance.
  4. Solve720 × 3.375 / (6.0e5) = 0.00405 m = 4.05 mm, which matches 4.05.
  5. CheckL cubed = 3.375 and 3 E I = 6.0e5, so the ratio is 4.05e-3 m, and the tolerance check passes.
  6. ConclusionThe code agrees with the hand calculation, so the result can be trusted.
Result. computed 4.05 mm, validated against the hand calculation.
06

Misconceptions and diagnostics

MistakeSymptomDiagnostic questionCorrection
Hard-coding dataRewriting code for new data"Could this read from a file?"Load data with np.loadtxt.
No validationWrong answers pass silently"What known case confirms this?"Check against a hand calc within a tolerance.
Unseeded randomnessAnswer changes each run"Is anything random here?"Fix it with np.random.seed(0).
Undocumented inputsNobody can rerun it"Are the inputs stated and commented?"List inputs at the top with units and comments.
07

Practice ladder

Level 1 · Direct skill

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)).

Level 2 · Mixed concept

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.

Level 3 · Independent problem

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.

Transfer task | Real engineering

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.

08

Working with AI, and proving it yourself

Use AI as a tutor, not a black box

"Explain why validating against a known value matters."
"Suggest a known case I could check my result against, then I will test it."
"Write my whole analysis." Build and validate it yourself.
"Trust this number." Validate it against a reference yourself.

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.

Must include: file input, a validation check, stated inputs with units, and comments explaining the reasoning.
09

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.

TodayFinish this quiz and Levels 1 and 2 of the ladder.
+1 dayAdd a validation check to an earlier script.
+3 daysRewrite one calculation to read from a file.
+7 daysCarry these habits into Numerical Methods.
+30 daysValidate and document every result by habit.
10

Textbook mapping

This module follows Hans Fangohr, Introduction to Python for Computational Science and Engineering. Use these references to read further.

Topic in this moduleWhere to read more
Reading and writing filesFangohr, chapter on Input and Output, files
Loading data with NumPyFangohr, Numerical Python, loadtxt and savetxt
Testing and validationFangohr, 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.