Exemplo n.º 1
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

f_qual = int(input("How did you liked the food ? [0-10] > "))
s_qual = int(input("How did you liked the service ? [0-10] > "))

quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')

tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

quality.automf(3)
service.automf(3)

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])

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'])

tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])

tipping = ctrl.ControlSystemSimulation(tipping_ctrl)

tipping.input['quality'] = f_qual
tipping.input['service'] = s_qual

tipping.compute()
Exemplo n.º 2
0
def ParteDifusa(VADIDF):
        # Los rangos que se va moaver las variable
    sujeto = ctrl.Antecedent(np.arange(0, 6, 1), 'sujeto')
    tiempo_verbal = ctrl.Antecedent(np.arange(0, 6, 1), 'tiempo_verbal')
    adjetivo = ctrl.Antecedent(np.arange(0, 6, 1), 'adjetivo')
    adverbio = ctrl.Antecedent(np.arange(0, 6, 1), 'adverbio')    
    nivelAprendizajeIngles = ctrl.Consequent(np.arange(5, 21, 1), 'nivelAprendizajeIngles')

    sujeto['bajo'] = fuzz.trimf(sujeto.universe, [0, 0, 3])
    sujeto['normal'] = fuzz.trimf(sujeto.universe, [2, 5, 5])
    tiempo_verbal['bajo'] = fuzz.trimf(tiempo_verbal.universe, [0, 0, 3])
    tiempo_verbal['normal'] = fuzz.trimf(tiempo_verbal.universe, [2, 5, 5])
    adjetivo['bajo'] = fuzz.trimf(adjetivo.universe, [0, 0, 3])
    adjetivo['normal'] = fuzz.trimf(adjetivo.universe, [2, 5, 5])    
    adverbio['bajo'] = fuzz.trimf(adverbio.universe, [0, 0, 3])
    adverbio['normal'] = fuzz.trimf(adverbio.universe, [2, 5, 5])
            
    nivelAprendizajeIngles['C'] = fuzz.trimf(nivelAprendizajeIngles.universe, [5, 5, 10])
    nivelAprendizajeIngles['B'] = fuzz.trimf(nivelAprendizajeIngles.universe, [8, 12, 16])
    nivelAprendizajeIngles['A'] = fuzz.trimf(nivelAprendizajeIngles.universe, [14, 16, 17])
    nivelAprendizajeIngles['AD'] = fuzz.trimf(nivelAprendizajeIngles.universe, [16, 20, 20])    

#################################################################################################
    figVisualizacion =ctrl.fuzzyvariable.FuzzyVariableVisualizer(sujeto).view() 
    figAnalisis =ctrl.fuzzyvariable.FuzzyVariableVisualizer(tiempo_verbal).view()       
    figDeduccionInformal =ctrl.fuzzyvariable.FuzzyVariableVisualizer(adjetivo).view()
    figDeduccionFormal =ctrl.fuzzyvariable.FuzzyVariableVisualizer(adverbio).view()
    figNCG =ctrl.fuzzyvariable.FuzzyVariableVisualizer(nivelAprendizajeIngles).view() 
    graph1_url = grafico_variable_fuzzy(figVisualizacion[0],"static/images/fuzzy/sujeto.jpg")    
    graph2_url = grafico_variable_fuzzy(figAnalisis[0],"static/images/fuzzy/tiempo_verbal.jpg")
    graph3_url = grafico_variable_fuzzy(figDeduccionInformal[0],"static/images/fuzzy/adjetivo.jpg")
    graph4_url = grafico_variable_fuzzy(figDeduccionFormal[0],"static/images/fuzzy/adverbio.jpg")
    graph5_url = grafico_variable_fuzzy(figNCG[0],"static/images/fuzzy/nivelAprendizajeIngles.jpg")
    
#################################################################################################
    
    #-------reglas nivelAprendizajeIngles
    rule1 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['bajo'] & adjetivo['bajo'] & adverbio['bajo'], nivelAprendizajeIngles['C'])
    rule2 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['bajo'] & adjetivo['bajo'] & adverbio['normal'], nivelAprendizajeIngles['C'])
    rule3 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['bajo'] & adjetivo['normal'] & adverbio['bajo'], nivelAprendizajeIngles['C'])
    rule4 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['bajo'] & adjetivo['normal'] & adverbio['normal'], nivelAprendizajeIngles['C'])        
    rule5 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['normal'] & adjetivo['bajo'] & adverbio['bajo'], nivelAprendizajeIngles['C'])
    rule6 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['normal'] & adjetivo['bajo'] & adverbio['normal'], nivelAprendizajeIngles['C'])
    rule7 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['normal'] & adjetivo['normal'] & adverbio['bajo'], nivelAprendizajeIngles['C'])   
    rule8 = ctrl.Rule(sujeto['bajo'] & tiempo_verbal['normal'] & adjetivo['normal'] & adverbio['normal'], nivelAprendizajeIngles['C'])
    rule9 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['bajo'] & adjetivo['bajo'] & adverbio['bajo'], nivelAprendizajeIngles['B'])
    rule10 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['bajo'] & adjetivo['bajo'] & adverbio['normal'], nivelAprendizajeIngles['B'])
    rule11 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['bajo'] & adjetivo['normal'] & adverbio['bajo'], nivelAprendizajeIngles['B'])
    rule12 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['bajo'] & adjetivo['normal'] & adverbio['normal'], nivelAprendizajeIngles['B'])
    rule13 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['normal'] & adjetivo['bajo'] & adverbio['bajo'], nivelAprendizajeIngles['B'])
    rule14 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['normal'] & adjetivo['bajo'] & adverbio['normal'], nivelAprendizajeIngles['A'])
    rule15 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['normal'] & adjetivo['normal'] & adverbio['bajo'], nivelAprendizajeIngles['A'])
    rule16 = ctrl.Rule(sujeto['normal'] & tiempo_verbal['normal'] & adjetivo['normal'] & adverbio['normal'], nivelAprendizajeIngles['AD'])
    
    acc_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10,
                                    rule11, rule12, rule13, rule14, rule15, rule16])
    
    acc = ctrl.ControlSystemSimulation(acc_ctrl)
    
    
    #entradas al sistema
    acc.input['sujeto'] = VADIDF[0]
    acc.input['tiempo_verbal'] = VADIDF[1]
    acc.input['adjetivo'] = VADIDF[2]
    acc.input['adverbio'] = VADIDF[3]    
    acc.compute()
    nivel_competencia = acc.output['nivelAprendizajeIngles']
    print("nivel de Aprendizaje en Ingles: ",nivel_competencia)  
   
    figNCG2 =ctrl.fuzzyvariable.FuzzyVariableVisualizer(nivelAprendizajeIngles).view(sim=acc)    
    graph6_url = grafico_variable_fuzzy(figNCG2[0],"static/images/fuzzy/nivelAprendizajeIngles.jpg")        
    return nivel_competencia
Exemplo n.º 3
0
## Generate the dataset, save the data and a plot of it as well

import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from skfuzzy import control as ctrl
import scipy.io

# Set for reproducibility
np.random.seed(seed=123)

loc_risk = ctrl.Antecedent(np.arange(0, 11, 1), 'loc_risk')
maintenance = ctrl.Antecedent(np.arange(0, 11, 1), 'maintenance')
downtime = ctrl.Consequent(np.arange(0, 101, 1), 'downtime')

# Membership functions with parameters pre-specified.
# Data would be generated from this fuzzy system
# MCMC would be used later to identify whether the parameters of the fuzzy system can be recovered from the data.
loc_risk['low'] = fuzz.trimf(loc_risk.universe, [0, 0, 5])
loc_risk['medium'] = fuzz.trimf(loc_risk.universe, [0, 5, 10])
loc_risk['high'] = fuzz.trimf(loc_risk.universe, [5, 10, 10])

maintenance['poor'] = fuzz.trimf(maintenance.universe, [0, 0, 5])
maintenance['average'] = fuzz.trimf(maintenance.universe, [0, 5, 10])
maintenance['good'] = fuzz.trimf(maintenance.universe, [5, 10, 10])

downtime['low'] = fuzz.trimf(downtime.universe, [0, 0, 50])
downtime['medium'] = fuzz.trimf(downtime.universe, [0, 50, 100])
downtime['high'] = fuzz.trimf(downtime.universe, [50, 100, 100])
Exemplo n.º 4
0
#INITIAL CONDITIONS: Where is the quadcopter at the beginning of the simulation?
##############################################################################
v0 = 0; u0 = 0; w0 = 0; x0 = 2.; y0 = 2.; theta0 = np.radians(0);

##############################################################################
#SET TARGET: Where do you want the quadcopter to be?
##############################################################################
target = [0, 5] # [x-coordinate, y-coordinate]

##############################################################################
#FUZZY CONTROLLER
##############################################################################
from skfuzzy import control as ctrl

#Antecedents
alt_error = ctrl.Antecedent(np.arange(-20, 20, .5), 'alt_error')
alt_delta = ctrl.Antecedent(np.arange(-5, 5, .125), 'alt_delta')

theta = ctrl.Antecedent(np.arange(-3.14, 3.14 ,.05), 'theta')
omega = ctrl.Antecedent(np.arange(-3.14/4, 3.14/4 ,.05/4), 'omega')

#Consequents
force = ctrl.Consequent(np.arange(5.8, 13.8, .2), 'force')
torque = ctrl.Consequent(np.arange(-3.14, 3.14, .05), 'torque')

# Auto-membership function population is possible with .automf(3, 5, or 7)
names = ['nb', 'ns', 'ze', 'ps', 'pb']

alt_error.automf(names=names)
alt_delta.automf(names=names)
Exemplo n.º 5
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

