def test_run_with_debug(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["ababa", "babb"], alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack, debug=True) searcher.auto_search()
def __init__(self, n=None, k=None, strategy_pack=None, flogger_kwargs={'processname': 'runner'},**kwargs): self.start_tilings = [] if filename is not None: assert n == None and k == None f = open(filename, 'r') for line in f: line = line.strip() self.start_tilings.append(Tiling.from_string(line)) f.close() else: for basis in combinations(PermSet(n), k): self.start_tilings.append(Tiling([Obstruction.single_cell(patt, (0, 0)) for patt in basis])) strategy_pack.ver_strats = [verify_points] function_kwargs = {"basis": []} function_kwargs.update(kwargs.get('kwargs', dict())) CombinatorialSpecificationSearcher.__init__( self, self.start_tilings[0], strategy_pack, function_kwargs=function_kwargs, **kwargs) self.start_labels = [] for start_tiling in self.start_tilings: self.classdb.add(start_tiling, expandable=True) self.start_labels.append(self.classdb.get_label(start_tiling)) for label in self.start_labels: self.classqueue.add_to_working(label)
def test_forget_ruledb(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["ababa", "babb"], alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack, ruledb="forget") return searcher.auto_search()
def test_pickle_specification(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["ababa", "babb"], alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack) spec = searcher.auto_search() spec.count_objects_of_size(10) pickle.dumps(spec)
def test_do_level(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["aabb", "bbbbab"], alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack) with pytest.raises(NoMoreClassesToExpandError): while True: searcher.do_level() assert all(searcher.classqueue.queue_sizes)
def test_emtpy_rule_first(): """ When recomputing the rules. The forest extractor should favor the empty rule. """ empty_class = AvoidingWithPrefix("ab", ["ab"], ["a", "b"]) assert empty_class.is_empty() css = CombinatorialSpecificationSearcher(empty_class, pack, ruledb=RuleDBForest()) spec = css.auto_search() assert isinstance(spec.rules_dict[empty_class].strategy, EmptyStrategy)
def test_forest_ruledb(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["ababa", "babb"], alphabet) ruledb = RuleDBForest() searcher = CombinatorialSpecificationSearcher(start_class, pack, ruledb=ruledb) spec = searcher.auto_search() expected_count = [1, 2, 4, 8, 15, 27, 48, 87, 157, 283] count = [spec.count_objects_of_size(n) for n in range(10)] assert count == expected_count
def expanded_spec( tiling: Tiling, pack: StrategyPack, symmetries: FrozenSet[FrozenSet[Perm]] ) -> CombinatorialSpecification: """ Return a spec where any tiling that does not have the basis in one cell is verified. """ pack = pack.add_verification(NoBasisVerification(symmetries), apply_first=True) with TmpLoggingLevel(logging.WARN): css = CombinatorialSpecificationSearcher(tiling, pack) spec = css.auto_search() return spec
def auto_search(self, **kwargs): verbose = kwargs.get('verbose', False) kwargs['verbose'] = False if verbose: max_time = kwargs.get('max_time', None) kwargs['max_time'] = kwargs.get('status_update', None) status_update = kwargs.get('status_update', None) kwargs['status_update'] = None print("Starting universe scope with the tilings:") for t in self.start_tilings: print(t) else: max_time = kwargs.get('max_time', None) status_update = None trees = None time = 0 while trees is None: trees = CombinatorialSpecificationSearcher.auto_search(self, **kwargs) time += self._time_taken if max_time is not None and max_time > time: break if status_update is not None: kwargs['max_time'] = self._time_taken + status_update if verbose: print(scope.status()) if verbose: print("PROOF TREES FOUND") for start_tiling, tree in zip(self.start_tilings, trees): print(start_tiling) print(json.dumps(tree.to_jsonable()))
def __init__(self, start_class, strategy_pack, # symmetry=False, forward_equivalence=False, logger_kwargs={'processname': 'runner'}, **kwargs): """Initialise TileScope.""" if isinstance(start_class, str): basis = Basis([Perm.to_standard([int(c) for c in p]) for p in start_class.split('_')]) elif isinstance(start_class, list): basis = Basis(start_class) elif isinstance(start_class, Tiling): start_tiling = start_class if start_class.dimensions == (1, 1): basis = Basis([o.patt for o in start_class.obstructions]) else: basis = [] if not isinstance(start_class, Tiling): start_tiling = Tiling( obstructions=[Obstruction.single_cell(patt, (0, 0)) for patt in basis]) if strategy_pack.symmetries==True: symmetries = [Tiling.inverse, Tiling.reverse, Tiling.complement, Tiling.antidiagonal, Tiling.rotate90, Tiling.rotate180, Tiling.rotate270] # symmetries = [sym for sym in symmetries # if sym(start_tiling) == start_tiling] strategy_pack.symmetries = symmetries else: symmetries = [] function_kwargs = {"basis": basis} function_kwargs.update(kwargs.get('kwargs', dict())) CombinatorialSpecificationSearcher.__init__( self, start_tiling, strategy_pack, symmetry=symmetries, forward_equivalence=forward_equivalence, function_kwargs=function_kwargs, logger_kwargs=logger_kwargs, **kwargs)
def test_cant_count_unexpanded(): """ Test that the expanded spec is not using the same rule object as the original spec. """ alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["aa"], alphabet) class SomeVerification(VerificationStrategy): """ Verify the specific root for this run so that we get a specification with only one rule. """ comb_class = AvoidingWithPrefix("a", ["aa"], alphabet) def verified(self, comb_class): return comb_class == SomeVerification.comb_class def formal_step(self): return f"Verify {SomeVerification.comb_class}" def from_dict(self, d): raise NotImplementedError def get_terms(self, comb_class, n): raise NotImplementedError def pack(self, comb_class): if comb_class == SomeVerification.comb_class: return pack else: raise NotImplementedError extra_pack = pack.add_verification(SomeVerification()) searcher = CombinatorialSpecificationSearcher(start_class, extra_pack) spec = searcher.auto_search() with pytest.raises(NotImplementedError): spec.count_objects_of_size(10) new_spec = spec.expand_verified() with pytest.raises(NotImplementedError): spec.count_objects_of_size(10) assert new_spec.count_objects_of_size(10) == 144 for rule1, rule2 in itertools.product(spec, new_spec): assert not (rule1 is rule2)
def get_word_searcher(avoid, alphabet): pack = StrategyPack( initial_strats=[RemoveFrontOfPrefix()], inferral_strats=[], expansion_strats=[[ExpansionStrategy()]], ver_strats=[AtomStrategy()], name=( "Finding specification for words avoiding consecutive patterns."), ) start_class = AvoidingWithPrefix("", avoid, alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack) return searcher
def test_expand_size1_spec(): """ Test that the expansion of spec with only one verification rule works. """ alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["ababa", "babb"], alphabet) class RootVerificationStrategy(VerificationStrategy): """ Verify the specific root for this run so that we get a specification with only one rule. """ def verified(self, comb_class): return comb_class == start_class def formal_step(self): return f"Verify {start_class}" def from_dict(self, d): raise NotImplementedError def pack(self, comb_class): if comb_class == start_class: return pack else: raise NotImplementedError verif_root_pack = StrategyPack( [], [], [], [RootVerificationStrategy()], "root_verif" ) searcher = CombinatorialSpecificationSearcher(start_class, verif_root_pack) spec = searcher.auto_search() assert spec.number_of_rules() == 1 new_spec = spec.expand_verified() assert new_spec.number_of_rules() > 1 assert new_spec.count_objects_of_size(10) == 511
def test_no_spec_exception(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["aabb", "bbbbab"], alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack) for _ in range(2): searcher.do_level() assert not searcher.ruledb.has_specification() with pytest.raises(SpecificationNotFound): searcher.get_specification() with pytest.raises(SpecificationNotFound): searcher.ruledb.get_specification_rules()
def specification(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["ababa", "babb"], alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack) return searcher.auto_search()
if __name__ == "__main__": example_alphabet = input( ("Input the alphabet (letters should be separated by a" " comma):")).split(",") example_patterns = tuple( map( Word, input(("Input the patterns to be avoided (patterns should be " "separated by a comma):")).split(","), )) start_class = AvoidingWithPrefix(Word(), example_patterns, example_alphabet) searcher = CombinatorialSpecificationSearcher(start_class, pack, debug=True) spec = searcher.auto_search(status_update=10) print(spec) print(spec.get_genf()) import time for n in range(20): print("=" * 10, n, "=" * 10) start_time = time.time() print(spec.count_objects_of_size(n)) print("Counting time:", round(time.time() - start_time, 2), "seconds") start_time = time.time() c = 0
def verify_letters_and_perms(config, **kwargs): if isinstance(config, Letter): return VerificationRule("Its a letter.") elif config.last_letter is None and len(config.config.slots) == 0: return VerificationRule("Its a permutation.") pack = StrategyPack(initial_strats=[remove_letter, equivalent], inferral_strats=[], expansion_strats=[[expansion]], ver_strats=[verify_letters_and_perms], name=("Finding regular insertion encodings")) if __name__ == "__main__": from permuta.permutils import is_insertion_encodable_maximum basis = input("Enter comma separated permutations: ") basis = [Perm.to_standard(p) for p in basis.split(',')] if is_insertion_encodable_maximum(basis): start_class = Suffixes(Configuration(Perm(), (0, )), basis) print(Configuration(Perm((0, )), (0, ))) searcher = CombinatorialSpecificationSearcher(start_class, pack, debug=True) tree = searcher.auto_search(status_update=10) tree.get_min_poly(solve=True) else: print("Not insertion encodable")
def test_iterative(): alphabet = ["a", "b"] start_class = AvoidingWithPrefix("", ["a"], alphabet) it_pack = pack.make_iterative("iterative") searcher = CombinatorialSpecificationSearcher(start_class, it_pack) searcher.auto_search()