def fuzz_accuracy_sigmf(self, topic_index_list, x_universe, y_universe):
        x_topic = ctrl.Antecedent(topic_index_list, 'topic')
        y_accuracy  = ctrl.Consequent(y_universe,'accuracy')

        y_accuracy['absolutely_wrong'] = fuzz.sigmf(y_accuracy.universe, 0.1, 0.3)
        y_accuracy['understandable_wrong'] = fuzz.dsigmf(y_accuracy.universe, 0.3, 0.2, 0.4, 0.2)
        y_accuracy['reasonable'] = fuzz.dsigmf(y_accuracy.universe, 0.5, 0.2, 0.6, 0.2)
        y_accuracy['good'] = fuzz.dsigmf(y_accuracy.universe, 0.7, 0.2, 0.8, 0.2)
        y_accuracy['absolutely_right'] = fuzz.sigmf(y_accuracy.universe, 0.9, 0.2)

        return x_topic
예제 #2
0
def membership_f(mf, x, abcd):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
    """
    if mf == 'zmf': return fuzz.zmf(x, abcd[0], abcd[1])  # zmf(x, a, b)
    elif mf == 'trimf': return fuzz.trimf(x, abcd[0:3])  # trimf(x, abc)
    elif mf == 'dsigmf':
        return fuzz.dsigmf(x, abcd[0], abcd[1], abcd[2],
                           abcd[3])  # dsigmf(x, b1, c1, b2, c2)
    elif mf == 'gauss2mf':
        return fuzz.gauss2mf(
            x, abcd[0], abcd[1], abcd[2],
            abcd[3])  # gauss2mf(x, mean1, sigma1, mean2, sigma2)
    elif mf == 'gaussmf':
        return fuzz.gaussmf(x, abcd[0], abcd[1])  # gaussmf(x, mean, sigma)
    elif mf == 'gbellmf':
        return fuzz.gbellmf(x, abcd[0], abcd[1],
                            abcd[2])  # gbellmf(x, a, b, c)
    elif mf == 'piecemf':
        return fuzz.piecemf(x, abcd[0:3])  # piecemf(x, abc)
    elif mf == 'pimf':
        return fuzz.pimf(x, abcd[0], abcd[1], abcd[2],
                         abcd[3])  # pimf(x, a, b, c, d)
    elif mf == 'psigmf':
        return fuzz.psigmf(x, abcd[0], abcd[1], abcd[2],
                           abcd[3])  # psigmf(x, b1, c1, b2, c2)
    elif mf == 'sigmf':
        return fuzz.sigmf(x, abcd[0], abcd[1])  # sigmf(x, b, c)
    elif mf == 'smf':
        return fuzz.smf(x, abcd[0], abcd[1])  # smf(x, a, b)
    elif mf == 'trapmf':
        return fuzz.trapmf(x, abcd)  # trapmf(x, abcd)
예제 #3
0
 def __createMF(self, mf_type, params, universe):
     return {
         "trapezoid": lambda *args: fuzz.trapmf(*args),
         "gaussian": lambda *args: fuzz.gaussmf(*args),
         "sigmoid": lambda *args: fuzz.sigmf(*args)
     }.get(mf_type.lower(), lambda *args: fuzz.trimf(*args))(universe,
                                                             params)
예제 #4
0
def membership_f(mf, x, abcd):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
    """
    if mf == "zmf":
        return fuzz.zmf(x, abcd[0], abcd[1])  # zmf(x, a, b)
    elif mf == "trimf":
        return fuzz.trimf(x, abcd[0:3])  # trimf(x, abc)
    elif mf == "dsigmf":
        return fuzz.dsigmf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # dsigmf(x, b1, c1, b2, c2)
    elif mf == "gauss2mf":
        return fuzz.gauss2mf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # gauss2mf(x, mean1, sigma1, mean2, sigma2)
    elif mf == "gaussmf":
        return fuzz.gaussmf(x, abcd[0], abcd[1])  # gaussmf(x, mean, sigma)
    elif mf == "gbellmf":
        return fuzz.gbellmf(x, abcd[0], abcd[1], abcd[2])  # gbellmf(x, a, b, c)
    elif mf == "piecemf":
        return fuzz.piecemf(x, abcd[0:3])  # piecemf(x, abc)
    elif mf == "pimf":
        return fuzz.pimf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # pimf(x, a, b, c, d)
    elif mf == "psigmf":
        return fuzz.psigmf(x, abcd[0], abcd[1], abcd[2], abcd[3])  # psigmf(x, b1, c1, b2, c2)
    elif mf == "sigmf":
        return fuzz.sigmf(x, abcd[0], abcd[1])  # sigmf(x, b, c)
    elif mf == "smf":
        return fuzz.smf(x, abcd[0], abcd[1])  # smf(x, a, b)
    elif mf == "trapmf":
        return fuzz.trapmf(x, abcd)  # trapmf(x, abcd)
예제 #5
0
    def plotMF(self, x, inputVar):
        from skfuzzy import gaussmf, gbellmf, sigmf

        for mf in range(len(self.memFuncs[inputVar])):
            if self.memFuncs[inputVar][mf][0] == 'gaussmf':
                y = gaussmf(x, **self.memClass.MFList[inputVar][mf][1])
            elif self.memFuncs[inputVar][mf][0] == 'gbellmf':
                y = gbellmf(x, **self.memClass.MFList[inputVar][mf][1])
            elif self.memFuncs[inputVar][mf][0] == 'sigmf':
                y = sigmf(x, **self.memClass.MFList[inputVar][mf][1])

            plt.plot(x, y, 'r')

        plt.show()
예제 #6
0
파일: anfis.py 프로젝트: JDWarner/anfis
    def plotMF(self, x, inputVar):
        import matplotlib.pyplot as plt
        from skfuzzy import gaussmf, gbellmf, sigmf

        for mf in range(len(self.memFuncs[inputVar])):
            if self.memFuncs[inputVar][mf][0] == 'gaussmf':
                y = gaussmf(x,**self.memClass.MFList[inputVar][mf][1])
            elif self.memFuncs[inputVar][mf][0] == 'gbellmf':
                y = gbellmf(x,**self.memClass.MFList[inputVar][mf][1])
            elif self.memFuncs[inputVar][mf][0] == 'sigmf':
                y = sigmf(x,**self.memClass.MFList[inputVar][mf][1])

            plt.plot(x,y,'r')

        plt.show()
