示例#1
0
def test_WGate():
    nqubits = 2
    basis_states = superposition_basis(nqubits)
    assert qapply(WGate(nqubits)*basis_states) == basis_states

    expected = ((2/sqrt(pow(2, nqubits)))*basis_states) - IntQubit(1, nqubits=nqubits)
    assert qapply(WGate(nqubits)*IntQubit(1, nqubits=nqubits)) == expected
示例#2
0
def test_grover():
    nqubits = 2
    assert apply_grover(return_one_on_one, nqubits) == IntQubit(1, nqubits=nqubits)

    nqubits = 4
    basis_states = superposition_basis(nqubits)
    expected = (-13*basis_states)/64 + 264*IntQubit(2, nqubits)/256
    assert apply_grover(return_one_on_two, 4) == qapply(expected)
示例#3
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 _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)
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)))
示例#6
0
def superposition_basis(nqubits):
    """Creates an equal superposition of the computational basis.

    Parameters
    ==========

    nqubits : int
        The number of qubits.

    Returns
    =======

    state : Qubit
        An equal superposition of the computational basis with nqubits.

    Examples
    ========

    Create an equal superposition of 2 qubits::

        >>> from sympy.physics.quantum.grover import superposition_basis
        >>> superposition_basis(2)
        |0>/2 + |1>/2 + |2>/2 + |3>/2
    """

    amp = 1/sqrt(2**nqubits)
    return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)])
示例#7
0
def test_IntQubit():
    assert IntQubit(8).as_int() == 8
    assert IntQubit(8).qubit_values == (1, 0, 0, 0)
    assert IntQubit(7, 4).qubit_values == (0, 1, 1, 1)
    assert IntQubit(3) == IntQubit(3, 2)

    #test Dual Classes
    assert IntQubit(3).dual_class() == IntQubitBra
    assert IntQubitBra(3).dual_class() == IntQubit

    assert IntQubit(5)._eval_innerproduct_IntQubitBra(
        IntQubitBra(5)) == Integer(1)
    assert IntQubit(4)._eval_innerproduct_IntQubitBra(
        IntQubitBra(5)) == Integer(0)
    raises(ValueError, lambda: IntQubit(4, 1))
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)))
示例#9
0
 def _represent_ZGate(self, basis, **options):
     """
     Represent the OracleGate in the computational basis.
     """
     nbasis = 2**self.nqubits  # compute it only once
     matrixOracle = eye(nbasis)
     # Flip the sign given the output of the oracle function
     for i in range(nbasis):
         if self.search_function(IntQubit(i, nqubits=self.nqubits)):
             matrixOracle[i, i] = NegativeOne()
     return matrixOracle
示例#10
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)")
示例#11
0
def test_IntQubit():
    assert IntQubit(8).as_int() == 8
    assert IntQubit(8).qubit_values == (1, 0, 0, 0)
    assert IntQubit(7, 4).qubit_values == (0, 1, 1, 1)
    assert IntQubit(3) == IntQubit(3, 2)

    #test Dual Classes
    assert IntQubit(3).dual_class() == IntQubitBra
    assert IntQubitBra(3).dual_class() == IntQubit

    raises(ValueError, lambda: IntQubit(4, 1))
示例#12
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)")
示例#13
0
def test_IntQubit():
    assert IntQubit(8).as_int() == 8
    assert IntQubit(8).qubit_values == (1,0,0,0)
    assert IntQubit(7, 4).qubit_values == (0,1,1,1)
    assert IntQubit(3) == IntQubit(3,2)

    #test Dual Classes
    assert IntQubit(3).dual_class == IntQubitBra
    assert IntQubitBra(3).dual_class == IntQubit
