or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

circuits.mddevices.mdindex.mdlinalg.mdops.mdprotocols.mdqis.mdremaining-modules.mdsim.mdstudy.mdtransformers.md

ops.mddocs/

0

# Gates and Operations

1

2

The ops module provides the fundamental building blocks for quantum circuits: gates, operations, qubits, and gate sets. It includes a comprehensive library of quantum gates ranging from basic Pauli gates to complex multi-qubit operations and noise channels.

3

4

## Core Abstractions

5

6

### Gate - Base Class for Quantum Gates

7

8

Abstract base class for quantum gates that can be applied to qubits.

9

10

```python { .api }

11

class Gate:

12

"""Abstract base class for quantum gates."""

13

14

@abc.abstractmethod

15

def _num_qubits_(self) -> int:

16

"""Number of qubits this gate acts on."""

17

18

def num_qubits(self) -> int:

19

"""Number of qubits this gate acts on."""

20

21

def on(self, *qubits: 'cirq.Qid') -> 'cirq.Operation':

22

"""Apply this gate to the given qubits, creating an Operation."""

23

24

def on_each(self, *targets: Iterable['cirq.Qid']) -> List['cirq.Operation']:

25

"""Apply this gate to each qubit/set of qubits."""

26

27

def wrap_in_linear_combination(self, coefficient: Union[complex, float] = 1) -> 'cirq.LinearCombinationOfGates':

28

"""Wrap gate in a linear combination with given coefficient."""

29

30

def controlled(self, num_controls: int = None,

31

control_values: Sequence[Union[int, Collection[int]]] = None,

32

control_qid_shape: Sequence[int] = None) -> 'cirq.ControlledGate':

33

"""Create a controlled version of this gate."""

34

35

def with_probability(self, probability: float) -> 'cirq.RandomGateChannel':

36

"""Create a probabilistic channel that applies this gate."""

37

38

def __pow__(self, exponent: Union[float, sympy.Symbol]) -> 'cirq.Gate':

39

"""Raise gate to a power."""

40

41

def __mul__(self, other) -> Union['cirq.LinearCombinationOfGates', NotImplemented]:

42

"""Multiply gates (tensor product or linear combination)."""

43

```

44

45

### Operation - Gate Applied to Specific Qubits

46

47

Represents a gate applied to specific qubits.

48

49

```python { .api }

50

class Operation:

51

"""Abstract base class for quantum operations."""

52

53

@property

54

@abc.abstractmethod

55

def gate(self) -> Optional['cirq.Gate']:

56

"""The gate applied by this operation."""

57

58

@property

59

@abc.abstractmethod

60

def qubits(self) -> Tuple['cirq.Qid', ...]:

61

"""Qubits targeted by this operation."""

62

63

def with_qubits(self, *new_qubits: 'cirq.Qid') -> 'cirq.Operation':

64

"""Return a copy with different target qubits."""

65

66

def controlled_by(self, *control_qubits: 'cirq.Qid',

67

control_values: Union[None, int, Iterable[Union[None, int]]] = None) -> 'cirq.Operation':

68

"""Add control qubits to this operation."""

69

70

def with_tags(self, *new_tags) -> 'cirq.Operation':

71

"""Return a copy with additional tags."""

72

73

def without_tags(self, *tags_to_remove) -> 'cirq.Operation':

74

"""Return a copy with specified tags removed."""

75

76

def with_probability(self, probability: float) -> 'cirq.Operation':

77

"""Wrap in probabilistic channel."""

78

79

def __pow__(self, exponent) -> 'cirq.Operation':

80

"""Raise operation to a power."""

81

82

def transform_qubits(self, qubit_map: Dict['cirq.Qid', 'cirq.Qid']) -> 'cirq.Operation':

83

"""Transform qubits according to mapping."""

84

```

85

86

### TaggedOperation

87

88

Operation with associated metadata tags.

89

90

```python { .api }

91

class TaggedOperation(Operation):

92

"""Operation with associated metadata tags."""

93

94

def __init__(self, sub_operation: Operation, *tags) -> None:

95

"""Initialize tagged operation."""

96

97

@property

98

def sub_operation(self) -> Operation:

99

"""The wrapped operation."""

100

101

@property

102

def tags(self) -> FrozenSet:

103

"""Tags associated with this operation."""

104

```

105

106

## Single-Qubit Gates

107

108

### Pauli Gates

109

110

The fundamental single-qubit Pauli operators.

111

112

```python { .api }

113

class XPowGate(EigenGate):

114

"""X rotation gate: X^exponent."""

115

116

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

117

"""Initialize X power gate."""

118

119

def _eigen_components(self) -> List[Tuple[float, np.ndarray]]:

120

"""Eigenvalues and eigenvectors of X gate."""

121

122

class YPowGate(EigenGate):

123

"""Y rotation gate: Y^exponent."""

124

125

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

126

"""Initialize Y power gate."""

127

128

class ZPowGate(EigenGate):

129

"""Z rotation gate: Z^exponent."""

130

131

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

132

"""Initialize Z power gate."""

133

134

# Common gate instances

135

X: XPowGate # Pauli-X gate

136

Y: YPowGate # Pauli-Y gate

137

Z: ZPowGate # Pauli-Z gate

138

```

139

140

### Rotation Gates

141

142

Parameterized rotation gates around different axes.

143

144

