# Computational Engineering

*Tactiverge Academy course pack · version 1.0.0*

Using programming to solve engineering problems: Python, algorithms, data analysis, simulation and the first ideas of computer vision.

**Audience:** Curious students aged 13 and over with access to a computer or a free online Python environment. No prior programming experience needed.

> This work is licensed under the Creative Commons Attribution 4.0 International licence (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/. Attribute as: Tactiverge Academy, https://tactiverge.win.



---

# Module 1: Python fundamentals

The core of the Python language — values, variables, decisions, loops and functions — taught through small engineering calculations.

**Objectives**

- Write and run Python 3 programs that perform calculations with numbers, strings and lists.
- Explain why floating-point results are approximate and compare them safely.
- Use if/elif/else, for and while to make decisions and repeat work.
- Write functions with parameters and return values, and reuse them.
- Simulate a simple physical process by stepping it forward in time.


## 1.1 Values, variables and expressions

*Your first engineering calculations in Python: numbers, text, lists, the math module and the surprising truth about decimals.* (about 35 min)

### Why engineers program

Engineers spend a surprising amount of time calculating: the current through a resistor, the stress in a bracket, the average of a hundred sensor readings. A calculator is fine for one answer. But when the same calculation must be repeated for many values, checked, shared with a teammate, and rerun next week with new data, a short program is faster and far less error-prone. Python is a popular language for this work because it is readable, free, and has a huge collection of scientific tools built on top of it.

You can follow this lesson with Python 3 installed on a computer, or in any free online Python environment. Type the examples yourself rather than copying them — typing makes you notice the details.

### Your first program

```python
print("Hello, engineer!")
```

`print` is a **function**: a named piece of code that does a job. You call it by writing its name followed by parentheses containing its input. Text in quotes is called a **string**. When you run this, Python displays:

```
Hello, engineer!
```

### Variables: naming values

A **variable** is a name attached to a value. You create one with `=`, which in Python means "store the value on the right under the name on the left" — not "is equal to" in the mathematical sense.

```python
voltage = 9.0       # volts
resistance = 450.0  # ohms
current = voltage / resistance
print(current)
```

Output:

```
0.02
```

This is Ohm's law, I = V / R: 9 volts across 450 ohms drives 0.02 amps. Everything after a `#` is a **comment**. Python ignores comments; they are for people. Writing the unit next to each value is an excellent habit. Many real engineering failures have come from mixing up units, and a comment costs nothing.

Good variable names describe what they hold. `current` is clearer than `c`, and `motor_speed_rpm` is clearer still. Python names may contain letters, digits and underscores, cannot start with a digit, and are case-sensitive: `Voltage` and `voltage` are different variables.

### Numbers and arithmetic

Python has two main kinds of number. **Integers** (`int`) are whole numbers like `3` or `-12`. **Floating-point numbers** (`float`) have a decimal point, like `3.0` or `0.02`. The arithmetic operators are:

```python
print(7 / 2)    # division: 3.5
print(7 // 2)   # floor division (whole part): 3
print(7 % 2)    # remainder: 1
print(2 ** 10)  # power: 1024
```

Python follows the usual order of operations — powers first, then multiplication and division, then addition and subtraction — and parentheses override it. When in doubt, add parentheses: they make your intent obvious to the next reader.

### Decimals are approximate

Try this:

```python
print(0.1 + 0.2)
```

The output is:

```
0.30000000000000004
```

This is not a bug in Python. Computers store floats in binary, and most decimal fractions — including 0.1 — cannot be written exactly in binary, just as 1/3 cannot be written exactly in decimal. The stored value is extremely close but not exact, and tiny differences can show up. The same thing happens in almost every programming language.

The practical lesson for engineers: **never test floats for exact equality**. Instead, ask whether two values are close enough:

```python
import math
print(math.isclose(0.1 + 0.2, 0.3))   # True
```

### Formatting output

Raw numbers with many digits are hard to read. An **f-string** — a string with an `f` before the opening quote — lets you insert values and control their format:

```python
current = 9.0 / 450.0
print(f"Current: {current * 1000:.1f} mA")
```

Output:

```
Current: 20.0 mA
```

Inside the braces is any expression; `:.1f` means "show it as a decimal with one digit after the point". Reporting a sensible number of digits is part of communicating honestly: printing 20.000000 mA suggests a precision your measurement probably does not have.

### Strings

Strings hold text. You can join them with `+`, find their length with `len`, and change them with methods such as `.upper()`:

```python
name = "servo"
print(name.upper())     # SERVO
print(len(name))        # 5
print(name + "-01")     # servo-01
```

A common surprise: `"3" + "4"` is `"34"`, because joining two strings sticks them together. To do arithmetic on text that contains a number — for example, a value read from a file — convert it first with `int("42")` or `float("2.5")`.

### Lists

A **list** holds several values in order, inside square brackets. Lists are how you will handle sets of measurements.

```python
readings = [20.2, 20.4, 19.8, 20.0]   # temperatures in °C
average = sum(readings) / len(readings)
print(f"Average: {average:.2f} °C")   # Average: 20.10 °C

print(readings[0])    # first item: 20.2
print(readings[-1])   # last item: 20.0
print(max(readings))  # 20.4
readings.append(20.6) # add a new reading at the end
print(len(readings))  # 5
```

Notice that the first item is at position **0**, not 1. Python, like most programming languages, counts positions (called **indices**) from zero. Negative indices count from the end.

### The math module

Python's built-in `math` module provides square roots, π, trigonometry and much more. Import it once at the top of your program:

```python
import math

print(math.sqrt(2))                    # 1.4142135623730951
print(math.pi)                         # 3.141592653589793
print(math.cos(math.radians(60)))      # 0.5000000000000001
```

Two things to notice. First, the trigonometry functions use **radians**, so convert degrees with `math.radians`. Writing `math.cos(60)` computes the cosine of 60 *radians*, which is about −0.952 — a silent, plausible-looking mistake. Second, the cosine of 60° prints as 0.5000000000000001 rather than 0.5, for the same floating-point reason you saw earlier.

### Worked example: one link of a robot arm

The tip of a 10 cm link rotated 30° from horizontal is at (L · cos θ, L · sin θ):

```python
import math

length_cm = 10.0
angle_deg = 30.0
angle = math.radians(angle_deg)

x = length_cm * math.cos(angle)
y = length_cm * math.sin(angle)
print(f"Tip at ({x:.2f}, {y:.2f}) cm")
```

Output:

```
Tip at (8.66, 5.00) cm
```

This is exactly the calculation from the Robotics Foundations lesson on coordinates — now in a form you can rerun for any length and angle in a second.

> **Errors are information.** You will see error messages constantly, and so does every experienced programmer. Read the **last line** first: it names the kind of error (such as `NameError` or `TypeError`) and usually what went wrong. The lines above it show where. Changing one thing at a time and rerunning is the fastest way to fix most problems.

#### Check your understanding

1. What does print(7 // 2) display?
   A) 3.5
   B) 3
   C) 1
   D) 4

2. Why does 0.1 + 0.2 print as 0.30000000000000004?
   A) Python has a bug in addition
   B) Decimal fractions like 0.1 cannot be stored exactly in binary, so floats are very close approximations
   C) The computer ran out of memory
   D) print always adds extra digits

3. Given readings = [4.0, 5.5, 6.1], what is readings[1]?
   A) 4.0
   B) 6.1
   C) 5.5
   D) An error

4. A student writes math.sin(90) expecting 1. What is the problem?
   A) math.sin does not exist
   B) 90 must be written as a string
   C) math.sin expects radians, so this computes the sine of 90 radians
   D) sin(90°) is actually 0

5. What does "3" + "4" produce in Python?
   A) 7
   B) 12
   C) An error
   D) "34"

**Go further:**

- The Python Tutorial (official documentation): https://docs.python.org/3/tutorial/index.html — The official, free tutorial from the Python developers. Sections 3 to 5 cover the material in this module in more depth.


## 1.2 Decisions, loops, functions and a first simulation

*Make programs that decide, repeat and organize their work — then use them to simulate a cup of tea cooling, one step at a time.* (about 40 min)

### Programs that decide

So far, every program ran each line once, top to bottom. Real engineering code needs to make decisions: *if* a temperature is too high, raise an alarm. Python uses `if`, `elif` (short for "else if") and `else`:

```python
temperature = 31.5   # °C

if temperature > 30:
    print("Warning: too hot")
elif temperature < 10:
    print("Warning: too cold")
else:
    print("Temperature OK")
```

Output:

```
Warning: too hot
```

Python checks each condition in order and runs the block under the **first** one that is true, then skips the rest. Two details matter:

- Each condition line ends with a colon `:`.
- The lines that belong to it are **indented**, conventionally by four spaces. In Python, indentation is not decoration — it defines which lines are inside the `if`. Inconsistent indentation is a common beginner error.

Conditions use comparison operators: `>`, `<`, `>=`, `<=`, `==` (equal) and `!=` (not equal). Note that `==` tests equality, while a single `=` assigns a value. You can combine conditions with `and`, `or` and `not`, and Python even allows chained comparisons such as `0 <= value <= 50`.

### Repeating with for

A `for` loop runs a block once for each item in a sequence:

```python
readings = [12.1, 12.3, 55.0, 12.2, 12.4]

for r in readings:
    print(r)
```

Each time around the loop, `r` holds the next value. To repeat something a set number of times, use `range`. `range(5)` produces 0, 1, 2, 3, 4 — five numbers, starting at zero and stopping *before* 5.

Loops and decisions combine naturally. That reading of 55.0 looks suspicious next to its neighbours. Let us find it:

```python
for i, r in enumerate(readings):
    if r > 50:
        print(f"Reading {i} looks wrong: {r}")
```

Output:

```
Reading 2 looks wrong: 55.0
```

`enumerate` gives you each item's index along with its value, which is useful when you need to report *where* a problem is.

### Repeating with while

A `while` loop repeats as long as a condition stays true. Use it when you do not know in advance how many repetitions you need.

A ball is dropped from 100 cm, and each bounce reaches 60% of the previous height. How many bounces until it rises less than 1 cm?

```python
height = 100.0   # cm
bounces = 0

while height > 1.0:
    height = height * 0.6
    bounces += 1      # same as bounces = bounces + 1

print(f"{bounces} bounces, last height {height:.3f} cm")
```

Output:

```
10 bounces, last height 0.605 cm
```

Always make sure something inside a `while` loop moves it towards finishing. If `height` never shrank, the loop would run forever.

### Functions: naming a piece of work

A **function** packages a calculation so you can reuse it. You define one with `def`, give it **parameters** (inputs) and use `return` to hand back a result:

```python
def current_ma(voltage, resistance):
    """Return the current in milliamps through a resistor (Ohm's law)."""
    return voltage / resistance * 1000

print(current_ma(9.0, 450.0))           # 20.0
print(f"{current_ma(5.0, 220.0):.1f}")  # 22.7
```

The text in triple quotes is a **docstring**, describing what the function does. Functions make programs easier to read (a good name explains intent), easier to test (you can check one function on its own), and easier to fix (a correction in one place applies everywhere it is used).

Here are two functions that work together to clean up a list of readings:

```python
def average(values):
    return sum(values) / len(values)

def keep_in_range(values, low, high):
    kept = []
    for v in values:
        if low <= v <= high:
            kept.append(v)
    return kept

readings = [12.1, 12.3, 55.0, 12.2, 12.4]
clean = keep_in_range(readings, 0, 50)

print(f"All readings: {average(readings):.2f}")   # 20.80
print(f"In range:     {average(clean):.2f}")      # 12.25
```

One bad reading pulled the average from about 12 to nearly 21. Filtering helps — but think carefully before discarding data. The 55.0 might be a sensor glitch, or it might be a real event you need to know about. Removing values should be a deliberate, documented decision, never a quiet way to get a nicer number.

### A first simulation: cooling tea

Many physical processes can be simulated by asking: *given the state now, what will it be a moment later?* — and repeating. This is called **stepping forward in time**.

A hot drink cools faster when it is much hotter than the room, and more slowly as it approaches room temperature. A simple model, known as Newton's law of cooling, says the rate of cooling is proportional to the temperature difference. Over a small time step, the drop in temperature is roughly:

```
drop = k · (T − T_room) · dt
```

where k is a cooling constant that depends on the cup, and dt is the length of the step. In Python:

```python
temperature = 90.0   # °C, starting temperature
room = 20.0          # °C
k = 0.1              # cooling constant, per minute (an assumed value)
dt = 1.0             # time step, minutes

for minute in range(1, 11):
    temperature = temperature - k * (temperature - room) * dt
    print(f"t = {minute:2d} min   T = {temperature:5.1f} °C")
```

Output:

```
t =  1 min   T =  83.0 °C
t =  2 min   T =  76.7 °C
t =  3 min   T =  71.0 °C
t =  4 min   T =  65.9 °C
t =  5 min   T =  61.3 °C
t =  6 min   T =  57.2 °C
t =  7 min   T =  53.5 °C
t =  8 min   T =  50.1 °C
t =  9 min   T =  47.1 °C
t = 10 min   T =  44.4 °C
```

The drops get smaller as the tea approaches room temperature, which matches everyday experience. Notice the shape of this code: it is the same "next = now + change" pattern as the feedback controller in Robotics Foundations. Stepping a model forward in time is one of the most important ideas in computational engineering.

### Step size matters

Let us wrap the simulation in a function and ask how long the tea takes to cool to 60 °C:

```python
def minutes_to_cool(start, room, k, target, dt):
    t = 0.0
    temp = start
    while temp > target:
        temp = temp - k * (temp - room) * dt
        t += dt
    return t

print(round(minutes_to_cool(90.0, 20.0, 0.1, 60.0, dt=1.0), 2))   # 6.0
print(round(minutes_to_cool(90.0, 20.0, 0.1, 60.0, dt=0.1), 2))   # 5.6
```

The two answers differ. With one-minute steps, the simulation can only report whole minutes and assumes the cooling rate stays fixed for a whole minute. Smaller steps follow the true curve more closely; for this model, the exact answer is about 5.6 minutes. Choosing a step size small enough to be accurate but large enough to run quickly is a decision every simulation engineer makes — and a result is not trustworthy until you have checked that making the step smaller does not change it much.

> **A simulation is a model, not a measurement.** The cooling constant k = 0.1 above is an assumed value, not a measured one. When you share results from a simulation, say which values were assumed, which were measured, and what step size you used. Never present simulated numbers as if they were experimental data.

#### Project: Programming project: a sensor log checker

Write a Python program, on a computer or in a free online Python environment, that analyses a list of at least 15 temperature readings you make up (include one or two obviously wrong values).

Your program should use **at least two functions** of your own and should:

1. Print the number of readings, the minimum, the maximum and the average.
2. Report the index and value of any reading outside a range you choose, and explain your choice of range in a comment.
3. Print the average with and without the out-of-range readings, clearly labelled.
4. Extend the cooling simulation: find how long the tea takes to reach 60 °C for dt = 1, 0.5, 0.1 and 0.01, and print the results in a small table.

No hardware is required.

**Deliverables**

- A Python 3 file with at least two documented functions
- Program output showing the summary statistics and flagged readings
- A step-size table and two or three sentences on what it shows

#### Check your understanding

1. Which numbers does range(4) produce?
   A) 1, 2, 3, 4
   B) 0, 1, 2, 3
   C) 0, 1, 2, 3, 4
   D) 4

2. What decides which lines belong inside an if block in Python?
   A) Indentation
   B) Curly braces
   C) Semicolons
   D) The word end

3. temperature = 25. Which line is printed by: if temperature > 30: ... elif temperature > 20: print("warm") else: print("cool")?
   A) Nothing
   B) warm
   C) cool
   D) Both warm and cool

4. Why might a while loop run forever?
   A) Because while loops are always infinite
   B) Because nothing inside the loop changes the condition towards becoming false
   C) Because the loop has a docstring
   D) Because it uses floats

5. In the cooling simulation, the result changed when the step size shrank from 1.0 to 0.1 minutes. What is the best conclusion?
   A) The program is broken
   B) Larger steps are always more accurate
   C) The coarse step was too large to follow the curve accurately; results should be checked by reducing the step until they stop changing much
   D) Step size never matters

**Go further:**

- Python documentation — Built-in Functions: https://docs.python.org/3/library/functions.html — The official reference for print, len, sum, max, range, enumerate, round and the other built-ins used in this lesson.
- The Python Tutorial — official documentation: https://docs.python.org/3/tutorial/index.html — Section 4 covers if, for, range and defining functions in more detail.


## 1.3 Lists, dictionaries and looping over data

*Organise real engineering data in Python: slice and transform lists of sensor readings, describe a component with a dictionary, and loop over tables and grid maps.* (about 35 min)

### Why data structures matter

A robot is a data factory. A distance sensor produces a new number every few milliseconds. Each wheel has settings such as a gear ratio and a speed limit. A map of the room might be a grid of hundreds of cells, each free or blocked. Before you can analyse any of this, you need a sensible way to hold it in a program.

You have already met **lists** and the `for` loop. This lesson goes further: taking pieces of lists, building new lists from old ones, and a second structure — the **dictionary** — that stores values under names instead of positions. Together they can represent almost any dataset you will meet in this pathway.

### Slicing: taking part of a list

Here are seven temperature readings, one per second. One of them looks odd.

```python
readings = [20.1, 20.3, 20.2, 35.9, 20.4, 20.2, 20.5]   # °C

print(readings[0:3])      # items 0, 1 and 2
print(readings[-3:])      # the last three
print(readings[::2])      # every second item
print(35.9 in readings)   # is this value in the list?
print(sorted(readings))   # a new, sorted copy
```

Output:

```
[20.1, 20.3, 20.2]
[20.4, 20.2, 20.5]
[20.1, 20.2, 20.4, 20.5]
True
[20.1, 20.2, 20.2, 20.3, 20.4, 20.5, 35.9]
```

A slice `readings[start:stop]` includes `start` but stops *before* `stop`, just like `range`. Leaving out a number means "from the beginning" or "to the end". A third number is the step. Slicing always produces a **new** list and never changes the original.

### A trap: two names, one list

Lists can be changed after they are created — you can append, remove or overwrite items. That makes this behaviour important:

```python
readings = [20.1, 20.3, 20.2, 35.9, 20.4]
cleaned = readings        # this does NOT copy the list
cleaned[3] = 20.3         # "fix" the spike
print(readings)

readings = [20.1, 20.3, 20.2, 35.9, 20.4]
cleaned = readings.copy() # a genuine, separate copy
cleaned[3] = 20.3
print(readings)
```

Output:

```
[20.1, 20.3, 20.2, 20.3, 20.4]
[20.1, 20.3, 20.2, 35.9, 20.4]
```

Writing `cleaned = readings` gives the *same* list a second name, so changing one changes "both". In the first case the raw data was silently overwritten — exactly the kind of quiet error that ruins an experiment. When you want to keep the original, make a copy with `.copy()` or a slice `readings[:]`.

### Building new lists: comprehensions

A very common job is turning one list into another: converting units, or picking out items that meet a condition. A **list comprehension** does this in one line. Here, raw counts from a distance sensor's analog-to-digital converter are turned into volts (for this converter, 1023 counts means 3.3 V):

```python
raw_counts = [512, 530, 498, 1023, 505]

volts = [round(c * 3.3 / 1023, 2) for c in raw_counts]
print(volts)

saturated = [i for i, c in enumerate(raw_counts) if c >= 1023]
print("Saturated at indices:", saturated)
```

Output:

```
[1.65, 1.71, 1.61, 3.3, 1.63]
Saturated at indices: [3]
```

Read the first comprehension aloud: "round(c × 3.3 / 1023) **for** each c **in** raw_counts". The second adds an `if` to keep only some items. A reading stuck at the maximum count usually means the signal went off the top of the scale, so it is worth flagging rather than trusting.

### Walking two lists together, and sliding windows

`zip` pairs up items from two lists, which is ideal when two sensors were sampled at the same moments. For a two-wheeled robot, the difference between the wheel speeds tells you whether it is driving straight:

```python
left = [100, 102, 98, 101]    # mm/s
right = [100, 110, 120, 101]  # mm/s
print([r - l for l, r in zip(left, right)])
```

Output:

```
[0, 8, 22, 0]
```

A positive difference means the right wheel is faster, so the robot is turning left.

Sometimes each output depends on a *group* of neighbouring inputs. A **moving average** replaces each run of `window` readings with its mean, smoothing out noise:

```python
readings = [20.1, 20.3, 20.2, 35.9, 20.4, 20.2, 20.5]
window = 3

smoothed = []
for i in range(len(readings) - window + 1):
    chunk = readings[i:i + window]
    smoothed.append(round(sum(chunk) / window, 2))
print(smoothed)
```

Output:

```
[20.2, 25.47, 25.5, 25.5, 20.37]
```

Seven readings give five windows, which is why the loop runs `len(readings) - window + 1` times. Notice what happened to the spike: averaging did not remove it, it *smeared* it across three outputs. Knowing what a method does to unusual data is as important as knowing how to code it.

### Dictionaries: values with names

A list is good for many values of the same kind in order. A **dictionary** (`dict`) is better when each value has a meaning, such as the settings of one wheel drive. Each entry is a **key** and a **value**:

```python
drive = {"name": "left_drive", "max_rpm": 300, "gear_ratio": 30}

print(drive["max_rpm"])                    # look up by key
drive["max_rpm"] = 280                     # change a value
drive["encoder_cpr"] = 12                  # add a new key
print(drive.get("current_limit_a", 2.0))   # missing key: use a default
print("gear_ratio" in drive)               # does the key exist?

for key, value in drive.items():
    print(f"{key:12} = {value}")
```

Output:

```
300
2.0
True
name         = left_drive
max_rpm      = 280
gear_ratio   = 30
encoder_cpr  = 12
```

Asking for a key that does not exist with square brackets, such as `drive["current_limit_a"]`, stops the program with a `KeyError`. `.get(key, default)` is the safe alternative when a missing key is normal. Dictionaries remember the order in which keys were added.

### Counting with a dictionary

Dictionaries are perfect for counting. Here is a made-up status log from a robot:

```python
log = ["OK", "OK", "LOW_BATTERY", "OK", "STALL", "OK", "STALL"]

counts = {}
for status in log:
    counts[status] = counts.get(status, 0) + 1
print(counts)
```

Output:

```
{'OK': 4, 'LOW_BATTERY': 1, 'STALL': 2}
```

The first time a status appears, `.get` returns 0, so the count starts at 1.

### Tables and grids

Real datasets combine the two structures. A **list of dictionaries** works like a table, one dictionary per row. Here, two distance sensors were logged together (made-up values), and we regroup the table into a **dictionary of lists**, one list per sensor:

```python
samples = [
    {"t": 0.0, "sensor": "front", "mm": 412},
    {"t": 0.0, "sensor": "left", "mm": 95},
    {"t": 0.1, "sensor": "front", "mm": 398},
    {"t": 0.1, "sensor": "left", "mm": 97},
    {"t": 0.2, "sensor": "front", "mm": 381},
    {"t": 0.2, "sensor": "left", "mm": 96},
]

by_sensor = {}
for s in samples:
    name = s["sensor"]
    if name not in by_sensor:
        by_sensor[name] = []
    by_sensor[name].append(s["mm"])

print(by_sensor)
for name, values in by_sensor.items():
    print(f"{name}: closest {min(values)} mm")
```

Output:

```
{'front': [412, 398, 381], 'left': [95, 97, 96]}
front: closest 381 mm
left: closest 95 mm
```

The front distance is shrinking steadily (the robot is approaching something) while the left distance holds near 96 mm (it is following a wall).

A **list of lists** works like a grid. This is how many robots store a map: 0 for a free cell, 1 for an obstacle. You read a cell with two indices, row first: `grid[row][col]`.

```python
grid = [
    [0, 0, 0, 1, 0],
    [0, 1, 0, 1, 0],
    [0, 1, 0, 0, 0],
    [0, 0, 0, 1, 0],
]

print(grid[1][3])   # row 1, column 3

obstacles = 0
for row in grid:
    for cell in row:
        if cell == 1:
            obstacles += 1
print(f"{len(grid)} x {len(grid[0])} grid, {obstacles} obstacle cells")

for row in grid:
    print("".join("#" if cell == 1 else "." for cell in row))
```

Output:

```
1
4 x 5 grid, 5 obstacle cells
...#.
.#.#.
.#...
...#.
```

A loop inside a loop visits every cell. The last two lines build each row as a string of characters and join them, a quick way to *see* a map. You will use this grid again when you meet path-planning algorithms.

### Recap

- Slices like `values[a:b]` take part of a list without changing it; `b` is excluded.
- Assigning a list to a second name does not copy it. Use `.copy()` to protect raw data.
- Comprehensions build new lists: `[f(x) for x in xs if condition]`.
- `zip` walks two lists in step; a sliding window looks at neighbouring items.
- Dictionaries store values under keys; `.get` handles missing keys, `.items()` loops over pairs.
- Lists of dictionaries act as tables; lists of lists act as grids.

> **Keep the raw data.** Never overwrite your original measurements while cleaning them. Work on a copy, keep the raw list unchanged, and record which values you changed or removed and why. Then anyone, including you next month, can check that the cleaning was reasonable.

#### Check your understanding

1. Given values = [5, 6, 7, 8, 9], what is values[1:3]?
   A) [5, 6, 7]
   B) [6, 7, 8]
   C) [6, 7]
   D) [5, 6]

2. After a = [1, 2, 3]; b = a; b[0] = 99, what is a?
   A) [99, 2, 3]
   B) [1, 2, 3]
   C) [99]
   D) An error

3. drive = {"max_rpm": 300}. What does drive.get("gear_ratio", 1) return?
   A) A KeyError
   B) None
   C) 300
   D) 1

4. Which structure best represents a map where each cell is free or blocked?
   A) A single string
   B) A list of lists, indexed as grid[row][col]
   C) A dictionary with one key
   D) One integer

5. A 3-reading moving average is applied to data containing one large spike. What happens to the spike?
   A) It is removed completely
   B) It is spread, at reduced height, across several smoothed values
   C) It becomes larger
   D) The average ignores it automatically

#### Project: Programming project: a wheel log summary

Make up a list of at least 12 dictionaries, each describing one sample from a two-wheeled robot: a time in seconds, a left wheel speed and a right wheel speed in mm/s. Include a stretch where the robot turns and one sample where a speed is impossible (for example, 5000 mm/s). Label the data as made-up in a comment.

Write a program that:

1. Builds separate `left` and `right` lists using comprehensions.
2. Uses `zip` to print, for each sample, whether the robot is going straight, turning left or turning right. Choose and justify a tolerance in a comment.
3. Counts how many samples fall into each category using a dictionary.
4. Applies a 3-sample moving average to each wheel's speeds and prints the result, then writes two sentences on what happened to your impossible value.

No hardware is required.

**Deliverables**

- A Python 3 file using lists, dictionaries, a comprehension and zip
- Printed output showing the per-sample classification and the category counts
- Two or three sentences on how the moving average treated the impossible value

**Go further:**

- The Python Tutorial — Data Structures: https://docs.python.org/3/tutorial/datastructures.html — Official documentation on list methods, list comprehensions, dictionaries and looping techniques.


## 1.4 Writing and testing functions

*Design functions with clear inputs and outputs, document them with docstrings, and prove they work with small assert-based tests — before a bug reaches the robot.* (about 35 min)

### Why test a function?

Imagine a function that converts wheel encoder ticks into distance. Your robot's odometry, its speed estimate and its "stop after one metre" behaviour all call it. If it contains a small mistake, every one of those features is wrong — and nothing crashes, so nobody notices until the robot drives into a table leg. Functions let you write a calculation once; **tests** let you trust it once.

In the previous lesson on decisions and loops you learned to define functions with `def`, parameters and `return`. This lesson is about writing them *well*: giving each one a clear job, documenting it, and checking it automatically.

### Return values, not just printing

A function can show something on screen with `print`, or hand a value back with `return`. They are not the same:

```python
def show_speed(rpm):
    print(f"Speed: {rpm} rpm")

result = show_speed(120)
print(result)
```

Output:

```
Speed: 120 rpm
None
```

`show_speed` printed a message, but it returned nothing, which Python represents as the special value `None`. Any later code that tries to calculate with `result` will fail. A good rule: **calculation functions return values; only the outer part of the program prints them.** A function that just returns a value, without printing or changing anything else, is also the easiest kind to test.

### Parameters with defaults

Many engineering functions have settings that rarely change. Give those parameters **default values**, so callers only supply them when they differ:

```python
def adc_to_volts(counts, vref=3.3, max_count=1023):
    """Convert a raw analog-to-digital converter reading to volts.

    counts: the integer reading, from 0 to max_count.
    vref: the reference voltage in volts, which gives max_count.
    max_count: the largest reading the converter can produce.
    Returns the voltage as a float.
    """
    return counts * vref / max_count

print(adc_to_volts(1023))
print(f"{adc_to_volts(2048, vref=5.0, max_count=4095):.3f}")
```

Output:

```
3.3
2.501
```

The second call names its arguments (`vref=5.0`). These **keyword arguments** make calls self-explanatory: a reader does not have to remember which number is which.

### Docstrings: the contract

The triple-quoted text at the top of `adc_to_volts` is its **docstring**. A good docstring is a contract between the function and anyone who uses it. It says:

- what the function does, in one line;
- what each parameter means, **including its units**;
- what it returns;
- anything surprising, such as values it cannot handle.

Python stores the docstring with the function, so `help(adc_to_volts)` displays it. Writing it first is also a design test: if you cannot describe a function's job in one sentence, it is probably doing too much and should be split.

### Returning more than one value

Sometimes a calculation naturally produces two results. Return them separated by commas and **unpack** them at the call:

```python
def min_max(values):
    """Return the smallest and largest of a non-empty list of numbers."""
    return min(values), max(values)

low, high = min_max([12.1, 12.4, 11.9, 12.6])
print(low, high)
print(f"Spread: {high - low:.1f}")
```

Output:

```
11.9 12.6
Spread: 0.7
```

### Testing with assert

An `assert` statement checks that something is true. If it is, nothing happens. If it is not, the program stops with an `AssertionError`. That makes it a tiny, automatic test.

Here is a distance function for a wheel with an encoder. One full revolution of a wheel of diameter d rolls a distance of π × d, so a 65 mm wheel travels π × 65 ≈ 204.2 mm per revolution.

```python
import math

def wheel_distance_mm(ticks, ticks_per_rev, diameter_mm):
    """Distance rolled by a wheel, in mm, from encoder ticks.

    Negative ticks mean the wheel turned backwards.
    """
    revolutions = ticks / ticks_per_rev
    return revolutions * math.pi * diameter_mm

def test_wheel_distance():
    # No ticks: no distance.
    assert wheel_distance_mm(0, 360, 65) == 0
    # One revolution: one circumference, worked out by hand.
    assert math.isclose(wheel_distance_mm(360, 360, 65), 204.2035, rel_tol=1e-6)
    # Half a revolution: half the distance.
    assert math.isclose(wheel_distance_mm(180, 360, 65), 0.5 * math.pi * 65)
    # Backwards: same size, opposite sign.
    assert math.isclose(wheel_distance_mm(-360, 360, 65), -math.pi * 65)

test_wheel_distance()
print("wheel_distance_mm: all tests passed")
```

Output:

```
wheel_distance_mm: all tests passed
```

Notice three habits. Each test has a comment saying *why* the expected answer is right. Results that involve π are compared with `math.isclose`, never `==`, because floats are approximate (`rel_tol=1e-6` allows a relative difference of one part in a million, which covers rounding the hand-worked value to 204.2035). And the tests are gathered in a function whose name starts with `test_`, so they can be rerun after every change.

### A test that catches a bug

Here is a `clamp` function, used to keep a speed command inside safe limits. It contains a realistic copy-and-paste mistake:

```python
def clamp(value, low, high):
    """Limit value to the range low to high."""
    if value < low:
        return low
    if value > high:
        return low      # bug: should be high
    return value

def test_clamp():
    assert clamp(50, 0, 100) == 50, "inside the range"
    assert clamp(-20, 0, 100) == 0, "below the range"
    assert clamp(150, 0, 100) == 100, "above the range"
    assert clamp(0, 0, 100) == 0, "exactly on the lower edge"
    assert clamp(100, 0, 100) == 100, "exactly on the upper edge"

try:
    test_clamp()
    print("clamp: all tests passed")
except AssertionError as error:
    print("clamp: test FAILED:", error)
```

Output:

```
clamp: test FAILED: above the range
```

The text after the comma in each `assert` is a message shown when it fails, so the failure tells you immediately which case broke. (The `try`/`except` lines catch the error so we can print it neatly; the lesson on errors explains them. Without them you would see a full traceback ending in `AssertionError: above the range`.) Change `return low` to `return high` and the same tests print `clamp: all tests passed`.

Imagine this bug in a robot: any speed request above the limit would be replaced by the *minimum*, perhaps full reverse. A five-line test found it in a second.

### Choosing good test cases

A handful of well-chosen cases beats dozens of random ones. For each function, try to include:

