Exemplo n.º 1
0
def Automate_in_one_lettre(Char: str) -> automaton:
    nom = get_random_string(4)
    if Char != "%":
        nom = Automaton(nom)
        nom.add_transition("0", Char, "1")
        nom.make_accept("1")
        return nom
    else:
        nom = Automaton(str(nom))
        nom.add_transition("0", "%", "1")
        nom.make_accept("1")
        return nom
Exemplo n.º 2
0
def main():

    path = 'entrada.txt'

    input_file = open_input(path)
    transitions_raw = get_transitions(input_file)
    intial_or_final = initial_and_final(input_file)
    states_dict = get_states(transitions_raw, intial_or_final)
    word = get_word(input_file)

    states = load_states(states_dict)
    transitions = load_transitions(states, transitions_raw)

    a = Automaton('Automato Finito', word, transitions)

    inicial = a.get_initials_list()

    for i in inicial:
        a.start_reach(word, i)
        word = get_word(input_file)

    #print(a.get_steps())

    gif = 1
    for s in a.get_steps():
        save_dot_and_png(a, s)
        save_gif(gif)
        gif += 1
Exemplo n.º 3
0
    def union_to_automaton(self, first_aut, second_aut):
        """ Converte uma expressao de uniao em seu respectivo automato """

        final_state = self.create_state()
        finals = {final_state}
        initial = self.create_state()
        states = first_aut.states.union(second_aut.states).union(
            {initial, final_state})
        alphabet = first_aut.alphabet.union(second_aut.alphabet)

        resulting_function = {}
        resulting_function.update(first_aut.function)
        resulting_function.update(second_aut.function)

        resulting_function[initial] = {
            '&': {initial, first_aut.initial, second_aut.initial}
        }
        resulting_function[final_state] = {'&': finals}

        for final in first_aut.finals.union(second_aut.finals):
            resulting_function[final]['&'].add(final_state)

        # print(f"resulting_function = {resulting_function}")

        return Automaton(states, alphabet, resulting_function, finals, initial)
Exemplo n.º 4
0
def determinise(automate: Automaton):
    automateDet = Automaton("deterministe")
    automateDet.initial = automate.initial
    listeEtats = []
    listeEtats.append(set([automate.initial.name]))
    listeEtatsNew = listeEtats
    print(listeEtats)
    while len(listeEtats) != 0:
        elt1 = listeEtats[0]
        listeEtats = listeEtats[1:]
        for elt11 in elt1:
            for x in automate.alphabet:
                EtatDest = []
                for (source, symbol, destination) in automate.transitions:
                    if source == str(elt11) and symbol == x:
                        EtatDest.append(destination)
                if (len(EtatDest) != 0) and EtatDest not in listeEtatsNew:
                    listeEtats.append(EtatDest)
                    listeEtatsNew.append(EtatDest)
                    automateDet.add_transition(str(elt1), x, str(EtatDest))
    for etat in automate.acceptstates:
        for elt1 in listeEtatsNew:
            if etat in elt1:
                automateDet.make_accept(str(elt1))
    return automateDet
Exemplo n.º 5
0
    def parseAut(problem, it):
        '''parseAut(problem, it) -> Automaton

Parses an automaton (resp. transducer) representation into an instance of the
Automaton class.  Modifies problem, it.
'''
        # initialize
        aut = Automaton()

        for line in it:
            if (line == "}"): # end of automaton
                return aut
            elif (line[0:2] == "//"): # comments
                pass
            elif (line == ""): # empty string
                pass
            elif (reStartStates.match(line)): # start states
                Parser.parseStartStates(aut, line)
            elif (reAcceptStates.match(line)): # accepting states
                Parser.parseAcceptStates(aut, line)
            elif (reEpsTrans.match(line)): # epsilon transition
                Parser.parseEpsTrans(aut, line)
            elif (reAutTrans.match(line)) or (reTransdTrans.match(line)):
                Parser.parseTrans(problem, aut, line)
            else:
                raise Exception("Syntax error: " + line)
