Ejemplo n.º 1
0
    def tri_pi_tri(var, term: str, values):
        var[term] = fuzzy_or(
            var.universe, trimf(var.universe,
                                [values[0], values[1], values[1]]),
            var.universe,
            pimf(var.universe, values[1], values[1], values[2], values[2]))[1]

        var[term] = fuzzy_or(
            var.universe, var[term].mf, var.universe,
            trimf(var.universe, [values[2], values[2], values[3]]))[1]

        return var
Ejemplo n.º 2
0
def init_fls_common_part(
):  #TO DO: put this parameter as class or in another module
    global object_distance, object_direction
    # New Antecedent objects
    object_distance = ctrl.Antecedent(range_meter, 'distance')
    object_direction = ctrl.Antecedent(range_degree, 'direction')

    # Membership functions

    # Distance
    object_distance['Near'] = fuzz.trapmf(range_meter, [0, 0, IZW, 2 * IZW])
    object_distance['Medium'] = fuzz.trimf(range_meter,
                                           [IZW, 2 * IZW, 4 * IZW])
    object_distance['Far'] = fuzz.trapmf(range_meter, [2 * IZW, 4 * IZW, 3, 3])
    # Direction -180~180
    rear_d_p2 = fuzz.trapmf(range_degree, [-180, -180, -135, -90])
    object_direction['Right'] = fuzz.trimf(range_degree, [-135, -90, -45])
    object_direction['FrontRight'] = fuzz.trimf(range_degree, [-90, -45, 0])
    object_direction['Front'] = fuzz.trimf(range_degree, [-45, 0, 45])
    object_direction['FrontLeft'] = fuzz.trimf(range_degree, [0, 45, 90])
    object_direction['Left'] = fuzz.trimf(range_degree, [45, 90, 135])
    rear_d_p1 = fuzz.trapmf(range_degree, [90, 135, 180, 180])
    null, object_direction['BigRear'] = fuzz.fuzzy_or(range_degree, rear_d_p1,
                                                      range_degree, rear_d_p2)
    print("init_fls_common_part")
Ejemplo n.º 3
0
def init_risk_assessment():
    range_type = np.arange(0, 2 + 1, 1)
    # New Antecedent/Consequent objects
    object_type = ctrl.Antecedent(range_type, 'type')
    object_speed = ctrl.Antecedent(range_meter_per_second, 'speed')
    object_orientation = ctrl.Antecedent(range_degree, 'orientation')
    object_risk = ctrl.Consequent(range_risk, 'risk')
    # Type
    object_type['StaObj'] = fuzz.trimf(range_type, [0, 0, 0.1])
    object_type['DynObj'] = fuzz.trimf(range_type, [0.9, 1, 1.1])
    object_type['Human'] = fuzz.trimf(range_type, [1.9, 2, 2])
    # Speed
    object_speed['Slow'] = fuzz.trapmf(range_meter_per_second,
                                       [0, 0, 0.5, 1.0])
    object_speed['Medium'] = fuzz.trapmf(range_meter_per_second,
                                         [0.5, 1.0, 1.0, 1.5])
    object_speed['Fast'] = fuzz.trimf(range_meter_per_second, [1.0, 1.5, 1.5])
    # Orientation
    object_orientation['Front'] = fuzz.trimf(range_degree, [-45, 0, 45])
    object_orientation['FrontLeft'] = fuzz.trimf(range_degree, [0, 45, 90])
    object_orientation['Left'] = fuzz.trimf(range_degree, [45, 90, 135])
    object_orientation['RearLeft'] = fuzz.trimf(range_degree, [90, 135, 180])
    rear_p1 = fuzz.trimf(range_degree, [135, 180, 180])
    rear_p2 = fuzz.trimf(range_degree, [-180, -180, -135])
    null, object_orientation['Rear'] = fuzz.fuzzy_or(range_degree, rear_p1,
                                                     range_degree, rear_p2)
    object_orientation['RearRight'] = fuzz.trimf(range_degree,
                                                 [-180, -135, -90])
    object_orientation['Right'] = fuzz.trimf(range_degree, [-135, -90, -45])
    object_orientation['FrontRight'] = fuzz.trimf(range_degree, [-90, -45, 0])
    # Risk
    object_risk['VeryLow'] = fuzz.trimf(range_risk, [0, 0, 1])
    object_risk['Low'] = fuzz.trimf(range_risk, [0, 1, 2])
    object_risk['Medium'] = fuzz.trimf(range_risk, [1, 2, 3])
    object_risk['High'] = fuzz.trimf(range_risk, [2, 3, 4])
    object_risk['VeryHigh'] = fuzz.trimf(range_risk, [3, 4, 4])

    fls_name = "/rules/ra_full.data"
    fls_data_path = package_path + fls_name
    print(fls_data_path)

    #if os.path.exists(fls_name):
    if os.path.exists(fls_data_path):
        print("FLS exists!")
        #f = open(fls_name,'rb')
        f = open(fls_data_path, 'rb')
        ra_fls = pickle.load(f)
    else:
        print("Init FLS")
        from assessment_rules import rule_list_generator
        assessment_rule_list = rule_list_generator(
            object_type, object_distance, object_direction, object_speed,
            object_orientation, object_risk)
        ra_fls = ctrl.ControlSystem(assessment_rule_list)
        #f = open(fls_name,'wb')
        f = open(fls_data_path, 'wb')
        pickle.dump(ra_fls, f)
        f.close
    global risk_assessment_instance
    risk_assessment_instance = ctrl.ControlSystemSimulation(ra_fls)