1. **A typical case** whose answer you have worked out by hand or from a trusted source.
2. **Boundaries** — values exactly on the edges, like 0 and 100 above. Off-by-one mistakes live here.
3. **Special cases** — zero, negative numbers, an empty list, a single item.
4. **Properties** that must always hold, even when you do not know the exact answer: half the ticks should give half the distance; clamping should never return a value outside the range.

Never compute the expected answer by calling the function you are testing. That only checks that the function agrees with itself.

Many engineers write the tests *before* the function. Deciding what `average([])` should do, before writing `average`, forces you to think about awkward cases up front. Larger projects use test runners such as pytest (a free tool installed separately), which find every function named `test_...` and run it — the same plain `assert` statements work there too.

### Recap

- Calculation functions should **return** results; leave printing to the caller.
- Default and keyword arguments make functions convenient and calls readable.
- A docstring states the job, the parameters with units, and the return value.
- `assert condition, "message"` is a minimal automatic test; compare floats with `math.isclose`.
- Test typical values, boundaries, special cases and properties, with expected answers worked out independently.
- Rerun your tests after every change.

> **Tests check what you thought of.** Passing tests show that a function behaves correctly *for the cases you tested*. They cannot prove it is correct for everything. When a bug slips through, first write a test that reproduces it, then fix the code. The bug can never quietly return.

#### Check your understanding

1. A function prints a result but has no return statement. What does calling it give back?
   A) The printed text
   B) 0
   C) None
   D) An error

2. Why should a test compare wheel_distance_mm(360, 360, 65) with math.isclose rather than ==?
   A) Because the result involves π and floating-point arithmetic, so it may differ from the hand value in the last digits
   B) Because == cannot compare numbers
   C) Because math.isclose is faster
   D) Because the function returns a string

3. Which set of test cases is best for clamp(value, 0, 100)?
   A) 50 only
   B) Ten random values between 0 and 100
   C) 50, -20, 150, 0 and 100
   D) Values computed by calling clamp itself

4. What happens when assert x > 0, "x must be positive" runs with x = -3?
   A) Nothing; assert only prints a warning
   B) x is changed to 3
   C) The program carries on and returns False
   D) An AssertionError with the message "x must be positive" is raised

5. In def adc_to_volts(counts, vref=3.3), what does vref=3.3 mean?
   A) vref is always 3.3 and cannot be changed
   B) vref defaults to 3.3 when the caller does not supply it
   C) The function returns 3.3
   D) counts must equal 3.3

#### Project: Programming project: a tested toolkit

Build a small Python module of engineering helpers, each with a docstring and a test function.

1. `average(values)` — decide, and document, what it should do for an empty list.
2. `celsius_to_fahrenheit(c)` — test it with values you can check by hand: 0 °C is 32 °F and 100 °C is 212 °F, and −40 is the same in both scales.
3. `wheel_distance_mm(ticks, ticks_per_rev, diameter_mm)` from this lesson.
4. `clamp(value, low, high)` — add a test that checks the result is never outside the range for every whole number from −200 to 200.

Then deliberately break each function in a small way (change an operator, a sign or a boundary) and confirm that at least one of your tests fails. If a break goes unnoticed, add a test that catches it.

No hardware is required.

**Deliverables**

- A Python 3 file with four documented functions and a test_ function for each
- Output showing every test passing
- A short list of the deliberate bugs you introduced and which test caught each one

**Go further:**

- The Python Tutorial — More on Defining Functions: https://docs.python.org/3/tutorial/controlflow.html — Official coverage of default arguments, keyword arguments and documentation strings (see section 4.9).
- Python Language Reference — Simple statements: https://docs.python.org/3/reference/simple_stmts.html — Includes the precise definition of the assert statement.


## 1.5 Reading files and CSV data

*Save and load data with Python's standard library: write and read text files safely, parse CSV logs with the csv module, cope with missing values and save your results.* (about 35 min)

### Why files?

Everything so far has lived inside the program: you typed the readings into a list. Real data does not arrive that way. A data logger writes a file to a memory card; a robot saves a log of every run; a teammate emails a spreadsheet of test results. To analyse any of it, your program must **read files** — and to share your results, it must **write** them.

The most common format for engineering data is **CSV**, "comma-separated values": a plain text file where each line is a row and commas separate the columns. Spreadsheets can open and save it, and Python can read it with nothing but its standard library.

To follow along, run each example from the same folder. The first example creates the file that the next ones read, so you do not need any data of your own.

### Writing a text file

```python
lines = ["time_s,temp_c", "0,21.4", "10,21.9", "20,22.7", "30,23.1"]

with open("temps.csv", "w", encoding="utf-8") as f:
    for line in lines:
        f.write(line + "\n")

print("Saved temps.csv")
```

Output:

```
Saved temps.csv
```

`open(name, "w")` opens a file for **writing**, creating it — or **replacing** it, without warning, if it already exists. The `with` statement closes the file automatically when the indented block ends, even if something goes wrong part-way through. Always use it. `\n` is the **newline** character; `write` does not add one for you. `encoding="utf-8"` makes sure symbols such as °C are saved the same way on every computer.

### Reading it back

Opening a file with no mode reads it. Looping over the file gives one line at a time:

```python
with open("temps.csv", encoding="utf-8") as f:
    for line in f:
        print(repr(line))
```

Output:

```
'time_s,temp_c\n'
'0,21.4\n'
'10,21.9\n'
'20,22.7\n'
'30,23.1\n'
```

`repr` shows exactly what is in each string, including the invisible newline at the end. Every line is **text**, even the ones that look like numbers. To use the data, strip off the newline, split at the comma and convert:

```python
times = []
temps = []

with open("temps.csv", encoding="utf-8") as f:
    header = f.readline()          # read and skip the first line
    for line in f:
        t_text, temp_text = line.strip().split(",")
        times.append(float(t_text))
        temps.append(float(temp_text))

print(times)
print(temps)
rate = (temps[-1] - temps[0]) / (times[-1] - times[0])   # °C per second
print(f"Warming at {rate * 60:.2f} °C per minute")
```

Output:

```
[0.0, 10.0, 20.0, 30.0]
[21.4, 21.9, 22.7, 23.1]
Warming at 3.40 °C per minute
```

`.strip()` removes spaces and newlines from both ends, and `.split(",")` breaks the line into a list of pieces. Forgetting to convert is a classic bug: `"21.4" < "3.0"` is `True`, because strings are compared letter by letter, not by value.

### When splitting by commas breaks

Splitting on commas works until a field itself contains a comma — for example a note such as "load added, then removed". CSV handles this by putting such fields in quotes, and the standard `csv` module understands the rules. Let us create a made-up log from a small drive test using `csv.writer`:

```python
import csv

rows = [
    ["time_s", "current_a", "rpm", "note"],
    [0.0, 0.42, 0, "start"],
    [0.5, 1.85, 140, ""],
    [1.0, 1.10, 210, ""],
    [1.5, "", 212, "current sensor dropout"],
    [2.0, 1.04, 215, "load added, then removed"],
]

with open("drive_log.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(rows)

with open("drive_log.csv", encoding="utf-8") as f:
    print(f.read())
```

Output:

```
time_s,current_a,rpm,note
0.0,0.42,0,start
0.5,1.85,140,
1.0,1.1,210,
1.5,,212,current sensor dropout
2.0,1.04,215,"load added, then removed"

```

The writer added quotes around the note containing a comma, and left an empty field where a current reading is missing. The `newline=""` argument is what the `csv` documentation asks for when opening files for the `csv` module; it stops blank lines appearing between rows on some systems.

### Reading CSV with DictReader

`csv.DictReader` reads the header row for you and returns each following row as a **dictionary**, keyed by column name. That makes code readable and robust to someone adding a column later:

```python
import csv

currents = []
missing = 0

with open("drive_log.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        if row["current_a"] == "":
            missing += 1
            continue                  # skip to the next row
        currents.append(float(row["current_a"]))

print(f"{len(currents)} current readings, {missing} missing")
print(f"Peak current: {max(currents):.2f} A")
print(f"Mean current: {sum(currents) / len(currents):.3f} A")
```

Output:

```
4 current readings, 1 missing
Peak current: 1.85 A
Mean current: 1.103 A
```

Every value from `DictReader` is a string, so we still convert with `float`. `continue` jumps straight to the next row of the loop. Note that we **counted** the missing value instead of silently dropping it: "mean of 4 readings, 1 missing" is an honest summary; "mean current 1.103 A" on its own hides a gap in the data.

### Writing your results

Results are worth saving too, so a report or another program can use them. Here we compute a summary for each column and write it to a new file, leaving the original log untouched:

```python
import csv

with open("drive_log.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

summary = []
for column in ["current_a", "rpm"]:
    values = [float(r[column]) for r in rows if r[column] != ""]
    summary.append([column, len(values), min(values), max(values)])

with open("drive_summary.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["column", "count", "min", "max"])
    writer.writerows(summary)

with open("drive_summary.csv", encoding="utf-8") as f:
    print(f.read(), end="")
```

Output:

```
column,count,min,max
current_a,4,0.42,1.85
rpm,5,0.0,215.0
```

`list(csv.DictReader(f))` reads every row into a list of dictionaries — the "table" structure from the lesson on lists and dictionaries. That is fine for files of thousands of rows. For very large logs, loop over the reader row by row as in the previous example, so the whole file never has to fit in memory at once.

### When the file is not where you think

If Python cannot find a file, it stops with `FileNotFoundError`. A relative name like `"drive_log.csv"` is looked up in the **current working directory** — usually the folder you ran the program from, which is not always the folder containing your script. `import os` followed by `print(os.getcwd())` shows where Python is looking. Keeping data files next to your script, and running the script from that folder, avoids most of these problems.

### Recap

- Use `with open(...) as f:` so files are always closed; `"w"` replaces a file, so never point it at your raw data.
- Lines read from a file are strings ending in `\n`: strip, split and convert them.
- The `csv` module handles quoting and commas inside fields; open CSV files with `newline=""`.
- `csv.DictReader` gives each row as a dictionary keyed by the header.
- Count missing or invalid values and report them, rather than silently dropping them.
- Write results to a new file, keeping the original log unchanged.

> **Raw data is read-only.** Treat the files your experiment produced as read-only: open them with no mode (reading), and write anything derived from them to a new file with a different name. A program that opens your only copy of a log with `"w"` will erase it in an instant. Keeping the raw file means every processing step can be checked and repeated.

#### Check your understanding

1. What happens if you run open("results.csv", "w") and results.csv already exists?
   A) Python refuses and raises an error
   B) The new data is added to the end of the file
   C) The existing contents are erased and the file starts empty
   D) Python asks for confirmation

2. Each line read from a text file such as temps.csv is…
   A) A string, usually ending in a newline character
   B) A float
   C) A list of numbers
   D) A dictionary

3. Why use the csv module rather than line.split(",")?
   A) split is not allowed on strings read from files
   B) The csv module converts every value to a number automatically
   C) The csv module makes files smaller
   D) It correctly handles quoted fields that themselves contain commas

4. A log has 50 rows and 3 have an empty temperature field. What is the most honest summary?
   A) Report the mean of the 47 valid readings and state that 3 were missing
   B) Treat the missing values as 0 and report the mean of 50
   C) Delete the 3 rows from the original file
   D) Report only the mean, since missing values are unimportant

5. Your program raises FileNotFoundError for "log.csv", but the file is definitely on your computer. What is the most likely cause?
   A) The file is too large to open
   B) Python is looking in a different current working directory
   C) CSV files cannot be opened with open
   D) The file must be renamed to log.txt

#### Project: Programming project: a log processor

Write a program in two parts.

**Part 1 — make the data.** Write a CSV file called `room_log.csv` with columns `time_s`, `temp_c` and `humidity_pct` and at least 30 rows of made-up readings, one every 10 seconds. Put a comment saying the data is made up. Leave at least two fields empty and put the text `ERR` in one.

**Part 2 — analyse it.** Using `csv.DictReader`:

1. For each of the two measurement columns, count the valid, empty and non-numeric values. (Hint: a value is numeric if it is not empty and not `ERR`; the lesson on errors shows a more general method.)
2. Compute the minimum, maximum and mean of each column using only valid values.
3. Write the results to `room_summary.csv`, one row per column, and print the summary file.
4. Confirm that `room_log.csv` is unchanged by printing its first three lines at the end.

No hardware is required.

**Deliverables**

- A Python 3 program that writes room_log.csv and produces room_summary.csv
- Printed output showing counts of valid and missing values for each column
- The contents of room_summary.csv

**Go further:**

- Python documentation — csv: CSV File Reading and Writing: https://docs.python.org/3/library/csv.html — The official reference for csv.reader, csv.writer, DictReader and DictWriter, with examples.
- The Python Tutorial — Input and Output: https://docs.python.org/3/tutorial/inputoutput.html — Section 7.2 explains opening, reading and writing files and why the with statement is recommended.


## 1.6 Errors, tracebacks and debugging

*Read Python's error messages with confidence, handle expected problems with try and except, and find silent logic bugs with a systematic debugging method.* (about 35 min)

### Why debugging is a core engineering skill

Every program of any size has bugs while it is being written. Professional engineers are not people who never make mistakes; they are people who find mistakes quickly and methodically. On a robot this matters twice over: a bug can mean a crash in the software *and* a crash in the physical world. This lesson gives you a toolkit: how to read error messages, how to make a program cope with problems you expect, and how to hunt down the ones you did not expect.

### Three kinds of error

1. **Syntax errors.** The code is not valid Python, so it will not run at all. Python points at the problem before anything happens.
2. **Runtime errors (exceptions).** The code is valid but something goes wrong while it runs — dividing by zero, opening a missing file — and Python stops with a **traceback**.
3. **Logic errors.** The program runs to the end and prints an answer, but the answer is wrong. Python cannot detect these, which makes them the most dangerous.

A syntax error looks like this, for a missing colon:

```
  File "check.py", line 1
    if speed > 10
                 ^
SyntaxError: expected ':'
```

The caret `^` marks where Python got confused. The real mistake is usually there or on the line just before it.

### Reading a traceback

Save this program as `rover.py` and run it:

```python
# rover.py
def average(values):
    return sum(values) / len(values)

def report(name, values):
    print(f"{name}: {average(values):.1f} mm")

report("front", [412, 398, 381])
report("rear", [])
```

Output:

```
front: 397.0 mm
Traceback (most recent call last):
  File "rover.py", line 9, in <module>
    report("rear", [])
    ~~~~~~^^^^^^^^^^^^
  File "rover.py", line 6, in report
    print(f"{name}: {average(values):.1f} mm")
                     ~~~~~~~^^^^^^^^
  File "rover.py", line 3, in average
    return sum(values) / len(values)
           ~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
```

(Python prints the full path to the file; it is shortened here. The `~` and `^` markers appear in recent versions of Python and may look slightly different on yours.)

Read a traceback **from the bottom up**:

- The **last line** says *what* went wrong: a `ZeroDivisionError`.
- The entry just above it says *where*: line 3, inside `average`.
- Moving upwards, each entry shows *who called whom*: `average` was called by `report` on line 6, which was called from the main program on line 9.

The first report worked; the second passed an empty list, so `len(values)` was 0. The traceback shows the line that crashed, but the real cause is often further up the chain — here, the caller supplied data the function could not handle.

### Common exceptions and what they usually mean

- `NameError: name 'sped' is not defined` — a typo in a variable name, or using a variable before creating it. Recent Python versions add a hint such as "Did you mean: 'speed'?".
- `TypeError: can only concatenate str (not "float") to str` — mixing types, such as `"Speed: " + 12.5`. Use an f-string instead.
- `ValueError: could not convert string to float: 'n/a'` — the type is right but the content is not, typical of messy data files.
- `IndexError: list index out of range` — asking for position 10 of a shorter list, often an off-by-one loop.
- `KeyError: 'max_amps'` — a dictionary has no such key; check the spelling or use `.get`.
- `FileNotFoundError` — the file is not in the folder Python is looking in.

### Handling errors you expect

Some problems are not bugs but facts of life. Sensors return garbage, and logs contain `ERR`. For these, use `try` and `except`: Python tries the indented block, and if the named exception happens, it runs the `except` block instead of stopping.

```python
def parse_reading(text):
    """Return text as a float, or None if it is not a valid number."""
    try:
        return float(text)
    except ValueError:
        return None

raw = ["12.5", "12.7", "ERR", "", "12.6"]
values = []
bad = []
for i, text in enumerate(raw):
    value = parse_reading(text)
    if value is None:
        bad.append(i)
    else:
        values.append(value)

print(values)
print("Could not read indices:", bad)
```

Output:

```
[12.5, 12.7, 12.6]
Could not read indices: [2, 3]
```

Two rules keep `try` honest. First, **catch only the specific exception you expect** (`ValueError` here). A bare `except:` catches *everything*, including your own typos, and turns real bugs into silent wrong answers. Second, **record what you skipped**, as `bad` does here.

Your own functions can raise exceptions too. That is often better than returning a misleading value:

```python
def average(values):
    """Mean of a non-empty list. Raises ValueError for an empty list."""
    if len(values) == 0:
        raise ValueError("average() needs at least one value")
    return sum(values) / len(values)

try:
    print(average([]))
except ValueError as error:
    print("Problem:", error)
```

Output:

```
Problem: average() needs at least one value
```

A clear message at the moment of the mistake beats a confusing failure three functions later.

### Hunting a logic bug

Logic bugs give no traceback, so you need a method. Here is a moving-average function with a mistake. On a small input whose answer you can work out by hand, the averages of [1, 2, 3], [2, 3, 4] and [3, 4, 5] should be 2, 3 and 4:

```python
def moving_average(values, window):
    out = []
    for i in range(len(values) - window):
        out.append(sum(values[i:i + window]) / window)
    return out

print(moving_average([1, 2, 3, 4, 5], 3))
```

Output:

```
[2.0, 3.0]
```

One window is missing. The quickest way to see why is to **print the program's state** inside the loop. Writing `=` at the end of an expression in an f-string prints the expression and its value:

```python
def moving_average(values, window):
    out = []
    for i in range(len(values) - window):
        print(f"{i=} {values[i:i + window]=}")
        out.append(sum(values[i:i + window]) / window)
    return out

print(moving_average([1, 2, 3, 4, 5], 3))
```

Output:

```
i=0 values[i:i + window]=[1, 2, 3]
i=1 values[i:i + window]=[2, 3, 4]
[2.0, 3.0]
```

The loop never reaches `i = 2`. Five values and a window of three give 5 − 3 + 1 = 3 windows, but `range(5 - 3)` produces only 0 and 1. The fix is `range(len(values) - window + 1)` — the version from the lesson on lists. Now remove the debugging `print` and turn the hand-worked example into a test, `assert moving_average([1, 2, 3, 4, 5], 3) == [2.0, 3.0, 4.0]`, so this bug can never come back.

### A debugging method

When something is wrong, work through these steps instead of changing code at random:

1. **Reproduce it.** Find the smallest input that shows the problem every time.
2. **Read the message.** Bottom line first, then the line it points to.
3. **Form a guess** about the cause, and predict what you would see if it were true.
4. **Test the guess.** Print values, add an `assert`, or try a smaller input. Python's built-in debugger, started by putting `breakpoint()` on a line, lets you pause there and inspect variables.
5. **Divide and conquer.** If you cannot tell where it goes wrong, check the data halfway through the program. Is it already wrong there? Then the bug is in the first half. Repeat.
6. **Change one thing at a time**, and rerun your tests after every fix.
7. **Explain it aloud.** Describing the code line by line to someone else — or to a rubber duck — often reveals the assumption you got wrong.

Keep a short note of bugs that took a long time. Patterns appear quickly: off-by-one ranges, unconverted strings, units mixed up.

### Recap

- Syntax errors stop the program before it runs; exceptions stop it while running; logic errors do not stop it at all.
- Read tracebacks from the bottom: what happened, where, and the chain of calls that led there.
- Use `try`/`except` for problems you expect, catch specific exceptions, and record what you skipped.
- `raise` a clear exception when a function receives input it cannot handle.
- For logic bugs, use a small input with a known answer, print the state, and narrow down methodically.

> **Fix the cause, not the output.** It is tempting to "fix" a wrong result by adjusting a constant until the number looks right, or by wrapping code in `try` and ignoring every error. That hides the bug rather than removing it, and any result produced that way cannot be trusted. Find the real cause, fix it, and add a test.

#### Check your understanding

1. Where should you start reading a Python traceback?
   A) The first line, "Traceback (most recent call last)"
   B) The middle entry
   C) The last line, which names the exception and describes it
   D) It does not matter; all lines say the same thing

2. float("ERR") raises which exception?
   A) ValueError
   B) TypeError
   C) NameError
   D) KeyError

3. Why is a bare except: (catching every exception) usually a bad idea?
   A) It makes the program run slower
   B) It is not valid Python
   C) It only catches syntax errors
   D) It also hides unexpected bugs such as typos, so the program carries on silently with wrong results

4. A program runs without any error message but prints a wrong average. What kind of error is this?
   A) A syntax error
   B) A logic error
   C) A runtime exception
   D) A hardware fault

5. You suspect a bug somewhere in a 200-line data-processing script. What is a good first step?
   A) Rewrite the whole script from scratch
   B) Check the data at the halfway point to see whether it is already wrong there
   C) Change several lines at once and see if the output improves
   D) Wrap the whole script in try and except

#### Project: Debugging project: three bugs

The program below is meant to convert a list of temperature readings from °C to °F, skipping any that cannot be read, and print every converted value. It contains **three** bugs.

```python
readings = ["20.5", "21.0", "bad", "22.5", "23.0"]

def to_numbers(texts):
    numbers = []
    for t in texts:
        numbers.append(float(t))
    return numbers

def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 23

values = to_numbers(readings)
for i in range(1, len(values)):
    print(celsius_to_fahrenheit(values[i]))
```

1. Run it and read the traceback. Write down what it tells you before changing anything.
2. Fix the bug the traceback reveals using `try`/`except`, and make the program report how many readings it skipped.
3. Find the two remaining logic bugs using test cases you can check by hand (0 °C is 32 °F; 100 °C is 212 °F) and by printing the loop variable.
4. Add `assert` tests so that each bug would be caught if it came back.

No hardware is required.

**Deliverables**

- The corrected Python 3 program with assert tests
- A short bug log: for each bug, the symptom, how you found it and the fix
- Output showing all four valid readings converted correctly

**Go further:**

- The Python Tutorial — Errors and Exceptions: https://docs.python.org/3/tutorial/errors.html — Official explanation of syntax errors, exceptions, try/except and raising your own exceptions.
- Python documentation — Built-in Exceptions: https://docs.python.org/3/library/exceptions.html — A reference describing every standard exception, such as ValueError, KeyError and IndexError.
- Python documentation — pdb, the Python debugger: https://docs.python.org/3/library/pdb.html — How to pause a program with breakpoint(), step through it line by line and inspect variables.


---

# Module 2: Engineering algorithms

Step-by-step methods that engineers rely on — searching, sorting, root finding and optimization — and how to judge how fast they are.

**Objectives**

- Describe an algorithm precisely enough that someone else could follow it.
- Implement linear and binary search and compare how their run time grows.
- Find the root of an equation numerically using bisection.
- Explain the difference between an exact and an approximate (numerical) answer.


## 2.1 Algorithms and complexity

*What makes a method an algorithm, how to count the steps it takes, and how big-O notation predicts whether it will still be fast when the problem grows.* (about 30 min)

### Why speed is a design requirement

A robot's planner might have 50 milliseconds to decide where to move next. A test on a small map runs instantly, so everything seems fine. Then the map grows ten times larger and the planner takes not ten times longer but a hundred — and the robot stutters, or stops. Engineers need a way to predict, *before* this happens, how the work a method does grows with the size of its input. That is what this lesson is about.

### What is an algorithm?

An **algorithm** is a precise, finite sequence of steps that turns an input into an output. "Find the hottest reading" becomes an algorithm when it is written so carefully that anyone (or any computer) following it gets the same answer:

1. Take the first reading as the best so far.
2. For each remaining reading, compare it with the best so far; if it is larger, it becomes the new best.
3. When no readings are left, the best so far is the answer.

In Python, with a counter for the comparisons:

```python
def largest(values):
    best = values[0]
    comparisons = 0
    for v in values[1:]:
        comparisons += 1
        if v > best:
            best = v
    return best, comparisons

print(largest([3.2, 7.9, 1.4, 7.1, 5.5]))
```

Output:

```
(7.9, 4)
```

Five readings needed four comparisons. A thousand readings would need 999. In general, for n readings the algorithm does n − 1 comparisons: the work grows **in proportion** to n.

### Counting steps instead of timing

Why count steps rather than time the program with a stopwatch? Times depend on the computer, on what else is running and on the language. Step counts depend only on the algorithm and the input, so they let you compare methods fairly and predict what will happen on bigger inputs.

Now a harder problem. A simulation has n obstacles and must check every pair for a collision. The first obstacle is checked against all the others, the second against those after it, and so on:

```python
def count_pair_checks(n):
    checks = 0
    for i in range(n):
        for j in range(i + 1, n):
            checks += 1
    return checks

for n in [10, 100, 1000]:
    print(f"{n:5d} obstacles: {count_pair_checks(n):7d} checks")
```

Output:

```
   10 obstacles:      45 checks
  100 obstacles:    4950 checks
 1000 obstacles:  499500 checks
```

The exact formula is n(n − 1)/2. Each time n grows ten times, the work grows roughly a **hundred** times. A loop inside a loop is the classic sign of this behaviour.

### Big-O notation

**Big-O notation** describes how the number of steps grows as the input size n becomes large, ignoring constant factors and smaller terms. The largest-reading algorithm does n − 1 steps: it is **O(n)**, "order n", or linear. The pair check does n(n − 1)/2 = ½n² − ½n steps. For large n the n² term dominates and the ½ is just a constant, so it is **O(n²)**, quadratic.

The common growth rates, from best to worst:

- **O(1)**, constant: the same work whatever n is, such as reading `values[0]`.
- **O(log n)**, logarithmic: the work grows by one step each time n *doubles*. Binary search, in the next lesson, is like this.
- **O(n)**, linear: one pass through the data.
- **O(n log n)**: good sorting algorithms.
- **O(n²)**, quadratic: comparing every item with every other item.
- **O(2ⁿ)**, exponential: trying every subset of n items. Adding a single item doubles the work.

Numbers make the difference vivid:

```python
import math

print(f"{'n':>9} {'log2 n':>7} {'n log2 n':>12} {'n²':>15}")
for n in [10, 1000, 1_000_000]:
    print(f"{n:>9} {math.log2(n):>7.1f} {n * math.log2(n):>12.0f} {n * n:>15}")
```

Output:

```
        n  log2 n     n log2 n              n²
       10     3.3           33             100
     1000    10.0         9966         1000000
  1000000    19.9     19931569   1000000000000
```

Suppose a computer does about 100 million simple steps per second (a rough figure; real speeds vary a lot). For a million items, an O(n log n) method needs about 20 million steps — a fraction of a second. An O(n²) method needs a million million steps — around three hours. An O(2ⁿ) method with n = 100 needs about 1.3 × 10³⁰ steps, which would keep that computer busy for roughly 400 million million years, tens of thousands of times the age of the universe.

### Same problem, different algorithm

Big-O matters most when it helps you choose between methods. Every sensor on a robot's bus must have a unique ID. Here are two ways to check a list of IDs for duplicates:

```python
def has_duplicate_pairs(ids):
    """Compare every pair: O(n²)."""
    steps = 0
    for i in range(len(ids)):
        for j in range(i + 1, len(ids)):
            steps += 1
            if ids[i] == ids[j]:
                return True, steps
    return False, steps

def has_duplicate_set(ids):
    """Remember what we have seen in a set: O(n)."""
    seen = set()
    steps = 0
    for x in ids:
        steps += 1
        if x in seen:
            return True, steps
        seen.add(x)
    return False, steps

ids = list(range(2000))      # 2000 different IDs: the worst case
print(has_duplicate_pairs(ids))
print(has_duplicate_set(ids))
```

Output:

```
(False, 1999000)
(False, 2000)
```

A **set** is a Python collection that stores each value once and can answer "is x in here?" in roughly constant time, however large it is. Using it turns nearly two million steps into two thousand. Same answer, a thousand times less work, and the gap widens as n grows.

Notice that we tested the **worst case**: a list with no duplicates, so neither function can stop early. When engineers quote a big-O figure, they usually mean the worst case, because that is the one that makes a robot miss its deadline.

### What big-O does not tell you

Big-O is a guide, not the whole story:

- It ignores constant factors. An O(n) method that does 1,000 operations per item can be slower than an O(n²) method for small n.
- For small inputs, the simplest code is often the best choice. Optimise only where it matters.
- It counts time, not memory. The set version uses extra memory to save time — a common trade-off.

When speed really matters, **measure** as well: Python's `time.perf_counter()` returns a precise clock reading, so the difference between two readings taken before and after a function call tells you how long it took. Run it several times, because individual timings vary.

### Recap

- An algorithm is a precise, finite set of steps from input to output.
- Counting steps lets you compare algorithms independently of the computer.
- Big-O describes growth for large n, ignoring constants: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ).
- A loop inside a loop over the same data often means O(n²).
- A better algorithm or data structure, such as a set, can beat a faster computer by a huge margin.
- Use big-O to choose, then measure to confirm.

> **Estimate before you run.** Before running a long job, estimate its step count. If an O(n²) method takes 1 second for 10,000 items, it will take about 100 seconds for 100,000 and about 3 hours for a million. A thirty-second estimate can save a wasted afternoon — or tell you to look for a better algorithm.

#### Check your understanding

1. An algorithm does 3n + 20 steps for an input of size n. What is its big-O?
   A) O(1)
   B) O(n)
   C) O(n²)
   D) O(3n + 20)

2. An O(n²) method takes 2 seconds for 1,000 items. Roughly how long for 10,000 items?
   A) 20 seconds
   B) 4 seconds
   C) 200 seconds
   D) 2,000 seconds

3. Why do engineers usually quote the worst case?
   A) Because the worst case is the most common
   B) Because a system must meet its deadline even on the hardest input it may receive
   C) Because the best case cannot be calculated
   D) Because big-O is only defined for the worst case

4. Which change made the duplicate-ID check so much faster?
   A) Using a faster computer
   B) Writing the loops in a different order
   C) Storing seen IDs in a set, so each membership check takes roughly constant time
   D) Testing a smaller list

5. For an O(log n) algorithm, what happens to the work when n doubles?
   A) It doubles
   B) It quadruples
   C) It stays exactly the same
   D) It grows by about one step

#### Project: Programming project: measure growth

Investigate how step counts grow, using Python and a sheet of graph paper (or a free spreadsheet).

1. Use `count_pair_checks` from this lesson for n = 10, 20, 40, 80, 160 and record the results. Each time n doubles, what happens to the count?
2. Write a function that counts the steps to sum a list of n numbers, and record it for the same values of n.
3. Plot both on the same axes. Describe the shapes in a sentence each.
4. Use `time.perf_counter()` to time `has_duplicate_pairs` and `has_duplicate_set` on worst-case lists of 1,000, 2,000 and 4,000 IDs. Repeat each timing three times and note how much it varies. Do the timings grow the way the step counts predict?

No hardware is required.

**Deliverables**

- A table of step counts for both functions and a hand-drawn or spreadsheet plot
- Timings for the two duplicate checks, with repeats
- A paragraph comparing your measurements with the big-O predictions

**Go further:**

- Big O notation — Wikipedia: https://en.wikipedia.org/wiki/Big_O_notation — A thorough reference, including the formal definition and a list of common orders of growth.


## 2.2 Searching and sorting

*Find things in data quickly: linear search, binary search on sorted data, a simple sorting algorithm traced by hand, and why sorting first often pays off.* (about 35 min)

### Why searching and sorting matter

A robot that combines two sensors constantly asks questions like "which camera frame was taken closest to this force reading?" A log of a long test may hold millions of timestamped rows. Finding the right one by checking every row is slow; finding it in twenty steps is possible — **if the data is sorted**. Searching and sorting are some of the most studied algorithms in computing, and they show beautifully how the right method changes the cost from O(n) to O(log n).

### Linear search

The simplest search looks at each item in turn until it finds a match:

```python
def linear_search(items, target):
    """Return (index of target, steps taken), or (-1, steps) if absent."""
    steps = 0
    for i, x in enumerate(items):
        steps += 1
        if x == target:
            return i, steps
    return -1, steps

parts = ["M3-bolt", "bearing-608", "spacer-10", "M3-nut", "servo-horn"]
print(linear_search(parts, "M3-nut"))
print(linear_search(parts, "gear-20T"))
```

Output:

```
(3, 4)
(-1, 5)
```

Linear search works on any list, sorted or not, and is perfectly fine for small lists. But its worst case — the target is last or absent — checks every item, so it is O(n). A million items means up to a million comparisons.

### Binary search

If the list is **sorted**, there is a much better way. Think of finding a word in a dictionary: you open it in the middle, see whether your word comes before or after that page, and throw away half the book. Repeat with the remaining half, and so on.

```python
def binary_search(items, target):
    """items must be sorted in increasing order."""
    low, high = 0, len(items) - 1
    steps = 0
    while low <= high:
        steps += 1
        mid = (low + high) // 2
        if items[mid] == target:
            return mid, steps
        elif items[mid] < target:
            low = mid + 1      # target is in the upper half
        else:
            high = mid - 1     # target is in the lower half
    return -1, steps

print(binary_search([3, 8, 12, 15, 21, 30, 42], 21))
```

