Example #1
0
def run_options(ttable, options, stats=None):
  """Run the Accelerated Turing Machine Simulator, running a few simple filters
  first and using intelligent blockfinding."""
  if options.steps == 0:
    options.steps = INF

  if options.time:
    # Note: We cannot practically use time.clock() because it often
    # only has 10ms granularity.
    start_time = time.time()
    pre_sim_end_time = start_time + (options.time / 10)
    end_time = start_time + options.time
  else:
    start_time = end_time = None

#  ## Test for quickly for infinite machine
#  if Reverse_Engineer_Filter.test(ttable):
#    return Exit_Condition.INFINITE, ("Reverse_Engineer",)
#
  ## Construct the Macro Turing Machine (Backsymbol-k-Block-Macro-Machine)
  m = Turing_Machine.make_machine(ttable)
#
  block_size = options.block_size
#  if not block_size:
#    # If no explicit block-size given, use inteligent software to find one
#    block_size = Block_Finder.block_finder(m, options,
#                                           end_time=pre_sim_end_time)
#
#  # Do not create a 1-Block Macro-Machine (just use base machine)
#  if block_size != 1:
#    m = Turing_Machine.Block_Macro_Machine(m, block_size)
#  if options.backsymbol:
#    m = Turing_Machine.Backsymbol_Macro_Machine(m)

#  if options.ctl:
#    CTL_config = setup_CTL(m, options.bf_limit1, end_time=pre_sim_end_time)

#    # Run CTL filters unless machine halted
#    if CTL_config:
#      CTL_config_copy = copy.deepcopy(CTL_config)
#      if CTL1.CTL(m, CTL_config_copy, end_time=pre_sim_end_time):
#        return Exit_Condition.INFINITE, ("CTL_A*",)
#
#      CTL_config_copy = copy.deepcopy(CTL_config)
#      if CTL2.CTL(m, CTL_config_copy, end_time=pre_sim_end_time):
#        return Exit_Condition.INFINITE, ("CTL_A*_B",)

  ## Set up the simulator
  sim = Simulator.Simulator(m, options, end_time=end_time)

  ## Run the simulator
#  while (sim.step_num < options.steps and 
#         sim.op_state == Turing_Machine.RUNNING and
#         sim.tape.compressed_size() <= options.tape_limit):
  sim.seek(options.steps)
#    if sim.op_state == Turing_Machine.TIME_OUT and sim.step_num == 0:
#      sim.op_state = Turing_Machine.RUNNING
#      sim.end_time += options.time

  # TODO(shawn): pass the stats object into sim so we don't have to copy.
  if stats:
    stats.num_rules += len(sim.prover.rules)
    stats.num_recursive_rules += sim.prover.num_recursive_rules
    stats.num_collatz_rules += sim.prover.num_collatz_rules
    stats.num_failed_proofs += sim.prover.num_failed_proofs

  ## Resolve end conditions and return relevent info.
  if sim.tape.compressed_size() > options.tape_limit:
    return Exit_Condition.OVER_TAPE, (sim.tape.compressed_size(), sim.step_num)

  elif sim.op_state == Turing_Machine.TIME_OUT:
    return Exit_Condition.TIME_OUT, (time.time() - start_time, sim.step_num)

  elif sim.op_state == Turing_Machine.RUNNING:
    return Exit_Condition.MAX_STEPS, (sim.step_num,)

  elif sim.op_state == Turing_Machine.HALT:
    return Exit_Condition.HALT, (sim.step_num, sim.get_nonzeros())

  elif sim.op_state == Turing_Machine.INF_REPEAT:
    return Exit_Condition.INFINITE, (sim.inf_reason,)

  elif sim.op_state == Turing_Machine.UNDEFINED:
    on_symbol, on_state = sim.op_details[0][:2]
    return Exit_Condition.UNDEF_CELL, (on_state, on_symbol,
                                       sim.step_num, sim.get_nonzeros())

  raise Exception, (sim.op_state, ttable, sim)
