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

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

        # MEMBERSHIPS FUN

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.type = ctrl.ControlSystemSimulation(self.typeControl)
    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])
Beispiel #3
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
def test_lambda_cut_boundaries():
    x = np.arange(10)
    mfx = fuzz.trapmf(x, [0, 6, 7, 10])

    assert_allclose(fuzz.lambda_cut_boundaries(x, mfx, 0.2), np.r_[1.2])

    x = np.arange(11)
    mfx = fuzz.trapmf(x, [0, 6, 7, 10])
    assert_allclose(fuzz.lambda_cut_boundaries(x, mfx, 0.2), np.r_[1.2, 9.4])
Beispiel #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)
Beispiel #6
0
def test_defuzz():
    x = np.arange(21) - 10
    gmf = fuzz.gaussmf(x, 0, 2)

    assert_allclose(0, fuzz.defuzz(x, gmf, 'centroid'), atol=1e-9)
    assert_allclose(0, fuzz.defuzz(x, gmf, 'bisector'), atol=1e-9)
    assert_allclose(0, fuzz.defuzz(x, gmf, 'mom'))
    assert_allclose(0, fuzz.defuzz(x, gmf, 'som'))
    assert_allclose(0, fuzz.defuzz(x, gmf, 'lom'))

    # Fuzzy plateau to differentiate mom, som, lom
    trapmf = fuzz.trapmf(x, [-1, 3, 7, 8])

    assert_allclose(3, fuzz.defuzz(x, trapmf, 'som'))
    assert_allclose(5, fuzz.defuzz(x, trapmf, 'mom'))
    assert_allclose(7, fuzz.defuzz(x, trapmf, 'lom'))


    # Make sure som/lom work for all-negative universes:
    x_neg = x-20
    assert_allclose(-17, fuzz.defuzz(x_neg, trapmf, 'som'))
    assert_allclose(-13, fuzz.defuzz(x_neg, trapmf, 'lom'))
    
    # Bad string argument
    assert_raises(ValueError, fuzz.defuzz, x, trapmf, 'bad string')
Beispiel #7
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 
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')
Beispiel #9
0
def eval_membership_function_akt(akt_values, positive_change_akt, negative_change_akt):
	'''Evaluates membership function for akt '''
	akt_high = fuzz.gaussmf(akt_values, 1, 0.1)
	akt_low = fuzz.gaussmf(akt_values, 0, 0.3)
	akt_high1 = fuzz.trapmf(akt_values,(0.1,0.1,0.8,1.4))
	positive_change_akt_high = fuzz.gaussmf(positive_change_akt, 1, 0.01)
	positive_change_akt_low = fuzz.gaussmf(positive_change_akt, 0, 0.01)
	negative_change_akt_high = fuzz.gaussmf(negative_change_akt, -1, 0.01)
	negative_change_akt_low = fuzz.gaussmf(negative_change_akt, 0, 0.01)
	return (akt_low, akt_high, positive_change_akt_low, positive_change_akt_high, negative_change_akt_low, negative_change_akt_high, akt_high1)
Beispiel #10
0
def eval_membership_function_erk(erk_values, positive_change_erk, negative_change_erk):
	'''Evaluates membership function for erk '''
	erk_high = fuzz.gaussmf(erk_values, 1, 0.1)
	erk_low = fuzz.gaussmf(erk_values, 0, 0.1)
	erk_high1 = fuzz.trapmf(erk_values,(0.1,0.1,0.8,1.4))
	positive_change_erk_high = fuzz.gaussmf(positive_change_erk, 1, 0.01)
	positive_change_erk_low = fuzz.gaussmf(positive_change_erk, 0, 0.01)
	negative_change_erk_high = fuzz.gaussmf(negative_change_erk, -1, 0.01)
	negative_change_erk_low = fuzz.gaussmf(negative_change_erk, 0, 0.01)
	return (erk_low, erk_high, positive_change_erk_low, positive_change_erk_high, negative_change_erk_low, negative_change_erk_high, erk_high1)
Beispiel #11
0
def eval_membership_function_pi3k(pi3k_values, positive_change_pi3k, negative_change_pi3k):
	'''Evaluates membership function for pi3k '''
	pi3k_high = fuzz.gaussmf(pi3k_values, 1, 0.1)
	pi3k_low = fuzz.gaussmf(pi3k_values, 0, 0.1)
	pi3k_high1 = fuzz.trapmf(pi3k_values,(0.1,0.1,0.8,1.4))
	positive_change_pi3k_high = fuzz.gaussmf(positive_change_pi3k, 1, 0.01)
	positive_change_pi3k_low = fuzz.gaussmf(positive_change_pi3k, 0, 0.01)
	negative_change_pi3k_high = fuzz.gaussmf(negative_change_pi3k, -1, 0.01)
	negative_change_pi3k_low = fuzz.gaussmf(negative_change_pi3k, 0, 0.01)
	return (pi3k_low, pi3k_high, positive_change_pi3k_low, positive_change_pi3k_high, negative_change_pi3k_low, negative_change_pi3k_high, pi3k_high1)
Beispiel #12
0
def eval_membership_function_egfr(egfr_values, positive_change_egfr, negative_change_egfr):
	'''Evaluates membership function for egfr '''
	egfr_high = fuzz.gaussmf(egfr_values,1, 0.1)
	egfr_low = fuzz.gaussmf(egfr_values,0, 0.1)
	egfr_high1 = fuzz.trapmf(egfr_values,(0.1,0.1,0.8,1.4))
	positive_change_egfr_high = fuzz.gaussmf(positive_change_egfr,1, 0.1)
	positive_change_egfr_low = fuzz.gaussmf(positive_change_egfr, 0, 0.1)
	negative_change_egfr_high = fuzz.gaussmf(negative_change_egfr, -1, 0.1)
	negative_change_egfr_low = fuzz.gaussmf(negative_change_egfr, 0, 0.1)
	return (egfr_low, egfr_high, positive_change_egfr_low, positive_change_egfr_high, negative_change_egfr_low, negative_change_egfr_high, egfr_high1)
Beispiel #13
0
def eval_membership_function_raf(raf_values, positive_change_raf, negative_change_raf):
	'''Evaluates membership function for raf '''
	raf_high = fuzz.gaussmf(raf_values, 1, 0.1)
	raf_low = fuzz.gaussmf(raf_values, 0, 0.1)
	raf_high1 = fuzz.trapmf(raf_values,(0.1,0.1,0.8,1.4))
	positive_change_raf_high = fuzz.gaussmf(positive_change_raf, 1, 0.01)
	positive_change_raf_low = fuzz.gaussmf(positive_change_raf, 0, 0.01)
	negative_change_raf_high = fuzz.gaussmf(negative_change_raf, -1, 0.01)
	negative_change_raf_low = fuzz.gaussmf(negative_change_raf, 0, 0.01)
	return (raf_low, raf_high, positive_change_raf_low, positive_change_raf_high, negative_change_raf_low, negative_change_raf_high, raf_high1)
Beispiel #14
0
def generar_actividad(graficar=False):

    # se coloca 11 para que numpy tome efectivamente 11 espacio [0 a 10]
    intensity = np.arange(0, 11, 1)
    # Marco Actividad (Entrada)
    rest = fuzz.trapmf(intensity, [0, 0, 2, 4])
    active = fuzz.trapmf(intensity, [2, 4, 6, 8])
    workout = fuzz.trapmf(intensity, [6, 8, 10, 10])

    # if graficar:
    #     # graficar el marco
    #     fig, ax = plt.subplots()
    #     ax.plot(intensity, rest, 'b', intensity, active, 'y', intensity, workout, 'r')
    #     ax.set_ylabel('Fuzzy membership')
    #     ax.set_xlabel('Activity Intensity (1 - 10)')
    #     ax.set_ylim(-0.05, 1.05)
    #     ax.set_xlim(0.0, 10)
    #     #fig.savefig('graphs/actividad.png', bbox_inches='tight')
    #
    return {'intensity': intensity, 'rest': rest, 'active': active, 'workout': workout}
Beispiel #15
0
def generar_clase(graficar=False):

    # se usa para el marco de salida para ver que horario tendra el platillo
    clase = np.arange(0, 11, 1)

    # Marco Pertenencia (Salida)
    breakfast = fuzz.trapmf(clase, [0, 0, 2, 4])
    lunch = fuzz.trapmf(clase, [2, 4, 6, 8])
    dinner = fuzz.trapmf(clase, [6, 8, 10, 10])
    #
    # if graficar:
    #     # graficar el marco
    #     fig, ax = plt.subplots()
    #     ax.plot(clase, breakfast, 'b', clase, lunch, 'y', clase, dinner, 'r')
    #     ax.set_ylabel('Fuzzy membership')
    #     ax.set_xlabel('Dish Classification (1 - 10)')
    #     ax.set_ylim(-0.05, 1.05)
    #     ax.set_xlim(0.0, 10)
    #     #fig.savefig('graphs/clase.png', bbox_inches='tight')

    return {'clase': clase, 'breakfast': breakfast, 'lunch': lunch, 'dinner':dinner}
Beispiel #16
0
def generar_calorico(graficar=False):

    # se usa para el marco de salida para ver que horario tendra el platillo
    caloric = np.arange(0, 800, 1)

    # Marco Pertenencia (Salida)
    low = fuzz.trapmf(caloric, [0, 0, 350, 550])
    standard = fuzz.trapmf(caloric, [350, 450, 550, 650])
    high = fuzz.trapmf(caloric, [550, 650, 800, 800])

    # if graficar:
    #     # graficar el marco
    #     fig, ax = plt.subplots()
    #     ax.plot(caloric, low, 'b', caloric, standard, 'y', caloric, high, 'r')
    #     ax.set_ylabel('Fuzzy membership')
    #     ax.set_xlabel('Caloric Classification (Calories)')
    #     ax.set_ylim(-0.05, 1.05)
    #     ax.set_xlim(0, 800)
    #     #fig.savefig('graphs/calorico.png', bbox_inches='tight')

    return {'caloric': caloric, 'low': low, 'standard': standard, 'high':high}
Beispiel #17
0
def generar_hora(graficar=False):
    # debido que a el paquete de logica difusa no recibe flotantes, se expresara el
    # el tiempo como minutos (entero) 1 dia = 1440 minutos
    # no se toma el minuto 1440, que equivale a 24:00 ya incluido como hora 00:00
    horario = np.arange(0, 1440, 1)

    # Marco hora (Entrada)
    morning = fuzz.trapmf(horario, [0, 0, 480, 720])
    afternoon = fuzz.trapmf(horario, [480, 720, 960, 1200]) # trapecio
    evening = fuzz.trapmf(horario,[960, 1200, 1439, 1439])

    # if graficar:
    #     # graficar el marco
    #     fig, ax = plt.subplots()
    #     ax.plot(horario, morning, 'r', horario, afternoon, 'm', horario, evening, 'b')
    #     ax.set_ylabel('Fuzzy membership')
    #     ax.set_xlabel('Day (Minutes)')
    #     ax.set_ylim(-0.05, 1.05)
    #     ax.set_xlim(0.0, 1400)
    #     #fig.savefig('graphs/hora.png', bbox_inches='tight')
    #
    return {'horario': horario, 'morning': morning,
            'afternoon': afternoon, 'evening': evening}
