def read_rules(): #file=open("rules_new.txt","r") file=open("rules.txt","r") rules=file.readlines() file.close() rules_objects=[] for each in rules: each=each.replace("\n","") each=each.replace(" ","") if (each != ""): rule_object=Rule(each) rules_objects.append(rule_object) choice = int(input("Enter Part No.:")) if choice == 1: input_rule=input("Enter Term: ") input_rule_object=Rule(input_rule) result_rule=evaluate(rules_objects,input_rule_object) print ("Evaluated Solution:",result_rule.string) elif choice == 2: input_rule=input("Enter Equation to be solved: ") input_rule_object=Rule(input_rule) part_two_type_check(input_rule_object) if input_rule_object.function_type=='->': part_two_main(rules_objects,input_rule_object) else: print("Wrong Equation. Exiting.") else : print("Wrong Choice. Exiting.")
def pjcintersection(rls1, w1, rls2, w2, ds, wsc, cac, F, fd): mrls = [] for i in range(len(rls1)): for j in range(len(rls2)): newantec = [] noint = 0 for f in F: ai = rls1[i].searchantec(f) aj = rls2[j].searchantec(f) newc, outcome = getintersection(ai, aj, f, fd[f]) if outcome == 0: noint = 1 newantec.extend(newc) newrl = None wij = getweight(w1[i], w2[j], wsc) cij = assignclass(w1[i], w2[j], rls1[i].cons, rls2[j].cons, cac) if noint == 1: newrl = Rule([], cij) noint = 0 else: newrl = Rule(newantec, cij) entry = TableEntryPJC(rls1[i], w1[i], rls2[j], w2[j], newrl, wij) mrls.append(entry) return mrls self
def insert_rule(self, row): """This function inserts new rule into rule map and if a rule already exists then updates the existing rule""" IP = Range(row[3]) if '-' in row[2]: # Port is ranged port_range = row[2].split("-") start = int(port_range[0]) end = int(port_range[1]) for port in range(start, end + 1): if int(port) in self.rule_map: existing_rule = self.rule_map[int(port)] existing_rule.extend_permission(Rule(row[0], row[1], IP)) self.rule_map[int(port)] = Rule(row[0], row[1], IP) else: # Port is fixed port = row[2] if int(port) in self.rule_map: existing_rule = self.rule_map[int(port)] existing_rule.extend_permission(Rule(row[0], row[1], IP)) self.rule_map[int(port)] = Rule(row[0], row[1], IP)
def getdtrules(dt): ID_IDX = 0 IF1_IDX = 3 ID1_IDX = 6 IF2_IDX = 8 ID2_IDX = 11 CLASS_IDX = 2 LAB_IDX = 4 class_str = "class" delim = " " stdc = {} for i in dt: lv1tkns = i.strip('\n').split(" ") id = 0 try: id = int(lv1tkns[ID_IDX]) except ValueError: continue if lv1tkns[CLASS_IDX] == class_str: stdc[id] = lv1tkns[LAB_IDX] else: stdc[id] = lv1tkns[IF1_IDX] + delim + lv1tkns[ID1_IDX] + delim + lv1tkns[IF2_IDX] + delim + lv1tkns[ID2_IDX] vislst = [] rules = [] ids = list(stdc.keys()) ids.sort() exp1, exp2 = getexprs(stdc[ids[0]]) vislst.extend([[Rule([exp1[0]], ""), exp1[1]], [Rule([exp2[0]], ""), exp2[1]]]) curr = None while len(vislst) > 0: if curr is None: curr = vislst[0] vislst.remove(curr) exp1, exp2 = getexprs(stdc[curr[1]]) if exp1 is None: curr[0].cons = stdc[curr[1]] rules.append(curr[0]) curr = None else: newant = list(curr[0].antec) newant.append(exp2[0]) newrl = Rule(newant, "") curr[1] = exp1[1] curr[0].antec.append(exp1[0]) vislst.append( [newrl, exp2[1]]) return rules
def create_rules(): rules = {} rules[0] = Rule('center', 41, 1.1, 3, 8, 'min', ["Obiekt ", " znajduje się na środku pola", ". "], ["Object ", " is on the center of field", ". "]) rules[1] = Rule('top left corner', 42, 1, 1.1, 6, 'min', ["Obiekt ", " znajduje się w lewym-górnym narożniku pola", ". "], ["Object ", " is on the left-top corner of field", ". "]) rules[2] = Rule('top right corner', 43, 1.1, 5, 6, 'min', ["Obiekt ", " znajduje się w prawym-górnym narożniku pola", ". "], ["Object ", " is on the left-top corner of field", ". "]) rules[3] = Rule('bottom right corner', 44, 1.1, 5, 10, 'min', ["Obiekt ", " w prawym-dolnym narożniku pola", ". "], ["Object ", " is on the right-bottom corner of field", ". "]) rules[4] = Rule('bottom left corner', 45, 1, 1, 10, 'min', ["Obiekt ", " znajduje się w lewym-dolnym narożniku pola", ". "], ["Object ", " is on the left-bottom corner of field", ". "]) rules[5] = Rule('top left part', 46, 1, 2, 7, 'min', ["Obiekt ", " znajduje się w lewej-górnej części pola", ". "], ["Object ", " is on the left-top part of field", ". "]) rules[6] = Rule('top right part', 47, 1, 4, 7, 'min', ["Obiekt ", " znajduje się w prawej-górnej części pola", ". "], ["Object ", " is on the right-top part of field", ". "]) rules[7] = Rule('bottom right part', 48, 1, 4, 9, 'min', ["Obiekt ", " znajduje się w prawej-dolnej części pola", ". "], ["Object ", " is on the right-bottom part of field", ". "]) rules[8] = Rule('bottom left part', 49, 1, 2, 9, 'min', ["Obiekt ", " znajduje się w lewej-dolnej części pola", ". "], ["Object ", " is on the left-bottom part of field", ". "]) return rules
def create_three_step_left_org(self): """ creates rules like: a L b AND b L c AND c L d -> a L d :return: """ this_rules = [] for direction in self.left_code: for obj1 in self.obj_code: for obj2 in self.obj_code: for obj3 in self.obj_code: for obj4 in self.obj_code: if obj1 != obj2 and obj1 != obj3 and obj1 != obj4 and obj2 != obj3 and obj2 != obj4 and \ obj3 != obj4: rule_str = "" rule_str += self.impl_code[0] # -> rule_str += self.con_code[0] # AND rule_str += self.left_code[3] # lefts rule_str += obj1 rule_str += obj2 rule_str += self.con_code[0] # AND rule_str += self.left_code[3] # lefts rule_str += obj3 rule_str += obj4 rule_str += self.left_code[3] # lefts rule_str += obj2 rule_str += obj3 rule_str += direction rule_str += obj1 rule_str += obj3 this_rules.append(Rule(rule_str, False)) return this_rules
def generate_negative_rules(self, train, confident_value_pass, zone_confident_pass): class_value_arr = self.get_class_value_array(train) self.prepare_data_rows(train) for i in range(0, len(self.rule_base_array)): rule_negative = Rule(self.data_base) rule_negative.antecedent = self.rule_base_array[i].antecedent positive_rule_class_value = self.rule_base_array[i].get_class() print("the positive rule class value is " + str(positive_rule_class_value) + " ,the i is :" + str(i)) # rule_negative.setClass(positive_rule_class_value) for j in range(0, len(class_value_arr)): class_type = int(class_value_arr[j]) if positive_rule_class_value != class_type: # need to get another class value for negative rule rule_negative.setClass(class_type) # change the class type in the rule rule_negative.calculate_confident_support(self.data_row_array) print("Negative rule's confident value is :" + str(rule_negative.confident_value)) if rule_negative.confident_value > confident_value_pass and rule_negative.zone_confident > zone_confident_pass: rule_negative.weight = rule_negative.confident_value if not (self.duplicated_negative_rule(rule_negative)): for k in range(0, len(rule_negative.antecedent)): print("antecedent L_ " + str(rule_negative.antecedent[j])) # print("Negative rule's class value " + str(rule_negative.get_class())) # print(" Negative rule's weight, confident_vale " + str(rule_negative.weight)) # print(" Negative rule's zone confident value " + str(rule_negative.zone_confident)) # print("Negative rule's positive_rule_class_value" + str(positive_rule_class_value)) # print("Negative rule's class_type" + str(class_type)) self.negative_rule_base_array.append(rule_negative)
def createRandomRule(agentPool, ruleType): conditions = [] # Conditions for a rule # RS rule if ruleType == 0: # Set conditions of rules as a random amount of random predicates for i in range(randint(1, maxRulePredicates)): newCond = PredicateSet.getRandomPredicate() if checkValidCond(newCond, conditions): conditions.append(newCond) # RSint rule elif ruleType == 1: # Set conditions of rules as a random amount of random predicates for i in range(randint(1, maxRulePredicates)): newCond = agentPool.getRandomRSintPredicate() if checkValidCond(newCond, conditions): conditions.append(newCond) # Get index of possible action. SUMO changes phases on indexes action = randrange( 0, len(agentPool.getActionSet()) ) # Set rule action to a random action from ActionSet pertaining to Agent Pool being serviced #print("The action set is:", agentPool.getActionSet()) rule = Rule(ruleType, conditions, action, agentPool) return rule
def create_basic_rules_front_back(self): """ creates rules like: a F b <-> b B a :return: """ this_rules = [] for direction in range(0, 4): for each1 in self.objects: for each2 in self.objects: if each1 != each2: # start making front/back rules parent = Node("<->") lchild = Node(self.front[direction], None, None, parent) rchild = Node(self.back[direction], None, None, parent) rrchild = Node(each1, None, None, rchild) rlchild = Node(each2, None, None, rchild) rchild.right = rrchild rchild.left = rlchild lrchild = Node(each2, None, None, lchild) llchild = Node(each1, None, None, lchild) lchild.left = llchild lchild.right = lrchild parent.left = lchild parent.right = rchild rule = Rule(parent) this_rules.append(rule) return this_rules
def goalToRule(path): with open(path) as f: jsonFile = json.load(f) lhs = Graph("lhs") if "objects" in jsonFile["graph"]: for objects in jsonFile["graph"]["objects"]: lhs.addVertex(objects["id"], objects["type"]) if "relations" in jsonFile["graph"]: for relations in jsonFile["graph"]["relations"]: lhs.addEdge(relations["source"], relations["target"], relations["type"]) rhs = Graph("rhs") nacs = [] cnt = 0 if "nacs" in jsonFile: for nac in jsonFile["nacs"]: str = "nac {}".format(cnt) cnt += 1 g = Graph(str) if "objects" in nac: for objects in nac["objects"]: g.addVertex(objects["id"], objects["type"]) if "relations" in nac: for relations in nac["relations"]: g.addEdge(relations["source"], relations["target"], relations["type"]) nacs.append(g) return Rule("goal", lhs, rhs, nacs)
def substitute(lhs,rhs,term): global substitutions substitutions.clear() if match_terms(lhs,term): term = Rule(rhs.string) term = substitute_helper(term) return True,term if term.object_type=='bfun': status1,result1 = substitute(lhs,rhs,term.parameter_1) if (status1): term.parameter_1 = result1 status2,result2 = substitute(lhs,rhs,term.parameter_2) if (status2): term.parameter_2 = result2 if (status1 or status2): term.string=term.function_type + "(" + term.parameter_1.string + "," + term.parameter_2.string +")" return True,term if term.object_type=='ufun': status,result=substitute(lhs,rhs,term.parameter_1) if (status == True): term.parameter_1=result term.string=term.function_type+"("+result.string+")" return True,term return False,term
def detect_relationship_rules(self, relationship, rule_count_limit=1): ''' @return a list of Rule objects, no longer than rule_count_limit ''' extract_objects = lambda figure: FigureObjectSet(figure.objects) figure_sequence = map(extract_objects, relationship) return [Rule(figure_sequence)]
def searchForBestAntecedent(self,example,clas): ruleInstance=Rule( ) ruleInstance.setTwoParameters(self.n_variables, self.compatibilityType) print("In searchForBestAntecedent ,self.n_variables is :" + str(self.n_variables)) ruleInstance.setClass(clas) print("In searchForBestAntecedent ,self.n_labels is :" + str(self.n_labels)) for i in range( 0,self.n_variables): max = 0.0 etq = -1 per= None for j in range( 0, self.n_labels) : print("Inside the second loop of searchForBestAntecedent......") per = self.dataBase.membershipFunction(i, j, example[i]) if (per > max) : max = per etq = j if (max == 0.0) : print("There was an Error while searching for the antecedent of the rule") print("Example: ") for j in range(0,self.n_variables): print(example[j] + "\t") print("Variable " + str(i)) exit(1) ruleInstance.antecedent[i] = self.dataBase.clone(i, etq) return ruleInstance
def newObject(self,e=''): """ adds into the current ruleChain (starting a new Rule) """ self.ruleChains[self.rcpos].append(Rule(e)) self.ruleChains[self.rcpos][-1].minZoom=float(self.scalepair[0]) self.ruleChains[self.rcpos][-1].maxZoom=float(self.scalepair[1])
def __init__(self, identifier, actionSet, minIndividualRunsPerGen, trafficLightsAssigned): self.id = identifier # AgentPool name self.actionSet = actionSet # A list of action names that can be applied by assigned TL's of the pool self.addDoNothingAction() # Add "do nothing" action to action set self.trafficLightsAssigned = [ ] # List of traffic lights using Agent Pool self.setTrafficLightsAssigned(trafficLightsAssigned) self.individuals = [] self.userDefinedRuleSet = [ Rule(-1, ["emergencyVehicleApproachingVertical"], -1, self), Rule(-1, ["emergencyVehicleApproachingHorizontal"], -1, self), Rule(-1, ["maxGreenPhaseTimeReached"], -1, self), Rule(-1, ["maxYellowPhaseTimeReached"], -1, self) ] self.minIndividualRunsPerGen = minIndividualRunsPerGen
def predict_test(): earley = Earley('a') earley.rules = [Rule('S#', 'S'), Rule('S', 'a')] earley.situations_dict[0] = set() earley.situations_dict[0].add(Situation('S#', 'S', 0, 0)) earley.predict(0) is_added = False to_add = Situation('S', 'a', 0, 0) for sit in earley.situations_dict[0]: if (sit.input == to_add.input and sit.output == to_add.output and sit.point == to_add.point and sit.ind == to_add.ind): is_added = True assert is_added is True print('Predict test passed\n')
def write_in_rule(rules_string_arr): rule = Rule() scope = 0 skip_idx = 0 # print('ARR: ', rules_string_arr) if len(rules_string_arr[-1]) < 1 or rules_string_arr[-1][0] not in letters: print('Expression must and with letter!') return None for i in rules_string_arr: if skip_idx > 0: skip_idx -= 1 continue if i in letters: rule.facts.append(i) elif i in operations: rule.operations.append(i) else: tmp_rule, skip_idx = new_group_str(rules_string_arr) if tmp_rule is None or skip_idx is None: return None scope += 1 if tmp_rule is None: return None rule.facts.append(tmp_rule) return rule
def __init__(self, refresh, vsrv_num, rule_num, vsrv_nam): CTK.Container.__init__(self) rule = Rule('vserver!%s!rule!%s!match' % (vsrv_num, rule_num)) rule_nam = rule.GetName() self += CTK.RawHTML('<h2><a href="/vserver/%s">%s</a> → %s</h2>' % (vsrv_num, CTK.escape_html(vsrv_nam), rule_nam))
def create_three_step_right_org(self): this_rules = [] for direction in self.right_code: for obj1 in self.obj_code: for obj2 in self.obj_code: for obj3 in self.obj_code: for obj4 in self.obj_code: if obj1 != obj2 and obj1 != obj3 and obj1 != obj4 and obj2 != obj3 and obj2 != obj4 and \ obj3 != obj4: rule_str = "" rule_str += self.impl_code[0] # -> rule_str += self.con_code[0] # AND rule_str += self.right_code[3] # lefts rule_str += obj1 rule_str += obj2 rule_str += self.con_code[0] # AND rule_str += self.right_code[3] # lefts rule_str += obj3 rule_str += obj4 rule_str += self.right_code[3] # lefts rule_str += obj2 rule_str += obj3 rule_str += direction rule_str += obj1 rule_str += obj3 this_rules.append(Rule(rule_str, False)) return this_rules
def create_one_sided_rules_left(self): """ creates rules like: a L b AND b L c -> a L c :return: """ this_rules = [] for direction in self.left_code: for obj1 in self.obj_code: for obj2 in self.obj_code: for obj3 in self.obj_code: if obj1 != obj2 and obj2 != obj3 and obj1 != obj3: rule_str = "" rule_str += self.impl_code[0] # -> rule_str += self.con_code[0] # AND rule_str += self.left_code[3] # lefts rule_str += obj1 rule_str += obj2 rule_str += self.left_code[3] # lefts rule_str += obj2 rule_str += obj3 rule_str += direction rule_str += obj1 rule_str += obj3 this_rules.append(Rule(rule_str, False)) return this_rules
def __specialize_complexes(self, stars): new_star = [] if stars is self.selectors: for selector in self.selectors: rule = Rule.Rule() rule.add_condition(selector[0], selector[1]) new_star.append(rule) return new_star else: for selector in self.selectors: for star in stars: star_copy = Rule.Rule() star_copy.add_existing_conditions(star.conditions) star_copy.add_condition(selector[0], selector[1]) if star_copy.check_if_conditions_unique(): new_star.append(star_copy) return new_star
def arr_to_rule(arr): rule = Rule() for i in arr: if i in letters: rule.facts.append(i) else: rule.operations.append(i) return rule
def newObject(self, e=''): """ adds into the current ruleChain (starting a new Rule) """ rule = Rule(e) rule.minZoom = float(self.scalepair[0]) rule.maxZoom = float(self.scalepair[1]) self.ruleChains.append(rule)
def load_rules(self, rules): print('Loading rules...') for i in rules: rule = Rule(i) self.knowledge_base.append(rule) # associa uma um valor (A) às regras nas quais ele # aparece no lado direito de uma regra self.values_table[rule.right].add_rule(rule)
def rule(self, p): # Just do LOD=1 for now newRule = Rule(p.left, p.right, 1) if newRule.label in self.ruleFromLabel: self.ruleFromLabel[newRule.label].append(newRule) else: self.ruleFromLabel[newRule.label] = [newRule] return newRule
def test_misshapen_indices_3(): indices = [ ((1, -2), (10, 20)), ((3, 4, 5), (-30, 40)), ((6, -7, 8, 9), (60, 70)), ] with pytest.raises(ValueError): Rule(indices, GAME_OF_LIFE_RULESET)
def extractRules(chF, enF, subaF, waF): chSentList = [line.split() for line in codecs.open(chF, 'r', 'utf-8').readlines()] enSentList = [line.split() for line in codecs.open(enF, 'r', 'utf-8').readlines()] subaList = [[item.split('-') for item in line.split()] for line in codecs.open(subaF, 'r', 'utf-8').readlines()] subaList = [[[int(d) for d in item] for item in line] for line in subaList] waList = [line for line in codecs.open(waF, 'r', 'utf-8').readlines()] assert len(chSentList) == len(enSentList) == len(subaList) == len(waList), \ "len(chSentList) == %d, len(enSentList) == %d, len(subaList) == %d, len(waList) == %d" % (len(chSentList), len(enSentList), len(subaList), len(waList)) ruleList = [] for i in xrange(len(subaList)): #print i, # rules with non-terminal Xs subaDic = _level_(subaList[i]) waMatrix = oneline2waMatrix(waList[i], len(chSentList[i]), len(enSentList[i])) for bigSquare in subaDic: rule = _extract_(bigSquare, subaDic[bigSquare], chSentList[i], enSentList[i], waMatrix) if rule: ruleList.append(rule) # rules without non-terminal Xs for square in subaList[i]: lhsSrc, lhsTgt = 'X', 'X' rhsSrc = range(square[0], square[1]) rhsTgt = range(square[2], square[3]) align = [] if _isLegalRule_(rhsSrc, rhsTgt, chSentList[i], enSentList[i], "complete"): rule = Rule(lhsSrc, lhsTgt, rhsSrc, rhsTgt, align, waMatrix, chSentList[i], enSentList[i], square) ruleList.append(rule) # rules that are word alignments (i.e. word pairs) but not corresponding subtree alignments #pdb.set_trace() lhsSrc, lhsTgt = 'X', 'X' rhsSrc, rhsTgt, align = [], [], [] # here align is for the alignment of Xs, not word alignment, so keep empty for item in waList[i].split(): k = int(item.split('-')[0]) j = int(item.split('-')[1]) if waMatrix[k][j]: if sum(waMatrix[k]) == 1 and sum([row[j] for row in waMatrix]) == 1: rhsSrc, rhsTgt = [k], [j] if _isLegalRule_(rhsSrc, rhsTgt, chSentList[i], enSentList[i], "complete"): rule = Rule(lhsSrc, lhsTgt, rhsSrc, rhsTgt, align, waMatrix, chSentList[i], enSentList[i], (k, k + 1, j, j + 1)) ruleList.append(rule) return ruleList
def __init__(self, identifier, actionSet, minIndividualRunsPerGen): self.id = identifier # AgentPool name self.actionSet = actionSet # A list of action names that can be applied by assigned TL's of the pool self.addDoNothingAction() # Add "do nothing" action to action set self.trafficLightsAssigned = [ ] # List of traffic lights using Agent Pool self.individuals = [] self.userDefinedRuleSet = [ Rule(-1, ["emergencyVehicleApproachingVertical"], -1, self), Rule(-1, ["emergencyVehicleApproachingHorizontal"], -1, self), Rule(-1, ["maxGreenPhaseTimeReached"], -1, self), Rule(-1, ["maxYellowPhaseTimeReached"], -1, self) ] self.coopPredicates = self.initCoopPredicates( ) # Store Observations of communicated intentions here since they are agent specific self.initIndividuals( ) # Populate Agent Pool's own rule set with random rules self.minIndividualRunsPerGen = minIndividualRunsPerGen
def parseAndRecipe(recipe): global AllNTs recipe = recipe.strip()[1:-1] recipeDelimiters = getDelimiters(recipe) # print recipeDelimiters # for x in range(len(recipeDelimiters)): # print recipe[recipeDelimiters[x]] alphaLetters = [] fullOrder = False i = 0 del1 = 0 del2 = recipeDelimiters[0] + 2 if len(recipeDelimiters) >= 2 else len( recipe) while True: i += 1 currentPiece = recipe[del1:del2].strip() #print "current:", currentPiece if currentPiece == "": del1 = del2 if i < len(recipeDelimiters): del2 = recipeDelimiters[i] else: break continue elif currentPiece[1] == "(": order = parseOrder(currentPiece[1:-1]) elif currentPiece[0] == "N": order = [] resultOfOr = parseOrRecipe(currentPiece[4:]) alphaLetters.append(NT(resultOfOr[0])) #print "here:", currentPiece[:2] elif currentPiece[0] == "O" or currentPiece[1] == "O": #OR #(Place in sentence, (NT, rules)) resultOfOr = parseOrRecipe(currentPiece) alphaLetters.append(NT(resultOfOr[0])) elif currentPiece[0] == "F": fullOrder = True resultOfOr = parseOrRecipe(currentPiece[8:].strip()) alphaLetters.append(NT(resultOfOr[0])) del1 = del2 if i == len(recipeDelimiters) + 1: break elif i == len(recipeDelimiters): del2 = len(recipe) else: del2 = recipeDelimiters[i] + 2 if fullOrder: order = [] for num in range(len(alphaLetters) - 1): order.append((num, num + 1)) letter = generateNextLetter() AllNTs.append(letter) newRule = Rule(NT(letter), alphaLetters, order) addRule(newRule) return (letter, newRule)
def AddRule(self, inputVariables, linguisticInputVariables, outputVariables, linguisticOutputVariables): membershipFunctionsDict = dict() for inputVariable, linguisticVariable in zip(inputVariables, linguisticInputVariables): membershipFunctionsDict[inputVariable] = self.membershipFunctions[linguisticVariable] for outputVariable, linguisticVariable in zip(outputVariables, linguisticOutputVariables): membershipFunctionsDict[outputVariable] = self.membershipFunctions[linguisticVariable] self.rules.append(Rule(inputVariables, outputVariable, membershipFunctionsDict))