def work(lines, fitas):

    number_of_lines = len(lines)
    '''valores de entrada que representam a turing machine de entrada'''
    input_alphabet = lines[0].split()
    tape_alphabet = lines[1]
    whitespace = lines[2]
    states = lines[3].split()
    initial_state = lines[4]
    final_states = lines[5].split()
    number_of_tapes = lines[6]
    transitions = []
    '''laco que pegara as transicoes'''
    for i in range(7, number_of_lines):
        transitions.append(lines[i].split())

    tape_list = []  #lista de fitas
    number_of_args = int(number_of_tapes)  #+2
    '''laco de repeticao que construira a lista de fitas'''
    for i in range(0, number_of_args):  #2
        if len(fitas) >= i:  # caso tenha simbolos, ele coloca na fita
            tape_list.append(Tape(whitespace, tape_alphabet, list(fitas[i])))
        else:  # caso nao tenha, coloca simbolos que representam o branco
            tape_list.append(Tape(whitespace, tape_alphabet, [whitespace]))
    '''Instancia a turing machine'''
    tm = turing_machine(states, final_states, initial_state, transitions,
                        whitespace, tape_list)
    '''executa a turing machine'''
    result = tm.run()
    if result[0] == 1:
        return True
Пример #2
0
def main2():
    tape1 = Tape('101011', '01')
    tape2 = Tape('', '01')
    states = [
        State('qCopy', StateType.Start),
        State('qReturn', StateType.Empty),
        State('qTest', StateType.Empty),
        State('qa', StateType.Accept),
        State('qr', StateType.Reject)
    ]
    transitions = [
        TransitionTwoTape('qCopy', '$', '$', 'qCopy', '$', '$',
                          Direction.Right, Direction.Right),
        TransitionTwoTape('qCopy', '0', '#', 'qCopy', '0', '0',
                          Direction.Right, Direction.Right),
        TransitionTwoTape('qCopy', '1', '#', 'qCopy', '1', '1',
                          Direction.Right, Direction.Right),
        TransitionTwoTape('qCopy', '#', '#', 'qReturn', '#', '#',
                          Direction.Neutral, Direction.Left),
        TransitionTwoTape('qReturn', '#', '0', 'qReturn', '#', '0',
                          Direction.Neutral, Direction.Left),
        TransitionTwoTape('qReturn', '#', '1', 'qReturn', '#', '1',
                          Direction.Neutral, Direction.Left),
        TransitionTwoTape('qReturn', '#', '$', 'qTest', '#', '$',
                          Direction.Left, Direction.Right),
        TransitionTwoTape('qTest', '0', '0', 'qTest', '0', '0', Direction.Left,
                          Direction.Right),
        TransitionTwoTape('qTest', '1', '1', 'qTest', '1', '1', Direction.Left,
                          Direction.Right),
        TransitionTwoTape('qTest', '$', '#', 'qa', '$', '#', Direction.Neutral,
                          Direction.Neutral),
        TransitionTwoTape('qTest', '1', '0', 'qr', '1', '0', Direction.Neutral,
                          Direction.Neutral),
        TransitionTwoTape('qTest', '0', '1', 'qr', '0', '1', Direction.Neutral,
                          Direction.Neutral)
    ]
    tm = TuringMachine(states, transitions, tape1, tape2)
    print(
        "\nTwo-tape Turing machine recognizes whether a binary string is a palindrome."
    )
    tm.process2()
    print("\nInput string:")
    print(tm.get_tape1())
    if (tm.current_state.type == StateType.Accept):
        print('\nAccepting')
    if (tm.current_state.type == StateType.Reject):
        print('\nRejecting')
    pass
    def __init__(self, machine_description_file):
        with open(machine_description_file) as input_file:
            init_string = input_file.read()
            split = init_string.split("111")
            machine_info = split[0]
            transitions = split[1]
            inputtape = split[2]
            split_machine = machine_info.split("1")
            print("**************Prime Turing Machine**************")
            print("\nUsing the following metadata:")
            print(machine_info)
            print("\nUsing the following transitions:")
            print(transitions)

            if len(split_machine) != 7:
                raise ValueError('Incorrect number of metadata fields')
            self.states = split_machine[0]
            self.tape_symbols = split_machine[1]
            self.input_symbols = split_machine[2]
            self.blank_symbol = split_machine[3]
            self.current_state = split_machine[4]
            self.accept_state = split_machine[5]
            self.reject_state = split_machine[6]

        self.transition_table = TransitionTable()

        print("\nTransition table: ")
        print("st1\tsym1\tst2\tsym2\tdir")

        if transitions:
            split_transitions = transitions.split("11")
            for transition in split_transitions:
                self.transition_table.add_transition(Transition.create_from_string(transition))
        self.tape = Tape(inputtape.split("1"), self.blank_symbol)