```python { .api }

145

def rx(rads: float) -> XPowGate:

146

"""X-axis rotation by given radians."""

147

148

def ry(rads: float) -> YPowGate:

149

"""Y-axis rotation by given radians."""

150

151

def rz(rads: float) -> ZPowGate:

152

"""Z-axis rotation by given radians."""

153

154

class Rx(XPowGate):

155

"""X rotation gate specified in radians."""

156

157

def __init__(self, rads: Union[float, sympy.Symbol]) -> None:

158

"""Initialize X rotation."""

159

160

class Ry(YPowGate):

161

"""Y rotation gate specified in radians."""

162

163

def __init__(self, rads: Union[float, sympy.Symbol]) -> None:

164

"""Initialize Y rotation."""

165

166

class Rz(ZPowGate):

167

"""Z rotation gate specified in radians."""

168

169

def __init__(self, rads: Union[float, sympy.Symbol]) -> None:

170

"""Initialize Z rotation."""

171

```

172

173

### Hadamard and Phase Gates

174

175

```python { .api }

176

class HPowGate(EigenGate):

177

"""Hadamard power gate: H^exponent."""

178

179

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

180

"""Initialize Hadamard power gate."""

181

182

H: HPowGate # Hadamard gate

183

S: ZPowGate # S gate (√Z, phase gate)

184

T: ZPowGate # T gate (∜Z)

185

```

186

187

### Phased Rotation Gates

188

189

Advanced single-qubit gates with phase parameters.

190

191

```python { .api }

192

class PhasedXPowGate(Gate):

193

"""Phased X rotation gate."""

194

195

def __init__(self, *, phase_exponent: Union[float, sympy.Symbol],

196

exponent: Union[float, sympy.Symbol] = 1.0,

197

global_shift: float = 0.0) -> None:

198

"""Initialize phased X power gate."""

199

200

@property

201

def phase_exponent(self) -> Union[float, sympy.Symbol]:

202

"""Phase parameter."""

203

204

@property

205

def exponent(self) -> Union[float, sympy.Symbol]:

206

"""Rotation exponent."""

207

208

class PhasedXZGate(Gate):

209

"""Combined phased X and Z gate."""

210

211

def __init__(self, *, x_exponent: Union[float, sympy.Symbol],

212

z_exponent: Union[float, sympy.Symbol],

213

axis_phase_exponent: Union[float, sympy.Symbol]) -> None:

214

"""Initialize phased XZ gate."""

215

```

216

217

### Identity and Global Phase

218

219

```python { .api }

220

class IdentityGate(Gate):

221

"""Identity gate."""

222

223

def __init__(self, qid_shape: Tuple[int, ...] = (2,),

224

*, num_qubits: Optional[int] = None) -> None:

225

"""Initialize identity gate."""

226

227

class GlobalPhaseGate(Gate):

228

"""Global phase gate."""

229

230

def __init__(self, coefficient: Union[float, complex, sympy.Symbol]) -> None:

231

"""Initialize global phase gate."""

232

233

I: IdentityGate # Identity gate

234

235

def identity_each(*qubits: 'cirq.Qid') -> List[Operation]:

236

"""Apply identity to each qubit."""

237

238

def global_phase_operation(coefficient: Union[complex, float, sympy.Symbol]) -> Operation:

239

"""Create global phase operation."""

240

```

241

242

## Two-Qubit Gates

243

244

### CNOT and Controlled Gates

245

246

```python { .api }

247

class CNotPowGate(EigenGate):

248

"""Controlled-NOT power gate: CNOT^exponent."""

249

250

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

251

"""Initialize CNOT power gate."""

252

253

class CXPowGate(CNotPowGate):

254

"""Alias for CNotPowGate."""

255

256

class CZPowGate(EigenGate):

257

"""Controlled-Z power gate: CZ^exponent."""

258

259

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

260

"""Initialize CZ power gate."""

261

262

# Common instances

263

CNOT: CNotPowGate # Controlled-NOT gate

264

CX: CXPowGate # Alias for CNOT

265

CZ: CZPowGate # Controlled-Z gate

266

267

def cphase(turns: Union[float, sympy.Symbol]) -> CZPowGate:

268

"""Controlled phase gate."""

269

```

270

271

### SWAP Gates

272

273

```python { .api }

274

class SwapPowGate(EigenGate):

275

"""SWAP power gate: SWAP^exponent."""

276

277

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

278

"""Initialize SWAP power gate."""

279

280

class ISwapPowGate(EigenGate):

281

"""iSWAP power gate: iSWAP^exponent."""

282

283

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

284

"""Initialize iSWAP power gate."""

285

286

SWAP: SwapPowGate # SWAP gate

287

ISWAP: ISwapPowGate # iSWAP gate

288

SQRT_ISWAP: ISwapPowGate # √iSWAP gate

289

SQRT_ISWAP_INV: ISwapPowGate # √iSWAP† gate

290

291

def riswap(rads: Union[float, sympy.Symbol]) -> ISwapPowGate:

292

"""Parameterized iSWAP gate."""

293

```

294

295

### Fermionic Simulation Gates

296

297

Gates designed for fermionic quantum simulation.

298

299

```python { .api }

300

class FSimGate(Gate):

301

"""Fermionic simulation gate."""

302

303

def __init__(self, theta: Union[float, sympy.Symbol], phi: Union[float, sympy.Symbol]) -> None:

304

"""Initialize FSim gate with theta and phi parameters."""

305

306

@property

307

def theta(self) -> Union[float, sympy.Symbol]:

308

"""Theta parameter (iSWAP-like rotation)."""

309

310

@property

311

def phi(self) -> Union[float, sympy.Symbol]:

312

"""Phi parameter (controlled-phase)."""

313

314

class PhasedFSimGate(Gate):

315

"""Phased fermionic simulation gate."""

316

317

def __init__(self, *, theta: Union[float, sympy.Symbol],

318

zeta: Union[float, sympy.Symbol] = 0,

319

chi: Union[float, sympy.Symbol] = 0,

320

gamma: Union[float, sympy.Symbol] = 0,

321

phi: Union[float, sympy.Symbol] = 0) -> None:

322

"""Initialize phased FSim gate."""

323

324

class PhasedISwapPowGate(Gate):

325

"""Phased iSWAP power gate."""

326

327

def __init__(self, *, phase_exponent: Union[float, sympy.Symbol],

328

exponent: Union[float, sympy.Symbol] = 1.0) -> None:

329

"""Initialize phased iSWAP power gate."""

330

```

