def test_run_mixture_with_gates(dtype): q0 = cirq.LineQubit(0) simulator = cirq.Simulator(dtype=dtype) circuit = cirq.Circuit(cirq.H(q0), cirq.phase_flip(0.5)(q0), cirq.H(q0), cirq.measure(q0)) result = simulator.run(circuit, repetitions=100) assert sum(result.measurements['0'])[0] < 80 assert sum(result.measurements['0'])[0] > 20
def test_phase_flip_channel_text_diagram(): pf = cirq.phase_flip(0.987654) assert cirq.circuit_diagram_info( pf, args=round_to_6_prec) == cirq.CircuitDiagramInfo( wire_symbols=('PF(0.987654)', )) assert cirq.circuit_diagram_info( pf, args=round_to_2_prec) == cirq.CircuitDiagramInfo( wire_symbols=('PF(0.99)', )) assert cirq.circuit_diagram_info(pf, no_precision) == cirq.CircuitDiagramInfo( wire_symbols=('PF(0.987654)', ))
def test_phase_flip_channel_eq(): a = cirq.phase_flip(0.0099999) b = cirq.phase_flip(0.01) c = cirq.phase_flip(0.0) assert cirq.approx_eq(a, b, atol=1e-2) et = cirq.testing.EqualsTester() et.make_equality_group(lambda: c) et.add_equality_group(cirq.phase_flip(0.1)) et.add_equality_group(cirq.phase_flip(0.4)) et.add_equality_group(cirq.phase_flip(0.6)) et.add_equality_group(cirq.phase_flip(0.8))
def test_kraus(): I = np.eye(2) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) Z = np.diag([1, -1]) a, b = cirq.LineQubit.range(2) m = cirq.Moment() assert cirq.has_kraus(m) k = cirq.kraus(m) assert len(k) == 1 assert np.allclose(k[0], np.array([[1.0]])) m = cirq.Moment(cirq.S(a)) assert cirq.has_kraus(m) k = cirq.kraus(m) assert len(k) == 1 assert np.allclose(k[0], np.diag([1, 1j])) m = cirq.Moment(cirq.CNOT(a, b)) assert cirq.has_kraus(m) k = cirq.kraus(m) print(k[0]) assert len(k) == 1 assert np.allclose( k[0], np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])) p = 0.1 m = cirq.Moment(cirq.depolarize(p).on(a)) assert cirq.has_kraus(m) k = cirq.kraus(m) assert len(k) == 4 assert np.allclose(k[0], np.sqrt(1 - p) * I) assert np.allclose(k[1], np.sqrt(p / 3) * X) assert np.allclose(k[2], np.sqrt(p / 3) * Y) assert np.allclose(k[3], np.sqrt(p / 3) * Z) p = 0.2 q = 0.3 m = cirq.Moment(cirq.bit_flip(p).on(a), cirq.phase_flip(q).on(b)) assert cirq.has_kraus(m) k = cirq.kraus(m) assert len(k) == 4 assert np.allclose(k[0], np.sqrt((1 - p) * (1 - q)) * np.kron(I, I)) assert np.allclose(k[1], np.sqrt(q * (1 - p)) * np.kron(I, Z)) assert np.allclose(k[2], np.sqrt(p * (1 - q)) * np.kron(X, I)) assert np.allclose(k[3], np.sqrt(p * q) * np.kron(X, Z))
def __init__(self, abstract_circuit: QCircuit, variables, use_mapping=True, noise=None, *args, **kwargs): self.op_lookup = { 'I': (cirq.ops.IdentityGate, None), 'X': (cirq.ops.common_gates.XPowGate, map_1), 'Y': (cirq.ops.common_gates.YPowGate, map_1), 'Z': (cirq.ops.common_gates.ZPowGate, map_1), 'H': (cirq.ops.common_gates.HPowGate, map_1), 'Rx': (cirq.ops.common_gates.XPowGate, map_2), 'Ry': (cirq.ops.common_gates.YPowGate, map_2), 'Rz': (cirq.ops.common_gates.ZPowGate, map_2), 'SWAP': (cirq.ops.SwapPowGate, None), } self.tq_to_sympy = {} self.counter = 0 super().__init__(abstract_circuit=abstract_circuit, variables=variables, noise=noise, use_mapping=use_mapping, *args, **kwargs) if len(self.tq_to_sympy.keys()) is None: self.sympy_to_tq = None self.resolver = None else: self.sympy_to_tq = {v: k for k, v in self.tq_to_sympy.items()} self.resolver = cirq.ParamResolver( {k: v(variables) for k, v in self.sympy_to_tq.items()}) if self.noise is not None: self.noise_lookup = { 'bit flip': [lambda x: cirq.bit_flip(x)], 'phase flip': [lambda x: cirq.phase_flip(x)], 'phase damp': [cirq.phase_damp], 'amplitude damp': [cirq.amplitude_damp], 'phase-amplitude damp': [cirq.amplitude_damp, cirq.phase_damp], 'depolarizing': [lambda x: cirq.depolarize(p=(3 / 4) * x)] } self.circuit = self.build_noisy_circuit(self.noise)
def test_mixture_simulation(): q0, q1 = cirq.LineQubit.range(2) pflip = cirq.phase_flip(p=0.4) bflip = cirq.bit_flip(p=0.6) cirq_circuit = cirq.Circuit( cirq.X(q0)**0.5, cirq.X(q1)**0.5, pflip.on(q0), bflip.on(q1), ) possible_circuits = [ cirq.Circuit(cirq.X(q0)**0.5, cirq.X(q1)**0.5, pf, bf) # Extract the operators from the mixtures to construct trajectories. for pf in [NoiseStep(m).on(q0) for m in cirq.channel(pflip)] for bf in [NoiseStep(m).on(q1) for m in cirq.channel(bflip)] ] possible_states = [ cirq.Simulator().simulate(pc).state_vector() for pc in possible_circuits ] # Since some "gates" were non-unitary, we must normalize. possible_states = [ps / np.linalg.norm(ps) for ps in possible_states] # Minimize flaky tests with a fixed seed. qsimSim = qsimcirq.QSimSimulator(seed=1) result_hist = [0] * len(possible_states) run_count = 100 for _ in range(run_count): result = qsimSim.simulate(cirq_circuit, qubit_order=[q0, q1]) for i, ps in enumerate(possible_states): if cirq.allclose_up_to_global_phase(result.state_vector(), ps): result_hist[i] += 1 break # Each observed result should match one of the possible_results. assert sum(result_hist) == run_count # Over 100 runs, it's reasonable to expect all four outcomes. assert all(result_count > 0 for result_count in result_hist)
def _get_noise_proto_pairs(): q0 = cirq.GridQubit(0, 0) pairs = [ # Depolarization. (cirq.Circuit(cirq.depolarize(p=0.3)(q0)), _build_op_proto("DP", ['p'], [0.3], ['0_0'])), # Asymmetric depolarization. (cirq.Circuit( cirq.asymmetric_depolarize(p_x=0.1, p_y=0.2, p_z=0.3)(q0)), _build_op_proto("ADP", ['p_x', 'p_y', 'p_z'], [0.1, 0.2, 0.3], ['0_0'])), # Generalized Amplitude damp. (cirq.Circuit(cirq.generalized_amplitude_damp(p=0.1, gamma=0.2)(q0)), _build_op_proto("GAD", ['p', 'gamma'], [0.1, 0.2], ['0_0'])), # Amplitude damp. (cirq.Circuit(cirq.amplitude_damp(gamma=0.1)(q0)), _build_op_proto("AD", ['gamma'], [0.1], ['0_0'])), # Reset. (cirq.Circuit(cirq.reset(q0)), _build_op_proto("RST", [], [], ['0_0'])), # Phase damp. (cirq.Circuit(cirq.phase_damp(gamma=0.1)(q0)), _build_op_proto("PD", ['gamma'], [0.1], ['0_0'])), # Phase flip. (cirq.Circuit(cirq.phase_flip(p=0.1)(q0)), _build_op_proto("PF", ['p'], [0.1], ['0_0'])), # Bit flip. (cirq.Circuit(cirq.bit_flip(p=0.1)(q0)), _build_op_proto("BF", ['p'], [0.1], ['0_0'])) ] return pairs
def test_controlled_mixture(): class NoDetails(cirq.Gate): def num_qubits(self) -> int: return 1 c_no = cirq.ControlledGate( num_controls=1, sub_gate=NoDetails(), ) assert not cirq.has_mixture(c_no) assert cirq.mixture(c_no, None) is None c_yes = cirq.ControlledGate( sub_gate=cirq.phase_flip(0.25), num_controls=1, ) assert cirq.has_mixture(c_yes) assert cirq.approx_eq(cirq.mixture(c_yes), [ (0.75, np.eye(4)), (0.25, cirq.unitary(cirq.CZ)), ])
def test_phase_flip_channel_str(): assert str(cirq.phase_flip(0.3)) == 'phase_flip(p=0.3)'
def test_phase_flip_channel_invalid_probability(): with pytest.raises(ValueError, match='was less than 0'): cirq.phase_flip(-0.1) with pytest.raises(ValueError, match='was greater than 1'): cirq.phase_flip(1.1)
def test_phase_flip_mixture(): d = cirq.phase_flip(0.3) assert_mixtures_equal(cirq.mixture(d), ((0.7, np.eye(2)), (0.3, Z))) assert cirq.has_mixture(d)
def test_phase_flip_overload(): d = cirq.phase_flip() d2 = cirq.phase_flip(0.3) assert str(d) == 'Z' assert str(d2) == 'phase_flip(p=0.3)'
def test_phase_flip_channel(): d = cirq.phase_flip(0.3) np.testing.assert_almost_equal( cirq.channel(d), (np.sqrt(1.0 - 0.3) * np.eye(2), np.sqrt(0.3) * Z)) assert cirq.has_channel(d)
def test_phase_flip_channel(): d = cirq.phase_flip(0.3) np.testing.assert_almost_equal( cirq.kraus(d), (np.sqrt(1.0 - 0.3) * np.eye(2), np.sqrt(0.3) * Z)) cirq.testing.assert_consistent_channel(d) cirq.testing.assert_consistent_mixture(d)
def __init__(self, abstract_circuit: QCircuit, variables, use_mapping=True, noise=None, device=None, *args, **kwargs): """ Parameters ---------- abstract_circuit: QCircuit: Tequila unitary to compile to cirq variables: dict: values of all variables in the circuit, to compile with. use_mapping: bool: whether or not to use a mapping that eliminates unnecessary qubits from the circuit. noise: Noise to apply to the circuit. device: device on which to emulatedly execute all sampling. args kwargs """ self.op_lookup = { 'I': (cirq.ops.IdentityGate, None), 'X': (cirq.ops.common_gates.XPowGate, map_1), 'Y': (cirq.ops.common_gates.YPowGate, map_1), 'Z': (cirq.ops.common_gates.ZPowGate, map_1), 'H': (cirq.ops.common_gates.HPowGate, map_1), 'Rx': (cirq.ops.common_gates.XPowGate, map_2), 'Ry': (cirq.ops.common_gates.YPowGate, map_2), 'Rz': (cirq.ops.common_gates.ZPowGate, map_2), 'SWAP': (cirq.ops.SwapPowGate, None), } self.tq_to_sympy = {} self.counter = 0 if device is not None: self.compiler_arguments['cc_max'] = True super().__init__(abstract_circuit=abstract_circuit, variables=variables, noise=noise, use_mapping=use_mapping, device=device, *args, **kwargs) if len(self.tq_to_sympy.keys()) is None: self.sympy_to_tq = None self.resolver = None else: self.sympy_to_tq = {v: k for k, v in self.tq_to_sympy.items()} self.resolver = cirq.ParamResolver( {k: v(variables) for k, v in self.sympy_to_tq.items()}) if self.device is not None: self.circuit = self.build_device_circuit() if self.noise is not None: if self.noise == 'device': raise TequilaException( 'cannot get device noise for cirq yet, sorry!') self.noise_lookup = { 'bit flip': [lambda x: cirq.bit_flip(x)], 'phase flip': [lambda x: cirq.phase_flip(x)], 'phase damp': [cirq.phase_damp], 'amplitude damp': [cirq.amplitude_damp], 'phase-amplitude damp': [cirq.amplitude_damp, cirq.phase_damp], 'depolarizing': [lambda x: cirq.depolarize(p=(3 / 4) * x)] } self.circuit = self.build_noisy_circuit(self.noise)
def test_controlled_mixture(): a, b = cirq.LineQubit.range(2) c_yes = cirq.ControlledOperation(controls=[b], sub_operation=cirq.phase_flip(0.25).on(a)) assert cirq.has_mixture(c_yes) assert cirq.approx_eq(cirq.mixture(c_yes), [(0.75, np.eye(4)), (0.25, cirq.unitary(cirq.CZ))])
def test_phase_flip_channel_text_diagram(): assert (cirq.circuit_diagram_info( cirq.phase_flip(0.3)) == cirq.CircuitDiagramInfo( wire_symbols=('PF(0.3)', )))
def __init__(self, abstract_circuit: QCircuit, variables, qubit_map=None, noise=None, device=None, *args, **kwargs): """ Parameters ---------- abstract_circuit: QCircuit: Tequila unitary to compile to cirq variables: dict: values of all variables in the circuit, to compile with. qubit_map: dictionary: a qubit map which maps the abstract qubits in the abstract_circuit to the qubits on the backend there is no need to initialize the corresponding backend types the dictionary should simply be {int:int} (preferred) or {int:name} if None the default will map to qubits 0 ... n_qubits -1 in the backend noise: Noise to apply to the circuit. device: device on which to emulatedly execute all sampling. args kwargs """ self.op_lookup = { 'I': (cirq.ops.IdentityGate, None), 'X': (cirq.ops.common_gates.XPowGate, map_1), 'Y': (cirq.ops.common_gates.YPowGate, map_1), 'Z': (cirq.ops.common_gates.ZPowGate, map_1), 'H': (cirq.ops.common_gates.HPowGate, map_1), 'Rx': (cirq.ops.common_gates.XPowGate, map_2), 'Ry': (cirq.ops.common_gates.YPowGate, map_2), 'Rz': (cirq.ops.common_gates.ZPowGate, map_2), 'SWAP': (cirq.ops.SwapPowGate, None), } self.tq_to_sympy = {} self.counter = 0 if device is not None: self.compiler_arguments['cc_max'] = True super().__init__(abstract_circuit=abstract_circuit, variables=variables, noise=noise, qubit_map=qubit_map, device=device, *args, **kwargs) if len(self.tq_to_sympy.keys()) is None: self.sympy_to_tq = None self.resolver = None else: self.sympy_to_tq = {v: k for k, v in self.tq_to_sympy.items()} self.resolver = cirq.ParamResolver( {k: v(variables) for k, v in self.sympy_to_tq.items()}) if self.device is not None: self.circuit = self.build_device_circuit() if self.noise is not None: if self.noise == 'device': raise TequilaException( 'cannot get device noise for cirq yet, sorry!') self.noise_lookup = { 'bit flip': [lambda x: cirq.bit_flip(x)], 'phase flip': [lambda x: cirq.phase_flip(x)], 'phase damp': [cirq.phase_damp], 'amplitude damp': [cirq.amplitude_damp], 'phase-amplitude damp': [cirq.amplitude_damp, cirq.phase_damp], 'depolarizing': [lambda x: cirq.depolarize(p=(3 / 4) * x)] } self.circuit = self.build_noisy_circuit(self.noise)
def test_controlled_mixture(): c_yes = cirq.ControlledGate(sub_gate=cirq.phase_flip(0.25), num_controls=1) assert cirq.has_mixture(c_yes) assert cirq.approx_eq(cirq.mixture(c_yes), [(0.75, np.eye(4)), (0.25, cirq.unitary(cirq.CZ))])