예제 #7
0
def membership_f(mf, x, abc = [0,0,0], a = 1, b = 2, c = 3, d = 4, abcd = [0,0,0,0]):

        return {
            'trimf'   : fuzz.trimf(x, abc),                                 # trimf(x, abc)
            'dsigmf'  : fuzz.dsigmf(x, a, b, c, d),                         # dsigmf(x, b1, c1, b2, c2)
            'gauss2mf': fuzz.gauss2mf(x, a, b, c, d),                       # gauss2mf(x, mean1, sigma1, mean2, sigma2)
            'gaussmf' : fuzz.gaussmf(x, a, b),                              # gaussmf(x, mean, sigma)
            'gbellmf' : fuzz.gbellmf(x, a, b, c),                           # gbellmf(x, a, b, c)
            'piecemf' : fuzz.piecemf(x, abc),                               # piecemf(x, abc)
            'pimf'    : fuzz.pimf(x, a, b, c, d),                           # pimf(x, a, b, c, d)
            'psigmf'  : fuzz.psigmf(x, a, b, c, d),                         # psigmf(x, b1, c1, b2, c2)
            'sigmf'   : fuzz.sigmf(x, a, b),                                # sigmf(x, b, c)
            'smf'     : fuzz.smf(x, a, b),                                  # smf(x, a, b)
            'trapmf'  : fuzz.trapmf(x, abcd),                               # trapmf(x, abcd)
            'zmf'     : fuzz.zmf(x, a, b),                                  # zmf(x, a, b)
                }[mf]
예제 #8
0
    def plotMF(self, x, inputVar):
        import matplotlib.pyplot as plt
        from skfuzzy import gaussmf, gbellmf, sigmf
        print("memFuncs")
        print(self.memFuncs)
        fig = plt.figure(figsize=(16, 12))
        for mf in range(len(self.memFuncs[inputVar])):
            if self.memFuncs[inputVar][mf][0] == 'gaussmf':
                y = gaussmf(x, **self.memClass.MFList[inputVar][mf][1])
            elif self.memFuncs[inputVar][mf][0] == 'gbellmf':
                y = gbellmf(x, **self.memClass.MFList[inputVar][mf][1])
            elif self.memFuncs[inputVar][mf][0] == 'sigmf':
                y = sigmf(x, **self.memClass.MFList[inputVar][mf][1])

            plt.plot(x, y, 'r')
            plt.savefig("mf" + str(inputVar) + ".png")
        fig.clear()
예제 #9
0
    def __init__(self, ref, view=False):
        # Referência, força aplicada e força máxima capaz de ser aplicada
        # pelo controlador
        self.ref = ref
        self.f = 0
        self.f_max = 1.5*abs(m*g)
        # Intervalos das variáveis de entrada
        self.position_error_range = numpy.arange(-100, 100, 0.01)
        self.velocity_range = numpy.arange(-100, 100, 0.01)
        # Intervalo da variável de saída
        self.output_range = numpy.arange(-1, 1, 0.01)
        # Definição das funções de pertinência da variável de erro de posição
        self.e_N = skfuzzy.sigmf(self.position_error_range, -5, -1)
        self.e_Z = skfuzzy.gaussmf(self.position_error_range, 0, 2)
        self.e_P = skfuzzy.sigmf(self.position_error_range, 5, 1)
        # Definição das funções de pertinência da variável de velocidade
        self.v_N = skfuzzy.sigmf(self.velocity_range, -5, -1)
        self.v_Z = skfuzzy.gaussmf(self.velocity_range, 0, 2)
        self.v_P = skfuzzy.sigmf(self.velocity_range, 5, 1)
        # Definição das funções de pertinência da variável de saída
        self.o_N = skfuzzy.sigmf(self.output_range, -0.5, -10)
        self.o_Z = skfuzzy.gaussmf(self.output_range, 0, 0.2)
        self.o_P = skfuzzy.sigmf(self.output_range, 0.5, 10)

        # Visualização das funções de pertinência das entradas e saídas
        if view:
            fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(8, 9))

            ax0.plot(self.position_error_range, self.e_N, 'b', linewidth=1.5, label='Negativo')
            ax0.plot(self.position_error_range, self.e_Z, 'g', linewidth=1.5, label='Zero')
            ax0.plot(self.position_error_range, self.e_P, 'r', linewidth=1.5, label='Positivo')
            ax0.set_title('Erro de posição')
            ax0.legend()

            ax1.plot(self.velocity_range, self.v_N, 'b', linewidth=1.5, label='Negativo')
            ax1.plot(self.velocity_range, self.v_Z, 'g', linewidth=1.5, label='Zero')
            ax1.plot(self.velocity_range, self.v_P, 'r', linewidth=1.5, label='Positivo')
            ax1.set_title('Velocidade')
            ax1.legend()

            ax2.plot(self.output_range, self.o_N, 'b', linewidth=1.5, label='Redução')
            ax2.plot(self.output_range, self.o_Z, 'g', linewidth=1.5, label='Manutenção')
            ax2.plot(self.output_range, self.o_P, 'r', linewidth=1.5, label='Aumento')
            ax2.set_title('Saída')
            ax2.legend()

            for ax in (ax0, ax1, ax2):
                ax.spines['top'].set_visible(False)
                ax.spines['right'].set_visible(False)
                ax.get_xaxis().tick_bottom()
                ax.get_yaxis().tick_left()

            plt.tight_layout()
예제 #10
0
    def __createMF(self, mf_type, params, universe):
        """
        Creates a membership function based on the given type.
        The triangular MF is considered as the default case

        Parameters
        --------------
        :param mf_type:
        :param params:
        :param universe:
        :return: a membership function
        """
        return {
            TRAPEZOID_MF: lambda *args: fuzz.trapmf(*args),
            GAUSSIAN_MF: lambda *args: fuzz.gaussmf(args[0], *args[1]),
            SIGMOID_MF: lambda *args: fuzz.sigmf(*args)
        }.get(mf_type.lower(), lambda *args: fuzz.trimf(*args))(universe,
                                                                params)
예제 #11
0
    def plotMF(self, x, inputNumber):
        """plotMF(self, x, inputNumber)

        Parameters
        ----------
        x : 1d array or iterable
            表示したいmfの横軸の値
        inputNumber : int
            入力するデータの種類を配列の添字で示したもの

        """

        import matplotlib.pyplot as plt
        from skfuzzy import gaussmf, gbellmf, sigmf
        """gaussmf()

        Parameters
        ----------
        x : 1d array or iterable
            横軸の値
        mean : float
            中央値
        sigma : float
            標準偏差

        Returns
        -------
        y : 1d array
            関数の出力

        """

        for mf in range(len(self.memFuncs[inputNumber])):
            if self.memFuncs[inputNumber][mf][0] == 'gaussmf':
                y = gaussmf(x, **self.memClass.MFList[inputNumber][mf][1])
            elif self.memFuncs[inputNumber][mf][0] == 'gbellmf':
                y = gbellmf(x, **self.memClass.MFList[inputNumber][mf][1])
            elif self.memFuncs[inputNumber][mf][0] == 'sigmf':
                y = sigmf(x, **self.memClass.MFList[inputNumber][mf][1])

            plt.plot(x, y, 'r')

        plt.show()
