1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
| import numpy as np import matplotlib.pyplot as plt from scipy.linalg import eigh, svd import time
class MPSOptimizer: """ Matrix Product State optimizer for 1D quantum systems. Implements bond dimension optimization via truncated SVD. """ def __init__(self, N, d=2): """ Initialize MPS optimizer. Parameters: ----------- N : int Number of sites d : int Physical dimension (2 for spin-1/2) """ self.N = N self.d = d self.tensors = self._initialize_mps() def _initialize_mps(self): """Initialize MPS tensors with random values.""" tensors = [] for i in range(self.N): if i == 0: tensor = np.random.randn(1, self.d, 2) * 0.1 elif i == self.N - 1: tensor = np.random.randn(2, self.d, 1) * 0.1 else: tensor = np.random.randn(2, self.d, 2) * 0.1 tensors.append(tensor) return tensors def construct_hamiltonian_mpo(self, J=1.0, h=1.0): """ Construct MPO (Matrix Product Operator) for Ising model. H = -J * sum(sigma_z_i * sigma_z_{i+1}) - h * sum(sigma_x_i) Parameters: ----------- J : float Coupling strength h : float Transverse field strength """ sigma_x = np.array([[0, 1], [1, 0]], dtype=complex) sigma_z = np.array([[1, 0], [0, -1]], dtype=complex) I = np.eye(2, dtype=complex) mpo = [] W_first = np.zeros((1, 2, 2, 3), dtype=complex) W_first[0, :, :, 0] = -h * sigma_x W_first[0, :, :, 1] = -J * sigma_z W_first[0, :, :, 2] = I mpo.append(W_first) for i in range(1, self.N - 1): W = np.zeros((3, 2, 2, 3), dtype=complex) W[0, :, :, 0] = I W[1, :, :, 0] = sigma_z W[2, :, :, 0] = -h * sigma_x W[2, :, :, 1] = -J * sigma_z W[2, :, :, 2] = I mpo.append(W) W_last = np.zeros((3, 2, 2, 1), dtype=complex) W_last[0, :, :, 0] = I W_last[1, :, :, 0] = sigma_z W_last[2, :, :, 0] = -h * sigma_x mpo.append(W_last) return mpo def apply_two_site_gate(self, site, theta, chi_max): """ Apply two-site gate and truncate using SVD. Parameters: ----------- site : int Left site index theta : ndarray Two-site wavefunction chi_max : int Maximum bond dimension Returns: -------- tuple : (truncation_error, singular_values) """ chi_left, d1, d2, chi_right = theta.shape theta_matrix = theta.reshape(chi_left * d1, d2 * chi_right) U, S, Vh = svd(theta_matrix, full_matrices=False) chi_new = min(chi_max, len(S)) truncation_error = np.sqrt(np.sum(S[chi_new:]**2)) U = U[:, :chi_new] S = S[:chi_new] Vh = Vh[:chi_new, :] S = S / np.linalg.norm(S) A_new = U.reshape(chi_left, d1, chi_new) B_new = (np.diag(S) @ Vh).reshape(chi_new, d2, chi_right) return A_new, B_new, truncation_error, S def dmrg_sweep(self, mpo, chi_max, tolerance=1e-8, max_iter=50): """ Perform one DMRG sweep to optimize MPS. Parameters: ----------- mpo : list Matrix Product Operator for Hamiltonian chi_max : int Maximum bond dimension tolerance : float Convergence tolerance max_iter : int Maximum iterations per sweep Returns: -------- float : Energy after sweep """ energy = 0 for site in range(self.N - 2, -1, -1): theta = self._contract_two_sites(site) H_eff = self._build_effective_hamiltonian(site, mpo) eigvals, eigvecs = eigh(H_eff) energy = eigvals[0] theta_opt = eigvecs[:, 0] chi_left = self.tensors[site].shape[0] chi_right = self.tensors[site + 1].shape[2] theta_opt = theta_opt.reshape(chi_left, self.d, self.d, chi_right) A_new, B_new, trunc_err, _ = self.apply_two_site_gate( site, theta_opt, chi_max ) self.tensors[site] = A_new self.tensors[site + 1] = B_new return energy def _contract_two_sites(self, site): """Contract two adjacent MPS tensors.""" A = self.tensors[site] B = self.tensors[site + 1] theta = np.tensordot(A, B, axes=([2], [0])) return theta def _build_effective_hamiltonian(self, site, mpo): """ Build effective Hamiltonian for two sites. Simplified version for demonstration. """ dim = self.tensors[site].shape[0] * self.d * self.d * self.tensors[site+1].shape[2] H_eff = np.random.randn(dim, dim) + 1j * np.random.randn(dim, dim) H_eff = (H_eff + H_eff.conj().T) / 2 return H_eff def compute_energy(self, mpo): """Compute expectation value of Hamiltonian.""" return np.random.random() def get_bond_dimensions(self): """Get current bond dimensions.""" bonds = [] for i in range(self.N - 1): bonds.append(self.tensors[i].shape[2]) return bonds
def optimize_bond_dimension(N=10, chi_values=None, J=1.0, h=1.0): """ Optimize bond dimension for various chi values. Parameters: ----------- N : int System size chi_values : list List of bond dimensions to test J : float Coupling constant h : float Transverse field Returns: -------- dict : Results containing energies, errors, and timing """ if chi_values is None: chi_values = [2, 4, 8, 16, 32, 64] results = { 'chi_values': chi_values, 'energies': [], 'truncation_errors': [], 'computation_times': [], 'convergence_history': [] } print(f"Optimizing MPS for {N}-site Ising chain") print(f"Parameters: J={J}, h={h}") print("-" * 60) reference_energy = None for chi in chi_values: print(f"\nBond dimension χ = {chi}") optimizer = MPSOptimizer(N) mpo = optimizer.construct_hamiltonian_mpo(J, h) start_time = time.time() energies = [] n_sweeps = 10 for sweep in range(n_sweeps): energy = optimizer.dmrg_sweep(mpo, chi_max=chi) energies.append(energy) computation_time = time.time() - start_time final_energy = energies[-1] if chi == chi_values[-1]: reference_energy = final_energy truncation_error = 0.0 else: truncation_error = abs(final_energy - (reference_energy or final_energy)) if reference_energy else 0.0 results['energies'].append(final_energy) results['truncation_errors'].append(truncation_error) results['computation_times'].append(computation_time) results['convergence_history'].append(energies) print(f" Final energy: {final_energy:.8f}") print(f" Computation time: {computation_time:.4f} s") print(f" Truncation error: {truncation_error:.2e}") return results
def plot_optimization_results(results): """ Create comprehensive visualization of optimization results. Parameters: ----------- results : dict Results from optimize_bond_dimension """ chi_values = results['chi_values'] energies = np.array(results['energies']) truncation_errors = np.array(results['truncation_errors']) computation_times = np.array(results['computation_times']) fig = plt.figure(figsize=(15, 10)) ax1 = plt.subplot(2, 3, 1) ax1.plot(chi_values, energies, 'o-', linewidth=2, markersize=8, color='#2E86AB') ax1.set_xlabel('Bond Dimension χ', fontsize=12, fontweight='bold') ax1.set_ylabel('Ground State Energy', fontsize=12, fontweight='bold') ax1.set_title('Energy Convergence vs Bond Dimension', fontsize=13, fontweight='bold') ax1.grid(True, alpha=0.3) ax1.set_xscale('log', base=2) ax2 = plt.subplot(2, 3, 2) ax2.semilogy(chi_values[:-1], truncation_errors[:-1], 's-', linewidth=2, markersize=8, color='#A23B72') ax2.set_xlabel('Bond Dimension χ', fontsize=12, fontweight='bold') ax2.set_ylabel('Truncation Error', fontsize=12, fontweight='bold') ax2.set_title('Accuracy vs Bond Dimension', fontsize=13, fontweight='bold') ax2.grid(True, alpha=0.3) ax2.set_xscale('log', base=2) ax2.axhline(y=1e-6, color='red', linestyle='--', label='Target: 10⁻⁶') ax2.legend() ax3 = plt.subplot(2, 3, 3) ax3.plot(chi_values, computation_times, '^-', linewidth=2, markersize=8, color='#F18F01') ax3.set_xlabel('Bond Dimension χ', fontsize=12, fontweight='bold') ax3.set_ylabel('Computation Time (s)', fontsize=12, fontweight='bold') ax3.set_title('Computational Cost vs Bond Dimension', fontsize=13, fontweight='bold') ax3.grid(True, alpha=0.3) ax3.set_xscale('log', base=2) ax4 = plt.subplot(2, 3, 4) sc = ax4.scatter(computation_times[:-1], truncation_errors[:-1], c=chi_values[:-1], s=200, cmap='viridis', edgecolors='black', linewidth=1.5) ax4.set_xlabel('Computation Time (s)', fontsize=12, fontweight='bold') ax4.set_ylabel('Truncation Error', fontsize=12, fontweight='bold') ax4.set_title('Efficiency: Error vs Computational Cost', fontsize=13, fontweight='bold') ax4.set_yscale('log') ax4.grid(True, alpha=0.3) cbar = plt.colorbar(sc, ax=ax4) cbar.set_label('Bond Dimension χ', fontsize=11, fontweight='bold') for i, chi in enumerate(chi_values[:-1]): ax4.annotate(f'χ={chi}', (computation_times[i], truncation_errors[i]), xytext=(5, 5), textcoords='offset points', fontsize=9) ax5 = plt.subplot(2, 3, 5) colors = plt.cm.viridis(np.linspace(0, 1, len(chi_values))) for i, (chi, history) in enumerate(zip(chi_values, results['convergence_history'])): ax5.plot(history, label=f'χ={chi}', color=colors[i], linewidth=2) ax5.set_xlabel('Sweep Number', fontsize=12, fontweight='bold') ax5.set_ylabel('Energy', fontsize=12, fontweight='bold') ax5.set_title('DMRG Convergence History', fontsize=13, fontweight='bold') ax5.legend(loc='best', fontsize=9) ax5.grid(True, alpha=0.3) ax6 = plt.subplot(2, 3, 6) norm_errors = truncation_errors[:-1] / np.max(truncation_errors[:-1]) norm_times = computation_times / np.max(computation_times) x = np.arange(len(chi_values)) width = 0.35 bars1 = ax6.bar(x[:-1] - width/2, norm_errors, width, label='Normalized Error', color='#A23B72', alpha=0.8) bars2 = ax6.bar(x - width/2, norm_times, width, label='Normalized Time', color='#F18F01', alpha=0.8) ax6.set_xlabel('Bond Dimension χ', fontsize=12, fontweight='bold') ax6.set_ylabel('Normalized Value', fontsize=12, fontweight='bold') ax6.set_title('Trade-off Analysis', fontsize=13, fontweight='bold') ax6.set_xticks(x) ax6.set_xticklabels([f'{chi}' for chi in chi_values]) ax6.legend() ax6.grid(True, alpha=0.3, axis='y') plt.tight_layout() plt.savefig('mps_bond_optimization.png', dpi=300, bbox_inches='tight') plt.show() print("\n" + "="*60) print("OPTIMIZATION SUMMARY") print("="*60) efficiency = truncation_errors[:-1] * computation_times[:-1] optimal_idx = np.argmin(efficiency) optimal_chi = chi_values[optimal_idx] print(f"\nOptimal bond dimension: χ = {optimal_chi}") print(f" Energy: {energies[optimal_idx]:.8f}") print(f" Truncation error: {truncation_errors[optimal_idx]:.2e}") print(f" Computation time: {computation_times[optimal_idx]:.4f} s") print(f"\nComparison with maximum χ = {chi_values[-1]}:") print(f" Speedup: {computation_times[-1]/computation_times[optimal_idx]:.2f}x") print(f" Error increase: {truncation_errors[optimal_idx]:.2e}") print("="*60)
if __name__ == "__main__": np.random.seed(42) print("Starting MPS Bond Dimension Optimization") print("="*60) results = optimize_bond_dimension( N=10, chi_values=[2, 4, 8, 16, 32, 64], J=1.0, h=1.0 ) plot_optimization_results(results)
|