pendapatan = ctrl.Antecedent(np.arange(0, 3, 1), 'pendapatan')
hutang = ctrl.Antecedent(np.arange(0, 100, 1), 'hutang')
BLT = ctrl.Consequent(np.arange(0, 3, 1), 'BLT')

pendapatan['rendah'] = fuzz.trimf(pendapatan.universe, [0, 0, 1])
pendapatan['sedang'] = fuzz.trimf(pendapatan.universe, [0, 1, 2])
pendapatan['tinggi'] = fuzz.trimf(pendapatan.universe, [1, 2, 2])

hutang['rendah'] = fuzz.trimf(hutang.universe, [0, 0, 49])
hutang['sedang'] = fuzz.trimf(hutang.universe, [0, 49, 98])
hutang['tinggi'] = fuzz.trimf(hutang.universe, [49, 98, 98])

BLT['tidak_layak'] = fuzz.trimf(BLT.universe, [0, 0, 0.5])
BLT['layak'] = fuzz.trimf(BLT.universe, [0.5, 1, 1])

rule1 = ctrl.Rule(pendapatan['rendah'] & hutang['rendah'], BLT['layak'])
rule2 = ctrl.Rule(pendapatan['rendah'] & hutang['sedang'], BLT['layak'])
rule3 = ctrl.Rule(pendapatan['rendah'] & hutang['tinggi'], BLT['layak'])
rule4 = ctrl.Rule(pendapatan['sedang'] & hutang['rendah'], BLT['tidak_layak'])
rule5 = ctrl.Rule(pendapatan['sedang'] & hutang['sedang'], BLT['tidak_layak'])
rule6 = ctrl.Rule(pendapatan['sedang'] & hutang['tinggi'], BLT['layak'])
rule7 = ctrl.Rule(pendapatan['tinggi'] & hutang['rendah'], BLT['tidak_layak'])
rule8 = ctrl.Rule(pendapatan['tinggi'] & hutang['sedang'], BLT['tidak_layak'])
rule9 = ctrl.Rule(pendapatan['tinggi'] & hutang['tinggi'], BLT['tidak_layak'])

tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9])
pos_l = fzy.trimf(posicao, [0, 0, 5])
pos_c = fzy.trimf(posicao, [4, 5, 6])
pos_r = fzy.trimf(posicao, [5, 10, 10])

# Direção: low = esquerda; medium = centro; high = direita
direct_l = fzy.trimf(direcao, [0, 0, 5])
direct_m = fzy.trimf(direcao, [4, 5, 6])
direct_h = fzy.trimf(direcao, [5, 10, 10])

# Velocidade de saida: low = baixa; medium = normal; high = alta
vel_sa_l = fzy.trapmf(velocidade_saida, [0, 0, 2, 4])
vel_sa_m = fzy.trimf(velocidade_saida, [3, 5, 7])
vel_sa_h = fzy.trapmf(velocidade_saida, [6, 8, 10, 10])

# Define as entradas e saidas do sistema
velocidade_entrada = ctrl.Antecedent(velocidade_entrada,
                                     "Velocidade de Entrada")
proximidade = ctrl.Antecedent(proximidade, "Proximidade")
posicao = ctrl.Antecedent(posicao, "Posição")
direcao = ctrl.Consequent(direcao, "Direção")
velocidade_saida = ctrl.Consequent(velocidade_saida, "Velocidade de Saida")

# Faixa de valores para utilizar nas regras
velocidade_entrada["Baixa"] = vel_en_l
velocidade_entrada["Normal"] = vel_en_m
velocidade_entrada["Alta"] = vel_en_h

proximidade["Perto"] = pro_c
proximidade["Normal"] = pro_m
proximidade["Longe"] = pro_f

posicao["Esquerda"] = pos_l
Exemplo n.º 7
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Cria as variáveis do problema
comida = ctrl.Antecedent(np.arange(0, 26, 1), 'comida')
servico = ctrl.Antecedent(np.arange(0, 11, 1), 'servico')
gorjeta = ctrl.Consequent(np.arange(0, 26, 1), 'gorjeta')

# Cria as funções de pertinência usando tipos variados
servico['ruim'] = fuzz.trimf(servico.universe, [0, 0, 5])
servico['aceitável'] = fuzz.gaussmf(servico.universe, 5, 2)
servico['excelente'] = fuzz.gaussmf(servico.universe, 10, 3)

comida['péssima'] = fuzz.trapmf(comida.universe, [0, 7, 12, 15])
comida['comível'] = fuzz.trapmf(comida.universe, [13, 16, 18, 20])
comida['deliciosa'] = fuzz.trapmf(comida.universe, [17, 20, 23, 25])

gorjeta['baixa'] = fuzz.trimf(gorjeta.universe, [0, 0, 13])
gorjeta['média'] = fuzz.trapmf(gorjeta.universe, [0, 13, 15, 25])
gorjeta['alta'] = fuzz.trimf(gorjeta.universe, [15, 25, 25])

comida.view()
servico.view()
gorjeta.view()

#Regras
rule1 = ctrl.Rule(servico['excelente'] | comida['deliciosa'], gorjeta['alta'])
rule2 = ctrl.Rule(servico['aceitável'], gorjeta['média'])
rule3 = ctrl.Rule(servico['ruim'] & comida['péssima'], gorjeta['baixa'])
Exemplo n.º 8
0
    def init_fuzzy(self):
        """
        Make fuzzy setup by defining membership functions and rules
        """

        # Set the difference between the right front sensor and the right back sensor
        difference_right_sensors = ctrl.Antecedent(np.arange(-1.0, 1.0, 0.001),
                                                   'difference_right_sensors')
        difference_right_sensors['negative'] = fuzz.trimf(
            difference_right_sensors.universe, [-1.0, -1.0, 0.0])
        difference_right_sensors['zero'] = fuzz.trimf(
            difference_right_sensors.universe, [-0.015, 0.0, 0.015])
        difference_right_sensors['positive'] = fuzz.trimf(
            difference_right_sensors.universe, [0.0, 1.0, 1.0])

        # Set the distances of the front sensors
        distances_front_sensors = list()
        for i in range(3):
            distances_front_sensors.append(
                ctrl.Antecedent(np.arange(0, 5.0, self.steps),
                                'distance_front_sensor_' + str(i + 1)))
            distances_front_sensors[i]['close'] = fuzz.trapmf(
                distances_front_sensors[i].universe, [0.0, 0.0, 0.3, 0.8])
            distances_front_sensors[i]['away'] = fuzz.trapmf(
                distances_front_sensors[i].universe, [0.3, 0.8, 5.0, 5.0])

        # Define available velocities for each wheel
        v_left = ctrl.Consequent(
            np.arange(-self.max_speed, 1.0 + self.max_speed, 0.01), 'vl')
        v_right = ctrl.Consequent(
            np.arange(-self.max_speed, 1.0 + self.max_speed, 0.01), 'vr')

        # Define the membership functions for the wheels speed
        v_left['fast'] = fuzz.trimf(v_left.universe,
                                    [2.0, 2.0, self.max_speed])
        v_left['regular'] = fuzz.trimf(v_left.universe, [0.0, 2.0, 2.0])
        v_left['zero'] = fuzz.trimf(v_left.universe, [-0.1, 0.0, 0.1])
        v_right['fast'] = fuzz.trimf(v_right.universe,
                                     [2.0, 2.0, self.max_speed])
        v_right['regular'] = fuzz.trimf(v_left.universe, [0.0, 2.0, 2.0])
        v_right['zero'] = fuzz.trimf(v_right.universe, [-0.1, 0.0, 0.1])

        # Rules to make the robot follow the wall by turning left, right or going forward
        # Turn left
        rule_l1 = ctrl.Rule(
            distances_front_sensors[0]['close']
            | distances_front_sensors[1]['close']
            | distances_front_sensors[2]['close'], v_left['zero'])
        rule_r1 = ctrl.Rule(
            distances_front_sensors[0]['close']
            | distances_front_sensors[1]['close']
            | distances_front_sensors[2]['close'], v_right['fast'])

        # Turn right
        rule_l2 = ctrl.Rule(
            difference_right_sensors['positive']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_left['fast'])
        rule_r2 = ctrl.Rule(difference_right_sensors['positive'],
                            v_right['zero'])

        # Go forward, next to the wall
        rule_l3 = ctrl.Rule(
            difference_right_sensors['zero']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_left['regular'])
        rule_r3 = ctrl.Rule(
            difference_right_sensors['zero']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_right['regular'])
        rule_l4 = ctrl.Rule(
            difference_right_sensors['negative']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_left['regular'])
        rule_r4 = ctrl.Rule(
            difference_right_sensors['negative']
            & distances_front_sensors[0]['away']
            & distances_front_sensors[1]['away'], v_right['regular'])

        vel_ctrl = ctrl.ControlSystem([
            rule_l1, rule_l2, rule_l3, rule_l4, rule_r1, rule_r2, rule_r3,
            rule_r4
        ])
        self.fuzzy_system = ctrl.ControlSystemSimulation(vel_ctrl)
Exemplo n.º 9
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl



# antecedentes

servicio = ctrl.Antecedent(np.arange(0, 10, 1), 'servicio')
calidad  = ctrl.Antecedent(np.arange(0, 10, 1), 'calidad')

propina  = ctrl.Consequent(np.arange(0, 10, 1), 'propina')

# funciones de pertenencia automaticas
servicio.automf(3);

calidad['bajo'] = fuzz.trapmf(calidad.universe, [0,0, 1, 5])
calidad['medio'] = fuzz.trapmf(calidad.universe, [2, 3, 6, 7])
calidad['alto'] = fuzz.trapmf(calidad.universe, [5, 8, 10, 10])

