Esempio n. 1
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt

value_PWM_x_serv = ctrl.Consequent(np.arange(-100, 101, 1), 'value_PWM_x_serv')
# value_PWM_y_serv = ctrl.Consequent(np.arange(-100, 101, 1), 'value_PWM_y_serv')

x_error = ctrl.Antecedent(np.arange(-200, 201, 1), 'x_error')
# y_error = ctrl.Antecedent(np.arange(-200, 201, 1), 'y_error')

value_PWM_x_serv['low'] = fuzz.trapmf(value_PWM_x_serv.universe,
                                      [-100, -100, -20, 0])
value_PWM_x_serv['medium'] = fuzz.trimf(value_PWM_x_serv.universe,
                                        [-20, 0, 20])
value_PWM_x_serv['high'] = fuzz.trapmf(value_PWM_x_serv.universe,
                                       [0, 20, 100, 100])
# value_PWM_x_serv.view()

# value_PWM_y_serv['low'] = fuzz.trapmf(value_PWM_y_serv.universe, [-100,-100, -20, 0])
# value_PWM_y_serv['medium'] = fuzz.trimf(value_PWM_y_serv.universe, [-20, 0, 20])
# value_PWM_y_serv['high'] = fuzz.trapmf(value_PWM_y_serv.universe, [0, 20 ,100 ,100])
# value_PWM_y_serv.view()

x_error['poor'] = fuzz.trapmf(x_error.universe, [-200, -200, -150, 0])
x_error['average'] = fuzz.trimf(x_error.universe, [-150, 0, 150])
x_error['good'] = fuzz.trapmf(x_error.universe, [0, 150, 200, 200])
# x_error.view()

# y_error['poor'] = fuzz.trapmf(y_error.universe, [-200,-200,-150, 0])
# y_error['average'] = fuzz.trimf(y_error.universe, [-150, 0, 150])
Esempio n. 2
0
# Fuzzy Control System - Tipping Problem

import numpy as np
import matplotlib.pyplot as plt
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Antecedent = input
# Consequent = output
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')

# Auto-membership function population
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])

# You can see how these look with .view()
quality['average'].view()
plt.show()

service.view()
plt.show()

tip.view()
plt.show()
Esempio n. 3
0
MA['high'] = fuzz.trapmf(MA.universe, [40, 60, 400, 400])

# Set up MACD as an antecedent
MACD = ctrl.Antecedent(np.arange(-200, 201, 1), 'MACD')
MACD['low'] = fuzz.trapmf(MACD.universe, [-200, -200, -15, -8])
MACD['med'] = fuzz.trapmf(MACD.universe, [-15, -8, 8, 15])
MACD['high'] = fuzz.trapmf(MACD.universe, [8, 15, 200, 200])

# Set up RSI as an antecedent
RSI = ctrl.Antecedent(np.arange(0, 101, 1), 'RSI')
RSI['low'] = fuzz.trapmf(RSI.universe, [0, 0, 30, 40])
RSI['med'] = fuzz.trapmf(RSI.universe, [30, 40, 60, 70])
RSI['high'] = fuzz.trapmf(RSI.universe, [60, 70, 100, 100])

# Set up Trading Volume as a consequent
volume = ctrl.Consequent(np.arange(-10, 11, 1), 'volume')
volume['sell'] = fuzz.trapmf(volume.universe, [-10, -10, -6, -5])
volume['hold'] = fuzz.trapmf(volume.universe, [-6, -5, 5, 6])
volume['buy'] = fuzz.trapmf(volume.universe, [5, 6, 10, 10])

#____________________________________________________________________

# Set up the Buy/Sell/Hold rules
rule01 = ctrl.Rule(MA['low'] & MACD['low'] & RSI['low'], volume['sell'])
rule02 = ctrl.Rule(MA['low'] & MACD['low'] & RSI['med'], volume['sell'])
rule03 = ctrl.Rule(MA['low'] & MACD['low'] & RSI['high'], volume['sell'])
rule04 = ctrl.Rule(MA['low'] & MACD['med'] & RSI['low'], volume['hold'])
rule05 = ctrl.Rule(MA['low'] & MACD['med'] & RSI['med'], volume['sell'])
rule06 = ctrl.Rule(MA['low'] & MACD['med'] & RSI['high'], volume['sell'])
rule07 = ctrl.Rule(MA['low'] & MACD['high'] & RSI['low'], volume['buy'])
rule08 = ctrl.Rule(MA['low'] & MACD['high'] & RSI['med'], volume['hold'])
Esempio n. 4
0
from skfuzzy import control as ctrl


def sqrt(num):
    return num**0.5


def square(num):
    return num**2


# Generate semesta dari fuzzy set sebagai numpy array
suhu = ctrl.Antecedent(np.arange(15, 36, 1), 'suhu')
lembab = ctrl.Antecedent(np.arange(0, 101, 1), 'lembab')
orang = ctrl.Antecedent(np.arange(0, 31, 1), 'orang')
thermostat = ctrl.Consequent(np.arange(15, 36, 1), 'thermostat')

#Generate nilai-nilai membership function dengan trimf untuk membuat triangular membership function
suhu['rendah'] = fuzz.trimf(suhu.universe, [15, 15, 25])
suhu['sedang'] = fuzz.trimf(suhu.universe, [23, 25, 29])
suhu['tinggi'] = fuzz.trimf(suhu.universe, [27, 35, 36])
lembab['rendah'] = fuzz.trimf(lembab.universe, [0, 0, 41])
lembab['sedang'] = fuzz.trimf(lembab.universe, [35, 55, 76])
lembab['tinggi'] = fuzz.trimf(lembab.universe, [70, 100, 101])
orang['sedikit'] = fuzz.trimf(orang.universe, [0, 0, 21])
orang['banyak'] = fuzz.trimf(orang.universe, [10, 30, 31])
thermostat['agak rendah'] = np.array(
    list(map(sqrt, fuzz.trimf(suhu.universe, [15, 15, 25]))))
thermostat['rendah'] = fuzz.trimf(suhu.universe, [15, 15, 25])
thermostat['sangat rendah'] = np.array(
    list(map(square, fuzz.trimf(suhu.universe, [15, 15, 25]))))
Esempio n. 5
0
    def fuzzy_factor(self, bufferT, diffBufferT):
        T = self.T
        d = self.d  #DeltaTime

        # Cria as variáveis do problema
        bufferTime = ctrl.Antecedent(np.arange(0, 4 * T, 0.01), 'bufferTime')
        diffBufferTime = ctrl.Antecedent(
            np.arange((-2) * d, (4 * d) + 10, 0.005), 'diffBufferTime')
        bitratefactor = ctrl.Consequent(np.arange(0, 2.5, 0.01),
                                        'bitratefactor')

        # Cria automaticamente o mapeamento entre valores nítidos e difusos
        # usando uma função de pertinência padrão (triângulo)
        bufferTime['short'] = fuzz.trapmf(bufferTime.universe,
                                          [0, 0, (2 * T) / 3, T])
        bufferTime['close'] = fuzz.trimf(bufferTime.universe,
                                         [(2 * T) / 3, T, 4 * T])
        bufferTime['long'] = fuzz.trapmf(bufferTime.universe,
                                         [T, 4 * T, 10 * T, 10 * T])

        # Cria as funções de pertinência usando tipos variados
        diffBufferTime['falling'] = fuzz.trapmf(
            diffBufferTime.universe, [-120, -120, ((-2) * d) / 3, 0])
        diffBufferTime['steady'] = fuzz.trimf(diffBufferTime.universe,
                                              [((-2) * d) / 3, 0, 4 * d])
        diffBufferTime['rising'] = fuzz.trapmf(diffBufferTime.universe,
                                               [0, 4 * d, 10 * d, 10 * d])

        N2 = 0.25
        N1 = 0.5
        Z = 1
        P1 = 1.5
        P2 = 2

        bitratefactor['reduce'] = fuzz.trapmf(bitratefactor.universe,
                                              [0, 0, N2, N1])
        bitratefactor['small reduce'] = fuzz.trimf(bitratefactor.universe,
                                                   [N2, N1, Z])
        bitratefactor['no change'] = fuzz.trimf(bitratefactor.universe,
                                                [N1, Z, P1])
        bitratefactor['small increase'] = fuzz.trimf(bitratefactor.universe,
                                                     [Z, P1, P2])
        bitratefactor['increase'] = fuzz.trapmf(bitratefactor.universe,
                                                [P1, P2, 2.5, 2.5])

        rule1 = ctrl.Rule(bufferTime['short'] & diffBufferTime['falling'],
                          bitratefactor['reduce'])
        rule2 = ctrl.Rule(bufferTime['close'] & diffBufferTime['falling'],
                          bitratefactor['small reduce'])
        rule3 = ctrl.Rule(bufferTime['long'] & diffBufferTime['falling'],
                          bitratefactor['no change'])
        rule4 = ctrl.Rule(bufferTime['short'] & diffBufferTime['steady'],
                          bitratefactor['small reduce'])
        rule5 = ctrl.Rule(bufferTime['close'] & diffBufferTime['steady'],
                          bitratefactor['no change'])
        rule6 = ctrl.Rule(bufferTime['long'] & diffBufferTime['steady'],
                          bitratefactor['small increase'])
        rule7 = ctrl.Rule(bufferTime['short'] & diffBufferTime['rising'],
                          bitratefactor['no change'])
        rule8 = ctrl.Rule(bufferTime['close'] & diffBufferTime['rising'],
                          bitratefactor['small increase'])
        rule9 = ctrl.Rule(bufferTime['long'] & diffBufferTime['rising'],
                          bitratefactor['increase'])

        bitratefactor_ctrl = ctrl.ControlSystem(
            [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9])
        bitratefactor_simulador = ctrl.ControlSystemSimulation(
            bitratefactor_ctrl)

        # Entrando com alguns valores para qualidade da comida e do serviço
        # Eixo X do gráfico
        bitratefactor_simulador.input['bufferTime'] = bufferT
        bitratefactor_simulador.input['diffBufferTime'] = diffBufferT

        # Computando o resultado
        bitratefactor_simulador.compute()

        print("BitrateAtual * ",
              bitratefactor_simulador.output['bitratefactor'])
        """
        #Gera 3 graficos quando buffir_size = 50
        import matplotlib.pyplot as plt
        if bufferT == 50:
            bufferTime.view(sim=bitratefactor_simulador)
            diffBufferTime.view(sim=bitratefactor_simulador)
            bitratefactor.view(sim=bitratefactor_simulador)
        
            plt.show()
        """
        return bitratefactor_simulador.output['bitratefactor']
