def test_act_using_probabilistic_single_qubit_channel():
    class ProbabilisticSorX(cirq.Gate):
        def num_qubits(self) -> int:
            return 1

        def _kraus_(self):
            return [
                cirq.unitary(cirq.S) * np.sqrt(1 / 3),
                cirq.unitary(cirq.X) * np.sqrt(2 / 3),
            ]

    initial_state = cirq.testing.random_superposition(dim=16).reshape(
        (2, ) * 4)
    mock_prng = mock.Mock()

    mock_prng.random.return_value = 1 / 3 + 1e-6
    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty_like(initial_state),
        qubits=cirq.LineQubit.range(4),
        prng=mock_prng,
        log_of_measurement_results={},
        initial_state=np.copy(initial_state),
        dtype=initial_state.dtype,
    )
    cirq.act_on(ProbabilisticSorX(), args, [cirq.LineQubit(2)])
    np.testing.assert_allclose(
        args.target_tensor.reshape(16),
        cirq.final_state_vector(
            cirq.X(cirq.LineQubit(2))**-1,
            initial_state=initial_state,
            qubit_order=cirq.LineQubit.range(4),
        ),
        atol=1e-8,
    )

    mock_prng.random.return_value = 1 / 3 - 1e-6
    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty_like(initial_state),
        qubits=cirq.LineQubit.range(4),
        prng=mock_prng,
        log_of_measurement_results={},
        initial_state=np.copy(initial_state),
        dtype=initial_state.dtype,
    )
    cirq.act_on(ProbabilisticSorX(), args, [cirq.LineQubit(2)])
    np.testing.assert_allclose(
        args.target_tensor.reshape(16),
        cirq.final_state_vector(
            cirq.S(cirq.LineQubit(2)),
            initial_state=initial_state,
            qubit_order=cirq.LineQubit.range(4),
        ),
        atol=1e-8,
    )
def test_probability_comes_up_short_results_in_fallback():
    class Short(cirq.Gate):
        def num_qubits(self) -> int:
            return 1

        def _kraus_(self):
            return [
                cirq.unitary(cirq.X) * np.sqrt(0.999),
                np.eye(2) * 0,
            ]

    mock_prng = mock.Mock()
    mock_prng.random.return_value = 0.9999

    args = cirq.ActOnStateVectorArgs(
        target_tensor=np.array([1, 0], dtype=np.complex64),
        available_buffer=np.empty(2, dtype=np.complex64),
        qubits=cirq.LineQubit.range(1),
        prng=mock_prng,
        log_of_measurement_results={},
    )

    cirq.act_on(Short(), args, cirq.LineQubit.range(1))

    np.testing.assert_allclose(
        args.target_tensor,
        np.array([0, 1]),
    )
def test_pretty_print():
    args = cirq.ActOnStateVectorArgs(
        target_tensor=np.array([1]),
        available_buffer=np.array([1]),
        prng=np.random.RandomState(0),
        log_of_measurement_results={},
        qubits=[],
    )
    final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator())
    result = cirq.StateVectorTrialResult(cirq.ParamResolver(), {}, final_step_result)

    # Test Jupyter console output from
    class FakePrinter:
        def __init__(self):
            self.text_pretty = ''

        def text(self, to_print):
            self.text_pretty += to_print

    p = FakePrinter()
    result._repr_pretty_(p, False)
    assert p.text_pretty == 'measurements: (no measurements)\n\nphase:\noutput vector: |⟩'

    # Test cycle handling
    p = FakePrinter()
    result._repr_pretty_(p, True)
    assert p.text_pretty == 'StateVectorTrialResult(...)'