Beispiel #18
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]
Beispiel #19
0
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'))
def test_defuzz():
    x = np.arange(21) - 10
    gmf = fuzz.gaussmf(x, 0, 2)

    assert_allclose(0, fuzz.defuzz(x, gmf, 'centroid'), atol=1e-9)
    assert_allclose(0, fuzz.defuzz(x, gmf, 'bisector'))
    assert_allclose(0, fuzz.defuzz(x, gmf, 'mom'))
    assert_allclose(0, fuzz.defuzz(x, gmf, 'som'))
    assert_allclose(0, fuzz.defuzz(x, gmf, 'lom'))

    # Fuzzy plateau to differentiate mom, som, lom
    trapmf = fuzz.trapmf(x, [-1, 3, 7, 8])

    assert_allclose(3, fuzz.defuzz(x, trapmf, 'som'))
    assert_allclose(5, fuzz.defuzz(x, trapmf, 'mom'))
    assert_allclose(7, fuzz.defuzz(x, trapmf, 'lom'))

    # Bad string argument
    assert_raises(ValueError, fuzz.defuzz, x, trapmf, 'bad string')
Beispiel #21
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)
Beispiel #22
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]
Beispiel #23
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 fuzzy_custom(height, growth, canopy):
    """ Perform fuzzy logic analysis on data. """
    stress_data = np.empty_like(height)

    # Create inputs/outputs to the fuzzy control system
    h_var = ctrl.Antecedent(np.linspace(-0.01, 1.01, num=100), 'height')
    g_var = ctrl.Antecedent(np.linspace(-0.01, 1.01, num=100), 'growth')
    c_var = ctrl.Antecedent(np.linspace(-0.01, 1.01, num=100), 'canopy')
    stress_var = ctrl.Consequent(np.linspace(0, 1, num=100), 'stress')

    # Create membership functions for Antecedents and Consequents
    g_var.automf(3)
    c_var.automf(3)

    h_var['poor'] = fuzz.trapmf(np.linspace(-0.01, 1.01, num=100),
                                [0, 0, 0.25, 0.5])
    h_var['average'] = fuzz.trimf(np.linspace(-0.01, 1.01, num=100),
                                  [0.25, 0.5, 0.75])
    h_var['good'] = fuzz.trapmf(np.linspace(-0.01, 1.01, num=100),
                                [0.5, 0.75, 1, 1])

    stress_var['low'] = fuzz.trapmf(np.linspace(-0.01, 1.01, num=100),
                                    [0, 0, 0.25, 0.5])
    stress_var['med'] = fuzz.trimf(np.linspace(-0.01, 1.01, num=100),
                                   [0.25, 0.5, 0.75])
    stress_var['high'] = fuzz.trapmf(np.linspace(-0.01, 1.01, num=100),
                                     [0.5, 0.75, 1, 1])

    # Create basic rule-set grouping poor performance with high stress

    # Low height rules
    #     GROWTH
    # H     L M H
    # E    ______
    # I  L| L L M
    # G  M| L L L
    # H  H| L L L
    # T
    rule_l1 = ctrl.Rule((h_var['poor'] & g_var['good'] & c_var['good']),
                        stress_var['med'])
    rule_l2 = ctrl.Rule((h_var['poor'] & g_var['poor']), stress_var['high'])
    rule_l3 = ctrl.Rule((h_var['poor'] & g_var['average']), stress_var['high'])
    rule_l4 = ctrl.Rule((h_var['poor'] & c_var['poor']), stress_var['high'])
    rule_l5 = ctrl.Rule((h_var['poor'] & c_var['average']), stress_var['high'])

    # Med height rules
    #     GROWTH
    # H     L M H
    # E    ______
    # I  L| M M H
    # G  M| M M M
    # H  H| L M M
    # T
    rule_m1 = ctrl.Rule((h_var['average'] & g_var['good'] & c_var['good']),
                        stress_var['low'])
    rule_m2 = ctrl.Rule((h_var['average'] & g_var['poor'] & c_var['poor']),
                        stress_var['high'])
    rule_m3 = ctrl.Rule((h_var['average'] & g_var['average']),
                        stress_var['med'])
    rule_m4 = ctrl.Rule((h_var['average'] & c_var['average']),
                        stress_var['med'])
    rule_m5 = ctrl.Rule((h_var['average'] & g_var['poor'] & c_var['good']),
                        stress_var['med'])
    rule_m6 = ctrl.Rule((h_var['average'] & g_var['good'] & c_var['poor']),
                        stress_var['med'])

    # High height rule
    #     GROWTH
    # H     L M H
    # E    ______
    # I  L| H H H
    # G  M| H H H
    # H  H| H H H
    # T
    rule_h1 = ctrl.Rule((h_var['good']), stress_var['low'])

    # Create the fuzzy control system with the defined rule-set
    stress_sys = ctrl.ControlSystem([
        rule_l1, rule_l2, rule_l3, rule_l4, rule_l5, rule_m1, rule_m2, rule_m3,
        rule_m4, rule_m5, rule_m6, rule_h1
    ])
    stress_sim = ctrl.ControlSystemSimulation(stress_sys)

    for i in range(height.shape[2]):

        # Split off layer from rest of data
        height_layer = height[:, :, i]
        growth_layer = growth[:, :, i]
        canopy_layer = canopy[:, :, i]

        # Normalize all of the data
        height_layer = np.divide(height_layer, np.amax(height_layer))
        growth_layer = np.divide(growth_layer, np.amax(growth_layer))
        canopy_layer = np.divide(canopy_layer, np.amax(canopy_layer))

        # Input each data map into the simulation
        stress_sim.input['height'] = height_layer
        stress_sim.input['growth'] = growth_layer
        stress_sim.input['canopy'] = canopy_layer

        # Run the simulation and extract the output
        stress_sim.compute()
        stress_layer = stress_sim.output['stress']

        # Smooth out local minimums and maximums
        stress_layer = img.grey_opening(stress_layer,
                                        structure=np.ones((3, 3)))

        stress_data[:, :, i] = stress_layer

    return stress_data
Beispiel #25
0
  def __init__(self):
    #inputs
    self.catch = ctrl.Antecedent(np.arange(57, 68, 0.1), 'Catch')
    self.catch['Novice'] = fuzz.trapmf(self.catch.universe, [0,57, 57.5, 58])
    self.catch['Intermediate'] = fuzz.gaussmf(self.catch.universe, 60.8, 1)
    self.catch['National'] = fuzz.gaussmf(self.catch.universe, 63.7, 1)
    self.catch['International'] = fuzz.trapmf(self.catch.universe, [66.1, 66.9, 68,68])

    self.finish = ctrl.Antecedent(np.arange(36, 46, 0.1), 'Finish')
    self.finish['Novice'] = fuzz.trapmf(self.finish.universe, [0,36,37.2,38])
    self.finish['Intermediate'] = fuzz.gaussmf(self.finish.universe, 39.9, 0.8)
    self.finish['National'] = fuzz.gaussmf(self.finish.universe, 42.2, 0.8)
    self.finish['International'] = fuzz.trapmf(self.finish.universe, [43.6, 45.4, 46, 46])

    self.slip = ctrl.Antecedent(np.arange(2, 10, 0.1), 'Slip')
    self.slip['Novice'] = fuzz.trapmf(self.slip.universe, [7.7, 8.8, 10, 10])
    self.slip['Intermediate'] = fuzz.gaussmf(self.slip.universe, 6.7, 0.6)
    self.slip['National'] = fuzz.gaussmf(self.slip.universe, 5.2, 0.6)
    self.slip['International'] = fuzz.trapmf(self.slip.universe, [2, 2, 3.5, 3.9])

    self.wash = ctrl.Antecedent(np.arange(9, 30, 0.1), 'Wash')
    self.wash['Novice'] = fuzz.trapmf(self.wash.universe, [25.4, 28.1,30,30])
    self.wash['Intermediate'] = fuzz.gaussmf(self.wash.universe, 23.5, 1.2)
    self.wash['National'] = fuzz.gaussmf(self.wash.universe, 20.2, 1.2)
    self.wash['International'] = fuzz.trapmf(self.wash.universe, [9,9, 15.5, 18.3])
    
    self.length = ctrl.Antecedent(np.arange(95, 115, 0.1), 'Length')
    self.length['Novice'] = fuzz.trapmf(self.length.universe, [95,95, 97.1, 98.4])
    self.length['Intermediate'] = fuzz.gaussmf(self.length.universe, 101.4, 1.4)
    self.length['National'] = fuzz.gaussmf(self.length.universe, 105.2, 1.4)
    self.length['International'] = fuzz.trapmf(self.length.universe, [107.7, 110, 115,115])

    #output 
    self.quality = ctrl.Consequent(np.arange(0, 101, 0.1), 'Quality')
    #setting membership functions
    self.quality['Novice'] = fuzz.gaussmf(self.quality.universe, 0, 10)
    self.quality['Intermediate'] = fuzz.gaussmf(self.quality.universe, 40, 8)
    self.quality['National'] = fuzz.gaussmf(self.quality.universe, 60, 8)
    self.quality['International'] = fuzz.gaussmf(self.quality.universe, 100, 10)

    #catch 
    rule1 = ctrl.Rule(self.catch['Novice'], self.quality['Novice'])
    rule2 = ctrl.Rule(self.catch['Intermediate'], self.quality['Intermediate'])
    rule3 = ctrl.Rule(self.catch['National'], self.quality['National'])
    rule4 = ctrl.Rule(self.catch['International'], self.quality['International'])
    #finish
    rule5 = ctrl.Rule(self.finish['Novice'], self.quality['Novice'])
    rule6 = ctrl.Rule(self.finish['Intermediate'], self.quality['Intermediate'])
    rule7 = ctrl.Rule(self.finish['National'], self.quality['National'])
    rule8 = ctrl.Rule(self.finish['International'], self.quality['International'])
    #slip
    rule9  = ctrl.Rule(self.slip['Novice'], self.quality['Novice'])
    rule10 = ctrl.Rule(self.slip['Intermediate'], self.quality['Intermediate'])
    rule11 = ctrl.Rule(self.slip['National'], self.quality['National'])
    rule12 = ctrl.Rule(self.slip['International'], self.quality['International'])
    #wash
    rule13 = ctrl.Rule(self.wash['Novice'], self.quality['Novice'])
    rule14 = ctrl.Rule(self.wash['Intermediate'], self.quality['Intermediate'])
    rule15 = ctrl.Rule(self.wash['National'], self.quality['National'])
    rule16 = ctrl.Rule(self.wash['International'], self.quality['International'])
    #length
    rule17 = ctrl.Rule(self.length['Novice'], self.quality['Novice'])
    rule18 = ctrl.Rule(self.length['Intermediate'], self.quality['Intermediate'])
    rule19 = ctrl.Rule(self.length['National'], self.quality['National'])
    rule20 = ctrl.Rule(self.length['International'], self.quality['International'])

    rowingFIS_ctrl = ctrl.ControlSystem([
      rule1, rule2, rule3, rule4, #catch
      rule5, rule6, rule7, rule8,#finish
      rule9, rule10, rule11, rule12,#slip
      rule13, rule14, rule15, rule16,#wash
      rule17, rule18, rule19, rule20#length
    ])

    self.rowingFis = ctrl.ControlSystemSimulation(rowingFIS_ctrl)
