0
# Random Objects and Testing
1
2
Generation of random quantum objects for testing, benchmarking, and quantum algorithm development.
3
4
## Capabilities
5
6
### Random States
7
8
Generate random quantum states with specified properties.
9
10
```python { .api }
11
def rand_ket(N: int, density: float = 1, dims: list = None) -> Qobj:
12
"""
13
Generate random state vector.
14
15
Parameters:
16
- N: Dimension of Hilbert space
17
- density: Sparsity parameter (1 = dense, <1 = sparse)
18
- dims: Dimensions for tensor structure
19
20
Returns:
21
- Qobj: Random normalized state vector |ψ⟩
22
"""
23
24
def rand_dm(N: int, density: float = 0.75, dims: list = None) -> Qobj:
25
"""
26
Generate random density matrix.
27
28
Parameters:
29
- N: Dimension of Hilbert space
30
- density: Sparsity parameter
31
- dims: Dimensions for tensor structure
32
33
Returns:
34
- Qobj: Random positive semidefinite density matrix
35
"""
36
```
37
38
### Random Operators
39
40
Generate random quantum operators and matrices.
41
42
```python { .api }
43
def rand_herm(N: int, density: float = 0.75, dims: list = None) -> Qobj:
44
"""
45
Generate random Hermitian operator.
46
47
Parameters:
48
- N: Matrix dimension
49
- density: Sparsity parameter
50
- dims: Dimensions for tensor structure
51
52
Returns:
53
- Qobj: Random Hermitian operator H = H†
54
"""
55
56
def rand_unitary(N: int, density: float = 0.75, dims: list = None) -> Qobj:
57
"""
58
Generate random unitary operator.
59
60
Parameters:
61
- N: Matrix dimension
62
- density: Sparsity parameter
63
- dims: Dimensions for tensor structure
64
65
Returns:
66
- Qobj: Random unitary operator U†U = UU† = I
67
"""
68
```
69
70
### Random Stochastic Matrices
71
72
Generate random stochastic and doubly stochastic matrices.
73
74
```python { .api }
75
def rand_stochastic(N: int, density: float = 0.75, kind: str = 'left') -> Qobj:
76
"""
77
Generate random stochastic matrix.
78
79
Parameters:
80
- N: Matrix dimension
81
- density: Sparsity parameter
82
- kind: 'left', 'right', or 'doubly' stochastic
83
84
Returns:
85
- Qobj: Random stochastic matrix
86
"""
87
```
88
89
### Random Quantum Channels
90
91
Generate random quantum channels and operations.
92
93
```python { .api }
94
def rand_kraus_map(N: int, dims: list = None) -> list:
95
"""
96
Generate random quantum channel as Kraus operators.
97
98
Parameters:
99
- N: Dimension of Hilbert space
100
- dims: Dimensions for tensor structure
101
102
Returns:
103
- list: List of Kraus operators {Kᵢ} with ∑ᵢ Kᵢ†Kᵢ = I
104
"""
105
106
def rand_super(N: int, dims: list = None) -> Qobj:
107
"""
108
Generate random superoperator.
109
110
Parameters:
111
- N: Dimension of underlying Hilbert space
112
- dims: Dimensions for tensor structure
113
114
Returns:
115
- Qobj: Random completely positive superoperator
116
"""
117
118
def rand_super_bcsz(N: int, enforce_tp: bool = True, rank: int = None, dims: list = None) -> Qobj:
119
"""
120
Generate random superoperator using BCSZ construction.
121
122
Parameters:
123
- N: Dimension of Hilbert space
124
- enforce_tp: Enforce trace preservation
125
- rank: Rank of Choi matrix (default: N²)
126
- dims: Dimensions for tensor structure
127
128
Returns:
129
- Qobj: Random CPTP or CP superoperator
130
"""
131
```
132
133
### Usage Examples
134
135
```python
136
import qutip as qt
137
import numpy as np
138
139
# Random state vectors
140
N = 10
141
psi_random = qt.rand_ket(N)
142
print(f"Random state norm: {psi_random.norm():.6f}") # Should be 1
143
print(f"Random state shape: {psi_random.shape}")
144
145
# Sparse random state
146
psi_sparse = qt.rand_ket(N, density=0.3) # 30% non-zero elements
147
print(f"Sparse state sparsity: {psi_sparse.data.nnz / (N * 1):.2f}")
148
149
# Random density matrices
150
rho_random = qt.rand_dm(N)
151
print(f"Random DM trace: {rho_random.tr():.6f}") # Should be 1
152
print(f"Random DM positivity: {all(rho_random.eigenenergies() >= -1e-12)}")
153
154
# Check density matrix properties
155
eigenvals = rho_random.eigenenergies()
156
print(f"DM eigenvalues range: [{eigenvals.min():.6f}, {eigenvals.max():.6f}]")
157
print(f"DM purity: {(rho_random**2).tr():.3f}")
158
159
# Random Hermitian operators
160
H_random = qt.rand_herm(N)
161
print(f"Hermitian check: {(H_random - H_random.dag()).norm():.2e}") # Should be ~0
162
163
# Random unitary operators
164
U_random = qt.rand_unitary(N)
165
unitarity_check = (U_random * U_random.dag() - qt.qeye(N)).norm()
166
print(f"Unitarity check: {unitarity_check:.2e}") # Should be ~0
167
168
# Verify unitary preserves norms
169
psi_test = qt.rand_ket(N)
170
psi_evolved = U_random * psi_test
171
print(f"Norm preservation: {psi_test.norm():.6f} -> {psi_evolved.norm():.6f}")
172
173
# Random stochastic matrices
174
S_left = qt.rand_stochastic(N, kind='left') # Columns sum to 1
175
S_right = qt.rand_stochastic(N, kind='right') # Rows sum to 1
176
S_doubly = qt.rand_stochastic(N, kind='doubly') # Both rows and columns sum to 1
177
178
# Check stochasticity
179
col_sums = np.sum(S_left.full(), axis=0)
180
row_sums = np.sum(S_right.full(), axis=1)
181
print(f"Left stochastic column sums: {col_sums[:3]}...") # Should be all 1s
182
print(f"Right stochastic row sums: {row_sums[:3]}...") # Should be all 1s
183
184
# Random quantum channels
185
kraus_ops = qt.rand_kraus_map(4) # 4-dimensional system
186
print(f"Number of Kraus operators: {len(kraus_ops)}")
187
188
# Verify completeness relation: ∑ᵢ Kᵢ†Kᵢ = I
189
completeness = sum(K.dag() * K for K in kraus_ops)
190
identity_check = (completeness - qt.qeye(4)).norm()
191
print(f"Kraus completeness check: {identity_check:.2e}")
192
193
# Apply random channel to state
194
rho_in = qt.rand_dm(4)
195
rho_out = sum(K * rho_in * K.dag() for K in kraus_ops)
196
print(f"Channel preserves trace: {rho_in.tr():.6f} -> {rho_out.tr():.6f}")
197
198
# Random superoperator
199
S = qt.rand_super(3) # 3x3 system -> 9x9 superoperator
200
print(f"Superoperator shape: {S.shape}")
201
202
# Test on random density matrix
203
rho_test = qt.rand_dm(3)
204
rho_vec = qt.operator_to_vector(rho_test)
205
rho_out_vec = S * rho_vec
206
rho_out = qt.vector_to_operator(rho_out_vec)
207
print(f"Superoperator trace preservation: {rho_test.tr():.6f} -> {rho_out.tr():.6f}")
208
209
# BCSZ random superoperator (guaranteed CPTP)
210
S_bcsz = qt.rand_super_bcsz(3, enforce_tp=True)
211
rho_bcsz_vec = S_bcsz * rho_vec
212
rho_bcsz = qt.vector_to_operator(rho_bcsz_vec)
213
print(f"BCSZ trace preservation: {rho_bcsz.tr():.6f}")
214
215
# Benchmarking with random objects
216
def benchmark_expectation_values(N, num_trials=100):
217
"""Benchmark expectation value calculations."""
218
import time
219
220
# Generate random objects
221
operators = [qt.rand_herm(N) for _ in range(10)]
222
states = [qt.rand_ket(N) for _ in range(num_trials)]
223
224
start_time = time.time()
225
for psi in states:
226
for op in operators:
227
_ = qt.expect(op, psi)
228
end_time = time.time()
229
230
total_calculations = num_trials * len(operators)
231
avg_time = (end_time - start_time) / total_calculations
232
print(f"Average expectation value time (N={N}): {avg_time*1000:.3f} ms")
233
234
# Run benchmarks
235
for N in [10, 50, 100]:
236
benchmark_expectation_values(N, num_trials=20)
237
238
# Random object properties analysis
239
def analyze_random_properties(N=20, num_samples=100):
240
"""Analyze statistical properties of random objects."""
241
242
# Random Hermitian eigenvalue statistics
243
eigenvals_all = []
244
for _ in range(num_samples):
245
H = qt.rand_herm(N)
246
eigenvals_all.extend(H.eigenenergies())
247
248
eigenvals_all = np.array(eigenvals_all)
249
print(f"Random Hermitian eigenvalues:")
250
print(f" Mean: {eigenvals_all.mean():.3f}")
251
print(f" Std: {eigenvals_all.std():.3f}")
252
print(f" Range: [{eigenvals_all.min():.3f}, {eigenvals_all.max():.3f}]")
253
254
# Random density matrix purity statistics
255
purities = []
256
for _ in range(num_samples):
257
rho = qt.rand_dm(N)
258
purities.append((rho**2).tr())
259
260
purities = np.array(purities)
261
print(f"Random density matrix purities:")
262
print(f" Mean: {purities.mean():.3f}")
263
print(f" Std: {purities.std():.3f}")
264
print(f" Range: [{purities.min():.3f}, {purities.max():.3f}]")
265
print(f" (Maximum purity = 1.0, minimum = 1/{N} = {1/N:.3f})")
266
267
analyze_random_properties()
268
269
# Tensor product random objects
270
# Multi-qubit random states
271
dims = [2, 2, 2] # 3-qubit system
272
psi_3qubit = qt.rand_ket(8, dims=dims)
273
print(f"3-qubit random state dims: {psi_3qubit.dims}")
274
275
# Random two-qubit gate
276
U_2qubit = qt.rand_unitary(4, dims=[[2,2], [2,2]])
277
print(f"2-qubit gate dims: {U_2qubit.dims}")
278
279
# Test gate on product states
280
psi_00 = qt.tensor(qt.basis(2,0), qt.basis(2,0))
281
psi_entangled = U_2qubit * psi_00
282
283
# Measure entanglement
284
rho_total = psi_entangled * psi_entangled.dag()
285
rho_A = qt.ptrace(rho_total, 0)
286
entanglement = qt.entropy_vn(rho_A)
287
print(f"Entanglement generated by random gate: {entanglement:.3f}")
288
289
# Random quantum circuit simulation
290
def random_circuit(n_qubits, depth, gate_prob=0.7):
291
"""Generate random quantum circuit."""
292
N = 2**n_qubits
293
U_total = qt.qeye([2]*n_qubits)
294
295
for layer in range(depth):
296
# Random single-qubit gates
297
for qubit in range(n_qubits):
298
if np.random.random() < gate_prob:
299
# Random single-qubit unitary
300
U_local = qt.rand_unitary(2)
301
302
# Embed in full space
303
gate_list = [qt.qeye(2) for _ in range(n_qubits)]
304
gate_list[qubit] = U_local
305
U_layer = qt.tensor(*gate_list)
306
U_total = U_layer * U_total
307
308
# Random two-qubit gates
309
for qubit in range(n_qubits-1):
310
if np.random.random() < gate_prob/2: # Less frequent
311
# Random CNOT-like gate
312
if np.random.random() < 0.5:
313
gate = qt.cnot(N=n_qubits, control=qubit, target=qubit+1)
314
else:
315
gate = qt.cz_gate(N=n_qubits, control=qubit, target=qubit+1)
316
U_total = gate * U_total
317
318
return U_total
319
320
# Test random circuit
321
n_qubits = 3
322
circuit_depth = 5
323
U_circuit = random_circuit(n_qubits, circuit_depth)
324
325
# Apply to initial state
326
initial_state = qt.tensor(*[qt.basis(2,0) for _ in range(n_qubits)]) # |000⟩
327
final_state = U_circuit * initial_state
328
329
print(f"Random circuit unitarity: {(U_circuit * U_circuit.dag() - qt.qeye(2**n_qubits)).norm():.2e}")
330
print(f"Final state norm: {final_state.norm():.6f}")
331
332
# Measure final state in computational basis
333
probs = [(abs(final_state[i,0])**2) for i in range(2**n_qubits)]
334
print(f"Computational basis probabilities: {[f'{p:.3f}' for p in probs]}")
335
```
336
337
## Types
338
339
```python { .api }
340
# All random object functions return Qobj instances with appropriate
341
# type ('ket', 'oper', 'super') and specified dimensions
342
```