Esempio n. 6
0
def comb_cap_fis(in_network, model_run, scratch, max_da_thresh):
    """
    The combined capacity FIS function
    :param in_network: The input BRAT network
    :param model_run: The model being run, either 'Hpe' or 'ex" (Potential or Existing)
    :param scratch: The current workspace
    :param max_da_thresh: The drainage area value above which the stream is assumed to not support dam building
    :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 = "oCC_HPE"
        veg_field = "oVC_HPE"
        mcc_field = "mCC_HPE_CT"
    else:
        out_field = "oCC_EX"
        veg_field = "oVC_EX"
        mcc_field = "mCC_EX_CT"

    # check for oCC_* 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")
    ovc_np = arcpy.da.FeatureClassToNumPyArray(in_network, veg_field)
    ihydsp2_np = arcpy.da.FeatureClassToNumPyArray(in_network, "iHyd_SP2")
    ihydsplow_np = arcpy.da.FeatureClassToNumPyArray(in_network, "iHyd_SPLow")
    igeoslope_np = arcpy.da.FeatureClassToNumPyArray(in_network, "iGeo_Slope")

    segid_array = np.asarray(segid_np, np.int64)
    ovc_array = np.asarray(ovc_np, np.float64)
    ihydsp2_array = np.asarray(ihydsp2_np, np.float64)
    ihydsplow_array = np.asarray(ihydsplow_np, np.float64)
    igeoslope_array = np.asarray(igeoslope_np, np.float64)

    # check that inputs are within range of fis
    # if not, re-assign the value to just within range
    ovc_array[ovc_array < 0] = 0
    ovc_array[ovc_array > 45] = 45
    ihydsp2_array[ihydsp2_array < 0] = 0.0001
    ihydsp2_array[ihydsp2_array > 10000] = 10000
    ihydsplow_array[ihydsplow_array < 0] = 0.0001
    ihydsplow_array[ihydsplow_array > 10000] = 10000
    igeoslope_array[igeoslope_array > 1] = 1

    # delete temp arrays
    items = [segid_np, ovc_np, ihydsp2_np, ihydsplow_np, igeoslope_np]
    for item in items:
        del item

    # create antecedent (input) and consequent (output) objects to hold universe variables and membership functions
    ovc = ctrl.Antecedent(np.arange(0, 45, 0.01), 'input1')
    sp2 = ctrl.Antecedent(np.arange(0, 10000, 1), 'input2')
    splow = ctrl.Antecedent(np.arange(0, 10000, 1), 'input3')
    slope = ctrl.Antecedent(np.arange(0, 1, 0.0001), 'input4')
    density = ctrl.Consequent(np.arange(0, 45, 0.01), 'result')

    # build membership functions for each antecedent and consequent object
    ovc['none'] = fuzz.trimf(ovc.universe, [0, 0, 0.1])
    ovc['rare'] = fuzz.trapmf(ovc.universe, [0, 0.1, 0.5, 1.5])
    ovc['occasional'] = fuzz.trapmf(ovc.universe, [0.5, 1.5, 4, 8])
    ovc['frequent'] = fuzz.trapmf(ovc.universe, [4, 8, 12, 25])
    ovc['pervasive'] = fuzz.trapmf(ovc.universe, [12, 25, 45, 45])

    sp2['persists'] = fuzz.trapmf(sp2.universe, [0, 0, 1000, 1200])
    sp2['breach'] = fuzz.trimf(sp2.universe, [1000, 1200, 1600])
    sp2['oblowout'] = fuzz.trimf(sp2.universe, [1200, 1600, 2400])
    sp2['blowout'] = fuzz.trapmf(sp2.universe, [1600, 2400, 10000, 10000])

    splow['can'] = fuzz.trapmf(splow.universe, [0, 0, 150, 175])
    splow['probably'] = fuzz.trapmf(splow.universe, [150, 175, 180, 190])
    splow['cannot'] = fuzz.trapmf(splow.universe, [180, 190, 10000, 10000])

    slope['flat'] = fuzz.trapmf(slope.universe, [0, 0, 0.0002, 0.005])
    slope['can'] = fuzz.trapmf(slope.universe, [0.0002, 0.005, 0.12, 0.15])
    slope['probably'] = fuzz.trapmf(slope.universe, [0.12, 0.15, 0.17, 0.23])
    slope['cannot'] = fuzz.trapmf(slope.universe, [0.17, 0.23, 1, 1])

    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(ovc['none'], density['none'])
    rule2 = ctrl.Rule(splow['cannot'], density['none'])
    rule3 = ctrl.Rule(slope['cannot'], density['none'])
    rule4 = ctrl.Rule(
        ovc['rare'] & sp2['persists'] & splow['can'] & ~slope['cannot'],
        density['rare'])
    rule5 = ctrl.Rule(
        ovc['rare'] & sp2['persists'] & splow['probably'] & ~slope['cannot'],
        density['rare'])
    rule6 = ctrl.Rule(
        ovc['rare'] & sp2['breach'] & splow['can'] & ~slope['cannot'],
        density['rare'])
    rule7 = ctrl.Rule(
        ovc['rare'] & sp2['breach'] & splow['probably'] & ~slope['cannot'],
        density['rare'])
    rule8 = ctrl.Rule(
        ovc['rare'] & sp2['oblowout'] & splow['can'] & ~slope['cannot'],
        density['rare'])
    rule9 = ctrl.Rule(
        ovc['rare'] & sp2['oblowout'] & splow['probably'] & ~slope['cannot'],
        density['rare'])
    rule10 = ctrl.Rule(
        ovc['rare'] & sp2['blowout'] & splow['can'] & ~slope['cannot'],
        density['none'])
    rule11 = ctrl.Rule(
        ovc['rare'] & sp2['blowout'] & splow['probably'] & ~slope['cannot'],
        density['none'])
    rule12 = ctrl.Rule(
        ovc['occasional'] & sp2['persists'] & splow['can'] & ~slope['cannot'],
        density['occasional'])
    rule13 = \
        ctrl.Rule(ovc['occasional'] & sp2['persists'] & splow['probably'] & ~slope['cannot'], density['occasional'])
    rule14 = ctrl.Rule(
        ovc['occasional'] & sp2['breach'] & splow['can'] & ~slope['cannot'],
        density['occasional'])
    rule15 = ctrl.Rule(
        ovc['occasional'] & sp2['breach'] & splow['probably']
        & ~slope['cannot'], density['occasional'])
    rule16 = ctrl.Rule(
        ovc['occasional'] & sp2['oblowout'] & splow['can'] & ~slope['cannot'],
        density['occasional'])
    rule17 = \
        ctrl.Rule(ovc['occasional'] & sp2['oblowout'] & splow['probably'] & ~slope['cannot'], density['occasional'])
    rule18 = ctrl.Rule(
        ovc['occasional'] & sp2['blowout'] & splow['can'] & ~slope['cannot'],
        density['rare'])
    rule19 = ctrl.Rule(
        ovc['occasional'] & sp2['blowout'] & splow['probably']
        & ~slope['cannot'], density['rare'])
    rule20 = ctrl.Rule(
        ovc['frequent'] & sp2['persists'] & splow['can'] & slope['flat'],
        density['occasional'])
    rule21 = ctrl.Rule(
        ovc['frequent'] & sp2['persists'] & splow['can'] & slope['can'],
        density['frequent'])
    rule22 = ctrl.Rule(
        ovc['frequent'] & sp2['persists'] & splow['can'] & slope['probably'],
        density['occasional'])
    rule23 = ctrl.Rule(
        ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['flat'],
        density['occasional'])
    rule24 = ctrl.Rule(
        ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['can'],
        density['frequent'])
    rule25 = ctrl.Rule(
        ovc['frequent'] & sp2['persists'] & splow['probably']
        & slope['probably'], density['occasional'])
    rule26 = ctrl.Rule(
        ovc['frequent'] & sp2['breach'] & splow['can'] & slope['flat'],
        density['occasional'])
    rule27 = ctrl.Rule(
        ovc['frequent'] & sp2['breach'] & splow['can'] & slope['can'],
        density['frequent'])
    rule28 = ctrl.Rule(
        ovc['frequent'] & sp2['breach'] & splow['can'] & slope['probably'],
        density['occasional'])
    rule29 = ctrl.Rule(
        ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['flat'],
        density['occasional'])
    rule30 = ctrl.Rule(
        ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['can'],
        density['frequent'])
    rule31 = ctrl.Rule(
        ovc['frequent'] & sp2['breach'] & splow['probably']
        & slope['probably'], density['occasional'])
    rule32 = ctrl.Rule(
        ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['flat'],
        density['occasional'])
    rule33 = ctrl.Rule(
        ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['can'],
        density['frequent'])
    rule34 = ctrl.Rule(
        ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['probably'],
        density['occasional'])
    rule35 = ctrl.Rule(
        ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['flat'],
        density['rare'])
    rule36 = ctrl.Rule(
        ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['can'],
        density['occasional'])
    rule37 = ctrl.Rule(
        ovc['frequent'] & sp2['oblowout'] & splow['probably']
        & slope['probably'], density['rare'])
    rule38 = ctrl.Rule(
        ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['flat'],
        density['rare'])
    rule39 = ctrl.Rule(
        ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['can'],
        density['rare'])
    rule40 = ctrl.Rule(
        ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['probably'],
        density['rare'])
    rule41 = ctrl.Rule(
        ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['flat'],
        density['rare'])
    rule42 = ctrl.Rule(
        ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['can'],
        density['rare'])
    rule43 = ctrl.Rule(
        ovc['frequent'] & sp2['blowout'] & splow['probably']
        & slope['probably'], density['rare'])
    rule44 = ctrl.Rule(
        ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['flat'],
        density['frequent'])
    rule45 = ctrl.Rule(
        ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['can'],
        density['pervasive'])
    rule46 = ctrl.Rule(
        ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['probably'],
        density['frequent'])
    rule47 = ctrl.Rule(
        ovc['pervasive'] & sp2['persists'] & splow['probably'] & slope['flat'],
        density['frequent'])
    rule48 = ctrl.Rule(
        ovc['pervasive'] & sp2['persists'] & splow['probably'] & slope['can'],
        density['pervasive'])
    rule49 = ctrl.Rule(
        ovc['pervasive'] & sp2['persists'] & splow['probably']
        & slope['probably'], density['frequent'])
    rule50 = ctrl.Rule(
        ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['flat'],
        density['frequent'])
    rule51 = ctrl.Rule(
        ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['can'],
        density['pervasive'])
    rule52 = ctrl.Rule(
        ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['probably'],
        density['frequent'])
    rule53 = ctrl.Rule(
        ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['flat'],
        density['frequent'])
    rule54 = ctrl.Rule(
        ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['can'],
        density['pervasive'])
    rule55 = ctrl.Rule(
        ovc['pervasive'] & sp2['breach'] & splow['probably']
        & slope['probably'], density['frequent'])
    rule56 = ctrl.Rule(
        ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['flat'],
        density['frequent'])
    rule57 = ctrl.Rule(
        ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['can'],
        density['pervasive'])
    rule58 = ctrl.Rule(
        ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['probably'],
        density['frequent'])
    rule59 = ctrl.Rule(
        ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['flat'],
        density['occasional'])
    rule60 = ctrl.Rule(
        ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['can'],
        density['frequent'])
    rule61 = \
        ctrl.Rule(ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['probably'], density['occasional'])
    rule62 = ctrl.Rule(
        ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['flat'],
        density['occasional'])
    rule63 = ctrl.Rule(
        ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['can'],
        density['occasional'])
    rule64 = ctrl.Rule(
        ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['probably'],
        density['rare'])
    rule65 = ctrl.Rule(
        ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['flat'],
        density['occasional'])
    rule66 = ctrl.Rule(
        ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['can'],
        density['occasional'])
    rule67 = ctrl.Rule(
        ovc['pervasive'] & sp2['blowout'] & splow['probably']
        & slope['probably'], density['rare'])

    comb_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, rule26, rule27, rule28,
        rule29, rule30, rule31, rule32, rule33, rule34, rule35, rule36, rule37,
        rule38, rule39, rule40, rule41, rule42, rule43, rule44, rule45, rule46,
        rule47, rule48, rule49, rule50, rule51, rule52, rule53, rule54, rule55,
        rule56, rule57, rule58, rule59, rule60, rule61, rule62, rule63, rule64,
        rule65, rule66, rule67
    ])
    comb_fis = ctrl.ControlSystemSimulation(comb_ctrl)

    # run fuzzy inference system on inputs and defuzzify output
    # TODO Test this using nas instead of zeros
    out = np.zeros(len(ovc_array))
    for i in range(len(out)):
        comb_fis.input['input1'] = ovc_array[i]
        comb_fis.input['input2'] = ihydsp2_array[i]
        comb_fis.input['input3'] = ihydsplow_array[i]
        comb_fis.input['input4'] = igeoslope_array[i]
        comb_fis.compute()
        out[i] = comb_fis.output['result']

    # save fuzzy inference system output as table
    columns = np.column_stack((segid_array, out))
    out_table = os.path.dirname(in_network) + "/" + out_field + "_Table.txt"
    # TODO See if possible to skip this step
    np.savetxt(out_table,
               columns,
               delimiter=",",
               header="ReachID, " + out_field,
               comments="")
    occ_table = scratch + "/" + out_field + "Tbl"
    arcpy.CopyRows_management(out_table, occ_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(occ_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 bare excepts. What kind of error is this trying to catch?
            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 combined capacity (occ_*) values in stream network
    # correct for occ_* greater than ovc_* as vegetation is most limiting factor in model
    # (i.e., combined fis value should not be greater than the vegetation capacity)
    # set occ_* to 0 if the drainage area is greater than the user defined threshold
    # this enforces a stream size threshold above which beaver dams won't persist and/or won't be built
    # set occ_* 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, veg_field, 'iGeo_DA', 'iGeo_Slope']) 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
            if row[0] > row[1]:
                row[0] = row[1]
            if row[2] >= float(max_da_thresh):
                row[0] = 0.0
            cursor.updateRow(row)

    # delete temporary tables and arrays
    arcpy.Delete_management(out_table)
    arcpy.Delete_management(occ_table)
    items = [columns, out, x, mfx_none, defuzz_none]
    for item in items:
        del item

    # calculate dam count (mCC_**_CT) for each reach as number of dams * reach length (in km)
    arcpy.AddField_management(in_network, mcc_field, 'SHORT')
    with arcpy.da.UpdateCursor(in_network,
                               [mcc_field, out_field, 'iGeo_Len']) as cursor:
        for row in cursor:
            len_km = row[2] / 1000
            raw_ct = row[1] * len_km
            if 1 > raw_ct > 0:
                row[0] = 1
            else:
                row[0] = round(raw_ct)
            cursor.updateRow(row)

    # calculate dam count historic departure as difference between potential count and existing count
    if model_run == 'ex':
        arcpy.AddField_management(in_network, 'mCC_HisDep', 'SHORT')
        with arcpy.da.UpdateCursor(
                in_network,
            ['mCC_HisDep', 'mCC_EX_CT', 'mCC_HPE_CT']) as cursor:
            for row in cursor:
                row[0] = row[2] - row[1]
                cursor.updateRow(row)
# this is a refactored version of the code
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl  # I am using this library to easily create membership functions

# Step 1: Create Antecedents/Consequents, plus variables to hold membership functions

age = ctrl.Antecedent(
    np.arange(0, 10, 1), 'age'
)  # -> this is our first antecedent, we repeat the logic, change the ranges
distance = ctrl.Antecedent(np.arange(0, 10, 1), 'distance')
energy_rating = ctrl.Antecedent(np.arange(0, 100, 1), 'energy_rating')
population = ctrl.Antecedent(np.arange(0, 10, 1), 'population')
# then the consequence, ranges really depend on your paramaters
price_increase = ctrl.Consequent(np.arange(0, 60, 1), 'price_increase')


# This method defines which membership functions are to be used dependant on the input variable
# universe is explicitly stating that these are global variables, specifically that they are "arrays"
def set_obj(obj, key1, value_1, key2, value_2, key3, value_3):
    obj[key1] = fuzz.trimf(obj.universe, value_1)
    if len(value_2) > 1:
        obj[key2] = fuzz.trimf(obj.universe, value_2)
    if obj.label == 'energy_rating':
        obj[key3] = fuzz.trimf(obj.universe, value_3)
    else:
        obj[key3] = fuzz.trapmf(obj.universe, value_3)


# This defines the values to be used in each membership function as well as labeling them accordingly.
Esempio n. 8
0
    def Init_Rule(self):
        universe0 = np.linspace(-3000, 3000, 5)  # Delta Destination Distance
        universe1 = np.linspace(-180, 180, 5)  # Delta Destination Angular
        universe2 = np.linspace(0, 25, 5)  # Velocity
        universe3 = np.array([-20, -15, 0, 15, 20])  # Angular Velocity

        dD = ctrl.Antecedent(universe0, 'dD')
        dT = ctrl.Antecedent(universe1, 'dT')
        oV = ctrl.Consequent(universe2, 'oV')
        oW = ctrl.Consequent(universe3, 'oW')

        # names0 = ['nb', 'ns',  'ze', 'ps', 'pb']
        dD.automf(names=['NHD', 'NLD', 'ZD', 'PLD', 'PHD'])
        dT.automf(names=['NHA', 'NLA', 'ZA', 'PLA', 'PHA'])
        oV.automf(names=['ZERO', 'SLOW', 'MEDIUM', 'FAST', 'HFAST'])
        oW.automf(names=['HL', 'L', 'ST', 'R', 'HR'])

        rule0 = ctrl.Rule(antecedent=(dD['NHD'] & dT['NHA']),
                          consequent=(oV['SLOW'], oW['HR']))
        rule1 = ctrl.Rule(antecedent=(dD['NLD'] & dT['NHA']),
                          consequent=(oV['SLOW'], oW['HR']))
        rule2 = ctrl.Rule(antecedent=(dD['ZD'] & dT['NHA']),
                          consequent=(oV['SLOW'], oW['HR']))
        rule3 = ctrl.Rule(antecedent=(dD['PLD'] & dT['NHA']),
                          consequent=(oV['SLOW'], oW['R']))
        rule4 = ctrl.Rule(antecedent=(dD['PHD'] & dT['NHA']),
                          consequent=(oV['SLOW'], oW['ST']))

        rule5 = ctrl.Rule(antecedent=(dD['NHD'] & dT['NLA']),
                          consequent=(oV['SLOW'], oW['HR']))
        rule6 = ctrl.Rule(antecedent=(dD['NLD'] & dT['NLA']),
                          consequent=(oV['SLOW'], oW['R']))
        rule7 = ctrl.Rule(antecedent=(dD['ZD'] & dT['NLA']),
                          consequent=(oV['MEDIUM'], oW['R']))
        rule8 = ctrl.Rule(antecedent=(dD['PLD'] & dT['NLA']),
                          consequent=(oV['SLOW'], oW['ST']))
        rule9 = ctrl.Rule(antecedent=(dD['PHD'] & dT['NLA']),
                          consequent=(oV['SLOW'], oW['L']))

        rule10 = ctrl.Rule(antecedent=(dD['NHD'] & dT['ZA']),
                           consequent=(oV['MEDIUM'], oW['HR']))
        rule11 = ctrl.Rule(antecedent=(dD['NLD'] & dT['ZA']),
                           consequent=(oV['MEDIUM'], oW['R']))
        rule12 = ctrl.Rule(antecedent=(dD['ZD'] & dT['ZA']),
                           consequent=(oV['FAST'], oW['ST']))
        rule13 = ctrl.Rule(antecedent=(dD['PLD'] & dT['ZA']),
                           consequent=(oV['MEDIUM'], oW['L']))
        rule14 = ctrl.Rule(antecedent=(dD['PHD'] & dT['ZA']),
                           consequent=(oV['MEDIUM'], oW['HL']))

        rule15 = ctrl.Rule(antecedent=(dD['NHD'] & dT['PLA']),
                           consequent=(oV['SLOW'], oW['R']))
        rule16 = ctrl.Rule(antecedent=(dD['NLD'] & dT['PLA']),
                           consequent=(oV['SLOW'], oW['ST']))
        rule17 = ctrl.Rule(antecedent=(dD['ZD'] & dT['PLA']),
                           consequent=(oV['MEDIUM'], oW['L']))
        rule18 = ctrl.Rule(antecedent=(dD['PLD'] & dT['PLA']),
                           consequent=(oV['SLOW'], oW['L']))
        rule19 = ctrl.Rule(antecedent=(dD['PHD'] & dT['PLA']),
                           consequent=(oV['SLOW'], oW['HL']))

        rule20 = ctrl.Rule(antecedent=(dD['NHD'] & dT['PHA']),
                           consequent=(oV['SLOW'], oW['ST']))
        rule21 = ctrl.Rule(antecedent=(dD['NLD'] & dT['PHA']),
                           consequent=(oV['SLOW'], oW['L']))
        rule22 = ctrl.Rule(antecedent=(dD['ZD'] & dT['PHA']),
                           consequent=(oV['SLOW'], oW['HL']))
        rule23 = ctrl.Rule(antecedent=(dD['PLD'] & dT['PHA']),
                           consequent=(oV['SLOW'], oW['HL']))
        rule24 = ctrl.Rule(antecedent=(dD['PHD'] & dT['PHA']),
                           consequent=(oV['SLOW'], oW['HL']))

        self.my_rules = [
            rule0, rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8,
            rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16,
            rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24
        ]
Esempio n. 9
0
"""

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