示例#14
0
def test_grover_iteration_2():
    numqubits = 4
    basis_states = superposition_basis(numqubits)
    v = OracleGate(numqubits, return_one_on_two)
    # After (pi/4)sqrt(pow(2, n)), IntQubit(2) should have highest prob
    # In this case, after around pi times (3 or 4)
    iterated = grover_iteration(basis_states, v)
    iterated = qapply(iterated)
    iterated = grover_iteration(iterated, v)
    iterated = qapply(iterated)
    iterated = grover_iteration(iterated, v)
    iterated = qapply(iterated)
    # In this case, probability was highest after 3 iterations
    # Probability of Qubit('0010') was 251/256 (3) vs 781/1024 (4)
    # Ask about measurement
    expected = (-13*basis_states)/64 + 264*IntQubit(2, numqubits)/256
    assert qapply(expected) == iterated
示例#15
0
def test_IntQubit():
    iqb = IntQubit(8)
    assert iqb.as_int() == 8
    assert iqb.qubit_values == (1, 0, 0, 0)

    iqb = IntQubit(7, 4)
    assert iqb.qubit_values == (0, 1, 1, 1)
    assert IntQubit(3) == IntQubit(3, 2)

    #test Dual Classes
    iqb = IntQubit(3)
    iqb_bra = IntQubitBra(3)
    assert iqb.dual_class() == IntQubitBra
    assert iqb_bra.dual_class() == IntQubit

    iqb = IntQubit(5)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1)

    iqb = IntQubit(4)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0)
    raises(ValueError, lambda: IntQubit(4, 1))
def n_kron(*args):
    result = np.array([[1. + 0.j]])
    for op in args:
        result = np.kron(result, op)
    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)
示例#17
0
def test_OracleGate():
    v = OracleGate(1, lambda qubits: qubits == IntQubit(0))
    assert qapply(v*IntQubit(0)) == -IntQubit(0)
    assert qapply(v*IntQubit(1)) == IntQubit(1)

    nbits = 2
    v = OracleGate(2, return_one_on_two)
    assert qapply(v*IntQubit(0, nbits)) == IntQubit(0, nqubits=nbits)
    assert qapply(v*IntQubit(1, nbits)) == IntQubit(1, nqubits=nbits)
    assert qapply(v*IntQubit(2, nbits)) == -IntQubit(2, nbits)
    assert qapply(v*IntQubit(3, nbits)) == IntQubit(3, nbits)

    assert represent(OracleGate(1, lambda qubits: qubits == IntQubit(0)), nqubits=1) == \
           Matrix([[-1, 0], [0, 1]])
    assert represent(v, nqubits=2) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
示例#18
0
def test_superposition_basis():
    nbits = 2
    first_half_state = IntQubit(0, nqubits=nbits)/2 + IntQubit(1, nqubits=nbits)/2
    second_half_state = IntQubit(2, nbits)/2 + IntQubit(3, nbits)/2
    assert first_half_state + second_half_state == superposition_basis(nbits)

    nbits = 3
    firstq = (1/sqrt(8))*IntQubit(0, nqubits=nbits) + (1/sqrt(8))*IntQubit(1, nqubits=nbits)
    secondq = (1/sqrt(8))*IntQubit(2, nbits) + (1/sqrt(8))*IntQubit(3, nbits)
    thirdq = (1/sqrt(8))*IntQubit(4, nbits) + (1/sqrt(8))*IntQubit(5, nbits)
    fourthq = (1/sqrt(8))*IntQubit(6, nbits) + (1/sqrt(8))*IntQubit(7, nbits)
    assert firstq + secondq + thirdq + fourthq == superposition_basis(nbits)
示例#19
0
def return_one_on_one(qubits):
    return qubits == IntQubit(1, nqubits=qubits.nqubits)
示例#20
0
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)

f1 = lambda qubits: qubits == IntQubit(1)
f2 = lambda qubits: qubits == IntQubit(2)
f3 = lambda qubits: qubits == IntQubit(3)
f4 = lambda qubits: qubits == IntQubit(4)
f5 = lambda qubits: qubits == IntQubit(5)
f6 = lambda qubits: qubits == IntQubit(6)
f7 = lambda qubits: qubits == IntQubit(7)
f8 = lambda qubits: qubits == IntQubit(8)