def test_state_vector_trial_result_repr():
    q0 = cirq.NamedQubit('a')
    args = cirq.ActOnStateVectorArgs(
        target_tensor=np.array([0, 1], dtype=np.int32),
        available_buffer=np.array([0, 1], dtype=np.int32),
        prng=np.random.RandomState(0),
        log_of_measurement_results={},
        qubits=[q0],
    )
    final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator())
    trial_result = cirq.StateVectorTrialResult(
        params=cirq.ParamResolver({'s': 1}),
        measurements={'m': np.array([[1]], dtype=np.int32)},
        final_step_result=final_step_result,
    )
    expected_repr = (
        "cirq.StateVectorTrialResult("
        "params=cirq.ParamResolver({'s': 1}), "
        "measurements={'m': np.array([[1]], dtype=np.int32)}, "
        "final_step_result=cirq.SparseSimulatorStep("
        "sim_state=cirq.ActOnStateVectorArgs("
        "target_tensor=np.array([0, 1], dtype=np.int32), "
        "available_buffer=np.array([0, 1], dtype=np.int32), "
        "qubits=(cirq.NamedQubit('a'),), "
        "log_of_measurement_results={}), "
        "dtype=np.complex64))"
    )
    assert repr(trial_result) == expected_repr
    assert eval(expected_repr) == trial_result
示例#5
0
def test_reset_act_on():
    with pytest.raises(TypeError, match="Failed to act"):
        cirq.act_on(cirq.ResetChannel(), object())

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(index=(1, 1, 1, 1, 1),
                                   shape=(2, 2, 2, 2, 2),
                                   dtype=np.complex64),
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        axes=[1],
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )

    cirq.act_on(cirq.ResetChannel(), args)
    assert args.log_of_measurement_results == {}
    np.testing.assert_allclose(
        args.target_tensor,
        cirq.one_hot(index=(1, 0, 1, 1, 1),
                     shape=(2, 2, 2, 2, 2),
                     dtype=np.complex64),
    )

    cirq.act_on(cirq.ResetChannel(), args)
    assert args.log_of_measurement_results == {}
    np.testing.assert_allclose(
        args.target_tensor,
        cirq.one_hot(index=(1, 0, 1, 1, 1),
                     shape=(2, 2, 2, 2, 2),
                     dtype=np.complex64),
    )
示例#6
0
def test_reset_act_on():
    with pytest.raises(TypeError, match="Failed to act"):
        cirq.act_on(cirq.ResetChannel(), DummyActOnArgs(), qubits=())

    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2), dtype=np.complex64),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
        initial_state=cirq.one_hot(index=(1, 1, 1, 1, 1),
                                   shape=(2, 2, 2, 2, 2),
                                   dtype=np.complex64),
        dtype=np.complex64,
    )

    cirq.act_on(cirq.ResetChannel(), args, [cirq.LineQubit(1)])
    assert args.log_of_measurement_results == {}
    np.testing.assert_allclose(
        args.target_tensor,
        cirq.one_hot(index=(1, 0, 1, 1, 1),
                     shape=(2, 2, 2, 2, 2),
                     dtype=np.complex64),
    )

    cirq.act_on(cirq.ResetChannel(), args, [cirq.LineQubit(1)])
    assert args.log_of_measurement_results == {}
    np.testing.assert_allclose(
        args.target_tensor,
        cirq.one_hot(index=(1, 0, 1, 1, 1),
                     shape=(2, 2, 2, 2, 2),
                     dtype=np.complex64),
    )
示例#7
0
def test_act_on_state_vector():
    a, b = [cirq.LineQubit(3), cirq.LineQubit(1)]
    m = cirq.measure(a, b, key='out', invert_mask=(True, ))

    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
        initial_state=cirq.one_hot(shape=(2, 2, 2, 2, 2), dtype=np.complex64),
        dtype=np.complex64,
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 0]}

    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
        initial_state=cirq.one_hot(index=(0, 1, 0, 0, 0),
                                   shape=(2, 2, 2, 2, 2),
                                   dtype=np.complex64),
        dtype=np.complex64,
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 1]}

    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
        initial_state=cirq.one_hot(index=(0, 1, 0, 1, 0),
                                   shape=(2, 2, 2, 2, 2),
                                   dtype=np.complex64),
        dtype=np.complex64,
    )
    cirq.act_on(m, args)
    datastore = cast(cirq.ClassicalDataDictionaryStore, args.classical_data)
    out = cirq.MeasurementKey('out')
    assert args.log_of_measurement_results == {'out': [0, 1]}
    assert datastore.records[out] == [(0, 1)]
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [0, 1]}
    assert datastore.records[out] == [(0, 1), (0, 1)]
