def test_UGate(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) # Test basic case where gate exists in 1-qubit space u1 = UGate((0, ), uMat) assert represent(u1, nqubits=1) == uMat assert qapply(u1 * Qubit('0')) == a * Qubit('0') + c * Qubit('1') assert qapply(u1 * Qubit('1')) == b * Qubit('0') + d * Qubit('1') # Test case where gate exists in a larger space u2 = UGate((1, ), uMat) u2Rep = represent(u2, nqubits=2) for i in range(4): assert u2Rep*qubit_to_matrix(IntQubit(i,2)) ==\ qubit_to_matrix(qapply(u2*IntQubit(i,2)))
def _apply_operator_Qubit(self, qubits, **options): """ This directly calculates the controlled mod of the second half of the register and puts it in the second This will look pretty when we get Tensor Symbolically working """ n = 1 k = 0 # Determine the value stored in high memory. for i in range(self.t): k += n * qubits[self.t + i] n *= 2 # The value to go in low memory will be out. out = int(self.a**k % self.N) # Create array for new qbit-ket which will have high memory unaffected outarray = list(qubits.args[0][:self.t]) # Place out in low memory for i in reversed(range(self.t)): outarray.append((out >> i) & 1) return Qubit(*outarray)
def ewl_parametrized_01_10() -> EWL: psi = (Qubit('01') + i * Qubit('10')) / sqrt2 alice = U_theta_alpha_beta(theta=theta1, alpha=alpha1, beta=beta1) bob = U_theta_alpha_beta(theta=theta2, alpha=alpha2, beta=beta2) return EWL(psi=psi, C=C, D=D, players=[alice, bob])
from sympy.physics.quantum import TensorProduct from sympy.physics.quantum.qubit import Qubit from ewl.utils import amplitude_to_prob, is_unitary, number_of_qubits, sympy_to_numpy_matrix i = sp.I sqrt2 = sp.sqrt(2) sin = sp.sin cos = sp.cos exp = sp.exp x = sp.Symbol('x', real=True) @pytest.mark.parametrize('psi, expected', [ ((Qubit('0') + i * Qubit('1')) / sqrt2, 1), ((Qubit('00') + i * Qubit('11')) / sqrt2, 2), ((Qubit('000') + i * Qubit('111')) / sqrt2, 3), ]) def test_number_of_qubits(psi, expected: int): assert number_of_qubits(psi) == expected @pytest.mark.parametrize('U, expected', [ (Matrix([[1, 0], [0, 1]]), True), (Matrix([[2, 3], [4, 5]]), False), (Matrix([[cos(x), -sin(x)], [sin(x), cos(x)]]), True), ]) def test_is_unitary(U: Matrix, expected: bool): assert is_unitary(U) is expected
# \begin{pmatrix} # 1 & 0 & 0 & 0 \\ # 0 & 0 & 1 & 0 \\ # 0 & 1 & 0 & 0 \\ # 0 & 0 & 0 & 1 \\ # \end{pmatrix} # $$ # In[1]: from sympy import * from sympy.physics.quantum import * from sympy.physics.quantum.qubit import Qubit, QubitBra init_printing() # ベクトルや行列を綺麗に表示するため psi = Qubit('0') psi represent(psi) # <div> # $$ # \text{SWAP}= # \begin{pmatrix} # 1 & 0 & 0 & 0 \\ # 0 & 0 & 1 & 0 \\ # 0 & 1 & 0 & 0 \\ # 0 & 0 & 0 & 1 \\ # \end{pmatrix} # $$ # </div>
def test_represent_tgate(): """Test the representation of the T gate.""" circuit = TGate(0) * Qubit('01') assert Matrix([0, exp(I * pi / 4), 0, 0]) == represent(circuit, nqubits=2)
def test_cgate(): """Test the general CGate.""" # Test single control functionality CNOTMatrix = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) assert represent(CGate(1, XGate(0)), nqubits=2) == CNOTMatrix # Test multiple control bit functionality ToffoliGate = CGate((1, 2), XGate(0)) assert represent(ToffoliGate, nqubits=3) == \ Matrix( [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) ToffoliGate = CGate((3, 0), XGate(1)) assert qapply(ToffoliGate*Qubit('1001')) == \ matrix_to_qubit(represent(ToffoliGate*Qubit('1001'), nqubits=4)) assert qapply(ToffoliGate*Qubit('0000')) == \ matrix_to_qubit(represent(ToffoliGate*Qubit('0000'), nqubits=4)) CYGate = CGate(1, YGate(0)) CYGate_matrix = Matrix( ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 0, -I), (0, 0, I, 0))) # Test 2 qubit controlled-Y gate decompose method. assert represent(CYGate.decompose(), nqubits=2) == CYGate_matrix CZGate = CGate(0, ZGate(1)) CZGate_matrix = Matrix( ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, -1))) assert qapply(CZGate * Qubit('11')) == -Qubit('11') assert matrix_to_qubit(represent(CZGate*Qubit('11'), nqubits=2)) == \ -Qubit('11') # Test 2 qubit controlled-Z gate decompose method. assert represent(CZGate.decompose(), nqubits=2) == CZGate_matrix CPhaseGate = CGate(0, PhaseGate(1)) assert qapply(CPhaseGate*Qubit('11')) == \ I*Qubit('11') assert matrix_to_qubit(represent(CPhaseGate*Qubit('11'), nqubits=2)) == \ I*Qubit('11') # Test that the dagger, inverse, and power of CGate is evaluated properly assert Dagger(CZGate) == CZGate assert pow(CZGate, 1) == Dagger(CZGate) assert Dagger(CZGate) == CZGate.inverse() assert Dagger(CPhaseGate) != CPhaseGate assert Dagger(CPhaseGate) == CPhaseGate.inverse() assert Dagger(CPhaseGate) == pow(CPhaseGate, -1) assert pow(CPhaseGate, -1) == CPhaseGate.inverse()
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_represent_zgate(): """Test the representation of the Z gate.""" circuit = ZGate(0) * Qubit('00') answer = represent(circuit, nqubits=2) assert Matrix([1, 0, 0, 0]) == answer
def test_issue_5923(): # most of the issue regarding sympification of args has been handled # and is tested internally by the use of args_cnc through the quantum # module, but the following is a test from the issue that used to raise. assert TensorProduct(1, Qubit('1')*Qubit('1').dual) == \ TensorProduct(1, OuterProduct(Qubit(1), QubitBra(1)))
def test_fidelity(): #test with kets up = JzKet(S(1) / 2, S(1) / 2) down = JzKet(S(1) / 2, -S(1) / 2) updown = (S(1) / sqrt(2)) * up + (S(1) / sqrt(2)) * down #check with matrices up_dm = represent(up * Dagger(up)) down_dm = represent(down * Dagger(down)) updown_dm = represent(updown * Dagger(updown)) assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3 assert fidelity(up_dm, down_dm) < 1e-3 assert abs(fidelity(up_dm, updown_dm) - (S(1) / sqrt(2))) < 1e-3 assert abs(fidelity(updown_dm, down_dm) - (S(1) / sqrt(2))) < 1e-3 #check with density up_dm = Density([up, 1.0]) down_dm = Density([down, 1.0]) updown_dm = Density([updown, 1.0]) assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3 assert abs(fidelity(up_dm, down_dm)) < 1e-3 assert abs(fidelity(up_dm, updown_dm) - (S(1) / sqrt(2))) < 1e-3 assert abs(fidelity(updown_dm, down_dm) - (S(1) / sqrt(2))) < 1e-3 #check mixed states with density updown2 = (sqrt(3) / 2) * up + (S(1) / 2) * down d1 = Density([updown, 0.25], [updown2, 0.75]) d2 = Density([updown, 0.75], [updown2, 0.25]) assert abs(fidelity(d1, d2) - 0.991) < 1e-3 assert abs(fidelity(d2, d1) - fidelity(d1, d2)) < 1e-3 #using qubits/density(pure states) state1 = Qubit('0') state2 = Qubit('1') state3 = (S(1) / sqrt(2)) * state1 + (S(1) / sqrt(2)) * state2 state4 = (sqrt(S(2) / 3)) * state1 + (S(1) / sqrt(3)) * state2 state1_dm = Density([state1, 1]) state2_dm = Density([state2, 1]) state3_dm = Density([state3, 1]) assert fidelity(state1_dm, state1_dm) == 1 assert fidelity(state1_dm, state2_dm) == 0 assert abs(fidelity(state1_dm, state3_dm) - 1 / sqrt(2)) < 1e-3 assert abs(fidelity(state3_dm, state2_dm) - 1 / sqrt(2)) < 1e-3 #using qubits/density(mixed states) d1 = Density([state3, 0.70], [state4, 0.30]) d2 = Density([state3, 0.20], [state4, 0.80]) assert abs(fidelity(d1, d1) - 1) < 1e-3 assert abs(fidelity(d1, d2) - 0.996) < 1e-3 assert abs(fidelity(d1, d2) - fidelity(d2, d1)) < 1e-3 #TODO: test for invalid arguments # non-square matrix mat1 = [[0, 0], [0, 0], [0, 0]] mat2 = [[0, 0], [0, 0]] raises(ValueError, lambda: fidelity(mat1, mat2)) # unequal dimensions mat1 = [[0, 0], [0, 0]] mat2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] raises(ValueError, lambda: fidelity(mat1, mat2)) # unsupported data-type x, y = 1, 2 # random values that is not a matrix raises(ValueError, lambda: fidelity(x, y))
import operator import random def prod(iterable): return functools.reduce(operator.mul, iterable, 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) '''
def ewl() -> EWL: psi = (Qubit('00') + i * Qubit('11')) / sqrt2 alice = U_theta_alpha_beta(theta=pi / 2, alpha=pi / 2, beta=0) bob = U_theta_alpha_beta(theta=0, alpha=0, beta=0) return EWL(psi=psi, C=C, D=D, players=[alice, bob])
def run_circuit(self, circuit): """Run a circuit and return object. Args: circuit (QobjExperiment): Qobj experiment Returns: dict: A dictionary of results which looks something like: { "data":{ 'statevector': array([sqrt(2)/2, 0, 0, sqrt(2)/2], dtype=object)}, "status": --status (string)-- } Raises: SympySimulatorError: if an error occurred. """ self._number_of_qubits = circuit.header.number_of_qubits self._statevector = 0 self._statevector = Qubit(*tuple([0] * self._number_of_qubits)) for operation in circuit.instructions: if getattr(operation, 'conditional', None): raise SympySimulatorError( 'conditional operations not supported ' 'in statevector simulator') if operation.name in ('measure', 'reset'): raise SympySimulatorError( 'operation {} not supported by sympy statevector simulator.' .format(operation.name)) if operation.name in ('U', 'u1', 'u2', 'u3'): qubit = operation.qubits[0] opname = operation.name.upper() opparas = getattr(operation, 'params', None) _sym_op = SympyStatevectorSimulator.get_sym_op( opname, tuple([qubit]), opparas) _applied_statevector = _sym_op * self._statevector self._statevector = qapply(_applied_statevector) elif operation.name == 'id': logger.info( 'Identity gate is ignored by sympy-based statevector simulator.' ) elif operation.name == 'barrier': logger.info( 'Barrier is ignored by sympy-based statevector simulator.') elif operation.name in ('CX', 'cx'): qubit0 = operation.qubits[0] qubit1 = operation.qubits[1] opname = operation.name.upper() opparas = getattr(operation, 'params', None) q0q1tuple = tuple([qubit0, qubit1]) _sym_op = SympyStatevectorSimulator.get_sym_op( opname, q0q1tuple, opparas) self._statevector = qapply(_sym_op * self._statevector) else: backend = self.name err_msg = '{0} encountered unrecognized operation "{1}"' raise SympySimulatorError( err_msg.format(backend, operation.name)) matrix_form = represent(self._statevector) shape_n = matrix_form.shape[0] list_form = [matrix_form[i, 0] for i in range(shape_n)] # Return the results data = { 'statevector': np.asarray(list_form), } return { 'name': circuit.header.name, 'data': data, 'status': 'DONE', 'success': True, 'shots': 1 }
return result zero = np.array([[1. + 0.j], [0. + 0.j]]) one = np.array([[0. + 0.j], [1. + 0.j]]) print("> Sympy хэрэглэн qubit дүрслэх туршилтууд :\n") print("qubit |5> буюу integer дүрслэл ") q0 = IntQubit(5) print("qubit int :", q0) print("qubit nqubits :", q0.nqubits) print("qubit values :", q0.qubit_values) q1 = Qubit(q0) print("sympy qubit дүрслэл :", q1, "\n") print("IntQubit(1, 1)") q2 = IntQubit(1, 1) print(q2, Qubit(q2)) print("IntQubit(1,0,1,0,1)") q3 = IntQubit(1, 0, 1, 0, 1) print(q3, Qubit(q3)) print(q3.qubit_values) print(Qubit(q3).qubit_values) print("Dagger", q1, Dagger(q1)) ip = Dagger(q1) * q1 print(ip) print(ip.doit())
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- from sympy.physics.quantum.qubit import Qubit q = Qubit('01101') print("---includes---\n") print(q) print("len: {}\n".format(q.dimension)) print("--------------\n")
from sympy.physics.quantum import represent from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.qubit import QubitBra from sympy.physics.quantum.dagger import Dagger sympy.init_printing() # In[5]: print('sympy version : ', sympy.__version__) # 1量子ビットをブラケット記号を用いて指定します。 # In[6]: # 1量子ビット q0 = Qubit('0') q1 = Qubit('1') p0 = QubitBra('1') p1 = QubitBra('1') # In[7]: q0 # In[8]: q1 # In[9]: p0
def test_gate(): a, b, c, d = symbols("a,b,c,d") uMat = Matrix([[a, b], [c, d]]) q = Qubit(1, 0, 1, 0, 1) g1 = IdentityGate(2) g2 = CGate((3, 0), XGate(1)) g3 = CNotGate(1, 0) g4 = UGate((0, ), uMat) assert str(g1) == "1(2)" assert pretty(g1) == "1 \n 2" assert upretty(g1) == u"1 \n 2" assert latex(g1) == r"1_{2}" sT(g1, "IdentityGate(Integer(2))") assert str(g1 * q) == "1(2)*|10101>" ascii_str = """\ 1 *|10101>\n\ 2 \ """ ucode_str = u("""\ 1 ⋅❘10101⟩\n\ 2 \ """) assert pretty(g1 * q) == ascii_str assert upretty(g1 * q) == ucode_str assert latex(g1 * q) == r"1_{2} {\left|10101\right\rangle }" sT( g1 * q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))", ) assert str(g2) == "C((3,0),X(1))" ascii_str = """\ C /X \\\n\ 3,0\\ 1/\ """ ucode_str = u("""\ C ⎛X ⎞\n\ 3,0⎝ 1⎠\ """) assert pretty(g2) == ascii_str assert upretty(g2) == ucode_str assert latex(g2) == r"C_{3,0}{\left(X_{1}\right)}" sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))") assert str(g3) == "CNOT(1,0)" ascii_str = """\ CNOT \n\ 1,0\ """ ucode_str = u("""\ CNOT \n\ 1,0\ """) assert pretty(g3) == ascii_str assert upretty(g3) == ucode_str assert latex(g3) == r"CNOT_{1,0}" sT(g3, "CNotGate(Integer(1),Integer(0))") ascii_str = """\ U \n\ 0\ """ ucode_str = u("""\ U \n\ 0\ """) assert (str(g4) == """\ U((0,),Matrix([\n\ [a, b],\n\ [c, d]]))\ """) assert pretty(g4) == ascii_str assert upretty(g4) == ucode_str assert latex(g4) == r"U_{0}" sT( g4, "UGate(Tuple(Integer(0)),MutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))", )
def test_sympy__physics__quantum__qubit__Qubit(): from sympy.physics.quantum.qubit import Qubit assert _test_args(Qubit(0, 0, 0))
import sympy as sp from sympy import Array from sympy.physics.quantum.qubit import Qubit from ewl import EWL from ewl.parametrizations import U_Eisert_Wilkens_Lewenstein, U_Frackiewicz_Pykacz, U_theta_phi_alpha, U_theta_alpha_beta i = sp.I pi = sp.pi sqrt2 = sp.sqrt(2) theta_A, phi_A, alpha_A, beta_A = sp.symbols('theta_A phi_A alpha_A beta_A', real=True) theta_B, phi_B, alpha_B, beta_B = sp.symbols('theta_B phi_B alpha_B beta_B', real=True) psi = 1 / sqrt2 * Qubit('00') + i / sqrt2 * Qubit('11') payoff_matrix = Array([ [ [3, 0], [5, 1], ], [ [3, 5], [0, 1], ], ]) def make_Quantum_Prisoners_Dilemma_Eisert_Wilkens_Lewenstein() -> EWL: """ Quantum Prisoner's Dilemma with original EWL parametrization
def test_dagger(): lhs = Dagger(Qubit(0)) * Dagger(H(0)) rhs = Dagger(Qubit(1)) / sqrt(2) + Dagger(Qubit(0)) / sqrt(2) assert qapply(lhs, dagger=True) == rhs
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_represent_ygate(): """Test the representation of the Y gate.""" circuit = YGate(0) * Qubit('00') answer = represent(circuit, nqubits=2) assert answer[0] == 0 and answer[1] == I and \ answer[2] == 0 and answer[3] == 0
def run_circuit(self, circuit): """Run a circuit and return object. Args: circuit (dict): JSON that describes the circuit Returns: dict: A dictionary of results which looks something like:: { "data":{ 'statevector': array([sqrt(2)/2, 0, 0, sqrt(2)/2], dtype=object)}, "status": --status (string)-- } Raises: SimulatorError: if an error occurred. """ ccircuit = circuit['compiled_circuit'] self._number_of_qubits = ccircuit['header']['number_of_qubits'] self._statevector = 0 self._statevector = Qubit(*tuple([0]*self._number_of_qubits)) for operation in ccircuit['operations']: if 'conditional' in operation: raise SimulatorError('conditional operations not supported ' 'in statevector simulator') if operation['name'] == 'measure' or operation['name'] == 'reset': raise SimulatorError('operation {} not supported by ' 'sympy statevector simulator.'.format(operation['name'])) if operation['name'] in ['U', 'u1', 'u2', 'u3']: qubit = operation['qubits'][0] opname = operation['name'].upper() opparas = operation['params'] _sym_op = SympyStatevectorSimulator.get_sym_op(opname, tuple([qubit]), opparas) _applied_statevector = _sym_op * self._statevector self._statevector = qapply(_applied_statevector) elif operation['name'] in ['id']: logger.info('Identity gate is ignored by sympy-based statevector simulator.') elif operation['name'] in ['barrier']: logger.info('Barrier is ignored by sympy-based statevector simulator.') elif operation['name'] in ['CX', 'cx']: qubit0 = operation['qubits'][0] qubit1 = operation['qubits'][1] opname = operation['name'].upper() if 'params' in operation: opparas = operation['params'] else: opparas = None q0q1tuple = tuple([qubit0, qubit1]) _sym_op = SympyStatevectorSimulator.get_sym_op(opname, q0q1tuple, opparas) self._statevector = qapply(_sym_op * self._statevector) else: backend = globals()['__configuration']['name'] err_msg = '{0} encountered unrecognized operation "{1}"' raise SimulatorError(err_msg.format(backend, operation['name'])) matrix_form = represent(self._statevector) shape_n = matrix_form.shape[0] list_form = [matrix_form[i, 0] for i in range(shape_n)] # Return the results data = { 'statevector': np.asarray(list_form), } return {'name': circuit['name'], 'data': data, 'status': 'DONE'}
def test_represent_phasegate(): """Test the representation of the S gate.""" circuit = PhaseGate(0) * Qubit('01') answer = represent(circuit, nqubits=2) assert Matrix([0, I, 0, 0]) == answer
def test_gate(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) q = Qubit(1, 0, 1, 0, 1) g1 = IdentityGate(2) g2 = CGate((3, 0), XGate(1)) g3 = CNotGate(1, 0) g4 = UGate((0, ), uMat) assert str(g1) == '1(2)' assert pretty(g1) == '1 \n 2' assert upretty(g1) == u'1 \n 2' assert latex(g1) == r'1_{2}' sT(g1, "IdentityGate(Integer(2))") assert str(g1 * q) == '1(2)*|10101>' ascii_str = \ """\ 1 *|10101>\n\ 2 \ """ ucode_str = \ u"""\ 1 ⋅❘10101⟩\n\ 2 \ """ assert pretty(g1 * q) == ascii_str assert upretty(g1 * q) == ucode_str assert latex(g1 * q) == r'1_{2} {\left|10101\right\rangle }' sT( g1 * q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))" ) assert str(g2) == 'C((3,0),X(1))' ascii_str = \ """\ C /X \\\n\ 3,0\\ 1/\ """ ucode_str = \ u"""\ C ⎛X ⎞\n\ 3,0⎝ 1⎠\ """ assert pretty(g2) == ascii_str assert upretty(g2) == ucode_str assert latex(g2) == r'C_{3,0}{\left(X_{1}\right)}' sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))") assert str(g3) == 'CNOT(1,0)' ascii_str = \ """\ CNOT \n\ 1,0\ """ ucode_str = \ u"""\ CNOT \n\ 1,0\ """ assert pretty(g3) == ascii_str assert upretty(g3) == ucode_str assert latex(g3) == r'CNOT_{1,0}' sT(g3, "CNotGate(Integer(1),Integer(0))") # str(g4) Fails #assert str(g4) == '' ascii_str = \ """\ U \n\ 0\ """ ucode_str = \ u"""\ U \n\ 0\ """ assert pretty(g4) == ascii_str assert upretty(g4) == ucode_str assert latex(g4) == r'U_{0}' sT( g4, "UGate(Tuple(Integer(0)),MutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))" )
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 run_circuit(self, circuit): """Run a circuit and return object Args: circuit (dict): JSON that describes the circuit Returns: dict: A dictionary of results which looks something like:: { "data":{ 'classical_state': 0, 'counts': {'11': 1}, 'quantum_state': array([sqrt(2)/2, 0, 0, sqrt(2)/2], dtype=object)}, "status": --status (string)-- } Raises: SimulatorError: if an error occurred. """ ccircuit = circuit['compiled_circuit'] self._number_of_qubits = ccircuit['header']['number_of_qubits'] self._number_of_cbits = ccircuit['header']['number_of_clbits'] self._quantum_state = 0 self._classical_state = 0 cl_reg_index = [] # starting bit index of classical register cl_reg_nbits = [] # number of bits in classical register cbit_index = 0 for cl_reg in ccircuit['header']['clbit_labels']: cl_reg_nbits.append(cl_reg[1]) cl_reg_index.append(cbit_index) cbit_index += cl_reg[1] if circuit['config']['seed'] is None: random.seed(random.getrandbits(32)) else: random.seed(circuit['config']['seed']) actual_shots = self._shots self._quantum_state = Qubit(*tuple([0]*self._number_of_qubits)) self._classical_state = 0 # Do each operation in this shot for operation in ccircuit['operations']: if 'conditional' in operation: # not related to sympy mask = int(operation['conditional']['mask'], 16) if mask > 0: value = self._classical_state & mask while (mask & 0x1) == 0: mask >>= 1 value >>= 1 if value != int(operation['conditional']['val'], 16): continue if operation['name'] in ['U', 'u1', 'u2', 'u3']: qubit = operation['qubits'][0] opname = operation['name'].upper() opparas = operation['params'] _sym_op = SympyQasmSimulator.get_sym_op(opname, tuple([qubit]), opparas) _applied_quantum_state = _sym_op * self._quantum_state self._quantum_state = qapply(_applied_quantum_state) # Check if CX gate elif operation['name'] in ['id']: logger.info('Identity gate is ignored by sympy-based qasm simulator.') elif operation['name'] in ['CX', 'cx']: qubit0 = operation['qubits'][0] qubit1 = operation['qubits'][1] opname = operation['name'].upper() if 'params' in operation: opparas = operation['params'] else: opparas = None q0q1tuple = tuple([qubit0, qubit1]) _sym_op = SympyQasmSimulator.get_sym_op(opname, q0q1tuple, opparas) self._quantum_state = qapply(_sym_op * self._quantum_state) # Check if measure elif operation['name'] == 'measure': logger.info('The statement measure is ignored by sympy-based qasm simulator.') elif operation['name'] == 'reset': logger.info('The statement reset is ignored by sympy-based qasm simulator.') elif operation['name'] == 'barrier': logger.info('The statement barrier is ignored by sympy-based qasm simulator.') else: backend = globals()['__configuration']['name'] err_msg = '{0} encountered unrecognized operation "{1}"' raise SimulatorError(err_msg.format(backend, operation['name'])) outcomes = [] matrix_form = represent(self._quantum_state) shape_n = matrix_form.shape[0] list_form = [matrix_form[i, 0] for i in range(shape_n)] pdist = [SympyQasmSimulator._conjugate_square(matrix_form[i, 0]) for i in range(shape_n)] norm_pdist = [float(i)/sum(pdist) for i in pdist] for _ in range(actual_shots): _classical_state_observed = np.random.choice(np.arange(0, shape_n), p=norm_pdist) outcomes.append(bin(_classical_state_observed)[2:].zfill( self._number_of_cbits)) # Return the results counts = dict(Counter(outcomes)) # data['quantum_state']: consistent with other backends. data = { 'counts': self._format_result(counts, cl_reg_index, cl_reg_nbits), 'quantum_state': np.asarray(list_form), 'classical_state': self._classical_state } return {'data': data, 'status': 'DONE'}
from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.grover import OracleGate from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.gate import HadamardGate from sympy.physics.quantum.grover import superposition_basis from sympy.physics.quantum.grover import grover_iteration from sympy.physics.quantum.grover import apply_grover from Qubit import QubitString from QubitCollection import QubitCollection q1 = QubitString(Qubit(0), "one") q2 = QubitString(Qubit(1, 0), "two") q3 = QubitString(Qubit(0, 1, 1), "three") q4 = QubitString(Qubit(0, 1, 0, 1), "four") q5 = QubitString(Qubit(1, 0, 1, 0, 0), "five") q6 = QubitString(Qubit(0, 1, 0, 1, 1, 0), "six") q7 = QubitString(Qubit(0, 0, 1, 1, 1, 0, 0), "seven") q8 = QubitString(Qubit(0, 0, 1, 0, 1, 0, 1, 0), "eight") qcol = QubitCollection() qcol.add(q1.qutuple) qcol.add(q2.qutuple) qcol.add(q3.qutuple) qcol.add(q4.qutuple) qcol.add(q5.qutuple) qcol.add(q6.qutuple) qcol.add(q7.qutuple) qcol.add(q8.qutuple)
def main(): return Qubit('00')1