예제 #12
0
def membership_f(mf, x, abc=[0, 0, 0], a=1, b=2, c=3, d=4, abcd=[0, 0, 0, 0]):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
        abc - list containing triangular edge point x-values
    """
    return {
        "trimf": fuzz.trimf(x, abc),  # trimf(x, abc)
        "dsigmf": fuzz.dsigmf(x, a, b, c, d),  # dsigmf(x, b1, c1, b2, c2)
        "gauss2mf": fuzz.gauss2mf(x, a, b, c, d),  # gauss2mf(x, mean1, sigma1, mean2, sigma2)
        "gaussmf": fuzz.gaussmf(x, a, b),  # gaussmf(x, mean, sigma)
        "gbellmf": fuzz.gbellmf(x, a, b, c),  # gbellmf(x, a, b, c)
        "piecemf": fuzz.piecemf(x, abc),  # piecemf(x, abc)
        "pimf": fuzz.pimf(x, a, b, c, d),  # pimf(x, a, b, c, d)
        "psigmf": fuzz.psigmf(x, a, b, c, d),  # psigmf(x, b1, c1, b2, c2)
        "sigmf": fuzz.sigmf(x, a, b),  # sigmf(x, b, c)
        "smf": fuzz.smf(x, a, b),  # smf(x, a, b)
        "trapmf": fuzz.trapmf(x, abcd),  # trapmf(x, abcd)
        "zmf": fuzz.zmf(x, a, b),  # zmf(x, a, b)
    }[mf]
예제 #13
0
def membership_f(mf, x, abc = [0,0,0], a = 1, b = 2, c = 3, d = 4, abcd = [0,0,0,0]):
    """
    Returns y values corresponding to type of type of Membership fn.
    arguments:
        mf - string containing type of Membership function
        x  - x axis values
        abc - list containing triangular edge point x-values
    """
    return {
        'trimf'   : fuzz.trimf(x, abc),                                 # trimf(x, abc)
        'dsigmf'  : fuzz.dsigmf(x, a, b, c, d),                         # dsigmf(x, b1, c1, b2, c2)
        'gauss2mf': fuzz.gauss2mf(x, a, b, c, d),                       # gauss2mf(x, mean1, sigma1, mean2, sigma2)
        'gaussmf' : fuzz.gaussmf(x, a, b),                              # gaussmf(x, mean, sigma)
        'gbellmf' : fuzz.gbellmf(x, a, b, c),                           # gbellmf(x, a, b, c)
        'piecemf' : fuzz.piecemf(x, abc),                               # piecemf(x, abc)
        'pimf'    : fuzz.pimf(x, a, b, c, d),                           # pimf(x, a, b, c, d)
        'psigmf'  : fuzz.psigmf(x, a, b, c, d),                         # psigmf(x, b1, c1, b2, c2)
        'sigmf'   : fuzz.sigmf(x, a, b),                                # sigmf(x, b, c)
        'smf'     : fuzz.smf(x, a, b),                                  # smf(x, a, b)
        'trapmf'  : fuzz.trapmf(x, abcd),                               # trapmf(x, abcd)
        'zmf'     : fuzz.zmf(x, a, b),                                  # zmf(x, a, b)
            }[mf]
예제 #14
0
    Santiago Ocampo Orrego - Código: 1004679255

    Membresía Sigmoide

    Cambios: - He modificado el diseño y la posición de la etiqueta 'Servicio'

"""

# Función de membresía sigmoide

import numpy as np
import skfuzzy as sk
import matplotlib.pyplot as plt

# Se define la variable independiente
x = np.arange(-11, 11, 1)

# Se define la variable dependiente sigmoide de membresía
vd_sigmoide = sk.sigmf(x, 0, 1)

# Se grafica la función de membresía
plt.figure()
plt.plot(x, vd_sigmoide, 'b', linewidth=1.5, label='Servicio')

plt.title('Calidad del Servicio en un Restaurante\n')
plt.ylabel('Membresía')
plt.xlabel('Nivel de Servicio')
plt.legend(loc='upper left', fancybox=True, shadow=True)

plt.show()
예제 #15
0
    def test_object(self):
        import pandas as pd
        import numpy as np
        import skfuzzy as fuzz
        from skfuzzy import control as ctrl
        from sklearn.datasets import make_blobs
        from sklearn.ensemble import RandomForestClassifier
        import matplotlib.pyplot as plt

        from fuzzyml import FuzzyClassifier
        from fuzzyml import plot_decision_function

        X, y = make_blobs(n_samples=1000, centers=4, random_state=0)
        X = pd.DataFrame(X)
        cols = ["f1", "f2"]
        X.columns = cols
        y[y == 2] = 0
        not_visible = y == 3
        y[not_visible] = 1
        X_visible = X.iloc[~not_visible]
        y_visible = y[~not_visible]

        # New Antecedent/Consequent objects hold universe variables and membership functions
        feature1 = ctrl.Antecedent(np.arange(-6, 6, 1), X.columns[0])
        feature1['G1'] = fuzz.gaussmf(feature1.universe, -2, 2)
        feature1['G2'] = fuzz.gaussmf(feature1.universe, 2, 2)
        feature1.view()
        feature2 = ctrl.Antecedent(np.arange(-4, 12, 1), X.columns[1])
        feature2['G1'] = fuzz.sigmf(feature2.universe, 2, -2)
        feature2['G2'] = fuzz.gaussmf(feature2.universe, 3, 2)
        feature2['G3'] = fuzz.sigmf(feature2.universe, 5, 2)
        feature2.view()
        label = ctrl.Consequent(np.arange(0, 11, 1), 'label')
        label['L1'] = fuzz.gaussmf(label.universe, 0, 2)
        label['L2'] = fuzz.gaussmf(label.universe, 10, 2)
        label.view()

        # rules
        rule1 = ctrl.Rule(feature1['G1'] & feature2['G2'], label['L2'])
        rule3 = ctrl.Rule(feature2['G3'], label['L1'])

        # control
        ctrl_sys = ctrl.ControlSystem([rule1, rule3])
        fuzzy_ctrl = ctrl.ControlSystemSimulation(ctrl_sys)

        # load ML models
        model = RandomForestClassifier(random_state=0)
        fuzzy_model = FuzzyClassifier(model, fuzzy_ctrl)

        # fit fuzzy model
        fuzzy_model.fit(X_visible, y_visible)
        score_fz = fuzzy_model.score(X, y)

        # fit standard model
        model.fit(X_visible, y_visible)
        score_dt = model.score(X, y)

        plt.figure(figsize=[10, 5])
        plt.subplot(121)
        plot_decision_function(fuzzy_model, "Fuzzy - acc %.2f" % score_fz, X,
                               y, not_visible)
        plt.subplot(122)
        plot_decision_function(model, "No rules - acc %.2f" % score_dt, X, y,
                               not_visible)
        plt.tight_layout()
        plt.savefig("./decision_boundaries.png")
        plt.show()

        self.assertTrue(score_dt == 0.75)
        self.assertTrue(score_fz == 0.924)

        return
예제 #16
0
start = 0
stop = 10 + 0.001
step = 0.25
x = np.arange(start, stop, step)
print(x)

