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

qis.mddocs/

0

# Quantum Information Science

1

2

The qis module provides tools and methods for quantum information science, including quantum state representations, channel transformations, information measures, and stabilizer formalism. It serves as the mathematical foundation for quantum computing operations.

3

4

## Quantum State Representations

5

6

### QuantumState - General State Container

7

8

```python { .api }

9

class QuantumState:

10

"""General quantum state representation."""

11

12

def __init__(self, data: 'cirq.QUANTUM_STATE_LIKE',

13

qid_shape: Optional[Tuple[int, ...]] = None,

14

dtype: Optional[Type[np.number]] = None,

15

validate: bool = True,

16

atol: float = 1e-7) -> None:

17

"""Initialize quantum state.

18

19

Args:

20

data: State vector, density matrix, or integer

21

qid_shape: Shape of qid system

22

dtype: Numeric data type

23

validate: Whether to validate the state

24

atol: Absolute tolerance for validation

25

"""

26

27

@property

28

def data(self) -> np.ndarray:

29

"""State data (vector or density matrix)."""

30

31

@property

32

def qid_shape(self) -> Tuple[int, ...]:

33

"""Shape of the qid system."""

34

35

def state_vector(self) -> np.ndarray:

36

"""Get state vector representation (if pure state)."""

37

38

def density_matrix(self) -> np.ndarray:

39

"""Get density matrix representation."""

40

41

def partial_trace_over(self, keep_indices: Sequence[int]) -> 'QuantumState':

42

"""Compute partial trace, keeping specified subsystems."""

43

44

class QuantumStateRepresentation(enum.Enum):

45

"""Enumeration of quantum state representations."""

46

47

STATE_VECTOR = "STATE_VECTOR"

48

DENSITY_MATRIX = "DENSITY_MATRIX"

49

50

def quantum_state(state_like: 'cirq.QUANTUM_STATE_LIKE',

51

qid_shape: Optional[Tuple[int, ...]] = None,

52

validate: bool = True,

53

dtype: Optional[Type[np.number]] = None) -> QuantumState:

54

"""Create quantum state from various inputs."""

55

```

56

57

### State Vector Functions

58

59

Functions for working with pure quantum states.

60

61

```python { .api }

62

def to_valid_state_vector(state_rep: 'cirq.STATE_VECTOR_LIKE',

63

num_qubits: Optional[int] = None,

64

qid_shape: Optional[Tuple[int, ...]] = None,

65

dtype: Optional[Type[np.number]] = None,

66

atol: float = 1e-7) -> np.ndarray:

67

"""Convert and validate state vector.

68

69

Args:

70

state_rep: State vector representation

71

num_qubits: Number of qubits (if qid_shape not given)

72

qid_shape: Shape of qid system

73

dtype: Numeric data type

74

atol: Tolerance for normalization validation

75

76

Returns:

77

Valid normalized state vector

78

"""

79

80

def validate_normalized_state_vector(state_vector: np.ndarray,

81

qid_shape: Tuple[int, ...],

82

dtype: Optional[Type[np.number]] = None,

83

atol: float = 1e-7) -> np.ndarray:

84

"""Validate that state vector is normalized."""

85

86

def bloch_vector_from_state_vector(state_vector: np.ndarray,

87

index: int,

88

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

89

"""Calculate Bloch vector for a single qubit from state vector.

90

91

Args:

92

state_vector: Full system state vector

93

index: Index of qubit to get Bloch vector for

94

qid_shape: Shape of qid system

95

96

Returns:

97

3D Bloch vector [x, y, z] coordinates

98

"""

99

100

def dirac_notation(state_vector: np.ndarray,

101

decimals: int = 2,

102

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

103

"""Convert state vector to Dirac notation string.

104

105

Args:

106

state_vector: State vector to represent

107

decimals: Number of decimal places for coefficients

108

qid_shape: Shape of qid system

109

110

Returns:

111

Dirac notation string like "|00⟩ + |11⟩"

112

"""

113

```

114

115

### Density Matrix Functions

116

117

Functions for working with mixed quantum states.

118

119

