Nexus Learn

Practical 8B: Building a Fuzzy System II: Testing, Control Surface and Tuning

Lab Practical CS-511 Artificial Intelligence 8 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. Test a fuzzy system over its whole input range with response curves.
  2. Draw and read the control surface of a two-input fuzzy system.
  3. Find gaps in a rule base (inputs where no rule fires) and fix them.
  4. Tune a membership function and compare defuzzification methods.

2. Word Bank

Word

Simple meaning

Real-world example

Response curve

Output plotted against one input while the others stay fixed

Fan speed vs temperature at 70 % humidity

Control surface

3-D plot of the output for every pair of input values

A 'landscape' of fan speed

Rule coverage

Every possible input fires at least one rule

No rule for cold -> no answer at 5 °C

Gap

An input where no rule fires, so there is no output

KeyError: 'fan'

Tuning

Adjusting sets or rules until the behaviour is right

Make 'hot' start at 26 °C

Vectorised input

Giving a whole array of inputs at once

51 temperatures in one compute()

3. Background

Why test a fuzzy system?

In P08a we checked a few inputs. A real controller (the fan in a classroom, the AC in a bank, a tubewell motor) must behave sensibly for EVERY input. Engineers test fuzzy systems in three ways: (1) response curves - change one input and watch the output; (2) the control surface - a 3-D plot of the output over two inputs, which shows jumps, flat areas and wrong regions at a glance; (3) coverage - check that some rule fires everywhere.

Vectorised simulation

ControlSystemSimulation accepts NumPy arrays: give 51 temperatures (or a whole meshgrid) and one compute() returns all the outputs. Use np.meshgrid to make every (temperature, humidity) pair for the surface.

Tuning

If users say 'the fan is too slow on sticky 30 °C days', we change a membership function or a rule, then test again. MATLAB's Fuzzy Logic Designer has a Rule Viewer and Surface Viewer for exactly this; we build our own.

Data files for this lab

No data file is needed - the programs make their own data.

4. Time Plan (50 minutes)

Minutes

Activity

Part

0-5

Background: response curve, control surface, coverage

1-3

5-10

Guided warm-up: response curve and control surface

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 response curve: fan speed against temperature

Humidity is fixed at 70 %; 51 temperatures go in as one array.

import numpy as np

import skfuzzy as fuzz

from skfuzzy import control as ctrl

temp = ctrl.Antecedent(np.arange(0, 51, 1), "temperature")

hum = ctrl.Antecedent(np.arange(0, 101, 1), "humidity")

fan = ctrl.Consequent(np.arange(0, 101, 1), "fan")

temp["cold"] = fuzz.trapmf(temp.universe, [0, 0, 10, 20])

temp["comfortable"] = fuzz.trimf(temp.universe, [15, 24, 33])

temp["hot"] = fuzz.trapmf(temp.universe, [28, 38, 50, 50])

hum["dry"] = fuzz.trapmf(hum.universe, [0, 0, 20, 50])

hum["normal"] = fuzz.trimf(hum.universe, [30, 50, 70])

hum["humid"] = fuzz.trapmf(hum.universe, [50, 80, 100, 100])

fan["slow"] = fuzz.trimf(fan.universe, [0, 0, 50])

fan["medium"] = fuzz.trimf(fan.universe, [25, 50, 75])

fan["fast"] = fuzz.trimf(fan.universe, [50, 100, 100])

rules = [ctrl.Rule(temp["cold"], fan["slow"]),

ctrl.Rule(temp["comfortable"] & hum["dry"], fan["slow"]),

ctrl.Rule(temp["comfortable"] & ~hum["dry"], fan["medium"]),

ctrl.Rule(temp["hot"] & hum["dry"], fan["medium"]),

ctrl.Rule(temp["hot"] & ~hum["dry"], fan["fast"])]

import matplotlib.pyplot as plt

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules))

t = np.arange(0, 51, 1)

sim.input["temperature"] = t

sim.input["humidity"] = np.full(t.shape, 70)

sim.compute()

speed = sim.output["fan"]

plt.figure(figsize=(7, 2.6)); plt.plot(t, speed)

plt.xlabel("Temperature (°C)"); plt.ylabel("Fan speed (%)"); plt.title("Humidity 70 %"); plt.grid(alpha=0.3)

plt.tight_layout(); plt.savefig("response.png", dpi=90)

for x in range(0, 51, 10):

print(f"{x:>2} C -> {speed[x]:.1f} %")

print("Saved response.png")

Output

0 C -> 16.7 %

10 C -> 16.7 %

20 C -> 50.0 %

30 C -> 60.3 %

40 C -> 83.3 %

50 C -> 83.3 %

Saved response.png

A2. The control surface

np.meshgrid makes every pair of temperature and humidity; one compute() fills the whole grid.

# ... set-up: imports, variables, terms and the five rules (copy from Part A1) ...

import matplotlib.pyplot as plt

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules))

T, H = np.meshgrid(np.arange(0, 51, 2), np.arange(0, 101, 5))

sim.input["temperature"] = T

sim.input["humidity"] = H

sim.compute()

Z = sim.output["fan"]

fig = plt.figure(figsize=(6, 4)); ax = fig.add_subplot(projection="3d")

ax.plot_surface(T, H, Z, cmap="viridis")

ax.set_xlabel("Temperature (°C)"); ax.set_ylabel("Humidity (%)"); ax.set_zlabel("Fan (%)")