Output:

```
(4, 3)
```

Trace it by hand. The search range starts as indices 0 to 6. Step 1: the middle is index 3, value 15, which is less than 21, so the target must be in indices 4 to 6. Step 2: the middle is index 5, value 30, too big, so the range becomes index 4 alone. Step 3: index 4 holds 21. Found.

Each step halves the range, so a list of n items needs at most about log₂ n + 1 steps: O(log n). On a large log the difference is dramatic. Here is a made-up log with a timestamp every 10 milliseconds — a million entries:

```python
def linear_search(items, target):
    steps = 0
    for i, x in enumerate(items):
        steps += 1
        if x == target:
            return i, steps
    return -1, steps

def binary_search(items, target):
    low, high = 0, len(items) - 1
    steps = 0
    while low <= high:
        steps += 1
        mid = (low + high) // 2
        if items[mid] == target:
            return mid, steps
        elif items[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1, steps

timestamps_ms = list(range(0, 10_000_000, 10))   # 1,000,000 sorted entries
print(len(timestamps_ms))
print(linear_search(timestamps_ms, 9_876_540))
print(binary_search(timestamps_ms, 9_876_540))
```

Output:

```
1000000
(987654, 987655)
(987654, 20)
```

Nearly a million steps against 20. Binary search is easy to get slightly wrong, though: a `<` where you need `<=`, or `high = mid` instead of `mid - 1`, can make it miss items or loop forever. Test it on small lists, including an empty list, a one-item list and targets at both ends. Python's standard `bisect` module provides carefully tested versions; `bisect.bisect_left(items, target)` returns the position where `target` is, or would be inserted, which is exactly what you need to find the *nearest* timestamp rather than an exact match.

### Sorting: insertion sort

Binary search needs sorted data, so how do you sort? **Insertion sort** is the method many people use for a hand of playing cards: take each new card and slide it left past every larger card until it is in place.

```python
def insertion_sort(values):
    items = values.copy()                 # leave the original alone
    for i in range(1, len(items)):
        current = items[i]
        j = i - 1
        while j >= 0 and items[j] > current:
            items[j + 1] = items[j]       # shift the larger item right
            j -= 1
        items[j + 1] = current            # drop current into the gap
        print(f"after placing {current:2d}: {items}")
    return items

insertion_sort([42, 17, 8, 30, 23])
```

Output:

```
after placing 17: [17, 42, 8, 30, 23]
after placing  8: [8, 17, 42, 30, 23]
after placing 30: [8, 17, 30, 42, 23]
after placing 23: [8, 17, 23, 30, 42]
```

After each step, the front part of the list is sorted. In the worst case (a list in reverse order) each new item slides past every item before it, giving about n²/2 moves: O(n²). But if the data is *almost* sorted — like timestamps that arrive slightly out of order — each item moves only a little, and insertion sort is close to O(n).

### Sorting in practice

For real work, use Python's built-in `sorted` (or the list method `.sort()`). It uses an algorithm called Timsort, which is O(n log n) in the worst case and very fast on partly sorted data. You can sort records by any field by passing a **key** function:

```python
parts = [
    {"name": "bracket", "mass_g": 42},
    {"name": "bolt", "mass_g": 3},
    {"name": "wheel", "mass_g": 65},
]

def by_mass(part):
    return part["mass_g"]

for p in sorted(parts, key=by_mass, reverse=True):
    print(p["name"], p["mass_g"])
```

Output:

```
wheel 65
bracket 42
bolt 3
```

### Why sorted data helps

Sorting once makes many later questions cheap:

- **Searching**: binary search in O(log n).
- **Minimum and maximum**: the first and last items.
- **Median**: the middle item, a robust "typical value" that a single outlier cannot drag around.
- **Duplicates**: equal values end up next to each other.

Is it worth it? Sorting costs O(n log n). If you search only once, a single O(n) linear search is cheaper. If you will search many times, sort once and every search afterwards costs only O(log n).

### Recap

- Linear search works on any list but is O(n).
- Binary search halves the range each step, O(log n), but needs sorted data and careful boundary handling.
- Insertion sort is simple and O(n²) in the worst case, but fast on nearly sorted data.
- In practice, use `sorted` with a `key`; it is O(n log n).
- Sort once when you will search, rank or take medians many times.

#### Check your understanding

1. What must be true of a list before binary search gives correct results?
   A) It must contain only integers
   B) It must be sorted
   C) It must have an even number of items
   D) It must contain no more than 1,000 items

2. About how many steps does binary search need, at most, for a sorted list of 1,000,000 items?
   A) About 20
   B) About 1,000
   C) About 500,000
   D) About 1,000,000

3. Insertion sort is given a list that is already almost in order. How does it perform?
   A) It is at its worst, O(n²)
   B) It cannot handle sorted input
   C) It is close to O(n), because each item moves only a short distance
   D) It always takes exactly n log n steps

4. You need to look up 10,000 different values in an unsorted list of 1,000,000 readings. What is the best plan?
   A) Run linear search 10,000 times
   B) Sort the list once, then use binary search for each value
   C) Use binary search on the unsorted list
   D) Sort the list again before every search

5. Why is the median often a better 'typical value' than the mean for sensor data with occasional glitches?
   A) The median is always larger
   B) The median is easier to calculate on unsorted data
   C) The median uses every value equally
   D) A single extreme value barely changes the median, but it can shift the mean a lot

#### Project: Programming project: aligning two sensor logs

Two made-up sensor logs were recorded at different rates: a camera log with a timestamp every 33 ms and a force log with a timestamp every 10 ms, both starting at 0 and lasting 10 seconds. Create them in Python as sorted lists of timestamps in milliseconds.

1. For each camera timestamp, find the force timestamp closest to it. Do it first with linear search, then with `bisect.bisect_left` (check the item at the returned position and the one before it).
2. Count the total comparisons made by your linear method, and time both methods with `time.perf_counter()`.
3. Check that both methods give identical matches.
4. Write your own `insertion_sort` and test it against `sorted` on 20 random lists (use the `random` module), including an empty list and a list with repeated values.

No hardware is required.

**Deliverables**

- A Python 3 program that matches each camera timestamp to the nearest force timestamp in two ways
- Comparison counts and timings for both methods
- Test output showing insertion_sort agrees with sorted

**Go further:**

- Python documentation — bisect: array bisection algorithm: https://docs.python.org/3/library/bisect.html — Tested binary-search functions for finding positions in sorted lists.
- Python documentation — Sorting Techniques: https://docs.python.org/3/howto/sorting.html — How to use sorted and .sort with key functions, reverse order and stable sorting.
- Binary search — Wikipedia: https://en.wikipedia.org/wiki/Binary_search — The algorithm, its variants and its many off-by-one pitfalls.


## 2.3 Numerical root finding

*Solve equations that have no neat formula: the bisection method, which always works if you can bracket a root, and Newton's method, which is far faster but can fail.* (about 35 min)

### Why engineers solve equations numerically

Many engineering questions come down to "where does this quantity become zero?" At what speed does a drive motor's torque exactly balance the load, so the robot stops accelerating? At what angle does an arm's tip reach a target height? Where does a beam's deflection equal its limit? Rewrite each as f(x) = 0, and the answer is a **root** of f.

Some equations can be solved with algebra. Many cannot, or the algebra is messy. **Numerical root finding** gives an answer to any accuracy you choose by improving a guess step by step. Methods like these also run inside calculators, spreadsheets and simulation software whenever they solve an equation.

### The idea behind bisection

Suppose f is a smooth, unbroken curve, f(a) is negative and f(b) is positive. Then somewhere between a and b the curve must cross zero. (This is the *intermediate value theorem*, but the picture is enough: you cannot walk from below sea level to above it without crossing the shoreline.) The interval [a, b] **brackets** a root.

Now look at the midpoint m. Either f(m) has the same sign as f(a), so the root lies between m and b, or it does not, so the root lies between a and m. Either way we keep a bracket half as wide. Repeat until the bracket is narrower than the tolerance you need.

```python
def bisection(f, a, b, tol):
    """Find a root of f between a and b to within tol."""
    if f(a) * f(b) > 0:
        raise ValueError("f(a) and f(b) must have opposite signs")
    steps = 0
    while b - a > tol:
        mid = (a + b) / 2
        if f(a) * f(mid) <= 0:   # sign change in the left half
            b = mid
        else:                    # sign change in the right half
            a = mid
        steps += 1
    return (a + b) / 2, steps

def f(x):
    return x * x - 2           # its positive root is √2

print(bisection(f, 1.0, 2.0, 1e-6))
```

Output:

```
(1.4142136573791504, 20)
```

The true value is √2 = 1.41421356…, and the answer is within the tolerance of one millionth. Notice that `bisection` takes the function `f` itself as a parameter. In Python, functions are values that can be passed around like numbers, so one root finder works for any equation.

### How many steps?

Each step halves the bracket. Starting with width 1, after n steps the width is 1/2ⁿ. We need 1/2ⁿ < 10⁻⁶, so 2ⁿ > 1,000,000, which first happens at n = 20. Bisection's cost is completely predictable — another O(log) algorithm, like binary search, and for exactly the same reason.

### An engineering example: when does the motor stop accelerating?

A small motor's torque falls roughly linearly with speed. Suppose (made-up but realistic numbers) it gives 0.5 N·m at standstill and zero at 30 rad/s. The load it drives needs 0.05 N·m to overcome friction, plus a term that grows with the square of speed, 0.0004 ω². The robot speeds up while the motor torque exceeds the load torque and settles where they are equal, so we want the root of the **net torque**:

```python
def bisection(f, a, b, tol):
    if f(a) * f(b) > 0:
        raise ValueError("f(a) and f(b) must have opposite signs")
    steps = 0
    while b - a > tol:
        mid = (a + b) / 2
        if f(a) * f(mid) <= 0:
            b = mid
        else:
            a = mid
        steps += 1
    return (a + b) / 2, steps

def net_torque(w):
    motor = 0.5 * (1 - w / 30)       # N·m, falls to zero at 30 rad/s
    load = 0.05 + 0.0004 * w * w     # N·m, friction plus a drag-like term
    return motor - load

w, steps = bisection(net_torque, 0.0, 30.0, 1e-6)
print(f"{w:.4f} rad/s after {steps} steps, residual {net_torque(w):.1e} N·m")
```

Output:

```
18.6512 rad/s after 25 steps, residual 4.1e-09 N·m
```

The bracket [0, 30] is a natural choice: at standstill the net torque is +0.45 N·m, and at 30 rad/s the motor gives nothing, so it is negative. The **residual**, f evaluated at the answer, is tiny — always check it, because it confirms you really found a root. This particular equation is a quadratic, so we can verify with the quadratic formula: the positive root is 18.6512 rad/s. Testing a numerical method on a problem with a known exact answer is how you build trust in it before using it on problems you cannot solve by hand.

### Newton's method

Bisection only uses the *sign* of f. **Newton's method** uses its slope too. At the current guess x, draw the tangent line to the curve and follow it down to where it crosses zero. That crossing is the next guess:

```
x_next = x − f(x) / f′(x)
```

where f′(x) is the derivative, the slope of f at x. For f(x) = x² − 2, the slope is f′(x) = 2x:

```python
def newton(f, dfdx, x, tol=1e-12, max_steps=50):
    for step in range(1, max_steps + 1):
        x_new = x - f(x) / dfdx(x)
        print(f"step {step}: x = {x_new:.15f}")
        if abs(x_new - x) < tol:
            return x_new
        x = x_new
    raise RuntimeError("Newton's method did not converge")

def f(x):
    return x * x - 2

def dfdx(x):
    return 2 * x

newton(f, dfdx, 1.0)
```

Output:

```
step 1: x = 1.500000000000000
step 2: x = 1.416666666666667
step 3: x = 1.414215686274510
step 4: x = 1.414213562374690
step 5: x = 1.414213562373095
step 6: x = 1.414213562373095
```

Look at how the correct digits grow: about 1, then 3, then 6, then 12, then full precision. Near a root, Newton's method roughly **doubles the number of correct digits** at each step. Five steps reach full double precision; bisection, gaining one binary digit per step, would need about 50.

### When Newton's method fails

That speed has a price. Newton's method has no bracket, so nothing guarantees it stays near the root:

- If the slope is zero, the formula divides by zero. If it is merely small, the next guess flies far away.
- It can **cycle**. For f(x) = x³ − 2x + 2 starting at x = 0, the steps go 0, 1, 0, 1, … forever.
- If an equation has several roots, it may find a different one from the one you wanted.
- It needs the derivative, which you may have to work out (or estimate numerically).

```python
def f(x):
    return x**3 - 2 * x + 2

def dfdx(x):
    return 3 * x**2 - 2

x = 0.0
for step in range(1, 5):
    x = x - f(x) / dfdx(x)
    print(f"step {step}: x = {x}")
```

Output:

```
step 1: x = 1.0
step 2: x = 0.0
step 3: x = 1.0
step 4: x = 0.0
```

That is why `newton` above has a `max_steps` limit and raises an error instead of looping forever. Professional solvers often combine the two ideas: they keep a bracket for safety and take Newton-like steps for speed whenever those steps stay inside it.

### Choosing a method

- **Bisection**: needs a bracket with a sign change; slow but guaranteed, with a predictable number of steps.
- **Newton**: needs a good starting guess and the derivative; extremely fast when it works, but can diverge or cycle.
- **Either way**: set a tolerance and a step limit, check the residual, and test on a problem with a known answer.

### Recap

- A root is where f(x) = 0; many engineering questions can be written this way.
- Bisection halves a bracketing interval each step; n steps shrink it by 2ⁿ.
- Newton's method follows tangent lines and roughly doubles correct digits per step near the root.
- Newton's method can fail by dividing by a tiny slope, cycling or finding the wrong root.
- Always limit steps, check residuals and verify against a known case.

> **Plot or tabulate first.** Before running any root finder, evaluate f at a handful of points and look at the signs. It shows you where roots are, how many there are and where a bracket can start. Thirty seconds of looking prevents most root-finding surprises.

#### Check your understanding

1. Bisection on an interval of width 8 runs for 3 steps. How wide is the bracket now?
   A) 5
   B) 2
   C) 1
   D) 0.5

2. Which condition must hold before bisection can start on [a, b]?
   A) f(a) and f(b) have opposite signs
   B) f(a) = f(b)
   C) The derivative of f is known
   D) a and b are both positive

3. Newton's method uses which formula for the next guess?
   A) x_next = (a + b) / 2
   B) x_next = x + f(x) × f′(x)
   C) x_next = f(x) / x
   D) x_next = x − f(x) / f′(x)

4. Newton's method starting at x = 0 alternates 0, 1, 0, 1, … for one equation. What is the best response?
   A) Let it run longer; it will settle eventually
   B) Stop at the step limit, then try a different start or use bisection on a bracket
   C) Accept 0.5 as the root
   D) Newton's method cannot cycle, so the code must be wrong

5. Why compute the residual f(x) at the answer?
   A) It confirms the answer really makes f close to zero
   B) It makes the method converge faster
   C) It gives the derivative
   D) It is needed to start bisection

#### Project: Programming project: a root-finding race

Compare bisection and Newton's method on paper and in Python.

1. By hand, with a calculator, do four steps of bisection for x² − 5 = 0 on [2, 3], and three steps of Newton's method starting at x = 2. Record each guess.
2. In Python, solve the same equation with both methods to a tolerance of 10⁻¹⁰. Print the guesses at each step and the number of steps.
3. Solve cos(x) = x (rewrite it as f(x) = cos(x) − x). Find a bracket by tabulating f at x = 0, 0.25, 0.5, … , 1.5 first.
4. Try Newton's method on x³ − 2x + 2 = 0 from x = 0 and from x = −2. Describe what happens, and use bisection to find the real root reliably.

No hardware is required.

**Deliverables**

- Hand-worked tables of guesses for both methods
- A Python 3 program with both root finders and printed step-by-step output
- A short paragraph comparing speed and reliability, using your results

**Go further:**

- Bisection method — Wikipedia: https://en.wikipedia.org/wiki/Bisection_method — The method, its error bound and a worked example.
- Newton's method — Wikipedia: https://en.wikipedia.org/wiki/Newton%27s_method — Derivation from the tangent line, convergence and examples of failure such as cycling.


## 2.4 Numerical integration and differentiation

*Turn sampled data into totals and rates: the trapezoid rule for distance from speed, finite differences for speed from position, and how step size and noise create error.* (about 35 min)

### Why calculus on data?

A wheel encoder tells a robot how fast it is going, sample by sample — but you want to know how *far* it has travelled. A distance sensor tells you *where* an object is at each moment — but a collision warning needs to know how fast it is *approaching*. Going from a rate to a total is **integration**; going from a quantity to its rate of change is **differentiation**.

In a maths class these are done with formulas. On a robot you rarely have a formula — you have a list of numbers taken at regular times. This lesson shows how to integrate and differentiate *samples*, and, just as importantly, how wrong the answers can be.

If you have not met calculus yet, the two ideas you need are simple. The **integral** of speed over time is the area under the speed–time graph, which is the distance travelled. The **derivative** of position is the slope of the position–time graph, which is the speed.

### The trapezoid rule

Between two samples, we do not know exactly what happened. The simplest reasonable assumption is that the speed changed in a straight line. The area under that line is a **trapezoid**: its width is the time step Δt and its average height is the average of the two speeds.

```
area of one slice = ½ × (v₁ + v₂) × Δt
```

Add up all the slices and you have the distance. Here is a made-up log of a robot accelerating and then cruising, sampled every 0.5 s:

```python
times = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]          # s
speeds = [0.0, 0.18, 0.31, 0.40, 0.42, 0.41, 0.40]   # m/s

distance = 0.0
for i in range(1, len(times)):
    dt = times[i] - times[i - 1]
    distance += 0.5 * (speeds[i] + speeds[i - 1]) * dt

print(f"Distance travelled: {distance:.3f} m")
```

Output:

```
Distance travelled: 0.960 m
```

Check the first slice by hand: ½ × (0 + 0.18) × 0.5 = 0.045 m. Computing `dt` from the timestamps, rather than assuming it is constant, means the code still works if a sample arrives late — which, on real hardware, happens.

### How accurate is it?

To measure the error of a method, test it on a problem with a known answer. The area under sin(x) from 0 to π is exactly 2. Here the trapezoid rule is written for a function, using n equal slices:

```python
import math

def trapezoid(f, a, b, n):
    """Integrate f from a to b using n equal trapezoids."""
    h = (b - a) / n
    total = 0.5 * (f(a) + f(b))
    for i in range(1, n):
        total += f(a + i * h)
    return total * h

for n in [4, 8, 16, 32]:
    estimate = trapezoid(math.sin, 0.0, math.pi, n)
    print(f"n = {n:2d}   estimate = {estimate:.6f}   error = {2 - estimate:.6f}")
```

Output:

```
n =  4   estimate = 1.896119   error = 0.103881
n =  8   estimate = 1.974232   error = 0.025768
n = 16   estimate = 1.993570   error = 0.006430
n = 32   estimate = 1.998393   error = 0.001607
```

Each time the number of slices doubles, the error falls by a factor of about **four**. Halving the step h quarters the error, so the error is proportional to h²: the trapezoid rule is a **second-order** method. Knowing the order lets you predict how many samples you need for a given accuracy.

### Finite differences

To estimate a derivative from samples, use the slope between nearby points. There are three common versions, with a small step h:

```
forward:   f′(x) ≈ (f(x + h) − f(x)) / h
backward:  f′(x) ≈ (f(x) − f(x − h)) / h
central:   f′(x) ≈ (f(x + h) − f(x − h)) / (2h)
```

The central difference looks equally far ahead and behind, so its errors largely cancel. Let us test on sin(x) at x = 1, where the exact derivative is cos(1) ≈ 0.5403:

```python
import math

x = 1.0
exact = math.cos(x)

print(f"{'h':>8} {'forward error':>14} {'central error':>14}")
for h in [0.1, 0.01, 0.001]:
    forward = (math.sin(x + h) - math.sin(x)) / h
    central = (math.sin(x + h) - math.sin(x - h)) / (2 * h)
    print(f"{h:>8} {abs(forward - exact):>14.2e} {abs(central - exact):>14.2e}")
```

Output:

```
       h  forward error  central error
     0.1       4.29e-02       9.00e-04
    0.01       4.22e-03       9.00e-06
   0.001       4.21e-04       9.01e-08
```

(`4.29e-02` is scientific notation for 4.29 × 10⁻², or 0.0429.) Dividing h by 10 divides the forward error by 10 — first order — but divides the central error by 100 — second order. For the same samples, the central difference is far more accurate.

### Too small a step

If smaller steps are better, why not use h = 10⁻¹³? Try it:

```python
import math

x = 1.0
exact = math.cos(x)
for h in [1e-5, 1e-8, 1e-11, 1e-13]:
    central = (math.sin(x + h) - math.sin(x - h)) / (2 * h)
    print(f"h = {h:.0e}   central error = {abs(central - exact):.1e}")
```

Output:

```
h = 1e-05   central error = 1.1e-11
h = 1e-08   central error = 3.0e-09
h = 1e-11   central error = 1.2e-06
h = 1e-13   central error = 1.8e-04
```

Beyond a point, the error *grows*. Floats carry only about 16 significant digits. When h is tiny, sin(x + h) and sin(x − h) are almost equal, and subtracting them cancels most of those digits, leaving mostly rounding error — which is then divided by the tiny 2h. There is a best step size: big enough to avoid rounding trouble, small enough to keep the approximation error low.

### Noise: the real enemy of differentiation

With real sensors, rounding error is small compared with **measurement noise**. Suppose a robot moves at a steady 0.2 m/s and its position is measured every 10 ms, but each reading is off by half a millimetre, alternately high and low (made-up noise, chosen to make the effect easy to see):

```python
dt = 0.01                                          # s
true_position = [0.2 * i * dt for i in range(6)]   # m, steady 0.2 m/s
noise = [0.0005, -0.0005, 0.0005, -0.0005, 0.0005, -0.0005]   # m
measured = [p + n for p, n in zip(true_position, noise)]

speeds = [(measured[i + 1] - measured[i]) / dt for i in range(5)]
print([round(v, 2) for v in speeds])
```

Output:

```
[0.1, 0.3, 0.1, 0.3, 0.1]
```

A position error of only 0.5 mm turned into a speed error of 0.1 m/s — half the true speed! The difference of two noisy readings is divided by a small Δt, which **amplifies** noise. Integration does the opposite: adding many samples tends to average noise out (although any constant bias accumulates, which is why a robot that integrates a slightly offset accelerometer drifts further and further off).

Practical remedies for differentiating noisy data:

- Smooth the data first, for example with a moving average, accepting some delay.
- Take the difference over a longer interval (larger Δt), trading responsiveness for less noise.
- Measure the rate directly if possible: an encoder's tick rate, or a gyroscope instead of differentiating angles.

### Recap

- Integration accumulates (area under the curve); differentiation measures change (slope).
- The trapezoid rule adds ½(v₁ + v₂)Δt slices; its error falls with h².
- Forward differences have error proportional to h; central differences, h².
- Steps that are too small cause rounding errors; there is a best step size.
- Differentiation amplifies noise, integration averages noise but accumulates bias.
- Always test a numerical method on a problem with a known answer.

> **Report the method, not just the number.** A distance or speed computed from samples is an estimate. When you report it, say how it was computed (for example, "trapezoid rule on 0.5 s samples") and give a sense of its error. A number like 0.960 m presented without that context implies a precision that the data may not support.

#### Check your understanding

1. Speeds of 0.2 m/s and 0.4 m/s are measured 0.5 s apart. What distance does the trapezoid rule give for that interval?
   A) 0.30 m
   B) 0.15 m
   C) 0.10 m
   D) 0.60 m

2. Doubling the number of trapezoids on a smooth function reduced the error by about a factor of four. What does this tell you?
   A) The method has a bug
   B) The error is proportional to h
   C) The error is proportional to h², so the method is second order
   D) The error is independent of h

3. Why is the central difference usually more accurate than the forward difference for the same h?
   A) It looks equally far on both sides, so the leading error terms cancel
   B) It uses fewer function evaluations
   C) It divides by a smaller number
   D) It only works on straight lines

4. Making h extremely small (such as 10⁻¹³) made the derivative estimate worse. Why?
   A) The sine function is not defined for small numbers
   B) Python rounds h to zero
   C) Smaller steps always increase approximation error
   D) Subtracting two nearly equal floats loses most significant digits, and the rounding error is then divided by a tiny number

5. Position readings have 0.5 mm of noise and are taken every 10 ms. What happens when you differentiate them to get speed?
   A) The noise disappears
   B) The noise is amplified, because the difference is divided by a small time step
   C) The speed is exact as long as the robot moves steadily
   D) The noise is converted into a constant offset

#### Project: Programming project: from speed to distance and back

Create a made-up speed log for a robot that speeds up, cruises and slows down, with samples every 0.1 s for 10 s. Use a formula, so you also know the exact distance (for example, constant acceleration phases, where the distance can be worked out by hand from areas of triangles and rectangles).

1. Integrate the speed log with the trapezoid rule and compare with your exact distance. Repeat using every second, fifth and tenth sample only. How does the error change?
2. Integrate to get position at every sample, then differentiate the positions with forward and central differences. Compare with the original speeds.
3. Add made-up noise to the positions using `random.uniform(-0.001, 0.001)` (call `random.seed(1)` first so your results repeat). Differentiate again, then try smoothing the positions with a 5-sample moving average first.
4. Summarise what you learned about integrating and differentiating real data in a short paragraph.

No hardware is required.

**Deliverables**

- A Python 3 program with trapezoid integration and two finite-difference methods
- A table of distance errors for different sampling intervals
- Printed or plotted speeds recovered from noisy and smoothed positions, with a short discussion

**Go further:**

- Trapezoidal rule — Wikipedia: https://en.wikipedia.org/wiki/Trapezoidal_rule — Derivation, error analysis and the uniform-grid formula used in this lesson.
- Finite difference — Wikipedia: https://en.wikipedia.org/wiki/Finite_difference — Forward, backward and central differences and their relationship to derivatives.


## 2.5 Path planning on grids

*Find routes for a mobile robot on a grid map: breadth-first search for the fewest moves, Dijkstra's algorithm for the cheapest route, and A*, which uses a heuristic to search less.* (about 40 min)

### Why path planning?

A delivery robot in a warehouse, a vacuum robot in a living room and a rover on rough ground all face the same question: *how do I get from here to there without hitting anything?* Before a robot can drive, something must turn a map and a goal into a sequence of moves. That is **path planning**.

A common, simple map is an **occupancy grid**: the world is divided into equal square cells, each marked free or blocked. You met grids as lists of lists in the lesson on lists and dictionaries. Here we use a list of strings, which is easier to read, and allow the robot to move one cell up, down, left or right at a time.

### The map and some helpers

Save this as `gridmap.py`; the programs that follow import it. `#` is a wall, `.` is free floor, `~` is sand that the robot can cross but only slowly, `S` is the start and `G` the goal. Cells are identified by **tuples** `(row, col)` — a tuple is like a list that cannot be changed, and it can be used as a dictionary key.

```python
# gridmap.py
GRID = [
    "............",
    ".##########.",
    "S....~~~...G",
    ".######.###.",
    "......#.....",
    "....#...#...",
]

def find(grid, symbol):
    """Return the (row, col) of the first cell containing symbol."""
    for r, row in enumerate(grid):
        if symbol in row:
            return (r, row.index(symbol))

def neighbours(grid, cell):
    """Cells up, down, left and right of cell that are inside the map and not walls."""
    r, c = cell
    result = []
    for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        nr, nc = r + dr, c + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#":
            result.append((nr, nc))
    return result

def trace_path(came_from, goal):
    """Follow came_from links back from goal to the start."""
    path = []
    cell = goal
    while cell is not None:
        path.append(cell)
        cell = came_from[cell]
    path.reverse()
    return path

def show(grid, path):
    """Print the map with the path drawn as * characters."""
    for r, row in enumerate(grid):
        print("".join("*" if (r, c) in path and ch in ".~" else ch for c, ch in enumerate(row)))
```

### Breadth-first search

**Breadth-first search (BFS)** explores outwards from the start like a ripple on a pond: first every cell one move away, then every cell two moves away, and so on. The first time the ripple reaches the goal, it has found a route with the **fewest moves**.

BFS keeps a **queue** of cells waiting to be explored. New cells join at the back; the next cell to explore comes from the front, so cells are explored in order of distance. A dictionary `came_from` records, for each cell reached, which cell we came from. That serves two purposes: it tells us which cells we have already seen, so we never explore one twice, and it lets us trace the path backwards from the goal at the end.

```python
from collections import deque
from gridmap import GRID, find, neighbours, trace_path, show

def bfs(grid, start, goal):
    came_from = {start: None}
    queue = deque([start])
    expanded = 0
    while queue:
        cell = queue.popleft()          # oldest cell first
        expanded += 1
        if cell == goal:
            return trace_path(came_from, goal), expanded
        for nxt in neighbours(grid, cell):
            if nxt not in came_from:    # not seen before
                came_from[nxt] = cell
                queue.append(nxt)
    return None, expanded               # the goal cannot be reached

start, goal = find(GRID, "S"), find(GRID, "G")
path, expanded = bfs(GRID, start, goal)
print(f"{len(path) - 1} moves, {expanded} cells expanded")
show(GRID, path)
```

Output:

```
11 moves, 41 cells expanded
............
.##########.
S**********G
.######.###.
......#.....
....#...#...
```

`deque`, from the standard `collections` module, is a list designed for fast adding and removing at both ends. BFS found the straight route along the middle row: 11 moves. "Expanded" counts the cells whose neighbours we examined, a fair measure of the work done.

But look at the route: it drives straight through three cells of sand. BFS treats every move as equal, so it cannot know that sand is slow.

### Dijkstra's algorithm: the cheapest path

Suppose moving into a free cell costs 1 and moving into sand costs 5. The middle route costs 8 × 1 + 3 × 5 = 23. Is there something cheaper?

**Dijkstra's algorithm** generalises BFS to moves with different costs. Instead of exploring cells in order of *number of moves*, it always explores the cell with the lowest **total cost so far**. To pick that cell quickly it uses a **priority queue**: Python's `heapq` module keeps a list arranged so the smallest item can always be removed in O(log n) time.

### A*: searching with a sense of direction

Dijkstra explores in every direction equally, including away from the goal. The **A star** algorithm, written A* for short, adds a **heuristic**: an estimate of the remaining cost to the goal. It explores cells in order of

```
priority = cost so far + estimated cost still to go
```

On a grid with up/down/left/right moves, a natural estimate is the **Manhattan distance**: the number of rows plus the number of columns between a cell and the goal. Because every move costs at least 1, this estimate can never be more than the true remaining cost. A heuristic with that property is called **admissible**, and it guarantees that A* still finds the cheapest path.

The two algorithms are so similar that one function can do both — Dijkstra is simply A* with an estimate of zero:

```python
import heapq
from gridmap import GRID, find, neighbours, trace_path, show

def step_cost(grid, cell):
    return 5 if grid[cell[0]][cell[1]] == "~" else 1   # sand is slow

def manhattan(a, b):
    return abs(a[0] - b[0]) + abs(a[1] - b[1])

def plan(grid, start, goal, use_heuristic):
    came_from = {start: None}
    cost_so_far = {start: 0}
    frontier = [(0, start)]                  # (priority, cell)
    expanded = 0
    while frontier:
        _, cell = heapq.heappop(frontier)    # lowest priority first
        expanded += 1
        if cell == goal:
            return trace_path(came_from, goal), cost_so_far[goal], expanded
        for nxt in neighbours(grid, cell):
            new_cost = cost_so_far[cell] + step_cost(grid, nxt)
            if nxt not in cost_so_far or new_cost < cost_so_far[nxt]:
                cost_so_far[nxt] = new_cost
                came_from[nxt] = cell
                priority = new_cost
                if use_heuristic:
                    priority += manhattan(nxt, goal)
                heapq.heappush(frontier, (priority, nxt))
    return None, None, expanded

start, goal = find(GRID, "S"), find(GRID, "G")
for name, use_heuristic in [("Dijkstra", False), ("A*", True)]:
    path, cost, expanded = plan(GRID, start, goal, use_heuristic)
    print(f"{name}: {len(path) - 1} moves, cost {cost}, {expanded} cells expanded")
show(GRID, path)
```

Output:

```
Dijkstra: 15 moves, cost 15, 42 cells expanded
A*: 15 moves, cost 15, 22 cells expanded
************
*##########*
S....~~~...G
.######.###.
......#.....
....#...#...
```

Both algorithms chose the route around the top: 15 moves instead of 11, but a cost of 15 instead of 23. The *shortest* path and the *cheapest* path are different things, and the planner can only optimise what its costs describe.

Both found the same cost, but A* expanded 22 cells while Dijkstra expanded 42. The heuristic steered A* towards the goal, so it wasted less effort on cells in the bottom of the map. On large maps — a warehouse might be thousands of cells across — this saving is what makes planning fast enough to run while the robot moves.