Ejemplo n.º 4
0
    def aggregate(self, MFs):
        o1 = MFs.pop()
        if self.aggregator == 'MAX':
            while len(MFs) > 0:
                o2 = MFs.pop()
                o1[0], o1[1] = fuzz.fuzzy_or(o1[0], o1[1], o2[0], o2[1])

        return o1
Ejemplo n.º 5
0
 def aggregate(self, MFs):
     o1 = MFs.pop()
     if self.aggregator == 'MAX':
         while len(MFs) > 0:
             o2 = MFs.pop()
             o1[0],o1[1] = fuzz.fuzzy_or( o1[0],o1[1],o2[0],o2[1] )
             
             
     return o1
Ejemplo n.º 6
0
 def get_consequent_membership_function(consequent: ctrl.Consequent,
                                        controller):
     terms = list(consequent.terms.keys())
     universe = consequent.universe
     _, result, _ = CrispValueCalculator(consequent[terms[0]], controller)
     for i in range(1, len(terms)):
         term = terms[i]
         _, temp, _ = CrispValueCalculator(consequent[term], controller)
         _, result = fuzzy_or(universe, result, universe, temp)
     return MfMapping(universe,
                      result), CrispValueCalculator(consequent, controller)
Ejemplo n.º 7
0
def init_RA():
    object_distance = ctrl.Antecedent(range_meter, 'distance')  # 0- 3  meter
    object_direction = ctrl.Antecedent(range_degree,
                                       'direction')  # -180~180 degree
    object_risk = ctrl.Antecedent(range_risk, 'risk')

    #global left_speed,right_speed # When Consequent need visualization
    left_speed = ctrl.Consequent(range_meter_per_second, 'left')
    right_speed = ctrl.Consequent(range_meter_per_second, 'right')

    # Custom membership functions can be built interactively with a familiar Pythonic API
    distance_p1 = fuzz.gaussmf(range_meter, IZW, 0.1)
    distance_p2 = fuzz.gaussmf(range_meter, IZW, 0.1)
    # Distance
    object_distance['Near'] = fuzz.gaussmf(range_meter, 0.5 * IZW, 0.1)  #0.2
    object_distance['Medium'] = fuzz.gaussmf(range_meter, IZW, 0.1)  #0.4
    object_distance['Far'] = fuzz.gaussmf(range_meter, 2.0 * IZW, 0.2)  #0.8
    # Direction
    object_direction['Front'] = fuzz.gaussmf(range_degree, 0, 15)
    object_direction['FrontLeft'] = fuzz.gaussmf(range_degree, 45, 15)
    object_direction['Left'] = fuzz.gaussmf(range_degree, 90, 15)
    object_direction['FrontRight'] = fuzz.gaussmf(range_degree, -45, 15)
    object_direction['Right'] = fuzz.gaussmf(range_degree, -90, 15)
    rear_d_p1 = fuzz.gaussmf(range_degree, 180, 60)
    rear_d_p2 = fuzz.gaussmf(range_degree, -180, 60)
    null, object_direction['BigRear'] = fuzz.fuzzy_or(range_degree, rear_d_p1,
                                                      range_degree, rear_d_p2)
    # Risk
    object_risk['VeryLow'] = fuzz.gaussmf(range_risk, 0, 0.3)
    object_risk['Low'] = fuzz.gaussmf(range_risk, 1, 0.3)
    object_risk['Medium'] = fuzz.gaussmf(range_risk, 2, 0.3)
    object_risk['High'] = fuzz.gaussmf(range_risk, 3, 0.3)
    object_risk['VeryHigh'] = fuzz.gaussmf(range_risk, 4, 0.3)

    # Left Speed
    left_speed['Stop'] = fuzz.gaussmf(range_meter_per_second, 0.0, 0.1)
    left_speed['Slow'] = fuzz.gaussmf(range_meter_per_second, 0.2, 0.2)
    left_speed['Medium'] = fuzz.gaussmf(range_meter_per_second, 0.8, 0.2)
    left_speed['Fast'] = fuzz.gaussmf(range_meter_per_second, 1.2, 0.2)
    # Right Speed
    right_speed['Stop'] = fuzz.gaussmf(range_meter_per_second, 0.0, 0.1)
    right_speed['Slow'] = fuzz.gaussmf(range_meter_per_second, 0.2, 0.2)
    right_speed['Medium'] = fuzz.gaussmf(range_meter_per_second, 0.8, 0.2)
    right_speed['Fast'] = fuzz.gaussmf(range_meter_per_second, 1.2, 0.2)

    from mitigation_rules import rule_list_generator
    rule_list = rule_list_generator(object_distance, object_direction,
                                    object_risk, left_speed, right_speed)

    global risk_mitigation_instance  # We don't need to change the FLS
    risk_mitigation_fls = ctrl.ControlSystem(rule_list)
    risk_mitigation_instance = ctrl.ControlSystemSimulation(
        risk_mitigation_fls)
