Exemple #1
0
    def defuzz(self):
        """Derive crisp value based on membership of adjective(s)."""
        if not self.sim._array_inputs:
            ups_universe, output_mf, cut_mfs = self.find_memberships()

            if len(cut_mfs) == 0:
                raise ValueError(
                    "No terms have memberships.  Make sure you "
                    "have at least one rule connected to this "
                    "variable and have run the rules calculation.")

            try:
                return defuzz(ups_universe, output_mf,
                              self.var.defuzzify_method)
            except AssertionError:
                raise ValueError(
                    "Crisp output cannot be calculated, likely "
                    "because the system is too sparse. Check to "
                    "make sure this set of input values will "
                    "activate at least one connected Term in each "
                    "Antecedent via the current set of Rules.")
        else:
            # Calculate using array-aware version, one cut at a time.
            output = np.zeros(self.sim._array_shape, dtype=np.float64)

            it = np.nditer(output, ['multi_index'],
                           [['writeonly', 'allocate']])

            for out in it:
                universe, mf = self.find_memberships_nd(it.multi_index)
                out[...] = defuzz(universe, mf, self.var.defuzzify_method)

            return output
Exemple #2
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')
Exemple #3
0
 def speed_type(speedvalue, speedtype): 
     if speedtype == "Fast": 
         new_arg = fuzz.interp_universe(speedo, fast, speedvalue)[-1]
         tip_fast = np.fmin(fast, new_arg)
         try:
             res = fuzz.defuzz(speedo, tip_fast, 'centroid')
         except:
             return new_arg, 0
     elif speedtype == "Slower":
         new_arg = fuzz.interp_universe(speedo, slower, speedvalue)[-1]
         tip_slower = np.fmin(slower, new_arg)
         try:
             res = fuzz.defuzz(speedo, tip_slower, 'centroid')
         except:
             return new_arg, 0
     elif speedtype == "Slow": 
         new_arg = fuzz.interp_universe(speedo, slow, speedvalue)[-1]
         tip_slow = np.fmin(slow, new_arg)
         try:
             res = fuzz.defuzz(speedo, tip_slow, 'centroid')
         except:
             return new_arg, 0
     elif speedtype == "Stop": 
         new_arg = fuzz.interp_universe(speedo, stop, speedvalue)[-1]
         tip_stop = np.fmin(stop, new_arg)
         try:
             res = fuzz.defuzz(speedo, tip_stop, 'centroid')
         except:
             return new_arg, 0
     return new_arg, res
    def defuzz(self):
        """Derive crisp value based on membership of adjective(s)."""
        if not self.sim._array_inputs:
            ups_universe, output_mf, cut_mfs = self.find_memberships()

            if len(cut_mfs) == 0:
                raise ValueError("No terms have memberships.  Make sure you "
                                 "have at least one rule connected to this "
                                 "variable and have run the rules calculation.")

            try:
                return defuzz(ups_universe, output_mf,
                              self.var.defuzzify_method)
            except AssertionError:
                raise ValueError("Crisp output cannot be calculated, likely "
                                 "because the system is too sparse. Check to "
                                 "make sure this set of input values will "
                                 "activate at least one connected Term in each "
                                 "Antecedent via the current set of Rules.")
        else:
            # Calculate using array-aware version, one cut at a time.
            output = np.zeros(self.sim._array_shape, dtype=np.float64)

            it = np.nditer(output, ['multi_index'], [['writeonly', 'allocate']])

            for out in it:
                universe, mf = self.find_memberships_nd(it.multi_index)
                out[...] = defuzz(universe, mf, self.var.defuzzify_method)

            return output
Exemple #5
0
def desfuzzy(universe, fuzzy_array):
    # Defuzzify this membership function five ways
    defuzz_centroid = fuzz.defuzz(universe, fuzzy_array,
                                  'centroid')  # Same as skfuzzy.centroid
    defuzz_bisector = fuzz.defuzz(universe, fuzzy_array, 'bisector')

    # Collect info for vertical lines
    labels = [
        'centroid', 'bisector', 'mean of maximum', 'min of maximum',
        'max of maximum'
    ]
    xvals = [defuzz_centroid, defuzz_bisector]
    colors = ['r', 'b']

    ymax = [fuzz.interp_membership(universe, fuzzy_array, i) for i in xvals]

    # Display and compare defuzzification results against membership function
    plt.figure(figsize=(8, 5))

    plt.plot(universe, fuzzy_array, 'k')
    for xv, y, label, color in zip(xvals, ymax, labels, colors):
        plt.vlines(xv, 0, y, label=label, color=color)
    plt.ylabel('Fuzzy membership')
    plt.xlabel('Universe variable (arb)')
    plt.ylim(-0.1, 1.1)
    plt.legend(loc=2)

    plt.show()
Exemple #6
0
    def _setDefuzzMethod(self, m):
        rightMax = 'Right-Max'
        centroid = 'Centroid'

        # u - aggregated membership function values.
        if m == rightMax:
            self._defuzzMethod = lambda u: fz.defuzz(self._rotationAngleX, u,
                                                     'lom')
        elif m == centroid:
            self._defuzzMethod = lambda u: fz.defuzz(self._rotationAngleX, u,
                                                     'centroid')
        else:
            raise ValueError(f'Expected "{rightMax}" or "{centroid}"')
Exemple #7
0
def interpret_data(agent):
    ball_angle = angle2D(agent.ball, agent.me)
    ball_distance = distance2D(agent.ball, agent.me)  # Get distance to ball

    rule = []
    throttle_activation = []
    steer_activation = []

    for i in range(0, agent.num_rules):
        if (agent.labels[i * 3 + 2].find('c') > 0):
            rule_a1 = fuzz.interp_membership(agent.universes[i * 3],
                                             agent.ruleset[i * 3],
                                             ball_distance)
            rule_a2 = fuzz.interp_membership(agent.universes[i * 3 + 1],
                                             agent.ruleset[i * 3 + 1],
                                             ball_angle)
            active_rule = np.fmax(rule_a1, rule_a2)
            rule_support = np.fmin(active_rule, agent.ruleset[i * 3 + 2])
            throttle_activation.append(rule_support)
        else:
            rule_a1 = fuzz.interp_membership(agent.universes[i * 3],
                                             agent.ruleset[i * 3],
                                             ball_distance)
            rule_a2 = fuzz.interp_membership(agent.universes[i * 3 + 1],
                                             agent.ruleset[i * 3 + 1],
                                             ball_angle)
            active_rule = np.fmax(rule_a1, rule_a2)
            rule_support = np.fmin(active_rule, agent.ruleset[i * 3 + 2])
            steer_activation.append(rule_support)

    agg_throttle = 0
    agg_steer = 0

    for i in range(0, len(throttle_activation) - 1):
        agg_throttle = np.fmax(throttle_activation[i],
                               throttle_activation[i + 1])

    for i in range(0, len(steer_activation) - 1):
        agg_steer = np.fmax(steer_activation[i], steer_activation[i + 1])

    throttle = 0
    steer = 0

    if (any(agg_throttle) > 0):
        throttle = fuzz.defuzz(agent.fuzzy.throttle, agg_throttle, 'centroid')

    if (any(agg_steer) > 0):
        steer = fuzz.defuzz(agent.fuzzy.turn, agg_steer, 'centroid')
        #print(steer)

    return [throttle, steer]
