import numpy as np
import matplotlib.pyplot as plt
import skfuzzy as fuzz
from skfuzzy import control as ctrl

#Creating the Tipping Controller Using the skfuzzy control API

quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')#Generate the array [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

#Auto-membership function population 
quality.automf(3)#Three triangles will be created for input "quality", automf(x): x=3,5,7
service.automf(3)#Three triangles will be created for input "service"
#how automf knows the three options low, medium, high since they have not be defined??

# membership functions
tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])

quality.view()
service.view()
tip.view()

# Rules
rule1 = ctrl.Rule(quality['poor'] | service['poor'], tip['low'])
rule2 = ctrl.Rule(service['average'], tip['medium'])
rule3 = ctrl.Rule(service['good'] | quality['good'], tip['high'])

#Control System Creation and Simulation
tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])#Create Control System using "ControlSystem" class from the skfuzzy.control module
tipping = ctrl.ControlSystemSimulation(tipping_ctrl)
tipping.input['quality'] = 6.5
tipping.input['service'] = 9.8

# Crunch the numbers
tipping.compute()

print (tipping.output['tip']) #The resulting suggested tip is 19.84%
tip.view(sim=tipping)
plt.show()