예제 #1
0
def test_to_valid_state_vector():
    with pytest.raises(ValueError, match='Computational basis state is out of range'):
        cirq.to_valid_state_vector(2, 1)
    np.testing.assert_almost_equal(
        cirq.to_valid_state_vector(np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64), 2),
        np.array([1.0, 0.0, 0.0, 0.0]),
    )
    np.testing.assert_almost_equal(
        cirq.to_valid_state_vector(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.complex64), 2),
        np.array([0.0, 1.0, 0.0, 0.0]),
    )
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(0, 2), np.array([1.0, 0.0, 0.0, 0.0]))
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(1, 2), np.array([0.0, 1.0, 0.0, 0.0]))

    v = cirq.to_valid_state_vector([0, 1, 2, 0], qid_shape=(3, 3, 3, 3))
    assert v.shape == (3 ** 4,)
    assert v[6 + 9] == 1

    v = cirq.to_valid_state_vector([False, True, False, False], num_qubits=4)
    assert v.shape == (16,)
    assert v[4] == 1

    v = cirq.to_valid_state_vector([0, 1, 0, 0], num_qubits=2)
    assert v.shape == (4,)
    assert v[1] == 1

    v = cirq.to_valid_state_vector(np.array([1, 0], dtype=np.complex64), qid_shape=(2, 1))
    assert v.shape == (2,)
    assert v[0] == 1
예제 #2
0
def test_invalid_to_valid_state_vector():
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(
            np.array([1.0, 0.0], dtype=np.complex64), 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(-1, 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(5, 2)
    with pytest.raises(TypeError):
        _ = cirq.to_valid_state_vector('not an int', 2)
예제 #3
0
def test_to_valid_state_vector():
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(
        np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64), 2),
        np.array([1.0, 0.0, 0.0, 0.0]))
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(
        np.array([0.0, 1.0, 0.0, 0.0], dtype=np.complex64), 2),
        np.array([0.0, 1.0, 0.0, 0.0]))
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(0, 2),
                                   np.array([1.0, 0.0, 0.0, 0.0]))
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(1, 2),
                                   np.array([0.0, 1.0, 0.0, 0.0]))
예제 #4
0
def test_invalid_to_valid_state_vector():
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(
            np.array([1.0, 0.0], dtype=np.complex64), 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(-1, 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(5, 2)
    with pytest.raises(TypeError):
        _ = cirq.to_valid_state_vector('not an int', 2)
    with pytest.raises(ValueError, match=r'num_qubits != len\(qid_shape\)'):
        _ = cirq.to_valid_state_vector(0, 5, qid_shape=(1, 2, 3))
def states_with_phases(st: np.ndarray):
    """Returns several states similar to st with modified global phases."""
    st = np.array(st, dtype="complex64")
    yield st
    phases = [np.exp(1j * np.pi / 6), -1j, 1j, -1, np.exp(-1j * np.pi / 28)]
    random = np.random.RandomState(1)
    for _ in range(3):
        curr_st = copy.deepcopy(st)
        cirq.to_valid_state_vector(curr_st, num_qubits=2)
        for i in range(4):
            phase = random.choice(phases)
            curr_st[i] *= phase
        yield curr_st
예제 #6
0
def test_to_valid_state_vector():
    np.testing.assert_almost_equal(
        cirq.to_valid_state_vector(
            np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64), 2),
        np.array([1.0, 0.0, 0.0, 0.0]))
    np.testing.assert_almost_equal(
        cirq.to_valid_state_vector(
            np.array([0.0, 1.0, 0.0, 0.0], dtype=np.complex64), 2),
        np.array([0.0, 1.0, 0.0, 0.0]))
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(0, 2),
                                   np.array([1.0, 0.0, 0.0, 0.0]))
    np.testing.assert_almost_equal(cirq.to_valid_state_vector(1, 2),
                                   np.array([0.0, 1.0, 0.0, 0.0]))

    v = cirq.to_valid_state_vector([0, 1, 2, 0], qid_shape=(3, 3, 3, 3))
    assert v.shape == (3**4, )
    assert v[6 + 9] == 1

    v = cirq.to_valid_state_vector([False, True, False, False], num_qubits=4)
    assert v.shape == (16, )
    assert v[4] == 1

    v = cirq.to_valid_state_vector([0, 1, 0, 0], num_qubits=2)
    assert v.shape == (4, )
    assert v[1] == 1

    v = cirq.to_valid_state_vector(np.array([1, 0], dtype=np.complex64),
                                   qid_shape=(2, 1))
    assert v.shape == (2, )
    assert v[0] == 1