Exemplo n.º 6
0
    def test_nfa_nfa_1(self):
        """Convertion from NFA to DFA."""
        q1, q2, q3 = map(State, ['q1', 'q2', 'q3'])

        q1.add_transition('b', q2)
        q1.add_transition('$', q3)
        q2.add_transition('a', [q2, q3])
        q2.add_transition('b', q3)
        q3.add_transition('a', q1)

        M = Automaton('M', [q1, q2, q3], ['a', 'b'], q1, q1)
        D = M.to_dfa()

        self.assertTrue('q1' in D.Q[0].ready)
        self.assertTrue('q3' in D.Q[0].ready)
        self.assertEqual(len(D.Q[0].ready), 2)

        self.assertTrue('q2' in D.Q[1].ready)
        self.assertEqual(len(D.Q[1].ready), 1)

        self.assertTrue('q2' in D.Q[2].ready)
        self.assertTrue('q3' in D.Q[2].ready)
        self.assertEqual(len(D.Q[2].ready), 2)

        self.assertTrue('q3' in D.Q[3].ready)
        self.assertEqual(len(D.Q[3].ready), 1)

        self.assertTrue('q1' in D.Q[4].ready)
        self.assertTrue('q2' in D.Q[4].ready)
        self.assertTrue('q3' in D.Q[4].ready)
        self.assertEqual(len(D.Q[4].ready), 3)

        self.assertEqual(len(D.Q[5].ready), 0)
Exemplo n.º 7
0
    def closure_to_automaton(self, automaton):
        """ Converte o fechamento para um automato """

        final_state = self.create_state()
        finals = {final_state}
        initial = self.create_state()
        states = automaton.states.union({initial, final_state})
        alphabet = automaton.alphabet

        resulting_function = {}
        resulting_function.update(automaton.function)

        resulting_function[initial] = {
            '&': {initial, automaton.initial, final_state}
        }
        resulting_function[final_state] = {'&': finals}

        finals_copy = automaton.finals.copy()
        for final in finals_copy:
            resulting_function[final]['&'].add(automaton.initial)
            resulting_function[final]['&'].add(final_state)

        # print(f"resulting_function = {resulting_function}")

        return Automaton(states, alphabet, resulting_function, finals, initial)
Exemplo n.º 8
0
    def test_2(self):
        """Example 1.30, p. 51 (extension with epsilon transitions).
        Michael Sipser, Introduction to the theory of computation, 3-rd ed.
        """
        q1, q2, q3, q4 = map(State, ['q1', 'q2', 'q3', 'q4'])

        q1.add_transition('1', [q1, q2])
        q1.add_transition('0', q1)
        q2.add_transition('0', q3)
        q2.add_transition('1', q3)
        q2.add_transition('$', q3)
        q3.add_transition('0', q4)
        q3.add_transition('1', q4)
        q3.add_transition('$', q4)

        M = Automaton('M', [q1, q2, q3, q4], ['0', '1'], q1, q4)

        self.assertListEqual(M.active_states, [q1])
        M.transition('0')
        self.assertListEqual(M.active_states, [q1])
        M.transition('1')
        self.assertListEqual(M.active_states, [q1, q2, q3, q4])
        M.transition('0')
        self.assertListEqual(M.active_states, [q1, q3, q4])
        M.transition('0')
        self.assertListEqual(M.active_states, [q1, q4])
        M.transition('1')
        self.assertListEqual(M.active_states, [q1, q2, q3, q4])
        M.transition('0')
        self.assertListEqual(M.active_states, [q1, q3, q4])
        M.transition('0')
        self.assertListEqual(M.active_states, [q1, q4])

        self.assertTrue(M.is_accepted())
Exemplo n.º 9
0
def convert_graph_fmt(filename, fmt, output_dir=None):
    automaton = Automaton(fromfile=filename)
    filename_dir, filename_name = os.path.split(filename)
    if output_dir:
        filename_dir = output_dir
    new_filename = os.path.join(filename_dir,
                                ".".join([filename_name.split('.')[0], fmt]))
    automaton.export(filename=new_filename)
Exemplo n.º 10
0
def enabledToFair(autEnabled):
    '''enabledToFair(autEnabled) -> Automaton

Encodes fairness into the Enabled automaton, thus obtaining the language of all
possible configurations with enabledness encoded.
'''
    result = Automaton()

    return result
