def generate_mf_group(self, G, x): mf_group = {} for (k, v) in G.iteritems(): shp = v['shp'] mf = v['mf'] if mf == 'trap': mf_group[k] = trapmf(x, shp) if mf == 'tri': mf_group[k] = trimf(x, shp) if mf == 'gbell': mf_group[k] = gbellmf(x, shp[0], shp[1], shp[2]) if mf == 'gauss': mf_group[k] = gaussmf(x, shp[0], shp[1]) if mf == 'gauss2': mf_group[k] = gauss2mf(x, shp[0], shp[1]) if mf == 'sig': mf_group[k] = sigmf(x, shp[0], shp[1]) if mf == 'psig': mf_group[k] = psigmf(x, shp[0], shp[1], shp[2], shp[3]) if mf == 'zmf': mf_group[k] = zmf(x, shp[0], shp[1], shp[2], shp[3]) if mf == 'smf': mf_group[k] = smf(x, shp[0], shp[1], shp[2], shp[3]) if mf == 'pimf': mf_group[k] = pimf(x, shp[0], shp[1], shp[2], shp[3]) if mf == 'piecemf': mf_group[k] = piecemf(x, shp[0], shp[1], shp[2], shp[3]) return mf_group
def test_interp_membership(): x = np.r_[0:4.1:0.1] mfx = trapmf(x, [0, 1, 2, 4]) yy = interp_membership(x, mfx, 0) assert yy == 0 yy = interp_membership(x, mfx, 0.535) assert_allclose(np.r_[yy], np.r_[0.535]) yy = interp_membership(x, mfx, np.pi / 3.) assert yy == 1 yy = interp_membership(x, mfx, 2.718) assert_allclose(np.r_[yy], np.r_[0.641]) assert_allclose(interp_membership(x, mfx, [0.2, 2.73, 3.14]), np.asarray([interp_membership(x, mfx, i) for i in [0.2, 2.73, 3.14]])) mfx[-1] = 0.7 mfx[0] = 0.2 assert_allclose([0, 0], interp_membership(x, mfx, [-11, 5])) assert_allclose([0.2, 0.7], interp_membership(x, mfx, [-11, 5], False))
def _plot_mf_for(x): '''Given the x-values, plot a series of example membership functions''' tests = OrderedDict([ # Gaussians: ('gauss', skmemb.gaussmf(x, 50, 10)), ('left gauss', leftgaussmf(x, 50, 10)), ('right gauss', rightgaussmf(x, 50, 10)), # Triangles: ('triangular', skmemb.trimf(x, [25, 50, 75])), ('left linear', leftlinearmf(x, 25, 75)), ('right linear', rightlinearmf(x, 25, 75)), # fuzzylite: ('cosine', cosinemf(x, 50, 50)), ('inc concave', concavemf(x, 50, 75)), ('dec concave', concavemf(x, 50, 25)), ('spike', spikemf(x, 50, 50)), ('inc ramp', rampmf(x, 25, 75)), ('dec ramp', rampmf(x, 75, 25)), # Rectangle-ish ('trapezoid', skmemb.trapmf(x, [20, 40, 60, 80])), ('rectangle', rectanglemf(x, 25, 75)), ('singleton', singletonmf(x, 50)), ]) # Example point sets: ps_tests = [[(40, 0.5), (60, 1)], [(10, 0.5), (25, 0.25), (40, 0.75), (80, .5)], [(0, 1), (40, 0.25), (50, .5), (99, 0)]] # Now try some interpolation methods on these: for method in ['linear', 'lagrange', 'spline', 'cubic']: tests.update([('{} ex{}'.format(method, i), pointsetmf(x, ps, method)) for i, ps in enumerate(ps_tests)]) return tests
def test_trapmf(): x = np.arange(-4, 3.1, 0.1) abcd = (-4, -4, 2, np.pi) expected = np.ones_like(x) idx = np.logical_and(x > 2, x < np.pi) expected[idx] = np.interp(x[idx], np.r_[2, np.pi], np.r_[1, 0]) expected[x > np.pi] = 0 test = trapmf(x, abcd) assert_allclose(test, expected)
def test_interp_membership(): x = np.r_[0:4.1:0.1] mfx = trapmf(x, [0, 1, 2, 4]) yy = interp_membership(x, mfx, 0) assert yy == 0 yy = interp_membership(x, mfx, 0.535) assert_allclose(np.r_[yy], np.r_[0.535]) yy = interp_membership(x, mfx, np.pi / 3.) assert yy == 1 yy = interp_membership(x, mfx, 2.718) assert_allclose(np.r_[yy], np.r_[0.641])
def test_interp_universe(): x = np.r_[0:4.1:0.1] mfx = trapmf(x, [0, 1, 2, 4]) xx = interp_universe(x, mfx, 0.5) assert_allclose(xx, [0.5, 3]) xx = interp_universe(x, mfx, 0.0) assert_allclose(xx, [0, 4]) xx = interp_universe(x, mfx, 1.5) assert len(xx) == 0 xx = interp_universe(x, mfx, 0.3) y = [interp_membership(x, mfx, value) for value in xx] assert_allclose(y, 0.3)
ax[2].set_ylabel('Control u') ax[2].set_title('Fuzzy logic control action u') fig.suptitle('Simulation. Gain K = ' + str(K)) plt.show() return xx1, xx2, uu, tt if __name__ == '__main__': """ These functions represent an inverted pendulum. """ # Membership Matrices x1 = np.arange(-10, 10.1, 0.1) # Angle range, 1d array, length N, Fuzzy state variable #1. N1 = trapmf(x1, [-10, -10, -2, 0]) # Negative membership function Z1 = trimf(x1, [-2, 0, 2]) # Zero membership function P1 = trapmf(x1, [0, 2, 10, 10]) # Positive membership function M1 = np.vstack((N1, Z1, P1)) # Input 1 membership matrix, 2d array, shape (Q1, N), Matrix with Q1 membership functions for x1. x2 = np.arange(-10, 10.1, 0.1) # Angular velocity range, 1d array, length M, Fuzzy state variable #2. N2 = trapmf(x2, [-10, -10, -2, 0]) # Negative membership function Z2 = trimf(x2, [-2, 0, 2]) # Zero membership function P2 = trapmf(x2, [0, 2, 10, 10]) # Positive membership function M2 = np.vstack((N2, Z2, P2)) # Input 2 membership matrix, 2d array, shape (Q2, M), Matrix with Q2 membership functions for x2. # Fuzzy control (u) and member functions u = np.arange(-25, 25.25, 0.25) # Fuzzy control output variable, 1d array, length U, Feedback control action variable. NBu = trapmf(u, [-25, -25, -16, -8]) # Big Negative` membership function Nu = trimf(u, [-16, -8, 0]) # Negative` membership function Zu = trimf(u, [-8, 0, 8]) # Zero` membership function
import numpy as np import skfuzzy as fuzz import skfuzzy.membership as mf import matplotlib.pyplot as plt x_tempTest = np.arange(0, 101, 1) x_firmTest = np.arange(0, 101, 1) y_quality = np.arange(0, 101, 1) temp_low = mf.trapmf(x_tempTest, [0, 0, 10, 40]) temp_med = mf.trimf(x_tempTest, [20, 50, 80]) temp_hig = mf.trapmf(x_tempTest, [60, 90, 100, 100]) firm_low = mf.trimf(x_firmTest, [0, 0, 40]) firm_med = mf.trimf(x_firmTest, [30, 50, 70]) firm_hig = mf.trimf(x_firmTest, [60, 100, 100]) #result_no = mf.trimf(y_quality, [0, 0, 100]) #result_ok = mf.trimf(y_quality, [0, 100, 100]) quality_verylow = mf.trimf(y_quality, [0, 0, 25]) quality_bitlow = mf.trimf(y_quality, [0, 25, 50]) quality_middle = mf.trimf(y_quality, [25, 50, 75]) quality_bithigh = mf.trimf(y_quality, [50, 75, 100]) quality_veryhig = mf.trimf(y_quality, [75, 100, 100]) fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(6, 10)) ax0.plot(x_tempTest, temp_low, 'r', linewidth=2, label='Düşük') ax0.plot(x_tempTest, temp_med, 'g', linewidth=2, label='Orta') ax0.plot(x_tempTest, temp_hig, 'b', linewidth=2, label='Yüksek')
def __init__(self): # Create input and output variables self.lsonar = ctrl.Antecedent(self.sonar_interval, 'lsonar') self.rsonar = ctrl.Antecedent(self.sonar_interval, 'rsonar') self.last_theta = ctrl.Antecedent(self.theta_interval, 'last_theta') self.theta = ctrl.Consequent(self.theta_interval, 'theta') self.v_x = ctrl.Consequent(self.v_interval, 'v_x') # we need membership functions! distance_levels = ['dangerous', 'unsafe', 'safe'] theta_directions = ['left', 'centre', 'right'] velocity_levels = ['slow', 'medium', 'fast'] self.lsonar.automf(names=distance_levels) self.rsonar.automf(names=distance_levels) self.last_theta.automf(names=theta_directions) self.theta.automf(names=theta_directions) self.v_x.automf(names=velocity_levels) low_mshp = mshp.trimf(self.sonar_interval, [0.25, 0.25, 0.31]) mid_mshp = mshp.trimf(self.sonar_interval, [0.28, 0.35, 0.45]) high_mshp = mshp.trapmf(self.sonar_interval, [0.4, 0.6, 2.55, 2.55]) self.lsonar['dangerous'] = low_mshp self.lsonar['unsafe'] = mid_mshp self.lsonar['safe'] = high_mshp self.rsonar['dangerous'] = low_mshp self.rsonar['unsafe'] = mid_mshp self.rsonar['safe'] = high_mshp left_angle_mshp = mshp.gaussmf(self.theta_interval, 0.7, 0.2) centre_angle_mshp = mshp.gaussmf(self.theta_interval, 0, 0.1) right_angle_mshp = mshp.gaussmf(self.theta_interval, -0.7, 0.2) self.theta['left'] = left_angle_mshp self.theta['centre'] = centre_angle_mshp self.theta['right'] = right_angle_mshp self.last_theta['left'] = left_angle_mshp self.last_theta['centre'] = centre_angle_mshp self.last_theta['right'] = right_angle_mshp self.v_x['slow'] = mshp.trimf(self.v_interval, [0, 0, 0.32]) self.v_x['medium'] = mshp.gaussmf(self.v_interval, 0.5, 0.36) self.v_x['fast'] = mshp.trapmf(self.v_interval, [0.75, 0.95, 1.0, 1.0]) # Here the rules are defined! # look at http://pythonhosted.org/scikit-fuzzy/auto_examples/plot_control_system_advanced.html#set-up-the-fuzzy-control-system # and http://pythonhosted.org/scikit-fuzzy/auto_examples/plot_tipping_problem_newapi.html # for good examples rules = [] # Sonars are NOT dangerous, go fast and forward rules.append(ctrl.Rule(label="FastAndForward", antecedent=(~self.lsonar['dangerous'] & ~self.rsonar['dangerous']), consequent=(self.theta['centre'], self.v_x['fast']))) # Right sonar reads dangerous, left does not, steer left rules.append(ctrl.Rule(label="SteerLeftCaution", antecedent=(~self.lsonar['dangerous'] & self.rsonar['dangerous']), consequent=(self.theta['left'], self.v_x['slow']))) # Left sonar reads dangerous, right does not, steer left rules.append(ctrl.Rule(label="SteerRightCaution", antecedent=(self.lsonar['dangerous'] & ~self.rsonar['dangerous']), consequent=(self.theta['right'], self.v_x['slow']))) # Right sonar is NOT safe, left reads safe, turn left full speed rules.append(ctrl.Rule(label="SteerLeftReckless", antecedent=(self.lsonar['safe'] & ~self.rsonar['safe']), consequent=(self.theta['left'], self.v_x['fast']))) # Left sonar is NOT safe, right reads safe, turn right full speed rules.append(ctrl.Rule(label="SteerRightReckless", antecedent=(~self.lsonar['safe'] & self.rsonar['safe']), consequent=(self.theta['right'], self.v_x['fast']))) # Left sonar is NOT dangerous and right is NOT safe, turn left medium speed rules.append(ctrl.Rule(label="SteerLeftWatchSpeed", antecedent=(~self.lsonar['dangerous'] & ~self.rsonar['safe']), consequent=(self.theta['left'], self.v_x['medium']))) # Right sonar is NOT dangerous and left is NOT safe, turn right medium speed rules.append(ctrl.Rule(label="SteerRightWatchSpeed", antecedent=(~self.lsonar['safe'] & ~self.rsonar['dangerous']), consequent=(self.theta['right'], self.v_x['medium']))) # Last theta was right, right sonar is dangerous, turn left slow speed rules.append(ctrl.Rule(label="SteerLeftMedSpeed", antecedent=(self.rsonar['dangerous'] & self.last_theta['right']), consequent=(self.theta['left'], self.v_x['medium']))) # Last theta was left, left sonar is dangerous, turn right slow speed rules.append(ctrl.Rule(label="SteerRightMedSpeed", antecedent=(self.lsonar['dangerous'] & self.last_theta['left']), consequent=(self.theta['right'], self.v_x['medium']))) # Last theta was left, rsonar reads not dangerous, turn centre, full speed rules.append(ctrl.Rule(label="OutOfDangerFromLeft", antecedent=(~self.rsonar['dangerous'] & self.last_theta['left']), consequent=(self.theta['centre'], self.v_x['fast']))) # Last theta was right, lsonar reads not dangerous, turn centre, full speed rules.append(ctrl.Rule(label="OutOfDangerFromRight", antecedent=(~self.lsonar['dangerous'] & self.last_theta['right']), consequent=(self.theta['centre'], self.v_x['fast']))) # Create the control system self.system = ctrl.ControlSystem(rules=rules) # System is created, just create a simulation, input values and call compute() self.sim = ctrl.ControlSystemSimulation(self.system)
import numpy as np from skfuzzy import control as ctrl from skfuzzy import membership as mf speed = ctrl.Antecedent(np.arange(0, 85, 0.1), 'speed') distance = ctrl.Antecedent(np.arange(0, 3000, 0.5), 'distance') brake = ctrl.Consequent(np.arange(0, 100, 0.5), 'brake') throttle = ctrl.Consequent(np.arange(0, 100, 0.5), 'throttle') speed['stopped'] = mf.trimf(speed.universe, [0, 0, 2]) speed['very slow'] = mf.trimf(speed.universe, [1, 2.5, 4]) speed['slow'] = mf.trimf(speed.universe, [2.5, 6.5, 10.5]) speed['medium fast'] = mf.trimf(speed.universe, [6.5, 26.5, 46.5]) speed['fast'] = mf.trapmf(speed.universe, [26.5, 70, 85, 85]) distance['at'] = mf.trimf(distance.universe, [0, 0, 2]) distance['very near'] = mf.trimf(distance.universe, [1, 3, 5]) distance['near'] = mf.trimf(distance.universe, [3, 101.5, 200]) distance['medium far'] = mf.trimf(distance.universe, [100, 1550, 3000]) distance['far'] = mf.trapmf(distance.universe, [1500, 2250, 3000, 3000]) brake['no'] = mf.trimf(brake.universe, [0, 0, 40]) brake['very slight'] = mf.trimf(brake.universe, [20, 50, 80]) brake['slight'] = mf.trimf(brake.universe, [70, 83.5, 97]) brake['medium'] = mf.trimf(brake.universe, [95, 97, 99]) brake['full'] = mf.trimf(brake.universe, [98, 100, 100]) throttle['no'] = mf.trimf(throttle.universe, [0, 0, 2]) throttle['very slight'] = mf.trimf(throttle.universe, [1, 3, 5]) throttle['slight'] = mf.trimf(throttle.universe, [3, 16.5, 30]) throttle['medium'] = mf.trimf(throttle.universe, [20, 50, 80])
import matplotlib.pyplot as plt import skfuzzy.membership as skmemb def visualise_all(x, y1, y2, all_norms=_all_norms): '''Plot the norm and conorm for the given sample inputs''' ncols = 3 fig, axes = plt.subplots(nrows=len(all_norms), ncols=ncols, figsize=(8, 9)) fig.tight_layout() fig.subplots_adjust(bottom=-.25) for row, name in enumerate(_all_norms.keys()): for col in range(ncols): # so all have the same (0,1) y-axis axes[row][col].set_ylim([-0.05, 1.05]) axes[row][0].set_title('Sample inputs') axes[row][0].plot(x, y1) axes[row][0].plot(x, y2) axes[row][1].set_title(name + ' norm') axes[row][1].plot(x, _all_norms[name].and_func(y1, y2)) axes[row][2].set_title(name + ' co-norm') axes[row][2].plot(x, _all_norms[name].or_func(y1, y2)) if __name__ == '__main__': for fam in _all_norms.values(): check_classic(fam) check_duality(fam) sample_x = np.arange(0, 100) sample_y1 = skmemb.trapmf(sample_x, [15, 30, 55, 75]) sample_y2 = skmemb.trapmf(sample_x, [25, 45, 70, 85]) visualise_all(sample_x, sample_y1, sample_y2)
import matplotlib.pyplot as plt # In[45]: x_bodytemp = np.arange(20, 50 , 1) x_respiratory = np.arange(0, 50 , 1) x_pulse = np.arange(0, 150 , 1) y_areacolour = np.arange(0, 4, 1) # In[46]: bodytemp_verylow = mf.trapmf(x_bodytemp, [-100, 0, 30, 34.5]) bodytemp_low = mf.trapmf(x_bodytemp, [0, 34.5, 35 ,36 ]) bodytemp_normal = mf.trimf(x_bodytemp, [36, 36.5, 37]) bodytemp_high = mf.trapmf(x_bodytemp, [36, 38, 41, 42]) bodytemp_veryhigh = mf.trapmf(x_bodytemp, [41, 42,45, 100]) # In[47]: respiratory_low = mf.trimf(x_respiratory, [-100, 0, 12]) respiratory_normal = mf.trapmf(x_respiratory, [8, 12, 20, 24]) respiratory_high = mf.trimf(x_respiratory, [20, 50, 100]) # In[48]: