0
# Cirq
1
2
Cirq is a Python framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits. It provides a complete toolkit for quantum circuit design, optimization, simulation, and analysis, with comprehensive support for quantum gates, noise modeling, device characterization, and quantum algorithms.
3
4
## Package Information
5
6
- **Package Name**: cirq
7
- **Package Type**: PyPI
8
- **Language**: Python
9
- **Installation**: `pip install cirq`
10
- **Minimum Python Version**: 3.11
11
12
## Core Imports
13
14
```python
15
import cirq
16
17
# Import specific components
18
from cirq import Circuit, GridQubit, H, CNOT, measure
19
from cirq import Simulator, DensityMatrixSimulator
20
from cirq import LineQubit, X, Y, Z, S, T
21
22
# Import for parameter sweeps
23
from cirq import ParamResolver, Linspace
24
25
# Import for noise modeling
26
from cirq import NoiseModel, DepolarizingChannel
27
```
28
29
## Basic Usage
30
31
```python
32
import cirq
33
import numpy as np
34
35
# Create qubits
36
q0, q1 = cirq.LineQubit.range(2)
37
38
# Build a quantum circuit
39
circuit = cirq.Circuit()
40
circuit.append(cirq.H(q0)) # Hadamard gate on qubit 0
41
circuit.append(cirq.CNOT(q0, q1)) # CNOT gate
42
circuit.append(cirq.measure(q0, q1, key='result')) # Measurement
43
44
print("Circuit:")
45
print(circuit)
46
47
# Simulate the circuit
48
simulator = cirq.Simulator()
49
result = simulator.run(circuit, repetitions=100)
50
print("Measurement results:")
51
print(result.histogram(key='result'))
52
53
# Get final state vector (without measurement)
54
circuit_no_measure = circuit[:-1] # Remove measurement
55
final_state = simulator.simulate(circuit_no_measure)
56
print("Final state vector:")
57
print(final_state.final_state_vector)
58
```
59
60
## Architecture
61
62
Cirq follows a layered architecture for quantum computing:
63
64
### Core Components
65
66
- **Circuits & Operations**: Quantum circuits composed of moments containing operations
67
- **Gates & Qubits**: Quantum gates acting on qubit identifiers
68
- **Devices**: Hardware constraints and noise models
69
- **Simulators**: Classical simulation of quantum circuits
70
- **Protocols**: Extensible interfaces for quantum operations
71
72
### Key Abstractions
73
74
- **Circuit**: Container for quantum operations organized in time-ordered moments
75
- **Gate**: Abstract quantum operation that can be applied to qubits
76
- **Operation**: Instance of a gate applied to specific qubits
77
- **Moment**: Set of operations that occur simultaneously
78
- **Simulator**: Engine for classical quantum circuit simulation
79
80
## Capabilities
81
82
### Circuit Construction and Manipulation
83
84
Build and manipulate quantum circuits with intuitive Python syntax.
85
86
```python { .api }
87
class Circuit:
88
def __init__(self, *contents: 'cirq.OP_TREE') -> None: ...
89
def append(self, op_tree: 'cirq.OP_TREE', strategy: InsertStrategy = InsertStrategy.NEW_THEN_INLINE) -> None: ...
90
def insert(self, index: int, op_tree: 'cirq.OP_TREE', strategy: InsertStrategy = InsertStrategy.NEW_THEN_INLINE) -> None: ...
91
def moments(self) -> List[Moment]: ...
92
def all_qubits(self) -> FrozenSet['cirq.Qid']: ...
93
def num_qubits(self) -> int: ...
94
95
class Moment:
96
def __init__(self, *operations: 'cirq.Operation') -> None: ...
97
def operates_on(self, qubits: Iterable['cirq.Qid']) -> bool: ...
98
def operations(self) -> FrozenSet['cirq.Operation']: ...
99
```
100
101
[Circuits and Moments](./circuits.md)
102
103
### Quantum Gates and Operations
104
105
Comprehensive library of quantum gates including Pauli gates, rotation gates, multi-qubit gates, and noise channels.
106
107
```python { .api }
108
# Single-qubit gates
109
X: XPowGate
110
Y: YPowGate
111
Z: ZPowGate
112
H: HPowGate
113
S: ZPowGate # S gate (phase gate)
114
T: ZPowGate # T gate
115
116
# Rotation gates
117
def rx(rads: float) -> XPowGate: ...
118
def ry(rads: float) -> YPowGate: ...
119
def rz(rads: float) -> ZPowGate: ...
120
121
# Multi-qubit gates
122
CNOT: CNotPowGate
123
CZ: CZPowGate
124
SWAP: SwapPowGate
125
TOFFOLI: CCXPowGate
126
```
127
128
[Gates and Operations](./ops.md)
129
130
### Quantum Circuit Simulation
131
132
Multiple simulation backends for different use cases and performance requirements.
133
134
```python { .api }
135
class Simulator(SimulatorBase):
136
def run(self, program: 'cirq.CIRCUIT_LIKE', param_resolver: 'cirq.ParamResolverOrSimilarType' = None,
137
repetitions: int = 1) -> 'cirq.Result': ...
138
def simulate(self, program: 'cirq.CIRCUIT_LIKE', param_resolver: 'cirq.ParamResolverOrSimilarType' = None,
139
initial_state: 'cirq.STATE_VECTOR_LIKE' = None) -> SimulationTrialResult: ...
140
141
class DensityMatrixSimulator(SimulatorBase):
142
def simulate(self, program: 'cirq.CIRCUIT_LIKE', param_resolver: 'cirq.ParamResolverOrSimilarType' = None,
143
initial_state: 'cirq.QUANTUM_STATE_LIKE' = None) -> DensityMatrixTrialResult: ...
144
```
145
146
[Simulators and Simulation](./sim.md)
147
148
### Device Modeling and Noise
149
150
Model quantum hardware constraints and realistic noise for NISQ applications.
151
152
```python { .api }
153
class GridQubit(Qid):
154
def __init__(self, row: int, col: int) -> None: ...
155
@property
156
def row(self) -> int: ...
157
@property
158
def col(self) -> int: ...
159
160
class NoiseModel:
161
def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE': ...
162
163
def depolarize(p: float, n_qubits: int = None) -> DepolarizingChannel: ...
164
```
165
166
[Devices and Noise Modeling](./devices.md)
167
168
### Parameter Sweeps and Studies
169
170
Run parameterized experiments and parameter sweeps for algorithm optimization.
171
172
```python { .api }
173
class ParamResolver:
174
def __init__(self, param_dict: Dict[Union[str, sympy.Symbol], Any] = None) -> None: ...
175
def resolve(self, value: Any) -> Any: ...
176
177
class Linspace(Sweep):
178
def __init__(self, key: Union[str, sympy.Symbol], start: float, stop: float, length: int) -> None: ...
179
180
def sample_sweep(program: 'cirq.CIRCUIT_LIKE', params: 'cirq.Sweepable',
181
repetitions: int = 1) -> List['cirq.Result']: ...
182
```
183
184
[Parameter Studies](./study.md)
185
186
### Quantum Information Science Tools
187
188
Utilities for quantum state manipulation, channel representations, and quantum information measures.
189
190
```python { .api }
191
def fidelity(state1: 'cirq.QUANTUM_STATE_LIKE', state2: 'cirq.QUANTUM_STATE_LIKE') -> float: ...
192
def von_neumann_entropy(state: 'cirq.QUANTUM_STATE_LIKE') -> float: ...
193
def kraus_to_choi(kraus_operators: Sequence[np.ndarray]) -> np.ndarray: ...
194
def density_matrix_from_state_vector(state_vector: np.ndarray) -> np.ndarray: ...
195
```
196
197
[Quantum Information Science](./qis.md)
198
199
### Linear Algebra and Mathematical Utilities
200
201
Mathematical functions for quantum computing including matrix decompositions and special operations.
202
203
```python { .api }
204
def kak_decomposition(unitary: np.ndarray) -> KakDecomposition: ...
205
def is_unitary(matrix: np.ndarray) -> bool: ...
206
def partial_trace(tensor: np.ndarray, keep_indices: List[int], qid_shape: Tuple[int, ...]) -> np.ndarray: ...
207
```
208
209
[Linear Algebra](./linalg.md)
210
211
### Circuit Transformers and Optimization
212
213
Transform and optimize quantum circuits for different target hardware and improved performance.
214
215
```python { .api }
216
def merge_single_qubit_gates_to_phxz(circuit: Circuit, context: TransformerContext = None) -> Circuit: ...
217
def optimize_for_target_gateset(circuit: Circuit, gateset: CompilationTargetGateset) -> Circuit: ...
218
def single_qubit_matrix_to_gates(matrix: np.ndarray, tolerance: float = 1e-10) -> List['cirq.Operation']: ...
219
```
220
221
[Transformers and Optimization](./transformers.md)
222
223
### Protocols and Extensibility
224
225
Extensible protocol system for adding custom behavior to quantum operations.
226
227
```python { .api }
228
def unitary(val: Any) -> np.ndarray: ...
229
def decompose(val: Any, intercepting_decomposer: Callable = None) -> List['cirq.Operation']: ...
230
def apply_unitary(val: Any, args: ApplyUnitaryArgs) -> Union[np.ndarray, None]: ...
231
```
232
233
[Protocols](./protocols.md)
234
235
### Visualization and Analysis
236
237
Tools for visualizing quantum circuits, states, and measurement results.
238
239
```python { .api }
240
def plot_state_histogram(result: 'cirq.Result', ax: matplotlib.axes.Axes = None) -> matplotlib.axes.Axes: ...
241
def plot_density_matrix(matrix: np.ndarray) -> None: ...
242
class Heatmap:
243
def __init__(self, value_map: Mapping[Tuple[int, ...], float]) -> None: ...
244
```
245
246
[Visualization](./remaining-modules.md#visualization-tools)
247
248
### Quantum Experiments and Characterization
249
250
Built-in experiments for quantum device characterization and benchmarking.
251
252
```python { .api }
253
def single_qubit_randomized_benchmarking(sampler: 'cirq.Sampler', qubit: 'cirq.Qid',
254
use_cliffords: bool = True) -> RandomizedBenchMarkResult: ...
255
def xeb_fidelity(circuit_results: Dict['cirq.Circuit', List[int]],
256
simulated_probs: Dict['cirq.Circuit', np.ndarray]) -> float: ...
257
```
258
259
[Experiments and Characterization](./remaining-modules.md#experiments-and-characterization)
260
261
### Value Types and Utilities
262
263
Utility classes for time, measurement keys, classical data, and other quantum computing values.
264
265
```python { .api }
266
class Duration:
267
def __init__(self, *, picos: int = 0, nanos: int = 0, micros: int = 0, millis: int = 0) -> None: ...
268
269
class MeasurementKey:
270
def __init__(self, name: str, path: Tuple[str, ...] = ()) -> None: ...
271
```
272
273
[Value Types and Utilities](./remaining-modules.md#value-types-and-utilities)
274
275
### Workflow and Sampling
276
277
High-level workflow utilities for quantum computation and measurement collection.
278
279
```python { .api }
280
class Sampler:
281
def run(self, program: 'cirq.CIRCUIT_LIKE', param_resolver: 'cirq.ParamResolverOrSimilarType' = None,
282
repetitions: int = 1) -> 'cirq.Result': ...
283
284
class PauliSumCollector:
285
def __init__(self, circuit: 'cirq.Circuit', observables: List['cirq.PauliSum'],
286
sampler: 'cirq.Sampler') -> None: ...
287
```
288
289
[Workflow and Sampling](./remaining-modules.md#workflow-and-sampling)
290
291
### Interoperability
292
293
Integration with other quantum computing frameworks and tools.
294
295
```python { .api }
296
def quirk_json_to_circuit(json_text: str) -> Circuit: ...
297
def quirk_url_to_circuit(url: str) -> Circuit: ...
298
```
299
300
[Interoperability](./remaining-modules.md#interoperability)
301
302
## Type System
303
304
```python { .api }
305
# Core type aliases
306
OP_TREE = Union[Operation, Iterable['OP_TREE']]
307
CIRCUIT_LIKE = Union[Circuit, FrozenCircuit, Iterable[Any]]
308
QUANTUM_STATE_LIKE = Union[int, np.ndarray, 'cirq.QuantumState']
309
STATE_VECTOR_LIKE = Union[int, np.ndarray, Sequence[Union[int, float, complex]]]
310
PAULI_STRING_LIKE = Union[PauliString, str]
311
PAULI_GATE_LIKE = Union[Pauli, PauliString, str]
312
DURATION_LIKE = Union[Duration, float, int]
313
RANDOM_STATE_OR_SEED_LIKE = Union[int, np.random.RandomState, np.random.Generator]
314
315
# Parameter types
316
ParamDictType = Mapping[Union[str, sympy.Symbol], Any]
317
ParamResolverOrSimilarType = Union[ParamResolver, ParamDictType, Iterable[Any]]
318
Sweepable = Union[Sweep, ParamResolver, ParamDictType, Iterable[Any]]
319
```
320
321
This comprehensive documentation covers all major capabilities of the cirq quantum computing framework, enabling developers to build, simulate, and analyze quantum circuits without needing to access the source code directly.