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