Esempio n. 1
0
 def test(self):
     x = QubitCollection()
     y = QubitString(Qubit(0, 0, 0), "one")
     z = QubitString(Qubit(1, 0, 0), "two")
     x.add(y.qutuple)
     x.add(z.qutuple)
     print(x.size())
    def _apply_operator_Qubit(self, qubits, **options):
        """

        Calcula Vx da segunda metade do registrador e armazena na
        primeira metade

        """

        a = 1
        j = 0
        # Determina o valor de j no segundo registrador.
        for i in range(self.t):
            j = j + a * qubits[self.n + i]
            a = a * 2

        # Calcula o valor que será armazenado no primeiro registrador.
        value = int(self.x**j % self.N)

        primeiro = Qubit(IntQubit(value, self.n))

        array = list(qubits[k]
                     for k in reversed(range(self.n, self.n + self.t)))
        for i in reversed(range(self.n)):
            array.append(primeiro[i])

        #print Qubit(*array), self.x, j, value

        return Qubit(*array)
Esempio n. 3
0
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)))
Esempio n. 4
0
def ewl_fixed() -> EWL:
    i = sp.I
    pi = sp.pi
    sqrt2 = sp.sqrt(2)
    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])
Esempio n. 5
0
def ewl_parametrized() -> EWL:
    i = sp.I
    sqrt2 = sp.sqrt(2)
    theta1, alpha1, beta1, theta2, alpha2, beta2 = sp.symbols(
        'theta1 alpha1 beta1 theta2 alpha2 beta2', real=True)
    psi = (Qubit('00') + i * Qubit('11')) / 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])
Esempio n. 6
0
def test_swap_gate():
    """Test the SWAP gate."""
    swap_gate_matrix = Matrix(((1,0,0,0),(0,0,1,0),(0,1,0,0),(0,0,0,1)))
    assert represent(SwapGate(1,0).decompose(), nqubits=2) == swap_gate_matrix
    assert qapply(SwapGate(1,3)*Qubit('0010')) == Qubit('1000')
    nqubits = 4
    for i in range(nqubits):
        for j in range(i):
            assert represent(SwapGate(i,j), nqubits=nqubits) ==\
                represent(SwapGate(i,j).decompose(), nqubits=nqubits)
Esempio n. 7
0
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()
Esempio n. 8
0
def test_eval_args():
    # check instance created
    assert isinstance(Density([Ket(0), 0.5], [Ket(1), 0.5]), Density)
    assert isinstance(Density([Qubit('00'), 1/sqrt(2)],
                              [Qubit('11'), 1/sqrt(2)]), Density)

    #test if Qubit object type preserved
    d = Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)])
    for (state, prob) in d.args:
        assert isinstance(state, Qubit)

    # check for value error, when prob is not provided
    raises(ValueError, lambda: Density([Ket(0)], [Ket(1)]))
Esempio n. 9
0
def period_find(a, N):
    """Finds the period of a in modulo N arithmetic

    This is quantum part of Shor's algorithm.It takes two registers,
    puts first in superposition of states with Hadamards so: |k>|0>
    with k being all possible choices. It then does a controlled mod and
    a QFT to determine the order of a.
    """
    epsilon = .5
    #picks out t's such that maintains accuracy within epsilon
    t = int(2 * math.ceil(log(N, 2)))
    # make the first half of register be 0's |000...000>
    start = [0 for x in range(t)]
    #Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0>
    factor = 1 / sqrt(2**t)
    qubits = 0
    for i in range(2**t):
        qbitArray = arr(i, t) + start
        qubits = qubits + Qubit(*qbitArray)
    circuit = (factor * qubits).expand()
    #Controlled second half of register so that we have:
    # |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n>
    circuit = CMod(t, a, N) * circuit
    #will measure first half of register giving one of the a**k%N's
    circuit = apply_operators(circuit)
    print "controlled Mod'd"
    for i in range(t):
        circuit = measure_partial_oneshot(circuit, i)
        # circuit = measure(i)*circuit
    # circuit = apply_operators(circuit)
    print "measured 1"
    #Now apply Inverse Quantum Fourier Transform on the second half of the register
    circuit = apply_operators(QFT(t, t * 2).decompose() * circuit,
                              floatingPoint=True)
    print "QFT'd"
    for i in range(t):
        circuit = measure_partial_oneshot(circuit, i + t)
        # circuit = measure(i+t)*circuit
    # circuit = apply_operators(circuit)
    print circuit
    if isinstance(circuit, Qubit):
        register = circuit
    elif isinstance(circuit, Mul):
        register = circuit.args[-1]
    else:
        register = circuit.args[-1].args[-1]

    print register
    n = 1
    answer = 0
    for i in range(len(register) / 2):
        answer += n * register[i + t]
        n = n << 1
    if answer == 0:
        raise OrderFindingException(
            "Order finder returned 0. Happens with chance %f" % epsilon)
    #turn answer into r using continued fractions
    g = getr(answer, 2**t, N)
    print g
    return g