Exemplo n.º 11
0
def intersect(automaton1: Automaton, automaton2: Automaton) -> Automaton:
    automaton1 = automaton1.as_DFA()
    automaton2 = automaton2.as_DFA()
    states = get_states_cross_product(automaton1, automaton2)
    initial = automaton1.initial + automaton2.initial
    accept = set()
    for a1 in automaton1.accept:
        for a2 in automaton2.accept:
            accept.add(a1+a2)
    alphabet = automaton1.alphabet | automaton2.alphabet
    return Automaton(states, initial, accept, alphabet)
Exemplo n.º 12
0
def test_app():
    passwords = [
        ("x", "", "1"),
        ("want", "a", "epuu7Aeja9"),
        ("emerge", "bamboo", "zexae2Moo2"),
        ("question", "predict", "dahTho9Thai5yiasie1c"),
        ("quick fiber estate ripple phrase", "topic", "huu4aeju2gooth1iS6ai")
    ]

    auto = Automaton()
    client = Client(auto)

    # Test password insertion
    assert client.get_size() == 0
    for i, (name, login, password) in enumerate(passwords):
        auto.actions = "rb"
        client.add(name, login, password)
        assert client.get_size() == i+1

    subtest_password_list(client, passwords)
    subtest_has_name(client, passwords)
    subtest_password_retrieval(client, auto, passwords)

    # Export in plain text and also in encrypted form
    # Do this before password removal testing
    auto.actions = "brb"
    export_plain = client.export(encrypt=False)
    auto.actions = "b"
    export_encrypted = client.export()

    # Test password removal
    removal_order = [name for name, _, _ in passwords]
    random.shuffle(removal_order)
    names = set(removal_order)
    for name in removal_order:
        auto.actions = "rb"
        client.delete_by_name(name)
        names.remove(name)
        assert set(client.get_names()) == names
    assert client.get_size() == 0

    # Test import plain
    subtest_clear(client, auto, passwords)
    auto.actions = ";b"
    client.import_("1.1.0", export_plain, encrypted=False)
    subtest_password_list(client, passwords)
    subtest_password_retrieval(client, auto, passwords)

    # Test import encrypted
    subtest_clear(client, auto, passwords)
    auto.actions = ";b"
    client.import_("1.1.0", export_encrypted, encrypted=True)
    subtest_password_list(client, passwords)
    subtest_password_retrieval(client, auto, passwords)
Exemplo n.º 13
0
def kleene_star(automaton1: Automaton) -> Automaton:
    states = automaton1.states
    newInitial = State("kleen_initial")
    states.add(newInitial)

    for state in automaton1.states:
        if state.name in automaton1.accept:
            state.add_transition(newInitial.name, EPSILON_SYMBOL)

    automaton1.accept.add(newInitial.name)
    newInitial.add_transition(automaton1.initial, EPSILON_SYMBOL)
    return Automaton(states, newInitial.name, automaton1.accept, automaton1.alphabet)
Exemplo n.º 14
0
def main():
    parser = argparse.ArgumentParser(
        description="Operation for automatons"
    )
    parser.add_argument("--automaton1", "-a", dest="automaton1", type=str, required=True, help="File of the first automaton description")
    parser.add_argument("--automaton2", "-b", dest="automaton2", type=str, help="File of the second automaton description. Not required for operation kleene_star")
    parser.add_argument("--operation", "-o", dest="operation", type=str, required=True, choices=OPS, help="Operation to execute")
    args = parser.parse_args()
    automaton1 = Automaton(from_file=args.automaton1)
    check_errors(automaton1.errors)
    if args.operation != "kleene_star":
        automaton2 = None
        if args.automaton2:
            automaton2 = Automaton(from_file=args.automaton2)
        else:
            print("Need to define --automaton2")
            sys.exit(1)
        check_errors(automaton2.errors)
        result = getattr(operations, args.operation)(automaton1, automaton2)
    else:
        result = operations.kleene_star(automaton1)
    print(result.render())
Exemplo n.º 15
0
def get_rule_30(steps=None):
    """for get rule 30

    Args:
        steps (int): number of steps to run the rule 30

    Returns:
        cell_json(list): python object notation of """

    # cells = [[0,0,0,0,1,0,0,0,0],
    #     [0,0,0,1,1,1,0,0,0],
    #     [0,0,1,1,0,0,1,0,0],
    #     [0,1,1,0,1,1,1,1,0],
    #     [1,1,0,0,1,0,0,0,1]]

    cells = Automaton(steps, rule=30).string()

    cell_json = [{"z": cells, "y": list(range(1, steps))}]
    # cell_json = [{"z":cells}]

    logging.info("\n" + str(Automaton(20, rule=30).string()))

    return cell_json
