def __init__(self, lowest=0, highest=40, step=0.5):
        super(ControlTemperature, self).__init__()
        self.lowest = lowest
        self.highest = highest
        self.step = step

        self.temp      = np.arange(lowest, highest, step)
        self.temp_err  = np.arange(-50, 50, 0.1)
        self.temp_roc  = np.arange(-30, 30, 0.1)  # degress c per minute
        self.chill_out = np.arange(-100, 100, 1)
        # self.heat_out  = np.arange(0, 100, 1)

        #Current Temperature
        self.te_too_cold = fuzz.trapmf(self.temp_err, [-40, -30, -1.5, -1])
        self.te_cold     = fuzz.trimf(self.temp_err, [-1.5, -1, -0.5])
        self.te_optimal  = fuzz.trimf(self.temp_err, [-0.5, 0, 0.5])
        self.te_hot      = fuzz.trimf(self.temp_err, [0.5, 1, 1.5])
        self.te_too_hot  = fuzz.trapmf(self.temp_err, [1, 1.5, 30, 40])

        #Temperature Rate of Change (deg C per minute)
        self.tr_cooling_quickly = fuzz.trapmf(self.temp_roc, [-20, -10, -0.5, -0.25])

        # Output - Chiller
        self.co_off    = fuzz.trimf(self.chill_out, [0, 0, 5])
        self.co_low    = fuzz.trimf(self.chill_out, [5, 20, 40])
        self.co_medium = fuzz.trimf(self.chill_out, [20, 40, 60])
        self.co_high   = fuzz.trapmf(self.chill_out, [40, 60, 100, 100])

        # Output - Heater
        self.ho_off    = fuzz.trimf(self.chill_out, [-5, 0, 0])
        self.ho_low    = fuzz.trimf(self.chill_out, [-40, -20, -5])
        self.ho_medium = fuzz.trimf(self.chill_out, [-60, -40, -20])
        self.ho_high   = fuzz.trapmf(self.chill_out, [-100, -100, -60, -40])
def test_tipping_problem():
    # The full tipping problem uses many of these methods
    food = ctrl.Antecedent(np.linspace(0, 10, 11), 'quality')
    service = ctrl.Antecedent(np.linspace(0, 10, 11), 'service')
    tip = ctrl.Consequent(np.linspace(0, 25, 26), 'tip')

    food.automf(3)
    service.automf(3)

    # Manual membership function definition
    tip['bad'] = fuzz.trimf(tip.universe, [0, 0, 13])
    tip['middling'] = fuzz.trimf(tip.universe, [0, 13, 25])
    tip['lots'] = fuzz.trimf(tip.universe, [13, 25, 25])

    # Define fuzzy rules
    rule1 = ctrl.Rule(food['poor'] | service['poor'], tip['bad'])
    rule2 = ctrl.Rule(service['average'], tip['middling'])
    rule3 = ctrl.Rule(service['good'] | food['good'], tip['lots'])

    # The control system - defined both possible ways
    tipping = ctrl.ControlSystem([rule1, rule2, rule3])

    tipping2 = ctrl.ControlSystem()
    tipping2.addrule(rule2)
    tipping2.addrule(rule3)
    tipping2.addrule(rule1)

    tip_sim = ctrl.ControlSystemSimulation(tipping)
    tip_sim2 = ctrl.ControlSystemSimulation(tipping2)

    # Inputs added both possible ways
    inputs = {'quality': 6.5, 'service': 9.8}
    for key, value in inputs.items():
        tip_sim.input[key] = value

    tip_sim2.inputs(inputs)

    # Compute the system
    tip_sim.compute()
    tip_sim2.compute()

    # Ensure both methods of defining rules yield the same results
    for val0, val1 in zip(tip_sim.output.values(),
                          tip_sim2.output.values()):
        tst.assert_allclose(val0, val1)

    # Verify against manual computation
    tst.assert_allclose(tip_sim.output['tip'], 19.8578, atol=1e-2, rtol=1e-2)
Exemple #3
0
def rangeToMF(range, type):
    """
    Translate the range into a list of x_values and an MF function. 
    
    range : list/tuple
        range to translate to MF
        
    type : string
        type of MF:
        'sing' - singleton MF
        'gauss' - gaussian MF function (mean, standard deviation)
        'tri' - triangular MF function 
        'trap' - trapezoidal MF function
    """
    c = 100 #number of x points

    minR = float(min(range))
    maxR = float(max(range))
    
    if type == 'sing': #singleton
        c = 10 #special short mf for singleton
        if maxR == minR: 
            #print "SAME R"
            ran = max(abs(0.15*minR),0.0001)
            xrange = [minR-ran, minR+ran, ran/c]
            Xs = [minR-2.*ran, minR-1.*ran, minR, minR+1.*ran, minR+2.*ran,]
            Ys = [0.0, 0.0, 1.0, 0.0, 0.0]
        else:            
            ran = abs(maxR-minR)
            xrange = [minR, maxR, ran/c]
            Xs, Ys = singleton_to_fuzzy(sum(range)/len(range), xrange)
        
    elif type == 'gauss': #gaussian MF
        std_range = (1./4.) #0.25
        if minR == maxR: ran = max(0.0001,abs(0.05*minR))#0.05
        else:            ran = abs(maxR - minR) #check for min=max and get range
        Xs = np.arange(minR - 0.5*ran, maxR + 0.5*ran, 2*ran/c) 
        Ys = fuzz.gaussmf(Xs, sum(range)/len(range), std_range*(ran)) #gaussian mf with 4sigma = range (to 97.7% "certainty")
    
    elif type == 'tri': #triangular MF
        if minR == maxR:
            ran = max(abs(0.2*minR),0.001)
            xrange = [0.9*minR, 1.1*maxR, ran/c,]
            Xs, Ys = singleton_to_fuzzy(sum(range)/len(range), xrange)
        else:
            Xs = np.arange(0.9*minR, 1.1*maxR, (1.1*maxR-0.9*minR)/c) #create fuzzy MF for output
            Ys = fuzz.trimf(Xs, [minR, sum(range)/len(range), maxR])

    elif type == 'trap': #trapezoidal MF
        if minR == maxR:
            ran = max(abs(0.2*minR),0.001)
            xrange = [0.9*minR, 1.1*maxR, ran/c,]
            Xs, Ys = singleton_to_fuzzy(sum(range)/len(range), xrange)
        else:
            Xs = np.arange(0.9*minR, 1.1*maxR, (1.1*maxR-0.9*minR)/c) #create fuzzy MF for output
            Ys = fuzz.trapmf(Xs, [minR, minR, maxR, maxR])
    else: 
        raise StandardError("Unknown type of membership function: %s" % type)
        
    return [np.asarray(Xs), np.asarray(Ys)] #create MF 
Exemple #4
0
 def __init__(self):
     # Generate universe functions
     self.distance = np.arange(0.,181.,1.)
     self.acceleration = np.arange(0.,0.1,0.01)
     
     # Generate Distance membership functions
     self.near = fuzz.trapmf(self.distance, (-1.,-1.,20.,65.))
     self.medium = fuzz.trapmf(self.distance,(35.,80.,120.,135.))
     self.far = fuzz.trapmf(self.distance,(105.,170.,180.,200.))
     
     # Generate Acceleration membership functions
     self.slow = fuzz.trimf(self.acceleration, (-1.,0.,0.05))
     self.normal = fuzz.trapmf(self.acceleration,(0.02,0.035,0.04,0.07))
     self.fast = fuzz.trapmf(self.acceleration,(0.06,0.085,0.1,0.2))
 
     # Fuzzy relation
     self.R1 = fuzz.relation_product(self.near,self.slow)
     self.R2 = fuzz.relation_product(self.medium,self.normal)
     self.R3 = fuzz.relation_product(self.far,self.fast)
     
     
     # Combine the fuzzy relation
     self.R_combined = np.fmax(self.R1, np.fmax(self.R2, self.R3))
     
     self.thetaOne = 0.0
     self.thetaTwo = 0.0
     
     self.InputDistanceAngle = 0.0
     self.OutputAcceleration = 0.0
     
     
     self.visualize = True
Exemple #5
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)
def test_tipping_problem():
    # The full tipping problem uses many of these methods
    food = Antecedent(np.linspace(0, 10, 11), 'quality')
    service = Antecedent(np.linspace(0, 10, 11), 'service')
    tip = Consequent(np.linspace(0, 25, 26), 'tip')

    food.automf(3)
    service.automf(3)

    # Manual membership function definition
    tip['bad'] = trimf(tip.universe, [0, 0, 13])
    tip['middling'] = trimf(tip.universe, [0, 13, 25])
    tip['lots'] = trimf(tip.universe, [13, 25, 25])

    # Define fuzzy rules
    rule1 = Rule(food['poor'] | service['poor'], tip['bad'])
    rule2 = Rule(service['average'], tip['middling'])
    rule3 = Rule(service['good'] | food['good'], tip['lots'])

    # The control system - defined both possible ways
    tipping = ControlSystem([rule1, rule2, rule3])

    tipping2 = ControlSystem()
    tipping2.addrule(rule2)
    tipping2.addrule(rule3)
    tipping2.addrule(rule1)

    tip_sim = ControlSystemSimulation(tipping)
    tip_sim2 = ControlSystemSimulation(tipping2)

    # Inputs added both possible ways
    inputs = {'quality': 6.5, 'service': 9.8}
    for key, value in inputs.items():
        tip_sim.input[key] = value

    tip_sim2.inputs(inputs)

    # Compute the system
    tip_sim.compute()
    tip_sim2.compute()

    assert tip_sim.output == tip_sim2.output
    tst.assert_allclose(tip_sim.output['tip'], 20.244508118433625)
def test_lambda_cut_series():
    x = np.arange(21) - 10
    mfx = fuzz.trimf(x, [-2, 3, 5])

    expected = np.array([[ 0.  , -2.,  5.],
                         [ 0.25,  0.,  4.],
                         [ 0.5 ,  1.,  4.],
                         [ 0.75,  2.,  3.],
                         [ 1.  ,  3.,  3.]])

    assert_allclose(expected, fuzz.lambda_cut_series(x, mfx, 5))
Exemple #8
0
    def __init__(self):
        # Generate universe variables

        distance = ctrl.Antecedent(np.arange(-440, 441, 1), 'distance')  # paddle.x - ball.x
        paddle_speed = ctrl.Consequent(np.arange(-12,13,4), 'speed')  # paddle.x +=paddle_speed


        # Auto-membership function population is possible with .automf(3, 5, or 7)
        # Generate fuzzy membership functions
        distance['far right'] = fuzz.trimf(distance.universe, [-440, -250, -110])
        distance['close right'] = fuzz.trimf(distance.universe, [-200, -10, 0])
        distance['close left'] = fuzz.trimf(distance.universe, [0, 10, 200])
        distance['far left'] = fuzz.trimf(distance.universe, [200, 440, 440])

        paddle_speed.automf(7)
        rule1 = ctrl.Rule(distance['far left'], paddle_speed['dismal'])
        rule2 = ctrl.Rule(distance['close left'], paddle_speed['dismal'])
        rule3 = ctrl.Rule(distance['close right'], paddle_speed['excellent'])
        rule4 = ctrl.Rule(distance['far right'], paddle_speed['excellent'])
        # rule5 = ctrl.Rule(distance['above'], paddle_speed['average'])

        paddle_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4])
        self.agent = ctrl.ControlSystemSimulation(paddle_ctrl)
    def __init__(self):
        # Generate universe variables

        distance = ctrl.Antecedent(np.arange(-8, 9, 1), 'distance')
        trajectory = ctrl.Consequent(np.arange(-2, 3, 1), 'trajectory')

        # Auto-membership function population is possible with .automf(3, 5, or 7)
        distance.automf(3)

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

        rule1 = ctrl.Rule(distance['poor'], trajectory['low'])
        rule2 = ctrl.Rule(distance['average'], trajectory['medium'])
        rule3 = ctrl.Rule(distance['good'], trajectory['high'])

        # 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)
        trajectoryping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
        self.agent = ctrl.ControlSystemSimulation(trajectoryping_ctrl)
def test_lambda_cut():
    x = np.arange(21) - 10
    mfx = fuzz.trimf(x, [-2, 3, 5])

    # fuzz.lambda_cut test
    expected = np.r_[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                     1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
    result = fuzz.lambda_cut(mfx, 0.33)
    assert_allclose(expected, result)

    # fuzz.arglcut test
    expected = np.r_[10, 11, 12, 13, 14]
    result = fuzz.arglcut(mfx, 0.33)

    assert len(result) == 1
    assert_allclose(expected, result[0])
Exemple #11
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]
def throttle_command(speed_read):

    # Universe of discourse
    speed = np.arange(60,150,.1)
    throttle_value = np.arange(0,1,0.01)

    # Input membership functions
    too_slow = fuzz.trapmf(speed,[60,60,80,85])
    slow = fuzz.trimf(speed,[83,90,97])
    cruise = fuzz.trimf(speed,[95,100,105])
    fast = fuzz.trimf(speed,[103,110,117])
    too_fast = fuzz.trapmf(speed,[115,120,150,150])

    # Output membership functions
    very_low = fuzz.trimf(throttle_value,[0,0,0.15])
    low = fuzz.trimf(throttle_value,[0.1,0.25,0.4])
    medium = fuzz.trimf(throttle_value,[0.35,0.5,0.65])
    high = fuzz.trimf(throttle_value,[0.6,0.75,0.9])
    very_high = fuzz.trimf(throttle_value,[0.85,1,1])

    # membership values
    speed_cat_too_slow = fuzz.interp_membership(speed,too_slow,speed_read)
    speed_cat_slow = fuzz.interp_membership(speed,slow,speed_read)
    speed_cat_cruise = fuzz.interp_membership(speed,cruise,speed_read)
    speed_cat_fast = fuzz.interp_membership(speed,fast,speed_read)
    speed_cat_too_fast = fuzz.interp_membership(speed,too_fast,speed_read)

    # If part of rules
    rule1 = speed_cat_too_slow
    rule2 = speed_cat_slow
    rule3 = speed_cat_cruise
    rule4 = speed_cat_fast
    rule5 = speed_cat_too_fast

    # Then part of rules
    imp1 = np.fmin(rule1,very_high)
    imp2 = np.fmin(rule2,high)
    imp3 = np.fmin(rule3,medium)
    imp4 = np.fmin(rule4,low)
    imp5 = np.fmin(rule5,very_low)

    aggregate_membership = np.fmax(imp1,np.fmax(imp2,np.fmax(imp3,np.fmax(imp4,imp5))))

    return fuzz.defuzz(throttle_value,aggregate_membership,'centroid')
def test_bisector():
    x = np.arange(6)
    mfx = fuzz.trimf(x, [0, 5, 5])
    expected = 3.53553390593274

    # Test both triangle code paths
    assert_allclose(expected, fuzz.defuzz(x, mfx, 'bisector'))
    assert_allclose(5 - expected, fuzz.defuzz(x, 1 - mfx, 'bisector'))

    # Test singleton input
    y = np.r_[2]
    mfy = np.r_[0.33]
    assert_allclose(y, fuzz.defuzz(y, mfy, 'bisector'))

    # Test rectangle code path
    mfx = fuzz.trapmf(x, [2, 2, 4, 4])
    assert_allclose(3., fuzz.defuzz(x, mfx, 'bisector'))
Exemple #14
0
 def load_rules(self, filename):
     with open(filename, 'r') as jsonfile:
             rules = json.loads(jsonfile.read())
             self.actions = rules['actions']
             self.state = rules['state']
             self.rules = rules['results']
             self.x = np.arange(self.state['min'], self.state['max'])
             for subset, parts in self.rules.items():
                 aggregated = []
                 points = []
                 for n, v in parts.items():
                     print n
                     if v['mf'] == 'tri':
                         mf = fuzz.trimf(self.x, v['shp'])
                     if v['mf'] == 'trap':
                         mf = fuzz.trapmf(self.x, v['shp'])
                     elif v['mf'] == 'gbell':
                         mf = fuzz.gbellmf(self.x, v['shp'])
                     aggregated.append(mf)
                     points.append(v['pts'])
                 self.rules[subset] = (aggregated, points)
Exemple #15
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]
Exemple #16
0
def paramsToMF(params):
    """
    Translate the piecewise params list of x_values to an MF function. Assumes a 
    list of length: 
    1 - singleton MF
    2 - gaussian MF function (mean, standard deviation)
    3 - triangular MF function 
    4 - trapezoidal MF function
    """
    c = 100.0
    if len(params) == 1: #singleton
        c = 50 #special short MF for singleton
        xrange = [0.9*params[0], 1.1*params[0], 2*0.2*params[0]/c]
        x, y = singleton_to_fuzzy(params[0], xrange)
        
    if len(params) == 2: #gaussian MF
        #print "PARAMS:", params
        if params[1] == 0.0: v = 0.01*params[0]
        else:                v = params[1]
        x = np.arange( params[0] - 6*v, 
                       params[0] + 6*v,
                      (14.0*v/c) ) #use 6 sigmas
        y = fuzz.gaussmf(x, params[0], params[1])
        
    elif len(params) == 3: #triangular MF
        if max(params) == min(params): prange = max(params)
        else:                          prange = max(params) - min(params)
        x = np.arange( min(params), max(params),prange/c)
        y = fuzz.trimf(x, params)  
                   
    elif len(params) == 4: #trapezoidal MF
        if max(params) == min(params): prange = max(params)
        else:                          prange = max(params) - min(params)
        x = np.arange( min(params), max(params),prange/c)
        y = fuzz.trapmf(x, params)
        
    return [np.asarray(x), np.asarray(y)] #create MF 
def test_lambda_cut_boundaries_degenerate():
    x = np.arange(11)
    mfx = fuzz.trimf(x, [0, 7, 10])
    assert_allclose(fuzz.lambda_cut_boundaries(x, mfx, 1), np.r_[7])
def test_multiple_rules_same_consequent_term():
    # 2 input variables, 1 output variable and 7 instances.
    x1_inputs = [0.6, 0.2, 0.4, 0.7, 1, 1.2, 1.8]
    x2_inputs = [0.9, 1, 0.8, 0, 1.2, 0.6, 1.8]

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

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

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

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

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

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

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

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

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

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

        sim0.compute()
        sim1.compute()

        tst.assert_allclose(sim0.output['y'], sim1.output['y'])
        tst.assert_allclose(expected, sim0.output['y'], atol=1e-4, rtol=1e-4)
Exemple #19
0
import numpy as np
import skfuzzy as fuzz

# New Antecedent/Consequent objects hold universe variables and membership functions
quality = fuzz.Antecedent(np.arange(0, 11, 1), 'quality')
service = fuzz.Antecedent(np.arange(0, 11, 1), 'service')
tip = fuzz.Consequent(np.arange(0, 26, 1), 'tip')

