def test_gate_result_initialization_errors(): """Check ``ValueError``s during the initialization of ``GateResult`` object.""" from qibo.tensorflow import measurements decimal_samples = np.random.randint(0, 4, (100, )) binary_samples = np.random.randint(0, 2, (100, 2)) with pytest.raises(ValueError): res = measurements.GateResult((0, 1), decimal_samples=decimal_samples, binary_samples=binary_samples) binary_samples = np.random.randint(0, 2, (100, 4)) with pytest.raises(ValueError): res = measurements.GateResult((0, 1), binary_samples=binary_samples)
def _execute(self, initial_state: Optional[InitStateType] = None, nshots: Optional[int] = None) -> OutputType: """Performs ``circuit.execute``.""" state = self.get_initial_state(initial_state) special_gates = iter(self.queues.special_queue) for i, queues in enumerate(self.queues.queues): if queues: # standard gate self._joblib_execute(state, queues) else: # special gate gate = next(special_gates) if isinstance(gate, tuple): # SWAP global-local qubit self._swap(state, *gate) else: self._special_gate_execute(state, gate) for gate in special_gates: # pragma: no cover self._special_gate_execute(state, gate) self._final_state = state if self.measurement_gate is None or nshots is None: return state with tf.device(self.memory_device): samples = self.measurement_gate( state.vector, nshots, samples_only=True, is_density_matrix=self.using_density_matrix) self.measurement_gate_result = measurements.GateResult( self.measurement_gate.qubits, state, decimal_samples=samples) result = measurements.CircuitResult(self.measurement_tuples, self.measurement_gate_result) return result
def test_post_measurement_asymmetric_bitflips(): """Check applying asymmetric bitflips to measurement samples.""" import tensorflow as tf from qibo.config import DTYPES from qibo.tensorflow import measurements qubits = tuple(range(4)) samples = np.random.randint(0, 2, (20, 4)) result = measurements.GateResult(qubits, binary_samples=samples) p1_map = {0: 0.2, 1: 0.0, 2: 0.0, 3: 0.1} tf.random.set_seed(123) noisy_result = result.apply_bitflips(p0=0.2, p1=p1_map) p0 = 0.2 * np.ones(4) p1 = np.array([0.2, 0.0, 0.0, 0.1]) tf.random.set_seed(123) sprobs = tf.random.uniform(samples.shape, dtype=DTYPES.get('DTYPE')).numpy() target_samples = np.copy(samples).ravel() ids = (np.where(target_samples == 0)[0], np.where(target_samples == 1)[0]) target_samples[ ids[0]] = samples.ravel()[ids[0]] + (sprobs < p0).ravel()[ids[0]] target_samples[ ids[1]] = samples.ravel()[ids[1]] - (sprobs < p1).ravel()[ids[1]] target_samples = target_samples.reshape(samples.shape) np.testing.assert_allclose(noisy_result.samples(), target_samples)
def test_post_measurement_bitflips(probs): """Check applying bitflips to measurement samples.""" import tensorflow as tf from qibo.config import DTYPES from qibo.tensorflow import measurements qubits = tuple(range(4)) samples = np.random.randint(0, 2, (20, 4)) result = measurements.GateResult(qubits, binary_samples=samples) tf.random.set_seed(123) noisy_result = result.apply_bitflips(probs) tf.random.set_seed(123) if isinstance(probs, dict): probs = np.array([probs[q] for q in qubits]) sprobs = tf.random.uniform(samples.shape, dtype=DTYPES.get('DTYPE')).numpy() flipper = sprobs < probs target_samples = (samples + flipper) % 2 np.testing.assert_allclose(noisy_result.samples(), target_samples)
def _repeated_execute( self, nreps: int, initial_state: Optional[InitStateType] = None) -> tf.Tensor: results = [] for _ in range(nreps): state = self._device_execute(initial_state) if self.measurement_gate is not None: results.append(self.measurement_gate(state, nshots=1)[0]) del (state) else: results.append(tf.identity(state)) results = tf.stack(results, axis=0) if self.measurement_gate is None: return results mgate_result = measurements.GateResult(self.measurement_gate.qubits, decimal_samples=results) return measurements.CircuitResult(self.measurement_tuples, mgate_result)
def _execute(self, initial_state: Optional[InitStateType] = None, nshots: Optional[int] = None) -> OutputType: """Performs ``circuit.execute`` on specified device.""" self.using_density_matrix = False self._final_state = None state = self.get_initial_state(initial_state) if self.using_tfgates: shape = (1 + self.using_density_matrix) * self.nqubits * (2, ) state = tf.reshape(state, shape) if self._compiled_execute is None: state = self._eager_execute(state) else: state, callback_results = self._compiled_execute(state) for callback, results in callback_results.items(): callback.extend(results) if self.using_tfgates: shape = tf.cast( (1 + self.using_density_matrix) * (2**self.nqubits, ), dtype=DTYPES.get('DTYPEINT')) state = tf.reshape(state, shape) self._final_state = state if self.measurement_gate is None or nshots is None: return self._final_state samples = self.measurement_gate( state, nshots, samples_only=True, is_density_matrix=self.using_density_matrix) self.measurement_gate_result = measurements.GateResult( self.measurement_gate.qubits, decimal_samples=samples) return measurements.CircuitResult(self.measurement_tuples, self.measurement_gate_result)
def test_post_measurement_bitflip_errors(): """Check errors raised by `GateResult.apply_bitflips` and `gates.M`.""" from qibo.tensorflow import measurements samples = np.random.randint(0, 2, (20, 3)) result = measurements.GateResult((0, 1, 3), binary_samples=samples) # Passing wrong qubit ids in bitflip error map with pytest.raises(KeyError): noisy_result = result.apply_bitflips({0: 0.1, 2: 0.2}) # Passing wrong bitflip error map type with pytest.raises(TypeError): noisy_result = result.apply_bitflips("test") # Passing negative bitflip probability with pytest.raises(ValueError): noisy_result = result.apply_bitflips(-0.4) # Check bitflip error map errors when creating measurement gate gate = gates.M(0, 1, p0=2 * [0.1]) with pytest.raises(ValueError): gate = gates.M(0, 1, p0=4 * [0.1]) with pytest.raises(KeyError): gate = gates.M(0, 1, p0={0: 0.1, 2: 0.2}) with pytest.raises(TypeError): gate = gates.M(0, 1, p0="test")