def test_qubits(): a = cirq.QubitId() b = cirq.QubitId() assert Moment([cirq.X(a), cirq.X(b)]).qubits == {a, b} assert Moment([cirq.X(a)]).qubits == {a} assert Moment([cirq.CZ(a, b)]).qubits == {a, b}
def test_qubits(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert Moment([cirq.X(a), cirq.X(b)]).qubits == {a, b} assert Moment([cirq.X(a)]).qubits == {a} assert Moment([cirq.CZ(a, b)]).qubits == {a, b}
def test_with_operation(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert Moment().with_operation(cirq.X(a)) == Moment([cirq.X(a)]) assert (Moment([cirq.X(a)]).with_operation(cirq.X(b)) == Moment( [cirq.X(a), cirq.X(b)])) with pytest.raises(ValueError): _ = Moment([cirq.X(a)]).with_operation(cirq.X(a))
def as_circuit(self): if self._circuit is not None: return self._circuit else: self._circuit = self.to_circuit()[0] self._circuit.insert(0, Moment([ H(LineQubit(i)) for i in range(self.n) ])) # hack to show all qubits self._circuit.insert( 0, Moment([H(LineQubit(i)) for i in range(self.n)])) return self._circuit
def test_copy(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') original = Moment([cirq.CZ(a, b)]) copy = original.__copy__() assert original == copy assert id(original) != id(copy)
def solve(self, output_mode=None, output_file_name=None): result_depth, list_scheduled_gate_name, list_scheduled_gate_qubits, final_mapping = super( ).solve("IR") circuit = Circuit() for t in range(result_depth): moment = Moment() for i, qubits in enumerate(list_scheduled_gate_qubits[t]): if isinstance(qubits, int): moment = moment.with_operation( GateOperation(list_scheduled_gate_name[t][i], (self.map_to_cirq_qubit[qubits], ))) else: if list_scheduled_gate_name[t][i] == "SWAP": moment = moment.with_operation( GateOperation(SWAP, (self.map_to_cirq_qubit[qubits[0]], self.map_to_cirq_qubit[qubits[1]]))) else: moment = moment.with_operation( GateOperation(list_scheduled_gate_name[t][i], (self.map_to_cirq_qubit[qubits[0]], self.map_to_cirq_qubit[qubits[1]]))) circuit += moment final_cirq_mapping = dict() for i in range(self.count_program_qubit): final_cirq_mapping[self.map_to_cirq_qubit[ final_mapping[i]]] = self.map_program_qubit_to[i] return [circuit, final_cirq_mapping]
def _simplify_circuit_exponents(circuit: Circuit) -> None: """Simplifies the gate exponents of the input circuit if possible, mutating the input circuit. Args: circuit: The circuit to simplify. """ # Iterate over moments for moment_idx, moment in enumerate(circuit): simplified_operations = [] # Iterate over operations in moment for op in moment: if not isinstance(op, GateOperation): simplified_operations.append(op) continue if isinstance(op.gate, EigenGate): simplified_gate: Gate = _simplify_gate_exponent(op.gate) else: simplified_gate = op.gate simplified_operation = op.with_gate(simplified_gate) simplified_operations.append(simplified_operation) # Mutate the input circuit circuit[moment_idx] = Moment(simplified_operations)
def test_copy(): a = cirq.QubitId() b = cirq.QubitId() original = Moment([cirq.CZ(a, b)]) copy = original.__copy__() assert original == copy assert id(original) != id(copy)
def test_json_dict(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') mom = Moment([cirq.CZ(a, b)]) assert mom._json_dict_() == { 'cirq_type': 'Moment', 'operations': (cirq.CZ(a, b),) }
def test_validation(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') d = cirq.NamedQubit('d') _ = Moment([]) _ = Moment([cirq.X(a)]) _ = Moment([cirq.CZ(a, b)]) _ = Moment([cirq.CZ(b, d)]) _ = Moment([cirq.CZ(a, b), cirq.CZ(c, d)]) _ = Moment([cirq.CZ(a, c), cirq.CZ(b, d)]) _ = Moment([cirq.CZ(a, c), cirq.X(b)]) with pytest.raises(ValueError): _ = Moment([cirq.X(a), cirq.X(a)]) with pytest.raises(ValueError): _ = Moment([cirq.CZ(a, c), cirq.X(c)]) with pytest.raises(ValueError): _ = Moment([cirq.CZ(a, c), cirq.CZ(c, d)])
def test_container_methods(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') m = Moment([cirq.H(a), cirq.H(b)]) assert list(m) == list(m.operations) # __iter__ assert list(iter(m)) == list(m.operations) # __contains__ for free. assert cirq.H(b) in m assert len(m) == 2
def test_validation(): a = cirq.QubitId() b = cirq.QubitId() c = cirq.QubitId() d = cirq.QubitId() _ = Moment([]) _ = Moment([cirq.X(a)]) _ = Moment([cirq.CZ(a, b)]) _ = Moment([cirq.CZ(b, d)]) _ = Moment([cirq.CZ(a, b), cirq.CZ(c, d)]) _ = Moment([cirq.CZ(a, c), cirq.CZ(b, d)]) _ = Moment([cirq.CZ(a, c), cirq.X(b)]) with pytest.raises(ValueError): _ = Moment([cirq.X(a), cirq.X(a)]) with pytest.raises(ValueError): _ = Moment([cirq.CZ(a, c), cirq.X(c)]) with pytest.raises(ValueError): _ = Moment([cirq.CZ(a, c), cirq.CZ(c, d)])
def test_indexes_by_list_of_qubits(): q = cirq.LineQubit.range(4) moment = cirq.Moment([cirq.Z(q[0]), cirq.CNOT(q[1], q[2])]) assert moment[[q[0]]] == Moment([cirq.Z(q[0])]) assert moment[[q[1]]] == Moment([cirq.CNOT(q[1], q[2])]) assert moment[[q[2]]] == Moment([cirq.CNOT(q[1], q[2])]) assert moment[[q[3]]] == Moment([]) assert moment[q[0:2]] == moment assert moment[q[1:3]] == Moment([cirq.CNOT(q[1], q[2])]) assert moment[q[2:4]] == Moment([cirq.CNOT(q[1], q[2])]) assert moment[[q[0], q[3]]] == Moment([cirq.Z(q[0])]) assert moment[q] == moment
def scale_parameters( circ: Circuit, scale_factor: float, sigma: float, seed: Optional[int] = None, ) -> Circuit: """Adds parameter noise to a circuit with level noise. This adds noise to the actual parameter instead of adding an parameter channel. Args: circ: The quantum program as a Cirq circuit object. All measurements should be in the last moment of the circuit. scale_factor: Amount to scale the base noise level of parameters by. sigma: Base noise level (variance) in parameter rotations seed: random seed Returns: The input circuit with scaled rotation angles """ final_moments = [] noise = (scale_factor - 1) * sigma rng = np.random.RandomState(seed) for moment in circ: curr_moment = [] for op in moment.operations: gate = copy.deepcopy(op.gate) qubits = op.qubits if isinstance(gate, MeasurementGate): curr_moment.append(gate(*qubits)) else: assert isinstance(gate, EigenGate) base_gate = _get_base_gate(gate) param = gate.exponent * np.pi error = rng.normal(loc=0.0, scale=np.sqrt(noise)) new_param = param + error curr_moment.append( base_gate(exponent=new_param / np.pi)(*qubits) ) final_moments.append(Moment(curr_moment)) return Circuit(final_moments)
def qubit_ops_to_circuit(ops: 'QubitOperator', qpu: List[LineQubit]) -> 'Circuit': """Generate a circuit that can be run on a Cirq simulator from the ops passed Args: ops (Qubit Operator) - a product of operations to compile into a circuit qpu (Qid) - the quantum processing unit that this circuit will be run on Returns: (circuit) - returns a circuit to run in cirq """ gates = [] for operation in ops: gate_type = operation[1] qubit = qpu[operation[0]] gates.append(qubit_op_to_gate(gate_type, qubit)) moment = [Moment(gates)] return Circuit(moment)
def scale_parameters( circuit: QPROGRAM, scale_factor: float, base_variance: float, seed: Optional[int] = None, ) -> Circuit: """Applies parameter-noise scaling to the input circuit, assuming that each gate has the same base level of noise. Args: circuit: The circuit to scale as a QPROGRAM. All measurements should be in the last moment of the circuit. scale_factor: The amount to scale the base noise level by. base_variance: The base level (variance) of parameter noise, assumed to be the same for each gate of the circuit. seed: Optional seed for random number generator. Returns: The parameter noise scaled circuit. """ final_moments = [] noise = (scale_factor - 1) * base_variance rng = np.random.RandomState(seed) for moment in circuit: curr_moment = [] for op in moment.operations: # type: ignore gate = copy.deepcopy(op.gate) qubits = op.qubits if isinstance(gate, MeasurementGate): curr_moment.append(gate(*qubits)) else: assert isinstance(gate, EigenGate) base_gate = _get_base_gate(gate) param = gate.exponent * np.pi error = rng.normal(loc=0.0, scale=np.sqrt(noise)) new_param = param + error curr_moment.append( base_gate(exponent=new_param / np.pi)(*qubits)) final_moments.append(Moment(curr_moment)) return Circuit(final_moments)
def test_operates_on(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') # Empty case. assert not Moment().operates_on([]) assert not Moment().operates_on([a]) assert not Moment().operates_on([b]) assert not Moment().operates_on([a, b]) # One-qubit operation case. assert not Moment([cirq.X(a)]).operates_on([]) assert Moment([cirq.X(a)]).operates_on([a]) assert not Moment([cirq.X(a)]).operates_on([b]) assert Moment([cirq.X(a)]).operates_on([a, b]) # Two-qubit operation case. assert not Moment([cirq.CZ(a, b)]).operates_on([]) assert Moment([cirq.CZ(a, b)]).operates_on([a]) assert Moment([cirq.CZ(a, b)]).operates_on([b]) assert Moment([cirq.CZ(a, b)]).operates_on([a, b]) assert not Moment([cirq.CZ(a, b)]).operates_on([c]) assert Moment([cirq.CZ(a, b)]).operates_on([a, c]) assert Moment([cirq.CZ(a, b)]).operates_on([a, b, c]) # Multiple operations case. assert not Moment([cirq.X(a), cirq.X(b)]).operates_on([]) assert Moment([cirq.X(a), cirq.X(b)]).operates_on([a]) assert Moment([cirq.X(a), cirq.X(b)]).operates_on([b]) assert Moment([cirq.X(a), cirq.X(b)]).operates_on([a, b]) assert not Moment([cirq.X(a), cirq.X(b)]).operates_on([c]) assert Moment([cirq.X(a), cirq.X(b)]).operates_on([a, c]) assert Moment([cirq.X(a), cirq.X(b)]).operates_on([a, b, c])
def test_approx_eq(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert not cirq.approx_eq(Moment([cirq.X(a)]), cirq.X(a)) # Default is empty. Iterables get frozen into tuples. assert cirq.approx_eq(Moment(), Moment([])) assert cirq.approx_eq(Moment([]), Moment(())) assert cirq.approx_eq(Moment([cirq.X(a)]), Moment([cirq.X(a)])) assert not cirq.approx_eq(Moment([cirq.X(a)]), Moment([cirq.X(b)])) assert cirq.approx_eq(Moment([cirq.XPowGate(exponent=0)(a)]), Moment([cirq.XPowGate(exponent=1e-9)(a)])) assert not cirq.approx_eq(Moment([cirq.XPowGate(exponent=0)(a)]), Moment([cirq.XPowGate(exponent=1e-7)(a)])) assert cirq.approx_eq(Moment([cirq.XPowGate(exponent=0)(a)]), Moment([cirq.XPowGate(exponent=1e-7)(a)]), atol=1e-6)
def test_equality(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') d = cirq.NamedQubit('d') eq = cirq.testing.EqualsTester() # Default is empty. Iterables get frozen into tuples. eq.add_equality_group(Moment(), Moment([]), Moment(())) eq.add_equality_group(Moment([cirq.X(d)]), Moment((cirq.X(d), ))) # Equality depends on gate and qubits. eq.add_equality_group(Moment([cirq.X(a)])) eq.add_equality_group(Moment([cirq.X(b)])) eq.add_equality_group(Moment([cirq.Y(a)])) # Equality depends on order. eq.add_equality_group(Moment([cirq.X(a), cirq.X(b)])) eq.add_equality_group(Moment([cirq.X(b), cirq.X(a)])) # Two qubit gates. eq.make_equality_group(lambda: Moment([cirq.CZ(c, d)])) eq.make_equality_group(lambda: Moment([cirq.CZ(a, c)])) eq.make_equality_group(lambda: Moment([cirq.CZ(a, b), cirq.CZ(c, d)])) eq.make_equality_group(lambda: Moment([cirq.CZ(a, c), cirq.CZ(b, d)]))
def test_bool(): assert not Moment() a = cirq.NamedQubit('a') assert Moment([cirq.X(a)])
def test_repr(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') original = Moment([cirq.CZ(a, b)]) cirq.testing.assert_equivalent_repr(original)
def test_without_operations_touching(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') # Empty case. assert Moment().without_operations_touching([]) == Moment() assert Moment().without_operations_touching([a]) == Moment() assert Moment().without_operations_touching([a, b]) == Moment() # One-qubit operation case. assert (Moment([cirq.X(a) ]).without_operations_touching([]) == Moment([cirq.X(a)])) assert (Moment([cirq.X(a)]).without_operations_touching([a]) == Moment()) assert (Moment([cirq.X(a) ]).without_operations_touching([b]) == Moment([cirq.X(a)])) # Two-qubit operation case. assert (Moment([cirq.CZ(a, b)]).without_operations_touching([]) == Moment( [cirq.CZ(a, b)])) assert (Moment([cirq.CZ(a, b)]).without_operations_touching([a]) == Moment()) assert (Moment([cirq.CZ(a, b)]).without_operations_touching([b]) == Moment()) assert (Moment([cirq.CZ(a, b)]).without_operations_touching([c]) == Moment( [cirq.CZ(a, b)])) # Multiple operation case. assert (Moment([cirq.CZ(a, b), cirq.X(c)]).without_operations_touching( []) == Moment([cirq.CZ(a, b), cirq.X(c)])) assert (Moment([cirq.CZ(a, b), cirq.X(c) ]).without_operations_touching([a]) == Moment([cirq.X(c)])) assert (Moment([cirq.CZ(a, b), cirq.X(c) ]).without_operations_touching([b]) == Moment([cirq.X(c)])) assert (Moment([cirq.CZ(a, b), cirq.X(c)]).without_operations_touching( [c]) == Moment([cirq.CZ(a, b)])) assert (Moment([cirq.CZ(a, b), cirq.X(c) ]).without_operations_touching([a, b]) == Moment([cirq.X(c)])) assert (Moment([cirq.CZ(a, b), cirq.X(c)]).without_operations_touching([a, c]) == Moment())