# Auto-membership function population is possible with .automf(3, 5, or 7)
quality.automf(3)
service.automf(3)

# Custom membership functions can be built interactively with a familiar, Pythonic API
tip['poor'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['average'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['good'] = fuzz.trimf(tip.universe, [13, 25, 25])

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

# Rule objects connect one or more antecedent membership functions with
# one or more consequent membership functions, using 'or' or 'and' to combine the antecedents.
#   * rule1: "If food is poor OR services is poor, then tip will be poor
#   * rule2: "If service is average, then tip will be average
#   * rule3: "If service is good OR food is good, then tip will be good
rule1 = fuzz.Rule([quality['poor'], service['poor']], tip['poor'], kind='or')
rule2 = fuzz.Rule(service['average'], tip['average'])
rule3 = fuzz.Rule([service['good'], quality['good']], tip['good'])
    def __init__(self, intensidade_interacoes_AC, intensidade_interacoes_BC, similaridade_entre_vertices, idade_interacoes_AC, idade_interacoes_BC):
        print intensidade_interacoes_AC, intensidade_interacoes_BC, similaridade_entre_vertices, idade_interacoes_AC,idade_interacoes_BC
        self.intensidade_interacoes_AC = intensidade_interacoes_AC
        self.intensidade_interacoes_BC = intensidade_interacoes_BC
        self.similaridade_entre_vertices = similaridade_entre_vertices
        self.idade_interacoes_AC = idade_interacoes_AC
        self.idade_interacoes_BC = idade_interacoes_BC
        
        # Generate universe variables
        self.x_intensidade_interacoes_AC   = np.arange(0, 10, 1)
        self.x_intensidade_interacoes_BC   = np.arange(0, 10, 1)
        self.x_similaridade_entre_vertices = np.arange(0, 101, 1)
        self.x_idade_interacoes_AC         = np.arange(0, 10, 1)
        self.x_idade_interacoes_BC         = np.arange(0, 10, 1)
        self.x_potencial_ligacao           = np.arange(0, 100, 1)

        # Generate fuzzy membership functions
        self.intensidade_interacoes_AC_baixa   = fuzz.trimf(self.x_intensidade_interacoes_AC, [0, 0, 6])
        self.intensidade_interacoes_AC_alta    = fuzz.trapmf(self.x_intensidade_interacoes_AC, [2, 6, 10, 10])
        self.intensidade_interacoes_BC_baixa   = fuzz.trimf(self.x_intensidade_interacoes_BC, [0, 0, 6])
        self.intensidade_interacoes_BC_alta    = fuzz.trapmf(self.x_intensidade_interacoes_BC, [2, 6, 10, 10])
        self.similaridade_entre_vertices_baixa = fuzz.trimf(self.x_similaridade_entre_vertices, [0, 0, 60])
        self.similaridade_entre_vertices_alta  = fuzz.trimf(self.x_similaridade_entre_vertices, [40, 100, 100])
        self.idade_interacoes_AC_baixa         = fuzz.trimf(self.x_idade_interacoes_AC, [0, 0, 6])
        self.idade_interacoes_AC_alta          = fuzz.trimf(self.x_idade_interacoes_AC, [4, 10, 10])
        self.idade_interacoes_BC_baixa         = fuzz.trimf(self.x_idade_interacoes_BC, [0, 0, 6])
        self.idade_interacoes_BC_alta          = fuzz.trimf(self.x_idade_interacoes_BC, [4, 10, 10])
        self.potencial_ligacao_baixo           = fuzz.trimf(self.x_potencial_ligacao, [0, 0, 60])
        self.potencial_ligacao_medio           = fuzz.trimf(self.x_potencial_ligacao, [10, 50, 90])
        self.potencial_ligacao_alto            = fuzz.trimf(self.x_potencial_ligacao, [40, 100, 100])
    
        self.grau_intensidade_interacoes_AC_baixa   = fuzz.interp_membership(self.x_intensidade_interacoes_AC, self.intensidade_interacoes_AC_baixa, intensidade_interacoes_AC)
        self.grau_intensidade_interacoes_AC_alta    = fuzz.interp_membership(self.x_intensidade_interacoes_AC, self.intensidade_interacoes_AC_alta, intensidade_interacoes_AC)

        self.grau_intensidade_interacoes_BC_baixa   = fuzz.interp_membership(self.x_intensidade_interacoes_BC, self.intensidade_interacoes_BC_baixa, intensidade_interacoes_BC)
        self.grau_intensidade_interacoes_BC_alta    = fuzz.interp_membership(self.x_intensidade_interacoes_BC, self.intensidade_interacoes_BC_alta, intensidade_interacoes_BC)

        self.grau_similaridade_entre_vertices_baixa = fuzz.interp_membership(self.x_similaridade_entre_vertices, self.similaridade_entre_vertices_baixa, similaridade_entre_vertices)
        self.grau_similaridade_entre_vertices_alta  = fuzz.interp_membership(self.x_similaridade_entre_vertices, self.similaridade_entre_vertices_alta, similaridade_entre_vertices)

        self.grau_idade_interacoes_AC_baixa         = fuzz.interp_membership(self.x_idade_interacoes_AC, self.idade_interacoes_AC_baixa, self.idade_interacoes_AC)
        self.grau_idade_interacoes_AC_alta          = fuzz.interp_membership(self.x_idade_interacoes_AC, self.idade_interacoes_AC_alta, self.idade_interacoes_AC)

        self.grau_idade_interacoes_BC_baixa         = fuzz.interp_membership(self.x_idade_interacoes_BC, self.idade_interacoes_BC_baixa, self.idade_interacoes_BC)
        self.grau_idade_interacoes_BC_alta          = fuzz.interp_membership(self.x_idade_interacoes_BC, self.idade_interacoes_BC_alta, self.idade_interacoes_BC)
        
        active_rule1 = np.fmin(self.grau_intensidade_interacoes_AC_alta, np.fmin(self.grau_intensidade_interacoes_BC_alta, np.fmin(self.grau_similaridade_entre_vertices_alta, np.fmin(self.grau_idade_interacoes_AC_baixa, self.grau_idade_interacoes_BC_baixa))))
        potencial_ligacao_rule1 = np.fmin(active_rule1, self.potencial_ligacao_alto)
        print('active_rule1 ', active_rule1)
        

        active_rule2 = np.fmin(self.grau_intensidade_interacoes_AC_baixa, np.fmin(self.grau_intensidade_interacoes_BC_baixa, np.fmin(self.grau_similaridade_entre_vertices_baixa, np.fmin(self.grau_idade_interacoes_AC_alta, self.grau_idade_interacoes_BC_alta))))
        potencial_ligacao_rule2 = np.fmin(active_rule2, self.potencial_ligacao_baixo)
        print('active_rule2 ', active_rule2)
        #print('potencial_ligacao_rule2 ', potencial_ligacao_rule2)

        active_rule3 = np.fmin(self.grau_intensidade_interacoes_AC_alta, np.fmin(self.grau_intensidade_interacoes_BC_alta, np.fmin(self.grau_similaridade_entre_vertices_baixa, np.fmin(self.grau_idade_interacoes_AC_baixa, self.grau_idade_interacoes_BC_baixa))))
        potencial_ligacao_rule3 = np.fmin(active_rule3, self.potencial_ligacao_medio)
        print('active_rule3 ', active_rule3)
        #print('potencial_ligacao_rule3 ', potencial_ligacao_rule3)

        active_rule4 = np.fmin(self.grau_intensidade_interacoes_AC_baixa, np.fmin(self.grau_intensidade_interacoes_BC_baixa, np.fmin(self.grau_similaridade_entre_vertices_alta, np.fmin(self.grau_idade_interacoes_AC_baixa, self.grau_idade_interacoes_BC_baixa))))
        potencial_ligacao_rule4 = np.fmin(active_rule4, self.potencial_ligacao_medio)
        print('active_rule4 ', active_rule4)
        #print('potencial_ligacao_rule4 ', potencial_ligacao_rule4)
        
        # Aggregate all three output membership functions together
        aggregated = np.fmax(potencial_ligacao_rule1,
                             np.fmax(potencial_ligacao_rule2, np.fmax(potencial_ligacao_rule3, potencial_ligacao_rule4)))

        # Calculate defuzzified result
        self.potencial_ligacao = fuzz.defuzz(self.x_potencial_ligacao, aggregated, 'centroid')
        
        self.grau_potencial_ligacao = fuzz.interp_membership(self.x_potencial_ligacao, aggregated, self.potencial_ligacao)
Exemple #21
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(30, 80, 0.1)

# Se define un array para la funcion miembro gauss
lento = sk.trimf(x, [30, 30, 50])
medio = sk.trimf(x, [30, 50, 70])
medio_rapido = sk.trimf(x, [50, 60, 70])
rapido = sk.trimf(x, [60, 80, 780])

# Graficar
plt.figure()
plt.plot(x, rapido, 'b', linewidth=1.5, label='Rapido')
plt.plot(x, medio_rapido, 'k', linewidth=1.5, label='Medio-rapido')
plt.plot(x, medio, 'm', linewidth=1.5, label='Medio')
plt.plot(x, lento, 'r', linewidth=1.5, label='Lento')

plt.title('Pentalti difuso')
plt.ylabel('Membresia')
plt.xlabel('Velocidad (km/h)')
plt.legend(loc='center right',
           bbox_to_anchor=(1.25, 0.5),
           ncol=1,
           fancybox=True,
           shadow=True)
Exemple #22
0
at27['b'] = fuzz.trapmf(at27.universe, [0, minb[27], maxb[27], 1])

at26 = ctrl.Antecedent(np.arange(0, 1, 0.0001), 'at26')
at26['m'] = fuzz.trapmf(at26.universe, [0, minm[26], maxm[26], 1])
at26['b'] = fuzz.trapmf(at26.universe, [0, minb[26], maxb[26], 1])

at29 = ctrl.Antecedent(np.arange(0, 1, 0.0001), 'at29')
at29['m'] = fuzz.trapmf(at29.universe, [0, minm[29], maxm[29], 1])
at29['b'] = fuzz.trapmf(at29.universe, [0, minb[29], maxb[29], 1])

at28 = ctrl.Antecedent(np.arange(0, 1, 0.0001), 'at28')
at28['m'] = fuzz.trapmf(at28.universe, [0, minm[28], maxm[28], 1])
at28['b'] = fuzz.trapmf(at28.universe, [0, minb[28], maxb[28], 1])

output = ctrl.Consequent(np.arange(0, 1, 0.01), 'output')
output['m'] = fuzz.trimf(output.universe, [0, 0, 0.6])
# output['idk'] = fuzz.trimf(output.universe, [0, 0.5, 1])
output['b'] = fuzz.trimf(output.universe, [0.4, 1, 1])

rule1 = ctrl.Rule(
    at0['m'] | at1['m'] | at2['m'] | at3['m'] | at4['m'] | at5['m'] | at6['m']
    | at7['m'] | at8['m'] | at9['m'] | at10['m'] | at11['m'] | at12['m']
    | at13['m'] | at14['m'] | at15['m'] | at16['m'] | at17['m'] | at18['m']
    | at19['m'] | at20['m'] | at21['m'] | at22['m'] | at23['m'] | at24['m']
    | at25['m'] | at26['m'] | at27['m'] | at28['m'] | at29['m'], output['m'])
rule2 = ctrl.Rule(
    at0['b'] | at1['b'] | at2['b'] | at3['b'] | at4['b'] | at5['b'] | at6['b']
    | at7['b'] | at8['b'] | at9['b'] | at10['b'] | at11['b'] | at12['b']
    | at13['b'] | at14['b'] | at15['b'] | at16['b'] | at17['b'] | at18['b']
    | at19['b'] | at20['b'] | at21['b'] | at22['b'] | at23['b'] | at24['b']
    | at25['b'] | at26['b'] | at27['b'] | at28['b'] | at29['b'], output['b'])
Exemple #23
0
def Fuzzy_Ctrl(Goal_pos,Act_pos):
	# New Antecedent/Consequent objects hold universe variables and membership functions
	Distance = ctrl.Antecedent(np.arange(0, 100+0.1, 0.1), 'Distance') #Input
	Angle = ctrl.Antecedent(np.arange(-np.pi, np.pi+0.001, 0.001), 'Angle') #Input

	Velocity = ctrl.Consequent(np.arange(-0.13, 0.26+0.13+0.01, 0.01), 'Velocity') #Output
	Omega = ctrl.Consequent(np.arange(-1.82-1.82-0.01, 1.82+1.82+0.01, 0.01), 'Omega') #Output

	# Auto-membership function population is possible with .automf(3, 5, or 7)
	#Distance.automf(5)
	#Velocity.automf(3)

	# Custom membership functions can be built interactively with a familiar, Pythonic API
	Distance['Near'] = fuzz.trimf(Distance.universe, [0, 0, 0.5])
	Distance['Mid'] = fuzz.trimf(Distance.universe, [0, 0.5, 1])
	Distance['Far'] = fuzz.trapmf(Distance.universe, [0.5, 1, 100, 100])

	Angle['Neg'] = fuzz.trapmf(Angle.universe, [-np.pi, -np.pi, -np.pi/4, 0])
	Angle['Zero'] = fuzz.trimf(Angle.universe, [-np.pi/4, 0, np.pi/4])
	Angle['Pos'] = fuzz.trapmf(Angle.universe, [0, np.pi/4, np.pi, np.pi])

	Velocity['Zero'] = fuzz.trimf(Velocity.universe, [-0.13, 0, 0.13])
	Velocity['Half'] = fuzz.trimf(Velocity.universe, [0, 0.13, 0.26])
	Velocity['Full'] = fuzz.trimf(Velocity.universe, [0.13, 0.26, 0.26+0.13])

	Omega['Negative'] = fuzz.trimf(Omega.universe, [-1.82-1.82, -1.82, 0])
	Omega['Zero'] = fuzz.trimf(Omega.universe, [-1.82, 0, 1.82])
	Omega['Positive'] = fuzz.trimf(Omega.universe, [0, 1.82, 1.82+1.82])

	# You can see how these look with .view()
	#Distance.view()
	#Angle.view()

	#Velocity.view()
	#Omega.view()

	#Identify Rules
	#rule0 = ctrl.Rule(antecedent=((Distance['nb'] & delta['nb']) |
	#                              (Distance['ns'] & delta['nb']) |
	#                              (Distance['nb'] & delta['ns'])),
	#                  consequent=output['nb'], label='rule nb')
	rule1 = ctrl.Rule(Angle['Neg'], Velocity['Zero'])
	rule2 = ctrl.Rule(Angle['Neg'], Omega['Negative'])
	rule3 = ctrl.Rule(Angle['Pos'], Velocity['Zero'])
	rule4 = ctrl.Rule(Angle['Pos'], Omega['Positive'])
	rule5 = ctrl.Rule(Angle['Zero'], Omega['Zero'])
	rule6 = ctrl.Rule(antecedent=((Distance['Near'] & Angle['Zero'])),
		          consequent=Velocity['Zero'])
	rule7 = ctrl.Rule(antecedent=((Distance['Mid'] & Angle['Zero'])),
		          consequent=Velocity['Half'])
	rule8 = ctrl.Rule(antecedent=((Distance['Far'] & Angle['Zero'])),
		          consequent=Velocity['Full'])

	Robot_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8])
	#Robot_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule6, rule7, rule8])
	Motion = ctrl.ControlSystemSimulation(Robot_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)
	dis = np.sqrt((Goal_pos[0]-Act_pos[0])**2+(Goal_pos[1]-Act_pos[1])**2)
	print('distance is',dis)
	Motion.input['Distance'] = dis
	global last
	ang = np.arctan2((Goal_pos[1]-Act_pos[1]),(Goal_pos[0]-Act_pos[0]))-Act_pos[2]
	while ang < last-np.pi: ang += 2*np.pi
	while ang > last+np.pi: ang -= 2*np.pi
	last = ang
	print('angle is',ang)
	Motion.input['Angle'] = ang

	# Crunch the numbers
	Motion.compute()

	print(Motion.output['Velocity'])
	#Velocity.view(sim=Motion)
	out1 = Motion.output['Velocity']

	print(Motion.output['Omega'])
	#Omega.view(sim=Motion)
	out2 = Motion.output['Omega']

	Cont_input = [out1,out2]
	print(Cont_input)
	return Cont_input
Exemple #24
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as karar

ortamSicakligi = karar.Antecedent(np.arange(20, 50, 1), 'ortam sıcaklığı')
nemOrani = karar.Antecedent(np.arange(0, 101, 1), 'nem oranı')
ortamKisiSayisi = karar.Antecedent(np.arange(1, 21, 1),
                                   'ortamdaki kişi sayısı')
sonuc = karar.Consequent(np.arange(0, 101, 1), 'klimanın durumu')

ortamSicakligi['düşük'] = fuzz.trimf(ortamSicakligi.universe, [20, 23, 25])
ortamSicakligi['orta'] = fuzz.trimf(ortamSicakligi.universe, [25, 30, 35])
ortamSicakligi['yüksek'] = fuzz.trimf(ortamSicakligi.universe, [40, 45, 50])

nemOrani['düşük'] = fuzz.trimf(nemOrani.universe, [0, 20, 30])
nemOrani['orta'] = fuzz.trimf(nemOrani.universe, [30, 50, 70])
nemOrani['yüksek'] = fuzz.trimf(nemOrani.universe, [70, 90, 100])

ortamKisiSayisi['az'] = fuzz.trimf(ortamKisiSayisi.universe, [1, 3, 5])
ortamKisiSayisi['orta'] = fuzz.trimf(ortamKisiSayisi.universe, [5, 7, 10])
ortamKisiSayisi['çok'] = fuzz.trimf(ortamKisiSayisi.universe, [10, 15, 20])

sonuc['sıcaklık derecesini arttır'] = fuzz.trimf(sonuc.universe, [0, 0, 50])
sonuc['soğutmayı arttır'] = fuzz.trimf(sonuc.universe, [0, 50, 100])
sonuc['şuanki dereceyi koru'] = fuzz.trimf(sonuc.universe, [50, 100, 100])

ortamSicakligi.view()
nemOrani.view()
ortamKisiSayisi.view()
sonuc.view()
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]
    print("Exception : ", e)

conn.close()
"""
PM10 = np.array(PM10)
NO2 = np.array(NO2)
CO = np.array(CO)
"""

PM10 = np.arange(0, 531, 1)
NO2 = np.arange(0, 2011, 1)
CO = np.arange(0, 32011, 1)
HKİ = np.arange(0, 501, 1)