# Triangular membership function
trimf = fuzz.trimf(x, [0, 5, 10])

# Trapezoidal membership function
trapmf = fuzz.trapmf(x, [0, 2, 8, 10])

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

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

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

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

# Gaussian function
mean = 5.0
sigma = 1.25
예제 #17
0
# margin of outputs rules determin if a state is a valid state
STATE_DIFF_MARGIN = 0.2

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

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

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

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

state_ground = fuzz.gaussmf(states, 1, 0.1)
state_climb = fuzz.gaussmf(states, 2, 0.1)
state_descend = fuzz.gaussmf(states, 3, 0.1)
state_cruise = fuzz.gaussmf(states, 4, 0.1)


# Visualize these universes and membership functions
def plot_logics():
    plt.figure(figsize=(10, 8))
예제 #18
0
 def defineClassTwo(self, x, center_point, width):
     y = np.zeros(len(x))
     idx = x > center_point
     y[idx] = fuzz.sigmf(x[idx], center_point, width)
     return y
예제 #19
0
Fi.automf(3, names=['No', 'Leve', 'Alta'])
DC.automf(3, names=binary)
Mi.automf(3, names=binary)
Fa.automf(3, names=binary)
CN.automf(3, names=binary)
Es.automf(3, names=binary)
DG.automf(5, names=['No', 'Leve', 'Severo', '~No', 'X'])
DR.automf(3, names=binary)
Ri.automf(3, names=binary)

# -------------------------------------
# Generate fuzzy membership functions
# -------------------------------------

# Fiebre
Fi['No'] = fuzz.sigmf(Fi.universe, -30, 0.3)
Fi['Leve'] = fuzz.gbellmf(Fi.universe, 0.587, 3.28, 38.3)
Fi['Alta'] = fuzz.sigmf(Fi.universe, 11.76, 39.1)

# Dolor de cabeza
no_sigmoid = fuzz.sigmf(DC.universe, -30, 0.3)
DC['No'] = no_sigmoid
DC['~No'] = 1 - no_sigmoid

# Mialgia
no_sigmoid = fuzz.sigmf(Mi.universe, -30, 0.3)
Mi['No'] = no_sigmoid
Mi['~No'] = 1 - no_sigmoid

# Fatiga
no_sigmoid = fuzz.sigmf(Fa.universe, -64.3, 0.2)
예제 #20
0
파일: fuzzy.py 프로젝트: Mabeesha/DDA
                                       '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:
    gun_damage_pc['low'] = fuzz.trimf(
        gun_damage_pc.universe, [gun_damage_pc_min, gun_damage_pc_min, 100])
    gun_damage_pc['high'] = fuzz.trimf(gun_damage_pc.universe,
                                       [gun_damage_pc_min, 100, 100])
elif gun_damage_pc_funtype == 1:
    c = (-2.0 * np.log(99)) / (gun_damage_pc_min - 100)
    gun_damage_pc['low'] = fuzz.sigmf(gun_damage_pc.universe,
                                      (100 + gun_damage_pc_min) / 2.0,
                                      -1.0 * c)
    gun_damage_pc['high'] = fuzz.sigmf(gun_damage_pc.universe,
                                       (100 + gun_damage_pc_min) / 2.0, c)

if speed_npc_funtype == 0:
    speed_npc['low'] = fuzz.trimf(speed_npc.universe,
                                  [speed_npc_min, speed_npc_min, 100])
    speed_npc['high'] = fuzz.trimf(speed_npc.universe,
                                   [speed_npc_min, 100, 100])
elif speed_npc_funtype == 1:
    c = (-2.0 * np.log(99)) / (gun_damage_pc_min - 100)
    speed_npc['low'] = fuzz.sigmf(speed_npc.universe,
                                  (100 + speed_npc_min) / 2.0, -1.0 * c)
    speed_npc['high'] = fuzz.sigmf(speed_npc.universe,
                                   (100 + speed_npc_min) / 2.0, c)
예제 #21
0
def get_length_penalty(sent_len):
    # 0.5 value for len=2
    # quickly raising to 1 at ~10 words
    return fuzz.sigmf(sent_len, 2, 0.5)
