Nexus Learn

Practical 10B: Custom Functions and a Rule File

Lab Practical CS-511 Artificial Intelligence 10 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. Write a custom membership function (generalised bell) and check it against scikit-fuzzy.
  2. Replace the AND operator with a custom one (product) and compare the results.
  3. Store the rule base in a JSON file so rules can change without changing the program.
  4. Choose the rule file from the command line and test a new rule.

2. Word Bank

Word

Simple meaning

Real-world example

Custom function

Your own Python function used inside the fuzzy system

gbell(x, a, b, c)

Generalised bell

Smooth bell-shaped membership function with width a, slope b, centre c

'comfortable' around 24 °C

T-norm

Any operator that can serve as fuzzy AND

min, product

JSON

A text format for data: { } objects, [ ] lists, double quotes

rules.json

Rule base

The list of IF-THEN rules of a fuzzy system

five fan rules

Data-driven program

Behaviour comes from a data file, not from code

change rules.json, not the .py

3. Background

Custom functions

MATLAB's Fuzzy Logic Toolbox lets you plug in your own membership functions, AND/OR methods and defuzzifiers. In Python this is natural: any function that takes x and returns degrees in [0, 1] can be a membership function, and any function of two degrees that behaves like AND (a T-norm: min, product, ...) can replace min. P09a already passed the implication method as a parameter; today we do the same for membership functions and AND.

Generalised bell

gbell(x) = 1 / (1 + |(x - c)/a|^(2b)): centre c, width a (degree 0.5 at c ± a), slope b (bigger = steeper sides). scikit-fuzzy has fuzz.gbellmf(x, a, b, c) - we write our own and compare.

Rules as data

If the rules are inside the code, only a programmer can change them. If they are in a JSON file, an agriculture officer or a teacher can edit the file and run again. rules.json (in the lab folder) holds the five fan rules in words such as 'humidity is not dry'; a small engine reads and evaluates them.

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)

rules.json

{

"name": "Pedestal fan, Burewala summer",

"rules": [

{"if": ["temperature is cold"], "then": "slow"},

{"if": ["temperature is comfortable", "humidity is dry"], "then": "slow"},

{"if": ["temperature is comfortable", "humidity is not dry"], "then": "medium"},

{"if": ["temperature is hot", "humidity is dry"], "then": "medium"},

{"if": ["temperature is hot", "humidity is not dry"], "then": "fast"}

]

}

4. Time Plan (50 minutes)

Minutes

Activity

Part

0-5

Background: custom MF, T-norms, rules as data

1-3

5-10

Guided warm-up: rules from JSON; a custom membership function

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. The rule base in a file

Read rules.json, print the rules in words and evaluate them with a small engine. The answer must equal P09 (82.78 % at 36 °C, 70 %).

import json

from functools import reduce

import numpy as np

import skfuzzy as fuzz

import fanfis

def degree(condition, t, h):

"""'temperature is hot' or 'humidity is not dry' -> degree for the inputs t, h."""

words = condition.split()

var, negate, term = words[0], words[2] == "not", words[-1]

x, sets, value = (fanfis.t_x, fanfis.T, t) if var == "temperature" else (fanfis.h_x, fanfis.H, h)

m = fanfis.mu(x, sets[term], value)

return 1 - m if negate else m

def load_rules(path):

return json.load(open(path))["rules"]

def mamdani_rules(rules, t, h, and_op=min):

agg = np.zeros_like(fanfis.f_x, dtype=float)

for r in rules:

w = reduce(and_op, [degree(c, t, h) for c in r["if"]])

agg = np.fmax(agg, np.fmin(fanfis.F[r["then"]], w))

return float(fuzz.defuzz(fanfis.f_x, agg, "centroid"))

data = json.load(open("rules.json"))

print(data["name"])

for i, r in enumerate(data["rules"], 1):

print(f" R{i} IF {' AND '.join(r['if'])} THEN fan is {r['then']}")

