Exemplo n.º 1
2
    def __init__(self):
        # INPUTY
        self.buildingType = ctrl.Antecedent(np.arange(0, 400, 1), "Technologia budynku")
        self.wearWater = ctrl.Antecedent(np.arange(0, 500, 0.1), "Zuzycie wody na osobe")

        self.zone = ctrl.Antecedent(np.arange(15, 25, 0.01), "Strefa klimatyczna")
        self.isolation = ctrl.Antecedent(np.arange(1, 100, 1), "Procentowa termoizolacja budynku")
        self.surface = ctrl.Antecedent(np.arange(20, 150, 0.01), "Powierzchnia grzewcza")
        # OUTPUTY
        self.typeFurnance = ctrl.Consequent(np.arange(1, 100, 1), "Rodzaj pieca")

        # MEMBERSHIPS FUN

        self.buildingType['starebudownictwo'] = fuzz.trapmf(self.buildingType.universe, [170, 350, 400, 400])
        self.buildingType['70-85'] = fuzz.gaussmf(self.buildingType.universe, 260, 25)
        self.buildingType['86-92'] = fuzz.gaussmf(self.buildingType.universe, 200, 20)
        self.buildingType['93-97'] = fuzz.gaussmf(self.buildingType.universe, 160, 15)
        self.buildingType['98-07'] = fuzz.gaussmf(self.buildingType.universe, 120, 15)
        self.buildingType['energooszczedny'] = fuzz.gaussmf(self.buildingType.universe, 80, 15)
        self.buildingType['niskoenegetyczny'] = fuzz.gaussmf(self.buildingType.universe, 45, 10)
        self.buildingType['pasywny'] = fuzz.trapmf(self.buildingType.universe, [0, 0, 15, 100])

        # ----------------------

        self.wearWater['1 osoba'] = fuzz.zmf(self.wearWater.universe, 20, 80)
        self.wearWater['2 osoba'] = fuzz.gaussmf(self.wearWater.universe, 100, 30)
        self.wearWater['3 osoba'] = fuzz.gaussmf(self.wearWater.universe, 150, 30)
        self.wearWater['4 osoba'] = fuzz.gaussmf(self.wearWater.universe, 200, 40)
        self.wearWater['5 osoba'] = fuzz.gaussmf(self.wearWater.universe, 250, 50)
        self.wearWater['6 osoba'] = fuzz.gaussmf(self.wearWater.universe, 300, 60)
        self.wearWater['7 osoba'] = fuzz.gaussmf(self.wearWater.universe, 350, 60)
        self.wearWater['8 osoba'] = fuzz.smf(self.wearWater.universe, 310, 470)

        # ----------------------

        self.zone['Strefa 1'] = fuzz.gaussmf(self.zone.universe, 16, 0.5)
        self.zone['Strefa 2'] = fuzz.gaussmf(self.zone.universe, 18, 0.9)
        self.zone['Strefa 3'] = fuzz.gaussmf(self.zone.universe, 20, 1.5)
        self.zone['Strefa 4'] = fuzz.gaussmf(self.zone.universe, 22, 1.2)
        self.zone['Strefa 5'] = fuzz.gaussmf(self.zone.universe, 24, 0.45)

        # ---------------------

        self.surface['kawalerka'] = fuzz.zmf(self.surface.universe, 25, 65)
        self.surface['mieszkanie'] = fuzz.gaussmf(self.surface.universe, 75, 30)
        self.surface['apartament'] = fuzz.gaussmf(self.surface.universe, 111, 8)
        self.surface['dom_jednorodzinny'] = fuzz.gaussmf(self.surface.universe, 130, 3.5)
        self.surface['willa'] = fuzz.smf(self.surface.universe, 130, 150)

        # --------------------

        self.isolation['brak'] = fuzz.zmf(self.isolation.universe, 5, 15)
        self.isolation['slabo'] = fuzz.gaussmf(self.isolation.universe, 20, 7)
        self.isolation['srednio'] = fuzz.gaussmf(self.isolation.universe, 50, 20)
        self.isolation['dobrze'] = fuzz.gaussmf(self.isolation.universe, 70, 10)
        self.isolation['doskonale'] = fuzz.smf(self.isolation.universe, 75, 95)

        self.typeFurnance['weglowy'] = fuzz.zmf(self.typeFurnance.universe, 4, 40)
        self.typeFurnance['gazowy'] = fuzz.gbellmf(self.typeFurnance.universe, 23, 2.5, 50)
        self.typeFurnance['pompa ciepla'] = fuzz.smf(self.typeFurnance.universe, 70, 100)

        # -----------------------
        # RULES
        rules = [

            ctrl.Rule(self.buildingType['pasywny'] & self.wearWater['4 osoba'] & self.surface['dom_jednorodzinny'] &
                      self.isolation['doskonale'], self.typeFurnance['pompa ciepla']),
            ctrl.Rule(self.buildingType['starebudownictwo'] & self.wearWater['8 osoba'] & self.isolation['brak'] &
                      self.surface['dom_jednorodzinny'],
                      self.typeFurnance['weglowy']),
            ctrl.Rule(self.buildingType['starebudownictwo'] & self.wearWater['7 osoba'] & self.isolation['slabo'] &
                      self.surface['dom_jednorodzinny'],
                      self.typeFurnance['weglowy']),
            ctrl.Rule(self.buildingType['starebudownictwo'] & self.wearWater['6 osoba'] & self.isolation['slabo'] &
                      self.surface['dom_jednorodzinny'],
                      self.typeFurnance['weglowy']),

            ctrl.Rule(self.buildingType['70-85'] & self.wearWater['6 osoba'] & self.isolation['slabo'] & self.surface[
                'dom_jednorodzinny'],
                      self.typeFurnance['weglowy']),

            ctrl.Rule(self.buildingType['niskoenegetyczny'] & self.wearWater['5 osoba'] & self.isolation['dobrze'] &
                      self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']),

            ctrl.Rule(self.buildingType['energooszczedny'] & self.wearWater['5 osoba'] & self.isolation['dobrze'] &
                      self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']),

            ctrl.Rule(self.buildingType['energooszczedny'] & self.wearWater['4 osoba'] & self.isolation['dobrze'] &
                      self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']),

            ctrl.Rule(self.buildingType['niskoenegetyczny'] & self.wearWater['5 osoba'] & self.isolation['dobrze'] &
                      self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']),

            ctrl.Rule(self.buildingType['93-97'] & self.wearWater['2 osoba'] & self.isolation['srednio'] & self.surface[
                'kawalerka'], self.typeFurnance['gazowy']),

            ctrl.Rule(self.buildingType['93-97'] & self.wearWater['3 osoba'] & self.isolation['srednio'] & self.surface[
                'mieszkanie'], self.typeFurnance['gazowy']),

            ctrl.Rule(self.buildingType['93-97'] & self.wearWater['4 osoba'] & self.isolation['srednio'] & self.surface[
                'mieszkanie'], self.typeFurnance['gazowy']),

            ctrl.Rule(self.buildingType['98-07'] & self.wearWater['2 osoba'] & self.isolation['srednio'] & self.surface[
                'kawalerka'], self.typeFurnance['gazowy']),
            ctrl.Rule(self.buildingType['98-07'] & self.wearWater['3 osoba'] & self.isolation['srednio'] & self.surface[
                'mieszkanie'], self.typeFurnance['gazowy']),
            ctrl.Rule(self.buildingType['98-07'] & self.wearWater['4 osoba'] & self.isolation['srednio'] & self.surface[
                'mieszkanie'], self.typeFurnance['gazowy']),
            ctrl.Rule(self.buildingType['98-07'] & self.wearWater['5 osoba'] & self.isolation['srednio'] & self.surface[
                'apartament'], self.typeFurnance['gazowy']),
        ]

        # Controll System
        self.typeControl = ctrl.ControlSystem(rules)

        self.type = ctrl.ControlSystemSimulation(self.typeControl)
Exemplo n.º 2
0
    def __init__(self,
                 minm,
                 maxm,
                 n_variavel,
                 media=None,
                 dp=None,
                 dados=None,
                 passo=0.01,
                 likert=3,
                 tipo='antecedente'):
        # dados: vetor de dados de referência.
        # minm: valor mínimo.git init.
        # maxm: valor máximo.
        # n_variavel: nome da variavel.
        # passo: nível de discretização da variável fuzzy.
        # tipo: tipo de variável fuzzy.
        # likert: tamanho da escala.

        self.min = minm
        self.max = maxm

        # Calcula a média e desvio padrão a partir dos dados fornecidos,
        # caso contrário os estima a partir dos valores mínimo e máximo.
        try:
            self.media = dados.mean()
            self.dp = dados.std()
            media = self.media
            dp = self.dp
        except Exception:
            try:
                self.media = media * 1
                self.dp = dp * 1
            except Exception:
                self.media = (minm + maxm) / 2
                self.dp = ((maxm - minm)**2 / 12)**0.5
                media = self.media
                dp = self.dp

        if tipo == 'consequente':
            self.vf = ctrl.Consequent(np.arange(minm, maxm, passo), n_variavel)
        else:
            self.vf = ctrl.Antecedent(np.arange(minm, maxm, passo), n_variavel)

        if (likert == 5):
            self.vf['muito baixo'] = fuzz.zmf(self.vf.universe, media - 5 * dp,
                                              media - 2 * dp)
            self.vf['baixo'] = fuzz.gaussmf(self.vf.universe, media - 2 * dp,
                                            dp)
            self.vf['medio'] = fuzz.gaussmf(self.vf.universe, media, dp)
            self.vf['alto'] = fuzz.gaussmf(self.vf.universe, media + 2 * dp,
                                           dp)
            self.vf['muito alto'] = fuzz.smf(self.vf.universe, media + 2 * dp,
                                             media + 5 * dp)
        elif (likert == 3):
            self.vf['baixo'] = fuzz.zmf(self.vf.universe, minm, media)
            self.vf['medio'] = fuzz.gaussmf(self.vf.universe, media, dp)
            self.vf['alto'] = fuzz.smf(self.vf.universe, media, maxm)
        else:
            raise RuntimeError(
                "Utilize escalas tipo likert com 3 ou 5 categorias.")
Exemplo n.º 3
0
    def __init__(self, parameter, x_minSOC_range, x_E_range, y_alpha_range):
        # 创建一个模糊控制变量
        self.x_minSOC = ctrl.Antecedent(x_minSOC_range, 'minSOC')
        self.x_E = ctrl.Antecedent(x_E_range, 'E')
        self.y_alpha = ctrl.Consequent(y_alpha_range, 'alpha')

        # 定义了模糊集及其隶属度函数
        self.x_minSOC['NB'] = fuzz.zmf(x_minSOC_range, parameter['x_min_zmf10'], parameter['x_min_zmf11'])
        self.x_minSOC['NS'] = fuzz.trimf(x_minSOC_range, parameter['x_min_trimf1'])
        self.x_minSOC['ZO'] = fuzz.trimf(x_minSOC_range, parameter['x_min_trimf2'])
        self.x_minSOC['PS'] = fuzz.trimf(x_minSOC_range, parameter['x_min_trimf3'])
        self.x_minSOC['PB'] = fuzz.smf(x_minSOC_range, parameter['x_min_smf10'], parameter['x_min_smf11'])

        self.x_E['NB'] = fuzz.zmf(x_E_range, parameter['x_E_zmf10'], parameter['x_E_zmf11'])
        self.x_E['PB'] = fuzz.smf(x_E_range, parameter['x_E_smf10'], parameter['x_E_smf11'])

        self.y_alpha['NB'] = fuzz.zmf(y_alpha_range, parameter['y_zmf10'], parameter['y_zmf11'])
        self.y_alpha['NS'] = fuzz.trimf(y_alpha_range, parameter['y_trimf1'])
        self.y_alpha['ZO'] = fuzz.trimf(y_alpha_range, parameter['y_trimf2'])
        self.y_alpha['PS'] = fuzz.trimf(y_alpha_range, parameter['y_trimf3'])
        self.y_alpha['PB'] = fuzz.smf(y_alpha_range, parameter['y_smf10'], parameter['y_smf11'])
        self.y_alpha['NB1'] = fuzz.zmf(y_alpha_range, parameter['y_zmf20'], parameter['y_zmf21'])
        self.y_alpha['PB1'] = fuzz.trimf(y_alpha_range, parameter['y_trimf4'])

        # 设置输出alpha去模糊方法-质心去模糊方法
        self.y_alpha.defuzzify_method = 'mom'
        self.system = None
        self.sim = None
def consecuentes():
    agua = ctrl.Consequent(
        [0, 30, 60, 90, 120, 150, 200, 250, 300, 350, 400, 450], 'agua')
    cafe = ctrl.Consequent(np.arange(0, 151, 1), 'cafe')
    leche = ctrl.Consequent(np.arange(0, 58, 1), 'leche')
    chocolate = ctrl.Consequent(np.arange(0, 15, 1), 'chocolate')
    tiempo = ctrl.Consequent(np.arange(1, 4.5, 0.5), 'tiempo')

    agua['poca'] = fuzz.zmf(agua.universe, 90, 300)
    agua['media'] = fuzz.trimf(agua.universe, [125, 250, 350])
    agua['mucha'] = fuzz.smf(agua.universe, 200, 345)

    cafe['poca'] = fuzz.zmf(cafe.universe, 45, 76)
    cafe['media'] = fuzz.trimf(cafe.universe, [45, 75, 100])
    cafe['mucha'] = fuzz.smf(cafe.universe, 74, 100)

    leche['poca'] = fuzz.zmf(leche.universe, 14, 29)
    leche['media'] = fuzz.trimf(leche.universe, [14, 28, 42])
    leche['mucha'] = fuzz.smf(leche.universe, 27, 42)

    chocolate['poca'] = fuzz.zmf(chocolate.universe, 4, 8)
    chocolate['media'] = fuzz.trimf(chocolate.universe, [4, 7, 10])
    chocolate['mucha'] = fuzz.smf(chocolate.universe, 6, 10)

    tiempo['poca'] = fuzz.zmf(tiempo.universe, 1.5, 3.0)
    tiempo['media'] = fuzz.trimf(tiempo.universe, [1.5, 2.5, 3.5])
    tiempo['mucha'] = fuzz.smf(tiempo.universe, 2.0, 3.5)

    return agua, cafe, leche, chocolate, tiempo
Exemplo n.º 5
0
    def __init__(self):
        """Initialize of the FlightPhase object."""
        super(FlightPhase, self).__init__()

        # logic states
        self.alt_range = np.arange(0, 40000, 1)
        self.roc_range = np.arange(-4000, 4000, 0.1)
        self.spd_range = np.arange(0, 600, 1)
        self.states = np.arange(0, 6, 0.01)

        self.alt_gnd = fuzz.zmf(self.alt_range, 0, 200)
        self.alt_lo = fuzz.gaussmf(self.alt_range, 10000, 10000)
        self.alt_hi = fuzz.gaussmf(self.alt_range, 35000, 20000)

        self.roc_zero = fuzz.gaussmf(self.roc_range, 0, 100)
        self.roc_plus = fuzz.smf(self.roc_range, 10, 1000)
        self.roc_minus = fuzz.zmf(self.roc_range, -1000, -10)

        self.spd_hi = fuzz.gaussmf(self.spd_range, 600, 100)
        self.spd_md = fuzz.gaussmf(self.spd_range, 300, 100)
        self.spd_lo = fuzz.gaussmf(self.spd_range, 0, 50)

        self.state_ground = fuzz.gaussmf(self.states, 1, 0.1)
        self.state_climb = fuzz.gaussmf(self.states, 2, 0.1)
        self.state_descent = fuzz.gaussmf(self.states, 3, 0.1)
        self.state_cruise = fuzz.gaussmf(self.states, 4, 0.1)
        self.state_level = fuzz.gaussmf(self.states, 5, 0.1)

        self.state_lable_map = {1: 'GND', 2: 'CL', 3: 'DE', 4: 'CR', 5: 'LVL'}

        self.ts = None
        self.alt = None
        self.spd = None
        self.roc = None
Exemplo n.º 6
0
    def fuzzify_direc_val(self, direc_vals, stop_vals):

        direc_f = fuzzy.trimf(direc_vals, [-1, 0, 1])
        direc_l = fuzzy.zmf(direc_vals, -1, 0)
        direc_r = 1.0 - fuzzy.zmf(direc_vals, 0, 1)
        stop = 1.0 - fuzzy.zmf(stop_vals, 0.5, 1.5)

        return direc_f, direc_l, direc_r, stop
Exemplo n.º 7
0
def calculate_pi3k_mfs(egfr, erk, pi3k):
	egfr_low = fuzz.zmf(egfr, 0, 0.95)
	egfr_high = fuzz.smf(egfr, 0.1, 0.9)
	erk_low = fuzz.zmf(erk, 0, 0.9)
	erk_high = fuzz.smf(erk, 0, 0.9)
	pi3k_low = fuzz.gaussmf(pi3k, 0, egfr[egfr.size - 1]/20)
	pi3k_high = fuzz.gaussmf(pi3k, egfr[egfr.size - 1], egfr[egfr.size - 1]/20)
	return ((egfr_low, egfr_high), (erk_low, erk_high), (pi3k_low, pi3k_high))
Exemplo n.º 8
0
def calculate_raf_mfs( egfr, akt, raf):
	egfr_low = fuzz.zmf(egfr, 0, 0.95)
	egfr_high = fuzz.smf(egfr, 0.1, 0.9)
	akt_low = fuzz.zmf(akt, 0, 0.95)
	akt_high = fuzz.smf(akt, 0.1, 0.9)
	raf_low = fuzz.gaussmf(raf, 0, egfr[egfr.size - 1]/20)
	raf_high = fuzz.gaussmf(raf, egfr[egfr.size - 1], egfr[egfr.size - 1]/20)
	return ((egfr_low, egfr_high), (akt_low, akt_high), (raf_low, raf_high))
Exemplo n.º 9
0
def membership_f(mf, x, abcd):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
    """
    if mf == "zmf":
        return fuzz.zmf(x, abcd[0], abcd[1])  # zmf(x, a, b)
    elif mf == "trimf":
        return fuzz.trimf(x, abcd[0:3])  # trimf(x, abc)
    elif mf == "dsigmf":
        return fuzz.dsigmf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # dsigmf(x, b1, c1, b2, c2)
    elif mf == "gauss2mf":
        return fuzz.gauss2mf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # gauss2mf(x, mean1, sigma1, mean2, sigma2)
    elif mf == "gaussmf":
        return fuzz.gaussmf(x, abcd[0], abcd[1])  # gaussmf(x, mean, sigma)
    elif mf == "gbellmf":
        return fuzz.gbellmf(x, abcd[0], abcd[1], abcd[2])  # gbellmf(x, a, b, c)
    elif mf == "piecemf":
        return fuzz.piecemf(x, abcd[0:3])  # piecemf(x, abc)
    elif mf == "pimf":
        return fuzz.pimf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # pimf(x, a, b, c, d)
    elif mf == "psigmf":
        return fuzz.psigmf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # psigmf(x, b1, c1, b2, c2)
    elif mf == "sigmf":
        return fuzz.sigmf(x, abcd[0], abcd[1])  # sigmf(x, b, c)
    elif mf == "smf":
        return fuzz.smf(x, abcd[0], abcd[1])  # smf(x, a, b)
    elif mf == "trapmf":
        return fuzz.trapmf(x, abcd)  # trapmf(x, abcd)
Exemplo n.º 10
0
def EcHistDifuso(img):
    gris = np.uint8(color.rgb2gray(cv2.resize(img, (576, 432))) * 255)
    fil, col = gris.shape

    pixel = np.linspace(0, 255, 256)
    oscuros = fuzzy.zmf(
        pixel, 25, 130
    )  #Conjunto difuzo tipo Z, en el 25 empieza a caer, y cae hasta 130, luego es 0
    claros = fuzzy.smf(pixel, 130, 230)
    grises = fuzzy.gbellmf(
        pixel, 55, 3, 128)  #Apertura de campana, pendiente de caída, centro

    s1 = 10
    s2 = 128
    s3 = 245

    newg = np.zeros(256)
    for i in range(256):
        newg[i] = (oscuros[i] * s1 + grises[i] * s2 +
                   claros[i] * s3) / (oscuros[i] + grises[i] + claros[i])

    ehf = np.zeros([fil, col])
    for ff in range(fil):
        for cc in range(col):
            valor = gris[ff, cc]
            ehf[ff, cc] = newg[valor]
    ehf = np.uint8(ehf)

    #Se salva el archivo

    path_file = ('static/%s.jpg' % uuid.uuid4().hex)
    io.imsave(path_file, ehf)
    return json.dumps(path_file)  #Regresa el nombre de la imagen
Exemplo n.º 11
0
def membership_f(mf, x, abcd):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
    """
    if mf == 'zmf': return fuzz.zmf(x, abcd[0], abcd[1])  # zmf(x, a, b)
    elif mf == 'trimf': return fuzz.trimf(x, abcd[0:3])  # trimf(x, abc)
    elif mf == 'dsigmf':
        return fuzz.dsigmf(x, abcd[0], abcd[1], abcd[2],
                           abcd[3])  # dsigmf(x, b1, c1, b2, c2)
    elif mf == 'gauss2mf':
        return fuzz.gauss2mf(
            x, abcd[0], abcd[1], abcd[2],
            abcd[3])  # gauss2mf(x, mean1, sigma1, mean2, sigma2)
    elif mf == 'gaussmf':
        return fuzz.gaussmf(x, abcd[0], abcd[1])  # gaussmf(x, mean, sigma)
    elif mf == 'gbellmf':
        return fuzz.gbellmf(x, abcd[0], abcd[1],
                            abcd[2])  # gbellmf(x, a, b, c)
    elif mf == 'piecemf':
        return fuzz.piecemf(x, abcd[0:3])  # piecemf(x, abc)
    elif mf == 'pimf':
        return fuzz.pimf(x, abcd[0], abcd[1], abcd[2],
                         abcd[3])  # pimf(x, a, b, c, d)
    elif mf == 'psigmf':
        return fuzz.psigmf(x, abcd[0], abcd[1], abcd[2],
                           abcd[3])  # psigmf(x, b1, c1, b2, c2)
    elif mf == 'sigmf':
        return fuzz.sigmf(x, abcd[0], abcd[1])  # sigmf(x, b, c)
    elif mf == 'smf':
        return fuzz.smf(x, abcd[0], abcd[1])  # smf(x, a, b)
    elif mf == 'trapmf':
        return fuzz.trapmf(x, abcd)  # trapmf(x, abcd)
Exemplo n.º 12
0
    def get_fuzzy_membership_map():
        normal_trapezoid = np_array([120, 280, 320, 500])

        return {
            Cost.CHEAP: lambda x: zmf(x, a=0, b=180),
            Cost.NORMAL: lambda x: trapmf(x, abcd=normal_trapezoid),
            Cost.EXPENSIVE: lambda x: smf(x, a=300, b=1000)
        }
Exemplo n.º 13
0
def calculate_egfr_mfs(time, egf, egfr, egf_index, t):
	size = egf.size
	#egfr = np.linspace(0, egf[egf_index], size)
	time_low = fuzz.zmf(time, 0, time[egf.size*t - t] - time[egf_index*t] + time[t] )
	time_high = fuzz.smf(time, 0, time[egf.size*t - t] - time[egf_index*t] + time[t] )
	egfr_low = fuzz.gaussmf(egfr, 0, egf[egf_index]/20)
	egfr_high = transform_gaussmf(egfr, (egf[egf_index], egf[egf_index]/20), 1)
	return ((time_low, time_high, egfr_low, egfr_high))
Exemplo n.º 14
0
    def get_fuzzy_membership_map():
        average_trapezoid = np_array([10, 48, 52, 90])

        return {
            Distance.SHORT: lambda x: zmf(x, a=0, b=30),
            Distance.AVERAGE: lambda x: trapmf(x, abcd=average_trapezoid),
            Distance.LONG: lambda x: smf(x, a=20, b=100)
        }
Exemplo n.º 15
0
def antecedentes():
    temperatura = ctrl.Antecedent(np.arange(-10, 41, 1), 'temperatura')
    tazaSize = ctrl.Antecedent(
        [0, 30, 60, 90, 120, 150, 200, 250, 300, 350, 400, 450, 451],
        'tazaSize')
    intensidad = ctrl.Antecedent(np.arange(1, 6, 1), 'intensidad')

    temperatura['frio'] = fuzz.zmf(temperatura.universe, -10, 41)
    temperatura['calido'] = fuzz.gaussmf(temperatura.universe, 18, 10)
    temperatura['caluroso'] = fuzz.smf(temperatura.universe, -11, 41)

    tazaSize['pequeno'] = fuzz.zmf(tazaSize.universe, 0, 451)
    tazaSize['mediano'] = fuzz.gaussmf(tazaSize.universe, 240, 100)
    tazaSize['grande'] = fuzz.smf(tazaSize.universe, 0, 451)

    intensidad['suave'] = fuzz.zmf(intensidad.universe, 0, 5)
    intensidad['medio'] = fuzz.gaussmf(intensidad.universe, 3, 1)
    intensidad['fuerte'] = fuzz.smf(intensidad.universe, 0, 5)

    return temperatura, tazaSize, intensidad
Exemplo n.º 16
0
def _makeMemberFunctions(x):
    """
    Returns matrix of member functions values for given universal set.

    Rows denote values for following terms: Low, Medium, High.
    """

    half = x[x.size // 2]

    return np.vstack((fz.zmf(x, x[0], half), fz.trimf(x, [x[0], half, x[-1]]),
                      fz.smf(x, half, x[-1])))
Exemplo n.º 17
0
def membership_f(mf, x, abc = [0,0,0], a = 1, b = 2, c = 3, d = 4, abcd = [0,0,0,0]):

        return {
            'trimf'   : fuzz.trimf(x, abc),                                 # trimf(x, abc)
            'dsigmf'  : fuzz.dsigmf(x, a, b, c, d),                         # dsigmf(x, b1, c1, b2, c2)
            'gauss2mf': fuzz.gauss2mf(x, a, b, c, d),                       # gauss2mf(x, mean1, sigma1, mean2, sigma2)
            'gaussmf' : fuzz.gaussmf(x, a, b),                              # gaussmf(x, mean, sigma)
            'gbellmf' : fuzz.gbellmf(x, a, b, c),                           # gbellmf(x, a, b, c)
            'piecemf' : fuzz.piecemf(x, abc),                               # piecemf(x, abc)
            'pimf'    : fuzz.pimf(x, a, b, c, d),                           # pimf(x, a, b, c, d)
            'psigmf'  : fuzz.psigmf(x, a, b, c, d),                         # psigmf(x, b1, c1, b2, c2)
            'sigmf'   : fuzz.sigmf(x, a, b),                                # sigmf(x, b, c)
            'smf'     : fuzz.smf(x, a, b),                                  # smf(x, a, b)
            'trapmf'  : fuzz.trapmf(x, abcd),                               # trapmf(x, abcd)
            'zmf'     : fuzz.zmf(x, a, b),                                  # zmf(x, a, b)
                }[mf]
Exemplo n.º 18
0
def get_terms(individual):
    terms_individual = []
    for attribute in individual:
        terms_num = len(attribute)
        terms = []
        for i in range(terms_num):
            numbers = np.arange(0, attribute[i][1] + 1, 1)
            if 0 < i < terms_num - 1:
                term_numbers = attribute[i][0]
                term_numbers.sort()
                term = fuzz.trapmf(numbers, term_numbers)
            elif i == 0:
                term = fuzz.zmf(numbers, attribute[i][0][0], attribute[i][1])
            else:
                term = fuzz.smf(numbers, attribute[i][0][0], attribute[i][1])
            terms.append(term)
        terms_individual.append(terms)
    return terms_individual
Exemplo n.º 19
0
Arquivo: r.py Projeto: NPSDC/Modeling
def eval_membership_functions(initial_values):
	'''Technically they should have been calcultated using fuzz.someMf but since they are same to save computation we do this'''
	egf_high = fuzz.gaussmf(initial_values[0], 1, 0.1)
	egf_low = fuzz.gaussmf(initial_values[0], 0, 0.1)
	hrg_high = egf_high
	hrg_low = egf_low
	egfr_high = egf_high
	egfr_low =  egf_low
	erk_high = egfr_high  
	erk_low = egfr_low 
	pi3k_high = egfr_high
	pi3k_low = egfr_low
	akt_high = egfr_high  
	akt_low = egfr_low 
	raf_high = egfr_high
	raf_low = egfr_low
	time_high = fuzz.smf(initial_values[7], 0, 1)
	time_low = fuzz.zmf(initial_values[7], 0, 1)
	return ((egf_low, egf_high), (hrg_low, hrg_high), (egfr_low, egfr_high), (raf_low, raf_high), (pi3k_low, pi3k_high), (erk_low, erk_high), \
			(akt_low, akt_high), (time_low, time_high))
Exemplo n.º 20
0
def membership_f(mf, x, abc = [0,0,0], a = 1, b = 2, c = 3, d = 4, abcd = [0,0,0,0]):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
        abc - list containing triangular edge point x-values
    """
    return {
        'trimf'   : fuzz.trimf(x, abc),                                 # trimf(x, abc)
        'dsigmf'  : fuzz.dsigmf(x, a, b, c, d),                         # dsigmf(x, b1, c1, b2, c2)
        'gauss2mf': fuzz.gauss2mf(x, a, b, c, d),                       # gauss2mf(x, mean1, sigma1, mean2, sigma2)
        'gaussmf' : fuzz.gaussmf(x, a, b),                              # gaussmf(x, mean, sigma)
        'gbellmf' : fuzz.gbellmf(x, a, b, c),                           # gbellmf(x, a, b, c)
        'piecemf' : fuzz.piecemf(x, abc),                               # piecemf(x, abc)
        'pimf'    : fuzz.pimf(x, a, b, c, d),                           # pimf(x, a, b, c, d)
        'psigmf'  : fuzz.psigmf(x, a, b, c, d),                         # psigmf(x, b1, c1, b2, c2)
        'sigmf'   : fuzz.sigmf(x, a, b),                                # sigmf(x, b, c)
        'smf'     : fuzz.smf(x, a, b),                                  # smf(x, a, b)
        'trapmf'  : fuzz.trapmf(x, abcd),                               # trapmf(x, abcd)
        'zmf'     : fuzz.zmf(x, a, b),                                  # zmf(x, a, b)
            }[mf]
Exemplo n.º 21
0
def membership_f(mf, x, abc=[0, 0, 0], a=1, b=2, c=3, d=4, abcd=[0, 0, 0, 0]):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
        abc - list containing triangular edge point x-values
    """
    return {
        "trimf": fuzz.trimf(x, abc),  # trimf(x, abc)
        "dsigmf": fuzz.dsigmf(x, a, b, c, d),  # dsigmf(x, b1, c1, b2, c2)
        "gauss2mf": fuzz.gauss2mf(x, a, b, c, d),  # gauss2mf(x, mean1, sigma1, mean2, sigma2)
        "gaussmf": fuzz.gaussmf(x, a, b),  # gaussmf(x, mean, sigma)
        "gbellmf": fuzz.gbellmf(x, a, b, c),  # gbellmf(x, a, b, c)
        "piecemf": fuzz.piecemf(x, abc),  # piecemf(x, abc)
        "pimf": fuzz.pimf(x, a, b, c, d),  # pimf(x, a, b, c, d)
        "psigmf": fuzz.psigmf(x, a, b, c, d),  # psigmf(x, b1, c1, b2, c2)
        "sigmf": fuzz.sigmf(x, a, b),  # sigmf(x, b, c)
        "smf": fuzz.smf(x, a, b),  # smf(x, a, b)
        "trapmf": fuzz.trapmf(x, abcd),  # trapmf(x, abcd)
        "zmf": fuzz.zmf(x, a, b),  # zmf(x, a, b)
    }[mf]
Exemplo n.º 22
0
    def __init__(self, p, n_variavel, tipo='antecedente'):
        # p: probabilidade de evento favorável.
        # n_variavel: nome da variavel.
        # tipo: tipo de variável fuzzy.

        self.min = 0
        self.max = 1

        # Estima a média e o desvio padrão.
        self.media = p
        self.dp = (p * (1 - p))**0.5

        if tipo == 'consequente':
            # O passo foi padronizado em 0.01.
            self.vf = ctrl.Consequent(np.arange(0, 1, 0.01), n_variavel)
        else:
            self.vf = ctrl.Antecedent(np.arange(0, 1, 0.01), n_variavel)

        # Escala Likert padronizada por 3 categorias para uma binomial normalizada.
        self.vf['baixo'] = fuzz.zmf(self.vf.universe, 0, p)
        self.vf['medio'] = fuzz.gaussmf(self.vf.universe, p, self.dp)
        self.vf['alto'] = fuzz.smf(self.vf.universe, p, 1)
Exemplo n.º 23
0
# Trapezoidal membership function
trapmf = fuzz.trapmf(x, [0, 2, 8, 10])

# Sigmoid membership function
center = 5.0
width_control = 2.0
sigmf = fuzz.sigmf(x, center, width_control)

# S-function
foot = 1.0
ceiling = 9.0
smf = fuzz.smf(x, foot, ceiling)

# Z-function
zmf = fuzz.zmf(x, foot, ceiling)

# Pi-function
pimf = fuzz.pimf(x, 0.0, 4.0, 5.0, 10.0)

# Gaussian function
mean = 5.0
sigma = 1.25
gaussmf = fuzz.gaussmf(x, mean, sigma)

# Generalized Bell-Shaped function
width = 2.0
slope = 4.0
center = 5.0
gbellmf = fuzz.gbellmf(x, width, slope, center)
Exemplo n.º 24
0
def calculate_akt_mfs(pi3k, akt):
	pi3k_low = fuzz.zmf(pi3k, 0, 0.95)
	pi3k_high = fuzz.smf(pi3k, 0, 0.9)
	akt_low = fuzz.gaussmf(akt, 0, akt[akt.size -1]/20)
	akt_high = fuzz.gaussmf(akt, akt[akt.size -1], akt[akt.size -1]/20)
	return ((pi3k_low, pi3k_high), (akt_low, akt_high))
Exemplo n.º 25
0
#   * Quality and service on subjective ranges [0, 10]
#   * Tip has a range of [0, 25] in units of percentage points
x_qual = np.arange(0, 11, 1)
x_serv = np.arange(0, 11, 1)
x_tip = np.arange(0, 26, 1)

# Generate fuzzy membership functions
qual_lo = fuzz.gaussmf(x_qual, 3, 0.5)
qual_md = fuzz.gbellmf(x_qual, 1, 1, 5)
qual_hi = fuzz.piecemf(x_qual, [6, 7, 10])
serv_lo = fuzz.pimf(x_serv, 0, 2.9, 3, 8)
serv_md = fuzz.sigmoid(x_serv, 0.5)
serv_hi = fuzz.smf(x_serv, 6, 9)
tip_lo = fuzz.trapmf(x_tip, [0, 0, 3, 6])
tip_md = fuzz.trimf(x_tip, [0, 13, 25])
tip_hi = fuzz.zmf(x_tip, 14, 20)
# Visualize these universes and membership functions
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(8, 9))

ax0.plot(x_qual, qual_lo, 'b', linewidth=1.5, label='Bad')
ax0.plot(x_qual, qual_md, 'g', linewidth=1.5, label='Decent')
ax0.plot(x_qual, qual_hi, 'r', linewidth=1.5, label='Great')
ax0.set_title('Food quality')
ax0.legend()

ax1.plot(x_serv, serv_lo, 'b', linewidth=1.5, label='Poor')
ax1.plot(x_serv, serv_md, 'g', linewidth=1.5, label='Acceptable')
ax1.plot(x_serv, serv_hi, 'r', linewidth=1.5, label='Amazing')
ax1.set_title('Service quality')
ax1.legend()
Exemplo n.º 26
0
import numpy as np
import skfuzzy as fuzz
from matplotlib import pyplot as plt
from scipy import stats
from filters import SavitzkyGolay

# margin of outputs rules determin if a state is a valid state
STATE_DIFF_MARGIN = 0.2

# logic states
alt_range = np.arange(0, 40000, 1)
dh_range = np.arange(-20, 20, 0.1)
spd_range = np.arange(0, 600, 1)
states = np.arange(0, 5, 0.01)

alt_gnd = fuzz.zmf(alt_range, 0, 200)
alt_lo = fuzz.gaussmf(alt_range, 10000, 10000)
alt_hi = fuzz.gaussmf(alt_range, 30000, 10000)

dh_zero = fuzz.gaussmf(dh_range, 0, 5)
dh_plus = fuzz.sigmf(dh_range, 6, 1)
dh_minus = fuzz.sigmf(dh_range, -6, -1)

spd_hi = fuzz.gaussmf(spd_range, 600, 200)
spd_md = fuzz.gaussmf(spd_range, 100, 100)
spd_lo = fuzz.gaussmf(spd_range, 0, 50)

state_ground = fuzz.gaussmf(states, 1, 0.1)
state_climb = fuzz.gaussmf(states, 2, 0.1)
state_descend = fuzz.gaussmf(states, 3, 0.1)
state_cruise = fuzz.gaussmf(states, 4, 0.1)
Exemplo n.º 27
0
"""

# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline
import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt
from skfuzzy import control as ctrl

temperature = ctrl.Antecedent(np.arange(0, 41, 1), 'temperature')
humidity = ctrl.Antecedent(np.arange(0, 100, 1), 'humidity')
light = ctrl.Antecedent(np.arange(0, 1000, 1), 'light')

survivability = ctrl.Consequent(np.arange(0, 90, 1), 'survivability')

temperature['cold'] = fuzz.zmf(temperature.universe, 0, 17)
temperature['warm'] = fuzz.trimf(temperature.universe, [13, 28, 34])
temperature['hot'] = fuzz.trimf(temperature.universe, [30, 40, 41])

humidity['wet'] = fuzz.trimf(humidity.universe, [65, 100, 100])
humidity['moist'] = fuzz.trimf(humidity.universe, [15, 50, 70])
humidity['dry'] = fuzz.zmf(humidity.universe, 0, 20)

light['low'] = fuzz.zmf(light.universe, 0, 300)
light['good'] = fuzz.trimf(light.universe, [250, 650, 900])
light['high'] = fuzz.trimf(light.universe, [800, 1000, 1000])

survivability['very low'] = fuzz.trimf(survivability.universe, [0, 0, 15])
survivability['low'] = fuzz.trimf(survivability.universe, [15, 20, 30])
survivability['pretty'] = fuzz.trimf(survivability.universe, [30, 35, 45])
survivability['good'] = fuzz.trimf(survivability.universe, [45, 55, 75])
Exemplo n.º 28
0
from collections import namedtuple
from numpy import arange
from skfuzzy import control, trapmf, smf, zmf


state_health = control.Antecedent(arange(0, 100, 1), 'state_health')
state_health.automf(number=3, names=['bad', 'good', 'excellent'])

calories = control.Antecedent(arange(0, 5000, 1), 'calories')
universe = calories.universe
calories['little'] = zmf(universe, 1000, 1300)
calories['enough'] = trapmf(universe, [1000, 1100, 1800, 2100])
calories['lot'] = smf(universe, 2000, 2300)

training_experience = control.Antecedent(arange(0, 20, 1), 'training_experience')
universe = training_experience.universe
training_experience['small'] = zmf(universe, 1, 4)
training_experience['medium'] = trapmf(universe, [3, 4, 8, 12])
training_experience['large'] = smf(universe, 10, 15)

decision = control.Consequent(arange(0, 20, 1), 'decision')
decision.automf(number=3, names=['low', 'middle', 'high'])

prereq_one = (
    state_health['bad']
    & (calories['little'] | calories['enough'])
    & (training_experience['small'] | training_experience['medium'])
)
rule_one = control.Rule(prereq_one, decision['low'])

prereq_two = (
Exemplo n.º 29
0
def eval_membership_function_egf(egf_values):
	'''Evaluates membership function for egf '''
	egf_high = fuzz.smf(egf_values, 0, 1)
	egf_low = fuzz.zmf(egf_values, 0, 1)
	return (egf_low, egf_high)
Exemplo n.º 30
0
# Calcular rangos de [HumMin, HumMax] y [HumCrit, HumMin]
hum_min_max = abs(hum_min - hum_max)
hum_min_crit = abs(hum_crit - hum_min)

# Valores del riego
values = np.array([0.0, 0.5, 1.0, 1.5])

# Rangos de valores para cada modelo difuso
x_hum = np.arange(1024)
x_lum = np.arange(1001)
x_tmp = np.arange(100)
x_reg = np.linspace(0.0, 1.5, 16)

# Establecer conjuntos difusos
hum_hi = fuzz.zmf(x_hum, hum_max - hum_min_max / 4, hum_max)
hum_md = fuzz.trapmf(
    x_hum,
    [hum_max - hum_min_max / 4, hum_max, hum_min, hum_min + hum_min_crit / 2])
hum_lo = fuzz.smf(x_hum, hum_min + hum_min_crit / 3, hum_crit)

lum_lo = fuzz.zmf(x_lum, lum_min - 50, lum_min)
lum_md = fuzz.trapmf(x_lum, [lum_min - 50, lum_min, lum_max, lum_max + 50])
lum_hi = fuzz.smf(x_lum, lum_max, lum_max + 50)

tmp_lo = fuzz.zmf(x_tmp, tmp_min - 5, tmp_min)
tmp_md = fuzz.trapmf(x_tmp, [tmp_min - 5, tmp_min, tmp_max, tmp_crit])
tmp_hi = fuzz.smf(x_tmp, tmp_max, tmp_crit)

reg_no = fuzz.trimf(x_reg, [0.0, 0.0, 0.5])
reg_lo = fuzz.trimf(x_reg, [0.0, 0.5, 1.0])
Exemplo n.º 31
0
import numpy as np
import skfuzzy as fuzz
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline

# margin of outputs rules determin if a state is a valid state
STATE_DIFF_MARGIN = 0.2

# logic states
alt_range = np.arange(0, 40000, 1)
roc_range = np.arange(-4000, 4000, 0.1)
spd_range = np.arange(0, 600, 1)
states = np.arange(0, 6, 0.01)

alt_gnd = fuzz.zmf(alt_range, 0, 200)
alt_lo = fuzz.gaussmf(alt_range, 10000, 5000)
alt_hi = fuzz.gaussmf(alt_range, 35000, 20000)

roc_zero = fuzz.gaussmf(roc_range, 0, 100)
roc_plus = fuzz.smf(roc_range, 10, 1000)
roc_minus = fuzz.zmf(roc_range, -1000, -10)

spd_hi = fuzz.gaussmf(spd_range, 600, 100)
spd_md = fuzz.gaussmf(spd_range, 200, 100)
spd_lo = fuzz.gaussmf(spd_range, 0, 50)

state_ground = fuzz.gaussmf(states, 1, 0.1)
state_climb = fuzz.gaussmf(states, 2, 0.1)
state_descent = fuzz.gaussmf(states, 3, 0.1)
state_cruise = fuzz.gaussmf(states, 4, 0.1)
state_level = fuzz.gaussmf(states, 5, 0.1)
import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt
from skfuzzy import control as ctrl

weather = ctrl.Antecedent(np.arange(-30, 60, 0.1), 'weather')
bloodSugar = ctrl.Antecedent(np.arange(30, 1000,0.1), 'bloodSugar')
wool = ctrl.Consequent(np.arange(0, 100, 0.1), 'wool')
cotton = ctrl.Consequent(np.arange(0, 100,0.1), 'cotton')
color = ctrl.Consequent(np.arange(0,255, 0.1), 'color')

weather['cold'] = fuzz.zmf(weather.universe, -30,15)
weather['warm'] = fuzz.gaussmf(weather.universe, 15,25)
weather['hot'] = fuzz.smf(weather.universe, 25, 60)

bloodSugar['hypoglycemia'] = fuzz.zmf(bloodSugar.universe, 0, 70)
bloodSugar['normal'] = fuzz.gaussmf(bloodSugar.universe, 70, 100)
bloodSugar['hyperglycemia'] = fuzz.smf(bloodSugar.universe, 100, 1000)

wool['low'] = fuzz.trimf(wool.universe, [0, 0, 33])
wool['medium'] = fuzz.trimf(wool.universe, [0, 33, 66])
wool['high'] = fuzz.trimf(wool.universe, [33, 66, 100])

cotton['low'] = fuzz.trimf(cotton.universe, [0, 0, 33])
cotton['medium'] = fuzz.trimf(cotton.universe, [0, 33, 66])
cotton['high'] = fuzz.trimf(cotton.universe, [33, 66, 100])

color['black'] = fuzz.trimf(color.universe, [0, 0, 100])
color['greys'] = fuzz.trimf(color.universe, [100,100,200])
color['white'] = fuzz.trimf(color.universe, [150,150,255])
Exemplo n.º 33
0
 def get_fuzzy_membership_map():
     return {
         Free.FREE: lambda x: zmf(x, a=0, b=6),
         Free.NOT_FREE: lambda x: smf(x, a=2, b=10)
     }
Exemplo n.º 34
0
def geo_fuzzy_lingvo_scale(objects, cluster_id):
    percentage = 0
    average_profit = 0
    profit_by_type = {geo_frame.columns[2]: 0, geo_frame.columns[3]: 0, geo_frame.columns[4]: 0}

    for row, series in geo_frame.iterrows():
        if row not in objects:
            continue
        average_profit += int(series[0])
        percentage += int(series[1])
        profit_by_type[geo_frame.columns[2]] += int(series[2])
        profit_by_type[geo_frame.columns[3]] += int(series[3])
        profit_by_type[geo_frame.columns[4]] += int(series[4])

    for key in profit_by_type.keys():
        profit_by_type[key] /= len(objects)

    dominating_type = get_dominating_type(profit_by_type)

    average_profit = round(average_profit / len(objects))
    percentage = round(percentage / len(objects), 2)
    # Generate universe variables
    x_tendency = np.arange(0, 100, 1)

    # Generate fuzzy membership functions
    mfn_insignificant = fuzz.zmf(x_tendency, 0, 5)
    mfn_low = fuzz.trimf(x_tendency, [5, 30, 30])
    mfn_middle = fuzz.trimf(x_tendency, [30, 65, 65])
    mfn_main = fuzz.trimf(x_tendency, [65, 100, 100])

    # Visualize these universes and membership functions
    fig, ax = plt.subplots(nrows=1, figsize=(8, 3))

    ax.plot(x_tendency, mfn_insignificant, "r", linewidth=2.5, label="незначительная")
    ax.plot(x_tendency, mfn_low, "r", linewidth=1, label="малая")
    ax.plot(x_tendency, mfn_middle, "grey", linewidth=1, label="средняя")
    ax.plot(x_tendency, mfn_main, "g", linewidth=1, label="основная")
    ax.set_title("Доля выручки сегмента Big Data")
    ax.legend()

    # Turn off top/right axes
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    plt.tight_layout()
    fig.savefig("output/geo_fuzzy_scale.png")

    # Interpretation
    interp_insignificant = fuzz.interp_membership(x_tendency, mfn_insignificant, percentage)
    interp_low = fuzz.interp_membership(x_tendency, mfn_low, percentage)
    interp_middle = fuzz.interp_membership(x_tendency, mfn_middle, percentage)
    interp_main = fuzz.interp_membership(x_tendency, mfn_main, percentage)

    activation_insignificant = np.fmin(interp_insignificant, mfn_insignificant)
    activation_low = np.fmin(interp_low, mfn_low)
    activation_middle = np.fmin(interp_middle, mfn_middle)
    activation_main = np.fmin(interp_main, mfn_main)

    zeroes = np.zeros_like(x_tendency)

    # Visualize this
    fig, ax0 = plt.subplots(figsize=(8, 3))

    ax0.fill_between(x_tendency, zeroes, activation_insignificant, facecolor="r", alpha=0.7)
    ax0.plot(x_tendency, mfn_insignificant, "r", linewidth=2, linestyle="--", )

    ax0.fill_between(x_tendency, zeroes, activation_low, facecolor="r", alpha=0.7)
    ax0.plot(x_tendency, mfn_low, "r", linewidth=0.5, linestyle="--", )

    ax0.fill_between(x_tendency, zeroes, activation_middle, facecolor="grey", alpha=0.7)
    ax0.plot(x_tendency, mfn_middle, "grey", linewidth=0.5, linestyle="--")

    ax0.fill_between(x_tendency, zeroes, activation_main, facecolor="g", alpha=0.7)
    ax0.plot(x_tendency, mfn_main, "g", linewidth=0.5, linestyle="--")

    ax0.set_title("Cluster: " + str(cluster_id))

    # Turn off top/right axes
    ax0.spines["top"].set_visible(False)
    ax0.spines["right"].set_visible(False)
    ax0.get_xaxis().tick_bottom()
    ax0.get_yaxis().tick_left()

    img = "geo_fuzzy_" + str(cluster_id) + ".png"
    fig.savefig("output/" + img)

    # Aggregate all output membership functions together
    aggregated = np.fmax(activation_middle,
                         np.fmax(activation_main,
                                 np.fmax(activation_low, activation_insignificant)))

    # Calculate defuzzified result
    tendency = fuzz.defuzz(x_tendency, aggregated, 'centroid')
    # tendency_activation = fuzz.interp_membership(x_tendency, aggregated, tendency)  # for plot

    data_for_ui = None, None, None
    if tendency <= 5:
        data_for_ui = "danger", "glyphicon-arrow-down", "Незначительная"
    elif 5 < tendency < 30:
        data_for_ui = "danger", "glyphicon-arrow-down", "Малая"
    elif 30 <= tendency < 65:
        data_for_ui = "default", "glyphicon-minus", "Средняя"
    elif 65 <= tendency < 100:
        data_for_ui = "success", "glyphicon-arrow-up", "Основная"

    return str("%.2f" % tendency), data_for_ui[0], data_for_ui[2], img, average_profit, dominating_type
Exemplo n.º 35
0
def calculate_erk_mfs(raf, erk):
	raf_low = fuzz.zmf(raf, 0, 0.95)
	raf_high = fuzz.smf(erk, 0.1, 0.9)
	erk_low = fuzz.gaussmf(erk, 0, raf[raf.size - 1]/20)
	erk_high = fuzz.gaussmf(erk, raf[raf.size - 1], raf[raf.size - 1]/20)
	return (raf_low, raf_high, erk_low, erk_high)
 def mf_zmf(self, a, t, s):
     t = str(self.transform_class_to_target(t))
     return fz.zmf(self.ant[a].universe, s['min' + t], s['pke' + t])
Exemplo n.º 37
0
def buildFuzzySystem(showDescription=False):
    """ 
    ===========================================================================
    Build Fuzzy Sistem for variable: memory  
    ===========================================================================   
    
    **Args**:
        showDescription: (boolean)
    **Returns**:
        None
    """
    #==========================================================================
    # Set labels of inputs and outputs
    #==========================================================================

    var_in1_label = 'memory'
    var_out_label = 'out'

    logger.info("buildFuzzySystem:" + var_in1_label)

    #==========================================================================
    # Set numerical range of inputs and outputs
    #==========================================================================

    in1_max = 100.0

    var_in1_universe = np.arange(0, in1_max, in1_max / 1000.0)
    var_out_universe = np.arange(0, 1, 0.01)

    #==========================================================================
    # Set inputs(Antecedent) and outputs (Consequent)
    #==========================================================================

    var_in1 = ctrl.Antecedent(var_in1_universe, var_in1_label)
    var_out = ctrl.Consequent(var_out_universe, var_out_label)

    #==========================================================================
    # Set membership functions of fuzzy set
    #==========================================================================

    var_in1.automf(number=3, variable_type='quant')
    var_in1['average'] = fuzz.trapmf(
        var_in1.universe,
        [in1_max * 0.2, in1_max * 0.4, in1_max * 0.8, in1_max * 0.9])
    var_in1['high'] = fuzz.smf(var_in1.universe, in1_max * 0.8, in1_max * 0.95)

    var_out['low'] = fuzz.zmf(var_out.universe, 0.4, 0.8)
    var_out['high'] = fuzz.smf(var_out.universe, 0.7, 0.9)

    #==========================================================================
    # Set fuzzy rules
    #==========================================================================

    rule1 = ctrl.Rule(var_in1['high'], var_out['high'])
    rule2 = ctrl.Rule(var_in1['low'] | var_in1['average'], var_out['low'])

    #==========================================================================
    # Build fuzzy control system and simulation
    #==========================================================================

    var_ctrl = ctrl.ControlSystem([rule1, rule2])
    var_fuzzysim = ctrl.ControlSystemSimulation(var_ctrl)

    #==========================================================================
    # Set fuzzy rules
    #==========================================================================

    if showDescription:
        fig = plt.figure(figsize=(12, 12))
        plt.subplot(3, 1, 1)
        plt.title('Input: ' + var_in1_label)
        plt.plot(var_in1_universe, var_in1['low'].mf, label='low')
        plt.plot(var_in1_universe, var_in1['average'].mf, label='average')
        plt.plot(var_in1_universe, var_in1['high'].mf, label='high')
        plt.legend()

        plt.subplot(3, 1, 2)
        plt.title('Output: ' + var_out_label)
        plt.plot(var_out_universe, var_out['low'].mf, label='low')
        plt.plot(var_out_universe, var_out['high'].mf, label='high')
        plt.legend()

        var_fuzzysim.input[var_in1_label] = var_in1_universe
        var_fuzzysim.compute()
        y = var_fuzzysim.output[var_out_label]
        plt.subplot(3, 1, 3)
        plt.plot(var_in1_universe,
                 y,
                 label='Fuzzy transform of ' + var_in1_label)

        #plt.show()
        plt.savefig('/tmp/fuzzy_' + var_in1_label + '.png')

    return var_fuzzysim
Exemplo n.º 38
0
        ax[i].plot([defuzzValue[i], defuzzValue[i]], [0, activation],
                   'k',
                   linewidth=1.5,
                   alpha=0.9)
        ax[i].set_title(title[i])
    SetAxes(ax)


#--------------------初始化系统------------------------------------
#设置输入与输出变量的论域
amplitude_universe = np.linspace(-1, 1, num=100)
etLoss_universe = np.linspace(0, 0.5, num=100)
etProfit_universe = np.linspace(0, 1, num=100)

# 创建三个模糊隶属函数:一个价格波动幅度(amplitude)输入, 两个输出
amplitude_N_High = fuzz.zmf(amplitude_universe, -0.7, -0.3)  #波动幅度为负大
amplitude_N_Medin = fuzz.gaussmf(amplitude_universe, -0.2, 0.1)  #波动幅度为负中
amplitude_N_Low = fuzz.gaussmf(amplitude_universe, -0.05, -0.1)  #波动幅度为负小
amplitude_P_Low = fuzz.gaussmf(amplitude_universe, 0.05, 0.1)  #波动幅度为正小
amplitude_P_Medin = fuzz.gaussmf(amplitude_universe, 0.1, 0.2)  #波动幅度为正中
amplitude_P_High = fuzz.smf(amplitude_universe, 0.3, 0.7)  #波动幅度为正大
#设置预期损失隶属函数
etLoss_Low = fuzz.gaussmf(etLoss_universe, 0, 0.1)
etLoss_Medin = fuzz.gaussmf(etLoss_universe, 0.2, 0.1)
etLoss_High = fuzz.smf(etLoss_universe, 0.2, 0.4)
#设置预期盈利隶属函数
etProfit_Low = fuzz.gaussmf(etProfit_universe, 0, 0.1)
etProfit_Medin = fuzz.gaussmf(etProfit_universe, 0.2, 0.1)
etProfit_High = fuzz.smf(etProfit_universe, 0.2, 0.4)

#--------------------模糊计算系统------------------------------------
Exemplo n.º 39
0
def eval_membership_function_hrg(hrg_values):
	'''Evaluates membership function for hrg '''
	hrg_high = fuzz.smf(hrg_values, 0 , 1)
	hrg_low = fuzz.zmf(hrg_values, 0, 1)
	return (hrg_low, hrg_high)
Exemplo n.º 40
0
    def createFuzzy(self):
        self.fuzz_pend1 = ctrl.Antecedent(np.arange(-1.5, 1.6, 0.1), 'join1')
        self.fuzz_pend1_v = ctrl.Antecedent(np.arange(-10, 10, 0.1), 'pend1_v')
        self.fuzz_motor = ctrl.Consequent(np.arange(-150, 150, 1), 'motor')

        self.fuzz_position = ctrl.Antecedent(np.arange(-13, 13, 0.1),
                                             'position')
        self.fuzz_vv2 = ctrl.Antecedent(np.arange(-10, 10, 0.1), 'v')
        self.fuzz_motor2 = ctrl.Consequent(np.arange(-100, 100, 1), 'motor2')

        self.fuzz_pend1['poor'] = fuzz.zmf(self.fuzz_pend1.universe, -0.2,
                                           -0.1)
        self.fuzz_pend1['mediocre'] = fuzz.trimf(self.fuzz_pend1.universe,
                                                 [-0.2, -0.1, 0])
        self.fuzz_pend1['average'] = fuzz.trimf(self.fuzz_pend1.universe,
                                                [-0.1, 0, 0.1])
        self.fuzz_pend1['decent'] = fuzz.trimf(self.fuzz_pend1.universe,
                                               [0, 0.1, 0.2])
        self.fuzz_pend1['good'] = fuzz.smf(self.fuzz_pend1.universe, 0.1, 0.2)

        self.fuzz_pend1_v['poor'] = fuzz.zmf(self.fuzz_pend1_v.universe, -2,
                                             -1)
        self.fuzz_pend1_v['mediocre'] = fuzz.trimf(self.fuzz_pend1_v.universe,
                                                   [-2, -1, 0])
        self.fuzz_pend1_v['average'] = fuzz.trimf(self.fuzz_pend1_v.universe,
                                                  [-1, 0, 1])
        self.fuzz_pend1_v['decent'] = fuzz.trimf(self.fuzz_pend1_v.universe,
                                                 [0, 1, 2])
        self.fuzz_pend1_v['good'] = fuzz.smf(self.fuzz_pend1_v.universe, 1, 2)

        self.fuzz_motor['poor'] = fuzz.zmf(self.fuzz_motor.universe, -50, -20)
        self.fuzz_motor['average'] = fuzz.trimf(self.fuzz_motor.universe,
                                                [-50, 0, 50])
        self.fuzz_motor['good'] = fuzz.smf(self.fuzz_motor.universe, 20, 50)

        self.fuzz_position['poor'] = fuzz.zmf(self.fuzz_position.universe, -5,
                                              -2)
        self.fuzz_position['average'] = fuzz.trimf(self.fuzz_position.universe,
                                                   [-5, 0, 5])
        self.fuzz_position['good'] = fuzz.smf(self.fuzz_position.universe, 2,
                                              5)

        self.fuzz_motor2['poor'] = fuzz.zmf(self.fuzz_motor2.universe, -50,
                                            -20)
        self.fuzz_motor2['average'] = fuzz.trimf(self.fuzz_motor2.universe,
                                                 [-50, 0, 50])
        self.fuzz_motor2['good'] = fuzz.smf(self.fuzz_motor2.universe, 20, 50)

        self.fuzz_vv2['poor'] = fuzz.zmf(self.fuzz_vv2.universe, -5, -2.5)
        self.fuzz_vv2['average'] = fuzz.trimf(self.fuzz_vv2.universe,
                                              [-5, 0, 5])
        self.fuzz_vv2['good'] = fuzz.smf(self.fuzz_vv2.universe, 2.5, 5)

        # self.fuzz_pend1['average'].view()
        # self.fuzz_pend1_v['average'].view()
        # self.fuzz_motor['average'].view()
        # self.fuzz_position['average'].view()
        # self.fuzz_vv2['average'].view()
        # self.fuzz_motor2['average'].view()

        self.rule1 = ctrl.Rule(
            self.fuzz_pend1['poor'] & self.fuzz_pend1_v['poor'],
            self.fuzz_motor['poor'])
        self.rule2 = ctrl.Rule(
            self.fuzz_pend1['poor'] & self.fuzz_pend1_v['mediocre'],
            self.fuzz_motor['poor'])
        self.rule3 = ctrl.Rule(
            self.fuzz_pend1['poor'] & self.fuzz_pend1_v['average'],
            self.fuzz_motor['poor'])
        self.rule4 = ctrl.Rule(
            self.fuzz_pend1['poor'] & self.fuzz_pend1_v['decent'],
            self.fuzz_motor['poor'])
        self.rule5 = ctrl.Rule(
            self.fuzz_pend1['poor'] & self.fuzz_pend1_v['good'],
            self.fuzz_motor['poor'])

        self.rule6 = ctrl.Rule(
            self.fuzz_pend1['mediocre'] & self.fuzz_pend1_v['poor'],
            self.fuzz_motor['poor'])
        self.rule7 = ctrl.Rule(
            self.fuzz_pend1['mediocre'] & self.fuzz_pend1_v['mediocre'],
            self.fuzz_motor['poor'])
        self.rule8 = ctrl.Rule(
            self.fuzz_pend1['mediocre'] & self.fuzz_pend1_v['average'],
            self.fuzz_motor['poor'])
        self.rule9 = ctrl.Rule(
            self.fuzz_pend1['mediocre'] & self.fuzz_pend1_v['decent'],
            self.fuzz_motor['average'])
        self.rule10 = ctrl.Rule(
            self.fuzz_pend1['mediocre'] & self.fuzz_pend1_v['good'],
            self.fuzz_motor['average'])

        self.rule11 = ctrl.Rule(
            self.fuzz_pend1['average'] & self.fuzz_pend1_v['poor'],
            self.fuzz_motor['poor'])
        self.rule12 = ctrl.Rule(
            self.fuzz_pend1['average'] & self.fuzz_pend1_v['mediocre'],
            self.fuzz_motor['poor'])
        self.rule13 = ctrl.Rule(
            self.fuzz_pend1['average'] & self.fuzz_pend1_v['average'],
            self.fuzz_motor['average'])
        self.rule14 = ctrl.Rule(
            self.fuzz_pend1['average'] & self.fuzz_pend1_v['decent'],
            self.fuzz_motor['good'])
        self.rule15 = ctrl.Rule(
            self.fuzz_pend1['average'] & self.fuzz_pend1_v['good'],
            self.fuzz_motor['good'])

        self.rule16 = ctrl.Rule(
            self.fuzz_pend1['decent'] & self.fuzz_pend1_v['poor'],
            self.fuzz_motor['average'])
        self.rule17 = ctrl.Rule(
            self.fuzz_pend1['decent'] & self.fuzz_pend1_v['mediocre'],
            self.fuzz_motor['average'])
        self.rule18 = ctrl.Rule(
            self.fuzz_pend1['decent'] & self.fuzz_pend1_v['average'],
            self.fuzz_motor['good'])
        self.rule19 = ctrl.Rule(
            self.fuzz_pend1['decent'] & self.fuzz_pend1_v['decent'],
            self.fuzz_motor['good'])
        self.rule20 = ctrl.Rule(
            self.fuzz_pend1['decent'] & self.fuzz_pend1_v['good'],
            self.fuzz_motor['good'])

        self.rule21 = ctrl.Rule(
            self.fuzz_pend1['good'] & self.fuzz_pend1_v['poor'],
            self.fuzz_motor['good'])
        self.rule22 = ctrl.Rule(
            self.fuzz_pend1['good'] & self.fuzz_pend1_v['mediocre'],
            self.fuzz_motor['good'])
        self.rule23 = ctrl.Rule(
            self.fuzz_pend1['good'] & self.fuzz_pend1_v['average'],
            self.fuzz_motor['good'])
        self.rule24 = ctrl.Rule(
            self.fuzz_pend1['good'] & self.fuzz_pend1_v['decent'],
            self.fuzz_motor['good'])
        self.rule25 = ctrl.Rule(
            self.fuzz_pend1['good'] & self.fuzz_pend1_v['good'],
            self.fuzz_motor['good'])

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

        self.rule110 = ctrl.Rule(
            self.fuzz_vv2['poor'] & self.fuzz_position['poor'],
            self.fuzz_motor2['good'])
        self.rule111 = ctrl.Rule(
            self.fuzz_vv2['poor'] & self.fuzz_position['average'],
            self.fuzz_motor2['good'])
        self.rule112 = ctrl.Rule(
            self.fuzz_vv2['poor'] & self.fuzz_position['good'],
            self.fuzz_motor2['average'])
        self.rule113 = ctrl.Rule(
            self.fuzz_vv2['average'] & self.fuzz_position['poor'],
            self.fuzz_motor2['good'])
        self.rule114 = ctrl.Rule(
            self.fuzz_vv2['average'] & self.fuzz_position['average'],
            self.fuzz_motor2['average'])
        self.rule115 = ctrl.Rule(
            self.fuzz_vv2['average'] & self.fuzz_position['good'],
            self.fuzz_motor2['poor'])
        self.rule116 = ctrl.Rule(
            self.fuzz_vv2['good'] & self.fuzz_position['poor'],
            self.fuzz_motor2['average'])
        self.rule117 = ctrl.Rule(
            self.fuzz_vv2['good'] & self.fuzz_position['average'],
            self.fuzz_motor2['poor'])
        self.rule118 = ctrl.Rule(
            self.fuzz_vv2['good'] & self.fuzz_position['good'],
            self.fuzz_motor2['poor'])

        self.pendulum_ctrl2 = ctrl.ControlSystem([
            self.rule110, self.rule111, self.rule112, self.rule113,
            self.rule114, self.rule115, self.rule116, self.rule117,
            self.rule118
        ])

        self.pendulum_fuzz2 = ctrl.ControlSystemSimulation(self.pendulum_ctrl2)
Exemplo n.º 41
0
def eval_membership_function_time(time_values):
	'''Evaluates membership function for time '''
	time_high = fuzz.smf(time_values, 0, 1)
	time_low = fuzz.zmf(time_values, 0, 1)
	return (time_low, time_high)
Exemplo n.º 42
0
    tabX1.append(float(i))
for i in file['x2']:
    tabX2.append(float(i))
for i in file['x3']:
    tabX3.append(float(i))
for i in file['y']:
    tabY.append(float(i))

# Declare input/output
x1 = ctrl.Antecedent(np.arange(min(tabX1), max(tabX1), 0.001), 'x1')
x2 = ctrl.Antecedent(np.arange(min(tabX2), max(tabX2), 0.001), 'x2')
x3 = ctrl.Antecedent(np.arange(min(tabX3), max(tabX3), 0.001), 'x3')
y = ctrl.Consequent(np.arange(min(tabY), max(tabY), 0.001), 'y')

# Make membership functions
x1['lo'] = fuzz.zmf(x1.universe, min(tabX1), float((max(tabX1) + min(tabX1)) / 2))
x1['md'] = fuzz.gaussmf(x1.universe, float((max(tabX1) + min(tabX1)) / 2), 0.05)
x1['hi'] = fuzz.smf(x1.universe, float((max(tabX1) + min(tabX1)) / 2), max(tabX1))

x2['lo'] = fuzz.zmf(x2.universe, min(tabX2), float((max(tabX2) + min(tabX2)) / 2))
x2['md'] = fuzz.gaussmf(x2.universe, float((max(tabX2) + min(tabX2)) / 2), 0.05)
x2['hi'] = fuzz.smf(x2.universe, float((max(tabX2) + min(tabX2)) / 2), max(tabX2))

x3['lo'] = fuzz.zmf(x3.universe, min(tabX3), float((max(tabX3) + min(tabX3)) / 2))
x3['md'] = fuzz.gaussmf(x3.universe, float((max(tabX3) + min(tabX3)) / 2), 0.05)
x3['hi'] = fuzz.smf(x3.universe, float((max(tabX3) + min(tabX3)) / 2), max(tabX3))

y['lo'] = fuzz.zmf(y.universe, min(tabY), float((max(tabY) + min(tabY)) / 2))
y['md'] = fuzz.gaussmf(y.universe, float((max(tabY) + min(tabY)) / 2), 0.05)
y['hi'] = fuzz.smf(y.universe, float((max(tabY) + min(tabY)) / 2), max(tabY))
Exemplo n.º 43
0
import numpy as np
import skfuzzy as fuzz
from matplotlib import pyplot as plt
from scipy import stats
from napy.filters import Spline

# margin of outputs rules determin if a state is a valid state
STATE_DIFF_MARGIN = 0.2

# logic states
alt_range = np.arange(0, 40000, 1)
roc_range = np.arange(-4000, 4000, 0.1)
spd_range = np.arange(0, 600, 1)
states = np.arange(0, 6, 0.01)

alt_gnd = fuzz.zmf(alt_range, 0, 200)
alt_lo = fuzz.gaussmf(alt_range, 10000, 5000)
alt_hi = fuzz.gaussmf(alt_range, 35000, 20000)

roc_zero = fuzz.gaussmf(roc_range, 0, 100)
roc_plus = fuzz.smf(roc_range, 10, 1000)
roc_minus = fuzz.zmf(roc_range, -1000, -10)

spd_hi = fuzz.gaussmf(spd_range, 600, 100)
spd_md = fuzz.gaussmf(spd_range, 200, 100)
spd_lo = fuzz.gaussmf(spd_range, 0, 50)

state_ground = fuzz.gaussmf(states, 1, 0.1)
state_climb = fuzz.gaussmf(states, 2, 0.1)
state_descent = fuzz.gaussmf(states, 3, 0.1)
state_cruise = fuzz.gaussmf(states, 4, 0.1)
Exemplo n.º 44
0
def FuzzyController(autonomy, MSD, time):
    # Generate universe variables
    #   * Quality and service on subjective ranges [0, 10]
    #   * Tip has a range of [0, 25] in units of percentage points
    x_MSD = np.arange(0, 400, 1)
    x_autonomy = np.arange(0, 400, 1)
    x_time = np.arange(0, 1000, 1)
    x_method = np.arange(0, 1, 0.01)

    # Generate fuzzy membership functions
    MSD_lo = fuzz.zmf(x_MSD, 0, 200)
    MSD_md = fuzz.pimf(x_MSD, 100, 150, 250, 300)
    MSD_hi = fuzz.smf(x_MSD, 200, 400)
    autonomy_lo = fuzz.zmf(x_autonomy, 0, 200)
    autonomy_md = fuzz.pimf(x_autonomy, 100, 150, 250, 300)
    autonomy_hi = fuzz.smf(x_autonomy, 200, 400)
    time_lo = fuzz.zmf(x_time, 0, 500)
    time_md = fuzz.pimf(x_time, 250, 400, 600, 750)
    time_hi = fuzz.smf(x_time, 500, 1000)
    method_lo = fuzz.zmf(x_method, 0, 0.5)
    method_md = fuzz.pimf(x_method, 0.25, 0.4, 0.6, 0.75)
    method_hi = fuzz.smf(x_method, 0.5, 1)

    # We need the activation of our fuzzy membership functions at these values.
    # The exact values 6.5 and 9.8 do not exist on our universes...
    # This is what fuzz.interp_membership exists for!
    autonomy = 100
    MSD = 50
    time = 800

    MSD_level_lo = fuzz.interp_membership(x_MSD, MSD_lo, MSD)
    MSD_level_md = fuzz.interp_membership(x_MSD, MSD_md, MSD)
    MSD_level_hi = fuzz.interp_membership(x_MSD, MSD_hi, MSD)

    autonomy_level_lo = fuzz.interp_membership(x_autonomy, autonomy_lo, autonomy)
    autonomy_level_md = fuzz.interp_membership(x_autonomy, autonomy_md, autonomy)
    autonomy_level_hi = fuzz.interp_membership(x_autonomy, autonomy_hi, autonomy)

    time_level_lo = fuzz.interp_membership(x_time, time_lo, time)
    time_level_md = fuzz.interp_membership(x_time, time_md, time)
    time_level_hi = fuzz.interp_membership(x_time, time_hi, time)

    # Rules
    active_rule11 = np.fmin(MSD_level_lo, autonomy_level_lo)
    active_rule12 = np.fmax(np.fmin(time_level_lo, autonomy_level_lo), active_rule11)
    method_activation_lo = np.fmin(active_rule12, method_lo)

    active_rule21 = np.fmin(MSD_level_md, autonomy_level_md)
    active_rule22 = np.fmax(np.fmin(time_level_md, autonomy_level_md), active_rule21)
    method_activation_md = np.fmin(active_rule22, method_md)

    active_rule31 = np.fmin(MSD_level_hi, autonomy_level_hi)
    active_rule32 = np.fmax(np.fmin(time_level_hi, autonomy_level_hi), active_rule31)
    method_activation_hi = np.fmin(active_rule32, method_hi)

    method0 = np.zeros_like(x_method)

    # Aggregate all three output membership functions together
    aggregated = np.fmax(method_activation_lo,
                         np.fmax(method_activation_md, method_activation_hi))

    # Calculate defuzzified result
    method = fuzz.defuzz(x_method, aggregated, 'centroid')
    method_activation = fuzz.interp_membership(x_method, aggregated, method)  # for plot

    method1 = np.arange(method, method + 1, 1)
    method_lo1 = fuzz.zmf(method1, 0, 0.5)
    method_md1 = fuzz.pimf(method1, 0.25, 0.4, 0.6, 0.75)
    method_hi1 = fuzz.smf(method1, 0.5, 1)

    stats = {"pot-fields": method_lo1[0], "bio": method_md1[0], "rules": method_hi1[0]}
    method = max(stats.items(), key=operator.itemgetter(1))[0]
    return method
Exemplo n.º 45
0
def fuzzy_lingvo_scale(objects, cluster_id):
    mean_growth_times = 0

    is_first_iteration = True
    for column, series in data_frame.iteritems():
        if column not in objects:
            continue

        series = series.drop("Пространство")
        start_value = int(series[0])
        end_value = int(series[-1])

        growth_times = end_value if start_value == 0 else float(end_value / start_value)
        mean_growth_times = growth_times if is_first_iteration else (mean_growth_times + growth_times) / 2
        is_first_iteration = False

    # Generate universe variables
    x_tendency = np.arange(0, 40, 1)

    # Generate fuzzy membership functions
    mfn_high_fall = fuzz.zmf(x_tendency, 0, 0.5)
    mfn_fall = fuzz.trimf(x_tendency, [0.5, 1, 1])
    mfn_flat = fuzz.trimf(x_tendency, [1, 2, 2])
    mfn_growth = fuzz.trimf(x_tendency, [2, 10, 10])
    mfn_high_growth = fuzz.trimf(x_tendency, [10, 40, 40])

    # Visualize these universes and membership functions
    fig, ax = plt.subplots(nrows=1, figsize=(8, 3))

    ax.plot(x_tendency, mfn_high_fall, "r", linewidth=2.5, label="High fall")
    ax.plot(x_tendency, mfn_fall, "r", linewidth=1, label="Fall")
    ax.plot(x_tendency, mfn_flat, "grey", linewidth=1, label="Flat")
    ax.plot(x_tendency, mfn_growth, "g", linewidth=1, label="Growth")
    ax.plot(x_tendency, mfn_high_growth, "g", linewidth=2.5, label="High growth")
    ax.set_title("Fuzzy scale of trend")
    ax.legend()

    # Turn off top/right axes
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    plt.tight_layout()
    fig.savefig("output/fuzzy_scale.png")

    # Interpretation
    interp_high_fall = fuzz.interp_membership(x_tendency, mfn_high_fall, mean_growth_times)
    interp_fall = fuzz.interp_membership(x_tendency, mfn_fall, mean_growth_times)
    interp_flat = fuzz.interp_membership(x_tendency, mfn_flat, mean_growth_times)
    interp_growth = fuzz.interp_membership(x_tendency, mfn_growth, mean_growth_times)
    interp_high_growth = fuzz.interp_membership(x_tendency, mfn_high_growth, mean_growth_times)

    activation_high_fall = np.fmin(interp_high_fall, mfn_high_fall)
    activation_fall = np.fmin(interp_fall, mfn_fall)
    activation_flat = np.fmin(interp_flat, mfn_flat)
    activation_growth = np.fmin(interp_growth, mfn_growth)
    activation_high_growth = np.fmin(interp_high_growth, mfn_high_growth)

    zeroes = np.zeros_like(x_tendency)

    # Visualize this
    fig, ax0 = plt.subplots(figsize=(8, 3))

    ax0.fill_between(x_tendency, zeroes, activation_high_fall, facecolor="r", alpha=0.7)
    ax0.plot(x_tendency, mfn_high_fall, "r", linewidth=2, linestyle="--", )

    ax0.fill_between(x_tendency, zeroes, activation_fall, facecolor="r", alpha=0.7)
    ax0.plot(x_tendency, mfn_fall, "r", linewidth=0.5, linestyle="--", )

    ax0.fill_between(x_tendency, zeroes, activation_flat, facecolor="grey", alpha=0.7)
    ax0.plot(x_tendency, mfn_flat, "grey", linewidth=0.5, linestyle="--")

    ax0.fill_between(x_tendency, zeroes, activation_growth, facecolor="g", alpha=0.7)
    ax0.plot(x_tendency, mfn_growth, "g", linewidth=0.5, linestyle="--")

    ax0.fill_between(x_tendency, zeroes, activation_high_growth, facecolor="g", alpha=0.7)
    ax0.plot(x_tendency, mfn_high_growth, "g", linewidth=2, linestyle="--")

    ax0.set_title("Cluster: " + str(cluster_id) + " | Objects: " + str(objects))

    # Turn off top/right axes
    ax0.spines["top"].set_visible(False)
    ax0.spines["right"].set_visible(False)
    ax0.get_xaxis().tick_bottom()
    ax0.get_yaxis().tick_left()

    plt.tight_layout()
    img = "fuzzy_" + str(cluster_id) + ".png"
    fig.savefig("output/" + img)

    # Aggregate all output membership functions together
    aggregated = np.fmax(activation_flat,
                         np.fmax(activation_growth,
                                 np.fmax(activation_fall,
                                         np.fmax(activation_high_growth, activation_high_fall))))

    # Calculate defuzzified result
    tendency = fuzz.defuzz(x_tendency, aggregated, 'centroid')
    # tendency_activation = fuzz.interp_membership(x_tendency, aggregated, tendency)  # for plot

    data_for_ui = None, None, None
    if tendency <= 0.5:
        data_for_ui = "danger", "glyphicon-arrow-down", "High fall"
    elif 0 < tendency < 1:
        data_for_ui = "danger", "glyphicon-arrow-down", "Fall"
    elif 1 <= tendency < 2:
        data_for_ui = "default", "glyphicon-minus", "Flat"
    elif 2 <= tendency < 10:
        data_for_ui = "success", "glyphicon-arrow-up", "Growth"
    elif 10 <= tendency <= 40:
        data_for_ui = "success", "glyphicon-arrow-up", "High growth"

    return str("%.2f" % tendency), data_for_ui[0], data_for_ui[1], data_for_ui[2], img
import numpy as np
import skfuzzy as fuzz
from matplotlib import pyplot as plt

# Problem: from service quality and food quality to tip amount
x_service = np.arange(0, 10.01, 0.5)
x_food = np.arange(0, 10.01, 0.5)
x_tip = np.arange(0, 25.01, 1.0)

# Membership functions
service_low = fuzz.trimf(x_service, [0, 0, 5])
service_middle = fuzz.trimf(x_service, [0, 5, 10])
service_high = fuzz.trimf(x_service, [5, 10, 10])

food_low = fuzz.zmf(x_food, 0, 5)
food_middle = fuzz.pimf(x_food, 0, 4, 5, 10)
food_high = fuzz.smf(x_food, 5, 10)

tip_low = fuzz.trimf(x_tip, [0, 0, 13])
tip_middle = fuzz.trimf(x_tip, [0, 13, 25])
tip_high = fuzz.trimf(x_tip, [13, 25, 25])

# Input: service score and food score
service_score = 9.5
food_score = 4.0

service_low_degree = fuzz.interp_membership(x_service, service_low,
                                            service_score)
service_middle_degree = fuzz.interp_membership(x_service, service_middle,
                                               service_score)
service_high_degree = fuzz.interp_membership(x_service, service_high,