예제 #22
0
def get_score(dict):
    kopidict = dict
    kopi_input = float(kopidict['kopi'])
    milk_input = float(kopidict['milk'])
    sugar_input = float(kopidict['sugar'])
    count = 1

    #To set the universe range dynamically
    max_level = 11
    # print("Max Level and count:")
    # print(max_level)
    # print(count)
    min_level = 0
    milk_y = 0
    sugar_y = 0
    score = 0
    sugar_level = 11
    print("Milk Value:" + str(milk_input), end="\t")
    print("Sugar Value:" + str(sugar_input), end="\t")
    print("Kopi Value:" + str(kopi_input))
    # max_level=100
    """Kopi Level"""
    kopi_bins = np.arange(0, max_level, count)
    kopi = ctrl.Antecedent(kopi_bins, 'kopi')
    mid_kopi = max_level // 2
    kopi_LP_1 = (min_level + mid_kopi) // 5
    kopi_LP_2 = (kopi_LP_1 + mid_kopi) // 2
    kopi_TR_1 = mid_kopi // 2
    kopi_TR_2 = mid_kopi
    kopi_TR_3 = kopi_TR_1 + kopi_TR_2
    kopi_HP_1 = (max_level + mid_kopi) // 2.5
    kopi_HP_2 = (max_level + mid_kopi) // 5 + mid_kopi
    # print(kopi_bins)
    # print(kopi_HP_2,kopi_HP_1)
    kopi_thick = fuzz.smf(kopi.universe, kopi_HP_1, kopi_HP_2)
    kopi_norm = fuzz.trimf(kopi.universe, [kopi_TR_1, kopi_TR_2, kopi_TR_3])
    kopi_thin = fuzz.zmf(kopi.universe, kopi_LP_1, kopi_LP_2)
    kopi['thin'] = kopi_thin
    kopi['norm'] = kopi_norm
    kopi['thick'] = kopi_thick
    # kopi.view()
    # pyplot.show()
    # print("Printing Kopi MFs:")
    # print(fuzz.interp_membership(kopi.universe,kopi_thin,kopi_input))
    # print(fuzz.interp_membership(kopi.universe,kopi_norm,kopi_input))
    # print(fuzz.interp_membership(kopi.universe,kopi_thick,kopi_input))
    """Milk Level"""
    milk_pre_bins = np.arange(0, 1, 0.1)
    milk_pre = ctrl.Antecedent(milk_pre_bins, 'milk_pre')
    milk_pre_mf = fuzz.sigmf(milk_pre.universe, 0.5, 1)
    milk_pre['milk_pre'] = milk_pre_mf
    #milk input value being passed as the last argument
    val_milk = fuzz.interp_membership(milk_pre.universe, milk_pre_mf,
                                      milk_input)
    # print("Milk MF:")
    # print(val_milk)

    if val_milk == 0.0:
        milk_y = 1
        # print("Milk Required")
        milk_bins = np.arange(0, max_level, count)
        milk = ctrl.Antecedent(milk_bins, 'milk')
        mid_milk = max_level // 2
        milk_LP_1 = (min_level + mid_milk) // 5
        milk_LP_2 = (milk_LP_1 + mid_milk) // 2
        milk_TR_1 = mid_milk // 2
        milk_TR_2 = mid_milk
        milk_TR_3 = milk_TR_1 + milk_TR_2
        milk_HP_1 = (max_level + mid_milk) // 2.5
        milk_HP_2 = (max_level + mid_milk) // 5 + mid_milk
        milk_extra = fuzz.smf(milk.universe, milk_HP_1, milk_HP_2)
        milk_norm = fuzz.trimf(milk.universe,
                               [milk_TR_1, milk_TR_2, milk_TR_3])
        milk_less = fuzz.zmf(milk.universe, milk_LP_1, milk_LP_2)
        milk['less'] = milk_less
        milk['norm'] = milk_norm
        milk['extra'] = milk_extra
        milk_temp = fuzz.smf(milk_pre.universe, 0.5, 1)
        milk_pre['milk_pre'] = milk_temp
        # milk.view()
        # pyplot.show()
        # print("Printing Milk MFs:")
        # print(fuzz.interp_membership(milk.universe,milk_less,milk_input))
        # print(fuzz.interp_membership(milk.universe,milk_norm,milk_input))
        # print(fuzz.interp_membership(milk.universe,milk_extra,milk_input))
        # print(fuzz.interp_membership(milk_pre.universe,milk_temp,milk_input))
    else:
        milk_y = 0
        # print("No milk")
        milk_bins = np.arange(0, max_level, count)
        milk = ctrl.Antecedent(milk_bins, 'milk')
        milk_mf = fuzz.smf(milk.universe, 0.5, 1)
        milk['less'] = milk_mf
        milk['norm'] = milk_mf
        milk['extra'] = milk_mf
        milk_temp = fuzz.zmf(milk_pre.universe, 0.5, 1)
        milk_pre['milk_pre'] = milk_temp
        # print(fuzz.interp_membership(milk.universe,milk_mf,milk_input))
        # print(fuzz.interp_membership(milk.universe,milk_mf,milk_input))
        # print(fuzz.interp_membership(milk.universe,milk_mf,milk_input))
        # print(fuzz.interp_membership(milk_pre.universe,milk_temp,milk_input))
    """Sugar Membership Function"""
    sugar_pre_bins = np.arange(0, 1, 0.1)
    sugar_pre = ctrl.Antecedent(sugar_pre_bins, 'sugar_pre')
    sugar_pre_mf = fuzz.sigmf(sugar_pre.universe, 0.5, 1)
    sugar_pre['sugar_pre'] = sugar_pre_mf
    #sugar input value being passed as the last argument
    val_sugar = fuzz.interp_membership(sugar_pre.universe, sugar_pre_mf,
                                       sugar_input)
    # print("Sugar MF:")
    # print(val_sugar)

    if val_sugar == 0.0:
        sugar_y = 1
        sugar_bins = np.arange(0, sugar_level, 1)
        sugar = ctrl.Antecedent(sugar_bins, 'sugar')
        # print("Sugar Required")
        sugar_extra = fuzz.smf(sugar.universe, 6, 8)
        sugar_norm = fuzz.trimf(sugar.universe, [3, 5, 7])
        sugar_less = fuzz.zmf(sugar.universe, 2, 4)
        sugar['norm'] = sugar_norm
        sugar['extra'] = sugar_extra
        sugar['less'] = sugar_less
        sugar_temp = fuzz.smf(sugar_pre.universe, 0.5, 1)
        sugar_pre['sugar_pre'] = sugar_temp
        # sugar.view()
        # pyplot.show()
        # print(fuzz.interp_membership(sugar.universe,sugar_less,sugar_input))
        # print(fuzz.interp_membership(sugar.universe,sugar_norm,sugar_input))
        # print(fuzz.interp_membership(sugar.universe,sugar_extra,sugar_input))
        # print(fuzz.interp_membership(sugar_pre.universe,sugar_temp,sugar_input))
    else:
        sugar_y = 0
        sugar_bins = np.arange(0, sugar_level, 1)
        sugar = ctrl.Antecedent(sugar_bins, 'sugar')
        sugar_mf = fuzz.smf(sugar.universe, 0.5, 1)
        sugar['norm'] = sugar_mf
        sugar['extra'] = sugar_mf
        sugar['less'] = sugar_mf
        sugar_temp = fuzz.zmf(sugar_pre.universe, 0.5, 1)
        sugar_pre['sugar_pre'] = sugar_temp
        # print(fuzz.interp_membership(sugar.universe,sugar_mf,sugar_input))
        # print(fuzz.interp_membership(sugar.universe,sugar_mf,sugar_input))
        # print(fuzz.interp_membership(sugar.universe,sugar_mf,sugar_input))
        # print(fuzz.interp_membership(sugar_pre.universe,sugar_temp,sugar_input))
        print("No Sugar")
    """Ouput Membership Function"""
    universe = np.linspace(-19, 19, 39)
    # print(universe)
    output = ctrl.Consequent(universe, 'output')
    # names = ['Kopi_O', 'Kopi_O_KoSong', 'Kopi_O_Siew_Dai', 'Kopi_O_Ga_Dai', 'Kopi_C','Kopi_C_Siew_Dai','Kopi_C_Ga_Dai','Kopi','Kopi_Gao','Kopi_C_Gau_Ga_Dai','Kopi_Po']
    names = [
        'KOPSD', 'KOP', 'KOPGD', 'KOSD', 'KOGD', 'KO', 'KOGSD', 'KOG', 'KOGGD',
        'KOPK', 'KOK', 'KOGK', 'KP', 'KG', 'KDL', 'KPSD', 'KD', 'KGSD', 'KP',
        'KP', 'K', 'NA', 'KPGD', 'KGD', 'KGGD', 'KCPSD', 'KCSD', 'KCGSD',
        'KCP', 'KC', 'KCG', 'KCPGD', 'KCGD', 'KCGGD', 'KCPK', 'KCK', 'KCGK',
        'NA', 'NA'
    ]
    # print(len(names))
    out = output.automf(names=names)

    # Rules for zero milk and various sugar levels
    rule_1 = ctrl.Rule(milk_pre['milk_pre'] & sugar['less'] & kopi['thin'],
                       output['KOPSD'],
                       label='KOPSD')
    rule_2 = ctrl.Rule(milk_pre['milk_pre'] & sugar['norm'] & kopi['thin'],
                       output['KOP'],
                       label='KOP')
    rule_3 = ctrl.Rule(milk_pre['milk_pre'] & sugar['extra'] & kopi['thin'],
                       output['KOPGD'],
                       label='KOPGD')  #KOP
    rule_4 = ctrl.Rule(milk_pre['milk_pre'] & sugar['less'] & kopi['norm'],
                       output['KOSD'],
                       label='KOSD')  #KOPGD
    rule_5 = ctrl.Rule(milk_pre['milk_pre'] & sugar['extra'] & kopi['norm'],
                       output['KOGD'],
                       label='KOGD')
    rule_6 = ctrl.Rule(milk_pre['milk_pre'] & sugar['norm'] & kopi['norm'],
                       output['KO'],
                       label='KO')
    rule_7 = ctrl.Rule(milk_pre['milk_pre'] & sugar['less'] & kopi['thick'],
                       output['KOGSD'],
                       label='KOGSD')
    rule_8 = ctrl.Rule(milk_pre['milk_pre'] & sugar['norm'] & kopi['thick'],
                       output['KOG'],
                       label='KOG')
    rule_9 = ctrl.Rule(milk_pre['milk_pre'] & sugar['extra'] & kopi['thick'],
                       output['KOGGD'],
                       label='KOGGD')

    # #Rules for zero sugar and zero milk
    rule_10 = ctrl.Rule(milk_pre['milk_pre'] & sugar_pre['sugar_pre']
                        & kopi['thin'],
                        output['KOPK'],
                        label='KOPK')
    rule_11 = ctrl.Rule(milk_pre['milk_pre'] & sugar_pre['sugar_pre']
                        & kopi['norm'],
                        output['KOK'],
                        label='KOK')
    rule_12 = ctrl.Rule(milk_pre['milk_pre'] & sugar_pre['sugar_pre']
                        & kopi['thick'],
                        output['KOGK'],
                        label='KOGK')

    #Rules for no sugar and various milk levels (Normal and Less - Condensed)
    rule_13 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar_pre['sugar_pre'] & kopi['thin'],
        output['KP'],
        label='KP')
    rule_14 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar_pre['sugar_pre'] & kopi['norm'],
        output['KG'],
        label='KG')
    rule_15 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar_pre['sugar_pre'] & kopi['thick'],
        output['KDL'],
        label='KDL')

    #Rules for various sugar levels and various milk levels (Normal and Less - Condensed)
    rule_16 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['less'] & kopi['thin'],
        output['KPSD'],
        label='KPSD')
    rule_17 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['less'] & kopi['norm'],
        output['KD'],
        label='KD')
    rule_18 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['less'] & kopi['thick'],
        output['KGSD'],
        label='KGSD')
    rule_19 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['norm'] & kopi['thin'],
        output['KP'],
        label='KP_1')
    rule_20 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['norm'] & kopi['norm'],
        output['K'],
        label='K')
    rule_21 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['norm'] & kopi['thick'],
        output['KG'],
        label='KG_1')
    rule_22 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['extra'] & kopi['thin'],
        output['KPGD'],
        label='KPGD')  #KPGD
    rule_23 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['extra'] & kopi['norm'],
        output['KGD'],
        label='KGD')  #KGD
    rule_24 = ctrl.Rule(
        (milk['less'] | milk['norm']) & sugar['extra'] & kopi['thick'],
        output['KGGD'],
        label='KGGD')  #KGGD

    #Rules for various sugar and extra milk levels
    rule_25 = ctrl.Rule(milk['extra'] & sugar['less'] & kopi['thin'],
                        output['KCPSD'],
                        label='KCPSD')
    rule_26 = ctrl.Rule(milk['extra'] & sugar['less'] & kopi['norm'],
                        output['KCSD'],
                        label='KCSD')
    rule_27 = ctrl.Rule(milk['extra'] & sugar['less'] & kopi['thick'],
                        output['KCGSD'],
                        label='KCGSD')
    rule_28 = ctrl.Rule(milk['extra'] & sugar['norm'] & kopi['thin'],
                        output['KCP'],
                        label='KCP')
    rule_29 = ctrl.Rule(milk['extra'] & sugar['norm'] & kopi['norm'],
                        output['KC'],
                        label='KC')
    rule_30 = ctrl.Rule(milk['extra'] & sugar['norm'] & kopi['thick'],
                        output['KCG'],
                        label='KCG')
    rule_31 = ctrl.Rule(milk['extra'] & sugar['extra'] & kopi['thin'],
                        output['KCPGD'],
                        label='KCPGD')
    rule_32 = ctrl.Rule(milk['extra'] & sugar['extra'] & kopi['norm'],
                        output['KCGD'],
                        label='KCGD')
    rule_33 = ctrl.Rule(milk['extra'] & sugar['extra'] & kopi['thick'],
                        output['KCGGD'],
                        label='KCGGD')

    #Rules for no sugar and extra milk levels
    rule_34 = ctrl.Rule(milk['extra'] & sugar_pre['sugar_pre'] & kopi['thin'],
                        output['KCPK'],
                        label='KCPK')
    rule_35 = ctrl.Rule(milk['extra'] & sugar_pre['sugar_pre'] & kopi['norm'],
                        output['KCK'],
                        label='KCK')
    rule_36 = ctrl.Rule(milk['extra'] & sugar_pre['sugar_pre'] & kopi['thick'],
                        output['KCGK'],
                        label='KCGK')
    # rule_1.view()

    # print("Milk_y and Sugar_y:"+str(milk_y)+"   "+str(sugar_y))
    if milk_y == 0 and sugar_y == 1:
        # print("Rules for kopi without milk and various sugar levels")
        ctrl_sys = ctrl.ControlSystem([
            rule_1, rule_2, rule_3, rule_4, rule_5, rule_6, rule_7, rule_8,
            rule_9
        ])
        # sim = ctrl.ControlSystemSimulation(ctrl_sys, flush_after_run=35 * 35 + 1)
        sim = ctrl.ControlSystemSimulation(ctrl_sys)
        sim.input['kopi'] = kopi_input
        sim.input['sugar'] = sugar_input
        sim.input['milk_pre'] = milk_input
        sim.compute()
        score = sim.output['output']
        # output.view(sim=sim)
        # pyplot.show()
    elif milk_y == 0 and sugar_y == 0:
        # print("Rules for kopi without milk and sugar ")
        ctrl_sys = ctrl.ControlSystem([rule_10, rule_11, rule_12])
        # sim = ctrl.ControlSystemSimulation(ctrl_sys, flush_after_run=35 * 35 + 1)
        sim = ctrl.ControlSystemSimulation(ctrl_sys)
        sim.input['kopi'] = kopi_input
        sim.input['sugar_pre'] = sugar_input
        sim.input['milk_pre'] = milk_input
        sim.compute()
        score = sim.output['output']
        # output.view(sim=sim)
        # pyplot.show()
    elif milk_y == 1 and sugar_y == 0:
        # print("Rules for kopi with milk and no sugar")
        ctrl_sys = ctrl.ControlSystem(
            [rule_13, rule_14, rule_15, rule_34, rule_35, rule_36])
        # sim = ctrl.ControlSystemSimulation(ctrl_sys, flush_after_run=35 * 35 + 1)
        sim = ctrl.ControlSystemSimulation(ctrl_sys)
        sim.input['kopi'] = kopi_input
        sim.input['sugar_pre'] = sugar_input
        sim.input['milk'] = milk_input
        sim.compute()
        score = sim.output['output']
        # output.view(sim=sim)
        # pyplot.show()
    elif milk_y == 1 and sugar_y == 1:
        # print("Rules for kopi various levels of milk and sugar")
        ctrl_sys = ctrl.ControlSystem([
            rule_16, rule_17, rule_18, rule_19, rule_20, rule_21, rule_22,
            rule_23, rule_24, rule_25, rule_26, rule_27, rule_28, rule_29,
            rule_30, rule_31, rule_32, rule_33
        ])
        # sim = ctrl.ControlSystemSimulation(ctrl_sys, flush_after_run=35 * 35 + 1)
        sim = ctrl.ControlSystemSimulation(ctrl_sys)
        sim.input['kopi'] = kopi_input
        sim.input['sugar'] = sugar_input
        sim.input['milk'] = milk_input
        sim.compute()
        score = sim.output['output']
        # output.view(sim=sim)
        # pyplot.show()

    # #Calculate fuzzy score output for determing the Kopi type
    # # score = fuzzyscore()
    # ctrl_sys= ctrl.ControlSystem([rule_1,rule_2,rule_3,rule_4,rule_5,rule_6,rule_7,rule_8,rule_9,rule_10,rule_11,rule_12,rule_13,rule_14,rule_15,rule_16,rule_17,rule_18,rule_19,rule_20,rule_21,rule_22,rule_23,rule_24,rule_25,rule_26,rule_27,rule_28,rule_29,rule_30,rule_31,rule_32,rule_33,rule_34,rule_35,rule_36])
    # sim = ctrl.ControlSystemSimulation(ctrl_sys, flush_after_run=35 * 35 + 1)

    # for i in range(1,11):
    #     print(fuzz.interp_membership(kopi.universe,kopi_thin,i))
    #     print(fuzz.interp_membership(kopi.universe,kopi_norm,i))
    #     print(fuzz.interp_membership(kopi.universe,kopi_thick,i))
    #     for j in range(1,11):
    #         print("milk")
    #         milk_input=j
    #         sugar_input=9
    #         print(fuzz.interp_membership(milk.universe,milk_less,milk_input))
    #         print(fuzz.interp_membership(milk.universe,milk_norm,milk_input))
    #         print(fuzz.interp_membership(milk.universe,milk_extra,milk_input))
    #         sim.input['kopi']= i
    #         sim.input['milk']= milk_input
    #         sim.input['milk_pre']= milk_input
    #         sim.input['sugar']= sugar_input
    #         sim.input['sugar_pre']= sugar_input
    #         sim.compute()
    #         score = sim.output['output']
    #         print(score)

    print("score = ", end="\t")
    print(score)
    #return (score)
    return names[int(round(score)) + 19]
