def test_text(self): rule = r.Rule() self.assertEqual(str(rule), '3/23', 'Default rule string incorrect.') rule = r.Rule('12/23') self.assertEqual(str(rule), '12/23') rule = r.Rule('9876543210/') self.assertEqual(str(rule), '0123456789/') rule = r.Rule('/11') self.assertEqual(str(rule), '/1') rule = r.Rule('') self.assertEqual(str(rule), '/')
def testRule_Weight(self): dummy_rule = rule.Rule('dummy', 0.5) # Mocking the _CalculateAntecedent function: dummy_rule._CalculateAntecedent = lambda x: x + 2.0 dummy_rule.Evaluate(4.0) self.assertAlmostEquals(3.0, dummy_rule.output)
def LoadConfig(self, filename): """Load fuzzy configuration.""" sys = fuzzy_config.ReadConfig(filename) for p_input in sys.input: name = p_input.name input_ = sys_input.Input(name) self.inputs[name] = input_ self.elements_mapping[name] = input_ for p_set in sys.set: name = p_set.name fset = membership.CreateSet(p_set.type, name, p_set.param) self.sets[name] = fset self.elements_mapping[name] = fset for p_output in sys.output: name = p_output.name self.outputs[name] = sys_output.Output(name) for p_consequent in sys.consequent: name = p_consequent.name consequent_ = consequent.Consequent(self.sets[p_consequent.set]) self.consequents[name] = consequent_ self.outputs[p_consequent.output].consequents.append(consequent_) for p_rule in sys.rule: name = p_rule.name rule_ = rule.Rule(p_rule.antecedent) self.rules[name] = rule_ # mapping the consequent associated to the rule self.consequents[p_rule.consequent].rules.append(rule_)
def seed(self, input, grammars, models, weights): fwords = [sym.fromstring(f) for f in input.fwords] self.models = models self.weights = weights # Seed the dotchart. This will give the extracted rules self.grammars = [(g, DotChart(self, fwords)) for g in grammars if isinstance(g, Grammar)] for (g,dotchart) in self.grammars: for i in xrange(self.n): if g.filterspan(i,i,self.n): dotchart.add(g.root,i,i,()) self.dot_added += 1 for g in grammars: if isinstance(g, NewGrammar): g.input(input) for i in xrange(self.n): for j in xrange(i+1,self.n+1): for (r,) in g.get_rules(i,j): estimate_rule(r, models, weights) self.add_axiom(i, j, r) # Last resort for unknown French word: pass it through for i in xrange(0, len(fwords)): for x in self.default_nonterminals: r = rule.Rule(x, rule.Phrase(fwords[i:i+1]), rule.Phrase(fwords[i:i+1]), scores=svector.Vector('unknown', 1.)) estimate_rule(r, models, weights) self.add_axiom(i, i+1, r)
def parse_from_dict(rule_dict) -> rule.Rule: return rule.Rule( id="immediate", name="One shot Rule", description="This is a rule created using the VM APIs", conditions=rule_dict, )
def TimeTest(): def dieFunction(state): return 0 def stayFunction(state): return state def birthFunction(state): return 1 TestRule = rule.Rule(True, 3, 2, [1, 1], True, dieFunction) TestRule.addRule([2], stayFunction) TestRule.addRule([3], birthFunction) TestMap = map.Map([50, 30], [False, False], 1) TestMap[3][1] = 1 TestMap[4][2] = 1 TestMap[5][2] = 1 TestMap[3][3] = 1 TestMap[4][3] = 1 TestMap.print2D() TestTime = Time(TestMap, TestRule) while True: TestTime.update({'draw': True})
def seed(self, flattice, grammars, models, weights): self.models = models self.weights = weights # Seed the dotchart. This will give the extracted rules self.grammars = [(g, DotChart(self, flattice)) for g in grammars if isinstance(g, Grammar)] for (g, dotchart) in self.grammars: for i in xrange(self.flattice.n - 1): if g.filterspan(self.flattice, i, i): dotchart.add(g.root, i, i, ()) self.dot_added += 1 for g in grammars: if isinstance(g, NewGrammar): g.input(flattice) for i in xrange(self.flattice.n - 1): for j in xrange(i + 1, self.flattice.n): for (r, ) in g.get_rules(i, j): estimate_rule(r, models, weights) self.add_axiom(i, j, r) # Last resort for unknown French word: pass it through for edge in flattice.edges: for x in self.default_nonterminals: r = rule.Rule(x, [edge.w], [edge.w], scores=svector.Vector('unknown', 1.)) estimate_rule(r, models, weights) self.add_axiom(edge.i, edge.j, r)
def GliderTest(): def dieFunction(state): return 0 def stayFunction(state): return state def birthFunction(state): return 1 TestRule = rule.Rule(True, 3, 2, [1, 1], False, dieFunction) TestRule.addRule([2], stayFunction) TestRule.addRule([3], birthFunction) TestRule = fileSystem.loadRule(fileSystem.getProjectRoot() + 'Python/Rules/conways.rule') TestMap = map.Map([60, 60], [True, True], 0) TestMap[2][1] = 1 TestMap[3][2] = 1 TestMap[4][2] = 1 TestMap[2][3] = 1 TestMap[3][3] = 1 TestMap.print2D() TestTime = Time(TestMap, TestRule) while True: TestTime.update({'draw': True})
def test_text_init(self): "Test the Rule object creation from text" # 1. Create Rule object from text myobj = rule.Rule(EXAMPLE_TEXT) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(myobj.text, EXAMPLE_TEXT) self.assertEqual(myobj.name, 'row') self.assertEqual(len(myobj.ranges), 2) self.assertEqual(myobj.ranges[0][0], 6) self.assertEqual(myobj.ranges[0][1], 11) self.assertEqual(myobj.ranges[1][0], 33) self.assertEqual(myobj.ranges[1][1], 44) # 3. Test methods self.assertEqual(myobj.is_valid(1), False) self.assertEqual(myobj.is_valid(6), True) self.assertEqual(myobj.is_valid(7), True) self.assertEqual(myobj.is_valid(11), True) self.assertEqual(myobj.is_valid(12), False) self.assertEqual(myobj.is_valid(40), True) self.assertEqual(myobj.is_valid(45), False) self.assertEqual(myobj.is_valid(50), False)
def document_to_rule_obj(self, document) -> rule.Rule: doc_id = document.id document = document.to_dict() logger.debug(f"Parsing and constructing a rule obj for {doc_id}") try: rule_obj = rule.Rule( id=doc_id, name=document["name"], description=document["description"], enabled=document["enabled"], conditions=document["conditions"], actions=document["actions"], ) if "execution_count" in document: rule_obj.set_execution_count(document["execution_count"]) return rule_obj except ValidationError as e: logger.error( f"ValidationError in parsing rule document {doc_id} -> {e}") except SchemaError as e: logger.error( f"SchemaError in parsing rule document {doc_id} -> {e}") except Exception as e: logger.error(f"Some unknown error occurred. Error: {e}")
def _add_new_rule(cls, tokens, shapes_dict, rules): rule_name = tokens[1] left_shape_name = tokens[2] right_shape_name = tokens[4] left_shape = shapes_dict[left_shape_name] right_shape = shapes_dict[right_shape_name] new_rule = rule.Rule(rule_name, left_shape, right_shape) rules.append(new_rule)
def __init__(self, name, sig, pre, post, body): self.ref = name self.id = Fun.index self.sig = sig self.pre = Precondition(pre, self) self.post = Postcondition(post, self) self.body = [rule.Rule(r, self) for r in body] self.argsSize = len(sig[1]) Fun.index = Fun.index + 1 cons.funs[name] = self.id
def make_rules(self): local_adn = self.adn while (len(local_adn) > 0): nextrule = rule.Rule() local_adn = nextrule.build_from_adn(local_adn) if nextrule.isRule(): self.rules.append(nextrule)
def _get_rule(self, left_shape, right_shape): """Receives the left and right shapes: Shape Shape Prompts for a name. Returns the new rule: Rule """ prompt_for_name = 'Enter the name of the rule' name = rs.GetString(prompt_for_name) new_rule = rule.Rule(name, left_shape, right_shape) return new_rule
def test_empty_init(self): "Test the default Rule creation" # 1. Create default Rule object myobj = rule.Rule() # 2. Make sure it has the default values self.assertEqual(myobj.part2, False) self.assertEqual(myobj.text, None) self.assertEqual(myobj.name, None) self.assertEqual(myobj.ranges, [])
def main(): if __builtin__.testmode: logging.warn('!!!!!!TESTMODE ACTIVATED!!!!!!') logging.basicConfig(stream=sys.stderr) logging.getLogger().setLevel(logging.DEBUG) while 1: try: # read config file c = config.Config(os.getcwd()+"/config.ini") c.readFile() # instantiate the sensors vra = ventilation_relay.VentilationRelay(c.readValue("ventilation","port")) # digital port 7 waa = water_atomizer.WaterAtomizer(c.readValue("atomizer","port")) # digital port 8 ths = temp_sensor.TempHumiditySensor(c.readValue("thsensor","port")) # digital port 4 pra = pump_relay.PumpRelay(c.readValue("pump","port")) # digital port 2 lra = light_relay.LightRelay(c.readValue("light","port")) # digital port 3 sms = soil_moisture_sensor.SoilMoistureSensor(c.readValue("smsensor","port")) # analog port 0 sls = light_sensor.LightSensor(c.readValue("lightsensor","port")) # analog port 1 # create the rules pump_rule = rule.Rule(lambdas.pump_lambda, [sms, pra]) # activate water pump if sensor value light_rule = rule.Rule(lambdas.light_lambda, [c.readValue("light","from"), c.readValue("light","to")]) # activate light between 4:00 and 23:00 ventilation_rule = rule.Rule(lambdas.ventilation_lambda, [c.readValue("ventilation","from"), c.readValue("ventilation","to")]) # activate ventilation from minute 0 to minute 2 atomizer_rule = rule.Rule(lambdas.atomizer_lambda, [ths]) # humidify the air if needed # create processors rp = rule_processor.RuleProcessor([pump_rule, pra], [light_rule, lra], [ventilation_rule, vra], [atomizer_rule, waa]) ts = thingspeak_client.TSClient(vra, waa, ths, pra, lra, sms, sls) #wi = web_interface.fill_sensor_list([vra, waa, ths, pra, lra, sms, sls]) # run the GardenPi threads rp.process() ts.updateVals() time.sleep(60) except KeyboardInterrupt: raise except: print(sys.exc_info()[0]) pass
def __init__(self, text=None, part2=False): # 1. Set the initial values self.part2 = part2 self.text = text self.rules = {} # 2. Process text (if any) if text is not None and len(text) > 0: for line in text: new_rule = rule.Rule(text=line, part2=part2) self.rules[new_rule.bag] = new_rule
def test_part_one(self): "Test part one examples of Rule object" # 1. Loop for all the examples for example in EXAMPLES: # 2. Create Rule object from text myobj = rule.Rule(text=example['text']) # 3. Check the part one result self.assertEqual(myobj.sumation(), example['sum']) self.assertEqual(myobj.can_contain_shiny_gold, example['can'])
def make_forest(fieldss): nodes = {} goal_ids = set() for fields in fieldss: node_id = fields['hyp'] if node_id not in nodes: nodes[node_id] = forest.Item(sym.fromtag('PHRASE'), 0, 0, []) node = nodes[node_id] if node_id == 0: r = rule.Rule(sym.fromtag('PHRASE'), rule.Phrase([]), rule.Phrase([])) node.deds.append(forest.Deduction((), r, svector.Vector())) else: m = scores_re.match(fields['scores']) core_values = [float(x) for x in m.group(1).split(',')] dcost = svector.Vector(m.group(2).encode('utf8')) for i, x in enumerate(core_values): dcost["_core%d" % i] = x back = int(fields['back']) ant = nodes[back] f = fields['src-phrase'].encode('utf8').split() e = fields['tgt-phrase'].encode('utf8').split() if len(f) != int(fields['cover-end']) - int(fields['cover-start']) + 1: sys.stderr.write("warning: French phrase length didn't match covered length\n") f = rule.Phrase([sym.setindex(sym.fromtag('PHRASE'), 1)] + f) e = rule.Phrase([sym.setindex(sym.fromtag('PHRASE'), 1)] + e) r = rule.Rule(sym.fromtag('PHRASE'), f, e) ded = forest.Deduction((ant,), r, dcost) node.deds.append(ded) if int(fields['forward']) < 0: # goal goal_ids.add(node_id) goal = forest.Item(None, 0, 0, []) for node_id in goal_ids: goal.deds.append(forest.Deduction((nodes[node_id],), None, svector.Vector())) return goal
def __init__(self, text=None, part2=False): # 1. Set the initial values self.part2 = part2 self.text = text self.rules = [] # 2. Process text (if any) if text is not None and len(text) > 0: for line in text: if line.startswith('your ticket'): break self.rules.append(rule.Rule(text=line, part2=part2))
def test_empty_init(self): "Test the default Rule creation" # 1. Create default Rule object myobj = rule.Rule() # 2. Make sure it has the default values self.assertEqual(myobj.part2, False) self.assertEqual(myobj.text, None) self.assertEqual(myobj.bag, None) self.assertEqual(myobj.bags, []) self.assertEqual(myobj.numbers, []) self.assertEqual(myobj.can_contain_shiny_gold, None)
def test(): params = dict(a=3, b=2, name="Manfred") sp = parser(params) try: pr = sp.parseString("undefined") except KeyError: pass else: raise RuntimeError("should have gotten an KeyError on 'undefined'") for want, toparse in [ (True, "(or 0 1)"), (True, "true"), (True, "True"), (False, "false"), (True, "(or (= a 5) (= b 2))"), (True, "(or (= a 5) (= b 2))"), (True, "(and (eq name 'Manfred') (eq b 2))"), (True, "(and (= name 'Manfred') (or (= a 5) (= b 2)))"), (True, "(== a (+ 1 b))"), (False, '(== name "Ada")'), (True, '(== name "Manfred")'), (True, "(== name 'Manfred')"), (True, '(!= name "Ada")'), (False, '(!= name "Manfred")'), (True, '(| a b)'), (True, '(| (< a b) (> a b))'), (True, '(& (= a 3) (= 2 b))'), (True, '(and (== a 3) (eq 2 b))'), (True, '(!= name "name")'), ]: pr = sp.parseString(toparse, parseAll=True) #if len(pr) == 1 and len(pr[0]) == 1: print(pr) pr = pr[0] print("parsed:", type(pr), pr) if isinstance(pr, ParseResults): r = rule.Rule(pr, return_bool=True) print("rule:", r) result = r.match() print(f'Rule result: "{toparse}" on {params} gives {result}') else: result = True if pr else False print(f'Literal result: "{toparse}" on {params} gives {result}') assert (want == result) print()
def test_is_alive_next_generation(self): rule = r.Rule() self.assertTrue(rule.is_alive_next_generation(True, 3)) self.assertTrue(rule.is_alive_next_generation(True, 2)) self.assertTrue(rule.is_alive_next_generation(False, 3)) self.assertFalse(rule.is_alive_next_generation(True, 4)) self.assertFalse(rule.is_alive_next_generation(True, 1)) self.assertFalse(rule.is_alive_next_generation(False, 4)) self.assertFalse(rule.is_alive_next_generation(False, 2)) rule = r.Rule('23/12') self.assertTrue(rule.is_alive_next_generation(True, 1)) self.assertTrue(rule.is_alive_next_generation(True, 2)) self.assertTrue(rule.is_alive_next_generation(False, 2)) self.assertTrue(rule.is_alive_next_generation(False, 3)) self.assertFalse(rule.is_alive_next_generation(True, 3)) self.assertFalse(rule.is_alive_next_generation(True, 0)) self.assertFalse(rule.is_alive_next_generation(False, 4)) self.assertFalse(rule.is_alive_next_generation(False, 1))
def loadRule(filename): rawFile = open(filename) text = rawFile.read() lineList = text.split('\n') propertiesList = [] for line in lineList: if line != '': property = line.split(':') if property[1].lower() == 'true': property[1] = True elif property[1].lower() == 'false': property[1] = False propertiesList.append(property) firstRulePos = 7 for i in range(firstRulePos, len(propertiesList) - 1): propertiesList[i][0] = propertiesList[i][0].split(',') propertiesList[i][1] = propertiesList[i][1].split(',') for j in range(0, len(propertiesList[i][1])): if not propertiesList[5][1]: propertiesList[i][1][j] = propertiesList[i][1][j].split('-') if len(propertiesList[i][1][j]) == 1: propertiesList[i][1][j].append(propertiesList[i][1][j][0]) propertiesList[i][1][j][0] = int(propertiesList[i][1][j][0]) propertiesList[i][1][j][1] = int(propertiesList[i][1][j][1]) center = propertiesList[3][1].split(', ') for i in range(0, len(center)): center[i] = int(center[i]) actionTable = getBaseActions() loadedRule = rule.Rule(propertiesList[0][1], int(propertiesList[1][1]), int(propertiesList[2][1]), center, propertiesList[4][1], propertiesList[5][1], int(propertiesList[6][1])) for i in range(firstRulePos, len(propertiesList) - 1): for j in propertiesList[i][0]: if propertiesList[5][1]: loadedRule.addRuleFromNeighbourhood(int(j), propertiesList[i][1], int(propertiesList[i][2])) else: loadedRule.addRule(int(j), propertiesList[i][1], int(propertiesList[i][2])) return loadedRule
def test_text_one(self): "Test the Rule object creation from text with two alternates" # 1. Create Rule object from text myobj = rule.Rule(EXAMPLE_ONE) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 12) self.assertEqual(myobj.number, 1) self.assertEqual(myobj.definition, '2 3 | 3 2') # 3. Check methods self.assertEqual(myobj.is_constant(), False) self.assertEqual(myobj.alternatives(), ['2 3 ', ' 3 2'])
def test_text_four(self): "Test the Rule object creation from text with constant rule" # 1. Create Rule object from text myobj = rule.Rule(EXAMPLE_FOUR) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 6) self.assertEqual(myobj.number, 4) self.assertEqual(myobj.definition, '"a"') # 3. Check methods self.assertEqual(myobj.is_constant(), True) self.assertEqual(myobj.letter(), 'a')
def handle_ruleadd(self): rules = self.main.listrules row = 0 if len(rules.selectedIndexes()) > 0: selected = rules.selectedIndexes()[0] row = selected.row() newrule = rule.Rule(name="new_rule") self.rulemod.addRuleBefore(row, newrule) self.select_row(row) # Send back to Mallory server self.remote_rule.update_rules(self.rulemod.getRules())
def _get_rule(self, left_shape, right_shape): """Receives the left and right shapes: Shape Shape Prompts for a name. Returns the new rule: Rule """ prompt_for_name = 'Enter the name of the rule' name = rs.GetString(prompt_for_name) while not self._is_well_formed(name): prompt_for_name = ('The name may not contain a space or a #. ' + 'Enter the name of the rule') name = rs.GetString(prompt_for_name) new_rule = rule.Rule(name, left_shape, right_shape) return new_rule
def test_text_zero(self): "Test the Rule object creation from text with one alternate" # 1. Create Rule object from text myobj = rule.Rule(EXAMPLE_ZERO) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 8) self.assertEqual(myobj.number, 0) self.assertEqual(myobj.definition, '4 1 5') # 3. Check methods self.assertEqual(myobj.is_constant(), False) self.assertEqual(myobj.alternatives(), ['4 1 5'])
def __init__(self): """creat all the needed parts""" backserver = server.Server() #start the server control = controlwindow.Controlwindow(backserver) #create the lisener scanner = bluescanner.Bluescanner(control) #create the scanner scanner.run #num = number of people needed #group must be None #target must be None #name must be None #verbose must be None #*args array of users #**kargs arrary of positions newrule = rule.Rule(2, None, None, None, None, {backserver.someuser}, None) control.addrule(newrule, scanner.getcurrentuser)