NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

Here's just the Fuzzy Logic AC Controller:

```python
import numpy as np
import matplotlib.pyplot as plt

def trimf(x, a, b, c):
if x <= a or x >= c:
return 0.0
elif a < x <= b:
return (x - a) / (b - a)
else:
return (c - x) / (c - b)

def trapmf(x, a, b, c, d):
if x <= a or x >= d:
return 0.0
elif a < x <= b:
return (x - a) / (b - a)
elif b < x <= c:
return 1.0
else:
return (d - x) / (d - c)

def fuzzify_temperature(temp):
return {
'cold': trapmf(temp, 0, 0, 15, 22),
'comfortable': trimf(temp, 18, 24, 30),
'warm': trimf(temp, 26, 32, 38),
'hot': trapmf(temp, 34, 40, 50, 50),
}

def fuzzify_humidity(hum):
return {
'low': trapmf(hum, 0, 0, 25, 45),
'medium': trimf(hum, 30, 50, 70),
'high': trapmf(hum, 55, 75, 100, 100),
}

def apply_rules(temp_fuzzy, hum_fuzzy):
t = temp_fuzzy
h = hum_fuzzy
return {
'off': max(min(t['cold'], h['low']),
min(t['cold'], h['medium'])),
'low': max(min(t['cold'], h['high']),
min(t['comfortable'], h['low'])),
'medium': max(min(t['comfortable'], h['medium']),
min(t['comfortable'], h['high']),
min(t['warm'], h['low'])),
'high': max(min(t['warm'], h['medium']),
min(t['warm'], h['high']),
min(t['hot'], h['low'])),
'max': max(min(t['hot'], h['medium']),
min(t['hot'], h['high'])),
}

def cooling_mf(x, label):
mfs = {
'off': trapmf(x, 0, 0, 5, 15),
'low': trimf(x, 10, 25, 40),
'medium': trimf(x, 35, 50, 65),
'high': trimf(x, 60, 75, 90),
'max': trapmf(x, 85, 95, 100, 100),
}
return mfs[label]

def defuzzify(rule_strengths):
x_vals = np.linspace(0, 100, 500)
aggregated = np.zeros(len(x_vals))
for label, strength in rule_strengths.items():
for i, x in enumerate(x_vals):
clipped = min(strength, cooling_mf(x, label))
aggregated[i] = max(aggregated[i], clipped)
if np.sum(aggregated) == 0:
return 0.0
return np.sum(x_vals * aggregated) / np.sum(aggregated)

def plot_membership_functions():
fig, axes = plt.subplots(1, 3, figsize=(16, 4))
fig.suptitle("Fuzzy Logic AC Controller — Membership Functions", fontsize=13, fontweight='bold')

temps = np.linspace(0, 50, 500)
ax = axes[0]
ax.plot(temps, [trapmf(t, 0, 0, 15, 22) for t in temps], 'b', label='Cold')
ax.plot(temps, [trimf(t, 18, 24, 30) for t in temps], 'g', label='Comfortable')
ax.plot(temps, [trimf(t, 26, 32, 38) for t in temps], 'orange', label='Warm')
ax.plot(temps, [trapmf(t, 34, 40, 50, 50) for t in temps], 'r', label='Hot')
ax.set_title("Temperature (°C)")
ax.set_xlabel("Temperature")
ax.set_ylabel("Membership")
ax.legend()
ax.grid(True, alpha=0.3)

hums = np.linspace(0, 100, 500)
ax = axes[1]
ax.plot(hums, [trapmf(h, 0, 0, 25, 45) for h in hums], 'b', label='Low')
ax.plot(hums, [trimf(h, 30, 50, 70) for h in hums], 'g', label='Medium')
ax.plot(hums, [trapmf(h, 55, 75, 100, 100) for h in hums], 'r', label='High')
ax.set_title("Humidity (%)")
ax.set_xlabel("Humidity")
ax.legend()
ax.grid(True, alpha=0.3)

speeds = np.linspace(0, 100, 500)
ax = axes[2]
ax.plot(speeds, [trapmf(s, 0, 0, 5, 15) for s in speeds], 'navy', label='Off')
ax.plot(speeds, [trimf(s, 10, 25, 40) for s in speeds], 'b', label='Low')
ax.plot(speeds, [trimf(s, 35, 50, 65) for s in speeds], 'g', label='Medium')
ax.plot(speeds, [trimf(s, 60, 75, 90) for s in speeds], 'orange', label='High')
ax.plot(speeds, [trapmf(s, 85, 95, 100, 100) for s in speeds], 'r', label='Max')
ax.set_title("Cooling Speed (%)")
ax.set_xlabel("Cooling Speed")
ax.legend()
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig("membership_functions.png", dpi=150)
plt.show()

def plot_output_aggregation(rule_strengths, crisp_output):
x_vals = np.linspace(0, 100, 500)
aggregated = np.zeros(len(x_vals))
colors = {'off': 'navy', 'low': 'blue', 'medium': 'green', 'high': 'orange', 'max': 'red'}

plt.figure(figsize=(10, 5))
for label, strength in rule_strengths.items():
clipped = [min(strength, cooling_mf(x, label)) for x in x_vals]
plt.fill_between(x_vals, 0, clipped, alpha=0.3, color=colors[label], label=f'{label} (α={strength:.2f})')
for i, x in enumerate(x_vals):
aggregated[i] = max(aggregated[i], clipped[i])

plt.fill_between(x_vals, 0, aggregated, alpha=0.15, color='black', label='Aggregated')
plt.axvline(crisp_output, color='red', linewidth=2, linestyle='--', label=f'Crisp Output = {crisp_output:.1f}%')
plt.title("Output Aggregation & Defuzzification (Centroid)")
plt.xlabel("Cooling Speed (%)")
plt.ylabel("Membership")
plt.legend(loc='upper left')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("aggregation.png", dpi=150)
plt.show()

def fuzzy_ac_controller(temperature, humidity, verbose=True):
temp_fuzzy = fuzzify_temperature(temperature)
hum_fuzzy = fuzzify_humidity(humidity)
rule_strengths = apply_rules(temp_fuzzy, hum_fuzzy)
cooling_speed = defuzzify(rule_strengths)

if verbose:
print(f"n{'='*45}")
print(f" Fuzzy Logic AC Controller")
print(f"{'='*45}")
print(f" Input Temperature : {temperature}°C")
print(f" Input Humidity : {humidity}%")
print(f"n Fuzzified Temperature:")
for k, v in temp_fuzzy.items():
print(f" {k:<14}: {v:.3f}")
print(f"n Fuzzified Humidity:")
for k, v in hum_fuzzy.items():
print(f" {k:<14}: {v:.3f}")
print(f"n Rule Firing Strengths:")
for k, v in rule_strengths.items():
bar = '█' * int(v * 20)
print(f" {k:<8}: {v:.3f} {bar}")
print(f"n ✅ Cooling Speed : {cooling_speed:.1f}%")
if cooling_speed < 15:
decision = "AC OFF / Standby"
elif cooling_speed < 35:
decision = "Low Cooling"
elif cooling_speed < 60:
decision = "Moderate Cooling"
elif cooling_speed < 82:
decision = "High Cooling"
else:
decision = "Maximum Cooling"
print(f" 🌬️ Decision : {decision}")
print(f"{'='*45}n")

return cooling_speed, rule_strengths

if __name__ == "__main__":
test_cases = [
(15, 20, "Cool and dry day"),
(24, 50, "Comfortable day"),
(32, 65, "Warm and humid"),
(42, 80, "Very hot and humid"),
(28, 30, "Mildly warm, low humidity"),
]

for temp, hum, desc in test_cases:
print(f"n📍 Scenario: {desc}")
fuzzy_ac_controller(temp, hum)

plot_membership_functions()

speed, strengths = fuzzy_ac_controller(38, 75, verbose=False)
plot_output_aggregation(strengths, speed)
```

Install the one dependency and run:

```bash
pip install numpy matplotlib
python fuzzy_ac.py
```
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.