Exemplo n.º 16
0
def TestTP():
    a1 = Automaton("dummy")
    a1.from_txtfile("test/a.af")
    a2 = Automaton("dummy1")
    a2.from_txtfile("test/b.af")
    a1.to_graphviz(a1.name + ".gv")
    a2.to_graphviz(a2.name + ".gv")
    print(a1)
    print(a2)
    print(concat(a1, a2))
    a1star = kleene(a1)
    print()
    print(a1star)
    a1star.to_graphviz("a1star.gv")

    a1a2 = concat(a1, a2)
    print()
    print(a1a2)
    a1a2.to_graphviz("a1a2.gv")

    a1ora2 = union(a1, a2)
    print()
    print(a1ora2)
    a1ora2.to_graphviz("a1ora2.gv")
Exemplo n.º 17
0
def check(rules, tests, parser_args={}):
    print "-" * 70
    g = Grammar(rules)
    a = Automaton(g)
    fd = open(join(testdir, "tmp.py"), "w")
    a.write_parser(fd)
    fd.close()
    del a, g

    import tmp
    reload(tmp)
    p = tmp.Parser(**parser_args)

    EOF.set_real_eof(p.EOF)

    for input, e_tree, e_err in tests:
        e_err = [(x[0], frozenset(x[1])) for x in e_err]

        print "input: " + repr(input)
        try:
            tree = p.parse((x, k) for k, x in enumerate(input))
            err = []
        except p.ParseErrors, e:
            tree = e.tree
            err = e.errors
            err = [(x[0], frozenset(x[1])) for x in err]

        success = True
        for e in e_err:
            if e not in err:
                print "  missed error: " + repr(e)
                success = False
        for e in err:
            if e not in e_err:
                print "  unexpected error: " + repr(e)
                success = False
        if e_tree != ignore and tree != e_tree:
            print "  unexpected result:"
            print "    expected: " + repr(e_tree)
            print "    got: " + repr(tree)
            success = False

        if success:
            print "  success"
        else:
            print "  failure"
            global errors
            errors += 1
Exemplo n.º 18
0
Arquivo: main.py Projeto: PicoJr/cell
def main():
    parser = argparse.ArgumentParser(
        description='display 1-D cellular automaton')
    parser.add_argument('rule', type=int, help='wolframe rule (0-255)')
    parser.add_argument('steps', type=int, help='number of steps')
    parser.add_argument('seed', help='bin(seed) -> first line')
    parser.add_argument('--debug',
                        action='store_true',
                        help='for debug purpose')
    parser.add_argument('--raw', action='store_true', help='display with 0,1')
    args = parser.parse_args()
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    automaton = Automaton(args.rule, args.seed)
    automaton.display()
    automaton.print_steps(args.steps, args.raw)
Exemplo n.º 19
0
 def __init__(self, examples=None, automaton=None):
     """
     :args:
         automaton   - (optional) instance of Automaton class
         examples    - list of strings, this can include the empty string ('')
     """
     self.A = automaton if automaton else Automaton()
     self.S = sorted(set(examples))
     self.Σ = {char for s in self.S for char in s}
     # If empty string is accepted, make root accepting state
     self.root = self.A.add_node(
         is_initial=True, is_final=True if self.S[0] == '' else False)
     # Drop empty string from list of examples
     if self.S[0] == '':
         self.S = self.S[1:]
     self.verbose = False
Exemplo n.º 20
0
    def concatenation_to_automaton(self, first_aut, second_aut):  #pylint: disable=R0201
        """ Converte uma expressao de concatenacao em seu respectivo automato """

        states = first_aut.states.union(second_aut.states)
        finals = second_aut.finals
        initial = first_aut.initial
        alphabet = first_aut.alphabet.union(second_aut.alphabet)

        resulting_function = {}
        resulting_function.update(first_aut.function)
        resulting_function.update(second_aut.function)

        finals_copy = first_aut.finals.copy()
        for final in finals_copy:
            resulting_function[final]['&'].add(second_aut.initial)

        return Automaton(states, alphabet, resulting_function, finals, initial)