```python { .api }

120

def density_matrix(state: 'cirq.QUANTUM_STATE_LIKE',

121

qid_shape: Optional[Tuple[int, ...]] = None,

122

validate: bool = True,

123

dtype: Optional[Type[np.number]] = None,

124

atol: float = 1e-7) -> np.ndarray:

125

"""Create density matrix from state specification.

126

127

Args:

128

state: State vector, density matrix, or integer

129

qid_shape: Shape of qid system

130

validate: Whether to validate result

131

dtype: Numeric data type

132

atol: Tolerance for validation

133

134

Returns:

135

Density matrix as numpy array

136

"""

137

138

def density_matrix_from_state_vector(state_vector: np.ndarray) -> np.ndarray:

139

"""Convert state vector to density matrix.

140

141

Args:

142

state_vector: Pure state vector

143

144

Returns:

145

Density matrix ρ = |ψ⟩⟨ψ|

146

"""

147

148

def to_valid_density_matrix(density_matrix_rep: Union[np.ndarray, 'cirq.QUANTUM_STATE_LIKE'],

149

num_qubits: Optional[int] = None,

150

qid_shape: Optional[Tuple[int, ...]] = None,

151

dtype: Optional[Type[np.number]] = None,

152

atol: float = 1e-7) -> np.ndarray:

153

"""Convert and validate density matrix."""

154

155

def validate_density_matrix(density_matrix: np.ndarray,

156

qid_shape: Tuple[int, ...],

157

dtype: Optional[Type[np.number]] = None,

158

atol: float = 1e-7) -> np.ndarray:

159

"""Validate density matrix properties (Hermitian, positive semidefinite, trace 1)."""

160

```

161

162

## Quantum Channels and Operations

163

164

### Channel Representation Conversions

165

166

Functions for converting between different quantum channel representations.

167

168

```python { .api }

169

def kraus_to_choi(kraus_operators: Sequence[np.ndarray]) -> np.ndarray:

170

"""Convert Kraus operators to Choi matrix representation.

171

172

Args:

173

kraus_operators: Sequence of Kraus operator matrices

174

175

Returns:

176

Choi matrix of the quantum channel

177

"""

178

179

def choi_to_kraus(choi: np.ndarray, atol: float = 1e-10) -> Tuple[np.ndarray, ...]:

180

"""Convert Choi matrix to Kraus operators.

181

182

Args:

183

choi: Choi matrix representation

184

atol: Tolerance for eigenvalue cutoff

185

186

Returns:

187

Tuple of Kraus operator matrices

188

"""

189

190

def kraus_to_superoperator(kraus_operators: Sequence[np.ndarray],

191

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

192

"""Convert Kraus operators to superoperator matrix.

193

194

Args:

195

kraus_operators: Sequence of Kraus operators

196

qid_shape: Shape of qid system

197

198

Returns:

199

Superoperator matrix representation

200

"""

201

202

def superoperator_to_kraus(superoperator: np.ndarray,

203

qid_shape: Optional[Tuple[int, ...]] = None,

204

atol: float = 1e-10) -> Tuple[np.ndarray, ...]:

205

"""Convert superoperator matrix to Kraus operators."""

206

207

def choi_to_superoperator(choi: np.ndarray,

208

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

209

"""Convert Choi matrix to superoperator matrix."""

210

211

def superoperator_to_choi(superoperator: np.ndarray,

212

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

213

"""Convert superoperator matrix to Choi matrix."""

214

```

215

216

### Operation Channel Representations

217

218

```python { .api }

219

def operation_to_choi(operation: 'cirq.Operation') -> np.ndarray:

220

"""Get Choi representation of a quantum operation.

221

222

Args:

223

operation: Quantum operation

224

225

Returns:

226

Choi matrix of the operation

227

"""

228

229

def operation_to_superoperator(operation: 'cirq.Operation') -> np.ndarray:

230

"""Get superoperator representation of a quantum operation.

231

232

Args:

233

operation: Quantum operation

234

235

Returns:

236

Superoperator matrix of the operation

237

"""

238

```

239

240

## Quantum Information Measures

241

242

### Fidelity Measures

243

244

```python { .api }

245

def fidelity(state1: 'cirq.QUANTUM_STATE_LIKE',

246

state2: 'cirq.QUANTUM_STATE_LIKE',

247

qid_shape: Optional[Tuple[int, ...]] = None,

248

validate: bool = True,

249

atol: float = 1e-7) -> float:

250

"""Calculate quantum fidelity between two states.

251

252

Args:

253

state1: First quantum state

254

state2: Second quantum state

255

qid_shape: Shape of qid system

256

validate: Whether to validate inputs

257

atol: Tolerance for validation

258

259

Returns:

260

Fidelity F(ρ₁, ρ₂) ∈ [0, 1]

261

262

Notes:

263

For pure states: F(|ψ⟩, |φ⟩) = |⟨ψ|φ⟩|²

264

For mixed states: F(ρ₁, ρ₂) = tr(√(√ρ₁ρ₂√ρ₁))

265

"""

266

267

def entanglement_fidelity(channel: Union[Sequence[np.ndarray], np.ndarray],

268

state: Optional['cirq.QUANTUM_STATE_LIKE'] = None) -> float:

269

"""Calculate entanglement fidelity of a quantum channel.

270

271

Args:

272

channel: Kraus operators or Choi matrix of channel

273

state: Input state (maximally mixed if not specified)

274

275

Returns:

276

Entanglement fidelity of the channel

277

"""

278

```