Exemple #8
0
    def getFuzzyAcceleration(self, currentBatAngle, predictedBatAngle):

        dif = abs(currentBatAngle - predictedBatAngle)
        if (dif > 180):
            self.InputDistanceAngle = 360 - dif
        else:
            self.InputDistanceAngle = dif
        '''    
        self.thetaOne = abs(currentBatAngle-predictedBatAngle)
        self.thetaTwo = currentBatAngle + (360-predictedBatAngle)
        
        if(self.thetaOne < self.thetaTwo):
            self.InputDistanceAngle = self.thetaOne
        else:
            self.InputDistanceAngle = self.thetaTwo
        '''

        self.InputDistanceAngle = int(self.InputDistanceAngle)

        #print "final angle to cover----",int(self.InputDistanceAngle)
        #print "buggy parth=============",self.R_combined[self.distance == self.InputDistanceAngle]

        self.OutputAcceleration = fuzz.defuzz(
            self.acceleration,
            self.R_combined[self.distance == self.InputDistanceAngle],
            'centroid')

        #print "correspoinding acceleration",self.OutputAcceleration

        return self.OutputAcceleration

        #test code starts here
        '''
def fuzzy_system(generation_val, convergence_val):
    # just to ensure that value excceding 1 will be taken care by the code.
    if (convergence_val > 1):
        convergence_val = 0.99

    x_generation = np.arange(0, 1500, 50)
    x_convergence = np.arange(0, 1, 0.1)
    x_recombinationRate = np.arange(0, 0.5, 0.1)

    # Generate fuzzy membership functions
    generation_lo = fuzz.trapmf(x_generation, [0, 0, 200, 300])
    generation_md = fuzz.trimf(x_generation, [290, 550, 700])
    generation_hi = fuzz.trapmf(x_generation, [690, 700, 1500, 1500])
    convergence_lo = fuzz.trapmf(x_convergence, [0, 0, 0.2, 0.3])
    convergence_md = fuzz.trapmf(x_convergence, [0.25, 0.4, 0.6, 0.75])
    convergence_hi = fuzz.trapmf(x_convergence, [0.7, 0.8, 1, 1])
    recom_lo = fuzz.trapmf(x_recombinationRate, [0, 0, 0.3, 0.4])
    recom_md = fuzz.trapmf(x_recombinationRate, [0.35, 0.5, 0.5, 0.7])
    recom_hi = fuzz.trapmf(x_recombinationRate, [0.7, 0.9, 1, 1])

    generation_level_lo = fuzz.interp_membership(x_generation, generation_lo,
                                                 generation_val)
    generation_level_md = fuzz.interp_membership(x_generation, generation_md,
                                                 generation_val)
    generation_level_hi = fuzz.interp_membership(x_generation, generation_hi,
                                                 generation_val)

    convergence_level_lo = fuzz.interp_membership(x_convergence,
                                                  convergence_lo,
                                                  convergence_val)
    convergence_level_md = fuzz.interp_membership(x_convergence,
                                                  convergence_md,
                                                  convergence_val)
    convergence_level_hi = fuzz.interp_membership(x_convergence,
                                                  convergence_hi,
                                                  convergence_val)

    # if generation level is high, recombination is low, do nothing to explore
    rate_activation_lo = np.fmin(generation_level_hi, recom_lo)

    # if generation is medium and convergence is low, recombination is medium: Try to boost the exploration
    active_rule1 = np.fmin(generation_level_md,
                           fuzz.fuzzy_not(convergence_level_lo))
    rate_activation_md = np.fmin(active_rule1, recom_md)

    # if generation is low or medium and convergence is high, give high recombination
    active_rule2 = np.fmax(fuzz.fuzzy_not(generation_level_hi),
                           convergence_level_hi)
    rate_activation_hi = np.fmin(active_rule2, recom_hi)

    aggregated = np.fmax(rate_activation_lo,
                         np.fmax(rate_activation_md, rate_activation_hi))

    try:
        recom_rate = fuzz.defuzz(x_recombinationRate, aggregated, 'centroid')
    except:
        # if the member function is empty, just set the value to default low only
        recom_rate = 0.25

    return recom_rate
Exemple #10
0
def compute(tam, dst):
    # se difusan los valores.
    (tam_peq, tam_med, tam_grd) = pertenenciaTam(tam)
    (dst_crc, dst_ljs, dst_afr) = pertenenciaDst(dst)

    # se calcula la regla 1.
    prc_alt_grd = np.fmin(tam_grd, prc_alt)

    # se calcula la regla 2.
    prc_alt_crc = np.fmin(dst_crc, prc_alt)

    # se calcula la regla 3.
    prc_med_peqMedLjs = np.fmin(np.fmin(np.fmax(tam_peq, tam_med), dst_ljs),
                                prc_med)

    # se calcula la regla 4.
    prc_baj_peqMedAfr = np.fmin(np.fmin(np.fmax(tam_peq, tam_med), dst_afr),
                                prc_baj)

    # se combinan los resultados
    resultados_ = np.fmax(
        prc_alt_grd,
        np.fmax(prc_alt_crc, np.fmax(prc_med_peqMedLjs, prc_baj_peqMedAfr)))

    # se calcula el resultado "afilado" (usando el centroide de la forma)
    precio = fuzz.defuzz(x_prc, resultados_, 'centroid')
    return precio
Exemple #11
0
def compute_tip_amout(qual_val, serv_val):
    qual_level_poor = fuzz.interp_membership(x_qual, qual_poor, qual_val)
    qual_level_amazing = fuzz.interp_membership(x_qual, qual_amazing, qual_val)

    serv_level_poor = fuzz.interp_membership(x_serv, serv_poor, serv_val)
    serv_level_acceptable = fuzz.interp_membership(x_serv, serv_acceptable,
                                                   serv_val)
    serv_level_amazing = fuzz.interp_membership(x_serv, serv_amazing, serv_val)

    # Rule 1: IF service = poor OR food = poor THEN tip = low
    satisfaction_rule1 = np.fmax(qual_level_poor, serv_level_poor)
    tip_activation_low = np.fmin(satisfaction_rule1, tip_low)

    # Rule 2: IF service = acceptable THEN tip = medium
    tip_acitvation_medium = np.fmin(serv_level_acceptable, tip_medium)

    # Rule 3: IF service = amazing OR food = amazing THEN tip = high
    satisfaction_rule3 = np.fmax(qual_level_amazing, serv_level_amazing)
    tip_activation_high = np.fmin(satisfaction_rule3, tip_high)
    tip0 = np.zeros_like(x_tip)

    #각 규칙의 추론결과 결합
    aggregated = np.fmax(tip_activation_low,
                         np.fmax(tip_acitvation_medium, tip_activation_high))

    # 비퍼지화
    tip = fuzz.defuzz(x_tip, aggregated, 'centroid')
    return tip
Exemple #12
0
 def getFuzzyAcceleration(self,currentBatAngle,predictedBatAngle):
     
     dif = abs(currentBatAngle - predictedBatAngle)
     if(dif > 180):
         self.InputDistanceAngle = 360- dif
     else:
         self.InputDistanceAngle = dif
     '''    
     self.thetaOne = abs(currentBatAngle-predictedBatAngle)
     self.thetaTwo = currentBatAngle + (360-predictedBatAngle)
     
     if(self.thetaOne < self.thetaTwo):
         self.InputDistanceAngle = self.thetaOne
     else:
         self.InputDistanceAngle = self.thetaTwo
     '''
            
     self.InputDistanceAngle = int(self.InputDistanceAngle)
      
     #print "final angle to cover----",int(self.InputDistanceAngle)
     #print "buggy parth=============",self.R_combined[self.distance == self.InputDistanceAngle]
         
     self.OutputAcceleration = fuzz.defuzz(self.acceleration,self.R_combined[self.distance == self.InputDistanceAngle], 'centroid')
     
     #print "correspoinding acceleration",self.OutputAcceleration
     
     return self.OutputAcceleration
 
     #test code starts here
     '''
Exemple #13
0
    def run(self):

            """ inputs[0] =  ERROR AXIS          ., so stores all possible error values
                inputs[1] =  DEL_ERROR AXIS      .,     ,,
                inputs[2] =  CONTROL_OUTPUT AXIS .,     ,,
                    
                ERROR                  DEL_ERROR               CONTROL_OUTPUT         m_value for crisp e and delta_e values

                b[0][0] -ve Medium  || b[1][0] -ve Medium  ||  b[2][0] -ve Medium   ..        f[0] |  f_d[0] 
                b[0][1] -ve small   || b[1][1] -ve small   ||  b[2][1] -ve small    ..        f[1] |  f_d[1]
                b[0][2] zero        || b[1][2] zero        ||  b[2][2] zero         ..        f[2] |  f_d[2]
                b[0][3] +ve small   || b[1][3] +ve small   ||  b[2][3] +ve small    ..        f[3] |  f_d[3]
                b[0][4] +ve Medium  || b[1][4] +ve Medium  ||  b[2][4] +_ve Medium  ..        f[4] |  f_d[4] 
                
                f_mat is fuzzy fuzzy_matrix
            """
            inputs = [ np.arange(var[0], var[1]+1, 1) for var in self.var_ranges] #step size  = 1, third dimension of b matrix. As of now, an assumption.
            b  = []
            output = [0,0,0,0,0]
            out_final = []
            for i in range(3) :
                    b.append( [membership_f(self.mu[i], inputs[i], a) for a in self.d_mu[i] ])
            # To visualize the membership func. call .. [ visualize_mf(b,inputs)  ]
            
            f ,f_d = error_fuzzify(inputs, b, self.error, self.delta_e)            
            f_mat = fuzzy_matrix(f,f_d)
            output = rule_base(b, f_mat, output)
            print 'output : ', output
            aggregated = np.fmax(output[0], np.fmax(output[1],np.fmax(output[2], np.fmax(output[3], output[4]))))
            out_final = fuzz.defuzz(inputs[2], aggregated, 'centroid')
            out_activation = fuzz.interp_membership(inputs[2], aggregated, out_final)  # for plot
            visualize.visualize_mf(b,inputs,output, out_final, out_activation, aggregated)
            visualize.visualize_output(b, inputs, out_final, out_activation, aggregated)
            plt.show()
Exemple #14
0
def fuzz_system(aftertaste, acidity):
    aftertaste_level_D = fuzz.interp_membership(x_aftertaste, aftertaste_D, aftertaste)
    aftertaste_level_O = fuzz.interp_membership(x_aftertaste, aftertaste_O, aftertaste)
    aftertaste_level_Y = fuzz.interp_membership(x_aftertaste, aftertaste_Y, aftertaste)
    
    # print("membership aftertaste_level_D: ", aftertaste_level_D)
    # print("membership aftertaste_level_O: ", aftertaste_level_O)
    # print("membership aftertaste_level_Y: ", aftertaste_level_Y)
    
    acidity_level_D = fuzz.interp_membership(x_acidity, acidity_D, acidity)
    acidity_level_O = fuzz.interp_membership(x_acidity, acidity_O, acidity)
    acidity_level_Y = fuzz.interp_membership(x_acidity, acidity_Y, acidity)
    
    # print("membership acidity_level_D: ", acidity_level_D)
    # print("membership acidity_level_O: ", acidity_level_O)
    # print("membership acidity_level_Y: ", acidity_level_Y)
    
    active_rule1 = np.fmin(acidity_level_D, aftertaste_level_D)
    active_rule2 = np.fmin(acidity_level_O, aftertaste_level_O)
    active_rule3 = np.fmin(acidity_level_Y, aftertaste_level_Y)
    
    flavor_activation_1 = np.fmin(active_rule1, flavor_D)
    flavor_activation_2 = np.fmin(active_rule2, flavor_O)
    flavor_activation_3 = np.fmin(active_rule3, flavor_Y)
    
    # flavor0 = np.zeros_like(x_flavor)
    aggregated = np.fmax (flavor_activation_1, 
                      np.fmax(flavor_activation_2, flavor_activation_3)) 
    flavor_model = fuzz.defuzz(x_flavor, aggregated, 'centroid')
    # flavor_activation = wash_activation = fuzz.interp_membership(x_flavor, aggregated, flavor_model)
    
    return flavor_model
 def update_reputation(self):
     eps = 0.1
     t = np.ones(self.num_peers) * (1 / self.num_peers)
     t_next = np.ones(self.num_peers) * (1 / self.num_peers)
     dif = eps
     c = 0
     while dif >= eps:
         for v in range(self.num_peers):
             t_v = 0
             s = 0
             for i in self.connected_peers[v]:
                 s += t[i]
             if s != 0:
                 x = 1
                 fuzzy_t_v = self.transactions[v][0][1]
                 for tr in self.transactions[v][1:]:
                     crisp = t[tr[0]] / s
                     r = PeerTrustFuzzyEnv.fuzzy_mul(tr[1], crisp)
                     fuzzy_t_v = PeerTrustFuzzyEnv.fuzzy_add(fuzzy_t_v, r)
                 if self.fuzz_type == 1:
                     pass
                 elif self.fuzz_type == 2:
                     fuzzy_t_v = PeerTrustFuzzyEnv.defuzz_2(fuzzy_t_v)
                 else:
                     raise NotImplementedError
                 f = fuzzy_t_v, np.array([0, 1, 1, 0])
                 t_v = fuzz.defuzz(f[0], f[1], self.defuzz_method)
             t_next[v] = t_v
         d = t_next - t
         dif = np.linalg.norm(d)
         t = t_next
         c += 1
     self.convergence.append(c)
     self.reputation = t_next
