def test_superposition_of_states(): assert qapply(CNOT(0,1)*HadamardGate(0)*(1/sqrt(2)*Qubit('01') + 1/sqrt(2)*Qubit('10'))).expand() == (Qubit('01')/2 + Qubit('00')/2 - Qubit('11')/2 +\ Qubit('10')/2) assert matrix_to_qubit(represent(CNOT(0,1)*HadamardGate(0)\ *(1/sqrt(2)*Qubit('01') + 1/sqrt(2)*Qubit('10')), nqubits=2))\ == (Qubit('01')/2 + Qubit('00')/2 - Qubit('11')/2 + Qubit('10')/2)
def test_apply_represent_equality(): gates = [ HadamardGate(int(3 * random.random())), XGate(int(3 * random.random())), ZGate(int(3 * random.random())), YGate(int(3 * random.random())), ZGate(int(3 * random.random())), PhaseGate(int(3 * random.random())), ] circuit = Qubit( int(random.random() * 2), int(random.random() * 2), int(random.random() * 2), int(random.random() * 2), int(random.random() * 2), int(random.random() * 2), ) for i in range(int(random.random() * 6)): circuit = gates[int(random.random() * 6)] * circuit mat = represent(circuit, nqubits=6) states = qapply(circuit) state_rep = matrix_to_qubit(mat) states = states.expand() state_rep = state_rep.expand() assert state_rep == states
def test_superposition_of_states(): state = 1 / sqrt(2) * Qubit('01') + 1 / sqrt(2) * Qubit('10') state_gate = CNOT(0, 1) * HadamardGate(0) * state state_expanded = Qubit('01') / 2 + Qubit('00') / 2 - Qubit( '11') / 2 + Qubit('10') / 2 assert qapply(state_gate).expand() == state_expanded assert matrix_to_qubit(represent(state_gate, nqubits=2)) == state_expanded
def test_quantum_fourier(): assert QFT(0,3).decompose() == SwapGate(0,2)*HadamardGate(0)*CGate((0,), PhaseGate(1))\ *HadamardGate(1)*CGate((0,), TGate(2))*CGate((1,), PhaseGate(2))*HadamardGate(2) assert IQFT(0,3).decompose() == HadamardGate(2)*CGate((1,), RkGate(2,-2))*CGate((0,),RkGate(2,-3))\ *HadamardGate(1)*CGate((0,), RkGate(1,-2))*HadamardGate(0)*SwapGate(0,2) assert represent(QFT(0,3), nqubits=3)\ == Matrix([[exp(2*pi*I/8)**(i*j%8)/sqrt(8) for i in range(8)] for j in range(8)]) assert QFT(0, 4).decompose() #non-trivial decomposition assert qapply(QFT(0,3).decompose()*Qubit(0,0,0)).expand() ==\ qapply(HadamardGate(0)*HadamardGate(1)*HadamardGate(2)*Qubit(0,0,0)).expand()
def test_superposition_of_states(): state = 1 / sqrt(2) * Qubit("01") + 1 / sqrt(2) * Qubit("10") state_gate = CNOT(0, 1) * HadamardGate(0) * state state_expanded = ( Qubit("01") / 2 + Qubit("00") / 2 - Qubit("11") / 2 + Qubit("10") / 2 ) assert qapply(state_gate).expand() == state_expanded assert matrix_to_qubit(represent(state_gate, nqubits=2)) == state_expanded
def decompose(self): """Decomposes IQFT into elementary gates.""" start = self.args[0] finish = self.args[1] circuit = 1 for i in range((finish-start)//2): circuit = SwapGate(i+start, finish-i-1)*circuit for level in range(start, finish): for i in reversed(range(level-start)): circuit = CGate(level-i-1, RkGate(level, -i-2))*circuit circuit = HadamardGate(level)*circuit return circuit
def decompose(self): """Decomposes QFT into elementary gates.""" start = self.label[0] finish = self.label[1] circuit = 1 for level in reversed(range(start, finish)): circuit = HadamardGate(level) * circuit for i in range(level - start): circuit = CGate(level - i - 1, RkGate(level, i + 2)) * circuit #FIXME-py3k: TypeError: 'Rational' object cannot be interpreted as an integer for i in range((finish - start) / 2): circuit = SwapGate(i + start, finish - i - 1) * circuit return circuit
def test_gate(): """Test a basic gate.""" h = HadamardGate(1) assert h.min_qubits == 2 assert h.nqubits == 1 i0 = Wild('i0') i1 = Wild('i1') h0_w1 = HadamardGate(i0) h0_w2 = HadamardGate(i0) h1_w1 = HadamardGate(i1) assert h0_w1 == h0_w2 assert h0_w1 != h1_w1 assert h1_w1 != h0_w2 cnot_10_w1 = CNOT(i1, i0) cnot_10_w2 = CNOT(i1, i0) cnot_01_w1 = CNOT(i0, i1) assert cnot_10_w1 == cnot_10_w2 assert cnot_10_w1 != cnot_01_w1 assert cnot_10_w2 != cnot_01_w1
def test_compound_gates(): """Test a compound gate representation.""" circuit = YGate(0) * ZGate(0) * XGate(0) * HadamardGate(0) * Qubit('00') answer = represent(circuit, nqubits=2) assert Matrix([I / sqrt(2), I / sqrt(2), 0, 0]) == answer
def test_represent_hadamard(): """Test the representation of the hadamard gate.""" circuit = HadamardGate(0) * Qubit('00') answer = represent(circuit, nqubits=2) # Check that the answers are same to within an epsilon. assert answer == Matrix([sqrt2_inv, sqrt2_inv, 0, 0])
def test_sympy__physics__quantum__gate__HadamardGate(): from sympy.physics.quantum.gate import HadamardGate assert _test_args(HadamardGate(0))
def find_r(x, N): """ Encontra o período de x em aritimética módulo N. Essa é a parte realmente quântica da solução. Põe a primeira parte do registrador em um estado de superposição |j> |0>, com j = 0 to 2 ** n - 1, usando a porta Hadamard. Depois aplica a porta Vx e IQFT para determinar a ordem de x. """ # Calcula o número de qubits necessários n = int(math.ceil(log(N, 2))) t = int(math.ceil(2 * log(N, 2))) print("n: ", n) print("t: ", t) # Cria o registrador register = Qubit(IntQubit(0, t + n)) print("register: ", register) # Põe a segunda metade do registrado em superposição |1>|0> + |2>|0> + ... |j>|0> + ... + |2 ** n - 1>|0> print("Aplicando Hadamard...") circuit = 1 for i in reversed(list(range(n, n + t))): circuit = HadamardGate(i) * circuit circuit = qapply(circuit * register) print("Circuit Hadamard:\n", circuit.simplify()) # Calcula os valores para a primeira metade do registrador |1>|x ** 1 % N> + |2>|x ** 2 % N> + ... + |k>|x ** k % N >+ ... + |2 ** n - 1 = j>|x ** j % N> print("Aplicando Vx...") circuit = qapply(Vx(n, t, x, N) * circuit) print("Circuit Vx:\n", circuit.simplify()) # Faz a medição da primeira metade do registrador obtendo um dos [x ** j % N's] print("Medindo 0->n ...") circuit = measure_partial_oneshot(circuit, range(n)) print("Circuit 0->n:\n", circuit.simplify()) # Aplica a Transformada de Fourier Quântica Inversa na segunda metade do registrador print("Aplicando a transformada inversa...") circuit = qapply(IQFT(n, n + t).decompose() * circuit) print("Circuit IQFT:\n", circuit.simplify()) # Faz a medição da segunda metade do registrador um dos valores da transformada while ( True ): # O correto seria repetir a rotina inteira, mas é suficiente repetir a medição. # Num computador quântico real o estado colapsaria e não seria possível medi-lo novamente. print("Medindo n->n+t ...") #measurement = measure_partial_oneshot(circuit, range(n, n + t)) measurement = measure_all_oneshot(circuit) print(measurement.simplify()) if isinstance(measurement, Qubit): register = measurement elif isinstance(measurement, Mul): register = measurement.args[-1] else: register = measurement.args[-1].args[-1] print("Medicao: ", register) # Converte o qubit de binário para decimal k = 1 answer = 0 for i in range(t): answer += k * register[n + i] k = k << 1 print("Medicao: ", answer) if answer != 0: break print("2^t: ", 2**t) # Lista os termos da fração continuada fraction = continued_fraction(answer, 2**t) # A soma dos termos da fração continuada é a razão entre dois # números primos entre si (p e q onde MDC(p, q) == 1) que # multiplicados resultam N (somar apenas os termos menores ou iguais a N) r = 0 for x in fraction: if (x > N): break else: print("fraction: ", x) r = r + x return r
def test_gate(): """Test a basic gate.""" h = HadamardGate(1) assert h.min_qubits == 2 assert h.nqubits == 1
#行列に書き直そう! n = 10 itr = 8 f_ = [0] * n #[0,0,...0,0]の箱を用意 f_[1] = 1 #f1=1 #f_[random.randint(0, n-1)] = 1 fa = Qubit(*f_) #|010> basis = [] for psi_ in itertools.product([0, 1], repeat=n): basis.append(Qubit(*psi_)) psi0 = sum(basis) / sqrt(2**n) psi = sum(basis) / sqrt(2**n) Hs = prod([HadamardGate(i) for i in range(n)]) Is = prod([IdentityGate(i) for i in range(n)]) ''' p_ = [0]*n p = Qubit(*p_) psi0 = qapply(Hs*p).doit() psi = qapply(Hs*p) ''' Uf = lambda q: qapply(Is * q - 2 * fa * Dagger(fa) * q) #lambda 引数:処理内容 Us = lambda q: qapply(2 * psi0 * Dagger(psi0) * q - Is * q) for i in range(itr): psi = Us(Uf(psi)) y = [v[1] for v in measure_all(psi)] x = [''.join(map(str, v[0].qubit_values)) for v in measure_all(psi)]