Пример #4
0
def test_set_string_empty_tape_left_left_right_a():
    tape = Tape('B', ['a', 'b', 'X', 'B'], [])
    tape.move_left()
    tape.move_left()
    tape.move_right()
    tape.set_content('a')
    assert "(['B', 'a'])@1" == str(tape)
Пример #5
0
 def __init__(self, initial):
     self.__acceptance = ["halt", "halt-accept"]
     self.__rejection = ["halt-reject"]
     self.__current = initial
     self.__tape = Tape()
     self.__status = {}
     self.__steps = 0
Пример #6
0
def test_set_content_empty_tape_left_left_right():
    tape = Tape('B', ['a', 'b', 'X', 'B'], [])
    tape.move_left()
    tape.move_left()
    tape.move_right()
    tape.set_content('a')
    assert tape.get_content() == 'a'
    assert tape.position == 1
Пример #7
0
 def __init__(self):
     self.CNF = Configurator()
     self.ConfData = self.CNF.getConfigData()
     self.WL = WriterLog(self.ConfData['logfile']['filepath'],
                         self.ConfData['logfile']['filename'])
     self.TP = Tape(self.ConfData['tape']['filepath'],
                    self.ConfData['tape']['filename'],
                    self.ConfData['tape']['separator'])
     self.TP.readInput()
Пример #8
0
 def random_matching_tape(self, ctx: AssertionCtx) -> Tape:
     for var in self._used_variables:
         if var not in ctx.bound_vars:
             ctx.bound_vars[var] = ctx.random_biased_byte()
     data: List[int] = []
     for cell in self._cells:
         data.append(cell.random_matching(ctx))
     tape = Tape(self._offset_of_current, data, False, True)
     self.apply_bounds_to_tape(tape)
     return tape
Пример #9
0
 def __init__(self, machine_config, tape_content):
     self.input_alphabet = machine_config[0]
     self.tape_alphabet = machine_config[1]
     self.blank_symbol = ''.join(machine_config[2])
     self.states = machine_config[3]
     self.init_state = ''.join(machine_config[4])
     self.final_states = machine_config[5]
     self.qnt_tapes = int(''.join(machine_config[6]))
     self.transictions = machine_config[7:]
     self.tape_content = tape_content
     self.tape = Tape(self.tape_content, self.blank_symbol)
Пример #10
0
def run_diagnostic(states, start_state, iterations):
    tape = Tape()

    next_state = start_state

    for i in range(iterations):
        next_steps = states[next_state].eval(tape.mem_value)
        tape.mark_pos(next_steps[0])
        tape.shift(next_steps[1])
        next_state = next_steps[2]

    return tape
    def simulate(self, tape_input, print_configurations=False):
        self.state = self.start_state
        tape = Tape(tape_input, self.blank_symbol)
        while not self._final_state():
            if print_configurations:
                tape.print_configuration(self.state)

            try:
                self._step(tape)
            except KeyError as error:
                print(error)
                return
        print("Turing Machine halted in an Accepting state")
Пример #12
0
 def __init__(self,
              initial_state,
              states,
              tapes=[Tape()],
              is_deterministic=True):
     self.tapes = tapes
     self.is_deterministic = is_deterministic
     self.states = dict()
     for state, transitions in states.items():
         new_state = State(state, self, transitions)
         self.states[state] = new_state
     self.state = self.states[initial_state]
     self.traversed_transitions = []
Пример #13
0
def run():
    ctx = nufhe.Context()
    secret_key, cloud_key = ctx.make_key_pair()
    vm = ctx.make_virtual_machine(cloud_key)

    # Create tape
    # Create VM
    # Execute instruction
    # Get output tape encrypted
    # Decrypt tape to get execution results

    tape = Tape()

    # Create tape of size n

    n = 2

    indices = []  # Encrypt indices before feeding into VM
    for x in range(n):
        tape.add_cell(Number.from_plaintext(0, ctx, secret_key))
        indices.append(Number.from_plaintext(x, ctx, secret_key))

    utils.logic = vm
    utils.flag = Number.from_plaintext(1, ctx, secret_key,
                                       size=1)  # Flag for conditions
    utils.one = Number.from_plaintext(1, ctx, secret_key, size=1)  # A one
    utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1)  # A zero
    utils.data_ptr = Number.from_plaintext(0, ctx,
                                           secret_key)  # Cell to perform op on

    blind_machine = VirtualMachine(tape, indices)

    # Add 1 instruction
    """for x in range(3):
        inc_data_ptr = Number.from_plaintext(0, ctx, secret_key)
        inc_data_cell = Number.from_plaintext(1, ctx, secret_key)

        blind_machine.step(inc_data_ptr, inc_data_cell)
    """

    #print(utils.one + utils.one)

    A = 129
    B = 5

    sum = Number.from_plaintext(A, ctx, secret_key) + Number.from_plaintext(
        B, ctx, secret_key)

    print(sum.decrypt(ctx, secret_key))
    print(A, "+", B, "=", sum.decrypt(ctx, secret_key, decimal=True))
Пример #14
0
    def setUp(self):
        ctx = FakeContext()
        secret_key = ctx.generate_keys()

        tape = Tape()
        tape_indices = tape.generate_tape(2, ctx, secret_key)

        utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1)
        utils.one = Number.from_plaintext(1, ctx, secret_key, size=1)
        utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1)

        # Initial state of machine

        data_ptr = Number.from_plaintext(0, ctx, secret_key)
        instruction_ptr = Number.from_plaintext(0, ctx, secret_key)

        # Defines instructions
        
        inc_data_ptr = Number.from_plaintext(1, ctx, secret_key)
        inc_data_cell = Number.from_plaintext(2, ctx, secret_key)
        dec_data_ptr = Number.from_plaintext(3, ctx, secret_key)
        dec_data_cell = Number.from_plaintext(4, ctx, secret_key)
        mark_loop = Number.from_plaintext(5, ctx, secret_key)
        loop_back = Number.from_plaintext(6, ctx, secret_key)


        instruction_set = {
            "+":inc_data_cell,
            "-":dec_data_cell,
            ">":inc_data_ptr,
            "<":dec_data_ptr,
            "[":mark_loop,
            "]":loop_back
        }

        instructions, instruction_indices = VirtualMachine.compile("++[>+++<-]", instruction_set, ctx, secret_key)
            
        self.blind_machine = VirtualMachine(
                tape,
                tape_indices,
                instruction_indices,
                instruction_set,
                instructions,
                instruction_ptr,
                data_ptr
        )

        self.context = ctx
        self.secret_key = secret_key
        self.tape = tape
Пример #15
0
def increment(word, verbose=False):
    tape = Tape(word, '|')
    states = [
                State("s0", StateType.Start),
                State("s1", StateType.Empty),
                State("sf", StateType.Final)
             ]

    transitions = [
                     Transition("s0", "$", "s1", "$", Direction.Right),
                     Transition("s1", "|", "s1", "|", Direction.Right),
                     Transition("s1", "#", "sf", "|", Direction.Neutral)
                  ]

    return TuringMachine(states, transitions, tape, verbose)
Пример #16
0
def run(code, tape_size=2):
    ctx = NUFHEContext()
    #ctx = FakeContext()

    secret_key = ctx.generate_keys()

    # Create tape with size of 2

    tape = Tape()
    tape_indices = tape.generate_tape(tape_size, ctx, secret_key)

    utils.flag = Number.from_plaintext(1, ctx, secret_key, size=1)
    utils.one = Number.from_plaintext(1, ctx, secret_key, size=1)
    utils.zero = Number.from_plaintext(0, ctx, secret_key, size=1)

    # Initial state of machine

    data_ptr = Number.from_plaintext(0, ctx, secret_key)
    instruction_ptr = Number.from_plaintext(0, ctx, secret_key)

    # Defines instructions

    inc_data_ptr = Number.from_plaintext(1, ctx, secret_key)
    inc_data_cell = Number.from_plaintext(2, ctx, secret_key)
    dec_data_ptr = Number.from_plaintext(3, ctx, secret_key)
    dec_data_cell = Number.from_plaintext(4, ctx, secret_key)
    mark_loop = Number.from_plaintext(5, ctx, secret_key)
    loop_back = Number.from_plaintext(6, ctx, secret_key)

    instruction_set = {
        "+": inc_data_cell,
        "-": dec_data_cell,
        ">": inc_data_ptr,
        "<": dec_data_ptr,
        "[": mark_loop,
        "]": loop_back
    }

    instructions, instruction_indices = VirtualMachine.compile(
        code, instruction_set, ctx, secret_key)

    blind_machine = VirtualMachine(tape, tape_indices, instruction_indices,
                                   instruction_set, instructions,
                                   instruction_ptr, data_ptr)

    blind_machine.run()

    pprint.pprint(tape.decrypt_tape(secret_key))
Пример #17
0
 def __init__(self,
              tape="",
              blank_symbol=" ",
              initial_state="",
              final_states=None,
              transition_function=None):
     self.__tape = Tape(tape)
     self.__head_position = 0
     self.__blank_symbol = blank_symbol
     self.__current_state = initial_state
     if transition_function == None:
         self.__transition_function = {}
     else:
         self.__transition_function = transition_function
     if final_states == None:
         self.__final_states = set()
     else:
         self.__final_states = set(final_states)
Пример #18
0
def main1():
    print(
        "\nTuring machine recognizes whether or not the number of 0s is a power of 2."
    )
    st = '0000000000000000000000'
    tape1 = Tape(st, '0x')
    print("\nInput string:")
    print(st)
    states = [
        State('q1', StateType.Start),
        State('q2', StateType.Empty),
        State('q3', StateType.Empty),
        State('q4', StateType.Empty),
        State('q5', StateType.Empty),
        State('qa', StateType.Accept),
        State('qr', StateType.Reject)
    ]
    transitions = [
        Transition('q1', '$', 'q1', '$', Direction.Right),
        Transition('q1', '0', 'q2', '#', Direction.Right),
        Transition('q1', '#', 'qr', '#', Direction.Right),
        Transition('q1', 'x', 'qr', 'x', Direction.Right),
        Transition('q2', 'x', 'q2', 'x', Direction.Right),
        Transition('q2', '#', 'qa', '#', Direction.Right),
        Transition('q2', '0', 'q3', 'x', Direction.Right),
        Transition('q3', 'x', 'q3', 'x', Direction.Right),
        Transition('q3', '#', 'q5', '#', Direction.Left),
        Transition('q3', '0', 'q4', '0', Direction.Right),
        Transition('q4', '0', 'q3', 'x', Direction.Right),
        Transition('q4', 'x', 'q4', 'x', Direction.Right),
        Transition('q4', '#', 'qr', '#', Direction.Right),
        Transition('q5', '#', 'q2', '#', Direction.Right),
        Transition('q5', '0', 'q5', '0', Direction.Left),
        Transition('q5', 'x', 'q5', 'x', Direction.Left)
    ]
    tm = TuringMachine(states, transitions, tape1)
    tm.process1()
    if (tm.current_state.type == StateType.Accept):
        print('\nAccepting')
    if (tm.current_state.type == StateType.Reject):
        print('\nRejecting')
    pass
    def __init__(self,
                 nb_of_states=config.NB_OF_STATES,
                 nb_of_symbols=config.NB_OF_SYMBOLS,
                 init_state=0,
                 init_tape_length=config.TOTAL_ENCODING_LENGTH):

        self.nb_of_states = nb_of_states
        self.nb_of_symbols = nb_of_symbols

        self.init_state = init_state
        self.current_state = init_state
        self.tape = Tape(nb_of_symbols, init_tape_length)

        # [old_state][symbon_read] => ( symbol_to_write, movement, new_state )
        #self.action_table = [[ ( 0, '', 0 ) ] * nb_of_symbols ] * nb_of_states # Problem = works by reference
        self.action_table = []
        for old_state in range(nb_of_states):
            self.action_table.append([])
            for symbol_read in range(nb_of_symbols):
                self.action_table[old_state].append((0, '', 0))
Пример #20
0
def run(args: Args, io: Io) -> None:
    program = None
    try:
        load_start_time = time.time()
        source_file = SourceFile(args)
        code = parse.source(source_file, args)
        tape = Tape(0, [], True, False)
        program = Program(tape, code, io)
        program_start_time = time.time()
        logger.info('Took ' +
                    str(round(program_start_time - load_start_time, 2)) +
                    's to load program')
        if args.prop_tests:
            run_property_tests(args, cast(Program, program))
        else:
            run_normally(cast(Program, program))
        io.reset()
    except (ProgramError, ParseError) as e:
        if args.expect_fail:
            return
        else:
            raise
    finally:
        if program:
            program_end_time = time.time()
            input_time = io.time_waiting_for_input()
            program_time = program_end_time - program_start_time - input_time
            logger.info('Took ' + str(round(program_time, 2)) +
                        's to run the program' + ' (plus ' +
                        str(round(input_time, 2)) + 's waiting for input)')
            logger.info('Ran ' + str(program.emulated_ops) +
                        ' virtual brainfuck operations')
            logger.info('Ran ' + str(program.real_ops) +
                        ' real constant time operations')
            if not args.prop_tests:
                logger.info('Tape: ' + str(tape))
    if args.expect_fail:
        error = UnexpectedSuccessError('Succeeded unexpectedly')
        if program:
            error.tape = program.tape
        raise error
Пример #21
0
def main():
    (options, args) = parse_args()
    cardsFilePath = args[0]
    tape = Tape(options.defaultValue, options.tapeSize)
    maxIterations = options.maxIterations
    with open(cardsFilePath, "r") as handle:
        cards = json.load(handle)

    currentState = "start"
    iterationCount = 0
    while (currentState != "halt") and (iterationCount < maxIterations):
        instructions = cards[currentState][tape.read()]
        tape.write(instructions["write"])
        tape.move(instructions["move"])
        currentState = instructions["next"]
        print currentState
        print tape.statusToString()
        iterationCount += 1

    if currentState != "halt":
        print "maximum iterations exceeded!"
Пример #22
0
def subtract(word, verbose=False):
    tape = Tape(word, '|&')
    states = [
                State("s0", StateType.Start),
                State("s1", StateType.Empty),
                State("s2", StateType.Empty),
                State("s3", StateType.Empty),
                State("s4", StateType.Empty),
                State("s5", StateType.Empty),
                State("s6", StateType.Empty),
                State("s7", StateType.Empty),
                State("s8", StateType.Empty),
                State("sf", StateType.Final)
             ]

    transitions = [
                     Transition("s0", "$", "s0", "$", Direction.Right),
                     Transition("s0", "#", "sf", "#", Direction.Neutral),
                     Transition("s0", "|", "s1", "|", Direction.Right),
                     Transition("s1", "|", "s1", "|", Direction.Right),
                     Transition("s1", "#", "s2", "#", Direction.Right),
                     Transition("s2", "#", "s2", "#", Direction.Right),
                     Transition("s2", "|", "s3", "|", Direction.Right),
                     Transition("s3", "|", "s4", "|", Direction.Left),
                     Transition("s3", "#", "s6", "#", Direction.Left),
                     Transition("s4", "|", "s5", "#", Direction.Left),
                     Transition("s5", "#", "s5", "#", Direction.Left),
                     Transition("s5", "|", "s2", "#", Direction.Right),
                     Transition("s5", "$", "s2", "$", Direction.Right),
                     Transition("s6", "|", "s7", "#", Direction.Left),
                     Transition("s7", "#", "s7", "#", Direction.Left),
                     Transition("s7", "$", "sf", "$", Direction.Neutral),
                     Transition("s7", "|", "s8", "#", Direction.Left),
                     Transition("s8", "|", "s8", "|", Direction.Left),
                     Transition("s8", "$", "sf", "$", Direction.Neutral)
                  ]

    return TuringMachine(states, transitions, tape, verbose)
Пример #23
0
 def __init__(self, screen):
     self.screen = screen
     self.tape = Tape()
from turing_machine import TuringMachine
from state import State, StateType
from transition import Transition
from direction import Direction
from tape import Tape

# Simple test to check whether the turing machine is working
tape = Tape('|||', '|')
states = [
    State("s0", StateType.Start),
    State("s1", StateType.Empty),
    State("sf", StateType.Final)
]