Beispiel #26
0
def evaluate(x,
             X,
             y,
             X_test,
             y_test,
             rated,
             mfs,
             rules,
             p,
             resampling,
             num_samples=200,
             n_ratio=0.6):

    # print(solution.variables)
    i = 0
    for var in sorted(mfs.keys()):
        for mf in range(len(mfs[var])):
            if mfs[var][mf]['type'] == 'gauss':
                mfs[var][mf]['param'] = x[i:i + 2]
                mfs[var][mf]['func'] = fuzz.gaussmf(
                    mfs[var][mf]['universe'], mfs[var][mf]['param'][0],
                    np.abs(mfs[var][mf]['param'][1]))
                i += 2
            elif mfs[var][mf]['type'] == 'trap':
                mfs[var][mf]['param'] = sorted(x[i:i + 4])
                mfs[var][mf]['func'] = fuzz.trapmf(mfs[var][mf]['universe'],
                                                   mfs[var][mf]['param'])
                i += 4

    for r in sorted(rules.keys()):
        for i in range(len(rules[r])):
            ind = int(re.sub("\D", "", rules[r][i]['name']))
            rules[r][i]['param'] = mfs[rules[r][i]['var_name']][ind]['param']
            rules[r][i]['func'] = mfs[rules[r][i]['var_name']][ind]['func']

    activations = pd.DataFrame(
        index=X.index, columns=['rule.' + str(i) for i in range(len(rules))])
    for rule in sorted(rules.keys()):
        act = []
        for mf in rules[rule]:
            act.append(
                fuzz.interp_membership(mf['universe'], mf['func'],
                                       X[mf['var_name']]))
        activations[rule] = np.power(np.prod(np.array(act), axis=0), 1 / p)

    lin_models = dict()
    for rule in activations.columns:
        indices = activations[rule].index[activations[rule] >= 0.01].tolist()
        if len(indices) > num_samples and len(indices) < n_ratio * X.shape[0]:
            X1 = X.loc[indices].values
            y1 = y.loc[indices].values
            # if resampling:
            #     if X1.shape[0] < 300:
            #         X1, y1 = resampling_fun(X1,y1)
            lin_models[rule] = LinearRegression().fit(X1, y1.ravel())
        elif len(indices) > 0:
            lin_models[rule] = 'null'
        else:
            lin_models[rule] = None
    for rule in sorted(rules.keys()):
        indices = activations[rule].index[activations[rule] >= 0.01].tolist()
        if len(indices) <= num_samples and len(indices) < n_ratio * X.shape[
                0] and len(indices) < n_ratio * X.shape[0]:
            del rules[rule]
            del lin_models[rule]
    activations_test = pd.DataFrame(
        index=X_test.index,
        columns=['rule.' + str(i) for i in sorted(rules.keys())])
    for rule in sorted(rules.keys()):
        act = []
        for mf in rules[rule]:
            act.append(
                fuzz.interp_membership(mf['universe'], mf['func'],
                                       X_test[mf['var_name']]))
        activations_test[rule] = np.power(np.prod(np.array(act), axis=0),
                                          1 / p)

    preds = pd.DataFrame(index=X_test.index, columns=sorted(rules.keys()))
    for rule in sorted(rules.keys()):
        indices = activations_test[rule].index[
            activations_test[rule] >= 0.01].tolist()
        if len(indices) != 0:
            X1 = X_test.loc[indices].values
            if (lin_models[rule] != 'null' and not lin_models[rule] is None):
                preds.loc[indices, rule] = lin_models[rule].predict(X1).ravel()
            elif lin_models[rule] == 'null':
                preds.loc[indices, rule] = 1e+15
    pred = preds.mean(axis=1)
    pred[pred.isnull()] = 1e+15
    # pred.name='target'
    # pred=pred.to_frame()
    err = (pred.values.ravel() - y_test.values.ravel()) / rated

    objectives = [np.sum(np.square(err)), np.mean(np.abs(err))]
    return objectives
Beispiel #27
0
def buildFuzzySystem(showDescription=False):
    """ 
    ===========================================================================
    Build Fuzzy Sistem for variable: cnxs: network connections  
    ===========================================================================   
    
    **Args**:
        showDescription: (boolean)
    **Returns**:
        None
    """
    #==========================================================================
    # Set labels of inputs and outputs
    #==========================================================================

    in1_max = 10000

    var_in1_label = 'net_io_rate_in'
    var_out_label = 'out'

    logger.info("buildFuzzySystem:" + var_in1_label)

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

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

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

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

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

    var_in1.automf(number=3, variable_type='quant')
    var_in1['low'] = fuzz.trimf(var_in1.universe, [0, 0, in1_max * 0.1])
    var_in1['average'] = fuzz.trapmf(
        var_in1.universe, [0, 0.1 * in1_max, 0.3 * in1_max, 0.5 * in1_max])
    var_in1['high'] = fuzz.smf(var_in1.universe, 0.3 * in1_max, 0.5 * in1_max)

    var_out.automf(number=3, variable_type='quant')

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

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

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

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

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

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

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

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

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

    return var_fuzzysim
Beispiel #28
0

# In[3]:




x_korban = np.arange(0, 55,1)
x_infrastruktur = np.arange(0, 55,1)
x_tim = np.arange(0, 25, 1)


# In[ ]:


korban_minor = fuzz.trapmf(x_korban, [0,0,5,20])
korban_masif = fuzz.trapmf(x_korban, [10,40,60,60])

infrastruktur_minor = fuzz.trapmf(x_infrastruktur, [0,0,5,20])
infrastruktur_masif = fuzz.trapmf(x_infrastruktur, [15,45,60,60])

tim_sedikit = fuzz.trapmf(x_tim, [0,0,5,15])
tim_banyak =  fuzz.trapmf(x_tim, [10,20,30,30])


# In[14]:


angka = []
for x in sys.argv[1] :
    x = sys.argv[1].split(",")
Beispiel #29
0
matplotlib.use("TkAgg")
import matplotlib.pyplot as plot

# Variáveis do Problema
velocidade = ctrl.Antecedent(np.arange(0, 101, 1), "velocidade")
limite = ctrl.Antecedent(np.arange(0, 101, 1), "limite")
multa = ctrl.Consequent(np.arange(0, 1001, 1), "multa")

velocidade.automf(names=["baixa", "media", "alta"])

# Cria funções de pertinência usando tipos variados
limite["baixo"] = fuzz.trimf(limite.universe, [0, 0, 50])
limite["medio"] = fuzz.gaussmf(limite.universe, 50, 5)
limite["alto"] = fuzz.gaussmf(limite.universe, 100, 20)

multa["baixa"] = fuzz.trapmf(multa.universe, [0, 0, 200, 500])
multa["media"] = fuzz.trimf(multa.universe, [300, 500, 700])
multa["alta"] = fuzz.trimf(multa.universe, [500, 1000, 1000])

# Regras de decisões
rule1 = ctrl.Rule(limite["baixo"] & velocidade["alta"], multa["alta"])
rule2 = ctrl.Rule(limite["medio"] & velocidade["alta"], multa["media"])
rule3 = ctrl.Rule(limite["alto"] & velocidade["alta"], multa["baixa"])
rule4 = ctrl.Rule(limite["baixo"] & velocidade["media"], multa["media"])
rule5 = ctrl.Rule(limite["medio"] & velocidade["media"], multa["baixa"])
rule6 = ctrl.Rule(limite["baixo"] & velocidade["baixa"], multa["baixa"])
rule7 = ctrl.Rule(limite["baixo"] & velocidade["media"], multa["media"])
rule8 = ctrl.Rule(limite["baixo"] & velocidade["alta"], multa["alta"])


class Aplicacao:
Beispiel #30
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt
import time

# Antecedents objects
distancesAntecedents = []
for i in range(8):
    distancesAntecedents.append(
        ctrl.Antecedent(np.arange(0, 5, 0.01), 'distance_' + str(i)))
vel_left = ctrl.Consequent(np.arange(-5, 5, 0.1), 'vel_left')
vel_right = ctrl.Consequent(np.arange(-5, 5, 0.1), 'vel_right')

for i in range(8):
    distancesAntecedents[i]["perto"] = fuzz.trapmf(
        distancesAntecedents[i].universe, [0, 0, 0.8, 2.5])
    distancesAntecedents[i]["longe"] = fuzz.trapmf(
        distancesAntecedents[i].universe, [0.8, 2.5, 6, 6])

vel_left['pos_fast'] = fuzz.trimf(vel_left.universe, [1, 5, 5])
vel_left['pos_slow'] = fuzz.trimf(vel_left.universe, [0, 1.5, 1.5])
vel_left['neg_fast'] = fuzz.trimf(vel_left.universe, [-5, -5, -1])
vel_left['neg_slow'] = fuzz.trimf(vel_left.universe, [-1.5, -1.5, 0])
vel_right['pos_fast'] = fuzz.trimf(vel_left.universe, [1, 4.8, 4.8])
vel_right['pos_slow'] = fuzz.trimf(vel_left.universe, [0, 1.3, 1.3])
vel_right['neg_fast'] = fuzz.trimf(vel_left.universe, [-5, -5, -1])
vel_right['neg_slow'] = fuzz.trimf(vel_left.universe, [-1.5, -1.5, 0])

rule1 = ctrl.Rule(
    distancesAntecedents[3]['perto'] | distancesAntecedents[4]['perto'],
    vel_left['pos_fast'])
parser.add_argument("--output_csv",
                    default='./output_part1.csv',
                    type=str,
                    help='Input csv file path')
args = parser.parse_args()

# Define universe
price = np.arange(0, 31, 1)
distance = np.arange(0, 21, 1)
rating = np.arange(0, 6, 1)
going = 1
not_going = 0
label = np.arange(0, 1.01, 0.01)

# Define membership function
cheap = fuzz.trapmf(price, [0, 0, 7, 10])
medium_price = fuzz.trimf(price, [7, 12, 18])
expensive = fuzz.trapmf(price, [14, 25, 30, 30])

close = fuzz.trapmf(distance, [0, 0, 5, 7])
medium_distance = fuzz.trimf(distance, [5, 10, 15])
far = fuzz.trapmf(distance, [10, 15, 20, 20])

bad = fuzz.trapmf(rating, [0, 0, 2, 3])
moderate = fuzz.trimf(rating, [2, 3, 4])
good = fuzz.trapmf(rating, [3, 4, 5, 5])

not_go = fuzz.trimf(label, [0, 0, 1.0])
will_go = fuzz.trimf(label, [0, 1.0, 1.0])

# Plot MF graph
Beispiel #32
0
def funcionGrande(tamanio):
	grande = fuzz.trapmf(tamanio.universe,[250,350,450,450])
	return grande
Beispiel #33
0
def funcionMediano(tamanio):
	mediano = fuzz.trapmf(tamanio.universe,[90,200,250,350])
	return mediano
Beispiel #34
0
def funcionPequenio(tamanio):
	pequenio = fuzz.trapmf(tamanio.universe,[0,0,90,200])
	return pequenio
import skfuzzy as fuzz
import matplotlib.pyplot as plt

# input variables
input_participants = 120
input_available_slots = 15
input_test_difficulty = 5

# create universes
participants = np.arange(50, 201, 1)
available_slots = np.arange(0, 21, 1)
test_difficulty = np.arange(0, 11, 1)
acceptance_probability = np.arange(0, 101, 1)

# create membership functions
participants_low = fuzz.trapmf(participants, [50, 50, 75, 110])
participants_medium = fuzz.trimf(participants, [90, 120, 150])
participants_high = fuzz.trapmf(participants, [130, 160, 200, 200])

available_slots_low = fuzz.trapmf(available_slots, [0, 0, 2, 8])
available_slots_medium = fuzz.trapmf(available_slots, [4, 8, 12, 16])
available_slots_high = fuzz.trapmf(available_slots, [13, 17, 20, 20])