# graficar las funciones de pertenencia
servicio.view()
calidad.view()

# consecuente
propina['bajo'] = fuzz.trapmf(calidad.universe, [0,0, 1, 5])
propina['medio'] = fuzz.trapmf(calidad.universe, [2, 3, 6, 7])
propina['alto'] = fuzz.trapmf(calidad.universe, [5, 8, 10, 10])

# graficar las funciones de pertenencia
Exemplo n.º 10
0
    def veg_cap_fis(model_run):
        """
        Vegetation capacity fis function
        :param model_run: The model being run, either 'Hpe' or 'ex"
        :return:
        """

        arcpy.env.overwriteOutput = True

        # get list of all fields in the flowline network
        fields = [f.name for f in arcpy.ListFields(in_network)]

        # set the carrying capacity and vegetation field depending on whether potential or existing run
        if model_run == 'Hpe':
            out_field = "oVC_Hpe"
            riparian_field = "iVeg100Hpe"
            streamside_field = "iVeg_30Hpe"
        else:
            out_field = "oVC_EX"
            riparian_field = "iVeg100EX"
            streamside_field = "iVeg_30EX"

        # check for oVC_* field in the network attribute table and delete if exists
        if out_field in fields:
            arcpy.DeleteField_management(in_network, out_field)

        # get arrays for fields of interest
        segid_np = arcpy.da.FeatureClassToNumPyArray(in_network, "ReachID")
        riparian_np = arcpy.da.FeatureClassToNumPyArray(
            in_network, riparian_field)
        streamside_np = arcpy.da.FeatureClassToNumPyArray(
            in_network, streamside_field)

        segid_array = np.asarray(segid_np, np.int64)
        riparian_array = np.asarray(riparian_np, np.float64)
        streamside_array = np.asarray(streamside_np, np.float64)

        # check that inputs are within range of fis
        # if not, re-assign the value to just within range
        riparian_array[riparian_array < 0] = 0
        riparian_array[riparian_array > 4] = 4
        streamside_array[streamside_array < 0] = 0
        streamside_array[streamside_array > 4] = 4

        # delete temp arrays
        items = [segid_np, riparian_np, streamside_np]
        for item in items:
            del item

        # create antecedent (input) and consequent (output) objects to hold universe variables and membership functions
        riparian = ctrl.Antecedent(np.arange(0, 4, 0.01), 'input1')
        streamside = ctrl.Antecedent(np.arange(0, 4, 0.01), 'input2')
        density = ctrl.Consequent(np.arange(0, 45, 0.01), 'result')

        # build membership functions for each antecedent and consequent object
        riparian['unsuitable'] = fuzz.trapmf(riparian.universe, [0, 0, 0.1, 1])
        riparian['barely'] = fuzz.trimf(riparian.universe, [0.1, 1, 2])
        riparian['moderately'] = fuzz.trimf(riparian.universe, [1, 2, 3])
        riparian['suitable'] = fuzz.trimf(riparian.universe, [2, 3, 4])
        riparian['preferred'] = fuzz.trimf(riparian.universe, [3, 4, 4])

        streamside['unsuitable'] = fuzz.trapmf(streamside.universe,
                                               [0, 0, 0.1, 1])
        streamside['barely'] = fuzz.trimf(streamside.universe, [0.1, 1, 2])
        streamside['moderately'] = fuzz.trimf(streamside.universe, [1, 2, 3])
        streamside['suitable'] = fuzz.trimf(streamside.universe, [2, 3, 4])
        streamside['preferred'] = fuzz.trimf(streamside.universe, [3, 4, 4])

        density['none'] = fuzz.trimf(density.universe, [0, 0, 0.1])
        density['rare'] = fuzz.trapmf(density.universe, [0, 0.1, 0.5, 1.5])
        density['occasional'] = fuzz.trapmf(density.universe, [0.5, 1.5, 4, 8])
        density['frequent'] = fuzz.trapmf(density.universe, [4, 8, 12, 25])
        density['pervasive'] = fuzz.trapmf(density.universe, [12, 25, 45, 45])

        # build fis rule table
        rule1 = ctrl.Rule(riparian['unsuitable'] & streamside['unsuitable'],
                          density['none'])
        rule2 = ctrl.Rule(riparian['barely'] & streamside['unsuitable'],
                          density['rare'])
        rule3 = ctrl.Rule(riparian['moderately'] & streamside['unsuitable'],
                          density['rare'])
        rule4 = ctrl.Rule(riparian['suitable'] & streamside['unsuitable'],
                          density['occasional'])
        rule5 = ctrl.Rule(riparian['preferred'] & streamside['unsuitable'],
                          density['occasional'])
        rule6 = ctrl.Rule(riparian['unsuitable'] & streamside['barely'],
                          density['rare'])
        # matBRAT has consequent as 'occasional'
        rule7 = ctrl.Rule(riparian['barely'] & streamside['barely'],
                          density['rare'])
        rule8 = ctrl.Rule(riparian['moderately'] & streamside['barely'],
                          density['occasional'])
        rule9 = ctrl.Rule(riparian['suitable'] & streamside['barely'],
                          density['occasional'])
        rule10 = ctrl.Rule(riparian['preferred'] & streamside['barely'],
                           density['occasional'])
        rule11 = ctrl.Rule(riparian['unsuitable'] & streamside['moderately'],
                           density['rare'])
        rule12 = ctrl.Rule(riparian['barely'] & streamside['moderately'],
                           density['occasional'])
        rule13 = ctrl.Rule(riparian['moderately'] & streamside['moderately'],
                           density['occasional'])
        rule14 = ctrl.Rule(riparian['suitable'] & streamside['moderately'],
                           density['frequent'])
        rule15 = ctrl.Rule(riparian['preferred'] & streamside['moderately'],
                           density['frequent'])
        rule16 = ctrl.Rule(riparian['unsuitable'] & streamside['suitable'],
                           density['occasional'])
        rule17 = ctrl.Rule(riparian['barely'] & streamside['suitable'],
                           density['occasional'])
        rule18 = ctrl.Rule(riparian['moderately'] & streamside['suitable'],
                           density['frequent'])
        rule19 = ctrl.Rule(riparian['suitable'] & streamside['suitable'],
                           density['frequent'])
        rule20 = ctrl.Rule(riparian['preferred'] & streamside['suitable'],
                           density['pervasive'])
        rule21 = ctrl.Rule(riparian['unsuitable'] & streamside['preferred'],
                           density['occasional'])
        rule22 = ctrl.Rule(riparian['barely'] & streamside['preferred'],
                           density['frequent'])
        rule23 = ctrl.Rule(riparian['moderately'] & streamside['preferred'],
                           density['pervasive'])
        rule24 = ctrl.Rule(riparian['suitable'] & streamside['preferred'],
                           density['pervasive'])
        rule25 = ctrl.Rule(riparian['preferred'] & streamside['preferred'],
                           density['pervasive'])

        # FIS
        veg_ctrl = ctrl.ControlSystem([
            rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9,
            rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17,
            rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25
        ])
        veg_fis = ctrl.ControlSystemSimulation(veg_ctrl)

        # run fuzzy inference system on inputs and defuzzify output
        out = np.zeros(len(riparian_array))
        for i in range(len(out)):
            veg_fis.input['input1'] = riparian_array[i]
            veg_fis.input['input2'] = streamside_array[i]
            veg_fis.compute()
            out[i] = veg_fis.output['result']

        # save fuzzy inference system output as table
        columns = np.column_stack((segid_array, out))
        # TODO See if possible to skip this step
        out_table = os.path.dirname(
            in_network) + "/" + out_field + "_Table.txt"
        np.savetxt(out_table,
                   columns,
                   delimiter=",",
                   header="ReachID, " + out_field,
                   comments="")
        ovc_table = scratch + "/" + out_field + "Tbl"
        arcpy.CopyRows_management(out_table, ovc_table)

        # join the fuzzy inference system output to the flowline network
        # create empty dictionary to hold input table field values
        tbl_dict = {}
        # add values to dictionary
        with arcpy.da.SearchCursor(ovc_table,
                                   ['ReachID', out_field]) as cursor:
            for row in cursor:
                tbl_dict[row[0]] = row[1]
        # populate flowline network out field
        arcpy.AddField_management(in_network, out_field, 'DOUBLE')
        with arcpy.da.UpdateCursor(in_network,
                                   ['ReachID', out_field]) as cursor:
            for row in cursor:
                try:
                    a_key = row[0]
                    row[1] = tbl_dict[a_key]
                    cursor.updateRow(row)
                # TODO There should be no blank exception statements. What error is this catching?
                except:
                    pass
        tbl_dict.clear()

        # calculate defuzzified centroid value for density 'none' MF group
        # this will be used to re-classify output values that fall in this group
        # important: will need to update the array (x) and MF values (mfx) if the
        #            density 'none' values are changed in the model
        x = np.arange(0, 45, 0.01)
        mfx_none = fuzz.trimf(x, [0, 0, 0.1])
        defuzz_none = round(fuzz.defuzz(x, mfx_none, 'centroid'), 6)
        mfx_pervasive = fuzz.trapmf(x, [12, 25, 45, 45])
        defuzz_pervasive = round(fuzz.defuzz(x, mfx_pervasive, 'centroid'))

        # update vegetation capacity (ovc_*) values in stream network
        # set ovc_* to 0 if output falls fully in 'none' category and to 40 if falls fully in 'pervasive' category

        with arcpy.da.UpdateCursor(in_network, [out_field]) as cursor:
            for row in cursor:
                if round(row[0], 6) == defuzz_none:
                    row[0] = 0.0
                if round(row[0]) >= defuzz_pervasive:
                    row[0] = 40.0
                cursor.updateRow(row)

        # delete temporary tables and arrays
        arcpy.Delete_management(out_table)
        arcpy.Delete_management(ovc_table)
        items = [columns, out, x, mfx_none, defuzz_none]
        for item in items:
            del item