279

280

### Entropy Measures

281

282

```python { .api }

283

def von_neumann_entropy(state: 'cirq.QUANTUM_STATE_LIKE',

284

qid_shape: Optional[Tuple[int, ...]] = None,

285

validate: bool = True,

286

atol: float = 1e-7) -> float:

287

"""Calculate von Neumann entropy of a quantum state.

288

289

Args:

290

state: Quantum state (pure or mixed)

291

qid_shape: Shape of qid system

292

validate: Whether to validate input

293

atol: Tolerance for validation

294

295

Returns:

296

von Neumann entropy S(ρ) = -tr(ρ log ρ) in bits

297

298

Notes:

299

- Pure states have zero entropy

300

- Maximally mixed n-qubit state has entropy n

301

"""

302

303

def process_renyi_entropy_from_bitstrings(bitstrings: Sequence[int],

304

num_qubits: int,

305

alpha: float = 2.0) -> float:

306

"""Calculate process Rényi entropy from measurement bitstrings.

307

308

Args:

309

bitstrings: Measurement outcomes as integers

310

num_qubits: Number of qubits measured

311

alpha: Rényi entropy parameter

312

313

Returns:

314

Process Rényi entropy

315

"""

316

```

317

318

## Stabilizer Formalism

319

320

### CliffordTableau

321

322

Stabilizer state representation using Clifford tableau.

323

324

```python { .api }

325

class CliffordTableau:

326

"""Clifford tableau for stabilizer state representation."""

327

328

def __init__(self, num_qubits: int,

329

initial_state: int = 0) -> None:

330

"""Initialize Clifford tableau.

331

332

Args:

333

num_qubits: Number of qubits

334

initial_state: Initial computational basis state

335

"""

336

337

@property

338

def num_qubits(self) -> int:

339

"""Number of qubits in the tableau."""

340

341

def copy(self) -> 'CliffordTableau':

342

"""Create a copy of the tableau."""

343

344

def stabilizers(self) -> List['cirq.PauliString']:

345

"""Get stabilizer generators."""

346

347

def destabilizers(self) -> List['cirq.PauliString']:

348

"""Get destabilizer generators."""

349

350

def to_state_vector(self) -> np.ndarray:

351

"""Convert to state vector representation (exponential cost)."""

352

353

def apply_single_qubit_clifford(self, clifford: 'cirq.SingleQubitCliffordGate',

354

qubit_index: int) -> None:

355

"""Apply single-qubit Clifford gate."""

356

357

def apply_cx(self, control: int, target: int) -> None:

358

"""Apply CNOT gate between control and target qubits."""

359

360

def apply_cz(self, qubit1: int, qubit2: int) -> None:

361

"""Apply CZ gate between two qubits."""

362

363

def measure(self, qubit_index: int, prng: Optional[np.random.Generator] = None) -> int:

364

"""Measure qubit in computational basis."""

365

```

366

367

### StabilizerState

368

369

General stabilizer state representation.

370

371

```python { .api }

372

class StabilizerState:

373

"""Stabilizer state representation."""

374

375

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

376

"""Initialize stabilizer state."""

377

378

@property

379

def num_qubits(self) -> int:

380

"""Number of qubits."""

381

382

def copy(self) -> 'StabilizerState':

383

"""Create a copy of the state."""

384

385

def stabilizer_generators(self) -> List['cirq.PauliString']:

386

"""Get stabilizer generators."""

387

388

def to_numpy(self) -> np.ndarray:

389

"""Convert to state vector (exponential cost for large systems)."""

390

391

def inner_product_of_state_and_x(self, x: int) -> complex:

392

"""Compute ⟨ψ|x⟩ where |x⟩ is computational basis state."""

393

```

394

395

## Utility Functions

396

397

### State Validation and Construction

398

399