331

332

### Givens Rotations and Special Gates

333

334

```python { .api }

335

def givens(angle_rads: Union[float, sympy.Symbol]) -> FSimGate:

336

"""Givens rotation gate."""

337

338

class TwoQubitDiagonalGate(Gate):

339

"""Two-qubit diagonal unitary gate."""

340

341

def __init__(self, diag_angles_radians: Sequence[Union[float, sympy.Symbol]]) -> None:

342

"""Initialize with diagonal angles."""

343

```

344

345

## Three-Qubit Gates

346

347

### Toffoli and Controlled-Controlled Gates

348

349

```python { .api }

350

class CCXPowGate(Gate):

351

"""Controlled-controlled-X gate (Toffoli): CCX^exponent."""

352

353

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

354

"""Initialize CCX power gate."""

355

356

class CCZPowGate(Gate):

357

"""Controlled-controlled-Z gate: CCZ^exponent."""

358

359

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

360

"""Initialize CCZ power gate."""

361

362

class CCNotPowGate(CCXPowGate):

363

"""Alias for CCXPowGate."""

364

365

class CSwapGate(Gate):

366

"""Controlled SWAP gate (Fredkin gate)."""

367

368

def __init__(self) -> None:

369

"""Initialize controlled SWAP gate."""

370

371

# Common instances

372

CCX: CCXPowGate # Controlled-controlled-X (Toffoli)

373

TOFFOLI: CCXPowGate # Alias for CCX

374

CCZ: CCZPowGate # Controlled-controlled-Z

375

CCNOT: CCNotPowGate # Alias for CCX

376

CSWAP: CSwapGate # Controlled SWAP (Fredkin)

377

FREDKIN: CSwapGate # Alias for CSWAP

378

```

379

380

### Three-Qubit Diagonal Gates

381

382

```python { .api }

383

class ThreeQubitDiagonalGate(Gate):

384

"""Three-qubit diagonal unitary gate."""

385

386

def __init__(self, diag_angles_radians: Sequence[Union[float, sympy.Symbol]]) -> None:

387

"""Initialize with 8 diagonal angles."""

388

```

389

390

## Parity Gates

391

392

Parity interaction gates for quantum simulation.

393

394

```python { .api }

395

class XXPowGate(EigenGate):

396

"""XX parity interaction gate: XX^exponent."""

397

398

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

399

"""Initialize XX power gate."""

400

401

class YYPowGate(EigenGate):

402

"""YY parity interaction gate: YY^exponent."""

403

404

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

405

"""Initialize YY power gate."""

406

407

class ZZPowGate(EigenGate):

408

"""ZZ parity interaction gate: ZZ^exponent."""

409

410

def __init__(self, *, exponent: Union[float, sympy.Symbol] = 1.0, global_shift: float = 0.0) -> None:

411

"""Initialize ZZ power gate."""

412

413

XX: XXPowGate # XX parity gate

414

YY: YYPowGate # YY parity gate

415

ZZ: ZZPowGate # ZZ parity gate

416

```

417

418

### Mølmer-Sørensen Gate

419

420

```python { .api }

421

class MSGate(Gate):

422

"""Mølmer-Sørensen gate for trapped ion systems."""

423

424

def __init__(self, num_qubits: int, *, rads: Union[float, sympy.Symbol] = np.pi/4) -> None:

425

"""Initialize MS gate."""

426

427

def ms(*qubits: 'cirq.Qid', rads: Union[float, sympy.Symbol] = np.pi/4) -> MSGate:

428

"""Mølmer-Sørensen gate function."""

429

```

430

431

## Measurement Gates

432

433

### Computational Basis Measurements

434

435

```python { .api }

436

class MeasurementGate(Gate):

437

"""Computational basis measurement."""

438

439

def __init__(self, num_qubits: Optional[int] = None,

440

key: Union[str, 'cirq.MeasurementKey'] = '',

441

invert_mask: Union[None, int, Sequence[bool], Sequence[int]] = None,

442

qid_shape: Optional[Tuple[int, ...]] = None) -> None:

443

"""Initialize measurement gate."""

444

445

@property

446

def key(self) -> str:

447

"""Measurement key for storing results."""

448

449

@property

450

def invert_mask(self) -> Tuple[bool, ...]:

451

"""Mask indicating which qubits to invert before measurement."""

452

453

def with_bits_flipped(self, *bit_positions: int) -> 'MeasurementGate':

454

"""Return measurement with flipped invert mask."""

455

456

def measure(*qubits: 'cirq.Qid', key: Union[str, 'cirq.MeasurementKey'] = None,

457

invert_mask: Union[None, int, Sequence[bool], Sequence[int]] = None) -> Operation:

458

"""Measure qubits in computational basis."""

459

460

def measure_each(*qubits: 'cirq.Qid', key_func: Callable[['cirq.Qid'], str] = str) -> List[Operation]:

461

"""Measure each qubit individually."""

462

463

# Shorthand

464

M = measure

465

```

466

467

### Pauli Basis Measurements

468

469

```python { .api }

470

class PauliMeasurementGate(Gate):

471

"""Pauli basis measurement."""

472

473

def __init__(self, observable: 'cirq.PauliString',

474

key: Union[str, 'cirq.MeasurementKey'] = '') -> None:

475

"""Initialize Pauli measurement."""

476

477

@property

478

def observable(self) -> 'cirq.PauliString':

479

"""Pauli string to measure."""

480

481

def measure_single_paulistring(pauli_string: 'cirq.PauliString',

482

key: Union[str, 'cirq.MeasurementKey'] = None) -> List[Operation]:

483

"""Measure a single Pauli string."""

484

485

def measure_paulistring_terms(pauli_strings: Sequence['cirq.PauliString'],

486

key: Union[str, 'cirq.MeasurementKey'] = None) -> List[Operation]:

487

"""Measure multiple Pauli string terms."""

488

```