print(f"36 C, 70 %: rule file {mamdani_rules(data['rules'], 36, 70):.2f} % fanfis {fanfis.mamdani(36, 70):.2f} %")

Output

Pedestal fan, Burewala summer

R1 IF temperature is cold THEN fan is slow

R2 IF temperature is comfortable AND humidity is dry THEN fan is slow

R3 IF temperature is comfortable AND humidity is not dry THEN fan is medium

R4 IF temperature is hot AND humidity is dry THEN fan is medium

R5 IF temperature is hot AND humidity is not dry THEN fan is fast

36 C, 70 %: rule file 82.78 % fanfis 82.78 %

A2. A custom membership function

Write the generalised bell by hand and compare it with scikit-fuzzy's gbellmf and with the P07a triangle.

import numpy as np

import skfuzzy as fuzz

import matplotlib.pyplot as plt

def gbell(x, a, b, c):

return 1 / (1 + np.abs((x - c) / a) ** (2 * b))

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

mine, lib = gbell(x, 6, 2, 24), fuzz.gbellmf(x, 6, 2, 24)

print(f"largest difference from fuzz.gbellmf: {np.abs(mine - lib).max():.2e}")

for t in (18, 24, 30, 33):

print(f"{t} C: bell {mine[t]:.3f} triangle {fuzz.trimf(x, [15, 24, 33])[t]:.3f}")

plt.figure(figsize=(7, 2.4)); plt.plot(x, mine, label="custom gbell(6, 2, 24)"); plt.plot(x, fuzz.trimf(x, [15, 24, 33]), "--", label="trimf [15, 24, 33]")

plt.xlabel("Temperature (°C)"); plt.ylabel("Degree"); plt.title("comfortable"); plt.legend(); plt.grid(alpha=0.3)

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

print("Saved bell.png")

Output

largest difference from fuzz.gbellmf: 0.00e+00

18 C: bell 0.500 triangle 0.333

24 C: bell 1.000 triangle 1.000

30 C: bell 0.500 triangle 0.333

33 C: bell 0.165 triangle 0.000

Saved bell.png

Part B - Predict the Output

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

B1.

import json

rule = json.loads('{"if": ["temperature is hot", "humidity is not dry"], "then": "fast"}')

print(len(rule["if"]), rule["then"], rule["if"][1].split()[2])

My prediction

B2.

a, b = 0.6, 0.5

print(min(a, b), a * b)

My prediction

B3.

def gbell(x, a, b, c):

return 1 / (1 + abs((x - c) / a) ** (2 * b))

print(gbell(24, 6, 2, 24), gbell(30, 6, 2, 24), gbell(18, 6, 2, 24))

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.

import json

rule = json.loads("{'if': ['temperature is hot'], 'then': 'fast'}")

print(rule)

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

C2.

import json

from functools import reduce

import numpy as np

import skfuzzy as fuzz

import fanfis

def degree(condition, t, h):

"""'temperature is hot' or 'humidity is not dry' -> degree for the inputs t, h."""

words = condition.split()

var, negate, term = words[0], words[2] == "not", words[-1]

x, sets, value = (fanfis.t_x, fanfis.T, t) if var == "temperature" else (fanfis.h_x, fanfis.H, h)

m = fanfis.mu(x, sets[term], value)

return 1 - m if negate else m

def load_rules(path):

return json.load(open(path))["rules"]

def mamdani_rules(rules, t, h, and_op=min):

agg = np.zeros_like(fanfis.f_x, dtype=float)

for r in rules:

w = reduce(and_op, [degree(c, t, h) for c in r["if"]])

agg = np.fmax(agg, np.fmin(fanfis.F[r["then"]], w))

return float(fuzz.defuzz(fanfis.f_x, agg, "centroid"))

rules = load_rules("rules.json") + [{"if": ["temperature is warm"], "then": "medium"}]

print(mamdani_rules(rules, 30, 40))

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

C3.

import numpy as np

import skfuzzy as fuzz

def gbell(x, a, b, c):

return 1 / (1 + np.abs((x - c) / a) ** b)

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