예제 #23
0
def fuzzy_contrast(folder, image_file, figsize=(10, 10),
                   channel=None, show=False):
    """Increase the contrast of input image by using fuzzy logic.

    Parameters
    ----------
    folder : string
        Directory containing image_file
    image_file : string
        Filename of image to be analyzed
    figsize : tuple of int or float
        Size of output image
    show : bool
        If True, outputs image to Jupyter notebook display.
    channel : int
        Channel of image to read in for multichannel images e.g.
        testim[:, :, channel]

    Returns
    -------
    rf_image : numpy.ndarray
        Output image

    Examples
    --------

    """

    # Build fuzzy logic system.
    dark = ctrl.Antecedent(np.linspace(0, 1, 101), 'dark')
    darker = ctrl.Consequent(np.linspace(0, 1, 101), 'darker')

    w = 90
    dark['dark'] = 1 - fuzz.sigmf(dark.universe, 0.425, w)
    dark['gray'] = fuzz.trimf(dark.universe, [0.35, 0.5, 0.65])
    dark['bright'] = fuzz.sigmf(dark.universe, 0.575, w)

    slope = 3.7
    width = 0.04
    darker['darker'] = fuzz.gbellmf(darker.universe, width, slope, 0.1)
    darker['midgray'] = fuzz.gbellmf(darker.universe, width, slope, 0.5)
    darker['brighter'] = fuzz.gbellmf(darker.universe, width, slope, 0.9)

    rule1 = ctrl.Rule(dark['dark'], darker['darker'])
    rule2 = ctrl.Rule(dark['gray'], darker['midgray'])
    rule3 = ctrl.Rule(dark['bright'], darker['brighter'])

    Fctrl = ctrl.ControlSystem([rule1, rule2, rule3])
    F = ctrl.ControlSystemSimulation(Fctrl)

    # Apply to image
    fname = '{}/{}'.format(folder, image_file)
    test_image = sio.imread(fname)
    if channel is None:
        test_image = test_image / test_image.max()
    else:
        test_image = test_image[:, :, channel] / test_image[:, :, channel].max()
    F.input['dark'] = test_image
    F.compute()
    fuzzy_image = F.output['darker']
    rf_image = (255.0 / fuzzy_image.max() * (fuzzy_image - fuzzy_image.min())
                ).astype(np.uint8)

    if show:
        fig, ax = plt.subplots(figsize=figsize)
        ax.imshow(rf_image, cmap='gray', vmin=0, vmax=255.0)
        ax.axis('off')

    output = "fuzzy_{}.png".format(image_file.split('.')[0])
    sio.imsave(folder+'/'+output, rf_image)

    return rf_image
