1. Objectives
- Turn the P08/P09 fan controller into a module (fanfis.py) and a command-line program (fan_cli.py).
- Read options with argparse: types, defaults, required options and help text.
- Validate inputs and explain the result (fired rules) on request with a flag.
- Process a whole file of readings in batch mode and choose the inference method from the command line.
2. Word Bank
Word | Simple meaning | Real-world example |
|---|---|---|
Command line (terminal) | A text window where you type commands | python fan_cli.py --temp 36 |
Argument / option | A value given to a program when it starts | --temp 36 --hum 70 |
argparse | Python's library that reads command-line options and makes --help | parser.add_argument(...) |
Flag | An on/off option with no value | --explain |
Module | A .py file whose functions other programs import | import fanfis |
Batch mode | Processing many inputs from a file in one run | --csv readings.csv |
3. Background
Why a command line?
MATLAB's Fuzzy Logic Toolbox can be used without its designer window, from commands and scripts. Real controllers run the same way: a small program on a Raspberry Pi or a server is started with options, reads sensor values and prints or sends the result - no buttons, no notebook. Today the P09 fan controller becomes a module, fanfis.py (given), and a command-line program, fan_cli.py, that you write.
argparse in four lines
parser = argparse.ArgumentParser(description=...); parser.add_argument('--temp', type=float, required=True, help=...); args = parser.parse_args(); then use args.temp. argparse converts types, fills defaults, prints --help and stops with a clear error if an option is missing or wrong.
How this handout shows terminal output
In the lab you save fan_cli.py in VS Code and type python fan_cli.py --temp 36 --hum 70 in the terminal. In this handout each program is saved with open(...).write(...) and run with a small cli() helper (subprocess), so the output you see is the real terminal output. The line starting with $ is what you would type.
Data files for this lab
fanfis.py
"""fanfis.py - the P08/P09 fan controller as a small module (CS-511 P10). Inputs: temperature 0-50 C, humidity 0-100 %. Output: fan speed 0-100 %.""" import numpy as np import skfuzzy as fuzz t_x = np.arange(0, 51, 1); h_x = np.arange(0, 101, 1); f_x = np.arange(0, 101, 1) T = {"cold": fuzz.trapmf(t_x, [0, 0, 10, 20]), "comfortable": fuzz.trimf(t_x, [15, 24, 33]), "hot": fuzz.trapmf(t_x, [28, 38, 50, 50])} H = {"dry": fuzz.trapmf(h_x, [0, 0, 20, 50]), "normal": fuzz.trimf(h_x, [30, 50, 70]), "humid": fuzz.trapmf(h_x, [50, 80, 100, 100])} F = {"slow": fuzz.trimf(f_x, [0, 0, 50]), "medium": fuzz.trimf(f_x, [25, 50, 75]), ... (38 data rows in total - copy the full file from the lab folder) |
readings.csv
hour,temperature,humidity 06,29,70 09,33,60 12,39,45 15,42,35 18,38,50 21,33,65 00,30,75 03,28,80 |
4. Time Plan (50 minutes)
Minutes | Activity | Part |
|---|---|---|
0-5 | Background: module + command line; argparse in four lines | 1-3 |
5-10 | Guided warm-up: use the module; a first command-line program | 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. Use the controller as a module
fanfis.py (given in the lab folder) holds the sets, the rules, fire(), mamdani() and sugeno() from P09. Any program can import it.
import fanfis print("Rules:") for i, r in enumerate(fanfis.RULES, 1): print(f" R{i} {r}") for t, h in [(36, 70), (30, 40)]: print(f"{t} C, {h} %: Mamdani {fanfis.mamdani(t, h):.2f} %, Sugeno {fanfis.sugeno(t, h):.2f} %") |
Output Rules: R1 IF cold THEN slow R2 IF comfortable AND dry THEN slow R3 IF comfortable AND NOT dry THEN medium R4 IF hot AND dry THEN medium R5 IF hot AND NOT dry THEN fast 36 C, 70 %: Mamdani 82.78 %, Sugeno 83.00 % 30 C, 40 %: Mamdani 45.04 %, Sugeno 45.88 % |
A2. A first command-line program
Save the program as fan_cli.py and run it with options. Try --help: argparse writes the help text for you.
import subprocess, sys def cli(script, *args): # runs: python script args... (like typing it in the terminal) r = subprocess.run([sys.executable, script, *args], capture_output=True, text=True) print("$ python " + " ".join([script, *args])) err = r.stderr if "Traceback" in err: # show only the last line of a long traceback err = "Traceback (most recent call last):\n ...\n" + err.strip().splitlines()[-1] print((r.stdout + err).rstrip()) open('fan_cli.py', 'w').write('''import argparse import fanfis parser = argparse.ArgumentParser(description="Fuzzy fan controller (CS-511)") parser.add_argument("--temp", type=float, required=True, help="temperature in C (0-50)") parser.add_argument("--hum", type=float, default=50, help="humidity in %% (0-100), default 50") args = parser.parse_args() print(f"fan speed: {fanfis.mamdani(args.temp, args.hum):.1f} %") ''') cli("fan_cli.py", "--temp", "36", "--hum", "70") cli("fan_cli.py", "--temp", "30") cli("fan_cli.py", "--help") |
Output $ python fan_cli.py --temp 36 --hum 70 fan speed: 82.8 % $ python fan_cli.py --temp 30 fan speed: 60.3 % $ python fan_cli.py --help usage: fan_cli.py [-h] --temp TEMP [--hum HUM] Fuzzy fan controller (CS-511) options: -h, --help show this help message and exit --temp TEMP temperature in C (0-50) --hum HUM humidity in % (0-100), default 50 |
Part B - Predict the Output
Write your prediction BEFORE running the code. Then run it and correct yourself in a different colour.
B1.
import argparse p = argparse.ArgumentParser() p.add_argument("--temp", type=float) p.add_argument("--hum", type=float, default=50) a = p.parse_args(["--temp", "36"]) print(a.temp, a.hum, type(a.temp).__name__) |
My prediction |
B2.
import argparse p = argparse.ArgumentParser() p.add_argument("--explain", action="store_true") print(p.parse_args([]).explain, p.parse_args(["--explain"]).explain) |
My prediction |
B3.
import fanfis print(round(fanfis.mamdani(36, 70), 2), round(fanfis.sugeno(36, 70), 2)) |
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: the cli() helper (as shown earlier) ... open('fan_cli.py', 'w').write('''import argparse import fanfis parser = argparse.ArgumentParser(description="Fuzzy fan controller (CS-511)") parser.add_argument("--temp", type=float, required=True, help="temperature in C (0-50)") parser.add_argument("--hum", type=float, default=50, help="humidity in %% (0-100), default 50") args = parser.parse_args() print(f"fan speed: {fanfis.mamdani(args.temp, args.hum):.1f} %") ''') cli("fan_cli.py", "--hum", "70") |
It runs and prints $ python fan_cli.py --hum 70 usage: fan_cli.py [-h] --temp TEMP [--hum HUM] fan_cli.py: error: the following arguments are required: --temp |
Bug, why it happens, and the fixed line(s) |
C2.
# ... set-up: the cli() helper (as shown earlier) ... open('fan_cli.py', 'w').write('''import argparse import fanfis parser = argparse.ArgumentParser(description="Fuzzy fan controller (CS-511)") parser.add_argument("--temp", type=float, required=True, help="temperature in C (0-50)") parser.add_argument("--hum", type=float, default=50, help="humidity in %% (0-100), default 50") args = parser.parse_args() print(f"fan speed: {fanfis.mamdani(args.temp, args.hum):.1f} %") ''') cli("fan_cli.py", "--temp", "60", "--hum", "30") |
It runs and prints $ python fan_cli.py --temp 60 --hum 30 Traceback (most recent call last): ... skfuzzy.defuzzify.exceptions.EmptyMembershipError: The membership function area is empty. |
Bug, why it happens, and the fixed line(s) |
C3.
# ... set-up: the cli() helper (as shown earlier) ... open('fan_cli.py', 'w').write('''import argparse import fanfis parser = argparse.ArgumentParser(description="Fuzzy fan controller (CS-511)") parser.add_argument("--temp", type=float, required=True, help="temperature in C (0-50)") parser.add_argument("--hum", type=float, default=50, help="humidity in %% (0-100), default 50") args = parser.parse_args() print(f"fan speed: {fanfis.mamdani(args.hum, args.temp):.1f} %") ''') cli("fan_cli.py", "--temp", "34", "--hum", "30") |
It runs and prints $ python fan_cli.py --temp 34 --hum 30 fan speed: 45.0 % |
Bug, why it happens, and the fixed line(s) |
Part D - Graded Tasks (10 marks)
Task | Level | Title | Marks |
|---|---|---|---|
T1 | Easy | fan_cli.py with argparse | 3 |
T2 | Medium | Validation and --explain | 3 |
T3 | Challenge | Batch mode: a day of readings | 4 |
Total | 10 |
Task 1 (Easy, 3 marks): fan_cli.py with argparse
Write fan_cli.py with argparse: --temp (float, required), --hum (float, default 50), and help text for both. It prints the Mamdani fan speed. Run it for (36 °C, 70 %), (30 °C, 40 %) and (20 °C, default humidity), and show --help.
Sample run (your output must match):
Output $ python fan_cli.py --temp 36 --hum 70 fan speed: 82.8 % $ python fan_cli.py --temp 30 --hum 40 fan speed: 45.0 % $ python fan_cli.py --temp 20 fan speed: 50.0 % $ python fan_cli.py -h usage: fan_cli.py [-h] --temp TEMP [--hum HUM] Fuzzy fan controller (CS-511) options: -h, --help show this help message and exit --temp TEMP temperature in C (0-50) --hum HUM humidity in % (0-100), default 50 |
Your code (or attach the file) |
Task 2 (Medium, 3 marks): Validation and --explain
Extend fan_cli.py: (a) if --temp is outside 0-50 or --hum outside 0-100, stop with parser.error and a clear message instead of a crash; (b) add a flag --explain that prints every rule that fired with its strength before the speed. Run: --temp 60; --temp 30 --hum 40 --explain; --temp 36 --hum 70 --explain.
Sample run (your output must match):
Output $ python fan_cli.py --temp 60 usage: fan_cli.py [-h] --temp TEMP [--hum HUM] [--explain] fan_cli.py: error: --temp must be between 0 and 50, got 60.0 $ python fan_cli.py --temp 30 --hum 40 --explain R2 IF comfortable AND dry THEN slow strength 0.33 R3 IF comfortable AND NOT dry THEN medium strength 0.33 R4 IF hot AND dry THEN medium strength 0.20 R5 IF hot AND NOT dry THEN fast strength 0.20 fan speed: 45.0 % $ python fan_cli.py --temp 36 --hum 70 --explain R5 IF hot AND NOT dry THEN fast strength 0.80 fan speed: 82.8 % |
Your code (or attach the file) |
Task 3 (Challenge, 4 marks): Batch mode: a day of readings
readings.csv (in the lab folder) has eight readings from a June day in Burewala. Write fan_batch.py with --csv (required), --method mamdani|sugeno (choices, default mamdani) and --out (default fan_plan.csv). It prints one line per reading and writes hour, temperature, humidity, fan to the output CSV. Run it with both methods. At which hour does the fan run fastest, and how much do the two methods differ at 09:00?
Sample run (your output must match):
Output $ python fan_batch.py --csv readings.csv 06:00 29 C 70 % fan 54.9 % 09:00 33 C 60 % fan 80.6 % 12:00 39 C 45 % fan 76.3 % 15:00 42 C 35 % fan 65.5 % 18:00 38 C 50 % fan 83.3 % 21:00 33 C 65 % fan 80.6 % 00:00 30 C 75 % fan 60.3 % 03:00 28 C 80 % fan 50.0 % mamdani: 8 readings -> fan_plan.csv $ python fan_batch.py --csv readings.csv --method sugeno --out fan_plan_sugeno.csv 06:00 29 C 70 % fan 56.1 % 09:00 33 C 60 % fan 83.0 % 12:00 39 C 45 % fan 77.5 % 15:00 42 C 35 % fan 66.5 % 18:00 38 C 50 % fan 83.0 % 21:00 33 C 65 % fan 83.0 % 00:00 30 C 75 % fan 62.4 % 03:00 28 C 80 % fan 50.0 % sugeno: 8 readings -> fan_plan_sugeno.csv hour,temperature,humidity,fan 06,29.0,70.0,54.9 09,33.0,60.0,80.6 12,39.0,45.0,76.3 15,42.0,35.0,65.5 18,38.0,50.0,83.3 21,33.0,65.0,80.6 00,30.0,75.0,60.3 03,28.0,80.0,50.0 |
Your code (or attach the file) |
Part E - Post-Lab Questions (finish as homework if time runs out)
E1. Write the four argparse lines that read a required float option --temp, and use it.
Your answer |
E2. Why is it better to check the range with parser.error than to let the program crash?
Your answer |
E3. Why split the controller into fanfis.py and fan_cli.py?
Your answer |
Marking Rubric (applied to Part D)
Criterion | Full | Partial | None |
|---|---|---|---|
Programs run from the terminal without errors | Runs fully | Small fixable error | Does not run |
argparse used correctly (types, required, default, choices, flags) | All correct | One slip | Several wrong |
Validation, --explain and batch CSV output | All present | Some missing | None |
Answers to the questions in Tasks 1-3 | Clear and correct | Partly correct | Missing |
Submission
- Make a folder RollNo_P10a with fan_cli.py, fan_batch.py, fan_plan.csv and a screenshot of your terminal running Task 2.
- Upload the zipped folder to the LMS / Google Classroom by the end of the day.
- Copy the Task 2 program and its three runs into your Lab Book (Practical 10a page).
- Keep fanfis.py - P10b adds custom functions and a rule file to it.