Exemplo n.º 11
0
pygame.display.set_caption("intersect")

ballorg = 250
count = 0
running = True

threadlist = []
lineAmmount = 8
incrementLine = 360 / lineAmmount

rot = 0

global q
q = queue()

closeness = ctrl.Antecedent((np.arange(0, 500, 1)), "Closeness")
meteorCount = ctrl.Antecedent(np.arange(0, 50, 1), "Meteors")

danger = ctrl.Consequent(np.arange(0, 100, 1), "Danger")

meteorCount['lots'] = fuzz.trapmf(meteorCount.universe, [30, 50, 100, 100])
meteorCount['many'] = fuzz.trimf(meteorCount.universe, [15, 40, 100])
meteorCount['few'] = fuzz.trimf(meteorCount.universe, [0, 10, 20])

closeness['close'] = fuzz.trimf(closeness.universe, [0, 100, 200])
closeness['distant'] = fuzz.trimf(closeness.universe, [100, 250, 400])
closeness['far'] = fuzz.trimf(closeness.universe, [350, 500, 500])

danger['low'] = fuzz.trimf(danger.universe, [0, 0, 30])
danger['med'] = fuzz.trimf(danger.universe, [20, 50, 100])
danger['high'] = fuzz.trimf(danger.universe, [75, 100, 100])
Exemplo n.º 12
0
    def computeQuality(self, M1_level, M2_level):
        #INPUT-------------------------------------------------------------------------
        M1 = ctrl.Antecedent(np.arange(0, 1.0, 0.01), 'M1 level')
        M2 = ctrl.Antecedent(np.arange(0, 1.0, 0.01), 'M2 level')

        #OUTPUT-------------------------------------------------------------------------
        BikeWay = ctrl.Consequent(np.arange(0, 1.0, 0.01), 'BikeWay')

        #SET DEFINITION-----------------------------------------------------------------
        M1.automf(names=['Very Good', 'Good', 'Moderate', 'Bad', 'Very Bad'])
        M2.automf(names=['Very Good', 'Good', 'Moderate', 'Bad', 'Very Bad'])
        BikeWay.automf(
            names=['Very Good', 'Good', 'Moderate', 'Bad', 'Very Bad'])

        #RULES--------------------------------------------------------------------------
        rule1 = ctrl.Rule(M1['Very Bad'] | M2['Very Bad'], BikeWay['Very Bad'])
        rule2 = ctrl.Rule(((M1['Bad'] & (M2['Bad'] | M2['Moderate'])) |
                           (M1['Moderate'] & M2['Bad'])), BikeWay['Bad'])
        rule3 = ctrl.Rule(((M1['Bad'] & (M2['Good'] | M2['Very Good'])) |
                           (M1['Moderate'] & M2['Moderate']) |
                           ((M1['Good'] | M1['Very Good']) & M2['Bad'])),
                          BikeWay['Moderate'])
        rule4 = ctrl.Rule(((M1['Moderate'] & (M2['Good'] | M2['Very Good'])) |
                           (M1['Good'] & (M2['Moderate'] | M2['Good'])) |
                           (M1['Very Good'] & M2['Moderate'])),
                          BikeWay['Good'])
        rule5 = ctrl.Rule(
            ((M1['Good'] | M1['Very Good']) & (M2['Good'] | M2['Very Good'])),
            BikeWay['Very Good'])

        BikeWay_control = ctrl.ControlSystem(
            [rule1, rule2, rule3, rule4, rule5])
        BikeWay_simulator = ctrl.ControlSystemSimulation(BikeWay_control)

        BikeWay_simulator.input['M1 level'] = M1_level
        BikeWay_simulator.input['M2 level'] = M2_level
        BikeWay_simulator.compute()
        BikeWay_level = BikeWay_simulator.output['BikeWay']

        M1Quality = self.numericToName(M1_level)
        M2Quality = self.numericToName(M2_level)

        bikeWayQuality = "Very Bad"
        if (M1Quality == "Bad" and
            (M2Quality == 'Bad' or M2Quality == 'Moderate')) or (
                M1Quality == "Moderate" and M2Quality == 'Bad'):
            bikeWayQuality = "Bad"
        elif (M1Quality == "Bad" and
              (M2Quality == "Good" or M2Quality == "Very Good")) or (
                  M1Quality == "Moderate" and M2Quality == "Moderate") or (
                      (M1Quality == "Good" or M1Quality == "Very Good")
                      and M2Quality == "Bad"):
            bikeWayQuality = "Moderate"
        elif (M1Quality == "Moderate" and
              (M2Quality == "Good" or M2Quality == "Very Good")) or (
                  M1Quality == "Good" and
                  (M2Quality == "Moderate" or M2Quality == "Good")) or (
                      M1Quality == "Very Good" and M2Quality == "Moderate"):
            bikeWayQuality = "Good"
        elif (M1Quality == "Good"
              or M1Quality == "Very Good") and (M2Quality == "Good"
                                                or M2Quality == "Very Good"):
            bikeWayQuality = "Very Good"

        print("          M1 quality = " + M1Quality)
        print("          M2 quality = " + M2Quality)
        print("          BikeWay quality = " + bikeWayQuality + " (" +
              str(BikeWay_level) + ")")

        #BikeWay.view(sim=BikeWay_simulator)
        #plt.show()

        return self.encodeQuality(bikeWayQuality)
Exemplo n.º 13
0
def fuzzy_val_generator(light_level_in, temp_level_in):

    # Input and Output array declaration
    light_level = ctrl.Antecedent(
        np.arange(0, 21, 1),
        'light_level')  # should change the range according to the sensor value
    temp_level = ctrl.Antecedent(
        np.arange(0, 21, 1),
        'temp_level')  # should change the range according to the sensor value
    power_level_for_light = ctrl.Consequent(
        np.arange(0, 11, 1), 'power_level_for_light'
    )  # should change the range according to the sensor value
    power_level_for_temp = ctrl.Consequent(
        np.arange(0, 11, 1), 'power_level_for_temp'
    )  # should change the range according to the sensor value

    # Auto membership function population
    light_level.automf(3)  # poor, average, good
    temp_level.automf(3)
    power_level_for_light.automf(3)
    power_level_for_temp.automf(3)

    # rules initialization
    rule1 = ctrl.Rule(
        light_level['poor'] & temp_level['poor'],
        (power_level_for_light['good'], power_level_for_temp['good']))
    rule2 = ctrl.Rule(
        light_level['poor'] & temp_level['average'],
        (power_level_for_light['good'], power_level_for_temp['average']))
    rule3 = ctrl.Rule(
        light_level['poor'] & temp_level['good'],
        (power_level_for_light['good'], power_level_for_temp['poor']))
    rule4 = ctrl.Rule(
        light_level['average'] & temp_level['poor'],
        (power_level_for_light['average'], power_level_for_temp['good']))
    rule5 = ctrl.Rule(
        light_level['average'] & temp_level['average'],
        (power_level_for_light['average'], power_level_for_temp['average']))
    rule6 = ctrl.Rule(
        light_level['average'] & temp_level['good'],
        (power_level_for_light['average'], power_level_for_temp['poor']))
    rule7 = ctrl.Rule(
        light_level['good'] & temp_level['poor'],
        (power_level_for_light['poor'], power_level_for_temp['good']))
    rule8 = ctrl.Rule(
        light_level['good'] & temp_level['average'],
        (power_level_for_light['poor'], power_level_for_temp['average']))
    rule9 = ctrl.Rule(
        light_level['good'] & temp_level['good'],
        (power_level_for_light['poor'], power_level_for_temp['poor']))

    # Control system and simulation
    power_ctrl = ctrl.ControlSystem(
        [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9])
    power = ctrl.ControlSystemSimulation(power_ctrl)

    power.input['light_level'] = light_level_in
    power.input['temp_level'] = temp_level_in

    power.compute()

    return power.output['power_level_for_light'], power.output[
        'power_level_for_temp']
Exemplo n.º 14
0
 def create_function(self):
     self.opinion = ctrl.Antecedent(self.opinion_universe, 'opinion')
     self.emotion = ctrl.Antecedent(self.emotion_universe, 'emotion')
     self.time = ctrl.Antecedent(self.time_universe, 'time')
     self.rules = ctrl.Antecedent(self.rules_universe, 'rules')
Exemplo n.º 15
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control

people = control.Antecedent(np.arange(0, 300, 1), 'people')
tech_supplies = control.Antecedent(np.arange(0, 500, 1), 'tech_supplies')
skill = control.Antecedent(np.arange(0, 100, 1), 'skill')
productivity = control.Consequent(np.arange(0, 100, 1), 'productivity')
cost = control.Consequent(np.arange(0, 100, 1), 'cost')
tech_supplies_demand = control.Consequent(np.arange(0, 100, 1), 'tech_supplies_demand')

tech_supplies.automf(3)
skill.automf(3)
productivity.automf(3)
cost.automf(5)
people.automf(3)
tech_supplies_demand.automf(3)

tech_supplies_demand_rule_1 = control.Rule(tech_supplies['poor'] & people['average'],
                                           tech_supplies_demand['average'])
tech_supplies_demand_rule_2 = control.Rule(tech_supplies['average'] & people['good'],
                                           tech_supplies_demand['average'])