### The three algorithms side by side

- **BFS**: explores in order of number of moves. Finds the fewest-move path. Uses a plain queue.
- **Dijkstra**: explores in order of cost so far. Finds the cheapest path when costs differ. Uses a priority queue.
- **A star** (A*): explores in order of cost so far plus an estimate of the cost to go. Finds the cheapest path, usually exploring far fewer cells, provided the estimate never overestimates.

If the heuristic *overestimates* — say you multiplied the Manhattan distance by 10 — A* becomes greedier and faster but may return a path that is not the cheapest. Sometimes that trade-off is acceptable; it should always be a deliberate choice.

### From grid paths to real robots

A planned grid path is a starting point, not the end of the story:

- **Robot size**: a robot is not a point. Planners usually *inflate* obstacles by the robot's radius, so a path through free cells keeps the whole body clear.
- **Resolution**: big cells make planning fast but can close narrow gaps; small cells are accurate but give the planner more work.
- **Movement**: real robots can move diagonally and turn smoothly. Grid paths are often smoothed afterwards.
- **Change**: people and doors move. Robots replan as their sensors update the map, which is another reason planning speed matters.
- **Unreachable goals**: if walls enclose the goal, the search runs out of cells and returns `None`. Code that uses the path must handle that case.

### Recap

- An occupancy grid divides the world into free and blocked cells; neighbours are the cells one move away.
- BFS explores outward with a queue and finds the path with the fewest moves.
- Dijkstra's algorithm uses a priority queue to find the cheapest path when moves have different costs.
- A* adds an admissible heuristic, such as the Manhattan distance, to find the same cheapest path while exploring less.
- A `came_from` dictionary both prevents revisiting cells and lets you rebuild the path.
- Real planners also inflate obstacles, choose a resolution and replan as the world changes.

> **A plan is not a guarantee.** A path is only as good as the map it was planned on. Maps can be out of date, and sensors miss things. Real mobile robots combine planning with independent safety measures — obstacle detection while driving, speed limits near people and a way to stop immediately — rather than trusting a planned path alone.

#### Check your understanding

1. What does breadth-first search guarantee on a grid where every move costs the same?
   A) It finds a path with the fewest moves, if one exists
   B) It always expands fewer cells than A*
   C) It finds the path that avoids sand
   D) It never needs a visited set

2. Why did Dijkstra's algorithm choose a 15-move route when BFS found an 11-move one?
   A) Dijkstra's algorithm has a bug
   B) The 11-move route crossed sand, so it cost 23, while the 15-move route cost only 15
   C) Dijkstra's algorithm always prefers longer routes
   D) BFS cannot see the top row

3. In A*, a cell's priority is…
   A) its estimated distance to the goal only
   B) the number of times it has been visited
   C) its row number plus its column number
   D) the cost to reach it so far plus an estimate of the cost from it to the goal

4. A heuristic is 'admissible' if…
   A) it never overestimates the true remaining cost
   B) it is always exactly correct
   C) it is larger than the true cost
   D) it uses diagonal moves

5. Why do planners often inflate obstacles on the map before planning?
   A) To make the map look tidier
   B) To reduce the number of cells
   C) So a path through free cells keeps the robot's whole body, not just its centre, clear of obstacles
   D) Because A* only works with large obstacles

#### Project: Project: a planner of your own

**On paper.** Draw a 6 × 8 grid with a start, a goal and a few walls. Run BFS by hand: write 0 in the start cell, 1 in every free neighbour, 2 in their unvisited free neighbours, and so on until you reach the goal. Then trace the path back by stepping to any neighbour with a number one smaller.

**In Python.** Copy `gridmap.py` and the two planners from this lesson, then:

1. Design your own map of at least 10 × 15 cells, including a region of costly cells. Check that BFS, Dijkstra and A* behave as you expect, and record moves, cost and cells expanded for each.
2. Make the goal unreachable by surrounding it with walls. Make sure your program prints a clear message instead of crashing.
3. Multiply the heuristic by 3. Does A* still find the cheapest path? How many cells does it expand?
4. Add diagonal moves with a cost of 1.4, and explain in a sentence why the Manhattan distance is no longer admissible for this case.

No hardware is required.

**Deliverables**

- A photo or scan of your hand-worked BFS grid
- A Python 3 program and a table comparing the three algorithms on your map
- Short answers to steps 3 and 4

**Go further:**

- Breadth-first search — Wikipedia: https://en.wikipedia.org/wiki/Breadth-first_search — The algorithm, its use of a queue and its properties.
- Dijkstra's algorithm — Wikipedia: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm — The shortest-path algorithm for weighted graphs, with an animated example.
- A* search algorithm — Wikipedia: https://en.wikipedia.org/wiki/A*_search_algorithm — How heuristics guide the search, and what admissibility guarantees.
- Python documentation — heapq: heap queue algorithm: https://docs.python.org/3/library/heapq.html — The priority queue used by the Dijkstra and A* code in this lesson.


## 2.6 Optimisation basics

*Choose the best design or setting systematically: define an objective function, search it by brute force, descend its slope with gradient descent, and beware of local minima.* (about 35 min)

### Why optimise?

Engineering is full of choices with a "best" answer somewhere among many possibilities. Which calibration factor makes a sensor agree most closely with a ruler? Which controller gain gives the fastest response without overshoot? Which arm length lets a gripper reach every shelf while staying light? Guessing and checking by hand works for one or two options. **Optimisation** is the systematic version: describe what "best" means as a number, then let an algorithm search for the setting that makes that number as small (or as large) as possible.

### The ingredients

Every optimisation problem has three parts:

1. **Decision variables**: the things you are allowed to choose, such as a gain k.
2. **An objective function**: a single number that measures how good a choice is. By convention we usually *minimise* it, so it is often called a **cost** or **error**.
3. **Constraints**: limits on the choices, such as "the arm must weigh less than 400 g" or "the gain must be positive".

The hardest and most important step is usually the second: writing down, as a number, what you actually want.

### A worked example: calibrating a sensor

A distance sensor reports raw values that should be proportional to distance. We place a target at five carefully measured distances and record the raw values (made-up data). We want the scale factor k such that distance ≈ k × reading.

A natural objective is the **sum of squared errors**: for each measurement, take the difference between the predicted and true distance, square it so that positive and negative errors both count, and add them up. A perfect k would score zero.

```python
reference_mm = [100, 200, 300, 400, 500]   # true distances, measured with a ruler
reading = [52, 98, 151, 203, 248]         # raw sensor values (made-up)

def error(k):
    """Sum of squared differences between k × reading and the true distance, in mm²."""
    return sum((k * r - d) ** 2 for r, d in zip(reading, reference_mm))

for k in [1.5, 2.0, 2.5]:
    print(f"k = {k}: error = {error(k):9.1f} mm²")
```

Output:

```
k = 1.5: error =   34199.5 mm²
k = 2.0: error =      88.0 mm²
k = 2.5: error =   34887.5 mm²
```

(`sum(... for ...)` adds up the values produced by a loop, like a list comprehension without building the list.) The error is huge on either side and small near k = 2. The objective function turns a vague question — "which k fits best?" — into a precise one: "which k makes `error(k)` smallest?"

### Brute force: grid search

The most reliable method is to try many values and keep the best. Here we try k from 1.50 to 2.50 in steps of 0.01:

```python
reference_mm = [100, 200, 300, 400, 500]
reading = [52, 98, 151, 203, 248]

def error(k):
    return sum((k * r - d) ** 2 for r, d in zip(reading, reference_mm))

best_k = 1.5
for i in range(150, 251):
    k = i / 100
    if error(k) < error(best_k):
        best_k = k

print(f"Grid search: k = {best_k:.2f}, error = {error(best_k):.1f} mm²")
```

Output:

```
Grid search: k = 2.00, error = 88.0 mm²
```

Grid search is simple and hard to fool, but it has two weaknesses. Its answer is only as fine as the grid. And its cost explodes with the number of variables: 101 values for one variable is cheap, but 101 values for each of 5 variables is 101⁵, about ten billion evaluations. That is exponential growth again, from the lesson on complexity.

### Gradient descent: walking downhill

Imagine standing on a hillside in thick fog, wanting to reach the valley floor. You cannot see the valley, but you can feel which way the ground slopes under your feet. So you take a step downhill, feel again, and repeat. That is **gradient descent**.

The slope of the objective at k is its derivative. For our error function it is

```
slope(k) = Σ 2 × r × (k × r − d)
```

(you can check it numerically with a central difference, from the lesson on numerical differentiation). If the slope is positive, the error increases as k increases, so we should decrease k, and vice versa. Each step moves k against the slope, scaled by a **step size** (often called the **learning rate**):

```
k_new = k − rate × slope(k)
```

```python
reference_mm = [100, 200, 300, 400, 500]
reading = [52, 98, 151, 203, 248]

def slope(k):
    return sum(2 * r * (k * r - d) for r, d in zip(reading, reference_mm))

def gradient_descent(k, rate, steps):
    for _ in range(steps):
        k = k - rate * slope(k)
    return k

for rate in [1e-7, 1e-6, 3e-6, 1e-5]:
    k = gradient_descent(1.0, rate, 20)
    print(f"rate {rate:.0e}: k after 20 steps = {k:.4f}")

exact = sum(r * d for r, d in zip(reading, reference_mm)) / sum(r * r for r in reading)
print(f"Exact least-squares answer: k = {exact:.4f}")
```

Output:

```
rate 1e-07: k after 20 steps = 1.4272
rate 1e-06: k after 20 steps = 1.9959
rate 3e-06: k after 20 steps = 1.9975
rate 1e-05: k after 20 steps = -77905.8195
Exact least-squares answer: k = 1.9975
```

The step size matters enormously:

- **Too small** (10⁻⁷): every step is tiny, and after 20 steps k has crept only from 1.0 to about 1.43.
- **About right** (3 × 10⁻⁶): k reaches the exact answer, 1.9975, to four decimal places.
- **Too large** (10⁻⁵): each step overshoots the valley so far that it lands higher up the other side, the next step overshoots even more, and k flies off to nonsense. The method has **diverged**.

For this simple problem there is an exact formula (this is the method of least squares, which the Data Analysis module covers), and that is exactly why it is a good test: we can check that gradient descent finds the right answer before trusting it on problems with no formula. Notice too that grid search gave 2.00, the nearest grid point to 1.9975.

### Local minima

Our error function has a single valley. Many real objectives have several. Consider this function, chosen as an illustration:

```
f(x) = x⁴ − 3x² + x
```

It has two valleys: a deep one near x = −1.30 and a shallower one near x = 1.13. Gradient descent only ever walks downhill, so which valley it ends in depends on where it starts:

```python
def f(x):
    return x**4 - 3 * x**2 + x

def dfdx(x):
    return 4 * x**3 - 6 * x + 1

for start in [2.0, -2.0, 0.0]:
    x = start
    for _ in range(200):
        x = x - 0.01 * dfdx(x)
    print(f"start {start:+.1f} -> x = {x:+.4f}, f(x) = {f(x):+.4f}")
```

Output:

```
start +2.0 -> x = +1.1309, f(x) = -1.0702
start -2.0 -> x = -1.3008, f(x) = -3.5139
start +0.0 -> x = -1.3008, f(x) = -3.5139
```

Starting at +2, the method settles at x ≈ 1.13, a **local minimum**: lower than everything nearby, but not the lowest point overall. The **global minimum**, f ≈ −3.51 at x ≈ −1.30, is found only from the other starts. Gradient descent has no way to know that a deeper valley exists over the hill.

Common defences:

- **Multiple starts**: run from several starting points and keep the best result.
- **A coarse grid search first**, then gradient descent from the best grid point.
- **Understand the problem**: plotting or tabulating the objective often reveals how many valleys there are.

### What you optimise is what you get

An optimiser will find the best answer to the question you *wrote down*, not the one you meant. Minimise only an arm's mass and it will become too weak to lift anything; minimise only a robot's travel time and it may drive dangerously fast. Real objectives combine goals and respect constraints — for example "minimise travel time, subject to speed below 0.5 m/s near people". Always check an optimised result against common sense and against the requirements it must meet.

### Recap

- An optimisation problem has decision variables, an objective function and constraints.
- The sum of squared errors is a common objective for fitting a model to measurements.
- Grid search is simple and robust but becomes very expensive with many variables.
- Gradient descent steps against the slope: k_new = k − rate × slope(k). Too small a rate is slow; too large diverges.
- Gradient descent can stop in a local minimum; multiple starts or a coarse search first help.
- Test an optimiser on a problem with a known answer, and check that its result makes engineering sense.

> **Optimise on one set, check on another.** A calibration or tuning that is optimised on a set of measurements will always look good on those same measurements. To know whether it really works, test it on fresh measurements that were not used in the optimisation, and report that result.

#### Check your understanding

1. In the sensor calibration example, what is the objective function?
   A) The list of raw readings
   B) The sum of squared differences between k × reading and the true distances
   C) The scale factor k
   D) The number of measurements

2. Gradient descent finds slope(k) = +40 at the current k. Which way should k move?
   A) Increase k, because the slope is positive
   B) Leave k unchanged
   C) Decrease k, because the error rises as k increases
   D) Set k to 40

3. With a step size of 10⁻⁵, k shot off to about −77,906. What happened?
   A) The method found a better minimum
   B) The data must contain an error
   C) The step size was too small
   D) The step size was so large that each step overshot the minimum by more than the last, so the method diverged

4. Gradient descent started at x = 2 settles at x ≈ 1.13, but f is lower at x ≈ −1.30. Why?
   A) x ≈ 1.13 is a local minimum, and gradient descent only moves downhill from where it starts
   B) Gradient descent always finds the global minimum, so the code is wrong
   C) The function has no minimum
   D) The step size was too large

5. Grid search over 100 values per variable is cheap for one variable. Roughly how many evaluations does it need for 4 variables?
   A) 400
   B) 10,000
   C) 100,000,000
   D) 1,000,000,000,000

#### Project: Programming project: tune it yourself

Use optimisation to choose two parameters.

1. Extend the calibration model to distance ≈ k × reading + c, where c is an offset. Make up six measurements (label them as made-up) and write an error function of both k and c.
2. Find the best k and c by grid search over a sensible range. Count the number of error evaluations.
3. Implement gradient descent for both variables at once: compute the slope with respect to k and with respect to c (you can estimate each with a central difference), and update both at every step. Try at least three step sizes and record what happens.
4. For f(x) = x⁴ − 3x² + x, run gradient descent from 21 starting points between −3 and 3. Count how many end in each valley.
5. Write a paragraph on which method you would trust more, and why, for a problem with 10 variables.

No hardware is required.

**Deliverables**

- A Python 3 program with grid search and gradient descent for the two-parameter calibration
- A table of results for different step sizes
- The count of starts ending in each valley, and your paragraph

**Go further:**

- Gradient descent — Wikipedia: https://en.wikipedia.org/wiki/Gradient_descent — The method, the role of the step size and its behaviour on different kinds of function.
- Mathematical optimization — Wikipedia: https://en.wikipedia.org/wiki/Mathematical_optimization — An overview of objective functions, constraints, local and global optima and the main families of methods.


---

# Module 3: Data analysis

Turning measurements into understanding: summary statistics, plotting, uncertainty and the difference between correlation and cause.

**Objectives**

- Compute and interpret mean, median, range and standard deviation.
- Choose an appropriate plot for a dataset and label it fully.
- Fit a straight line to data and judge whether the fit is reasonable.
- Explain why correlation alone does not establish causation.


## 3.1 Describing data

*Summarise a set of measurements with the mean, median, range and standard deviation, and learn what each one hides.* (about 30 min)

### Why summarise?

Suppose you are testing a robot gripper and you time how long it takes to close, nine times in a row. A teammate asks: "How fast is it?" You could read out all nine numbers, but after nine hundred trials that stops working. Engineers need a few numbers that capture **where the data sits** and **how spread out it is**. These are called **summary statistics**, and choosing the right ones is the first step of almost every analysis.

Here is the data we will use throughout this lesson. It is **made up for illustration**:

```
Gripper closing time (ms), 9 trials:
212, 208, 215, 210, 209, 214, 211, 213, 260
```

Eight of the trials are close together. One, 260 ms, is much slower. Keep an eye on it.

### The mean

The **mean** (the everyday "average") is the sum of the values divided by how many there are:

```
mean = (x₁ + x₂ + … + xₙ) / n
     = 1952 / 9
     ≈ 216.9 ms
```

The mean uses every value, which is its strength and its weakness. Notice that 216.9 ms is *larger than eight of the nine trials*. The single slow trial has dragged it upwards.

### The median

The **median** is the middle value once the data is sorted:

```
208, 209, 210, 211, 212, 213, 214, 215, 260
                    ^^^
```

With nine values the middle one is the 5th, so the median is 212 ms. With an even number of values, the median is the mean of the two middle ones. The median barely cares how extreme the largest value is: if the slow trial had been 2600 ms, the median would still be 212 ms. We say the median is **robust** to outliers, while the mean is not.

Neither is "better". If you care about the total time for a thousand grasps, the mean is what matters, because slow trials really do add up. If you want a typical trial, the median often describes it more honestly.

### The range

The **range** is the largest value minus the smallest: 260 − 208 = 52 ms. It is easy to compute and easy to understand, but it depends only on the two most extreme values, so one odd trial changes it completely. It also tends to grow as you collect more data, because you get more chances to see an extreme.

### The standard deviation

We want a measure of spread that uses every value. The idea: find how far each value is from the mean (its **deviation**), square those distances so negatives do not cancel positives, average them, and take the square root to get back to the original units.

Let us do it by hand for a tiny set, 4, 6, 7, 8, 10, whose mean is 7:

```
value   deviation   deviation²
  4        −3           9
  6        −1           1
  7         0           0
  8         1           1
 10         3           9
                 sum = 20
```

Now there is a choice to make, and it matters.

- If these five values are the **entire population** you care about, divide by n = 5. The variance is 20 / 5 = 4 and the **population standard deviation** is √4 = 2.
- If they are a **sample** from a larger process (for example, five trials of a gripper that will close thousands of times), divide by n − 1 = 4. The variance is 20 / 4 = 5 and the **sample standard deviation** is √5 ≈ 2.236.

Why n − 1? The deviations are measured from the sample's own mean, which is by construction as close as possible to these particular values. That makes the squared deviations slightly too small on average compared with deviations from the true, unknown mean. Dividing by n − 1 instead of n corrects for this. In engineering you almost always have a sample, so the n − 1 version is the usual default. It is written **s**.

Python's `statistics` module has both:

```python
import statistics

values = [4, 6, 7, 8, 10]
print(statistics.pstdev(values))   # population: divide by n
print(statistics.stdev(values))    # sample: divide by n - 1
```

Output:

```
2.0
2.23606797749979
```

A rough guide: for data that bunches around the middle, most values lie within about one standard deviation of the mean, and very few lie more than three away.

### Summarising the gripper data in Python

```python
import statistics

# Made-up data for illustration: time (ms) for a gripper to close, 9 trials
times = [212, 208, 215, 210, 209, 214, 211, 213, 260]

print("n      =", len(times))
print("mean   =", round(statistics.mean(times), 1))
print("median =", statistics.median(times))
print("range  =", max(times) - min(times))
print("stdev  =", round(statistics.stdev(times), 1))
```

Output:

```
n      = 9
mean   = 216.9
median = 212
range  = 52
stdev  = 16.3
```

Now compare the same statistics with and without the slow trial:

```python
import statistics

times = [212, 208, 215, 210, 209, 214, 211, 213, 260]
clean = times[:-1]   # the same trials without the 260 ms one

for label, data in [("all 9", times), ("first 8", clean)]:
    print(f"{label:8s} mean {statistics.mean(data):6.1f}  "
          f"median {statistics.median(data):6.1f}  "
          f"stdev {statistics.stdev(data):5.1f}")
```

Output:

```
all 9    mean  216.9  median  212.0  stdev  16.3
first 8  mean  211.5  median  211.5  stdev   2.4
```

The median moved by half a millisecond. The mean moved by more than 5 ms, and the standard deviation shrank from 16.3 ms to 2.4 ms. One trial out of nine was responsible for almost all of the apparent spread. That is a clue worth following: was the gripper snagging on something? Was a cable caught? The summary statistics have not answered the question, but they have told you where to look.

### What to report

A good description of a dataset usually includes:

- **n**, the number of values. A mean of 5 values and a mean of 500 deserve different levels of trust.
- A **centre**: the mean, the median, or both when they disagree.
- A **spread**: the standard deviation (say whether it is sample or population) and often the minimum and maximum.
- **Units**, every time.

Better still, look at the data itself before trusting any summary. Very different datasets can share the same mean and standard deviation. The next lessons show how to picture data and how to say how certain a mean is.

### Recap

- The **mean** uses every value and is pulled by outliers; the **median** is the middle value and is robust to them.
- The **range** is simple but depends only on the two extremes.
- The **standard deviation** measures typical distance from the mean. Use the **sample** version (divide by n − 1, `statistics.stdev`) when your data is a sample of a larger process, which is nearly always.
- Report n, a centre, a spread and units, and look at the raw data too.

> **Outliers are data until proven otherwise.** It is tempting to delete the 260 ms trial because it spoils a neat result. Don't, unless you have a recorded reason (for example, "trial 9: cable snagged, noted at the time"). If you exclude values, say how many, which ones and why, and ideally show the results both with and without them, as we did above.

#### Project: Measure your reaction time with a ruler

You need a 30 cm ruler, a partner, a pencil and paper, and Python.

1. Your partner holds the ruler vertically with the 0 mark between your open finger and thumb. Without warning, they let go and you catch it. Record the mark where you caught it, in centimetres.
2. Do **20 trials** and write every result down, including any you fumble.
3. Convert each distance to a reaction time using the falling-object formula t = √(2d / g), with d in metres and g = 9.81 m/s². For example, 15 cm gives t = √(2 × 0.15 / 9.81) ≈ 0.175 s.
4. In Python, compute n, the mean, median, range and sample standard deviation of your times.
5. Repeat the summary for your first 10 and last 10 trials. Did you get faster with practice?

**Deliverables**

- A table of all 20 distances and reaction times
- A Python script that prints n, mean, median, range and sample standard deviation
- Two or three sentences comparing the mean and median, and the first and last 10 trials

#### Check your understanding

1. The values 3, 4, 5, 6, 100 have a median of:
   A) 23.6
   B) 5
   C) 97
   D) 4.5

2. When should you divide by n − 1 rather than n when computing a standard deviation?
   A) When your values are a sample from a larger process you want to describe
   B) Only when n is larger than 100
   C) When the data contains negative numbers
   D) Never; n − 1 is an old approximation

3. Removing one slow trial changed the gripper mean from 216.9 ms to 211.5 ms but the median only from 212 ms to 211.5 ms. What does this show?
   A) The median was calculated wrongly
   B) The mean is always smaller than the median
   C) The mean is sensitive to an extreme value; the median is not
   D) The slow trial should be deleted

4. For the values 2, 4, 6 (mean 4), what is the sample standard deviation?
   A) √(8/3) ≈ 1.63
   B) 8
   C) 4
   D) √(8/2) = 2

5. Why is the range a weak measure of spread on its own?
   A) It cannot be computed in Python
   B) It depends only on the two most extreme values, so a single odd value changes it
   C) It is always zero
   D) It has no units

**Go further:**

- Python documentation — statistics module: https://docs.python.org/3/library/statistics.html — Official reference for mean, median, stdev, pstdev and the other functions used in this module.
- Standard deviation — Wikipedia: https://en.wikipedia.org/wiki/Standard_deviation — More examples, plus the difference between population and sample standard deviation.


## 3.2 Measurement uncertainty and error bars

*Every measurement comes with uncertainty. Learn to estimate it from repeated measurements, report a mean with its standard error, and draw honest error bars.* (about 30 min)

### A number without uncertainty is half a result

A robot needs to place a part in a slot that is 50.20 mm wide. You measure the part and get 50.11 mm. Will it fit? It depends on something the single number does not tell you: **how sure are you?** If your measurement could easily be off by 0.01 mm, the part fits. If it could be off by 0.2 mm, you do not know yet. Engineers therefore report measurements as a value **and** an uncertainty, such as 50.11 ± 0.01 mm, and they say what the ± means.

### Two kinds of error

In measurement, "error" does not mean a mistake. It means the difference between what you measured and the true value.

- **Random error** changes from one reading to the next: a slightly different grip on the calipers, electrical noise in a sensor, the exact moment you press a stopwatch. Readings scatter both above and below the true value.
- **Systematic error** pushes every reading the same way: calipers that read 0.05 mm when closed, a scale that was never zeroed, a thermometer in direct sunlight. Readings can agree beautifully with each other and all be wrong.

Repeating a measurement and averaging helps with random error. **It does nothing for systematic error.** You only find systematic error by checking your instrument against a known reference, such as a gauge block or a calibration weight.

### Repeated measurements

Here are six repeated measurements of the same bracket (**made-up data for illustration**):

```
50.12, 50.08, 50.15, 50.10, 50.06, 50.13 mm
```

The sample standard deviation s, from the previous lesson, describes how much a *single* reading scatters. But we are going to report the *mean* of six readings, and a mean is more reliable than any one reading, because random errors partly cancel when you average.

### The standard error of the mean

How much would the mean itself wobble if you repeated the whole set of six measurements again and again? The answer is the **standard error of the mean** (SE):

```
SE = s / √n
```

The √n is the key idea. Averaging 4 readings halves the uncertainty of the mean compared with one reading; averaging 100 readings cuts it by a factor of 10. To halve your standard error you need **four times** as many measurements. Precision gets expensive.

```python
import math
import statistics

# Made-up data for illustration: one bracket's length (mm), measured 6 times
lengths = [50.12, 50.08, 50.15, 50.10, 50.06, 50.13]

n = len(lengths)
mean = statistics.mean(lengths)
s = statistics.stdev(lengths)
se = s / math.sqrt(n)

print(f"n = {n}")
print(f"mean = {mean:.3f} mm")
print(f"s    = {s:.3f} mm")
print(f"SE   = {se:.3f} mm")
print(f"Result: {mean:.2f} ± {se:.2f} mm (mean ± SE, n = {n})")
```

Output:

```
n = 6
mean = 50.107 mm
s    = 0.033 mm
SE   = 0.014 mm
Result: 50.11 ± 0.01 mm (mean ± SE, n = 6)
```

Notice the rounding. The uncertainty is about 0.01 mm, so quoting the mean as 50.1067 mm would claim precision you do not have. A good rule: round the uncertainty to one or two significant figures, then round the value to the same decimal place.

### Watching the standard error shrink

In a simulation we can choose the true value, which is impossible in a real experiment. Here every simulated reading is the true length, 50.00 mm, plus random noise with a standard deviation of 0.40 mm:

```python
import math
import random
import statistics

random.seed(7)
TRUE_LENGTH = 50.00   # mm, known only because this is a simulation
NOISE = 0.40          # mm, standard deviation of each reading

for n in [4, 16, 64, 256]:
    readings = [random.gauss(TRUE_LENGTH, NOISE) for _ in range(n)]
    s = statistics.stdev(readings)
    se = s / math.sqrt(n)
    print(f"n = {n:3d}   mean = {statistics.mean(readings):.3f}   "
          f"s = {s:.3f}   SE = {se:.3f}")
```

Output:

```
n =   4   mean = 49.971   s = 0.156   SE = 0.078
n =  16   mean = 49.941   s = 0.390   SE = 0.097
n =  64   mean = 49.979   s = 0.390   SE = 0.049
n = 256   mean = 50.026   s = 0.424   SE = 0.026
```

Three things to notice:

1. **s does not shrink** as n grows; it settles near the true noise, 0.40 mm. More data does not make individual readings less noisy.
2. **SE does shrink**, roughly halving each time n quadruples. More data makes the *mean* more certain.
3. With only 4 readings, s came out at 0.156 mm, far below the true 0.40 mm. With small samples, even the estimate of spread is unreliable, which is why the SE for n = 4 looks deceptively small.

The `random.seed(7)` line makes the "random" numbers the same every time you run the program, so you can check your output against this page.

### Error bars and what they mean

On a plot, uncertainty is usually drawn as an **error bar**: a line through each point showing a range. The trouble is that error bars can mean several different things:

- **±1 standard deviation**: how much individual readings scatter.
- **±1 standard error**: how uncertain the mean is.
- **A 95% confidence interval**: a range constructed so that, if you repeated the experiment many times, about 95% of such ranges would contain the true mean.

These can differ by a large factor. For our bracket, ±1 s is ±0.033 mm, but ±1 SE is ±0.014 mm. **Always state which one you drew**, and always state n.

For large samples, a 95% confidence interval is approximately the mean ± 2 SE. For small samples you need a larger multiplier taken from a table of the *t-distribution*; with n = 6 it is about 2.57. So a careful 95% interval for the bracket is 50.107 ± 2.57 × 0.0136, or roughly 50.07 to 50.14 mm. Now we can answer the opening question: even the top of that range leaves a gap below 50.20 mm, so the part fits, **provided** there is no systematic error in the calipers.

### Recap

- Report a measurement as a value, an uncertainty and an explanation of what the uncertainty means.
- **Random error** scatters readings and is reduced by averaging; **systematic error** biases every reading and is found only by calibration.
- The **standard error** of a mean is s / √n. Quadrupling the number of measurements halves it.
- Error bars must be labelled: standard deviation, standard error or confidence interval, with n.
- Round the value to match its uncertainty.

> **Averaging cannot fix a bad instrument.** If your calipers read 0.05 mm too high, a thousand careful readings will give you a beautifully precise mean that is 0.05 mm wrong. Before a series of measurements, check the zero and, if you can, measure something whose size you already know.

#### Check your understanding

1. Ten readings have a sample standard deviation of 0.6 V. What is the standard error of their mean?
   A) 0.06 V
   B) 0.6 V
   C) About 0.19 V
   D) About 1.9 V

2. You want to halve the standard error of a mean you currently compute from 25 readings. Roughly how many readings do you need?
   A) 50
   B) 100
   C) 30
   D) 625

3. Every reading from a thermometer is 1.5 °C too high because it sits in sunlight. What will averaging many readings do?
   A) Remove the 1.5 °C error
   B) Make the error larger
   C) Turn it into a random error
   D) Give a precise mean that is still about 1.5 °C too high

4. A graph shows two means with error bars but does not say what the bars are. Why is this a problem?
   A) Error bars could show the standard deviation, standard error or a confidence interval, which differ greatly in size and meaning
   B) Error bars are not allowed on graphs
   C) It makes no difference what they show
   D) Error bars always show the range

5. In the simulation, why did the sample standard deviation stay near 0.4 mm as n increased, while the standard error shrank?
   A) Because the random seed was fixed
   B) Because s describes the scatter of single readings, which does not change, while SE describes the uncertainty of the mean, which improves with more data
   C) Because Python rounds large samples
   D) Because the true value changed

**Go further:**

- Standard error — Wikipedia: https://en.wikipedia.org/wiki/Standard_error — The standard error of the mean, its derivation and its relationship to confidence intervals.
- Observational error — Wikipedia: https://en.wikipedia.org/wiki/Observational_error — Random and systematic errors with more examples of where each comes from.
- NIST/SEMATECH e-Handbook of Statistical Methods: https://www.itl.nist.gov/div898/handbook/ — A free, detailed engineering statistics reference from the US National Institute of Standards and Technology.


## 3.3 Visualising data honestly

*Choose the right kind of plot for your data, label it fully, and recognise the tricks that make charts mislead.* (about 25 min)

### Why plot at all?

Summary statistics squeeze a dataset into a few numbers, and squeezing loses information. Two sets of sensor readings can share the same mean and standard deviation while one is a smooth drift and the other is two separate clusters. A plot shows you shape, trends, gaps and outliers in a second, and it is often the moment you discover that something went wrong in an experiment. Plot your data **before** you trust any summary of it.

Plots are also how you communicate results. A clear plot lets a reader check your claim with their own eyes. A misleading plot can persuade people of something the data does not support, sometimes without the author meaning to.

### Choose the plot that matches the question

- **Line plot**: one quantity changing over time or along an ordered axis, such as a joint angle sampled every 10 ms. The line implies the values are connected, so do not use it for unrelated categories.
- **Scatter plot**: the relationship between two measured quantities, such as load and extension of a spring. Each point is one observation. This is the plot behind line fitting and correlation, later in this module.
- **Histogram**: the distribution of one quantity. Divide the range into equal-width **bins** and count how many values fall in each. It shows whether data is bunched, skewed, or has more than one peak.
- **Bar chart**: a quantity for a few separate categories, such as success rate for three gripper designs. Add error bars and state n.
- **Dot plot or strip plot**: every individual value for a few groups. With small samples (say, under 20 per group), showing every point is more honest than a bar, because a bar hides how many values there are and how they are spread.

### A histogram with only the standard library

You do not need special software to see a distribution. This program bins 60 simulated distance readings (**made-up data**, generated with a fixed seed) and prints a text histogram:

```python
import random

random.seed(3)
# Made-up data for illustration: 60 simulated distance readings (cm)
readings = [round(random.gauss(30.0, 0.5), 1) for _ in range(60)]

bin_width = 0.5
start = 28.5
counts = {}
for r in readings:
    b = start + bin_width * int((r - start) // bin_width)
    counts[b] = counts.get(b, 0) + 1

for b in sorted(counts):
    print(f"{b:4.1f}-{b + bin_width:4.1f} cm | {'#' * counts[b]}")
```

Output:

```
28.5-29.0 cm | ###
29.0-29.5 cm | #########
29.5-30.0 cm | #######################
30.0-30.5 cm | ###############
30.5-31.0 cm | #########
31.0-31.5 cm | #
```

Each bin includes its left edge and excludes its right edge, so a reading of exactly 29.0 cm is counted in the 29.0–29.5 bin. Try changing `bin_width` to 0.2 or 1.0. Bins that are too wide hide the shape; bins that are too narrow make random noise look like structure. There is no single correct width, which is itself a reason to be careful: a histogram's message can depend on a choice the reader never sees.

### Making a proper plot with matplotlib (optional)

For real reports, most Python users use the **matplotlib** library. It is not part of the standard library, so it must be installed first (for example with `pip install matplotlib`), and many free online Python environments already include it. This example plots means with standard-error bars:

```python
import matplotlib.pyplot as plt

# Made-up data for illustration
load_n = [0, 1, 2, 3, 4, 5]
extension_mm = [0.1, 2.1, 3.9, 6.2, 7.9, 10.1]
se_mm = [0.1, 0.1, 0.2, 0.2, 0.2, 0.3]

plt.errorbar(load_n, extension_mm, yerr=se_mm, fmt="o", capsize=4)
plt.xlabel("Load (N)")
plt.ylabel("Extension (mm)")
plt.title("Spring extension vs load (mean ± SE, n = 5 per load)")
plt.xlim(left=0)
plt.ylim(bottom=0)
plt.grid(True, alpha=0.3)
plt.savefig("spring.png", dpi=150)
```

Every element earns its place: axis labels with units, a title that says what the error bars mean and how many trials each point represents, and a grid that helps readers read values.

### How charts mislead

Most misleading charts come from a handful of tricks. Learn to spot them in other people's work and to avoid them in your own.

**1. A bar chart whose axis does not start at zero.** A bar's *length* tells the reader its size. Suppose (**made-up numbers**) gripper A succeeds in 92% of trials and gripper B in 94%. If the vertical axis starts at 91%, bar A is 1 unit tall and bar B is 3 units tall. B looks three times better, when the real difference is 2 percentage points. Bar charts should start at zero. Line and scatter plots may zoom in, because they encode values by position rather than length, but the axis labels must make the zoom obvious.

**2. Cherry-picked ranges.** Showing only the week when a robot performed well, or cutting the time axis just before a failure, can reverse the story. Show the whole range, or explain why you chose a window.

**3. Hidden sample sizes.** A bar for "3 trials" and a bar for "300 trials" look identical. Put n on the chart or in the caption.

**4. Missing or unlabelled error bars.** Without them, a reader cannot tell whether a difference is larger than the noise.

**5. Two different vertical axes.** Plotting two quantities with a left and a right axis lets the author slide and stretch either one until the lines appear to move together. Prefer two separate plots that share the horizontal axis.

**6. Smoothing or joining points that should not be joined.** Drawing a smooth curve through five scattered points suggests far more knowledge than five points provide. Show the points; add a fitted line only if you explain the model.

**7. Decoration that distorts.** 3D bars, tilted pie charts and pictures scaled in both width and height all make sizes hard to judge.

### A checklist before you share a plot

- Is this the right type of plot for the question?
- Are both axes labelled with quantity **and units**?
- Does a bar chart start at zero?
- Are n and the meaning of any error bars stated?
- Would someone who only saw the plot draw the same conclusion you did from the full data?

### Recap

Plot your data before trusting summaries. Match the plot to the question: line for change over an ordered axis, scatter for relationships, histogram for distributions, bars or dot plots for categories. Label everything, show uncertainty and sample sizes, start bar charts at zero, and avoid tricks that make a small or uncertain effect look large.

> **The plot should match the analysis.** If you excluded data, changed bin widths or zoomed an axis, say so in the caption. A reader should be able to reproduce your plot from your data and your description. Choosing the version of a chart that looks most impressive, rather than the one that represents the data most fairly, is a quiet form of misreporting.

#### Project: Redesign a misleading chart

Find a chart in a newspaper, an advert or a website that you think is misleading, or invent one using the made-up gripper success rates from this lesson.

1. Sketch the original on paper and list every problem you can find, using the seven tricks above.
2. Sketch an honest version that shows the same data. Label the axes with units and state n.
3. Using Python, print a text bar chart of the same values twice: once with bar lengths proportional to the values, and once proportional to (value − 91). Compare how the difference looks.
4. Optional: if you have matplotlib available, produce both versions as proper plots.

**Deliverables**

- A sketch of the original chart with its problems listed
- A sketch or plot of an honest version
- A short Python script that prints both text bar charts

#### Check your understanding

1. Which plot best shows how a single sensor's readings are distributed?
   A) A pie chart
   B) A line plot of the readings in sorted order
   C) A bar chart of the mean
   D) A histogram

2. Success rates of 92% and 94% are drawn as bars on an axis starting at 91%. How many times taller does the 94% bar look?
   A) About 1.02 times
   B) 2 times
   C) 3 times
   D) It looks the same

3. You have 6 trials per condition. Why might a dot plot be better than a bar chart of means?
   A) It shows every individual value, so readers can see the spread and the sample size
   B) Dot plots always make differences look larger
   C) Bar charts cannot show means
   D) Dot plots do not need axis labels

4. Why is changing a histogram's bin width something you should report?
   A) Bin width changes the units of the data
   B) Very wide bins can hide structure and very narrow bins can make noise look like structure, so the choice affects the message
   C) Histograms must always use 10 bins
   D) It changes the mean of the data

**Go further:**

- Pyplot tutorial — matplotlib documentation: https://matplotlib.org/stable/tutorials/pyplot.html — The official introduction to making line, scatter and bar plots with matplotlib.
- Misleading graph — Wikipedia: https://en.wikipedia.org/wiki/Misleading_graph — A catalogue of misleading chart techniques with illustrated examples.
- Histogram — Wikipedia: https://en.wikipedia.org/wiki/Histogram — How histograms are built and the different rules people use to choose bin widths.


## 3.4 Fitting lines with least squares

*Find the straight line that best fits a set of measurements, compute its slope and intercept by hand and in Python, and use residuals to judge whether a line was the right model.* (about 35 min)

### Why fit a line?

Many engineering relationships are, at least approximately, straight lines. A spring's extension is proportional to the load on it (Hooke's law). A temperature sensor's output voltage rises steadily with temperature. A wheel's distance travelled grows with the number of encoder counts. If you can find the line, you can **calibrate** a sensor, **estimate** a physical constant such as a spring's stiffness, and **predict** values you did not measure.

Real measurements never sit exactly on a line, because of noise. So the question becomes: which line fits *best*, and what does "best" mean?

### The data

A spring is hung from a hook and loaded with known weights. Its extension is measured each time (**made-up data for illustration**):

```
load (N)        0.0  1.0  2.0  3.0  4.0  5.0
extension (mm)  0.1  2.1  3.9  6.2  7.9 10.1
```

We want a line of the form

```
y = a + b · x
```

where x is the load, y is the extension, **b** is the slope (millimetres per newton) and **a** is the intercept (the extension at zero load).

### Residuals and "least squares"

For any candidate line, each data point has a **residual**: the measured value minus the value the line predicts.

```
residual = y_measured − (a + b · x)
```

A good line has small residuals. We cannot just add them up, because positive and negative residuals would cancel, so a terrible line could score zero. Instead we **square** each residual and add them. The **least-squares line** is the one that makes this sum of squared residuals as small as possible. Squaring also punishes large misses heavily, which is usually what we want, though it means a single wild outlier can tug the line noticeably.

Using calculus, one can show that the best slope and intercept are:

```
x̄ = mean of x,   ȳ = mean of y

     Σ (x − x̄)(y − ȳ)
b = ------------------
        Σ (x − x̄)²

a = ȳ − b · x̄
```

You do not need the calculus to use these. Read the slope formula as: "how much do x and y move together, divided by how much x moves on its own." The intercept formula guarantees that the line passes through the point (x̄, ȳ), the centre of the data.

### Working it by hand

x̄ = (0 + 1 + 2 + 3 + 4 + 5) / 6 = 2.5 and ȳ = 30.3 / 6 = 5.05.

```
  x     y    x − x̄   y − ȳ   (x − x̄)(y − ȳ)   (x − x̄)²
 0.0   0.1   −2.5    −4.95       12.375          6.25
 1.0   2.1   −1.5    −2.95        4.425          2.25
 2.0   3.9   −0.5    −1.15        0.575          0.25
 3.0   6.2    0.5     1.15        0.575          0.25
 4.0   7.9    1.5     2.85        4.275          2.25
 5.0  10.1    2.5     5.05       12.625          6.25
                          sum =  34.850   sum = 17.50
```

So b = 34.85 / 17.5 ≈ 1.991 mm/N and a = 5.05 − 1.991 × 2.5 ≈ 0.071 mm.

The spring stretches about 1.99 mm for every newton. Its stiffness is the inverse: k ≈ 1 / 1.991 ≈ 0.502 N/mm, or about 502 N/m. The small intercept, 0.07 mm, is close to zero, as Hooke's law predicts; it may come from how the zero reading was taken.

### The same calculation in Python

```python
import statistics

# Made-up data for illustration: a spring stretched by hanging loads
load = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]        # newtons
extension = [0.1, 2.1, 3.9, 6.2, 7.9, 10.1]  # millimetres

def fit_line(xs, ys):
    """Least-squares slope and intercept for y = a + b·x."""
    x_bar = statistics.mean(xs)
    y_bar = statistics.mean(ys)
    sxy = sum((x - x_bar) * (y - y_bar) for x, y in zip(xs, ys))
    sxx = sum((x - x_bar) ** 2 for x in xs)
    b = sxy / sxx
    a = y_bar - b * x_bar
    return a, b

a, b = fit_line(load, extension)
print(f"extension ≈ {a:.3f} + {b:.3f} × load")

print("load  measured  predicted  residual")
for x, y in zip(load, extension):
    predicted = a + b * x
    print(f"{x:4.1f}  {y:8.2f}  {predicted:9.3f}  {y - predicted:8.3f}")
```

Output:

```
extension ≈ 0.071 + 1.991 × load
load  measured  predicted  residual
 0.0      0.10      0.071     0.029
 1.0      2.10      2.063     0.037
 2.0      3.90      4.054    -0.154
 3.0      6.20      6.046     0.154
 4.0      7.90      8.037    -0.137
 5.0     10.10     10.029     0.071
```

Python 3.10 and later also include this calculation as `statistics.linear_regression(load, extension)`, which returns the same slope and intercept. Writing it yourself once is the best way to understand what the library does.

### Residuals tell you if a line was the right idea

The residuals above are small (about 0.15 mm at most) and scattered above and below zero with no obvious pattern. That is what you hope to see: the line captures the relationship and what is left looks like noise.

Now look at a sensor whose output curves upward (**made-up data**: y = x² exactly):

```python
import statistics

# Made-up data for illustration: a sensor whose output curves upward
x = [0, 1, 2, 3, 4, 5]
y = [0.0, 1.0, 4.0, 9.0, 16.0, 25.0]

fit = statistics.linear_regression(x, y)
residuals = [yi - (fit.intercept + fit.slope * xi) for xi, yi in zip(x, y)]
print(f"slope {fit.slope:.2f}, intercept {fit.intercept:.2f}")
print([round(r, 2) for r in residuals])
```

Output:

```
slope 5.00, intercept -3.33
[3.33, -0.67, -2.67, -2.67, -0.67, 3.33]
```

The residuals form a clear pattern: positive at both ends, negative in the middle, a "smile". A pattern in the residuals means the model is wrong, not just noisy. Here, a straight line is the wrong shape.

A popular single-number score is **R²**, the fraction of the variation in y that the line accounts for (1 means a perfect fit). For the spring, R² ≈ 0.999. For the curved sensor, R² ≈ 0.92, which sounds impressive, yet the line is plainly the wrong model. **Always look at the residuals**, not just R².

### Do not extrapolate carelessly

The fit tells you about loads between 0 and 5 N. Using it to predict the extension at 50 N assumes the spring keeps behaving the same way far outside anything you tested, but real springs eventually stretch permanently or their coils touch. Treat predictions outside your data range as guesses, and test them.

### Recap

- A **residual** is measured minus predicted. The **least-squares line** minimises the sum of squared residuals.
- Slope b = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)²; intercept a = ȳ − b · x̄. The line passes through (x̄, ȳ).
- The slope often has a physical meaning, such as the inverse of a spring's stiffness.
- Random-looking residuals suggest a good model; patterned residuals suggest the wrong one, whatever R² says.
- Be cautious about predicting outside the range of your data.

#### Project: Calibrate a rubber band

You need a rubber band, a small bag, coins of one type, a ruler, paper and Python. Hang the bag from the rubber band over the edge of a table, with the ruler held vertically beside it.

1. Record the length of the band with 0, 2, 4, 6, 8 and 10 coins in the bag. Repeat the whole series three times and use the mean length at each load.
2. Using your `fit_line` function, fit length against number of coins and print the residuals.
3. Do the residuals look random, or is there a pattern? Rubber bands are often not linear, so a pattern is a real finding, not a failure.
4. Try fitting only the first four loads. Does the slope change?

Keep heavy loads small, and keep faces away from a stretched band in case it snaps.

**Deliverables**

- A table of mean band length for each load
- Your fitted slope and intercept, with units
- A printed list of residuals and two or three sentences on whether a straight line suits the band

#### Check your understanding

1. Why does least squares add up squared residuals rather than plain residuals?
   A) Squaring makes the arithmetic faster
   B) Plain residuals can be positive or negative and cancel out, so a bad line could still score zero
   C) Residuals are always negative
   D) Squared residuals have the same units as y

2. Data has x̄ = 4 and ȳ = 10, and the least-squares slope is 2. What is the intercept?
   A) 2
   B) 8
   C) 10
   D) −2

3. The residuals of a line fit are positive at both ends and negative in the middle. What does this suggest?
   A) The fit is perfect
   B) There is too little noise
   C) The data was entered wrongly
   D) A straight line is the wrong shape for this relationship

4. A spring's extension is fitted as 1.991 mm per newton. What is its stiffness?
   A) 1.991 N/mm
   B) About 0.502 N/mm
   C) About 19.9 N/m
   D) It cannot be found from the slope

5. A line fits loads from 0 to 5 N very well. Why is predicting the extension at 50 N risky?
   A) Least squares only works for small numbers
   B) The slope formula breaks for large x
   C) Nothing you measured tells you the spring still behaves linearly that far out
   D) R² becomes negative above 5 N

**Go further:**

- Simple linear regression — Wikipedia: https://en.wikipedia.org/wiki/Simple_linear_regression — Derivation of the slope and intercept formulas and how to estimate their uncertainty.
- Least squares — Wikipedia: https://en.wikipedia.org/wiki/Least_squares — The history and wider uses of the least-squares idea beyond straight lines.


## 3.5 Comparing two conditions

*Decide whether a change really made a difference by comparing means, spreads and overlap, and by measuring the size of the effect, not just its existence.* (about 30 min)

### Did the change help?

Much of engineering is comparison. You tune a controller and want to know whether the joint now settles faster. You change a gripper's finger material and want to know whether it drops fewer objects. You run some trials with the old version and some with the new, and the means differ. But means **always** differ a little, even if nothing changed, because of noise. The real question is: **is the difference larger than the noise, and is it large enough to matter?**

### The data

A robot joint is commanded to move to a target, and we record its **settling time**: how long until it stays within a small band around the target. We test the old controller and a new one, 8 trials each (**made-up data for illustration**):

```
old: 1.42, 1.35, 1.51, 1.38, 1.47, 1.40, 1.55, 1.44 s
new: 1.31, 1.36, 1.28, 1.40, 1.25, 1.33, 1.37, 1.30 s
```

### Step 1: describe each condition

```python
import math
import statistics

# Made-up data for illustration: settling time (s) of one joint, 8 trials each
old = [1.42, 1.35, 1.51, 1.38, 1.47, 1.40, 1.55, 1.44]
new = [1.31, 1.36, 1.28, 1.40, 1.25, 1.33, 1.37, 1.30]

def describe(name, data):
    m = statistics.mean(data)
    s = statistics.stdev(data)
    print(f"{name}: n = {len(data)}, mean = {m:.3f} s, sd = {s:.3f} s")
    return m, s

m1, s1 = describe("old", old)
m2, s2 = describe("new", new)
n1, n2 = len(old), len(new)

diff = m1 - m2
se_diff = math.sqrt(s1**2 / n1 + s2**2 / n2)
pooled = math.sqrt(((n1 - 1) * s1**2 + (n2 - 1) * s2**2) / (n1 + n2 - 2))
d = diff / pooled

print(f"difference = {diff:.3f} s, SE of difference = {se_diff:.3f} s")
print(f"rough 95% range: {diff - 2 * se_diff:.3f} to {diff + 2 * se_diff:.3f} s")
print(f"pooled sd = {pooled:.3f} s, effect size d = {d:.2f}")
```

Output:

```
old: n = 8, mean = 1.440 s, sd = 0.067 s
new: n = 8, mean = 1.325 s, sd = 0.050 s
difference = 0.115 s, SE of difference = 0.030 s
rough 95% range: 0.056 to 0.174 s
pooled sd = 0.059 s, effect size d = 1.94
```

We will unpack each line.

### Step 2: how uncertain is the difference?

From the previous lessons, each mean has its own standard error, s / √n. When you subtract two independent means, their uncertainties combine. Variances (squared standard errors) add:

```
SE_difference = √( s₁²/n₁ + s₂²/n₂ )
              = √( 0.067²/8 + 0.050²/8 ) ≈ 0.030 s
```

Note that the uncertainties **add**, even though the means are subtracted. Comparing two noisy things is noisier than measuring either one.

The difference in means is 0.115 s, almost four times its standard error. A rough 95% range is the difference ± 2 SE, about 0.06 to 0.17 s. With only 8 trials per group, a more careful calculation uses a slightly larger multiplier from the t-distribution (about 2.2 here), but the range still sits comfortably above zero. So the improvement is very unlikely to be just noise.

### Step 3: how big is the effect?

"Unlikely to be noise" is not the same as "important". With thousands of trials, even a 0.001 s improvement can be reliably detected, yet nobody would care. So engineers also report an **effect size**.

The simplest effect size is the raw difference **in real units**: the new controller settles about 0.115 s faster, roughly 8% of the old 1.44 s. Often that is the most useful number of all, because you can judge it against a requirement.

A unit-free effect size, called **Cohen's d**, divides the difference by the typical spread within the groups:

```
d = (mean₁ − mean₂) / pooled standard deviation
```

The **pooled standard deviation** is a weighted average of the two groups' spreads (0.059 s here). Here d ≈ 1.9: the means are about two standard deviations apart. As a loose convention, d around 0.2 is often called small, 0.5 medium and 0.8 or more large, but these labels came from behavioural science and are only a rough guide. In engineering, what counts as large depends on the job.

### Step 4: look at the overlap

Means and effect sizes are summaries. Look at the individual trials as well:

```python
old = [1.42, 1.35, 1.51, 1.38, 1.47, 1.40, 1.55, 1.44]
new = [1.31, 1.36, 1.28, 1.40, 1.25, 1.33, 1.37, 1.30]

print("old sorted:", sorted(old))
print("new sorted:", sorted(new))

wins = sum(1 for o in old for n in new if n < o)
ties = sum(1 for o in old for n in new if n == o)
pairs = len(old) * len(new)
print(f"new faster in {wins} of {pairs} pairs ({wins / pairs:.0%}), ties: {ties}")
```

Output:

```
old sorted: [1.35, 1.38, 1.4, 1.42, 1.44, 1.47, 1.51, 1.55]
new sorted: [1.25, 1.28, 1.3, 1.31, 1.33, 1.36, 1.37, 1.4]
new faster in 59 of 64 pairs (92%), ties: 1
```

The two groups overlap between 1.35 and 1.40 s: the best old trial beat the worst new trial. Comparing every old trial with every new trial, the new controller was faster in 59 of the 64 pairs. This is an intuitive way to describe an effect: "pick one trial from each at random, and the new one is faster about nine times in ten."

Overlap matters for engineering decisions. If the requirement were "always settle within 1.40 s", the new controller met it in all 8 trials and the old one in only 3. That is a different and often more useful statement than a difference in means.

### Things that can fool you

- **Conditions that differ in more than one way.** If all the old trials ran in the morning and all the new ones in the afternoon, after the motors warmed up, the comparison mixes two changes. Interleave or randomise the order of trials.
- **Too few trials.** With 3 trials per group, standard deviations are themselves very uncertain, and a fluke can look like an effect.
- **Choosing the comparison after seeing the data.** If you measure ten things and report the one that changed, you have probably found noise.
- **Reporting only "it was significant".** Always give the size of the difference with its uncertainty, in real units.

### Recap

- Means always differ a little; compare the difference with its uncertainty, √(s₁²/n₁ + s₂²/n₂).
- A rough 95% range for the difference is ± 2 SE; small samples need a slightly larger multiplier.
- Report an **effect size**: the raw difference in units, and optionally Cohen's d = difference / pooled sd.
- Look at the **overlap** of individual trials and relate it to your actual requirement.
- Keep everything except the change you are testing the same, and decide on the comparison before you collect data.

> **Decide the comparison before you look.** Write down which quantity you will compare, how many trials you will run, and how you will decide, **before** running the trials. Changing these after seeing the results, for example adding trials until the difference looks convincing, makes your uncertainty estimates meaningless.

#### Check your understanding

1. Two means each have a standard error of 0.3. What is the standard error of their difference?
   A) 0
   B) 0.6
   C) About 0.42
   D) 0.3

2. Controller B's mean is 0.002 s faster than A's, and with 10,000 trials each this is clearly larger than the noise. What is the most sensible conclusion?
   A) B is a major improvement
   B) The difference is real but probably too small to matter; judge it against the requirement
   C) The result must be an error because the difference is small
   D) Effect size does not matter when the sample is large

3. Cohen's d is the difference in means divided by:
   A) the pooled standard deviation of the individual trials
   B) the standard error of the difference
   C) the number of trials
   D) the larger of the two means

4. All 'old' trials were run on Monday and all 'new' trials on Tuesday after maintenance. What is the main problem?
   A) Tuesday trials are always faster
   B) The sample sizes are too large
   C) There is no problem as long as n is the same
   D) Any difference could be caused by the day or the maintenance rather than the new controller

**Go further:**

- Effect size — Wikipedia: https://en.wikipedia.org/wiki/Effect_size — Cohen's d, the common-language effect size and other ways of expressing how big a difference is.
- MIT OpenCourseWare 18.05 — Introduction to Probability and Statistics: https://ocw.mit.edu/courses/18-05-introduction-to-probability-and-statistics-spring-2022/ — A free university course covering confidence intervals and comparing groups properly, for when you want the full theory.


## 3.6 Correlation is not causation

*Measure how strongly two quantities move together, then see in a simulation how a hidden third factor can create a strong correlation with no causal link, and how controlled experiments reveal the truth.* (about 30 min)

### A tempting conclusion

You log 300 test runs of a robot arm. You notice that on runs where the joint motor was hotter, the arm's position error was larger. The obvious conclusion: heat is causing the error, so add a cooling fan. That fan costs money, mass and power. Before buying it, you need to know whether heat really **causes** the error, or whether the two just happen to rise together. This lesson shows how to tell the difference.

### Measuring correlation

The **Pearson correlation coefficient**, r, measures how closely two quantities follow a straight-line relationship. It runs from −1 to +1:

- r = +1: the points lie exactly on a rising line.
- r = −1: the points lie exactly on a falling line.
- r = 0: no straight-line relationship (though there might still be a curved one).

It is built from the same pieces as the least-squares slope in the line-fitting lesson:

```
              Σ (x − x̄)(y − ȳ)
r = ---------------------------------
     √( Σ(x − x̄)² · Σ(y − ȳ)² )
```

For a straight-line fit, r² is the same as the R² you met in that lesson. Python 3.10 and later provide `statistics.correlation(xs, ys)`.

### A simulation where we know the truth

In real data you never know for certain what causes what. In a simulation, you write the rules, so you can check whether analysis methods find the truth. Here is a model of the robot arm (**simulated, made-up data**). The **payload** the arm carries makes the motor work harder, which heats it, and also bends the arm slightly, which increases position error. Temperature itself has **no effect** on error in this model.

```python
import random
import statistics

random.seed(4)
# Simulated, made-up data: 300 test runs of a robot arm.
# The payload drives BOTH motor temperature and position error.
# Temperature has NO effect on error in this model.
runs = []
for _ in range(300):
    payload = random.uniform(0.0, 5.0)                        # kg
    temp = 25 + 3.0 * payload + random.gauss(0, 1.5)          # °C
    error = 0.5 + 0.4 * payload + random.gauss(0, 0.3)        # mm
    runs.append((payload, temp, error))

temps = [t for _, t, _ in runs]
errors = [e for _, _, e in runs]
print(f"all runs:        r = {statistics.correlation(temps, errors):.2f}")

# Look only at runs with nearly the same payload
band = [(t, e) for p, t, e in runs if 2.0 <= p < 2.5]
r_band = statistics.correlation([t for t, _ in band], [e for _, e in band])
print(f"payload 2.0-2.5: r = {r_band:.2f}  ({len(band)} runs)")

fit = statistics.linear_regression(temps, errors)
print(f"slope: {fit.slope:.2f} mm per °C")
```

Output:

```
all runs:        r = 0.84
payload 2.0-2.5: r = 0.09  (27 runs)
slope: 0.12 mm per °C
```

Across all runs, temperature and error are strongly correlated, r = 0.84. A fitted line says error rises by about 0.12 mm per °C, which would suggest that cooling the motor by 10 °C cuts the error by over a millimetre. Yet we built the model, and we know temperature does nothing to error.

The payload is a **confounder**: a third factor that influences both quantities and makes them move together. When we look only at runs with nearly the same payload (2.0 to 2.5 kg), the correlation almost vanishes, r = 0.09. Holding the confounder roughly fixed reveals that, at a given payload, hotter runs are not worse.

Be careful with that last number too. It comes from only 27 runs, and small samples give noisy correlations: with other random seeds, the same band typically gives values anywhere from about −0.3 to +0.4. "Close to zero, with a lot of uncertainty" is the honest summary.

### Ways a correlation can arise without the cause you expect

1. **Confounding**: a third factor drives both, as with payload above. Classic non-engineering example: ice-cream sales and swimming accidents both rise in hot weather.
2. **Reverse causation**: the effect runs the other way. A struggling joint might draw more current *because* it is fighting a position error, so the error heats the motor rather than the reverse.
3. **Chance**: with few data points, or many pairs of quantities tested, some strong correlations appear by luck alone.
4. **Selection**: if you only logged runs that triggered an alarm, you may have created a pattern that does not exist in all runs.

### The controlled experiment

Stratifying by payload helped, but only because we thought of payload. There might be confounders nobody has thought of. The most powerful tool for establishing cause is the **controlled experiment**: **you** change the suspected cause, and you make sure nothing else changes along with it.

The key trick is **randomisation**. Decide by a coin flip whether each run gets extra heating. Then heating cannot be linked to payload, or to time of day, or to anything else, except by chance. Any difference in error between heated and unheated runs must be caused by the heat (or by luck, which we can estimate).

```python
import random
import statistics

random.seed(2)
# Simulated controlled experiment (made-up model, same as before).
# A coin flip decides whether each run gets an extra 10 °C of heating,
# so heating is independent of payload.
heated, unheated = [], []
for _ in range(300):
    payload = random.uniform(0.0, 5.0)
    heat_on = random.random() < 0.5
    temp = 25 + 3.0 * payload + (10 if heat_on else 0) + random.gauss(0, 1.5)
    error = 0.5 + 0.4 * payload + random.gauss(0, 0.3)
    (heated if heat_on else unheated).append(error)

print(f"heated:   n = {len(heated)}, mean error = {statistics.mean(heated):.2f} mm")
print(f"unheated: n = {len(unheated)}, mean error = {statistics.mean(unheated):.2f} mm")

diff = statistics.mean(heated) - statistics.mean(unheated)
se = (statistics.variance(heated) / len(heated)
      + statistics.variance(unheated) / len(unheated)) ** 0.5
print(f"difference = {diff:.2f} mm, SE of difference = {se:.2f} mm")
```

Output:

```
heated:   n = 154, mean error = 1.48 mm
unheated: n = 146, mean error = 1.51 mm
difference = -0.02 mm, SE of difference = 0.07 mm
```

(The rounded means differ by 0.03 mm; the unrounded difference is about 0.02 mm.) The correlation suggested 10 °C of heat should add over a millimetre of error. The experiment finds a difference of −0.02 mm, much smaller than its standard error of 0.07 mm: no detectable effect. The fan would have been wasted money. What would actually help is a stiffer arm, or compensating for payload in the controller.

In real engineering you cannot always run the ideal experiment, but you can often get close: change one thing at a time, randomise the order of trials, and keep a log of everything else that might matter.

### Recap

- The correlation coefficient r measures how closely two quantities follow a straight line, from −1 to +1.
- A strong correlation does not show that one quantity causes the other. Look for **confounders**, **reverse causation**, **chance** and **selection**.
- Holding a suspected confounder fixed can expose a misleading correlation, but only for confounders you have thought of.
- A **randomised controlled experiment**, where you change the suspected cause and nothing else, is the strongest way to establish cause.

> **Correlation is still useful.** Correlation is not worthless. It is how many investigations begin, and a correlation can be perfectly good for *prediction* even without a causal link: if hot motors reliably come with large errors, a temperature reading can warn you to expect a large error. It just cannot tell you that cooling the motor will fix anything. Prediction and intervention are different questions.

#### Project: Build a confounder of your own

Write a Python simulation, with a fixed random seed, of a situation where a hidden factor creates a misleading correlation. Ideas: hours of daylight driving both outdoor temperature and solar-panel output; class size driving both noise level and the number of questions asked.

1. Generate at least 200 made-up observations in which the hidden factor influences two measured quantities, but neither measured quantity affects the other.
2. Print the correlation between the two measured quantities.
3. Print the correlation within a narrow band of the hidden factor.
4. Add a randomised "experiment" in which you change one measured quantity by a coin flip, and show the other does not change.
5. Write a short paragraph, clearly labelled as describing simulated data, explaining what an analyst who never measured the hidden factor might wrongly conclude.

**Deliverables**

- A Python script with a fixed seed and comments describing the model
- Printed correlations for all data and for a narrow band
- Printed results of the randomised experiment and a short explanatory paragraph

#### Check your understanding

1. In the simulation, why were temperature and error strongly correlated even though temperature had no effect?
   A) Because the random seed was 4
   B) Because Pearson's r is always high for 300 points
   C) Because payload increased both temperature and error
   D) Because error causes temperature

2. Which value of r indicates the strongest straight-line relationship?
   A) 0.5
   B) −0.9
   C) 0.1
   D) 0

3. Why does deciding by coin flip which runs get extra heating make the experiment trustworthy?
   A) It breaks any link between heating and other factors such as payload, so a difference in error can be attributed to the heat or to chance
   B) Coin flips reduce the noise in each measurement
   C) It guarantees exactly half the runs are heated
   D) It makes the correlation coefficient equal to 1

4. A joint draws more current whenever its position error is large. An engineer concludes high current causes the error. What alternative should they consider first?
   A) That the data must be fake
   B) That current and error are unrelated
   C) That correlation always proves causation for electrical quantities
   D) Reverse causation: the controller drives more current because it is trying to correct a large error

5. Within the 2.0–2.5 kg payload band, r was 0.09 from 27 runs. What is the most honest summary?
   A) Temperature definitely has exactly zero effect
   B) Close to zero, but with only 27 runs the estimate is very uncertain
   C) Temperature has a strong effect at medium payloads
   D) The band is too narrow to compute r

**Go further:**

- Correlation does not imply causation — Wikipedia: https://en.wikipedia.org/wiki/Correlation_does_not_imply_causation — Many real examples of confounding, reverse causation and coincidence.
- Confounding — Wikipedia: https://en.wikipedia.org/wiki/Confounding — A fuller treatment of confounders and the methods used to control for them.


---

# Module 4: Scientific simulation

Building numerical models of physical systems, from falling objects to oscillating springs, and checking whether they can be trusted.

**Objectives**

- Model a system as a state that changes according to rules over time.
- Implement Euler's method to simulate motion under gravity.
- Test a simulation against a case with a known exact answer.
- Explain how step size affects accuracy and stability.


## 4.1 What a simulation is

*A simulation steps a model of the world forward in time. Learn what goes into a model, why every model rests on assumptions, and the difference between verifying and validating it.* (about 25 min)

### Why simulate?