Ejemplo n.º 8
0
 def aggregate(self, MFs):
     """
     Peform aggregation on the given outputs of the rules and returns aggregated MF
     
     ------INPUTS------
     MFs : list 
         list of MF functions
     ------OUTPUTS------ 
     o1 : list
          aggregation of all MFs
     """
     o1 = MFs.pop()
     if self.aggregator == 'MAX':
         while len(MFs) > 0:
             o2 = MFs.pop()
             o1[0],o1[1] = fuzz.fuzzy_or( o1[0],o1[1],o2[0],o2[1] )
     else: 
         raise StandardError('Havent coded this yet!')
             
     return o1
Ejemplo n.º 9
0
step = 0.5
x = np.arange(start, stop + delta, step)

# Triangular membership function
x1 = np.arange(0, 5 + delta, step)
trimf = fuzz.trimf(x1, [0, 2.5, 5])

# Trapezoidal membership function
x2 = np.arange(4, 10 + delta, step)
trapmf = fuzz.trapmf(x2, [4, 6, 8, 10])

# fuzzy logic
tri_not = fuzz.fuzzy_not(trimf)
trap_not = fuzz.fuzzy_not(trapmf)
x3, tri_trap_and = fuzz.fuzzy_and(x1, trimf, x2, trapmf)
x3, tri_trap_or = fuzz.fuzzy_or(x1, trimf, x2, trapmf)

# Defuzzify
centroid_x = fuzz.defuzz(x3, tri_trap_or, "centroid")
centroid_y = fuzz.interp_membership(x3, tri_trap_or, centroid_x)
bisector_x = fuzz.defuzz(x3, tri_trap_or, "bisector")
bisector_y = fuzz.interp_membership(x3, tri_trap_or, bisector_x)
mom_x = fuzz.defuzz(x3, tri_trap_or, "mom")
mom_y = fuzz.interp_membership(x3, tri_trap_or, mom_x)
som_x = fuzz.defuzz(x3, tri_trap_or, "som")
som_y = fuzz.interp_membership(x3, tri_trap_or, som_x)
lom_x = fuzz.defuzz(x3, tri_trap_or, "lom")
lom_y = fuzz.interp_membership(x3, tri_trap_or, lom_x)

# Whole config
fig_scale = 1.5
Ejemplo n.º 10
0
# Direction -180~180
rear_d_p2 = fuzz.trapmf(
    range_degree, [-180, -180, -135, -90])  #fuzz.gaussmf(range_degree,-180,60)
object_direction['Right'] = fuzz.trimf(
    range_degree, [-135, -90, -45])  #fuzz.gaussmf(range_degree,-90,15)
object_direction['FrontRight'] = fuzz.trimf(
    range_degree, [-90, -45, 0])  #fuzz.gaussmf(range_degree,-45,15)
object_direction['Front'] = fuzz.trimf(
    range_degree, [-45, 0, 45])  #fuzz.gaussmf(range_degree,0,15)