def calculate_target_speed(distance_to_go):
    distance, far, medium, close, v_close = set_distance_types()

    speed, fast, medium_fast, slow, stop = set_speed_types()

    # jeżeli daleko to szybko
    distance_level_far = fuzz.interp_membership(distance, far, distance_to_go)
    speed_activation_fast = np.fmin(distance_level_far, fast)

    # jeżeli średnio daleko to średnio szybko
    distance_level_medium = fuzz.interp_membership(distance, medium,
                                                   distance_to_go)
    speed_activation_medium = np.fmin(distance_level_medium, medium_fast)

    # jeżeli blisko to wolno
    distance_level_close = fuzz.interp_membership(distance, close,
                                                  distance_to_go)
    speed_activation_slow = np.fmin(distance_level_close, slow)

    # jeżeli bardzo blisko to stop
    distance_level_v_close = fuzz.interp_membership(distance, v_close,
                                                    distance_to_go)
    speed_activation_stop = np.fmin(distance_level_v_close, stop)

    # agregacja
    aggregated = np.fmax(
        speed_activation_fast,
        np.fmax(speed_activation_medium,
                np.fmax(speed_activation_stop, speed_activation_slow)))

    # obliczenie zdyskretyzowanego wyniku
    return fuzz.defuzz(speed, aggregated, 'mom')
Exemple #17
0
def compute_pi3k(egfr_value, erk_value, time_value, initial_values, mfs):
	"""Rules ---
	if egfr is high and erk is low and time is high then pi3k is high
	if egfr is low or erk is high or time is low then pi3k is low"""

	a1_1 = mfs[0][1][initial_values[0] == egfr_value] #egfr_high[egfr == egfr_value]
	a1_2 = mfs[1][0][ initial_values[1] == erk_value] #erk_low[erk == erk_value]
	a1_3 = mfs[3][1][ initial_values[3] == time_value]

	if( a1_1.size == 0):
		a1_1 = mfs[0][1][ find_closest(initial_values[0], egfr_value)]
	if( a1_2.size == 0):
		a1_2 = mfs[1][0][ find_closest(initial_values[1], erk_value)]
	if( a1_3.size == 0):
		a1_3 = mfs[3][1][ find_closest(initial_values[3], time_value)]

	a1 = min(a1_1 , a1_2, a1_3)
	c1 = np.fmin( np.linspace(a1, a1, 100), mfs[2][1])

	a2_1 = mfs[0][0][ initial_values[0] == egfr_value] #egfr_low[egfr == egfr_value]
	a2_2 = mfs[1][1][ initial_values[1] == erk_value] #erk_high[erk == erk_value]
	a2_3 = mfs[3][0][ initial_values[3] == time_value]

	if( a2_1.size == 0):
		a2_1 = mfs[0][0][ find_closest(initial_values[0], egfr_value)]
	if( a2_2.size == 0):
		a2_2 = mfs[1][1][ find_closest(initial_values[1], erk_value)]
	if( a2_3.size == 0):
		a2_3 = mfs[3][0][ find_closest(initial_values[3], time_value)]

	a2 = max(a2_1 , a2_2, a2_3)
	c2 = np.fmin( np.linspace(a2, a2, 100), mfs[2][0] )

	c_com = np.fmax(c1, c2)
	return fuzz.defuzz(initial_values[2], c_com, 'centroid')
Exemple #18
0
def defuzzify(output_ativations, classif):
    aggregated = 0
    for out in output_ativations:
        aggregated = np.fmax(aggregated, out)

    value = fuzz.defuzz(classif, aggregated, 'mom')
    return value
Exemple #19
0
def compute_akt(pi3k_value, time_value, initial_values, mfs):
	"""Rules-
		If pi3k is high and time is high akt is high
		If pi3k is low or time is low then akt is low"""
	a1_1 = mfs[0][1][initial_values[0] == pi3k_value]
	a1_2 = mfs[2][1][initial_values[2] == time_value]

	if( a1_1.size == 0):
		a1_1 = mfs[0][1][ find_closest(initial_values[0], pi3k_value)]
	if( a1_2.size == 0):
		a1_2 = mfs[2][1][ find_closest(initial_values[2], time_value)]

	a1 = min(a1_1, a1_2)
	c1 = np.fmin( np.linspace(a1, a1, 100), mfs[1][1])

	a2_1 = mfs[0][0][initial_values[0] == pi3k_value]
	a2_2 = mfs[2][0][initial_values[2] == time_value]

	if( a2_1.size == 0):
		a2_1 = mfs[0][0][ find_closest(initial_values[0], pi3k_value)]
	if( a2_2.size == 0):
		a2_2 = mfs[2][0][ find_closest(initial_values[2], time_value)]

	a2 = max(a2_1, a2_2)
	c2 = np.fmin( np.linspace(a2, a2, 100), mfs[1][0])

	c_com = np.fmax(c1,c2)
	return fuzz.defuzz( initial_values[1], c_com, 'centroid')
    def get_output(self, current_temp, target_temp, rate_of_change_per_minute):
        temp_err_in = self.temp_error_category(current_temp, target_temp,
                                               rate_of_change_per_minute)
        print "Temp Error", temp_err_in

        #What is the temperature doing?
        mf_temp_too_cold = temp_err_in['too_cold']
        mf_temp_cold = temp_err_in['cold']
        mf_temp_optimal = temp_err_in['optimal']
        mf_temp_hot = temp_err_in['hot']
        mf_temp_too_hot = temp_err_in['too_hot']

        mf_cooling_quickly = temp_err_in['cooling_quickly']

        #Then:
        when_too_cold = np.fmin(mf_temp_too_cold, self.ho_high)
        when_cold = np.fmin(mf_temp_cold, self.ho_low)
        when_optimal = np.fmin(mf_temp_optimal, self.co_off)
        when_hot = np.fmin(mf_temp_hot, self.co_low)
        when_too_hot = np.fmin(mf_temp_too_hot, self.co_high)

        #If the temperate is temp_hot AND cooling_quickly SET chiller off
        when_hot_and_cooling_quickly = np.fmin(
            np.fmin(mf_temp_hot, mf_cooling_quickly), self.co_off)

        aggregate_membership = np.fmax(
            when_hot_and_cooling_quickly,
            np.fmax(
                when_too_cold,
                np.fmax(when_cold,
                        np.fmax(when_optimal, np.fmax(when_hot,
                                                      when_too_hot)))))
        result = fuzz.defuzz(self.chill_out, aggregate_membership, 'centroid')

        return result
Exemple #21
0
 def defuzzify(self, method):
     """Compute crisp value from aggregated membership function.
     :param method: (str) name of defuzzification method
     """
     assert (not self.value)
     assert (self.aggrmf is not None)
     self.value = fuzz.defuzz(self.x, self.aggrmf, method)
Exemple #22
0
def fuzzy_inference(X, value1, value2, members, rules):
    mem1 = members[0]
    mem2 = members[1]
    mem3 = members[2]

    var1_low = fuzz.interp_membership(X[0], mem1[0], value1)
    var1_med = fuzz.interp_membership(X[0], mem1[1], value1)
    var1_high = fuzz.interp_membership(X[0], mem1[2], value1)
    var1 = [var1_low, var1_med, var1_high]

    var2_low = fuzz.interp_membership(X[1], mem2[0], value2)
    var2_med = fuzz.interp_membership(X[1], mem2[1], value2)
    var2_high = fuzz.interp_membership(X[1], mem2[2], value2)
    var2 = [var2_low, var2_med, var2_high]

    # Apply appropriate rule base
    activation_low, activation_med, activation_high, method = rule_base(
        var1, var2, mem3, rules)
    risk0 = np.zeros_like(X[0])

    # Aggregation of the three output memership functions
    aggregated = np.fmax(activation_low,
                         np.fmax(activation_med, activation_high))

    # Defuzzify aggregation to crisp value
    result = fuzz.defuzz(X[2], aggregated, method)
    return result, risk0, aggregated
    def get_output(self, current_temp, target_temp, rate_of_change_per_minute):
        temp_err_in = self.temp_error_category(current_temp, target_temp, rate_of_change_per_minute)
        print "Temp Error", temp_err_in

        #What is the temperature doing?
        mf_temp_too_cold = temp_err_in['too_cold']
        mf_temp_cold     = temp_err_in['cold']
        mf_temp_optimal  = temp_err_in['optimal']
        mf_temp_hot      = temp_err_in['hot']
        mf_temp_too_hot  = temp_err_in['too_hot']

        mf_cooling_quickly = temp_err_in['cooling_quickly']

        #Then:
        when_too_cold = np.fmin(mf_temp_too_cold, self.ho_high)
        when_cold     = np.fmin(mf_temp_cold, self.ho_low)
        when_optimal  = np.fmin(mf_temp_optimal, self.co_off)
        when_hot      = np.fmin(mf_temp_hot, self.co_low)
        when_too_hot  = np.fmin(mf_temp_too_hot, self.co_high)

        #If the temperate is temp_hot AND cooling_quickly SET chiller off
        when_hot_and_cooling_quickly = np.fmin(np.fmin(mf_temp_hot, mf_cooling_quickly), self.co_off)

        aggregate_membership = np.fmax(when_hot_and_cooling_quickly, np.fmax(when_too_cold, np.fmax(when_cold, np.fmax(when_optimal, np.fmax(when_hot, when_too_hot)))))
        result = fuzz.defuzz(self.chill_out, aggregate_membership, 'centroid')

        return result
Exemple #24
0
def compute_erk_change(raf_value, time_value, initial_values, mfs):
	"""Rules-
		If raf is high and time is high then positive_change_erk is high
		If raf is high1 and time is low then positive_change_erk is low
		If raf is low then positive_change_erk is low
		If raf is low and time is high then negative_change_erk is high
		If raf is low and time is low then negative_change_erk is low"""

	
	#Antecedent 1
	f = interp1d(initial_values[0][0], mfs[0][1])
	a1_1 = f(raf_value) #raf_high[raf == raf_value]
	f = interp1d(initial_values[2], mfs[2][1])
	a1_2 = f(time_value) #time_high[time == time_value]

	a1 = min(a1_1, a1_2)
	c1 = np.fmin( a1, mfs[1][3]) #mfs[1][3] is positive_change_erk_high

	#Antecedent 2
	f = interp1d(initial_values[0][0], mfs[0][6])
	a2_1 = f(raf_value)
	f = interp1d(initial_values[2], mfs[2][0]) #time_low[time == time_value]
	a2_2 = f(time_value)

	a2 = min(a2_1, a2_2)
	c2 = np.fmin( a2, mfs[1][2]) #mfs[1][2] is positive_change_raf_low

	c_com_positive = np.fmax(c1,c2)

	f = interp1d(initial_values[0][0], mfs[0][0])
	a3 = f(raf_value)
	c3 = np.fmin(a3, mfs[1][2])

	c_com_positive = np.fmax(c_com_positive, c3)
	pos_change = fuzz.defuzz( initial_values[1][1], c_com_positive, 'centroid') #initial_values[1][1] is positive_change_erk

	###Negative Change

	#Antecedent 3
	'''f = interp1d(initial_values[0][0], mfs[0][0])
	a3_1 = f(raf_value) #raf_low[raf == raf_value]
	a3_2 = a1_2 #time_high[time == time_value]

	a3 = min(a3_1,a3_2)
	c3 = np.fmin(a3, mfs[1][5]) #mfs[1][3] is negative_change_erk_high

	#Antecedent 4
	a4_1 = a3_1 #raf_low[raf == raf_value]
	a4_2 = a2_2 #time_low[time == time_value]

	a4 = min(a4_1, a4_2)
	c4 = np.fmin(a4, mfs[1][4]) #mfs[1][4] is negative_change_erk_low

	c_com_negative = np.fmax(c3, c4)
	neg_change = fuzz.defuzz(initial_values[1][2], c_com_negative, 'centroid') #initial_values[1][2] is negative_change_erk'''
	
	#print pos_change, neg_change
	#print pos_change
	return pos_change 