489

490

## Noise Channels

491

492

Quantum noise channels for realistic NISQ simulation.

493

494

### Depolarizing Channels

495

496

```python { .api }

497

class DepolarizingChannel(Gate):

498

"""Depolarizing noise channel."""

499

500

def __init__(self, p: Union[float, sympy.Symbol], n_qubits: int = None) -> None:

501

"""Initialize depolarizing channel with error probability p."""

502

503

@property

504

def p(self) -> Union[float, sympy.Symbol]:

505

"""Depolarizing probability."""

506

507

class AsymmetricDepolarizingChannel(Gate):

508

"""Asymmetric depolarizing noise channel."""

509

510

def __init__(self, p_x: Union[float, sympy.Symbol] = 0.0,

511

p_y: Union[float, sympy.Symbol] = 0.0,

512

p_z: Union[float, sympy.Symbol] = 0.0) -> None:

513

"""Initialize with individual Pauli error rates."""

514

515

def depolarize(p: Union[float, sympy.Symbol], n_qubits: int = None) -> DepolarizingChannel:

516

"""Create depolarizing channel."""

517

518

def asymmetric_depolarize(p_x: Union[float, sympy.Symbol] = 0.0,

519

p_y: Union[float, sympy.Symbol] = 0.0,

520

p_z: Union[float, sympy.Symbol] = 0.0) -> AsymmetricDepolarizingChannel:

521

"""Create asymmetric depolarizing channel."""

522

```

523

524

### Single-Qubit Error Channels

525

526

```python { .api }

527

class BitFlipChannel(Gate):

528

"""Bit flip noise channel (X error)."""

529

530

def __init__(self, p: Union[float, sympy.Symbol]) -> None:

531

"""Initialize bit flip channel."""

532

533

class PhaseFlipChannel(Gate):

534

"""Phase flip noise channel (Z error)."""

535

536

def __init__(self, p: Union[float, sympy.Symbol]) -> None:

537

"""Initialize phase flip channel."""

538

539

class PhaseDampingChannel(Gate):

540

"""Phase damping noise channel."""

541

542

def __init__(self, gamma: Union[float, sympy.Symbol]) -> None:

543

"""Initialize phase damping channel."""

544

545

def bit_flip(p: Union[float, sympy.Symbol]) -> BitFlipChannel:

546

"""Create bit flip channel."""

547

548

def phase_flip(p: Union[float, sympy.Symbol]) -> PhaseFlipChannel:

549

"""Create phase flip channel."""

550

551

def phase_damp(gamma: Union[float, sympy.Symbol]) -> PhaseDampingChannel:

552

"""Create phase damping channel."""

553

```

554

555

### Amplitude Damping Channels

556

557

```python { .api }

558

class AmplitudeDampingChannel(Gate):

559

"""Amplitude damping noise channel."""

560

561

def __init__(self, gamma: Union[float, sympy.Symbol]) -> None:

562

"""Initialize amplitude damping channel."""

563

564

class GeneralizedAmplitudeDampingChannel(Gate):

565

"""Generalized amplitude damping noise channel."""

566

567

def __init__(self, p: Union[float, sympy.Symbol],

568

gamma: Union[float, sympy.Symbol]) -> None:

569

"""Initialize generalized amplitude damping channel."""

570

571

def amplitude_damp(gamma: Union[float, sympy.Symbol]) -> AmplitudeDampingChannel:

572

"""Create amplitude damping channel."""

573

574

def generalized_amplitude_damp(p: Union[float, sympy.Symbol],

575

gamma: Union[float, sympy.Symbol]) -> GeneralizedAmplitudeDampingChannel:

576

"""Create generalized amplitude damping channel."""

577

```

578

579

### Advanced Noise Channels

580

581

```python { .api }

582

class ResetChannel(Gate):

583

"""Reset to specific state."""

584

585

def __init__(self, dimension: int = 2, reset_state: int = 0) -> None:

586

"""Initialize reset channel."""

587

588

class StatePreparationChannel(Gate):

589

"""State preparation channel."""

590

591

def __init__(self, target_state: Union[int, np.ndarray],

592

num_qubits: Optional[int] = None) -> None:

593

"""Initialize state preparation channel."""

594

595

class KrausChannel(Gate):

596

"""General Kraus noise channel."""

597

598

def __init__(self, kraus_ops: Sequence[np.ndarray]) -> None:

599

"""Initialize with Kraus operators."""

600

601

class MixedUnitaryChannel(Gate):

602

"""Mixed unitary noise channel."""

603

604

def __init__(self, mixture: Dict['cirq.Gate', float]) -> None:

605

"""Initialize with gate mixture."""

606

607

class RandomGateChannel(Gate):

608

"""Random gate noise channel."""

609

610

def __init__(self, sub_gate: 'cirq.Gate', probability: float = 1.0) -> None:

611

"""Initialize random gate channel."""

612

```

613

614

## Reset Operations

615

616

```python { .api }

617

class ResetChannel(Gate):

618

"""Reset qubits to |0⟩ state."""

619

620

def __init__(self, dimension: int = 2, reset_state: int = 0) -> None:

621

"""Initialize reset channel."""

622

623

def reset(*qubits: 'cirq.Qid') -> List[Operation]:

624

"""Reset qubits to |0⟩ state."""

625

626

def reset_each(*qubits: 'cirq.Qid') -> List[Operation]:

627

"""Reset each qubit individually to |0⟩."""

628

```