Example #2
0
    options.verbose_block_finder = True

  if options.loops and options.print_loops > options.loops:
    options.print_loops = options.loops

  if len(args) < 1:
    parser.error("Must have at least one argument, machine_file")
  filename = args[0]

  if len(args) >= 2:
    try:
      line = int(args[1])
    except ValueError:
      parser.error("line_number must be an integer.")
    if line < 1:
      parser.error("line_number must be >= 1")
  else:
    line = 1

  if options.csv:
    table = Input_CSV_Machine.read_csv_to_table(filename)
    machine = Input_CSV_Machine.convert_table_to_machine(table)
  else:
    ttable = IO.load_TTable_filename(filename, line)
    machine = Turing_Machine.make_machine(ttable)
    if not options.quiet:
      Turing_Machine.print_machine(machine)

  run(machine, options.block_size, options.backsymbol, options.prover,
               options.recursive, options)
Example #3
0
    def tape_code(self, args):
        self.stdout.write("\n")
        self.stdout.flush()

        self.swap_history()
        tape_state_string = raw_input("   Tape: ")
        self.swap_history()

        tape_state_tokens = tape_state_string.split()
        num_tokens = len(tape_state_tokens)

        for i in xrange(num_tokens):
            token = tape_state_tokens[i]
            if token[0] == "(" and token[-1] == ">":
                temp = token.replace(")", ") ")
                tape_state_tokens[i:i + 1] = temp.split()
                break
            elif token[0] == "<" and token[-1] == ")":
                temp = token.replace("(", " (")
                tape_state_tokens[i:i + 1] = temp.split()
                break

        tape_parse = [
            tape_state_token.split("^")
            for tape_state_token in tape_state_tokens
        ]

        tape_length = 0

        state_index = -1
        back_index = -1

        token_length = len(tape_parse)
        if token_length == 0:
            print
            return

        block_size = len(tape_parse[0][0])

        for i in xrange(token_length):
            token = tape_parse[i]
            if len(token) == 2:
                tape_length += 1
                if len(token[0]) != block_size:
                    print "\nTape symbol lengths don't match.\n"
                    return
                if token[0].translate(None,
                                      string.digits[:self.num_symbols]) != "":
                    print "\nSome of '%s' isn't in '%s'.\n" % (
                        token[0], string.digits[:self.num_symbols])
                    return
                if block_size == 1:
                    new_symbol = int(token[0])
                else:
                    new_symbol = Turing_Machine.Block_Symbol(
                        [int(c) for c in token[0]])
                token[0] = new_symbol
            elif token[0][0] == "(":
                if len(token[0]) != block_size + 2:
                    print "\nBack symbol length doesn't match tape symbol length.\n"
                    return
                back_index = i
            elif token[0][0] == "<":
                state_index = i
                tape_dir = 0
            elif token[0][-1] == ">":
                state_index = i
                tape_dir = 1
            else:
                print "\nUnrecognized tape entry, '%s'.\n" % (token, )
                return

        if back_index > -1:
            if tape_dir == 0:
                if state_index > back_index:
                    print "\nState and backsymbol are out of order.\n"
                    return
                elif state_index + 1 != back_index:
                    print "\nState and backsymbol aren't together.\n"
                    return
            else:
                if state_index < back_index:
                    print "\nState and backsymbol are out of order.\n"
                    return
                elif state_index - 1 != back_index:
                    print "\nState and backsymbol aren't together.\n"
                    return
            new_back_symbol = tape_parse[back_index][0][1:-1]
            if new_back_symbol.translate(
                    None, string.digits[:self.num_symbols]) != "":
                print "\nSome of back symbol, '%s', isn't in '%s'.\n" % (
                    new_back_symbol, string.digits[:self.num_symbols])
                return
            if block_size == 1:
                new_back_symbol = int(new_back_symbol)
            else:
                new_back_symbol = Turing_Machine.Block_Symbol(
                    [int(c) for c in new_back_symbol])
        else:
            new_back_symbol = ""

        new_tape = Tape.Chain_Tape()
        new_tape.dir = tape_dir

        new_tape.tape = [[], []]
        for i in xrange(token_length):
            if i < state_index and (back_index == -1 or i < back_index):
                if tape_parse[i][1] == "Inf":
                    expo = Tape.INF
                elif tape_parse[i][1][0] == "(":
                    expo = Expression_from_string(tape_parse[i][1])
                else:
                    if not tape_parse[i][1].isdigit():
                        print "\nTape exponent, '%s', isn't a number.\n" % (
                            token[1], )
                        return
                    expo = int(tape_parse[i][1])
                new_tape.tape[0].append(
                    Tape.Repeated_Symbol(tape_parse[i][0], expo))
            if i > state_index and (back_index == -1 or i > back_index):
                if tape_parse[i][1] == "Inf":
                    expo = Tape.INF
                elif tape_parse[i][1][0] == "(":
                    expo = Expression_from_string(tape_parse[i][1])
                else:
                    if not tape_parse[i][1].isdigit():
                        print "\nTape exponent, '%s', isn't a number.\n" % (
                            token[1], )
                        return
                    expo = int(tape_parse[i][1])
                new_tape.tape[1].append(
                    Tape.Repeated_Symbol(tape_parse[i][0], expo))

        new_tape.tape[1].reverse()
        new_tape.displace = 0

        if back_index >= 0:
            backsymbol = True
        else:
            backsymbol = False

        if self.sim_options.block_size == block_size and self.sim_options.backsymbol == backsymbol:
            same_sim = True
        else:
            self.sim_options.block_size = block_size
            self.sim_options.backsymbol = backsymbol
            same_sim = False

        if tape_dir == 0:
            new_state = tape_parse[state_index][0][1]
        else:
            new_state = tape_parse[state_index][0][0]

        if new_state.translate(None, states[:self.num_states]) != "":
            print "\nState, '%s', not one of '%s'.\n" % (
                new_state, states[:self.num_states])
            return

        new_state = Turing_Machine.Simple_Machine_State(
            states.index(new_state))

        if self.sim_options.backsymbol:
            new_state = Turing_Machine.Backsymbol_Macro_Machine_State(
                new_state, new_back_symbol)

        # Construct Machine (Backsymbol-k-Block-Macro-Machine)
        m = Turing_Machine.make_machine(self.TTable)

        # If no explicit block-size given set it to 1
        if not self.sim_options.block_size:
            self.sim_options.block_size = 1

        # Do not create a 1-Block Macro-Machine (just use base machine)
        if self.sim_options.block_size != 1:
            m = Turing_Machine.Block_Macro_Machine(m,
                                                   self.sim_options.block_size)
        if self.sim_options.backsymbol:
            m = Turing_Machine.Backsymbol_Macro_Machine(m)

        if self.sim.prover == None:
            self.sim_options.prover = False
        else:
            self.sim_options.prover = True

        if same_sim:
            self.sim_prover_save = self.sim.prover

        self.sim = Simulator.Simulator(m,
                                       options=self.sim_options,
                                       verbose_prefix="",
                                       init_tape=True)

        if same_sim:
            self.sim.prover = self.sim_prover_save

        self.sim.state = new_state
        self.sim.dir = tape_dir
        self.sim.tape = new_tape

        self.sim_prover_save = None

        self.stdout.write("\n")
        self.sim.verbose_print()