Esempio n. 10
0
def eqsup(n):
    state = Qubit('0'*n)

    for i in range(n):
        state = gate.H(i) * state

    return qapply(state)
Esempio n. 11
0
def test_hadamard_loop(printFlag=False, parallel=False):
    lp = 1  # loop size
    ms = 5
    me = 5
    for n in range(ms, me + 1):
        ts = 5.0  # target second
        lc = lp  # loop counter
        ss = 0.0  # sum sec
        for l in range(lc):
            # print(n)
            p = '0' * n
            # print(p)
            q = Qubit(p)
            # print(q)
            h = H(0)
            for i in range(1, n):
                h = H(i) * h
            print(h)

            executor = CythonExecutor(parallel=parallel)
            start = time.time()
            r = qapply(h * q, executor=executor)
            elapsed_time = time.time() - start
            ss += elapsed_time
            if printFlag:
                print(r)
            print("elapsed_time:\t{0},\t{1} [sec]".format(n, elapsed_time))

        print("average:\t{0}x{1},\t{2} [sec]".format(n, lc, ss / lc))
        assert ss / lc < ts
Esempio n. 12
0
def test_cnot_gate():
    """Test the CNOT gate."""
    circuit = CNotGate(1, 0)
    assert represent(circuit, nqubits=2) ==\
        Matrix([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]])
    circuit = circuit * Qubit('111')
    assert matrix_to_qubit(represent(circuit, nqubits=3)) ==\
        qapply(circuit)
def test_UGate_CGate_combo():
    a, b, c, d = symbols('a,b,c,d')
    uMat = Matrix([[a, b], [c, d]])
    cMat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, c, d]])

    # Test basic case where gate exists in 1-qubit space.
    u1 = UGate((0, ), uMat)
    cu1 = CGate(1, u1)
    assert represent(cu1, nqubits=2) == cMat
    assert qapply(cu1 * Qubit('10')) == a * Qubit('10') + c * Qubit('11')
    assert qapply(cu1 * Qubit('11')) == b * Qubit('10') + d * Qubit('11')
    assert qapply(cu1 * Qubit('01')) == Qubit('01')
    assert qapply(cu1 * Qubit('00')) == Qubit('00')

    # 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)))
Esempio n. 14
0
def test_CMod():
    assert apply_operators(CMod(4, 2, 2)*Qubit(0,0,1,0,0,0,0,0)) ==\
    Qubit(0,0,1,0,0,0,0,0)
    assert apply_operators(CMod(5, 5, 7)*Qubit(0,0,1,0,0,0,0,0,0,0)) ==\
    Qubit(0,0,1,0,0,0,0,0,1,0)
    assert apply_operators(CMod(3, 2, 3)*Qubit(0,1,0,0,0,0)) ==\
    Qubit(0,1,0,0,0,1)