629

630

## Matrix and Custom Gates

631

632

### MatrixGate

633

634

Define gates by their unitary matrices.

635

636

```python { .api }

637

class MatrixGate(Gate):

638

"""Gate defined by unitary matrix."""

639

640

def __init__(self, matrix: np.ndarray, *, name: str = None,

641

qid_shape: Optional[Tuple[int, ...]] = None) -> None:

642

"""Initialize gate with unitary matrix."""

643

644

@property

645

def matrix(self) -> np.ndarray:

646

"""Unitary matrix of the gate."""

647

```

648

649

### DiagonalGate

650

651

Gates with diagonal unitary matrices.

652

653

```python { .api }

654

class DiagonalGate(Gate):

655

"""Diagonal unitary gate."""

656

657

def __init__(self, diag_angles_radians: Sequence[Union[float, sympy.Symbol]]) -> None:

658

"""Initialize with diagonal phases."""

659

660

@property

661

def diag_angles_radians(self) -> Tuple[Union[float, sympy.Symbol], ...]:

662

"""Diagonal angles in radians."""

663

```

664

665

## Controlled Operations

666

667

### ControlledGate

668

669

Create controlled versions of any gate.

670

671

```python { .api }

672

class ControlledGate(Gate):

673

"""Controlled version of any gate."""

674

675

def __init__(self, sub_gate: 'cirq.Gate',

676

num_controls: Optional[int] = None,

677

control_values: Optional[Sequence[Union[int, Collection[int]]]] = None,

678

control_qid_shape: Optional[Tuple[int, ...]] = None) -> None:

679

"""Initialize controlled gate."""

680

681

@property

682

def sub_gate(self) -> 'cirq.Gate':

683

"""The controlled gate."""

684

685

@property

686

def num_controls(self) -> int:

687

"""Number of control qubits."""

688

689

class ControlledOperation(Operation):

690

"""Controlled version of any operation."""

691

692

def __init__(self, controls: Sequence['cirq.Qid'],

693

sub_operation: Operation,

694

control_values: Optional[Sequence[Union[int, Collection[int]]]] = None) -> None:

695

"""Initialize controlled operation."""

696

```

697

698

### Classically Controlled Operations

699

700

```python { .api }

701

class ClassicallyControlledOperation(Operation):

702

"""Operation controlled by classical measurement results."""

703

704

def __init__(self, sub_operation: Operation,

705

conditions: Sequence['cirq.Condition']) -> None:

706

"""Initialize classically controlled operation."""

707

```

708

709

## Pauli Strings and Operations

710

711

### Pauli Operators

712

713

```python { .api }

714

class Pauli(Gate):

715

"""Single-qubit Pauli operator."""

716

717

def __init__(self, *, _index: Optional[int] = None, name: Optional[str] = None) -> None:

718

"""Initialize Pauli operator."""

719

720

@classmethod

721

def by_index(cls, index: int) -> 'Pauli':

722

"""Get Pauli by index (0=I, 1=X, 2=Y, 3=Z)."""

723

724

@classmethod

725

def by_relative_index(cls, pauli: 'Pauli', relative_index: int) -> 'Pauli':

726

"""Get Pauli by relative index."""

727

728

# Pauli constants (also available as gate instances)

729

pauli_gates = [I, X, Y, Z] # Index-based access

730

```

731

732

### PauliString

733

734

Products of Pauli operators acting on multiple qubits.

735

736

```python { .api }

737

class PauliString:

738

"""Product of Pauli operators on multiple qubits."""

739

740

def __init__(self, qubit_pauli_map: Optional[Dict['cirq.Qid', 'cirq.Pauli']] = None,

741

coefficient: Union[int, float, complex] = 1) -> None:

742

"""Initialize Pauli string."""

743

744

@property

745

def coefficient(self) -> Union[int, float, complex]:

746

"""Complex coefficient."""

747

748

def keys(self) -> KeysView['cirq.Qid']:

749

"""Qubits with non-identity Pauli operators."""

750

751

def values(self) -> ValuesView['cirq.Pauli']:

752

"""Pauli operators in the string."""

753

754

def items(self) -> ItemsView['cirq.Qid', 'cirq.Pauli']:

755

"""(qubit, pauli) pairs."""

756

757

def __getitem__(self, qubit: 'cirq.Qid') -> 'cirq.Pauli':

758

"""Get Pauli operator on given qubit."""

759

760

def __mul__(self, other) -> Union['PauliString', 'PauliSum']:

761

"""Multiply with another Pauli string or scalar."""

762

763

def __pow__(self, exponent) -> 'PauliStringPhasor':

764

"""Exponentiate Pauli string."""

765

766

def conjugated_by(self, clifford: 'cirq.SupportsActOn') -> 'PauliString':

767

"""Conjugate by Clifford operation."""

768

769

def expectation_from_state_vector(self, state: np.ndarray, qubit_map: Dict['cirq.Qid', int]) -> complex:

770

"""Calculate expectation value."""

771

772

def zip_items(self, other: 'PauliString') -> Iterator[Tuple['cirq.Qid', Tuple['cirq.Pauli', 'cirq.Pauli']]]:

773

"""Zip items from two Pauli strings."""

774

775

def zip_paulis(self, other: 'PauliString') -> Iterator[Tuple['cirq.Pauli', 'cirq.Pauli']]:

776

"""Zip Pauli operators from two strings."""

777

```

778

779

### MutablePauliString

780

781

Mutable version of PauliString for efficient construction.

782

783