print(f"at 33 C: mine {gbell(x, 6, 2, 24)[33]:.3f}, scikit-fuzzy {fuzz.gbellmf(x, 6, 2, 24)[33]:.3f}")

It runs and prints

at 33 C: mine 0.308, scikit-fuzzy 0.165

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

Part D - Graded Tasks (10 marks)

Task

Level

Title

Marks

T1

Easy

A bell-shaped 'comfortable'

3

T2

Medium

A custom AND: product

3

T3

Challenge

Change the rules, not the code

4

Total

10

Task 1 (Easy, 3 marks): A bell-shaped 'comfortable'

Write gbell(x, a, b, c) yourself. Using a = 6, b = 2, c = 24 for 'comfortable', (a) print the largest difference from fuzz.gbellmf on 0-50 °C; (b) print the degree of 18, 21, 24, 27 and 30 °C for the bell and for trimf [15, 24, 33]; (c) plot both (save task1.png). Where does the bell give a higher degree than the triangle?

Sample run (your output must match):

Output

(a) largest difference from fuzz.gbellmf: 0.00e+00

(b) 18 C: bell 0.500 triangle 0.333

(b) 21 C: bell 0.941 triangle 0.667

(b) 24 C: bell 1.000 triangle 1.000

(b) 27 C: bell 0.941 triangle 0.667

(b) 30 C: bell 0.500 triangle 0.333

Saved task1.png

Your code (or attach the file)

Task 2 (Medium, 3 marks): A custom AND: product

fanfis.mamdani(t, h, and_op=...) accepts any AND function. Compute the fan speed for the five P07b days (30, 40), (34, 65), (38, 75), (41, 55), (36, 90) with and_op=min and with your own product function. Print a table with the difference. Which day changes and why do the others stay the same?

Sample run (your output must match):

Output

input min product diff

30 C, 40 % 45.04 51.37 +6.33

34 C, 65 % 81.43 81.43 +0.00

38 C, 75 % 83.33 83.33 +0.00

41 C, 55 % 83.33 83.33 +0.00

36 C, 90 % 82.78 82.78 +0.00

Your code (or attach the file)

Task 3 (Challenge, 4 marks): Change the rules, not the code

Write fis_rules.py with argparse options --rules (default rules.json), --temp and --hum that loads the rule file and prints the speed. Then create rules_v2.json = the five rules plus R6: IF temperature is comfortable AND humidity is humid THEN fast (sticky days feel hotter). Run both rule files for (26 °C, 85 %) and (30 °C, 40 %). Which input changes and why?

Sample run (your output must match):

Output

$ python fis_rules.py --temp 26 --hum 85

rules.json: 5 rules -> fan 50.0 %

$ python fis_rules.py --rules rules_v2.json --temp 26 --hum 85

rules_v2.json: 6 rules -> fan 66.6 %

$ python fis_rules.py --temp 30 --hum 40

rules.json: 5 rules -> fan 45.0 %

$ python fis_rules.py --rules rules_v2.json --temp 30 --hum 40

rules_v2.json: 6 rules -> fan 45.0 %

Your code (or attach the file)

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

E1. Write the generalised bell formula and explain a, b and c.

Your answer

E2. What is a T-norm? Give two examples and which is larger.

Your answer

E3. Give two advantages of keeping the rule base in a JSON file.

Your answer

Marking Rubric (applied to Part D)

Criterion

Full

Partial

None

Code runs without errors

Runs fully

Small fixable error

Does not run

Custom bell and product T-norm correct

All correct

One slip

Several wrong

Rule file loaded and chosen from the command line

All present

Some missing

None

Explanations (bell vs triangle, which day changes, which input changes)

Clear and correct

Partly correct

Missing

Submission

  • Make a folder RollNo_P10b with task1.py, task2.py, fis_rules.py, rules_v2.json and task1.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 10b page).
  • Keep fanfis.py and your rule files - P13 deploys a fuzzy system.

← All CS-511 material