def GetRules(self): print("Creating Fuzzy Rules. . .") for ruleBaseName, rules in self.InputRulesByRuleBaseName.items(): self.RulesByRuleBaseName[ruleBaseName] = dict() for rule in rules: # No tokenization, if you have a mish-mash of and/or/anything else, you might get unexpected results. antecedentsTermAggregate = str() antecedentsByAntecedentStr = dict() for term in rule.Terms: # if variableName is variableValue antecedent = self.AntecedentsByName[term.VariableName][ term.VariableValue] # no other obvious way of dealing with N chained connectives and dynamically creating aggregates # use a buffer dict which holds the antecedent based on their str(antecedent) value # we later eval to get the term aggregate. This is a VERY horrible way of doing this # but I couldn't really spot any other way of dealing with this issue other than reflection antecedentStr = str(antecedent) antecedentsByAntecedentStr[antecedentStr] = antecedent # order is very important, do not change. antecedentsTermAggregate += \ term.LogicalConnective.Operand +\ term.OpeningParentheses +\ term.BooleanOperand +\ 'antecedentsByAntecedentStr["' + antecedentStr + '"]' +\ term.ClosingParentheses # then variableName is variableValue result = self.ConsequentsByName[rule.Result.VariableName][ rule.Result.VariableValue] # eval on antecedents creates a potentially complex term aggregate fuzzyRule = ctrl.Rule(eval(antecedentsTermAggregate), result) self.RulesByRuleBaseName[ruleBaseName][rule.Name] = fuzzyRule return self.RulesByRuleBaseName
def createFuzzy(self): self.fuzz_pend1 = ctrl.Antecedent(np.arange(-1, 1.1, 0.1), 'join1') self.fuzz_motor = ctrl.Consequent(np.arange(-300, 300, 1), 'motor') self.fuzz_pend1.automf(7) self.fuzz_motor.automf(7) #self.fuzz_pend1['average'].view() #self.fuzz_motor['average'].view() self.rule1 = ctrl.Rule(self.fuzz_pend1['dismal'], self.fuzz_motor['dismal']) self.rule2 = ctrl.Rule(self.fuzz_pend1['poor'], self.fuzz_motor['poor']) self.rule3 = ctrl.Rule(self.fuzz_pend1['mediocre'], self.fuzz_motor['mediocre']) self.rule4 = ctrl.Rule(self.fuzz_pend1['average'], self.fuzz_motor['average']) self.rule5 = ctrl.Rule(self.fuzz_pend1['decent'], self.fuzz_motor['decent']) self.rule6 = ctrl.Rule(self.fuzz_pend1['good'], self.fuzz_motor['good']) self.rule7 = ctrl.Rule(self.fuzz_pend1['excellent'], self.fuzz_motor['excellent']) self.pendulum_ctrl = ctrl.ControlSystem([self.rule1, self.rule2, self.rule3, self.rule4, self.rule5, self.rule6, self.rule7]) self.pendulum_fuzz = ctrl.ControlSystemSimulation(self.pendulum_ctrl)
def __init__(self): proximityL = ctrl.Antecedent(np.arange(0, 11, 1), 'proximityL') proximityR = ctrl.Antecedent(np.arange(0, 11, 1), 'proximityR') angularVelocity = ctrl.Consequent( np.arange(-2, 3, 1), 'angularVelocity', defuzzify_method='centroid') linearVelocity = ctrl.Consequent( np.arange(0, 6, 1), 'linearVelocity', defuzzify_method='centroid') # Fuzzy Functions angularVelocity['right_high'] = fuzz.trapmf(angularVelocity.universe, [-2, -2, -1, 0]) angularVelocity['zero'] = fuzz.trimf(angularVelocity.universe, [0, 0, 0]) angularVelocity['left_high'] = fuzz.trapmf(angularVelocity.universe, [0, 1, 2, 2]) linearVelocity['zero'] = fuzz.trimf(linearVelocity.universe, [0, 0, 0]) linearVelocity['low'] = fuzz.trimf(linearVelocity.universe, [0, 1, 2]) linearVelocity['medium'] = fuzz.trapmf(linearVelocity.universe, [1, 2, 5, 5]) proximityL['far'] = fuzz.trapmf(proximityL.universe, [5, 6, 10, 10]) proximityL['close'] = fuzz.trapmf(proximityL.universe, [3, 4, 5, 6]) proximityL['very_close'] = fuzz.trapmf(proximityL.universe, [0, 0, 3, 4]) proximityR['far'] = fuzz.trapmf(proximityR.universe, [5, 6, 10, 10]) proximityR['close'] = fuzz.trapmf(proximityL.universe, [3, 4, 5, 6]) proximityR['very_close'] = fuzz.trapmf(proximityR.universe, [0, 0, 3, 4]) self.proximityL = proximityL self.proximityR = proximityR self.angularVelocity = angularVelocity self.linearVelocity = linearVelocity # Rules rules = [] rules.append(ctrl.Rule(proximityL['very_close'] & ~proximityR['very_close'], (angularVelocity['right_high'], linearVelocity['zero']))) rules.append(ctrl.Rule(proximityR['very_close'] & ~proximityL['very_close'], (angularVelocity['left_high'], linearVelocity['zero']))) rules.append(ctrl.Rule(proximityL['close'], (angularVelocity['right_high'], linearVelocity['low']))) rules.append(ctrl.Rule(proximityR['close'], (angularVelocity['left_high'], linearVelocity['low']))) rules.append(ctrl.Rule(proximityL['far'] & proximityR['far'], (angularVelocity['zero'], linearVelocity['medium']))) rules.append(ctrl.Rule(proximityL['very_close'] & proximityR['very_close'], (angularVelocity['right_high'], linearVelocity['zero']))) fuzzySystem = ctrl.ControlSystem(rules) self.fuzzySystemSim = ctrl.ControlSystemSimulation(fuzzySystem)
def __init__(self, bw, states): self.states = states + 1 self.bw = bw # Input self.processing = ctrl.Antecedent(np.arange(0, 100, 0.5), 'cpu') self.bw = ctrl.Antecedent(np.arange(0, bw, 1), 'bandwidth') # Output self.state = ctrl.Consequent(np.arange(0, self.states, 1), 'state') # Abstractions self.abstractions = [ "almost zero", "super low", "Very low", "low", "medium", "high", "Very high", "super high", "full" ] # membership functions self.processing.automf(names=self.abstractions) self.bw.automf(names=self.abstractions) self.state.automf(names=[f"{i}" for i in range(self.states)]) # Rules self.rules = [ ctrl.Rule( self.processing[name] | self.bw[name], self.state_or_zero(name), ) for name in self.abstractions ] # Controller self.controler = ctrl.ControlSystem(self.rules) # Simulator self.simulator = ctrl.ControlSystemSimulation(self.controler, cache=False)
def is_trash(self): return ctrl.Rule( super().is_trash() & (((self.kawaii[self.lowest] | self.kawaii[self.lower] | self.kawaii[self.low]) & (self.beautiful[self.lowest] | self.beautiful[self.lower] | self.beautiful[self.low])) | ((self.smart[self.lowest] | self.smart[self.lower] | self.smart[self.low]) & (self.baka[self.higher] | self.baka[self.highest])) | (self.short[self.low] | self.short[self.high] | self.short[self.higher] | self.short[self.highest]) | (self.tall[self.high] | self.tall[self.higher] | self.tall[self.highest]) | (self.innocent[self.higher] | self.innocent[self.highest]) | (self.lewd[self.lowest] | self.lewd[self.highest]) | ((self.female[self.high] | self.female[self.higher] | self.female[self.highest]) & ((self.tsundere[self.high] | self.tsundere[self.higher] | self.tsundere[self.highest]) | (self.catgirl[self.high] | self.catgirl[self.higher] | self.catgirl[self.highest]) | (self.clumsy[self.high] | self.clumsy[self.higher] | self.clumsy[self.highest]) | (self.s[self.higher] | self.s[self.highest]) | (self.m[self.higher] | self.m[self.highest]) | (self.flashy[self.high] | self.flashy[self.higher] | self.flashy[self.highest]) | (self.busty[self.highest]) | (self.flat[self.lowest]) | (self.yandere[self.higher] | self.yandere[self.highest]) | (self.cheerful[self.higher] | self.cheerful[self.highest]))) | ((self.male[self.high] | self.male[self.higher] | self.male[self.highest]) & ((self.m[self.highest]) | (self.plain[self.higher] | self.plain[self.highest]) | (self.busty[self.high] | self.busty[self.higher] | self.busty[self.highest])))), self.likeness['low'])
def is_trash(self): return ctrl.Rule( super().is_trash() & (((self.kawaii[self.lowest] | self.kawaii[self.lower] | self.kawaii[self.low]) & (self.beautiful[self.lowest] | self.beautiful[self.lower] | self.beautiful[self.low])) | ((self.smart[self.highest] | self.smart[self.higher] | self.smart[self.high]) & (self.baka[self.lowest])) | (self.tall[self.high] | self.tall[self.higher] | self.tall[self.highest]) | (self.lewd[self.high]) | (self.male[self.high] | self.male[self.higher] | self.male[self.highest]) & ((self.female[self.high] | self.female[self.higher] | self.female[self.highest]) & ((self.catgirl[self.high] | self.catgirl[self.higher] | self.catgirl[self.highest]) | (self.s[self.high] | self.s[self.higher] | self.s[self.highest]) | (self.flashy[self.high] | self.flashy[self.higher] | self.flashy[self.highest]) | (self.yandere[self.high] | self.yandere[self.higher] | self.yandere[self.highest]) | (self.gloomy[self.higher] | self.gloomy[self.highest])))), self.likeness['low'])
def _single_expert_rules(self, rule_file:str)->List: rules = pd.read_csv(rule_file) assert rules.shape[1] == 5,\ ('[Fuzzy Logic System T1 model][build_rules] wrong rule_file shape' '{} != (m, 5)'.format(rules.shape)) domain = {'calm':'calm', 'more_calm_than_moderate':'calm', 'between_calm_and_moderate':'moderate', 'more_moderate_than_calm':'moderate', 'moderate':'moderate', 'more_moderate_than_aggressive':'moderate', 'between_moderate_and_aggressive':'aggressive', 'more_aggressive_than_moderate':'aggressive', 'aggressive':'aggressive'} #self._check_rules(rules=rules) fuzz_rules = [] for line in rules.iterrows(): index, r = line[0], line[1] xs = domain[r['driving_style']] fr = ctrl.Rule(antecedent=(self.antecedent['Velocity'][r['velocity']] &\ self.antecedent['Acceleration'][r['acceleration']] &\ self.antecedent['Deceleration'][r['deceleration']] &\ self.antecedent['LateralJerk'][r['lateral_jerk']]), consequent=self.consequent['Behavior'][xs], label=f'rule - {index}') fuzz_rules.append(fr) return fuzz_rules
def get_drone_break_control_system_simulator(): # obstacle distance custom membership functions obstacle_distance['closest'] = fuzz.trimf(obstacle_distance.universe, [0, 0, 0]) obstacle_distance['too_close'] = fuzz.trimf(obstacle_distance.universe, [0, 1, 1]) obstacle_distance['closer'] = fuzz.trimf(obstacle_distance.universe, [1, 2, 5]) obstacle_distance['close'] = fuzz.trimf(obstacle_distance.universe, [2, 5, 10]) obstacle_distance['far'] = fuzz.trimf(obstacle_distance.universe, [5, 10, 15]) obstacle_distance['too_far'] = fuzz.trimf(obstacle_distance.universe, [10, 15, 15]) # obstacleDistance.automf(7) # drone velocity custom membership functions drone_velocity['stop'] = fuzz.trimf(drone_velocity.universe, [0, 0, 0]) drone_velocity['slowest'] = fuzz.trimf(drone_velocity.universe, [0, 1, 2]) drone_velocity['slow'] = fuzz.trimf(drone_velocity.universe, [1, 2, 3]) drone_velocity['fast'] = fuzz.trimf(drone_velocity.universe, [2, 3, 4]) drone_velocity['faster'] = fuzz.trimf(drone_velocity.universe, [3, 4, 5]) drone_velocity['fastest'] = fuzz.trimf(drone_velocity.universe, [4, 5, 5]) # prepare to show obstacle distance antecedent membership graph mapping obstacle_distance.view() # prepare to show drone velocity consequent membership graph mapping drone_velocity.view() # fuzzy rules rule1 = ctrl.Rule(obstacle_distance['too_far'], drone_velocity['fastest']) rule2 = ctrl.Rule(obstacle_distance['far'], drone_velocity['faster']) rule3 = ctrl.Rule(obstacle_distance['close'], drone_velocity['fast']) rule4 = ctrl.Rule(obstacle_distance['closer'], drone_velocity['slow']) rule5 = ctrl.Rule(obstacle_distance['too_close'], drone_velocity['slowest']) rule6 = ctrl.Rule(obstacle_distance['closest'], drone_velocity['stop']) drone_velocity_control = ctrl.ControlSystem( [rule1, rule2, rule3, rule4, rule5, rule6]) drone_break = ctrl.ControlSystemSimulation(drone_velocity_control) return drone_break
def __init__(self): # New Antecedent/Consequent objects hold universe variables and membership # functions f1 = ctrl.Antecedent(np.arange(0, 1.05, 0.05), 'Average of the generated background(F1)') f2 = ctrl.Antecedent( np.arange(0, 1.05, 0.05), 'Sum of difference values between backgroud and input image(F2)') p = ctrl.Consequent(np.arange(0, 1.05, 0.05), 'Output optimal threshold(p)') # Custom membership functions can be built interactively with a familiar, # Pythonic API f1['Low'] = fuzz.trimf(f1.universe, [0, 0, 0.4]) f1['Medium'] = fuzz.trimf(f1.universe, [0.3, 0.5, 0.7]) f1['High'] = fuzz.trimf(f1.universe, [0.6, 1, 1]) #f1.view() f2['Low'] = fuzz.trimf(f2.universe, [0.0, 0.0, 0.65]) f2['High'] = fuzz.trimf(f2.universe, [0.35, 1, 1]) #f2.view() p['Very Low'] = fuzz.trapmf(p.universe, [0, 0, 0.1, 0.2]) p['Low'] = fuzz.trimf(p.universe, [0.15, 0.25, 0.35]) p['Medium'] = fuzz.trimf(p.universe, [0.3, 0.4, 0.5]) p['High'] = fuzz.trimf(p.universe, [0.45, 0.55, 0.65]) p['Very High'] = fuzz.trapmf(p.universe, [0.6, 0.7, 1, 1]) #p.view() # You can see how these look with .view() rule1 = ctrl.Rule(f1['Low'] & f2['Low'], p['Low']) rule2 = ctrl.Rule(f1['Low'] & f2['High'], p['Very High']) rule3 = ctrl.Rule(f1['Medium'] & f2['Low'], p['Medium']) rule4 = ctrl.Rule(f1['Medium'] & f2['High'], p['Medium']) rule5 = ctrl.Rule(f1['High'] & f2['Low'], p['High']) rule6 = ctrl.Rule(f1['High'] & f2['High'], p['Very Low']) threshold_ctrl = ctrl.ControlSystem( [rule1, rule2, rule3, rule4, rule5, rule6]) self.threshold = ctrl.ControlSystemSimulation(threshold_ctrl)
def get_fuzzy_ctrl_system(): memb_fns = get_memb_fns() # for item in memb_fns: # item.view() (trans, bal, age, gender, education, income, occupation, cis) = memb_fns rule0 = ctrl.Rule(antecedent=(bal['high'] & trans['high']), consequent=cis['high']) rule1 = ctrl.Rule(antecedent=(bal['avg'] & trans['low']), consequent=cis['low']) rule2 = ctrl.Rule(antecedent=(occupation['retired']), consequent=cis['low']) rule3 = ctrl.Rule(antecedent=(age['old']), consequent=cis['low']) rule4 = ctrl.Rule(antecedent=(income['avg'] | income['high']), consequent=cis['mid']) rule5 = ctrl.Rule(antecedent=(income['low']), consequent=cis['low']) system = ctrl.ControlSystem( rules=[rule0, rule1, rule2, rule3, rule4, rule5]) ctrl_system = ctrl.ControlSystemSimulation(system) return ctrl_system
humidity['wet'] = fuzz.trimf(humidity.universe, [65, 100, 100]) humidity['moist'] = fuzz.trimf(humidity.universe, [15, 50, 70]) humidity['dry'] = fuzz.zmf(humidity.universe, 0, 20) light['low'] = fuzz.zmf(light.universe, 0, 300) light['good'] = fuzz.trimf(light.universe, [250, 650, 900]) light['high'] = fuzz.trimf(light.universe, [800, 1000, 1000]) survivability['very low'] = fuzz.trimf(survivability.universe, [0, 0, 15]) survivability['low'] = fuzz.trimf(survivability.universe, [15, 20, 30]) survivability['pretty'] = fuzz.trimf(survivability.universe, [30, 35, 45]) survivability['good'] = fuzz.trimf(survivability.universe, [45, 55, 75]) survivability['high'] = fuzz.trimf(survivability.universe, [75, 90, 90]) rule1 = ctrl.Rule(humidity['wet'] & light['low'] & temperature['cold'], survivability['very low']) rule2 = ctrl.Rule(humidity['wet'] & light['low'] & (temperature['warm'] | temperature['hot']), survivability['low']) rule3 = ctrl.Rule(humidity['wet'] & light['good'] & (temperature['cold'] | temperature['hot']), survivability['pretty']) rule4 = ctrl.Rule(humidity['wet'] & light['good'] & temperature['warm'], survivability['good']) rule5 = ctrl.Rule(humidity['wet'] & light['high'] & temperature['cold'], survivability['pretty']) rule6 = ctrl.Rule(humidity['wet'] & light['high'] & (temperature['warm'] | temperature['hot']), survivability['good']) rule7 = ctrl.Rule(humidity['moist'] & light['low'] & temperature['cold'], survivability['low']) rule8 = ctrl.Rule(humidity['moist'] & light['low'] & (temperature['warm'] | temperature['hot']), survivability['pretty']) rule9 = ctrl.Rule(humidity['moist'] & light['good'] & temperature['cold'], survivability['pretty']) rule10 = ctrl.Rule(humidity['moist'] & light['good'] & (temperature['warm'] | temperature['hot']), survivability['high']) rule11 = ctrl.Rule(humidity['moist'] & light['high'] & temperature['cold'], survivability['good']) rule12 = ctrl.Rule(humidity['moist'] & light['high'] & (temperature['warm'] | temperature['hot']), survivability['high']) rule13 = ctrl.Rule(humidity['dry'] & light['low'] & temperature['cold'], survivability['very low'])
----------- Now, to make these triangles useful, we define the *fuzzy relationship* between input and output variables. For the purposes of our example, consider three simple rules: 1. If the food is poor OR the service is poor, then the tip will be low 2. If the service is average, then the tip will be medium 3. If the food is good OR the service is good, then the tip will be high. Most people would agree on these rules, but the rules are fuzzy. Mapping the imprecise rules into a defined, actionable tip is a challenge. This is the kind of task at which fuzzy logic excels. """ rule1 = ctrl.Rule(quality['poor'] | service['poor'], tip['low']) rule2 = ctrl.Rule(service['average'], tip['medium']) rule3 = ctrl.Rule(service['good'] | quality['good'], tip['high']) rule1.view() """ .. image:: PLOT2RST.current_figure Control System Creation and Simulation --------------------------------------- Now that we have our rules defined, we can simply create a control system via: """ tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
def fuzzy_output(self): EvolutionaryProcess = ctrl.Antecedent(np.arange(0, 3.05, 0.02), 'ES') averageDiversity = ctrl.Antecedent(np.arange(0, 1.05, 0.1), 'AD') mutation = ctrl.Consequent(np.arange(0, 0.205, 0.01), 'mutation') # Auto-membership function population is possible with .automf(3, 5, or 7) # EvolutionaryProcess.automf(3) # averageDiversity.automf(3) EvolutionaryProcess['low'] = fuzz.trapmf(EvolutionaryProcess.universe, [0, 0, 0.5, 1]) EvolutionaryProcess['medium'] = fuzz.trimf( EvolutionaryProcess.universe, [0.8, 1.4, 2]) EvolutionaryProcess['high'] = fuzz.trapmf(EvolutionaryProcess.universe, [1.8, 2.4, 3, 3]) averageDiversity['low'] = fuzz.trapmf(averageDiversity.universe, [0, 0, 0.1, 0.3]) averageDiversity['medium'] = fuzz.trimf(averageDiversity.universe, [0.2, 0.4, 0.6]) averageDiversity['high'] = fuzz.trapmf(averageDiversity.universe, [0.4, 0.7, 1, 1]) # Custom membership functions can be built interactively with a familiar, # Pythonic API # mutation['lower'] = fuzz.trapmf(mutation.universe, [0, 0, 0.01, 0.02]) # mutation['low'] = fuzz.trimf(mutation.universe, [0.01, 0.03, 0.05]) # mutation['medium'] = fuzz.trimf(mutation.universe, [0.04, 0.06, 0.08]) # mutation['high'] = fuzz.trimf(mutation.universe, [0.07, 0.09, 0.12]) # mutation['higher'] = fuzz.trapmf(mutation.universe, [0.1, 0.15, 0.2, 0.2]) mutation['lower'] = fuzz.trapmf(mutation.universe, [0, 0, 0.05, 0.1]) mutation['low'] = fuzz.trimf(mutation.universe, [0.08, 0.1, 0.12]) mutation['medium'] = fuzz.trimf(mutation.universe, [0.11, 0.13, 0.15]) mutation['high'] = fuzz.trimf(mutation.universe, [0.14, 0.16, 0.18]) mutation['higher'] = fuzz.trapmf(mutation.universe, [0.17, 0.18, 0.2, 0.2]) # EvolutionaryProcess.view() # averageDiversity.view() # mutation.view() rule1 = ctrl.Rule(EvolutionaryProcess['high'], mutation['low']) rule2 = ctrl.Rule( EvolutionaryProcess['medium'] | averageDiversity['medium'], mutation['medium']) rule3 = ctrl.Rule( EvolutionaryProcess['medium'] | averageDiversity['low'], mutation['high']) rule4 = ctrl.Rule( EvolutionaryProcess['medium'] | averageDiversity['high'], mutation['low']) rule5 = ctrl.Rule(EvolutionaryProcess['low'] | averageDiversity['low'], mutation['lower']) rule6 = ctrl.Rule( EvolutionaryProcess['low'] | averageDiversity['medium'], mutation['medium']) rule7 = ctrl.Rule( EvolutionaryProcess['low'] | averageDiversity['high'], mutation['high']) rule1.view() tipping_ctrl = ctrl.ControlSystem( [rule1, rule2, rule3, rule4, rule5, rule6, rule7]) tipping = ctrl.ControlSystemSimulation(tipping_ctrl) # Pass inputs to ControlSystem using Antecedent labels with Pythonic API # Note: if you like passing many inputs all at once, use .inputs(dict_of_data) # tipping.input['ES'] = 1.0074484670015589 # tipping.input['AD'] = 0.5 tipping.input['ES'] = self.ES tipping.input['AD'] = self.AD # Crunch the numbers tipping.compute() print(tipping.output['mutation']) # mutation.view(sim=tipping) return tipping.output['mutation']
def CreateEngine(self,DestDiv=3,VDiv=3,VdestDiv=5,view=1,accl=3,acco=5): '''******* Input Fuzzification *********''' Destx = ctrl.Antecedent(np.arange(0,1+0.0001, 0.001), 'Destx') Destx.automf(DestDiv) if view==1: Destx.view() Desty = ctrl.Antecedent(np.arange(0,1+0.0001, 0.001), 'Desty') Desty.automf(DestDiv) if view==1: Desty.view() Vx = ctrl.Antecedent(np.arange(0, 1+0.001, 0.01), 'Vx') Vx.automf(VDiv) if view==1: Vx.view() Vy = ctrl.Antecedent(np.arange(0, 1+0.001, 0.01), 'Vy') Vy.automf(VDiv) if view==1: Vy.view() Dobsx = ctrl.Antecedent(np.arange(0,1+0.0001, 0.001), 'Dobsx') Dobsx.automf(DestDiv) if view==1: Dobsx.view() Dobsy = ctrl.Antecedent(np.arange(0,1+0.0001, 0.001), 'Dobsy') Dobsy.automf(DestDiv) if view==1: Dobsy.view() '''********Output Fuzzification***********''' Vdestx = ctrl.Consequent(np.arange(-accl-0.001, accl+0.001, 0.1), 'Vdestx') # Vdest = ctrl.Consequent(np.arange(0-0.001, 1+0.001, 0.1), 'Vdest') Vdestx.automf(VdestDiv) Vdesty = ctrl.Consequent(np.arange(-accl-0.001, accl+0.001, 0.1), 'Vdesty') # Vdest = ctrl.Consequent(np.arange(0-0.001, 1+0.001, 0.1), 'Vdest') Vdesty.automf(VdestDiv) Vobsx = ctrl.Consequent(np.arange(-acco-0.001, int(acco/2)+0.001, 0.1), 'Vobsx') # Vdest = ctrl.Consequent(np.arange(0-0.001, 1+0.001, 0.1), 'Vdest') Vobsx.automf(VdestDiv) Vobsy = ctrl.Consequent(np.arange(-acco-0.001, int(acco/2)+0.001, 0.1), 'Vobsy') # Vdest = ctrl.Consequent(np.arange(0-0.001, 1+0.001, 0.1), 'Vdest') Vobsy.automf(VdestDiv) if view==1: Vdestx.view() Vdesty.view() Vobsx.view() Vobsy.view() ''' V s poor m average f good Dest close poor m average far good Vdest s poor m average f good ''' ''' ***********Inference Rules************** ''' rule1 = ctrl.Rule(Vx['poor'] & Destx['poor'] | Vx['average'] & Destx['average'] , Vdestx['average']) rule2 = ctrl.Rule(Vy['poor'] & Desty['poor'] | Vy['average'] & Desty['average'] , Vdesty['average']) rule3 = ctrl.Rule(Vx['poor'] & Destx['average'] | Vx['poor'] & Destx['good'] | Vx['average'] & Destx['good'] , Vdestx['decent']) rule4 = ctrl.Rule(Vy['poor'] & Desty['average'] | Vy['poor'] & Desty['good'] | Vy['average'] & Desty['good'] , Vdesty['decent']) rule5 = ctrl.Rule(Vx['average'] & Destx['poor'] | Vx['good'] & Destx['average'] , Vdestx['mediocre']) rule6 = ctrl.Rule(Vy['average'] & Desty['poor'] | Vy['good'] & Desty['average'] , Vdesty['mediocre']) rule7 = ctrl.Rule(Vx['good'] & Destx['good'], Vdestx['good']) rule8 = ctrl.Rule(Vy['good'] & Desty['good'], Vdesty['good']) rule9 = ctrl.Rule(Vx['good'] & Destx['poor'], Vdestx['poor']) rule10 = ctrl.Rule(Vy['good'] & Desty['poor'], Vdesty['poor']) rule11 = ctrl.Rule(Vx['poor'] & Dobsx['poor'] | Vx['average'] & Dobsx['average'] , Vobsx['average']) rule12 = ctrl.Rule(Vy['poor'] & Dobsy['poor'] | Vy['average'] & Dobsy['average'] , Vobsy['average']) rule13 = ctrl.Rule(Vx['poor'] & Dobsx['average'] | Vx['poor'] & Dobsx['good'] | Vx['average'] & Dobsx['good'] , Vobsx['decent']) rule14 = ctrl.Rule(Vy['poor'] & Dobsy['average'] | Vy['poor'] & Dobsy['good'] | Vy['average'] & Dobsy['good'] , Vobsy['decent']) rule15 = ctrl.Rule(Vx['average'] & Dobsx['poor'] | Vx['good'] & Dobsx['average'] , Vobsx['mediocre']) rule16 = ctrl.Rule(Vy['average'] & Dobsy['poor'] | Vy['good'] & Dobsy['average'] , Vobsy['mediocre']) rule17 = ctrl.Rule(Vx['good'] & Dobsx['good'], Vobsx['good']) rule18 = ctrl.Rule(Vy['good'] & Dobsy['good'], Vobsy['good']) rule19 = ctrl.Rule(Vx['good'] & Destx['poor'], Vobsx['poor']) rule20 = ctrl.Rule(Vy['good'] & Desty['poor'], Vobsy['poor']) #rule1.view() VelControlLong1 = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5,rule6, rule7, rule8, rule9, rule10]) VelControlLong2 = ctrl.ControlSystem([rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20]) VCntrl1 = ctrl.ControlSystemSimulation(VelControlLong1) VCntrl2 = ctrl.ControlSystemSimulation(VelControlLong2) return VCntrl1,VCntrl2
def combFIS(model_run): arcpy.env.overwriteOutput = True # get list of all fields in the flowline network fields = [f.name for f in arcpy.ListFields(in_network)] # set the carrying capacity and vegetation field depending on whether potential or existing run if model_run == 'pt': out_field = "oCC_PT" veg_field = "oVC_PT" else: out_field = "oCC_EX" veg_field = "oVC_EX" # check for oCC_* field in the network attribute table and delete if exists if out_field in fields: arcpy.DeleteField_management(in_network, out_field) # get arrays for fields of interest segid_np = arcpy.da.FeatureClassToNumPyArray(in_network, "SegID") ovc_np = arcpy.da.FeatureClassToNumPyArray(in_network, veg_field) ihydsp2_np = arcpy.da.FeatureClassToNumPyArray(in_network, "iHyd_SP2") ihydsplow_np = arcpy.da.FeatureClassToNumPyArray( in_network, "iHyd_SPLow") igeoslope_np = arcpy.da.FeatureClassToNumPyArray( in_network, "iGeo_Slope") segid_array = np.asarray(segid_np, np.int64) ovc_array = np.asarray(ovc_np, np.float64) ihydsp2_array = np.asarray(ihydsp2_np, np.float64) ihydsplow_array = np.asarray(ihydsplow_np, np.float64) igeoslope_array = np.asarray(igeoslope_np, np.float64) # check that inputs are within range of fis # if not, re-assign the value to just within range ovc_array[ovc_array < 0] = 0 ovc_array[ovc_array > 45] = 45 ihydsp2_array[ihydsp2_array < 0] = 0.0001 ihydsp2_array[ihydsp2_array > 10000] = 10000 ihydsplow_array[ihydsplow_array < 0] = 0.0001 ihydsplow_array[ihydsplow_array > 10000] = 10000 igeoslope_array[igeoslope_array > 1] = 1 # delete temp arrays items = [segid_np, ovc_np, ihydsp2_np, ihydsplow_np, igeoslope_np] for item in items: del item # create antecedent (input) and consequent (output) objects to hold universe variables and membership functions ovc = ctrl.Antecedent(np.arange(0, 45, 0.01), 'input1') sp2 = ctrl.Antecedent(np.arange(0, 10000, 1), 'input2') splow = ctrl.Antecedent(np.arange(0, 10000, 1), 'input3') slope = ctrl.Antecedent(np.arange(0, 1, 0.0001), 'input4') density = ctrl.Consequent(np.arange(0, 45, 0.01), 'result') # build membership functions for each antecedent and consequent object ovc['none'] = fuzz.trimf(ovc.universe, [0, 0, 0.1]) ovc['rare'] = fuzz.trapmf(ovc.universe, [0, 0.1, 0.5, 1.5]) ovc['occasional'] = fuzz.trapmf(ovc.universe, [0.5, 1.5, 4, 8]) ovc['frequent'] = fuzz.trapmf(ovc.universe, [4, 8, 12, 25]) ovc['pervasive'] = fuzz.trapmf(ovc.universe, [12, 25, 45, 45]) sp2['persists'] = fuzz.trapmf(sp2.universe, [0, 0, 1000, 1200]) sp2['breach'] = fuzz.trimf(sp2.universe, [1000, 1200, 1600]) sp2['oblowout'] = fuzz.trimf(sp2.universe, [1200, 1600, 2400]) sp2['blowout'] = fuzz.trapmf(sp2.universe, [1600, 2400, 10000, 10000]) splow['can'] = fuzz.trapmf(splow.universe, [0, 0, 150, 175]) splow['probably'] = fuzz.trapmf(splow.universe, [150, 175, 180, 190]) splow['cannot'] = fuzz.trapmf(splow.universe, [180, 190, 10000, 10000]) slope['flat'] = fuzz.trapmf(slope.universe, [0, 0, 0.0002, 0.005]) slope['can'] = fuzz.trapmf(slope.universe, [0.0002, 0.005, 0.12, 0.15]) slope['probably'] = fuzz.trapmf(slope.universe, [0.12, 0.15, 0.17, 0.23]) slope['cannot'] = fuzz.trapmf(slope.universe, [0.17, 0.23, 1, 1]) density['none'] = fuzz.trimf(density.universe, [0, 0, 0.1]) density['rare'] = fuzz.trapmf(density.universe, [0, 0.1, 0.5, 1.5]) density['occasional'] = fuzz.trapmf(density.universe, [0.5, 1.5, 4, 8]) density['frequent'] = fuzz.trapmf(density.universe, [4, 8, 12, 25]) density['pervasive'] = fuzz.trapmf(density.universe, [12, 25, 45, 45]) # build fis rule table rule1 = ctrl.Rule(ovc['none'], density['none']) rule2 = ctrl.Rule(splow['cannot'], density['none']) rule3 = ctrl.Rule(slope['cannot'], density['none']) rule4 = ctrl.Rule( ovc['rare'] & sp2['persists'] & splow['can'] & ~slope['cannot'], density['rare']) rule5 = ctrl.Rule( ovc['occasional'] & sp2['persists'] & splow['can'] & ~slope['cannot'], density['occasional']) rule6 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['can'] & slope['can'], density['frequent']) rule7 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['can'] & slope['probably'], density['occasional']) rule8 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['flat'], density['pervasive']) rule9 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['can'], density['pervasive']) rule10 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['probably'], density['occasional']) rule11 = ctrl.Rule( ovc['rare'] & sp2['breach'] & splow['can'] & ~slope['cannot'], density['rare']) rule12 = ctrl.Rule( ovc['occasional'] & sp2['breach'] & splow['can'] & ~slope['cannot'], density['occasional']) rule13 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['can'], density['frequent']) rule14 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['probably'], density['occasional']) rule15 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['flat'], density['occasional']) rule16 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['can'], density['frequent']) rule17 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['probably'], density['occasional']) rule18 = ctrl.Rule( ovc['rare'] & sp2['oblowout'] & splow['can'] & ~slope['cannot'], density['rare']) rule19 = ctrl.Rule( ovc['occasional'] & sp2['oblowout'] & splow['can'] & ~slope['cannot'], density['occasional']) rule20 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['can'], density['frequent']) rule21 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['probably'], density['occasional']) rule22 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['flat'], density['occasional']) rule23 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['can'], density['frequent']) rule24 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['probably'], density['occasional']) rule25 = ctrl.Rule( ovc['rare'] & sp2['blowout'] & splow['can'] & ~slope['cannot'], density['none']) rule26 = ctrl.Rule( ovc['occasional'] & sp2['blowout'] & splow['can'] & ~slope['cannot'], density['rare']) rule27 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['can'], density['rare']) rule28 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['probably'], density['none']) rule29 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['flat'], density['rare']) rule30 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['can'], density['occasional']) rule31 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['probably'], density['rare']) rule32 = ctrl.Rule( ovc['rare'] & sp2['breach'] & splow['probably'] & ~slope['cannot'], density['rare']) rule33 = ctrl.Rule( ovc['occasional'] & sp2['breach'] & splow['probably'] & ~slope['cannot'], density['occasional']) rule34 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['can'], density['frequent']) rule35 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['probably'], density['occasional']) rule36 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['flat'], density['occasional']) rule37 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['can'], density['frequent']) rule38 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['probably'], density['occasional']) rule39 = ctrl.Rule( ovc['rare'] & sp2['oblowout'] & splow['probably'] & ~slope['cannot'], density['rare']) rule40 = ctrl.Rule( ovc['occasional'] & sp2['oblowout'] & splow['probably'] & ~slope['cannot'], density['occasional']) rule41 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['can'], density['occasional']) rule42 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['probably'], density['rare']) rule43 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['flat'], density['occasional']) rule44 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['can'], density['frequent']) rule45 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['probably'], density['occasional']) rule46 = ctrl.Rule( ovc['rare'] & sp2['blowout'] & splow['probably'] & ~slope['cannot'], density['none']) rule47 = ctrl.Rule( ovc['occasional'] & sp2['blowout'] & splow['probably'] & ~slope['cannot'], density['rare']) rule48 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['can'], density['rare']) rule49 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['probably'], density['none']) rule50 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['flat'], density['rare']) rule51 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['can'], density['occasional']) rule52 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['probably'], density['rare']) rule53 = ctrl.Rule( ovc['rare'] & sp2['persists'] & splow['probably'] & ~slope['cannot'], density['rare']) rule54 = ctrl.Rule( ovc['occasional'] & sp2['persists'] & splow['probably'] & ~slope['cannot'], density['rare']) rule55 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['flat'], density['occasional']) rule56 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['can'], density['frequent']) rule57 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['probably'], density['occasional']) rule58 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['flat'], density['frequent']) rule59 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['flat'], density['occasional']) rule60 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['flat'], density['occasional']) rule61 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['flat'], density['occasional']) rule62 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['flat'], density['rare']) rule63 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['flat'], density['rare']) rule64 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['probably'] & ~slope['cannot'], density['frequent']) rule65 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['can'] & slope['flat'], density['occasional']) comb_ctrl = ctrl.ControlSystem([ rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28, rule29, rule30, rule31, rule32, rule33, rule34, rule35, rule36, rule37, rule38, rule39, rule40, rule41, rule42, rule43, rule44, rule45, rule46, rule47, rule48, rule49, rule50, rule51, rule52, rule53, rule54, rule55, rule56, rule57, rule58, rule59, rule60, rule61, rule62, rule63, rule64, rule65 ]) comb_fis = ctrl.ControlSystemSimulation(comb_ctrl) # run fuzzy inference system on inputs and defuzzify output out = np.zeros( len(ovc_array)) # todo: test this using nas instead of zeros for i in range(len(out)): comb_fis.input['input1'] = ovc_array[i] comb_fis.input['input2'] = ihydsp2_array[i] comb_fis.input['input3'] = ihydsplow_array[i] comb_fis.input['input4'] = igeoslope_array[i] comb_fis.compute() out[i] = comb_fis.output['result'] # save fuzzy inference system output as table columns = np.column_stack((segid_array, out)) out_table = os.path.dirname( in_network ) + "/" + out_field + "_Table.txt" # todo: see if possible to skip this step np.savetxt(out_table, columns, delimiter=",", header="SegID, " + out_field, comments="") occ_table = scratch + "/" + out_field + "Tbl" arcpy.CopyRows_management(out_table, occ_table) # join the fuzzy inference system output to the flowline network # create empty dictionary to hold input table field values tblDict = {} # add values to dictionary with arcpy.da.SearchCursor(occ_table, ['SegID', out_field]) as cursor: for row in cursor: tblDict[row[0]] = row[1] # populate flowline network out field arcpy.AddField_management(in_network, out_field, 'DOUBLE') with arcpy.da.UpdateCursor(in_network, ['SegID', out_field]) as cursor: for row in cursor: try: aKey = row[0] row[1] = tblDict[aKey] cursor.updateRow(row) except: pass tblDict.clear() # calculate defuzzified centroid value for density 'none' MF group # this will be used to re-classify output values that fall in this group # important: will need to update the array (x) and MF values (mfx) if the # density 'none' values are changed in the model x = np.arange(0, 45, 0.01) mfx = fuzz.trimf(x, [0, 0, 0.1]) defuzz_centroid = round(fuzz.defuzz(x, mfx, 'centroid'), 6) # update combined capacity (occ_*) values in stream network # correct for occ_* greater than ovc_* as vegetation is most limiting factor in model # (i.e., combined fis value should not be greater than the vegetation capacity) # set occ_* to 0 if the drainage area is greater than the user defined threshold # this enforces a stream size threshold above which beaver dams won't persist and/or won't be built # set occ_* to 0 if output falls fully in 'none' category with arcpy.da.UpdateCursor( in_network, [out_field, veg_field, 'iGeo_DA', 'iGeo_Slope']) as cursor: for row in cursor: if row[0] > row[1]: row[0] = row[1] if row[2] >= float(max_DA_thresh): row[0] = 0.0 if round(row[0], 6) == defuzz_centroid: row[0] = 0.0 cursor.updateRow(row) # delete temporary tables and arrays arcpy.Delete_management(out_table) arcpy.Delete_management(occ_table) items = [columns, out, x, mfx, defuzz_centroid] for item in items: del item
def __init__(self, rr_lower_bound, r_lower_bound, fr_lower_bound, fl_lower_bound, l_lower_bound, rl_lower_bound): self.RR_LOWER_BOUND = rr_lower_bound self.R_LOWER_BOUND = r_lower_bound self.FR_LOWER_BOUND = fr_lower_bound self.FL_LOWER_BOUND = fl_lower_bound self.L_LOWER_BOUND = l_lower_bound self.RL_LOWER_BOUND = rl_lower_bound # New Antecedent/Consequent objects hold universe variables and membership functions # Generate universe variables of category 1: # INPUTS (ranges minima): # @ min_rear_right [0, 0.76] # @ min_right [0, 0.76] # @ min_front_right [0, 0.76] # @ min_front_left [0, 0.76] # @ min_left [0, 0.76] # @ min_rear_left [0, 0.76] #self.min_rear_right = ctrl.Antecedent(np.linspace(0, 0.76, 100), 'min rear right') #self.min_right = ctrl.Antecedent(np.linspace(0, 0.76, 100), 'min right') #self.min_front_right = ctrl.Antecedent(np.linspace(0, 0.76, 100), 'min front right') #self.min_front_left = ctrl.Antecedent(np.linspace(0, 0.76, 100), 'min front left') #self.min_left = ctrl.Antecedent(np.linspace(0, 0.76, 100), 'min left') #self.min_rear_left = ctrl.Antecedent(np.linspace(0, 0.76, 100), 'min rear left') self.min_rear_right = ctrl.Antecedent(np.linspace(0, 11, 100), 'min rear right') self.min_right = ctrl.Antecedent(np.linspace(0, 11, 100), 'min right') self.min_front_right = ctrl.Antecedent(np.linspace(0, 11, 100), 'min front right') self.min_front_left = ctrl.Antecedent(np.linspace(0, 11, 100), 'min front left') self.min_left = ctrl.Antecedent(np.linspace(0, 11, 100), 'min left') self.min_rear_left = ctrl.Antecedent(np.linspace(0, 11, 100), 'min rear left') # Generate universe variables of category 2: # INPUTS (ranges minima indexes): # @ index_rear_right [0, 1001] # @ index_right [0, 1001] # @ index_front_right [0, 1001] # @ index_front_left [0, 1001] # @ index_left [0, 1001] # @ index_rear_left [0, 1001] self.index_rear_right = ctrl.Antecedent(np.linspace(0, 1001, 500), 'index rear right') self.index_right = ctrl.Antecedent(np.linspace(0, 1001, 500), 'index right') self.index_front_right = ctrl.Antecedent(np.linspace(0, 1001, 500), 'index front right') self.index_front_left = ctrl.Antecedent(np.linspace(0, 1001, 500), 'index front left') self.index_left = ctrl.Antecedent(np.linspace(0, 1001, 500), 'index left') self.index_rear_left = ctrl.Antecedent(np.linspace(0, 1001, 500), 'index rear left') # Generate universe variable of category 3: # INPUT (near goal condition): # @ near_goal [0, 1] self.near_goal = ctrl.Antecedent(np.linspace(0, 1.1, 100), 'near goal') # Generate universe variable of category 4: # OUTPUTS (velocities): # @ Vx [-0.5, 0.5] # @ Vy [-0.5, 0.5] self.Vx = ctrl.Consequent(np.linspace(-0.6, 0.6, 500), 'Vx out') self.Vy = ctrl.Consequent(np.linspace(-0.6, 0.6, 500), 'Vy out') # Generate fuzzy membership functions for variables of category 1 self.min_rear_right['rr_close'] = fuzz.trapmf( self.min_rear_right.universe, [0, 0, 0.4, 0.45]) self.min_rear_right['rr_far'] = fuzz.trapmf( self.min_rear_right.universe, [0.4, 0.45, 0.65, 0.7]) self.min_rear_right['rr_dontcare'] = fuzz.trapmf( self.min_rear_right.universe, [0.65, 0.7, 11, 11]) self.min_right['r_close'] = fuzz.trapmf(self.min_right.universe, [0, 0, 0.4, 0.45]) self.min_right['r_far'] = fuzz.trapmf(self.min_right.universe, [0.4, 0.45, 0.65, 0.7]) self.min_right['r_dontcare'] = fuzz.trapmf(self.min_right.universe, [0.65, 0.7, 11, 11]) self.min_front_right['fr_close'] = fuzz.trapmf( self.min_front_right.universe, [0, 0, 0.4, 0.45]) self.min_front_right['fr_far'] = fuzz.trapmf( self.min_front_right.universe, [0.4, 0.45, 0.65, 0.7]) self.min_front_right['fr_dontcare'] = fuzz.trapmf( self.min_front_right.universe, [0.65, 0.7, 11, 11]) self.min_front_left['fl_close'] = fuzz.trapmf( self.min_front_left.universe, [0, 0, 0.4, 0.45]) self.min_front_left['fl_far'] = fuzz.trapmf( self.min_front_left.universe, [0.4, 0.45, 0.65, 0.7]) self.min_front_left['fl_dontcare'] = fuzz.trapmf( self.min_front_left.universe, [0.65, 0.7, 11, 11]) self.min_left['l_close'] = fuzz.trapmf(self.min_left.universe, [0, 0, 0.4, 0.45]) self.min_left['l_far'] = fuzz.trapmf(self.min_left.universe, [0.4, 0.45, 0.65, 0.7]) self.min_left['l_dontcare'] = fuzz.trapmf(self.min_left.universe, [0.65, 0.7, 11, 11]) self.min_rear_left['rl_close'] = fuzz.trapmf( self.min_rear_left.universe, [0, 0, 0.4, 0.45]) self.min_rear_left['rl_far'] = fuzz.trapmf(self.min_rear_left.universe, [0.4, 0.45, 0.65, 0.7]) self.min_rear_left['rl_dontcare'] = fuzz.trapmf( self.min_rear_left.universe, [0.65, 0.7, 11, 11]) # Generate fuzzy membership functions for variables of category 2 self.index_rear_right['rr_isrr'] = fuzz.trapmf( self.index_rear_right.universe, [0, 1, 100, 200]) self.index_rear_right['rr_isr'] = fuzz.trapmf( self.index_rear_right.universe, [100, 200, 260, 360]) self.index_rear_right['rr_isfr'] = fuzz.trapmf( self.index_rear_right.universe, [260, 361, 450, 550]) self.index_rear_right['rr_isfl'] = fuzz.trapmf( self.index_rear_right.universe, [450, 550, 640, 740]) self.index_rear_right['rr_isl'] = fuzz.trapmf( self.index_rear_right.universe, [640, 740, 800, 900]) self.index_rear_right['rr_isrl'] = fuzz.trapmf( self.index_rear_right.universe, [800, 900, 1000, 1000]) self.index_right['r_isrr'] = fuzz.trapmf(self.index_right.universe, [0, 1, 100, 200]) self.index_right['r_isr'] = fuzz.trapmf(self.index_right.universe, [100, 200, 260, 360]) self.index_right['r_isfr'] = fuzz.trapmf(self.index_right.universe, [260, 361, 450, 550]) self.index_right['r_isfl'] = fuzz.trapmf(self.index_right.universe, [450, 550, 640, 740]) self.index_right['r_isl'] = fuzz.trapmf(self.index_right.universe, [640, 740, 800, 900]) self.index_right['r_isrl'] = fuzz.trapmf(self.index_right.universe, [800, 900, 1000, 1000]) self.index_front_right['fr_isrr'] = fuzz.trapmf( self.index_front_right.universe, [0, 1, 100, 200]) self.index_front_right['fr_isr'] = fuzz.trapmf( self.index_front_right.universe, [100, 200, 260, 360]) self.index_front_right['fr_isfr'] = fuzz.trapmf( self.index_front_right.universe, [260, 361, 450, 550]) self.index_front_right['fr_isfl'] = fuzz.trapmf( self.index_front_right.universe, [450, 550, 640, 740]) self.index_front_right['fr_isl'] = fuzz.trapmf( self.index_front_right.universe, [640, 740, 800, 900]) self.index_front_right['fr_isrl'] = fuzz.trapmf( self.index_front_right.universe, [800, 900, 1000, 1000]) self.index_front_left['fl_isrr'] = fuzz.trapmf( self.index_front_left.universe, [0, 1, 100, 200]) self.index_front_left['fl_isr'] = fuzz.trapmf( self.index_front_left.universe, [100, 200, 260, 360]) self.index_front_left['fl_isfr'] = fuzz.trapmf( self.index_front_left.universe, [260, 361, 450, 550]) self.index_front_left['fl_isfl'] = fuzz.trapmf( self.index_front_left.universe, [450, 550, 640, 740]) self.index_front_left['fl_isl'] = fuzz.trapmf( self.index_front_left.universe, [640, 740, 800, 900]) self.index_front_left['fl_isrl'] = fuzz.trapmf( self.index_front_left.universe, [800, 900, 1000, 1000]) self.index_left['l_isrr'] = fuzz.trapmf(self.index_left.universe, [0, 1, 100, 200]) self.index_left['l_isr'] = fuzz.trapmf(self.index_left.universe, [100, 200, 260, 360]) self.index_left['l_isfr'] = fuzz.trapmf(self.index_left.universe, [260, 361, 450, 550]) self.index_left['l_isfl'] = fuzz.trapmf(self.index_left.universe, [450, 550, 640, 740]) self.index_left['l_isl'] = fuzz.trapmf(self.index_left.universe, [640, 740, 800, 900]) self.index_left['l_isrl'] = fuzz.trapmf(self.index_left.universe, [800, 900, 1000, 1000]) self.index_rear_left['rl_isrr'] = fuzz.trapmf( self.index_rear_left.universe, [0, 1, 100, 200]) self.index_rear_left['rl_isr'] = fuzz.trapmf( self.index_rear_left.universe, [100, 200, 260, 360]) self.index_rear_left['rl_isfr'] = fuzz.trapmf( self.index_rear_left.universe, [260, 361, 450, 550]) self.index_rear_left['rl_isfl'] = fuzz.trapmf( self.index_rear_left.universe, [450, 550, 640, 740]) self.index_rear_left['rl_isl'] = fuzz.trapmf( self.index_rear_left.universe, [640, 740, 800, 900]) self.index_rear_left['rl_isrl'] = fuzz.trapmf( self.index_rear_left.universe, [800, 900, 1000, 1000]) # Generate fuzzy membership functions for variable of category 3 self.near_goal['false'] = fuzz.trimf(self.near_goal.universe, [0, 0, 0]) self.near_goal['true'] = fuzz.trimf(self.near_goal.universe, [1, 1, 1]) # Generate fuzzy membership functions for variable of category 4 # final output to be sent to ROS: # U1_f = U1 + Vy # U2_f = U2 - Vx # delta_fuzz define the width of the singleton, for smaller values the controller will tends to return the full value of the considered outputs MMF # WARNING: values of delta_fuzz that are too small will cause the controller to stop working, always check that output MMF functions are consistent self.delta_fuzz = 0.05 # Vx output definition (singletons): self.Vx['-0.5'] = fuzz.trimf( self.Vx.universe, [-0.5 - self.delta_fuzz, -0.5, -0.5 + self.delta_fuzz]) self.Vx['-0.4'] = fuzz.trimf( self.Vx.universe, [-0.4 - self.delta_fuzz, -0.4, -0.4 + self.delta_fuzz]) self.Vx['-0.3'] = fuzz.trimf( self.Vx.universe, [-0.3 - self.delta_fuzz, -0.3, -0.3 + self.delta_fuzz]) self.Vx['-0.2'] = fuzz.trimf( self.Vx.universe, [-0.2 - self.delta_fuzz, -0.2, -0.2 + self.delta_fuzz]) self.Vx['-0.1'] = fuzz.trimf( self.Vx.universe, [-0.1 - self.delta_fuzz, -0.1, -0.1 + self.delta_fuzz]) self.Vx['vxstop'] = fuzz.trimf(self.Vx.universe, [-self.delta_fuzz, 0, +self.delta_fuzz]) self.Vx['0.1'] = fuzz.trimf( self.Vx.universe, [0.1 - self.delta_fuzz, 0.1, 0.1 + self.delta_fuzz]) self.Vx['0.2'] = fuzz.trimf( self.Vx.universe, [0.2 - self.delta_fuzz, 0.2, 0.2 + self.delta_fuzz]) self.Vx['0.3'] = fuzz.trimf( self.Vx.universe, [0.3 - self.delta_fuzz, 0.3, 0.3 + self.delta_fuzz]) self.Vx['0.4'] = fuzz.trimf( self.Vx.universe, [0.4 - self.delta_fuzz, 0.4, 0.4 + self.delta_fuzz]) self.Vx['0.5'] = fuzz.trimf( self.Vx.universe, [0.5 - self.delta_fuzz, 0.5, 0.5 + self.delta_fuzz]) # Vy output definition (singletons): self.Vy['-0.5'] = fuzz.trimf( self.Vy.universe, [-0.5 - self.delta_fuzz, -0.5, -0.5 + self.delta_fuzz]) self.Vy['-0.4'] = fuzz.trimf( self.Vy.universe, [-0.4 - self.delta_fuzz, -0.4, -0.4 + self.delta_fuzz]) self.Vy['-0.3'] = fuzz.trimf( self.Vy.universe, [-0.3 - self.delta_fuzz, -0.3, -0.3 + self.delta_fuzz]) self.Vy['-0.2'] = fuzz.trimf( self.Vy.universe, [-0.2 - self.delta_fuzz, -0.2, -0.2 + self.delta_fuzz]) self.Vy['-0.1'] = fuzz.trimf( self.Vy.universe, [-0.1 - self.delta_fuzz, -0.1, -0.1 + self.delta_fuzz]) self.Vy['vystop'] = fuzz.trimf(self.Vy.universe, [-self.delta_fuzz, 0, +self.delta_fuzz]) self.Vy['0.1'] = fuzz.trimf( self.Vy.universe, [0.1 - self.delta_fuzz, 0.1, 0.1 + self.delta_fuzz]) self.Vy['0.2'] = fuzz.trimf( self.Vy.universe, [0.2 - self.delta_fuzz, 0.2, 0.2 + self.delta_fuzz]) self.Vy['0.3'] = fuzz.trimf( self.Vy.universe, [0.3 - self.delta_fuzz, 0.3, 0.3 + self.delta_fuzz]) self.Vy['0.4'] = fuzz.trimf( self.Vy.universe, [0.4 - self.delta_fuzz, 0.4, 0.4 + self.delta_fuzz]) self.Vy['0.5'] = fuzz.trimf( self.Vy.universe, [0.5 - self.delta_fuzz, 0.5, 0.5 + self.delta_fuzz]) # Visualize membership #Vy['-0.5'].view() #plt.show() # FUZZY RULES SECTION self.rule1 = ctrl.Rule( self.min_front_left['fl_close'] | self.min_front_right['fr_close'], (self.Vx['vxstop'], self.Vy['-0.5'])) self.rule2 = ctrl.Rule( self.min_front_left['fl_far'] & self.min_front_right['fr_far'] & self.near_goal['false'], (self.Vx['vxstop'], self.Vy['-0.4'])) self.rule3 = ctrl.Rule( self.min_rear_left['rl_close'] & self.index_rear_left['rl_isrl'] & self.near_goal['false'], (self.Vx['0.4'], self.Vy['0.5'])) self.rule4 = ctrl.Rule( self.min_rear_left['rl_close'] & self.index_rear_left['rl_isl'] & self.near_goal['false'], (self.Vx['0.5'], self.Vy['0.4'])) self.rule5 = ctrl.Rule( self.min_front_left['fl_far'] & self.index_rear_left['rl_isrl'] & self.near_goal['false'], (self.Vx['0.3'], self.Vy['0.4'])) self.rule6 = ctrl.Rule( self.min_rear_left['rl_far'] & self.index_rear_left['rl_isl'] & self.near_goal['false'], (self.Vx['0.4'], self.Vy['0.3'])) self.rule7 = ctrl.Rule( self.min_rear_right['rr_close'] & self.index_rear_left['rl_isrr'] & self.near_goal['false'], (self.Vx['-0.4'], self.Vy['0.5'])) self.rule8 = ctrl.Rule( self.min_rear_right['rr_close'] & self.index_rear_right['rr_isr'] & self.near_goal['false'], (self.Vx['-0.5'], self.Vy['0.4'])) self.rule9 = ctrl.Rule( self.min_rear_right['rr_far'] & self.index_rear_right['rr_isrr'] & self.near_goal['false'], (self.Vx['-0.3'], self.Vy['0.4'])) self.rule10 = ctrl.Rule( self.min_rear_right['rr_far'] & self.index_rear_right['rr_isr'] & self.near_goal['false'], (self.Vx['-0.4'], self.Vy['0.3'])) self.rule11 = ctrl.Rule( self.min_left['l_close'] & self.index_left['l_isl'] & self.near_goal['false'], (self.Vx['0.5'], self.Vy['vystop'])) self.rule12 = ctrl.Rule( self.min_left['l_close'] & self.index_left['l_isrl'] & self.near_goal['false'], (self.Vx['0.5'], self.Vy['0.2'])) self.rule13 = ctrl.Rule( self.min_left['l_close'] & self.index_left['l_isfl'] & self.near_goal['false'], (self.Vx['0.5'], self.Vy['0.2'])) self.rule14 = ctrl.Rule( self.min_left['l_far'] & self.index_left['l_isl'] & self.near_goal['false'], (self.Vx['0.4'], self.Vy['vystop'])) self.rule15 = ctrl.Rule( self.min_left['l_far'] & self.index_left['l_isrl'] & self.near_goal['false'], (self.Vx['0.4'], self.Vy['0.1'])) self.rule16 = ctrl.Rule( self.min_left['l_far'] & self.index_left['l_isfl'] & self.near_goal['false'], (self.Vx['0.4'], self.Vy['-0.1'])) self.rule17 = ctrl.Rule( self.min_right['r_close'] & self.index_right['r_isr'] & self.near_goal['false'], (self.Vx['-0.5'], self.Vy['vystop'])) self.rule18 = ctrl.Rule( self.min_right['r_close'] & self.index_right['r_isrr'] & self.near_goal['false'], (self.Vx['-0.5'], self.Vy['0.2'])) self.rule19 = ctrl.Rule( self.min_right['r_close'] & self.index_right['r_isfr'] & self.near_goal['false'], (self.Vx['-0.5'], self.Vy['-0.2'])) self.rule20 = ctrl.Rule( self.min_right['r_far'] & self.index_right['r_isr'] & self.near_goal['false'], (self.Vx['-0.4'], self.Vy['vystop'])) self.rule21 = ctrl.Rule( self.min_right['r_far'] & self.index_right['r_isrr'] & self.near_goal['false'], (self.Vx['-0.4'], self.Vy['0.1'])) self.rule22 = ctrl.Rule( self.min_right['r_far'] & self.index_right['r_isfr'] & self.near_goal['false'], (self.Vx['-0.4'], self.Vy['-0.1'])) self.rule23 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_far'] & self.min_front_right['fr_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_left['fl_isfl'] & self.near_goal['false'], (self.Vx['vxstop'], self.Vy['-0.3'])) self.rule24 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_far'] & self.min_front_right['fr_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_left['fl_isl'] & self.near_goal['false'], (self.Vx['0.3'], self.Vy['-0.1'])) self.rule25 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_far'] & self.min_front_right['fr_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_left['fl_isfr'] & self.near_goal['false'], (self.Vx['-0.3'], self.Vy['-0.1'])) self.rule26 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_close'] & self.min_front_right['fr_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_left['fl_isfl'] & self.near_goal['false'], (self.Vx['vxstop'], self.Vy['-0.3'])) self.rule27 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_close'] & self.min_front_right['fr_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_left['fl_isl'] & self.near_goal['false'], (self.Vx['0.3'], self.Vy['-0.2'])) self.rule28 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_close'] & self.min_front_right['fr_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_left['fl_isfr'] & self.near_goal['false'], (self.Vx['-0.3'], self.Vy['-0.2'])) self.rule29 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_far'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_right['fr_isfl'] & self.near_goal['false'], (self.Vx['vxstop'], self.Vy['-0.3'])) self.rule30 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_far'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_right['fr_isl'] & self.near_goal['false'], (self.Vx['-0.3'], self.Vy['-0.1'])) self.rule31 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_far'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_right['fr_isfr'] & self.near_goal['false'], (self.Vx['0.3'], self.Vy['-0.1'])) self.rule32 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_close'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_right['fr_isfl'] & self.near_goal['false'], (self.Vx['vxstop'], self.Vy['-0.3'])) self.rule33 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_close'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_right['fr_isl'] & self.near_goal['false'], (self.Vx['-0.3'], self.Vy['-0.2'])) self.rule34 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_close'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.index_front_right['fr_isfr'] & self.near_goal['false'], (self.Vx['0.3'], self.Vy['-0.2'])) # rule to approach final target HERE: self.rule35 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_left['l_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.near_goal['true'], (self.Vx['vxstop'], self.Vy['-0.5'])) self.rule36 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_dontcare'] & (~self.min_rear_right['rr_dontcare']) & self.near_goal['true'], (self.Vx['0.4'], self.Vy['-0.4'])) self.rule37 = ctrl.Rule( ~self.min_rear_left['rl_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_dontcare'] & self.min_rear_right['rr_dontcare'] & self.near_goal['true'], (self.Vx['-0.4'], self.Vy['0.4'])) self.rule38 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & (~self.min_left['l_dontcare']) & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_dontcare'] & self.min_rear_right['rr_dontcare'] & self.near_goal['true'], (self.Vx['-0.4'], self.Vy['-0.1'])) self.rule39 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_dontcare'] & (~self.min_right['r_dontcare']) & self.min_rear_right['rr_dontcare'] & self.near_goal['true'], (self.Vx['0.4'], self.Vy['-0.1'])) self.rule40 = ctrl.Rule( ~self.min_rear_left['rl_dontcare'] & self.min_front_left['fl_dontcare'] & self.min_front_right['fr_dontcare'] & (~self.min_rear_right['rr_dontcare']) & self.near_goal['true'], (self.Vx['vxstop'], self.Vy['-0.4'])) self.rule41 = ctrl.Rule( self.min_rear_left['rl_dontcare'] & self.min_front_left['fl_dontcare'] & (~self.min_right['r_dontcare']) & (~self.min_rear_right['rr_dontcare']) & self.near_goal['true'], (self.Vx['0.4'], self.Vy['-0.3'])) self.rule42 = ctrl.Rule( ~self.min_rear_left['rl_dontcare'] & (~self.min_left['l_dontcare']) & self.min_front_left['fl_dontcare'] & self.min_right['r_dontcare'] & self.min_rear_right['rr_dontcare'] & self.near_goal['true'], (self.Vx['-0.4'], self.Vy['-0.3'])) # if player is in front of the robot in near target area ?? # self.rule43 = ctrl.Rule(self.min_rear_left['rl_dontcare'] & (~self.min_front_left['fl_dontcare']) | (~self.min_front_right['fr_dontcare']) & self.min_rear_right['rr_dontcare'] & self.near_goal['true'], (self.Vx['vxstop'],self.Vy['-0.5'])) # Now that we have our rules defined, we can simply create a control system via: self.fuzzyavoider_ctrl = ctrl.ControlSystem([ self.rule1, self.rule2, self.rule3, self.rule4, self.rule5, self.rule6, self.rule7, self.rule8, self.rule9, self.rule10, self.rule11, self.rule12, self.rule13, self.rule14, self.rule15, self.rule16, self.rule17, self.rule18, self.rule19, self.rule20, self.rule21, self.rule22, self.rule23, self.rule24, self.rule25, self.rule26, self.rule27, self.rule28, self.rule29, self.rule30, self.rule31, self.rule32, self.rule33, self.rule34, self.rule35, self.rule36, self.rule37, self.rule38, self.rule39, self.rule40, self.rule41, self.rule42 ]) # In order to simulate this control system, we will create a ControlSystemSimulation self.fuzzyAvoider = ctrl.ControlSystemSimulation( self.fuzzyavoider_ctrl)
def test_object(self): import pandas as pd import numpy as np import skfuzzy as fuzz from skfuzzy import control as ctrl from sklearn.datasets import make_blobs from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt from fuzzyml import FuzzyClassifier from fuzzyml import plot_decision_function X, y = make_blobs(n_samples=1000, centers=4, random_state=0) X = pd.DataFrame(X) cols = ["f1", "f2"] X.columns = cols y[y == 2] = 0 not_visible = y == 3 y[not_visible] = 1 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['L1'] = fuzz.gaussmf(label.universe, 0, 2) label['L2'] = fuzz.gaussmf(label.universe, 10, 2) label.view() # rules rule1 = ctrl.Rule(feature1['G1'] & feature2['G2'], label['L2']) 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) # 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() self.assertTrue(score_dt == 0.75) self.assertTrue(score_fz == 0.924) return
efficiency_axis.automf(3) qualifications_axis.automf(3) desire_to_develop_axis.automf(5) """ Auto-membership function population. """ grade_names = ['slaby', 'przecietny', 'sredni', 'przyzwoity', 'dobry'] grade.automf(names=grade_names) # rules rule1 = ctrl.Rule(antecedent=((efficiency_axis['poor'] & qualifications_axis['poor'] & desire_to_develop_axis['poor']) | (efficiency_axis['poor'] & qualifications_axis['average'] & desire_to_develop_axis['poor']) | (efficiency_axis['average'] & qualifications_axis['poor'] & desire_to_develop_axis['poor']) | (efficiency_axis['poor'] & qualifications_axis['poor'] & desire_to_develop_axis['mediocre']) ), consequent=(grade['slaby'])) rule2 = ctrl.Rule(antecedent=((efficiency_axis['poor'] & qualifications_axis['average'] & desire_to_develop_axis['mediocre']) | (efficiency_axis['average'] & qualifications_axis['poor'] & desire_to_develop_axis['mediocre']) | (efficiency_axis['poor'] & qualifications_axis['poor'] & desire_to_develop_axis['good']) | (efficiency_axis['poor'] & qualifications_axis['poor'] & desire_to_develop_axis['average']) | (efficiency_axis['poor'] & qualifications_axis['poor'] & desire_to_develop_axis['decent']) | (efficiency_axis['good'] & qualifications_axis['poor'] & desire_to_develop_axis['poor']) | (efficiency_axis['poor'] & qualifications_axis['good'] & desire_to_develop_axis['poor']) | (efficiency_axis['poor'] & qualifications_axis['good'] & desire_to_develop_axis['mediocre']) | (efficiency_axis['good'] & qualifications_axis['poor'] & desire_to_develop_axis['mediocre']) | (efficiency_axis['average'] & qualifications_axis['poor'] & desire_to_develop_axis['average']) | (efficiency_axis['average'] & qualifications_axis['average'] & desire_to_develop_axis['poor']) | (efficiency_axis['poor'] & qualifications_axis['average'] & desire_to_develop_axis['average'])),
def pulsetrap(edad,pulso): Age = ctrl.Antecedent(np.arange(0, 100, 1), "Age") Age["Child"] = fuzz.trapmf(Age.universe, [0, 0, 4.307, 12]) Age["Young"] = fuzz.trapmf(Age.universe, [9, 18.9, 27.1, 36.64]) Age["Adult"] = fuzz.trapmf(Age.universe, [32.9, 42.7, 53, 61.5079]) Age["Elder"] = fuzz.trapmf(Age.universe, [57.5, 85.3175, 100, 100]) Pulse = ctrl.Antecedent(np.arange(0, 220, 1), "Pulse") Pulse["VeryLow"] = fuzz.trapmf(Pulse.universe, [0, 0, 8.4392, 32.3]) Pulse["Low"] = fuzz.trapmf(Pulse.universe, [26.8, 34.6296, 50.3, 62.8]) Pulse["Normal"] = fuzz.trapmf(Pulse.universe, [59.0741, 73.6, 88.8, 102]) Pulse["High"] = fuzz.trapmf(Pulse.universe, [93.5, 116, 137, 162.672]) Pulse["VeryHigh"] = fuzz.trapmf(Pulse.universe, [155.6878, 205, 220, 220]) PLevels = ctrl.Consequent(np.arange(0, 100, 1), "PLevels") PLevels["BelowAV"] = fuzz.trapmf(PLevels.universe, [12.4, 16.8, 22.8836, 29.4]) PLevels["Excellent"] = fuzz.trapmf(PLevels.universe, [26.7, 32.672, 38.2, 43.4]) PLevels["AboveAV"] = fuzz.trapmf(PLevels.universe, [41.6, 50.7, 60.7143, 73.1]) PLevels["Low"] = fuzz.trapmf(PLevels.universe, [0, 0, 4.8942, 15]) PLevels["Very_High"] = fuzz.trapmf(PLevels.universe, [68.3862, 92.2, 101, 101]) regla1 = ctrl.Rule(Age["Child"] & Pulse["VeryLow"], PLevels["Low"]) regla2 = ctrl.Rule(Age["Child"] & Pulse["Low"], PLevels["Low"]) regla3 = ctrl.Rule(Age["Child"] & Pulse["Normal"], PLevels["Excellent"]) regla4 = ctrl.Rule(Age["Child"] & Pulse["High"], PLevels["Excellent"]) regla5 = ctrl.Rule(Age["Child"] & Pulse["VeryHigh"], PLevels["AboveAV"]) regla6 = ctrl.Rule(Age["Young"] & Pulse["VeryLow"], PLevels["Low"]) regla7 = ctrl.Rule(Age["Young"] & Pulse["Low"], PLevels["BelowAV"]) regla8 = ctrl.Rule(Age["Young"] & Pulse["Normal"], PLevels["Excellent"]) regla9 = ctrl.Rule(Age["Young"] & Pulse["High"], PLevels["AboveAV"]) regla10 = ctrl.Rule(Age["Young"] & Pulse["VeryHigh"], PLevels["Very_High"]) regla11 = ctrl.Rule(Age["Adult"] & Pulse["VeryLow"], PLevels["Low"]) regla12 = ctrl.Rule(Age["Adult"] & Pulse["Low"], PLevels["BelowAV"]) regla13 = ctrl.Rule(Age["Adult"] & Pulse["Normal"], PLevels["Excellent"]) regla14 = ctrl.Rule(Age["Adult"] & Pulse["High"], PLevels["AboveAV"]) regla15 = ctrl.Rule(Age["Adult"] & Pulse["VeryHigh"], PLevels["Very_High"]) regla16 = ctrl.Rule(Age["Elder"] & Pulse["High"], PLevels["Very_High"]) regla17 = ctrl.Rule(Age["Elder"] & Pulse["VeryHigh"], PLevels["Very_High"]) regla18 = ctrl.Rule(Age["Elder"] & Pulse["VeryLow"], PLevels["Low"]) regla19 = ctrl.Rule(Age["Elder"] & Pulse["Low"], PLevels["Excellent"]) regla20 = ctrl.Rule(Age["Elder"] & Pulse["Normal"], PLevels["Excellent"]) tipping_ctrl = ctrl.ControlSystem( [regla1, regla2, regla3, regla4, regla5, regla6, regla7, regla8, regla9, regla10, regla11, regla12, regla13, regla14, regla15, regla16, regla17, regla18, regla19, regla20]) tipping = ctrl.ControlSystemSimulation(tipping_ctrl) tipping.input['Age'] = edad tipping.input['Pulse'] = pulso tipping.compute() salida = tipping.output['PLevels'] return salida
saida = ctrl.Consequent(np.arange(-25, 25, 1), 'saida') #FunƧƵes de pertencimento erro['N'] = fuzz.trimf(erro.universe, [-20, -20, 0]) erro['Z'] = fuzz.trimf(erro.universe, [-20, 0, 20]) erro['P'] = fuzz.trimf(erro.universe, [0, 20, 20]) var_erro['N'] = fuzz.trimf(var_erro.universe, [-10, -10, 10]) var_erro['P'] = fuzz.trimf(var_erro.universe, [-10, 10, 10]) saida['N'] = fuzz.trimf(saida.universe, [-25, -25, 0]) saida['Z'] = fuzz.trimf(saida.universe, [-25, 0, 25]) saida['P'] = fuzz.trimf(saida.universe, [0, 25, 25]) #Regras r1 = ctrl.Rule(erro['N'] & var_erro['N'], saida['P']) r2 = ctrl.Rule(erro['N'] & var_erro['P'], saida['P']) r3 = ctrl.Rule(erro['Z'] & var_erro['N'], saida['Z']) r4 = ctrl.Rule(erro['Z'] & var_erro['P'], saida['Z']) r5 = ctrl.Rule(erro['P'] & var_erro['N'], saida['N']) r6 = ctrl.Rule(erro['P'] & var_erro['P'], saida['N']) #DefiniĆ§Ć£o do sistema de controle para defuzzificaĆ§Ć£o controle = ctrl.ControlSystem([r1, r2, r3, r4, r5, r6]) controle_sim = ctrl.ControlSystemSimulation(controle) #SimulaĆ§Ć£o com valores do exercĆcio controle_sim.input['erro'] = 16.0 controle_sim.input['var_erro'] = -2.0 controle_sim.compute()
distance['far'] = fuzz.trimf(distance.universe, [0, 0, 0.5]) distance['average'] = fuzz.trimf(distance.universe, [0, 0.5, 1]) distance['near'] = fuzz.trimf(distance.universe, [0.5, 1, 1]) # Custom membership functions can be built interactively with a familiar, # Pythonic API left['low'] = fuzz.trimf(left.universe, [0, 0, 5]) left['medium'] = fuzz.trimf(left.universe, [0, 5, 10]) left['high'] = fuzz.trimf(left.universe, [5, 10, 10]) right['low'] = fuzz.trimf(right.universe, [0, 0, 5]) right['medium'] = fuzz.trimf(right.universe, [0, 5, 10]) right['high'] = fuzz.trimf(right.universe, [5, 10, 10]) rule1 = ctrl.Rule(angle['negative'] & distance['far'], left['high']) rule2 = ctrl.Rule(angle['negative'] & distance['average'], left['medium']) rule3 = ctrl.Rule(angle['negative'] & distance['near'], left['high']) rule4 = ctrl.Rule(angle['zero'] & distance['far'], left['high']) rule5 = ctrl.Rule(angle['zero'] & distance['average'], left['medium']) rule6 = ctrl.Rule(angle['zero'] & distance['near'], left['low']) rule7 = ctrl.Rule(angle['positive'] & distance['far'], left['high']) rule8 = ctrl.Rule(angle['positive'] & distance['average'], left['low']) rule9 = ctrl.Rule(angle['positive'] & distance['near'], left['low']) rule11 = ctrl.Rule(angle['negative'] & distance['far'], right['high']) rule12 = ctrl.Rule(angle['negative'] & distance['average'], right['low']) rule13 = ctrl.Rule(angle['negative'] & distance['near'], right['low']) rule14 = ctrl.Rule(angle['zero'] & distance['far'], right['high']) rule15 = ctrl.Rule(angle['zero'] & distance['average'], right['medium']) rule16 = ctrl.Rule(angle['zero'] & distance['near'], right['low'])
dst_host_diff_srv_rate['low'] = fuzz.trimf(dst_host_diff_srv_rate.universe, [0, 25, 50]) dst_host_diff_srv_rate['meduim'] = fuzz.trimf(dst_host_diff_srv_rate.universe, [25, 50, 75]) dst_host_diff_srv_rate['high'] = fuzz.trimf(dst_host_diff_srv_rate.universe, [50, 75, 100]) #dst_host_diff_srv_rate.view() types = ctrl.Consequent(np.arange(0, 101, 1), 'types') types['Normal'] = fuzz.trimf(types.universe, [0, 0, 50]) #types['Risk'] = fuzz.trimf(types.universe, [25, 50, 75]) types['Attack'] = fuzz.trimf(types.universe, [50, 100, 100]) #types.view() rule1 = ctrl.Rule( dst_host_srv_count['low'] | dst_host_srv_count['high'] & dst_bytes['high'], types['Normal']) rule2 = ctrl.Rule(src_bytes['high'], types['Normal']) rule3 = ctrl.Rule(srv_count['high'] & src_bytes['low'] | src_bytes['high'], types['Normal']) rule4 = ctrl.Rule(num_compromised['high'], types['Normal']) rule5 = ctrl.Rule(serror_rate['high'], types['Normal']) rule6 = ctrl.Rule(dst_host_srv_count['high'], types['Normal']) rule7 = ctrl.Rule(dst_host_same_src_port_rate['high'], types['Normal']) rule8 = ctrl.Rule(dst_host_srv_diff_host_rate['high'], types['Normal']) rule9 = ctrl.Rule(dst_host_serror_rate['high'], types['Normal']) rule10 = ctrl.Rule(count['high'], types['Normal']) rule11 = ctrl.Rule( count['vlow'] & dst_host_same_srv_rate['low'] & dst_host_diff_srv_rate['low'] & same_srv_rate['low'] & diff_srv_rate['low'], types['Attack'])
def generar_selector(altura, diametro, transparencia, coberturaE): #FUSIFICADOR # Antecedentes # functions forma = ctrl.Antecedent(np.arange(0, 101, 1), 'forma') firmeza = ctrl.Antecedent(np.arange(0, 101, 1), 'firmeza') cobertura = ctrl.Antecedent(np.arange(0, 101, 1), 'cobertura') #Consecuentes calidad = ctrl.Consequent(np.arange(0, 11, 1), 'calidad') # Funcion de membresia de cada conjunto difuso #Antecedentes etiqueta_forma = ['Angosta', 'Normal', 'Ancha'] forma.automf(names=etiqueta_forma) etiqueta_firmeza = ['Podrida', 'Madura', 'Verde'] firmeza.automf(names=etiqueta_firmeza) etiqueta_cobertura = ['Leve', 'Parcial', 'Completa'] cobertura.automf(names=etiqueta_cobertura) #Consecuentes etiqueta_calidad = ['Desecho', 'Comercial', 'Exportable'] calidad.automf(names=etiqueta_calidad) #La salida por la cual saldrĆ” el fruto depende del diametro ingresado por el usuario if (diametro >= 18 and diametro < 19): salida = 1 elif (diametro >= 19 and diametro < 20): salida = 2 elif (diametro >= 20 and diametro < 21): salida = 3 elif (diametro >= 21 and diametro < 22): salida = 4 elif (diametro >= 22 and diametro < 23): salida = 5 elif (diametro >= 23 and diametro < 24): salida = 6 elif (diametro >= 24 and diametro < 25): salida = 7 elif (diametro >= 25 and diametro < 26): salida = 8 elif (diametro >= 26 and diametro < 27): salida = 9 elif (diametro >= 27 and diametro < 28): salida = 10 elif (diametro >= 28 and diametro < 29): salida = 11 elif (diametro >= 29 and diametro < 30): salida = 12 elif (diametro >= 30 and diametro < 31): salida = 13 elif (diametro >= 31 and diametro < 32): salida = 14 elif (diametro >= 32 and diametro < 33): salida = 15 # Caso particular menor a 18 mm o mayor a 33 (Desecho) elif (diametro < 18 or diametro >= 33): salida = 16 ############################DESCOMENTAR SI SE QUIERE VER GRAFICOS############################# # Mostrar grĆ”ficas componentes modelo #graficos antecedentes forma.view() #pausa() firmeza.view() #pausa() cobertura.view() #pausa() ###################SISTEMA DE INFERENCIA########################## #Aqui ocurre la logica principal del programa ya que se definen las reglas de la logica difusa de antecedentes->consecuencias y luego se calculan las #defusificaciones de los valores concecuentes, los cuales son enviados para ser escritos en un archivo de texto. #####Reglas difusas#### #La funcion Rule, crea las reglas a utilizar en la logica difusa, donde se anotan los antecedentes, con las variables logicas and, or, not segun corresponda #aplicando internamente mamdani #Finalmente, al realizar la defusificacion se usa ControlSystem para poder juntar todas las reglas y obtener los valores que mas se acomoden a las reglas. #Con controlSystemSimulation se simula el sistema difuso, y finalmente con input se ingresan las entradas. #EL diametro definirĆ” a cual salida debe ir cada cereza rule1 = ctrl.Rule(forma['Angosta'] & firmeza['Verde'] & cobertura['Leve'], calidad['Exportable']) rule2 = ctrl.Rule( forma['Angosta'] & firmeza['Verde'] & cobertura['Parcial'], calidad['Comercial']) rule3 = ctrl.Rule( forma['Angosta'] & firmeza['Verde'] & cobertura['Completa'], calidad['Desecho']) rule4 = ctrl.Rule(forma['Angosta'] & firmeza['Madura'] & cobertura['Leve'], calidad['Exportable']) rule5 = ctrl.Rule( forma['Angosta'] & firmeza['Madura'] & cobertura['Parcial'], calidad['Comercial']) rule6 = ctrl.Rule( forma['Angosta'] & firmeza['Madura'] & cobertura['Completa'], calidad['Desecho']) rule7 = ctrl.Rule( forma['Angosta'] & firmeza['Podrida'] & cobertura['Leve'], calidad['Desecho']) rule8 = ctrl.Rule( forma['Angosta'] & firmeza['Podrida'] & cobertura['Parcial'], calidad['Desecho']) rule9 = ctrl.Rule( forma['Angosta'] & firmeza['Podrida'] & cobertura['Completa'], calidad['Desecho']) rule10 = ctrl.Rule(forma['Normal'] & firmeza['Verde'] & cobertura['Leve'], calidad['Exportable']) rule11 = ctrl.Rule( forma['Normal'] & firmeza['Verde'] & cobertura['Parcial'], calidad['Exportable']) rule12 = ctrl.Rule( forma['Normal'] & firmeza['Verde'] & cobertura['Completa'], calidad['Desecho']) rule13 = ctrl.Rule(forma['Normal'] & firmeza['Madura'] & cobertura['Leve'], calidad['Exportable']) rule14 = ctrl.Rule( forma['Normal'] & firmeza['Madura'] & cobertura['Parcial'], calidad['Exportable']) rule15 = ctrl.Rule( forma['Normal'] & firmeza['Madura'] & cobertura['Completa'], calidad['Desecho']) rule16 = ctrl.Rule( forma['Normal'] & firmeza['Podrida'] & cobertura['Leve'], calidad['Desecho']) rule17 = ctrl.Rule( forma['Normal'] & firmeza['Podrida'] & cobertura['Parcial'], calidad['Desecho']) rule18 = ctrl.Rule( forma['Normal'] & firmeza['Podrida'] & cobertura['Completa'], calidad['Desecho']) rule19 = ctrl.Rule(forma['Ancha'] & firmeza['Verde'] & cobertura['Leve'], calidad['Exportable']) rule20 = ctrl.Rule( forma['Ancha'] & firmeza['Verde'] & cobertura['Parcial'], calidad['Exportable']) rule21 = ctrl.Rule( forma['Ancha'] & firmeza['Verde'] & cobertura['Completa'], calidad['Desecho']) rule22 = ctrl.Rule(forma['Ancha'] & firmeza['Madura'] & cobertura['Leve'], calidad['Exportable']) rule23 = ctrl.Rule( forma['Ancha'] & firmeza['Madura'] & cobertura['Parcial'], calidad['Comercial']) rule24 = ctrl.Rule( forma['Ancha'] & firmeza['Madura'] & cobertura['Completa'], calidad['Desecho']) rule25 = ctrl.Rule(forma['Ancha'] & firmeza['Podrida'] & cobertura['Leve'], calidad['Desecho']) rule26 = ctrl.Rule( forma['Ancha'] & firmeza['Podrida'] & cobertura['Parcial'], calidad['Desecho']) rule27 = ctrl.Rule( forma['Ancha'] & firmeza['Podrida'] & cobertura['Completa'], calidad['Desecho']) # Control system selector_ctrl = ctrl.ControlSystem([ rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27 ]) selector = ctrl.ControlSystemSimulation(selector_ctrl) # Entradas de la SimulaciĆ³n selector.input['forma'] = diametro / altura selector.input['firmeza'] = transparencia selector.input['cobertura'] = coberturaE # Computar resultados selector.compute() # Mostrar resultados #calidad.view(sim=selector) #pausa() escribir_archivo((altura, diametro, transparencia, coberturaE), (forma, firmeza, cobertura, calidad, salida)) plt.show() # Descomentar si se quieren observar los graficos #escribir_archivo(altura,diametro,transparencia,coberturaE,forma,) return
def main(): xp, yp, cp = load_csv() xp = np.asarray(xp) yp = np.asarray(yp) cp = np.asarray(cp) xpos = ctrl.Antecedent(np.arange(0, 1000000, 1000), 'xpos') ypos = ctrl.Antecedent(np.arange(0, 1000000, 1000), 'ypos') cluster = ctrl.Consequent(np.arange(0, 15, 1), 'cluster') xpos['0'] = fuzz.trimf(xpos.universe, [0, 0, 235000]) xpos['1'] = fuzz.trimf(xpos.universe, [235000, 280000, 325000]) xpos['2'] = fuzz.trimf(xpos.universe, [325000, 360000, 407000]) xpos['3'] = fuzz.trimf(xpos.universe, [407000, 455000, 513000]) xpos['4'] = fuzz.trimf(xpos.universe, [513000, 550000, 605000]) xpos['5'] = fuzz.trimf(xpos.universe, [605000, 660000, 733000]) xpos['6'] = fuzz.trimf(xpos.universe, [733000, 870000, 1000000]) ypos['0'] = fuzz.trimf(ypos.universe, [0, 0, 217000]) ypos['1'] = fuzz.trimf(ypos.universe, [217000, 240000, 263000]) ypos['2'] = fuzz.trimf(ypos.universe, [263000, 330000, 413000]) ypos['3'] = fuzz.trimf(ypos.universe, [413000, 450000, 490000]) ypos['4'] = fuzz.trimf(ypos.universe, [490000, 560000, 635000]) ypos['5'] = fuzz.trimf(ypos.universe, [635000, 660000, 687000]) ypos['6'] = fuzz.trimf(ypos.universe, [687000, 755000, 835000]) ypos['7'] = fuzz.trimf(ypos.universe, [835000, 970000, 1000000]) cluster['0'] = fuzz.trimf(cluster.universe, [0, 0, 2]) cluster['1'] = fuzz.trimf(cluster.universe, [1, 1.6, 3]) cluster['2'] = fuzz.trimf(cluster.universe, [2, 2.6, 4]) cluster['3'] = fuzz.trimf(cluster.universe, [3, 3.6, 5]) cluster['4'] = fuzz.trimf(cluster.universe, [4, 4.6, 6]) cluster['5'] = fuzz.trimf(cluster.universe, [5, 5.6, 7]) cluster['6'] = fuzz.trimf(cluster.universe, [6, 6.6, 8]) cluster['7'] = fuzz.trimf(cluster.universe, [7, 7.6, 9]) cluster['8'] = fuzz.trimf(cluster.universe, [8, 8.6, 10]) cluster['9'] = fuzz.trimf(cluster.universe, [9, 9.6, 11]) cluster['10'] = fuzz.trimf(cluster.universe, [10, 10.6, 12]) cluster['11'] = fuzz.trimf(cluster.universe, [11, 11.6, 13]) cluster['12'] = fuzz.trimf(cluster.universe, [12, 12.6, 14]) cluster['13'] = fuzz.trimf(cluster.universe, [13, 13.6, 15]) cluster['14'] = fuzz.trimf(cluster.universe, [14, 14.6, 16]) rule1 = ctrl.Rule((xpos['0'] | xpos['1']) & (ypos['6'] | ypos['7']), cluster['0']) rule2 = ctrl.Rule((xpos['2'] | xpos['3']) & (ypos['6'] | ypos['7']), cluster['1']) rule3 = ctrl.Rule((xpos['4'] | xpos['5']) & (ypos['6'] | ypos['7']), cluster['2']) rule4 = ctrl.Rule((xpos['6']) & (ypos['5'] | ypos['6'] | ypos['7']), cluster['3']) rule5 = ctrl.Rule((xpos['5'] | xpos['6']) & (ypos['3'] | ypos['4']), cluster['4']) rule6 = ctrl.Rule((xpos['4'] | xpos['5']) & (ypos['4'] | ypos['5']), cluster['5']) rule7 = ctrl.Rule((xpos['1'] | xpos['2'] | xpos['3']) & (ypos['4'] | ypos['5']), cluster['6']) rule8 = ctrl.Rule((xpos['0']) & (ypos['4'] | ypos['5']), cluster['7']) rule9 = ctrl.Rule((xpos['0']) & (ypos['1'] | ypos['2'] | ypos['3']), cluster['8']) rule10 = ctrl.Rule((xpos['1'] | xpos['2'] | xpos['3']) & (ypos['1'] | ypos['2'] | ypos['3']), cluster['9']) rule11 = ctrl.Rule((xpos['4'] | xpos['5']) & (ypos['1'] | ypos['2'] | ypos['3']), cluster['10']) rule12 = ctrl.Rule((xpos['6']) & (ypos['1'] | ypos['2'] | ypos['3']), cluster['11']) rule13 = ctrl.Rule((xpos['5'] | xpos['6']) & (ypos['0']), cluster['12']) rule14 = ctrl.Rule((xpos['3'] | xpos['4']) & (ypos['0'] | ypos['1']), cluster['13']) rule15 = ctrl.Rule((xpos['0'] | xpos['1'] | xpos['2']) & (ypos['0'] | ypos['1']), cluster['14']) # cluster.view() cluster_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15]) clustering = ctrl.ControlSystemSimulation(cluster_ctrl) similarity = 0 color_fuzz = [] for x, y, label in zip(xp, yp, cp): clustering.input['xpos'] = x clustering.input['ypos'] = y try: clustering.compute() # print(int(round(clustering.output['cluster'])), ' ', label) color_fuzz.append(int(round(clustering.output['cluster']))) if label == int(round(clustering.output['cluster'])): similarity += 1 except Exception as e: color_fuzz.append(20) print("% podobienstwa:", similarity/5000.*100) coloror = [colors[das] for das in color_fuzz] plt.scatter(xp, yp, color=coloror) plt.show()
b1 = demand['very little'] = fuzz.trimf(demand.universe, [3700, 3700, 4250]) b2 = demand['little'] = fuzz.trimf(demand.universe, [3700, 4250, 5250]) b3 = demand['average'] = fuzz.trimf(demand.universe, [4250, 5250, 6500]) b4 = demand['high'] = fuzz.trimf(demand.universe, [5250, 6500, 6900]) b5 = demand['very high'] = fuzz.trimf(demand.universe, [6500, 6900, 6900]) degreeOfInput2 = np.column_stack((b1, b2, b3, b4, b5)) demand.view() c1 = price['low'] = fuzz.trimf(price.universe, [0, 10, 23]) c2 = price['medium'] = fuzz.trimf(price.universe, [10, 23, 35]) c3 = price['high'] = fuzz.trimf(price.universe, [23, 35, 55]) degreeOfOput = np.column_stack((c1, c2, c3)) price.view() rule1 = ctrl.Rule(temperature['low'] & demand['very little'], price['low']) rule2 = ctrl.Rule(temperature['low'] & demand['little'], price['medium']) rule3 = ctrl.Rule(temperature['low'] & demand['average'], price['medium']) rule4 = ctrl.Rule(temperature['low'] & demand['high'], price['medium']) rule15 = ctrl.Rule(temperature['low'] & demand['very high'], price['high']) rule5 = ctrl.Rule(temperature['warm'] & demand['very little'], price['low']) rule6 = ctrl.Rule(temperature['warm'] & demand['little'], price['medium']) rule7 = ctrl.Rule(temperature['warm'] & demand['average'], price['medium']) rule8 = ctrl.Rule(temperature['warm'] & demand['high'], price['medium']) rule9 = ctrl.Rule(temperature['warm'] & demand['very high'], price['high']) rule10 = ctrl.Rule(temperature['hot'] & demand['very little'], price['low']) rule11 = ctrl.Rule(temperature['hot'] & demand['little'], price['medium']) rule12 = ctrl.Rule(temperature['hot'] & demand['average'], price['medium']) rule13 = ctrl.Rule(temperature['hot'] & demand['high'], price['high']) rule14 = ctrl.Rule(temperature['hot'] & demand['very high'], price['high']) rule1.view()
def Fuzzy_Ctrl(Goal_pos,Act_pos): # New Antecedent/Consequent objects hold universe variables and membership functions Distance = ctrl.Antecedent(np.arange(0, 100+0.1, 0.1), 'Distance') #Input Angle = ctrl.Antecedent(np.arange(-np.pi, np.pi+0.001, 0.001), 'Angle') #Input Velocity = ctrl.Consequent(np.arange(-0.13, 0.26+0.13+0.01, 0.01), 'Velocity') #Output Omega = ctrl.Consequent(np.arange(-1.82-1.82-0.01, 1.82+1.82+0.01, 0.01), 'Omega') #Output # Auto-membership function population is possible with .automf(3, 5, or 7) #Distance.automf(5) #Velocity.automf(3) # Custom membership functions can be built interactively with a familiar, Pythonic API Distance['Near'] = fuzz.trimf(Distance.universe, [0, 0, 0.5]) Distance['Mid'] = fuzz.trimf(Distance.universe, [0, 0.5, 1]) Distance['Far'] = fuzz.trapmf(Distance.universe, [0.5, 1, 100, 100]) Angle['Neg'] = fuzz.trapmf(Angle.universe, [-np.pi, -np.pi, -np.pi/4, 0]) Angle['Zero'] = fuzz.trimf(Angle.universe, [-np.pi/4, 0, np.pi/4]) Angle['Pos'] = fuzz.trapmf(Angle.universe, [0, np.pi/4, np.pi, np.pi]) Velocity['Zero'] = fuzz.trimf(Velocity.universe, [-0.13, 0, 0.13]) Velocity['Half'] = fuzz.trimf(Velocity.universe, [0, 0.13, 0.26]) Velocity['Full'] = fuzz.trimf(Velocity.universe, [0.13, 0.26, 0.26+0.13]) Omega['Negative'] = fuzz.trimf(Omega.universe, [-1.82-1.82, -1.82, 0]) Omega['Zero'] = fuzz.trimf(Omega.universe, [-1.82, 0, 1.82]) Omega['Positive'] = fuzz.trimf(Omega.universe, [0, 1.82, 1.82+1.82]) # You can see how these look with .view() #Distance.view() #Angle.view() #Velocity.view() #Omega.view() #Identify Rules #rule0 = ctrl.Rule(antecedent=((Distance['nb'] & delta['nb']) | # (Distance['ns'] & delta['nb']) | # (Distance['nb'] & delta['ns'])), # consequent=output['nb'], label='rule nb') rule1 = ctrl.Rule(Angle['Neg'], Velocity['Zero']) rule2 = ctrl.Rule(Angle['Neg'], Omega['Negative']) rule3 = ctrl.Rule(Angle['Pos'], Velocity['Zero']) rule4 = ctrl.Rule(Angle['Pos'], Omega['Positive']) rule5 = ctrl.Rule(Angle['Zero'], Omega['Zero']) rule6 = ctrl.Rule(antecedent=((Distance['Near'] & Angle['Zero'])), consequent=Velocity['Zero']) rule7 = ctrl.Rule(antecedent=((Distance['Mid'] & Angle['Zero'])), consequent=Velocity['Half']) rule8 = ctrl.Rule(antecedent=((Distance['Far'] & Angle['Zero'])), consequent=Velocity['Full']) Robot_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8]) Motion = ctrl.ControlSystemSimulation(Robot_ctrl) # Pass inputs to the ControlSystem using Antecedent labels with Pythonic API # Note: if you like passing many inputs all at once, use .inputs(dict_of_data) dis = np.sqrt((Goal_pos[0]-Act_pos[0])**2+(Goal_pos[1]-Act_pos[1])**2) print('distance is',dis) Motion.input['Distance'] = dis global last ang = np.arctan2((Goal_pos[1]-Act_pos[1]),(Goal_pos[0]-Act_pos[0]))-Act_pos[2] while ang < last-np.pi: ang += 2*np.pi while ang > last+np.pi: ang -= 2*np.pi last = ang print('angle is',ang) Motion.input['Angle'] = ang # Crunch the numbers Motion.compute() print(Motion.output['Velocity']) #Velocity.view(sim=Motion) out1 = Motion.output['Velocity'] print(Motion.output['Omega']) #Omega.view(sim=Motion) out2 = Motion.output['Omega'] Cont_input = [out1,out2] print(Cont_input) return Cont_input
food['Desagradable'] = fuzz.trapmf(food.universe, [0, 1, 3, 5]) food['Promedio'] = fuzz.trapmf(food.universe, [2, 4, 6, 8]) food['Deliciosa'] = fuzz.trapmf(food.universe, [5, 7, 9, 10]) tip['TacaƱa'] = fuzz.trimf(tip.universe, [0, 5, 10]) tip['Promedio'] = fuzz.trimf(tip.universe, [5, 15, 25]) tip['Generosa'] = fuzz.trimf(tip.universe, [20, 25, 30]) food.view() servicio.view() tip.view() rule1 = ctrl.Rule(servicio['Pobre'] | food['Desagradable'], tip['TacaƱa']) rule2 = ctrl.Rule(servicio['Bueno'], tip['Promedio']) rule3 = ctrl.Rule(servicio['Excelente'] | food['Deliciosa'], tip['Generosa']) rule1.view() tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3]) tipping = ctrl.ControlSystemSimulation(tipping_ctrl) """"" tipping.input['food'] = 1 tipping.input['service'] = 1 tipping.input['food'] = 8 tipping.input['service'] = 3
def _init_rules(self): self._rules = [] # ============================================================= # VERTICAL # ============================================================= # dont descent very fast self._rules.append( ctrl.Rule(self._v_speed['very-low'], self._v_thrust['very-high'])) # slow down when close to the landing self._rules.append( ctrl.Rule(self._v_speed['low'] & self._v_pos['center'], self._v_thrust['high'])) # keep descending if far from landing self._rules.append( ctrl.Rule( self._v_speed['low'] & (self._v_pos['high'] | self._v_pos['very-high']), self._v_thrust['center'])) # keep descending self._rules.append( ctrl.Rule(self._v_speed['center'], self._v_thrust['low'])) # dont go up! self._rules.append( ctrl.Rule(self._v_speed['high'], self._v_thrust['very-low'])) self._rules.append( ctrl.Rule(self._v_speed['very-high'], self._v_thrust['very-low'])) # ============================================================= # HORIZONTAL # ============================================================= # center when very far from center self._rules.append( ctrl.Rule(self._h_pos['very-left'], self._h_thrust['right'])) self._rules.append( ctrl.Rule(self._h_pos['very-right'], self._h_thrust['left'])) # but not too much self._rules.append( ctrl.Rule(self._h_pos['very-left'] & self._h_speed['very-right'], self._h_thrust['center'])) self._rules.append( ctrl.Rule(self._h_pos['very-right'] & self._h_speed['very-left'], self._h_thrust['center'])) # center when close to the center self._rules.append( ctrl.Rule(self._h_pos['left'] & self._h_speed['center'], self._h_thrust['right'])) self._rules.append( ctrl.Rule(self._h_pos['center'] & self._h_speed['left'], self._h_thrust['right'])) self._rules.append( ctrl.Rule(self._h_pos['center'] & self._h_speed['center'], self._h_thrust['center'])) self._rules.append( ctrl.Rule(self._h_pos['center'] & self._h_speed['right'], self._h_thrust['left'])) self._rules.append( ctrl.Rule(self._h_pos['right'] & self._h_speed['center'], self._h_thrust['left'])) # slow down if close to the center and moving too fast self._rules.append( ctrl.Rule(self._h_pos['center'] & self._h_speed['very-left'], self._h_thrust['very-right'])) self._rules.append( ctrl.Rule(self._h_pos['center'] & self._h_speed['left'], self._h_thrust['very-right'])) self._rules.append( ctrl.Rule(self._h_pos['center'] & self._h_speed['right'], self._h_thrust['very-left'])) self._rules.append( ctrl.Rule(self._h_pos['center'] & self._h_speed['very-right'], self._h_thrust['very-left']))
def __init__(self, cols, rows): self.x = cols self.y = rows self.position_y = ctrl.Antecedent(np.arange(0, self.y + 1, 1), 'position_y') self.position_x = ctrl.Antecedent(np.arange(0, self.x + 1, 1), 'position_x') self.position_y['very_low'] = fuzz.trimf(self.position_y.universe, [0, 0, self.y * 0.25]) self.position_y['low'] = fuzz.trimf(self.position_y.universe, [0, 0.25 * self.y, 0.5 * self.y]) self.position_y['center'] = fuzz.trimf( self.position_y.universe, [0.25 * self.y, 0.5 * self.y, 0.75 * self.y]) self.position_y['high'] = fuzz.trimf( self.position_y.universe, [0.5 * self.y, 0.75 * self.y, self.y]) self.position_y['very_high'] = fuzz.trimf( self.position_y.universe, [0.75 * self.y, self.y, self.y]) self.position_x['very_left'] = fuzz.trimf(self.position_x.universe, [0, 0, self.x * 0.25]) self.position_x['left'] = fuzz.trimf(self.position_x.universe, [0, 0.25 * self.x, 0.5 * self.x]) self.position_x['center'] = fuzz.trimf( self.position_x.universe, [0.25 * self.x, 0.5 * self.x, 0.75 * self.x]) self.position_x['right'] = fuzz.trimf( self.position_x.universe, [0.5 * self.x, 0.75 * self.x, self.x]) self.position_x['very_right'] = fuzz.trimf( self.position_x.universe, [0.75 * self.x, self.x, self.x]) self.output_y = ctrl.Consequent(np.arange(-40, 40, 1), 'output_y') self.output_x = ctrl.Consequent(np.arange(-40, 40, 1), 'output_x') self.output_y['very_low'] = fuzz.trimf(self.output_y.universe, [-30, -20, -10]) self.output_y['low'] = fuzz.trimf(self.output_y.universe, [-20, -10, 0]) self.output_y['center'] = fuzz.trimf(self.output_y.universe, [-10, 0, 10]) self.output_y['high'] = fuzz.trimf(self.output_y.universe, [0, 10, 20]) self.output_y['very_high'] = fuzz.trimf(self.output_y.universe, [10, 20, 30]) self.output_x['very_left'] = fuzz.trimf(self.output_x.universe, [-30, -20, -10]) self.output_x['left'] = fuzz.trimf(self.output_x.universe, [-20, -10, 0]) self.output_x['center'] = fuzz.trimf(self.output_x.universe, [-10, 0, 10]) self.output_x['right'] = fuzz.trimf(self.output_x.universe, [0, 10, 20]) self.output_x['very_right'] = fuzz.trimf(self.output_x.universe, [10, 20, 30]) self.y_str = ['very_low', 'low', 'center', 'high', 'very_high'] self.x_str = ['very_left', 'left', 'center', 'right', 'very_right'] self.rules = [] for i in range(5): for j in range(5): self.rules.append( ctrl.Rule(self.position_y[self.y_str[i]] & self.position_x[self.x_str[j]], consequent=[ self.output_y[self.y_str[i]], self.output_x[self.x_str[j]] ])) self.position_ctrl = ctrl.ControlSystem(self.rules) self.position = ctrl.ControlSystemSimulation(self.position_ctrl)
def main(projPath, in_network, pt_type, ex_type, max_DA_thresh, out_name, scratch): arcpy.env.overwriteOutput = True network_fields = [f.name for f in arcpy.ListFields(in_network)] if pt_type == "true": # check for oCC_PT field and delete if exists if "oCC_PT" in network_fields: arcpy.DeleteField_management(in_network, "oCC_PT") # check that inputs are within range of fis (slope already taken care of) cursor = arcpy.da.UpdateCursor(in_network, ["oVC_PT", "iHyd_SP2", "iHyd_SPLow"]) for row in cursor: if row[0] < 0: row[0] = 0 elif row[0] > 45: row[0] = 44 elif row[1] < 0: row[1] = 0.001 elif row[1] > 10000: row[1] = 10000 elif row[2] < 0: row[2] = 0.001 elif row[2] > 10000: row[2] = 10000 else: pass cursor.updateRow(row) del row del cursor # get arrays for fields of interest ovcex_a = arcpy.da.FeatureClassToNumPyArray(in_network, "oVC_PT") ihydsp2_a = arcpy.da.FeatureClassToNumPyArray(in_network, "iHyd_SP2") ihydsplow_a = arcpy.da.FeatureClassToNumPyArray( in_network, "iHyd_SPLow") igeoslope_a = arcpy.da.FeatureClassToNumPyArray( in_network, "iGeo_Slope") ovcex_array = np.asarray(ovcex_a, np.float64) ihydsp2_array = np.asarray(ihydsp2_a, np.float64) ihydsplow_array = np.asarray(ihydsplow_a, np.float64) igeoslope_array = np.asarray(igeoslope_a, np.float64) del ovcex_a, ihydsp2_a, ihydsplow_a, igeoslope_a ovc = ctrl.Antecedent(np.arange(0, 45, 0.225), 'input1') sp2 = ctrl.Antecedent(np.arange(0, 10000, 1), 'input2') splow = ctrl.Antecedent(np.arange(0, 10000, 1), 'input3') slope = ctrl.Antecedent(np.arange(0, 1, 0.001), 'input4') density = ctrl.Consequent(np.arange(0, 45, 0.5), 'result') # membership functions ovc['none'] = fuzz.trimf(ovc.universe, [0, 0, 0]) ovc['rare'] = fuzz.trapmf(ovc.universe, [0, 0, 0.5, 1]) ovc['occasional'] = fuzz.trapmf(ovc.universe, [0.5, 1, 4, 5]) ovc['frequent'] = fuzz.trapmf(ovc.universe, [4, 5, 12, 20]) ovc['pervasive'] = fuzz.trapmf(ovc.universe, [12, 20, 45, 45]) sp2['persists'] = fuzz.trapmf(sp2.universe, [0, 0, 1000, 1200]) sp2['breach'] = fuzz.trimf(sp2.universe, [1000, 1200, 1600]) sp2['oblowout'] = fuzz.trimf(sp2.universe, [1200, 1600, 2400]) sp2['blowout'] = fuzz.trapmf(sp2.universe, [1600, 2400, 10000, 10000]) splow['can'] = fuzz.trapmf(splow.universe, [0, 0, 150, 175]) splow['probably'] = fuzz.trapmf(splow.universe, [150, 175, 180, 190]) splow['cannot'] = fuzz.trapmf(splow.universe, [180, 190, 10000, 10000]) slope['flat'] = fuzz.trapmf(slope.universe, [0, 0, 0.0002, 0.005]) slope['can'] = fuzz.trapmf(slope.universe, [0.0002, 0.005, 0.12, 0.15]) slope['probably'] = fuzz.trapmf(slope.universe, [0.12, 0.15, 0.17, 0.23]) slope['cannot'] = fuzz.trapmf(slope.universe, [0.17, 0.23, 1, 1]) density['none'] = fuzz.trimf(density.universe, [0, 0, 0.1]) density['rare'] = fuzz.trapmf(density.universe, [0, 0.1, 0.5, 1.5]) density['occasional'] = fuzz.trapmf(density.universe, [0.5, 1.5, 4, 8]) density['frequent'] = fuzz.trapmf(density.universe, [4, 8, 12, 25]) density['pervasive'] = fuzz.trapmf(density.universe, [12, 25, 45, 45]) # rules rule1 = ctrl.Rule(ovc['none'], density['none']) rule2 = ctrl.Rule(splow['cannot'], density['none']) rule3 = ctrl.Rule(slope['cannot'], density['none']) rule4 = ctrl.Rule(ovc['rare'] & sp2['persists'] & splow['can'], density['rare']) rule5 = ctrl.Rule(ovc['occasional'] & sp2['persists'] & splow['can'], density['occasional']) rule6 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['can'] & slope['can'], density['frequent']) rule7 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['can'] & slope['probably'], density['occasional']) rule8 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['flat'], density['pervasive']) rule9 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['can'], density['pervasive']) rule10 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['probably'], density['occasional']) rule11 = ctrl.Rule(ovc['rare'] & sp2['breach'] & splow['can'], density['rare']) rule12 = ctrl.Rule(ovc['occasional'] & sp2['breach'] & splow['can'], density['occasional']) rule13 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['can'], density['frequent']) rule14 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['probably'], density['occasional']) rule15 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['flat'], density['occasional']) rule16 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['can'], density['frequent']) rule17 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['probably'], density['occasional']) rule18 = ctrl.Rule(ovc['rare'] & sp2['oblowout'] & splow['can'], density['rare']) rule19 = ctrl.Rule(ovc['occasional'] & sp2['oblowout'] & splow['can'], density['occasional']) rule20 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['can'], density['frequent']) rule21 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['probably'], density['occasional']) rule22 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['flat'], density['occasional']) rule23 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['can'], density['frequent']) rule24 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['probably'], density['occasional']) rule25 = ctrl.Rule(ovc['rare'] & sp2['blowout'] & splow['can'], density['none']) rule26 = ctrl.Rule(ovc['occasional'] & sp2['blowout'] & splow['can'], density['rare']) rule27 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['can'], density['rare']) rule28 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['probably'], density['none']) rule29 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['flat'], density['rare']) rule30 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['can'], density['occasional']) rule31 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['probably'], density['rare']) rule32 = ctrl.Rule(ovc['rare'] & sp2['breach'] & splow['probably'], density['rare']) rule33 = ctrl.Rule( ovc['occasional'] & sp2['breach'] & splow['probably'], density['occasional']) rule34 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['can'], density['frequent']) rule35 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['probably'], density['occasional']) rule36 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['flat'], density['occasional']) rule37 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['can'], density['frequent']) rule38 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['probably'], density['occasional']) rule39 = ctrl.Rule(ovc['rare'] & sp2['oblowout'] & splow['probably'], density['rare']) rule40 = ctrl.Rule( ovc['occasional'] & sp2['oblowout'] & splow['probably'], density['occasional']) rule41 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['can'], density['occasional']) rule42 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['probably'], density['rare']) rule43 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['flat'], density['occasional']) rule44 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['can'], density['frequent']) rule45 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['probably'], density['occasional']) rule46 = ctrl.Rule(ovc['rare'] & sp2['blowout'] & splow['probably'], density['none']) rule47 = ctrl.Rule( ovc['occasional'] & sp2['blowout'] & splow['probably'], density['rare']) rule48 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['can'], density['rare']) rule49 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['probably'], density['none']) rule50 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['flat'], density['rare']) rule51 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['can'], density['occasional']) rule52 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['probably'], density['rare']) rule53 = ctrl.Rule(ovc['rare'] & sp2['persists'] & splow['probably'], density['rare']) rule54 = ctrl.Rule( ovc['occasional'] & sp2['persists'] & splow['probably'], density['rare']) rule55 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['flat'], density['occasional']) rule56 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['can'], density['frequent']) rule57 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['probably'], density['occasional']) rule58 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['flat'], density['frequent']) rule59 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['flat'], density['occasional']) rule60 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['flat'], density['occasional']) rule61 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['flat'], density['occasional']) rule62 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['flat'], density['rare']) rule63 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['flat'], density['rare']) rule64 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['probably'], density['frequent']) comb_ctrl = ctrl.ControlSystem([ rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28, rule29, rule30, rule31, rule32, rule33, rule34, rule35, rule36, rule37, rule38, rule39, rule40, rule41, rule42, rule43, rule44, rule45, rule46, rule47, rule48, rule49, rule50, rule51, rule52, rule53, rule54, rule55, rule56, rule57, rule58, rule59, rule60, rule61, rule62, rule63, rule64 ]) comb_fis = ctrl.ControlSystemSimulation(comb_ctrl) # defuzzify out = np.zeros(len(ovcex_array)) for i in range(len(out)): comb_fis.input['input1'] = ovcex_array[i] comb_fis.input['input2'] = ihydsp2_array[i] comb_fis.input['input3'] = ihydsplow_array[i] comb_fis.input['input4'] = igeoslope_array[i] comb_fis.compute() out[i] = comb_fis.output['result'] # save the output text file fid = np.arange(0, len(out), 1) columns = np.column_stack((fid, out)) out_table = os.path.dirname(in_network) + "/oCC_PT_Table.txt" np.savetxt(out_table, columns, delimiter=",", header="FID, oCC_PT", comments="") occ_table = scratch + "/occ_pt_table" arcpy.CopyRows_management(out_table, occ_table) arcpy.JoinField_management(in_network, "FID", occ_table, "FID", "oCC_PT") arcpy.Delete_management(out_table) del out, fid, columns, out_table, occ_table elif ex_type == "true": # check for oCC_EX field and delete if exists if "oCC_EX" in network_fields: arcpy.DeleteField_management(in_network, "oCC_EX") # check that inputs are within range of fis (slope already taken care of) cursor = arcpy.da.UpdateCursor(in_network, ["oVC_EX", "iHyd_SP2", "iHyd_SPLow"]) for row in cursor: if row[0] < 0: row[0] = 0 elif row[0] > 45: row[0] = 44 elif row[1] < 0: row[1] = 0.001 elif row[1] > 10000: row[1] = 10000 elif row[2] < 0: row[2] = 0.001 elif row[2] > 10000: row[2] = 10000 else: pass cursor.updateRow(row) del row del cursor # correct for occ_pt greater than ovc_pt cursor = arcpy.da.UpdateCursor(in_network, ["oCC_PT", "oVC_PT"]) for row in cursor: if row[0] > row[1]: row[1] = row[0] cursor.updateRow(row) del row del cursor # get arrays for fields of interest ovcex_a = arcpy.da.FeatureClassToNumPyArray(in_network, "oVC_EX") ihydsp2_a = arcpy.da.FeatureClassToNumPyArray(in_network, "iHyd_SP2") ihydsplow_a = arcpy.da.FeatureClassToNumPyArray( in_network, "iHyd_SPLow") igeoslope_a = arcpy.da.FeatureClassToNumPyArray( in_network, "iGeo_Slope") ovcex_array = np.asarray(ovcex_a, np.float64) ihydsp2_array = np.asarray(ihydsp2_a, np.float64) ihydsplow_array = np.asarray(ihydsplow_a, np.float64) igeoslope_array = np.asarray(igeoslope_a, np.float64) del ovcex_a, ihydsp2_a, ihydsplow_a, igeoslope_a ovc = ctrl.Antecedent(np.arange(0, 45, 0.225), 'input1') sp2 = ctrl.Antecedent(np.arange(0, 10000, 1), 'input2') splow = ctrl.Antecedent(np.arange(0, 10000, 1), 'input3') slope = ctrl.Antecedent(np.arange(0, 1, 0.001), 'input4') density = ctrl.Consequent(np.arange(0, 45, 0.5), 'result') # membership functions ovc['none'] = fuzz.trimf(ovc.universe, [0, 0, 0]) ovc['rare'] = fuzz.trapmf(ovc.universe, [0, 0, 0.5, 1]) ovc['occasional'] = fuzz.trapmf(ovc.universe, [0.5, 1, 4, 5]) ovc['frequent'] = fuzz.trapmf(ovc.universe, [4, 5, 12, 20]) ovc['pervasive'] = fuzz.trapmf(ovc.universe, [12, 20, 45, 45]) sp2['persists'] = fuzz.trapmf(sp2.universe, [0, 0, 1000, 1200]) sp2['breach'] = fuzz.trimf(sp2.universe, [1000, 1200, 1600]) sp2['oblowout'] = fuzz.trimf(sp2.universe, [1200, 1600, 2400]) sp2['blowout'] = fuzz.trapmf(sp2.universe, [1600, 2400, 10000, 10000]) splow['can'] = fuzz.trapmf(splow.universe, [0, 0, 150, 175]) splow['probably'] = fuzz.trapmf(splow.universe, [150, 175, 180, 190]) splow['cannot'] = fuzz.trapmf(splow.universe, [180, 190, 10000, 10000]) slope['flat'] = fuzz.trapmf(slope.universe, [0, 0, 0.0002, 0.005]) slope['can'] = fuzz.trapmf(slope.universe, [0.0002, 0.005, 0.12, 0.15]) slope['probably'] = fuzz.trapmf(slope.universe, [0.12, 0.15, 0.17, 0.23]) slope['cannot'] = fuzz.trapmf(slope.universe, [0.17, 0.23, 1, 1]) density['none'] = fuzz.trimf(density.universe, [0, 0, 0.1]) density['rare'] = fuzz.trapmf(density.universe, [0, 0.1, 0.5, 1]) density['occasional'] = fuzz.trapmf(density.universe, [0.5, 1, 4, 5]) density['frequent'] = fuzz.trapmf(density.universe, [4, 5, 12, 20]) density['pervasive'] = fuzz.trapmf(density.universe, [12, 20, 45, 45]) # rules rule1 = ctrl.Rule(ovc['none'], density['none']) rule2 = ctrl.Rule(splow['cannot'], density['none']) rule3 = ctrl.Rule(slope['cannot'], density['none']) rule4 = ctrl.Rule(ovc['rare'] & sp2['persists'] & splow['can'], density['rare']) rule5 = ctrl.Rule(ovc['occasional'] & sp2['persists'] & splow['can'], density['occasional']) rule6 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['can'] & slope['can'], density['frequent']) rule7 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['can'] & slope['probably'], density['occasional']) rule8 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['flat'], density['pervasive']) rule9 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['can'], density['pervasive']) rule10 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['can'] & slope['probably'], density['occasional']) rule11 = ctrl.Rule(ovc['rare'] & sp2['breach'] & splow['can'], density['rare']) rule12 = ctrl.Rule(ovc['occasional'] & sp2['breach'] & splow['can'], density['occasional']) rule13 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['can'], density['frequent']) rule14 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['probably'], density['occasional']) rule15 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['flat'], density['occasional']) rule16 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['can'], density['frequent']) rule17 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['can'] & slope['probably'], density['occasional']) rule18 = ctrl.Rule(ovc['rare'] & sp2['oblowout'] & splow['can'], density['rare']) rule19 = ctrl.Rule(ovc['occasional'] & sp2['oblowout'] & splow['can'], density['occasional']) rule20 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['can'], density['frequent']) rule21 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['probably'], density['occasional']) rule22 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['flat'], density['occasional']) rule23 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['can'], density['frequent']) rule24 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['can'] & slope['probably'], density['occasional']) rule25 = ctrl.Rule(ovc['rare'] & sp2['blowout'] & splow['can'], density['none']) rule26 = ctrl.Rule(ovc['occasional'] & sp2['blowout'] & splow['can'], density['rare']) rule27 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['can'], density['rare']) rule28 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['probably'], density['none']) rule29 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['flat'], density['rare']) rule30 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['can'], density['occasional']) rule31 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['can'] & slope['probably'], density['rare']) rule32 = ctrl.Rule(ovc['rare'] & sp2['breach'] & splow['probably'], density['rare']) rule33 = ctrl.Rule( ovc['occasional'] & sp2['breach'] & splow['probably'], density['occasional']) rule34 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['can'], density['frequent']) rule35 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['probably'], density['occasional']) rule36 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['flat'], density['occasional']) rule37 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['can'], density['frequent']) rule38 = ctrl.Rule( ovc['pervasive'] & sp2['breach'] & splow['probably'] & slope['probably'], density['occasional']) rule39 = ctrl.Rule(ovc['rare'] & sp2['oblowout'] & splow['probably'], density['rare']) rule40 = ctrl.Rule( ovc['occasional'] & sp2['oblowout'] & splow['probably'], density['occasional']) rule41 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['can'], density['occasional']) rule42 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['probably'], density['rare']) rule43 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['flat'], density['occasional']) rule44 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['can'], density['frequent']) rule45 = ctrl.Rule( ovc['pervasive'] & sp2['oblowout'] & splow['probably'] & slope['probably'], density['occasional']) rule46 = ctrl.Rule(ovc['rare'] & sp2['blowout'] & splow['probably'], density['none']) rule47 = ctrl.Rule( ovc['occasional'] & sp2['blowout'] & splow['probably'], density['rare']) rule48 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['can'], density['rare']) rule49 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['probably'], density['none']) rule50 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['flat'], density['rare']) rule51 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['can'], density['occasional']) rule52 = ctrl.Rule( ovc['pervasive'] & sp2['blowout'] & splow['probably'] & slope['probably'], density['rare']) rule53 = ctrl.Rule(ovc['rare'] & sp2['persists'] & splow['probably'], density['rare']) rule54 = ctrl.Rule( ovc['occasional'] & sp2['persists'] & splow['probably'], density['rare']) rule55 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['flat'], density['occasional']) rule56 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['can'], density['frequent']) rule57 = ctrl.Rule( ovc['frequent'] & sp2['persists'] & splow['probably'] & slope['probably'], density['occasional']) rule58 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['can'] & slope['flat'], density['frequent']) rule59 = ctrl.Rule( ovc['frequent'] & sp2['breach'] & splow['probably'] & slope['flat'], density['occasional']) rule60 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['can'] & slope['flat'], density['occasional']) rule61 = ctrl.Rule( ovc['frequent'] & sp2['oblowout'] & splow['probably'] & slope['flat'], density['occasional']) rule62 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['can'] & slope['flat'], density['rare']) rule63 = ctrl.Rule( ovc['frequent'] & sp2['blowout'] & splow['probably'] & slope['flat'], density['rare']) rule64 = ctrl.Rule( ovc['pervasive'] & sp2['persists'] & splow['probably'], density['frequent']) comb_ctrl = ctrl.ControlSystem([ rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28, rule29, rule30, rule31, rule32, rule33, rule34, rule35, rule36, rule37, rule38, rule39, rule40, rule41, rule42, rule43, rule44, rule45, rule46, rule47, rule48, rule49, rule50, rule51, rule52, rule53, rule54, rule55, rule56, rule57, rule58, rule59, rule60, rule61, rule62, rule63, rule64 ]) comb_fis = ctrl.ControlSystemSimulation(comb_ctrl) # defuzzify out = np.zeros(len(ovcex_array)) for i in range(len(out)): comb_fis.input['input1'] = ovcex_array[i] comb_fis.input['input2'] = ihydsp2_array[i] comb_fis.input['input3'] = ihydsplow_array[i] comb_fis.input['input4'] = igeoslope_array[i] comb_fis.compute() out[i] = comb_fis.output['result'] # save the output text file fid = np.arange(0, len(out), 1) columns = np.column_stack((fid, out)) out_table = os.path.dirname(in_network) + "/oCC_EX_Table.txt" np.savetxt(out_table, columns, delimiter=",", header="FID, oCC_EX", comments="") occ_table = scratch + "/occ_ex_table" arcpy.CopyRows_management(out_table, occ_table) arcpy.JoinField_management(in_network, "FID", occ_table, "FID", "oCC_EX") arcpy.Delete_management(out_table) del out, fid, columns, out_table, occ_table cursor = arcpy.da.UpdateCursor(in_network, [ "oVC_EX", "iHyd_SPLow", "iGeo_Slope", "iGeo_DA", "oCC_EX", "oCC_PT" ]) for row in cursor: if row[0] == 0: row[4] = 0 elif row[1] > 190: row[4] = 0 row[5] = 0 elif row[2] >= 0.23: row[4] = 0 row[5] = 0 elif row[3] >= float(max_DA_thresh): row[4] = 0 row[5] = 0 elif row[4] > row[0]: row[4] = row[0] else: pass cursor.updateRow(row) del row del cursor out_network = os.path.dirname(in_network) + "/" + out_name + ".shp" arcpy.CopyFeatures_management(in_network, out_network) addxmloutput(projPath, in_network, out_network) else: raise Exception("either historic or existing must be selected") return