transitions = [
    Transition("s0", "$", "s1", "$", Direction.Right),
    Transition("s1", "|", "s1", "|", Direction.Right),
    Transition("s1", "#", "sf", "|", Direction.Neutral)
]

tm = TuringMachine(states, transitions, tape)
tm.process()
print(tm.get_tape())
from turing_machine import TuringMachine
from state import State, StateType
from transition import Transition
from direction import Direction
from tape import Tape

# Luis Gerson Rodriguez Sanchez
# Turin Machine 
# Run a multiplication turin Machine 
# Theory of computation 
# December 3 rd 2020 
print('insert your tape with a 0 at the END !!!!')
in_User=input(); 
tape = Tape(in_User, '')
states = [
            State("s0", StateType.Start),
            State("s1", StateType.Empty),
            State("s2", StateType.Empty),
            State("s3", StateType.Empty),
            State("s4", StateType.Empty),
            State("s5", StateType.Empty),
            State("s6", StateType.Empty),
            State("sf", StateType.Final)
         ]
 
transitions = [
                 Transition("s0", "S", "s0", "S", Direction.Right),
                 Transition("s0", "0", "s6", "S", Direction.Right),
                 Transition("s0", "1", "s1", "S", Direction.Right),
                 Transition("s1", "1", "s1", "1", Direction.Right),
                 Transition("s1", "0", "s2", "0", Direction.Right),
Пример #26
0
 def _init_tapes(self):
     tapes = []
     for i in range(0, self._fitas):
         tapes.append(Tape(self._conteudo[i], self._simb_branco))
     return tapes
Пример #27
0
from turing_machine import TuringMachine
from state import State, StateType
from transition import Transition
from direction import Direction
from tape import Tape

tape = Tape('aaabbb', 'abxy')
states = [
    State("s0", StateType.Start),
    State("s1", StateType.Empty),
    State("s2", StateType.Empty),
    State("sf", StateType.Final)
]

transitions = [
    Transition("s0", "$", "s0", "$", Direction.Right),
    Transition("s0", "a", "s1", "x", Direction.Right),
    Transition("s1", "a", "s1", "a", Direction.Right),
    Transition("s1", "b", "s2", "y", Direction.Left),
    Transition("s2", "a", "s2", "a", Direction.Left),
    Transition("s2", "x", "s0", "x", Direction.Right),
    Transition("s1", "y", "s1", "y", Direction.Right),
    Transition("s2", "y", "s2", "y", Direction.Left),
    Transition("s0", "y", "sf", "y", Direction.Neutral)
]

tm = TuringMachine(states, transitions, tape)
tm.process(verbose=True)
print(tm.get_tape())
Пример #28
0
    initial_state = lines[4]
    final_states = lines[5].split()
    number_of_tapes = lines[6]
    transitions = []
    '''laco que pegara as transicoes'''
    for i in range(7, number_of_lines):
        transitions.append(lines[i].split())

    tape_list = []  #lista de fitas
    number_of_args = 2 + int(number_of_tapes)
    '''laco de repeticao que construira a lista de fitas'''
    for i in range(2, number_of_args):
        if len(
                sys.argv
        ) >= i + 1:  # caso tenha simbolosnumber_of_tapesnumber_of_tapesnumber_of_tapesnumber_of_tapesnumber_of_tapesnumber_of_tapesnumber_of_tapes, ele coloca na fita
            tape_list.append(Tape(whitespace, tape_alphabet,
                                  list(sys.argv[i])))
        else:  # caso nao tenha, coloca simbolos que representam o branco
            tape_list.append(Tape(whitespace, tape_alphabet, [whitespace]))
    '''Instancia a turing machine'''
    tm = turing_machine(states, final_states, initial_state, transitions,
                        whitespace, tape_list)
    '''executa a turing machine'''
    result = tm.run()

    if result[0] == 1:
        print("Aceitou")
    else:
        print("Rejeitou")
    print(result[1])
Пример #29
0
from turing_machine import TuringMachine
from direction import Direction
from state import StateType, State
from tape import Tape
from transition import Transition

inp = int(input("Enter decimal digit: "))
word = ""
for i in range(inp):
    word += '1'
tape = Tape(word, "10x")
states = [
    State("s0", StateType.Start),
    State("s1", StateType.Empty),
    State("s2", StateType.Empty),
    State("s3", StateType.Empty),
    State("s4", StateType.Empty),  #getting rid of x in tape
    State("sf", StateType.Final)
]

transitions = [
    Transition('s0', '$', 's0', '$', Direction.Right),
    Transition('s0', '1', 's1', 'x', Direction.Left),
    Transition('s1', '$', 's2', '1', Direction.Right),
    Transition('s2', '1', 's2', '1', Direction.Right),
    Transition('s2', '0', 's2', '0', Direction.Right),
    Transition('s2', 'x', 's3', 'x', Direction.Right),
    Transition('s3', 'x', 's3', 'x', Direction.Right),
    Transition('s3', '1', 's1', 'x', Direction.Left),
    Transition('s1', '1', 's1', '0', Direction.Left),
    Transition('s1', 'x', 's1', 'x', Direction.Left),
Пример #30
0
    def __call__(self):
        print('Start testing!')

        test_sequences = iter(self.sequences)
        sequence = next(test_sequences)

        # create tapes
        input_tape = Tape(1, self.total_length, self.params.num_symbols, self.params.in_move_table,
                          initial=sequence)
        mem_tape = Tape(1, self.total_length, self.params.rnn_hidden, self.params.mem_move_table)
        output_tape = Tape(1, self.params.max_length, self.params.num_symbols, self.params.out_move_table,
                           initial=np.ones((1, self.params.max_length, self.params.num_symbols)) * -1)

        step = np.zeros((1, 1, self.params.num_symbols + self.params.rnn_hidden + 3))
        target = np.zeros((1, 1, self.params.num_symbols))
        state = np.zeros((2, 1, self.params.rnn_hidden))

        last_in_moves = np.ones((1, 1))
        last_mem_moves = np.ones((1, 1))
        last_out_moves = np.ones((1, 1))

        input_tape.print_tape()

        for i in range(sequence.shape[1]):
            print("=======================")
            print("step : ", i)
            # read input, memory from tape
            step_input = input_tape.read_tape()
            step_memory = mem_tape.read_tape()
            last_moves = np.concatenate((last_in_moves, last_mem_moves, last_out_moves), axis=1)
            step_concat = np.concatenate((step_input, step_memory, last_moves), axis=1)
            step[:, 0, :] = step_concat
            target[:, 0, :] = sequence[:, i, :]

            prediction, moves, hidden, state_tuple = self.sess.run([self.model.prediction, self.model.moves,
                                                                    self.model.hidden, self.model.state],
                                                                   {self.input: step, self.state: state,
                                                                    self.target: target})

            # update state
            state[0] = state_tuple[0]
            state[1] = state_tuple[1]

            # sample moves from logits
            # in_sample = sample(moves[0][:, 0, :])
            # mem_sample = sample(moves[1][:, 0, :])
            # out_sample = sample(moves[2][:, 0, :])
            in_sample = np.argmax(moves[0][:, 0, :], axis=1)
            mem_sample = np.argmax(moves[1][:, 0, :], axis=1)
            out_sample = np.argmax(moves[2][:, 0, :], axis=1)

            in_move = last_in_moves[:, 0] = input_tape.index_to_moves(in_sample)
            mem_move = last_mem_moves[:, 0] = mem_tape.index_to_moves(mem_sample)
            out_move = last_out_moves[:, 0] = output_tape.index_to_moves(out_sample)

            # if out_move, write to output_tape
            output_tape.write_tape(prediction[:, 0, :], out_move)

            # write memory
            mem_tape.write_tape(hidden[:, 0, :])

            # move ptrs
            input_tape.move_ptr(in_move)
            mem_tape.move_ptr(mem_move)
            output_tape.move_ptr(out_move)

            print("in_logits :", moves[0], ", in_move :", in_move, ", in_pos :", input_tape.get_ptr())
            print("mem_logits :", moves[1], ", mem_move :", mem_move, ", mem_pos :", mem_tape.get_ptr())
            print("out_logits :", moves[2], ", out_move :", out_move, ", out_pos :", output_tape.get_ptr())

            if out_move[0] == 1:
                print("prediction")
                print(prediction[:, 0, :])
                print("==> ", np.argmax(prediction[:, 0, :], axis=1))

            print("=======================")

        output_tape.print_max_indexes()