Exemple #25
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 defuzz(self):
     """Derive crisp value based on membership of adjective(s)."""
     output_mf, cut_mfs = self.find_memberships()
     if len(cut_mfs) == 0:
         raise ValueError("No terms have memberships.  Make sure you "
                          "have at least one rule connected to this "
                          "variable and have run the rules calculation.")
     return defuzz(self.var.universe, output_mf, self.var.defuzzify_method)
 def defuzz(self):
     """Derive crisp value based on membership of adjective(s)."""
     output_mf, cut_mfs = self.find_memberships()
     if len(cut_mfs) == 0:
         raise ValueError("No terms have memberships.  Make sure you "
                          "have at least one rule connected to this "
                          "variable and have run the rules calculation.")
     return defuzz(self.var.universe, output_mf, self.var.defuzzify_method)
def test_bisector():
    x = np.arange(6)
    mfx = fuzz.trimf(x, [0, 5, 5])
    expected = 3.53553390593274

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

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

    # Test rectangle code path
    mfx = fuzz.trapmf(x, [2, 2, 4, 4])
    assert_allclose(3., fuzz.defuzz(x, mfx, 'bisector'))
Exemple #29
0
def fuzzifier(nota_qualidade, nota_servico):

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

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

    # We need the activation of our fuzzy membership functions at these values.
    # The exact values 6.5 and 9.8 do not exist on our universes...
    # This is what fuzz.interp_membership exists for!
    qual_level_lo = fuzz.interp_membership(x_qual, qual_lo, nota_qualidade)
    qual_level_md = fuzz.interp_membership(x_qual, qual_md, nota_qualidade)
    qual_level_hi = fuzz.interp_membership(x_qual, qual_hi, nota_qualidade)

    serv_level_lo = fuzz.interp_membership(x_serv, serv_lo, nota_servico)
    serv_level_md = fuzz.interp_membership(x_serv, serv_md, nota_servico)
    serv_level_hi = fuzz.interp_membership(x_serv, serv_hi, nota_servico)

    # Now we take our rules and apply them. Rule 1 concerns bad food OR service.
    # The OR operator means we take the maximum of these two.
    active_rule1 = np.fmax(qual_level_lo, serv_level_lo)

    # Now we apply this by clipping the top off the corresponding output
    # membership function with `np.fmin`
    tip_activation_lo = np.fmin(active_rule1, tip_lo)  # removed entirely to 0

    # For rule 2 we connect acceptable service to medium tipping
    tip_activation_md = np.fmin(serv_level_md, tip_md)

    # For rule 3 we connect high service OR high food with high tipping
    active_rule3 = np.fmax(qual_level_hi, serv_level_hi)
    tip_activation_hi = np.fmin(active_rule3, tip_hi)
    tip0 = np.zeros_like(x_tip)

    # Aggregate all three output membership functions together
    aggregated = np.fmax(tip_activation_lo,
                         np.fmax(tip_activation_md, tip_activation_hi))

    # Calculate defuzzified result
    # ----------THIS IS THE ANWSER------------------
    tip = fuzz.defuzz(x_tip, aggregated, 'centroid')
    #------------------------------------------------

    return tip
Exemple #30
0
def compute_akt_change(pi3k_value, time_value, initial_values, mfs):
	"""Rules-
		If pi3k is high and time is high then positive_change_akt is high
		If pi3k is high1 and time is low then positive_change_akt is low
		If pi3k is low then positive_change_pi3k is low
		If pi3k is low and time is high then negative_change_akt is high
		If pi3k is low and time is low then negative_change_akt is low"""

	###Positive Change
	#Antecedent 1
	f = interp1d(initial_values[0][0], mfs[0][1])	
	a1_1 = f(pi3k_value) #pi3k_high[pi3k == pi3k_value]
	f = interp1d(initial_values[2], mfs[2][1])
	a1_2 = f(time_value) #time_high[time == time_value]

	a1 = min(a1_1, a1_2)
	c1 = np.fmin(a1, mfs[1][3]) #positive_change_akt is high

	#Antecedent 2
	f = interp1d(initial_values[0][0], mfs[0][6])
	a2_1 = f(pi3k_value) #pi3k_high[pi3k == pi3k_value]
	f = interp1d(initial_values[2], mfs[2][0])
	a2_2 = f(time_value) #time_low[time == time_value]

	a2 = min(a2_1, a2_2)
	c2 = np.fmin( a2, mfs[1][2]) #positive_change_akt is low

	c_com_positive = np.fmax(c1,c2)

	f = interp1d(initial_values[0][0], mfs[0][0])
	a3 = f(pi3k_value)
	c3 = np.fmin(a3, mfs[1][2])
	c_com_positive = np.fmax(c_com_positive, c3)
	pos_change = fuzz.defuzz( initial_values[1][1], c_com_positive, 'centroid') #initial_values[1][1] is positive_change_akt

	###Negative Change

	#Antecedent 3
	'''f = interp1d(initial_values[0][0], mfs[0][0])
	a3_1 = f(pi3k_value) #pi3k_low[pi3k == pi3k_value]
	a3_2 = a1_2 #time_high[time == time_value]

	a3 = min(a3_1, a3_2)
	c3 = np.fmin(a3, mfs[1][5]) #mfs[1][5] is negative_change_akt_high

	#Antecedent 4
	a4_1 = a3_1 #pi3k_low[pi3k == pi3k_value]
	a4_2 = a2_2 #time_low[time == time_value]

	a4 = min(a4_1, a4_2)
	c4 = np.fmin(a4, mfs[1][4]) #mfs[1][4] is negative_change_akt_low

	c_com_negative = np.fmax(c3, c4)
	neg_change = fuzz.defuzz(initial_values[1][2], c_com_negative, 'centroid') #initial_values[1][2] is negative_change_akt'''

	return pos_change 
Exemple #31
0
	def fuzzy_controller(self):
		x_vel = np.arange(-3.5, 2.1, 0.1)
		x_dis = np.arange(-80, 301, 1)
		x_acc  = np.arange(-0.5, 0.6, 0.1)


		vel_slow = fuzz.trimf(x_vel, [-3.5, -3.5, 0])
		vel_ok = fuzz.trimf(x_vel, [-3.5, 0, 2.0])
		vel_fast = fuzz.trimf(x_vel, [0, 2.0, 2.1])
		dis_close = fuzz.trimf(x_dis, [-80, -80, 0])
		dis_ok = fuzz.trimf(x_dis, [-80, 0, 300])
		dis_far = fuzz.trimf(x_dis, [0, 300, 300])
		decelerate = fuzz.trimf(x_acc, [-1, -0.5, 0])
		const = fuzz.trimf(x_acc, [-0.5, 0, 0.5])
		accelerate = fuzz.trimf(x_acc, [0, 0.5, 0.5])

		dis_level_close = fuzz.interp_membership(x_dis, dis_close, self.distance)
		dis_level_ok= fuzz.interp_membership(x_dis, dis_ok, self.distance)
		dis_level_far = fuzz.interp_membership(x_dis, dis_far, self.distance)

		vel_level_slow = fuzz.interp_membership(x_vel, vel_slow, self.delta_speed)
		vel_level_ok= fuzz.interp_membership(x_vel, vel_ok, self.delta_speed)
		vel_level_fast = fuzz.interp_membership(x_vel, vel_fast, self.delta_speed)

		rule1= np.fmin(dis_level_close, vel_level_slow)
		rule2= np.fmin(dis_level_close, vel_level_ok)
		rule3= np.fmin(dis_level_close, vel_level_fast)
		rule4= np.fmin(dis_level_ok, vel_level_slow)
		rule5= np.fmin(dis_level_ok, vel_level_ok)
		rule6= np.fmin(dis_level_ok, vel_level_fast)
		rule7= np.fmin(dis_level_far, vel_level_slow)
		rule8= np.fmin(dis_level_far, vel_level_ok)
		rule9= np.fmin(dis_level_far, vel_level_fast)

		decelerate_tot= max(rule1, rule2, rule3, rule6, rule9)
		const_tot= max(rule4, rule5, rule8)
		accelerate_tot = rule7

		decelerate_activation= np.fmin(decelerate_tot, decelerate)
		const_activation= np.fmin(const_tot, const)
		accelerate_activation= np.fmin(accelerate_tot, accelerate)
		
		tip0 = np.zeros_like(x_acc)



		####################################################################

		# Aggregate all three output membership functions together
		aggregated = np.fmax(decelerate_activation, np.fmax(const_activation, accelerate_activation))
		#print (aggregated)
		#print("Fuzzy")
		# Calculate defuzzified result
		acc = fuzz.defuzz(x_acc, aggregated, 'centroid')
		
		self.acc_activation = fuzz.interp_membership(x_acc, aggregated, acc)  # for plot		
def defuzzy_fast(slice) :
    speed_range = np.arange(DOMAIN[0],DOMAIN[1],0.01)
    speed_high_fx = fuzz.trimf(speed_range,[SPEED[3],SPEED[4],SPEED[5]])
    # print(speed_high_fx)

    speed_slice = np.fmin(slice,speed_high_fx)

    defuzzy_value  = fuzz.defuzz(speed_range, speed_slice ,'centroid')

    return defuzzy_value
Exemple #33
0
def calculate_erk(raf_mfs, erk_mfs, erk, raf_index):
	a1 = raf_mfs[0][raf_index]
	c1 = np.fmin(a1, erk_mfs[0])
	a2 = raf_mfs[1][raf_index]
	c2 = np.fmin(a2, erk_mfs[1])
	c_com = np.fmax(c1, c2)
	try:
		erk_val = fuzz.defuzz(erk, c_com, 'centroid')
	except AssertionError as e:
		erk_val = 0
	return erk_val