object_direction['FrontLeft'] = fuzz.trimf(
    range_degree, [0, 45, 90])  #fuzz.gaussmf(range_degree,45,15)
object_direction['Left'] = fuzz.trimf(
    range_degree, [45, 90, 135])  #fuzz.gaussmf(range_degree,90,15)
rear_d_p1 = fuzz.trapmf(
    range_degree, [90, 135, 180, 180])  #fuzz.gaussmf(range_degree,180,60)
null, object_direction['BigRear'] = fuzz.fuzzy_or(
    range_degree, rear_d_p1, range_degree, rear_d_p2)  # Combine the two parts
#object_direction.view()

# Risk
object_risk['VeryLow'] = fuzz.trimf(range_risk,
                                    [0, 0, 1])  #fuzz.gaussmf(range_risk,0,0.3)
object_risk['Low'] = fuzz.trimf(range_risk,
                                [0, 1, 2])  #fuzz.gaussmf(range_risk,1,0.3)
object_risk['Medium'] = fuzz.trimf(range_risk,
                                   [1, 2, 3])  #fuzz.gaussmf(range_risk,2,0.3)
object_risk['High'] = fuzz.trimf(range_risk,
                                 [2, 3, 4])  #fuzz.gaussmf(range_risk,3,0.3)
object_risk['VeryHigh'] = fuzz.trimf(
    range_risk, [3, 4, 4])  #fuzz.gaussmf(range_risk,4,0.3)
#object_risk.view()
Ejemplo n.º 11
0
from curve_mf import kinked_curve_mf

from skfuzzy import trapmf
from skfuzzy import smf as s_shape_mf
from skfuzzy import zmf as z_shape_mf

font = {'family': 'DejaVu Sans', 'weight': 'normal', 'size': 7}
plt.rc('font', **font)

universe = np.arange(0, 13)

mfA = kinked_curve_mf(universe, [(2, 0), (8, 0.5), (9, 0.25), (14, 0)])
mfB = kinked_curve_mf(universe, [(0, 1), (5, 0)])
mfC = kinked_curve_mf(universe, [(0, 0), (3, 1), (5, 0)])

B_and_C, mf_B_and_C = fuzz.fuzzy_or(universe, mfA, universe, mfB)
A_or_B_and_C, mf_A_or_B_and_C = fuzz.fuzzy_and(B_and_C, mf_B_and_C, universe,
                                               mfC)

fig = plt.figure(figsize=(10, 8))
grid = gridspec.GridSpec(nrows=2, ncols=6)

axA = fig.add_subplot(grid[0, :2],
                      xlim=(0, max(universe)),
                      ylim=(0, 1),
                      title='A')
axB = fig.add_subplot(grid[0, 2:4], sharex=axA, sharey=axA, title='B')
axC = fig.add_subplot(grid[0, 4:], sharex=axA, sharey=axA, title='C')
axBC = fig.add_subplot(grid[1, :3], sharex=axA, sharey=axA, title='B^C')
axD = fig.add_subplot(grid[1, 3:], sharex=axA, sharey=axA, title='AvB^C')
Ejemplo n.º 12
0
plt.figure()
plt.plot(x, bajo, 'b', linewidth=1.5, label='Bajo')
plt.plot(x, medio, 'r', linewidth=1.5, label='Medio')

# Ajustes gráfico
plt.title('Función Unión (máximo)')
plt.ylabel('Membresía')
plt.xlabel('Velocidad (Kilometros por hora)')
plt.legend(loc='best', fancybox=True, shadow=True)

for i in range(0, 11):
    plt.axvline(x=i, ymin=0, ymax=10, color='g', linestyle='-.')

plt.plot(0, 1, marker='o', markersize=10, color='g')
plt.plot(1, 0.8, marker='o', markersize=10, color='g')
plt.plot(2, 0.6, marker='o', markersize=10, color='g')
plt.plot(3, 0.6, marker='o', markersize=10, color='g')
plt.plot(4, 0.8, marker='o', markersize=10, color='g')
plt.plot(5, 1, marker='o', markersize=10, color='g')

plt.plot(6, 0.8, marker='o', markersize=10, color='g')
plt.plot(7, 0.6, marker='o', markersize=10, color='g')
plt.plot(8, 0.4, marker='o', markersize=10, color='g')
plt.plot(9, 0.2, marker='o', markersize=10, color='g')
plt.plot(10, 0, marker='o', markersize=10, color='g')

plt.show()