예제 #7
0
def test_measure_state_partial_indices():
    for index in range(3):
        for x in range(8):
            initial_state = cirq.to_valid_state_vector(x, 3)
            bits, state = cirq.measure_state_vector(initial_state, [index])
            np.testing.assert_almost_equal(state, initial_state)
            assert bits == [bool(1 & (x >> (2 - index)))]
예제 #8
0
def test_sample_state_partial_indices():
    for index in range(3):
        for x in range(8):
            state = cirq.to_valid_state_vector(x, 3)
            np.testing.assert_equal(
                cirq.sample_state_vector(state, [index]), [[bool(1 & (x >> (2 - index)))]]
            )
예제 #9
0
def test_measure_state_partial_indices_all_orders():
    for perm in itertools.permutations([0, 1, 2]):
        for x in range(8):
            initial_state = cirq.to_valid_state_vector(x, 3)
            bits, state = cirq.measure_state_vector(initial_state, perm)
            np.testing.assert_almost_equal(state, initial_state)
            assert bits == [bool(1 & (x >> (2 - p))) for p in perm]
예제 #10
0
def test_measure_state_no_indices_out_is_state():
    initial_state = cirq.to_valid_state_vector(0, 3)
    bits, state = cirq.measure_state_vector(initial_state, [],
                                            out=initial_state)
    assert [] == bits
    np.testing.assert_almost_equal(state, initial_state)
    assert state is initial_state
예제 #11
0
def test_sample_state_partial_indices_all_orders():
    for perm in itertools.permutations([0, 1, 2]):
        for x in range(8):
            state = cirq.to_valid_state_vector(x, 3)
            expected = [[bool(1 & (x >> (2 - p))) for p in perm]]
            np.testing.assert_equal(cirq.sample_state_vector(state, perm),
                                    expected)
예제 #12
0
    def __init__(self,
                 sphere_radius: int = 5,
                 state_vector: cirq.STATE_VECTOR_LIKE = None):
        """Initializes a BlochSphere.

        Also initializes it's parent class Widget with the bundle file provided.

        Args:
            sphere_radius: the radius of the bloch sphere in the three.js diagram.
                The default value is 5.
            state_vector: a state vector to pass in to be represented.

        Raises:
            ValueError: If the `sphere_radius` is not positive or the `state_vector` is not
                supplied.
        """
        super().__init__()
        if sphere_radius <= 0:
            raise ValueError('You must input a positive radius for the sphere')
        self.sphere_radius = sphere_radius

        if state_vector is None:
            raise ValueError(
                'No state vector given in BlochSphere initialization')

        self.bloch_vector = cirq.bloch_vector_from_state_vector(
            cirq.to_valid_state_vector(state_vector, num_qubits=1), 0)
예제 #13
0
def test_sample_state_repetitions():
    for perm in itertools.permutations([0, 1, 2]):
        for x in range(8):
            state = cirq.to_valid_state_vector(x, 3)
            expected = [[bool(1 & (x >> (2 - p))) for p in perm]] * 3

            result = cirq.sample_state_vector(state, perm, repetitions=3)
            np.testing.assert_equal(result, expected)
예제 #14
0
def test_measure_state_no_indices_out_is_not_state():
    initial_state = cirq.to_valid_state_vector(0, 3)
    out = np.zeros_like(initial_state)
    bits, state = cirq.measure_state_vector(initial_state, [], out=out)
    assert [] == bits
    np.testing.assert_almost_equal(state, initial_state)
    assert state is out
    assert out is not initial_state
예제 #15
0
def test_sample_no_repetitions():
    state = cirq.to_valid_state_vector(0, 3)
    np.testing.assert_almost_equal(
        cirq.sample_state_vector(state, [1], repetitions=0),
        np.zeros(shape=(0, 1)))
    np.testing.assert_almost_equal(
        cirq.sample_state_vector(state, [1, 2], repetitions=0),
        np.zeros(shape=(0, 2)))