Example #4
0
def recur_TM(TTable, block_size, back, prover, recursive, options):
    # Construct Machine (Backsymbol-k-Block-Macro-Machine)
    m = Turing_Machine.make_machine(TTable)

    # If no explicit block-size given, use inteligent software to find one
    if not block_size:
        block_size = Block_Finder.block_finder(m, options)

    #if not options.quiet:
    #  Turing_Machine.print_machine(m)

    # Do not create a 1-Block Macro-Machine (just use base machine)
    if block_size != 1:
        m = Turing_Machine.Block_Macro_Machine(m, block_size)
    if back:
        m = Turing_Machine.Backsymbol_Macro_Machine(m)

    global sim  # For debugging, especially with --manual
    sim = Simulator.Simulator(m, options)

    if options.manual:
        return  # Let's us run the machine manually. Must be run as python -i Quick_Sim.py

    groups = {}

    total_loops = 0
    # max_term_size = 100000000

    while (sim.op_state == Turing_Machine.RUNNING
           and (options.loops == 0 or total_loops < options.loops)):
        # print "%10d" % sim.step_num,"  ",sim.tape.print_with_state(sim.state)

        sim.step()

        # if sim.step_num > max_term_size:
        #   break

        if len(sim.tape.tape[0]) == 1 or len(sim.tape.tape[1]) == 1:
            min_config = strip_config(sim.state, sim.dir, sim.tape.tape)

            if len(min_config[0]) + len(min_config[-1]) <= 100:
                if min_config in groups:
                    # if len(groups[min_config]) >= 100:
                    #   groups[min_config].pop(0)

                    groups[min_config].append([
                        copy.deepcopy(sim.tape.tape[0][1:]),
                        copy.deepcopy(sim.tape.tape[1][1:]), sim.step_num
                    ])
                else:
                    groups[min_config] = [
                        [
                            copy.deepcopy(sim.tape.tape[0][1:]),
                            copy.deepcopy(sim.tape.tape[1][1:]), sim.step_num
                        ],
                    ]

        total_loops += 1

    #print "%10d" % sim.step_num,"  ",sim.tape.print_with_state(sim.state)
    #print

    sorted_keys = sorted(groups, key=lambda item: len(item[0]) + len(item[3]))

    print Output_Machine.display_ttable(TTable), "|",
    print "%5d" % len(groups)

    for min_config in sorted_keys:
        group = groups[min_config]

        recur_all = False

        if len(group) >= 4:
            print "  ", len(group), min_config

            growth = [[]
                      for i in xrange(len(group[0][0]) + len(group[0][1]) + 1)]
            for config in group:
                index = 0
                for symbol in config[0]:
                    growth[index].append(symbol.num)
                    index += 1
                for symbol in config[1]:
                    growth[index].append(symbol.num)
                    index += 1
                growth[index].append(config[2])

            recur_all = True

            for series in growth:
                print "     ", series

                (recur_found, coefs, constant) = recur_fit(series)

                if recur_found:
                    print "         success",
                    recur_print(coefs, constant)
                else:
                    print "         failure"

                recur_all = recur_all and recur_found
                print

            if recur_all:
                break

    print "  ", recur_all
    print
