def test_identity_global(): qubits = cirq.LineQubit.range(3) assert cirq.identity_each(*qubits) == cirq.IdentityGate(3).on(*qubits) qids = cirq.LineQid.for_qid_shape((1, 2, 3)) assert cirq.identity_each(*qids) == cirq.IdentityGate(3, (1, 2, 3)).on(*qids) with pytest.raises(ValueError, match='Not a cirq.Qid'): cirq.identity_each( qubits) # The user forgot to expand the list for example.
def test_decompose_once_with_qubits(): qs = cirq.LineQubit.range(3) # No default value results in descriptive error. with pytest.raises(TypeError, match='no _decompose_ method'): _ = cirq.decompose_once_with_qubits(NoMethod(), qs) with pytest.raises(TypeError, match='returned NotImplemented or None'): _ = cirq.decompose_once_with_qubits(DecomposeNotImplemented(), qs) with pytest.raises(TypeError, match='returned NotImplemented or None'): _ = cirq.decompose_once_with_qubits(DecomposeNone(), qs) # Default value works. assert cirq.decompose_once_with_qubits(NoMethod(), qs, 5) == 5 assert cirq.decompose_once_with_qubits(DecomposeNotImplemented(), qs, None) is None assert cirq.decompose_once_with_qubits(NoMethod(), qs, NotImplemented) is NotImplemented # Flattens into a list. assert cirq.decompose_once_with_qubits( DecomposeWithQubitsGiven(cirq.X.on_each), qs) == [ cirq.X(cirq.LineQubit(0)), cirq.X(cirq.LineQubit(1)), cirq.X(cirq.LineQubit(2)), ] assert cirq.decompose_once_with_qubits( DecomposeWithQubitsGiven(lambda *qubits: cirq.Y(qubits[0])), qs) == [cirq.Y(cirq.LineQubit(0))] assert cirq.decompose_once_with_qubits( DecomposeWithQubitsGiven(lambda *qubits: (cirq.Y(q) for q in qubits)), qs) == [ cirq.Y(cirq.LineQubit(0)), cirq.Y(cirq.LineQubit(1)), cirq.Y(cirq.LineQubit(2)) ] # Qudits, _decompose_ argument name is not 'qubits'. assert cirq.decompose_once_with_qubits( DecomposeQuditGate(), cirq.LineQid.for_qid_shape((1, 2, 3))) == [ cirq.identity_each(*cirq.LineQid.for_qid_shape((1, 2, 3))) ] # Works when qubits are generated. def use_qubits_twice(*qubits): a = list(qubits) b = list(qubits) yield cirq.X.on_each(*a) yield cirq.Y.on_each(*b) assert cirq.decompose_once_with_qubits( DecomposeWithQubitsGiven(use_qubits_twice), (q for q in qs)) == list(cirq.X.on_each(*qs)) + list(cirq.Y.on_each(*qs))
def test_merge_operations_deterministic_order(qubit_order): q = cirq.LineQubit.range(2) c_orig = cirq.Circuit(cirq.identity_each(*q), cirq.H.on_each(q[i] for i in qubit_order)) cirq.testing.assert_has_diagram( c_orig, ''' 0: ───I───H─── │ 1: ───I───H───''', ) c_new = cirq.merge_operations( c_orig, lambda op1, op2: op2 if isinstance(op1.gate, cirq.IdentityGate) else None ) cirq.testing.assert_has_diagram( c_new, ''' 0: ───H─────── 1: ───────H───''', )
def _identity_operation_from_dict(qubits, **kwargs): return cirq.identity_each(*qubits)
def test_simulate_identity_circuit(): """Tests simulating an identity circuit on three qubits.""" qreg = cirq.LineQubit.range(3) circ = cirq.Circuit(cirq.identity_each(qbit) for qbit in qreg) mps = MPSimulator().simulate(circ) assert np.allclose(mps.wavefunction(), circ.final_wavefunction())
def _decompose_(self, qids): yield cirq.identity_each(*qids)
def make_maxcut( graph: List[Tuple[int, int]], noise: float = 0, scale_noise: Optional[Callable[[Circuit, float], Circuit]] = None, factory: Optional[Factory] = None, ) -> Tuple[Callable[[np.ndarray], float], Callable[[np.ndarray], Circuit], np.ndarray]: """Makes an executor that evaluates the QAOA ansatz at a given beta and gamma parameters. Args: graph: The MAXCUT graph as a list of edges with integer labelled nodes. noise: The level of depolarizing noise. scale_noise: The noise scaling method for ZNE. factory: The factory to use for ZNE. Returns: (ansatz_eval, ansatz_maker, cost_obs) as a triple where * **ansatz_eval** -- function that evalutes the maxcut ansatz on the noisy cirq backend. * **ansatz_maker** -- function that returns an ansatz circuit. * **cost_obs** -- the cost observable as a dense matrix. """ # get the list of unique nodes from the list of edges nodes = list({node for edge in graph for node in edge}) nodes = list(range(max(nodes) + 1)) # one qubit per node qreg = [NamedQubit(str(nn)) for nn in nodes] def cost_step(beta: float) -> Circuit: return Circuit(ZZ(qreg[u], qreg[v])**beta for u, v in graph) def mix_step(gamma: float) -> Circuit: return Circuit(X(qq)**gamma for qq in qreg) def qaoa_ansatz(params: np.ndarray) -> Circuit: half = int(len(params) / 2) betas, gammas = params[:half], params[half:] qaoa_steps = sum( [ cost_step(beta) + mix_step(gamma) for beta, gamma in zip(betas, gammas) ], Circuit(), ) return Circuit(H.on_each(qreg)) + qaoa_steps # make the cost observable identity_matrix = np.eye(2**len(nodes)) cost_mat = -0.5 * sum( identity_matrix - Circuit([identity_each( *qreg), ZZ(qreg[i], qreg[j])]).unitary() for i, j in graph) noisy_backend = _make_noisy_backend(noise, cost_mat) # must have this function signature to work with scipy minimize def qaoa_cost(params: np.ndarray) -> float: qaoa_prog = qaoa_ansatz(params) if scale_noise is None and factory is None: return noisy_backend(qaoa_prog) else: assert scale_noise is not None return execute_with_zne( qaoa_prog, executor=noisy_backend, scale_noise=scale_noise, factory=factory, ) return qaoa_cost, qaoa_ansatz, cost_mat