```python { .api }

784

class MutablePauliString:

785

"""Mutable Pauli string for efficient construction."""

786

787

def __init__(self, qubit_pauli_map: Optional[Dict['cirq.Qid', 'cirq.Pauli']] = None,

788

coefficient: Union[int, float, complex] = 1) -> None:

789

"""Initialize mutable Pauli string."""

790

791

def __setitem__(self, qubit: 'cirq.Qid', pauli: 'cirq.Pauli') -> None:

792

"""Set Pauli operator on qubit."""

793

794

def __delitem__(self, qubit: 'cirq.Qid') -> None:

795

"""Remove qubit from string."""

796

797

def frozen(self) -> PauliString:

798

"""Convert to immutable PauliString."""

799

```

800

801

### Dense Pauli Strings

802

803

Efficient representation for dense Pauli strings.

804

805

```python { .api }

806

class BaseDensePauliString:

807

"""Base class for dense Pauli strings."""

808

809

def __init__(self, pauli_mask: Sequence[int], coefficient: Union[int, float, complex] = 1) -> None:

810

"""Initialize with packed Pauli representation."""

811

812

class DensePauliString(BaseDensePauliString):

813

"""Dense representation of Pauli strings."""

814

815

def on(self, *qubits: 'cirq.Qid') -> 'cirq.PauliString':

816

"""Apply to specific qubits, creating PauliString."""

817

818

class MutableDensePauliString(BaseDensePauliString):

819

"""Mutable dense Pauli string."""

820

821

def __setitem__(self, index: int, pauli: Union['cirq.Pauli', int]) -> None:

822

"""Set Pauli at given index."""

823

```

824

825

### Pauli String Operations

826

827

```python { .api }

828

class PauliStringGateOperation(Operation):

829

"""Gate operation from Pauli string."""

830

831

def __init__(self, pauli_string: PauliString) -> None:

832

"""Initialize from Pauli string."""

833

834

class SingleQubitPauliStringGateOperation(PauliStringGateOperation):

835

"""Single-qubit Pauli string operation."""

836

837

class PauliStringPhasor:

838

"""Exponential of a Pauli string: exp(i * exponent * pauli_string)."""

839

840

def __init__(self, pauli_string: PauliString,

841

*, exponent_neg: Union[float, sympy.Symbol] = 1.0,

842

exponent_pos: Union[float, sympy.Symbol] = 1.0) -> None:

843

"""Initialize Pauli string phasor."""

844

845

class PauliStringPhasorGate(Gate):

846

"""Gate for Pauli string exponentials."""

847

848

def __init__(self, pauli_string: PauliString,

849

*, exponent_neg: Union[float, sympy.Symbol] = 1.0,

850

exponent_pos: Union[float, sympy.Symbol] = 1.0) -> None:

851

"""Initialize Pauli string phasor gate."""

852

853

class PauliInteractionGate(Gate):

854

"""Pauli interaction gate."""

855

856

def __init__(self, pauli0: 'cirq.Pauli', pauli1: 'cirq.Pauli',

857

*, rads: Union[float, sympy.Symbol] = np.pi) -> None:

858

"""Initialize Pauli interaction gate."""

859

```

860

861

### Pauli Sums

862

863

```python { .api }

864

class PauliSum:

865

"""Sum of Pauli strings."""

866

867

def __init__(self, terms: Iterable[PauliString] = ()) -> None:

868

"""Initialize Pauli sum."""

869

870

def __add__(self, other) -> 'PauliSum':

871

"""Add Pauli sums or strings."""

872

873

def __mul__(self, other) -> 'PauliSum':

874

"""Multiply by scalar or other Pauli sum."""

875

876

def expectation_from_state_vector(self, state: np.ndarray, qubit_map: Dict['cirq.Qid', int]) -> complex:

877

"""Calculate expectation value."""

878

879

class PauliSumExponential:

880

"""Exponential of a Pauli sum."""

881

882

def __init__(self, pauli_sum: PauliSum, coefficient: Union[float, sympy.Symbol] = 1.0) -> None:

883

"""Initialize Pauli sum exponential."""

884

885

# Type aliases

886

PAULI_STRING_LIKE = Union[PauliString, str, Iterable[Tuple['cirq.Qid', Union['cirq.Pauli', str]]]]

887

PAULI_SUM_LIKE = Union[PauliSum, PauliString, str, int, float, complex]

888

```

889

890

## Linear Combinations

891

892

### Linear Combination of Gates

893

894

```python { .api }

895

class LinearCombinationOfGates:

896

"""Linear combination of gates with complex coefficients."""

897

898

def __init__(self, terms: Dict['cirq.Gate', Union[int, float, complex]]) -> None:

899

"""Initialize linear combination."""

900

901

def __add__(self, other) -> 'LinearCombinationOfGates':

902

"""Add linear combinations."""

903

904

def __mul__(self, scalar) -> 'LinearCombinationOfGates':

905

"""Multiply by scalar."""

906

907

def matrix(self, qubits: Sequence['cirq.Qid']) -> np.ndarray:

908

"""Calculate matrix representation."""

909

910

class LinearCombinationOfOperations:

911

"""Linear combination of operations."""

912

913

def __init__(self, terms: Dict[Operation, Union[int, float, complex]]) -> None:

914

"""Initialize linear combination of operations."""

915

```

916

917

## Qubit Management

918

919

### QubitManager Interface

920

921