예제 #16
0
def test_measure_state_reshape():
    results = []
    for x in range(8):
        initial_state = np.reshape(cirq.to_valid_state_vector(x, 3), [2] * 3)
        bits, state = cirq.measure_state_vector(initial_state, [2, 1, 0])
        results.append(bits)
        np.testing.assert_almost_equal(state, initial_state)
    expected = [list(reversed(x)) for x in list(itertools.product([False, True], repeat=3))]
    assert results == expected
예제 #17
0
def test_sample_state_big_endian():
    results = []
    for x in range(8):
        state = cirq.to_valid_state_vector(x, 3)
        sample = cirq.sample_state_vector(state, [2, 1, 0])
        results.append(sample)
    expecteds = [[list(reversed(x))] for x in list(itertools.product([False, True], repeat=3))]
    for result, expected in zip(results, expecteds):
        np.testing.assert_equal(result, expected)
예제 #18
0
def test_sample_state_big_endian():
    results = []
    for x in range(8):
        state = cirq.to_valid_state_vector(x, 3)
        sample = cirq.sample_state_vector(state, [2, 1, 0])
        results.append(sample)
    expected = [[list(reversed(x))]
                for x in list(itertools.product([False, True], repeat=3))]
    assert results == expected
def test_prepare_two_qubit_state_using_cz(state):
    state = cirq.to_valid_state_vector(state, num_qubits=2)
    q = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(cirq.prepare_two_qubit_state_using_cz(*q, state))
    ops_cz = [*circuit.findall_operations(lambda op: op.gate == cirq.CZ)]
    ops_2q = [*circuit.findall_operations(lambda op: cirq.num_qubits(op) > 1)]
    assert ops_cz == ops_2q
    assert len(ops_cz) <= 1
    assert cirq.allclose_up_to_global_phase(circuit.final_state_vector(),
                                            state)
예제 #20
0
def test_act_on_args_pure_state_creation():
    sim = cirq.Simulator()
    qids = cirq.LineQubit.range(3)
    shape = cirq.qid_shape(qids)
    args = sim._create_act_on_args(1, qids)
    values = list(args.values())
    arg = (
        values[0]
        .kronecker_product(values[1])
        .kronecker_product(values[2])
        .transpose_to_qubit_order(qids)
    )
    expected = cirq.to_valid_state_vector(1, len(qids), qid_shape=shape)
    np.testing.assert_allclose(arg.target_tensor, expected.reshape(shape))
def test_prepare_two_qubit_state_using_sqrt_iswap(state, use_sqrt_iswap_inv):
    state = cirq.to_valid_state_vector(state, num_qubits=2)
    q = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(
        cirq.prepare_two_qubit_state_using_sqrt_iswap(
            *q, state, use_sqrt_iswap_inv=use_sqrt_iswap_inv))
    sqrt_iswap_gate = cirq.SQRT_ISWAP_INV if use_sqrt_iswap_inv else cirq.SQRT_ISWAP
    ops_iswap = [
        *circuit.findall_operations(lambda op: op.gate == sqrt_iswap_gate)
    ]
    ops_2q = [*circuit.findall_operations(lambda op: cirq.num_qubits(op) > 1)]
    assert ops_iswap == ops_2q
    assert len(ops_iswap) <= 1
    assert cirq.allclose_up_to_global_phase(circuit.final_state_vector(),
                                            state)
예제 #22
0
def test_sample_state_partial_indices_oder():
    for x in range(8):
        state = cirq.to_valid_state_vector(x, 3)
        expected = [[bool(1 & (x >> 0)), bool(1 & (x >> 1))]]
        np.testing.assert_equal(cirq.sample_state_vector(state, [2, 1]),
                                expected)
예제 #23
0
def test_measure_state_index_out_of_range():
    state = cirq.to_valid_state_vector(0, 3)
    with pytest.raises(IndexError, match='-2'):
        cirq.measure_state_vector(state, [-2])
    with pytest.raises(IndexError, match='3'):
        cirq.measure_state_vector(state, [3])
예제 #24
0
def test_measure_state_partial_indices_order():
    for x in range(8):
        initial_state = cirq.to_valid_state_vector(x, 3)
        bits, state = cirq.measure_state_vector(initial_state, [2, 1])
        np.testing.assert_almost_equal(state, initial_state)
        assert bits == [bool(1 & (x >> 0)), bool(1 & (x >> 1))]