Exemplo n.º 21
0
def concat(automaton1: Automaton, automaton2: Automaton) -> Automaton:
    states = set()
    for state in sorted(automaton1.states):
        new_state = State(f"A1{state.name}")
        for trans in state.transitions:
            new_state.add_transition(f"A1{trans.target}", trans.symbol)
        if state.name in automaton1.accept:
            new_state.add_transition(f"A2{automaton2.initial}", EPSILON_SYMBOL)
        states.add(new_state)
    for state in sorted(automaton2.states):
        new_state = State(f"A2{state.name}")
        for trans in state.transitions:
            new_state.add_transition(f"A2{trans.target}", trans.symbol)
        states.add(new_state)
    initial = f"A1{automaton1.initial}"
    accept = set()
    for state_name in automaton2.accept:
        accept.add(f"A2{state_name}")
    alphabet = automaton1.alphabet | automaton2.alphabet
    return Automaton(states, initial, accept, alphabet)
Exemplo n.º 22
0
def regexp_to_automaton(re: str) -> Automaton:
    """
    Moore's algorithm: regular expression `re` -> non-deterministic automaton
    """
    postfix = RegExpReader(re).to_postfix()
    stack: List[Automaton] = []
    for c in postfix:
        if c in (".", "+", "*"):
            right = stack.pop()
            left = None
            if c != "*":
                left = stack.pop()
            result = operation(left, right, c)
            stack.append(result)
        else:
            automate = Automaton(c)
            automate.add_transition("0", c, "1")
            automate.make_accept("1")
            stack.append(automate)

    return stack[0]
Exemplo n.º 23
0
    def create_automaton(self, current_node=None):
        """ Cria o automato que corresponde a expressao """

        if current_node is None:
            current_node = self.expression_tree

        # print(f"Current node is {current_node.get_value()}")

        if current_node.get_left_child(
        ) is None and current_node.get_right_child() is None:
            state = self.create_state()
            final = self.create_state()
            function = {
                state: {
                    '&': {state},
                    current_node.get_value(): {final}
                },
                final: {
                    '&': {final}
                }
            }
            aut = Automaton({state, final}, {current_node.get_value()},
                            function, {final}, state)
            return aut

        if current_node.get_left_child() is not None:
            left_aut = self.create_automaton(current_node.get_left_child())
        if current_node.get_right_child() is not None:
            right_aut = self.create_automaton(current_node.get_right_child())

        if current_node.get_value() == '.':
            return self.concatenation_to_automaton(left_aut, right_aut)

        if current_node.get_value() == '+':
            return self.union_to_automaton(left_aut, right_aut)

        # O valor eh *
        if current_node.get_left_child() is not None:
            return self.closure_to_automaton(left_aut)
        return self.closure_to_automaton(right_aut)
Exemplo n.º 24
0
    def test_1(self):
        """Example 1.35, p. 52.
        Michael Sipser, Introduction to the theory of computation, 3-rd ed.
        """
        q1, q2, q3 = map(State, ['q1', 'q2', 'q3'])

        q1.add_transition('b', q2)
        q1.add_transition('$', q3)
        q2.add_transition('a', [q2, q3])
        q2.add_transition('b', q3)
        q3.add_transition('a', q1)

        M = Automaton('M', [q1, q2, q3], ['a', 'b'], q1, q1)

        self.assertListEqual(M.active_states, [q1, q3])
        M.transition('b')
        self.assertListEqual(M.active_states, [q2])
        M.transition('a')
        self.assertListEqual(M.active_states, [q2, q3])
        M.transition('b')
        self.assertListEqual(M.active_states, [q3])
        M.transition('a')
        self.assertListEqual(M.active_states, [q1, q3])
        self.assertTrue(M.is_accepted())

        M.reset()

        self.assertListEqual(M.active_states, [q1, q3])
        M.transition('b')
        self.assertListEqual(M.active_states, [q2])
        M.transition('a')
        self.assertListEqual(M.active_states, [q2, q3])
        M.transition('b')
        self.assertListEqual(M.active_states, [q3])
        M.transition('b')
        self.assertListEqual(M.active_states, [])
        M.transition('a')
        self.assertListEqual(M.active_states, [])
        self.assertTrue(not M.is_accepted())