v1 = OracleGate(q1.nQubits(), f1)
v2 = OracleGate(q2.nQubits(), f2)
v3 = OracleGate(q3.nQubits(), f3)
v4 = OracleGate(q4.nQubits(), f4)
v5 = OracleGate(q5.nQubits(), f5)
v6 = OracleGate(q6.nQubits(), f6)
v7 = OracleGate(q7.nQubits(), f7)
def test_OracleGate():
    v = OracleGate(1, lambda qubits: qubits == IntQubit(0))
    assert qapply(v*IntQubit(0)) == -IntQubit(0)
    assert qapply(v*IntQubit(1)) == IntQubit(1)

    nbits = 2
    v = OracleGate(2, return_one_on_two)
    assert qapply(v*IntQubit(0, nbits)) == IntQubit(0, nbits)
    assert qapply(v*IntQubit(1, nbits)) == IntQubit(1, nbits)
    assert qapply(v*IntQubit(2, nbits)) == -IntQubit(2, nbits)
    assert qapply(v*IntQubit(3, nbits)) == IntQubit(3, nbits)

    # Due to a bug of IntQubit, this first assertion is buggy
    # assert represent(OracleGate(1, lambda qubits: qubits == IntQubit(0)), nqubits=1) == \
    #     Matrix([[-1/sqrt(2), 0], [0, 1/sqrt(2)]])
    assert represent(v, nqubits=2) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
示例#22
0
def return_one_on_two(qubits):
    return qubits == IntQubit(2, qubits.nqubits)
示例#23
0
def test_IntQubit():
    # issue 9136
    iqb = IntQubit(0, nqubits=1)
    assert qubit_to_matrix(Qubit('0')) == qubit_to_matrix(iqb)

    qb = Qubit('1010')
    assert qubit_to_matrix(IntQubit(qb)) == qubit_to_matrix(qb)

    iqb = IntQubit(1, nqubits=1)
    assert qubit_to_matrix(Qubit('1')) == qubit_to_matrix(iqb)
    assert qubit_to_matrix(IntQubit(1)) == qubit_to_matrix(iqb)

    iqb = IntQubit(7, nqubits=4)
    assert qubit_to_matrix(Qubit('0111')) == qubit_to_matrix(iqb)
    assert qubit_to_matrix(IntQubit(7, 4)) == qubit_to_matrix(iqb)

    iqb = IntQubit(8)
    assert iqb.as_int() == 8
    assert iqb.qubit_values == (1, 0, 0, 0)

    iqb = IntQubit(7, 4)
    assert iqb.qubit_values == (0, 1, 1, 1)
    assert IntQubit(3) == IntQubit(3, 2)

    #test Dual Classes
    iqb = IntQubit(3)
    iqb_bra = IntQubitBra(3)
    assert iqb.dual_class() == IntQubitBra
    assert iqb_bra.dual_class() == IntQubit

    iqb = IntQubit(5)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1)

    iqb = IntQubit(4)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0)
    raises(ValueError, lambda: IntQubit(4, 1))

    raises(ValueError, lambda: IntQubit('5'))
    raises(ValueError, lambda: IntQubit(5, '5'))
    raises(ValueError, lambda: IntQubit(5, nqubits='5'))
    raises(TypeError, lambda: IntQubit(5, bad_arg=True))
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
示例#25
0
def test_sympy__physics__quantum__qubit__IntQubit():
    from sympy.physics.quantum.qubit import IntQubit
    assert _test_args(IntQubit(0))
示例#26
0
def demo_vgate_app(v):
    for i in range(2**v.nqubits):
        print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits))
        pprint(qapply(v * IntQubit(i, nqubits=v.nqubits)))
        qapply(v * IntQubit(i, nqubits=v.nqubits))