# New Antecedent/Consequent objects hold universe variables and membership \
# functions
sleep_quality = ctrl.Antecedent(np.arange(0, 11, 1), 'sleep_quality')
diet_quality = ctrl.Antecedent(np.arange(0, 11, 1), 'diet_quality')
emotional_wellness = ctrl.Antecedent(np.arange(0, 11, 1), 'emotional_wellness')
weather_quality = ctrl.Antecedent(np.arange(0, 11, 1), 'weather_quality')
physical_wellness = ctrl.Antecedent(np.arange(0, 11, 1), 'physical_wellness')

drug_dosage = ctrl.Consequent(np.arange(0, 5, 1), 'drug_dosage')

# Auto-membership function population is possible with .automf(3, 5, or 7)
sleep_quality.automf(3)
diet_quality.automf(3)
emotional_wellness.automf(3)
weather_quality.automf(3)
physical_wellness.automf(3)

# Custom membership functions can be built interactively with a familiar, \
# Pythonic API
drug_dosage['low'] = fuzz.trimf(drug_dosage.universe, [0, 0, 2])
drug_dosage['medium'] = fuzz.trimf(drug_dosage.universe, [0, 2, 4])
drug_dosage['high'] = fuzz.trimf(drug_dosage.universe, [2, 4, 4])

# You can see how these look with .view()
Esempio n. 10
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Antecedent for tire_pressure classification given from the output of the RNN
tire_pressure = ctrl.Antecedent(np.arange(0, 3, 1), 'tire_pressure')
# Consequent for the expected error in orientation based off the given tire_pressure classification
orientation_error = ctrl.Consequent(np.arange(-34, 34, 1), 'orientation_error')
predictionClass = 0

# Auto-membership function
tire_pressure.automf(3)

# Membership functions to compute the compensated orientation
orientation_error['center'] = fuzz.trimf(orientation_error.universe,
                                         [-33, -33, 0])
orientation_error['left'] = fuzz.trimf(orientation_error.universe,
                                       [-33, 0, 33])
orientation_error['right'] = fuzz.trimf(orientation_error.universe,
                                        [0, 33, 33])

# Fuzzy Rules:
# IF the tires are full THEN keep center
# IF the right tires are flat THEN keep left
# IF the left tires are flat THEN keep right
rule1 = ctrl.Rule(tire_pressure['poor'], orientation_error['left'])
rule2 = ctrl.Rule(tire_pressure['average'], orientation_error['center'])
rule3 = ctrl.Rule(tire_pressure['good'], orientation_error['right'])
# note: Antecedents in skfuzzy can only have fuzzy values of 'poor', 'average', and 'good'
# poor: tires are full
# average: right tires are flat
Esempio n. 11
0
def buildFuzzySystem(showDescription = False):
    """ 
    ===========================================================================
    Build Fuzzy Sistem for variable: cnxs: network connections  
    ===========================================================================   
    
    **Args**:
        showDescription: (boolean)
    **Returns**:
        None
    """ 
    #==========================================================================
    # Set labels of inputs and outputs
    #==========================================================================      
 
    in1_max = 100
    
    var_in1_label = 'users'
    var_out_label = 'out'
    
    logger.info("buildFuzzySystem:" + var_in1_label)
    
    #==========================================================================
    # Set numerical range of inputs and outputs
    #==========================================================================          
    
    var_in1_universe = np.arange(0, in1_max, in1_max/1000)
    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['low'] = fuzz.trimf(var_in1.universe, [0, 0, in1_max*0.2])
    var_in1['average'] = fuzz.trapmf(var_in1.universe, [0, 0.2*in1_max, 0.8*in1_max, in1_max])
    var_in1['high'] = fuzz.trimf(var_in1.universe, [0.8*in1_max, in1_max, in1_max])
    
    var_out.automf(number=3, variable_type='quant')
    
    #==========================================================================
    # Set fuzzy rules
    #========================================================================== 
    
    rule1 = ctrl.Rule(var_in1['high'], var_out['high'])
    rule2 = ctrl.Rule(var_in1['average']  , var_out['average'])
    rule3 = ctrl.Rule(var_in1['low']  , var_out['low'])
    
    #==========================================================================
    # Build fuzzy control system and simulation
    #==========================================================================
    
    var_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
    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
Esempio n. 12
0
    def handle_segment_size_request(self, msg):

        time_stop = datetime.datetime.now(
        )  # tempo guardado para calcular a vazão
        self.add_time(time_stop.timestamp())
        moving_avarage_factor = 5  # Usado para fazer média das últimas 5 qualidades para não variar bruscamente
        buffer_now = self.whiteboard.get_playback_buffer_size()
        throughput = 0
        max_throughput = 2
        quality_moving_avg = 0
        medium_quality = 8  # Valor inicial já que a qualidade média é calculada em tempo real usando os últimos 20 items
        medium_connection_throughput = -1
        if len(self.time_of_request) > 2:
            time_to_request = self.time_of_request[-1] - self.time_of_request[
                -2]
            throughput = self.bit_len[-1] / (time_to_request)
            self.add_throughput(throughput)
            max_throughput = max(self.throughput_arr)
            medium_connection_throughput = avg(self.throughput_arr[-20:])
        if len(buffer_now) > 0:
            buffer_now = buffer_now[-1][1]
        else:
            buffer_now = 0
        qualityArr = self.whiteboard.get_playback_qi()
        if len(qualityArr) > 0:
            medium_quality = qualityArr
            qualityArr = qualityArr[-moving_avarage_factor:]
            qualityArr = [item[1] for item in qualityArr]
            quality_moving_avg = avg(qualityArr)
            medium_quality = medium_quality[-20:]  # Valor médio da qualidade
            medium_quality = [item[1] for item in medium_quality]
            medium_quality = avg_the_last_is_the_most_significant(
                medium_quality)
        else:
            quality_moving_avg = 0

        max_buffer_size = self.config_parameters["max_buffer_size"]
        if len(self.time_of_request) < 4:
            medium_buffer_size = 0.5 * max_buffer_size
        else:
            medium_buffer_size = 0.6 * max_buffer_size - (
                0.4 * max_buffer_size *
                (self.time_of_request[-1] - self.time_of_request[0]) /
                self.duration)
            if medium_buffer_size < 0.2 * max_buffer_size:
                medium_buffer_size = 0.2 * max_buffer_size
            print('buffer -----------', medium_buffer_size)

        max_throughput_step = 1
        if max_throughput > 100:
            max_throughput_step = max_throughput / 40
        connection_throughput = ctrl.Antecedent(
            np.arange(0, max_throughput, max_throughput_step),
            'connection_throughput')
        buffer = ctrl.Antecedent(np.arange(0, max_buffer_size + 1, 1),
                                 'buffer')
        quality = ctrl.Consequent(np.arange(0, self.qualities_len, 1),
                                  'quality')
        # connection_throughput.automf(3)

        if medium_connection_throughput == -1:
            medium_connection_throughput = max_throughput / 2
        connection_throughput['poor'] = fuzz.trimf(
            connection_throughput.universe, [0, 0, round(max_throughput)])
        connection_throughput['average'] = fuzz.trimf(
            connection_throughput.universe,
            [0, round(medium_connection_throughput),
             round(max_throughput)])
        connection_throughput['good'] = fuzz.trimf(
            connection_throughput.universe, [
                round(medium_connection_throughput),
                round(max_throughput),
                round(max_throughput)
            ])

        buffer['low'] = fuzz.trimf(buffer.universe,
                                   [0, 0, round(medium_buffer_size)])
        buffer['medium'] = fuzz.trimf(
            buffer.universe, [0, round(medium_buffer_size), max_buffer_size])
        buffer['high'] = fuzz.trimf(
            buffer.universe,
            [round(medium_buffer_size), max_buffer_size, max_buffer_size])

        quality['low'] = fuzz.trimf(quality.universe,
                                    [0, 0, round(medium_quality)])
        quality['medium'] = fuzz.trimf(
            quality.universe,
            [0, round(medium_quality), self.qualities_len - 1])
        quality['high'] = fuzz.trimf(quality.universe, [
            round(medium_quality), self.qualities_len - 1,
            self.qualities_len - 1
        ])

        # quality.view()
        # wait = input("Press Enter to continue.")
        rule1 = ctrl.Rule(connection_throughput['poor'] | buffer['low'],
                          quality['low'])
        rule2 = ctrl.Rule(connection_throughput['average'], quality['medium'])
        # rule2 = ctrl.Rule(connection_throughput['average'] & buffer['medium'], quality['medium'])
        rule3 = ctrl.Rule(connection_throughput['good'] & buffer['low'],
                          quality['medium'])
        # rule4 = ctrl.Rule(connection_throughput['good'] & buffer['medium'], quality['high'])
        rule4 = ctrl.Rule(connection_throughput['good'] & buffer['high'],
                          quality['high'])

        quality_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4])
        new_quality = ctrl.ControlSystemSimulation(quality_ctrl)

        new_quality.input['buffer'] = buffer_now
        new_quality.input['connection_throughput'] = throughput
        new_quality.compute()
        quality_moving_avg = avg(
            [quality_moving_avg, new_quality.output['quality']])
        print('new quality---->', quality_moving_avg)
        # msg.add_quality_id(self.qi[int(quality_moving_avg)])
        msg.add_quality_id(self.qi[round(quality_moving_avg)])
        self.send_down(msg)
Esempio n. 13
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# import matplotlib.pyplot as plt

# input
time_dist = ctrl.Antecedent(np.arange(0, 2.05, 0.05), 'time_dist')
y_dist = ctrl.Antecedent(np.arange(-600, 601, 1), 'y_dist')
y_player = ctrl.Antecedent(np.arange(0, 601, 1), 'y_player')
# output
move = ctrl.Consequent(np.arange(-800, 810, 10), 'move')

time_dist['very small'] = fuzz.trimf(time_dist.universe, [0, 0, 0.1])
time_dist['small'] = fuzz.trimf(time_dist.universe, [0, 0.1, 0.3])
time_dist['medium'] = fuzz.trimf(time_dist.universe, [0.1, 0.3, 1])
time_dist['big'] = fuzz.trimf(time_dist.universe, [0.3, 2, 2])