Exemplo n.º 25
0
def re2a(er, trace=False):
    S = Automaton()
    name = {}

    q0 = er.shift(True, None)
    name[q0] = 0
    nq0 = name[q0]
    if trace:
        sys.stderr.write("Initial state: %d\nItems:\n%s\n" % (nq0, q0))
    S.addState(nq0, q0)
    S.makeInitial(nq0)
    if q0.isFinal():
        S.makeFinal(nq0, q0.category())

    pending = set([q0])
    while len(pending) != 0:
        q = pending.pop()
        nq = name[q]
        for charClass in q.movements():
            d = q.shift(False, charClass)
            if not name.has_key(d):
                pending.add(d)
                name[d] = len(name)
                nd = name[d]
                S.addState(nd, d)
                if trace:
                    sys.stderr.write(
                        "Added state: %d%s, from %d with class %s\nItems:\n%s\n"
                        % (nd, d.isFinal() and " (final)"
                           or "", nq, charClass, d))
                if d.isFinal():
                    S.makeFinal(nd, d.category())
            nd = name[d]
            S.addTransition(nq, charClass, nd)
    S.compactArcs()
    return S
Exemplo n.º 26
0

def union(a1: Automaton, a2: Automaton) -> Automaton:
    # TODO: implement union
    return a1


##################

if __name__ == "__main__":
    if len(sys.argv) != 3:
        usagestring = "Usage: {} <automaton-file1.af> <automaton-file2.af>"
        error(usagestring.format(sys.argv[0]))

    # First automaton, argv[1]
    a1 = Automaton("dummy")
    a1.from_txtfile(sys.argv[1])
    a1.to_graphviz(a1.name + ".gv")
    print(a1)

    # Second automaton, argv[2]
    a2 = Automaton("dummy")
    a2.from_txtfile(sys.argv[2])
    a2.to_graphviz(a2.name + ".gv")
    print(a2)

    a1star = kleene(a1)
    print()
    print(a1star)
    a1star.to_graphviz("a1star.gv")
Exemplo n.º 27
0
def delta0(q, e):
    res = set()
    if q == "q0":
        if e == "a":
            res = {"q2"}
        elif e == "b":
            res = {"q1"}
    elif q == "q1":
        if e == "a":
            res = {"q3"}
        elif e == "b":
            res = {"q0"}
    elif q == "q2":
        if e == "a":
            res = {"q2"}
        elif e == "b":
            res = {"q1"}
    elif q == "q3":
        if e == "a":
            res = {"q3"}
        elif e == "b":
            res = {"q3"}
    return res


automata = Automaton(states, alphabet, delta0, initial_state, final_states)

print(automata.execute({"q0"}, "a"))

print(automata.get_anti_language(5))
Exemplo n.º 28
0
# -*- coding:utf-8 -*-
from digraph import draw
from automaton import Automaton
from gui import GUI

aut = Automaton()
palabra = []
gui = GUI(aut, palabra)
gui.show()
Exemplo n.º 29
0
"""Example script that creates an image of 400 lines of rule 102."""

from automaton import Automaton

a = Automaton(102)
a.generate(400)

a.save_image("rule102.svg")
Exemplo n.º 30
0
def gather_terminal_states(state_transitions, is_valid_pwd):
    return [s for s in state_transitions if is_valid_pwd(s)]


if __name__ == "__main__":
    # Solve https://math.stackexchange.com/q/2452401/329832,
    # which should give 2,684,483,063,360

    # Configure the password:
    classes = [
        string.ascii_uppercase,
        string.digits,
    ]
    MIN_LENGTH = 8
    MAX_LENGTH = 10
    # Predicates:
    predicates = [
        lambda s: MIN_LENGTH <= sum(s) <= MAX_LENGTH,  # valid length?
        lambda s: s[1],  # has a digit?
    ]
    is_valid_pwd = lambda s: all(pred(s) for pred in predicates)

    state_transitions = generate_state_transitions(classes, MAX_LENGTH)
    terminal_states = gather_terminal_states(state_transitions, is_valid_pwd)

    automaton = Automaton(state_transitions, terminal_states)
    start = time.time()
    print(automaton.count_terminal_paths((0, ) * len(classes)))
    elapsed = time.time() - start
    print(f"Counted in {round(elapsed, 3)}s.")