test_difficulty_low = fuzz.trapmf(test_difficulty, [0, 0, 3, 5])
test_difficulty_medium = fuzz.trimf(test_difficulty, [4, 6, 8])
test_difficulty_high = fuzz.trapmf(test_difficulty, [7, 9, 10, 10])

acceptance_probability_low = fuzz.trimf(acceptance_probability, [0, 0, 50])
acceptance_probability_medium = fuzz.trimf(acceptance_probability, [10, 50, 90])
acceptance_probability_high = fuzz.trimf(acceptance_probability, [50, 100, 100])
def build_fuzzy_variables():
    # Sparse universe makes calculations faster, without sacrifice accuracy.
    # Only the critical points are included here; making it higher resolution is
    # unnecessary.
    universe_theta = np.array([-0.15, -0.1, -0.05, 0, 0.05, 0.1])
    universe_vtheta= np.array([-0.125, -0.075, -0.025, 0.025, 0.075, 0.125]) 
    universe_phi   = np.array([-0.2, -0.1, -0.05, 0.05, 0.1, 0.2])
    universe_vphi  = np.array([-0.125, -0.075, -0.025, 0.025, 0.075, 0.125])
    universe_output= np.arange(-1, 1.1, 1/6)
    # Create the three fuzzy variables - four inputs, one output
    theta = ctrl.Antecedent(universe_theta , 'theta')
    vtheta= ctrl.Antecedent(universe_vtheta, 'vtheta')
    phi   = ctrl.Antecedent(universe_phi   , 'phi')
    vphi  = ctrl.Antecedent(universe_vphi  , 'vphi')
    output= ctrl.Consequent(universe_output, 'output')
    
    # Set membership function
    # fuzz.trapmf(support_x,[0,0,20,30])
    sup = theta.universe
    theta['low']    = fuzz.trapmf(theta.universe, [sup[0], sup[0], sup[1], sup[2]])
    theta['normal'] = fuzz.trapmf(theta.universe, [sup[1], sup[2], sup[3], sup[4]])
    theta['high']   = fuzz.trapmf(theta.universe, [sup[3], sup[4], sup[5], sup[5]])
    
    sup = vtheta.universe
    vtheta['falling'] = fuzz.trapmf(vtheta.universe, [sup[0], sup[0], sup[1], sup[2]])
    vtheta['stable']  = fuzz.trapmf(vtheta.universe, [sup[1], sup[2], sup[3], sup[4]])
    vtheta['rising']  = fuzz.trapmf(vtheta.universe, [sup[3], sup[4], sup[5], sup[5]])
    
    sup = phi.universe
    phi['left']   = fuzz.trapmf(phi.universe, [sup[0], sup[0], sup[1], sup[2]])
    phi['center'] = fuzz.trapmf(phi.universe, [sup[1], sup[2], sup[3], sup[4]])
    phi['right']  = fuzz.trapmf(phi.universe, [sup[3], sup[4], sup[5], sup[5]])
    
    sup = vphi.universe
    vphi['goleft']  = fuzz.trapmf(vphi.universe, [sup[0], sup[0], sup[1], sup[2]])
    vphi['stable']  = fuzz.trapmf(vphi.universe, [sup[1], sup[2], sup[3], sup[4]])
    vphi['goright'] = fuzz.trapmf(vphi.universe, [sup[3], sup[4], sup[5], sup[5]])

    output.automf(names=['lefthard','left','leftslow','hold','rightslow','right','righthard'])
    return theta, vtheta, phi, vphi, output
Beispiel #37
0
  
Fuzzy logic calculations are excellent tools, but to use them the fuzzy result
must be converted back into a single number. This is known as defuzzification.
  
There are several possible methods for defuzzification, exposed via
`skfuzzy.defuzz`.
  