plt.tight_layout(); plt.savefig("surface.png", dpi=90)

print(f"grid {Z.shape}, fan from {Z.min():.1f} to {Z.max():.1f} %")

print("Saved surface.png")

Output

grid (21, 26), fan from 16.7 to 83.3 %

Saved surface.png

Part B - Predict the Output

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

B1.

# ... set-up: imports, variables, terms and the five rules (copy from Part A1) ...

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules))

sim.input["temperature"] = np.array([20, 36])

sim.input["humidity"] = np.array([70, 70])

sim.compute()

print(np.round(sim.output["fan"], 2))

My prediction

B2.

# ... set-up: imports, variables, terms and the five rules (copy from Part A1) ...

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules))

sim.input["temperature"] = 36

sim.input["humidity"] = 70

sim.compute(); print(round(sim.output["fan"], 2))

sim.input["humidity"] = 10

sim.compute(); print(round(sim.output["fan"], 2))

My prediction

B3.

# ... set-up: imports, variables, terms and the five rules (copy from Part A1) ...

fan.defuzzify_method = "mom" # mean of maximum

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules))

sim.input["temperature"] = 36

sim.input["humidity"] = 70

sim.compute(); print(round(sim.output["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: imports, variables, terms and the five rules (copy from Part A1) ...

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules[1:])) # rules 2-5 only

sim.input["temperature"] = 5

sim.input["humidity"] = 50

sim.compute()

print(sim.output["fan"])

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

C2.

# ... set-up: imports, variables, terms and the five rules (copy from Part A1) ...

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules))

sim.input["humidity"] = 70

for t in (10, 25, 40):

sim.input["temperature"] = t

print(t, "C ->", round(sim.output.get("fan", 0), 2))

It runs and prints

10 C -> 0

25 C -> 0

40 C -> 0

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

C3.

# ... set-up: imports, variables, terms and the five rules (copy from Part A1) ...

rules[4] = ctrl.Rule(temp["hot"] | ~hum["dry"], fan["fast"]) # rule 5: IF hot AND NOT dry THEN fast

sim = ctrl.ControlSystemSimulation(ctrl.ControlSystem(rules))

sim.input["temperature"] = 20

sim.input["humidity"] = 80

sim.compute()

print("fan at 20 C, 80 %:", round(sim.output["fan"], 2))

It runs and prints

fan at 20 C, 80 %: 68.96

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

Part D - Graded Tasks (10 marks)

Task

Level

Title

Marks

T1

Easy

Three response curves

3

T2

Medium

Read the control surface

3

T3

Challenge

Coverage check and tuning

4

Total

10

Task 1 (Easy, 3 marks): Three response curves

Plot fan speed against temperature (0-50 °C, step 1) for humidity 20 %, 50 % and 80 % on one figure (save task1.png). Print the speed at 30 °C for each humidity. Below what temperature do the three curves become the same, and why?

Sample run (your output must match):

Output

humidity 20 %: fan at 30 C = 31.8 %

humidity 50 %: fan at 30 C = 60.3 %

humidity 80 %: fan at 30 C = 60.3 %

curves identical for temperatures up to 15 C

Saved task1.png

Your code (or attach the file)

Task 2 (Medium, 3 marks): Read the control surface

Compute the control surface for temperature 0-50 °C (step 2) and humidity 0-100 % (step 5), plot it (save task2.png) and print: the lowest and highest fan speed with one input pair where each happens, and the percentage of grid points where the fan runs at 75 % or more.

Sample run (your output must match):

Output

lowest 16.7 % at 0 C, 0 %

highest 83.3 % at 38 C, 50 %

fan >= 75 % on 19.6 % of the grid

Saved task2.png

Your code (or attach the file)

Task 3 (Challenge, 4 marks): Coverage check and tuning

(a) Write gaps(rule_list) that tries every temperature 0-50 and humidity 0-100 in steps of 5 and returns the pairs where no rule fires ('fan' missing from sim.output). Print the number of gaps and the temperature range for rules 2-5 only, then for all five rules. (b) Users say the fan is too slow on sticky 30 °C, 80 % days. Change 'hot' to trapmf [26, 36, 50, 50], rebuild the rules and print the speed at (30 °C, 80 %) before and after.

Sample run (your output must match):

Output

rules 2-5: 84 gaps, temperatures 0-15 C

all five rules: 0 gaps

30 C, 80 %: before 60.3 %, after tuning 66.2 %

Your code (or attach the file)

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

E1. What is the difference between a response curve and a control surface?

Your answer

E2. What is a gap in a rule base and how did scikit-fuzzy show it?

Your answer

E3. After tuning 'hot', why must you look at the whole control surface again?

Your answer

Marking Rubric (applied to Part D)

Criterion

Full

Partial

None

Code runs without errors

Runs fully

Small fixable error

Does not run

Correct vectorised inputs, meshgrid and loops

All correct

One slip

Several wrong

Plots and printed results

All present

Some missing

None

Explanations (identical curves, surface, gaps, tuning)

Clear and correct

Partly correct

Missing

Submission

  • Make a folder RollNo_P08b with task1.py, task2.py, task3.py (or P08b.ipynb), task1.png and task2.png.
  • Upload the zipped folder to the LMS / Google Classroom by the end of the day.
  • Copy Task 2 and Task 3 code and output into your Lab Book (Practical 08b page); paste or sketch task2.png.
  • Keep your controller - P09 compares this Mamdani system with a Sugeno system.

← All CS-511 material