示例#8
0
def test_act_on():
    a, b = cirq.LineQubit.range(2)
    m = cirq.measure(a, b, key='out', invert_mask=(True, ))

    with pytest.raises(TypeError, match="Failed to act"):
        cirq.act_on(m, object())

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(shape=(2, 2, 2, 2, 2), dtype=np.complex64),
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        axes=[3, 1],
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 0]}

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(index=(0, 1, 0, 0, 0),
                                   shape=(2, 2, 2, 2, 2),
                                   dtype=np.complex64),
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        axes=[3, 1],
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [1, 1]}

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(index=(0, 1, 0, 1, 0),
                                   shape=(2, 2, 2, 2, 2),
                                   dtype=np.complex64),
        available_buffer=np.empty(shape=(2, 2, 2, 2, 2)),
        axes=[3, 1],
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [0, 1]}

    with pytest.raises(ValueError, match="already logged to key"):
        cirq.act_on(m, args)
示例#9
0
def test_act_on_qutrit():
    a, b = [cirq.LineQid(3, dimension=3), cirq.LineQid(1, dimension=3)]
    m = cirq.measure(a, b, key='out', invert_mask=(True, ))

    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty(shape=(3, 3, 3, 3, 3)),
        qubits=cirq.LineQid.range(5, dimension=3),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
        initial_state=cirq.one_hot(index=(0, 2, 0, 2, 0),
                                   shape=(3, 3, 3, 3, 3),
                                   dtype=np.complex64),
        dtype=np.complex64,
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [2, 2]}

    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty(shape=(3, 3, 3, 3, 3)),
        qubits=cirq.LineQid.range(5, dimension=3),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
        initial_state=cirq.one_hot(index=(0, 1, 0, 2, 0),
                                   shape=(3, 3, 3, 3, 3),
                                   dtype=np.complex64),
        dtype=np.complex64,
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [2, 1]}

    args = cirq.ActOnStateVectorArgs(
        available_buffer=np.empty(shape=(3, 3, 3, 3, 3)),
        qubits=cirq.LineQid.range(5, dimension=3),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
        initial_state=cirq.one_hot(index=(0, 2, 0, 1, 0),
                                   shape=(3, 3, 3, 3, 3),
                                   dtype=np.complex64),
        dtype=np.complex64,
    )
    cirq.act_on(m, args)
    assert args.log_of_measurement_results == {'out': [0, 2]}
 def get_result(state: np.ndarray, sample: float):
     mock_prng.random.return_value = sample
     args = cirq.ActOnStateVectorArgs(
         target_tensor=np.copy(state),
         available_buffer=np.empty_like(state),
         qubits=cirq.LineQubit.range(4),
         prng=mock_prng,
         log_of_measurement_results={},
     )
     cirq.act_on(Decay11(), args, [cirq.LineQubit(1), cirq.LineQubit(3)])
     return args.target_tensor
示例#11
0
def test_cannot_act():
    class NoDetails:
        pass

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(shape=(2, 2, 2), dtype=np.complex64),
        available_buffer=np.empty((2, 2, 2), dtype=np.complex64),
        axes=[1],
        prng=np.random.RandomState(),
        log_of_measurement_results={})

    with pytest.raises(TypeError, match="Failed to act"):
        cirq.act_on(NoDetails(), args)
def test_cannot_act():
    class NoDetails:
        pass

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(shape=(2, 2, 2), dtype=np.complex64),
        available_buffer=np.empty((2, 2, 2), dtype=np.complex64),
        qubits=cirq.LineQubit.range(3),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )

    with pytest.raises(TypeError, match="Can't simulate operations"):
        cirq.act_on(NoDetails(), args, qubits=())
