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
| import numpy as np import matplotlib.pyplot as plt import random from collections import defaultdict import seaborn as sns from scipy.optimize import differential_evolution import warnings warnings.filterwarnings('ignore')
np.random.seed(42) random.seed(42)
class HPProteinFolder: """ HP Model Protein Folding Optimizer This class implements a simplified protein folding model where: - H represents hydrophobic amino acids - P represents polar amino acids - Goal: Maximize hydrophobic contacts while avoiding collisions """ def __init__(self, sequence): """ Initialize the protein folder with an HP sequence Args: sequence (str): String of 'H' and 'P' characters representing the protein """ self.sequence = sequence self.length = len(sequence) self.moves = [(0, 1), (1, 0), (0, -1), (-1, 0)] self.move_names = ['U', 'R', 'D', 'L'] def decode_folding(self, angles): """ Convert angle representation to 2D coordinates Args: angles (list): List of angles (0-3) representing folding directions Returns: tuple: (coordinates, valid_folding_flag) """ if len(angles) != self.length - 1: return None, False coordinates = [(0, 0)] current_pos = (0, 0) occupied = {(0, 0)} for i, angle in enumerate(angles): move_idx = int(angle) % 4 dx, dy = self.moves[move_idx] new_pos = (current_pos[0] + dx, current_pos[1] + dy) if new_pos in occupied: return None, False coordinates.append(new_pos) occupied.add(new_pos) current_pos = new_pos return coordinates, True def calculate_energy(self, coordinates): """ Calculate the energy of a folding configuration Energy = -1 * (number of H-H contacts that are adjacent in space but not in sequence) Args: coordinates (list): List of (x, y) coordinates for each amino acid Returns: float: Energy value (lower is better) """ if coordinates is None: return float('inf') energy = 0 for i in range(self.length): for j in range(i + 2, self.length): if self.sequence[i] == 'H' and self.sequence[j] == 'H': dist = abs(coordinates[i][0] - coordinates[j][0]) + abs(coordinates[i][1] - coordinates[j][1]) if dist == 1: energy -= 1 return energy def objective_function(self, angles): """ Objective function for optimization Args: angles (array): Array of folding angles Returns: float: Energy to minimize """ coordinates, valid = self.decode_folding(angles) if not valid: return 1000 return self.calculate_energy(coordinates) def optimize_folding(self, method='differential_evolution', max_iterations=1000): """ Optimize protein folding using specified optimization method Args: method (str): Optimization method to use max_iterations (int): Maximum number of iterations Returns: tuple: (best_angles, best_energy, optimization_history) """ bounds = [(0, 3.99) for _ in range(self.length - 1)] history = [] def callback(xk, convergence=None): energy = self.objective_function(xk) history.append(energy) return False if method == 'differential_evolution': result = differential_evolution( self.objective_function, bounds, maxiter=max_iterations // 10, popsize=15, callback=callback, seed=42 ) best_angles = result.x best_energy = result.fun return best_angles, best_energy, history def monte_carlo_optimization(self, max_iterations=10000, temperature=1.0, cooling_rate=0.995): """ Monte Carlo optimization with simulated annealing Args: max_iterations (int): Maximum number of iterations temperature (float): Initial temperature cooling_rate (float): Temperature cooling rate Returns: tuple: (best_angles, best_energy, history) """ current_angles = [random.uniform(0, 3.99) for _ in range(self.length - 1)] current_energy = self.objective_function(current_angles) best_angles = current_angles.copy() best_energy = current_energy history = [current_energy] temp = temperature for iteration in range(max_iterations): new_angles = current_angles.copy() idx = random.randint(0, len(new_angles) - 1) new_angles[idx] = random.uniform(0, 3.99) new_energy = self.objective_function(new_angles) if new_energy < current_energy or random.random() < np.exp(-(new_energy - current_energy) / temp): current_angles = new_angles current_energy = new_energy if current_energy < best_energy: best_angles = current_angles.copy() best_energy = current_energy history.append(best_energy) temp *= cooling_rate if iteration % 1000 == 0: print(f"Iteration {iteration}: Best Energy = {best_energy:.3f}, Temp = {temp:.4f}") return best_angles, best_energy, history
sequences = { 'simple': 'HPHPPHHPHH', 'medium': 'HPHPPHHPHHPPHPPHHPHH', 'complex': 'HHPPHPHPHPPHPPHPPHPHPHHPPHPPH' }
print("=== Protein Folding Optimization Results ===\n")
sequence = sequences['medium'] print(f"Protein sequence: {sequence}") print(f"Length: {len(sequence)} amino acids") print(f"Hydrophobic residues: {sequence.count('H')}") print(f"Polar residues: {sequence.count('P')}\n")
folder = HPProteinFolder(sequence)
print("Running Differential Evolution optimization...") de_angles, de_energy, de_history = folder.optimize_folding(method='differential_evolution') de_coords, de_valid = folder.decode_folding(de_angles)
print(f"DE - Best energy: {de_energy:.3f}") print(f"DE - Valid folding: {de_valid}\n")
print("Running Monte Carlo with Simulated Annealing...") mc_angles, mc_energy, mc_history = folder.monte_carlo_optimization(max_iterations=5000) mc_coords, mc_valid = folder.decode_folding(mc_angles)
print(f"MC - Best energy: {mc_energy:.3f}") print(f"MC - Valid folding: {mc_valid}\n")
def analyze_folding(coordinates, sequence, title): """ Analyze and display folding statistics """ if coordinates is None: print(f"{title}: Invalid folding") return h_positions = [i for i, aa in enumerate(sequence) if aa == 'H'] p_positions = [i for i, aa in enumerate(sequence) if aa == 'P'] hh_contacts = 0 for i in range(len(sequence)): for j in range(i + 2, len(sequence)): if sequence[i] == 'H' and sequence[j] == 'H': dist = abs(coordinates[i][0] - coordinates[j][0]) + abs(coordinates[i][1] - coordinates[j][1]) if dist == 1: hh_contacts += 1 center_x = np.mean([coord[0] for coord in coordinates]) center_y = np.mean([coord[1] for coord in coordinates]) rg = np.sqrt(np.mean([(coord[0] - center_x)**2 + (coord[1] - center_y)**2 for coord in coordinates])) print(f"{title} Analysis:") print(f" H-H contacts: {hh_contacts}") print(f" Energy: {-hh_contacts}") print(f" Radius of gyration: {rg:.3f}") print(f" Span X: {max(coord[0] for coord in coordinates) - min(coord[0] for coord in coordinates)}") print(f" Span Y: {max(coord[1] for coord in coordinates) - min(coord[1] for coord in coordinates)}") print()
analyze_folding(de_coords, sequence, "Differential Evolution") analyze_folding(mc_coords, sequence, "Monte Carlo")
fig, axes = plt.subplots(2, 3, figsize=(18, 12)) fig.suptitle('Protein Folding Optimization Results', fontsize=16, fontweight='bold')
if de_coords and de_valid: ax = axes[0, 0] x_coords = [coord[0] for coord in de_coords] y_coords = [coord[1] for coord in de_coords] ax.plot(x_coords, y_coords, 'k-', linewidth=2, alpha=0.7, label='Backbone') for i, (x, y) in enumerate(de_coords): color = 'red' if sequence[i] == 'H' else 'blue' marker = 'o' if sequence[i] == 'H' else 's' ax.scatter(x, y, c=color, s=150, marker=marker, edgecolors='black', linewidth=1, zorder=5) ax.annotate(f'{i}', (x, y), xytext=(5, 5), textcoords='offset points', fontsize=8, ha='left') ax.set_title(f'Differential Evolution\nEnergy: {de_energy:.1f}', fontweight='bold') ax.set_xlabel('X coordinate') ax.set_ylabel('Y coordinate') ax.grid(True, alpha=0.3) ax.legend(['Backbone', 'Hydrophobic (H)', 'Polar (P)']) ax.set_aspect('equal')
if mc_coords and mc_valid: ax = axes[0, 1] x_coords = [coord[0] for coord in mc_coords] y_coords = [coord[1] for coord in mc_coords] ax.plot(x_coords, y_coords, 'k-', linewidth=2, alpha=0.7) for i, (x, y) in enumerate(mc_coords): color = 'red' if sequence[i] == 'H' else 'blue' marker = 'o' if sequence[i] == 'H' else 's' ax.scatter(x, y, c=color, s=150, marker=marker, edgecolors='black', linewidth=1, zorder=5) ax.annotate(f'{i}', (x, y), xytext=(5, 5), textcoords='offset points', fontsize=8, ha='left') ax.set_title(f'Monte Carlo\nEnergy: {mc_energy:.1f}', fontweight='bold') ax.set_xlabel('X coordinate') ax.set_ylabel('Y coordinate') ax.grid(True, alpha=0.3) ax.set_aspect('equal')
ax = axes[0, 2] if len(de_history) > 0: ax.plot(range(len(de_history)), de_history, 'g-', linewidth=2, label='Differential Evolution') if len(mc_history) > 0: sample_indices = np.linspace(0, len(mc_history)-1, min(200, len(mc_history)), dtype=int) sampled_history = [mc_history[i] for i in sample_indices] ax.plot(sample_indices, sampled_history, 'r-', linewidth=2, label='Monte Carlo')
ax.set_title('Optimization Convergence', fontweight='bold') ax.set_xlabel('Iteration') ax.set_ylabel('Best Energy Found') ax.legend() ax.grid(True, alpha=0.3)
ax = axes[1, 0]
random_energies = [] for _ in range(1000): random_angles = [random.uniform(0, 3.99) for _ in range(len(sequence) - 1)] energy = folder.objective_function(random_angles) if energy < 100: random_energies.append(energy)
if random_energies: ax.hist(random_energies, bins=30, alpha=0.7, color='skyblue', edgecolor='black') ax.axvline(de_energy, color='green', linestyle='--', linewidth=2, label=f'DE: {de_energy:.1f}') ax.axvline(mc_energy, color='red', linestyle='--', linewidth=2, label=f'MC: {mc_energy:.1f}') ax.set_title('Energy Distribution\n(Random vs Optimized)', fontweight='bold') ax.set_xlabel('Energy') ax.set_ylabel('Frequency') ax.legend() ax.grid(True, alpha=0.3)
ax = axes[1, 1] positions = list(range(len(sequence))) colors = ['red' if aa == 'H' else 'blue' for aa in sequence] bars = ax.bar(positions, [1]*len(sequence), color=colors, alpha=0.7, edgecolor='black')
ax.set_title('Protein Sequence', fontweight='bold') ax.set_xlabel('Position') ax.set_ylabel('Amino Acid Type') ax.set_xticks(positions[::2]) ax.set_xticklabels(positions[::2]) ax.set_yticks([0.5, 1]) ax.set_yticklabels(['', 'H/P'])
from matplotlib.patches import Patch legend_elements = [Patch(facecolor='red', alpha=0.7, label='Hydrophobic (H)'), Patch(facecolor='blue', alpha=0.7, label='Polar (P)')] ax.legend(handles=legend_elements)
ax = axes[1, 2] contact_matrix = np.zeros((len(sequence), len(sequence)))
best_coords = mc_coords if mc_valid else de_coords if best_coords: for i in range(len(sequence)): for j in range(len(sequence)): if i != j: dist = abs(best_coords[i][0] - best_coords[j][0]) + abs(best_coords[i][1] - best_coords[j][1]) if dist == 1: contact_matrix[i, j] = 1
im = ax.imshow(contact_matrix, cmap='RdYlBu_r', aspect='equal') ax.set_title('Contact Map\n(Best Solution)', fontweight='bold') ax.set_xlabel('Residue Index') ax.set_ylabel('Residue Index')
cbar = plt.colorbar(im, ax=ax, shrink=0.8) cbar.set_label('Contact')
plt.tight_layout() plt.show()
print("=== Performance Comparison ===") print(f"Differential Evolution:") print(f" Final Energy: {de_energy:.3f}") print(f" Convergence Steps: {len(de_history)}")
print(f"Monte Carlo + Simulated Annealing:") print(f" Final Energy: {mc_energy:.3f}") print(f" Total Steps: {len(mc_history)}")
if de_valid and mc_valid: if de_energy < mc_energy: print(f"\n🏆 Winner: Differential Evolution (Energy: {de_energy:.3f})") elif mc_energy < de_energy: print(f"\n🏆 Winner: Monte Carlo (Energy: {mc_energy:.3f})") else: print(f"\n🤝 Tie! Both methods achieved energy: {de_energy:.3f}") else: print(f"\n⚠️ Some optimizations produced invalid foldings")
print("\n=== Mathematical Analysis ===") print("Energy Function:") print("E = -∑(i,j) δ_HiHj * contact(i,j)") print("where δ_HiHj = 1 if both residues i,j are hydrophobic and adjacent") print("Lower energy indicates better folding (more H-H contacts)")
|