```python { .api }

922

class QubitManager:

923

"""Interface for managing ancilla qubits."""

924

925

@abc.abstractmethod

926

def qalloc(self, n: int = 1, dim: int = 2) -> List['cirq.Qid']:

927

"""Allocate n qubits of given dimension."""

928

929

@abc.abstractmethod

930

def qfree(self, qids: List['cirq.Qid']) -> None:

931

"""Free previously allocated qubits."""

932

933

class SimpleQubitManager(QubitManager):

934

"""Simple implementation of qubit manager."""

935

936

def __init__(self) -> None:

937

"""Initialize simple qubit manager."""

938

939

class GreedyQubitManager(QubitManager):

940

"""Greedy ancilla allocation strategy."""

941

942

def __init__(self, prefix: str = "ancilla", maximize_reuse: bool = False) -> None:

943

"""Initialize greedy qubit manager."""

944

945

class BorrowableQubit:

946

"""Qubit that can be borrowed temporarily."""

947

948

def __init__(self, qid: 'cirq.Qid') -> None:

949

"""Initialize borrowable qubit."""

950

951

class CleanQubit:

952

"""Clean ancilla qubit guaranteed to be in |0⟩ state."""

953

954

def __init__(self, qid: 'cirq.Qid') -> None:

955

"""Initialize clean qubit."""

956

```

957

958

## Gate Collections and Sets

959

960

### GateFamily

961

962

Collections of related gates for compilation and optimization.

963

964

```python { .api }

965

class GateFamily:

966

"""Collection of related gates."""

967

968

def __init__(self, gate: 'cirq.Gate',

969

name: Optional[str] = None,

970

description: Optional[str] = None,

971

tags_to_accept: Sequence = (),

972

tags_to_ignore: Sequence = ()) -> None:

973

"""Initialize gate family."""

974

975

def predicate(self, gate: 'cirq.Gate') -> bool:

976

"""Check if gate belongs to this family."""

977

978

class Gateset:

979

"""Set of allowed gates for compilation."""

980

981

def __init__(self, *gates: Union['cirq.Gate', GateFamily],

982

name: Optional[str] = None,

983

unroll_circuit_op: bool = True) -> None:

984

"""Initialize gateset."""

985

986

def validate(self, circuit_or_operation: Union['cirq.AbstractCircuit', Operation]) -> None:

987

"""Validate circuit against gateset."""

988

989

def __contains__(self, item) -> bool:

990

"""Check if gate/operation is in gateset."""

991

992

class AnyUnitaryGateFamily(GateFamily):

993

"""Family accepting any unitary gate."""

994

995

def __init__(self, num_qubits: int) -> None:

996

"""Initialize for given number of qubits."""

997

998

class AnyIntegerPowerGateFamily(GateFamily):

999

"""Family accepting integer powers of a gate."""

1000

1001

def __init__(self, gate: 'cirq.EigenGate') -> None:

1002

"""Initialize for eigen gate."""

1003

1004

class ParallelGateFamily(GateFamily):

1005

"""Family of parallel gate applications."""

1006

1007

def __init__(self, gate: 'cirq.Gate') -> None:

1008

"""Initialize for given gate."""

1009

```

1010

1011

## Operation Trees and Utilities

1012

1013

### Operation Tree Types

1014

1015

```python { .api }

1016

OP_TREE = Union[Operation, Iterable['OP_TREE']]

1017

"""Type representing nested operations."""

1018

1019

def flatten_op_tree(root: OP_TREE, preserve_moments: bool = True) -> Iterator[Union[Operation, 'cirq.Moment']]:

1020

"""Flatten nested operation tree."""

1021

1022

def flatten_to_ops(root: OP_TREE) -> List[Operation]:

1023

"""Flatten to operations only."""

1024

1025

def flatten_to_ops_or_moments(root: OP_TREE) -> List[Union[Operation, 'cirq.Moment']]:

1026

"""Flatten to operations or moments."""

1027

1028

def freeze_op_tree(root: OP_TREE) -> Tuple[Union[Operation, 'cirq.Moment'], ...]:

1029

"""Create immutable operation tree."""

1030

1031

def transform_op_tree(root: OP_TREE,

1032

op_transformation: Callable[[Operation], OP_TREE] = lambda e: e,

1033

moment_transformation: Callable[['cirq.Moment'], OP_TREE] = lambda e: e,

1034

preserve_moments: bool = True) -> OP_TREE:

1035

"""Transform operation tree with given functions."""

1036

```

1037

1038

### Special Operations

1039

1040

```python { .api }

1041

class ParallelGate(Gate):

1042

"""Parallel application of a gate to multiple qubit sets."""

1043

1044

def __init__(self, sub_gate: 'cirq.Gate', num_copies: int) -> None:

1045

"""Initialize parallel gate."""

1046

1047

def parallel_gate_op(gate: 'cirq.Gate', qubits: Sequence[Sequence['cirq.Qid']]) -> Operation:

1048

"""Create parallel gate operation."""

1049

1050

class WaitGate(Gate):

1051

"""Idle/wait operation for specified duration."""

1052

1053

def __init__(self, duration: 'cirq.Duration', num_qubits: int = 1) -> None:

1054

"""Initialize wait gate."""

1055

1056

def wait(*qubits: 'cirq.Qid', nanos: Union[float, int] = None) -> Operation:

1057

"""Create wait operation."""

1058

```

1059

1060

## Tags

1061

1062

Metadata tags for operations.

1063

1064

```python { .api }

1065

class VirtualTag:

1066

"""Tag for virtual/logical operations."""

1067

1068

def __init__(self) -> None:

1069

"""Initialize virtual tag."""

1070

1071

class RoutingSwapTag:

1072

"""Tag for routing SWAP operations."""

1073

1074

def __init__(self) -> None:

1075

"""Initialize routing SWAP tag."""

1076

```

1077

1078

## Special Purpose Gates

1079

1080

### Arithmetic and Boolean Gates

1081

1082

```python { .api }

1083

class ArithmeticGate(Gate):

1084

"""Arithmetic operation gate."""

1085

1086

def registers(self) -> Dict[str, Sequence[int]]:

1087

"""Register definitions for arithmetic operations."""

1088

1089

class BooleanHamiltonianGate(Gate):

1090

"""Boolean Hamiltonian gate."""

1091

1092

def __init__(self, parameter_names: Sequence[str],

1093

boolean_strs: Sequence[str],

1094

theta: Union[float, sympy.Symbol] = sympy.Symbol('theta')) -> None:

1095

"""Initialize Boolean Hamiltonian gate."""

1096

```