Exemple #34
0
def calculate_egfr(time_mfs, egfr_mfs, egfr, time_index):
	a1 = time_mfs[0][time_index]
	c1 = np.fmin(a1, egfr_mfs[0])
	a2 = time_mfs[1][time_index]
	c2 = np.fmin(a2, egfr_mfs[1])
	c_com = np.fmax(c1, c2)
	try:
		egfr_val = fuzz.defuzz(egfr, c_com, 'centroid')
	except AssertionError as e:
		egfr_val = 0
	return egfr_val
Exemple #35
0
def calaculate_akt(pi3k_mfs, akt_mfs, akt, pi3k_index):
	a1 = pi3k_mfs[0][pi3k_index]
	c1 = np.fmin(a1, akt_mfs[0])
	a2 = pi3k_mfs[1][pi3k_index]
	c2 = np.fmin(a2, akt_mfs[1])
	c_com = np.fmax(c1, c2)
	try:
		akt_val = fuzz.defuzz(akt, c_com, 'centroid')
	except AssertionError as e:
		akt_val = 0
	return akt_val
Exemple #36
0
    def Centroid(self, domain: np.ndarray, aggregatedVariable: np.ndarray) -> float:
        if not isinstance(domain, np.ndarray):
            raise TypeError("domain")
        if not isinstance(aggregatedVariable, np.ndarray):
            raise TypeError("aggregatedVariable")

        if len(domain) != len(aggregatedVariable):
            raise ValueError("len(domain) != len(aggregatedVariable)")

        output = fuzz.defuzz(domain, aggregatedVariable, 'centroid')
        return output
Exemple #37
0
def defuzzy(domain, newConsequentMFs):
    """Calculates the output value with the centroid based method. With the
    assumptions made, it will depens only on the degrees of activation and
    on the centroids of the original MFs."""

    # Sum all the activated MFs in order to obtain one aggregated MF.
    aggregated = np.sum(newConsequentMFs, axis=0)

    # Find the output value
    output = fuzz.defuzz(domain, aggregated, 'centroid')
    return output
Exemple #38
0
def next_action(t, b, s):
    """
    ¦  t: target angle
    ¦  b: ball angle
    ¦  s: spin
    """
    output = fuzz.defuzz(angle_dmn, output_function(t, b, s), 'centroid')
    outputrad = math.radians(output)
    cos_output = math.cos(outputrad)
    sin_output = math.sin(outputrad)
    return cos_output, sin_output
Exemple #39
0
def next_action(t, b, s):
    """
    ¦  t: target angle
    ¦  b: ball angle
    ¦  s: spin
    """
    output = fuzz.defuzz(angle_dmn, output_function(t, b, s), 'centroid')
    outputrad = math.radians(output)
    cos_output = math.cos(outputrad)
    sin_output = math.sin(outputrad)
    return cos_output, sin_output
Exemple #40
0
    def run_system(self, input_list, output_key, TESTMODE=False):
        """
        Runs the fuzzy system for a single output
        ------INPUTS------
        input_list : dict
            dict of inputs {'input1':value, 'input2':value, ...} 
        output_key : string
            string key of output to calculate
        TESTMODE : int
            testmode flag (1 = On)
        ------OUTPUTS------ 
        """
        self.TESTMODE = TESTMODE
        outs = []
        for rule in self.rulebase:   #iterate over rulebase
            if TESTMODE: 
                print '------------------------------------------------------------------------'
                print 'TRANSLATING RULE: ', rule.rule_id
                  
            #break apart antecedent and consequent
            if_i = rule.rule_list.index('IF')   
            then_i = rule.rule_list.index('THEN')
            rule_ant = copy.deepcopy(rule.rule_list[if_i+1:then_i])                         #get the rule antecedent
            rule_con = copy.deepcopy(rule.rule_list[then_i+1:len(rule.rule_list)+1])[0]     #get the rule consequent
            
            if rule_con[0] == output_key:               #only follow rule if it applies to given output 

                fs = self.rule_recurse(rule_ant, input_list, TESTMODE)[0]   #get firing strength

                if TESTMODE: print 'FIRING STREGTH, RULE', rule.rule_id, ':', fs
            
                output = copy.deepcopy(self.outputs[rule_con[0]].MFs[rule_con[2]]) #get output
                output[1] = self.implicate(fs, output)#use implication to get fuzzy consequent
                
                if TESTMODE: self.implicatedOutputs[rule.rule_id][self.outputs[rule_con[0]].name] = copy.deepcopy(output)
                    
                outs.append(output)
        
        #aggregate outputs
        if len(outs) > 0: 
            output_result = self.aggregate(outs)    #aggregate outputs if there are outputs
            
            if self.defuzz <> None: #defuzzify outputs
                output_result = fuzz.defuzz(output_result[0], output_result[1], self.defuzz)
        else:
            m1 = self.outputs[output_key].data_range[0]         #get output min
            m2 = self.outputs[output_key].data_range[1]         #get output max
            x1 = np.arange(m1,m2,0.01)                          #get x range
            output_result = [x1, np.asarray([0 for i in range(len(x1))])]   #return mf function of zeros
            
            if self.defuzz <> None: #defuzzify outputs
                output_result = [0,0]
            
        return output_result
    def get_extension(self, arriving_green_light_car, behind_red_light_car, extension_count):
        behind_red_light_level_few = fuzz.interp_membership(self.x_behind_red_light, self.behind_red_light_few, behind_red_light_car)
        behind_red_light_level_small = fuzz.interp_membership(self.x_behind_red_light, self.behind_red_light_small, behind_red_light_car)
        behind_red_light_level_medium = fuzz.interp_membership(self.x_behind_red_light, self.behind_red_light_medium, behind_red_light_car)
        behind_red_light_level_many = fuzz.interp_membership(self.x_behind_red_light, self.behind_red_light_many, behind_red_light_car)

        arriving_green_light_level_few = fuzz.interp_membership(self.x_arriving_green_light, self.arriving_green_light_few, arriving_green_light_car)
        arriving_green_light_level_small = fuzz.interp_membership(self.x_arriving_green_light, self.arriving_green_light_small, arriving_green_light_car)
        arriving_green_light_level_medium = fuzz.interp_membership(self.x_arriving_green_light, self.arriving_green_light_medium, arriving_green_light_car)
        arriving_green_light_level_many = fuzz.interp_membership(self.x_arriving_green_light, self.arriving_green_light_many, arriving_green_light_car)

        # Rule 1: If Arrival is few then Extension is zero.
        # Rule 2: If Arrival is small AND Queue is (few OR small) then Extension is short.
        # Rule 3: If Arrival is small AND Queue is (medium OR many) then Extension is zero.
        # Rule 4: If Arrival is medium AND Queue is (few OR small) then Extension is medium.
        # Rule 5: If Arrival is medium AND Queue is (medium OR many) then Extension is short.
        # Rule 6: If Arrival is many AND Queue is few then Extension is long.
        # Rule 7: If Arrival is many AND Queue is (small OR medium) then Extension is medium.
        # Rule 8: If Arrival is few AND Queue is many then Extension is short.

        rule1 = arriving_green_light_level_few
        rule2 = np.fmin(arriving_green_light_level_small,
                        np.fmax(behind_red_light_level_few, behind_red_light_level_small))
        rule3 = np.fmin(arriving_green_light_level_small,
                        np.fmax(behind_red_light_level_medium, behind_red_light_level_many))
        rule4 = np.fmin(arriving_green_light_level_medium,
                        np.fmax(behind_red_light_level_few, behind_red_light_level_small))
        rule5 = np.fmin(arriving_green_light_level_medium,
                        np.fmax(behind_red_light_level_medium, behind_red_light_level_many))
        rule6 = np.fmin(arriving_green_light_level_many, behind_red_light_level_few)
        rule7 = np.fmin(arriving_green_light_level_many,
                        np.fmax(behind_red_light_level_small, behind_red_light_level_medium))
        rule8 = np.fmin(arriving_green_light_level_many, behind_red_light_level_many)

        if extension_count == 0:
            extension_activation_zero = np.fmin(np.fmax(rule1, rule3), self.extension_zero)
            extension_activation_short = np.fmin(np.fmax(rule2, np.fmax(rule5, rule8)), self.extension_short)
            extension_activation_medium = np.fmin(np.fmax(rule4, rule7), self.extension_medium)
            extension_activation_long = np.fmin(rule6, self.extension_long)

        else:
            extension_activation_zero = np.fmin(
                np.fmax(rule1, np.fmax(rule2, np.fmax(rule3, np.fmax(rule5, rule8)))), self.extension_zero)
            extension_activation_short = np.fmin(np.fmax(rule4, rule7), self.extension_short)
            extension_activation_medium = np.fmin(rule6, self.extension_medium)
            extension_activation_long = np.fmin(0, self.extension_long)

        aggregated = np.fmax(extension_activation_zero, np.fmax(extension_activation_short,
                                                                np.fmax(extension_activation_medium,
                                                                        extension_activation_long)))

        return fuzz.defuzz(self.x_extension, aggregated, 'centroid')
Exemple #42
0
def rule_actividad(value, graficar=False):

    # recibe los datos para poder seguir el proceso difuso para encontrar la pertenencia
    # retorna el valor al que pertenece en la clase segun la hora
    mf_actividad = generar_actividad(False)
    mf_calorico = generar_calorico(False)

    # se usa para encontrar los grados de pertenencia del valor, borrificacion
    actividad_nivel_rest = fuzz.interp_membership(mf_actividad['intensity'],
                                                  mf_actividad['rest'], value)
    actividad_nivel_std = fuzz.interp_membership(mf_actividad['intensity'],
                                                 mf_actividad['active'], value)
    actividad_nivel_work = fuzz.interp_membership(mf_actividad['intensity'],
                                                  mf_actividad['workout'],
                                                  value)

    # regla: si rest -> low
    rest_activation = np.fmin(actividad_nivel_rest, mf_calorico['low'])
    # regla: si active -> std
    active_activation = np.fmin(actividad_nivel_std, mf_calorico['standard'])
    # regla: si workout -> high
    workout_activation = np.fmin(actividad_nivel_work, mf_calorico['high'])

    # deborrificacion
    agregado = np.fmax(rest_activation,
                       np.fmax(active_activation, workout_activation))
    caloric = fuzz.defuzz(mf_calorico['caloric'], agregado, 'centroid')

    # # graficar
    # if graficar:
    #     select_caloric = fuzz.interp_membership(mf_calorico['caloric'], agregado, caloric)
    #     caloric0 = np.zeros_like(mf_calorico['caloric'])
    #     fig, ax0 = plt.subplots(figsize=(8, 3))
    #
    #     ax0.plot(mf_calorico['caloric'], mf_calorico['low'], 'b', linewidth=0.5, linestyle='--', label='Low')
    #     ax0.plot(mf_calorico['caloric'], mf_calorico['standard'], 'g', linewidth=0.5, linestyle='--', label='Standard')
    #     ax0.plot(mf_calorico['caloric'], mf_calorico['high'], 'r', linewidth=0.5, linestyle='--', label='High')
    #     ax0.fill_between(mf_calorico['caloric'], caloric0, agregado, facecolor='Orange', alpha=0.7)
    #     ax0.plot([caloric, caloric], [0, select_caloric], 'k', linewidth=1.5, alpha=0.9)
    #     ax0.set_title('Dish Classification and Result (line)')
    #     ax0.legend()
    #     # Turn off top/right axes
    #     for ax in (ax0,):
    #         ax.spines['top'].set_visible(False)
    #         ax.spines['right'].set_visible(False)
    #         ax.get_xaxis().tick_bottom()
    #         ax.get_yaxis().tick_left()
    #
    #     plt.tight_layout()
    #     #fig.savefig('graphs/result_calorico.png', bbox_inches='tight')
    #
    return caloric, "caloric"
