def __init__(self): # INPUTY self.buildingType = ctrl.Antecedent(np.arange(0, 400, 1), "Technologia budynku") self.wearWater = ctrl.Antecedent(np.arange(0, 500, 0.1), "Zuzycie wody na osobe") self.zone = ctrl.Antecedent(np.arange(15, 25, 0.01), "Strefa klimatyczna") self.isolation = ctrl.Antecedent(np.arange(1, 100, 1), "Procentowa termoizolacja budynku") self.surface = ctrl.Antecedent(np.arange(20, 150, 0.01), "Powierzchnia grzewcza") # OUTPUTY self.typeFurnance = ctrl.Consequent(np.arange(1, 100, 1), "Rodzaj pieca") # MEMBERSHIPS FUN self.buildingType['starebudownictwo'] = fuzz.trapmf(self.buildingType.universe, [170, 350, 400, 400]) self.buildingType['70-85'] = fuzz.gaussmf(self.buildingType.universe, 260, 25) self.buildingType['86-92'] = fuzz.gaussmf(self.buildingType.universe, 200, 20) self.buildingType['93-97'] = fuzz.gaussmf(self.buildingType.universe, 160, 15) self.buildingType['98-07'] = fuzz.gaussmf(self.buildingType.universe, 120, 15) self.buildingType['energooszczedny'] = fuzz.gaussmf(self.buildingType.universe, 80, 15) self.buildingType['niskoenegetyczny'] = fuzz.gaussmf(self.buildingType.universe, 45, 10) self.buildingType['pasywny'] = fuzz.trapmf(self.buildingType.universe, [0, 0, 15, 100]) # ---------------------- self.wearWater['1 osoba'] = fuzz.zmf(self.wearWater.universe, 20, 80) self.wearWater['2 osoba'] = fuzz.gaussmf(self.wearWater.universe, 100, 30) self.wearWater['3 osoba'] = fuzz.gaussmf(self.wearWater.universe, 150, 30) self.wearWater['4 osoba'] = fuzz.gaussmf(self.wearWater.universe, 200, 40) self.wearWater['5 osoba'] = fuzz.gaussmf(self.wearWater.universe, 250, 50) self.wearWater['6 osoba'] = fuzz.gaussmf(self.wearWater.universe, 300, 60) self.wearWater['7 osoba'] = fuzz.gaussmf(self.wearWater.universe, 350, 60) self.wearWater['8 osoba'] = fuzz.smf(self.wearWater.universe, 310, 470) # ---------------------- self.zone['Strefa 1'] = fuzz.gaussmf(self.zone.universe, 16, 0.5) self.zone['Strefa 2'] = fuzz.gaussmf(self.zone.universe, 18, 0.9) self.zone['Strefa 3'] = fuzz.gaussmf(self.zone.universe, 20, 1.5) self.zone['Strefa 4'] = fuzz.gaussmf(self.zone.universe, 22, 1.2) self.zone['Strefa 5'] = fuzz.gaussmf(self.zone.universe, 24, 0.45) # --------------------- self.surface['kawalerka'] = fuzz.zmf(self.surface.universe, 25, 65) self.surface['mieszkanie'] = fuzz.gaussmf(self.surface.universe, 75, 30) self.surface['apartament'] = fuzz.gaussmf(self.surface.universe, 111, 8) self.surface['dom_jednorodzinny'] = fuzz.gaussmf(self.surface.universe, 130, 3.5) self.surface['willa'] = fuzz.smf(self.surface.universe, 130, 150) # -------------------- self.isolation['brak'] = fuzz.zmf(self.isolation.universe, 5, 15) self.isolation['slabo'] = fuzz.gaussmf(self.isolation.universe, 20, 7) self.isolation['srednio'] = fuzz.gaussmf(self.isolation.universe, 50, 20) self.isolation['dobrze'] = fuzz.gaussmf(self.isolation.universe, 70, 10) self.isolation['doskonale'] = fuzz.smf(self.isolation.universe, 75, 95) self.typeFurnance['weglowy'] = fuzz.zmf(self.typeFurnance.universe, 4, 40) self.typeFurnance['gazowy'] = fuzz.gbellmf(self.typeFurnance.universe, 23, 2.5, 50) self.typeFurnance['pompa ciepla'] = fuzz.smf(self.typeFurnance.universe, 70, 100) # ----------------------- # RULES rules = [ ctrl.Rule(self.buildingType['pasywny'] & self.wearWater['4 osoba'] & self.surface['dom_jednorodzinny'] & self.isolation['doskonale'], self.typeFurnance['pompa ciepla']), ctrl.Rule(self.buildingType['starebudownictwo'] & self.wearWater['8 osoba'] & self.isolation['brak'] & self.surface['dom_jednorodzinny'], self.typeFurnance['weglowy']), ctrl.Rule(self.buildingType['starebudownictwo'] & self.wearWater['7 osoba'] & self.isolation['slabo'] & self.surface['dom_jednorodzinny'], self.typeFurnance['weglowy']), ctrl.Rule(self.buildingType['starebudownictwo'] & self.wearWater['6 osoba'] & self.isolation['slabo'] & self.surface['dom_jednorodzinny'], self.typeFurnance['weglowy']), ctrl.Rule(self.buildingType['70-85'] & self.wearWater['6 osoba'] & self.isolation['slabo'] & self.surface[ 'dom_jednorodzinny'], self.typeFurnance['weglowy']), ctrl.Rule(self.buildingType['niskoenegetyczny'] & self.wearWater['5 osoba'] & self.isolation['dobrze'] & self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']), ctrl.Rule(self.buildingType['energooszczedny'] & self.wearWater['5 osoba'] & self.isolation['dobrze'] & self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']), ctrl.Rule(self.buildingType['energooszczedny'] & self.wearWater['4 osoba'] & self.isolation['dobrze'] & self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']), ctrl.Rule(self.buildingType['niskoenegetyczny'] & self.wearWater['5 osoba'] & self.isolation['dobrze'] & self.surface['dom_jednorodzinny'] | self.surface['willa'], self.typeFurnance['pompa ciepla']), ctrl.Rule(self.buildingType['93-97'] & self.wearWater['2 osoba'] & self.isolation['srednio'] & self.surface[ 'kawalerka'], self.typeFurnance['gazowy']), ctrl.Rule(self.buildingType['93-97'] & self.wearWater['3 osoba'] & self.isolation['srednio'] & self.surface[ 'mieszkanie'], self.typeFurnance['gazowy']), ctrl.Rule(self.buildingType['93-97'] & self.wearWater['4 osoba'] & self.isolation['srednio'] & self.surface[ 'mieszkanie'], self.typeFurnance['gazowy']), ctrl.Rule(self.buildingType['98-07'] & self.wearWater['2 osoba'] & self.isolation['srednio'] & self.surface[ 'kawalerka'], self.typeFurnance['gazowy']), ctrl.Rule(self.buildingType['98-07'] & self.wearWater['3 osoba'] & self.isolation['srednio'] & self.surface[ 'mieszkanie'], self.typeFurnance['gazowy']), ctrl.Rule(self.buildingType['98-07'] & self.wearWater['4 osoba'] & self.isolation['srednio'] & self.surface[ 'mieszkanie'], self.typeFurnance['gazowy']), ctrl.Rule(self.buildingType['98-07'] & self.wearWater['5 osoba'] & self.isolation['srednio'] & self.surface[ 'apartament'], self.typeFurnance['gazowy']), ] # Controll System self.typeControl = ctrl.ControlSystem(rules) self.type = ctrl.ControlSystemSimulation(self.typeControl)
def generate_mf(self): # Generate fuzzy membership functions self.parr_est['low'] = fuzz.trapmf(self.parr_est.universe, [0, 0, 0.3, 0.4]) self.parr_est['medium'] = fuzz.gaussmf(self.parr_est.universe, 0.5, 0.1) self.parr_est['high'] = fuzz.trapmf(self.parr_est.universe, [0.6, 0.7, 1.0, 1.0]) self.parr_est.view() self.lat_est['low'] = fuzz.trapmf(self.lat_est.universe, [0, 0, 0.3, 0.4]) self.lat_est['medium'] = fuzz.gaussmf(self.lat_est.universe, 0.5, 0.1) self.lat_est['high'] = fuzz.trapmf(self.lat_est.universe, [0.6, 0.7, 1.0, 1.0]) self.lat_est.view() self.band_ratio['low'] = fuzz.trapmf(self.band_ratio.universe, [0, 0, 0.3, 0.4]) self.band_ratio['medium'] = fuzz.gaussmf(self.band_ratio.universe, 0.5, 0.1) self.band_ratio['high'] = fuzz.trapmf(self.band_ratio.universe, [0.6, 0.7, 1.0, 1.0]) self.band_ratio.view() self.others_info['no'] = fuzz.trapmf(self.others_info.universe, [0, 0, 0.500, 0.500]) self.others_info['yes'] = fuzz.trapmf(self.others_info.universe, [0.500, 0.500, 1.0, 1.0]) self.others_info.view() self.container_loc['end'] = fuzz.trapmf(self.container_loc.universe, [0, 0, 0.3, 0.4]) self.container_loc['edge'] = fuzz.gaussmf(self.container_loc.universe, 0.5, 0.05) self.container_loc['cloud'] = fuzz.trapmf(self.container_loc.universe, [0.6, 0.7, 1.0, 1.0]) self.container_loc.view() self.generate_rules()
def carbonate_control(self): rate_sigma = 0.15 low = fuzz.gaussmf(self.carbgrowth, 0.2, rate_sigma) id = np.where(self.carbgrowth < 0.2)[0] low[id] = 1 id = np.where(self.carbgrowth > 1)[0] low[id] = 0 mid_sigma = 0.15 mid2 = fuzz.gaussmf(self.carbgrowth, 0.75, mid_sigma) mid = fuzz.gaussmf(self.carbgrowth, 1.25, mid_sigma) id1 = np.where(self.carbgrowth < 0.75)[0] id2 = np.where(self.carbgrowth > 1.25)[0] mid[id1[-1] : id2[0]] = 1.0 mid[: id1[-1]] = mid2[: id1[-1]] id = np.where(self.carbgrowth <= 0)[0] mid[id] = 0 mid[mid < 0.00001] = 0.0 high_sigma = 0.2 high = 1.0 - fuzz.gaussmf(self.carbgrowth, 1.2, high_sigma) id = np.where(self.carbgrowth < 1.2)[0] high[id] = 0 # Consequent object self.growth = ctrl.Consequent(self.carbgrowth, "growth") # Membership functions population self.growth["low"] = low self.growth["mid"] = mid self.growth["high"] = high return
def __init__(self): self.max_angle = 25.0 / 180 * math.pi inp_discr = 1.0 / 180 * math.pi inp_mean = 20.0 / 180 * math.pi inp_sigma = 20.0 / 180 * math.pi inp_values = np.linspace(-self.max_angle, self.max_angle, int(2 * self.max_angle / inp_discr) + 1) input = ctrl.Antecedent(inp_values, 'input') input['low'] = fuzz.gaussmf(input.universe, -inp_mean, inp_sigma) input['high'] = fuzz.gaussmf(input.universe, inp_mean, inp_sigma) self.max_output = 1 output_discr = 0.1 outp_mean1 = 0.4 outp_mean2 = 1 outp_hbreadth = 0.2 outp_values = np.linspace(-self.max_output, self.max_output, int(2 * self.max_output / output_discr) + 1) output = ctrl.Consequent(outp_values, 'output') output['too low'] = fuzz.trimf(output.universe, [-outp_mean2 - outp_hbreadth, -outp_mean2, -outp_mean2 + outp_hbreadth]) output['low'] = fuzz.trimf(output.universe, [-outp_mean1 - outp_hbreadth, -outp_mean1, -outp_mean1 + outp_hbreadth]) output['high'] = fuzz.trimf(output.universe, [outp_mean1 - outp_hbreadth, outp_mean1, outp_mean1 + outp_hbreadth]) output['too high'] = fuzz.trimf(output.universe, [outp_mean2 - outp_hbreadth, outp_mean2, outp_mean2 + outp_hbreadth]) rule1 = ctrl.Rule(input['low'] , output['high']) rule2 = ctrl.Rule(input['high'] , output['low']) rule3 = ctrl.Rule(input['high'] , output['too low']) rule4 = ctrl.Rule(input['low'] , output['too high']) control_system = ctrl.ControlSystem([rule1, rule2, rule3, rule4]) self.simulation = ctrl.ControlSystemSimulation(control_system)
def __init__(self, minm, maxm, n_variavel, media=None, dp=None, dados=None, passo=0.01, likert=3, tipo='antecedente'): # dados: vetor de dados de referência. # minm: valor mínimo.git init. # maxm: valor máximo. # n_variavel: nome da variavel. # passo: nível de discretização da variável fuzzy. # tipo: tipo de variável fuzzy. # likert: tamanho da escala. self.min = minm self.max = maxm # Calcula a média e desvio padrão a partir dos dados fornecidos, # caso contrário os estima a partir dos valores mínimo e máximo. try: self.media = dados.mean() self.dp = dados.std() media = self.media dp = self.dp except Exception: try: self.media = media * 1 self.dp = dp * 1 except Exception: self.media = (minm + maxm) / 2 self.dp = ((maxm - minm)**2 / 12)**0.5 media = self.media dp = self.dp if tipo == 'consequente': self.vf = ctrl.Consequent(np.arange(minm, maxm, passo), n_variavel) else: self.vf = ctrl.Antecedent(np.arange(minm, maxm, passo), n_variavel) if (likert == 5): self.vf['muito baixo'] = fuzz.zmf(self.vf.universe, media - 5 * dp, media - 2 * dp) self.vf['baixo'] = fuzz.gaussmf(self.vf.universe, media - 2 * dp, dp) self.vf['medio'] = fuzz.gaussmf(self.vf.universe, media, dp) self.vf['alto'] = fuzz.gaussmf(self.vf.universe, media + 2 * dp, dp) self.vf['muito alto'] = fuzz.smf(self.vf.universe, media + 2 * dp, media + 5 * dp) elif (likert == 3): self.vf['baixo'] = fuzz.zmf(self.vf.universe, minm, media) self.vf['medio'] = fuzz.gaussmf(self.vf.universe, media, dp) self.vf['alto'] = fuzz.smf(self.vf.universe, media, maxm) else: raise RuntimeError( "Utilize escalas tipo likert com 3 ou 5 categorias.")
def main(): X, y = make_blobs(n_samples=1000, centers=4, random_state=0) X = pd.DataFrame(X) cols = ["F0", "F1"] X.columns = cols y[y == 2] = 0 not_visible = y == 3 y[not_visible] = 1 w = np.argwhere(not_visible) y[w[-1]] = 0 X_visible = X.iloc[~not_visible] y_visible = y[~not_visible] # New Antecedent/Consequent objects hold universe variables and membership functions feature1 = ctrl.Antecedent(np.arange(-6, 6, 1), X.columns[0]) feature1['G1'] = fuzz.gaussmf(feature1.universe, -2, 2) feature1['G2'] = fuzz.gaussmf(feature1.universe, 2, 2) feature1.view() feature2 = ctrl.Antecedent(np.arange(-4, 12, 1), X.columns[1]) feature2['G1'] = fuzz.sigmf(feature2.universe, 2, -2) feature2['G2'] = fuzz.gaussmf(feature2.universe, 3, 2) feature2['G3'] = fuzz.sigmf(feature2.universe, 5, 2) feature2.view() label = ctrl.Consequent(np.arange(0, 11, 1), 'label') label['L0'] = fuzz.gaussmf(label.universe, 0, 2) label['L1'] = fuzz.gaussmf(label.universe, 10, 2) label.view() # rules rule1 = ctrl.Rule(feature1['G1'] & feature2['G2'], label['L0']) rule3 = ctrl.Rule(feature2['G3'], label['L1']) # control ctrl_sys = ctrl.ControlSystem([rule1, rule3]) fuzzy_ctrl = ctrl.ControlSystemSimulation(ctrl_sys) # load ML models model = RandomForestClassifier(random_state=0) fuzzy_model = FuzzyClassifier(model, fuzzy_ctrl, alpha=0.7, random_state=42) # fit fuzzy model fuzzy_model.fit(X_visible, y_visible) score_fz = fuzzy_model.score(X, y) # fit standard model model.fit(X_visible, y_visible) score_dt = model.score(X, y) plt.figure(figsize=[10, 5]) plt.subplot(121) plot_decision_function(fuzzy_model, "Fuzzy - acc %.2f" % score_fz, X, y, not_visible) plt.subplot(122) plot_decision_function(model, "No rules - acc %.2f" % score_dt, X, y, not_visible) plt.tight_layout() plt.savefig("./decision_boundaries.png") plt.show() return
def calculate_raf_mfs( egfr, akt, raf): egfr_low = fuzz.zmf(egfr, 0, 0.95) egfr_high = fuzz.smf(egfr, 0.1, 0.9) akt_low = fuzz.zmf(akt, 0, 0.95) akt_high = fuzz.smf(akt, 0.1, 0.9) raf_low = fuzz.gaussmf(raf, 0, egfr[egfr.size - 1]/20) raf_high = fuzz.gaussmf(raf, egfr[egfr.size - 1], egfr[egfr.size - 1]/20) return ((egfr_low, egfr_high), (akt_low, akt_high), (raf_low, raf_high))
def get_conf_mf(df, conf): # confidence (gaussian) conf['very_low'] = gaussmf(conf.universe, 0, 20) conf['low'] = gaussmf(conf.universe, 50, 10) conf['med'] = gaussmf(conf.universe, 70, 10) conf['high'] = gaussmf(conf.universe, 90, 10) conf['very_high'] = gaussmf(conf.universe, 100, 10) return conf
def calculate_pi3k_mfs(egfr, erk, pi3k): egfr_low = fuzz.zmf(egfr, 0, 0.95) egfr_high = fuzz.smf(egfr, 0.1, 0.9) erk_low = fuzz.zmf(erk, 0, 0.9) erk_high = fuzz.smf(erk, 0, 0.9) pi3k_low = fuzz.gaussmf(pi3k, 0, egfr[egfr.size - 1]/20) pi3k_high = fuzz.gaussmf(pi3k, egfr[egfr.size - 1], egfr[egfr.size - 1]/20) return ((egfr_low, egfr_high), (erk_low, erk_high), (pi3k_low, pi3k_high))
def extract_rules(X, y, alpha=0.05, verbose=False): y_set = set(y) # consequent step = 0.1 variance = 3 label = ctrl.Consequent(np.arange(0, 10 * (len(y_set) - 1) + step, step), 'label') for yi in y_set: label[f'L{yi}'] = fuzz.gaussmf(label.universe, 10 * yi, variance) if verbose: label.view() rule_dict = dict() extracted_rules = [] for c in range(0, X.shape[1]): v = X.iloc[:, c].var() / 10 val_range = np.arange(X.iloc[:, c].min() - v, X.iloc[:, c].max() + v, v) feature = ctrl.Antecedent(val_range, X.columns[c]) y_set_2 = copy.deepcopy(y_set) for yi in y_set: y_set_2.remove(yi) for yj in y_set_2: x0, x1 = X.iloc[y == yi, c], X.iloc[y == yj, c] t, p = stats.ttest_ind(x0, x1, equal_var=False) m0, m1 = np.mean(x0), np.mean(x1) if p < alpha: # rule A rule_str = f'{X.columns[c]}[Y{yi}] -> L{yi}' if rule_str not in rule_dict: feature[f'Y{yi}'] = fuzz.gaussmf( feature.universe, m0, v) ruleA = ctrl.Rule(feature[f'Y{yi}'], label[f'L{yi}']) extracted_rules.append(ruleA) rule_dict[rule_str] = True # rule B rule_str = f'{X.columns[c]}[Y{yj}] -> L{yj}' if rule_str not in rule_dict: feature[f'Y{yj}'] = fuzz.gaussmf( feature.universe, m1, v) ruleB = ctrl.Rule(feature[f'Y{yj}'], label[f'L{yj}']) extracted_rules.append(ruleB) rule_dict[rule_str] = True if verbose: print( f"F{c}\n\t{m1:.2f} -> y=1 [p={p:.2f}]\n\t{m0:.2f} -> y=0" ) feature.view() return extracted_rules
def __init__(self, ref, view=False): # Referência, força aplicada e força máxima capaz de ser aplicada # pelo controlador self.ref = ref self.f = 0 self.f_max = 1.5*abs(m*g) # Intervalos das variáveis de entrada self.position_error_range = numpy.arange(-100, 100, 0.01) self.velocity_range = numpy.arange(-100, 100, 0.01) # Intervalo da variável de saída self.output_range = numpy.arange(-1, 1, 0.01) # Definição das funções de pertinência da variável de erro de posição self.e_N = skfuzzy.sigmf(self.position_error_range, -5, -1) self.e_Z = skfuzzy.gaussmf(self.position_error_range, 0, 2) self.e_P = skfuzzy.sigmf(self.position_error_range, 5, 1) # Definição das funções de pertinência da variável de velocidade self.v_N = skfuzzy.sigmf(self.velocity_range, -5, -1) self.v_Z = skfuzzy.gaussmf(self.velocity_range, 0, 2) self.v_P = skfuzzy.sigmf(self.velocity_range, 5, 1) # Definição das funções de pertinência da variável de saída self.o_N = skfuzzy.sigmf(self.output_range, -0.5, -10) self.o_Z = skfuzzy.gaussmf(self.output_range, 0, 0.2) self.o_P = skfuzzy.sigmf(self.output_range, 0.5, 10) # Visualização das funções de pertinência das entradas e saídas if view: fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, figsize=(8, 9)) ax0.plot(self.position_error_range, self.e_N, 'b', linewidth=1.5, label='Negativo') ax0.plot(self.position_error_range, self.e_Z, 'g', linewidth=1.5, label='Zero') ax0.plot(self.position_error_range, self.e_P, 'r', linewidth=1.5, label='Positivo') ax0.set_title('Erro de posição') ax0.legend() ax1.plot(self.velocity_range, self.v_N, 'b', linewidth=1.5, label='Negativo') ax1.plot(self.velocity_range, self.v_Z, 'g', linewidth=1.5, label='Zero') ax1.plot(self.velocity_range, self.v_P, 'r', linewidth=1.5, label='Positivo') ax1.set_title('Velocidade') ax1.legend() ax2.plot(self.output_range, self.o_N, 'b', linewidth=1.5, label='Redução') ax2.plot(self.output_range, self.o_Z, 'g', linewidth=1.5, label='Manutenção') ax2.plot(self.output_range, self.o_P, 'r', linewidth=1.5, label='Aumento') ax2.set_title('Saída') ax2.legend() for ax in (ax0, ax1, ax2): ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.tight_layout()
def get_distance_mf(df, distance): # here, the first numnber is the universe, second number the central point, third the standard deviation distance['low'] = gaussmf(distance.universe, 0, (df['Distance'].max() / 10)) distance['med'] = gaussmf(distance.universe, (df['Distance'].max() / 4), (df['Distance'].max() / 10)) distance['high'] = gaussmf(distance.universe, df['Distance'].max(), (df['Distance'].max() / 2.5)) return distance
def get_total_nb_hom_mf(df, total_nb_hom): copy_nr_median = df['TotalCopyNr'].median() total_nb_hom['low'] = gaussmf(total_nb_hom.universe, copy_nr_median, copy_nr_median) total_nb_hom['med'] = gaussmf(total_nb_hom.universe, 4 * copy_nr_median, 1.5 * copy_nr_median) total_nb_hom['high'] = gaussmf(total_nb_hom.universe, df['TotalCopyNr'].max(), df['TotalCopyNr'].max() / 2.5) return total_nb_hom
def __init__(self): # Max and min values maxSpeed = 30 mimSpeed = 20 maxAngle = 37 mimAngle = -37 maxIS = 30 mimIS = 0 # Create the problem variables (Antecedent IS = ctrl.Antecedent(np.arange(mimIS, maxIS + 1, 1), 'IS') RG = ctrl.Antecedent(np.arange(mimAngle, maxAngle + 1, 1), 'RG') A10 = ctrl.Antecedent(np.arange(mimAngle, maxAngle, 1), 'A10') A30 = ctrl.Antecedent(np.arange(mimAngle, maxAngle, 1), 'A30') A50 = ctrl.Antecedent(np.arange(mimAngle, maxAngle, 1), 'A50') A70 = ctrl.Antecedent(np.arange(mimAngle, maxAngle, 1), 'A70') # Create the problem variables (Consequent) S = ctrl.Consequent(np.arange(mimSpeed, maxSpeed + 1, 1), 'S') # Automatically creates mapping between crisp and fuzzy values # using a standard membership function (triangle) RG.automf(names=['negative', 'neutral', 'positive']) # Creates membership functions using different types A10['negative'] = fuzz.gaussmf(A10.universe, mimAngle, 30) A10['neutral'] = fuzz.gaussmf(A10.universe, 0, 30) A10['positive'] = fuzz.gaussmf(A10.universe, maxAngle, 30) # Consequent: mapping between crisp and fuzzy values S.automf(names=['verylow', 'low', 'medium', 'high', 'veryhigh']) # Fuzzy rules creation rule1 = ctrl.Rule(RG['negative'] & A10['negative'], S['veryhigh']) rule2 = ctrl.Rule(RG['negative'] & A10['neutral'], S['veryhigh']) rule3 = ctrl.Rule(RG['negative'] & A10['positive'], S['high']) rule4 = ctrl.Rule(RG['neutral'] & A10['negative'], S['high']) rule4 = ctrl.Rule(RG['neutral'] & A10['neutral'], S['high']) rule4 = ctrl.Rule(RG['neutral'] & A10['positive'], S['high']) rule5 = ctrl.Rule(RG['positive'] & A10['negative'], S['medium']) rule6 = ctrl.Rule(RG['positive'] & A10['neutral'], S['medium']) rule7 = ctrl.Rule(RG['positive'] & A10['positive'], S['low']) # Creating and simulating a fuzzy controller S_ctrl = ctrl.ControlSystem( [rule1, rule2, rule3, rule4, rule5, rule6, rule7]) self.S_simulator = ctrl.ControlSystemSimulation(S_ctrl)
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
def membership_f(mf, x, abcd): """ Returns y values corresponding to type of type of Membership fn. arguments: mf - string containing type of Membership function x - x axis values """ if mf == 'zmf': return fuzz.zmf(x, abcd[0], abcd[1]) # zmf(x, a, b) elif mf == 'trimf': return fuzz.trimf(x, abcd[0:3]) # trimf(x, abc) elif mf == 'dsigmf': return fuzz.dsigmf(x, abcd[0], abcd[1], abcd[2], abcd[3]) # dsigmf(x, b1, c1, b2, c2) elif mf == 'gauss2mf': return fuzz.gauss2mf( x, abcd[0], abcd[1], abcd[2], abcd[3]) # gauss2mf(x, mean1, sigma1, mean2, sigma2) elif mf == 'gaussmf': return fuzz.gaussmf(x, abcd[0], abcd[1]) # gaussmf(x, mean, sigma) elif mf == 'gbellmf': return fuzz.gbellmf(x, abcd[0], abcd[1], abcd[2]) # gbellmf(x, a, b, c) elif mf == 'piecemf': return fuzz.piecemf(x, abcd[0:3]) # piecemf(x, abc) elif mf == 'pimf': return fuzz.pimf(x, abcd[0], abcd[1], abcd[2], abcd[3]) # pimf(x, a, b, c, d) elif mf == 'psigmf': return fuzz.psigmf(x, abcd[0], abcd[1], abcd[2], abcd[3]) # psigmf(x, b1, c1, b2, c2) elif mf == 'sigmf': return fuzz.sigmf(x, abcd[0], abcd[1]) # sigmf(x, b, c) elif mf == 'smf': return fuzz.smf(x, abcd[0], abcd[1]) # smf(x, a, b) elif mf == 'trapmf': return fuzz.trapmf(x, abcd) # trapmf(x, abcd)
def helper_dcentroid(mean=0, sigma=1, dc=0): x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, mean, sigma) assert_allclose(mean, fuzz.dcentroid(x, gmf, dc), atol=1e-3) assert_allclose(fuzz.centroid(x, gmf), fuzz.dcentroid(x, gmf, 0)) return None
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')
def __createMF(self, mf_type, params, universe): return { "trapezoid": lambda *args: fuzz.trapmf(*args), "gaussian": lambda *args: fuzz.gaussmf(*args), "sigmoid": lambda *args: fuzz.sigmf(*args) }.get(mf_type.lower(), lambda *args: fuzz.trimf(*args))(universe, params)
def rangeToMF(range, type): """ Translate the range into a list of x_values and an MF function. range : list/tuple range to translate to MF type : string type of MF: 'sing' - singleton MF 'gauss' - gaussian MF function (mean, standard deviation) 'tri' - triangular MF function 'trap' - trapezoidal MF function """ c = 100 #number of x points minR = float(min(range)) maxR = float(max(range)) if type == 'sing': #singleton c = 10 #special short mf for singleton if maxR == minR: #print "SAME R" ran = max(abs(0.15*minR),0.0001) xrange = [minR-ran, minR+ran, ran/c] Xs = [minR-2.*ran, minR-1.*ran, minR, minR+1.*ran, minR+2.*ran,] Ys = [0.0, 0.0, 1.0, 0.0, 0.0] else: ran = abs(maxR-minR) xrange = [minR, maxR, ran/c] Xs, Ys = singleton_to_fuzzy(sum(range)/len(range), xrange) elif type == 'gauss': #gaussian MF std_range = (1./4.) #0.25 if minR == maxR: ran = max(0.0001,abs(0.05*minR))#0.05 else: ran = abs(maxR - minR) #check for min=max and get range Xs = np.arange(minR - 0.5*ran, maxR + 0.5*ran, 2*ran/c) Ys = fuzz.gaussmf(Xs, sum(range)/len(range), std_range*(ran)) #gaussian mf with 4sigma = range (to 97.7% "certainty") elif type == 'tri': #triangular MF if minR == maxR: ran = max(abs(0.2*minR),0.001) xrange = [0.9*minR, 1.1*maxR, ran/c,] Xs, Ys = singleton_to_fuzzy(sum(range)/len(range), xrange) else: Xs = np.arange(0.9*minR, 1.1*maxR, (1.1*maxR-0.9*minR)/c) #create fuzzy MF for output Ys = fuzz.trimf(Xs, [minR, sum(range)/len(range), maxR]) elif type == 'trap': #trapezoidal MF if minR == maxR: ran = max(abs(0.2*minR),0.001) xrange = [0.9*minR, 1.1*maxR, ran/c,] Xs, Ys = singleton_to_fuzzy(sum(range)/len(range), xrange) else: Xs = np.arange(0.9*minR, 1.1*maxR, (1.1*maxR-0.9*minR)/c) #create fuzzy MF for output Ys = fuzz.trapmf(Xs, [minR, minR, maxR, maxR]) else: raise StandardError("Unknown type of membership function: %s" % type) return [np.asarray(Xs), np.asarray(Ys)] #create MF
def generate_sign_type(x, tri, sign_type, sigma=0.5): if sign_type == 'tri': sign = fuzz.trimf(x, tri) elif sign_type == 'gaus': sign = fuzz.gaussmf(x, tri[1], sigma) return sign
def test_centroid(): def helper_centroid(mean=0, sigma=1): x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, mean, sigma) assert_allclose(mean, fuzz.centroid(x, gmf), atol=1e-2) return None def helper_dcentroid(mean=0, sigma=1, dc=0): x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, mean, sigma) assert_allclose(mean, fuzz.dcentroid(x, gmf, dc), atol=1e-2) assert_allclose(fuzz.centroid(x, gmf), fuzz.dcentroid(x, gmf, 0)) return None for mean in np.arange(-5, 5, 2): for sigma in range(1, 3): helper_centroid(mean, sigma) for differential_centroid in 42 * (np.arange(11) - 5): helper_dcentroid(mean, sigma, differential_centroid) # Test with ends @ zero, to evaluate special cases in new defuzz method x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, 0, np.pi) gmf[0] = 0 gmf[-1] = 0 assert_allclose(0, fuzz.centroid(x, gmf), atol=1e-8)
def helper_dcentroid(mean=0, sigma=1, dc=0): x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, mean, sigma) assert_allclose(mean, fuzz.dcentroid(x, gmf, dc), atol=1e-1) assert_allclose(fuzz.centroid(x, gmf), fuzz.dcentroid(x, gmf, 0)) return None
def membership_f(mf, x, abcd): """ Returns y values corresponding to type of type of Membership fn. arguments: mf - string containing type of Membership function x - x axis values """ if mf == "zmf": return fuzz.zmf(x, abcd[0], abcd[1]) # zmf(x, a, b) elif mf == "trimf": return fuzz.trimf(x, abcd[0:3]) # trimf(x, abc) elif mf == "dsigmf": return fuzz.dsigmf(x, abcd[0], abcd[1], abcd[2], abcd[3]) # dsigmf(x, b1, c1, b2, c2) elif mf == "gauss2mf": return fuzz.gauss2mf(x, abcd[0], abcd[1], abcd[2], abcd[3]) # gauss2mf(x, mean1, sigma1, mean2, sigma2) elif mf == "gaussmf": return fuzz.gaussmf(x, abcd[0], abcd[1]) # gaussmf(x, mean, sigma) elif mf == "gbellmf": return fuzz.gbellmf(x, abcd[0], abcd[1], abcd[2]) # gbellmf(x, a, b, c) elif mf == "piecemf": return fuzz.piecemf(x, abcd[0:3]) # piecemf(x, abc) elif mf == "pimf": return fuzz.pimf(x, abcd[0], abcd[1], abcd[2], abcd[3]) # pimf(x, a, b, c, d) elif mf == "psigmf": return fuzz.psigmf(x, abcd[0], abcd[1], abcd[2], abcd[3]) # psigmf(x, b1, c1, b2, c2) elif mf == "sigmf": return fuzz.sigmf(x, abcd[0], abcd[1]) # sigmf(x, b, c) elif mf == "smf": return fuzz.smf(x, abcd[0], abcd[1]) # smf(x, a, b) elif mf == "trapmf": return fuzz.trapmf(x, abcd) # trapmf(x, abcd)
def test_centroid(): def helper_centroid(mean=0, sigma=1): x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, mean, sigma) assert_allclose(mean, fuzz.centroid(x, gmf), atol=1e-1) return None def helper_dcentroid(mean=0, sigma=1, dc=0): x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, mean, sigma) assert_allclose(mean, fuzz.dcentroid(x, gmf, dc), atol=1e-1) assert_allclose(fuzz.centroid(x, gmf), fuzz.dcentroid(x, gmf, 0)) return None for mean in np.arange(-5, 5, 2): for sigma in range(1, 3): helper_centroid(mean, sigma) for differential_centroid in 42 * (np.arange(11) - 5): helper_dcentroid(mean, sigma, differential_centroid) # Test with ends @ zero, to evaluate special cases in new defuzz method x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, 0, np.pi) gmf[0] = 0 gmf[-1] = 0 assert_allclose(0, fuzz.centroid(x, gmf), atol=1e-8)
def compute_degree(ratio, crisp_value, mean, sigma): # cast a higher ratio to 2 since that will always be impossible to make if crisp_value > 2: crisp_value = 2 # compute membership degree return fuzz.interp_membership(ratio.universe, fuzz.gaussmf(ratio.universe, mean, sigma), crisp_value)
def calculate_egfr_mfs(time, egf, egfr, egf_index, t): size = egf.size #egfr = np.linspace(0, egf[egf_index], size) time_low = fuzz.zmf(time, 0, time[egf.size*t - t] - time[egf_index*t] + time[t] ) time_high = fuzz.smf(time, 0, time[egf.size*t - t] - time[egf_index*t] + time[t] ) egfr_low = fuzz.gaussmf(egfr, 0, egf[egf_index]/20) egfr_high = transform_gaussmf(egfr, (egf[egf_index], egf[egf_index]/20), 1) return ((time_low, time_high, egfr_low, egfr_high))
def relevance(distance: float): """ Given the distance, it returns a degree of pertinence. Necessary to apply the fuzzy technique, in adjusting the weights. For distance 0, returns the degree of relevance 1 """ universe = np.arange(0, 100, 1) return fuzz.interp_membership(universe, fuzz.gaussmf(universe, 0.0, 5), distance)
def plotMF(self, x, inputVar): for mf in range(len(self.memFuncs[inputVar])): if self.memFuncs[inputVar][mf][0] == 'gaussmf': y = gaussmf(x, **self.memClass.MFList[inputVar][mf][1]) plt.plot(x, y, 'r') plt.show()
def __init__(self): # Initialize sparse universe universe = np.linspace(-1.0, 1.0, 20) # Create fuzzy variables theta_error = ctrl.Antecedent(universe, 'theta_error') out_omega = ctrl.Consequent(universe, 'out_omega') # Using Gaussian membership function theta_error['nb'] = fuzzy.gaussmf(theta_error.universe, -0.8, 0.3) theta_error['ns'] = fuzzy.gaussmf(theta_error.universe, -0.2, 0.1) theta_error['ze'] = fuzzy.gaussmf(theta_error.universe, 0.0, 0.1) theta_error['ps'] = fuzzy.gaussmf(theta_error.universe, 0.2, 0.1) theta_error['pb'] = fuzzy.gaussmf(theta_error.universe, 0.8, 0.3) out_omega['nb'] = fuzzy.gaussmf(out_omega.universe, -0.8, 0.2) out_omega['ns'] = fuzzy.gaussmf(out_omega.universe, -0.4, 0.2) out_omega['ze'] = fuzzy.gaussmf(out_omega.universe, 0.0, 0.2) out_omega['ps'] = fuzzy.gaussmf(out_omega.universe, 0.4, 0.2) out_omega['pb'] = fuzzy.gaussmf(out_omega.universe, 0.8, 0.2) rule_0 = ctrl.Rule(antecedent=(theta_error['nb']), consequent=(out_omega['pb']), label='rule_0') rule_1 = ctrl.Rule(antecedent=(theta_error['ns']), consequent=(out_omega['ps']), label='rule_1') rule_2 = ctrl.Rule(antecedent=(theta_error['ze']), consequent=(out_omega['ze']), label='rule_2') rule_3 = ctrl.Rule(antecedent=(theta_error['ps']), consequent=(out_omega['ns']), label='rule_3') rule_4 = ctrl.Rule(antecedent=(theta_error['pb']), consequent=(out_omega['nb']), label='rule_4') # Construct controller self.fuzzy_system = ctrl.ControlSystem( rules=[rule_0, rule_1, rule_2, rule_3, rule_4])
def eval_membership_functions(initial_values): '''Technically they should have been calcultated using fuzz.someMf but since they are same to save computation we do this''' egf_high = fuzz.gaussmf(initial_values[0], 1, 0.1) egf_low = fuzz.gaussmf(initial_values[0], 0, 0.1) hrg_high = egf_high hrg_low = egf_low egfr_high = egf_high egfr_low = egf_low erk_high = egfr_high erk_low = egfr_low pi3k_high = egfr_high pi3k_low = egfr_low akt_high = egfr_high akt_low = egfr_low raf_high = egfr_high raf_low = egfr_low time_high = fuzz.smf(initial_values[7], 0, 1) time_low = fuzz.zmf(initial_values[7], 0, 1) return ((egf_low, egf_high), (hrg_low, hrg_high), (egfr_low, egfr_high), (raf_low, raf_high), (pi3k_low, pi3k_high), (erk_low, erk_high), \ (akt_low, akt_high), (time_low, time_high))
def antecedentes(): temperatura = ctrl.Antecedent(np.arange(-10, 41, 1), 'temperatura') tazaSize = ctrl.Antecedent( [0, 30, 60, 90, 120, 150, 200, 250, 300, 350, 400, 450, 451], 'tazaSize') intensidad = ctrl.Antecedent(np.arange(1, 6, 1), 'intensidad') temperatura['frio'] = fuzz.zmf(temperatura.universe, -10, 41) temperatura['calido'] = fuzz.gaussmf(temperatura.universe, 18, 10) temperatura['caluroso'] = fuzz.smf(temperatura.universe, -11, 41) tazaSize['pequeno'] = fuzz.zmf(tazaSize.universe, 0, 451) tazaSize['mediano'] = fuzz.gaussmf(tazaSize.universe, 240, 100) tazaSize['grande'] = fuzz.smf(tazaSize.universe, 0, 451) intensidad['suave'] = fuzz.zmf(intensidad.universe, 0, 5) intensidad['medio'] = fuzz.gaussmf(intensidad.universe, 3, 1) intensidad['fuerte'] = fuzz.smf(intensidad.universe, 0, 5) return temperatura, tazaSize, intensidad
def accomodation_control(self): shallow_depth_sigma = 0.1 shallow2 = fuzz.gaussmf(self.waterdepth, 0.5, shallow_depth_sigma) shallow_depth_sigma = 3 shallow = fuzz.gaussmf(self.waterdepth, 5, shallow_depth_sigma) id1 = np.where(self.waterdepth < 0.5)[0] id2 = np.where(self.waterdepth > 5)[0] shallow[id1[-1] : id2[0]] = 1.0 shallow[: id1[-1]] = shallow2[: id1[-1]] id = np.where(self.waterdepth <= 0)[0] shallow[id] = 0 shallow[shallow < 0.00001] = 0.0 medium_depth_sigma = 2 medium2 = fuzz.gaussmf(self.waterdepth, 9, medium_depth_sigma) medium_depth_sigma = 4 medium = fuzz.gaussmf(self.waterdepth, 15, medium_depth_sigma) id1 = np.where(self.waterdepth < 9)[0] id2 = np.where(self.waterdepth > 15)[0] medium[id1[-1] : id2[0]] = 1.0 medium[: id1[-1]] = medium2[: id1[-1]] id = np.where(self.waterdepth <= 0)[0] medium[id] = 0 medium[medium < 0.00001] = 0.0 deep_sigma = 5 deep = 1.0 - fuzz.gaussmf(self.waterdepth, 15, deep_sigma) id = np.where(self.waterdepth < 15)[0] deep[id] = 0 # Antecedent object self.depth = ctrl.Antecedent(self.waterdepth, "depth") # Membership functions population self.depth["shallow"] = shallow self.depth["medium"] = medium self.depth["deep"] = deep return
def getZGaussiano(comida,servico): qual_lo = fuzz.gaussmf(x_qual, 0, 1.5) qual_md = fuzz.gaussmf(x_qual, 5, 1.5) qual_hi = fuzz.gaussmf(x_qual, 10, 1.5) serv_lo = fuzz.gaussmf(x_serv, 0, 1.5) serv_md = fuzz.gaussmf(x_serv, 5, 1.5) serv_hi = fuzz.gaussmf(x_serv, 10, 1.5) tip_lo = fuzz.gaussmf(x_tip, 0, 4) tip_md = fuzz.gaussmf(x_tip, 13, 4) tip_hi = fuzz.gaussmf(x_tip, 25, 4) qual_level_lo = fuzz.interp_membership(x_qual, qual_lo, comida) qual_level_md = fuzz.interp_membership(x_qual, qual_md, comida) qual_level_hi = fuzz.interp_membership(x_qual, qual_hi, comida) serv_level_lo = fuzz.interp_membership(x_serv, serv_lo, servico) serv_level_md = fuzz.interp_membership(x_serv, serv_md, servico) serv_level_hi = fuzz.interp_membership(x_serv, serv_hi, servico) # active_rule1 = np.fmax(qual_level_lo, serv_level_lo) tip_activation_lo = np.fmin(active_rule1, tip_lo) tip_activation_md = np.fmin(serv_level_md, tip_md) 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) # aggregated = np.fmax(tip_activation_lo, np.fmax(tip_activation_md, tip_activation_hi)) # tip = fuzz.defuzz(x_tip, aggregated, 'centroid') tip_activation = fuzz.interp_membership(x_tip, aggregated, tip) # plot] return tip
def member_of_function(crisp_value): # antecedent ratio = ctrl.Antecedent(np.arange(0, 2.1, 0.1), 'ratio') # define the means and sigmas per fuzzy set means = [0, 1.5, 2] sigmas = [0.75, 0.35, 0.75] # define the fuzzy sets ratio['comfortable'] = fuzz.gaussmf(ratio.universe, 0, 1.5) ratio['hasty'] = fuzz.gaussmf(ratio.universe, 1.5, 0.35) ratio['impossible'] = fuzz.gaussmf(ratio.universe, 2, 0.75) degrees = [] keys = ratio.terms.keys() # computing membership degree for all linguistic variables for i, label in enumerate(keys): degrees.append(compute_degree(ratio, crisp_value, means[i], sigmas[i])) #returning linguistic variable for highest membership degree and membership degree return keys[degrees.index(max(degrees))], degrees
def generate_mf(self): # Generate fuzzy membership functions self.speedup['low'] = fuzz.trapmf(self.speedup.universe, [1.0, 1.0, 1.1, 1.2]) self.speedup['medium'] = fuzz.gaussmf(self.speedup.universe, 1.3, 0.05) self.speedup['high'] = fuzz.trapmf(self.speedup.universe, [1.4, 1.7, 10.0, 10.0]) self.speedup.view() self.mag_runtime['low'] = fuzz.trapmf(self.mag_runtime.universe, [0, 0, 0.3, 0.4]) self.mag_runtime['medium'] = fuzz.gaussmf(self.mag_runtime.universe, 0.5, 0.1) self.mag_runtime['high'] = fuzz.trapmf(self.mag_runtime.universe, [0.6, 0.7, 1.0, 1.0]) self.mag_runtime.view() self.parr_est_out['low'] = fuzz.trapmf(self.parr_est_out.universe, [0, 0, 0.3, 0.4]) self.parr_est_out['medium'] = fuzz.gaussmf(self.parr_est_out.universe, 0.5, 0.1) self.parr_est_out['high'] = fuzz.trapmf(self.parr_est_out.universe, [0.6, 0.7, 1.0, 1.0]) self.parr_est_out.view() self.generate_rules()
def plotMF(self, x, inputVar): from skfuzzy import gaussmf, gbellmf, sigmf for mf in range(len(self.memFuncs[inputVar])): if self.memFuncs[inputVar][mf][0] == 'gaussmf': y = gaussmf(x, **self.memClass.MFList[inputVar][mf][1]) elif self.memFuncs[inputVar][mf][0] == 'gbellmf': y = gbellmf(x, **self.memClass.MFList[inputVar][mf][1]) elif self.memFuncs[inputVar][mf][0] == 'sigmf': y = sigmf(x, **self.memClass.MFList[inputVar][mf][1]) plt.plot(x, y, 'r') plt.show()
def plotMF(self, x, inputVar): import matplotlib.pyplot as plt from skfuzzy import gaussmf, gbellmf, sigmf for mf in range(len(self.memFuncs[inputVar])): if self.memFuncs[inputVar][mf][0] == 'gaussmf': y = gaussmf(x,**self.memClass.MFList[inputVar][mf][1]) elif self.memFuncs[inputVar][mf][0] == 'gbellmf': y = gbellmf(x,**self.memClass.MFList[inputVar][mf][1]) elif self.memFuncs[inputVar][mf][0] == 'sigmf': y = sigmf(x,**self.memClass.MFList[inputVar][mf][1]) plt.plot(x,y,'r') plt.show()
def eval_membership_function_akt(akt_values, positive_change_akt, negative_change_akt): '''Evaluates membership function for akt ''' akt_high = fuzz.gaussmf(akt_values, 1, 0.1) akt_low = fuzz.gaussmf(akt_values, 0, 0.3) akt_high1 = fuzz.trapmf(akt_values,(0.1,0.1,0.8,1.4)) positive_change_akt_high = fuzz.gaussmf(positive_change_akt, 1, 0.01) positive_change_akt_low = fuzz.gaussmf(positive_change_akt, 0, 0.01) negative_change_akt_high = fuzz.gaussmf(negative_change_akt, -1, 0.01) negative_change_akt_low = fuzz.gaussmf(negative_change_akt, 0, 0.01) return (akt_low, akt_high, positive_change_akt_low, positive_change_akt_high, negative_change_akt_low, negative_change_akt_high, akt_high1)
def eval_membership_function_egfr(egfr_values, positive_change_egfr, negative_change_egfr): '''Evaluates membership function for egfr ''' egfr_high = fuzz.gaussmf(egfr_values,1, 0.1) egfr_low = fuzz.gaussmf(egfr_values,0, 0.1) egfr_high1 = fuzz.trapmf(egfr_values,(0.1,0.1,0.8,1.4)) positive_change_egfr_high = fuzz.gaussmf(positive_change_egfr,1, 0.1) positive_change_egfr_low = fuzz.gaussmf(positive_change_egfr, 0, 0.1) negative_change_egfr_high = fuzz.gaussmf(negative_change_egfr, -1, 0.1) negative_change_egfr_low = fuzz.gaussmf(negative_change_egfr, 0, 0.1) return (egfr_low, egfr_high, positive_change_egfr_low, positive_change_egfr_high, negative_change_egfr_low, negative_change_egfr_high, egfr_high1)
def eval_membership_function_raf(raf_values, positive_change_raf, negative_change_raf): '''Evaluates membership function for raf ''' raf_high = fuzz.gaussmf(raf_values, 1, 0.1) raf_low = fuzz.gaussmf(raf_values, 0, 0.1) raf_high1 = fuzz.trapmf(raf_values,(0.1,0.1,0.8,1.4)) positive_change_raf_high = fuzz.gaussmf(positive_change_raf, 1, 0.01) positive_change_raf_low = fuzz.gaussmf(positive_change_raf, 0, 0.01) negative_change_raf_high = fuzz.gaussmf(negative_change_raf, -1, 0.01) negative_change_raf_low = fuzz.gaussmf(negative_change_raf, 0, 0.01) return (raf_low, raf_high, positive_change_raf_low, positive_change_raf_high, negative_change_raf_low, negative_change_raf_high, raf_high1)
def eval_membership_function_pi3k(pi3k_values, positive_change_pi3k, negative_change_pi3k): '''Evaluates membership function for pi3k ''' pi3k_high = fuzz.gaussmf(pi3k_values, 1, 0.1) pi3k_low = fuzz.gaussmf(pi3k_values, 0, 0.1) pi3k_high1 = fuzz.trapmf(pi3k_values,(0.1,0.1,0.8,1.4)) positive_change_pi3k_high = fuzz.gaussmf(positive_change_pi3k, 1, 0.01) positive_change_pi3k_low = fuzz.gaussmf(positive_change_pi3k, 0, 0.01) negative_change_pi3k_high = fuzz.gaussmf(negative_change_pi3k, -1, 0.01) negative_change_pi3k_low = fuzz.gaussmf(negative_change_pi3k, 0, 0.01) return (pi3k_low, pi3k_high, positive_change_pi3k_low, positive_change_pi3k_high, negative_change_pi3k_low, negative_change_pi3k_high, pi3k_high1)
def eval_membership_function_erk(erk_values, positive_change_erk, negative_change_erk): '''Evaluates membership function for erk ''' erk_high = fuzz.gaussmf(erk_values, 1, 0.1) erk_low = fuzz.gaussmf(erk_values, 0, 0.1) erk_high1 = fuzz.trapmf(erk_values,(0.1,0.1,0.8,1.4)) positive_change_erk_high = fuzz.gaussmf(positive_change_erk, 1, 0.01) positive_change_erk_low = fuzz.gaussmf(positive_change_erk, 0, 0.01) negative_change_erk_high = fuzz.gaussmf(negative_change_erk, -1, 0.01) negative_change_erk_low = fuzz.gaussmf(negative_change_erk, 0, 0.01) return (erk_low, erk_high, positive_change_erk_low, positive_change_erk_high, negative_change_erk_low, negative_change_erk_high, erk_high1)
def transform_gaussmf(x, param, val): point = param[0] y = fuzz.gaussmf(x, param[0], param[1]) idx = np.searchsorted(x, point, 'left') if(idx < x.size - 1): if(x[idx] == x[idx + 1]): idx += 1 if(val == 0): for i in xrange(idx): y[i] = 0 else: for i in xrange(idx + 1, x.size): y[i] = 0 return y
def membership_f(mf, x, abc = [0,0,0], a = 1, b = 2, c = 3, d = 4, abcd = [0,0,0,0]): return { 'trimf' : fuzz.trimf(x, abc), # trimf(x, abc) 'dsigmf' : fuzz.dsigmf(x, a, b, c, d), # dsigmf(x, b1, c1, b2, c2) 'gauss2mf': fuzz.gauss2mf(x, a, b, c, d), # gauss2mf(x, mean1, sigma1, mean2, sigma2) 'gaussmf' : fuzz.gaussmf(x, a, b), # gaussmf(x, mean, sigma) 'gbellmf' : fuzz.gbellmf(x, a, b, c), # gbellmf(x, a, b, c) 'piecemf' : fuzz.piecemf(x, abc), # piecemf(x, abc) 'pimf' : fuzz.pimf(x, a, b, c, d), # pimf(x, a, b, c, d) 'psigmf' : fuzz.psigmf(x, a, b, c, d), # psigmf(x, b1, c1, b2, c2) 'sigmf' : fuzz.sigmf(x, a, b), # sigmf(x, b, c) 'smf' : fuzz.smf(x, a, b), # smf(x, a, b) 'trapmf' : fuzz.trapmf(x, abcd), # trapmf(x, abcd) 'zmf' : fuzz.zmf(x, a, b), # zmf(x, a, b) }[mf]
def calcularParticaoGaussiana(self, index): pontoMedio = self.ponto_referencial + self.largura_entre_pontos_inferiores desvio = self.largura_entre_pontos_inferiores / 3.5 if index == 0: self.pontosCentrais.append(self.inicio) return fuzz.gauss2mf(self.eixo_x, self.inicio, 0.1, self.inicio, desvio) elif index == len(self.tiposConjunto) - 1: self.pontosCentrais.append(self.fim) return fuzz.gauss2mf(self.eixo_x, self.fim, desvio, self.fim, 0.1) else: self.pontosCentrais.append(pontoMedio) self.pontosIniciais.append("GAUSS") self.pontosFinais.append("GAUSS") self.ponto_referencial += self.largura_entre_pontos_inferiores #return fuzz.gauss2mf(self.eixo_x, pontoMedio, desvio * 2, self.fim, 0.1) return fuzz.gaussmf(self.eixo_x, pontoMedio, desvio)
def plotMF(self, x, inputVar): import matplotlib.pyplot as plt from skfuzzy import gaussmf, gbellmf, sigmf print("memFuncs") print(self.memFuncs) fig = plt.figure(figsize=(16, 12)) for mf in range(len(self.memFuncs[inputVar])): if self.memFuncs[inputVar][mf][0] == 'gaussmf': y = gaussmf(x, **self.memClass.MFList[inputVar][mf][1]) elif self.memFuncs[inputVar][mf][0] == 'gbellmf': y = gbellmf(x, **self.memClass.MFList[inputVar][mf][1]) elif self.memFuncs[inputVar][mf][0] == 'sigmf': y = sigmf(x, **self.memClass.MFList[inputVar][mf][1]) plt.plot(x, y, 'r') plt.savefig("mf" + str(inputVar) + ".png") fig.clear()
def __createMF(self, mf_type, params, universe): """ Creates a membership function based on the given type. The triangular MF is considered as the default case Parameters -------------- :param mf_type: :param params: :param universe: :return: a membership function """ return { TRAPEZOID_MF: lambda *args: fuzz.trapmf(*args), GAUSSIAN_MF: lambda *args: fuzz.gaussmf(args[0], *args[1]), SIGMOID_MF: lambda *args: fuzz.sigmf(*args) }.get(mf_type.lower(), lambda *args: fuzz.trimf(*args))(universe, params)
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 membership_f(mf, x, abc=[0, 0, 0], a=1, b=2, c=3, d=4, abcd=[0, 0, 0, 0]): """ Returns y values corresponding to type of type of Membership fn. arguments: mf - string containing type of Membership function x - x axis values abc - list containing triangular edge point x-values """ return { "trimf": fuzz.trimf(x, abc), # trimf(x, abc) "dsigmf": fuzz.dsigmf(x, a, b, c, d), # dsigmf(x, b1, c1, b2, c2) "gauss2mf": fuzz.gauss2mf(x, a, b, c, d), # gauss2mf(x, mean1, sigma1, mean2, sigma2) "gaussmf": fuzz.gaussmf(x, a, b), # gaussmf(x, mean, sigma) "gbellmf": fuzz.gbellmf(x, a, b, c), # gbellmf(x, a, b, c) "piecemf": fuzz.piecemf(x, abc), # piecemf(x, abc) "pimf": fuzz.pimf(x, a, b, c, d), # pimf(x, a, b, c, d) "psigmf": fuzz.psigmf(x, a, b, c, d), # psigmf(x, b1, c1, b2, c2) "sigmf": fuzz.sigmf(x, a, b), # sigmf(x, b, c) "smf": fuzz.smf(x, a, b), # smf(x, a, b) "trapmf": fuzz.trapmf(x, abcd), # trapmf(x, abcd) "zmf": fuzz.zmf(x, a, b), # zmf(x, a, b) }[mf]
def paramsToMF(params): """ Translate the piecewise params list of x_values to an MF function. Assumes a list of length: 1 - singleton MF 2 - gaussian MF function (mean, standard deviation) 3 - triangular MF function 4 - trapezoidal MF function """ c = 100.0 if len(params) == 1: #singleton c = 50 #special short MF for singleton xrange = [0.9*params[0], 1.1*params[0], 2*0.2*params[0]/c] x, y = singleton_to_fuzzy(params[0], xrange) if len(params) == 2: #gaussian MF #print "PARAMS:", params if params[1] == 0.0: v = 0.01*params[0] else: v = params[1] x = np.arange( params[0] - 6*v, params[0] + 6*v, (14.0*v/c) ) #use 6 sigmas y = fuzz.gaussmf(x, params[0], params[1]) elif len(params) == 3: #triangular MF if max(params) == min(params): prange = max(params) else: prange = max(params) - min(params) x = np.arange( min(params), max(params),prange/c) y = fuzz.trimf(x, params) elif len(params) == 4: #trapezoidal MF if max(params) == min(params): prange = max(params) else: prange = max(params) - min(params) x = np.arange( min(params), max(params),prange/c) y = fuzz.trapmf(x, params) return [np.asarray(x), np.asarray(y)] #create MF
def move_fuzzy(distance_in): """ A simple fuzzy movement algorithm. Hit the ball with the center of the paddle. """ # Convert the distance from this game's 550 unit tall area to # the 200 unit tall are this fuzzy system was made for in MATLAB distance_in = distance_in/2.75 ### Inputs ### # Input variable domain dist = np.arange(-100, 100, 1) # Input Membership Functions far_below = fuzz.gbellmf(dist, 79.68, 24.6, -90) close_below = fuzz.gaussmf(dist, -6.57989, 3.17) on_target = fuzz.gaussmf(dist, 0, 2) close_above = fuzz.gaussmf(dist, 6.58, 3.17) far_above = fuzz.gbellmf(dist, 79.68, 24.6, 90) # Fuzzifying the inputs def dist_category(dist_in): dist_cat_far_below = fuzz.interp_membership(dist, far_below, dist_in) dist_cat_close_below = fuzz.interp_membership(dist, close_below, dist_in) dist_cat_on_target = fuzz.interp_membership(dist, on_target, dist_in) dist_cat_close_above = fuzz.interp_membership(dist, close_above, dist_in) dist_cat_far_above = fuzz.interp_membership(dist, far_above, dist_in) return dict(fbelow = dist_cat_far_below, cbelow = dist_cat_close_below, target = dist_cat_on_target, cabove = dist_cat_close_above, fabove = dist_cat_far_above) ### Outputs ### # Output Variable Domain move = np.arange(-1, 1, 1) # Output Membership Functions down_fast = fuzz.trapmf(move, [-1.45, -1.05, -0.2, -0.1]) down_slow = fuzz.trimf(move, [-0.2, -0.1, 0]) none = fuzz.trimf(move, [-0.1, 0, 0.1]) up_slow = fuzz.trimf(move, [0, 0.1, 0.2]) up_fast = fuzz.trapmf(move, [0.1, 0.2, 1.14, 1.38]) ### Rules ### this_move = dist_category(float(distance_in)) rule1 = this_move['fbelow'] rule2 = this_move['cbelow'] rule3 = this_move['target'] rule4 = this_move['cabove'] rule5 = this_move['fabove'] # Apply implication operator (Mandami) connecting rules to # output mfs imp1 = np.fmin(rule1, down_fast) imp2 = np.fmin(rule2, down_slow) imp3 = np.fmin(rule3, none) imp4 = np.fmin(rule4, up_slow) imp5 = np.fmin(rule5, up_fast) # Aggregate outputs using max agg_memb = np.fmax(imp1, np.fmax(imp2, np.fmax(imp3, np.fmax(imp4, imp5)))) # Defuzzify using centroid and return the result move_result = fuzz.defuzz(move, agg_memb, 'centroid') return move_result
import numpy as np import skfuzzy as fuzz import matplotlib.pyplot as mpl # Step 1 : Fuzzify Input / Output #Input Variables have the same domain/ Universe functions service = np.arange(0,11,1) food = np.arange(0,11,1) # Output Variables Domain tip = np.arange(0,101,1) # Input Membership Functions # Service ser_p = fuzz.gaussmf(service ,0,1.5) ser_g = fuzz.gaussmf(service ,5,1.5) ser_e = fuzz.gaussmf(service ,10,1.5) # Food foo_r = fuzz.trapmf(food , [0, 0, 1, 3]) foo_d = fuzz.gaussmf(food, 10,1.5) # Output tip tip_ch = fuzz.trimf(tip, [0, 15, 30]) tip_ave = fuzz.trimf(tip, [25, 45, 70]) tip_gen = fuzz.trimf(tip, [60, 80, 100]) print 'tip_cheap', tip_ch print 'tip_average', tip_ave print 'tip_generous', tip_gen # Here I'll use your example service == 2 and food == 4 # These return a single value, which is combined using the rules in Step 3
def helper_centroid(mean=0, sigma=1): x = np.arange(21) - 10 gmf = fuzz.gaussmf(x, mean, sigma) assert_allclose(mean, fuzz.centroid(x, gmf), atol=1e-2) return None
def build_fuzz_system(fcl_file): """ Given a Fuzzy Control Language file (FCL), builds the appropriate objects to instantiate a fuzzy_system class object with. ------INPUTS------ fcl_file : string text file name of FCL file to build system with ------OUTPUTS------ inputs : dict dictionary of input objects in form {name: <__main__.input instance>, name: <__main__.input instance>, ...} outputs : dict dictionary of output objects in form {name: <__main__.output instance>, name: <__main__.output instance>, ...} rulebase : list list of rule objects in form [<__main__.rule instance>, ... ] AND_operator : string the AND operator for the system ('PRODUCT' or 'MIN') OR_operator : string the OR operator for the system (only setup for 'MAX' operator) aggregator : string means to aggregate outputs ('MAX' only one available) implication : string means to apply rule firing strength to output MFs ('PRODUCT' or 'MIN') defuzz : string defuzzification means ('centroid', 'bisector', 'mom', 'lom', 'som') """ #print "Reading FCL File:", fcl_file f = open(fcl_file, 'r') lines = f.readlines() #input structures: inputs = {} #dict of input structures outputs = {} #dict of output structures rulebase = [] #dict of rule structures AND_operator = None #and operator (PRODUCT or MIN) OR_operator = None #or operator (MAX) (per DeMorgan, opposite of AND) aggregator = None #means to aggregate outputs (max) implication = None #means to apply rule firing strength to output MFs defuzz = None #means for defuzzification #strip out comments #print "CLEANING FILE..." for l in lines: if l.strip().startswith('#'): lines[lines.index(l)] = '' #build input structures #print "INITIALIZING INPUTS..." flag = 0 # reading mode flag for l in lines: if l.strip().startswith('VAR_INPUT'): #search for var input block flag=1 continue if l.strip().startswith('END_VAR'): #end search for var input block flag=0 continue if flag == 1: #if flag set, enter reading mode if l.strip() == '': continue #skip empty lines t1 = l.rsplit(':') #split off variable name i = input(t1[0].strip()) #create input with variable name t2 = t1[1].rsplit(';') i.data_type = t2[0].strip() #add input variable type t3 = find_substring( t2[1], 'RANGE(', ')' ).rsplit("..") i.data_range = [ float(t3[0]), float(t3[1]) ] inputs[i.name] = i #build output structures #print "INITIALIZING OUTPUTS..." flag = 0 # reading mode flag for l in lines: if l.strip().startswith('VAR_OUTPUT'): #search for var input block flag=1 continue if l.strip().startswith('END_VAR'): #end search for var input block flag=0 continue if flag == 1: #if flag set, enter reading mode if l.strip() == '': continue #skip empty lines t1 = l.rsplit(':') #split off variable name i = output(t1[0].strip()) #create input with variable name t2 = t1[1].rsplit(';') i.data_type = t2[0].strip() #add input variable type t3 = find_substring( t2[1], 'RANGE(', ')' ).rsplit("..") i.data_range = [ float(t3[0]), float(t3[1]) ] outputs[i.name] = i #build input fuzzy MFs #print "BUILDING INPUT MFs..." flag = 0 # reading mode flag for l in lines: if l.strip().startswith('FUZZIFY'): #search for var input block flag=1 name = l.strip().rsplit(' ')[1].strip() #get input name continue if l.strip().startswith('END_FUZZIFY'): #end search for var input block flag=0 continue if flag == 1: #if flag set, enter reading mode if l.strip() == '': continue #skip empty lines t1 = l.rsplit('=') n = find_substring( t1[0], 'TERM', ':').strip(' \t\n\r') #pull term linguistic name points = [a.rsplit('(')[1] for a in t1[1].rsplit(';')[0].split(')') if ',' in a] #pull the piecewise points for j in range(len(points)): pts = [] for p1 in points[j].rsplit(','): if not ('mean' in p1 or 'std' in p1): pts.append(float(p1)) #convert point strings to float list else: pts.append(p1) points[j] = pts if len(points) <> 2: #if piecewise mf f_x = np.arange(min([p[0] for p in points]), max([p[0] for p in points]), (max([p[0] for p in points]) - min([p[0] for p in points]))/100.0) else: #for gaussian MF f_x = np.arange(inputs[name].data_range[0], inputs[name].data_range[1], (inputs[name].data_range[1]-inputs[name].data_range[0])/100) #x_points for MF #determine MF function type if len(points) == 2: f_y = fuzz.gaussmf(f_x, points[0][0], points[1][0]) elif len(points) == 3: f_y = fuzz.trimf(f_x, sorted([points[0][0],points[1][0],points[2][0]])) elif len(points) == 4: f_y = fuzz.trapmf(f_x, sorted([points[0][0],points[1][0],points[2][0],points[3][0]])) inputs[name].MFs[n] = [f_x, f_y] #add MF with linguistic term to input inputs[name].MFparams[n] = [p[0] for p in points] #add parameter values (3-tri; 4-trap) #build output fuzzy MFs #print "BUILDING OUTPUT MFs..." flag = 0 # reading mode flag for l in lines: if l.strip().startswith('DEFUZZIFY'): #search for var input block flag=1 name = l.strip().rsplit(' ')[1].strip(' \t\n\r') #get input name continue if l.strip().startswith('END_DEFUZZIFY'): #end search for var input block flag=0 continue if flag == 1: #if flag set, enter reading mode if l.strip() == '': continue #skip empty lines if not 'TERM' in l: continue t1 = l.rsplit('=') n = find_substring( t1[0], 'TERM', ':').strip() #pull term linguistic name points = [a.rsplit('(')[1] for a in t1[1].rsplit(';')[0].split(')') if ',' in a] #pull the piecewise points for j in range(len(points)): pts = [] for p1 in points[j].rsplit(','): if not ('mean' in p1 or 'std' in p1): pts.append(float(p1)) #convert point strings to float list else: pts.append(p1) points[j] = pts if len(points) <> 2: #if piecewise mf f_x = np.arange(min([p[0] for p in points]), max([p[0] for p in points]), ( max([p[0] for p in points]) - min([p[0] for p in points]) )/100.0) else: #for gaussian MF f_x = np.arange(outputs[name].data_range[0], outputs[name].data_range[1], (outputs[name].data_range[1]-outputs[name].data_range[0])/100.0) #x_points for MF #determine MF function type if len(points) == 2: f_y = fuzz.gaussmf(f_x, points[0][0], points[1][0]) elif len(points) == 3: f_y = fuzz.trimf(f_x, sorted([points[0][0],points[1][0],points[2][0]])) elif len(points) == 4: f_y = fuzz.trapmf(f_x, sorted([points[0][0],points[1][0],points[2][0],points[3][0]])) outputs[name].MFs[n] = [f_x, f_y] #add MF with linguistic term to input outputs[name].MFparams[n] = [p[0] for p in points] #add parameter values (3-tri; 4-trap) #build fuzzy rules #print "BUILDING FUZZY RULES..." flag = 0 # reading mode flag for i in range(len(lines)): if lines[i].strip().startswith('RULEBLOCK'): #search for var input block flag=1 continue if lines[i].strip().startswith('END_RULEBLOCK'): #end search for var input block flag=0 continue if flag == 1: #if flag set, enter reading mode if lines[i].strip() == '': continue #skip empty lines if lines[i].strip().startswith('RULE'): t1 = lines[i].strip(' \t\n\r').rsplit(':') #split off rule id from statement r = rule(str(t1[0].strip('RULE '))) #initialize rule with ID strs = t1[1] #init rule string #build rule string while not lines[i+1].strip().startswith('RULE') and not lines[i+1].strip().startswith('END_RULEBLOCK'): strs = strs + lines[i+1].strip() i = i+1 #build rule_list from rules string s = [] while '(' in strs or ')' in strs: if strs.find('(') < strs.find(')') and strs.find('(') > -1: s.append(strs.split('(',1)[0].strip('; \t\n\r')) s.append('(') strs = strs.split('(',1)[1] else: s.append(strs.split(')',1)[0].strip('; \t\n\r')) s.append(')') strs = strs.split(')',1)[1] s.append(strs) s1 = [] for j in range(len(s)): s1.extend(s[j].split(' ')) #split by spaces while '' in s1: s1.pop(s1.index('')) #remove extra white spaces while '(' in s1 or ')' in s1: j1,j2 = None, None for j in range(len(s1)): if s1[j] == '(': j1 = j if s1[j] == ')' and j1 <> None: j2 = j s1[j1:j2+1] = [s1[j1+1:j2]] break r.rule_list = s1 #add rule list to rule rulebase.append(r) #append rule to rule base continue #get other rulebase parameters (for implication method) if lines[i].strip().startswith('AND'): #pull AND operator t = lines[i].strip().strip(';').split(':') AND_operator = t[1].strip() #if AND_operator == 'MAX': OR_operator = 'MIN' #demorgan's law #if AND_operator == 'MIN': OR_operator = 'MAX' #demorgan's law elif lines[i].strip().startswith('OR'): #pull AND operator t = lines[i].strip().strip(';').split(':') OR_operator = t[1].strip() #if OR_operator == 'MAX': AND_operator = 'MIN' #demorgan's law #if OR_operator == 'MIN': AND_operator = 'MAX' #demorgan's law elif 'ACCU' in lines[i].strip(): t = find_substring(lines[i], '(*', '*)') t = t.strip().strip(';').split(':') aggregator = t[1] elif 'ACT' in lines[i].strip(): t = lines[i].strip().strip(';').split(':') implication = t[1] elif 'DEFUZZ' in lines[i].strip(): t = lines[i].strip().strip(';').split(':') defuzz = t[1] #print 'FCL Read Successfully!' return (inputs, outputs, rulebase, AND_operator, OR_operator, aggregator, implication, defuzz)
import numpy as np import skfuzzy as fuzz from matplotlib import pyplot as plt from scipy.interpolate import UnivariateSpline # margin of outputs rules determin if a state is a valid state STATE_DIFF_MARGIN = 0.2 # logic states alt_range = np.arange(0, 40000, 1) roc_range = np.arange(-4000, 4000, 0.1) spd_range = np.arange(0, 600, 1) states = np.arange(0, 6, 0.01) alt_gnd = fuzz.zmf(alt_range, 0, 200) alt_lo = fuzz.gaussmf(alt_range, 10000, 5000) alt_hi = fuzz.gaussmf(alt_range, 35000, 20000) roc_zero = fuzz.gaussmf(roc_range, 0, 100) roc_plus = fuzz.smf(roc_range, 10, 1000) roc_minus = fuzz.zmf(roc_range, -1000, -10) spd_hi = fuzz.gaussmf(spd_range, 600, 100) spd_md = fuzz.gaussmf(spd_range, 200, 100) spd_lo = fuzz.gaussmf(spd_range, 0, 50) state_ground = fuzz.gaussmf(states, 1, 0.1) state_climb = fuzz.gaussmf(states, 2, 0.1) state_descent = fuzz.gaussmf(states, 3, 0.1) state_cruise = fuzz.gaussmf(states, 4, 0.1) state_level = fuzz.gaussmf(states, 5, 0.1)
def calculate_akt_mfs(pi3k, akt): pi3k_low = fuzz.zmf(pi3k, 0, 0.95) pi3k_high = fuzz.smf(pi3k, 0, 0.9) akt_low = fuzz.gaussmf(akt, 0, akt[akt.size -1]/20) akt_high = fuzz.gaussmf(akt, akt[akt.size -1], akt[akt.size -1]/20) return ((pi3k_low, pi3k_high), (akt_low, akt_high))
import skfuzzy as fuzz from matplotlib import pyplot as plt from scipy import stats from filters import SavitzkyGolay # margin of outputs rules determin if a state is a valid state STATE_DIFF_MARGIN = 0.2 # logic states alt_range = np.arange(0, 40000, 1) dh_range = np.arange(-20, 20, 0.1) spd_range = np.arange(0, 600, 1) states = np.arange(0, 5, 0.01) alt_gnd = fuzz.zmf(alt_range, 0, 200) alt_lo = fuzz.gaussmf(alt_range, 10000, 10000) alt_hi = fuzz.gaussmf(alt_range, 30000, 10000) dh_zero = fuzz.gaussmf(dh_range, 0, 5) dh_plus = fuzz.sigmf(dh_range, 6, 1) dh_minus = fuzz.sigmf(dh_range, -6, -1) spd_hi = fuzz.gaussmf(spd_range, 600, 200) spd_md = fuzz.gaussmf(spd_range, 100, 100) spd_lo = fuzz.gaussmf(spd_range, 0, 50) state_ground = fuzz.gaussmf(states, 1, 0.1) state_climb = fuzz.gaussmf(states, 2, 0.1) state_descend = fuzz.gaussmf(states, 3, 0.1) state_cruise = fuzz.gaussmf(states, 4, 0.1)
def calculate_erk_mfs(raf, erk): raf_low = fuzz.zmf(raf, 0, 0.95) raf_high = fuzz.smf(erk, 0.1, 0.9) erk_low = fuzz.gaussmf(erk, 0, raf[raf.size - 1]/20) erk_high = fuzz.gaussmf(erk, raf[raf.size - 1], raf[raf.size - 1]/20) return (raf_low, raf_high, erk_low, erk_high)