tech_supplies_demand_rule_3 = control.Rule(tech_supplies['poor'] & people['good'],
                                           tech_supplies_demand['good'])
tech_supplies_demand_rule_4 = control.Rule(tech_supplies['good'],
                                           tech_supplies_demand['poor'])
tech_supplies_demand_rule_5 = control.Rule(tech_supplies['average'] & people['average'],
                                           tech_supplies_demand['poor'])
tech_supplies_demand_rule_6 = control.Rule(people['poor'],
                                           tech_supplies_demand['poor'])
Exemplo n.º 16
0
import skfuzzy as fuzz
import numpy as np
import skfuzzy.control as ctrl
import matplotlib.pyplot as plt

x_dhumi_range = np.arange(-6, 101, 1, np.float32)
x_hc_range = np.arange(-1, 6, 1, np.float32)
y_output_range = np.arange(0, 101, 1, np.float32)

# 创建模糊控制变量

x_dhumi = ctrl.Antecedent(x_dhumi_range, 'dhumi')
x_hc = ctrl.Antecedent(x_hc_range, 'hc')
y_output = ctrl.Consequent(y_output_range, 'output')

# 定义模糊集和其隶属度函数

x_dhumi['N'] = fuzz.trimf(x_dhumi_range, [-6, -6, 47])
x_dhumi['M'] = fuzz.trimf(x_dhumi_range, [-6, 47,100])
x_dhumi['P'] = fuzz.trimf(x_dhumi_range, [47, 100, 100])

x_hc['N'] = fuzz.trimf(x_hc_range, [-1, -1, 2])
x_hc['M'] = fuzz.trimf(x_hc_range, [-1, 2, 5])
x_hc['P'] = fuzz.trimf(x_hc_range, [2, 5, 5])

y_output['N'] = fuzz.trimf(y_output_range, [0, 0, 50])
y_output['M'] = fuzz.trimf(y_output_range, [0, 50, 100])
y_output['P'] = fuzz.trimf(y_output_range, [50, 100, 100])

# 设定输出output的解模糊方法——质心解模糊方式
y_output.defuzzify_method = 'centroid'
Exemplo n.º 17
0
# Fuzzy Logic Potted Plant Conditions Rating
# Author: Wojciech Kudłacik and Norbert Daniluk
# Inspiration: https://pythonhosted.org/scikit-fuzzy/auto_examples/plot_tipping_problem_newapi.html

import matplotlib.pyplot as plt
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
'''
List of inputs 

They hold universe values and membership functions 
'''
temperature = ctrl.Antecedent(np.arange(10, 31, 1), 'temperature')
luminosity = ctrl.Antecedent(np.arange(2500, 10001, 100), 'luminosity')
soil_moisture = ctrl.Antecedent(np.arange(0, 11, 1), 'soil_moisture')
'''
List of outputs

They hold universe values and membership functions
'''
condition_rating = ctrl.Consequent(np.arange(0, 11, 1), 'condition_rating')
'''
Inputs membership functions population

In this case functions are populated automatically using .automf function 
'''
temperature.automf(3)
luminosity.automf(3)
soil_moisture.automf(3)
'''
Exemplo n.º 18
0
def oraculo(detectionzone, contenedor):
    global zonadeteccion

    zonadeteccion = detectionzone
    PERSON_CERCA = (zonadeteccion.area / 1000) * 0.10
    PERSON_MEDIO = (zonadeteccion.area / 1000) * 0.06
    PERSON_LEJOS = (zonadeteccion.area / 1000) * 0.02

    CAR_CERCA = (zonadeteccion.area / 1000) * 0.20
    CAR_MEDIO = (zonadeteccion.area / 1000) * 0.12
    CAR_LEJOS = (zonadeteccion.area / 1000) * 0.05

    print("Personas")
    print(cuentaPersonas(contenedor))
    print(personasIzquierda(contenedor))
    print(personasCentro(contenedor))
    print(personasDerecha(contenedor))
    print(zonadeteccion.area)
    print(PERSON_CERCA)
    print(PERSON_MEDIO)
    print(PERSON_LEJOS)

    print("Coches")
    print(cuentaCoches(contenedor))
    print(cochesIzquierda(contenedor))
    print(cochesCentro(contenedor))
    print(cochesDerecha(contenedor))
    print(zonadeteccion.area)
    print(CAR_CERCA)
    print(CAR_MEDIO)
    print(CAR_LEJOS)

    ##--------------------------##
    ##          FUZZY           ##
    ##--------------------------##
    in_p_names = ['lejos', 'medio', 'cerca']
    p_izquierda = ctrl.Antecedent(np.arange(0, PERSON_CERCA + 1, 1),
                                  'p_izquierda')
    p_centro = ctrl.Antecedent(np.arange(0, PERSON_CERCA + 1, 1), 'p_centro')
    p_derecha = ctrl.Antecedent(np.arange(0, PERSON_CERCA + 1, 1), 'p_derecha')
    p_izquierda.automf(names=in_p_names)
    p_centro.automf(names=in_p_names)
    p_derecha.automf(names=in_p_names)
    p_izquierda['lejos'] = p_centro['lejos'] = p_derecha[
        'lejos'] = fuzz.trapmf(p_derecha.universe,
                               [0, 0, (PERSON_LEJOS - 2), PERSON_LEJOS])
    p_izquierda['medio'] = p_centro['medio'] = p_derecha[
        'medio'] = fuzz.trapmf(p_derecha.universe,
                               [(PERSON_LEJOS - 2), PERSON_LEJOS,
                                (PERSON_MEDIO - 2), PERSON_MEDIO])
    p_izquierda[
        'cerca'] = p_centro['cerca'] = p_derecha['cerca'] = fuzz.trapmf(
            p_derecha.universe,
            [(PERSON_MEDIO - 2), PERSON_MEDIO, PERSON_CERCA, PERSON_CERCA])

    in_c_names = ['lejos', 'medio', 'cerca']
    c_izquierda = ctrl.Antecedent(np.arange(0, CAR_CERCA + 1, 1),
                                  'c_izquierda')
    c_centro = ctrl.Antecedent(np.arange(0, CAR_CERCA + 1, 1), 'c_centro')
    c_derecha = ctrl.Antecedent(np.arange(0, CAR_CERCA + 1, 1), 'c_derecha')
    c_izquierda.automf(names=in_c_names)
    c_centro.automf(names=in_c_names)
    c_derecha.automf(names=in_c_names)
    c_izquierda['lejos'] = c_centro['lejos'] = c_derecha[
        'lejos'] = fuzz.trapmf(c_derecha.universe,
                               [0, 0, (CAR_LEJOS - 2), CAR_LEJOS])
    c_izquierda['medio'] = c_centro['medio'] = c_derecha[
        'medio'] = fuzz.trapmf(c_derecha.universe,
                               [(CAR_LEJOS - 2), CAR_LEJOS,
                                (CAR_MEDIO - 2), CAR_MEDIO])
    c_izquierda[
        'cerca'] = c_centro['cerca'] = c_derecha['cerca'] = fuzz.trapmf(
            c_derecha.universe,
            [(CAR_MEDIO - 2), CAR_MEDIO, CAR_CERCA, CAR_CERCA])

    out_d_names = [
        'mucho_izquierda', 'medio_izquierda', 'neutro', 'medio_derecha',
        'mucho_derecha'
    ]
    direccion = ctrl.Consequent(np.arange(0, 181, 1), 'direccion')
    direccion.automf(names=out_d_names)
    direccion['mucho_izquierda'] = fuzz.trapmf(direccion.universe,
                                               [0, 0, 35, 40])
    direccion['medio_izquierda'] = fuzz.trapmf(direccion.universe,
                                               [35, 40, 70, 75])
    direccion['neutro'] = fuzz.trapmf(direccion.universe, [70, 75, 105, 110])
    direccion['medio_derecha'] = fuzz.trapmf(direccion.universe,
                                             [105, 110, 140, 145])
    direccion['mucho_derecha'] = fuzz.trapmf(direccion.universe,
                                             [140, 145, 180, 180])

    out_f_names = ['leve', 'medio', 'fuerte']
    frenada = ctrl.Consequent(np.arange(0, 101, 1), 'frenada')
    frenada.automf(names=out_f_names)
    frenada['leve'] = fuzz.trapmf(frenada.universe, [0, 0, 16, 20])
    frenada['medio'] = fuzz.trapmf(frenada.universe, [16, 20, 35, 40])
    frenada['fuerte'] = fuzz.trapmf(frenada.universe, [35, 40, 100, 100])

    ## ------------------------------------------ //CONTROL VOLANTE\\ ------------------------------------------ ##
    d_rule1 = ctrl.Rule(antecedent=((p_izquierda['cerca']) &
                                    (p_centro['medio'] | p_centro['lejos'])),
                        consequent=direccion['mucho_derecha'])

    d_rule2 = ctrl.Rule(antecedent=((p_izquierda['medio']) &
                                    (p_centro['medio'] | p_centro['lejos'])),
                        consequent=direccion['medio_derecha'])

    d_rule3 = ctrl.Rule(
        antecedent=(((p_izquierda['lejos'] & p_derecha['lejos'])
                     | p_centro['cerca'])),
        consequent=direccion['neutro'])

    d_rule4 = ctrl.Rule(antecedent=((p_derecha['medio']) &
                                    (p_centro['medio'] | p_centro['lejos'])),
                        consequent=direccion['medio_izquierda'])

    d_rule5 = ctrl.Rule(antecedent=((p_derecha['cerca']) &
                                    (p_centro['medio'] | p_centro['lejos'])),
                        consequent=direccion['mucho_izquierda'])

    d_rule6 = ctrl.Rule(antecedent=((c_izquierda['cerca']) &
                                    (c_centro['medio'] | c_centro['lejos'])),
                        consequent=direccion['mucho_derecha'])

    d_rule7 = ctrl.Rule(antecedent=((c_izquierda['medio']) &
                                    (c_centro['medio'] | c_centro['lejos'])),
                        consequent=direccion['medio_derecha'])

    d_rule8 = ctrl.Rule(
        antecedent=(((c_izquierda['lejos'] & c_derecha['lejos'])
                     | c_centro['cerca'])),
        consequent=direccion['neutro'])

    d_rule9 = ctrl.Rule(antecedent=((c_derecha['medio']) &
                                    (c_centro['medio'] | c_centro['lejos'])),
                        consequent=direccion['medio_izquierda'])

    d_rule10 = ctrl.Rule(antecedent=((c_derecha['cerca']) &
                                     (c_centro['medio'] | c_centro['lejos'])),
                         consequent=direccion['mucho_izquierda'])

    ctrl_volante = ctrl.ControlSystem(rules=[
        d_rule1, d_rule2, d_rule3, d_rule4, d_rule5, d_rule6, d_rule7, d_rule8,
        d_rule9, d_rule10
    ])
    volante = ctrl.ControlSystemSimulation(ctrl_volante)

    volante.input['p_izquierda'] = personasIzquierda(contenedor)
    volante.input['p_centro'] = personasCentro(contenedor)
    volante.input['p_derecha'] = personasDerecha(contenedor)

    volante.input['c_izquierda'] = cochesIzquierda(contenedor)
    volante.input['c_centro'] = cochesCentro(contenedor)
    volante.input['c_derecha'] = cochesDerecha(contenedor)

    volante.compute()

    print("PREDICCION VOLANTE: ")
    print(volante.output['direccion'])
    ## ------------------------------------------ \\CONTROL VOLANTE// ------------------------------------------ ##
    ## --------------------------------------------------------------------------------------------------------- ##
    ## ------------------------------------------ //CONTROL FRENADA\\ ------------------------------------------ ##
    f_rule1 = ctrl.Rule(
        antecedent=((p_izquierda['cerca']) | (p_centro['cerca']) |
                    (p_derecha['cerca'])),
        consequent=frenada['fuerte'])

    f_rule2 = ctrl.Rule(
        antecedent=((p_izquierda['medio']) | (p_centro['medio']) |
                    (p_derecha['medio'])),
        consequent=frenada['medio'])

    f_rule3 = ctrl.Rule(
        antecedent=((p_izquierda['lejos']) | (p_centro['lejos']) |
                    (p_derecha['lejos'])),
        consequent=frenada['leve'])

    f_rule4 = ctrl.Rule(
        antecedent=((c_izquierda['cerca']) | (c_centro['cerca']) |
                    (c_derecha['cerca'])),
        consequent=frenada['fuerte'])
    f_rule5 = ctrl.Rule(
        antecedent=((c_izquierda['medio']) | (c_centro['medio']) |
                    (c_derecha['medio'])),
        consequent=frenada['medio'])

    f_rule6 = ctrl.Rule(
        antecedent=((c_izquierda['lejos']) | (c_centro['lejos']) |
                    (c_derecha['lejos'])),
        consequent=frenada['leve'])

    ctrl_freno = ctrl.ControlSystem(
        rules=[f_rule1, f_rule2, f_rule3, f_rule4, f_rule5, f_rule6])
    freno = ctrl.ControlSystemSimulation(ctrl_freno)

    freno.input['p_izquierda'] = personasIzquierda(contenedor)
    freno.input['p_centro'] = personasCentro(contenedor)
    freno.input['p_derecha'] = personasDerecha(contenedor)

    freno.input['c_izquierda'] = cochesIzquierda(contenedor)
    freno.input['c_centro'] = cochesCentro(contenedor)
    freno.input['c_derecha'] = cochesDerecha(contenedor)

    freno.compute()

    print("PREDICCION FRENADA: ")
    print(freno.output['frenada'])

    ## ------------------------------------------ \\CONTROL FRENADA// ------------------------------------------ ##

    return volante.output['direccion'], freno.output['frenada']
Exemplo n.º 19
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Cria as variáveis do problema
temp = ctrl.Antecedent(np.arange(0, 41, 1), 'temp')

u_ar = ctrl.Antecedent(np.arange(0, 101, 1), 'u_ar')

u_solo = ctrl.Antecedent(np.arange(0, 1025, 1), 'u_solo')

saldo = ctrl.Antecedent(np.arange(0, 101, 1), 'saldo')

irrig = ctrl.Consequent(np.arange(30, 101, 30), 'irrig')

# Cria automaticamente o mapeamento entre valores nítidos e difusos
# usando uma função de pertinência (triângulo)
temp['frio'] = fuzz.trimf(temp.universe, [0, 0, 20])
temp['agradavel'] = fuzz.trapmf(temp.universe, [10, 21, 22, 35])
temp['quente'] = fuzz.trimf(temp.universe, [22, 40, 40])

u_ar['seco'] = fuzz.trapmf(u_ar.universe, [0, 0, 40, 60])
u_ar['medio'] = fuzz.trapmf(u_ar.universe, [35, 60, 65, 80])
u_ar['umido'] = fuzz.trimf(u_ar.universe, [65, 100, 100])

u_solo['seco'] = fuzz.gaussmf(u_solo.universe, 0, 256)
u_solo['medio'] = fuzz.gaussmf(u_solo.universe, 512, 256)
u_solo['umido'] = fuzz.gaussmf(u_solo.universe, 1024, 256)

saldo['pouco'] = fuzz.trimf(saldo.universe, [0, 0, 20])
saldo['muito'] = fuzz.trimf(saldo.universe, [0, 100, 100])
Exemplo n.º 20
0
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt


def wall_follow(dist):
    distance_left = min(dist[:4])
    distance_right = min(dist[4:])
    walking.input['distance left'] = distance_left
    walking.input['distance right'] = distance_right
    walking.compute()

    return [walking.output['velocity left'], walking.output['velocity right']]


distance_left = ctrl.Antecedent(np.arange(0.2, 5.01, 0.01), 'distance left')
distance_right = ctrl.Antecedent(np.arange(0.2, 5.01, 0.01), 'distance right')

velocity_left = ctrl.Consequent(np.arange(0.0, 5.1, 0.1), 'velocity left')
velocity_right = ctrl.Consequent(np.arange(0.0, 5.1, 0.1), 'velocity right')

distance_left['low'] = fuzz.trimf(distance_left.universe, [0.2, 0.2, 0.3])
distance_left['medium'] = fuzz.trimf(distance_left.universe, [0.2, 0.3, 1.0])
distance_left['high'] = fuzz.trapmf(distance_left.universe,
                                    [0.5, 1.0, 5.0, 5.0])

distance_right['low'] = fuzz.trimf(distance_right.universe, [0.2, 0.2, 0.3])
distance_right['medium'] = fuzz.trimf(distance_right.universe, [0.2, 0.3, 1.0])
distance_right['high'] = fuzz.trapmf(distance_right.universe,
                                     [0.5, 1.0, 5.0, 5.0])
Exemplo n.º 21
0
Logica y Teoria de la Computacion
Dany Rubiano Jimenez
22.250.855-k
"""

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

############################################# Antecedentes #############################################

####### Factores de empaquetadura:
# Nivel esfuerzo empaque (incluye factores como cantidad de productos, cantidad de bolsas, entre otros)
# Tiempo (Tiempo que demora en terminar una vez el cliente esta listo)

esfuerzo = ctrl.Antecedent(np.arange(0, 8, 0.1),
                           'Nivel de esfuerzo del empaque')  #
tiempo_empaque = ctrl.Antecedent(
    np.arange(0, 10, 0.1), 'Tiempo de empaque'
)  # Tiempo que demora el empaque en terminar, despues que termina de pagar el cliente

####### Factores externos:
# Nivel de atención cajera (como una nota de 1 a 7, que mide factores de tiempo, amabilidad y otros)
# Tiempo de espera en fila (medido en minutos)

atencion_cajera = ctrl.Antecedent(np.arange(0, 7, 0.1),
                                  'Nivel de atencion cajera')
tiempo_espera = ctrl.Antecedent(
    np.arange(0, 30, 0.1), 'Tiempo de espera en fila'
)  # Cuanto tiempo se esta en la fila esperando atencion

####### Factores internos:
Exemplo n.º 22
0
# np.arange(min, max, step) : step will influence accuracy (esp. curve e.g. Gaussian MF)
step_meter = 0.02  # If the step are large, the Gaussian MF will regress to Triangular MF
step_meter_per_second = 0.02
step_risk = 1
range_degree = np.arange(
    -180, 180 + 1,
    1.0)  # Range: -180 degree ~ 180 degree for direction and orientation
range_meter = np.arange(0, 3.0 + step_meter,
                        step_meter)  # Range:  0 meter ~ 3 meter for distance
range_meter_per_second = np.arange(
    -1.0, 2.0 + step_meter_per_second,
    step_meter_per_second)  #Range:  -1.0 mps ~ 2 mps for speed
range_risk = np.arange(0, 5 + step_risk,
                       step_risk)  # Range: 0,1,2,3,4 for risk

object_distance = ctrl.Antecedent(range_meter, 'distance')  # 0- 3  meter
object_direction = ctrl.Antecedent(range_degree,
                                   'direction')  # -180~180 degree
object_risk = ctrl.Antecedent(range_risk, 'risk')

left_speed = ctrl.Consequent(range_meter_per_second, 'left')
right_speed = ctrl.Consequent(range_meter_per_second, 'right')

# Custom membership functions can be built interactively with a familiar Pythonic API
#distance_p1 = fuzz.gaussmf(range_meter,IZW,0.1)
#distance_p2 = fuzz.gaussmf(range_meter,IZW,0.1)
# Distance
object_distance['Near'] = fuzz.trapmf(
    range_meter, [0, 0, IZW, 2 * IZW]
)  #fuzz.gaussmf(range_meter,0.5*IZW,0.1) # skfuzzy.membership.gaussmf(x, mean, sigma)
object_distance['Medium'] = fuzz.trimf(
Exemplo n.º 23
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

pendapatan = ctrl.Antecedent(np.arange(0, 50, 5), 'pendapatan')
nilaiUN = ctrl.Antecedent(np.arange(0, 11, 1), 'nilaiUN')
kelayakan = ctrl.Consequent(np.arange(0, 101, 5), 'kelayakan')

pendapatan.automf(3)
nilaiUN.automf(3)

pendapatan['poor'] = fuzz.trapmf(pendapatan.universe, [0, 0, 5, 15])
pendapatan['average'] = fuzz.trimf(pendapatan.universe, [10, 20, 30])
pendapatan['good'] = fuzz.trapmf(pendapatan.universe, [25, 35, 50, 50])
pendapatan.view()

nilaiUN['poor'] = fuzz.trapmf(nilaiUN.universe, [0, 0, 4, 6])
nilaiUN['average'] = fuzz.trimf(nilaiUN.universe, [5, 6, 8])
nilaiUN['good'] = fuzz.trapmf(nilaiUN.universe, [7, 9, 10, 10])
nilaiUN.view()

kelayakan['low'] = fuzz.trapmf(kelayakan.universe, [0, 0, 20, 70])
kelayakan['high'] = fuzz.trapmf(kelayakan.universe, [50, 90, 100, 100])
kelayakan.view()

rule1 = ctrl.Rule(pendapatan['poor'] & nilaiUN['good'], kelayakan['high'])
rule2 = ctrl.Rule(pendapatan['average'] & nilaiUN['good'], kelayakan['high'])
rule3 = ctrl.Rule(pendapatan['good'] & nilaiUN['good'], kelayakan['low'])
rule4 = ctrl.Rule(pendapatan['poor'] & nilaiUN['average'], kelayakan['high'])
rule5 = ctrl.Rule(pendapatan['average'] & nilaiUN['average'], kelayakan['low'])
rule6 = ctrl.Rule(pendapatan['good'] & nilaiUN['average'], kelayakan['low'])
Exemplo n.º 24
0
Użytkownik na samym początku podaję swoje dane jak wiek, 
długość czas posiadanego prawa jazdy i ilość mieszkańców 
, w którym żyje.
'''
age_val = int(input("Podaj swój wiek  : "))
experience_val = int(input("Ile lat posiadasz swoje prawo jazdy? : "))
city_populacion_val = int(input("Podaj ilość mieszkańców twojego miasta : "))
'''
Określenie danych wejściowych i wyjściowych wygląda  następująco:
- wiek w zakresię od 18 do 56 lat. Powyżej tego zakresu składka je staję się niezmiennia 
- czas posiadania prawa jazdy, który mieści się w zakresie do 31 lat   
- (wyjście) skala od 0 do 100. Im możliwie korzystne ubecpieczenie tym blizej 100 .
'''