Exemple #43
0
def rule_hora(hour, graficar=False):

    # recibe los datos para poder seguir el proceso difuso para encontrar la pertenencia
    # retorna el valor al que pertenece en la clase segun la hora
    mf_hora = generar_hora(False)
    mf_clase = generar_clase(False)

    # se usa para encontrar los grados de pertenencia del valor, borrificacion
    hora_nivel_morn = fuzz.interp_membership(mf_hora['horario'],
                                             mf_hora['morning'], hour)
    hora_nivel_aft = fuzz.interp_membership(mf_hora['horario'],
                                            mf_hora['afternoon'], hour)
    hora_nivel_eve = fuzz.interp_membership(mf_hora['horario'],
                                            mf_hora['evening'], hour)

    # regla: si manana -> desayuno
    breakfast_activation = np.fmin(hora_nivel_morn, mf_clase['breakfast'])
    # regla: si medio dia -> almuerzo
    lunch_activation = np.fmin(hora_nivel_aft, mf_clase['lunch'])
    # regla: si medio dia -> almuerzo
    dinner_activation = np.fmin(hora_nivel_eve, mf_clase['dinner'])

    # deborrificacion
    agregado = np.fmax(breakfast_activation,
                       np.fmax(lunch_activation, dinner_activation))
    clase = fuzz.defuzz(mf_clase['clase'], agregado, 'centroid')

    # graficar
    # if graficar:
    #     select_clase = fuzz.interp_membership(mf_clase['clase'], agregado, clase)
    #     clase0 = np.zeros_like(mf_clase['clase'])
    #     fig, ax0 = plt.subplots(figsize=(8, 3))
    #
    #     ax0.plot(mf_clase['clase'], mf_clase['breakfast'], 'b', linewidth=0.5, linestyle='--', label='Breakfast')
    #     ax0.plot(mf_clase['clase'], mf_clase['lunch'], 'g', linewidth=0.5, linestyle='--', label='Lunch')
    #     ax0.plot(mf_clase['clase'], mf_clase['dinner'], 'r', linewidth=0.5, linestyle='--', label='Dinner')
    #     ax0.fill_between(mf_clase['clase'], clase0, agregado, facecolor='Orange', alpha=0.7)
    #     ax0.plot([clase, clase], [0, select_clase], 'k', linewidth=1.5, alpha=0.9)
    #     ax0.set_title('Dish Classification and Result (line)')
    #     ax0.legend()
    #     # Turn off top/right axes
    #     for ax in (ax0,):
    #         ax.spines['top'].set_visible(False)
    #         ax.spines['right'].set_visible(False)
    #         ax.get_xaxis().tick_bottom()
    #         ax.get_yaxis().tick_left()
    #
    #     plt.tight_layout()
    #     #fig.savefig('graphs/result_clase.png', bbox_inches='tight')
    #
    return clase, "clase"
Exemple #44
0
def make_decision(market_value, location, assets, income, interest, verbose=0):
    credit = apply_all_rules(market_value, location, assets, income, interest,
                             verbose)
    # defuzzification with mean of maximum
    defuzz_credit = fuzz.defuzz(x_credit, credit, 'mom')
    max_n = np.max(credit)

    if (verbose == 1):
        plt.rcParams["figure.figsize"] = 15, 5
        plt.plot(x_credit,
                 credit_very_low,
                 'c',
                 linestyle='--',
                 linewidth=1.5,
                 label='Very Low')
        plt.plot(x_credit,
                 credit_low,
                 'b',
                 linestyle='--',
                 linewidth=1.5,
                 label='Low')
        plt.plot(x_credit,
                 credit_medium,
                 'g',
                 linestyle='--',
                 linewidth=1.5,
                 label='Medium')
        plt.plot(x_credit,
                 credit_high,
                 'r',
                 linestyle='--',
                 linewidth=1.5,
                 label='High')
        plt.plot(x_credit,
                 credit_very_high,
                 'y',
                 linestyle='--',
                 linewidth=1.5,
                 label='Very High'), plt.title("Credit Value $ x10^3")
        plt.legend()

        plt.fill_between(x_credit, credit, color='b')
        plt.ylim(-0.1, 1.1)
        plt.grid(True)

        plt.plot(defuzz_credit, max_n, 'X', color='r')
        plt.show()

    print "Output: ", defuzz_credit, "x10^3 $"
    return defuzz_credit
Exemple #45
0
    def run(self):

        """ 
        Finds appropriate value of pid gains

        NO arguments : 

        inputs : List to contain discrete values of io variables in their range (step size = 1) for plotting. i.e, x axis
            inputs[0] =  ERROR AXIS          ., so stores all possible error values
            inputs[1] =  DEL_ERROR AXIS      .,     ,,
            inputs[2] =  CONTROL_OUTPUT AXIS .,     ,,
                
        b : 3d list, each layer (i.e, 2d list) contains 1d lists of y-values (in x of step size 1) of a particular fuzzy 
            subset of a particular i/o variable 
        
        muval_de, muval_e: Stores membership value of error and delta_error for each fuzzy subsets

            ERROR                  DEL_ERROR               CONTROL_OUTPUT         m_value for crisp e and delta_e values

            b[0][0] -ve Medium  || b[1][0] -ve Medium  ||  b[2][0] -ve Medium   ..        muval[0] |  muval_d[0] 
            b[0][1] -ve small   || b[1][1] -ve small   ||  b[2][1] -ve small    ..        muval[1] |  muval_d[1]
            b[0][2] zero        || b[1][2] zero        ||  b[2][2] zero         ..        muval[2] |  muval_d[2]
            b[0][3] +ve small   || b[1][3] +ve small   ||  b[2][3] +ve small    ..        muval[3] |  muval_d[3]
            b[0][4] +ve Medium  || b[1][4] +ve Medium  ||  b[2][4] +_ve Medium  ..        muval[4] |  muval_d[4] 
            
        f_mat is a 2d matrix containing rule strengths
        """
        inputs = [ np.arange(var[0], var[1]+1, 1) for var in self.io_ranges]
        b  = []
        for i in range(3) :
                b.append( [membership_f(self.mf_types[i], inputs[i], a) for a in self.f_ssets[i] ])

        # visualize.visualize_mf(b,inputs)
        # fuzzify Error and delta error to obtain their membership values for corr. fuzzy subsets
        muval_e  = fuzzify(inputs[0], b[0], self.error)
        muval_de = fuzzify(inputs[1], b[1], self.delta_e) 

        # print 'muval_e:', muval_e
        # print 'muval_de:', muval_de
        # Obtain the rule strength matrix
        f_mat = fuzzy_matrix(muval_e, muval_de)
        #  obtian the y value clipped by output activation for output fuzzy subsets
        output = rule_base(b, f_mat)
        aggregated = np.fmax(output[0], np.fmax(output[1],np.fmax(output[2], np.fmax(output[3], output[4]))))
        out_final  = fuzz.defuzz(inputs[2], aggregated, 'centroid')
        print "output:",out_final
        # plotting final output
        visualize.visualize_output(b, inputs, output, out_final, aggregated)
        plt.show()
Exemple #46
0
def rule_actividad(value, graficar=False):

    # recibe los datos para poder seguir el proceso difuso para encontrar la pertenencia
    # retorna el valor al que pertenece en la clase segun la hora
    mf_actividad = generar_actividad(False)
    mf_calorico = generar_calorico(False)

    # se usa para encontrar los grados de pertenencia del valor, borrificacion
    actividad_nivel_rest = fuzz.interp_membership(mf_actividad['intensity'], mf_actividad['rest'], value)
    actividad_nivel_std = fuzz.interp_membership(mf_actividad['intensity'], mf_actividad['active'], value)
    actividad_nivel_work = fuzz.interp_membership(mf_actividad['intensity'], mf_actividad['workout'], value)

    # regla: si rest -> low
    rest_activation = np.fmin(actividad_nivel_rest, mf_calorico['low'])
    # regla: si active -> std
    active_activation = np.fmin(actividad_nivel_std, mf_calorico['standard'])
    # regla: si workout -> high
    workout_activation = np.fmin(actividad_nivel_work, mf_calorico['high'])

    # deborrificacion
    agregado = np.fmax(rest_activation, np.fmax(active_activation, workout_activation))
    caloric = fuzz.defuzz(mf_calorico['caloric'], agregado, 'centroid')


    # # graficar
    # if graficar:
    #     select_caloric = fuzz.interp_membership(mf_calorico['caloric'], agregado, caloric)
    #     caloric0 = np.zeros_like(mf_calorico['caloric'])
    #     fig, ax0 = plt.subplots(figsize=(8, 3))
    #
    #     ax0.plot(mf_calorico['caloric'], mf_calorico['low'], 'b', linewidth=0.5, linestyle='--', label='Low')
    #     ax0.plot(mf_calorico['caloric'], mf_calorico['standard'], 'g', linewidth=0.5, linestyle='--', label='Standard')
    #     ax0.plot(mf_calorico['caloric'], mf_calorico['high'], 'r', linewidth=0.5, linestyle='--', label='High')
    #     ax0.fill_between(mf_calorico['caloric'], caloric0, agregado, facecolor='Orange', alpha=0.7)
    #     ax0.plot([caloric, caloric], [0, select_caloric], 'k', linewidth=1.5, alpha=0.9)
    #     ax0.set_title('Dish Classification and Result (line)')
    #     ax0.legend()
    #     # Turn off top/right axes
    #     for ax in (ax0,):
    #         ax.spines['top'].set_visible(False)
    #         ax.spines['right'].set_visible(False)
    #         ax.get_xaxis().tick_bottom()
    #         ax.get_yaxis().tick_left()
    #
    #     plt.tight_layout()
    #     #fig.savefig('graphs/result_calorico.png', bbox_inches='tight')
    # 
    return caloric, "caloric"