y_dist['negative big'] = fuzz.trimf(y_dist.universe, [-600, -600, -80])
y_dist['negative small'] = fuzz.trimf(y_dist.universe, [-600, -80, 0])
y_dist['negative very small'] = fuzz.trimf(y_dist.universe, [-80, -1, 1])
y_dist['positive very small'] = fuzz.trimf(y_dist.universe, [-1, 1, 80])
y_dist['positive small'] = fuzz.trimf(y_dist.universe, [0, 80, 600])
y_dist['positive big'] = fuzz.trimf(y_dist.universe, [80, 600, 600])

y_player['top'] = fuzz.trimf(y_player.universe, [0, 0, 90])
y_player['middle'] = fuzz.trapmf(y_player.universe, [0, 90, 510, 600])
y_player['bottom'] = fuzz.trimf(y_player.universe, [510, 600, 600])

move['fast up'] = fuzz.trimf(move.universe, [-800, -800, -450])
move['slow up'] = fuzz.trimf(move.universe, [-800, -450, 0])
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

potencia = ctrl.Antecedent(np.arange(0, 101, 1), 'potência')
vazao = ctrl.Antecedent(np.arange(0, 101, 1), 'vazão')
temperatura = ctrl.Consequent(np.arange(15, 46, 1), 'temperatura')

# Funções de Pertinência para a potência
potencia['baixa'] = fuzz.trapmf(potencia.universe, [0, 0, 20, 50])
potencia['média'] = fuzz.trimf(potencia.universe, [20, 50, 80])
potencia['alta'] = fuzz.trapmf(potencia.universe, [50, 80, 100, 100])

# Funções de Pertinência para a vazão
vazao['baixa'] = fuzz.trapmf(vazao.universe, [0, 0, 20, 50])
vazao['média'] = fuzz.trimf(vazao.universe, [20, 50, 80])
vazao['alta'] = fuzz.trapmf(vazao.universe, [50, 80, 100, 100])

# Funções de Pertinência para a temperatura
temperatura['baixa'] = fuzz.trapmf(temperatura.universe, [15, 15, 20, 30])
temperatura['agradável'] = fuzz.trimf(temperatura.universe, [20, 30, 40])
temperatura['alta'] = fuzz.trapmf(temperatura.universe, [30, 40, 45, 45])

potencia.view()

vazao.view()

temperatura.view()

# Regras de Inferência
rule1 = ctrl.Rule(potencia['baixa'] & vazao['baixa'], temperatura['agradável'])
Esempio n. 15
0
loaded_model = pickle.load(open(filename, 'rb'))
# result = loaded_model.score(X_test, Y_test)
# print(result)

#output of ML model
out_ml_model = loaded_model.predict_proba([[
    avg_running_time, avg_number_of_jumps, avg_Crouch_time_plus_walking_time
]])[0][1]
out_ml_model = out_ml_model * 100
print("is_aggresive : {}%".format(out_ml_model))

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

# Consequent
gun_damage_pc = ctrl.Consequent(np.arange(0, 101, 1), 'gun_damage_pc')
speed_npc = ctrl.Consequent(np.arange(0, 101, 1), 'speed_npc')
gun_accuracy_npc = ctrl.Consequent(np.arange(0, 101, 1), 'gun_accuracy_npc')
gun_damage_npc = ctrl.Consequent(np.arange(0, 101, 1), 'gun_damage_npc')
health_dec_factor = ctrl.Consequent(np.arange(0, 101, 1), 'health_dec_factor')
ammo = ctrl.Consequent(np.arange(0, 101, 1), 'ammo')
tot_enemy = ctrl.Consequent(np.arange(0, 101, 1), 'tot_enemy')
tot_enemy_1_location = ctrl.Consequent(np.arange(0, 101, 1),
                                       'tot_enemy_1_location')

# membershio function of Antecedent
is_aggresive['passive'] = fuzz.trimf(is_aggresive.universe, [0, 0, 100])
is_aggresive['aggresive'] = fuzz.trimf(is_aggresive.universe, [0, 100, 100])

# membership functions of Consequent
if gun_damage_pc_funtype == 0:
Esempio n. 16
0
def main(in_network, scratch):

    net_gpd = gpd.read_file(in_network, driver="ESRI Shapefile")

    net_gpd.loc[net_gpd['iVeg_40'] < 0, 'iVeg_40'] = 0
    net_gpd.loc[net_gpd['iVeg_10'] < 0, 'iVeg_10'] = 0
    net_gpd.loc[net_gpd['iVeg_40'] > 5, 'iVeg_40'] = 5
    net_gpd.loc[net_gpd['iVeg_10'] > 5, 'iVeg_10'] = 5

   
    riparian_array = net_gpd['iVeg_40'].values
    streamside_array = net_gpd['iVeg_10'].values

    # set up input and output ranges

    riparian = ctrl.Antecedent(np.arange(0, 5, 0.001), 'input1')
    streamside = ctrl.Antecedent(np.arange(0, 5, 0.001), 'input2')
    density = ctrl.Consequent(np.arange(0, 45, 0.5), 'result')

    riparian['unsuitablea'] = fuzz.trapmf(streamside.universe, [0, 0, 1, 1.5])
    riparian['barelya'] = fuzz.trapmf(streamside.universe, [1, 1.5, 2, 2.25])
    riparian['moderatelya'] = fuzz.trapmf(streamside.universe, [2, 2.25, 3.5, 4])
    riparian['suitablea'] = fuzz.trapmf(streamside.universe, [3.5, 4, 4.75, 5])
    riparian['preferreda'] = fuzz.trimf(riparian.universe, [4.5, 5, 5])

    streamside['unsuitable'] = fuzz.trapmf(streamside.universe, [0, 0, 1, 1.5])
    streamside['barely'] = fuzz.trapmf(streamside.universe, [1, 1.5, 2, 2.25])
    streamside['moderately'] = fuzz.trapmf(streamside.universe, [2, 2.25, 3.5, 4])
    streamside['suitable'] = fuzz.trapmf(streamside.universe, [3.5, 4, 4.75, 5])
    streamside['preferred'] = fuzz.trimf(riparian.universe, [4.5, 5, 5])

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

    # rules
    rule1 = ctrl.Rule(riparian['unsuitablea'] & streamside['unsuitable'], density['none'])
    rule2 = ctrl.Rule(riparian['barelya'] & streamside['unsuitable'], density['none'])
    rule3 = ctrl.Rule(riparian['moderatelya'] & streamside['unsuitable'], density['rare'])
    rule4 = ctrl.Rule(riparian['suitablea'] & streamside['unsuitable'], density['occasional'])
    rule5 = ctrl.Rule(riparian['preferreda'] & streamside['unsuitable'], density['frequent'])
    rule6 = ctrl.Rule(riparian['unsuitablea'] & streamside['barely'], density['rare'])
    rule7 = ctrl.Rule(riparian['barelya'] & streamside['barely'], density['rare'])
    rule8 = ctrl.Rule(riparian['moderatelya'] & streamside['barely'], density['occasional'])
    rule9 = ctrl.Rule(riparian['suitablea'] & streamside['barely'], density['frequent'])
    rule10 = ctrl.Rule(riparian['preferreda'] & streamside['barely'], density['frequent'])
    rule11 = ctrl.Rule(riparian['unsuitablea'] & streamside['moderately'], density['occasional']) #
    rule12 = ctrl.Rule(riparian['barelya'] & streamside['moderately'], density['occasional'])
    rule13 = ctrl.Rule(riparian['moderatelya'] & streamside['moderately'], density['occasional'])
    rule14 = ctrl.Rule(riparian['suitablea'] & streamside['moderately'], density['frequent'])
    rule15 = ctrl.Rule(riparian['preferreda'] & streamside['moderately'], density['frequent'])
    rule16 = ctrl.Rule(riparian['unsuitablea'] & streamside['suitable'], density['occasional'])
    rule17 = ctrl.Rule(riparian['barelya'] & streamside['suitable'], density['frequent'])
    rule18 = ctrl.Rule(riparian['moderatelya'] & streamside['suitable'], density['frequent'])
    rule19 = ctrl.Rule(riparian['suitablea'] & streamside['suitable'], density['frequent'])
    rule20 = ctrl.Rule(riparian['preferreda'] & streamside['suitable'], density['pervasive'])
    rule21 = ctrl.Rule(riparian['unsuitablea'] & streamside['preferred'], density['frequent'])
    rule22 = ctrl.Rule(riparian['barelya'] & streamside['preferred'], density['frequent'])
    rule23 = ctrl.Rule(riparian['moderatelya'] & streamside['preferred'], density['frequent'])
    rule24 = ctrl.Rule(riparian['suitablea'] & streamside['preferred'], density['pervasive'])
    rule25 = ctrl.Rule(riparian['preferreda'] & 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)

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

    net_gpd['oVC_EX'] = out

    net_gpd.to_file(in_network, driver="ESRI Shapefile")



    return in_network
Esempio n. 17
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

#Antecedents/Consequents
D = ctrl.Antecedent(np.arange(0,10.5,0.5), "distance")
A = ctrl.Antecedent(np.arange(0, 91, 1), "angle")
S = ctrl.Consequent(np.arange(0, 5.2, 0.2), "speed", defuzzify_method="mom")
ST = ctrl.Consequent(np.arange(0, 91, 1), "steering", defuzzify_method="lom")

#Memberships
D["N"] = fuzz.trimf(D.universe,[0,0,5])
D["F"] = fuzz.trimf(D.universe, [2.5,5,7.5])
D["VF"] = fuzz.trimf(D.universe, [5,10,10])

A["S"] = fuzz.trimf(A.universe,[0, 0, 20])
A["M"] = fuzz.trimf(A.universe, [15, 40, 60])
A["L"] = fuzz.trimf(A.universe, [55, 90, 90])

S["SS"] = fuzz.trimf(S.universe, [0, 0, 1.6])
S["MS"] = fuzz.trimf(S.universe, [1.2,2,2.8])
S["FS"] = fuzz.trimf(S.universe, [2.4, 3.2, 4])
S["MXS"] = fuzz.trimf(S.universe, [3.6, 5, 5])

ST["MST"] = fuzz.trimf(A.universe,[0, 0, 35])
ST["SST"] = fuzz.trimf(A.universe, [25, 45, 60])
ST["VST"] = fuzz.trimf(A.universe, [55, 90, 90])

