Nexus Learn

Practical 13A: Deploying a Fuzzy System I: A Model File and a General Engine

Lab Practical CS-511 Artificial Intelligence 9 min read Updated 8 Nov 2026
On this page
  1. 1. Objectives
  2. 2. Word Bank
  3. 3. Background
  4. 4. Time Plan (50 minutes)
  5. Part A - Guided Warm-up (type, run, observe)
  6. Part B - Predict the Output
  7. Part C - Bug Hunt
  8. Part D - Graded Tasks (10 marks)
  9. Part E - Post-Lab Questions (finish as homework if time runs out)
  10. Marking Rubric (applied to Part D)
  11. Submission

1. Objectives

  1. Explain why a deployed fuzzy system separates the MODEL (a data file) from the ENGINE (the code that runs it).
  2. Read and write a fuzzy model as a JSON file: inputs, terms, outputs and rules.
  3. Run the fan model with a general engine and check it gives the same answers as the P10 module.
  4. Write a model checker and deploy a new irrigation model with no change to the engine.

2. Word Bank

Word

Simple meaning

Real-world example

Deploy

Put a finished system into real use, outside the notebook where it was built

The fan controller running on a Raspberry Pi

Model file

A data file that holds everything about one fuzzy system (sets, rules)

fan_model.json

Engine

General code that can run any model file

fisengine.py: load_model(), evaluate()

JSON

JavaScript Object Notation: a plain-text format of {keys: values} and [lists] that every language can read

{"range": [0, 50]}

Parse

Read text and turn it into a structure the program can use

'IF ... THEN ...' -> (conditions, output)

Validation

Checking a model or input for mistakes before using it

unknown term 'warm'

3. Background

Model and engine

In P10 the fan's sets and rules were written inside fanfis.py, so changing a rule meant changing code. Real systems keep the KNOWLEDGE in a data file and the CODE in a general engine. MATLAB does exactly this: writeFIS saves a .fis file and readfis/evalfis load and run it. An engineer can then change a rule - or deploy a completely different controller - without touching (or re-testing) the code.

The model file

fan_model.json holds three parts: inputs (each with a range and its terms, e.g. "hot": ["trapmf", [28, 38, 50, 50]]), outputs (the same) and rules written as readable text: "IF temperature IS hot AND humidity IS NOT dry THEN fan IS fast". JSON is plain text, so it can be opened in Notepad, sent by e-mail and read by any programming language.

The engine

fisengine.py (given, about 50 lines) has load_model(path), which reads the file, builds the membership functions with scikit-fuzzy and parses the rules, and evaluate(model, inputs), which runs Mamdani inference (min for AND, clip, max, centroid - P09a) and returns a dictionary of outputs.

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"

]

}

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

irrigation.csv

moisture,temperature,minutes

16.4,19.3,77.1

35.0,28.3,26.2

40.1,38.6,11.5

11.4,41.8,111.6

17.4,37.8,101.9

56.4,16.1,7.2

13.5,25.8,90.7

16.5,19.9,82.9

57.4,45.0,11.0

41.1,19.3,13.2

... (100 data rows in total - copy the full file from the lab folder)

4. Time Plan (50 minutes)

Minutes

Activity

Part

0-5

Background: model vs engine; the JSON model file

1-3

5-10

Guided warm-up: read the JSON; run the engine once

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. Look inside the model file

Open fan_model.json with the json module (no fuzzy code needed) and list what it holds.

import json

with open("fan_model.json") as f:

m = json.load(f)

print(m["name"])

for name, v in m["inputs"].items():

print(f"input {name:<12} range {v['range']} terms {list(v['terms'])}")

for name, v in m["outputs"].items():

print(f"output {name:<12} range {v['range']} terms {list(v['terms'])}")

print(len(m["rules"]), "rules, e.g.", m["rules"][-1])

Output

Room fan controller (CS-511 P08-P10)

input temperature range [0, 50] terms ['cold', 'comfortable', 'hot']

input humidity range [0, 100] terms ['dry', 'normal', 'humid']

output fan range [0, 100] terms ['slow', 'medium', 'fast']

5 rules, e.g. IF temperature IS hot AND humidity IS NOT dry THEN fan IS fast

A2. Run the model with the engine

Load the model with the engine and evaluate one reading. Compare with the P10 module fanfis.mamdani().

import json

import numpy as np

from fisengine import load_model, evaluate

fan = load_model("fan_model.json")

import fanfis

out = evaluate(fan, {"temperature": 36, "humidity": 70})

print("engine:", out)

print(f"fanfis: {fanfis.mamdani(36, 70):.2f}")

Output

engine: {'fan': 82.77777777777777}

fanfis: 82.78

Part B - Predict the Output

Write your prediction BEFORE running the code. Then run it and correct yourself in a different colour.

B1.

from fisengine import parse_rule

print(parse_rule("IF temperature IS hot AND humidity IS NOT dry THEN fan IS fast"))

My prediction

B2.

import json

text = json.dumps({"range": [0, 50], "terms": {"cold": ["trapmf", [0, 0, 10, 20]]}})

back = json.loads(text)

print(type(text).__name__, type(back).__name__, back["terms"]["cold"][1][3])