# definiujemy membership funcions zaczynając od danyczah wejściowych i kończąc na wyjściowych
age = ctrl.Antecedent(np.arange(18, 56, 1), 'age')
experience = ctrl.Antecedent(np.arange(0, 31, 1), 'experience')
city_populacion = ctrl.Antecedent(np.arange(0, 500001, 1), 'city_populacion')
indicator = ctrl.Consequent(np.arange(0, 101, 1), 'indicator')

# definiujemy kształt naszych funkcji wejściowych. Dzielimy  wiek na :
# young, adult, old
age['young'] = fuzz.trimf(age.universe, [18, 25, 35])
age['adult'] = fuzz.trimf(age.universe, [25, 35, 45])
age['old'] = fuzz.trimf(age.universe, [35, 45, 55])

experience['beginner'] = fuzz.trimf(experience.universe, [0, 0, 15])
experience['intermediate'] = fuzz.trimf(experience.universe, [0, 15, 30])
experience['advanced'] = fuzz.trimf(experience.universe, [15, 30, 30])

city_populacion['small'] = fuzz.trimf(city_populacion.universe, [0, 0, 20000])
#importing libraries
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib
#configuring input and output variables
range_of_y = 1000
y=ctrl.Antecedent(np.arange(0,range_of_y+0.1,0.01),'lateral lane displacement')
range_of_acc= 300
y_acc=ctrl.Antecedent(np.arange(0,range_of_acc,0.001),'lateral accelaration')
error=100
e=ctrl.Antecedent(np.arange(-error,error,0.1),'error')
y['first']=fuzz.trapmf(y.universe,[0,range_of_y/16,3*range_of_y/16,4*range_of_y/16])
y['second']=fuzz.trapmf(y.universe,[5*range_of_y/16,6*range_of_y/16,7*range_of_y/16,8*range_of_y/16])
y['third']=fuzz.trapmf(y.universe,[9*range_of_y/16,10*range_of_y/16,11*range_of_y/16,12*range_of_y/16])
y['final']=fuzz.trapmf(y.universe,[13*range_of_y/16,14*range_of_y/16,15*range_of_y/16,16*range_of_y/16])
y_acc['GT0']=fuzz.trimf(y_acc.universe,[1,range_of_acc/2,range_of_acc])
y_acc['GE0']=fuzz.trimf(y_acc.universe,[0,range_of_acc/2,range_of_acc])
y_acc['LTM']=fuzz.trimf(y_acc.universe,[-range_of_acc,0,range_of_acc-1])
y_acc['GEM']=fuzz.trimf(y_acc.universe,[range_of_acc,range_of_acc,range_of_acc])
y_acc['GT-M']=fuzz.trimf(y_acc.universe,[-range_of_acc+1,0,range_of_acc])
y_acc['LE-M']=fuzz.trimf(y_acc.universe,[-range_of_acc,-range_of_acc,-range_of_acc])
y_acc['LT0']=fuzz.trimf(y_acc.universe,[-range_of_acc,-range_of_acc/2,-1])
y_acc['LE0']=fuzz.trimf(y_acc.universe,[-range_of_acc,-range_of_acc/2,0])
e['N']=fuzz.trimf(e.universe,[-error,-error,-1])
e['Z']=fuzz.trimf(e.universe,[-error/2,0,error/2])
e['P']=fuzz.trimf(e.universe,[1,error,error])

stear_angle=0.006
angle=ctrl.Consequent(np.arange(-stear_angle,stear_angle,0.0001),'stear_angle')
angle['s1']=fuzz.trimf(angle.universe,[0,0.0006/2,0.0006])
Exemplo n.º 26
0
    #inputs
    a_direcao.input['distanciaF'] = frente
    a_direcao.input['distanciaE'] = esquerda
    a_direcao.input['distanciaD'] = direita
    # Crunch the numbers
    a_direcao.compute()
    return (a_direcao.output['direcao'], a_direcao.output['velocidade'])


posicao_x = []
posicao_y = []

#variaveis fuzzy
direcao = ctrl.Consequent(np.arange(0, 11, 1), 'direcao')
velocidade = ctrl.Consequent(np.arange(0, 11, 1), 'velocidade')
distanciaF = ctrl.Antecedent(np.arange(0, 11, 1), 'distanciaF')
distanciaD = ctrl.Antecedent(np.arange(0, 11, 1), 'distanciaD')
distanciaE = ctrl.Antecedent(np.arange(0, 11, 1), 'distanciaE')

v_mp = [0, 0, 3]
v_p = [0, 3, 5]
v_m = [0, 5, 10]
v_l = [5, 8, 10]
v_ml = [8, 10, 10]

distanciaF['mperto'] = fuzz.trimf(distanciaF.universe, v_mp)
distanciaF['perto'] = fuzz.trimf(distanciaF.universe, v_p)
distanciaF['medio'] = fuzz.trimf(distanciaF.universe, v_m)
distanciaF['longe'] = fuzz.trimf(distanciaF.universe, v_ml)