예제 #24
0
    def __init__(self):
        # Create fuzzy variables
        num_pieces = ctrl.Antecedent(np.arange(2, 33, 1), 'num_pieces')
        num_moves = ctrl.Antecedent(np.arange(0, 150, 1), 'num_moves')
        white_king_advanced_squares = ctrl.Antecedent(
            np.arange(1, 9, 1), 'white_king_advanced_squares')
        black_king_advanced_squares = ctrl.Antecedent(
            np.arange(1, 9, 1), 'black_king_advanced_squares')
        game_phase = ctrl.Consequent(np.linspace(0, 1, 50), 'game_phase')

        # Populate the fuzzy variables with membership functions
        num_pieces['LOW'] = fuzz.gaussmf(num_pieces.universe, 0, 8)
        num_pieces['MEDIUM'] = fuzz.pimf(num_pieces.universe, 4, 15, 17, 28)
        num_pieces['HIGH'] = fuzz.gaussmf(num_pieces.universe, 32, 8)

        num_moves['LOW'] = fuzz.sigmf(num_moves.universe, 10, -.4)
        num_moves['MEDIUM'] = fuzz.pimf(num_moves.universe, 10, 20, 30, 60)
        num_moves['HIGH'] = fuzz.sigmf(num_moves.universe, 45, .1)

        a = fuzz.trimf(black_king_advanced_squares.universe, [1, 1, 8])
        b = fuzz.trimf(black_king_advanced_squares.universe, [1, 8, 8])
        white_king_advanced_squares['RETREATED'] = a
        white_king_advanced_squares['ADVANCED'] = b
        black_king_advanced_squares['RETREATED'] = a
        black_king_advanced_squares['ADVANCED'] = b

        n = ['OPENING', 'MIDDLE', 'END']
        # game_phase.automf(names=n)

        game_phase['OPENING'] = fuzz.trimf(game_phase.universe, [0, 0, .4])
        game_phase['MIDDLE'] = fuzz.trimf(game_phase.universe, [.3, .5, .7])
        game_phase['END'] = fuzz.trimf(game_phase.universe, [.6, 1, 1])

        # Add extra game phases for king file rules.
        game_phase['PROBABLY_OPENING'] = fuzz.trapmf(game_phase.universe,
                                                     [0, 0, .5, .6]) / 4
        game_phase['PROBABLY_END'] = fuzz.trapmf(game_phase.universe,
                                                 [.4, .5, 1, 1]) / 4

        rules = [
            ctrl.Rule(antecedent=num_pieces['HIGH'],
                      consequent=game_phase['OPENING']),
            ctrl.Rule(antecedent=num_pieces['MEDIUM'],
                      consequent=game_phase['MIDDLE']),
            ctrl.Rule(antecedent=num_pieces['LOW'],
                      consequent=game_phase['END']),
            ctrl.Rule(antecedent=num_moves['LOW'],
                      consequent=game_phase['OPENING']),
            ctrl.Rule(antecedent=num_moves['MEDIUM'],
                      consequent=game_phase['MIDDLE']),
            ctrl.Rule(antecedent=num_moves['HIGH'],
                      consequent=game_phase['END']),
            ctrl.Rule(antecedent=(white_king_advanced_squares['RETREATED']
                                  & black_king_advanced_squares['RETREATED']),
                      consequent=game_phase['PROBABLY_OPENING']),
            ctrl.Rule(antecedent=(white_king_advanced_squares['RETREATED']
                                  & black_king_advanced_squares['ADVANCED']),
                      consequent=game_phase['PROBABLY_OPENING']),
            ctrl.Rule(antecedent=(white_king_advanced_squares['ADVANCED']
                                  & black_king_advanced_squares['RETREATED']),
                      consequent=game_phase['PROBABLY_OPENING']),
            ctrl.Rule(antecedent=(white_king_advanced_squares['ADVANCED']
                                  & black_king_advanced_squares['ADVANCED']),
                      consequent=game_phase['PROBABLY_END'])
        ]

        system = ctrl.ControlSystem(rules=rules)
        self.sim = ctrl.ControlSystemSimulation(
            system, flush_after_run=1)  # TODO: when to flush.