def test_infer_target_tensor():
    dtype = np.complex64
    args = cirq.ActOnStateVectorArgs(
        qubits=cirq.LineQubit.range(2),
        initial_state=np.array([1.0, 0.0, 0.0, 0.0], dtype=dtype),
        dtype=dtype,
    )
    np.testing.assert_almost_equal(
        args.target_tensor,
        np.array([[1.0 + 0.0j, 0.0 + 0.0j], [0.0 + 0.0j, 0.0 + 0.0j]],
                 dtype=dtype),
    )

    args = cirq.ActOnStateVectorArgs(
        qubits=cirq.LineQubit.range(2),
        initial_state=0,
        dtype=dtype,
    )
    np.testing.assert_almost_equal(
        args.target_tensor,
        np.array([[1.0 + 0.0j, 0.0 + 0.0j], [0.0 + 0.0j, 0.0 + 0.0j]],
                 dtype=dtype),
    )
def test_with_qubits():
    original = cirq.ActOnStateVectorArgs(
        qubits=cirq.LineQubit.range(2),
        initial_state=1,
        dtype=np.complex64,
    )
    extened = original.with_qubits(cirq.LineQubit.range(2, 4))
    np.testing.assert_almost_equal(
        extened.target_tensor,
        cirq.state_vector_kronecker_product(
            np.array([[0.0 + 0.0j, 1.0 + 0.0j], [0.0 + 0.0j, 0.0 + 0.0j]],
                     dtype=np.complex64),
            np.array([[1.0 + 0.0j, 0.0 + 0.0j], [0.0 + 0.0j, 0.0 + 0.0j]],
                     dtype=np.complex64),
        ),
    )
def test_str_big():
    qs = cirq.LineQubit.range(20)
    args = cirq.ActOnStateVectorArgs(
        target_tensor=np.array([1] * 2 ** 10),
        available_buffer=np.array([1] * 2 ** 10),
        prng=np.random.RandomState(0),
        log_of_measurement_results={},
        qubits=qs,
    )
    final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator())
    result = cirq.StateVectorTrialResult(
        cirq.ParamResolver(),
        {},
        final_step_result,
    )
    assert 'output vector: [1 1 1 ..' in str(result)
def test_default_parameter():
    dtype = np.complex64
    tensor = cirq.one_hot(shape=(2, 2, 2), dtype=np.complex64)
    qubits = cirq.LineQubit.range(3)
    args = cirq.ActOnStateVectorArgs(
        qubits=qubits,
        initial_state=tensor,
        dtype=dtype,
    )
    qid_shape = cirq.protocols.qid_shape(qubits)
    tensor = np.reshape(tensor, qid_shape)
    np.testing.assert_almost_equal(
        args.target_tensor,
        tensor,
    )
    assert args.available_buffer.shape == tensor.shape
    assert args.available_buffer.dtype == tensor.dtype
示例#17
0
def test_str_big():
    qs = cirq.LineQubit.range(10)
    args = cirq.ActOnStateVectorArgs(
        prng=np.random.RandomState(0),
        log_of_measurement_results={},
        qubits=qs,
        initial_state=np.array([1] * 2**10, dtype=np.complex64) * 0.03125,
        dtype=np.complex64,
    )
    final_step_result = cirq.SparseSimulatorStep(args, cirq.Simulator())
    result = cirq.StateVectorTrialResult(
        cirq.ParamResolver(),
        {},
        final_step_result,
    )
    assert 'output vector: [0.03125+0.j 0.03125+0.j 0.03125+0.j ..' in str(
        result)