Esempio n. 15
0
def test_CMod():
    assert qapply(CMod(4, 2, 2)*Qubit(0, 0, 1, 0, 0, 0, 0, 0)) == \
        Qubit(0, 0, 1, 0, 0, 0, 0, 0)
    assert qapply(CMod(5, 5, 7)*Qubit(0, 0, 1, 0, 0, 0, 0, 0, 0, 0)) == \
        Qubit(0, 0, 1, 0, 0, 0, 0, 0, 1, 0)
    assert qapply(CMod(3, 2, 3)*Qubit(0, 1, 0, 0, 0, 0)) == \
        Qubit(0, 1, 0, 0, 0, 1)
Esempio n. 16
0
def test_qubit():
    q1 = Qubit("0101")
    q2 = IntQubit(8)
    assert str(q1) == "|0101>"
    assert pretty(q1) == "|0101>"
    assert upretty(q1) == u"❘0101⟩"
    assert latex(q1) == r"{\left|0101\right\rangle }"
    sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
    assert str(q2) == "|8>"
    assert pretty(q2) == "|8>"
    assert upretty(q2) == u"❘8⟩"
    assert latex(q2) == r"{\left|8\right\rangle }"
    sT(q2, "IntQubit(8)")
Esempio n. 17
0
def test_qubit():
    q1 = Qubit('0101')
    q2 = IntQubit(8)
    assert str(q1) == '|0101>'
    assert pretty(q1) == '|0101>'
    assert upretty(q1) == u'❘0101⟩'
    assert latex(q1) == r'{\left|0101\right\rangle }'
    sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
    assert str(q2) == '|8>'
    assert pretty(q2) == '|8>'
    assert upretty(q2) == u'❘8⟩'
    assert latex(q2) == r'{\left|8\right\rangle }'
    sT(q2, "IntQubit(8)")
Esempio n. 18
0
def test_cnot_gate():
    """Test the CNOT gate."""
    circuit = CNotGate(1, 0)
    assert represent(circuit, nqubits=2) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0],
                                                    [0, 0, 0, 1], [0, 0, 1,
                                                                   0]])
    circuit = circuit * Qubit("111")
    assert matrix_to_qubit(represent(circuit, nqubits=3)) == qapply(circuit)

    circuit = CNotGate(1, 0)
    assert Dagger(circuit) == circuit
    assert Dagger(Dagger(circuit)) == circuit
    assert circuit * circuit == 1
Esempio n. 19
0
def random_oracle(nqubits, min_img=1, max_img=1, q_type='bin'):
    """Create a random OracleGate under the given parameter

    Parameters
    ==========

    nqubits : int
        The number of qubits for OracleGate
    min_pic : int
        Minimum number of inverse images that are mapped to 1
    max_pic : int
        Maximum number of inverse images that are mapped to 1
    q_type : OracleGate
        Type of the Qubits that the oracle should be applied on.
        Can be 'bin' for binary (Qubit()) or 'int' for integer (IntQubit()).

    Returns
    =======

    OracleGate : random OracleGate under the given parameter

    Examples
    ========

    Generate random OracleGate that outputs 1 for 2-4 inputs::

        >>> from sympy.physics.quantum.grover import random_oracle
        >>> oracle = random_oracle(4, min_img=2, max_img=4, q_type="bin")

    """
    if q_type != 'bin' and q_type != 'int':
        raise QuantumError("q_type must be 'int' or 'bin'")

    if min_img < 1 or max_img < 1:
        raise QuantumError("min_pic, max_pic must be > 0")

    if min_img > max_img:
        raise QuantumError("max_pic must be >= min_pic")

    if min_img >= 2 ** nqubits or max_img > 2 ** nqubits:
        raise QuantumError("min_pic must be < 2**nqubits and max_pic must be <= 2**nqubits")

    import random
    pics = random.randint(min_img, max_img)
    integers = random.sample(range(2 ** nqubits), pics)
    if q_type == "int":
        items = [IntQubit(i) for i in integers]
    else:
        items = [Qubit(IntQubit(i)) for i in integers]

    return OracleGate(nqubits, lambda qubits: qubits in items)
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)))
Esempio n. 21
0
    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)
Esempio n. 22
0
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 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_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_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_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_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_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 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_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