def test_rule(self): f = DummyFeature('test1', {bool, int}, bool) f2 = DummyFeature('test2', {bool}, bool) m1 = BooleanMapper(mode='10') m2 = BooleanMapper(mode='10') rl1 = RuleLeaf(f, m1) rl2 = RuleLeaf(f2, m2) self.assertEqual(rl1.feat, f) self.assertEqual(rl1.mapper, m1) self.assertEqual(rl2.feat, f2) self.assertEqual(rl2.mapper, m2) r = Rule([rl1, rl2], [1.0, 1.0]) self.assertSetEqual({bool, int}, r.domains) self.assertIn(rl1, r.R) self.assertIn(rl2, r.R) d = DummyAgent() ar = Artifact(d, True) ret = r(ar) self.assertIsNone(ret) ar.domain = bool ret = r(ar) self.assertEqual(ret, 1.0) with self.assertRaises(TypeError): r = Rule([f, rl1], [0.1, 1.0]) mf = ModuloFeature(5) mf2 = ModuloFeature(10) mf3 = ModuloFeature(9) m3 = BooleanMapper(mode='10') rl1 = RuleLeaf(mf, m1) rl2 = RuleLeaf(mf2, m2) rl3 = RuleLeaf(mf3, m3) rule = Rule([rl1, rl2, rl3], [1.0, 1.0, 1.0]) ar = Artifact(d, 20) ar.domain = int self.assertAlmostEqual(rule(ar), 0.6666666666666666) rule = Rule([rl1, rl2, rl3], [-1.0, 1.0, 1.0]) self.assertAlmostEqual(rule(ar), 0.0) rule = Rule([rl1, rl2, rl3], [1.0, 1.0, -1.0]) self.assertAlmostEqual(rule(ar), 0.6666666666666666) rule = Rule([rl1, rl2, rl3], [1.0, 1.0, 0.0]) self.assertAlmostEqual(rule(ar), 1.0) rule = Rule([rl1, rl2, rl3], [0.0, 1.0, 1.0]) self.assertAlmostEqual(rule(ar), 0.5) m4 = BooleanMapper(mode='1-1') rl4 = RuleLeaf(mf3, m4) rule = Rule([rl1, rl2, rl4], [1.0, 1.0, -1.0]) self.assertAlmostEqual(rule(ar), 1.0)
def invent_number(self, low, high): '''Invent new number from given interval.''' self._log(logging.DEBUG, "Inventing number from ({}, {})" .format(low, high)) ars = [] steps = 0 while len(ars) < 10 and steps < 1000: steps += 1 r = randint(low, high) ar = Artifact(self, r) ar.domain = int if ar not in self.A: ars.append(ar) if len(ars) == 0: self._log(logging.INFO, "Could not invent new number!".format(self)) return 1, 0.0 best_eval, fr = self.evaluate(ars[0]) ars[0].add_eval(self, best_eval, fr) best_number = ars[0].obj best_ar = ars[0] for ar in ars[1:]: e, fr = self.evaluate(ar) ar.add_eval(self, e, fr) if e > best_eval: best_eval = e best_number = ar.obj best_ar = ar self._log(logging.DEBUG, "Invented number {}, with e = {}." .format(best_number, best_eval)) if best_eval > 0.5: rule = Rule([ModuloFeature(best_number)], [1.0]) rule.mappers = [BooleanMapper()] self.add_rule(rule, 1.0) self._log(logging.INFO, "Appended {} to features.".format(best_number)) return best_ar