예제 #25
0
def test_sample_no_indices_repetitions():
    state = cirq.to_valid_state_vector(0, 3)
    np.testing.assert_almost_equal(
        cirq.sample_state_vector(state, [], repetitions=2),
        np.zeros(shape=(2, 0)))
예제 #26
0
def test_sample_no_indices():
    state = cirq.to_valid_state_vector(0, 3)
    np.testing.assert_almost_equal(cirq.sample_state_vector(state, []),
                                   np.zeros(shape=(1, 0)))
예제 #27
0
def test_sample_state_negative_repetitions():
    state = cirq.to_valid_state_vector(0, 3)
    with pytest.raises(ValueError, match='-1'):
        cirq.sample_state_vector(state, [1], repetitions=-1)
예제 #28
0
def test_to_valid_state_vector_creates_new_copy():
    state = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64)
    out = cirq.to_valid_state_vector(state, 2)
    assert out is not state
예제 #29
0
def test_invalid_to_valid_state_vector():
    with pytest.raises(ValueError, match="Must specify"):
        _ = cirq.to_valid_state_vector(np.array([1]))

    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(np.array([1.0, 0.0], dtype=np.complex64), 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(-1, 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(5, 2)
    with pytest.raises(TypeError, match='Unrecognized type of STATE_LIKE'):
        _ = cirq.to_valid_state_vector('0000', 2)
    with pytest.raises(TypeError, match='Unrecognized type of STATE_LIKE'):
        _ = cirq.to_valid_state_vector('not an int', 2)
    with pytest.raises(ValueError, match=r'num_qubits != len\(qid_shape\)'):
        _ = cirq.to_valid_state_vector(0, 5, qid_shape=(1, 2, 3))

    with pytest.raises(ValueError, match='out of bounds'):
        _ = cirq.to_valid_state_vector([3], qid_shape=(3,))
    with pytest.raises(ValueError, match='out of bounds'):
        _ = cirq.to_valid_state_vector([-1], qid_shape=(3,))
    with pytest.raises(ValueError, match='but its shape was neither'):
        _ = cirq.to_valid_state_vector([], qid_shape=(3,))
    with pytest.raises(ValueError, match='but its shape was neither'):
        _ = cirq.to_valid_state_vector([0, 1], num_qubits=3)
    with pytest.raises(ValueError, match='ambiguous'):
        _ = cirq.to_valid_state_vector([1, 0], qid_shape=(2, 1))
    with pytest.raises(ValueError, match='ambiguous'):
        _ = cirq.to_valid_state_vector(np.array([1, 0], dtype=np.int64), qid_shape=(2, 1))
예제 #30
0
def test_invalid_to_valid_state_vector():
    with pytest.raises(ValueError, match="Please specify"):
        _ = cirq.to_valid_state_vector(np.array([1]))

    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(
            np.array([1.0, 0.0], dtype=np.complex64), 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(-1, 2)
    with pytest.raises(ValueError):
        _ = cirq.to_valid_state_vector(5, 2)
    with pytest.raises(ValueError, match='Invalid quantum state'):
        _ = cirq.to_valid_state_vector('0000', 2)
    with pytest.raises(ValueError, match='Invalid quantum state'):
        _ = cirq.to_valid_state_vector('not an int', 2)
    with pytest.raises(ValueError, match=r'num_qubits != len\(qid_shape\)'):
        _ = cirq.to_valid_state_vector(0, 5, qid_shape=(1, 2, 3))

    with pytest.raises(ValueError, match='out of bounds'):
        _ = cirq.to_valid_state_vector([3], qid_shape=(3, ))
    with pytest.raises(ValueError, match='out of bounds'):
        _ = cirq.to_valid_state_vector([-1], qid_shape=(3, ))
    with pytest.raises(ValueError, match='Invalid quantum state'):
        _ = cirq.to_valid_state_vector([], qid_shape=(3, ))
    with pytest.raises(ValueError, match='Invalid quantum state'):
        _ = cirq.to_valid_state_vector([0, 1], num_qubits=3)
    with pytest.raises(ValueError, match='ambiguous'):
        _ = cirq.to_valid_state_vector([1, 0], qid_shape=(2, 1))
    with pytest.raises(ValueError, match='ambiguous'):
        _ = cirq.to_valid_state_vector(np.array([1, 0], dtype=np.int64),
                                       qid_shape=(2, 1))