# Encontrando el máximo (Fuzzy OR)
print(sk.fuzzy_or(x, bajo, x, medio))
Ejemplo n.º 13
0
plt.ylabel('Membresia')
plt.xlabel('Velocidad km/h')
plt.legend(loc='center right',
           bbox_to_anchor=(1.25, 0.5),
           ncol=1,
           fancybox=True,
           shadow=True)

plt.axvline(x)

i = 0
while i <= range(10):
    plt.axvline(i, ymin=0, ymax=10, color='g', licestyle='-.')

plt.plot(0, 1, marker='o', markersize=10, color='g')
plt.plot(1, 0.8, marker='o', markersize=10, color='g')
plt.plot(2, 0.6, marker='o', markersize=10, color='g')
plt.plot(3, 0.6, marker='o', markersize=10, color='g')
plt.plot(4, 0.8, marker='o', markersize=10, color='g')
plt.plot(5, 1, marker='o', markersize=10, color='g')

plt.plot(6, 0.8, marker='o', markersize=10, color='g')
plt.plot(7, 0.6, marker='o', markersize=10, color='g')
plt.plot(8, 0.4, marker='o', markersize=10, color='g')
plt.plot(9, 0.2, marker='o', markersize=10, color='g')
plt.plot(10, 0, marker='o', markersize=10, color='g')

plt.show()

sk.fuzzy_or(x, bajo, x, medio)
Ejemplo n.º 14
0
def init_rule_based_system():
    # Antecedent/Consequent objects hold universe variables and membership functions

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

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

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

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

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

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

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

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

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

    #time_previous = time.time()  

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

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

    import cPickle as pickle 
    fls_name = "ra_full.data"

    if os.path.exists(fls_name):
        print("FLS exists!")
        f = open(fls_name,'rb')
        ra_fls = pickle.load(f)
    else:
        print("Init FLS")
        from assessment_rules import rule_list_generator
        assessment_rule_list=rule_list_generator(object_type,object_distance,object_direction, object_speed, object_orientation, object_risk)
        ra_fls = ctrl.ControlSystem(assessment_rule_list)
        f = open(fls_name,'wb')
        pickle.dump(ra_fls,f)
        f.close 
    """
    In order to simulate this control system, we will create a
    ``ControlSystemSimulation``.  Think of this object representing our controller
    applied to a specific set of cirucmstances. 
    """
    global risk_assessment_instance 
    risk_assessment_instance = ctrl.ControlSystemSimulation(ra_fls)
Ejemplo n.º 15
0
 def feedforward(self, inputs):
     """
     ------INPUTS------
     
     inputs : dict
         the set of outputs from previous nodes in form 
         {nodeName: value, nodeName: value, ...} (or inputs for input 
         nodes)   
     """
     #INPUT FEED FORWARD (fuzzify inputs)
     for inp in self.layer1:
         try:
             if inp in inputs: #check if input is given
                 if not isinstance(inputs[inp], list):
                     MF = fuzzOps.paramsToMF([inputs[inp]]) #get fuzzy MF for singleton
                     self.layer1[inp] = MF
                 else: 
                     self.layer1[inp] = inputs[inp]
             else: 
                 print "Not all inputs given!!!" 
                 self.layer3[self.layer3.keys()[0]] = None #set system output to None
         except:
             raise StandardError("NEFPROX input error!")
     
     #RULE FEED FORWARD (gets min (t-norm) firing strength of weights/MFterms and inputs)
     for rule in self.layer2: #for each rule
         for inp in self.connect1to2[rule]: #for each input in antecedent 
             fs = max(fuzz.fuzzy_and(self.inputMFs[inp][0], self.inputMFs[inp][1],
                                     self.layer1[inp[0]][0], self.layer1[inp[0]][1])[1])
             self.connect1to2[rule][inp] = fs
         self.layer2[rule] = min([self.connect1to2[rule][inp] for inp in self.connect1to2[rule]])
 
     #OUTPUT FEED FORWARD (apply minimum of firing strength and output MF (reduce output MF), then aggregate)
     outMFs = []
     for rule in self.connect2to3: #for each rule
         cons = self.connect2to3[rule].keys()[0]  #get consequent for single output
         if self.layer2[rule] > 0.0: #only for active rules (save time)
             outMF = copy.deepcopy(self.outputMFs[cons][:2])
             outMF[1] = np.asarray([ min(self.layer2[rule], outMF[1][i]) for i in range(len(outMF[1])) ])
                         #apply minimum of firing strength and output MF (reduce output MF)
             self.connect2to3[rule][cons] = outMF
             outMFs.append(outMF)
         else: #for inactive rules, applied MF is 0.0 for all 
             self.connect2to3[rule][cons] = [np.asarray([0.0, 0.0]), np.asarray([0.0,0.0])]
             
     #once all rules are reduced with MFs aggregate
     if len(outMFs) > 0: #check for no rules fired
         while len(outMFs) > 1: #get maximum (union) of all MFs (aggregation)
             outMFs0 = outMFs.pop(0)
             outMFs[0][0], outMFs[0][1] = fuzz.fuzzy_or(outMFs0[0], outMFs0[1], 
                                                         outMFs[0][0], outMFs[0][1])
         
         if   self.defuzz == None: pass
         elif self.defuzz == 'centroid': outMFs[0] = fuzz.defuzz(outMFs[0][0],outMFs[0][1],'centroid')
         elif self.defuzz == 'bisector': outMFs[0] = fuzz.defuzz(outMFs[0][0],outMFs[0][1],'bisector')
         elif self.defuzz == 'mom':      outMFs[0] = fuzz.defuzz(outMFs[0][0],outMFs[0][1],'mom')               #mean of maximum
         elif self.defuzz == 'som':      outMFs[0] = fuzz.defuzz(outMFs[0][0],outMFs[0][1],'som')               #min of maximum
         elif self.defuzz == 'lom':      outMFs[0] = fuzz.defuzz(outMFs[0][0],outMFs[0][1],'lom')               #max of maximum
         
         self.layer3[cons[0]] = outMFs[0]
         
     else:#if no rules fire, then output is None
     
         if self.defuzz == None:
             self.layer3[cons[0]] = [[0.0,0.0],[0.0,0.0]] #result 0.0 in fuzzy MF form
         else:
             self.layer3[cons[0]] = 0.0 #result 0.0 as crisp if some defuzz method specified
         
     return True