1097

1098

### Quantum Fourier Transform

1099

1100

```python { .api }

1101

class QuantumFourierTransformGate(Gate):

1102

"""Quantum Fourier transform gate."""

1103

1104

def __init__(self, num_qubits: int, *, without_reverse: bool = False) -> None:

1105

"""Initialize QFT gate."""

1106

1107

def qft(*qubits: 'cirq.Qid', without_reverse: bool = False, inverse: bool = False) -> List[Operation]:

1108

"""Quantum Fourier transform operation."""

1109

```

1110

1111

### Phase Gradient Gate

1112

1113

```python { .api }

1114

class PhaseGradientGate(Gate):

1115

"""Phase gradient gate for QFT implementation."""

1116

1117

def __init__(self, num_qubits: int, *, exponent: Union[float, sympy.Symbol] = 1.0) -> None:

1118

"""Initialize phase gradient gate."""

1119

```

1120

1121

### Uniform Superposition

1122

1123

```python { .api }

1124

class UniformSuperpositionGate(Gate):

1125

"""Gate that creates uniform superposition over computational basis states."""

1126

1127

def __init__(self, num_qubits: int) -> None:

1128

"""Initialize uniform superposition gate."""

1129

```

1130

1131

## Usage Examples

1132

1133

### Basic Gate Operations

1134

1135

```python

1136

import cirq

1137

import numpy as np

1138

1139

# Single-qubit operations

1140

q = cirq.LineQubit(0)

1141

circuit = cirq.Circuit([

1142

cirq.H(q), # Hadamard

1143

cirq.X(q)**0.5, # √X gate

1144

cirq.rz(np.pi/4)(q), # Z rotation

1145

])

1146

1147

# Multi-qubit operations

1148

q0, q1 = cirq.LineQubit.range(2)

1149

circuit.append([

1150

cirq.CNOT(q0, q1), # CNOT gate

1151

cirq.CZ(q0, q1)**0.5, # √CZ gate

1152

cirq.SWAP(q0, q1), # SWAP gate

1153

])

1154

1155

print("Circuit:")

1156

print(circuit)

1157

```

1158

1159

### Custom Gates from Matrices

1160

1161

```python

1162

import cirq

1163

import numpy as np

1164

1165

# Define custom single-qubit gate

1166

custom_matrix = np.array([[1, 1], [1, -1]]) / np.sqrt(2) # Hadamard matrix

1167

custom_gate = cirq.MatrixGate(custom_matrix, name="CustomH")

1168

1169

# Apply to qubit

1170

q = cirq.LineQubit(0)

1171

op = custom_gate(q)

1172

print(f"Custom gate operation: {op}")

1173

1174

# Two-qubit diagonal gate

1175

diagonal_angles = [0, np.pi/4, np.pi/2, 3*np.pi/4]

1176

diag_gate = cirq.TwoQubitDiagonalGate(diagonal_angles)

1177

1178

q0, q1 = cirq.LineQubit.range(2)

1179

circuit = cirq.Circuit(diag_gate(q0, q1))

1180

```

1181

1182

### Controlled Operations

1183

1184

```python

1185

import cirq

1186

1187

# Create controlled version of any gate

1188

target = cirq.LineQubit(0)

1189

control = cirq.LineQubit(1)

1190

1191

# Controlled Hadamard

1192

controlled_h = cirq.H.controlled()

1193

ch_op = controlled_h(control, target)

1194

1195

# Multi-controlled gate

1196

controls = cirq.LineQubit.range(3)

1197

target = cirq.LineQubit(3)

1198

ccch = cirq.H.controlled(num_controls=3)

1199

ccch_op = ccch(*controls, target)

1200

1201

print(f"Controlled H: {ch_op}")

1202

print(f"Triple-controlled H: {ccch_op}")

1203

```

1204

1205

### Pauli String Operations

1206

1207

```python

1208

import cirq

1209

1210

# Create Pauli string

1211

qubits = cirq.LineQubit.range(3)

1212

pauli_string = cirq.PauliString({

1213

qubits[0]: cirq.X,

1214

qubits[1]: cirq.Y,

1215

qubits[2]: cirq.Z

1216

}, coefficient=0.5)

1217

1218

print(f"Pauli string: {pauli_string}")

1219

1220

# Exponentiate to create rotation

1221

rotation_angle = np.pi/4

1222

phasor = pauli_string ** rotation_angle

1223

phasor_gate = cirq.PauliStringPhasorGate(pauli_string, exponent_neg=rotation_angle)

1224

1225

# Add to circuit

1226

circuit = cirq.Circuit(phasor_gate(*qubits))

1227

```

1228

1229

### Noise Channel Application

1230

1231

```python

1232

import cirq

1233

1234

# Build clean circuit

1235

qubits = cirq.LineQubit.range(2)

1236

circuit = cirq.Circuit([

1237

cirq.H(qubits[0]),

1238

cirq.CNOT(qubits[0], qubits[1])

1239

])

1240

1241

# Add noise after each gate

1242

noisy_circuit = cirq.Circuit()

1243

for moment in circuit:

1244

noisy_circuit.append(moment)

1245

# Add depolarizing noise after each operation

1246

for op in moment:

1247

for qubit in op.qubits:

1248

noisy_circuit.append(cirq.depolarize(0.01)(qubit))

1249

1250

print("Noisy circuit:")

1251

print(noisy_circuit)

1252

```

1253

1254

This comprehensive documentation covers the extensive gate and operation library in Cirq, providing the foundation for quantum circuit construction and NISQ simulation.