Before an engineering team builds a robot arm, they want answers. Will the motors be strong enough? How far will the arm sag under a load? What happens if the controller gains are set too high? Building and breaking real hardware to find out is slow, expensive and sometimes dangerous. A **simulation** lets you ask these questions in software: try a hundred designs in an afternoon, crash a virtual robot without harm, and see quantities, like the force inside a joint, that are hard to measure directly.

Simulations are used to design aircraft, forecast weather, plan spacecraft trajectories and train robot controllers. But a simulation is only as trustworthy as the model inside it and the care taken to check it. This module teaches you to build simple simulations **and** to question them.

### What is inside a simulation?

Every time-stepping simulation has the same ingredients:

- **State**: the numbers that describe the system at one instant. For a thrown ball: its height and its velocity. For a two-link arm: two joint angles and two joint speeds.
- **Rules**: equations that say how the state changes. Usually these come from physics, such as Newton's second law, F = m · a.
- **Parameters**: fixed numbers in the rules, such as mass, gravity or a spring's stiffness.
- **Initial conditions**: the state at the start.
- **A time step**, dt: how far forward each update jumps.

The simulation repeatedly applies "next state = current state + change over dt". You met this pattern when simulating a cooling cup of tea in Python fundamentals.

### Models and assumptions

A **model** is a simplified description of reality. Simplifying is not a flaw; it is the point. A model that included every air molecule around a thrown ball would be impossible to run. Instead we make **assumptions**, for example:

- Gravity is constant, 9.81 m/s², at every height.
- Air resistance is small enough to ignore.
- The ball is a point: its size and spin do not matter.

Each assumption makes the model simpler and each one can fail. Ignoring air resistance is fine for a heavy steel ball thrown gently; it is badly wrong for a table-tennis ball or a feather. A good engineer writes the assumptions down, so anyone using the results knows where they stop applying.

### A first simulation: a ball thrown upward

A ball is thrown straight up at 12 m/s. How high does it go? The state is height y and velocity v. Each step, the height changes by v · dt and the velocity changes by −g · dt.

```python
G = 9.81   # m/s², assumed constant (model assumption)

def max_height(v0, dt):
    """Step a ball thrown straight up until it stops rising."""
    y, v = 0.0, v0          # the state: height (m) and velocity (m/s)
    while v > 0:
        y = y + v * dt      # new height from current velocity
        v = v - G * dt      # new velocity from gravity
    return y

exact = 12.0**2 / (2 * G)
print(f"exact:      {exact:.4f} m")
for dt in [0.1, 0.01, 0.001]:
    h = max_height(12.0, dt)
    print(f"dt = {dt:<5}  {h:.4f} m   error {h - exact:+.4f} m")
```

Output:

```
exact:      7.3394 m
dt = 0.1    7.9482 m   error +0.6088 m
dt = 0.01   7.3996 m   error +0.0601 m
dt = 0.001  7.3455 m   error +0.0060 m
```

For this simple model there is an exact answer from algebra: the maximum height is v₀² / (2g) = 144 / 19.62 ≈ 7.339 m. That is a gift. It lets us check the simulation.

### Verification: solving the equations right

**Verification** asks: *does the program correctly solve the model we wrote down?* It is about bugs and numerical accuracy, not about the real world.

The table above is a verification test. Each time dt shrinks by a factor of 10, the error shrinks by about a factor of 10 too, and the result approaches the exact answer. That tells us two things: there is probably no bug, and we know how small dt must be for a given accuracy. If the error had *not* shrunk, or had settled on some wrong value, we would suspect a mistake in the code.

Ways to verify a simulation:

- Compare with a case that has an **exact solution**, as here.
- Check that results **converge** as dt gets smaller.
- Check **conservation laws**: for example, with no friction, total energy should stay (nearly) constant.
- Check **limiting cases**: a mass on a spring that starts at rest at its equilibrium position should never move; with gravity set to zero a thrown ball should never come down.
- Check **units and signs**: does the ball fall down, not up?

### Validation: solving the right equations

**Validation** asks a different question: *does the model describe reality well enough for our purpose?* The only way to answer it is to compare with **real measurements**.

Our ball model could pass every verification test and still fail validation. Throw a real table-tennis ball upward at 12 m/s and it will not reach 7.3 m, because air resistance, which we assumed away, is large for a light ball. The code is correct; the model is wrong for that ball. For a heavy ball thrown gently, the same model might agree with measurements within a few centimetres.

A handy way to remember the difference:

- **Verification**: are we solving the equations right?
- **Validation**: are we solving the right equations?

You need both. A perfectly verified simulation of the wrong model gives precise, confident, wrong answers. A model that once matched an experiment, but whose code has a bug, cannot be trusted for any new case.

Validation also has limits. A model validated for throws between 5 and 15 m/s tells you little about a throw at 100 m/s, where new effects matter. Every validated model comes with a **range of validity**.

### Recap

- A simulation steps a **state** forward using **rules**, **parameters**, **initial conditions** and a **time step**.
- Every model rests on **assumptions**. Write them down, because they define where the model stops working.
- **Verification** checks the code solves the model correctly: exact solutions, convergence as dt shrinks, conservation laws, limiting cases.
- **Validation** checks the model matches reality, by comparison with measurements, within a stated range.

> **Label simulated results as simulated.** When you report a number from a simulation, say so, list the main assumptions, and state whether the model has been validated against real measurements, and over what range. A simulated result presented as if it were a measurement can lead others to trust a design that has never been tested.

#### Check your understanding

1. Which of these is part of a ball simulation's state?
   A) The value of g
   B) The ball's current velocity
   C) The time step dt
   D) The programming language

2. A student checks that their simulation's error shrinks steadily as dt is reduced. What are they doing?
   A) Validation
   B) Calibration
   C) Verification
   D) Extrapolation

3. A ball simulation without air resistance matches the exact formula perfectly, but a real table-tennis ball goes much lower. What has failed?
   A) Validation: the model's assumption of no air resistance is wrong for this ball
   B) Verification: the code must have a bug
   C) Nothing: real measurements are always less accurate than simulations
   D) The exact formula is wrong

4. Why should you write down a model's assumptions?
   A) Because simulations will not run without comments
   B) To make the code longer
   C) Because assumptions make results more accurate
   D) Because they show where the model stops applying, so others do not use it outside that range

**Go further:**

- Verification and validation of computer simulation models — Wikipedia: https://en.wikipedia.org/wiki/Verification_and_validation_of_computer_simulation_models — A fuller account of how engineers build confidence in simulation models.


## 4.2 Time stepping with Euler's method

*Turn a rate-of-change equation into a simulation with Euler's method, measure its error against an exact answer, and extend it to systems with several state variables.* (about 30 min)

### Rates of change

Most physical laws are statements about **rates of change**. A capacitor discharges at a rate proportional to its voltage. A falling object's velocity changes at a rate set by gravity and drag. A robot joint's angle changes at a rate equal to its angular velocity. An equation that gives the rate of change of a quantity is called a **differential equation**, written like this:

```
dy/dt = f(t, y)
```

Read it as: "the rate at which y changes is some function of the time and of y itself." Sometimes you can solve such an equation exactly with calculus, but most real engineering equations, especially for robots with several moving parts, have no neat exact solution. Simulation lets you solve them numerically, one small step at a time.

### Euler's method

The simplest method is named after the mathematician Leonhard Euler. If you know y now and how fast it is changing now, assume it keeps changing at that rate for a short time dt:

```
y_next = y_now + f(t_now, y_now) · dt
t_next = t_now + dt
```

Geometrically, you follow the **tangent line** (the slope at the start of the step) for a distance dt, then recompute the slope and repeat. The true curve bends away from the tangent during the step, so every step makes a small error. Smaller steps, smaller errors.

### A worked example: a discharging capacitor

When a capacitor discharges through a resistor, its voltage V obeys

```
dV/dt = −V / (RC)
```

where RC is the **time constant**. Take RC = 2 s and a starting voltage of 5 V. The exact solution, from calculus, is V(t) = 5 · e^(−t/2), which gives V(4) = 5 · e^(−2) ≈ 0.6767 V. Having an exact answer lets us measure Euler's error.

Two steps by hand, with dt = 0.5 s:

```
Step 1: slope = −5 / 2 = −2.5 V/s
        V = 5 + (−2.5)(0.5) = 3.75 V      at t = 0.5 s
Step 2: slope = −3.75 / 2 = −1.875 V/s
        V = 3.75 + (−1.875)(0.5) = 2.8125 V   at t = 1.0 s
```

The exact voltage at t = 0.5 s is 5 · e^(−0.25) ≈ 3.894 V, so Euler is already slightly low. That makes sense: the voltage falls fastest at the start of each step, and Euler uses that steepest slope for the whole step.

In Python, it is worth writing Euler's method as a general function that accepts *any* rate function `f`:

```python
import math

RC = 2.0    # time constant, seconds
V0 = 5.0    # starting voltage, volts

def dVdt(t, V):
    return -V / RC

def euler(f, y0, t_end, dt):
    """Step dy/dt = f(t, y) from t = 0 to t_end with Euler's method."""
    steps = round(t_end / dt)
    t, y = 0.0, y0
    for _ in range(steps):
        y = y + f(t, y) * dt
        t = t + dt
    return y

exact = V0 * math.exp(-4.0 / RC)
print(f"exact V(4) = {exact:.4f} V")
for dt in [0.5, 0.25, 0.125, 0.0625]:
    v = euler(dVdt, V0, 4.0, dt)
    print(f"dt = {dt:<6}  V(4) = {v:.4f} V   error = {v - exact:+.4f} V")
```

Output:

```
exact V(4) = 0.6767 V
dt = 0.5     V(4) = 0.5006 V   error = -0.1761 V
dt = 0.25    V(4) = 0.5903 V   error = -0.0863 V
dt = 0.125   V(4) = 0.6339 V   error = -0.0427 V
dt = 0.0625  V(4) = 0.6554 V   error = -0.0213 V
```

Two details in the code are worth copying. Passing the function `dVdt` as an argument means the same `euler` works for any equation. And computing the number of steps with `round(t_end / dt)` avoids a floating-point trap: adding 0.1 to itself repeatedly never lands *exactly* on a round number, so a loop like `while t < t_end` can take one step too many.

### How fast does the error shrink?

Look at the error column: each time dt halves, the error roughly halves. Euler's method is called **first order**: the error at a fixed end time is roughly proportional to dt. That is useful to know, but also a limitation. To get one more correct decimal place, you need ten times as many steps. More advanced methods, such as the Runge–Kutta family, have errors proportional to dt² or dt⁴, so they gain accuracy much faster as dt shrinks. Euler remains the right place to start, because every other method builds on the same idea.

### Systems with more than one state variable

A moving object needs at least two state variables: position and velocity. The rules form a **system**: the rate of change of position is the velocity, and the rate of change of velocity is the acceleration. Euler's method applies to each variable in the same step:

```python
G = 9.81  # m/s²

def derivatives(state):
    """Rates of change for a dropped object: (dy/dt, dv/dt)."""
    y, v = state          # distance fallen (m), downward speed (m/s)
    return (v, G)

def euler_step(state, dt):
    rates = derivatives(state)
    return tuple(s + r * dt for s, r in zip(state, rates))

state = (0.0, 0.0)
dt = 0.1
for _ in range(20):       # 20 steps of 0.1 s = 2.0 s
    state = euler_step(state, dt)

y, v = state
print(f"Euler: fallen {y:.3f} m, speed {v:.3f} m/s")
print(f"Exact: fallen {0.5 * G * 2.0**2:.3f} m, speed {G * 2.0:.3f} m/s")
```

Output:

```
Euler: fallen 18.639 m, speed 19.620 m/s
Exact: fallen 19.620 m, speed 19.620 m/s
```

The speed is exactly right, because acceleration is constant, so its tangent line *is* the true line. The distance is too small by 0.981 m. Each step moves the object using the speed it had at the **start** of the step, but the object is speeding up throughout the step. For constant acceleration you can show this error is g · t · dt / 2 = 9.81 × 2.0 × 0.1 / 2 = 0.981 m, exactly what we see.

This pattern, a `derivatives` function that returns the rate of change of every state variable and a general step function, is how larger simulations are organised. To simulate a different system you change only `derivatives`.

### Recap

- A **differential equation** dy/dt = f(t, y) describes how a quantity changes.
- **Euler's method**: y_next = y_now + f(t_now, y_now) · dt. It follows the tangent line for one step.
- Euler's method is **first order**: halving dt roughly halves the error.
- Compute the number of steps with `round(t_end / dt)` rather than accumulating floats until a target.
- For several state variables, compute all the rates from the current state, then update every variable.

#### Project: Euler by hand and by machine

Work with a pencil, paper, a calculator and Python.

1. By hand, apply Euler's method to the capacitor equation dV/dt = −V / 2, starting from V = 5 V, with dt = 1 s, for 4 steps. Write a table of t, slope and V.
2. Compute the exact values 5 · e^(−t/2) for t = 1, 2, 3, 4 and add them to your table.
3. Check your hand table with the `euler` function from this lesson.
4. Use `euler` on a new equation of your choice, for example Newton's cooling dT/dt = −0.1 (T − 20) from T = 90 °C, and show that halving dt roughly halves the error at t = 10 min. The exact solution is T = 20 + 70 · e^(−0.1t).

**Deliverables**

- A hand-worked table with Euler and exact values
- Python output confirming the hand table
- A table of error against dt for your second equation, with one sentence on the pattern

#### Check your understanding

1. With y = 10, dy/dt = −2y and dt = 0.1, what is y after one Euler step?
   A) 8
   B) 12
   C) 9.8
   D) 0

2. Euler's method gives an error of 0.04 at t = 4 s with dt = 0.2 s. Roughly what error do you expect with dt = 0.1 s?
   A) 0.04
   B) 0.01
   C) 0.08
   D) 0.02

3. Why did the Euler simulation of a dropped object underestimate the distance fallen?
   A) Because g was rounded
   B) Because each step used the speed from the start of the step, while the object kept speeding up during it
   C) Because Python tuples lose precision
   D) Because the speed was wrong

4. Why compute the number of steps as round(t_end / dt) instead of looping while t < t_end?
   A) round makes the simulation run faster
   B) It is required by Python
   C) Repeatedly adding a float like 0.1 may not land exactly on t_end, so the while loop could take an extra step
   D) It makes Euler's method second order

**Go further:**

- Euler method — Wikipedia: https://en.wikipedia.org/wiki/Euler_method — The geometric picture, error analysis and a worked example of Euler's method.


## 4.3 Simulating a falling object with air drag

*Add air resistance to a falling-object simulation, discover terminal velocity, and verify the simulation against an exact solution.* (about 30 min)

### Why drag matters

Without air, every object falls with the same acceleration, and a feather and a hammer dropped together land together. That really happens on the Moon. On Earth, air pushes back on anything moving through it, and for light objects that push is large. Engineers need to model drag to predict how a parachute slows a payload, how fast a drone loses height when its rotors stop, or how far a part flies when it is thrown off a conveyor. Drag also shows why simulation is so useful: once drag is included, the simple algebra formulas for falling objects no longer apply.

### The forces

Take a ball falling straight down, and measure distance and speed downward. Two forces act on it:

- **Weight**, m · g, pulling down.
- **Drag**, pushing up (opposite to the motion). At everyday speeds, for objects larger than a few millimetres, drag is well described by

```
F_drag = ½ · ρ · C_d · A · v²
```

where ρ (rho) is the air density (about 1.2 kg/m³ at room conditions), A is the cross-sectional area facing the airflow, v is the speed and C_d is the **drag coefficient**, a number that captures how streamlined the shape is. A smooth sphere has C_d of roughly 0.47 over a wide range of speeds; a streamlined shape is much lower.

The important feature is v²: double the speed, and drag quadruples.

From Newton's second law, the acceleration is the net force divided by mass:

```
a = g − (½ ρ C_d A v²) / m
```

### Terminal velocity, without a simulation

As the ball speeds up, drag grows until it equals the weight. Then the net force is zero, acceleration stops, and the speed stays constant. This is the **terminal velocity**. Set drag equal to weight and solve for v:

```
½ ρ C_d A v_t² = m g
v_t = √( 2 m g / (ρ C_d A) )
```

For a table-tennis ball (mass 2.7 g, diameter 40 mm):

```
A   = π × 0.020² ≈ 0.001257 m²
v_t = √( 2 × 0.0027 × 9.81 / (1.2 × 0.47 × 0.001257) )
    ≈ √74.7 ≈ 8.65 m/s
```

A table-tennis ball can never fall faster than about 8.65 m/s in still air, however high you drop it from. A solid steel ball the same size weighs about 260 g, roughly 100 times more, so its terminal speed is about √100 = 10 times higher and drag barely matters over a short drop.

### Simulating the drop

How long does the ball take to fall 10 m, and how fast is it going when it lands? There is no simple algebra formula for the time, so we simulate:

```python
import math

G = 9.81          # m/s²
RHO = 1.2         # air density, kg/m³ (room conditions, assumed)
CD = 0.47         # drag coefficient of a smooth sphere (typical value)
MASS = 0.0027     # kg, a table-tennis ball
DIAMETER = 0.040  # m
AREA = math.pi * (DIAMETER / 2) ** 2

def acceleration(v):
    """Downward acceleration: gravity minus drag (v is downward speed)."""
    drag = 0.5 * RHO * CD * AREA * v * v     # newtons, opposes motion
    return G - drag / MASS

def drop(height, dt):
    """Return (time, impact speed) for a ball dropped from rest."""
    t, y, v = 0.0, 0.0, 0.0                  # y = distance fallen
    while y < height:
        a = acceleration(v)
        y = y + v * dt
        v = v + a * dt
        t = t + dt
    return t, v

v_terminal = math.sqrt(2 * MASS * G / (RHO * CD * AREA))
print(f"terminal speed: {v_terminal:.2f} m/s")

t, v = drop(10.0, 0.001)
print(f"with drag:    lands after {t:.2f} s at {v:.2f} m/s")
t0 = math.sqrt(2 * 10.0 / G)
print(f"without drag: lands after {t0:.2f} s at {G * t0:.2f} m/s")
```

Output:

```
terminal speed: 8.65 m/s
with drag:    lands after 1.75 s at 8.33 m/s
without drag: lands after 1.43 s at 14.01 m/s
```

Drag adds about 0.3 s to the fall and cuts the landing speed from 14 m/s to 8.3 m/s, already close to terminal velocity. For a light object, ignoring drag is not a small approximation; it is wrong by a factor of about 1.7 in speed.

Notice the structure: the physics lives in `acceleration(v)`, and `drop` is the same Euler loop you have seen before. Here the loop runs until a *condition* is met (y reaches the ground) rather than for a fixed time. The final step overshoots the ground slightly, by less than v · dt ≈ 8 mm, which is negligible with dt = 0.001 s.

### Verifying against an exact solution

For this particular case, a ball dropped from rest with v² drag, calculus does give an exact formula for the speed:

```
v(t) = v_t · tanh(g t / v_t)
```

where tanh is the *hyperbolic tangent*, a function that rises smoothly from 0 towards 1. You do not need to derive it to use it as a check. Python provides it as `math.tanh`.

```python
import math

G, RHO, CD, MASS = 9.81, 1.2, 0.47, 0.0027
AREA = math.pi * 0.020 ** 2
C = 0.5 * RHO * CD * AREA                # drag constant, kg/m
VT = math.sqrt(MASS * G / C)              # terminal speed

dt = 0.01
v = 0.0
print("  t (s)   Euler v   exact v   (m/s)")
for step in range(1, 301):                # 3 seconds
    v = v + (G - C * v * v / MASS) * dt
    if step % 50 == 0:
        t = step * dt
        exact = VT * math.tanh(G * t / VT)
        print(f"  {t:4.1f}   {v:7.3f}   {exact:7.3f}")
```

Output:

```
  t (s)   Euler v   exact v   (m/s)
   0.5     4.450     4.439
   1.0     7.044     7.025
   1.5     8.102     8.089
   2.0     8.469     8.463
   2.5     8.589     8.586
   3.0     8.628     8.626
```

Even with a coarser step of 0.01 s, Euler agrees with the exact speed to within about 0.02 m/s, and both approach 8.65 m/s. The simulation is **verified** for this case. Now we can trust it for cases with no exact formula: a ball thrown downward, or upward, or sideways, or an object whose drag coefficient changes as a parachute opens.

### Assumptions to keep in mind

This model assumes still air, constant air density, a constant drag coefficient, and an object that does not spin or tumble. Each can fail: wind adds sideways forces, density falls with altitude, C_d varies with speed and surface roughness, and spinning balls curve. **Validating** the model means dropping real objects and comparing, which is exactly what the project below asks you to do.

### Recap

- Drag at everyday speeds is F = ½ ρ C_d A v²; it grows with the square of speed.
- **Terminal velocity** is reached when drag equals weight: v_t = √(2mg / (ρ C_d A)).
- Light objects with large areas have low terminal speeds and are strongly affected by drag.
- Put the physics in an `acceleration` function and reuse the Euler loop.
- Verify against the exact tanh solution, then use the simulation for cases with no formula.

#### Project: Validate a drag model with paper cupcake cases

Paper cupcake cases (or coffee filters) fall slowly and stack neatly, so you can change the mass without changing the shape.

1. Measure a fixed drop height of about 1.5–2 m against a wall. Drop from an outstretched arm while standing on the floor; do not stand on chairs or tables.
2. Drop 1, 2, 4 and 8 stacked cases, timing each fall five times with a phone stopwatch. Record every time and compute the mean and standard error for each stack.
3. Weigh a stack of cases on a kitchen scale (or estimate from a packet), measure the diameter, and assume C_d ≈ 1.0 as a starting guess for this shape.
4. Simulate each drop in Python and compare with your measurements. Adjust C_d to fit one stack, then check whether the same C_d predicts the others.
5. Write down every assumption you made and where the model disagrees with reality.

**Deliverables**

- A table of measured fall times (mean ± SE, n = 5) for each stack
- A Python simulation with predicted fall times for each stack
- A short validation note: the fitted C_d, how well it predicts the other stacks, and the main sources of disagreement

#### Check your understanding

1. If a ball's speed doubles, what happens to the quadratic drag force on it?
   A) It doubles
   B) It stays the same
   C) It halves
   D) It becomes four times larger

2. What condition defines terminal velocity for a falling object?
   A) The drag force equals the weight, so the net force and acceleration are zero
   B) The object has fallen for exactly one second
   C) The drag force is zero
   D) The speed equals g

3. Two spheres have the same size and shape, but one is 4 times heavier. How do their terminal speeds compare?
   A) The heavier one's is 4 times higher
   B) They are equal
   C) The heavier one's is 2 times higher
   D) The heavier one's is 16 times higher

4. Why compare the simulation with the formula v_t · tanh(g t / v_t)?
   A) To validate the model against reality
   B) To verify that the code solves the drag equation correctly, using a case with a known exact answer
   C) Because Euler's method needs tanh to work
   D) To find the drag coefficient

**Go further:**

- Terminal velocity — Wikipedia: https://en.wikipedia.org/wiki/Terminal_velocity — The derivation of terminal velocity and the exact tanh solution for a dropped object.
- Drag coefficient — Wikipedia: https://en.wikipedia.org/wiki/Drag_coefficient — Typical drag coefficients for spheres, cubes, cars and other shapes.


## 4.4 Simulating a spring–mass–damper system

*Simulate the classic model of anything that vibrates, see how damping changes its behaviour, and connect it to how a controlled robot joint responds.* (about 35 min)

### The most useful model in engineering

A car's suspension, a building in an earthquake, a guitar string, a robot gripper finger flexing as it closes, and a robot joint under a position controller all behave, at least approximately, like a **mass on a spring with a damper**. Learn this one system well and you have a model for a huge range of things that vibrate, overshoot or settle.

Picture a mass m sliding on a frictionless surface, attached to a wall by a spring and a damper side by side. x is how far the mass is from its resting position.

- The **spring** pulls the mass back towards rest with force −k · x, where k is the stiffness in N/m. The further you stretch it, the harder it pulls (Hooke's law).
- The **damper**, like a piston in oil, resists motion with force −c · v, where c is the damping coefficient in N·s/m. The faster the mass moves, the harder it resists.

Newton's second law gives the acceleration:

```
m · a = −k · x − c · v
a = (−k · x − c · v) / m
```

The state is position x and velocity v. The rates of change are v and a. That is everything a simulation needs.

### Two numbers describe the behaviour

Without damping, the mass oscillates forever at the **natural frequency**

```
ω_n = √(k / m)     (radians per second)
period T = 2π / ω_n
```

A stiffer spring or a lighter mass oscillates faster.

How quickly the oscillation dies away depends on the **damping ratio**

```
ζ = c / (2 · √(k · m))
```

(ζ is the Greek letter zeta.) The quantity 2√(km) is called **critical damping**. Three regimes follow:

- **ζ < 1, underdamped**: the mass overshoots and oscillates, with the swings shrinking each time.
- **ζ = 1, critically damped**: the mass returns to rest as fast as possible without overshooting.
- **ζ > 1, overdamped**: no overshoot, but the return is sluggish, as if moving through treacle.

For our example: m = 0.5 kg and k = 20 N/m, so ω_n = √40 ≈ 6.325 rad/s, the period is about 0.993 s, and critical damping is 2√10 ≈ 6.325 N·s/m.

### The simulation

We pull the mass 0.10 m from rest, let go, and simulate three damping ratios:

```python
import math

M = 0.5    # kg
K = 20.0   # N/m
C_CRIT = 2 * math.sqrt(K * M)   # critical damping, N·s/m

def simulate(c, x0=0.10, t_end=3.0, dt=0.0001, report_every=0.5):
    """Explicit Euler for m·x'' + c·x' + k·x = 0. Returns reported (t, x)."""
    x, v = x0, 0.0
    out = []
    steps = round(t_end / dt)
    every = round(report_every / dt)
    for step in range(1, steps + 1):
        a = (-K * x - c * v) / M
        x, v = x + v * dt, v + a * dt
        if step % every == 0:
            out.append((step * dt, x))
    return out

print(f"natural frequency: {math.sqrt(K / M):.3f} rad/s, "
      f"period {2 * math.pi / math.sqrt(K / M):.3f} s")
print(f"critical damping:  {C_CRIT:.3f} N·s/m")
for zeta in [0.1, 1.0, 2.0]:
    rows = simulate(zeta * C_CRIT)
    xs = "  ".join(f"{x * 1000:6.1f}" for _, x in rows)
    print(f"zeta = {zeta}: x (mm) at 0.5 s steps: {xs}")
```

Output:

```
natural frequency: 6.325 rad/s, period 0.993 s
critical damping:  6.325 N·s/m
zeta = 0.1: x (mm) at 0.5 s steps:  -73.0    53.3   -38.9    28.4   -20.7    15.1
zeta = 1.0: x (mm) at 0.5 s steps:   17.6     1.3     0.1     0.0     0.0     0.0
zeta = 2.0: x (mm) at 0.5 s steps:   46.2    19.8     8.5     3.6     1.6     0.7
```

The line `x, v = x + v * dt, v + a * dt` updates both variables at once from their **old** values, which is exactly Euler's method. We used a very small step, 0.0001 s, for a reason explained in the next lesson.

### Reading the results

Each column is half a second apart, which is almost exactly half a period (0.993 s / 2).

- **ζ = 0.1**: the sign flips every column, because each half period the mass swings to the other side. The swings shrink by a roughly constant factor (73.0 → 53.3 → 38.9 → …, about 0.73 each time). That constant ratio is the signature of an underdamped system. After 3 s the mass is still 15 mm from rest.
- **ζ = 1.0**: the mass is at 17.6 mm after 0.5 s and effectively at rest by 1.5 s, with no overshoot. This is the fastest return without crossing zero.
- **ζ = 2.0**: no overshoot, but after 3 s the mass is still 0.7 mm away. More damping is not always better.

**Verification.** This system has an exact solution too. For ζ = 0.1, the textbook formula gives −72.9, 53.2, −38.8, 28.3, −20.6 and 15.0 mm at the same times, and for ζ = 1 it gives 17.6, 1.3 and 0.1 mm. The simulation agrees within 0.1 mm. You can also check that the oscillation's period matches 2π / ω_n.

### Why robot engineers care: a joint under PD control

In Robotics Foundations you met proportional control. Add a **derivative** term and the controller's torque on a joint is

```
torque = Kp · (target − angle) − Kd · angular_velocity
```

Compare this with the spring and damper: the **proportional gain Kp acts like a spring** pulling the joint towards the target, and the **derivative gain Kd acts like a damper** resisting fast motion. The joint's inertia plays the role of the mass. So a PD-controlled joint behaves like a spring–mass–damper, and everything above applies:

- Too little Kd (low ζ): the arm overshoots the target and wobbles.
- ζ near 1: fast, clean arrival with little or no overshoot.
- Too much Kd (high ζ): sluggish movement.
- Raising Kp makes the joint "stiffer" and faster (higher ω_n), but for the same damping ratio Kd must rise too.

This is why simulation is a standard first step in controller tuning: you can try gains safely in software before running them on a real arm, then validate on the hardware.

### Recap

- A spring–mass–damper obeys m · a = −k · x − c · v. Its state is position and velocity.
- The **natural frequency** ω_n = √(k/m) sets how fast it oscillates.
- The **damping ratio** ζ = c / (2√(km)) sets whether it is underdamped (ζ < 1), critically damped (ζ = 1) or overdamped (ζ > 1).
- Verify the simulation against the exact solution or at least against the expected period.
- A PD-controlled joint behaves like this system, with Kp as the spring and Kd as the damper.

#### Project: Find the fastest settling damping

Using the simulation from this lesson, investigate how damping affects **settling time**: the time after which the mass stays within 2% of its starting displacement (here, within ±2 mm).

1. Write a function `settling_time(c)` that simulates the release from 0.10 m and returns the last time at which |x| exceeds 0.002 m.
2. Compute settling times for ζ = 0.1, 0.2, 0.3, …, 2.0 and print them in a table.
3. Which ζ settles fastest? (You may find it is a little below 1, because a small overshoot that stays inside the band can be acceptable.)
4. Double k and repeat. What happens to the best ζ, and to the best settling time?
5. Explain, in two or three sentences, what this suggests about tuning Kd for a PD-controlled joint.

**Deliverables**

- A settling_time function and a table of settling time against ζ
- The best ζ for both stiffness values
- A short explanation linking the result to PD controller tuning

#### Check your understanding

1. A mass of 2 kg hangs on a spring of stiffness 50 N/m. What is its natural frequency ω_n?
   A) 25 rad/s
   B) 5 rad/s
   C) 100 rad/s
   D) 0.2 rad/s

2. A system with ζ = 0.1 is released from rest away from its equilibrium. What will it do?
   A) Return slowly without overshoot
   B) Stay where it is
   C) Return as fast as possible without overshoot
   D) Overshoot and oscillate with gradually shrinking swings

3. For m = 0.5 kg and k = 20 N/m, what damping coefficient c gives critical damping?
   A) About 6.3 N·s/m
   B) 20 N·s/m
   C) 10 N·s/m
   D) 0.5 N·s/m

4. In a PD-controlled robot joint, which gain behaves most like the damper?
   A) The proportional gain Kp
   B) The joint's mass
   C) The derivative gain Kd
   D) The target angle

5. Why might ζ = 2 be a poor choice even though it never overshoots?
   A) It makes the system oscillate forever
   B) It returns to rest sluggishly, taking much longer to settle than a system near ζ = 1
   C) It is impossible to simulate
   D) It increases the natural frequency

**Go further:**

- Harmonic oscillator — Wikipedia: https://en.wikipedia.org/wiki/Harmonic_oscillator — The exact solutions for the underdamped, critically damped and overdamped cases.
- Damping — Wikipedia: https://en.wikipedia.org/wiki/Damping — The damping ratio and real examples of damping in engineering.


## 4.5 Numerical stability and choosing a step size

*See how a step that is too large can make a simulation blow up, understand why, fix oscillating systems with semi-implicit Euler, and learn a routine for choosing dt.* (about 30 min)

### When a simulation explodes

You simulate a robot arm, run it for ten seconds of virtual time, and the joint angle reads 10³⁰ radians. Nothing physical caused this. The numerical method itself became **unstable**: tiny errors grew a little every step until they swamped the answer. Instability is one of the most common ways simulations fail, and it can be subtle, starting as a slow drift that looks almost physical. This lesson explains where it comes from and how to avoid it.

### Accuracy and stability are different

- **Accuracy** is how close each answer is to the truth. Inaccurate results are a bit wrong.
- **Stability** is whether errors stay bounded as the simulation runs. Unstable results grow without limit and become meaningless.

A method can be stable but inaccurate (a coarse step that gets the shape roughly right) or, over a short run, accurate-looking but unstable (errors that are tiny now but doubling every few steps).

### The simplest test: exponential decay

Take dy/dt = −k · y with k = 10 per second. The true solution decays smoothly to zero. One Euler step gives

```
y_next = y + (−k · y) · dt = (1 − k · dt) · y
```

So each step multiplies y by the same **amplification factor**, 1 − k · dt. Everything depends on that factor:

```python
K_RATE = 10.0   # decay rate, per second: dy/dt = -10·y

for dt in [0.05, 0.15, 0.25]:
    y = 1.0
    values = []
    for _ in range(6):
        y = y + (-K_RATE * y) * dt      # one Euler step
        values.append(f"{y:8.3f}")
    print(f"dt = {dt:4.2f} (k·dt = {K_RATE * dt:.1f}):", " ".join(values))
```