示例#18
0
def test_decomposed_fallback():
    class Composite(cirq.Gate):
        def num_qubits(self) -> int:
            return 1

        def _decompose_(self, qubits):
            yield cirq.X(*qubits)

    args = cirq.ActOnStateVectorArgs(
        target_tensor=cirq.one_hot(shape=(2, 2, 2), dtype=np.complex64),
        available_buffer=np.empty((2, 2, 2), dtype=np.complex64),
        axes=[1],
        prng=np.random.RandomState(),
        log_of_measurement_results={})

    cirq.act_on(Composite(), args)
    np.testing.assert_allclose(
        args.target_tensor,
        cirq.one_hot(index=(0, 1, 0), shape=(2, 2, 2), dtype=np.complex64))
def test_simulator_step_state_mixin():
    qubits = cirq.LineQubit.range(2)
    args = cirq.ActOnStateVectorArgs(
        log_of_measurement_results={'m': np.array([1, 2])},
        target_tensor=np.array([0, 1, 0, 0]).reshape((2, 2)),
        available_buffer=np.array([0, 1, 0, 0]).reshape((2, 2)),
        prng=cirq.value.parse_random_state(0),
        qubits=qubits,
    )
    result = cirq.SparseSimulatorStep(
        sim_state=args,
        dtype=np.complex64,
        simulator=None,  # type: ignore
    )
    rho = np.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
    np.testing.assert_array_almost_equal(rho, result.density_matrix_of(qubits))
    bloch = np.array([0, 0, -1])
    np.testing.assert_array_almost_equal(bloch, result.bloch_vector_of(qubits[1]))

    assert result.dirac_notation() == '|01⟩'
def test_positional_argument():
    with cirq.testing.assert_deprecated(
            'specify all the arguments with keywords', deadline='v0.15'):
        cirq.ActOnStateVectorArgs(
            np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64))
def test_axes_deprecation():
    rng = np.random.RandomState()
    state = np.array([1, 0], dtype=np.complex64)
    buf = np.array([1, 0], dtype=np.complex64)
    qids = tuple(cirq.LineQubit.range(1))
    log = {}

    # No kwargs
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        args = cirq.ActOnStateVectorArgs(state, buf, (1, ), rng, log,
                                         qids)  # type: ignore
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        assert args.axes == (1, )
    assert args.prng is rng
    assert args.target_tensor is state
    assert args.available_buffer is buf
    assert args.qubits is qids
    assert args.log_of_measurement_results is log

    # kwargs no axes
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        args = cirq.ActOnStateVectorArgs(
            state,
            buf,
            (1, ),  # type: ignore
            qubits=qids,
            prng=rng,
            log_of_measurement_results=log,
        )
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        assert args.axes == (1, )
    assert args.prng is rng
    assert args.target_tensor is state
    assert args.available_buffer is buf
    assert args.qubits is qids
    assert args.log_of_measurement_results is log

    # kwargs incl axes
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        args = cirq.ActOnStateVectorArgs(
            state,
            buf,
            axes=(1, ),
            qubits=qids,
            prng=rng,
            log_of_measurement_results=log,
        )
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        assert args.axes == (1, )
    assert args.prng is rng
    assert args.target_tensor is state
    assert args.available_buffer is buf
    assert args.qubits is qids
    assert args.log_of_measurement_results is log

    # all kwargs
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        args = cirq.ActOnStateVectorArgs(
            target_tensor=state,
            available_buffer=buf,
            axes=(1, ),
            qubits=qids,
            prng=rng,
            log_of_measurement_results=log,
        )
    with cirq.testing.assert_deprecated("axes", deadline="v0.13"):
        assert args.axes == (1, )
    assert args.prng is rng
    assert args.target_tensor is state
    assert args.available_buffer is buf
    assert args.qubits is qids
    assert args.log_of_measurement_results is log
def test_deprecated_target_tensor():
    with cirq.testing.assert_deprecated('Use initial_state instead',
                                        deadline='v0.15'):
        cirq.ActOnStateVectorArgs(
            target_tensor=np.array([1.0, 0.0, 0.0, 0.0], dtype=np.complex64))
def test_shallow_copy_buffers():
    args = cirq.ActOnStateVectorArgs()
    copy = args.copy(deep_copy_buffers=False)
    assert copy.available_buffer is args.available_buffer