#pm10_low = fuzz.trapmf(PM10,[0,0,40,75])
pm10_low = fuzz.trimf(PM10, [0, 0, 75])
pm10_medium = fuzz.trimf(PM10, [40, 150, 260])
pm10_high = fuzz.trimf(PM10, [180, 530, 530])
#pm10_high = fuzz.trapmf(PM10,[180,260,530,530])

#no2_low = fuzz.trapmf(NO2,[0,0,50,150])
no2_low = fuzz.trimf(NO2, [0, 0, 150])
no2_medium = fuzz.trimf(NO2, [50, 275, 550])
no2_high = fuzz.trimf(NO2, [300, 2010, 2010])
#no2_high = fuzz.trapmf(NO2,[300,550,2010,2010])

#co_low = fuzz.trapmf(CO,[0,0,4000,7750])
co_low = fuzz.trimf(CO, [0, 0, 7750])
co_medium = fuzz.trimf(CO, [4000, 10000, 16000])
co_high = fuzz.trimf(CO, [12000, 32010, 32010])
#co_high = fuzz.trapmf(CO,[12000,16000,32010,32010])
# Hugo BERANGER - M2 MIAGE IA

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

# Q1
res = ctrl.Antecedent(np.arange(0, 21, 1), 'resultat')
met = ctrl.Antecedent(np.arange(0, 21, 1), 'methode')
pre = ctrl.Antecedent(np.arange(0, 21, 1), 'presentation')
eva = ctrl.Consequent(np.arange(0, 21, 1), 'evaluation')

# Q2 Q3
res['mediocre'] = fuzz.trimf(res.universe, [0, 0, 10])
res['moyen'] = fuzz.trimf(res.universe, [0, 10, 20])
res['excellent'] = fuzz.trimf(res.universe, [10, 20, 20])

met['mediocre'] = fuzz.trimf(met.universe, [0, 0, 10])
met['moyen'] = fuzz.trimf(met.universe, [0, 10, 20])
met['excellent'] = fuzz.trimf(met.universe, [10, 20, 20])

pre['mediocre'] = fuzz.trimf(pre.universe, [0, 0, 10])
pre['moyen'] = fuzz.trimf(pre.universe, [0, 10, 20])
pre['excellent'] = fuzz.trimf(pre.universe, [10, 20, 20])

eva['mediocre'] = fuzz.trimf(eva.universe, [0, 0, 5])
eva['mauvais'] = fuzz.trimf(eva.universe, [0, 5, 10])
eva['moyen'] = fuzz.trimf(eva.universe, [5, 10, 15])
eva['bon'] = fuzz.trimf(eva.universe, [10, 15, 20])
eva['excellent'] = fuzz.trimf(eva.universe, [15, 20, 20])
from skfuzzy import control as ctrl

degree_dirt = ctrl.Antecedent(np.arange(1, 101, 1), 'degree_dirt')
type_dirt = ctrl.Antecedent(np.arange(1, 101, 1), 'type_dirt')
wash_time = ctrl.Consequent(np.arange(0, 61, 1), 'wash_time')

degree_name = ["Low", "Medium", "High"]
type_name = ["NonFat", "Medium", "Fat"]

degree_dirt.automf(names=degree_name)
type_dirt.automf(names=type_name)

degree_dirt.view()
type_dirt.view()

wash_time['very_short'] = fuzz.trimf(wash_time.universe, [0, 8, 12])
wash_time['short'] = fuzz.trimf(wash_time.universe, [8, 12, 20])
wash_time['medium'] = fuzz.trimf(wash_time.universe, [12, 20, 40])
wash_time['long'] = fuzz.trimf(wash_time.universe, [20, 40, 60])
wash_time['very_long'] = fuzz.trimf(wash_time.universe, [40, 60, 60])

wash_time.view()

rule1 = ctrl.Rule(degree_dirt['High'] | type_dirt['Fat'],
                  wash_time['very_long'])
rule2 = ctrl.Rule(degree_dirt['Medium'] | type_dirt['Fat'], wash_time['long'])
rule3 = ctrl.Rule(degree_dirt['Low'] | type_dirt['Fat'], wash_time['long'])
rule4 = ctrl.Rule(degree_dirt['High'] | type_dirt['Medium'], wash_time['long'])
rule5 = ctrl.Rule(degree_dirt['Medium'] | type_dirt['Medium'],
                  wash_time['medium'])
rule6 = ctrl.Rule(degree_dirt['Low'] | type_dirt['Medium'],
Exemple #29
0
# Generate universe variables
#   * Quality and service on subjective ranges [0, 10]
#   * Tip has a range of [0, 25] in units of percentage points

distance = 80
energy = 0
temperature = 30

x_distance = np.arange(0, 300, 1)
x_energy = np.arange(0, 100, 1)
x_temperature = np.arange(20, 30, 1)
x_speed = np.arange(0, 1, 0.1)

# Generate fuzzy membership functions for distance
distance_lo = fuzz.trimf(x_distance, [0, 0, 150])
distance_md = fuzz.trimf(x_distance, [0, 150, 300])
distance_hi = fuzz.trimf(x_distance, [150, 300, 300])

energy_lo = fuzz.trimf(x_energy, [0, 0, 50])
energy_md = fuzz.trimf(x_energy, [0, 50, 100])
energy_hi = fuzz.trimf(x_energy, [50, 100, 100])

temperature_lo = fuzz.trimf(x_temperature, [20, 20, 25])
temperature_md = fuzz.trimf(x_temperature, [20, 25, 30])
temperature_hi = fuzz.trimf(x_temperature, [25, 30, 30])

speed_lo = fuzz.trimf(x_speed, [0, 0, 0.5])
speed_md = fuzz.trimf(x_speed, [0, 0.5, 1])
speed_hi = fuzz.trimf(x_speed, [0.5, 1, 1])
Exemple #30
0
import numpy as np
import math
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Cria as variáveis do problema
distanciaEsq = ctrl.Antecedent(np.arange(0, 25, 0.01), 'distanciaEsq')
distanciaDir = ctrl.Antecedent(np.arange(0, 25, 0.01), 'distanciaDir')
distanciaFre = ctrl.Antecedent(np.arange(0, 25, 0.01), 'distanciaFre')
velocidadeEsq = ctrl.Consequent(np.arange(-1, 10, 0.5), 'velocidadeEsq')
velocidadeDir = ctrl.Consequent(np.arange(-1, 10, 0.5), 'velocidadeDir')

# Cria as funções de pertinência usando tipos variados
distanciaEsq['perto'] = fuzz.trapmf(distanciaEsq.universe, [0, 0, 0.5, 2])
distanciaEsq['media'] = fuzz.trimf(distanciaEsq.universe, [0.5, 2, 10])
distanciaEsq['longe'] = fuzz.trapmf(distanciaEsq.universe, [2, 10, 25, 25])

distanciaDir['perto'] = fuzz.trapmf(distanciaDir.universe, [0, 0, 0.5, 2])
distanciaDir['media'] = fuzz.trimf(distanciaDir.universe, [0.5, 2, 10])
distanciaDir['longe'] = fuzz.trapmf(distanciaDir.universe, [2, 10, 25, 25])

distanciaFre['perto'] = fuzz.trapmf(distanciaFre.universe, [0, 0, 0.01, 0.05])
distanciaFre['media'] = fuzz.trimf(distanciaFre.universe, [0.01, 2, 10])
distanciaFre['longe'] = fuzz.trapmf(distanciaFre.universe, [2, 10, 25, 25])

velocidadeEsq['negativa'] = fuzz.trimf(velocidadeEsq.universe, [-1, -1, 0])
velocidadeEsq['baixa'] = fuzz.trimf(velocidadeEsq.universe, [0, 0, 0.5])
velocidadeEsq['media'] = fuzz.trimf(velocidadeEsq.universe, [0.5, 2, 5])
velocidadeEsq['alta'] = fuzz.trapmf(velocidadeEsq.universe, [2, 5, 8, 10])
    imp4 = np.fmin(rule4,low)
    imp5 = np.fmin(rule5,very_low)

    aggregate_membership = np.fmax(imp1,np.fmax(imp2,np.fmax(imp3,np.fmax(imp4,imp5))))

    return fuzz.defuzz(throttle_value,aggregate_membership,'centroid')

# Self Test locally
speeds = np.arange(60,150,0.1)
y = np.zeros_like(speeds)
for i in range(len(speeds)):
    y[i] = throttle_command(speeds[i])

# Input membership functions
too_slow = fuzz.trapmf(speeds,[60,60,80,85])
slow = fuzz.trimf(speeds,[83,90,97])
cruise = fuzz.trimf(speeds,[95,100,105])
fast = fuzz.trimf(speeds,[103,110,117])
too_fast = fuzz.trapmf(speeds,[115,120,150,150])


plt.plot(speeds,y,speeds,too_slow,speeds,slow,speeds,cruise,speeds,fast,speeds,too_fast)
plt.xlabel('Airspeed (KIAS)')
plt.ylabel('Throttle Command/Speed Membership Functions')
plt.title('Throttle Commands vs. Airspeeds')
plt.legend(('Throttle Commands','Too Slow','Slow','Cruise','Fast','Too Fast'),bbox_to_anchor=(1.05, 1),loc=2, borderaxespad=0.)
plt.show()


### Test with x-plane
### Need to make sure that the ip address and send/recieve ports match your setup
Exemple #32
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
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 is possible with .automf(3, 5, or 7)
quality.automf(3)
service.automf(3)
# Custom membership functions can be built interactively with a familiar,
# Pythonic API
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()
service.view()
tip.view()

##
rule1 = ctrl.Rule(quality['poor'] | service['poor'], tip['low'])
rule2 = ctrl.Rule(service['average'], tip['medium'])
rule3 = ctrl.Rule(service['good'] | quality['good'], tip['high'])
rule1.view()
#
tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
Exemple #33
0
    cpu_medium = fuzz.trapmf(x_cpu, [0.1, 0.45, 0.55, 0.9 ])
    cpu_high = fuzz.trapmf(x_cpu, [0.4, 0.7, 0.8, 1.1 ])
    cpu_veryhigh = fuzz.trapmf(x_cpu, [0.6, 0.95, 1.05, 1.4 ])

    mem_verylow = fuzz.trapmf(x_mem, [-0.2, -0.1, 0.1, 0.4 ])
    mem_low = fuzz.trapmf(x_mem, [-0.1, 0.2, 0.3, 0.6 ])
    mem_medium = fuzz.trapmf(x_mem, [0.1, 0.45, 0.55, 0.9 ])
    mem_high = fuzz.trapmf(x_mem, [0.4, 0.7, 0.8, 1.1 ])
    mem_veryhigh = fuzz.trapmf(x_mem, [0.6, 0.95, 1.05, 1.4 ])

    rsptmstddev_low = fuzz.trapmf(x_rsptmstddev, [-0.1, -0.01, 0.2, 0.6 ])
    rsptmstddev_medium = fuzz.trapmf(x_rsptmstddev, [0.1, 0.4, 0.6, 1 ])
    rsptmstddev_high = fuzz.trapmf(x_rsptmstddev, [0.5, 0.8, 1, 1.3 ])

    load_extdec = fuzz.trapmf(x_load, [-0.7, -0.65, 0.55, 0.5 ])
    load_veryfastdec = fuzz.trimf(x_load, [ -0.6, -0.5, -0.4 ])
    load_fastdec = fuzz.trimf(x_load, [ -0.5, -0.4, -0.3 ])
    load_dec = fuzz.trimf(x_load, [ -0.4, -0.3, -0.2 ])
    load_smalldec = fuzz.trimf(x_load, [ -0.3, -0.2, -0.1 ])
    load_verysmalldec = fuzz.trimf(x_load, [ -0.2, -0.1, 0 ])
    load_nochange = fuzz.trimf(x_load, [-0.1, 0, 0.1 ])
    load_smallincrease = fuzz.trimf(x_load, [ 0, 0.1, 0.2 ])
    load_increase = fuzz.trimf(x_load, [ 0.1, 0.2, 0.3 ])
    load_fastincrease = fuzz.trimf(x_load, [ 0.2, 0.3, 0.4 ])
    load_veryfastincrease = fuzz.trapmf(x_load, [0.3, 0.35, 0.45, 0.5 ])

    # Input: service score and food score
    cpu_score = cpu_val / 100
    mem_score = mem_val / 100
    rsptime_score = rsp_time_val
Exemple #34
0
# membership function of the distance in region left
d_L = ctrl.Antecedent(np.arange(0, 8, 0.1), 'd_L')
d_L['N'] = fuzz.zmf(d_L.universe, 1.2, 8)
d_L['F'] = fuzz.smf(d_L.universe, 1.2, 8)

d_R = ctrl.Antecedent(np.arange(0, 4, 0.1), 'd_R')
d_R['N'] = fuzz.zmf(d_R.universe, 1.2, 8)
d_R['F'] = fuzz.smf(d_R.universe, 1.2, 8)

d_F = ctrl.Antecedent(np.arange(0, 4, 0.1), 'd_F')
d_F['N'] = fuzz.zmf(d_F.universe, 1.2, 8)
d_F['F'] = fuzz.smf(d_F.universe, 1.2, 8)
# d_R.view()

v = ctrl.Consequent(np.arange(0, 1.1, 0.1), 'v')
v['VL'] = fuzz.trimf(v.universe, [0, 0, 0.8])
v['L'] = fuzz.trimf(v.universe, [0, 0.8, 1])
v['H'] = fuzz.trimf(v.universe, [0.8, 1, 1])
# v.view()

theta = ctrl.Consequent(np.arange(0, 90.001, 0.1), 'theta')
theta['VS'] = fuzz.trimf(theta.universe, [0, 0, 22.5])
theta['S'] = fuzz.trimf(theta.universe, [0, 22.5, 45])
theta['M'] = fuzz.trimf(theta.universe, [22.5, 45, 67.5])
theta['B'] = fuzz.trimf(theta.universe, [45, 67.5, 90])
theta['VB'] = fuzz.trimf(theta.universe, [67.5, 90, 90])

# d_F.view()
# One Direction
# L
rule1 = ctrl.Rule(d_L['F'], v['VL'])
#control difuso
# jonatan hernandez henao
#1053864927
#encontrar valor de la propina a partir de la calidad del servicio

#importar librerias
import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt

x_calidad = np.arange(0, 11, 1)
x_servicio = np.arange(0, 11, 1)
x_propina = np.arange(0, 26, 1)

calidad_baja = fuzz.trimf(x_calidad, [0, 0, 5])
calidad_media = fuzz.trimf(x_calidad, [0, 5, 10])
calidad_alta = fuzz.trimf(x_calidad, [5, 10, 10])

servicio_bajo = fuzz.trimf(x_servicio, [0, 0, 5])
servicio_medio = fuzz.trimf(x_servicio, [0, 5, 10])
servicio_alto = fuzz.trimf(x_servicio, [5, 10, 10])

propina_baja = fuzz.trimf(x_propina, [0, 0, 13])
propina_media = fuzz.trimf(x_propina, [0, 13, 25])
propina_alta = fuzz.trimf(x_propina, [13, 25, 25])

fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(8, 9))
ax0.plot(x_calidad, calidad_baja, 'b', linewidth=1.5, label='Mala')
ax0.plot(x_calidad, calidad_media, 'g', linewidth=1.5, label='Aceptable')
ax0.plot(x_calidad, calidad_alta, 'r', linewidth=1.5, label='Buena')
ax0.set_title('Calidad de la comida')
Exemple #36
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
# input vaiable cgpa ,industry_knowledge , extra_co activties
#generating Universe variables for student performance to calculate CGPA

attendence=ctrl.Antecedent(np.arange(0,6,1),'attendence')  #(Attendence)
CA=ctrl.Antecedent(np.arange(0,26,1),'CA')                 #(CA-Continous Assignment)
MTE=ctrl.Antecedent(np.arange(0,21,1),'MTE')               #MTE=(MID TERM EXAMINATIONN)
ETE=ctrl.Antecedent(np.arange(0,51,1),'ETE')               #ETE(END TERM EXAMINATION)
CGPA=ctrl.Consequent(np.arange(0,11,1),'CGPA')             #CGPA OF STUDENT (OUPUT)

#generate fuzzy membership function for above variables

attendence['low']=fuzz.trimf(attendence.universe,[0,0,2])
attendence['average']=fuzz.trimf(attendence.universe,[0,2,5])
attendence['high']=fuzz.trimf(attendence.universe,[2,5,5])

'''attendence.view()'''
# generating fuzzy membership function for CA Variables

CA['low']=fuzz.trimf(CA.universe,[0,0,12])
CA["average"]=fuzz.trimf(CA.universe,[0,12,25])
CA["high"]=fuzz.trimf(CA.universe,[12,25,25])


'''CA.view()''' #view CA Graph
# Generating fuzzy Membership for MTE Variables