def test_IntQubit():
    iqb = IntQubit(8)
    assert iqb.as_int() == 8
    assert iqb.qubit_values == (1, 0, 0, 0)

    iqb = IntQubit(7, 4)
    assert iqb.qubit_values == (0, 1, 1, 1)
    assert IntQubit(3) == IntQubit(3, 2)

    #test Dual Classes
    iqb = IntQubit(3)
    iqb_bra = IntQubitBra(3)
    assert iqb.dual_class() == IntQubitBra
    assert iqb_bra.dual_class() == IntQubit

    iqb = IntQubit(5)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1)

    iqb = IntQubit(4)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0)
    raises(ValueError, lambda: IntQubit(4, 1))
示例#28
0
def test_grover_iteration_1():
    numqubits = 2
    basis_states = superposition_basis(numqubits)
    v = OracleGate(numqubits, return_one_on_one)
    expected = IntQubit(1, nqubits=numqubits)
    assert qapply(grover_iteration(basis_states, v)) == expected
示例#29
0
def demo_vgate_app(v):
    for i in range(2**v.nqubits):
        print 'qapply(v*IntQubit({0}, {1}))'.format(i, v.nqubits)
        pprint(qapply(v * IntQubit(i, v.nqubits)))
        qapply(v * IntQubit(i, v.nqubits))
示例#30
0
def test_OracleGate():
    v = OracleGate(1, lambda qubits: qubits == IntQubit(0))
    assert qapply(v*IntQubit(0)) == -IntQubit(0)
    assert qapply(v*IntQubit(1)) == IntQubit(1)

    nbits = 2
    v = OracleGate(2, return_one_on_two)
    assert qapply(v*IntQubit(0, nbits)) == IntQubit(0, nbits)
    assert qapply(v*IntQubit(1, nbits)) == IntQubit(1, nbits)
    assert qapply(v*IntQubit(2, nbits)) == -IntQubit(2, nbits)
    assert qapply(v*IntQubit(3, nbits)) == IntQubit(3, nbits)
示例#31
0
def test_IntQubit():
    # issue 9136
    iqb = IntQubit(0, nqubits=1)
    assert qubit_to_matrix(Qubit('0')) == qubit_to_matrix(iqb)

    qb = Qubit('1010')
    assert qubit_to_matrix(IntQubit(qb)) == qubit_to_matrix(qb)

    iqb = IntQubit(1, nqubits=1)
    assert qubit_to_matrix(Qubit('1')) == qubit_to_matrix(iqb)
    assert qubit_to_matrix(IntQubit(1)) == qubit_to_matrix(iqb)

    iqb = IntQubit(7, nqubits=4)
    assert qubit_to_matrix(Qubit('0111')) == qubit_to_matrix(iqb)
    assert qubit_to_matrix(IntQubit(7, 4)) == qubit_to_matrix(iqb)

    iqb = IntQubit(8)
    assert iqb.as_int() == 8
    assert iqb.qubit_values == (1, 0, 0, 0)

    iqb = IntQubit(7, 4)
    assert iqb.qubit_values == (0, 1, 1, 1)
    assert IntQubit(3) == IntQubit(3, 2)

    #test Dual Classes
    iqb = IntQubit(3)
    iqb_bra = IntQubitBra(3)
    assert iqb.dual_class() == IntQubitBra
    assert iqb_bra.dual_class() == IntQubit

    iqb = IntQubit(5)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1)

    iqb = IntQubit(4)
    iqb_bra = IntQubitBra(5)
    assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0)
    raises(ValueError, lambda: IntQubit(4, 1))

    raises(ValueError, lambda: IntQubit('5'))
    raises(ValueError, lambda: IntQubit(5, '5'))
    raises(ValueError, lambda: IntQubit(5, nqubits='5'))
    raises(TypeError, lambda: IntQubit(5, bad_arg=True))
示例#32
0
def black_box(qubits):
    return True if qubits == IntQubit(1, nqubits=qubits.nqubits) else False