#Rules
Esempio n. 18
0
def fuzzy_rules(sentence_feature_object):
    
    # print(sentence_feature_object)

    universe_features = np.arange(0,1,0.001)
    universe_result = np.arange(0,1,0.01)

    title_word = ctrl.Antecedent(universe_features, 'title_word')
    sentence_length = ctrl.Antecedent(universe_features, 'sentence_length')
    sentence_location = ctrl.Antecedent(universe_features, 'sentence_location')
    numerical_data = ctrl.Antecedent(universe_features, 'numerical_data')
    # thematic_keyword = ctrl.Antecedent(universe_features, 'thematic_keyword')
    # proper_noun = ctrl.Antecedent(universe_features, 'proper_noun')
    # sentence_similarity = ctrl.Antecedent(universe_features, 'sentence_similarity')
    # term_weight = ctrl.Antecedent(universe_features, 'term_weight')


    result = ctrl.Consequent(universe_result, 'result')


    # Auto-membership function population is possible with .automf(3, 5, or 7)
    title_word.automf(3)
    sentence_length.automf(3)
    sentence_location.automf(3)
    numerical_data.automf(3)
    # thematic_keyword.automf(3)
    # proper_noun.automf(3)
    # sentence_similarity.automf(3)
    # term_weight.automf(3)

    # Custom membership functions can be built interactively with a familiar,
    # Pythonic API
    result['low'] = fuzzy.trimf(result.universe, [0.000,0.30,0.500])
    result['medium'] = fuzzy.trimf(result.universe, [0.300,0.500,0.700])
    result['high'] = fuzzy.trimf(result.universe, [0.500,1.0,1.0])

   
    # 'poor'; 'average', or 'good'
   
    rule1  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule2  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["average"], result['low'])
    rule3  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["good"], result['low'])
    rule4  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["poor"], result['low'])
    rule5  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["average"], result['low'])
    rule6  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["good"], result['low'])
    rule7  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["poor"], result['low'])
    rule8  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["average"], result['low'])
    rule9  = ctrl.Rule(title_word["poor"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["good"], result['low'])
    rule10  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule11  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["average"], result['low'])
    rule12  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["good"], result['low'])
    rule13  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["average"] & numerical_data["poor"], result['low'])
    rule14  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule15  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["average"] & numerical_data["good"], result['medium'])
    rule16  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["good"] & numerical_data["poor"], result['low'])
    rule17  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["good"] & numerical_data["average"], result['medium'])
    rule18  = ctrl.Rule(title_word["poor"] & sentence_length["average"] & sentence_location["good"] & numerical_data["good"], result['high'])
    rule19  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule20  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["average"], result['low'])
    rule21  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["good"], result['low'])
    rule22  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["average"] & numerical_data["poor"], result['low'])
    rule23  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule24  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["average"] & numerical_data["good"], result['high'])
    rule25  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["good"] & numerical_data["poor"], result['low'])
    rule26  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["good"] & numerical_data["average"], result['high'])
    rule27  = ctrl.Rule(title_word["poor"] & sentence_length["good"] & sentence_location["good"] & numerical_data["good"], result['high'])
    rule28  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule29  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["average"], result['low'])
    rule30  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["good"], result['low'])
    rule31  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["poor"], result['low'])
    rule32  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule33  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["good"], result['medium'])
    rule34  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["poor"], result['low'])
    rule35  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["average"], result['medium'])
    rule36  = ctrl.Rule(title_word["average"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["good"], result['high'])
    rule37  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule38  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["average"], result['medium'])
    rule39  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["good"], result['medium'])
    rule40  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["average"] & numerical_data["poor"], result['medium'])
    rule41  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule42  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["average"] & numerical_data["good"], result['medium'])
    rule43  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["good"] & numerical_data["poor"], result['medium'])
    rule44  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["good"] & numerical_data["average"], result['medium'])
    rule45  = ctrl.Rule(title_word["average"] & sentence_length["average"] & sentence_location["good"] & numerical_data["good"], result['medium'])
    rule46  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule47  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["average"], result['medium'])
    rule48  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["good"], result['high'])
    rule49  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["average"] & numerical_data["poor"], result['medium'])
    rule50  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule51  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["average"] & numerical_data["good"], result['medium'])
    rule52  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["good"] & numerical_data["poor"], result['high'])
    rule53  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["good"] & numerical_data["average"], result['medium'])
    rule54  = ctrl.Rule(title_word["average"] & sentence_length["good"] & sentence_location["good"] & numerical_data["good"], result['high'])
    rule55  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule56  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["average"], result['low'])
    rule57  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["poor"] & numerical_data["good"], result['low'])
    rule58  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["poor"], result['low'])
    rule59  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule60  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["average"] & numerical_data["good"], result['high'])
    rule61  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["poor"], result['low'])
    rule62  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["average"], result['high'])
    rule63  = ctrl.Rule(title_word["good"] & sentence_length["poor"] & sentence_location["good"] & numerical_data["good"], result['high'])
    rule64  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule65  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["average"], result['medium'])
    rule66  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["poor"] & numerical_data["good"], result['high'])
    rule67  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["average"] & numerical_data["poor"], result['medium'])
    rule68  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule69  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["average"] & numerical_data["good"], result['medium'])
    rule70  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["good"] & numerical_data["poor"], result['high'])
    rule71  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["good"] & numerical_data["average"], result['medium'])
    rule72  = ctrl.Rule(title_word["good"] & sentence_length["average"] & sentence_location["good"] & numerical_data["good"], result['high'])
    rule73  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["poor"], result['low'])
    rule74  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["average"], result['high'])
    rule75  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["poor"] & numerical_data["good"], result['high'])
    rule76  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["average"] & numerical_data["poor"], result['high'])
    rule77  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["average"] & numerical_data["average"], result['medium'])
    rule78  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["average"] & numerical_data["good"], result['high'])
    rule79  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["good"] & numerical_data["poor"], result['high'])
    rule80  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["good"] & numerical_data["average"], result['high'])
    rule81  = ctrl.Rule(title_word["good"] & sentence_length["good"] & sentence_location["good"] & numerical_data["good"], result['high'])
    
    tipping_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, rule26, rule27, rule28, rule29, rule30, rule31, rule32, rule33, rule34, rule35, rule36, rule37, rule38, rule39, rule40, rule41, rule42, rule43, rule44, rule45, rule46, rule47, rule48, rule49, rule50, rule51, rule52, rule53, rule54, rule55, rule56, rule57, rule58, rule59, rule60, rule61, rule62, rule63, rule64, rule65, rule66, rule67, rule68, rule69, rule70, rule71, rule72, rule73, rule74, rule75, rule76, rule77, rule78, rule79, rule80, rule81])
    # tipping_ctrl = acr.customRule()
    #tipping control simmulation
    tipping = ctrl.ControlSystemSimulation(tipping_ctrl)

    # Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
    # Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
    tipping.input['title_word'] = sentence_feature_object['title_word']
    tipping.input['sentence_length'] = sentence_feature_object['sentence_length']
    tipping.input['sentence_location'] = sentence_feature_object['sentence_location']
    tipping.input['numerical_data'] = sentence_feature_object['numerical_data']
    # tipping.input['thematic_keyword'] = sentence_feature_object['thematic_keyword']
    # tipping.input['proper_noun'] = sentence_feature_object['proper_noun']
    # tipping.input['sentence_similarity'] = sentence_feature_object['sentence_similarity']
    # tipping.input['term_weight'] = sentence_feature_object['term_weight']

   
    # tipping.inputs(sentence_feature_object)

    # Crunch the numbers
    tipping.compute()

    return tipping.output['result']
Esempio n. 19
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import time
import  datetime
import matplotlib.pyplot as plt

        
##----------------Fuzzy Setting-----------------------------#
# New Antecedent/Consequent objects hold universe variables and membership
# functions
sound =ctrl.Antecedent(np.arange(0, 11, 1), 'sound')
air =ctrl.Antecedent(np.arange(0, 11, 1), 'air')
#light =ctrl.Antecedent(np.arange(0, 11, 1), 'temp')
switch_power = ctrl.Consequent(np.arange(0, 11, 1), 'switch_power')
sound.automf(3)
air.automf(3)
#light.automf(3)
#switch_power.automf(3)
switch_power['low'] = fuzz.trimf(switch_power.universe, [0, 0, 5])
switch_power['medium'] = fuzz.trimf(switch_power.universe, [0, 5, 10])
switch_power['high'] = fuzz.trimf(switch_power.universe, [5, 10, 10])

rule1 = ctrl.Rule(air['good'], switch_power['high'])
rule2 = ctrl.Rule(air['average'] & sound['average'], switch_power['low'])
rule3 = ctrl.Rule(air['average'] & sound['poor']  ,switch_power['high'])
rule4 = ctrl.Rule(air['poor']  | sound['good'], switch_power['low'])
tipping_ctrl = ctrl.ControlSystem([rule1,rule2,rule3,rule4])
tipping = ctrl.ControlSystemSimulation(tipping_ctrl)
#sound['average'].view()
#air['average'].view()
def fuzzy_logic_algo(sb, sk, crf):
    # New Antecedent/Consequent objects hold universe variables and membership
    # functions
    skill = ctrl.Antecedent(np.arange(0, 51, 1), 'skill')
    academic = ctrl.Antecedent(np.arange(0, 101, 1), 'academic')
    sucsratio = ctrl.Consequent(np.arange(0, 101, 1), 'success')

    # Custom membership functions can be built interactively with a familiar,
    # Pythonic API
    # Generate trapezoidal fuzzy membership functions
    skill['poor'] = fuzz.trapmf(skill.universe,
                                [0, 0, 15, 17])  # skill weak[0-17]
    skill['average'] = fuzz.trapmf(skill.universe,
                                   [17, 20, 30, 37])  # skill medium[17-37]
    skill['good'] = fuzz.trapmf(skill.universe,
                                [35, 37, 50, 50])  # skill good[35-50]

    # Generate trapezoidal fuzzy membership functions
    academic['poor'] = fuzz.trapmf(academic.universe,
                                   [0, 0, 40, 45])  # academic score weak[0-45]
    academic['average'] = fuzz.trapmf(
        academic.universe, [40, 45, 65, 70])  # academic score medium[40-70]
    academic['good'] = fuzz.trapmf(
        academic.universe, [65, 70, 100, 100])  # academic score good[65-100]

    # Generate trapezoidal fuzzy membership functions
    sucsratio['low'] = fuzz.trapmf(sucsratio.universe,
                                   [0, 0, 30, 35])  # academic score weak[0-35]
    sucsratio['medium'] = fuzz.trapmf(
        sucsratio.universe, [33, 35, 60, 70])  # academic score medium[33-70]
    sucsratio['high'] = fuzz.trapmf(
        sucsratio.universe,
        [65, 70, 100, 100])  # academic score medium[65-100]

    # You can see how these look with .view()
    #skill.view()
    #   plt.savefig("Graphs/Skill_MF.pdf")  # to save figue in to PDF format
    #  plt.savefig("Graphs/Skill_MF.png")  # to save figue in to PNG format

    # You can see how these look with .view()
    #academic.view()
    #  plt.savefig("Graphs/Academic_MF.pdf")  # to save figue in to PDF format
    #  plt.savefig("Graphs/Academic_MF.png")  # to save figue in to PNG format

    # You can see how these look with .view()
    # sucsratio.view()
    # plt.savefig("Graphs/Success_rate_MF.pdf")  # to save figue in to PDF format
    # plt.savefig("Graphs/Succeess_rate_MF.png")  # to save figue in to PNG format

    # Fuzzy rules
    rule1 = ctrl.Rule(academic['good'] & skill['good'], sucsratio['high'])
    rule2 = ctrl.Rule(academic['good'] & skill['average'], sucsratio['high'])
    rule3 = ctrl.Rule(academic['average'] & skill['average'],
                      sucsratio['medium'])
    rule4 = ctrl.Rule(academic['average'] & skill['good'], sucsratio['medium'])
    rule5 = ctrl.Rule(academic['poor'] | skill['poor'], sucsratio['low'])

    # Control System Creation and Simulation
    # Now that we have our rules defined, we can simply create a control system
    sucs_rate_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5])
    """
    In order to simulate this control system, we will create a
        "ControlSystemSimulation" :  Think of this object representing our controller applied to a specific set of cirucmstances.  
    """
    sucs_rate_final = ctrl.ControlSystemSimulation(sucs_rate_ctrl)
    """
    We can now simulate our control system by simply specifying the inputs
    and calling the ``compute`` method.
    """
    # Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
    # Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
    sucs_rate_final.input['academic'] = sb
    sucs_rate_final.input['skill'] = sk

    # Crunch the numbers
    sucs_rate_final.compute()
    ans = round(sucs_rate_final.output['success'], 4)
    # view results and print results
    print("Success Rate:", ans)
    update_scs_rate(ans, crf)
Esempio n. 21
0
def sistema(input_altitude_real: int, input_altitude_relativa: int,
            metodo_defuzz: str, graficos: bool) -> float:
    """
    O sistema inteiro foi contido em uma função para facilitar sua reutilização,
    necessitando apenas dos dados de entrada essenciais
    """

    # Variáveis de entrada abstraídas a partir das caracterísitcas e necessidades
    # da aeronave
    altitude_real = control.Antecedent(numpy.arange(0, 1000, 1),
                                       "altitude_real")
    altitude_relativa = control.Antecedent(numpy.arange(0, 1000, 1),
                                           "altitude_relativa")

    # Variável de saída para controle dos equipamentos da aeronave
    velocidade = control.Consequent(numpy.arange(0, 100, 1),
                                    "velocidade",
                                    defuzzify_method=metodo_defuzz)

    # Não utilizada devido à ausência de asa em quadrimotores
    # angulo_asa = control.Antecedent(numpy.arange(0, 90, 0.1), "angulo_asa")

    # Interpretação da variável de altitude real da aeronave
    # Essa variavel representa a altitude do veículo em relação ao nível do mar
    altitude_real["baixa"] = skfuzzy.trimf(altitude_real.universe, [0, 0, 250])
    altitude_real["media"] = skfuzzy.trapmf(altitude_real.universe,
                                            [200, 250, 500, 550])
    altitude_real["alta"] = skfuzzy.trimf(altitude_real.universe,
                                          [500, 600, 700])
    altitude_real["muito_alta"] = skfuzzy.trimf(altitude_real.universe,
                                                [650, 1000, 1000])

    # Interpretação da variável de altitude relativa da aeronave
    # Essa variavel representa a altitude do veículo em relção ao solo diretamente abaixo
    altitude_relativa["baixa"] = skfuzzy.trimf(altitude_real.universe,
                                               [0, 0, 200])
    altitude_relativa["media"] = skfuzzy.trapmf(altitude_real.universe,
                                                [150, 300, 500, 550])
    altitude_relativa["alta"] = skfuzzy.trimf(altitude_real.universe,
                                              [500, 1000, 1000])

    # Interpretação da variável de velocidade dos motores da aeronave
    velocidade["baixa"] = skfuzzy.trimf(velocidade.universe, [0, 0, 50])
    velocidade["media"] = skfuzzy.trimf(velocidade.universe, [25, 50, 75])
    velocidade["alta"] = skfuzzy.trimf(velocidade.universe, [75, 100, 100])

    # Regras para o controle de velocidade a partir das medições de altitude
    # Conjunto 1 - Tratando das condições de baixa e média altitudes reais
    regra_1 = control.Rule(
        altitude_relativa["baixa"] &
        (altitude_real["baixa"] | altitude_real["media"]), velocidade["alta"])
    regra_2 = control.Rule(
        altitude_relativa["media"] &
        (altitude_real["baixa"] | altitude_real["media"]), velocidade["media"])
    regra_3 = control.Rule(
        altitude_relativa["alta"] &
        (altitude_real["baixa"] | altitude_real["media"]
         | altitude_real["alta"]), velocidade["baixa"])
    # Conjunto 2 - Tratando das condições de alta altitude real
    regra_4 = control.Rule(altitude_relativa["baixa"] & altitude_real["alta"],
                           velocidade["media"])
    regra_5 = control.Rule(altitude_relativa["media"] & altitude_real["alta"],
                           velocidade["media"])
    # Conjunto 3 - Tratando das condições de altitude real muito alta
    regra_6 = control.Rule(
        altitude_relativa["baixa"] & altitude_real["muito_alta"],
        velocidade["baixa"])
    regra_7 = control.Rule(
        altitude_relativa["media"] & altitude_real["muito_alta"],
        velocidade["baixa"])

    # Construindo o sistema de regras
    controle_velocidade = control.ControlSystem(
        [regra_1, regra_2, regra_3, regra_4, regra_5, regra_6, regra_7])
    simulacao_velocidade = control.ControlSystemSimulation(controle_velocidade)

    # Inserção dos valores de entrada a serem processados
    simulacao_velocidade.input["altitude_real"] = input_altitude_real
    simulacao_velocidade.input["altitude_relativa"] = input_altitude_relativa

    # Realizando computação do modelo construído
    simulacao_velocidade.compute()

    # Exibição dos gráficos de entrada e saída do modelo Fuzzy
    if graficos:
        altitude_real.view()
        altitude_relativa.view()
        velocidade.view()
        velocidade.view(sim=simulacao_velocidade)

    return simulacao_velocidade.output["velocidade"]
Esempio n. 22
0
    click=clicks3x3[i]
    time=time3x3[i]
    avgclick=time/click
    list2=list()
    list2.append(0.0)
   # list3=np.array(sp.random.uniform(mindif,avgclick,(click-2)))
   # print(list3)
    for j in range(0,click-2):
        rand=np.random.uniform(j*avgclick,(j+1)*avgclick)
        list2.append(rand)
    list2.append(time)
    print(list2)
    