distanciaD['mperto'] = fuzz.trimf(distanciaD.universe, v_mp)
Exemplo n.º 27
0
    def __init__(self):
        # first we need to design the membership functions

        # The arrival membership function
        # assign the bounds of the membership function
        arrivals = ctrl.Antecedent(np.arange(0, 16, 1), 'arrivals')

        # assign the bounds of every fuzzy member
        arrivals["AN"] = fuzz.trimf(arrivals.universe, [0, 0, 2])
        arrivals["F"] = fuzz.trimf(arrivals.universe, [1, 4, 7])
        arrivals["MY"] = fuzz.trimf(arrivals.universe, [5, 9, 13])
        arrivals["TMY"] = fuzz.trimf(arrivals.universe, [10, 15, 15])

        # the queue membership function
        # assign the bounds of the queue membership function
        queue = ctrl.Antecedent(np.arange(0, 16, 1), 'queue')

        # assign the the bounds of each fuzzy member
        queue["VS"] = fuzz.trimf(queue.universe, [0, 0, 2])
        queue["S"] = fuzz.trimf(queue.universe, [1, 4, 7])
        queue["M"] = fuzz.trimf(queue.universe, [5, 9, 13])
        queue["L"] = fuzz.trimf(queue.universe, [10, 15, 15])

        # the extension membership function
        # assign the bounds of the extension membership function
        extension = ctrl.Consequent(np.arange(0, 7, 1), 'extension')

        # assign the bounds of each fuzzy member
        extension["Z"] = fuzz.trimf(extension.universe, [0, 0, 2])
        extension["SO"] = fuzz.trimf(extension.universe, [0, 2, 4])
        extension["ML"] = fuzz.trimf(extension.universe, [2, 4, 6])
        extension["LO"] = fuzz.trimf(extension.universe, [4, 6, 6])
        self.extension = extension

        # implement all the rules available
        rule1 = ctrl.Rule(arrivals["AN"] & queue["VS"], extension["Z"])
        rule2 = ctrl.Rule(arrivals["AN"] & queue["S"], extension["Z"])
        rule3 = ctrl.Rule(arrivals["AN"] & queue["M"], extension["Z"])
        rule4 = ctrl.Rule(arrivals["AN"] & queue["L"], extension["Z"])
        rule5 = ctrl.Rule(arrivals["F"] & queue["VS"], extension["SO"])
        rule6 = ctrl.Rule(arrivals["F"] & queue["S"], extension["SO"])
        rule7 = ctrl.Rule(arrivals["F"] & queue["M"], extension["Z"])
        rule8 = ctrl.Rule(arrivals["F"] & queue["L"], extension["Z"])
        rule9 = ctrl.Rule(arrivals["MY"] & queue["VS"], extension["ML"])
        rule10 = ctrl.Rule(arrivals["MY"] & queue["S"], extension["ML"])
        rule11 = ctrl.Rule(arrivals["MY"] & queue["M"], extension["SO"])
        rule12 = ctrl.Rule(arrivals["MY"] & queue["L"], extension["Z"])
        rule13 = ctrl.Rule(arrivals["TMY"] & queue["VS"], extension["LO"])
        rule14 = ctrl.Rule(arrivals["TMY"] & queue["S"], extension["ML"])
        rule15 = ctrl.Rule(arrivals["TMY"] & queue["M"], extension["ML"])
        rule16 = ctrl.Rule(arrivals["TMY"] & queue["L"], extension["SO"])

        # implement the control system that does the fuzzification, composition inference and defuzzification for us
        traffic_lights_ctrl = ctrl.ControlSystem(rules=[
            rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9,
            rule10, rule11, rule12, rule13, rule14, rule15, rule16
        ])
        if graphs:
            extension.view()
            arrivals.view()
            queue.view()
            traffic_lights_ctrl.view()

        self.traffic_lights_simulation = ctrl.ControlSystemSimulation(
            traffic_lights_ctrl)
Exemplo n.º 28
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt

temp = ctrl.Antecedent(np.arange(0, 101, 1), 'temp')
clock_speed = ctrl.Antecedent(np.arange(0, 4.5, 0.5), 'clock_speed')
fan_speed = ctrl.Consequent(np.arange(0, 6001, 1), 'fan_speed')

temp['cold'] = fuzz.trimf(temp.universe, [0, 0, 50])
temp['warm'] = fuzz.trimf(temp.universe, [30, 50, 70])
temp['hot'] = fuzz.trimf(temp.universe, [50, 100, 100])

clock_speed['low'] = fuzz.trimf(clock_speed.universe, [0, 0, 1.5])
clock_speed['normal'] = fuzz.trimf(clock_speed.universe, [0.5, 2, 3.5])
clock_speed['turbo'] = fuzz.trimf(clock_speed.universe, [2.5, 4, 4])

fan_speed['slow'] = fuzz.trimf(fan_speed.universe, [0, 0, 3500])
fan_speed['fast'] = fuzz.trimf(fan_speed.universe, [2500, 6000, 6000])

temp.view()
clock_speed.view()
fan_speed.view()

rules = []
rule1 = ctrl.Rule(temp['cold'] & clock_speed['low'], fan_speed['slow'])
rule2 = ctrl.Rule(temp['cold'] & clock_speed['normal'], fan_speed['slow'])
rule3 = ctrl.Rule(temp['cold'] & clock_speed['turbo'], fan_speed['fast'])
rule4 = ctrl.Rule(temp['warm'] & clock_speed['low'], fan_speed['slow'])
rule5 = ctrl.Rule(temp['warm'] & clock_speed['normal'], fan_speed['slow'])
rule6 = ctrl.Rule(temp['warm'] & clock_speed['turbo'], fan_speed['fast'])
Exemplo n.º 29
0
def test_multiple_rules_same_consequent_term():
    # 2 input variables, 1 output variable and 7 instances.
    x1_inputs = [0.6, 0.2, 0.4, 0.7, 1, 1.2, 1.8]
    x2_inputs = [0.9, 1, 0.8, 0, 1.2, 0.6, 1.8]

    dom = np.arange(0, 2.1, 0.01)
    x1 = ctrl.Antecedent(dom, "x1")
    x1['label0'] = fuzz.trimf(x1.universe, (0.2, 0.2, 0.6))
    x1['label1'] = fuzz.trimf(x1.universe, (0.2, 0.6, 1.0))
    x1['label2'] = fuzz.trimf(x1.universe, (0.6, 1.0, 1.4))
    x1['label3'] = fuzz.trimf(x1.universe, (1.0, 1.4, 1.8))
    x1['label4'] = fuzz.trimf(x1.universe, (1.4, 1.8, 1.8))

    x2 = ctrl.Antecedent(dom, "x2")
    x2['label0'] = fuzz.trimf(x2.universe, (0.0, 0.0, 0.45))
    x2['label1'] = fuzz.trimf(x2.universe, (0.0, 0.45, 0.9))
    x2['label2'] = fuzz.trimf(x2.universe, (0.45, 0.9, 1.35))
    x2['label3'] = fuzz.trimf(x2.universe, (0.9, 1.35, 1.8))
    x2['label4'] = fuzz.trimf(x2.universe, (1.35, 1.8, 1.8))

    y = ctrl.Consequent(dom, "y")
    y['label0'] = fuzz.trimf(y.universe, (0.3, 0.3, 0.725))
    y['label1'] = fuzz.trimf(y.universe, (0.3, 0.725, 1.15))
    y['label2'] = fuzz.trimf(y.universe, (0.725, 1.15, 1.575))
    y['label3'] = fuzz.trimf(y.universe, (1.15, 1.575, 2.0))
    y['label4'] = fuzz.trimf(y.universe, (1.575, 2.0, 2.0))

    r1 = ctrl.Rule(x1['label0'] & x2['label2'], y['label0'])
    r2 = ctrl.Rule(x1['label1'] & x2['label0'], y['label0'])
    r3 = ctrl.Rule(x1['label1'] & x2['label2'], y['label0'])

    # Equivalent to above 3 rules
    r123 = ctrl.Rule(
        (x1['label0'] & x2['label2']) | (x1['label1'] & x2['label0']) |
        (x1['label1'] & x2['label2']), y['label0'])

    r4 = ctrl.Rule(x1['label2'] & x2['label1'], y['label2'])
    r5 = ctrl.Rule(x1['label2'] & x2['label3'], y['label3'])
    r6 = ctrl.Rule(x1['label4'] & x2['label4'], y['label4'])

    # Build a system with three rules targeting the same Consequent Term,
    # and then an equivalent system with those three rules combined into one.
    cs0 = ctrl.ControlSystem([r1, r2, r3, r4, r5, r6])
    cs1 = ctrl.ControlSystem([r123, r4, r5, r6])

    expected_results = [
        0.438372093023, 0.443962536855, 0.461436409933, 0.445290345769, 1.575,
        1.15, 1.86162790698
    ]

    # Ensure the results are equivalent within error
    for inst, expected in zip(range(7), expected_results):
        sim0 = ctrl.ControlSystemSimulation(cs0)
        sim1 = ctrl.ControlSystemSimulation(cs1)

        sim0.input["x1"] = x1_inputs[inst]
        sim0.input["x2"] = x2_inputs[inst]
        sim1.input["x1"] = x1_inputs[inst]
        sim1.input["x2"] = x2_inputs[inst]

        sim0.compute()
        sim1.compute()

        tst.assert_allclose(sim0.output['y'], sim1.output['y'])
        tst.assert_allclose(expected, sim0.output['y'], atol=1e-4, rtol=1e-4)
Exemplo n.º 30
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt

#variable
pan_temp = ctrl.Antecedent(np.arange(0, 121, 0.5), 'pan_temp')
pan_weight = ctrl.Antecedent(np.arange(0, 3.1, 0.1), 'pan_weight')
heat_level = ctrl.Consequent(np.arange(0, 121, 0.5), 'heat_level')

#membership function
pan_temp['cold'] = fuzz.trimf(pan_temp.universe, [0, 0, 45])
pan_temp['warm'] = fuzz.trimf(pan_temp.universe, [30, 60, 90])
pan_temp['hot'] = fuzz.trimf(pan_temp.universe, [75, 105, 120])

pan_weight['low'] = fuzz.trimf(pan_weight.universe, [0, 0, 1.0])
pan_weight['medium'] = fuzz.trimf(pan_weight.universe, [0.5, 1.25, 2.0])
pan_weight['high'] = fuzz.trimf(pan_weight.universe, [1.5, 2.25, 3.0])

heat_level['low'] = fuzz.trimf(heat_level.universe, [0, 0, 60])
heat_level['medium'] = fuzz.trimf(heat_level.universe, [20, 60, 100])
heat_level['high'] = fuzz.trimf(heat_level.universe, [60, 100, 120])

pan_temp.view()
pan_weight.view()
heat_level.view()
plt.show()

#rules
r1 = ctrl.Rule(pan_temp['cold'] & pan_weight['low'], heat_level['medium'])
r2 = ctrl.Rule(pan_temp['cold'] & pan_weight['medium'], heat_level['medium'])