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)))
def test_sample_state(): state = np.zeros(8, dtype=np.complex64) state[0] = 1 / np.sqrt(2) state[2] = 1 / np.sqrt(2) for _ in range(10): assert cirq.sample_state_vector(state, [2, 1, 0]) in [[[False, False, False]], [[False, True, False]]] # Partial sample is correct. for _ in range(10): assert cirq.sample_state_vector(state, [2]) == [[False]] assert cirq.sample_state_vector(state, [0]) == [[False]]
def test_sample_state(): state = np.zeros(8, dtype=np.complex64) state[0] = 1 / np.sqrt(2) state[2] = 1 / np.sqrt(2) for _ in range(10): sample = cirq.sample_state_vector(state, [2, 1, 0]) assert (np.array_equal(sample, [[False, False, False]]) or np.array_equal(sample, [[False, True, False]])) # Partial sample is correct. for _ in range(10): np.testing.assert_equal(cirq.sample_state_vector(state, [2]), [[False]]) np.testing.assert_equal(cirq.sample_state_vector(state, [0]), [[False]])
def test_sample_state_seed(): state = np.ones(2) / np.sqrt(2) samples = cirq.sample_state_vector(state, [0], repetitions=10, seed=1234) assert np.array_equal(samples, [[False], [True], [False], [True], [True], [False], [False], [True], [True], [True]]) samples = cirq.sample_state_vector(state, [0], repetitions=10, seed=np.random.RandomState(1234)) assert np.array_equal(samples, [[False], [True], [False], [True], [True], [False], [False], [True], [True], [True]])
def test_deprecated(): with cirq.testing.assert_logs('cirq.bloch_vector_from_state_vector', 'deprecated'): _ = cirq.sim.bloch_vector_from_state_vector(np.array([1, 0]), 0) with cirq.testing.assert_logs('cirq.density_matrix_from_state_vector', 'deprecated'): _ = cirq.sim.density_matrix_from_state_vector(np.array([1, 0])) with cirq.testing.assert_logs('cirq.dirac_notation', 'deprecated'): _ = cirq.sim.dirac_notation(np.array([1, 0])) with cirq.testing.assert_logs('cirq.to_valid_state_vector', 'deprecated'): _ = cirq.sim.to_valid_state_vector(0, 1) with cirq.testing.assert_logs('irq.validate_normalized_state', 'deprecated'): _ = cirq.sim.validate_normalized_state(np.array([1, 0], dtype=np.complex64), qid_shape=(2, )) with cirq.testing.assert_logs('cirq.STATE_VECTOR_LIKE', 'deprecated'): # Reason for type: ignore: https://github.com/python/mypy/issues/5354 _ = cirq.sim.STATE_VECTOR_LIKE # type: ignore state_vector = np.array([1, 1]) / np.sqrt(2) with cirq.testing.assert_logs('state', 'state_vector', 'deprecated'): # pylint: disable=unexpected-keyword-arg,no-value-for-parameter _ = cirq.sample_state_vector(state=state_vector, indices=[0]) with cirq.testing.assert_logs('state', 'state_vector', 'deprecated'): # pylint: disable=unexpected-keyword-arg,no-value-for-parameter _ = cirq.measure_state_vector(state=state_vector, indices=[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)))]] )
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)
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)
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_run_correlations(dtype): q0, q1 = cirq.LineQubit.range(2) simulator = TFWaveFunctionSimulator(dtype=dtype) circuit = cirq.Circuit.from_ops(cirq.H(q0), cirq.CNOT(q0, q1)) for _ in range(10): circuit_op = simulator.simulate(circuit) with tf.Session() as sess: wf = sess.run(circuit_op) measurements = cirq.sample_state_vector(wf.reshape(-1), [0, 1])
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)
def _sample_helper(sim, state, n_qubits, n_samples): if isinstance(sim, cirq.sim.sparse_simulator.Simulator): return cirq.sample_state_vector(state.final_state, list(range(n_qubits)), repetitions=n_samples) if isinstance(sim, cirq.DensityMatrixSimulator): return cirq.sample_density_matrix(state.final_density_matrix, list(range(n_qubits)), repetitions=n_samples) return NotImplemented
def test_run_bit_flips(dtype): q0, q1 = cirq.LineQubit.range(2) simulator = TFWaveFunctionSimulator(dtype=dtype) for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit.from_ops((cirq.X**b0)(q0), (cirq.X**b1)(q1)) circuit_op = simulator.simulate(circuit) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) wf = sess.run(circuit_op) measurements = cirq.sample_state_vector(wf, [0, 1]) np.testing.assert_array_almost_equal(measurements[0], [b0, b1]) expected_state = np.zeros(shape=(2, 2)) expected_state[b0][b1] = 1.0 cirq.testing.assert_allclose_up_to_global_phase(wf.reshape(-1), np.reshape( expected_state, 4), atol=1e-6)
def test_sample_no_indices(): state = cirq.to_valid_state_vector(0, 3) assert [[]] == cirq.sample_state_vector(state, [])
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)
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)))
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)))
def test_sample_state_index_out_of_range(): state = cirq.to_valid_state_vector(0, 3) with pytest.raises(IndexError, match='-2'): cirq.sample_state_vector(state, [-2]) with pytest.raises(IndexError, match='3'): cirq.sample_state_vector(state, [3])
def test_sample_state_not_power_of_two(): with pytest.raises(ValueError, match='3'): cirq.sample_state_vector(np.array([1, 0, 0]), [1]) with pytest.raises(ValueError, match='5'): cirq.sample_state_vector(np.array([0, 1, 0, 0, 0]), [1])
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)
def test_sample_empty_state(): state = np.array([1.0]) np.testing.assert_almost_equal(cirq.sample_state_vector(state, []), np.zeros(shape=(1, 0)))
def batch_sample(circuits, param_resolvers, n_samples, simulator): """Sample from circuits using parallel processing. Returns a `np.ndarray` containing n_samples samples from all the circuits in circuits given that the corresponding `cirq.ParamResolver` in `param_resolvers` was used to resolve any symbols. Specifically the returned array at index `i,j` will correspond to a `np.ndarray` of booleans representing bitstring `j` that was sampled from `circuits[i]`. Samples are drawn using the provided simulator object (Currently supported are `cirq.DensityMatrixSimulator` and `cirq.Simulator`). Note: In order to keep numpy shape consistent, smaller circuits will have sample bitstrings padded with -2 on "qubits that don't exist in the circuit". Args: circuits: Python `list` of `cirq.Circuit`s. param_resolvers: Python `list` of `cirq.ParamResolver`s, where `param_resolvers[i]` is the resolver to be used with `circuits[i]`. n_samples: `int` describing number of samples to draw from each circuit. simulator: Simulator object. Currently supported are `cirq.DensityMatrixSimulator` and `cirq.Simulator`. Returns: `np.ndarray` containing the samples with invalid qubits blanked out. It's shape is [len(circuits), n_samples, <# qubits in largest circuit>]. circuits that are smaller than #qubits in largest circuit have null qubits in bitstrings mapped to -2. """ _validate_inputs(circuits, param_resolvers, simulator, 'sample') if _check_empty(circuits): return np.zeros((0, 0, 0), dtype=np.int32) if not isinstance(n_samples, int): raise TypeError('n_samples must be an int.' 'Given: {}'.format(type(n_samples))) if n_samples <= 0: raise ValueError('n_samples must be > 0.') biggest_circuit = max(len(circuit.all_qubits()) for circuit in circuits) return_mem_shape = (len(circuits), n_samples, biggest_circuit) shared_array = _make_simple_view(return_mem_shape, -2, np.int32, 'i') if isinstance(simulator, cirq.DensityMatrixSimulator): post_process = lambda state, size, n_samples: \ cirq.sample_density_matrix( state.final_density_matrix, [i for i in range(size)], repetitions=n_samples) elif isinstance(simulator, cirq.Simulator): post_process = lambda state, size, n_samples: cirq.sample_state_vector( state.final_state_vector, list(range(size)), repetitions=n_samples) else: raise TypeError( 'Simulator {} is not supported by batch_sample.'.format( type(simulator))) input_args = list( _prep_pool_input_args(range(len(circuits)), circuits, param_resolvers, [n_samples] * len(circuits))) with ProcessPool(processes=None, initializer=_setup_dict, initargs=(shared_array, return_mem_shape, simulator, post_process)) as pool: pool.starmap(_sample_worker_func, input_args) return _convert_simple_view_to_result(shared_array, np.int32, return_mem_shape)
def test_sample_no_indices_repetitions(): state = cirq.to_valid_state_vector(0, 3) assert [[], []] == cirq.sample_state_vector(state, [], repetitions=2)
def test_sample_empty_state(): state = np.array([]) assert cirq.sample_state_vector(state, []) == [[]]
def test_sample_no_repetitions(): state = cirq.to_valid_state_vector(0, 3) assert cirq.sample_state_vector(state, [1], repetitions=0) == [[]]