def test_diagonal_gate(): with pytest.raises(ValueError): diagonal = np.exp(2j * np.pi * np.random.random(5)) DiagonalGate(2, diagonal) with pytest.raises(ValueError): diagonal = np.ndarray(range(4)) DiagonalGate(2, diagonal) gate = DiagonalGate.random(2) assert cirq.circuit_diagram_info(gate) == cirq.CircuitDiagramInfo( wire_symbols=('Diag', 'Diag')) qubits = cirq.LineQubit.range(2) gate = DiagonalGate.random(2) circuit = cirq.Circuit.from_ops([gate(*qubits)]) actual_text_diagram = circuit.to_text_diagram() expected_text_diagram = """ 0: ───Diag─── │ 1: ───Diag─── """.strip() assert actual_text_diagram == expected_text_diagram
def _circuit_diagram_info_( self, args: cirq.CircuitDiagramInfoArgs, ) -> cirq.CircuitDiagramInfo: assert args.known_qubits is not None wire_symbols: List[str] = [] t, e = 0, 0 for qubit in args.known_qubits: if qubit in self.target: if t == 0: if isinstance(self.exponent, Sequence): e_str = 'e' else: e_str = str(self.exponent) wire_symbols.append(f'ModularExp(t*{self.base}**{e_str} % {self.modulus})') else: wire_symbols.append('t' + str(t)) t += 1 if isinstance(self.exponent, Sequence) and qubit in self.exponent: wire_symbols.append('e' + str(e)) e += 1 return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols))
def test_inverse_composite_diagram_info(): class Gate(cirq.Gate): def _decompose_(self, qubits): return cirq.S.on(qubits[0]) def num_qubits(self) -> int: return 1 c = cirq.inverse(Gate()) assert cirq.circuit_diagram_info(c, default=None) is None class Gate2(cirq.Gate): def _decompose_(self, qubits): return cirq.S.on(qubits[0]) def num_qubits(self) -> int: return 1 def _circuit_diagram_info_(self, args): return 's!' c = cirq.inverse(Gate2()) assert cirq.circuit_diagram_info(c) == cirq.CircuitDiagramInfo( wire_symbols=('s!', ), exponent=-1)
def _circuit_diagram_info_(self, args): if args.use_unicode_characters: return '[{}<->{}]'.format(self.flip_a, self.flip_b) return cirq.CircuitDiagramInfo( ('[{}<->{}]'.format(self.flip_a, self.flip_b), ))
def _circuit_diagram_info_( self, args: 'cirq.CircuitDiagramInfoArgs' ) -> 'cirq.CircuitDiagramInfo': return cirq.CircuitDiagramInfo( wire_symbols=('zzswap', f't={self._zz_gate.exponent:.3f}'))
def test_circuit_diagram_info_validate(): with pytest.raises(ValueError): _ = cirq.CircuitDiagramInfo('X')
def _circuit_diagram_info_(self, args): return cirq.CircuitDiagramInfo(('X',))
def test_text_diagram_info(gate, sym, exp): assert cirq.circuit_diagram_info(gate) == cirq.CircuitDiagramInfo( wire_symbols=(sym, ), exponent=exp)
def _circuit_diagram_info_(self, args): return cirq.CircuitDiagramInfo(( 'SWAP(d={})'.format(self.swap_dim0), 'SWAP(d={})'.format(self.swap_dim1), ))
def test_phase_damping_channel_text_diagram(): assert (cirq.circuit_diagram_info( cirq.phase_damp(0.3)) == cirq.CircuitDiagramInfo( wire_symbols=('PD(0.3)', )))
def test_reset_channel_text_diagram(): assert (cirq.circuit_diagram_info( cirq.RESET) == cirq.CircuitDiagramInfo(wire_symbols=('R', )))
def test_generalized_amplitude_damping_channel_text_diagram(): a = cirq.generalized_amplitude_damp(0.1, 0.3) assert (cirq.circuit_diagram_info(a) == cirq.CircuitDiagramInfo( wire_symbols=('GAD(0.1,0.3)', )))
def test_depolarizing_channel_text_diagram(): assert (cirq.circuit_diagram_info( cirq.depolarize(0.3)) == cirq.CircuitDiagramInfo( wire_symbols=('D(0.3)', )))
def test_rotation_error_channel_text_diagram(): assert (cirq.circuit_diagram_info(cirq.rotation_error( 0.3, 0.4, 0.5)) == cirq.CircuitDiagramInfo(wire_symbols=('RE(0.3,0.4,0.5)', )))
def _circuit_diagram_info_( self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo: return cirq.CircuitDiagramInfo(wire_symbols=('YXXY', '#2'), exponent=self._diagram_exponent(args))
def _circuit_diagram_info_(self, args): return cirq.CircuitDiagramInfo(('[Z {:+d}]'.format(self.increment), ))
def _circuit_diagram_info_(self, args): return cirq.CircuitDiagramInfo( ('[{:+d}%{}]'.format(self.increment, self.dimension), ))
def test_bit_flip_channel_text_diagram(): assert (cirq.circuit_diagram_info( cirq.bit_flip(0.3)) == cirq.CircuitDiagramInfo( wire_symbols=('BF(0.3)', )))
def test_measurement_gate_diagram(): # Shows key. assert cirq.circuit_diagram_info(cirq.MeasurementGate( 1, key='test')) == cirq.CircuitDiagramInfo(("M('test')", )) # Uses known qubit count. assert cirq.circuit_diagram_info( cirq.MeasurementGate(3, 'a'), cirq.CircuitDiagramInfoArgs( known_qubits=None, known_qubit_count=3, use_unicode_characters=True, precision=None, label_map=None, ), ) == cirq.CircuitDiagramInfo(("M('a')", 'M', 'M')) # Shows invert mask. assert cirq.circuit_diagram_info( cirq.MeasurementGate(2, 'a', invert_mask=(False, True))) == cirq.CircuitDiagramInfo( ("M('a')", "!M")) # Omits key when it is the default. a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') cirq.testing.assert_has_diagram( cirq.Circuit(cirq.measure(a, b)), """ a: ───M─── │ b: ───M─── """, ) cirq.testing.assert_has_diagram( cirq.Circuit(cirq.measure(a, b, invert_mask=(True, ))), """ a: ───!M─── │ b: ───M──── """, ) cirq.testing.assert_has_diagram( cirq.Circuit( cirq.measure(a, b, confusion_map={(1, ): np.array([[0, 1], [1, 0]])})), """ a: ───M──── │ b: ───?M─── """, ) cirq.testing.assert_has_diagram( cirq.Circuit( cirq.measure(a, b, invert_mask=(False, True), confusion_map={(1, ): np.array([[0, 1], [1, 0]])})), """ a: ───M───── │ b: ───!?M─── """, ) cirq.testing.assert_has_diagram( cirq.Circuit(cirq.measure(a, b, key='test')), """ a: ───M('test')─── │ b: ───M─────────── """, )
def test_asymmetric_depolarizing_channel_text_diagram(): a = cirq.asymmetric_depolarize(0.1, 0.2, 0.3) assert (cirq.circuit_diagram_info(a) == cirq.CircuitDiagramInfo( wire_symbols=('A(0.1,0.2,0.3)', )))
def test_reset_channel_text_diagram(): assert cirq.circuit_diagram_info( cirq.ResetChannel()) == cirq.CircuitDiagramInfo(wire_symbols=('R', )) assert cirq.circuit_diagram_info( cirq.ResetChannel(3)) == cirq.CircuitDiagramInfo(wire_symbols=('R', ))
def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs'): return cirq.CircuitDiagramInfo( wire_symbols=(str(self), ) + tuple(f'#{k+1}' for k in range(1, self._num_qubits)), exponent_qubit_index=0)
def test_circuit_diagram_info_init(): assert cirq.CircuitDiagramInfo(['a', 'b']).wire_symbols == ('a', 'b')
def test_circuit_info(): assert cirq.circuit_diagram_info(cirq.GridQubit( 5, 2)) == cirq.CircuitDiagramInfo(wire_symbols=('(5, 2)', )) assert cirq.circuit_diagram_info(cirq.GridQid( 5, 2, dimension=3)) == cirq.CircuitDiagramInfo( wire_symbols=('(5, 2) (d=3)', ))
def test_circuit_diagram_info_repr(): cirq.testing.assert_equivalent_repr(cirq.CircuitDiagramInfo(('X', 'Y'), 2))
def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs ) -> cirq.CircuitDiagramInfo: self.captured_diagram_args = args return cirq.CircuitDiagramInfo(wire_symbols=tuple(['MOCK']), exponent=1, connected=True)
def test_circuit_diagram_tagged_global_phase(): # Tests global phase operation q = cirq.NamedQubit('a') global_phase = cirq.GlobalPhaseOperation(coefficient=-1.0).with_tags('tag0') # Just global phase in a circuit assert cirq.circuit_diagram_info(global_phase, default='default') == 'default' cirq.testing.assert_has_diagram( cirq.Circuit(global_phase), "\n\nglobal phase: π['tag0']", use_unicode_characters=True ) cirq.testing.assert_has_diagram( cirq.Circuit(global_phase), "\n\nglobal phase: π", use_unicode_characters=True, include_tags=False, ) expected = cirq.CircuitDiagramInfo( wire_symbols=(), exponent=1.0, connected=True, exponent_qubit_index=None, auto_exponent_parens=True, ) # Operation with no qubits and returns diagram info with no wire symbols class NoWireSymbols(cirq.GlobalPhaseOperation): def _circuit_diagram_info_( self, args: 'cirq.CircuitDiagramInfoArgs' ) -> 'cirq.CircuitDiagramInfo': return expected no_wire_symbol_op = NoWireSymbols(coefficient=-1.0).with_tags('tag0') assert cirq.circuit_diagram_info(no_wire_symbol_op, default='default') == expected cirq.testing.assert_has_diagram( cirq.Circuit(no_wire_symbol_op), "\n\nglobal phase: π['tag0']", use_unicode_characters=True, ) # Two global phases in one moment tag1 = cirq.GlobalPhaseOperation(coefficient=1j).with_tags('tag1') tag2 = cirq.GlobalPhaseOperation(coefficient=1j).with_tags('tag2') c = cirq.Circuit([cirq.X(q), tag1, tag2]) cirq.testing.assert_has_diagram( c, """\ a: ─────────────X─────────────────── global phase: π['tag1', 'tag2']""", use_unicode_characters=True, precision=2, ) # Two moments with global phase, one with another tagged gate c = cirq.Circuit([cirq.X(q).with_tags('x_tag'), tag1]) c.append(cirq.Moment([cirq.X(q), tag2])) cirq.testing.assert_has_diagram( c, """\ a: ─────────────X['x_tag']─────X────────────── global phase: 0.5π['tag1'] 0.5π['tag2'] """, use_unicode_characters=True, include_tags=True, )
def test_circuit_diagram_info_repr(): info = cirq.CircuitDiagramInfo(('X', 'Y'), 2) assert repr(info) == ("cirq.DiagramInfo(wire_symbols=('X', 'Y')" ", exponent=2, connected=True)")