MTE["low"]=fuzz.trimf(MTE.universe,[0,0,10])
MTE["average"]=fuzz.trimf(MTE.universe,[0,10,20])
Exemple #37
0
def mamdani_defuzz(dism, disp, dor, cans):
	dismenorreia = dism
	dispareunia = disp
	dorNasCostasPernas = dor
	cansaco = cans

	def nivelLeve(entrada):
		if entrada == 0:
			return 1
		elif entrada >= 6:
			return 0
		else:
			return  1 - (entrada/6)

	def nivelModerado(entrada):
		if entrada == 5:
			return 1
		elif entrada < 5:
			return (entrada/6) - (1/6)
		else:
			return (11/6)-(entrada/6)

	def nivelIntenso(entrada):
		if entrada == 10:
			return 1
		elif entrada <=4:
			return 0
		else:
			return (entrada/6) - (4/6)	

	#Antecedentes
	dismenorreia_dominio = np.arange(0,11,0.1)		#nivel de dismenorreia (0 a 10)
	dispareunia_dominio = np.arange(0,11,1)		#nivel de dispareunia (0 a 10)
	dorNasCostasPernas_dominio = np.arange(0,11,1)		#nivel de dor nas costas/pernas (0 a 10)
	cansaco_dominio = np.arange(0,11,1)		#nivel de cansaco (0 a 10)

	#Consequente
	risco = np.arange(0,100,1)		#nivel de risco de endometriose (0 a 10)

	#Funcoes de pertinencia de dismenorreia
	dismenorreia_leve = fuzz.trimf(dismenorreia_dominio, [0,0,5])		#dismenorreia leve
	dismenorreia_moderada = fuzz.trimf(dismenorreia_dominio, [0,5,10])	#dismenorreia moderada
	dismenorreia_intensa = fuzz.trimf(dismenorreia_dominio, [5,10,10])	#dismenorreia intensa

	#Funcoes de pertinencia de dispareunia
	dispareunia_leve = fuzz.trimf(dispareunia_dominio, [0,0,5])			#dispareunia leve
	dispareunia_moderada = fuzz.trimf(dispareunia_dominio, [0,5,10])	#dispareunia moderada
	dispareunia_intensa = fuzz.trimf(dispareunia_dominio, [5,10,10])	#dispareunia intensa

	#Funcoes de pertinencia de Dor Nas Costas e Pernas
	dorCP_leve = fuzz.trimf(dorNasCostasPernas_dominio, [0,0,5])			#dor nas costas e/ou pernas leve
	dorCP_moderada = fuzz.trimf(dorNasCostasPernas_dominio, [0,5,10])		#dor nas costas e/ou pernas moderada
	dorCP_intensa = fuzz.trimf(dorNasCostasPernas_dominio, [5,10,10])		#dor nas costas e/ou pernas intensa

	#Funcoes de pertinencia de cansaco
	cansaco_leve = fuzz.trimf(cansaco_dominio, [0,0,5])				#cansaco leve
	cansaco_moderado = fuzz.trimf(cansaco_dominio, [0,5,10])		#cansaco moderada
	cansaco_intenso = fuzz.trimf(cansaco_dominio, [5,10,10])		#cansaco intensa

	#Funcoes de pertinencia do Risco de Endometriose
	risco_improvavel = fuzz.trimf(risco, [0,0,33])		#risco de endometriose baixo
	risco_poucoprovavel = fuzz.trimf(risco, [0,33,66])		#risco de endometriose medio
	risco_provavel = fuzz.trimf(risco, [33,66,100])		#risco de endometriose alto
	risco_muitoprovavel = fuzz.trimf(risco, [66,100,100])		#risco de endometriose alto	
	

	## Simulando uma entrada	
	#dismenorreia_nivel_leve = fuzz.interp_membership(dismenorreia_dominio, dismenorreia_leve, dismenorreia)	#faz a intersecao da entrada (10) com a funcao de pertinencia da dismenorreia leve	
	dismenorreia_nivel_leve = nivelLeve(dismenorreia)
	#dismenorreia_nivel_moderada = fuzz.interp_membership(dismenorreia_dominio, dismenorreia_moderada, dismenorreia)	#faz a intersecao da entrada (10) com a funcao de pertinencia da dismenorreia moderada
	dismenorreia_nivel_moderada = nivelModerado(dismenorreia)
	#dismenorreia_nivel_intensa = fuzz.interp_membership(dismenorreia_dominio, dismenorreia_intensa, dismenorreia)	#faz a intersecao da entrada (10) com a funcao de pertinencia da dismenorreia intensa
	dismenorreia_nivel_intensa = nivelIntenso(dismenorreia)
	
	#dispareunia_nivel_leve = fuzz.interp_membership(dispareunia_dominio, dispareunia_leve, dispareunia)	#faz a intersecao da entrada (8) com a funcao de pertinencia da dispareunia leve
	dispareunia_nivel_leve = nivelLeve(dispareunia)
	#dispareunia_nivel_moderada = fuzz.interp_membership(dispareunia_dominio, dispareunia_moderada, dispareunia)	#faz a intersecao da entrada (8) com a funcao de pertinencia da dispareunia moderada
	dispareunia_nivel_moderada = nivelModerado(dispareunia)
	#dispareunia_nivel_intensa = fuzz.interp_membership(dispareunia_dominio, dispareunia_intensa, dispareunia)	#faz a intersecao da entrada (8) com a funcao de pertinencia da dispareunia instensa
	dispareunia_nivel_intensa = nivelIntenso(dispareunia)
	
	#dorCP_nivel_leve = fuzz.interp_membership(dorNasCostasPernas_dominio, dorCP_leve, dorNasCostasPernas)	#faz a intersecao da entrada (8) com a funcao de pertinencia da dor nas costas/pernas leve
	dorCP_nivel_leve = nivelLeve(dorNasCostasPernas)
	#dorCP_nivel_moderada = fuzz.interp_membership(dorNasCostasPernas_dominio, dorCP_moderada, dorNasCostasPernas)	#faz a intersecao da entrada (8) com a funcao de pertinencia da dor nas costas/pernas moderada
	dorCP_nivel_moderada = nivelModerado(dorNasCostasPernas)
	#dorCP_nivel_intensa = fuzz.interp_membership(dorNasCostasPernas_dominio, dorCP_intensa, dorNasCostasPernas)	#faz a intersecao da entrada (8) com a funcao de pertinencia da dor nas costas/pernas intensa
	dorCP_nivel_intensa = nivelIntenso(dorNasCostasPernas)
	
	#cansaco_nivel_leve = fuzz.interp_membership(cansaco_dominio, cansaco_leve, cansaco)	#faz a intersecao da entrada (9) com a funcao de pertinencia de cansaco leve
	cansaco_nivel_leve = nivelLeve(cansaco)
	#cansaco_nivel_moderado = fuzz.interp_membership(cansaco_dominio, cansaco_moderado, cansaco)	#faz a intersecao da entrada (9) com a funcao de pertinencia de cansaco moderado
	cansaco_nivel_moderado = nivelModerado(cansaco)
	#cansaco_nivel_intenso = fuzz.interp_membership(cansaco_dominio, cansaco_intenso, cansaco)	#faz a intersecao da entrada (9) com a funcao de pertinencia de cansaco intenso
	cansaco_nivel_intenso = nivelIntenso(cansaco)

	regras_ativas = []

	## Base de regras
	#Regra 1: dismenorreia leve; dispareunia leve; dor costas/pernas leve; cansaco leve => risco improvavel
	ativa_regra1 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra1 = np.fmin(ativa_regra1, risco_improvavel)		#implicacao 
	if regra1.any() != 0:
		regras_ativas.append(1)

	#Regra 2: dismenorreia leve; dispareunia leve; dor costas/pernas leve; cansaco moderado => risco improvavel
	ativa_regra2 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra2 = np.fmin(ativa_regra2, risco_improvavel)		#implicacao 
	if regra2.any() != 0:
		regras_ativas.append(2)

	#Regra 3: dismenorreia leve; dispareunia leve; dor costas/pernas leve; cansaco intenso => risco pouco provavel
	ativa_regra3 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra3 = np.fmin(ativa_regra3, risco_poucoprovavel)		#implicacao 
	if regra3.any() != 0:
		regras_ativas.append(3)

	#Regra 4: dismenorreia leve; dispareunia leve; dor costas/pernas moderado; cansaco leve => risco improvavel
	ativa_regra4 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra4 = np.fmin(ativa_regra4, risco_improvavel)		#implicacao 
	if regra4.any() != 0:
		regras_ativas.append(4)

	#Regra 5: dismenorreia leve; dispareunia leve; dor costas/pernas moderado; cansaco moderado => risco improvavel
	ativa_regra5 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra5 = np.fmin(ativa_regra5, risco_improvavel)		#implicacao 
	if regra5.any() != 0:
		regras_ativas.append(5)

	#Regra 6: dismenorreia leve; dispareunia leve; dor costas/pernas moderado; cansaco intenso => risco pouco provavel
	ativa_regra6 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra6 = np.fmin(ativa_regra6, risco_poucoprovavel)		#implicacao 
	if regra6.any() != 0:
		regras_ativas.append(6)

	#Regra 7: dismenorreia leve; dispareunia leve; dor costas/pernas intenso; cansaco leve => risco pouco provavel
	ativa_regra7 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra7 = np.fmin(ativa_regra7, risco_poucoprovavel)		#implicacao 
	if regra7.any() != 0:
		regras_ativas.append(7)

	#Regra 8: dismenorreia leve; dispareunia leve; dor costas/pernas intenso; cansaco moderado => risco pouco provavel
	ativa_regra8 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra8 = np.fmin(ativa_regra8, risco_poucoprovavel)		#implicacao 
	if regra8.any() != 0:
		regras_ativas.append(8)

	#Regra 9: dismenorreia leve; dispareunia leve; dor costas/pernas intenso; cansaco intenso => risco provavel
	ativa_regra9 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra9 = np.fmin(ativa_regra9, risco_provavel)		#implicacao 
	if regra9.any() != 0:
		regras_ativas.append(9)

	#Regra 10: dismenorreia leve; dispareunia moderado; dor costas/pernas leve; cansaco leve => risco improvavel
	ativa_regra10 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra10 = np.fmin(ativa_regra10, risco_improvavel)		#implicacao 
	if regra10.any() != 0:
		regras_ativas.append(10)

	#Regra 11: dismenorreia leve; dispareunia moderado; dor costas/pernas leve; cansaco moderado => risco improvavel
	ativa_regra11 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra11 = np.fmin(ativa_regra11, risco_improvavel)		#implicacao 
	if regra11.any() != 0:
		regras_ativas.append(11)

	#Regra 12: dismenorreia leve; dispareunia moderado; dor costas/pernas leve; cansaco intenso => risco pouco provavel
	ativa_regra12 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra12 = np.fmin(ativa_regra12, risco_poucoprovavel)		#implicacao 
	if regra12.any() != 0:
		regras_ativas.append(12)

	#Regra 13: dismenorreia leve; dispareunia moderado; dor costas/pernas moderado; cansaco leve => risco improvavel
	ativa_regra13 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra13 = np.fmin(ativa_regra13, risco_improvavel)		#implicacao 
	if regra13.any() != 0:
		regras_ativas.append(13)

	#Regra 14: dismenorreia leve; dispareunia moderado; dor costas/pernas moderado; cansaco moderado => risco pouco provavel
	ativa_regra14 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra14 = np.fmin(ativa_regra14, risco_poucoprovavel)		#implicacao 
	if regra14.any() != 0:
		regras_ativas.append(14)

	#Regra 15: dismenorreia leve; dispareunia moderado; dor costas/pernas moderado; cansaco intenso => risco provavel
	ativa_regra15 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra15 = np.fmin(ativa_regra15, risco_provavel)		#implicacao 
	if regra15.any() != 0:
		regras_ativas.append(15)

	#Regra 16: dismenorreia leve; dispareunia moderado; dor costas/pernas intenso; cansaco leve => risco provavel
	ativa_regra16 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra16 = np.fmin(ativa_regra16, risco_provavel)		#implicacao 
	if regra16.any() != 0:
		regras_ativas.append(16)

	#Regra 17: dismenorreia leve; dispareunia moderado; dor costas/pernas intenso; cansaco moderado => risco provavel
	ativa_regra17 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra17 = np.fmin(ativa_regra17, risco_provavel)		#implicacao 
	if regra17.any() != 0:
		regras_ativas.append(17)

	#Regra 18: dismenorreia leve; dispareunia moderado; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra18 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra18 = np.fmin(ativa_regra18, risco_muitoprovavel)		#implicacao 
	if regra18.any() != 0:
		regras_ativas.append(18)

	#Regra 19: dismenorreia leve; dispareunia intenso; dor costas/pernas leve; cansaco leve => risco improvavel
	ativa_regra19 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra19 = np.fmin(ativa_regra19, risco_improvavel)		#implicacao 
	if regra19.any() != 0:
		regras_ativas.append(19)

	#Regra 20: dismenorreia leve; dispareunia intenso; dor costas/pernas leve; cansaco moderado => risco pouco provavel
	ativa_regra20 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra20 = np.fmin(ativa_regra20, risco_poucoprovavel)		#implicacao 
	if regra20.any() != 0:
		regras_ativas.append(20)

	#Regra 21: dismenorreia leve; dispareunia intenso; dor costas/pernas leve; cansaco intenso => risco provavel
	ativa_regra21 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra21 = np.fmin(ativa_regra21, risco_provavel)		#implicacao 
	if regra21.any() != 0:
		regras_ativas.append(21)

	#Regra 22: dismenorreia leve; dispareunia intenso; dor costas/pernas moderado; cansaco leve => risco pouco provavel
	ativa_regra22 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra22 = np.fmin(ativa_regra22, risco_poucoprovavel)		#implicacao 
	if regra22.any() != 0:
		regras_ativas.append(22)

	#Regra 23: dismenorreia leve; dispareunia intenso; dor costas/pernas moderado; cansaco moderado => risco provavel
	ativa_regra23 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra23 = np.fmin(ativa_regra23, risco_provavel)		#implicacao 
	if regra23.any() != 0:
		regras_ativas.append(23)

	#Regra 24: dismenorreia leve; dispareunia intenso; dor costas/pernas moderado; cansaco intenso => risco muito provavel
	ativa_regra24 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra24 = np.fmin(ativa_regra24, risco_muitoprovavel)		#implicacao 
	if regra24.any() != 0:
		regras_ativas.append(24)

	#Regra 25: dismenorreia leve; dispareunia intenso; dor costas/pernas intenso; cansaco leve => risco pouco provavel
	ativa_regra25 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra25 = np.fmin(ativa_regra25, risco_poucoprovavel)		#implicacao 
	if regra25.any() != 0:
		regras_ativas.append(25)

	#Regra 26: dismenorreia leve; dispareunia intenso; dor costas/pernas intenso; cansaco moderado => risco provavel
	ativa_regra26 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra26 = np.fmin(ativa_regra26, risco_provavel)		#implicacao 
	if regra26.any() != 0:
		regras_ativas.append(26)

	#Regra 27: dismenorreia leve; dispareunia intenso; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra27 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_leve, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra27 = np.fmin(ativa_regra27, risco_muitoprovavel)		#implicacao 
	if regra27.any() != 0:
		regras_ativas.append(27)

	#Regra 28: dismenorreia moderado; dispareunia leve; dor costas/pernas leve; cansaco leve => risco improvavel
	ativa_regra28 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra28 = np.fmin(ativa_regra28, risco_improvavel)		#implicacao 
	if regra28.any() != 0:
		regras_ativas.append(28)

	#Regra 29: dismenorreia moderado; dispareunia leve; dor costas/pernas leve; cansaco moderado => risco improvavel
	ativa_regra29 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra29 = np.fmin(ativa_regra29, risco_improvavel)		#implicacao 
	if regra29.any() != 0:
		regras_ativas.append(29)

	#Regra 30: dismenorreia moderado; dispareunia leve; dor costas/pernas leve; cansaco intenso => risco improvavel
	ativa_regra30 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra30 = np.fmin(ativa_regra30, risco_improvavel)		#implicacao 
	if regra30.any() != 0:
		regras_ativas.append(30)

	#Regra 31: dismenorreia moderado; dispareunia leve; dor costas/pernas moderado; cansaco leve => risco pouco provavel
	ativa_regra31 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra31 = np.fmin(ativa_regra31, risco_poucoprovavel)		#implicacao 
	if regra31.any() != 0:
		regras_ativas.append(31)

	#Regra 32: dismenorreia moderado; dispareunia leve; dor costas/pernas moderado; cansaco moderado => risco pouco provavel
	ativa_regra32 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra32 = np.fmin(ativa_regra32, risco_poucoprovavel)		#implicacao 
	if regra32.any() != 0:
		regras_ativas.append(32)

	#Regra 33: dismenorreia moderado; dispareunia leve; dor costas/pernas moderado; cansaco intenso => risco provavel
	ativa_regra33 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra33 = np.fmin(ativa_regra33, risco_provavel)		#implicacao 
	if regra33.any() != 0:
		regras_ativas.append(33)

	#Regra 34: dismenorreia moderado; dispareunia leve; dor costas/pernas intenso; cansaco leve => risco provavel
	ativa_regra34 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra34 = np.fmin(ativa_regra34, risco_provavel)		#implicacao 
	if regra34.any() != 0:
		regras_ativas.append(34)

	#Regra 35: dismenorreia moderado; dispareunia leve; dor costas/pernas intenso; cansaco moderado => risco provavel
	ativa_regra35 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra35 = np.fmin(ativa_regra35, risco_provavel)		#implicacao 
	if regra35.any() != 0:
		regras_ativas.append(35)

	#Regra 36: dismenorreia moderado; dispareunia leve; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra36 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra36 = np.fmin(ativa_regra36, risco_muitoprovavel)		#implicacao 
	if regra36.any() != 0:
		regras_ativas.append(36)

	#Regra 37: dismenorreia moderado; dispareunia moderado; dor costas/pernas leve; cansaco leve => risco improvavel
	ativa_regra37 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra37 = np.fmin(ativa_regra37, risco_improvavel)		#implicacao 
	if regra37.any() != 0:
		regras_ativas.append(37)

	#Regra 38: dismenorreia moderado; dispareunia moderado; dor costas/pernas leve; cansaco moderado => risco pouco provavel
	ativa_regra38 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra38 = np.fmin(ativa_regra38, risco_poucoprovavel)		#implicacao 
	if regra38.any() != 0:
		regras_ativas.append(38)

	#Regra 39: dismenorreia moderado; dispareunia moderado; dor costas/pernas leve; cansaco intenso => risco provavel
	ativa_regra39 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra39 = np.fmin(ativa_regra39, risco_provavel)		#implicacao 
	if regra39.any() != 0:
		regras_ativas.append(39)

	#Regra 40: dismenorreia moderado; dispareunia moderado; dor costas/pernas moderado; cansaco leve => risco improvavel
	ativa_regra40 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra40 = np.fmin(ativa_regra40, risco_improvavel)		#implicacao 
	if regra40.any() != 0:
		regras_ativas.append(40)

	#Regra 41: dismenorreia moderado; dispareunia moderado; dor costas/pernas moderado; cansaco moderado => risco pouco provavel
	ativa_regra41 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra41 = np.fmin(ativa_regra41, risco_poucoprovavel)		#implicacao 
	if regra41.any() != 0:
		regras_ativas.append(41)

	#Regra 42: dismenorreia moderado; dispareunia moderado; dor costas/pernas moderado; cansaco intenso => risco provavel
	ativa_regra42 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra42 = np.fmin(ativa_regra42, risco_provavel)		#implicacao 
	if regra42.any() != 0:
		regras_ativas.append(42)

	#Regra 43: dismenorreia moderado; dispareunia moderado; dor costas/pernas intenso; cansaco leve => risco provavel
	ativa_regra43 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra43 = np.fmin(ativa_regra43, risco_provavel)		#implicacao 
	if regra43.any() != 0:
		regras_ativas.append(43)

	#Regra 44: dismenorreia moderado; dispareunia moderado; dor costas/pernas intenso; cansaco moderado => risco provavel
	ativa_regra44 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra44 = np.fmin(ativa_regra44, risco_provavel)		#implicacao 
	if regra44.any() != 0:
		regras_ativas.append(44)

	#Regra 45: dismenorreia moderado; dispareunia moderado; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra45 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra45 = np.fmin(ativa_regra45, risco_muitoprovavel)		#implicacao 
	if regra45.any() != 0:
		regras_ativas.append(45)

	#Regra 46: dismenorreia moderado; dispareunia intenso; dor costas/pernas leve; cansaco leve => risco pouco provavel
	ativa_regra46 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra46 = np.fmin(ativa_regra46, risco_poucoprovavel)		#implicacao 
	if regra46.any() != 0:
		regras_ativas.append(46)

	#Regra 47: dismenorreia moderado; dispareunia intenso; dor costas/pernas leve; cansaco moderado => risco provavel
	ativa_regra47 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra47 = np.fmin(ativa_regra47, risco_provavel)		#implicacao 
	if regra47.any() != 0:
		regras_ativas.append(47)

	#Regra 48: dismenorreia moderado; dispareunia intenso; dor costas/pernas leve; cansaco intenso => risco provavel
	ativa_regra48 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra48 = np.fmin(ativa_regra48, risco_provavel)		#implicacao 
	if regra48.any() != 0:
		regras_ativas.append(48)

	#Regra 49: dismenorreia moderado; dispareunia intenso; dor costas/pernas moderado; cansaco leve => risco provavel
	ativa_regra49 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra49 = np.fmin(ativa_regra49, risco_provavel)		#implicacao 
	if regra49.any() != 0:
		regras_ativas.append(49)

	#Regra 50: dismenorreia moderado; dispareunia intenso; dor costas/pernas moderado; cansaco moderado => risco provavel
	ativa_regra50 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra50 = np.fmin(ativa_regra50, risco_provavel)		#implicacao 
	if regra50.any() != 0:
		regras_ativas.append(50)

	#Regra 51: dismenorreia moderado; dispareunia intenso; dor costas/pernas moderado; cansaco intenso => risco muito provavel
	ativa_regra51 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra51 = np.fmin(ativa_regra51, risco_muitoprovavel)		#implicacao 
	if regra51.any() != 0:
		regras_ativas.append(51)

	#Regra 52: dismenorreia moderado; dispareunia intenso; dor costas/pernas intenso; cansaco leve => risco provavel
	ativa_regra52 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra52 = np.fmin(ativa_regra52, risco_provavel)		#implicacao 
	if regra52.any() != 0:
		regras_ativas.append(52)

	#Regra 53: dismenorreia moderado; dispareunia intenso; dor costas/pernas intenso; cansaco moderado => risco muito provavel
	ativa_regra53 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra53 = np.fmin(ativa_regra53, risco_muitoprovavel)		#implicacao 
	if regra53.any() != 0:
		regras_ativas.append(53)

	#Regra 54: dismenorreia moderado; dispareunia intenso; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra54 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_moderada, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra54 = np.fmin(ativa_regra54, risco_muitoprovavel)		#implicacao 
	if regra54.any() != 0:
		regras_ativas.append(54)

	#Regra 55: dismenorreia intenso; dispareunia leve; dor costas/pernas leve; cansaco leve => risco improvavel
	ativa_regra55 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra55 = np.fmin(ativa_regra55, risco_improvavel)		#implicacao 
	if regra55.any() != 0:
		regras_ativas.append(55)

	#Regra 56: dismenorreia intenso; dispareunia leve; dor costas/pernas leve; cansaco moderado => risco improvavel
	ativa_regra56 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra56 = np.fmin(ativa_regra56, risco_improvavel)		#implicacao 
	if regra56.any() != 0:
		regras_ativas.append(56)

	#Regra 57: dismenorreia intenso; dispareunia leve; dor costas/pernas leve; cansaco intenso => risco pouco provavel
	ativa_regra57 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra57 = np.fmin(ativa_regra57, risco_poucoprovavel)		#implicacao 
	if regra57.any() != 0:
		regras_ativas.append(57)

	#Regra 58: dismenorreia intenso; dispareunia leve; dor costas/pernas moderado; cansaco leve => risco pouco provavel
	ativa_regra58 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra58 = np.fmin(ativa_regra58, risco_poucoprovavel)		#implicacao 
	if regra58.any() != 0:
		regras_ativas.append(58)

	#Regra 59: dismenorreia intenso; dispareunia leve; dor costas/pernas moderado; cansaco moderado => risco pouco provavel
	ativa_regra59 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra59 = np.fmin(ativa_regra59, risco_poucoprovavel)		#implicacao 
	if regra59.any() != 0:
		regras_ativas.append(59)

	#Regra 60: dismenorreia intenso; dispareunia leve; dor costas/pernas moderado; cansaco intenso => risco provavel
	ativa_regra60 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra60 = np.fmin(ativa_regra60, risco_provavel)		#implicacao 
	if regra60.any() != 0:
		regras_ativas.append(60)

	#Regra 61: dismenorreia intenso; dispareunia leve; dor costas/pernas intenso; cansaco leve => risco pouco provavel
	ativa_regra61 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra61 = np.fmin(ativa_regra61, risco_poucoprovavel)		#implicacao 
	if regra61.any() != 0:
		regras_ativas.append(61)

	#Regra 62: dismenorreia intenso; dispareunia leve; dor costas/pernas intenso; cansaco moderado => risco provavel
	ativa_regra62 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra62 = np.fmin(ativa_regra62, risco_provavel)		#implicacao 
	if regra62.any() != 0:
		regras_ativas.append(62)

	#Regra 63: dismenorreia intenso; dispareunia leve; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra63 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_leve)))		#composicao usando operador AND (minimo)
	regra63 = np.fmin(ativa_regra63, risco_muitoprovavel)		#implicacao 
	if regra63.any() != 0:
		regras_ativas.append(63)

	#Regra 64: dismenorreia intenso; dispareunia moderado; dor costas/pernas leve; cansaco leve => risco pouco provavel
	ativa_regra64 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra64 = np.fmin(ativa_regra64, risco_poucoprovavel)		#implicacao 
	if regra64.any() != 0:
		regras_ativas.append(64)

	#Regra 65: dismenorreia intenso; dispareunia moderado; dor costas/pernas leve; cansaco moderado => risco pouco provavel
	ativa_regra65 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra65 = np.fmin(ativa_regra65, risco_poucoprovavel)		#implicacao 
	if regra65.any() != 0:
		regras_ativas.append(65)

	#Regra 66: dismenorreia intenso; dispareunia moderado; dor costas/pernas leve; cansaco intenso => risco provavel
	ativa_regra66 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra66 = np.fmin(ativa_regra66, risco_provavel)		#implicacao 
	if regra66.any() != 0:
		regras_ativas.append(66)

	#Regra 67: dismenorreia intenso; dispareunia moderado; dor costas/pernas moderado; cansaco leve => risco pouco provavel
	ativa_regra67 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra67 = np.fmin(ativa_regra67, risco_poucoprovavel)		#implicacao 
	if regra67.any() != 0:
		regras_ativas.append(67)

	#Regra 68: dismenorreia intenso; dispareunia moderado; dor costas/pernas moderado; cansaco moderado => risco provavel
	ativa_regra68 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra68 = np.fmin(ativa_regra68, risco_provavel)		#implicacao 
	if regra68.any() != 0:
		regras_ativas.append(68)

	#Regra 69: dismenorreia intenso; dispareunia moderado; dor costas/pernas moderado; cansaco intenso => risco provavel
	ativa_regra69 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra69 = np.fmin(ativa_regra69, risco_provavel)		#implicacao 
	if regra69.any() != 0:
		regras_ativas.append(69)

	#Regra 70: dismenorreia intenso; dispareunia moderado; dor costas/pernas intenso; cansaco leve => risco provavel
	ativa_regra70 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra70 = np.fmin(ativa_regra70, risco_provavel)		#implicacao 
	if regra70.any() != 0:
		regras_ativas.append(70)

	#Regra 71: dismenorreia intenso; dispareunia moderado; dor costas/pernas intenso; cansaco moderado => risco provavel
	ativa_regra71 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra71 = np.fmin(ativa_regra71, risco_provavel)		#implicacao 
	if regra71.any() != 0:
		regras_ativas.append(71)

	#Regra 72: dismenorreia intenso; dispareunia moderado; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra72 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_moderada)))		#composicao usando operador AND (minimo)
	regra72 = np.fmin(ativa_regra72, risco_muitoprovavel)		#implicacao 
	if regra72.any() != 0:
		regras_ativas.append(72)

	#Regra 73: dismenorreia intenso; dispareunia intenso; dor costas/pernas leve; cansaco leve => risco pouco provavel
	ativa_regra73 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra73 = np.fmin(ativa_regra73, risco_poucoprovavel)		#implicacao 
	if regra73.any() != 0:
		regras_ativas.append(73)

	#Regra 74: dismenorreia intenso; dispareunia intenso; dor costas/pernas leve; cansaco moderado => risco provavel
	ativa_regra74 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra74 = np.fmin(ativa_regra74, risco_provavel)		#implicacao 
	if regra74.any() != 0:
		regras_ativas.append(74)

	#Regra 75: dismenorreia intenso; dispareunia intenso; dor costas/pernas leve; cansaco intenso => risco muito provavel
	ativa_regra75 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_leve, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra75 = np.fmin(ativa_regra75, risco_muitoprovavel)		#implicacao 
	if regra75.any() != 0:
		regras_ativas.append(75)

	#Regra 76: dismenorreia intenso; dispareunia intenso; dor costas/pernas moderado; cansaco leve => risco provavel
	ativa_regra76 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra76 = np.fmin(ativa_regra76, risco_provavel)		#implicacao 
	if regra76.any() != 0:
		regras_ativas.append(76)

	#Regra 77: dismenorreia intenso; dispareunia intenso; dor costas/pernas moderado; cansaco moderado => risco provavel
	ativa_regra77 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra77 = np.fmin(ativa_regra77, risco_provavel)		#implicacao 
	if regra77.any() != 0:
		regras_ativas.append(77)

	#Regra 78: dismenorreia intenso; dispareunia intenso; dor costas/pernas moderado; cansaco intenso => risco muito provavel
	ativa_regra78 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_moderada, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra78 = np.fmin(ativa_regra78, risco_muitoprovavel)		#implicacao 
	if regra78.any() != 0:
		regras_ativas.append(78)

	#Regra 79: dismenorreia intenso; dispareunia intenso; dor costas/pernas intenso; cansaco leve => risco muito provavel
	ativa_regra79 = np.fmin(cansaco_nivel_leve, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra79 = np.fmin(ativa_regra79, risco_muitoprovavel)		#implicacao 
	if regra79.any() != 0:
		regras_ativas.append(79)

	#Regra 80: dismenorreia intenso; dispareunia intenso; dor costas/pernas intenso; cansaco moderado => risco muito provavel
	ativa_regra80 = np.fmin(cansaco_nivel_moderado, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra80 = np.fmin(ativa_regra80, risco_muitoprovavel)		#implicacao 
	if regra80.any() != 0:
		regras_ativas.append(80)

	#Regra 81: dismenorreia intenso; dispareunia intenso; dor costas/pernas intenso; cansaco intenso => risco muito provavel
	ativa_regra81 = np.fmin(cansaco_nivel_intenso, np.fmin(dorCP_nivel_intensa, np.fmin(dismenorreia_nivel_intensa, dispareunia_nivel_intensa)))		#composicao usando operador AND (minimo)
	regra81 = np.fmin(ativa_regra81, risco_muitoprovavel)		#implicacao 
	if regra81.any() != 0:
		regras_ativas.append(81)

	print "regras ativas: "+str(regras_ativas)

	## Agregacao das regras
	agregacao = np.fmax(regra81,
		np.fmax(regra80,
		np.fmax(regra79,
		np.fmax(regra78,
		np.fmax(regra77,
		np.fmax(regra76,
		np.fmax(regra75,
		np.fmax(regra74,
		np.fmax(regra73,
		np.fmax(regra72,
		np.fmax(regra71,
		np.fmax(regra70,
		np.fmax(regra69,
		np.fmax(regra68,
		np.fmax(regra67,
		np.fmax(regra66,
		np.fmax(regra65,
		np.fmax(regra64,
		np.fmax(regra63,
		np.fmax(regra62,
		np.fmax(regra61,
		np.fmax(regra60,
		np.fmax(regra59,
		np.fmax(regra58,
		np.fmax(regra57,
		np.fmax(regra56,
		np.fmax(regra55,
		np.fmax(regra54,
		np.fmax(regra53,
		np.fmax(regra52,
		np.fmax(regra51,
		np.fmax(regra50,
		np.fmax(regra49,
		np.fmax(regra48,
		np.fmax(regra47,
		np.fmax(regra46,
		np.fmax(regra45,
		np.fmax(regra44,
		np.fmax(regra43,
		np.fmax(regra42,
		np.fmax(regra41,
		np.fmax(regra40,
		np.fmax(regra39,
		np.fmax(regra38,
		np.fmax(regra37,
		np.fmax(regra36,
		np.fmax(regra35,
		np.fmax(regra34,
		np.fmax(regra33,
		np.fmax(regra32,
		np.fmax(regra31,
		np.fmax(regra30,
		np.fmax(regra29,
		np.fmax(regra28,
		np.fmax(regra27, 
		np.fmax(regra26, 
		np.fmax(regra25, 
		np.fmax(regra24, 
		np.fmax(regra23, 
		np.fmax(regra22, 
		np.fmax(regra21, 
		np.fmax(regra20, 
		np.fmax(regra19, 
		np.fmax(regra18, 
		np.fmax(regra17, 
		np.fmax(regra16, 
		np.fmax(regra15, 
		np.fmax(regra14, 
		np.fmax(regra13, 
		np.fmax(regra12, 
		np.fmax(regra11,
		np.fmax(regra10,
		np.fmax(regra9, 
		np.fmax(regra8, 
		np.fmax(regra7, 
		np.fmax(regra6, 
		np.fmax(regra5, 
		np.fmax(regra4,
		np.fmax(regra3, 
		np.fmax(regra1, regra2))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))	#agregacao das regras

	risco0 = np.zeros_like(risco)	#variavel auxiliar para montar o grafico


	## Calculo do resultado defuzzificado
	risco_def = fuzz.defuzz(risco, agregacao, 'centroid')		#defuzzificacao pelo metodo centroide
	risco_ativacao = fuzz.interp_membership(risco, agregacao, risco_def)	#intersecao do risco defuzzificado com a funcao de pertinencia

	## Grafico da funcao de pertinencia resultante
	fig, ax0 = plt.subplots(figsize=(9.27,3.23))

	ax0.plot(risco, risco_improvavel, 'b', linewidth=0.5, label='I', linestyle='--')
	ax0.plot(risco, risco_poucoprovavel, 'g', linewidth=0.5, label='PP', linestyle='--')
	ax0.plot(risco, risco_provavel, 'y', linewidth=0.5, label='P', linestyle='--')
	ax0.plot(risco, risco_muitoprovavel, 'r', linewidth=1.5, label='MP', linestyle='--')
	ax0.legend(loc='upper center',bbox_to_anchor=(0.5, 1.05), ncol=4, fancybox=True, shadow=True)
	ax0.fill_between(risco, risco0, agregacao, facecolor='Orange', alpha=0.7)
	ax0.plot([risco_def, risco_def], [0, risco_ativacao], 'k', linewidth=1.5, alpha=0.9)
	plt.xticks(np.append(plt.xticks()[0],risco_def))
	plt.xlabel('risco (%)')
	ax0.set_title("Agregacao das regras e resultado defuzzificado")

	plt.tight_layout()
	plt.show()
	return risco_def
are defined in scikit-fuzzy as follows

"""
import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt

# Generate universe variables
#   * Quality and service on subjective ranges [0, 10]
#   * Tip has a range of [0, 25] in units of percentage points
x_qual = np.arange(0, 11, 1)
x_serv = np.arange(0, 11, 1)
x_tip  = np.arange(0, 26, 1)

# Generate fuzzy membership functions
qual_lo = fuzz.trimf(x_qual, [0, 0, 5])
qual_md = fuzz.trimf(x_qual, [0, 5, 10])
qual_hi = fuzz.trimf(x_qual, [5, 10, 10])
serv_lo = fuzz.trimf(x_serv, [0, 0, 5])
serv_md = fuzz.trimf(x_serv, [0, 5, 10])
serv_hi = fuzz.trimf(x_serv, [5, 10, 10])
tip_lo = fuzz.trimf(x_tip, [0, 0, 13])
tip_md = fuzz.trimf(x_tip, [0, 13, 25])
tip_hi = fuzz.trimf(x_tip, [13, 25, 25])

# Visualize these universes and membership functions
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(8, 9))

ax0.plot(x_qual, qual_lo, 'b', linewidth=1.5, label='Bad')
ax0.plot(x_qual, qual_md, 'g', linewidth=1.5, label='Decent')
ax0.plot(x_qual, qual_hi, 'r', linewidth=1.5, label='Great')
for key in xclasses.keys():
       for f in range(0,features_num):
            ff = [x[f] for x in  xclasses.get(key)]
            [f_min,f_max] = [min(ff),max(ff)]
            feature[f] = [f_min,f_max] TERM
            uni_min[f] = min([f_min,uni_min[f]]) 
            uni_max[f] = max([f_max,uni_max[f]])

uni_step = (uni_max - uni_min) / 1000
mfs = [[np.nan] for f in range(0, features_num)]        
mfs_uni = [[np.nan] for f in range(0, features_num)]
for lingvo in range(0, features_num):
    mfs_uni[lingvo] = np.arange(uni_min[lingvo],uni_max[lingvo],uni_step[lingvo])
    term = 0
    for term_key in xclasses.key():
         mfs[lingvo][term] = fuzz.trimf(mfs_uni[lingvp],[feature[x][0],feature[x][0]+(feature[x][1]-feature[x][0])/2,feature[x][1]])
         term=term+1
        
#mf1_universum=np.arange(universum_min,universum_max + universum_step,universum_step)

#mf_feature1 = fuzz.trimf(mf1_universum,[min(feature1),min(feature1)+((max(feature1)-min(feature1))/2),max(feature1)])
#mf_feature2 = fuzz.trimf(mf1_universum,[min(feature2),min(feature2)+((max(feature2)-min(feature2))/2),max(feature2)])

        
        

#%% visualization
fig, ax = plt.subplots()

x=0
plt.plot( mfs_uni[x],mfs,'r',mf1_universum,mf_feature2,'g')
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 10 22:10:02 2016

@author: meza
"""

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

x=np.arange(11)
print x

mfx=fuzz.trimf(x, [0, 5,10])
print mfx

plt.plot(x,mfx)
plt.grid('on')
plt.show()
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# New Antecedent/Consequent objects hold universe variables and membership
# functions
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 is possible with .automf(3, 5, or 7)
quality.automf(3)
service.automf(3)

# Custom membership functions can be built interactively with a familiar,
# Pythonic API
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])

"""
To help understand what the membership looks like, use the ``view`` methods.
"""

# You can see how these look with .view()
quality["average"].view()
"""
.. image:: PLOT2RST.current_figure
"""
service.view()
"""
.. image:: PLOT2RST.current_figure
Exemple #42
0
def init_rule_based_system():
    # Antecedent/Consequent objects hold universe variables and membership functions

    step_meter = 0.02 # If the step are large, the Gaussian MF will regress to Triangular MF
    step_meter_per_second = 0.02
    step_risk = 0.05
    range_type = np.arange(0, 2+1, 1)
    range_degree = np.arange(-180, 180+1, 1.0)    # Range: -180 degree ~ 180 degree for direction and orientation
    range_meter  = np.arange(0, 3.0+step_meter, step_meter)         # Range:  0 meter ~ 3 meter for distance
    range_meter_per_second = np.arange(0, 2.0+step_meter_per_second, step_meter_per_second)#Range:  0 mps ~ 2 mps for speed
    range_risk = np.arange(0, 5+step_risk, step_risk)  # Range: 0,1,2,3,4 for risk

    object_type = ctrl.Antecedent(range_type, 'type') 
    object_distance = ctrl.Antecedent(range_meter, 'distance') 
    object_orientation = ctrl.Antecedent(range_degree , 'orientation')#-180~180 degree
    object_direction  = ctrl.Antecedent(range_degree , 'direction') # -180~180 degree
    object_speed = ctrl.Antecedent(range_meter_per_second , 'speed')		#0- 3 m/s

    object_risk = ctrl.Consequent(range_risk, 'risk')

    # Custom membership functions can be built interactively with a familiar Pythonic API
    # Type
    object_type['StaObj'] = fuzz.trimf(range_type, [0, 0, 0.1])
    object_type['DynObj'] = fuzz.trimf(range_type, [0.9, 1, 1.1])
    object_type['Human'] = fuzz.trimf(range_type, [1.9, 2, 2])

    # Distance
    object_distance['Near']  = fuzz.trapmf(range_meter, [0, 0, IZW, 2*IZW])
    object_distance['Medium']= fuzz.trimf(range_meter, [IZW, 2*IZW, 4*IZW])
    object_distance['Far']   = fuzz.trapmf(range_meter, [2*IZW, 4*IZW, 3, 3])
    #object_distance.view()

    # Direction -180~180
    rear_d_p2 = fuzz.trapmf(range_degree, [-180, -180, -135, -90])
    object_direction['Right']  = fuzz.trimf(range_degree, [-135, -90, -45])
    object_direction['FrontRight']  = fuzz.trimf(range_degree, [-90, -45, 0])
    object_direction['Front']  =  fuzz.trimf(range_degree, [-45, 0, 45])
    object_direction['FrontLeft']= fuzz.trimf(range_degree, [0, 45, 90])
    object_direction['Left']= fuzz.trimf(range_degree, [45, 90, 135])
    rear_d_p1 = fuzz.trapmf(range_degree, [90, 135, 180,180]) 
    null,object_direction['BigRear']  =fuzz.fuzzy_or(range_degree,rear_d_p1,range_degree,rear_d_p2)
    print("init_fls_common_part")
    #object_direction.view()

    # Speed 
    object_speed['Slow']  = fuzz.trapmf(range_meter_per_second, [0, 0, 0.5, 1.0])
    object_speed['Medium']= fuzz.trapmf(range_meter_per_second, [0.5, 1.0, 1.0, 1.5])
    object_speed['Fast']  = fuzz.trimf(range_meter_per_second,[1.0,1.5,1.5])
    #object_speed.view()

    # Orientation
    object_orientation['Front']  = fuzz.trimf(range_degree, [-45, 0, 45])
    object_orientation['FrontLeft']=fuzz.trimf(range_degree, [0, 45, 90])
    object_orientation['Left']=  fuzz.trimf(range_degree, [45, 90, 135]) 
    object_orientation['RearLeft']= fuzz.trimf(range_degree, [90, 135, 180]) 
    rear_p1 = fuzz.trimf(range_degree, [135, 180,180]) 
    rear_p2 = fuzz.trimf(range_degree, [-180,-180,-135]) 
    null,object_orientation['Rear']  =fuzz.fuzzy_or(range_degree,rear_p1,range_degree,rear_p2)
    object_orientation['RearRight']  = fuzz.trimf(range_degree, [-180,-135,-90]) 
    object_orientation['Right']  = fuzz.trimf(range_degree, [-135,-90,-45]) 
    object_orientation['FrontRight']  = fuzz.trimf(range_degree, [-90,-45, 0]) 
    #object_orientation.view()

    # Risk
    object_risk['VeryLow'] = fuzz.trimf(range_risk, [0, 0, 1]) 
    object_risk['Low'] =  fuzz.trimf(range_risk, [0, 1, 2]) 
    object_risk['Medium'] =  fuzz.trimf(range_risk, [1, 2, 3]) 
    object_risk['High'] =  fuzz.trimf(range_risk, [2, 3, 4]) 
    object_risk['VeryHigh'] =  fuzz.trimf(range_risk, [3, 4, 4]) 
    """
    Fuzzy rules
    -----------
    """

    #time_previous = time.time()  

    #from rules_demo import rule_list_generator
    #from rules import rule_list_generator
    #rule_list=rule_list_generator(object_type,object_distance,object_direction, object_speed, object_orientation, object_risk)

    #run_time = time.time() - time_previous    
    #print 'execute time=',one_run_time,'s'           
    #print 'setting rules time=',run_time,'sec'  
    """
    Control System Creation and Simulation
    ---------------------------------------
    """
    global ra_fls

    import cPickle as pickle 
    fls_name = "ra_full.data"

    if os.path.exists(fls_name):
        print("FLS exists!")
        f = open(fls_name,'rb')
        ra_fls = pickle.load(f)
    else:
        print("Init FLS")
        from assessment_rules import rule_list_generator
        assessment_rule_list=rule_list_generator(object_type,object_distance,object_direction, object_speed, object_orientation, object_risk)
        ra_fls = ctrl.ControlSystem(assessment_rule_list)
        f = open(fls_name,'wb')
        pickle.dump(ra_fls,f)
        f.close 
    """
    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. 
    """
    global risk_assessment_instance 
    risk_assessment_instance = ctrl.ControlSystemSimulation(ra_fls)
def initialize():
    global input_buffer_occup, total_buffer_occup, inbff_, tobff_, r_cost_
    input_buffer_occup = np.arange(0, 9, 1)
    total_buffer_occup = np.arange(0, 41, 1)
    router_cost = np.arange(0, 41, 1)

    inbff_ = [[] for j in range(5)]
    tobff_ = [[] for j in range(5)]
    r_cost_ = [[] for j in range(5)]
    #global inbff_ = [[],[],[],[],[]]

    inbff_[0] = fuzz.trimf(input_buffer_occup, [0, 0, 2])
    inbff_[1] = fuzz.trimf(input_buffer_occup, [0, 2, 4])
    inbff_[2] = fuzz.trimf(input_buffer_occup, [2, 4, 6])
    inbff_[3] = fuzz.trimf(input_buffer_occup, [4, 6, 8])
    inbff_[4] = fuzz.trimf(input_buffer_occup, [6, 8, 8])
    fig, ax = plt.subplots()
    mf = ['Zero', 'Very Small', 'Small', 'Medium', 'Large']
    for i in range(5):
        ax.plot(input_buffer_occup, inbff_[i], label=mf[i])

    ax.legend(loc='upper right', shadow=True)
    plt.title("Membership Function For Input Buffer Occupied")
    plt.xlabel("Number of Input Buffer Occupied")
    plt.ylabel("Membership Value")

    tobff_[0] = fuzz.trimf(total_buffer_occup, [0, 0, 10])
    tobff_[1] = fuzz.trimf(total_buffer_occup, [0, 10, 20])
    tobff_[2] = fuzz.trimf(total_buffer_occup, [10, 20, 30])
    tobff_[3] = fuzz.trimf(total_buffer_occup, [20, 30, 40])
    tobff_[4] = fuzz.trimf(total_buffer_occup, [30, 40, 40])
    fig, ax = plt.subplots()
    for i in range(5):
        ax.plot(total_buffer_occup, tobff_[i], label=mf[i])

    ax.legend(loc='upper right', shadow=True)
    plt.title("Membership Function For Total Buffer Occupied")
    plt.xlabel("Number of Total Buffer Occupied")
    plt.ylabel("Membership Value")

    r_cost_[0] = fuzz.trimf(router_cost, [0, 0, 10])
    r_cost_[1] = fuzz.trimf(router_cost, [0, 10, 20])
    r_cost_[2] = fuzz.trimf(router_cost, [10, 20, 30])
    r_cost_[3] = fuzz.trimf(router_cost, [20, 30, 40])
    r_cost_[4] = fuzz.trimf(router_cost, [30, 40, 40])

    global value
    value = [0, 10, 20, 30, 40]
    plt.show()
Exemple #44
0
    def init_fuzzy(self):
        """
        Make fuzzy setup by defining membership functions and rules
        """

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

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

        distances_front_sensors[0].view()

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

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

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

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

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

        vel_ctrl = ctrl.ControlSystem([
            rule_l1, rule_l2, rule_l3, rule_l4, rule_r1, rule_r2, rule_r3,
            rule_r4
        ])
        self.fuzzy_system = ctrl.ControlSystemSimulation(vel_ctrl)
Exemple #45
0
import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt

x = np.arange(11)
print x
mfx = fuzz.trimf(x, [0, 3, 5])

plt.plot(x, mfx)
plt.grid()
plt.show()
Exemple #46
0
import numpy as np
import skfuzzy as fuzz
try:
    import matplotlib.pyplot as plt
except ImportError:
    pass

# Generate universe variables
#   * Quality and service on subjective ranges [0, 10]
#   * Tip has a range of [0, 25] in units of percentage points
x_qual = np.arange(0, 11, 1)
x_serv = np.arange(0, 11, 1)
x_tip  = np.arange(0, 26, 1)

# Generate fuzzy membership functions
qual_lo = fuzz.trimf(x_qual, [0, 0, 5])
qual_md = fuzz.trimf(x_qual, [0, 5, 10])
qual_hi = fuzz.trimf(x_qual, [5, 10, 10])
serv_lo = fuzz.trimf(x_serv, [0, 0, 5])
serv_md = fuzz.trimf(x_serv, [0, 5, 10])
serv_hi = fuzz.trimf(x_serv, [5, 10, 10])
tip_lo = fuzz.trimf(x_tip, [0, 0, 13])
tip_md = fuzz.trimf(x_tip, [0, 13, 25])
tip_hi = fuzz.trimf(x_tip, [13, 25, 25])

# Visualize these universes and membership functions
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(8, 9))

ax0.plot(x_qual, qual_lo, 'b', linewidth=1.5, label='Bad')
ax0.plot(x_qual, qual_md, 'g', linewidth=1.5, label='Decent')
ax0.plot(x_qual, qual_hi, 'r', linewidth=1.5, label='Great')
Exemple #47
0
def getRangeError(truthData, system, inMF='sing', outMF='sing'):
    """
    Get a system's error against a set of truth data using Range outputs. (MUST 
    BE SYSTEM WITH FUZZY OUTPUT, NOT CRISP). For crisp (sing) outMF, error is 
    distance outside alpha-cut at maximum of system's output fuzzy membership fucntion.
    For fuzzy outMF (gauss, tri, trap), gets output alpha-cut range at alpha=1.0, 
    and error is error function by fuzErrorAC.
    ------INPUTS------
    truthData - list
        truth data to compare system output to in form:
                [Quant Input, Qual Input, Output]
                with inputs as {('input'): [values], ('input'): [values], ... }
                and outputs as [output value(s)]
    system : module
        instance of system to get error on !MUST BE FUZZY OUTPUT!
    inMF : string
        type of MF to use for input data ('sing', 'tri', 'trap', 'gauss')
    outMF : string
        type of MF to use for output data ('sing', 'tri', 'trap', 'gauss')
    sysOutType : string
        type of output to use from system ('crisp' or 'fuzzy')
        converts fuzzy outputs to crisp via 'centroid' defuzzification
    ------OUTPUTS------
    error : list
        list of [truth[min,max], truth[min,max], error]
    """
    q = 0 #use quantitative data
    
    error = [] #track error for output

    #Turn Data to MFs
    for point in truthData:
        #create input MFs for each input
        for inp in point[q]:
            if inMF == 'sing':   #create singleton MF
                point[q][inp] = sum(point[q][inp])/len(point[q][inp]) #get mean of range (single value)
            elif inMF == 'tri':   #create triangluar MF (min, avg, max)
                x_range = np.arange(point[q][inp][0]*0.9, point[q][inp][1]*1.1, 
                                    (point[q][inp][1]*1.1 - point[q][inp][0]*0.9)/150)
                y_vals = fuzz.trimf(x_range, [point[q][inp][0], sum(point[q][inp])/len(point[q][inp]), point[q][inp][1]])
                point[q][inp] = [x_range, y_vals]
            elif inMF == 'trap':  #create traoeziodal MF (min, min, max, max)
                x_range = np.arange(point[q][inp][0]*0.9, point[q][inp][1]*1.1, 
                                    (point[q][inp][1]*1.1 - point[q][inp][0]*0.9)/150)
                y_vals = fuzz.trimf(x_range, [dataIt[q][inp][0], point[q][inp][0],
                                    point[q][inp][0], point[q][inp][1]])
                point[q][inp] = [x_range, y_vals]    
        #create output MFs
        if outMF == 'sing':   #create singleton MF
            point[2] = sum(point[2])/len(point[2]) #get average for singleton value
        elif outMF == 'tri':   #create singleton MF
            x_range = np.arange(point[2][0]*0.9, point[2][1]*1.1, 
                                (point[2][1]*1.1 - point[2][0]*0.9)/150)
            y_vals = fuzz.trimf(x_range, [point[2][0], sum(point[2])/len(point[2]), point[2][1]])
            point[2] = [x_range, y_vals]        
        elif outMF == 'trap':   #create singleton MF
            x_range = np.arange(point[2][0]*0.9, point[2][1]*1.1, (point[2][1]*1.1 - point[2][0]*0.9)/150)
            y_vals = fuzz.trimf(x_range, [point[2][0], point[2][0], point[2][1], point[2][1]])
            point[2] = [x_range, y_vals]
    
    #Get system responses to data
    for point in truthData:
        inputs = {key[0]+"_"+key[1]:point[0][key] for key in point[0]}
        output = system.run(inputs)
        if isinstance(output, dict): output = output.itervalues().next()
        point.append(output)
    
    for point in truthData:             
        #get error
        if not outMF=='sing':  #if data is fuzzy
            err = fuzzy_error.fuzErrorAC(point[2], point[3])
            truthRange = fuzzyOps.alpha_at_val(point[2][0], point[2][1], alpha=1.0)
            outRange = fuzzyOps.alpha_at_val(point[3], point[3])
        else:
            outRange = fuzzyOps.alpha_at_val(point[3][0], point[3][1])
            
            if None in outRange: err = None
            elif point[2] >= min(outRange) and point[2] <= max(outRange):
                err = 0
            elif point[2] < min(outRange):
                err = point[2] - min(outRange)
            elif point[2] > max(outRange):
                err = point[2] - max(outRange)
            truthRange = point[2]
            
        error.append([truthRange, outRange, err])
        
    return error   
Exemple #48
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

age = ctrl.Antecedent(np.arange(18, 100, 1), 'age')
jobs = ctrl.Antecedent(np.arange(0, 10, 1), 'jobs')
salary = ctrl.Consequent(np.arange(1500, 10000, 500), 'salary')

age['young'] = fuzz.trimf(age.universe, [18, 18, 35])
age['middle aged'] = fuzz.trimf(age.universe, [30, 40, 50])
age['old'] = fuzz.trimf(age.universe, [45, 65, 65])

jobs['few'] = fuzz.trimf(jobs.universe, [0, 0, 2])
jobs['medium'] = fuzz.trimf(jobs.universe, [1, 4, 6])
jobs['many'] = fuzz.trimf(jobs.universe, [5, 10, 10])

salary['low'] = fuzz.trimf(salary.universe, [1500, 1500, 2500])
salary['medium'] = fuzz.trimf(salary.universe, [2000, 5000, 7000])
salary['high'] = fuzz.trimf(salary.universe, [6000, 10000, 10000])
salary.view()
rules = []
rules.append(ctrl.Rule(age['young'] | jobs['few'], salary['low']))
rules.append(ctrl.Rule(age['middle aged'] & jobs['many'], salary['high']))
rules.append(ctrl.Rule(age['middle aged'] | jobs['medium'], salary['medium']))
rules.append(ctrl.Rule(age['middle aged'] & jobs['few'], salary['low']))
rules.append(ctrl.Rule(age['old'] | jobs['many'], salary['high']))

navigation_ctrl = ctrl.ControlSystem(rules)

fis = ctrl.ControlSystemSimulation(navigation_ctrl)
Exemple #49
0
sys.argv.append("--cp_ids")
sys.argv.append("1")

import RaicerSocket
from Utils import S_WAIT, S_COUNTDOWN, S_RUNNING, S_FINISHED, S_CRASHED, S_CANCELED, print_debug
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
from Features import FeatureCalculator
import time

# build fuzzy logic

# Antecedents
s_h = ctrl.Antecedent(np.arange(-30, 31, .1), 'speed h')
s_h['fast left'] = fuzz.trimf(s_h.universe, [-30, -30, -10])
s_h['medium left'] = fuzz.trimf(s_h.universe, [-15, -10, -5])
s_h['slow left'] = fuzz.trimf(s_h.universe, [-10, -1, 0])
s_h['slow'] = fuzz.trimf(s_h.universe, [-1, 0, 1])
s_h['slow right'] = fuzz.trimf(s_h.universe, [0, 1, 10])
s_h['medium right'] = fuzz.trimf(s_h.universe, [5, 10, 15])
s_h['fast right'] = fuzz.trimf(s_h.universe, [10, 30, 30])

s_v = ctrl.Antecedent(np.arange(-30, 31, .1), 'speed v')
s_v['fast up'] = fuzz.trimf(s_h.universe, [-30, -30, -10])
s_v['medium up'] = fuzz.trimf(s_h.universe, [-15, -10, -5])
s_v['slow up'] = fuzz.trimf(s_h.universe, [-10, -1, 0])
s_v['slow'] = fuzz.trimf(s_v.universe, [-1, 0, 1])
s_v['slow down'] = fuzz.trimf(s_h.universe, [0, 1, 10])
s_v['medium down'] = fuzz.trimf(s_h.universe, [5, 10, 15])
s_v['fast down'] = fuzz.trimf(s_h.universe, [10, 30, 30])
Exemple #50
0
mx = np.max(Im)
mx = mx.astype(int)
print mx
fcm_gr = ctrl.Antecedent(np.arange(-1, np.max(Im) + 2), 'grupos')
fcm_sl = ctrl.Consequent(np.arange(0,256,1), 'salida')
for i in range(ncenters):
    
    if i == 0:
        abc = [0, 0, cntr[ord[i+1]]]
        #print(abc)
    elif i == ncenters-1:
        abc = [cntr[ord[i-1]], cntr[ord[i]], np.max(Im)+2]
    else:
        abc = [cntr[ord[i-1]], cntr[ord[i]], cntr[ord[i+1]]]
    
    fu = fuzz.trimf(np.arange(-1, np.max(Im) + 2), abc)
    fu2 = fuzz.gaussmf(np.arange(0,256,1), lev*i, w[ord[i]] / 2)
    str1 = "ce" + str(i)
    str2 = "sl" + str(i)

    fcm_gr[str1] = fu
    fcm_sl[str2] = fu2



rl = []

for i in range(ncenters):
    s1 = "ce" + str(i)
    s2 = "sl" + str(i)
    rule = ctrl.Rule(fcm_gr[s1],fcm_sl[s2])
# A continuación se define manualmente el soporte de cada un de las etiquetas, en este caso trapezoidales.

Muy_Arriba = fuzz.trapmf(Rango_Equipos, [1, 1, 3, 5])
Arriba = fuzz.trapmf(Rango_Equipos, [3, 5, 7, 9])
Mitad = fuzz.trapmf(Rango_Equipos, [7, 9, 11, 13])
Abajo = fuzz.trapmf(Rango_Equipos, [11, 13, 15, 17])
Muy_Abajo = fuzz.trapmf(Rango_Equipos, [15, 17, 20, 20])

Minimo_Presupuesto = fuzz.trapmf(Rango_Presupuestos, [1, 1, 10, 20])
Bajo_Presupuesto = fuzz.trapmf(Rango_Presupuestos, [10, 30, 50, 70])
Normal_Presupuesto = fuzz.trapmf(Rango_Presupuestos, [50, 80, 110, 140])
Alto_Presupuesto = fuzz.trapmf(Rango_Presupuestos, [100, 200, 400, 500])
Enorme_Presupuesto = fuzz.trapmf(Rango_Presupuestos, [400, 700, 950, 950])

No_Racha_Ganando = fuzz.trimf(Rango_Rachas, [0, 0, 3])
Corta_Racha_Ganando = fuzz.trapmf(Rango_Rachas, [2, 3, 4, 5])
Normal_Racha_Ganando = fuzz.trapmf(Rango_Rachas, [3, 4, 5, 6])
Buena_Racha_Ganando = fuzz.trapmf(Rango_Rachas, [5, 7, 9, 11])
Enorme_Racha_Ganando = fuzz.trapmf(Rango_Rachas, [7, 18, 38, 38])

Buena_Racha_Perdiendo = fuzz.trimf(Rango_Rachas, [0, 0, 3])
Normal_Racha_Perdiendo = fuzz.trapmf(Rango_Rachas, [2, 4, 6, 8])
Mala_Racha_Perdiendo = fuzz.trapmf(Rango_Rachas, [6, 8, 10, 12])
Pesima_Racha_Perdiendo = fuzz.trapmf(Rango_Rachas, [8, 15, 38, 38])

Buena_Racha_Empatando = fuzz.trimf(Rango_Rachas, [0, 0, 4])
Normal_Racha_Empatando = fuzz.trapmf(Rango_Rachas, [3, 5, 7, 9])
Mala_Racha_Empatando = fuzz.trapmf(Rango_Rachas, [6, 8, 10, 12])
Pesima_Racha_Empatando = fuzz.trapmf(Rango_Rachas, [8, 15, 38, 38])
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt

temperatura = ctrl.Antecedent(np.arange(100, 500, 1), 'temperatura')
pressao = ctrl.Antecedent(np.arange(4, 12, 1), 'pressao')
acelerador = ctrl.Consequent(np.arange(0, 100, 1), 'acelerador')

temperatura['baixa'] = fuzz.trapmf(temperatura.universe, [100, 100, 200, 300])
temperatura['media'] = fuzz.trimf(temperatura.universe, [200, 300, 400])
temperatura['alta'] = fuzz.trapmf(temperatura.universe, [300, 400, 500, 500])
temperatura.view()

pressao['baixa'] = fuzz.trapmf(pressao.universe, [4, 4, 6, 8])
pressao['media'] = fuzz.trimf(pressao.universe, [6, 8, 10])
pressao['alta'] = fuzz.trapmf(pressao.universe, [8, 10, 12, 12])
pressao.view()

acelerador['min'] = fuzz.trapmf(acelerador.universe, [0, 0, 25, 50])
acelerador['0'] = fuzz.trimf(acelerador.universe, [25, 50, 75])
acelerador['max'] = fuzz.trapmf(acelerador.universe, [50, 75, 100, 100])
acelerador.view()

rule1 = ctrl.Rule(temperatura['media'] & pressao['media'], acelerador['0'])
rule2 = ctrl.Rule(temperatura['alta'] & pressao['alta'], acelerador['max'])
rule3 = ctrl.Rule(temperatura['media'] & pressao['media'], acelerador['0'])
rule4 = ctrl.Rule(temperatura['alta'] & pressao['alta'], acelerador['max'])

acelerador_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4])
acel = ctrl.ControlSystemSimulation(acelerador_ctrl)
Exemple #53
0
def fis_opt(e_teta, error, params=[], grafica=False):
    a, b, c, d, e, f, g, h = list(map(abs, params))
    #print(params,e_teta, error)
    factor_apertura = 1.3

    x_e_teta = np.arange(-5, 5, 0.5)
    x_error = np.arange(-5, 5, 0.5)
    x_omega = np.arange(-5, 5, 0.5)

    # Generate fuzzy membership functions trapezoidal y triangular
    e_teta_hi_neg = fuzz.trapmf(x_e_teta, [-100, -100, -5 + (a * 2), -1])
    e_teta_med_neg = fuzz.trimf(
        x_e_teta, [-1 - b * factor_apertura, -1, -1 + b * factor_apertura])
    e_teta_lo = fuzz.trimf(
        x_e_teta, [0 - c * factor_apertura, 0, 0 + c * factor_apertura])
    e_teta_med_pos = fuzz.trimf(
        x_e_teta, [1 - d * factor_apertura, 1, 1 + d * factor_apertura])
    e_teta_hi_pos = fuzz.trapmf(x_e_teta, [1, 5 - (a * 2), 100, 100])

    error_hi_neg = fuzz.trapmf(x_error, [-100, -100, -5 + (e * 2), -1])
    error_med_neg = fuzz.trimf(
        x_e_teta, [-1 * factor_apertura - f, -1, -1 + f * factor_apertura])
    error_lo = fuzz.trimf(
        x_error, [0 - g * factor_apertura, 0, 0 + g * factor_apertura])
    error_med_pos = fuzz.trimf(
        x_e_teta, [1 - h * factor_apertura, 1, 1 + h * factor_apertura])
    error_hi_pos = fuzz.trapmf(x_error, [1, 5 - (e * 2), 100, 100])

    omega_hi_neg = fuzz.trapmf(x_omega, [-5, -5, -2, -1])
    omega_med_neg = fuzz.trimf(x_omega, [-2, -1, -0])
    omega_lo = fuzz.trimf(x_omega, [-1, 0, 1])
    omega_med_pos = fuzz.trimf(x_omega, [0, 1, 2])
    omega_hi_pos = fuzz.trapmf(x_omega, [1, 2, 5, 8])

    # We need the activation of our fuzzy membership functions at these values.
    # This is what fuzz.interp_membership exists for!
    e_teta_level_hi_neg = fuzz.interp_membership(x_e_teta, e_teta_hi_neg,
                                                 e_teta)
    e_teta_level_med_neg = fuzz.interp_membership(x_e_teta, e_teta_med_neg,
                                                  e_teta)
    e_teta_level_lo = fuzz.interp_membership(x_e_teta, e_teta_lo, e_teta)
    e_teta_level_med_pos = fuzz.interp_membership(x_e_teta, e_teta_med_pos,
                                                  e_teta)
    e_teta_level_hi_pos = fuzz.interp_membership(x_e_teta, e_teta_hi_pos,
                                                 e_teta)

    error_level_hi_neg = fuzz.interp_membership(x_error, error_hi_neg, error)
    error_level_med_neg = fuzz.interp_membership(x_error, error_med_neg, error)
    error_level_lo = fuzz.interp_membership(x_error, error_lo, error)
    error_level_med_pos = fuzz.interp_membership(x_error, error_med_pos, error)
    error_level_hi_pos = fuzz.interp_membership(x_error, error_hi_pos, error)

    if grafica:
        # Visualize these universes and membership functions
        fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(8, 9))

        ax0.plot(x_e_teta,
                 e_teta_hi_neg,
                 'b',
                 linewidth=1.5,
                 label='Alto negativo')
        ax0.plot(x_e_teta,
                 e_teta_med_neg,
                 'm',
                 linewidth=1.5,
                 label='Medio negativo')
        ax0.plot(x_e_teta, e_teta_lo, 'g', linewidth=1.5, label='Bajo')
        ax0.plot(x_e_teta,
                 e_teta_med_pos,
                 'k',
                 linewidth=1.5,
                 label='Medio positivo')
        ax0.plot(x_e_teta,
                 e_teta_hi_pos,
                 'r',
                 linewidth=1.5,
                 label='Alto positivo')
        ax0.set_title('Error Theta')
        ax0.legend()

        ax1.plot(x_error,
                 error_hi_neg,
                 'b',
                 linewidth=1.5,
                 label='Alto negativo')
        ax1.plot(x_error,
                 error_med_neg,
                 'm',
                 linewidth=1.5,
                 label='Medio negativo')
        ax1.plot(x_error, error_lo, 'g', linewidth=1.5, label='Bajo')
        ax1.plot(x_error,
                 error_med_pos,
                 'k',
                 linewidth=1.5,
                 label='Medio positivo')
        ax1.plot(x_error,
                 error_hi_pos,
                 'r',
                 linewidth=1.5,
                 label='Alto positivo')
        ax1.set_title('Error')
        ax1.legend()

        ax2.plot(x_omega,
                 omega_hi_neg,
                 'b',
                 linewidth=1.5,
                 label='Alto negativo')
        ax2.plot(x_omega,
                 omega_med_neg,
                 'm',
                 linewidth=1.5,
                 label='Medio negativo')
        ax2.plot(x_omega, omega_lo, 'g', linewidth=1.5, label='Bajo')
        ax2.plot(x_omega,
                 omega_med_pos,
                 'k',
                 linewidth=1.5,
                 label='Medio positivo')
        ax2.plot(x_omega,
                 omega_hi_pos,
                 'r',
                 linewidth=1.5,
                 label='Alto positivo')
        ax2.set_title('Omega')
        ax2.legend()

        # Turn off top/right axes
        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()
        plt.show()

    # Now we take our rules and apply them.
    # fmin regresa el minimo de los dos arreglos o valores
    # fmax regresa el maximo de los dos arreglos o valores
    # The OR operator means we take the maximum of these two.
    # The AND operator means we take el minimun of these two

    # # Rule 1 si e_teta es hi_neg y error es low entonces omega es hi pos
    active_rule1 = np.fmin(e_teta_level_hi_neg, error_level_lo)
    # tip_activation_1 = np.fmin(active_rule1, omega_hi_pos)
    #
    # # Rule 2 si e_teta es hi_pos y error es low entonces omega es hi neg
    active_rule2 = np.fmin(e_teta_level_hi_pos, error_level_lo)
    # tip_activation_2 = np.fmin(active_rule2, omega_hi_neg)
    #
    # # Rule 3 si e_teta es low y error es low entonces omega es low
    active_rule3 = np.fmin(e_teta_level_lo, error_level_lo)
    # tip_activation_3 = np.fmin(active_rule3, omega_lo)
    #
    # # Rule 4 si e_teta es hi_neg y error es hi_neg entonces omega es hi pos
    active_rule4 = np.fmin(e_teta_level_hi_neg, error_level_hi_neg)
    # tip_activation_4 = np.fmin(active_rule4, omega_hi_pos)
    #
    # # Rule 5 si e_teta es hi_pos y error es hi_pos entonces omega es hi neg
    active_rule5 = np.fmin(e_teta_level_hi_pos, error_level_hi_pos)
    # tip_activation_5 = np.fmin(active_rule5, omega_hi_neg)
    #
    # # Rule 6 si e_teta es hi_pos y error es hi_neg entonces omega es bajo
    active_rule6 = np.fmin(e_teta_level_hi_pos, error_level_hi_neg)
    # tip_activation_6 = np.fmin(active_rule6, omega_lo)
    #
    # # Rule 7 si e_teta es hi_neg y error es hi_pos entonces omega es bajo
    active_rule7 = np.fmin(e_teta_level_hi_neg, error_level_hi_pos)
    # tip_activation_7 = np.fmin(active_rule7, omega_lo)
    #
    # # Rule 8 si e_teta es low y error es hi_pos entonces omega es hi_neg
    active_rule8 = np.fmin(e_teta_level_lo, error_level_hi_pos)
    # tip_activation_8 = np.fmin(active_rule8, omega_hi_neg)
    #
    # # Rule 9 si e_teta es low y error es hi_neg entonces omega es hi_pos
    active_rule9 = np.fmin(e_teta_level_lo, error_level_hi_neg)
    # tip_activation_9 = np.fmin(active_rule9, omega_hi_pos)
    #
    # # Rule 10 si e_teta es med_neg y error es med_neg entonces omega es med_neg
    active_rule10 = np.fmin(e_teta_level_med_neg, error_level_med_neg)
    # tip_activation_10 = np.fmin(active_rule10, omega_med_neg)
    #
    # # Rule 11 si e_teta es med_pos y error es med_pos entonces omega es med_neg
    active_rule11 = np.fmin(e_teta_level_med_pos, error_level_med_pos)
    # tip_activation_11 = np.fmin(active_rule11, omega_med_neg)
    #
    # # Rule 12 si e_teta es med_neg y error es med_pos entonces omega es med_neg
    active_rule12 = np.fmin(e_teta_level_med_neg, error_level_med_pos)
    # tip_activation_12 = np.fmin(active_rule12, omega_med_neg)
    #
    # # Rule 13 si e_teta es med_pos y error es med_neg entonces omega es med_pos
    active_rule13 = np.fmin(e_teta_level_med_pos, error_level_med_neg)
    # tip_activation_13 = np.fmin(active_rule13, omega_med_pos)
    #
    # # Rule 14 si e_teta es med_neg y error es hi_neg entonces omega es med_pos
    active_rule14 = np.fmin(e_teta_level_med_neg, error_level_hi_neg)
    # tip_activation_14 = np.fmin(active_rule14, omega_med_pos)
    #
    # # Rule 15 si e_teta es hi_neg y error es med_neg entonces omega es hi_pos
    active_rule15 = np.fmin(e_teta_level_hi_neg, error_level_med_neg)
    # tip_activation_15 = np.fmin(active_rule14, omega_hi_pos)
    #
    # # Rule 16 si e_teta es hi_neg y error es med_pos entonces omega es hi_neg
    active_rule16 = np.fmin(e_teta_level_hi_neg, error_level_med_pos)
    # tip_activation_16 = np.fmin(active_rule14, omega_hi_neg)
    #
    # # Rule 17 si e_teta es hi_pos y error es med_neg entonces omega es low
    active_rule17 = np.fmin(e_teta_level_hi_pos, error_level_med_neg)
    # tip_activation_17 = np.fmin(active_rule14, omega_lo)
    #
    # # Rule 18 si e_teta es hi_pos y error es med_pos entonces omega es lo
    active_rule18 = np.fmin(e_teta_level_hi_pos, error_level_med_pos)
    # tip_activation_18 = np.fmin(active_rule14, omega_lo)
    #
    # # Rule 19 si e_teta es med_neg y error es hi_pos entonces omega es med_pos
    active_rule19 = np.fmin(e_teta_level_med_neg, error_level_hi_pos)
    # tip_activation_19 = np.fmin(active_rule14, omega_med_pos)
    #
    # # Rule 20 si e_teta es med_pos y error es low entonces omega es med_neg
    active_rule20 = np.fmin(e_teta_level_med_pos, error_level_lo)
    # tip_activation_20 = np.fmin(active_rule14, omega_med_neg)
    #
    # # Rule 21 si e_teta es med_neg y error es low entonces omega es med_pos
    active_rule21 = np.fmin(e_teta_level_med_neg, error_level_lo)
    # tip_activation_21 = np.fmin(active_rule14, omega_med_pos)
    #
    # # Rule 22 si e_teta es low y error es med_neg entonces omega es med_pos
    active_rule22 = np.fmin(e_teta_level_lo, error_level_med_neg)
    # tip_activation_22 = np.fmin(active_rule14, omega_med_pos)
    #
    # # Rule 23 si e_teta es low y error es med_pos entonces omega es med_neg
    active_rule23 = np.fmin(e_teta_level_lo, error_level_med_pos)
    # tip_activation_23 = np.fmin(active_rule14, omega_med_neg)

    # # Rule 24 si e_teta es med_pos y error es hi_pos entonces omega es med_neg
    active_rule24 = np.fmin(e_teta_level_med_pos, error_level_hi_pos)
    # tip_activation_24 = np.fmin(active_rule24, omega_med_neg)

    # # Rule 25 si e_teta es med_pos y error es hi_neg entonces omega es med_pos
    active_rule25 = np.fmin(e_teta_level_med_pos, error_level_hi_neg)
    # tip_activation_25 = np.fmin(active_rule25, omega_med_neg)

    active_rule_Hi_neg = np.fmin(
        active_rule2,
        np.fmin(active_rule5, np.fmin(active_rule8, active_rule16)))
    tip_activation_Hi_neg = np.fmax(active_rule_Hi_neg, omega_hi_neg)

    active_rule_Hi_pos = np.fmin(
        active_rule1,
        np.fmin(active_rule4, np.fmin(active_rule9, active_rule15)))
    tip_activation_Hi_pos = np.fmax(active_rule_Hi_pos, omega_hi_pos)

    active_rule_med_neg = np.fmin(
        active_rule10,
        np.fmin(
            active_rule11,
            np.fmin(
                active_rule12,
                np.fmin(active_rule20, np.fmin(active_rule23,
                                               active_rule24)))))
    tip_activation_med_neg = np.fmax(active_rule_med_neg, omega_med_neg)

    active_rule_med_pos = np.fmin(
        active_rule13,
        np.fmin(
            active_rule14,
            np.fmin(
                active_rule19,
                np.fmin(active_rule21, np.fmin(active_rule22,
                                               active_rule25)))))
    tip_activation_med_pos = np.fmax(active_rule_med_pos, omega_med_pos)

    active_rule_low = np.fmin(
        active_rule3,
        np.fmin(active_rule6,
                np.fmin(active_rule7, np.fmin(active_rule17, active_rule18))))
    tip_activation_low = np.fmax(active_rule_low, omega_lo)

    #aggregated = np.fmax(tip_activation_23, np.fmax(tip_activation_22,np.fmax(tip_activation_21, np.fmax(tip_activation_20,np.fmax(tip_activation_19, np.fmax(tip_activation_18,np.fmax(tip_activation_17, np.fmax(tip_activation_16, np.fmax(tip_activation_15, np.fmax(tip_activation_14,np.fmax(tip_activation_13, np.fmax(tip_activation_12,np.fmax(tip_activation_11, np.fmax(tip_activation_10,np.fmax(tip_activation_9, np.fmax(tip_activation_8,np.fmax(tip_activation_7, np.fmax(tip_activation_6, np.fmax(tip_activation_5, np.fmax(tip_activation_4, np.fmax(tip_activation_1, np.fmax(tip_activation_2, tip_activation_3))))))))))))))))))))))
    aggregated = np.fmax(
        tip_activation_Hi_neg,
        np.fmax(
            tip_activation_Hi_pos,
            np.fmax(tip_activation_med_neg,
                    np.fmax(tip_activation_med_pos, tip_activation_low))))
    # Calculate defuzzified result
    omega = fuzz.defuzz(x_omega, aggregated, 'centroid')
    #tip_activation = fuzz.interp_membership(x_omega, aggregated, omega)  # for plot

    # Visualize this
    #    if grafica:
    #        fig, ax0 = plt.subplots(figsize=(8, 3))
    #
    #        ax0.fill_between(x_omega,  tip_activation_1, facecolor='b', alpha=0.7)
    #        ax0.plot(x_omega, omega_hi_neg, 'b', linewidth=0.5, linestyle='--', )
    #        ax0.fill_between(x_omega, tip_activation_2, facecolor='g', alpha=0.7)
    #        ax0.plot(x_omega, omega_lo, 'g', linewidth=0.5, linestyle='--')
    #        ax0.fill_between(x_omega,  tip_activation_3, facecolor='r', alpha=0.7)
    #        ax0.plot(x_omega, omega_hi_pos, 'r', linewidth=0.5, linestyle='--')
    #        ax0.set_title('Output membership activity')
    #
    #
    #    # Visualize this
    #    if grafica:
    #        fig, ax0 = plt.subplots(figsize=(8, 3))
    #
    #        ax0.plot(x_omega, omega_hi_neg, 'b', linewidth=0.5, linestyle='--', )
    #        ax0.plot(x_omega, omega_lo, 'g', linewidth=0.5, linestyle='--')
    #        ax0.plot(x_omega, omega_hi_pos, 'r', linewidth=0.5, linestyle='--')
    #        ax0.fill_between(x_omega,  aggregated, facecolor='Orange', alpha=0.7)
    #        ax0.plot([omega, omega], [0, tip_activation], 'k', linewidth=1.5, alpha=0.9)
    #        ax0.set_title('Aggregated membership and result (line)')

    # plt.tight_layout()
    # plt.show()
    return omega
Exemple #54
0
def FuzzControl(error):

    x_pos = np.arange(-480, 480, 1)
    x_speed = np.arange(0, 255, 1)

    # Generate fuzzy membership functions
    pos_NB = fuzz.trimf(x_pos, [-480, -360, -240])
    pos_NM = fuzz.trimf(x_pos, [-360, -240, -120])
    pos_NS = fuzz.trimf(x_pos, [-240, -120, 0])
    pos_0 = fuzz.trimf(x_pos, [-120, 0, 120])
    pos_S = fuzz.trimf(x_pos, [0, 120, 240])
    pos_M = fuzz.trimf(x_pos, [120, 240, 360])
    pos_B = fuzz.trimf(x_pos, [240, 360, 480])

    speed_NB = fuzz.trimf(x_speed, [0, 0, 43])
    speed_NM = fuzz.trimf(x_speed, [0, 43, 85])
    speed_NS = fuzz.trimf(x_speed, [43, 85, 128])
    speed_0 = fuzz.trimf(x_speed, [85, 128, 171])
    speed_S = fuzz.trimf(x_speed, [128, 171, 213])
    speed_M = fuzz.trimf(x_speed, [171, 213, 255])
    speed_B = fuzz.trimf(x_speed, [213, 255, 255])
    """
    Fuzzy rules
    -----------
    
    1. Si Error en pos es NB, entonces la Velocidad es B
    2. Si Error en pos es NM, entonces la Velocidad es M
    3. Si Error en pos es NS, entonces la Velocidad es S
    4. Si Error en pos es 0, entonces la Velocidad es 0
    5. Si Error en pos es S, entonces la Velocidad es NS
    6. Si Error en pos es M, entonces la Velocidad es NM
    7. Si Error en pos es B, entonces la Velocidad es NB.
    """

    level_pos_NB = fuzz.interp_membership(x_pos, pos_NB, error)
    level_pos_NM = fuzz.interp_membership(x_pos, pos_NM, error)
    level_pos_NS = fuzz.interp_membership(x_pos, pos_NS, error)
    level_pos_0 = fuzz.interp_membership(x_pos, pos_0, error)
    level_pos_S = fuzz.interp_membership(x_pos, pos_S, error)
    level_pos_M = fuzz.interp_membership(x_pos, pos_M, error)
    level_pos_B = fuzz.interp_membership(x_pos, pos_B, error)

    #Regla 1
    SNB = np.fmin(level_pos_NB, speed_B)
    #Regla 2
    SNM = np.fmin(level_pos_NM, speed_M)
    #Regla 3
    SNS = np.fmin(level_pos_NS, speed_S)
    #Regla 4
    S0 = np.fmin(level_pos_0, speed_0)
    #Regla 5
    SS = np.fmin(level_pos_S, speed_NS)
    #Regla 6
    SM = np.fmin(level_pos_M, speed_NM)
    #Regla 7
    SB = np.fmin(level_pos_B, speed_NB)

    # Aggregate all three output membership functions together
    aggregated = np.fmax(
        SNB,
        np.fmax(SNM, np.fmax(SNS, np.fmax(S0, np.fmax(SS, np.fmax(SM, SB))))))

    # Calculate defuzzified result
    Speed = fuzz.defuzz(x_speed, aggregated, 'centroid')
    Speedf = int(np.around(Speed, decimals=0))

    return Speedf
Exemple #55
0
"""
    if temperature is hot then ice cream parlor is crowded.
    if temperature is moderate then ice cream parlor is busy.
    if temperature is cool then ice cream parlor is quiet.
"""
import numpy as np
import skfuzzy as fuzz
import matplotlib.pyplot as plt

#Univerese functions
temp = np.arange(30, 101, 1)
customers = np.arange(0,36, 1)

#Membership function for heat
t_hot = fuzz.trimf(temp, [65, 100, 100])
t_mod = fuzz.trimf(temp, [30, 65, 100])
t_cool = fuzz.trapmf(temp, [20, 20, 30, 65])

#Membership function for customers
c_crowded = fuzz.trimf(customers, [24, 35, 35])
c_busy = fuzz.trimf(customers, [0, 24, 35])
c_quiet = fuzz.trimf(customers, [0, 0, 24])

"""Visualise system"""



# Visualize membership functions for temperature
'''fig, ax = plt.subplots()

ax.plot(temp, t_hot, 'r', temp, t_mod, 'm', temp, t_cool, 'b')
Exemple #56
0
import matplotlib.pyplot as plt
import numpy as np, skfuzzy as fuzz
from skfuzzy import control as ctrl

# define domain interval and resolution of fuzzy sets inputs-output
x_err      = np.arange(-4,4, 0.1)
x_errRate  = np.arange(-10,10, 0.1)
x_outPower = np.arange(-100,100, 0.1)

# define fuzzy set shapes or membership functions
err_N = fuzz.trapmf(x_err,[-4,-4,-2,0])
err_Z = fuzz.trimf(x_err,[-2,0,2])
err_P = fuzz.trapmf(x_err,[0,2,4,4])

errRate_N = fuzz.trapmf(x_errRate,[-10,-10,-5,0])
errRate_Z = fuzz.trimf(x_errRate,[-5,0,5])
errRate_P = fuzz.trapmf(x_errRate,[0,5,10,10])

outPower_C  = fuzz.trapmf(x_outPower, [-100,-100,-50,0])
outPower_NC = fuzz.trimf(x_outPower, [-50,0,50])
outPower_H  = fuzz.trapmf(x_outPower, [0,50,100,100])

# Visualize membership functions ----------------------------

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2, figsize=(11, 7))
ax1.plot(x_err, err_N, 'b', lw=2, label='err_N')
ax1.plot(x_err, err_P, 'r', lw=2, label='err_P')
ax1.plot(x_err, err_Z, 'orange', lw=2, label='err_Z')
ax1.set_xlabel('err', fontsize=10)
ax1.set_ylabel('Membership', fontsize=10)
ax1.set_title('Temp Different Fuzzy Sets')
Exemple #57
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl


fused_estimation = ctrl.Antecedent(np.arange(0, 11, 1), 'fused_estimation')
kde_result = ctrl.Antecedent(np.arange(0, 11, 1), 'kde_result')
current = ctrl.Antecedent(np.arange(0, 11, 1), 'current')

pov = ctrl.Consequent(np.arange(0, 11, 1), 'pov')

fused_estimation['low'] = fuzz.trimf(fused_estimation.universe, [0, 0, 5])
fused_estimation['medium'] = fuzz.trimf(fused_estimation.universe, [2, 5, 8])
fused_estimation['high'] = fuzz.trimf(fused_estimation.universe, [5, 8, 10])

kde_result['low'] = fuzz.trimf(kde_result.universe, [0, 0, 5])
kde_result['medium'] = fuzz.trimf(kde_result.universe, [2, 5, 8])
kde_result['high'] = fuzz.trimf(kde_result.universe, [5, 10, 10])

current['low'] = fuzz.trimf(current.universe, [0, 0, 5])
current['medium'] = fuzz.trimf(current.universe, [2, 5, 8])
current['high'] = fuzz.trimf(current.universe, [5, 10, 10])

pov['low'] = fuzz.trimf(pov.universe, [0, 0, 5])
pov['medium'] = fuzz.trimf(pov.universe, [2, 5, 8])
pov['high'] = fuzz.trimf(pov.universe, [5, 10, 10])


proportional=1

if proportional==1:
Exemple #58
0
    def vegFIS(model_run):

        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 == 'pt':
            out_field = "oVC_PT"
            riparian_field = "iVeg_100PT"
            streamside_field = "iVeg_30PT"
        else:
            out_field = "oVC_EX"
            riparian_field = "iVeg_100EX"
            streamside_field = "iVeg_30EX"

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

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

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

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

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

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

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

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

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

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

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

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

        # save fuzzy inference system output as table
        columns = np.column_stack((segid_array, out))
        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 = "")
        ovc_table = scratch + "/" + out_field + "Tbl"
        arcpy.CopyRows_management(out_table, ovc_table)

        # join the fuzzy inference system output to the flowline network
        # create empty dictionary to hold input table field values
        tblDict = {}
        # add values to dictionary
        with arcpy.da.SearchCursor(ovc_table, ['ReachID', out_field]) as cursor:
            for row in cursor:
                tblDict[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:
                    aKey = row[0]
                    row[1] = tblDict[aKey]
                    cursor.updateRow(row)
                except:
                    pass
        tblDict.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 = fuzz.trimf(x, [0, 0, 0.1])
        defuzz_centroid = round(fuzz.defuzz(x, mfx, 'centroid'), 6)

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

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

        # delete temporary tables and arrays
        arcpy.Delete_management(out_table)
        arcpy.Delete_management(ovc_table)
        items = [columns, out, x, mfx, defuzz_centroid]
        for item in items:
            del item
import numpy as np
import skfuzzy as fuzz

# New Antecedent/Consequent objects hold universe variables and membership
# functions
quality = fuzz.Antecedent(np.arange(0, 11, 1), 'quality')
service = fuzz.Antecedent(np.arange(0, 11, 1), 'service')
tip = fuzz.Consequent(np.arange(0, 26, 1), 'tip')

# Auto-membership function population is possible with .automf(3, 5, or 7)
quality.automf(3)
service.automf(3)

# Custom membership functions can be built interactively with a familiar,
# Pythonic API
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])

"""
To help understand what the membership looks like, use the ``view`` methods.
"""

# You can see how these look with .view()
quality['average'].view()
"""
.. image:: PLOT2RST.current_figure
"""
service.view()
"""
.. image:: PLOT2RST.current_figure
Exemple #60
0
def fuzzy_system(pv, ppv, ld):

    prev_req = ctrl.Antecedent(np.arange(0, 1.001, 0.001), 'prev_requests')
    prevprev_req = ctrl.Antecedent(np.arange(0, 1.001, 0.001),
                                   'prevprev_requests')
    load = ctrl.Antecedent(np.arange(0, 1.001, 0.001), 'load')
    crash = ctrl.Consequent(np.arange(0, 1.001, 0.001), 'crash')

    prev_req['poor'] = fuzz.trimf(prev_req.universe, [0, 0, 0.4])
    prev_req['average'] = fuzz.trimf(prev_req.universe, [0, 0.4, 0.6])
    prev_req['good'] = fuzz.trimf(prev_req.universe, [0.6, 1, 1])

    prevprev_req['poor'] = fuzz.trimf(prevprev_req.universe, [0, 0, 0.4])
    prevprev_req['average'] = fuzz.trimf(prevprev_req.universe, [0, 0.4, 0.6])
    prevprev_req['good'] = fuzz.trimf(prevprev_req.universe, [0.6, 1, 1])

    load['poor'] = fuzz.trimf(load.universe, [0, 0, 0.4])
    load['average'] = fuzz.trimf(load.universe, [0, 0.4, 0.6])
    load['good'] = fuzz.trimf(load.universe, [0.6, 1, 1])

    ##########################################################
    #                      Membership Definition             #
    ##########################################################

    prev_req.automf(3)
    prevprev_req.automf(3)
    load.automf(3)

    crash['NO'] = fuzz.trimf(crash.universe, [0, 0, 0.4])
    crash['Crash'] = fuzz.trimf(crash.universe, [0.4, 1, 1])

    #prev_req.view()
    #prevprev_req.view()
    #load.view()
    #crash.view()
    #plt.show()

    ##########################################################
    #                      Rules Definition                  #
    ##########################################################

    rule1 = ctrl.Rule(prev_req['poor'] & prevprev_req['poor'] & load['poor'],
                      crash['NO'])
    rule2 = ctrl.Rule(
        prev_req['poor'] & prevprev_req['average'] & load['poor'], crash['NO'])
    rule3 = ctrl.Rule(prev_req['poor'] & prevprev_req['good'] & load['poor'],
                      crash['NO'])

    rule4 = ctrl.Rule(
        prev_req['average'] & prevprev_req['poor'] & load['poor'], crash['NO'])
    rule5 = ctrl.Rule(
        prev_req['average'] & prevprev_req['average'] & load['poor'],
        crash['NO'])
    rule6 = ctrl.Rule(
        prev_req['average'] & prevprev_req['good'] & load['poor'], crash['NO'])

    rule7 = ctrl.Rule(prev_req['good'] & prevprev_req['poor'] & load['poor'],
                      crash['NO'])
    rule8 = ctrl.Rule(
        prev_req['good'] & prevprev_req['average'] & load['poor'], crash['NO'])
    rule9 = ctrl.Rule(prev_req['good'] & prevprev_req['good'] & load['poor'],
                      crash['NO'])

    rule10 = ctrl.Rule(
        prev_req['poor'] & prevprev_req['poor'] & load['average'], crash['NO'])
    rule11 = ctrl.Rule(
        prev_req['poor'] & prevprev_req['average'] & load['average'],
        crash['NO'])
    rule12 = ctrl.Rule(
        prev_req['poor'] & prevprev_req['good'] & load['average'], crash['NO'])

    rule13 = ctrl.Rule(
        prev_req['average'] & prevprev_req['poor'] & load['average'],
        crash['NO'])
    rule14 = ctrl.Rule(
        prev_req['average'] & prevprev_req['average'] & load['average'],
        crash['NO'])
    rule15 = ctrl.Rule(
        prev_req['average'] & prevprev_req['good'] & load['average'],
        crash['NO'])

    rule16 = ctrl.Rule(
        prev_req['good'] & prevprev_req['poor'] & load['average'], crash['NO'])
    rule17 = ctrl.Rule(
        prev_req['good'] & prevprev_req['average'] & load['average'],
        crash['NO'])
    rule18 = ctrl.Rule(
        prev_req['good'] & prevprev_req['good'] & load['average'], crash['NO'])

    rule19 = ctrl.Rule(prev_req['poor'] & prevprev_req['poor'] & load['good'],
                       crash['NO'])
    rule20 = ctrl.Rule(
        prev_req['poor'] & prevprev_req['average'] & load['good'], crash['NO'])
    rule21 = ctrl.Rule(prev_req['poor'] & prevprev_req['good'] & load['good'],
                       crash['NO'])  #maybe

    rule22 = ctrl.Rule(
        prev_req['average'] & prevprev_req['poor'] & load['good'], crash['NO'])
    rule23 = ctrl.Rule(
        prev_req['average'] & prevprev_req['average'] & load['good'],
        crash['Crash'])
    rule24 = ctrl.Rule(
        prev_req['average'] & prevprev_req['good'] & load['good'],
        crash['Crash'])

    rule25 = ctrl.Rule(prev_req['good'] & prevprev_req['poor'] & load['good'],
                       crash['Crash'])
    rule26 = ctrl.Rule(
        prev_req['good'] & prevprev_req['average'] & load['good'],
        crash['Crash'])
    rule27 = ctrl.Rule(prev_req['good'] & prevprev_req['good'] & load['good'],
                       crash['Crash'])

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

    crsh = ctrl.ControlSystemSimulation(input_control)

    ##########################################################
    #                      Inputs Definition                 #
    ##########################################################

    crsh.input['prev_requests'] = pv
    crsh.input['prevprev_requests'] = ppv
    crsh.input['load'] = ld

    print("inputs", pv, ppv, ld)

    crsh.compute()

    result = crsh.output['crash']
    print(result)
    #crash.view(sim=crsh)
    #plt.show()
    return result