Example #5
0
    def init_code(self, TTable, options):
        self.readline_save = 99

        self.readline = False
        try:
            import readline
            self.readline = readline
        except ImportError:
            try:
                import pyreadline as readline
                self.readline = readline
            # if we fail both readline and pyreadline
            except ImportError:
                print "Unable to import 'readline', line editing will be limited."
        else:
            import rlcompleter
            if sys.platform == 'darwin':
                readline.parse_and_bind("bind ^I rl_complete")
            else:
                readline.parse_and_bind("tab: complete")

        self.set_cmdnum(1)

        self.record_hist = True
        self.hist_cmd = False

        self.misc_header = "Unimplemented commands"

        self.TTable = TTable

        self.sim_options = options

        # Construct Machine (Backsymbol-k-Block-Macro-Machine)
        m = Turing_Machine.make_machine(self.TTable)

        if not self.sim_options.quiet:
            Turing_Machine.print_machine(m)

        # If no explicit block-size given set it to 1
        if not self.sim_options.block_size:
            self.sim_options.block_size = 1

        # Do not create a 1-Block Macro-Machine (just use base machine)
        if self.sim_options.block_size != 1:
            m = Turing_Machine.Block_Macro_Machine(m,
                                                   self.sim_options.block_size)
        if self.sim_options.backsymbol:
            m = Turing_Machine.Backsymbol_Macro_Machine(m)

        self.sim = Simulator.Simulator(m,
                                       options=self.sim_options,
                                       verbose_prefix="",
                                       init_tape=True)

        self.sim_prover_save = None

        self.num_states = self.sim.machine.num_states
        self.num_symbols = self.sim.machine.num_symbols

        print "Welcome to the machine!\n"

        self.sim.verbose_print()