Output:

```
dt = 0.05 (k·dt = 0.5):    0.500    0.250    0.125    0.062    0.031    0.016
dt = 0.15 (k·dt = 1.5):   -0.500    0.250   -0.125    0.062   -0.031    0.016
dt = 0.25 (k·dt = 2.5):   -1.500    2.250   -3.375    5.062   -7.594   11.391
```

- With k · dt = 0.5 the factor is 0.5: smooth decay, roughly right.
- With k · dt = 1.5 the factor is −0.5: the value still shrinks, but **flips sign** every step. The real system never goes negative, so this is badly inaccurate, though still stable.
- With k · dt = 2.5 the factor is −1.5: every step makes the value 1.5 times larger and flips its sign. **Unstable.** A decaying system has turned into an exploding one.

The rule: Euler's method on this equation is stable only if |1 − k · dt| ≤ 1, which means **dt ≤ 2 / k**, and it avoids sign flips only if dt ≤ 1 / k. The faster the system's own dynamics (the larger k), the smaller the step must be. Systems that mix very fast and very slow behaviour, called **stiff** systems, force a tiny step even when you only care about the slow part, which is why special methods exist for them.

### Oscillators: Euler always gains energy

Now take the spring–mass system from the previous lesson **without damping**. Its total energy, ½ m v² + ½ k x², should stay constant forever. With explicit Euler, one can show with a little algebra that every step multiplies the energy by exactly

```
1 + ω_n² · dt²
```

which is always greater than 1. With m = 0.5 kg, k = 20 N/m (ω_n² = 40) and dt = 0.01 s, the factor is 1.004 per step. That looks harmless, but over 1000 steps (10 s) it compounds to 1.004¹⁰⁰⁰ ≈ 54. **No step size makes explicit Euler stable for an undamped oscillator.** A smaller step only slows the growth. This is why the previous lesson needed dt = 0.0001 s.

### The fix: semi-implicit Euler

A tiny change to the order of updates makes a huge difference. Update the **velocity first**, then use the **new** velocity to update the position:

```python
M, K = 0.5, 20.0      # kg, N/m (no damping)
DT = 0.01             # s
STEPS = 1000          # 10 seconds

def energy(x, v):
    return 0.5 * M * v * v + 0.5 * K * x * x   # joules

def explicit_euler(x, v):
    a = -K * x / M
    return x + v * DT, v + a * DT          # both use OLD values

def semi_implicit_euler(x, v):
    a = -K * x / M
    v = v + a * DT                         # update velocity first...
    return x + v * DT, v                   # ...then position uses NEW v

for name, step in [("explicit", explicit_euler), ("semi-implicit", semi_implicit_euler)]:
    x, v = 0.10, 0.0
    e0 = energy(x, v)
    for _ in range(STEPS):
        x, v = step(x, v)
    print(f"{name:14s} energy after 10 s: {energy(x, v) / e0:7.3f} × start")
```

Output:

```
explicit       energy after 10 s:  54.164 × start
semi-implicit  energy after 10 s:   0.977 × start
```

Same equations, same step, same amount of work per step. Explicit Euler has inflated the energy 54-fold; semi-implicit Euler is within a few percent of the true value. If you keep running it, its energy wobbles slightly above and below the starting value (within about ±3.5% for this step) but never drifts away, even after thousands of seconds. This method, also called **symplectic Euler**, is stable for oscillators as long as ω_n · dt is below 2, and it is widely used in game physics and robotics simulators because it is as cheap as Euler but behaves far better for things that vibrate.

### Choosing a step size: a routine

There is no universal correct dt, but there is a reliable procedure:

1. **Find the fastest timescale** in the system: the shortest period of oscillation (2π / ω_n), or the shortest time constant (1 / k). Start with dt well below it, for example a twentieth or less.
2. **Check stability limits** for your method, such as dt ≤ 2 / k for Euler on decay or ω_n · dt below 2 for semi-implicit Euler on an oscillator. Stay well inside them.
3. **Run a convergence test**: halve dt and rerun. If the quantity you care about changes by less than your tolerance, the step is small enough. If not, halve again.
4. **Watch a conserved quantity** such as energy where one exists. Steady growth in a system that should conserve energy is a warning sign.
5. **Record the dt you used** and the result of your convergence test alongside any results you report.

### Recap

- **Accuracy** is closeness to the truth; **stability** is whether errors stay bounded.
- On dy/dt = −k · y, Euler multiplies y by (1 − k · dt) each step and is stable only for dt ≤ 2 / k.
- On an undamped oscillator, explicit Euler multiplies energy by (1 + ω_n² dt²) every step, so it is never stable.
- **Semi-implicit Euler** (velocity first, then position with the new velocity) keeps an oscillator's energy bounded at the same cost.
- Choose dt from the fastest timescale, respect stability limits, and confirm with a convergence test.

> **Instability can look like physics.** A slowly growing oscillation in a simulated arm might look like a real resonance. Before you believe a surprising result, halve the step size. If the surprise changes or disappears, it was the numerical method, not the physics.

#### Check your understanding

1. For dy/dt = −20 · y, what is the largest step for which explicit Euler is stable?
   A) 0.2 s
   B) 0.05 s
   C) 0.1 s
   D) 2 s

2. Euler on a decay equation gives values 1, −0.5, 0.25, −0.125, … What does this show?
   A) The system is physically oscillating
   B) The simulation is unstable
   C) The step size is perfect
   D) The method is stable but the step is too large to be accurate, since the true solution never changes sign

3. What is the only difference between explicit and semi-implicit Euler in this lesson?
   A) Semi-implicit Euler updates velocity first, then updates position using the new velocity
   B) Semi-implicit Euler uses a smaller time step
   C) Semi-implicit Euler ignores the spring force
   D) Semi-implicit Euler runs the loop backwards

4. You halve dt and an important result changes by 30%. What should you do?
   A) Report the result from the larger step
   B) Keep halving dt until the result stops changing by more than your tolerance
   C) Average the two results and report that
   D) Conclude the physics is chaotic

**Go further:**

- Semi-implicit Euler method — Wikipedia: https://en.wikipedia.org/wiki/Semi-implicit_Euler_method — The method's update rule, its energy behaviour and why it suits oscillating systems.
- Euler method — Wikipedia: https://en.wikipedia.org/wiki/Euler_method — Includes a section on numerical stability using a similar exponential-decay example.


## 4.6 Monte Carlo simulation and randomness

*Use random numbers to estimate π, see how the error shrinks with more samples, and propagate measurement uncertainty through a calculation or a whole simulation.* (about 30 min)

### Answers from randomness

So far, every simulation in this module has been **deterministic**: the same inputs always give the same output. But real engineering inputs are rarely known exactly. A part's length has a tolerance. A drag coefficient is an estimate. A sensor reading has noise. Engineers want to know: *given that the inputs are uncertain, how uncertain is the answer?*

**Monte Carlo simulation** answers this by brute force. Draw random inputs that match what you know about the uncertainty, run the calculation, repeat thousands of times, and look at the spread of the outputs. The name comes from the famous casino in Monaco, a nod to the role of chance. The method needs no advanced mathematics, works on almost any model, and is used everywhere from reliability engineering to robot motion planning.

### A first example: estimating π

Imagine a square of side 1 with a quarter circle of radius 1 drawn inside it, centred on one corner. The quarter circle's area is π/4; the square's is 1. Scatter points uniformly at random over the square. The fraction landing inside the quarter circle should be about π/4, so

```
π ≈ 4 × (points inside) / (total points)
```

A point (x, y) is inside if x² + y² ≤ 1.

```python
import math
import random

random.seed(2024)

def estimate_pi(n):
    inside = 0
    for _ in range(n):
        x, y = random.random(), random.random()
        if x * x + y * y <= 1.0:
            inside += 1
    return 4 * inside / n

for n in [100, 10_000, 1_000_000]:
    est = estimate_pi(n)
    print(f"N = {n:>9,}   estimate = {est:.5f}   error = {est - math.pi:+.5f}")
```

Output:

```
N =       100   estimate = 3.32000   error = +0.17841
N =    10,000   estimate = 3.11520   error = -0.02639
N = 1,000,000   estimate = 3.14267   error = +0.00108
```

`random.random()` returns a number between 0 and 1. `random.seed(2024)` makes the sequence repeatable: anyone running this code gets exactly these numbers. Computers produce **pseudo-random** numbers from a formula, which look random for practical purposes but are fully determined by the seed. That is a feature: a Monte Carlo result you cannot reproduce is hard to check.

### How fast does the error shrink?

Each point is like a coin flip that lands "inside" with probability π/4. The same √n law from the measurement uncertainty lesson applies: the typical error is about √(π(4 − π) / N) ≈ 1.64 / √N. That predicts about 0.16 for N = 100, 0.016 for N = 10,000 and 0.0016 for N = 1,000,000, consistent with the errors above. **Each extra correct digit costs 100 times more samples.** Monte Carlo is a poor way to compute π precisely, but the same 1/√N behaviour holds no matter how complicated the model is, and that is where Monte Carlo shines.

### Propagating measurement uncertainty

A pendulum's period T and length L give the local gravitational acceleration:

```
g = 4π² L / T²
```

Suppose you measured (**made-up values for illustration**) L = 1.000 m with an uncertainty of 0.005 m, and T = 2.006 s with an uncertainty of 0.010 s, where each uncertainty is one standard deviation. How uncertain is g?

```python
import math
import random
import statistics

random.seed(7)
# Made-up measurements for illustration: a simple pendulum
L_MEAN, L_SD = 1.000, 0.005   # length, m
T_MEAN, T_SD = 2.006, 0.010   # period, s

samples = []
for _ in range(100_000):
    L = random.gauss(L_MEAN, L_SD)
    T = random.gauss(T_MEAN, T_SD)
    samples.append(4 * math.pi**2 * L / T**2)

g_mean = statistics.mean(samples)
g_sd = statistics.stdev(samples)
print(f"g = {g_mean:.3f} ± {g_sd:.3f} m/s² (Monte Carlo, 100,000 samples)")

# Compare with the usual first-order formula for relative uncertainty
g0 = 4 * math.pi**2 * L_MEAN / T_MEAN**2
rel = math.sqrt((L_SD / L_MEAN) ** 2 + (2 * T_SD / T_MEAN) ** 2)
print(f"g = {g0:.3f} ± {g0 * rel:.3f} m/s² (formula)")
```

Output:

```
g = 9.811 ± 0.109 m/s² (Monte Carlo, 100,000 samples)
g = 9.811 ± 0.109 m/s² (formula)
```

`random.gauss(mean, sd)` draws from a normal (bell-shaped) distribution. The Monte Carlo answer matches the standard **propagation of uncertainty** formula, which adds relative uncertainties in quadrature, counting T twice because it is squared. Notice that the period's 0.5% uncertainty contributes a 1% uncertainty to g, twice the length's contribution. That tells you where to spend effort: time more swings.

When the formula applies, it is quicker. Monte Carlo's advantage is that it still works when the formula does not: when uncertainties are large, when the calculation is a whole simulation, or when you want the full spread of outcomes rather than one number.

### Uncertainty through a whole simulation

In the drag lesson we assumed a table-tennis ball has C_d = 0.47. Suppose (an **assumption for illustration**) we only know C_d to about ±0.05, as one standard deviation. How uncertain is the landing time from 10 m? There is no formula for it, but we can run the drag simulation a thousand times:

```python
import math
import random
import statistics

random.seed(5)
G, RHO, MASS = 9.81, 1.2, 0.0027
AREA = math.pi * 0.020 ** 2

def drop_time(cd, height=10.0, dt=0.001):
    t, y, v = 0.0, 0.0, 0.0
    while y < height:
        a = G - 0.5 * RHO * cd * AREA * v * v / MASS
        y, v, t = y + v * dt, v + a * dt, t + dt
    return t

# Assumption for illustration: Cd is 0.47 give or take 0.05 (one sd)
times = [drop_time(random.gauss(0.47, 0.05)) for _ in range(1000)]
times.sort()
print(f"mean landing time: {statistics.mean(times):.3f} s")
print(f"sd:                {statistics.stdev(times):.3f} s")
print(f"middle 95%:        {times[25]:.3f} s to {times[974]:.3f} s")
```

Output:

```
mean landing time: 1.751 s
sd:                0.035 s
middle 95%:        1.679 s to 1.822 s
```

After sorting, the 26th and 975th values bracket the middle 95% of the 1000 outcomes. So a fair statement is: "assuming C_d = 0.47 ± 0.05, the simulated landing time is about 1.75 s, with 95% of simulated outcomes between 1.68 and 1.82 s." That is far more useful than a single number, because it says how much to trust the prediction.

### Recap

- **Monte Carlo** methods estimate answers by repeating a calculation with random inputs and studying the outputs.
- Random-number generators are **pseudo-random**; set a **seed** so results can be reproduced.
- The error of a Monte Carlo estimate shrinks as **1/√N**: 100 times more samples for each extra digit.
- To **propagate uncertainty**, draw each uncertain input from its distribution, compute the result, and report the spread.
- Monte Carlo works even when there is no formula, including through a whole simulation.

> **Report how the randomness was set up.** With any Monte Carlo result, state the number of samples, the distributions you assumed for each input and why, and the random seed. Running many seeds and reporting only the one that gives the most convenient answer is cherry-picking, just as it would be with real measurements.

#### Check your understanding

1. In the π estimate, 7,850 of 10,000 random points land inside the quarter circle. What is the estimate of π?
   A) 3.14
   B) 0.785
   C) 7.85
   D) Exactly π

2. A Monte Carlo estimate has a typical error of 0.02 with 10,000 samples. About how many samples are needed for an error of 0.002?
   A) 100,000
   B) 20,000
   C) 1,000,000
   D) 10,000,000,000

3. Why set a random seed in a Monte Carlo program?
   A) It makes the numbers truly random
   B) It makes the result more accurate
   C) It is needed for random.gauss to work
   D) It makes the results reproducible, so others can check them exactly

4. In g = 4π²L/T², why did the 0.5% uncertainty in T matter more than the 0.5% uncertainty in L?
   A) Because T is measured in seconds
   B) Because T is squared, so its relative uncertainty counts twice
   C) Because Monte Carlo favours the last variable
   D) Because L is always measured more accurately

5. What is the main advantage of Monte Carlo over the propagation-of-uncertainty formula?
   A) It works even when there is no simple formula, such as for the output of a whole simulation
   B) It is always faster
   C) It needs no assumptions about the inputs
   D) It gives exact answers

**Go further:**

- Monte Carlo method — Wikipedia: https://en.wikipedia.org/wiki/Monte_Carlo_method — History of the method, the π example and its many uses in engineering and science.
- Propagation of uncertainty — Wikipedia: https://en.wikipedia.org/wiki/Propagation_of_uncertainty — The formulas for combining uncertainties, including the power rule used for the pendulum.
- Python documentation — random module: https://docs.python.org/3/library/random.html — Official reference for random.seed, random.random, random.gauss and reproducibility.


---

# Module 5: Introduction to computer vision

How a computer represents images as numbers and finds simple features such as colours, edges and objects in them.

**Objectives**

- Describe a digital image as a grid of pixel values in one or more colour channels.
- Apply thresholding to separate an object from its background.
- Explain how an edge detector responds to changes in brightness.
- Identify common reasons vision systems fail, such as lighting changes and occlusion.


## 5.1 Images as arrays of numbers

*A digital image is a grid of numbers. Learn how pixels, channels and resolution work by building and inspecting tiny images as Python lists.* (about 35 min)

### Why a robot needs to see numbers

When you look at a photo of a mug on a table, you see a mug. A robot that has to pick up that mug sees nothing of the kind. Its camera hands the computer a long list of numbers, one or more for every tiny square of the picture, and nothing else. Every skill a vision system has, from following a line on the floor to finding a part on a conveyor, comes from doing arithmetic on those numbers.

So the first step in computer vision is to stop thinking of an image as a picture and start thinking of it as **data**. Once you do, the tools from the Python and algorithms modules apply directly: loops, lists, functions and careful counting.

### Pixels and the grid

A digital image is divided into a rectangular grid of **pixels** (short for "picture elements"). In a **greyscale** image, each pixel holds one number for its brightness. The most common convention uses whole numbers from 0 (black) to 255 (white), because that range fits exactly in one **byte** (8 bits, 2⁸ = 256 possible values).

In Python, using only the standard library, a small greyscale image can be a **list of lists**: a list of rows, where each row is a list of pixel values.

```python
image = [
    [ 10,  10,  10,  10,  10],
    [ 10, 200, 200, 200,  10],
    [ 10, 200, 255, 200,  10],
    [ 10, 200, 200, 200,  10],
    [ 10,  10,  10,  10,  10],
]

height = len(image)        # number of rows
width = len(image[0])      # number of columns
print(f"{width} x {height} pixels")
print(image[2][2])         # row 2, column 2: the centre
print(image[0][4])         # top-right corner
```

Output:

```
5 x 5 pixels
255
10
```

This tiny image is a bright square with a white centre on a dark background. Two conventions matter, and mixing them up is one of the most common bugs in vision code:

- Pixels are indexed **row first, then column**: `image[row][col]`. In terms of x and y, that is `image[y][x]`, which feels backwards at first.
- Row 0 is the **top** of the image, and rows count downwards. This is the opposite of the y-axis you draw in maths lessons, where y increases upwards.

### Looking at the numbers

It helps to draw an image as text so you can check what your code is doing. The function below maps each brightness to a character, from `.` for dark to `@` for bright, and prints each character twice so the pixels look roughly square.

```python
def show(img):
    shades = ".:-=+*#%@"            # dark to bright
    for row in img:
        line = ""
        for value in row:
            line += shades[value * (len(shades) - 1) // 255] * 2
        print(line)

show(image)

total = 0
for row in image:
    total += sum(row)
pixels = len(image) * len(image[0])
print(f"Mean brightness: {total / pixels:.1f}")

negative = [[255 - v for v in row] for row in image]
print(negative[2])
```

Output:

```
..........
..######..
..##@@##..
..######..
..........
Mean brightness: 80.6
[245, 55, 0, 55, 245]
```

The mean brightness is simple arithmetic: 16 dark pixels at 10, 8 pixels at 200 and one at 255 give 2015 ÷ 25 = 80.6. Measuring the mean brightness of an image is a real technique: a camera's automatic exposure does something similar to decide whether a scene is too dark. The **negative** subtracts every value from 255, so dark becomes bright. Notice how naturally a single operation applies to every pixel with a list comprehension.

### Colour: three channels

A colour image stores **three** numbers per pixel, usually red, green and blue (**RGB**), each from 0 to 255. Each of those is called a **channel**. Mixing them at different strengths reproduces most colours a screen can show: (255, 0, 0) is pure red, (255, 255, 255) is white and (255, 140, 0) is orange. In Python, a colour pixel can be a tuple, and a colour image is a list of rows of tuples.

Many vision algorithms only need brightness, so a common first step converts colour to greyscale. A plain average of the three channels would work, but human eyes are much more sensitive to green than to blue, so a widely used formula weights the channels:

```python
orange = (255, 140, 0)    # (red, green, blue)

def to_grey(rgb):
    r, g, b = rgb
    return round(0.299 * r + 0.587 * g + 0.114 * b)

print(to_grey(orange))
print(to_grey((255, 0, 0)), to_grey((0, 255, 0)), to_grey((0, 0, 255)))

width, height, channels = 640, 480, 3
size_bytes = width * height * channels
print(f"{size_bytes} bytes per frame")
print(f"{size_bytes * 30 / 1e6:.1f} MB per second at 30 frames per second")
```

Output:

```
158
76 150 29
921600 bytes per frame
27.6 MB per second at 30 frames per second
```

Pure green looks about five times brighter than pure blue after conversion, which matches how they appear to people. The last two lines are an engineering estimate worth remembering: even a modest 640 × 480 colour camera produces nearly a million numbers per frame, and almost 28 megabytes every second at 30 frames per second. That is why robots often shrink images, convert them to greyscale or process only a region of interest before doing anything clever.

### Resolution

**Resolution** is the number of pixels in the grid, such as 640 × 480. More pixels capture finer detail, but cost more memory and processing time. Reducing resolution is often a sensible choice. Here is a function that halves resolution by averaging each 2 × 2 block of pixels:

```python
image = [
    [ 10,  20,  30,  40],
    [ 50,  60,  70,  80],
    [ 90, 100, 110, 120],
    [130, 140, 150, 160],
]

def downsample(img):
    """Halve the resolution by averaging each 2 x 2 block."""
    small = []
    for r in range(0, len(img), 2):
        row = []
        for c in range(0, len(img[0]), 2):
            block = img[r][c] + img[r][c + 1] + img[r + 1][c] + img[r + 1][c + 1]
            row.append(block // 4)
        small.append(row)
    return small

print(downsample(image))
```

Output:

```
[[35, 55], [115, 135]]
```

The top-left block holds 10, 20, 50 and 60, which average to 35. The new image has a quarter of the pixels, so later steps run about four times faster, but any detail smaller than two pixels is gone for good. Choosing a resolution is a trade-off between detail and speed, and the right answer depends on how small the things you need to see are.

### Recap

- A digital image is a grid of pixels, indexed `image[row][col]`, with row 0 at the top.
- Greyscale pixels usually hold one byte, 0 to 255; colour pixels hold three channels, often RGB.
- Converting to greyscale and reducing resolution are common first steps that trade detail for speed.
- Every vision technique in this module is arithmetic on these numbers.

> **Going further with libraries.** Real projects store images in libraries such as NumPy (fast arrays) and OpenCV (a large computer vision library), which must be installed separately. They are far faster than lists of lists, but they use the same ideas: rows, columns, channels and 0–255 values. One surprise to know about: OpenCV stores colour channels in **BGR** order (blue first) rather than RGB. The plain Python in this module lets you see every step before you hand the work to a library.

#### Project: Programming project: draw and measure your initials

Using Python 3 and only the standard library:

1. Create a greyscale image as a list of lists, at least 12 columns by 8 rows, that spells one of your initials in bright pixels (around 220) on a dark background (around 20).
2. Print it with the `show` function from this lesson and check it looks right.
3. Write a function that returns the mean brightness, and another that returns the number of pixels brighter than 128.
4. Downsample your image once with the `downsample` function (make the width and height even first). Print the result. Can you still read the letter? Write two sentences on what was lost.

**Deliverables**

- A Python file with your image and at least two functions of your own
- Printed output of the original and downsampled images
- Two or three sentences on the detail-versus-speed trade-off

#### Check your understanding

1. In a list-of-lists image, what does image[3][7] refer to?
   A) The pixel at x = 3, y = 7
   B) The pixel in row 3, column 7
   C) The 37th pixel in the image
   D) The brightness of channel 3 at pixel 7

2. Why do many greyscale images use values from 0 to 255?
   A) Cameras cannot detect more than 255 brightness levels
   B) 255 is the number of pixels in a row
   C) One byte holds 2⁸ = 256 different values, numbered 0 to 255
   D) Human eyes can see exactly 256 shades

3. How many numbers does a 320 × 240 RGB image contain?
   A) 76,800
   B) 230,400
   C) 960
   D) 25,600

4. Pure green (0, 255, 0) converts to a much brighter grey than pure blue (0, 0, 255). Why?
   A) The weighted formula gives green a large weight because human eyes are more sensitive to green
   B) Green pixels are physically larger on the sensor
   C) Blue light is always filtered out by the camera
   D) It is a rounding error

5. You halve an image's width and height. Which statement is true?
   A) Processing takes about half as long, and no detail is lost
   B) The image has half the pixels and twice the detail
   C) Nothing changes except the file name
   D) The image has a quarter of the pixels, so it is faster, but detail smaller than about two original pixels is lost

**Go further:**

- Digital image (Wikipedia): https://en.wikipedia.org/wiki/Digital_image — An overview of raster images, pixels and how digital images are stored.


## 5.2 Colour spaces and thresholding

*Separate an object from its background by brightness or by colour, and see why hue, saturation and value often work better than raw red, green and blue.* (about 35 min)

### Why segmentation comes first

Suppose a robot must pick up a red block from a grey table. Before it can work out where the block is, it must decide which pixels belong to the block and which belong to the table. That job is called **segmentation**, and the simplest way to do it is **thresholding**: compare every pixel with a cut-off value and keep the ones on one side.

Thresholding is crude, but it is fast, easy to understand and surprisingly useful in controlled settings such as a factory line with fixed lighting. It is also the clearest way to see a lesson that runs through all of computer vision: a method that works perfectly on one image can fail on the next because the lighting changed.

### Thresholding a greyscale image

Here is a small greyscale image of a bright object on a dark background. The function turns it into a **binary mask**: 1 where the pixel is brighter than the threshold, 0 elsewhere.

```python
image = [
    [ 30,  35,  32,  40,  38,  33],
    [ 36, 180, 190,  41,  37,  35],
    [ 31, 185, 200, 195,  39,  34],
    [ 38, 176, 188, 192,  42,  36],
    [ 33,  37,  40,  36,  35,  31],
]

def threshold(img, t):
    return [[1 if v > t else 0 for v in row] for row in img]

mask = threshold(image, 100)
for row in mask:
    print(" ".join(str(v) for v in row))
print("Object pixels:", sum(sum(row) for row in mask))
```

Output:

```
0 0 0 0 0 0
0 1 1 0 0 0
0 1 1 1 0 0
0 1 1 1 0 0
0 0 0 0 0 0
Object pixels: 8
```

The mask is far simpler than the image: every pixel is now a yes or a no. The next lessons build on masks like this one to find where objects are and how big they are.

### Choosing the threshold

Why 100? One good way to choose is to look at a **histogram**: a count of how many pixels fall into each range of brightness.

```python
values = [30, 35, 32, 40, 38, 33, 36, 180, 190, 41, 37, 35,
          31, 185, 200, 195, 39, 34, 38, 176, 188, 192, 42, 36,
          33, 37, 40, 36, 35, 31]

bins = [0] * 8                 # eight bins, each 32 levels wide
for v in values:
    bins[v // 32] += 1
for i, count in enumerate(bins):
    print(f"{i * 32:3d}-{i * 32 + 31:3d} {'#' * count}")
```

Output:

```
  0- 31 ###
 32- 63 ###################
 64- 95
 96-127
128-159
160-191 #####
192-223 ###
224-255
```

The background forms one clump on the left and the object forms another on the right, with an empty gap between. Any threshold in the gap, from about 64 to 159, separates them perfectly, and 100 sits safely in the middle. Real images are messier: the clumps overlap, and there is no perfect threshold. Methods exist to pick a threshold automatically from the histogram (Otsu's method is a well-known one), but the idea is the same: find the valley between two peaks.

### Why raw RGB struggles

Now consider colour. A red block on a table might give RGB values like (220, 40, 30) where it is lit, but only (90, 16, 12) on its shadowed side. A rule such as "red channel above 150" catches the lit side and misses the shadow completely, even though both are obviously the same red to a person. The trouble is that in RGB, **colour and brightness are tangled together**: when light dims, all three numbers fall at once.

### HSV: separating colour from brightness

The **HSV** colour space describes each colour with three different numbers:

- **Hue (H)**: which colour it is, as an angle around a colour wheel from 0° to 360°. Red is near 0°, green near 120°, blue near 240°, and the wheel wraps back to red at 360°.
- **Saturation (S)**: how strong or pure the colour is, from 0 (grey) to 1 (vivid).
- **Value (V)**: how bright it is, from 0 (black) to 1 (brightest).

Python's standard library includes `colorsys`, which converts between RGB and HSV using values from 0 to 1:

```python
import colorsys

def hsv(rgb):
    r, g, b = (v / 255 for v in rgb)
    h, s, v = colorsys.rgb_to_hsv(r, g, b)
    return round(h * 360), round(s, 2), round(v, 2)

red_in_light  = (220, 40, 30)
red_in_shadow = (90, 16, 12)
grey_card     = (120, 120, 120)

for name, px in [("red, lit", red_in_light),
                 ("red, shadow", red_in_shadow),
                 ("grey card", grey_card)]:
    print(f"{name:12s} RGB={px}  HSV={hsv(px)}")
```

Output:

```
red, lit     RGB=(220, 40, 30)  HSV=(3, 0.86, 0.86)
red, shadow  RGB=(90, 16, 12)  HSV=(3, 0.87, 0.35)
grey card    RGB=(120, 120, 120)  HSV=(0, 0.0, 0.47)
```

This is the key result. The lit and shadowed reds have **the same hue (3°) and nearly the same saturation**; only the value changed. The grey card's hue is meaningless (it prints 0), but its saturation of 0 tells you it has no colour at all.

### Segmenting by colour

A colour rule in HSV can now ignore brightness, within limits:

```python
import colorsys

def is_red(rgb):
    r, g, b = (v / 255 for v in rgb)
    h, s, v = colorsys.rgb_to_hsv(r, g, b)
    hue = h * 360
    red_hue = hue < 15 or hue > 345      # hue wraps around at 360°
    return red_hue and s > 0.5 and v > 0.2

pixels = [(220, 40, 30), (90, 16, 12), (120, 120, 120),
          (240, 200, 190), (200, 30, 60), (40, 8, 6)]
for px in pixels:
    print(px, is_red(px))
```

Output:

```
(220, 40, 30) True
(90, 16, 12) True
(120, 120, 120) False
(240, 200, 190) False
(200, 30, 60) True
(40, 8, 6) False
```

Each line of the rule has a reason. Red sits on both sides of 0°, so the hue test needs an **or** (the crimson (200, 30, 60) has a hue of about 349°). The saturation test rejects greys and pale pinks such as (240, 200, 190). The value test rejects pixels so dark that their hue is unreliable: (40, 8, 6) is technically reddish, but at that brightness a few units of sensor noise could swing its hue wildly. HSV does not make lighting problems disappear; it moves them into one number where you can deal with them.

### Recap

- Thresholding turns an image into a binary mask by comparing each pixel with a cut-off.
- A histogram shows where to put the threshold: in the valley between object and background.
- In RGB, a change in lighting changes all three channels; in HSV, it mainly changes value.
- Colour rules need care at the hue wrap-around and for very dark or very grey pixels.

> **Report the conditions, not just the threshold.** A threshold tuned on five photos taken at your desk may fail under a classroom's lights. When you report that a colour detector "works", say what lighting, camera and backgrounds you tested it on, and how many images. A result that only holds in one room is still useful, as long as you say so.

#### Check your understanding

1. A greyscale histogram has a peak around 40 and another around 190, with almost no pixels between 80 and 150. Which threshold is most sensible?
   A) 20
   B) 115
   C) 190
   D) 250

2. Why does a rule like "red channel above 150" often fail on shadowed parts of a red object?
   A) Shadows change the object's hue to blue
   B) The red channel only works outdoors
   C) Cameras cannot record red in shadows
   D) In RGB, dimmer light lowers all three channels, so a red surface in shadow can have a low red value

3. In HSV, which number changes most when the same surface moves from bright light into shadow?
   A) Hue
   B) Saturation
   C) Value
   D) None of them

4. Why does the red detector test hue < 15 OR hue > 345?
   A) Hue is measured around a circle, and red sits on both sides of 0°/360°
   B) To include green and blue as well
   C) Because colorsys returns negative hues
   D) It is a mistake; one test would be enough

5. What is the purpose of the saturation test (s > 0.5) in the red detector?
   A) It rejects very bright pixels
   B) It makes the code run faster
   C) It converts the image to greyscale
   D) It rejects greys and washed-out colours, whose hue is not meaningful

**Go further:**

- colorsys — Python documentation: https://docs.python.org/3/library/colorsys.html — The official reference for converting between RGB, HSV and other colour systems in the standard library.
- HSL and HSV (Wikipedia): https://en.wikipedia.org/wiki/HSL_and_HSV — How the HSV colour space is defined, with diagrams of the colour wheel.
- Thresholding (image processing) (Wikipedia): https://en.wikipedia.org/wiki/Thresholding_(image_processing) — Global and automatic thresholding methods, including Otsu's method.


## 5.3 Convolution and filters

*Slide a small grid of weights across an image to blur away noise or pick out edges, and work through both by hand and in Python.* (about 35 min)

### Why look at neighbourhoods

Thresholding looks at one pixel at a time. But a single pixel tells you very little: is that bright dot a real feature or a speck of sensor noise? Is this pixel part of an edge? To answer, you need to look at a pixel **together with its neighbours**. The tool for that is **convolution**, and it is the most important operation in image processing. Blurring, sharpening, edge detection and even the first layers of modern neural networks for vision are all built from it.

### The idea in one dimension

Start with a row of numbers, like one row of an image or a series of sensor readings:

```
signal = [10, 10, 10, 90, 10, 10, 50, 50, 50, 50]
```

The 90 looks like a spike of noise, and there is a genuine step up from 10 to 50 further along. A **kernel** is a short list of weights. To convolve, you place the kernel over each position, multiply each weight by the value beneath it, and add the results. With the kernel [1/3, 1/3, 1/3], each output is the average of a value and its two neighbours:

```python
signal = [10, 10, 10, 90, 10, 10, 50, 50, 50, 50]
kernel = [1/3, 1/3, 1/3]

smoothed = []
for i in range(1, len(signal) - 1):
    total = 0
    for k in range(3):
        total += kernel[k] * signal[i - 1 + k]
    smoothed.append(round(total, 1))
print(smoothed)
```

Output:

```
[10.0, 36.7, 36.7, 36.7, 23.3, 36.7, 50.0, 50.0]
```

Work through the second output by hand: the kernel covers 10, 10 and 90, so (10 + 10 + 90) ÷ 3 = 36.7. Two things happened. The spike has been flattened from 90 to about 37, which is good. But it has also been **spread out** over three positions, and the clean step from 10 to 50 has become a ramp. That is the fundamental trade-off of smoothing: it reduces noise and blurs real detail at the same time.

Notice also that the output is two values shorter than the input. At the very ends, the kernel would hang off the edge of the data. Code must decide what to do there: skip those positions (as here), pad with zeros, or repeat the edge values. Every image library makes a choice about borders, and it is worth knowing which.

### Two dimensions

For an image, the kernel becomes a small grid, usually 3 × 3. Place its centre over a pixel, multiply each of the nine weights by the pixel underneath, add the nine products, and write the total into the output image. Then slide one pixel along and repeat.

```python
def convolve(img, kernel):
    """Apply a 3 x 3 kernel to every interior pixel (borders are skipped)."""
    out = []
    for r in range(1, len(img) - 1):
        row = []
        for c in range(1, len(img[0]) - 1):
            total = 0
            for kr in range(3):
                for kc in range(3):
                    total += kernel[kr][kc] * img[r - 1 + kr][c - 1 + kc]
            row.append(round(total))
        out.append(row)
    return out
```

The test image below has a dark region on the left, a bright region on the right, and one noisy speck of 90 in the dark region.

```python
image = [
    [20, 20, 20, 200, 200, 200],
    [20, 20, 20, 200, 200, 200],
    [20, 90, 20, 200, 200, 200],
    [20, 20, 20, 200, 200, 200],
    [20, 20, 20, 200, 200, 200],
]
```

### Blur: the box filter

A **box filter** gives all nine weights the value 1/9, so each output pixel is the average of its 3 × 3 neighbourhood:

```python
box = [[1/9, 1/9, 1/9],
       [1/9, 1/9, 1/9],
       [1/9, 1/9, 1/9]]

for row in convolve(image, box):
    print(row)
```

Output:

```
[28, 88, 140, 200]
[28, 88, 140, 200]
[28, 88, 140, 200]
```

Check the first value by hand. The neighbourhood of row 1, column 1 holds eight 20s and the speck of 90: (8 × 20 + 90) ÷ 9 = 250 ÷ 9 ≈ 27.8, which rounds to 28. The speck has almost vanished. But look at the boundary: the sharp jump from 20 to 200 is now a gradual slope through 88 and 140. A **Gaussian blur**, which gives more weight to the centre than to the corners, is a popular gentler alternative that blurs edges a little less for the same noise reduction.

### Edges: the Sobel kernel

An **edge** is a place where brightness changes quickly. To find one, use a kernel whose weights **subtract** the left side from the right side. The well-known **Sobel** kernel for horizontal changes is:

```python
sobel_x = [[-1, 0, 1],
           [-2, 0, 2],
           [-1, 0, 1]]

for row in convolve(image, sobel_x):
    print(row)
```

Output:

```
[0, 650, 720, 0]
[0, 580, 720, 0]
[0, 650, 720, 0]
```

In flat regions, the left and right columns match, so the negative and positive weights cancel and the output is 0. Where the window straddles the boundary, the right column is bright and the left is dark. Over pure background either side of the edge, the response is (1 + 2 + 1) × (200 − 20) = 4 × 180 = 720. The weights sum to zero, which is why a uniform region gives exactly zero, however bright it is.

Now notice what the speck did. The second column should read 720 all the way down, like the third, but it reads 650, 580, 650. The speck of 90 sits in the left column of those windows and is subtracted, weakening the edge. **Edge detectors amplify differences, and noise is made of differences**, so edge kernels are very sensitive to noise. That is why practical edge detection usually **blurs first, then differentiates**.

A vertical version of the kernel (the same numbers, turned on its side) finds changes from top to bottom. Combining the two responses, gx and gy, as √(gx² + gy²) gives the edge strength in any direction.

### Recap

- Convolution slides a kernel over the data, multiplying and adding at each position.
- A box or Gaussian kernel averages neighbours: it reduces noise but blurs real edges.
- A Sobel kernel subtracts one side from the other: it responds strongly to edges and gives zero on flat regions.
- Edge detectors are sensitive to noise, so blur first; and always know how your code handles the borders.

> **Convolution or correlation?.** Strictly, mathematical convolution flips the kernel before sliding it, and the unflipped version is called **correlation**. For symmetric kernels such as the box filter, the two give identical results. For the Sobel kernel, flipping just changes the sign of the output. Many image libraries actually compute correlation, though everyone calls it convolution. If your edge comes out negative when you expected positive, this is a likely reason.

#### Project: Paper and Python project: filters by hand

1. On squared paper, draw a 6 × 6 greyscale image with a dark square in the middle of a bright background. Write a number in every cell.
2. By hand, apply the 3 × 3 box filter to at least four interior pixels, including two that sit on the square's edge. Show your working.
3. Apply the Sobel kernel to the same four pixels by hand.
4. Type your image into Python and use the `convolve` function to check your answers. If any differ, find out why.
5. Add one noisy pixel and compare the Sobel output with and without blurring first. Describe what you see in two or three sentences.

**Deliverables**

- Hand calculations for four pixels with both kernels
- Python output that confirms (or corrects) your hand results
- A short comparison of edge detection with and without blurring first

#### Check your understanding

1. A 3 × 3 box filter is applied to a neighbourhood of eight pixels at 50 and one at 140. What is the output?
   A) 50
   B) 60
   C) 140
   D) 95

2. What is the main cost of smoothing an image with a blur kernel?
   A) It always makes the image brighter
   B) It removes colour
   C) It spreads out sharp edges and fine detail as well as noise
   D) It changes the image's resolution

3. Why does the Sobel kernel give exactly 0 on a perfectly uniform region of brightness 200?
   A) Because its weights add up to zero, so equal values cancel
   B) Because 200 is above the threshold
   C) Because Sobel only works on dark regions
   D) Because borders are skipped

4. Why do practical edge detectors usually blur an image before applying an edge kernel?
   A) Blurring makes edges sharper
   B) Edge kernels only work on blurred images
   C) Blurring reduces the image to black and white
   D) Edge kernels respond to differences, and noise creates many small differences that would look like edges

**Go further:**

- Kernel (image processing) (Wikipedia): https://en.wikipedia.org/wiki/Kernel_(image_processing) — Common kernels for blurring, sharpening and edge detection, with example images.
- Sobel operator (Wikipedia): https://en.wikipedia.org/wiki/Sobel_operator — The Sobel kernels in both directions and how gradient strength and direction are computed.


## 5.4 Finding objects

*Turn a binary mask into a list of objects: group connected pixels into regions, then measure each region's area, centroid and bounding box.* (about 35 min)

### From pixels to things

After thresholding, a robot has a mask of 1s and 0s. But a gripper cannot reach for "pixels". It needs answers to questions like: *How many objects are there? Where is the middle of each one? How big is it?* This lesson turns a mask into exactly that: a list of objects, each with a size and a position.

The method has two parts. First, group pixels that touch into **connected regions**. Second, measure each region.

### Which pixels count as touching?

Two pixels are **neighbours** if they share an edge: up, down, left or right. This is called **4-connectivity**. Some systems also count the four diagonal neighbours, which is **8-connectivity**. The choice matters. Two blobs that touch only at a corner are one object under 8-connectivity and two objects under 4-connectivity. Neither is "correct"; you choose based on what your objects look like, and you say which you used.

### Labelling connected regions

The algorithm is a **flood fill**, closely related to the breadth-first search used for path planning on grids. Scan the mask row by row. When you meet a 1 you have not seen before, it is the start of a new region. Collect it, then repeatedly collect any unseen neighbours that are also 1, until the region stops growing. Then carry on scanning.

```python
mask = [
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 1, 0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0, 0, 1, 0],
    [0, 0, 1, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0, 1, 1, 0],
]

def find_regions(mask):
    """Return a list of regions; each region is a list of (row, col) pixels."""
    rows, cols = len(mask), len(mask[0])
    seen = [[False] * cols for _ in range(rows)]
    regions = []
    for r in range(rows):
        for c in range(cols):
            if mask[r][c] == 1 and not seen[r][c]:
                region = []
                to_visit = [(r, c)]
                seen[r][c] = True
                while to_visit:
                    pr, pc = to_visit.pop()
                    region.append((pr, pc))
                    for nr, nc in [(pr - 1, pc), (pr + 1, pc), (pr, pc - 1), (pr, pc + 1)]:
                        if 0 <= nr < rows and 0 <= nc < cols:
                            if mask[nr][nc] == 1 and not seen[nr][nc]:
                                seen[nr][nc] = True
                                to_visit.append((nr, nc))
                regions.append(region)
    return regions
```

Three details make this work. The `seen` grid ensures no pixel is counted twice, which also guarantees the loop finishes. The bounds check `0 <= nr < rows` stops the code from reading outside the image. And a pixel is marked as seen when it is *added* to `to_visit`, not when it is taken off, so it can never be queued twice.

### Measuring each region

Once you have a region's pixels, three measurements are easy and very useful:

- **Area**: the number of pixels. It tells you roughly how big the object looks.
- **Centroid**: the average row and average column of the region's pixels. It is the object's "centre of mass" in the image, and it is often the point a robot aims for.
- **Bounding box**: the smallest upright rectangle that contains the region, given by the top, left, bottom and right pixel positions.

```python
def describe(region):
    area = len(region)
    row_c = sum(p[0] for p in region) / area
    col_c = sum(p[1] for p in region) / area
    top = min(p[0] for p in region)
    bottom = max(p[0] for p in region)
    left = min(p[1] for p in region)
    right = max(p[1] for p in region)
    return area, (row_c, col_c), (top, left, bottom, right)

for i, region in enumerate(find_regions(mask)):
    area, (rc, cc), box = describe(region)
    print(f"Region {i}: area {area}, centroid (row {rc:.2f}, col {cc:.2f}), box {box}")
```

Output:

```
Region 0: area 7, centroid (row 2.00, col 2.00), box (1, 1, 3, 3)
Region 1: area 1, centroid (row 2.00, col 6.00), box (2, 6, 2, 6)
Region 2: area 6, centroid (row 5.00, col 5.50), box (4, 5, 6, 6)
```

Check Region 0 by hand. Its pixels are at rows 1, 1, 2, 2, 2, 3, 3, which add to 14, and 14 ÷ 7 = 2. Its columns are 1, 2, 1, 2, 3, 2, 3, which also add to 14, so the centroid is (2, 2). Region 2 is a 3-row by 2-column rectangle; its centroid falls at column 5.5, exactly between two pixel columns. Centroids do not have to land on a pixel, which is useful: averaging many pixels gives a position more precise than any single pixel.

### Rejecting noise

Region 1 is a single isolated pixel. In a real image, tiny regions like this are usually noise: a reflection, a speck of dust or a pixel that only just crossed the threshold. The simplest fix is a **minimum area**:

```python
MIN_AREA = 3
objects = [r for r in find_regions(mask) if len(r) >= MIN_AREA]
print(f"{len(objects)} objects kept")
```

Output:

```
2 objects kept
```

The minimum area is a design decision, just like the threshold. Set it too low and noise becomes "objects"; set it too high and small or distant real objects are thrown away. Write down the value you chose and why.

### What these numbers can and cannot tell you

The centroid and bounding box are in **pixel** coordinates. They tell the robot where the object appears in the image, not where it is in the room. Turning a pixel position into a real position needs a camera model, which is the subject of the next lesson. Area in pixels also depends on distance: the same object looks four times smaller in area when it is twice as far away.

Some useful extras are easy to compute from the same data. The bounding box's **fill ratio** (area ÷ box area) separates compact shapes from thin or ragged ones: Region 2 fills its box completely (6 ÷ 6 = 1.0), while Region 0 fills 7 ÷ 9 ≈ 0.78. The box's width-to-height ratio separates long objects from square ones.

### Recap

- Connected-component labelling groups touching mask pixels into regions with a flood fill.
- 4-connectivity and 8-connectivity can give different object counts; choose deliberately.
- Area, centroid and bounding box summarise each region; centroids can be more precise than one pixel.
- A minimum-area filter removes specks of noise, at the risk of discarding small real objects.

> **Rows, columns, x and y.** This lesson reports positions as (row, column). Many libraries and most maths use (x, y), where x is the column and y is the row. Before you send a centroid to any other piece of code, check which order it expects. Swapping them is a classic bug that makes a robot reach to a mirror-image position.

#### Project: Programming project: count the coins

1. Draw a 12 × 10 binary mask in Python containing four "coins" of different sizes, plus two single-pixel specks of noise. Make two of the coins touch only at one diagonal corner.
2. Run `find_regions` and `describe` and print a table of regions.
3. Change the neighbour list to use 8-connectivity (add the four diagonals). How many regions do you find now? Explain the difference.
4. Choose a minimum area that removes the noise but keeps every coin. Then sort the remaining objects from largest to smallest area.
5. Add a fill-ratio calculation and use it to tell round-ish blobs from thin lines.

**Deliverables**

- A Python file with your mask, both connectivity versions and the filtering step
- Printed results for 4- and 8-connectivity
- A short explanation of your chosen minimum area

#### Check your understanding

1. Two blobs touch only at one diagonal corner. How many regions does each rule find?
   A) One with 4-connectivity, two with 8-connectivity
   B) Two with 4-connectivity, one with 8-connectivity
   C) Two with both
   D) One with both

2. A region contains the pixels (0, 0), (0, 1), (1, 0) and (1, 1) as (row, col). What is its centroid?
   A) (1, 1)
   B) (0, 0)
   C) (0.5, 0.5)
   D) (2, 2)

3. In find_regions, why is each pixel marked as seen when it is added to to_visit?
   A) So that the same pixel cannot be queued or counted twice, which also ensures the loop ends
   B) To make the image brighter
   C) Because Python requires it for lists
   D) So that the bounding box is calculated correctly

4. You raise the minimum area from 3 to 50 pixels. What is the most likely risk?
   A) The program will crash
   B) More noise will be detected as objects
   C) The centroids will move
   D) Small or distant real objects will be discarded

5. An object's centroid is at pixel column 400. What does that tell the robot on its own?
   A) Where the object appears in the image, but not its position in the room without a camera model
   B) The object's distance in metres
   C) The object's exact position on the table
   D) The object's mass

**Go further:**

- Connected-component labeling (Wikipedia): https://en.wikipedia.org/wiki/Connected-component_labeling — Flood-fill and two-pass labelling algorithms, and the 4- and 8-connectivity definitions.
- Image segmentation (Wikipedia): https://en.wikipedia.org/wiki/Image_segmentation — A survey of ways to divide an image into regions, from thresholding to modern methods.


## 5.5 Camera geometry and the pinhole model

*How a 3D point becomes a pixel: the pinhole camera model, focal length in pixels, estimating distance from size, and why every camera needs calibrating.* (about 35 min)

### From pixels back to the world

The last lesson ended with a centroid in pixels. A robot arm, though, moves in metres. To connect the two, you need a model of how a camera turns points in the world into pixels. The standard starting point is the **pinhole camera model**. It is simple enough to work with on paper, yet it underlies almost every real camera calculation, from measuring objects to stereo depth.

### The pinhole camera

Imagine a closed box with a tiny hole in one side. Light from each point in the scene travels in a straight line through the hole and lands on the back wall, making an upside-down image. A real camera uses a lens instead of a hole, to gather more light, but for geometry the pinhole picture is remarkably accurate.

Set up coordinates with the hole at the origin. Z points straight out of the camera towards the scene, X points right, and Y points down (matching image rows). A point at (X, Y, Z) metres lands on the image at pixel position (u, v):

```
u = f · X / Z + cx
v = f · Y / Z + cy
```

Here f is the **focal length measured in pixels**, and (cx, cy) is the **principal point**, the pixel where the camera's central axis meets the image, usually close to the centre. The model's mathematics flips the image upright for you, so you do not need to worry about it being upside down.

The key feature is the **division by Z**. Things further away appear smaller and closer to the centre. That single division is what perspective is.

```python
f = 600.0              # focal length, pixels
cx, cy = 320.0, 240.0  # principal point (image centre), pixels

def project(X, Y, Z):
    """Pinhole projection of a point in camera coordinates (metres)."""
    u = f * X / Z + cx
    v = f * Y / Z + cy
    return round(u, 1), round(v, 1)

print(project(0.10, 0.05, 1.0))   # 10 cm right, 5 cm down, 1 m away
print(project(0.10, 0.05, 2.0))   # same offset, twice as far
print(project(0.20, 0.10, 2.0))   # twice the offset, twice as far
```

Output:

```
(380.0, 270.0)
(350.0, 255.0)
(380.0, 270.0)
```

Work through the first case: 600 × 0.10 ÷ 1.0 = 60 pixels right of centre, so u = 320 + 60 = 380. Moving the same point twice as far away halves its offset from the centre. And the third line reveals something important: a point twice as far away and twice as far to the side lands on **exactly the same pixel**. Every point along a line through the pinhole projects to the same place. **A single image loses depth.** From one pixel alone, you cannot tell how far away something is.

### What focal length in pixels means

Focal length is usually quoted in millimetres for a lens, but for calculations it is more convenient in pixels. It is linked to the **field of view**, the angle the camera can see. If the image is W pixels wide and the horizontal field of view is θ, then:

```
f = (W / 2) / tan(θ / 2)
```

```python
import math

def focal_pixels(image_width_px, horizontal_fov_deg):
    half = math.radians(horizontal_fov_deg / 2)
    return (image_width_px / 2) / math.tan(half)

print(f"{focal_pixels(640, 60):.1f} px")
print(f"{focal_pixels(640, 90):.1f} px")
```

Output:

```
554.3 px
320.0 px
```

A wider field of view means a smaller focal length in pixels: each pixel covers a larger angle, so you see more of the scene in less detail. Choosing a camera is partly choosing this trade-off.

### Distance from known size

If you know the real size of an object, you can recover the depth that a single image loses. An object of real height H at distance Z appears h pixels tall, where h = f · H / Z. Rearranging gives:

```
Z = f · H / h
```

```python
f = 600.0          # focal length, pixels
H = 0.065          # real height of a tennis-ball-sized object, metres

for h_pixels in [78, 39, 20]:
    Z = f * H / h_pixels
    print(f"{h_pixels:3d} px tall -> about {Z:.2f} m away")

# How much does a 1-pixel mistake matter?
Z_true = f * H / 20
Z_off  = f * H / 19
print(f"1 px error at 20 px changes the estimate by {(Z_off - Z_true) * 100:.1f} cm")
print(f"Each pixel spans {Z_true / f * 1000:.1f} mm at {Z_true:.2f} m")
```

Output:

```
 78 px tall -> about 0.50 m away
 39 px tall -> about 1.00 m away
 20 px tall -> about 1.95 m away
1 px error at 20 px changes the estimate by 10.3 cm
Each pixel spans 3.2 mm at 1.95 m
```

The last two lines are the engineering lesson. When the object is small in the image, a mistake of just one pixel in measuring its height (easily caused by blur or a slightly wrong threshold) shifts the distance estimate by about 10 cm. Vision measurements get **less precise with distance**, and quickly. A gripper that needs to be within a centimetre should not trust this estimate from two metres away.

### Why calibration matters

Everything above assumed you knew f, cx and cy exactly, and that the lens behaves like a perfect pinhole. Neither is true out of the box:

- The focal length printed on a lens is nominal, and the conversion to pixels depends on the exact sensor. A few percent error in f gives a few percent error in every distance.
- The principal point is rarely exactly at the image centre.
- Real lenses bend straight lines, especially near the edges of wide-angle images. This **lens distortion** (barrel or pincushion) means pixels near the corners are not where the pinhole formula predicts.

**Camera calibration** measures these values. The usual method photographs a printed pattern with known geometry, often a checkerboard, from many angles. Because the true square size is known, software can solve for the focal length, principal point and distortion that best explain where the corners appear. OpenCV includes tools for this (it must be installed separately). A calibrated camera can then remove distortion from images and turn pixels into reliable directions in space.

Calibration only holds for the setup you calibrated. Changing the zoom or focus, or knocking the lens, means calibrating again.

### Recap

- The pinhole model maps (X, Y, Z) to pixels with u = f · X / Z + cx and v = f · Y / Z + cy.
- Dividing by Z creates perspective, and means one image cannot reveal depth by itself.
- Focal length in pixels is set by image width and field of view.
- Known object size gives distance, Z = f · H / h, but precision falls quickly with distance.
- Calibration measures the real focal length, principal point and lens distortion.

> **State your uncertainty.** A distance printed as "1.95 m" looks precise. If a one-pixel error moves it by 10 cm, a more honest report is "about 1.9–2.1 m". When you report a measurement from an image, say how many pixels the object spanned and estimate how much a pixel of error would change your answer.

#### Project: Paper project: measure your own camera

You can do this with any phone or laptop camera, a ruler and Python.

1. Tape a sheet of paper with a 10 cm line drawn on it to a wall. Photograph it face-on from 50 cm, 100 cm and 150 cm, measured with a tape measure.
2. On a computer, zoom in on each photo and measure the line's length in pixels (most image viewers show the cursor position). Note the image width in pixels.
3. For each photo, calculate f = h · Z / H. Do the three values agree? Average them.
4. Use your f to predict the line's pixel length at 200 cm, then test the prediction.
5. Estimate how much a one-pixel measuring error changes your distance estimate at each distance.

**Deliverables**

- A table of distance, pixel length and calculated focal length
- Your prediction for 200 cm and the measured result
- A short note on which measurements you trust least, and why

#### Check your understanding

1. With f = 500 px and cx = 320, a point at X = 0.2 m, Z = 2 m projects to which u?
   A) 370
   B) 420
   C) 320
   D) 520

2. Why can a single camera image not tell you how far away a point is?
   A) Because cameras do not record brightness
   B) Because the image is upside down
   C) Because every point along a line through the pinhole projects to the same pixel
   D) Because pixels are too large

3. An object 0.10 m tall appears 50 px tall through a camera with f = 600 px. About how far away is it?
   A) 0.6 m
   B) 3.0 m
   C) 1.2 m
   D) 12 m

4. A camera is swapped for one with a wider field of view but the same image width. What happens to f in pixels?
   A) It gets larger
   B) It gets smaller
   C) It stays the same
   D) It becomes negative

5. What does camera calibration with a checkerboard measure?
   A) The colours the camera can see
   B) The speed of the robot
   C) The brightness threshold for segmentation
   D) The camera's focal length, principal point and lens distortion

**Go further:**

- Pinhole camera model (Wikipedia): https://en.wikipedia.org/wiki/Pinhole_camera_model — The geometry of the pinhole camera, with derivations of the projection equations.
- Camera resectioning (Wikipedia): https://en.wikipedia.org/wiki/Camera_resectioning — The intrinsic and extrinsic camera parameters that calibration estimates.
- Distortion (optics) (Wikipedia): https://en.wikipedia.org/wiki/Distortion_(optics) — Barrel and pincushion distortion and how they are modelled and corrected.


## 5.6 When vision fails

*Lighting changes, occlusion, motion blur and soft, shape-changing objects all break simple vision. See each failure in numbers, and why robots combine vision with other senses.* (about 40 min)

### A good engineer knows the limits

The previous lessons built a working pipeline: threshold an image, find connected regions, measure their centroids and turn pixels into positions. In a controlled test, it can work beautifully. Then the robot is moved to a new room, or the object starts moving, or a gripper finger gets in the way, and it fails.

Knowing **how** a sensor fails is as important as knowing how it works, because it tells you what to test, what to warn users about and what other sensors you might need. This lesson takes four common failure modes and shows each one in numbers.

### Failure 1: lighting

Here is the image from the thresholding lesson, with the same threshold of 100, under steadily dimmer light:

```python
image = [
    [ 30,  35,  32,  40,  38,  33],
    [ 36, 180, 190,  41,  37,  35],
    [ 31, 185, 200, 195,  39,  34],
    [ 38, 176, 188, 192,  42,  36],
    [ 33,  37,  40,  36,  35,  31],
]

def count_above(img, t):
    return sum(1 for row in img for v in row if v > t)

for gain in [1.0, 0.7, 0.55, 0.5]:            # 1.0 = original lighting
    dimmer = [[round(v * gain) for v in row] for row in image]
    print(f"light x{gain}: {count_above(dimmer, 100)} object pixels")
```

Output:

```
light x1.0: 8 object pixels
light x0.7: 8 object pixels
light x0.55: 6 object pixels
light x0.5: 0 object pixels
```

Down to 70% of the original light, nothing changes. At 55%, two pixels drop out and the object appears smaller, which would shift its centroid and its size-based distance estimate. At 50%, the object vanishes completely. The failure is not gradual and polite: the system goes from perfect to useless over a small change. Halving the light is easy to do by accident, for example when a cloud passes a window or someone stands between the lamp and the table.

Shadows, reflections and glare cause related problems. A shiny object can show a bright highlight that is the colour of the lamp, not the object. HSV helps with gentle brightness changes, as the colour lesson showed, but not with very dark pixels, glare or coloured light.

### Failure 2: occlusion

**Occlusion** means part of the object is hidden behind something else. For a robot grasping an object, the most common thing in the way is the robot's own gripper.

```python
def centroid(pixels):
    n = len(pixels)
    return (sum(p[0] for p in pixels) / n, sum(p[1] for p in pixels) / n)

# A 4 x 4 object occupying rows 2-5 and columns 2-5
full = [(r, c) for r in range(2, 6) for c in range(2, 6)]
# The same object with its right half hidden behind a gripper finger
visible = [(r, c) for (r, c) in full if c < 4]

print("Full object centroid:   ", centroid(full))
print("Half-hidden centroid:   ", centroid(visible))
```

Output:

```
Full object centroid:    (3.5, 3.5)
Half-hidden centroid:    (3.5, 2.5)
```

The object has not moved at all, but its measured centroid jumped a whole pixel column to the left, because the code can only average the pixels it can see. Worse, the error appears exactly when it matters most: as the gripper closes in, it hides more of the object. With heavier occlusion, the region may split into two pieces or disappear. The camera's view is **intermittent**: present some of the time, missing or misleading at other times.

### Failure 3: motion blur

A camera's shutter stays open for a short **exposure time**. If the object moves during that time, it smears across the image. Using the pinhole model, an object moving sideways at speed v, at distance Z, moves across the image at f · v / Z pixels per second, so the smear is:

```python
f = 600.0            # focal length, pixels
Z = 1.0              # distance to the object, metres
exposure = 1 / 60    # seconds the shutter is open

for speed in [0.05, 0.5, 2.0]:          # object speed across the view, m/s
    blur_px = f * speed * exposure / Z
    print(f"{speed:4.2f} m/s -> smeared over {blur_px:4.1f} px")
```

Output:

```
0.05 m/s -> smeared over  0.5 px
0.50 m/s -> smeared over  5.0 px
2.00 m/s -> smeared over 20.0 px
```

A slowly sliding object is fine. At half a metre per second, which is a gentle arm movement, edges are smeared over five pixels: the edge detector's response weakens, thresholds give ragged regions, and size measurements grow in the direction of motion. Shorter exposures reduce blur but let in less light, which brings back Failure 1. There is also **latency**: by the time an image has been captured, processed and acted on, the world has moved on.

### Failure 4: deformable objects

Everything so far assumed a **rigid** object with a fixed shape. Many real objects are not: cloth, cables, food, bags, sponges. A towel lying flat and the same towel crumpled have completely different areas, outlines and centroids. A known-size distance estimate is meaningless when the size keeps changing. And when a gripper squeezes a soft object, the most important information, such as how much it has compressed, whether it is slipping, or how hard the fingers are pressing, may be invisible to a camera altogether, hidden inside the grasp.

### Why robots add other senses

None of these failures means vision is a poor sensor. It gives rich, absolute information about where things are, at a distance, without touching. But it is weak exactly where a grasp happens: close up, partly hidden and in contact. So robots usually **combine** vision with other sensors that fail in different ways: joint encoders and wheel odometry that are always available but drift, force and touch sensors at the fingertips that feel contact directly, and depth sensors that measure distance. Combining them is called **sensor fusion**.

The explorer below shows the idea with two imperfect sensors tracking a moving point. The camera is accurate but drops out in bursts, like an occluded view. Odometry never drops out but slowly drifts.

> **Interactive:** Raise the dropout probability to simulate heavier occlusion and watch the camera-alone error grow while the fused estimate holds up. Then set odometry bias to zero and then to 3 cm/s to see how drift hurts dead reckoning. Compare the bar chart of errors (RMSE) for each estimate. Try it at https://tactiverge.win/academy/lab/#fusion

### What the explorer shows

The camera alone is excellent when it can see and poor during dropouts, because it can only hold its last reading. Odometry alone never has gaps but wanders further from the truth over time. The fused estimate uses odometry to carry the position through the gaps and the camera to correct the drift whenever it reappears. It is usually better than either sensor alone. That is the whole argument for fusion: **two sensors with different weaknesses can cover for each other**.

### A worked research question

Tactiverge's Project TV-01 is a *proposed* study built around exactly this problem. Its research question is: "Can inexpensive local force sensing compensate for intermittent visual information and improve cooperative robotic manipulation of unfamiliar deformable materials?" Notice how it names the failure modes from this lesson: *intermittent visual information* (occlusion and dropouts) and *deformable materials* (shapes that change). It proposes force sensing as the complementary sense. This is a question, not a finding. The study has no results, and nothing in this lesson is evidence that the approach works. It is here as an example of how understanding a sensor's failures leads directly to a testable engineering question.

### Recap

- Simple vision can fail suddenly when lighting changes, not gradually.
- Occlusion biases measurements such as centroids, often just as a gripper closes in.
- Motion blur grows with speed and exposure time: blur ≈ f · v · exposure / Z pixels.
- Deformable objects break assumptions of fixed size and shape, and contact is hard to see.
- Combining sensors with different failure modes, sensor fusion, makes a system more robust than any one sensor.

> **Test the failures on purpose.** It is tempting to demonstrate a vision system only under the conditions where it works. An honest evaluation deliberately includes dim light, partial occlusion, motion and unfamiliar objects, and reports how often the system fails in each. A list of known failure cases is one of the most useful things you can publish about a system.

#### Project: Programming project: a failure-mode report

Using the code from this module (Python standard library only):

1. Build a 12 × 12 greyscale test image of a bright object on a dark background, and a pipeline that thresholds it, finds the largest region and prints its area and centroid.
2. **Lighting:** multiply the image by gains from 1.0 down to 0.3 in steps of 0.1. Record at which gain the area first changes and at which the object disappears.
3. **Occlusion:** set columns of the object to the background value, one column at a time, and record how the centroid moves.
4. **Noise:** add random noise with `random.gauss(0, sigma)` for several values of sigma (use `random.seed(1)` so your results repeat). Record when false regions appear.
5. Write a one-page report listing each failure mode, the condition at which it appeared, and one idea (a different sensor, a different method or a change to the setup) that might reduce it. Label every number as coming from your synthetic test image.

**Deliverables**

- A Python file containing the pipeline and the three tests
- Tables of results for lighting, occlusion and noise
- A one-page failure-mode report with a mitigation idea for each failure

#### Check your understanding

1. In the lighting example, the object went from fully detected at 70% light to completely missing at 50%. What does this suggest?
   A) The camera is broken
   B) Dimmer light always improves detection
   C) Fixed thresholds can fail abruptly with modest lighting changes, so lighting must be tested or controlled
   D) The threshold should be set to 255

2. A gripper finger hides the right half of an object. What happens to the centroid measured from the visible pixels?
   A) It stays at the true centre
   B) It shifts towards the right, behind the finger
   C) It shifts towards the visible left part, even though the object has not moved
   D) It cannot be calculated at all

3. With f = 600 px, Z = 1 m and an exposure of 1/60 s, how much blur does an object moving at 1 m/s cause?
   A) 1 px
   B) 60 px
   C) 0.1 px
   D) 10 px

4. Why is estimating distance from known size unreliable for a towel?
   A) Towels are always too far away
   B) A deformable object has no fixed size or shape, so its apparent size does not reliably reveal its distance
   C) Towels have no colour
   D) The pinhole model does not apply to cloth

5. Which statement about the TV-01 research question is accurate?
   A) It is a proposed study with no results, used here as an example of a question shaped by vision's failure modes
   B) It proved that force sensing fixes occlusion
   C) It showed that cameras are unnecessary
   D) It is a finished experiment whose data appear in the explorer

**Go further:**

- Sensor fusion (Wikipedia): https://en.wikipedia.org/wiki/Sensor_fusion — An overview of why and how information from several sensors is combined.
- Motion blur (Wikipedia): https://en.wikipedia.org/wiki/Motion_blur — How exposure time and movement create blur in photographs and video.