My prediction

B3.

# ... set-up: load the fan model with the engine (as shown earlier) ...

print(round(evaluate(fan, {"temperature": 5, "humidity": 90})["fan"], 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: load the fan model with the engine (as shown earlier) ...

m = json.load(open("fan_model.json"))

m["rules"][4] = "IF temperature IS warm AND humidity IS NOT dry THEN fan IS fast"

json.dump(m, open("fan_v2.json", "w"))

fan2 = load_model("fan_v2.json")

print(evaluate(fan2, {"temperature": 36, "humidity": 70}))

Bug, why it happens, and the fixed line(s)

C2.

# ... set-up: load the fan model with the engine (as shown earlier) ...

m = json.load(open("fan_model.json"))

m["inputs"]["temperature"]["terms"]["comfortable"] = ["trimf", [33, 24, 15]]

json.dump(m, open("fan_v3.json", "w"))

fan3 = load_model("fan_v3.json")

Bug, why it happens, and the fixed line(s)

C3.

# ... set-up: load the fan model with the engine (as shown earlier) ...

reading = {"temperature": 36, "humidity": 0.70} # sensor gives humidity as a fraction

print(round(evaluate(fan, reading)["fan"], 2))

It runs and prints

50.0

Bug, why it happens, and the fixed line(s)

Part D - Graded Tasks (10 marks)

Task

Level

Title

Marks

T1

Easy

Same answers as before?

3

T2

Medium

A model checker

3

T3

Challenge

Deploy a new controller with no code change

4

Total

10

Task 1 (Easy, 3 marks): Same answers as before?

Run the fan model with the engine on every row of readings.csv (8 readings from P10a). Print a table with hour, temperature, humidity, the engine's fan speed and fanfis.mamdani(), and check that the largest difference is below 0.01.

Sample run (your output must match):

Output

hour temperature humidity engine fanfis

6 29 70 54.87 54.87

9 33 60 80.56 80.56

12 39 45 76.32 76.32

15 42 35 65.46 65.46

18 38 50 83.33 83.33

21 33 65 80.56 80.56

0 30 75 60.28 60.28

3 28 80 50.00 50.00

largest difference: 0.000000 -> same answers

Your code (or attach the file)

Task 2 (Medium, 3 marks): A model checker

Write check_model(m) that takes the dictionary from json.load and returns a list of problems: (1) a rule uses an unknown variable or term; (2) a term's numbers are not in increasing order; (3) a term's numbers lie outside the variable's range. Test it on fan_model.json (no problems) and on a copy with three mistakes: rule 3 uses 'warm', 'comfortable' is [33, 24, 15] and 'humid' is [50, 80, 100, 120].

Sample run (your output must match):

Output

fan_model.json: no problems

- temperature.comfortable: numbers [33, 24, 15] are not in increasing order

- humidity.humid: numbers [50, 80, 100, 120] go outside the range [0, 100]

- rule 3: 'temperature' has no term 'warm'

Your code (or attach the file)

Task 3 (Challenge, 4 marks): Deploy a new controller with no code change

Write irrigation_model.json for the P11 tubewell problem: moisture 0-60 % (dry trapmf [0, 0, 20, 30], moist trimf [20, 30, 40], wet trapmf [30, 40, 60, 60]); temperature 15-45 °C (mild trapmf [15, 15, 25, 35], hot trapmf [25, 35, 45, 45]); output minutes 0-120 (short trimf [0, 10, 30], medium trimf [20, 50, 80], long trimf [60, 100, 120]); rules: dry AND mild -> medium, dry AND hot -> long, moist -> medium, wet -> short. Run it with the SAME engine on irrigation.csv, print the pump time for (25 %, 38 °C), and the RMSE on the last 30 readings. Compare with P11's ANFIS (test RMSE 5.43 min, 2.10 after tuning).

Sample run (your output must match):

Output

25 %, 38 C -> 71.2 minutes

test RMSE (last 30 readings): 13.14 minutes (ANFIS P11a 5.43, tuned P11b 2.10)

Your code (or attach the file)

Part E - Post-Lab Questions (finish as homework if time runs out)

E1. Why do deployed fuzzy systems keep the model in a data file instead of in the code?

Your answer

E2. Name the three parts of fan_model.json.

Your answer

E3. Give two mistakes a model checker should catch, and why it should run when the file is loaded.

Your answer

Marking Rubric (applied to Part D)

Criterion

Full

Partial

None

Code runs without errors

Runs fully

Small fixable error

Does not run

Engine reproduces the P10 controller (table + difference check)

All correct

One slip

Several wrong

Model checker finds all three kinds of problem

Correct and tested

Partly correct

Missing

New irrigation model deployed with the same engine; RMSE and comparison

Clear and correct

Partly correct

Missing

Submission

  • Make a folder RollNo_P13a with task1.py, task2.py, task3.py (or P13a.ipynb) and irrigation_model.json.
  • Upload the zipped folder to the LMS / Google Classroom by the end of the day.
  • Copy Task 2 code and output into your Lab Book (Practical 13a page).
  • Keep fisengine.py, fan_model.json and check_model() - P13b tests, speeds up and runs the controller.

← All CS-511 material