```python { .api }

400

def eye_tensor(qid_shape: Sequence[int]) -> np.ndarray:

401

"""Create identity tensor for given qid shape.

402

403

Args:

404

qid_shape: Dimensions of each qid

405

406

Returns:

407

Identity tensor

408

"""

409

410

def one_hot(*, index: Union[int, Sequence[int]],

411

shape: Union[int, Sequence[int]],

412

dtype: Type[np.number] = np.complex64) -> np.ndarray:

413

"""Create one-hot state vector.

414

415

Args:

416

index: Index or indices for non-zero entry

417

shape: Shape of resulting tensor

418

dtype: Data type

419

420

Returns:

421

One-hot tensor with single non-zero entry

422

"""

423

424

def validate_indices(num_qubits: int, indices: Sequence[int]) -> None:

425

"""Validate qubit indices are in valid range."""

426

427

def validate_qid_shape(vals: Any, qid_shape: Tuple[int, ...], name: str = 'vals') -> None:

428

"""Validate that values match expected qid shape."""

429

430

def infer_qid_shape(vals: Any, default: Optional[Tuple[int, ...]] = None) -> Tuple[int, ...]:

431

"""Infer qid shape from values."""

432

```

433

434

### Noise Characterization

435

436

Functions for characterizing and converting noise parameters.

437

438

```python { .api }

439

def decay_constant_to_xeb_fidelity(decay_constant: float, num_qubits: int) -> float:

440

"""Convert decay constant to cross-entropy benchmarking fidelity."""

441

442

def decay_constant_to_pauli_error(decay_constant: float) -> float:

443

"""Convert decay constant to Pauli error rate."""

444

445

def pauli_error_to_decay_constant(pauli_error: float) -> float:

446

"""Convert Pauli error rate to decay constant."""

447

448

def xeb_fidelity_to_decay_constant(xeb_fidelity: float, num_qubits: int) -> float:

449

"""Convert XEB fidelity to decay constant."""

450

451

def pauli_error_from_t1(t1_ns: float, gate_time_ns: float) -> float:

452

"""Calculate Pauli error from T1 coherence time."""

453

454

def average_error(errors: Sequence[float]) -> float:

455

"""Calculate average error rate."""

456

457

def decoherence_pauli_error(t1_ns: float, t2_ns: float, gate_time_ns: float) -> float:

458

"""Calculate decoherence Pauli error from T1, T2, and gate time."""

459

```

460

461

## Type Aliases

462

463

```python { .api }

464

QUANTUM_STATE_LIKE = Union[int, np.ndarray, 'cirq.QuantumState']

465

"""Type for objects that can represent quantum states."""

466

467

STATE_VECTOR_LIKE = Union[int, np.ndarray, Sequence[Union[int, float, complex]]]

468

"""Type for objects that can represent state vectors."""

469

```

470

471

## Usage Examples

472

473

### Quantum State Operations

474

475

```python

476

import cirq

477

import numpy as np

478

479

# Create quantum states in different ways

480

print("=== Creating Quantum States ===")

481

482

# From computational basis

483

zero_state = cirq.quantum_state(0, qid_shape=(2, 2)) # |00⟩

484

print(f"Zero state: {cirq.dirac_notation(zero_state.state_vector())}")

485

486

# From state vector

487

bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2) # (|00⟩ + |11⟩)/√2

488

bell_qs = cirq.quantum_state(bell_state)

489

print(f"Bell state: {cirq.dirac_notation(bell_qs.state_vector())}")

490

491

# From density matrix

492

mixed_state = np.eye(4) / 4 # Maximally mixed 2-qubit state

493

mixed_qs = cirq.quantum_state(mixed_state)

494

print(f"Mixed state entropy: {cirq.von_neumann_entropy(mixed_qs):.3f} bits")

495

496

# Bloch vector of single qubit

497

qubit_0_bloch = cirq.bloch_vector_from_state_vector(bell_state, index=0)

498

print(f"Qubit 0 Bloch vector: {qubit_0_bloch}")

499

```

500

501

### Quantum Channel Analysis

502

503

```python

504

import cirq

505

import numpy as np

506

507

# Analyze depolarizing channel

508

print("=== Quantum Channel Analysis ===")

509

510

# Create depolarizing channel

511

p = 0.1 # Error probability

512

depol_channel = cirq.depolarize(p)

513

kraus_ops = cirq.kraus(depol_channel)

514

print(f"Depolarizing channel has {len(kraus_ops)} Kraus operators")

515

516

# Convert between representations

517

choi_matrix = cirq.kraus_to_choi(kraus_ops)

518

superop_matrix = cirq.kraus_to_superoperator(kraus_ops)

519

520

print(f"Choi matrix shape: {choi_matrix.shape}")

521

print(f"Superoperator shape: {superop_matrix.shape}")

522

523

# Channel fidelity

524

input_state = np.array([1, 0]) # |0⟩ state

525

ent_fidelity = cirq.entanglement_fidelity(kraus_ops, input_state)

526

print(f"Entanglement fidelity: {ent_fidelity:.4f}")

527

528

# Back-convert to verify

529

recovered_kraus = cirq.choi_to_kraus(choi_matrix)

530

print(f"Recovered {len(recovered_kraus)} Kraus operators")

531

```