def game_type(player, comp):
    """ A fuzzy algorithm to define the offensiveness and/or 
    defensiveness of the game. Determines how aggressive the fuzzy 
    player is"""

    score_diff = float(player-comp)
    ### Inputs ###
    # Input Variable Domain
    score = np.arange(-21, 21, 1)
    
    # Input membership functions
    score_ahead = fuzz.gaussmf(score, -21, 8.823)
    score_tied = fuzz.gaussmf(score, 0, 9.012)
    score_behind = fuzz.gaussmf(score, 21, 8.823)

    # Fuzzifying the current input
    def score_category(sc):
        score_cat_ahead = fuzz.interp_membership(score, score_ahead, sc)
        score_cat_tied = fuzz.interp_membership(score, score_tied, sc)
        score_cat_behind = fuzz.interp_membership(score, score_behind, sc)
        return dict(ahead = score_cat_ahead, tied = score_cat_tied, behind = score_cat_behind)

    ### Outputs ###
    # Output Variable Domain
    game = np.arange(0, 1, 1)

    # Output membership functions
    game_defensive = fuzz.gaussmf(game, 0, 0.162899)
    game_offensive = fuzz.gauss2mf(game, 0.30291, 0.090976, 1.31, 0.416)

    ### Rules ###
    current_score = score_category(score_diff)

    # Going to make this a hard opponent, so if the score is tied or 
    # if the human is winning, it will play offensively
    rule1 = current_score['ahead']
    rule2 = np.fmax(current_score['tied'], current_score['behind'])

    # Apply implication operator (Mamdami)
    imp1 = np.fmin(rule1, game_defensive)
    imp2 = np.fmin(rule2, game_offensive)

    # Aggregate outputs using max
    aggregate_membership = np.fmax(imp1, imp2)

    # Defuzzify using centroid and return the result
    result_game = fuzz.defuzz(game, aggregate_membership, 'centroid')
    return result_game
Exemple #48
0
def calculate_pi3k(egfr_mfs, erk_mfs, pi3k_mfs, pi3k, egfr_index, erk_index):
	a1 =  egfr_mfs[0][egfr_index]
	c1 = np.fmin(a1, pi3k_mfs[0])
	a2 = erk_mfs[1][erk_index]
	c2 = np.fmin(a2, pi3k_mfs[0])
	c_com = np.fmax(c1, c2)
	a3_1 = egfr_mfs[1][egfr_index]
	a3_2 = erk_mfs[0][erk_index]
	a3 = min(a3_1, a3_2)
	c3 = np.fmin(a3, pi3k_mfs[1])
	c_com = np.fmax(c_com, c3)
	try:
		pi3k_val = fuzz.defuzz(pi3k, c_com, 'centroid')
	except AssertionError as e:
		pi3k_val = 0
	return pi3k_val
Exemple #49
0
def calculate_raf(egfr_mfs, akt_mfs, raf_mfs, raf, egfr_index, akt_index):
	a1 =  egfr_mfs[1][egfr_index]
	c1 = np.fmin(a1, raf_mfs[1])
	a2 = akt_mfs[1][akt_index]
	c2 = np.fmin(a2, raf_mfs[1])
	c_com = np.fmax(c1, c2)
	a3_1 = egfr_mfs[0][egfr_index]
	a3_2 = akt_mfs[0][akt_index]
	a3 = min(a3_1, a3_2)
	c3 = np.fmin(a3, raf_mfs[0])
	c_com = np.fmax(c_com, c3)
	try:
		raf_val = fuzz.defuzz(raf, c_com, 'centroid')
	except AssertionError as e:
		raf_val = 0
	return raf_val
 def defuzz(self):
     """Derive crisp value based on membership of adjective(s)."""
     ups_universe, output_mf, cut_mfs = self.find_memberships()
     if len(cut_mfs) == 0:
         raise ValueError("No terms have memberships.  Make sure you "
                          "have at least one rule connected to this "
                          "variable and have run the rules calculation.")
     try:
         return defuzz(ups_universe, output_mf,
                       self.var.defuzzify_method)
     except AssertionError:
         raise ValueError("Crisp output cannot be calculated, likely "
                          "because the system is too sparse. Check to "
                          "make sure this set of input values will "
                          "activate at least one connected Term in each "
                          "Antecedent via the current set of Rules.")
Exemple #51
0
def rule_hora(hour, graficar=False):

    # recibe los datos para poder seguir el proceso difuso para encontrar la pertenencia
    # retorna el valor al que pertenece en la clase segun la hora
    mf_hora = generar_hora(False)
    mf_clase = generar_clase(False)

    # se usa para encontrar los grados de pertenencia del valor, borrificacion
    hora_nivel_morn = fuzz.interp_membership(mf_hora['horario'], mf_hora['morning'], hour)
    hora_nivel_aft = fuzz.interp_membership(mf_hora['horario'], mf_hora['afternoon'], hour)
    hora_nivel_eve = fuzz.interp_membership(mf_hora['horario'], mf_hora['evening'], hour)

    # regla: si manana -> desayuno
    breakfast_activation = np.fmin(hora_nivel_morn, mf_clase['breakfast'])
    # regla: si medio dia -> almuerzo
    lunch_activation = np.fmin(hora_nivel_aft, mf_clase['lunch'])
    # regla: si medio dia -> almuerzo
    dinner_activation = np.fmin(hora_nivel_eve, mf_clase['dinner'])

    # deborrificacion
    agregado = np.fmax(breakfast_activation, np.fmax(lunch_activation, dinner_activation))
    clase = fuzz.defuzz(mf_clase['clase'], agregado, 'centroid')

    # graficar
    # if graficar:
    #     select_clase = fuzz.interp_membership(mf_clase['clase'], agregado, clase)
    #     clase0 = np.zeros_like(mf_clase['clase'])
    #     fig, ax0 = plt.subplots(figsize=(8, 3))
    #
    #     ax0.plot(mf_clase['clase'], mf_clase['breakfast'], 'b', linewidth=0.5, linestyle='--', label='Breakfast')
    #     ax0.plot(mf_clase['clase'], mf_clase['lunch'], 'g', linewidth=0.5, linestyle='--', label='Lunch')
    #     ax0.plot(mf_clase['clase'], mf_clase['dinner'], 'r', linewidth=0.5, linestyle='--', label='Dinner')
    #     ax0.fill_between(mf_clase['clase'], clase0, agregado, facecolor='Orange', alpha=0.7)
    #     ax0.plot([clase, clase], [0, select_clase], 'k', linewidth=1.5, alpha=0.9)
    #     ax0.set_title('Dish Classification and Result (line)')
    #     ax0.legend()
    #     # Turn off top/right axes
    #     for ax in (ax0,):
    #         ax.spines['top'].set_visible(False)
    #         ax.spines['right'].set_visible(False)
    #         ax.get_xaxis().tick_bottom()
    #         ax.get_yaxis().tick_left()
    #
    #     plt.tight_layout()
    #     #fig.savefig('graphs/result_clase.png', bbox_inches='tight')
    #
    return clase, "clase"
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')
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')
Exemple #54
0
def compute_egfr(egf_value, hrg_value, time_value, initial_values, mfs ):	

	"""Rules---
	If egf is high or hrg is high and time is high then egfr is high
	if egf is low and hrg is low or time is low then egfr is low"""

	a1_1 = mfs[0][1][initial_values[0] == egf_value] #egf_high[egf == egf_value]
	a1_2 = mfs[1][1][ initial_values[1] == hrg_value ] #hrg_high[hrg == hrg_value]
	a1_3 = mfs[3][1][ initial_values[3] == time_value]

	if( a1_1.size == 0):
		a1_1 = mfs[0][1][ find_closest(initial_values[0], egf_value)]
	if( a1_2.size == 0):
		a1_2 = mfs[1][1][ find_closest(initial_values[1], hrg_value)]
	if( a1_3.size == 0):
		a1_3 = mfs[3][1][ find_closest(initial_values[3], time_value)]

	a1 = max( a1_1, a1_2) 
	a1 = min(a1, a1_3 )
	c1 = np.fmin(np.linspace(a1, a1, 100), mfs[2][1])

	a2_1 = mfs[0][0][initial_values[0] == egf_value] #egf_low[egf == egf_value]
	a2_2 = mfs[1][0][initial_values[1] == hrg_value] #hrg_low[hrg == hrg_value]
	a2_3 = mfs[3][0][initial_values[3] == time_value]

	if( a2_1.size == 0):
		a2_1 = mfs[0][0][ find_closest(initial_values[0], egf_value)]
	if( a2_2.size == 0):
		a2_2 = mfs[1][0][ find_closest(initial_values[1], hrg_value)]
	if( a2_3.size == 0):
		a2_3 = mfs[3][0][ find_closest(initial_values[3], hrg_value)]

	a2 = min(a2_1, a2_2)
	a2 = max(a2, a2_3)
	c2 = np.fmin(np.linspace(a2,a2,100), mfs[2][0])

	c_com = np.fmax(c1, c2)
	
	a =  fuzz.defuzz(initial_values[2], c_com, 'centroid')
	return a
Exemple #55
0
def compute_raf(egfr_value, akt_value, time_value, initial_values, mfs):
	"""Rules---
	If egfr is high or akt is high and time is high then raf is high
	if egfr is low and akt is low  or time is low then raf is low"""	

	a1_1 = mfs[0][1][initial_values[0] == egfr_value] #egfr_high[egfr == egfr_value]
	a1_2 = mfs[1][1][initial_values[1] == akt_value] #akt_high[akt == akt_value]
	a1_3 = mfs[3][1][initial_values[3] == time_value]

	if( a1_1.size == 0):
		a1_1 = mfs[0][1][ find_closest(initial_values[0], egfr_value)]
	if( a1_2.size == 0):
		a1_2 = mfs[1][1][ find_closest(initial_values[1], akt_value)]
	if(a1_3.size == 0):
		a1_3 = mfs[3][1][ find_closest(initial_values[3], time_value)]

	a1 = max( a1_1 , a1_2 )
	a1 = min(a1_3, a1)
	#print egfr_value
	c1 = np.fmin( np.linspace(a1, a1, 100), mfs[2][1])

	a2_1 = mfs[0][0][initial_values[0] == egfr_value] #egfr_low[egfr == egfr_value]
	a2_2 = mfs[1][0][initial_values[1] == akt_value] #akt_low[akt == akt_value]
	a2_3 = mfs[3][0][initial_values[3] == time_value]

	if( a2_1.size == 0):
		a2_1 = mfs[0][0][ find_closest(initial_values[0], egfr_value)]
	if( a2_2.size == 0):
		a2_2 = mfs[1][0][ find_closest(initial_values[1], akt_value)]
	if( a2_3.size == 0):
		a2_3 = mfs[3][0][ find_closest(initial_values[3], time_value)]

	a2 = min(a2_1 ,a2_2 )
	a2 = max(a2_3, a2)
	c2 = np.fmin( np.linspace(a2, a2, 100), mfs[2][0])

	c_com = np.fmax(c1, c2)
	return fuzz.defuzz(initial_values[2], c_com, 'centroid')