"""
import numpy as np
import matplotlib.pyplot as plt
import skfuzzy as fuzz
  
  
# Generate trapezoidal membership function on range [0, 1]
x = np.arange(0, 5.05, 0.1)
mfx = fuzz.trapmf(x, [2, 2.5, 3, 4.5])
  
# Defuzzify this membership function five ways
defuzz_centroid = fuzz.defuzz(x, mfx, 'centroid')  # Same as skfuzzy.centroid
defuzz_bisector = fuzz.defuzz(x, mfx, 'bisector')
defuzz_mom = fuzz.defuzz(x, mfx, 'mom')
defuzz_som = fuzz.defuzz(x, mfx, 'som')
defuzz_lom = fuzz.defuzz(x, mfx, 'lom')
  
# Collect info for vertical lines
labels = ['centroid', 'bisector', 'mean of maximum', 'min of maximum',
          'max of maximum']
xvals = [defuzz_centroid,
         defuzz_bisector,
         defuzz_mom,
         defuzz_som,
Beispiel #38
0
import Node611
import excel
import mcpras
import time

#Fuzzy Controller

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

#Membership functions

#Pdif

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

#Vdif

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

#Vref

Vrefd['N'] = fuzz.trimf(Vrefd.universe, [-0.3, -0.2, -0.1])
Vrefd['P'] = fuzz.trimf(Vrefd.universe, [0.1, 0.2, 0.3])
Vrefd['Z'] = fuzz.trimf(Vrefd.universe, [-0.01, 0, 0.01])
Beispiel #39
0
    def init_fuzzy_logic(self):
        xa = ctrl.Antecedent(np.arange(-0.5, 9, 0.01), 'xa')
        ya = ctrl.Antecedent(np.arange(-0.3, 9, 0.01), 'ya')
        angle = ctrl.Antecedent(np.arange(-44.6, 121, 0.01), 'angle')
        steering = ctrl.Consequent(np.arange(-35, 37.38, 0.01), 'steering')

        # Custom membership functions
        xa['S'] = fuzz.trimf(xa.universe, [-0.23, 0.20, 0.57])
        xa['B'] = fuzz.trimf(xa.universe, [0.4, 0.7, 1])
        xa['P'] = fuzz.trimf(xa.universe, [0.93, 1.47, 1.92])
        xa['PB'] = fuzz.trapmf(xa.universe, [1.74, 2.14, 9, 9])
        # xa.view()
        # plt.show()
        ya['S'] = fuzz.trimf(ya.universe, [-0.3, 0.4, 1.21])
        ya['B'] = fuzz.trimf(ya.universe, [0.94, 1.65, 2.24])
        ya['PM'] = fuzz.trimf(ya.universe, [2.18, 2.52, 2.75])
        ya['PB'] = fuzz.trapmf(ya.universe, [2.75, 3.23, 9, 9])
        # ya.view()
        # plt.show()
        angle['N'] = fuzz.trapmf(angle.universe, [-44.6, -27.6, -17.6, -2.3])
        angle['Z'] = fuzz.trimf(angle.universe, [-4.46, 0, 2.03])
        angle['P'] = fuzz.trapmf(angle.universe, [0.11, 7.37, 56.3, 91])
        angle['PM'] = fuzz.trimf(angle.universe, [88, 90, 93.2])
        angle['PB'] = fuzz.trapmf(angle.universe, [92.45, 97, 120, 120])
        # angle.view()
        # plt.show()
        steering['NB'] = fuzz.trimf(steering.universe, [-35, -32.14, -29.15])
        steering['NM'] = fuzz.trimf(steering.universe,
                                    [-29.77, -20.43, -11.09])
        steering['N'] = fuzz.trimf(steering.universe, [-20.43, -11.71, -2.87])
        steering['Z'] = fuzz.trimf(steering.universe, [-3.85, 0, 4.12])
        steering['P'] = fuzz.trimf(steering.universe, [2.87, 11.71, 20.43])
        steering['PM'] = fuzz.trimf(steering.universe, [4.98, 14.95, 24.91])
        steering['PB'] = fuzz.trapmf(steering.universe,
                                     [23.67, 26.16, 37.37, 37.37])
        # steering.view()
        # plt.show()

        # When xa is S
        rule1 = ctrl.Rule(xa['S'] & ya['S'] & angle['P'], steering['NB'])
        rule2 = ctrl.Rule(xa['S'] & ya['B'] & angle['P'], steering['NB'])
        rule21 = ctrl.Rule(xa['S'] & ya['B'] & angle['PM'], steering['Z'])
        rule22 = ctrl.Rule(xa['S'] & ya['B'] & angle['PB'], steering['P'])
        rule3 = ctrl.Rule(xa['S'] & ya['S'] & angle['PM'], steering['Z'])

        # When xa is B
        rule4 = ctrl.Rule(xa['B'] & ya['B'] & angle['P'], steering['NB'])
        rule41 = ctrl.Rule(xa['B'] & ya['S'] & angle['PM'], steering['Z'])
        rule42 = ctrl.Rule(xa['B'] & ya['B'] & angle['PM'], steering['Z'])

        # When xa is P
        rule5 = ctrl.Rule(xa['P'] & ya['B'] & angle['Z'], steering['NM'])
        rule6 = ctrl.Rule(xa['P'] & ya['B'] & angle['P'], steering['NM'])

        # When xa is PB
        rule7 = ctrl.Rule(xa['PB'] & ya['B'] & angle['N'], steering['NB'])
        rule8 = ctrl.Rule(xa['PB'] & ya['B'] & angle['Z'], steering['Z'])
        rule9 = ctrl.Rule(xa['PB'] & ya['B'] & angle['P'], steering['PB'])
        # rule1.view()
        # plt.show()
        steering_ctrl = ctrl.ControlSystem([
            rule1, rule2, rule21, rule3, rule4, rule41, rule42, rule5, rule6,
            rule7, rule8, rule9
        ])
        return ctrl.ControlSystemSimulation(steering_ctrl)
 def __init__(self, abcd):
     self.x_points = np.arange(abcd[0], abcd[3]+1,1)
     self.fct = fuzz.trapmf(self.x_points, abcd)
# Delta para aumento do espaço de entrada
Dc = .00001
Dl = .00001
# Definindo espaço de entrada
comprimento = ctrl.Antecedent(np.arange(minc - Dc, maxc + Dc, .00001),
                              'comprimento')
largura = ctrl.Antecedent(np.arange(minl - Dl, maxl + Dl, .00001), 'largura')
# Denifinindo espaço de saída
# especie = ctrl.Consequent(np.arange(0, 2.01, 0.01),'especie')
especie = ctrl.Consequent(np.arange(0, 3.01, 0.01), 'especie')

# Definindo conjuntos

# Comprimento Baixo(CB), Médio(CM) e Alto(CA)
comprimento['CB'] = fuzz.trapmf(comprimento.universe,
                                [minc, minc, mediaCe1, mediaCe2])
comprimento['CM'] = fuzz.trimf(comprimento.universe,
                               [mediaCe1, mediaCe2, mediaCe3])
comprimento['CA'] = fuzz.trapmf(comprimento.universe,
                                [mediaCe2, mediaCe3, maxc, maxc])

# Largura Baixa(LB), Média(LM) e Alta(LA)
largura['LB'] = fuzz.trapmf(largura.universe, [minl, minl, mediaLe1, mediaLe2])
largura['LM'] = fuzz.trimf(largura.universe, [mediaLe1, mediaLe2, mediaLe3])
largura['LA'] = fuzz.trapmf(largura.universe, [mediaLe2, mediaLe3, maxl, maxl])

# Definindo saída como Espécie 1 (E1), 2 (E2) e 3 (E3)

especie['E1'] = fuzz.trimf(especie.universe, [0, 0, 1])
especie['E2'] = fuzz.trimf(especie.universe, [1, 1.5, 2])
especie['E3'] = fuzz.trimf(especie.universe, [2, 3, 3])
    sensor_mp = [0, 0, 0, 20]
    sensor_p = [0, 20, 90, 100]
    sensor_l = [100, 150, 200, 300]
    sensor_ml = [200, 300, 500, 500]

    # Actuators trampf points
    actuator_l = [0, 0, 0, 50]
    actuator_m = [50, 70, 110, 130]
    actuator_r = [100, 150, 200, 200]
    '''
    f_s2['mp'] = fuzz.trapmf(f_s2.universe, sensor_mp)
    f_s2['p'] = fuzz.trapmf(f_s2.universe, sensor_p)
    f_s2['l'] = fuzz.trapmf(f_s2.universe, sensor_l)
    f_s2['ml'] = fuzz.trapmf(f_s2.universe, sensor_ml)
    '''
    f_s4['mp'] = fuzz.trapmf(f_s4.universe, sensor_mp)
    f_s4['p'] = fuzz.trapmf(f_s4.universe, sensor_p)
    f_s4['l'] = fuzz.trapmf(f_s4.universe, sensor_l)
    f_s4['ml'] = fuzz.trapmf(f_s4.universe, sensor_ml)
    '''
    f_s5['mp'] = fuzz.trapmf(f_s5.universe, sensor_mp)
    f_s5['p'] = fuzz.trapmf(f_s5.universe, sensor_p)
    f_s5['l'] = fuzz.trapmf(f_s5.universe, sensor_l)
    f_s5['ml'] = fuzz.trapmf(f_s5.universe, sensor_ml)

    f_s7['mp'] = fuzz.trapmf(f_s7.universe, sensor_mp)
    f_s7['p'] = fuzz.trapmf(f_s7.universe, sensor_p)
    f_s7['l'] = fuzz.trapmf(f_s7.universe, sensor_l)
    f_s7['ml'] = fuzz.trapmf(f_s7.universe, sensor_ml)

    f_s10['mp'] = fuzz.trapmf(f_s10.universe, sensor_mp)
Beispiel #43
0
    
    #calculate overlap
    overlap = 100.*float(min(max(outRange), max(alt[7])) - max(min(outRange), min(alt[7])))/ \
              max( max(outRange)-min(outRange) , max(alt[7])-min(alt[7]) )
    print alt[0], overlap, '% overlap'
    
    ax1.bar(outRange[0], 0.3, width=outRange[1]-outRange[0], bottom=ps_inputs.index(alt)+0.7, color='r')
    ax1.bar(alt[7][0],   0.3, width=alt[7][1]-alt[7][0],     bottom=ps_inputs.index(alt)+1.0, color='b')
    ax1.text(max(max(outRange),max(alt[7]))+0.5, ps_inputs.index(alt)+0.9, str(round(overlap,1))+'%',
             fontsize=10)
    
    #plot actual outputs
    i = ps_inputs.index(alt)
    ax2[(i-(i%2))/2, i%2].plot(output[0], output[1], '-r')
    exp_x = np.arange(0.9*min(alt[7]), 1.1*max(alt[7]), (max(alt[7])-min(alt[7]))/50.)
    exp_y = fuzz.trapmf(exp_x, [min(alt[7]), min(alt[7]), max(alt[7]), max(alt[7])]) 
    ax2[(i-(i%2))/2, i%2].plot(exp_x, exp_y, '-b')


ax1.set_ylim([0,11])
ax1.set_xlim([5,25])
ax1.yaxis.grid(True)
ax1.set_yticks(range(1,11))
ax1.set_yticklabels([alt[0] for alt in ps_inputs])
ax1.set_xlabel('System L/D')

fontP = FontProperties()
fontP.set_size('medium')
ax1.legend(['Fuzzy System Output', 'Expert System Evaluations'], bbox_to_anchor=(1.0, 1.06), prop=fontP)

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

# 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
Beispiel #45
0
 def create_mfs(self, model_mfs, type_mf, num_mf, var_range, var_name):
     mfs = []
     if type_mf in {
             'hdd_h2', 'temp_max', 'flux', 'wind', 'temp', 'Temp', 'load',
             'power'
     }:
         mean = np.linspace(var_range[0], var_range[1], num=num_mf)
         std = var_range[1] / num_mf
         for i in range(num_mf):
             mfs.append({
                 'name':
                 'mf_' + type_mf + str(i),
                 'var_name':
                 var_name,
                 'type':
                 'gauss',
                 'param': [mean[i], 1.25 * std],
                 'universe':
                 np.arange(var_range[0] - std - .01,
                           var_range[1] + std + .01, .001),
                 'func':
                 fuzz.gaussmf(
                     np.arange(var_range[0] - std - .01,
                               var_range[1] + std + .01, .001), mean[i],
                     std)
             })
     elif type_mf in {
             'sp_index', 'dayweek', 'cloud', 'hour', 'month', 'direction',
             'sp_days'
     }:
         mean = np.linspace(var_range[0], var_range[1], num=num_mf)
         std = var_range[1] / num_mf
         std1 = var_range[1] / (2 * num_mf)
         for i in range(num_mf):
             param = [
                 mean[i] - 1.5 * std, mean[i] - 1.25 * std1,
                 mean[i] + 1.25 * std1, mean[i] + 1.5 * std
             ]
             mfs.append({
                 'name':
                 'mf_' + type_mf + str(i),
                 'var_name':
                 var_name,
                 'type':
                 'trap',
                 'param':
                 param,
                 'universe':
                 np.arange(var_range[0] - .01 - std,
                           var_range[1] + std + .01, .001),
                 'func':
                 fuzz.trapmf(
                     np.arange(
                         var_range[0] - .01 - std,
                         var_range[1] + std + .01,
                         .001,
                     ), param)
             })
     else:
         raise NameError('MF type not recognize')
     model_mfs[var_name] = mfs
     return model_mfs
Beispiel #46
0
            for i in range(len(y)):
                if i <= maxX: y2.append(maxY) #extend function towards min (left)
                else:         y2.append(y[i])
        if direction is 'min':
            minX = min([i for i in range(len(yMs)) if yMs[i] == 1])
            y2 = []
            for i in range(len(y)):
                if i >= minX: y2.append(maxY) #extend function towards max (right)
                else:         y2.append(y[i])
                
        if plot:
            ax.plot(x,y2, '--c')
            ax.plot([goal, goal], [0.,1.], ':k')
            ax.set_ylim([0.0,1.01])
            plt.show()
    
        d = fuzz.interp_membership(x,y2,goal)
        return d
    except:
        e = sys.exc_info()[0]
        print "Error calculating fuzzy POS:", e
        return 0.0

################################################################################
if __name__=="__main__":
    Ax = np.arange(1,9,0.1)
    Ay = fuzz.trapmf(Ax, [4,5,6,7])
    POS = fuzzyPOS(Ax,Ay,4.5,direction='min', plot=True)
    print "POSmin:", POS
    POS = fuzzyPOS(Ax,Ay,6.5, plot=True)
    print "POSmax:", POS
Beispiel #47
0
def cantidadesAguaLecheChocolateCafeTiempo():
    agua = ctrl.Consequent(
        [0, 30, 60, 90, 120, 150, 200, 250, 300, 350, 400, 450],
        'agua')  #consecuente agua
    agua['poca'] = fuzz.trapmf(agua.universe, [0, 0, 90, 200])
    agua['media'] = fuzz.trapmf(agua.universe, [90, 200, 250, 350])
    agua['mucha'] = fuzz.trapmf(agua.universe, [250, 350, 450, 450])
    cafe = ctrl.Consequent(np.arange(0, 30, 1), 'cafe')  #consecuente cafe
    cafe['poca'] = fuzz.trapmf(cafe.universe, [0, 0, 7, 15])
    cafe['media'] = fuzz.trimf(cafe.universe, [10, 15, 20])
    cafe['mucha'] = fuzz.trapmf(cafe.universe, [15, 22, 30, 30])
    leche = ctrl.Consequent(np.arange(0, 50, 1), 'leche')  #consecuente leche
    leche['poca'] = fuzz.trapmf(leche.universe, [0, 0, 13, 25])
    leche['media'] = fuzz.trimf(leche.universe, [13, 25, 38])
    leche['mucha'] = fuzz.trapmf(leche.universe, [25, 38, 50, 50])
    chocolate = ctrl.Consequent(np.arange(0, 80, 1),
                                'chocolate')  #consecuente chocolate
    chocolate['poca'] = fuzz.trapmf(chocolate.universe, [0, 0, 20, 40])
    chocolate['media'] = fuzz.trimf(chocolate.universe, [20, 40, 60])
    chocolate['mucha'] = fuzz.trapmf(chocolate.universe, [40, 60, 80, 80])
    tiempo = ctrl.Consequent(np.arange(0, 34, 1),
                             'tiempo')  #consecuente tiempo
    tiempo['poca'] = fuzz.trapmf(tiempo.universe, [0, 0, 8, 17])
    tiempo['media'] = fuzz.trimf(tiempo.universe, [8, 17, 25])
    tiempo['mucha'] = fuzz.trapmf(tiempo.universe, [17, 25, 34, 34])
    #se grafican todos los consecuentes
    graficar.graficarGrid(
        agua.universe, cafe.universe, leche.universe, chocolate.universe,
        tiempo.universe, [agua['poca'].mf, agua['media'].mf, agua['mucha'].mf],
        [cafe["poca"].mf, cafe["media"].mf, cafe["mucha"].mf],
        [leche["poca"].mf, leche["media"].mf, leche["mucha"].mf],
        [chocolate["poca"].mf, chocolate["media"].mf, chocolate["mucha"].mf],
        [tiempo["poca"].mf, tiempo["media"].mf, tiempo["mucha"].mf],
        ["Poca", "Media", "Mucha"], [
            "Agua [ml]", "Cafe [grs]", "Leche [grs]", "Chocolate [grs]",
            "Tiempo [s]"
        ], ["Pertenencia", "Pertenencia", "Pertenencia", "Pertenencia"],
        "Cantidades vs Pertenencia")
    return agua, cafe, leche, chocolate, tiempo
Beispiel #48
0
    def evaluate(self, x, X, y, X_test, y_test, rated, mfs, rules, p,
                 resampling):

        # print(solution.variables)
        i = 0
        for var in sorted(mfs.keys()):
            for mf in range(len(mfs[var])):
                if mfs[var][mf]['type'] == 'gauss':
                    mfs[var][mf]['param'] = x[i:i + 2]
                    mfs[var][mf]['func'] = fuzz.gaussmf(
                        mfs[var][mf]['universe'], mfs[var][mf]['param'][0],
                        np.abs(mfs[var][mf]['param'][1]))
                    i += 2
                elif mfs[var][mf]['type'] == 'trap':
                    mfs[var][mf]['param'] = sorted(x[i:i + 4])
                    mfs[var][mf]['func'] = fuzz.trapmf(
                        mfs[var][mf]['universe'], mfs[var][mf]['param'])
                    i += 4

        for r in sorted(rules.keys()):
            for i in range(len(rules[r])):
                ind = int(re.sub("\D", "", rules[r][i]['name']))
                rules[r][i]['param'] = mfs[rules[r][i]
                                           ['var_name']][ind]['param']
                rules[r][i]['func'] = mfs[rules[r][i]['var_name']][ind]['func']

        activations = pd.DataFrame(
            index=X.index, columns=[rule for rule in sorted(rules.keys())])
        for rule in sorted(rules.keys()):
            act = []
            for mf in rules[rule]:
                act.append(
                    fuzz.interp_membership(mf['universe'], mf['func'],
                                           X[mf['var_name']]))
            activations[rule] = np.power(np.prod(np.array(act), axis=0), 1 / p)

        lin_models = dict()
        remove_null_rules = []

        for rule in sorted(activations.columns):
            indices = activations[rule].index[
                activations[rule] >= 0.01].tolist()

            if len(indices) > self.num_samples and len(
                    indices) < self.n_ratio * X.shape[0]:
                X1 = X.loc[indices].values
                y1 = y.loc[indices].values

                lin_models[rule] = LinearRegression().fit(X1, y1.ravel())
            elif len(indices) > 0:
                lin_models[rule] = 'null'
                remove_null_rules.append(rule)
            else:
                lin_models[rule] = None
                remove_null_rules.append(rule)

        total = 0
        for rule in sorted(rules.keys()):
            indices = activations[rule].index[
                activations[rule] >= 0.01].tolist()
            act = activations.loc[indices].copy(deep=True)
            act = act.drop(columns=[rule])
            if len(indices) <= self.num_samples and len(
                    indices) < self.n_ratio * X.shape[0] and not act.isnull(
                    ).all(axis=1).any():
                del rules[rule]
                del lin_models[rule]
            else:
                print(len(indices))
                self.logger.info("Number of samples of rule %s is %s", rule,
                                 len(indices))
            total += len(indices)
        print(total)
        self.logger.info("Number of samples of dataset with %s is %s",
                         X.shape[0], total)

        activations_test = pd.DataFrame(
            index=X_test.index,
            columns=[rule for rule in sorted(rules.keys())])
        for rule in sorted(rules.keys()):
            act = []
            for mf in rules[rule]:
                act.append(
                    fuzz.interp_membership(mf['universe'], mf['func'],
                                           X_test[mf['var_name']]))
            activations_test[rule] = np.power(np.prod(np.array(act), axis=0),
                                              1 / p)

        preds = pd.DataFrame(index=X_test.index,
                             columns=sorted(lin_models.keys()))
        for rule in sorted(rules.keys()):
            indices = activations_test[rule].index[
                activations_test[rule] >= 0.01].tolist()
            if len(indices) != 0:
                X1 = X_test.loc[indices].values
                y1 = y_test.loc[indices].values
                if (lin_models[rule] != 'null'
                        and not lin_models[rule] is None):
                    preds.loc[indices,
                              rule] = lin_models[rule].predict(X1).ravel()
                elif lin_models[rule] == 'null':
                    preds.loc[indices, rule] = 1e+15
                if isinstance(rated, float) or isinstance(rated, int):
                    err = (preds.loc[indices, rule].values.ravel() -
                           y1.ravel()) / rated
                else:
                    err = (preds.loc[indices, rule].values.ravel() -
                           y1.ravel()) / y1.ravel()
                self.logger.info("MAE of rule %s is %s", rule,
                                 np.mean(np.abs(err)))
        pred = preds.mean(axis=1)
        pred[pred.isnull()] = 1e+15
        # pred.name='target'
        # pred=pred.to_frame()
        err = (pred.values.ravel() - y_test.values.ravel()) / rated

        self.objectives = [np.sum(np.square(err)), np.mean(np.abs(err))]
        self.rules = rules
        self.mfs = mfs
        fmodel = dict()
        fmodel['mfs'] = self.mfs
        fmodel['rules'] = self.rules
        fmodel['result'] = self.objectives[1]
        print('Error = ', self.objectives[1])
        return fmodel
Beispiel #49
0
  def __init__(self):
    #inputs
    self.catch = ctrl.Antecedent(np.arange(58, 70, 0.1), 'Catch')
    self.catch['Novice'] = fuzz.trapmf(self.catch.universe, [0,58,60,61.5])
    self.catch['Intermediate'] = fuzz.gaussmf(self.catch.universe, 63.1, 0.7)
    self.catch['National'] = fuzz.gaussmf(self.catch.universe, 65.7, 0.7)
    self.catch['International'] = fuzz.trapmf(self.catch.universe, [67.6, 68.2, 70, 70])

    self.finish = ctrl.Antecedent(np.arange(38, 46, 0.1), 'Finish')
    self.finish['Novice'] = fuzz.trapmf(self.finish.universe, [0,38,38,38.9])
    self.finish['Intermediate'] = fuzz.gaussmf(self.finish.universe, 40.8, 0.8)
    self.finish['National'] = fuzz.gaussmf(self.finish.universe, 43.1, 0.8)
    self.finish['International'] = fuzz.trapmf(self.finish.universe, [45.1, 45.8, 46, 46])

    self.slip = ctrl.Antecedent(np.arange(2, 8, 0.1), 'Slip')
    self.slip['Novice'] = fuzz.trapmf(self.slip.universe, [6.9, 7.4, 8,8])
    self.slip['Intermediate'] = fuzz.gaussmf(self.slip.universe, 5.6, 0.4)
    self.slip['National'] = fuzz.gaussmf(self.slip.universe, 4.1, 0.4)
    self.slip['International'] = fuzz.trapmf(self.slip.universe, [2, 2, 2.2, 2.9])

    self.wash = ctrl.Antecedent(np.arange(9, 20, 0.1), 'Wash')
    self.wash['Novice'] = fuzz.trapmf(self.wash.universe, [18.9, 19.4, 20, 20])
    self.wash['Intermediate'] = fuzz.gaussmf(self.wash.universe, 16.8, 1)
    self.wash['National'] = fuzz.gaussmf(self.wash.universe, 14.3, 1)
    self.wash['International'] = fuzz.trapmf(self.wash.universe, [9,9, 10.9,12.5])
    
    self.length = ctrl.Antecedent(np.arange(95, 115, 0.1), 'Length')
    self.length['Novice'] = fuzz.trapmf(self.length.universe, [95,95,100.2,102.3])
    self.length['Intermediate'] = fuzz.gaussmf(self.length.universe, 104.7, 1.2)
    self.length['National'] = fuzz.gaussmf(self.length.universe, 108, 1.2)
    self.length['International'] = fuzz.trapmf(self.length.universe, [108.0, 111.4, 115,115])

    #output 
    self.quality = ctrl.Consequent(np.arange(0, 101, 0.1), 'Quality')
    #setting membership functions
    self.quality['Novice'] = fuzz.gaussmf(self.quality.universe, 0, 10)
    self.quality['Intermediate'] = fuzz.gaussmf(self.quality.universe, 40, 8)
    self.quality['National'] = fuzz.gaussmf(self.quality.universe, 60, 8)
    self.quality['International'] = fuzz.gaussmf(self.quality.universe, 100, 10)

    #catch 
    rule1 = ctrl.Rule(self.catch['Novice'], self.quality['Novice'])
    rule2 = ctrl.Rule(self.catch['Intermediate'], self.quality['Intermediate'])
    rule3 = ctrl.Rule(self.catch['National'], self.quality['National'])
    rule4 = ctrl.Rule(self.catch['International'], self.quality['International'])
    #finish
    rule5 = ctrl.Rule(self.finish['Novice'], self.quality['Novice'])
    rule6 = ctrl.Rule(self.finish['Intermediate'], self.quality['Intermediate'])
    rule7 = ctrl.Rule(self.finish['National'], self.quality['National'])
    rule8 = ctrl.Rule(self.finish['International'], self.quality['International'])
    #slip
    rule9  = ctrl.Rule(self.slip['Novice'], self.quality['Novice'])
    rule10 = ctrl.Rule(self.slip['Intermediate'], self.quality['Intermediate'])
    rule11 = ctrl.Rule(self.slip['National'], self.quality['National'])
    rule12 = ctrl.Rule(self.slip['International'], self.quality['International'])
    #wash
    rule13 = ctrl.Rule(self.wash['Novice'], self.quality['Novice'])
    rule14 = ctrl.Rule(self.wash['Intermediate'], self.quality['Intermediate'])
    rule15 = ctrl.Rule(self.wash['National'], self.quality['National'])
    rule16 = ctrl.Rule(self.wash['International'], self.quality['International'])
    #length
    rule17 = ctrl.Rule(self.length['Novice'], self.quality['Novice'])
    rule18 = ctrl.Rule(self.length['Intermediate'], self.quality['Intermediate'])
    rule19 = ctrl.Rule(self.length['National'], self.quality['National'])
    rule20 = ctrl.Rule(self.length['International'], self.quality['International'])

    rowingFIS_ctrl = ctrl.ControlSystem([
      rule1, rule2, rule3, rule4, #catch
      rule5, rule6, rule7, rule8,#finish
      rule9, rule10, rule11, rule12,#slip
      rule13, rule14, rule15, rule16,#wash
      rule17, rule18, rule19, rule20#length
    ])

    self.rowingFis = ctrl.ControlSystemSimulation(rowingFIS_ctrl)
Beispiel #50
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')
ax.set_ylabel('Fuzzy membership')
Beispiel #51
0
def calculate_obj2(value_ini_21, value_ini_22, value_ini_23):

    #OBJETIVO 2: Crear experiencias gratamente memorables para posicionar la marca EMTEL en el corazón de los clientes
    # Generate universe variables
    #   El rango de las iniciativas estrategicas es [0,110]
    #   El rango del objetivo de salida es [0,110]
    # Inic1 = Crear cultura basada en la experiencia
    # Inic2 = Alcanzar los tiempos promedio de instalacion y reparación requeridos
    # Inic3 = Garantizar los niveles de calidad establecidos en la prestación de los servicios TIC

    # New Antecedent/Consequent objects hold universe variables and membership
    # functions
    Inic1 = ctrl.Antecedent(np.arange(0, 110, 1), 'Inic1')
    Inic2 = ctrl.Antecedent(np.arange(0, 110, 1), 'Inic2')
    Inic3 = ctrl.Antecedent(np.arange(0, 110, 1), 'Inic3')
    Obj2 = ctrl.Consequent(np.arange(0, 110, 1), 'Objetivo 2')

    # Generate fuzzy membership functions
    Inic1['Dmayor'] = fuzz.trapmf(Inic1.universe, [-1, 0, 20, 29])
    Inic1['Dmenor'] = fuzz.trimf(Inic1.universe, [30, 40, 55])
    Inic1['Fmenor'] = fuzz.trimf(Inic1.universe, [44, 60, 78])
    Inic1['Fmayor'] = fuzz.trapmf(Inic1.universe, [76, 80, 110, 120])

    Inic2['Dmayor'] = fuzz.trapmf(Inic2.universe, [-1, 0, 20, 29])
    Inic2['Dmenor'] = fuzz.trimf(Inic2.universe, [32, 40, 58])
    Inic2['Fmenor'] = fuzz.trimf(Inic2.universe, [36, 60, 69])
    Inic2['Fmayor'] = fuzz.trapmf(Inic2.universe, [75, 80, 110, 120])

    Inic3['Dmayor'] = fuzz.trapmf(Inic3.universe, [-1, 0, 20, 22])
    Inic3['Dmenor'] = fuzz.trimf(Inic3.universe, [31, 40, 55])
    Inic3['Fmenor'] = fuzz.trimf(Inic3.universe, [44, 60, 77])
    Inic3['Fmayor'] = fuzz.trapmf(Inic3.universe, [72, 80, 110, 120])

    Obj2['Dmayor'] = fuzz.trapmf(Obj2.universe, [-1, 0, 20, 35])
    Obj2['Dmenor'] = fuzz.trimf(Obj2.universe, [30, 40, 55])
    Obj2['Fmenor'] = fuzz.trimf(Obj2.universe, [50, 60, 76])
    Obj2['Fmayor'] = fuzz.trapmf(Obj2.universe, [60, 80, 110, 120])

    #generate rules membreship
    rule1 = ctrl.Rule(Inic1['Dmenor'] | Inic2['Fmenor'], Obj2['Fmenor'])
    rule2 = ctrl.Rule(Inic1['Fmayor'], Obj2['Fmenor'])
    rule3 = ctrl.Rule(Inic1['Fmayor'] & Inic2['Fmayor'], Obj2['Fmayor'])
    rule4 = ctrl.Rule(Inic1['Fmenor'] & Inic3['Fmenor'], Obj2['Fmenor'])
    rule5 = ctrl.Rule(Inic3['Fmayor'] | Inic2['Fmayor'] | Inic1['Fmayor'],
                      Obj2['Fmenor'])

    #create system control and simulation
    solving_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5])
    solving = ctrl.ControlSystemSimulation(solving_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)
    solving.input['Inic1'] = value_ini_21
    solving.input['Inic2'] = value_ini_22
    solving.input['Inic3'] = value_ini_23
    # Crunch the numbers
    solving.compute()

    #value objetivo 2
    Obj2_result = solving.output['Objetivo 2']

    #update data
    n = 1
    data = [['Objetivo', 'Valor'], ['Objetivo 1', 0], ['Objetivo 2', 0],
            ['Objetivo 3', 0], ['Objetivo 4', 0], ['Objetivo 5', 0],
            ['Objetivo 6', 0], ['Objetivo 7', 0]]

    with open('static/data/datamain.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            data[n] = ['Objetivo', row['Valor']]
            n = n + 1

    #update table
    data[2][1] = Obj2_result

    with open('static/data/datamain.csv', 'w') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerows(data)

    csvFile.close()
Beispiel #52
0
def controle_fuzzy():

    # Descrição do conjunto universo para os antecedentes e consequentes
    posicao_lateral = ctrl.Antecedent(np.arange(-90, 90, 0.1),
                                      'Posicao Lateral')
    posicao_derivadaerro = ctrl.Antecedent(np.arange(-3000, 3000, 0.1),
                                           'Derivada Erro')
    posicao_frontal = ctrl.Antecedent(np.arange(30, 1120, 0.1),
                                      'Posicao Frontal')
    angulo_volante = ctrl.Consequent(np.arange(-35, 35, 0.1), 'Angulo Volante')
    velocidade = ctrl.Consequent(np.arange(-1, 8, 0.1), 'Velocidade')

    # Funções de pertinência para a derivada do erro
    posicao_derivadaerro['Muito Direita'] = fuzz.trapmf(
        posicao_derivadaerro.universe, [-3000, -2900, -800, -90])
    posicao_derivadaerro['Direita'] = fuzz.trapmf(
        posicao_derivadaerro.universe, [-800, -600, -150, 0])
    posicao_derivadaerro['Meio'] = fuzz.trimf(posicao_derivadaerro.universe,
                                              [-150, 0, 150])
    posicao_derivadaerro['Esquerda'] = fuzz.trapmf(
        posicao_derivadaerro.universe, [0, 150, 500, 600])
    posicao_derivadaerro['Muito Esquerda'] = fuzz.trapmf(
        posicao_derivadaerro.universe, [600, 800, 2900, 3000])
    # Funções de pertinência para os sensores laterais
    posicao_lateral['Muito Direita'] = fuzz.trapmf(posicao_lateral.universe,
                                                   [-100, -90, -70, -35])
    posicao_lateral['Direita'] = fuzz.trapmf(posicao_lateral.universe,
                                             [-40, -20, -10, 0])
    posicao_lateral['Meio'] = fuzz.trimf(posicao_lateral.universe,
                                         [-15, 0, 15])
    posicao_lateral['Esquerda'] = fuzz.trapmf(posicao_lateral.universe,
                                              [0, 10, 25, 40])
    posicao_lateral['Muito Esquerda'] = fuzz.trapmf(posicao_lateral.universe,
                                                    [35, 70, 90, 100])
    # Funções de pertinência para o sensor frontal
    posicao_frontal['Perto'] = fuzz.trapmf(posicao_frontal.universe,
                                           [-1, 0, 100, 150])
    posicao_frontal['Longe'] = fuzz.trapmf(posicao_frontal.universe,
                                           [120, 450, 900, 1130])
    # Funções de pertinência para os sensores laterais
    angulo_volante['Muito Direita'] = fuzz.trapmf(angulo_volante.universe,
                                                  [-33, -30, -15, -10])
    angulo_volante['Direita'] = fuzz.trapmf(angulo_volante.universe,
                                            [-12, -8, -2, 0])
    angulo_volante['Meio'] = fuzz.trimf(angulo_volante.universe, [-2, 0, 2])
    angulo_volante['Esquerda'] = fuzz.trapmf(angulo_volante.universe,
                                             [0, 2, 8, 12])
    angulo_volante['Muito Esquerda'] = fuzz.trapmf(angulo_volante.universe,
                                                   [10, 15, 30, 35])
    # Funções de pertinência para o sensor frontal
    velocidade['Devagar'] = fuzz.trimf(velocidade.universe, [0.5, 2.5, 4])
    velocidade['Rapido'] = fuzz.trimf(velocidade.universe, [3, 7, 10])

    #Regras
    rule1 = ctrl.Rule(
        posicao_lateral['Meio'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], angulo_volante['Meio'])
    rule1_2 = ctrl.Rule(
        posicao_lateral['Meio'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], velocidade['Rapido'])

    rule2 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Muito Esquerda'],
        angulo_volante['Muito Direita'])
    rule2_2 = ctrl.Rule(posicao_lateral['Esquerda'] & posicao_frontal['Perto']
                        & posicao_derivadaerro['Muito Esquerda'],
                        velocidade['Devagar'])  #Devagar

    rule3 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Muito Direita'],
        angulo_volante['Muito Esquerda'])
    rule3_2 = ctrl.Rule(posicao_lateral['Direita'] & posicao_frontal['Perto']
                        & posicao_derivadaerro['Muito Direita'],
                        velocidade['Devagar'])  #Devagar

    rule4 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Esquerda'], angulo_volante['Meio'])
    rule4_2 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Esquerda'], velocidade['Rapido'])

    rule5 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Direita'], angulo_volante['Meio'])
    rule5_2 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Direita'], velocidade['Rapido'])

    rule6 = ctrl.Rule(
        posicao_lateral['Meio'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], angulo_volante['Meio'])
    rule6_2 = ctrl.Rule(posicao_lateral['Meio'] & posicao_frontal['Perto']
                        & posicao_derivadaerro['Meio'],
                        velocidade['Rapido'])  #Devagar

    rule7 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Muito Esquerda'],
        angulo_volante['Muito Direita'])
    rule7_2 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Muito Esquerda'], velocidade['Devagar'])

    rule8 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Muito Direita'],
        angulo_volante['Muito Esquerda'])
    rule8_2 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Muito Direita'], velocidade['Devagar'])

    rule9 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Esquerda'], angulo_volante['Direita'])
    rule9_2 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Esquerda'], velocidade['Rapido'])

    rule10 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Direita'], angulo_volante['Esquerda'])
    rule10_2 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Direita'], velocidade['Rapido'])

    rule11 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], angulo_volante['Esquerda'])
    rule11_2 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], velocidade['Rapido'])

    rule12 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], angulo_volante['Direita'])
    rule12_2 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], velocidade['Rapido'])

    rule13 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], angulo_volante['Muito Direita'])
    rule13_2 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], velocidade['Devagar'])

    rule14 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], angulo_volante['Muito Esquerda'])
    rule14_2 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], velocidade['Devagar'])

    rule15 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Esquerda'], angulo_volante['Muito Direita'])
    rule15_2 = ctrl.Rule(posicao_lateral['Esquerda'] & posicao_frontal['Perto']
                         & posicao_derivadaerro['Esquerda'],
                         velocidade['Devagar'])  #Devagar

    rule16 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Direita'], angulo_volante['Muito Esquerda'])
    rule16_2 = ctrl.Rule(posicao_lateral['Direita'] & posicao_frontal['Perto']
                         & posicao_derivadaerro['Direita'],
                         velocidade['Devagar'])  #Devagar

    rule17 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], angulo_volante['Muito Esquerda'])
    rule17_2 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], velocidade['Devagar'])

    rule18 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], angulo_volante['Muito Direita'])
    rule18_2 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Meio'], velocidade['Devagar'])

    rule19 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Esquerda'], angulo_volante['Esquerda'])
    rule19_2 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Esquerda'], velocidade['Rapido'])

    rule20 = ctrl.Rule(posicao_lateral['Direita'] & posicao_frontal['Perto']
                       & posicao_derivadaerro['Esquerda'],
                       angulo_volante['Muito Esquerda'])  #
    rule20_2 = ctrl.Rule(
        posicao_lateral['Direita'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Esquerda'], velocidade['Devagar'])

    rule21 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Direita'], angulo_volante['Direita'])
    rule21_2 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Direita'], velocidade['Rapido'])

    rule22 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Direita'], angulo_volante['Muito Esquerda'])
    rule22_2 = ctrl.Rule(
        posicao_lateral['Esquerda'] & posicao_frontal['Perto']
        & posicao_derivadaerro['Direita'], velocidade['Devagar'])

    rule23 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], angulo_volante['Direita'])
    rule23_2 = ctrl.Rule(
        posicao_lateral['Muito Esquerda'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], velocidade['Rapido'])

    rule24 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], angulo_volante['Esquerda'])
    rule24_2 = ctrl.Rule(
        posicao_lateral['Muito Direita'] & posicao_frontal['Longe']
        & posicao_derivadaerro['Meio'], velocidade['Rapido'])

    car_ctrl = ctrl.ControlSystem([
        rule1, rule1_2, rule2, rule2_2, rule3, rule3_2, rule4, rule4_2, rule5,
        rule5_2, rule6, rule6_2, rule7, rule7_2, rule8, rule8_2, rule9,
        rule9_2, rule10, rule10_2, rule11, rule11_2, rule12, rule12_2, rule13,
        rule13_2, rule14, rule14_2, rule15, rule15_2, rule16, rule16_2, rule17,
        rule17_2, rule18, rule18_2, rule19, rule19_2, rule20, rule20_2, rule21,
        rule21_2, rule22, rule22_2, rule23, rule23_2, rule24, rule24_2
    ])
    carro = ctrl.ControlSystemSimulation(car_ctrl)
    return carro
    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)
Beispiel #54
0
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sns.set()
from mpl_toolkits.mplot3d import Axes3D

driving = ctrl.Antecedent(np.arange(0, 101, 1), 'driving')
journey_time = ctrl.Antecedent(np.arange(0, 21, 1), 'journey_time')
tip = ctrl.Consequent(np.arange(0, 210, 1), 'tip')

driving['bad'] = fuzz.trapmf(driving.universe, [0, 0, 30, 50])
driving['average'] = fuzz.trapmf(driving.universe, [30, 50, 50, 70])
driving['good'] = fuzz.trapmf(driving.universe, [60, 80, 100, 100])

journey_time['short'] = fuzz.trapmf(journey_time.universe, [0, 0, 0, 10])
journey_time['medium'] = fuzz.trapmf(journey_time.universe, [5, 10, 10, 15])
journey_time['long'] = fuzz.trapmf(journey_time.universe, [10, 20, 20, 20])

tip['small'] = fuzz.trapmf(tip.universe, [0, 50, 50, 100])
tip['moderate'] = fuzz.trapmf(tip.universe, [50, 100, 100, 150])
tip['big'] = fuzz.trapmf(tip.universe, [100, 150, 150, 200])

# driving.view()
# journey_time.view()
# tip.view()
# plt.show()

rule1 = ctrl.Rule(driving['good'] & journey_time['short'], tip['big'])
Beispiel #55
0
def calculate_obj1(value_ini_11, value_ini_12):

    #OBJETIVO 1: GARANTIZAR LA SOSTENEBILIDAD ECONOMICA DE LA ORGANIZACION
    # Generate universe variables
    #   El rango de las iniciativas estrategicas es [0,110]
    #   El rango del objetivo de salida es [0,110]
    # Inic1 = Disminuir los pasivos a corto plazo
    # Inic2 = Incrementar los ingresos

    # New Antecedent/Consequent objects hold universe variables and membership
    # functions

    Inic_1_1 = ctrl.Antecedent(np.arange(0, 110, 1),
                               'Disminuir los pasivos...')
    Inic_1_2 = ctrl.Antecedent(np.arange(0, 110, 1),
                               'Incrementar los ingresos')
    Obj1 = ctrl.Consequent(np.arange(0, 110, 1), 'Objetivo 1')

    # Generate fuzzy membership functions
    Inic_1_1['Dmayor'] = fuzz.trapmf(Inic_1_1.universe, [-1, 0, 20, 29])
    Inic_1_1['Dmenor'] = fuzz.trimf(Inic_1_1.universe, [12, 40, 46])
    Inic_1_1['Fmenor'] = fuzz.trimf(Inic_1_1.universe, [36, 60, 72])
    Inic_1_1['Fmayor'] = fuzz.trapmf(Inic_1_1.universe, [76, 80, 110, 120])

    Inic_1_2['Dmayor'] = fuzz.trapmf(Inic_1_2.universe, [-1, 0, 20, 35])
    Inic_1_2['Dmenor'] = fuzz.trimf(Inic_1_2.universe, [37, 40, 56])
    Inic_1_2['Fmenor'] = fuzz.trimf(Inic_1_2.universe, [56, 60, 75])
    Inic_1_2['Fmayor'] = fuzz.trapmf(Inic_1_2.universe, [72, 80, 110, 120])

    Obj1['Dmayor'] = fuzz.trapmf(Obj1.universe, [-1, 0, 20, 35])
    Obj1['Dmenor'] = fuzz.trimf(Obj1.universe, [30, 40, 55])
    Obj1['Fmenor'] = fuzz.trimf(Obj1.universe, [50, 60, 76])
    Obj1['Fmayor'] = fuzz.trapmf(Obj1.universe, [60, 80, 110, 120])

    # generate rules
    rule_1_1 = ctrl.Rule(Inic_1_1['Dmenor'] | Inic_1_2['Fmenor'],
                         Obj1['Fmenor'])
    rule_1_2 = ctrl.Rule(Inic_1_1['Fmayor'], Obj1['Fmenor'])
    rule_1_3 = ctrl.Rule(Inic_1_1['Fmayor'] & Inic_1_2['Fmayor'],
                         Obj1['Fmayor'])

    #create system control and simulation
    solving_ctrl_obj1 = ctrl.ControlSystem([rule_1_1, rule_1_2, rule_1_3])
    solving_obj1 = ctrl.ControlSystemSimulation(solving_ctrl_obj1)

    # 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)
    solving_obj1.input['Disminuir los pasivos...'] = value_ini_11
    solving_obj1.input['Incrementar los ingresos'] = value_ini_12
    # Crunch the numbers
    solving_obj1.compute()

    #value objetivo 1
    Obj1_result = solving_obj1.output['Objetivo 1']

    #update data
    n = 1

    data = [['Objetivo', 'Valor'], ['Objetivo 1', 0], ['Objetivo 2', 0],
            ['Objetivo 3', 0], ['Objetivo 4', 0], ['Objetivo 5', 0],
            ['Objetivo 6', 0], ['Objetivo 7', 0]]

    with open('static/data/datamain.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            data[n] = ['Objetivo', row['Valor']]
            n = n + 1

    data[1][1] = Obj1_result

    with open('static/data/datamain.csv', 'w') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerows(data)

    csvFile.close()
Beispiel #56
0
import matplotlib.pyplot as plt

kwargs = {'lw': 20, 'solid_capstyle': 'round'}


if __name__ == '__main__':

    # Generate membership functions corresponding to S, F, I, and U in logo
    x_sf = np.arange(0, 3.1, 0.1) - 0.1
    x_f2 = np.arange(0, 2.7, 0.1) - 0.1
    x_i = np.arange(3.6, 4.05, 0.1)
    x_u1 = np.arange(3.0, 3.45, 0.1)
    x_u2 = np.arange(3.0, 4.05, 0.1)
    x_u3 = np.arange(4.0, 4.45, 0.1)

    s_mf = fuzz.trapmf(x_sf, [1, 2, 3, 3]) * (2. / 3) + 0.4
    f_mf1 = fuzz.trapmf(x_sf, [1, 2, 3, 3]) * (2. / 3)
    f_mf2 = fuzz.trapmf(x_f2, [1, 1.6, 2.6, 2.6]) * 0.4
    i_mf = (x_i - 3.6) * (2. / 3) + 0.4
    u1_mf = (x_u1 - 3) * (2. / 3)
    u2_mf = np.zeros_like(x_u2)
    u3_mf = (x_u3 - 4) * (2. / 3)

    bot = 0.4 * 2 / 3

    # Plot various membership functions
    fig, ax = plt.subplots(figsize=(8, 6))

    s = ax.plot(x_sf, s_mf, 'k', **kwargs)
    f1 = ax.plot(x_sf + 0.4, f_mf1, 'k', **kwargs)
    f2 = ax.plot(x_f2 + 0.4, f_mf2, 'k', **kwargs)
Beispiel #57
0
def calculate_obj3(value_ini_31):
    #OBJETIVO 3: INCURSIONAR EN NUEVAS OPORTUNIDADES DE NEGOCIO
    # Generate universe variables
    #   El rango de las iniciativas estrategicas es [0,110]
    #   El rango del objetivo de salida es [0,110]
    # Inic1 = Generar nuevas oportunidades de negocio

    # New Antecedent/Consequent objects hold universe variables and membership
    # functions
    Inic1 = ctrl.Antecedent(np.arange(0, 110, 1), 'Inic1')
    Obj3 = ctrl.Consequent(np.arange(0, 110, 1), 'Objetivo 3')

    # Generate fuzzy membership functions
    Inic1['Dmayor'] = fuzz.trapmf(Inic1.universe, [-1, 0, 20, 26])
    Inic1['Dmenor'] = fuzz.trimf(Inic1.universe, [21, 40, 57])
    Inic1['Fmenor'] = fuzz.trimf(Inic1.universe, [55, 60, 79])
    Inic1['Fmayor'] = fuzz.trapmf(Inic1.universe, [72, 80, 110, 120])

    Obj3['Dmayor'] = fuzz.trapmf(Obj3.universe, [-1, 0, 20, 35])
    Obj3['Dmenor'] = fuzz.trimf(Obj3.universe, [30, 40, 55])
    Obj3['Fmenor'] = fuzz.trimf(Obj3.universe, [50, 60, 76])
    Obj3['Fmayor'] = fuzz.trapmf(Obj3.universe, [60, 80, 110, 120])

    #generate rules membreship
    rule1 = ctrl.Rule(Inic1['Dmayor'], Obj3['Dmayor'])
    rule2 = ctrl.Rule(Inic1['Dmenor'], Obj3['Dmenor'])
    rule3 = ctrl.Rule(Inic1['Fmenor'], Obj3['Fmenor'])
    rule4 = ctrl.Rule(Inic1['Fmayor'], Obj3['Fmayor'])

    #create system control and simulation
    solving_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4])
    solving = ctrl.ControlSystemSimulation(solving_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)
    solving.input['Inic1'] = value_ini_31
    # Crunch the numbers
    solving.compute()

    #value objetivo 3
    Obj3_result = solving.output['Objetivo 3']

    #update data
    n = 1
    data = [['Objetivo', 'Valor'], ['Objetivo 1', 0], ['Objetivo 2', 0],
            ['Objetivo 3', 0], ['Objetivo 4', 0], ['Objetivo 5', 0],
            ['Objetivo 6', 0], ['Objetivo 7', 0]]

    with open('static/data/datamain.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            data[n] = ['Objetivo', row['Valor']]
            n = n + 1

    #update table
    data[3][1] = Obj3_result

    with open('static/data/datamain.csv', 'w') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerows(data)

    csvFile.close()
Beispiel #58
0
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Cria as variáveis do problema
air_temp = ctrl.Antecedent(np.arange(0, 51, 1), 'air_temp')
air_h = ctrl.Antecedent(np.arange(0, 101, 1), 'air_humidity')
s_moisture = ctrl.Antecedent(np.arange(0, 101, 1), 'soil_moisture')
balance = ctrl.Antecedent(np.arange(0, 421, 1), 'balance')

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

# Cria manualmente o mapeamento entre valores nítidos e difusos
s_moisture['dry'] = fuzz.trapmf(s_moisture.universe, [0, 0, 10, 22])
s_moisture['moderate'] = fuzz.trapmf(s_moisture.universe, [13, 22, 28, 37])
s_moisture['wet'] = fuzz.trapmf(s_moisture.universe, [28, 40, 100, 100])

air_h['low'] = fuzz.trapmf(air_h.universe, [0, 0, 70, 85])
air_h['high'] = fuzz.trapmf(air_h.universe, [75, 90, 100, 100])

air_temp['cool'] = fuzz.trapmf(air_temp.universe, [0, 0, 22, 34])
air_temp['hot'] = fuzz.trapmf(air_temp.universe, [22, 34, 50, 50])

balance['little'] = fuzz.trapmf(balance.universe, [0, 0, 120, 140])
balance['average'] = fuzz.trapmf(balance.universe, [120, 140, 280, 300])
balance['much'] = fuzz.trapmf(balance.universe, [280, 300, 420, 420])

pumping['veryshort'] = fuzz.trapmf(pumping.universe, [0, 0, 1, 3])
pumping['short'] = fuzz.trapmf(pumping.universe, [1, 3, 4, 6])
pumping['average'] = fuzz.trapmf(pumping.universe, [4, 6, 7, 9])
pumping['long'] = fuzz.trapmf(pumping.universe, [7, 9, 10, 10])
#    fitnessValue = (dfFit['Asset'][len(dfFit)-1], yearstart, yearend, dfFit)

    fitnessValue = (dfFit['Asset'][len(dfFit) - 1], yearstart, yearend,
                    dfFit.loc[len(dfFit) - 1, :])

    return fitnessValue


###############################################################################
### Fuzzy one-time setup
###############################################################################

# Set up RSI as an antecedent
MA = ctrl.Antecedent(np.arange(-1000, 401, 1), 'MA')
MA['low'] = fuzz.trapmf(MA.universe, [-1000, -1000, -60, -40])
MA['med'] = fuzz.trapmf(MA.universe, [-60, -40, 40, 60])
MA['high'] = fuzz.trapmf(MA.universe, [40, 60, 400, 400])

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

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