qbf.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/python
  2. # A Quantum Brainfuck interpreter
  3. # For now, very basic with no error checking
  4. # Implements extra commands:
  5. # '1' initializes the current cell to 1
  6. # '0' initializes the current cell to 0
  7. # '#' outputs the probabilities of all the different possible states
  8. import qubit
  9. import sys
  10. DEBUG = True # Adds some extra helpful commands
  11. if len(sys.argv) != 2:
  12. print "Usage:", sys.argv[0], "<filename>"
  13. raise SystemExit
  14. infile = file(sys.argv[1])
  15. program = infile.read()
  16. memory = qubit.Register(2)
  17. qubit_positions = range(2)
  18. mp = 0
  19. cp = 0
  20. while cp < len(program):
  21. cmd = program[cp]
  22. if cmd == '<':
  23. mp -= 1
  24. elif cmd == '>':
  25. mp += 1
  26. if mp >= memory.length:
  27. qubit_positions.append(memory.length)
  28. memory.add_bit()
  29. if mp >= 20:
  30. # just a precaution, feel free to remove this
  31. print "Pointer moved right too many qubits; terminating"
  32. elif cmd == '%':
  33. qubit.Hadamard.apply(memory, [qubit_positions[mp]])
  34. elif cmd == '!':
  35. qubit.CV.apply(memory,[qubit_positions[mp],qubit_positions[mp+1]])
  36. elif cmd == '&':
  37. temp = qubit_positions[mp]
  38. qubit_positions[mp] = qubit_positions[mp+1]
  39. qubit_positions[mp+1] = temp
  40. elif cmd == '.':
  41. # Output the qubit
  42. # For now, output it as a '1' or '0' and output causes observation
  43. output = memory.observe(qubit_positions[mp])
  44. print output,
  45. elif cmd == ',':
  46. # input a qubit
  47. i = raw_input("\nPlease enter 1 or 0: ")
  48. i = int(i)
  49. assert i == 1 or i == 0
  50. memory.set(qubit_positions[mp], i)
  51. elif cmd == '[':
  52. # observe the current qubit, loop if it's 1
  53. bit = memory.observe(qubit_positions[mp])
  54. if not bit:
  55. # skip till the end of the loop
  56. bracket_level = 1
  57. while bracket_level:
  58. cp += 1
  59. if program[cp] == '[': bracket_level += 1
  60. if program[cp] == ']': bracket_level -= 1
  61. elif cmd == ']':
  62. # just go back to the matching bracket
  63. bracket_level = -1
  64. while bracket_level:
  65. cp -= 1
  66. if program[cp] == '[': bracket_level += 1
  67. if program[cp] == ']': bracket_level -= 1
  68. cp -= 1
  69. # Now, some helpful debugging commands:
  70. elif DEBUG and cmd == '1':
  71. memory.set(qubit_positions[mp], 1)
  72. elif DEBUG and cmd == '0':
  73. memory.set(qubit_positions[mp], 0)
  74. elif DEBUG and cmd == '#':
  75. # pretty print memory contents
  76. print
  77. for i in range(len(memory.contents)):
  78. print '|'+''.join([str(b) for b in qubit.n2bits(i,memory.length)])+'>',
  79. print '%.2f' % (abs(memory.contents[i])**2)
  80. else:
  81. # do nothing
  82. pass
  83. cp += 1