Exemple #56
0
    def calculate(self, p, i, d):
        """ Calculates the fuzzy output gain """

        # Calculate membership value for each function 
        if self.p_range is not None:
            p_interp = {k: interp_membership(self.p_range, mf, p) for k, mf in self.p_mf.iteritems()}
            print max(p_interp.iteritems(), key=operator.itemgetter(1))[0]
        else:
            p_interp = {}
        if self.i_range is not None:
            i_interp = {k: interp_membership(self.i_range, mf, i) for k, mf in self.i_mf.iteritems()}
            print max(i_interp.iteritems(), key=operator.itemgetter(1))[0]
        else:
            i_interp = {}
        if self.d_range is not None:
            d_interp = {k: interp_membership(self.d_range, mf, d) for k, mf in self.d_mf.iteritems()}
            print max(d_interp.iteritems(), key=operator.itemgetter(1))[0]
        else:
            d_interp = {}
        
        # Merge rule-bases
        dicts = [p_interp, i_interp, d_interp]
        super_dict = {}
        for k in set(k for d in dicts for k in d):
            super_dict[k] = [d[k] for d in dicts if k in d]

        # Generated inferences by rule implications
        aggregate_membership = np.zeros(len(self.c_range))
        for a,b,c in self.c_rules:
            try:
                impl = np.fmin(super_dict[a], super_dict[b]) * self.c_mf[c]
                aggregate_membership = np.fmax(impl, aggregate_membership)
            except:
                pass

        c = defuzz(self.c_range, aggregate_membership, 'centroid')
        return c # this is the resulting "value" of the current state
    if i < 8: ax.set_xticklabels([])
    ax.text(np.average(system_evals[i][4]), 0.8, system_names[i], rotation=90, fontsize=10)
    ax.xaxis.grid(True)
    if i == 0: ax.legend(['DFES Output', 'Benchmark MF', 'Benchmark Range'],
                         bbox_to_anchor=(1.85, 1.38), ncol=3, fontsize=12)

plt.subplots_adjust(left=0.09, bottom=0.08, right=0.94, top=0.94, wspace=None, hspace=0.18)
    
### PLOT GWT results
fig = plt.figure(figsize=(10,8))
res_ind = 4
alpha = 1.0
for i in range(len(results)):
    ax = plt.subplot(5,2,i+1)
    ax.plot(results[i][res_ind][0],results[i][res_ind][1], lw=2.0)
    cent = fuzz.defuzz(np.array(results[i][res_ind][0]), np.array(results[i][res_ind][1]), 'centroid')
    plt.plot([cent, cent], [0.0,2.0], '-r', lw=2.5)
    ax.set_ylim([0.0, 1.01])
    ax.set_yticks([0.0, 0.5, 1.0])
    ax.set_ylabel(r' $\mu(x)$')
    #ax.set_xticks([5000, 10000, 15000, 20000])
    ax.set_xticks([5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000])
    ax.set_xticklabels([5, 10, 15, 20, 25, 30, 35, 40, 45])
    #ax.set_xlim([1000,25000])
    if i > 7: ax.set_xlabel('Gross Weight (x1000 lbs)')
    if i < 8: ax.set_xticklabels([])
    ax.grid(True)
plt.subplots_adjust(left=0.09, bottom=0.08, right=0.94, top=0.94, wspace=None, hspace=0.18)

### PLOT Pinst results
fig = plt.figure(figsize=(10,8))
def test1():
    test_name = 'SYS: In:7-2 Out:9-2   DATA: In:3 Out:3'
    
    print "*************************************"
    print "TESTING:  ", test_name
    inMFs = input_7gaussMFs       #system in
    outMFs = output_9gaussMFs
    defuzz = None
    
    outForm = 'tri'
    inDataForm = 'tri'
    outDataForm = 'tri'
    errType = 'fuzzy'
    
    input_arrays, output_arrays = generate_MFs(inMFs, outMFs)
    
    inputMFs = {    ('VL_SYS_UNION', 'phi'):        copy.deepcopy(input_arrays['phi']),('FWD_SYS_UNION', 'phi'):       copy.deepcopy(input_arrays['phi']), ('WING_SYS_TYPE', 'phi'):       copy.deepcopy(input_arrays['phi']),('ENG_SYS_TYPE', 'phi'):        copy.deepcopy(input_arrays['phi']),
                    ('VL_SYS_UNION', 'w'):          copy.deepcopy(input_arrays['w']),('VL_SYS_TYPE', 'TP'):          copy.deepcopy(input_arrays['TP']),('WING_SYS_TYPE', 'WS'):        copy.deepcopy(input_arrays['WS']),('VL_SYS_PROP', 'sigma'):       copy.deepcopy(input_arrays['sigma']),    
                    ('VL_SYS_TYPE', 'e_d'):         copy.deepcopy(input_arrays['e_d']),('VL_SYS_DRV', 'eta_d'):        copy.deepcopy(input_arrays['eta_d']),('FWD_SYS_DRV', 'eta_d'):       copy.deepcopy(input_arrays['eta_d']),('FWD_SYS_PROP', 'eta_p'):      copy.deepcopy(input_arrays['eta_p']),
                }
    inputPARAMs = { ('VL_SYS_UNION', 'phi'):        copy.deepcopy(inMFs['phi']), ('FWD_SYS_UNION', 'phi'):       copy.deepcopy(inMFs['phi']),('WING_SYS_TYPE', 'phi'):       copy.deepcopy(inMFs['phi']),('ENG_SYS_TYPE', 'phi'):        copy.deepcopy(inMFs['phi']),    
                    ('VL_SYS_UNION', 'w'):          copy.deepcopy(inMFs['w']), ('VL_SYS_TYPE', 'TP'):          copy.deepcopy(inMFs['TP']),('WING_SYS_TYPE', 'WS'):        copy.deepcopy(inMFs['WS']), ('VL_SYS_PROP', 'sigma'):       copy.deepcopy(inMFs['sigma']),    
                    ('VL_SYS_TYPE', 'e_d'):         copy.deepcopy(inMFs['e_d']),('VL_SYS_DRV', 'eta_d'):        copy.deepcopy(inMFs['eta_d']),('FWD_SYS_DRV', 'eta_d'):       copy.deepcopy(inMFs['eta_d']),('FWD_SYS_PROP', 'eta_p'):      copy.deepcopy(inMFs['eta_p']),
                }
    
    outputMFs = {'sys_phi' : copy.deepcopy(output_arrays['sys_phi'])}
    outputPARAMs = {'sys_phi' : copy.deepcopy(outMFs['sys_phi'])}
    
    combinedData = copy.deepcopy(data)
    print combinedData[0]
    #generate rules
    with Timer() as t:
        rule_grid = train_system(inputMFs, outputMFs, combinedData, 
                                 inDataMFs=inDataForm, outDataMFs=outDataForm,
                                 ruleMethod=3)
    
    #write out FCL
    write_fcl_file_FRBS(inputPARAMs, outputPARAMs, rule_grid, defuzz, 'test_sys_phi.fcl')
    
    #get system
    inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, \
        defuzz = build_fuzz_system('test_sys_phi.fcl')
    sys = Fuzzy_System(inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, 
                    implication, defuzz)
    
    print '=> ', t.secs, 'secs to build', len(sys.rulebase), 'rules'
    
    #test system
    with Timer() as t:
        error = getError(combinedData, sys, inMF=inDataForm, outMF=outDataForm, sysOutType=errType)
    print '=> ', t.secs, 'secs to check error'
    print 'Total System Error:', sum([err[2] for err in error])
    print 'Mean Square System Error:', (1.0/len(error))*sum([err[2]**2 for err in error])
    print 'Root Mean Square System Error:', ( (1.0/len(error)) * sum([err[2]**2 for err in error]) )**0.5
    
    #actual vs. predicted plot
    plt.figure()
    plt.title('Actual vs. Predicted at Max Alpha Cut'+test_name)
    for err in error:
        if outDataForm == 'gauss': AC_actual = fuzzyOps.alpha_cut(0.8, [err[0][0],err[0][1]])
        else: AC_actual = fuzzyOps.alpha_at_val(err[0][0],err[0][1])
        if outForm == 'gauss': AC_pred = fuzzyOps.alpha_cut(0.8, (err[1][0],err[1][1]))
        else: AC_pred = fuzzyOps.alpha_at_val(err[1][0],err[1][1])
        
        plt.scatter(AC_actual[0], AC_pred[0], marker='o', c='r')
        plt.scatter(AC_actual[1], AC_pred[1], marker='x', c='b')
    
    plt.plot([1,9],[1,9], '--k')     
    plt.xlim([1,9])
    plt.ylim([1,9])
    plt.xlabel('Actual')
    plt.ylabel('Predicted')
    
    #visuzlize system with random data point
    #i = random.randrange(0, len(combinedData))
    #inputs = {key[0]+"_"+key[1]:combinedData[i][0][key] for key in combinedData[i][0]}
    #sys.run(inputs, TESTMODE=True)
    
    #check random data points (9)
    plt.figure()
    plt.title('Random Tests:'+test_name)
    for j in range(9):
        i = random.randrange(0, len(combinedData))
        inputs = {key[0]+"_"+key[1]:combinedData[i][0][key] for key in combinedData[i][0]}
        sysOut = sys.run(inputs)
        sysOut = sysOut[sysOut.keys()[0]]
        plt.subplot(3,3,j+1)
        plt.plot(sysOut[0], sysOut[1], '-r')
        plt.plot(combinedData[i][2][0], combinedData[i][2][1], '--k')
        plt.ylim([0,1.1])
        plt.xlim([1,9])
    
    #actual vs. error plot
    plt.figure()
    plt.title('Actual (Centroid) vs. Error'+test_name)
    cents = [fuzz.defuzz(err[0][0], err[0][1], 'centroid') for err in error]
    plt.scatter(cents, [err[2] for err in error])
    plt.xlabel('Actual (Centroid)')
    plt.ylabel('Fuzzy Error')