예제 #25
0
import numpy as np
import skfuzzy as sk
import matplotlib.pyplot as plt

# Se defube un array x para el manejo del factor de calidad en un restaurante
x = np.arange(-11, 11, 1)

# Se defube un array para la funcion miembro gauss
calidad = sk.sigmf(x, 0, 1)

# Graficar
plt.figure()
plt.plot(x, calidad, 'b', linewidth=1.5, label='Servicio')

plt.title('Calidad del servicio en un restaurante')
plt.ylabel('Membresia')
plt.xlabel('Nivel de servicio')
plt.legend(loc='center right', bbox_to_anchor=(
    1.25, 0.5), ncol=1, fancybox=True, shadow=True)
예제 #26
0
Al = ctrl.Consequent(alergia, 'Al')
In = ctrl.Consequent(influenza, 'In')

# linguistic values
diagno = ['PP', 'Po', 'X', 'Pr' 'MP']
Co.automf(5, names=diagno)
Re.automf(5, names=diagno)
Al.automf(5, names=diagno)
In.automf(5, names=diagno)

# -------------------------------------
# Generate fuzzy membership functions
# -------------------------------------

# Covid-19
Co['PP'] = fuzz.sigmf(Co.universe, -50, 0.2)
Co['Po'] = fuzz.gbellmf(Co.universe, 0.14, 2.5, 0.33)
Co['Pr'] = fuzz.gbellmf(Co.universe, 0.14, 2.5, 0.66)
Co['MP'] = fuzz.sigmf(Co.universe, 50, 0.8)

# Resfriado
Re['PP'] = fuzz.sigmf(Re.universe, -50, 0.2)
Re['Po'] = fuzz.gbellmf(Re.universe, 0.14, 2.5, 0.33)
Re['Pr'] = fuzz.gbellmf(Re.universe, 0.14, 2.5, 0.66)
Re['MP'] = fuzz.sigmf(Re.universe, 50, 0.8)

# Alergia
Al['PP'] = fuzz.sigmf(Al.universe, -50, 0.2)
Al['Po'] = fuzz.gbellmf(Al.universe, 0.14, 2.5, 0.33)
Al['Pr'] = fuzz.gbellmf(Al.universe, 0.14, 2.5, 0.66)
Al['MP'] = fuzz.sigmf(Al.universe, 50, 0.8)
예제 #27
0
파일: newFIS.py 프로젝트: valentina2095/AI
arousal['very high'] = fuzz.gaussmf(arousal.universe, 4.9, 1.3)

valence['very low'] = fuzz.gaussmf(valence.universe, -4.8, 1.6)
valence['low'] = fuzz.gaussmf(valence.universe, -3, 1.5)
valence['mid'] = fuzz.gaussmf(valence.universe, 0, 1.3)
valence['high'] = fuzz.gaussmf(valence.universe, 3.5, 1.7)
valence['very high'] = fuzz.gaussmf(valence.universe, 4.9, 1.3)

angle['happiness'] = fuzz.gaussmf(angle.universe, 13, 53)
angle['excitement'] = fuzz.gaussmf(angle.universe, 70, 40)
angle['frustration'] = fuzz.gaussmf(angle.universe, 135, 35)
angle['depression'] = fuzz.gaussmf(angle.universe, 218, 37)
angle['boredom'] = fuzz.gaussmf(angle.universe, 280, 40)
angle['calm'] = fuzz.gaussmf(angle.universe, 350, 55)

intensity['low'] = fuzz.sigmf(intensity.universe, 2, -4)
intensity['middle'] = fuzz.pimf(intensity.universe, 2, 2.1, 4.9, 5)
intensity['high'] = fuzz.sigmf(intensity.universe, 5, 4)

arousal.view()
valence.view()
angle.view()
intensity.view()

#### arousal-valence to angle relations ####
rule1a = ctrl.Rule(valence['very low'] & arousal['very low'],
                   angle['depression'])
rule2a = ctrl.Rule(valence['very low'] & arousal['low'], angle['depression'])
rule3a = ctrl.Rule(valence['very low'] & arousal['mid'], angle['depression'])
rule4a = ctrl.Rule(valence['very low'] & arousal['high'], angle['frustration'])
rule5a = ctrl.Rule(valence['very low'] & arousal['very high'],