1. Objectives
- Write automatic tests for a fuzzy controller and act on a failing test.
- Replace slow inference with a precomputed lookup table and bilinear interpolation; measure error and speed.
- Build a command-line controller that reads sensor data, handles missing and out-of-range readings, and writes a log.
2. Word Bank
Word | Simple meaning | Real-world example |
|---|---|---|
Test (unit test) | A small program that checks one behaviour automatically and says PASS or FAIL | fan(39, 45) must be 76.32 |
assert | Python statement that stops with AssertionError if a condition is false | assert 0 <= y <= 100 |
Monotonic | Always moving one way: hotter never gives a slower fan | 54.9, 80.6, 83.3 ... |
Lookup table | Answers computed once in advance and stored, so the program only looks them up | 51 x 101 fan speeds |
Bilinear interpolation | Estimating a value inside a grid square from its four corners | Speed at 30.4 C, 61.7 % |
Log file | A file where a running program writes what it did, line by line | fan_log.csv |
3. Background
Before a controller goes live
A fan, pump or heater controller runs for months without anyone watching. Before deploying it we must be sure it behaves well (tests), that it is fast enough for a cheap processor such as a Raspberry Pi or an Arduino (speed), and that it survives bad sensor data - a loose wire gives an empty value, a faulty sensor reads 55 °C (robustness).
Tests that run themselves
A test is a small function that checks one fact with assert: a known answer, outputs always 0-100, 'hotter is never slower'. We run all tests after every change. A FAILING test is not a disaster - it is information: it shows something we did not know about our system.
Lookup tables
Small embedded controllers often cannot run scikit-fuzzy. Instead the fuzzy system is evaluated ONCE on a grid (every whole degree and every whole %), the 5151 answers are stored, and the controller only interpolates between the four nearest grid points. MATLAB's Fuzzy Logic Toolbox and embedded-code generators use the same idea.
Data files for this lab
fisengine.py
"""fisengine.py - a small engine that runs ANY Mamdani fuzzy system stored in a JSON model file (CS-511 P13). load_model(path) reads the file; evaluate(model, inputs) returns the crisp outputs.""" import json import numpy as np import skfuzzy as fuzz SHAPES = {"trimf": fuzz.trimf, "trapmf": fuzz.trapmf, "gaussmf": lambda x, p: fuzz.gaussmf(x, *p)} def load_model(path): with open(path) as f: ... (43 data rows in total - copy the full file from the lab folder) |
fan_model.json
{ "name": "Room fan controller (CS-511 P08-P10)", "inputs": { "temperature": {"range": [0, 50], "points": 51, "terms": { "cold": ["trapmf", [0, 0, 10, 20]], "comfortable": ["trimf", [15, 24, 33]], "hot": ["trapmf", [28, 38, 50, 50]]}}, "humidity": {"range": [0, 100], "points": 101, "terms": { "dry": ["trapmf", [0, 0, 20, 50]], "normal": ["trimf", [30, 50, 70]], "humid": ["trapmf", [50, 80, 100, 100]]}} }, "outputs": { "fan": {"range": [0, 100], "points": 101, "terms": { "slow": ["trimf", [0, 0, 50]], "medium": ["trimf", [25, 50, 75]], "fast": ["trimf", [50, 100, 100]]}} }, "rules": [ "IF temperature IS cold THEN fan IS slow", "IF temperature IS comfortable AND humidity IS dry THEN fan IS slow", "IF temperature IS comfortable AND humidity IS NOT dry THEN fan IS medium", "IF temperature IS hot AND humidity IS dry THEN fan IS medium", "IF temperature IS hot AND humidity IS NOT dry THEN fan IS fast" ] } |
sensor.csv
time,temperature,humidity 06:00,29,70 08:00,31, 10:00,35,62 12:00,39,45 14:00,55,30 16:00,41,38 18:00,36,70 20:00,33,65 22:00,30,-5 |
4. Time Plan (50 minutes)
Minutes | Activity | Part |
|---|---|---|
0-5 | Background: tests, speed, bad sensor data | 1-3 |
5-10 | Guided warm-up: a first test; how long one evaluation takes | Part A |
10-13 | Predict the output | Part B |
13-17 | Bug hunt | Part C |
17-47 | Graded tasks 1-3 | Part D |
47-50 | Wrap-up; post-lab questions set as homework | Part E |
Part A - Guided Warm-up (type, run, observe)
A1. A first automatic test
A test checks one behaviour and says PASS or FAIL. Here: a known answer from P13a.
import numpy as np from fisengine import load_model, evaluate fan = load_model("fan_model.json") speed = lambda t, h: evaluate(fan, {"temperature": t, "humidity": h})["fan"] def test_known_value(): assert abs(speed(39, 45) - 76.32) < 0.01, f"got {speed(39, 45):.2f}" for test in (test_known_value,): try: test(); print("PASS", test.__name__) except AssertionError as e: print("FAIL", test.__name__, "-", e) |
Output PASS test_known_value |
A2. How long does one evaluation take?
Time 1000 evaluations with time.perf_counter(). (Your times will be different - they depend on the computer.)
# ... set-up: load the fan model with the engine (as shown earlier) ... import time start = time.perf_counter() for _ in range(1000): speed(30, 60) ms = (time.perf_counter() - start) / 1000 * 1000 print(f"one evaluation: about {ms:.3f} ms -> about {1000 / ms:,.0f} evaluations per second") |
Output one evaluation: about 0.099 ms -> about 10,132 evaluations per second |
Part B - Predict the Output
Write your prediction BEFORE running the code. Then run it and correct yourself in a different colour.
B1.
import numpy as np table = np.array([[10, 20], [30, 40]]) a, b = 0.5, 0.5 # exactly in the middle of the square print((1 - a) * (1 - b) * table[0, 0] + a * (1 - b) * table[1, 0] + (1 - a) * b * table[0, 1] + a * b * table[1, 1]) |
My prediction |
B2.
try: assert 2 + 2 == 5, "maths is broken" print("PASS") except AssertionError as e: print("FAIL:", e) |
My prediction |
B3.
import numpy as np print(np.clip(55, 0, 50), np.clip(-5, 0, 100), np.clip(33, 0, 50)) |
My prediction |
Part C - Bug Hunt
Each program has ONE bug. Some crash with an error message; others run but give a wrong answer (silent logic error - the dangerous kind). Find the bug, explain it and write the fix.
C1.
# ... set-up: load the fan model with the engine (as shown earlier) ... T_AXIS, H_AXIS = np.arange(0, 51), np.arange(0, 101) # every whole degree and every whole % table = np.array([[speed(t, h) for h in H_AXIS] for t in T_AXIS]) # 51 x 101 = 5151 answers, computed once def lookup(t, h): i, j = int(t), int(h) # the grid square that holds (t, h) a, b = t - i, h - j # how far across the square (0 to 1) return ((1 - a) * (1 - b) * table[i, j] + a * (1 - b) * table[i + 1, j] + (1 - a) * b * table[i, j + 1] + a * b * table[i + 1, j + 1]) print(round(lookup(50, 100), 2)) |
Bug, why it happens, and the fixed line(s) |
C2.
# ... set-up: load the fan model with the engine (as shown earlier) ... T_AXIS, H_AXIS = np.arange(0, 51), np.arange(0, 101) table = np.array([[speed(t, h) for t in T_AXIS] for h in H_AXIS]) # 101 x 51 print("table[39, 45] =", round(float(table[39, 45]), 2), " engine:", round(speed(39, 45), 2)) |
It runs and prints table[39, 45] = 69.36 engine: 76.32 |
Bug, why it happens, and the fixed line(s) |
C3.
# ... set-up: load the fan model with the engine (as shown earlier) ... import csv for row in csv.DictReader(open("sensor.csv")): if row["time"] == "08:00": h = float(row["humidity"] or 0) # empty humidity becomes 0 print(row, "->", round(speed(float(row["temperature"]), h), 2)) |
It runs and prints {'time': '08:00', 'temperature': '31', 'humidity': ''} -> 38.23 |
Bug, why it happens, and the fixed line(s) |
Part D - Graded Tasks (10 marks)
Task | Level | Title | Marks |
|---|---|---|---|
T1 | Easy | A test suite - and a test that fails | 3 |
T2 | Medium | A lookup table: how accurate, how fast? | 3 |
T3 | Challenge | The deployed controller | 4 |
Total | 10 |
Task 1 (Easy, 3 marks): A test suite - and a test that fails
Write four tests and a small runner that prints PASS or FAIL for each: (1) speed(39, 45) is 76.32 (± 0.01); (2) every output on the grid t = 0, 5, ..., 50 and h = 0, 10, ..., 100 is between 0 and 100; (3) at humidity 70 a hotter room never gets a slower fan (t = 0 to 50); (4) the same at humidity 20. For any failing test, print where it fails and explain why.
Sample run (your output must match):
Output PASS test_known_value PASS test_output_range PASS test_monotonic_humid FAIL test_monotonic_dry - slower at 7 temperatures, first (18, 21.47, 21.11), biggest drop 17 -> 24 C: 21.47 -> 16.67 |
Your code (or attach the file) |
Task 2 (Medium, 3 marks): A lookup table: how accurate, how fast?
Build the 51 x 101 lookup table (every whole °C and %) and the bilinear lookup(t, h). Save the table with np.save ('fan_table.npy'). On 300 random readings (np.random.default_rng(13)) report the largest and mean difference from the engine, and time both methods on the same readings. How many times faster is the table?
Sample run (your output must match):
Output table shape (51, 101); largest difference 0.67 %, mean 0.017 % engine 86 µs per reading, table 2.1 µs -> about 42 times faster |
Your code (or attach the file) |
Task 3 (Challenge, 4 marks): The deployed controller
Write controller.py: it takes the sensor file name as a command-line argument (argparse), loads fan_table.npy and uses lookup(). For each row of the sensor file: if a value is missing, keep the previous fan speed and print a WARNING; if a value is outside its range (0-50 °C, 0-100 %), clip it and print a WARNING; otherwise use it. Write every decision to fan_log.csv (time, temperature, humidity, fan, note). Run it on sensor.csv and print the log.
Sample run (your output must match):
Output $ python controller.py sensor.csv WARNING 08:00: missing value - kept previous speed WARNING 14:00: out of range (55 C, 30 %) - clipped WARNING 22:00: out of range (30 C, -5 %) - clipped 9 readings processed, log written to fan_log.csv time,temperature,humidity,fan,note 06:00,29,70,54.9,ok 08:00,31,,54.9,missing value - kept previous speed 10:00,35,62,82.2,ok 12:00,39,45,76.3,ok 14:00,55,30,60.8,"out of range (55 C, 30 %) - clipped" 16:00,41,38,68.3,ok 18:00,36,70,82.8,ok 20:00,33,65,80.6,ok 22:00,30,-5,31.8,"out of range (30 C, -5 %) - clipped" |
Your code (or attach the file) |
Part E - Post-Lab Questions (finish as homework if time runs out)
E1. What did the failing monotonic test tell you about the fan design?
Your answer |
E2. Why use a lookup table on a small controller, and what does it cost?
Your answer |
E3. How should a deployed controller treat a missing or impossible reading?
Your answer |
Marking Rubric (applied to Part D)
Criterion | Full | Partial | None |
|---|---|---|---|
Code runs without errors | Runs fully | Small fixable error | Does not run |
Four tests, runner and explanation of the failing test | All correct | One slip | Several wrong |
Lookup table saved; error and speed measured | Correct and explained | Partly correct | Missing |
Controller handles missing and out-of-range values and writes the log | Clear and correct | Partly correct | Missing |
Submission
- Make a folder RollNo_P13b with task1.py, task2.py, controller.py (or P13b.ipynb), fan_table.npy and fan_log.csv.
- Upload the zipped folder to the LMS / Google Classroom by the end of the day.
- Copy Task 3 code and the log into your Lab Book (Practical 13b page).
- P14 (next week) uses fuzzy logic on images: edge detection.