Ejemplo n.º 16
0
if __name__ == "__main__":
    # Create universe of discourse in Python using linspace ()
    X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False)

    # Create two fuzzy sets by defining any membership function
    # (trapmf(), gbellmf(), gaussmf(), etc).
    abc1 = [0, 25, 50]
    abc2 = [25, 50, 75]
    young = fuzz.membership.trimf(X, abc1)
    middle_aged = fuzz.membership.trimf(X, abc2)

    # Compute the different operations using inbuilt functions.
    one = np.ones(75)
    zero = np.zeros((75,))
    # 1. Union = max(µA(x), µB(x))
    union = fuzz.fuzzy_or(X, young, X, middle_aged)[1]
    # 2. Intersection = min(µA(x), µB(x))
    intersection = fuzz.fuzzy_and(X, young, X, middle_aged)[1]
    # 3. Complement (A) = (1- min(µA(x))
    complement_a = fuzz.fuzzy_not(young)
    # 4. Difference (A/B) = min(µA(x),(1- µB(x)))
    difference = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1]
    # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))]
    alg_sum = young + middle_aged - (young * middle_aged)
    # 6. Algebraic Product = (µA(x) * µB(x))
    alg_product = young * middle_aged
    # 7. Bounded Sum = min[1,(µA(x), µB(x))]
    bdd_sum = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1]
    # 8. Bounded difference = min[0,(µA(x), µB(x))]
    bdd_difference = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1]
Ejemplo n.º 17
0
# Speed
object_speed['Slow'] = fuzz.gaussmf(range_meter_per_second, 0.5, 0.2)
object_speed['Medium'] = fuzz.gaussmf(range_meter_per_second, 1.0, 0.2)
object_speed['Fast'] = fuzz.gaussmf(range_meter_per_second, 1.5, 0.2)
#object_speed.view()

# Direction
object_direction['Front'] = fuzz.gaussmf(range_degree, 0, 15)
object_direction['FrontLeft'] = fuzz.gaussmf(range_degree, 45, 15)
object_direction['Left'] = fuzz.gaussmf(range_degree, 90, 15)
object_direction['FrontRight'] = fuzz.gaussmf(range_degree, -45, 15)
object_direction['Right'] = fuzz.gaussmf(range_degree, -90, 15)
rear_d_p1 = fuzz.gaussmf(range_degree, 180, 60)
rear_d_p2 = fuzz.gaussmf(range_degree, -180, 60)
null, object_direction['BigRear'] = fuzz.fuzzy_or(range_degree, rear_d_p1,
                                                  range_degree, rear_d_p2)
#object_direction.view()

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