532

533

### Fidelity and Distance Measures

534

535

```python

536

import cirq

537

import numpy as np

538

539

print("=== Fidelity Measures ===")

540

541

# Create two quantum states

542

state1 = np.array([1, 0, 0, 0]) # |00⟩

543

state2 = np.array([0, 1, 1, 0]) / np.sqrt(2) # (|01⟩ + |10⟩)/√2

544

545

# Pure state fidelity

546

fid = cirq.fidelity(state1, state2)

547

print(f"Fidelity between |00⟩ and (|01⟩ + |10⟩)/√2: {fid:.4f}")

548

549

# Mixed state fidelity

550

rho1 = np.outer(state1, state1) # Pure state density matrix

551

rho2 = np.eye(4) / 4 # Maximally mixed state

552

553

mixed_fid = cirq.fidelity(rho1, rho2)

554

print(f"Fidelity between pure |00⟩ and maximally mixed: {mixed_fid:.4f}")

555

556

# von Neumann entropy

557

entropy1 = cirq.von_neumann_entropy(rho1)

558

entropy2 = cirq.von_neumann_entropy(rho2)

559

print(f"Entropy of pure state: {entropy1:.6f}")

560

print(f"Entropy of maximally mixed: {entropy2:.3f}")

561

```

562

563

### Stabilizer Formalism

564

565

```python

566

import cirq

567

568

print("=== Stabilizer Formalism ===")

569

570

# Create Clifford tableau

571

num_qubits = 3

572

tableau = cirq.CliffordTableau(num_qubits)

573

574

# Apply Clifford gates

575

tableau.apply_single_qubit_clifford(cirq.H, 0) # H on qubit 0

576

tableau.apply_cx(0, 1) # CNOT(0, 1)

577

tableau.apply_cx(0, 2) # CNOT(0, 2)

578

579

# Get stabilizer generators

580

stabilizers = tableau.stabilizers()

581

print("Stabilizers of GHZ state:")

582

for i, stab in enumerate(stabilizers):

583

print(f" S_{i}: {stab}")

584

585

# Convert to state vector (expensive for large systems)

586

if num_qubits <= 10: # Only for small systems

587

state_vector = tableau.to_state_vector()

588

print(f"State vector: {cirq.dirac_notation(state_vector)}")

589

590

# Measure a qubit

591

measurement_result = tableau.measure(0)

592

print(f"Measured qubit 0: {measurement_result}")

593

```

594

595

### Noise Characterization

596

597

```python

598

import cirq

599

600

print("=== Noise Characterization ===")

601

602

# Convert between noise representations

603

t1_ns = 50000 # 50 μs T1 time

604

t2_ns = 25000 # 25 μs T2 time

605

gate_time_ns = 50 # 50 ns gate time

606

607

# Calculate various error rates

608

pauli_error_t1 = cirq.pauli_error_from_t1(t1_ns, gate_time_ns)

609

decoherence_error = cirq.decoherence_pauli_error(t1_ns, t2_ns, gate_time_ns)

610

611

print(f"Pauli error from T1: {pauli_error_t1:.6f}")

612

print(f"Total decoherence error: {decoherence_error:.6f}")

613

614

# Convert to decay constants

615

decay_constant = cirq.pauli_error_to_decay_constant(decoherence_error)

616

xeb_fidelity = cirq.decay_constant_to_xeb_fidelity(decay_constant, num_qubits=2)

617

618

print(f"Decay constant: {decay_constant:.6f}")

619

print(f"2-qubit XEB fidelity: {xeb_fidelity:.6f}")

620

621

# Average multiple error sources

622

gate_errors = [0.001, 0.0015, 0.0008, 0.0012] # Different gate error rates

623

avg_error = cirq.average_error(gate_errors)

624

print(f"Average gate error: {avg_error:.6f}")

625

```

626

627

This quantum information science toolkit provides the mathematical foundation for quantum computing, enabling analysis of quantum states, channels, and information-theoretic quantities essential for NISQ applications.