Sequential Quantum Gate Decomposer  v1.9.6
Powerful decomposition of general unitarias into one- and two-qubit gates gates
basic_usage.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 """
3 Basic Usage Example for SQUANDER Density Matrix Module
4 
5 Demonstrates:
6 - Creating density matrices
7 - Applying quantum circuits
8 - Adding noise
9 - Computing quantum properties
10 """
11 
12 import numpy as np
13 import sys
14 
15 try:
16  from squander.density_matrix import (
17  DensityMatrix,
18  NoisyCircuit,
19  DepolarizingChannel,
20  AmplitudeDampingChannel,
21  )
22 except ImportError as e:
23  print(f"Error: Could not import density matrix module: {e}")
24  print("Please build the module first: python setup.py build_ext")
25  sys.exit(1)
26 
27 
29  """Example 1: Pure state evolution."""
30  print("\n" + "="*60)
31  print("Example 1: Pure State Evolution")
32  print("="*60)
33 
34  # Create 2-qubit density matrix (initialized to |00⟩)
35  rho = DensityMatrix(qbit_num=2)
36  print(f"Initial state: |00⟩⟨00|")
37  print(f" Purity: {rho.purity():.4f} (pure state)")
38  print(f" Entropy: {rho.entropy():.4f} bits")
39 
40  # Create Bell state circuit
41  circuit = NoisyCircuit(2)
42  circuit.add_H(0) # Hadamard on qubit 0
43  circuit.add_CNOT(1, 0) # CNOT with control=0, target=1
44 
45  # Apply circuit
46  circuit.apply_to(np.array([]), rho)
47 
48  print(f"\nAfter Bell state circuit:")
49  print(f" Purity: {rho.purity():.4f} (still pure)")
50  print(f" Entropy: {rho.entropy():.4f} bits")
51 
52  # Get density matrix
53  rho_np = rho.to_numpy()
54  print(f"\nDensity matrix shape: {rho_np.shape}")
55  print(f"Diagonal elements: {np.diag(rho_np).real}")
56 
57 
59  """Example 2: Simulation with noise."""
60  print("\n" + "="*60)
61  print("Example 2: Noise Simulation")
62  print("="*60)
63 
64  # Create circuit
65  circuit = NoisyCircuit(2)
66  circuit.add_H(0)
67  circuit.add_CNOT(1, 0)
68 
69  # Start with pure state
70  rho = DensityMatrix(qbit_num=2)
71  circuit.apply_to(np.array([]), rho)
72 
73  print(f"After circuit (no noise):")
74  print(f" Purity: {rho.purity():.4f}")
75 
76  # Add depolarizing noise
77  noise = DepolarizingChannel(qbit_num=2, error_rate=0.05)
78  noise.apply(rho)
79 
80  print(f"\nAfter 5% depolarizing noise:")
81  print(f" Purity: {rho.purity():.4f} (< 1, now mixed)")
82  print(f" Entropy: {rho.entropy():.4f} bits (> 0)")
83 
84  # Add more noise
85  for i in range(10):
86  noise.apply(rho)
87 
88  print(f"\nAfter repeated noise application:")
89  print(f" Purity: {rho.purity():.4f}")
90  print(f" Approaching maximally mixed (purity → 0.25)")
91 
92 
94  """Example 3: T1 and T2 noise."""
95  print("\n" + "="*60)
96  print("Example 3: T1 and T2 Noise")
97  print("="*60)
98 
99  # Create superposition state |+⟩ on qubit 0
100  psi = np.array([1, 1, 0, 0], dtype=complex) / np.sqrt(2)
101  rho = DensityMatrix(psi)
102 
103  rho_np = rho.to_numpy()
104  coherence_initial = abs(rho_np[0, 1])
105 
106  print(f"Initial state: |+0⟩")
107  print(f" Coherence ρ(0,1): {coherence_initial:.4f}")
108  print(f" Purity: {rho.purity():.4f}")
109 
110  # Apply T1 noise (amplitude damping)
111  t1_noise = AmplitudeDampingChannel(target_qbit=0, gamma=0.1)
112  t1_noise.apply(rho)
113 
114  print(f"\nAfter T1 noise (10% decay):")
115  print(f" Purity: {rho.purity():.4f}")
116 
117  # Apply T2 noise (phase damping) would further reduce coherence
118  # (Will be fully implemented in Phase 1)
119 
120 
122  """Example 4: Maximally mixed state."""
123  print("\n" + "="*60)
124  print("Example 4: Maximally Mixed State")
125  print("="*60)
126 
127  # Create maximally mixed state
128  rho = DensityMatrix.maximally_mixed(qbit_num=2)
129 
130  print(f"Maximally mixed state (2 qubits):")
131  print(f" Purity: {rho.purity():.4f} (= 1/2² = 0.25)")
132  print(f" Entropy: {rho.entropy():.4f} bits (= log₂(4) = 2)")
133 
134  # Eigenvalues
135  eigs = rho.eigenvalues()
136  print(f" Eigenvalues: {eigs} (all equal for maximally mixed)")
137 
138 
140  """Example 5: Partial trace."""
141  print("\n" + "="*60)
142  print("Example 5: Partial Trace")
143  print("="*60)
144 
145  # Create Bell state
146  circuit = NoisyCircuit(2)
147  circuit.add_H(0)
148  circuit.add_CNOT(1, 0)
149 
150  rho_full = DensityMatrix(qbit_num=2)
151  circuit.apply_to(np.array([]), rho_full)
152 
153  print(f"Full Bell state (2 qubits):")
154  print(f" Purity: {rho_full.purity():.4f} (pure)")
155 
156  # Trace out qubit 1
157  rho_reduced = rho_full.partial_trace([1])
158 
159  print(f"\nReduced state (qubit 0 only):")
160  print(f" Purity: {rho_reduced.purity():.4f} (maximally mixed)")
161  print(f" Entropy: {rho_reduced.entropy():.4f} bits")
162 
163  print(f"\nThis demonstrates entanglement: tracing out one qubit")
164  print(f"of an entangled pair gives a maximally mixed state.")
165 
166 
167 def main():
168  """Run all examples."""
169  print("\n" + "="*60)
170  print("SQUANDER Density Matrix Module - Basic Usage Examples")
171  print("="*60)
172 
173  try:
179 
180  print("\n" + "="*60)
181  print("All examples completed successfully!")
182  print("="*60 + "\n")
183 
184  except Exception as e:
185  print(f"\nError running examples: {e}")
186  import traceback
187  traceback.print_exc()
188  sys.exit(1)
189 
190 
191 if __name__ == "__main__":
192  main()
193 
def example_2_noise_simulation()
Definition: basic_usage.py:58
def example_5_partial_trace()
Definition: basic_usage.py:139
def example_1_pure_state_evolution()
Definition: basic_usage.py:28
def example_3_t1_t2_noise()
Definition: basic_usage.py:93
def example_4_maximally_mixed()
Definition: basic_usage.py:121