#fuzzy
time=ctrl.Antecedent(np.arange(30,70,1),'time')
iq=ctrl.Consequent(np.arange(70,200,1),'iq')

time.automf(5)
time.view()

iq['normal']=fuzz.gaussmf(iq.universe,115,4)
iq['superior']=fuzz.gaussmf(iq.universe,130,4)
iq['very superior']=fuzz.gaussmf(iq.universe,145,4)
iq['dullness']=fuzz.gaussmf(iq.universe,85,4)
iq['mensa level']=fuzz.gaussmf(iq.universe,200,4)

iq.view()
rule1=ctrl.Rule(time['poor'],iq['mensa level'])
rule2=ctrl.Rule(time['mediocre'],iq['very superior'])
rule3=ctrl.Rule(time['average'],iq['superior'])
rule4=ctrl.Rule(time['decent'],iq['normal'])
Esempio n. 23
0
    def __init__(self):
        evoparation = ctrl.Antecedent(
            np.arange(0, 15, 0.2),
            'evoparation')  # chia độ bốc hơi từ 0-15 với khoảng cách 0.1
        humidity = ctrl.Antecedent(
            np.arange(0, 100, 0.2),
            'humidity')  # chia độ ẩm từ 0-100(%) với khoảng cách 0.2
        pressure = ctrl.Antecedent(
            np.arange(990, 1030, 0.1), 'pressure'
        )  # chia áp suất từ 990-1020(.10^2 Pa) với khoảng cách 0.1
        cloud = ctrl.Antecedent(np.arange(0, 8, 1),
                                'cloud')  # chia mây từ 0-8 với khoảng cách 1
        temp = ctrl.Antecedent(
            np.arange(15, 40, 0.1),
            'temp')  # chia nhiệt độ từ 15-38(độ C) với khoảng cách 0.1
        rainfall = ctrl.Consequent(
            np.arange(0, 120, 0.2),
            'rainfall')  # chia lượng mưa từ 0-120(mm) với khoảng cách 0.2

        evoparation['low'] = fz.trapmf(
            evoparation.universe, [0, 0, 3, 4])  # độ bốc hơi thấp => mưa nhiều
        evoparation['medium'] = fz.trapmf(evoparation.universe,
                                          [3.4, 4, 7, 10])
        evoparation['high'] = fz.trapmf(
            evoparation.universe,
            [8, 12, 15, 15])  # độ bốc hơi quá cao => mưa nhiều

        humidity['low'] = fz.trapmf(humidity.universe, [0, 0, 60, 75])
        humidity['high'] = fz.trapmf(humidity.universe,
                                     [65, 80, 100, 100])  # độ ẩm cao mưa nhiều

        pressure['low'] = fz.trapmf(
            pressure.universe,
            [990, 990, 1009, 1012])  # áp suất thấp mưa nhiều
        pressure['high'] = fz.trapmf(pressure.universe,
                                     [1009, 1012, 1030, 1030])

        cloud['low'] = fz.trapmf(cloud.universe, [0, 0, 5, 7])
        cloud['high'] = fz.trapmf(cloud.universe,
                                  [6, 7, 8, 8])  # nhiều mây mưa nhiều

        temp['low'] = fz.trapmf(temp.universe, [15, 15, 20, 24.2])
        temp['medium'] = fz.trapmf(
            temp.universe, [23, 25, 29, 32])  # nhiệt độ TB thì mưa cao hơn
        temp['high'] = fz.trapmf(temp.universe, [28.5, 35, 40, 40])

        rainfall['very_low'] = fz.trapmf(rainfall.universe,
                                         [0, 0, 2, 4])  # không mưa
        rainfall['low'] = fz.trapmf(rainfall.universe, [3, 5, 8, 12])  # mưa ít
        rainfall['medium'] = fz.trapmf(rainfall.universe, [10, 15, 35, 40])
        rainfall['high'] = fz.trapmf(rainfall.universe,
                                     [35, 45, 120, 120])  # mưa nhiều

        rules = [
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi thấp
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ thấp
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['low'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi TB
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ thấp
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['low'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi cao
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ thấp
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['low'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi thấp
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ TB
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['low']),
            ctrl.Rule(
                evoparation['low'] & temp['medium'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['medium']),
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi TB
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ TB
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['low']),
            ctrl.Rule(
                evoparation['medium'] & temp['medium'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi cao
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ TB
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['low']),
            ctrl.Rule(
                evoparation['high'] & temp['medium'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['high']),
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi thấp
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ cao
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['low'] & temp['high'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi TB
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ cao
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['medium'] & temp['high'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['low']),
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['low']
                & pressure['high'] & cloud['low'],
                rainfall['very_low']),  # tại bốc hơi cao
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['low']
                & pressure['high'] & cloud['high'],
                rainfall['very_low']),  # nhiệt độ cao
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['low']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['low']
                & pressure['low'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['high']
                & pressure['high'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['high']
                & pressure['high'] & cloud['high'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['high']
                & pressure['low'] & cloud['low'], rainfall['very_low']),
            ctrl.Rule(
                evoparation['high'] & temp['high'] & humidity['high']
                & pressure['low'] & cloud['high'], rainfall['low']),
        ]

        CT = ctrl.ControlSystem(rules)
        self.Defz = ctrl.ControlSystemSimulation(CT)
Esempio n. 24
0
def run_fuzzy_system(tightness, aggressiveness, money_opponent, money_player,
                     probability_hand):
    # Compute risk aversion opponent
    # Input: tightness and aggressiveness of the opponent
    # Output: risk aversive behavior of the opponent
    tight = np.arange(0, 1, 0.1)
    x_aggress = np.arange(0, 1, 0.1)
    x_risk_av = np.arange(0, 1, 0.1)
    # Risk = [tight, x_aggress, x_risk_av]
    # risk_members = compute_memberships(Risk, [0, 0.5, 1])
    # aversion, risk0, aggregated= fuzzy_inference(Risk, tightness, aggressiveness, risk_members, "risk")
    # titles = ["Tightness opponent", "Aggressiveness opponent", "Risk aversive behavior"]

    # Compute optimal strategy player
    # Input: quality cards opponent and odds player
    # Ouput: indication of optimal strategy for player
    aggressiveness_opponent = ctrl.Antecedent(np.arange(0, 1.1, 0.1),
                                              'aggressiveness')
    aggressiveness_opponent['low'] = fuzz.trimf(
        aggressiveness_opponent.universe, [0, 0, 0.5])
    aggressiveness_opponent['medium'] = fuzz.trimf(
        aggressiveness_opponent.universe, [0, 0.5, 1])
    aggressiveness_opponent['high'] = fuzz.trimf(
        aggressiveness_opponent.universe, [0.5, 1, 1])
    tightness_opponent = ctrl.Antecedent(np.arange(0, 1.1, 0.1),
                                         'tightness_opponent')
    tightness_opponent['low'] = fuzz.trimf(tightness_opponent.universe,
                                           [0, 0, 0.5])
    tightness_opponent['medium'] = fuzz.trimf(tightness_opponent.universe,
                                              [0, 0.5, 1])
    tightness_opponent['high'] = fuzz.trimf(tightness_opponent.universe,
                                            [0.5, 1, 1])
    risk_aversion = ctrl.Consequent(np.arange(0, 1.1, 0.1), 'risk_aversion')
    risk_aversion['low'] = fuzz.trimf(risk_aversion.universe, [0, 0, 0.5])
    risk_aversion['medium'] = fuzz.trimf(risk_aversion.universe, [0, 0.5, 1])
    risk_aversion['high'] = fuzz.trimf(risk_aversion.universe, [0.5, 1, 1])

    rules = []

    rules.append(
        ctrl.Rule(tightness_opponent['low'] & aggressiveness_opponent['low'],
                  risk_aversion['medium']))
    rules.append(
        ctrl.Rule(
            tightness_opponent['low'] & aggressiveness_opponent['medium'],
            risk_aversion['low']))
    rules.append(
        ctrl.Rule(tightness_opponent['low'] & aggressiveness_opponent['high'],
                  risk_aversion['low']))
    rules.append(
        ctrl.Rule(
            tightness_opponent['medium'] & aggressiveness_opponent['low'],
            risk_aversion['high']))
    rules.append(
        ctrl.Rule(
            tightness_opponent['medium'] & aggressiveness_opponent['medium'],
            risk_aversion['medium']))
    rules.append(
        ctrl.Rule(
            tightness_opponent['medium'] & aggressiveness_opponent['high'],
            risk_aversion['low']))
    rules.append(
        ctrl.Rule(tightness_opponent['high'] & aggressiveness_opponent['low'],
                  risk_aversion['high']))
    rules.append(
        ctrl.Rule(
            tightness_opponent['high'] & aggressiveness_opponent['medium'],
            risk_aversion['high']))
    rules.append(
        ctrl.Rule(tightness_opponent['high'] & aggressiveness_opponent['high'],
                  risk_aversion['medium']))

    aversion_ctrl = ctrl.ControlSystem(rules)
    risk_averse = ctrl.ControlSystemSimulation(aversion_ctrl)
    risk_averse.input['aggressiveness'] = aggressiveness
    risk_averse.input['tightness_opponent'] = tightness

    risk_averse.compute()

    aversion = risk_averse.output['risk_aversion']

    # Compute quality cards opponent
    # Input: risk aversive behavior and money left opponent
    # Output: estimation of the quality of the cards of opponent
    x_left_opponent = np.arange(0, 1, 0.1)
    x_quality = np.arange(0, 1, 0.1)
    Quality = [x_risk_av, x_left_opponent, x_quality]
    quality_members = compute_memberships(Quality, [0, 0.5, 1])
    quality_cards_opponent_out, risk0, aggregated = fuzzy_inference(
        Quality, aversion, money_opponent, quality_members, "quality")
    titles = [
        "Risk aversion opponent", "Money left opponent ",
        "Quality cards opponent"
    ]
    #visualize_memberships(Quality, quality_members[0], quality_members[1], quality_members[2], titles)
    #visualize_result(Quality, quality_members[2], risk0, aggregated, quality_cards_opponent)
    # print("quality", quality_cards_opponent_out)

    # # Compute odds player
    # # Input: probability hand of hand player and money left player
    # # Ouput: estimation of how good the players chances are
    # probability= np.arange(0, 1, 0.1)
    # money_left_player = np.arange(0, 1, 0.1)
    # player_odds = np.arange(0, 1, 0.1)
    # Odds = [probability, money_left_player, player_odds ]
    # odds_members = compute_memberships(Odds, [0, 0.5, 1])
    # odds_player_out, risk0, aggregated = fuzzy_inference(Odds, probability_hand, money_player, odds_members, "odds")
    # titles = ["Probability hand", "Money left player", "Odds player"]
    # #visualize_memberships(Odds, odds_members[0], odds_members[1], odds_members[2], titles)
    # #visualize_result(Odds, odds_members[2], risk0, aggregated, odds_player)
    # # print("odds", odds_player_out)

    # Compute optimal strategy player
    # Input: quality cards opponent and odds player and aggressiveness_opponent
    # Ouput: indication of optimal strategy for player
    quality_cards_opponent = ctrl.Antecedent(np.arange(0, 1.1, 0.1),
                                             'quality_cards_opponent')
    quality_cards_opponent['low'] = fuzz.trimf(quality_cards_opponent.universe,
                                               [0, 0, 0.5])
    quality_cards_opponent['medium'] = fuzz.trimf(
        quality_cards_opponent.universe, [0, 0.5, 1])
    quality_cards_opponent['high'] = fuzz.trimf(
        quality_cards_opponent.universe, [0.5, 1, 1])
    odds_player = ctrl.Antecedent(np.arange(0, 1.1, 0.1), 'odds_player')
    odds_player['low'] = fuzz.trimf(odds_player.universe, [0, 0, 0.5])
    odds_player['medium'] = fuzz.trimf(odds_player.universe, [0, 0.5, 1])
    odds_player['high'] = fuzz.trimf(odds_player.universe, [0.5, 1, 1])
    strategy_optimal = ctrl.Consequent(np.arange(0, 1.1, 0.1),
                                       'strategy_optimal')
    strategy_optimal['fold'] = fuzz.trimf(strategy_optimal.universe,
                                          [0, 0, 0.5])
    strategy_optimal['call'] = fuzz.trimf(strategy_optimal.universe,
                                          [0, 0.5, 1])
    strategy_optimal['raise'] = fuzz.trimf(strategy_optimal.universe,
                                           [0.5, 1, 1])

    rules = []

    rules.append(
        ctrl.Rule(
            odds_player['low'] & quality_cards_opponent['low']
            & aggressiveness_opponent['low'], strategy_optimal['call']))
    rules.append(
        ctrl.Rule(
            odds_player['low'] & quality_cards_opponent['low']
            & aggressiveness_opponent['medium'], strategy_optimal['call']))
    rules.append(
        ctrl.Rule(
            odds_player['low'] & quality_cards_opponent['low']
            & aggressiveness_opponent['high'], strategy_optimal['raise']))
    rules.append(
        ctrl.Rule(odds_player['low'] & quality_cards_opponent['medium'],
                  strategy_optimal['fold']))
    rules.append(
        ctrl.Rule(odds_player['low'] & quality_cards_opponent['high'],
                  strategy_optimal['fold']))
    rules.append(
        ctrl.Rule(odds_player['medium'] & quality_cards_opponent['low'],
                  strategy_optimal['call']))
    rules.append(
        ctrl.Rule(odds_player['medium'] & quality_cards_opponent['medium'],
                  strategy_optimal['raise']))
    rules.append(
        ctrl.Rule(odds_player['medium'] & quality_cards_opponent['high'],
                  strategy_optimal['fold']))
    rules.append(
        ctrl.Rule(odds_player['high'] & quality_cards_opponent['low'],
                  strategy_optimal['call']))
    rules.append(
        ctrl.Rule(odds_player['high'] & quality_cards_opponent['medium'],
                  strategy_optimal['raise']))
    rules.append(
        ctrl.Rule(odds_player['high'] & quality_cards_opponent['high'],
                  strategy_optimal['raise']))
    rules.append(
        ctrl.Rule(
            odds_player['high'] & quality_cards_opponent['low']
            & aggressiveness_opponent['high'], strategy_optimal['raise']))
    rules.append(
        ctrl.Rule(
            odds_player['high'] & quality_cards_opponent['medium']
            & aggressiveness_opponent['high'], strategy_optimal['raise']))
    rules.append(
        ctrl.Rule(
            odds_player['high'] & quality_cards_opponent['high']
            & aggressiveness_opponent['high'], strategy_optimal['raise']))
    rules.append(ctrl.Rule(odds_player['low'], strategy_optimal['raise']))

    strategy_ctrl = ctrl.ControlSystem(rules)
    strategize = ctrl.ControlSystemSimulation(strategy_ctrl)
    strategize.input['aggressiveness'] = aggressiveness
    strategize.input['odds_player'] = probability_hand
    strategize.input['quality_cards_opponent'] = quality_cards_opponent_out

    strategize.compute()

    optimal = strategize.output['strategy_optimal']

    # strategy_optimal.view(sim=strategize)

    optimal = get_move_and_degree(optimal, strategy_optimal.universe)

    return optimal
Esempio n. 25
0
# Scaling champions stats to 0.0-1.0


for i, max_stat in enumerate(max_stats_list):
    df[df.columns[i + 1]] = df[df.columns[i + 1]] / max_stat
    print(df[df.columns[i + 1]])
    print("The end of this stat")


hp_fuzzy = ctrl.Antecedent(np.arange(0, 1.01, 0.01), "hp_fuzzy")


mean_hp_fuzzy = ctrl.Antecedent(np.arange(0, 1.01, 0.01), "mean_hp_fuzzy")


points_fuzzy = ctrl.Consequent(np.arange(0, 1.01, 0.01), "points_fuzzy")


hp_fuzzy["poor"] = fuzz.gbellmf(hp_fuzzy.universe, 0.025, 0.95, 0.2)
hp_fuzzy["mediocre"] = fuzz.gbellmf(hp_fuzzy.universe, 0.025, 0.95, 0.4)
hp_fuzzy["average"] = fuzz.gbellmf(hp_fuzzy.universe, 0.025, 0.95, 0.6)
hp_fuzzy["decent"] = fuzz.gbellmf(hp_fuzzy.universe, 0.025, 0.95, 0.8)
hp_fuzzy["good"] = fuzz.gbellmf(hp_fuzzy.universe, 0.025, 0.95, 1.0)


mean_hp_fuzzy["poor"] = fuzz.gbellmf(mean_hp_fuzzy.universe, 0.025, 0.95, 0.2)
mean_hp_fuzzy["mediocre"] = fuzz.gbellmf(mean_hp_fuzzy.universe, 0.025, 0.95, 0.4)
mean_hp_fuzzy["average"] = fuzz.gbellmf(mean_hp_fuzzy.universe, 0.025, 0.95, 0.6)
mean_hp_fuzzy["decent"] = fuzz.gbellmf(mean_hp_fuzzy.universe, 0.025, 0.95, 0.8)
mean_hp_fuzzy["good"] = fuzz.gbellmf(mean_hp_fuzzy.universe, 0.025, 0.95, 1.0)
Esempio n. 26
0
# --------------------------------------------------------
# Sistema fuzzy exemplo
# Controle de velocidade baseado na leitura da distancia
# --------------------------------------------------------
import skfuzzy as fuzzy
import numpy as np
from skfuzzy import control as ctrl

# --------------------------------------------------------
# Definição dos conjuntos universo (entrada e saída)
# --------------------------------------------------------
distancia = ctrl.Antecedent(np.arange(0, 80, 1), 'Distancia')
velocidade = ctrl.Consequent(np.arange(0, 255, 1), 'Velocidade')

# --------------------------------------------------------
# Definição dos conjuntos fuzzy
# --------------------------------------------------------
distancia['Perto'] = fuzzy.trimf(distancia.universe, [0, 10, 20])
distancia['Longe'] = fuzzy.trimf(distancia.universe, [18, 30, 50])
distancia['Muito longe'] = fuzzy.trimf(distancia.universe, [48, 60, 85])

# Mostrar gráfico da distancia
distancia.view()

velocidade['Lento'] = fuzzy.trimf(velocidade.universe, [0, 100, 150])
velocidade['Rapido'] = fuzzy.trimf(velocidade.universe, [140, 170, 190])
velocidade['Muito rapido'] = fuzzy.trimf(velocidade.universe, [180, 220, 255])

# Mostrar gráfico da velocidade
velocidade.view()
Esempio n. 27
0
from skfuzzy import control as ctrl
import csv

#s = input("Enter Speed:(-1 to leave Open):" )
#h = input("Enter Hardness:(-1 to leave Open):" )
#w = input("Enter Width:(-1 to leave Open):" )
#f = input("Enter Feed:(-1 to leave Open):" )
#Input Variables
speed = ctrl.Antecedent(np.arange(1, 100, 1), 'speed')
hardness = ctrl.Antecedent(np.arange(30, 40, 1), 'hardness')
width = ctrl.Antecedent(np.arange(0.05, 0.20, 0.01), 'width')
feed = ctrl.Antecedent(np.arange(1, 5, 1), 'feed')
amr = ctrl.Antecedent(np.arange(0, 5000, 50), 'amr')

#Output Variables
energy = ctrl.Consequent(np.arange(0, 500, 5), 'energy')
scenergy = ctrl.Consequent(np.arange(0, 10, 0.1), 'scenergy')
mrr = ctrl.Consequent(np.arange(0, 1000, 5), 'mrr')
vb = ctrl.Consequent(np.arange(0, 0.2, 0.0005), 'vb')
vb3 = ctrl.Consequent(np.arange(0, 0.2, 0.0005), 'vb3')
avgstatcutforce = ctrl.Consequent(np.arange(0, 1500, 10), 'avgstatcutforce')
avgdynfeedforce = ctrl.Consequent(np.arange(0, 1300, 10), 'avgdynfeedforce')

#input fuzzysets
#speed
speed['slow'] = fuzz.trapmf(speed.universe, [1, 1, 28, 57])
speed['medium'] = fuzz.trimf(speed.universe, [28, 57, 89])
speed['fast'] = fuzz.trapmf(speed.universe, [57, 89, 100, 100])
#feed
feed['small'] = fuzz.trapmf(feed.universe, [0.05, 0.05, 0.07, 0.12])
feed['medium'] = fuzz.trimf(feed.universe, [0.07, 0.12, 0.17])
Esempio n. 28
0
HBeAg['POSITIVA'] = fuzz.trimf(HBeAg.universe, [0.65, 0.8, 1.2])

Anti_HBeAg=  ctrl.Antecedent(np.arange(0, 1.51, 0.01),'Anti_HBeAg')

Anti_HBeAg['POSITIVA'] = fuzz.trimf(Anti_HBeAg.universe, [0, 0.4, 0.85])
Anti_HBeAg['NEGATIVA'] = fuzz.trimf(Anti_HBeAg.universe, [0.75, 1.1, 1.5])

HBV_DNA=  ctrl.Antecedent(np.arange(0, 20.5, 0.5),'HBV_DNA')

HBV_DNA['NEGATIVA'] = fuzz.trimf(HBV_DNA.universe, [0, 5.5, 10.5])
HBV_DNA['POSITIVA'] = fuzz.trimf(HBV_DNA.universe, [9.5, 15.5, 20])


#consecuentes

DBH = ctrl.Consequent(np.arange(0, 1.01, 0.01), 'DBH')

DBH['NO HEPATITIS'] = fuzz.trimf(DBH.universe, [0, 0, 0.25])
DBH['HEPATITIS AGUDA'] = fuzz.trimf(DBH.universe, [0, 0.25, 0.5])
DBH['HEPATITIS CRONICA'] = fuzz.trimf(DBH.universe, [0.25, 0.5, 0.75])
DBH['INMUNIDAD POR VACUNACION'] = fuzz.trimf(DBH.universe, [0.5, 0.75,1])
DBH['INMUNIDAD POR INFECCION ANTERIOR'] = fuzz.trimf(DBH.universe, [0.75, 1, 1])

#Pintar los antecedentes

AST.view()
ALT.view()
HBsAg.view()
Anti_HBsAg.view()
Anti_HBcAg.view()
Anti_HBcAg_IgM.view()
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import Node611
import excel
import mcpras
import time

#Fuzzy Controller

Vrefd = ctrl.Consequent(np.arange(-2, 2, 0.1), 'Vrefd')
Pdif = ctrl.Antecedent(np.arange(-200, 200, 0.01), 'Pdif')

#Membership functions

#Pdif

Pdif['N'] = fuzz.trapmf(Pdif.universe, [-100, -2, -0.2, -0.01])
Pdif['P'] = fuzz.trapmf(Pdif.universe, [0.01, 0.2, 2, 100])
Pdif['Z'] = fuzz.trimf(Pdif.universe, [-0.01, 0, 0.01])

#Vref

Vrefd['N'] = fuzz.trimf(Vrefd.universe, [-0.2, -0.1, 0])
Vrefd['P'] = fuzz.trimf(Vrefd.universe, [0, 0.1, 0.2])
Vrefd['Z'] = fuzz.trimf(Vrefd.universe, [-0.01, 0, 0.01])

##Rules

rule1 = ctrl.Rule(Pdif['P'], Vrefd['P'])
rule2 = ctrl.Rule(Pdif['N'], Vrefd['N'])
Esempio n. 30
0
    def adjustment_ctrl(self, new_state, status, latency, servers, ram,
                        memory):
        ram_state = int(ram)
        print("RAM STATE (ram):" + str(ram_state))
        #The reward calculation is based on scoring the previous action with the reward of the new state, also I should take into consideration all the moments that there is no new regard to add then to the reward
        print("Reinforcement Learning Fine Tunning")
        if self.step == 0:
            #Copy previous value of self not the pointer!!!!
            self.last_action = [[[self.array_ram_lo], [self.array_ram_med],
                                 [self.array_ram_hi]], new_state]
            print(self.last_action)
            self.step += 1
        else:

            print(self.last_action)

            #Reward Calculus
            value_reward = 0
            #I have to consider also minimum RAM and CPU allocated gives maximum reward
            if status >= 500:
                value_reward -= status
            elif status >= 200 and status < 300:
                value_reward += 200
            value_reward += (-ram + 400) * 2  #None
            value_reward += (100 if servers == 1 else 0)
            value_reward += int(-(latency * 10) + 200)
            temp = (300 - np.abs(70 - memory) * (30 if memory > 70 else 30))
            ref = ((memory - 70) / 20 if memory > 70 else
                   (memory - 70) / 50)  #50
            value_reward += temp
            self.reward = value_reward  #+randint(-25,25)#Adding to reward for testing proposes
            print("################")
            file.write(
                str(status) + "," + str((-ram + 400) * 4) + "," +
                str((100 if servers == 1 else 0)) + "," +
                str(int(-latency + 200)) + "," + str(self.reward) + "\n")
            print("RAM Value:" + str(ram))
            print("Reward RAM: " + str((-ram + 400) * 4))
            print("Reward Latency: " + str(int(-latency + 200)))
            print("Reward Memory: " + str(300 - (np.abs(70 - memory) *
                                                 (30 if memory > 70 else 4))))
            print("################")

            self.step += 1

            if 1:  #self.step==2:

                #self.step=0

                #State is a number from 0 to 2 referencing to the possible action taken
                #Instead of taking into consideration the rule, I take into consideration the action every time that is performed as each action should be possible

                #Aggregation of overall reward after action
                #rewards=np.median(self.reward)
                rewards = self.reward

                #Action
                array_parameters_actions = self.last_action[0]
                state = self.last_action[1]
                action = [array_parameters_actions[state], servers]
                #Look for used action
                actions_table = [e[0] == action for e in self.q[state]]
                actions_table_1 = [
                    e[0] == [array_parameters_actions[1], servers]
                    for e in self.q[1]
                ]
                actions_table_0 = [
                    e[0] == [array_parameters_actions[0], servers]
                    for e in self.q[0]
                ]
                actions_table_2 = [
                    e[0] == [array_parameters_actions[2], servers]
                    for e in self.q[2]
                ]
                if any(actions_table):
                    #Update reward
                    self.q[state][actions_table.index(True)][1] = np.median(
                        [self.q[state][actions_table.index(True)][1], rewards])
                else:
                    #Create new state with new reward
                    #print("Table")
                    #print(self.q[state])
                    (self.q[state]).append([action, rewards])

                if self.increase >= 10:
                    if any(actions_table_1):
                        #Update reward
                        self.q[1][actions_table_1.index(True)][1] = np.median([
                            self.q[1][actions_table_1.index(True)][1], rewards
                        ])
                    else:
                        #Create new state with new reward
                        #print("Table")
                        #print(self.q[state])
                        (self.q[1]).append(
                            [[array_parameters_actions[1], servers], rewards])

                if self.increase_state0 >= 10:
                    if any(actions_table_0):
                        #Update reward
                        self.q[0][actions_table_0.index(True)][1] = np.median([
                            self.q[0][actions_table_0.index(True)][1], rewards
                        ])
                    else:
                        #Create new state with new reward
                        #print("Table")
                        #print(self.q[state])
                        (self.q[0]).append(
                            [[array_parameters_actions[0], servers], rewards])

                    if any(actions_table_2):
                        #Update reward
                        self.q[2][actions_table_2.index(True)][1] = np.median([
                            self.q[2][actions_table_2.index(True)][1], rewards
                        ])
                    else:
                        #Create new state with new reward
                        #print("Table")
                        #print(self.q[state])
                        (self.q[2]).append(
                            [[array_parameters_actions[2], servers], rewards])

                print("Previous State Comprobation: " + str(state))
                #Based on overrall performance on the Q table pick the best seed and update the system
                position_reward = -1
                #For loop best performance
                factor = 1.2
                state_base = int(state)
                #state=0
                if state == 0:
                    self.increase += 1
                    self.increase_state0 = 0
                    print("Update State 0")
                    if len(self.q[state]) < 3:
                        print("IN-RANDOM 5" if (len(self.q[state]) %
                                                5 == 0) else "")
                        print("Random Search")
                        if new_state != 4:
                            self.array_ram_lo = [
                                99, 150 + randint(-50, 50), 200
                            ]
                        else:
                            print("Random Search on Neutral")
                            self.array_ram_hi = [
                                100, 150 + randint(-45, 45), 200
                            ]
                    else:
                        print("Random Optimizer based on Reward")

                        highest_reward = 0
                        position_reward = 0
                        for enum, rew_state in enumerate(self.q[state]):
                            if enum == 0:
                                highest_reward = rew_state[1] * (enum / len(
                                    self.q[state]) if enum > 15 else 1)

                            else:
                                if highest_reward < rew_state[1]:
                                    highest_reward = rew_state[1] * (
                                        enum /
                                        len(self.q[state]) if enum > 15 else 1)
                                    position_reward = enum
                        if (self.step % 100 != 0):
                            #discount=(1 if float(len(self.q[state]))/float(factor)<=1 else float(len(self.q[state]))/float(factor))

                            #if new_state!=4:
                            #State Modify
                            #self.array_ram_lo=[self.q[state][position_reward][0][0][0][0]+randint(int(-10)+int(50*ref),int(10)+int(50*ref)),self.q[state][position_reward][0][0][0][1]+(50*ref),self.q[state][position_reward][0][0][0][2]+int(50*ref)]
                            self.array_ram_lo = [
                                self.q[state][position_reward][0][0][0][0],
                                self.q[state][position_reward][0][0][0][1] +
                                randint(
                                    int(-10) + int(50 * ref),
                                    int(10) + int(50 * ref)),
                                self.q[state][position_reward][0][0][0][2]
                            ]

                            if self.increase > 10:
                                #print("Decreasing")
                                #print(len(self.q[1]))
                                #print(self.q[1])
                                for enum, rew_state in enumerate(self.q[1]):
                                    if enum == 0:
                                        highest_reward = rew_state[1] * (
                                            enum / len(self.q[1])
                                            if enum > 15 else 1)  #Memory lose
                                        position_reward = 0

                                    else:
                                        #print(rew_state[1])
                                        if highest_reward < rew_state[1]:
                                            highest_reward = rew_state[1] * (
                                                enum / len(self.q[1]) if enum >
                                                15 else 1)  # Memory lose
                                            position_reward = enum
                                #print(self.q[1][position_reward][0][0][0][0])
                                self.array_ram_med = [
                                    self.q[1][position_reward][0][0][0][0],
                                    self.q[1][position_reward][0][0][0][1] +
                                    randint(-10 + int(50 * ref),
                                            10 + int(50 * ref)),
                                    self.q[1][position_reward][0][0][0][2]
                                ]

                #state=1
                elif state == 1:
                    self.increase = 0
                    self.increase_state0 += 1
                    print("Update State 1")
                    if len(self.q[state]) < 3:
                        print("IN-RANDOM 5" if (len(self.q[state]) %
                                                5 == 0) else "")
                        print("Random Search")
                        if new_state != 4:
                            self.array_ram_med = [
                                200, 250 + randint(-50, 50), 300
                            ]
                        else:
                            print("Random Search on Neutral")
                            self.array_ram_hi = [
                                200, 250 + randint(-45, 45), 300
                            ]
                    else:
                        print("///////////////")
                        print("Random Optimizer based on Reward 1")
                        highest_reward = 0
                        position_reward = 0

                        print("Reward")
                        for enum, rew_state in enumerate(self.q[state]):
                            if enum == 0:
                                highest_reward = rew_state[1] * (
                                    enum / len(self.q[state])
                                    if enum > 15 else 1)  #Memory lose

                            else:
                                #print(rew_state[1])
                                if highest_reward < rew_state[1]:
                                    highest_reward = rew_state[1] * (
                                        enum / len(self.q[state])
                                        if enum > 15 else 1)  # Memory lose
                                    position_reward = enum
                        print(highest_reward)
                        #if (self.step % 100!=0):
                        #discount= (1 if float(len(self.q[state]))/float(factor)<=1 else float(len(self.q[state]))/float(factor))
                        #if new_state!=4:
                        print("Random Add: " + str(ref))
                        print(
                            randint(
                                int(-10) + int(50 * ref),
                                int(10) + int(50 * ref)))
                        #if new_state==2:
                        #	ref=-ref
                        if self.increase_state0 > 13 and self.increase_state0 % 3 == 1:
                            self.array_ram_med = [
                                self.q[state][position_reward][0][0][0][0],
                                self.q[state][position_reward][0][0][0][1] +
                                randint(
                                    int(-10) + int(50 * ref),
                                    int(10) + int(50 * ref)),
                                self.q[state][position_reward][0][0][0][2]
                            ]

                        else:
                            self.array_ram_med = [
                                self.q[state][position_reward][0][0][0][0],
                                self.q[state][position_reward][0][0][0][1] +
                                randint(0, int(100)),
                                self.q[state][position_reward][0][0][0][2]
                            ]

                        if self.increase_state0 > 10:
                            print("Decreasing")
                            for enum, rew_state in enumerate(self.q[0]):
                                if enum == 0:
                                    highest_reward = rew_state[1] * (
                                        enum / len(self.q[0])
                                        if enum > 15 else 1)  #Memory lose
                                    position_reward = 0

                                else:

                                    if highest_reward < rew_state[1]:
                                        highest_reward = rew_state[1] * (
                                            enum / len(self.q[0])
                                            if enum > 15 else 1)  # Memory lose
                                        position_reward = enum

                            self.array_ram_lo = [
                                self.q[0][position_reward][0][0][0][0],
                                self.q[0][position_reward][0][0][0][1] +
                                randint(-10 + int(50 * ref),
                                        10 + int(50 * ref)),
                                self.q[0][position_reward][0][0][0][2]
                            ]

                            for enum, rew_state in enumerate(self.q[2]):
                                if enum == 0:
                                    highest_reward = rew_state[1] * (
                                        enum / len(self.q[2])
                                        if enum > 15 else 1)  #Memory lose
                                    position_reward = 0

                                else:

                                    if highest_reward < rew_state[1]:
                                        highest_reward = rew_state[1] * (
                                            enum / len(self.q[2])
                                            if enum > 15 else 1)  # Memory lose
                                        position_reward = enum

                            self.array_ram_hi = [
                                self.q[2][position_reward][0][0][0][0],
                                self.q[2][position_reward][0][0][0][1] +
                                randint(-10 + int(50 * ref),
                                        10 + int(50 * ref)),
                                self.q[2][position_reward][0][0][0][2]
                            ]

                #state=2
                elif state == 2:
                    print("Update State 2")
                    self.increase_state0 = 0
                    if len(self.q[state]) < 3:
                        print("IN-RANDOM 5" if (len(self.q[state]) %
                                                5 == 0) else "")
                        print("Random Search")
                        if new_state != 4:
                            self.array_ram_hi = [
                                300, 350 + randint(-50, 50), 400
                            ]
                        else:
                            print("Random Search on Neutral")
                            self.array_ram_hi = [
                                300, 350 + randint(-45, 45), 400
                            ]
                    else:
                        print("Random Optimizer based on Reward")
                        highest_reward = 0
                        position_reward = 0
                        self.increase += 1
                        for enum, rew_state in enumerate(self.q[state]):
                            if enum == 0:
                                highest_reward = rew_state[1] * (enum / len(
                                    self.q[state]) if enum > 15 else 1)

                            else:
                                if highest_reward < rew_state[1]:
                                    highest_reward = rew_state[1] * (
                                        enum /
                                        len(self.q[state]) if enum > 15 else 1)
                                    position_reward = enum
                        if (self.step % 100 != 0):
                            discount = (1 if float(len(self.q[state])) /
                                        float(factor) <= 1 else
                                        float(len(self.q[state])) /
                                        float(factor))
                            print("Exploit")
                            print(self.q[state][position_reward][0][0][0])
                            print(self.q[state][position_reward][0][0][0][0] +
                                  randint(int(-50 /
                                              discount), int(25 / discount)))

                            self.array_ram_hi = [
                                self.q[state][position_reward][0][0][0][0],
                                self.q[state][position_reward][0][0][0][1] +
                                randint(
                                    int(-10) + int(50 * ref),
                                    int(10) + int(50 * ref)),
                                self.q[state][position_reward][0][0][0][2]
                            ]

                            if self.increase > 10:
                                print("Increasing")
                                for enum, rew_state in enumerate(self.q[1]):
                                    if enum == 0:
                                        highest_reward = rew_state[1] * (
                                            enum / len(self.q[1])
                                            if enum > 15 else 1)  #Memory lose
                                        position_reward = 0

                                    else:

                                        if highest_reward < rew_state[1]:
                                            highest_reward = rew_state[1] * (
                                                enum / len(self.q[1]) if enum >
                                                15 else 1)  # Memory lose
                                            position_reward = enum

                                self.array_ram_med = [
                                    self.q[1][position_reward][0][0][0][0],
                                    self.q[1][position_reward][0][0][0][1] +
                                    randint(-10 + int(50 * ref),
                                            10 + int(50 * ref)),
                                    self.q[1][position_reward][0][0][0][2]
                                ]

                #For this first test Im only going to record the results without trying to work around the explore-exploit problem, as first I would like to see if the logic is already working.

                state = int(state_base)
                print("Previous State COmprobation: " + str(state))
                #print("Q-table")
                #print(self.q)

                self.file_q_table.write('%s \n' % self.q)
                ram = np.arange(100, 351, 1)
                print("Variability: " + str(self.variability))
                print("State: " + str(state) + ", New State: " +
                      str(new_state))

                print("New Parameters Before Rules")
                print(self.array_ram_lo)
                print(self.array_ram_med)
                print(self.array_ram_hi)
                print("##############")

                if self.array_ram_hi[1] > self.array_ram_hi[2]:
                    self.array_ram_hi[1] = self.array_ram_hi[2]
                if self.array_ram_hi[0] > self.array_ram_hi[1]:
                    self.array_ram_hi[1] = self.array_ram_hi[0]

                if self.array_ram_med[0] > self.array_ram_med[1]:
                    self.array_ram_med[1] = self.array_ram_med[0]
                if self.array_ram_med[1] > self.array_ram_med[2]:
                    self.array_ram_med[1] = self.array_ram_med[2]
                if self.array_ram_lo[1] > self.array_ram_lo[2]:
                    self.array_ram_lo[1] = self.array_ram_lo[2]
                if self.array_ram_lo[0] > self.array_ram_lo[1]:
                    self.array_ram_lo[1] = self.array_ram_lo[0]

                print("New Parameters After Rules")
                print(self.array_ram_lo)
                print(self.array_ram_med)
                print(self.array_ram_hi)
                print("##############")
                file_fuzzy.write(
                    str(self.array_ram_lo[0]) + "," +
                    str(self.array_ram_lo[1]) + "," +
                    str(self.array_ram_lo[2]) + "," +
                    str(self.array_ram_med[0]) + "," +
                    str(self.array_ram_med[1]) + "," +
                    str(self.array_ram_med[2]) + "," +
                    str(self.array_ram_hi[0]) + "," +
                    str(self.array_ram_hi[1]) + "," +
                    str(self.array_ram_hi[2]) + "\n")
                ram_lo = fuzz.trimf(ram, self.array_ram_lo)
                ram_md = fuzz.trimf(ram, self.array_ram_med)
                ram_hi = fuzz.trimf(ram, self.array_ram_hi)
                ram_antecedent = ctrl.Antecedent(ram, 'ram_antecedent')

                self.ram_consequent = ctrl.Consequent(ram, 'ram_consequent')
                self.ram_consequent['ram_lo'] = ram_antecedent[
                    'ram_lo'] = ram_lo
                self.ram_consequent['ram_md'] = ram_antecedent[
                    'ram_md'] = ram_md
                self.ram_consequent['ram_hi'] = ram_antecedent[
                    'ram_hi'] = ram_hi

                self.rule1r = ctrl.Rule(
                    self.memory_antecedent['memory_hi']
                    & ram_antecedent['ram_lo'], self.ram_consequent['ram_md'])

                self.rule2r = ctrl.Rule(
                    self.memory_antecedent['memory_hi'] &
                    (ram_antecedent['ram_md'] | ram_antecedent['ram_hi']),
                    self.ram_consequent['ram_hi'])

                self.rule3r = ctrl.Rule(
                    self.memory_antecedent['memory_lo']
                    & ram_antecedent['ram_hi'], self.ram_consequent['ram_md'])

                self.rule4r = ctrl.Rule(
                    self.memory_antecedent['memory_lo'] &
                    (ram_antecedent['ram_md'] | ram_antecedent['ram_lo']),
                    self.ram_consequent['ram_lo'])

                #Update system
                self.scalability_ram_ctrl = ctrl.ControlSystem(
                    [self.rule1r, self.rule2r, self.rule3r, self.rule4r])

                #### 	SERVER RELATED RULES ####

                self.rule1s = ctrl.Rule(
                    self.memory_antecedent['memory_hi']
                    & ram_antecedent['ram_hi']
                    & self.servers_antecedent['servers_1'],
                    self.servers_consequent['servers_2'])

                self.rule2s = ctrl.Rule(
                    (self.memory_antecedent['memory_lo']
                     | self.memory_antecedent['memory_md'])
                    & ram_antecedent['ram_lo'] & ~ram_antecedent['ram_hi']
                    & self.servers_antecedent['servers_2'],
                    self.servers_consequent['servers_1'])

                self.scalability_server_ctrl = ctrl.ControlSystem(
                    [self.rule1s, self.rule2s])

                #Updating State for New Iteration
                if new_state != 4:
                    self.last_action = [[[self.array_ram_lo],
                                         [self.array_ram_med],
                                         [self.array_ram_hi]], new_state]
                else:
                    self.last_action = [[[self.array_ram_lo],
                                         [self.array_ram_med],
                                         [self.array_ram_hi]],
                                        self.last_action[1]]
                print("Update action")
                print(self.last_action)