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
| import numpy as np import matplotlib.pyplot as plt from scipy.optimize import differential_evolution, minimize from scipy.integrate import odeint from mpl_toolkits.mplot3d import Axes3D import warnings warnings.filterwarnings('ignore')
R = 8.314 k_B = 1e8 k_C = 1e6 E_B = 50000 E_C = 45000
def reaction_rates(y, t, T, P, Cat): """ Calculate reaction rates for the chemical system y[0] = [A], y[1] = [B], y[2] = [C] """ A, B, C = y T_K = T + 273.15 r_B = k_B * A * (Cat**0.5) * (P**0.8) * np.exp(-E_B / (R * T_K)) r_C = k_C * A * (T**0.3) * np.exp(-E_C / (R * T_K)) dA_dt = -r_B - r_C dB_dt = r_B dC_dt = r_C return [dA_dt, dB_dt, dC_dt]
def simulate_reaction(T, P, Cat, t_max=10, A0=1.0): """ Simulate the reaction over time Returns final concentrations and time series """ y0 = [A0, 0, 0] t = np.linspace(0, t_max, 1000) solution = odeint(reaction_rates, y0, t, args=(T, P, Cat)) return t, solution
def objective_function(params): """ Multi-objective function to minimize: - Maximize B yield (minimize -B) - Minimize reaction time (minimize time to reach 90% conversion) - Minimize C formation (minimize C) """ T, P, Cat = params t, solution = simulate_reaction(T, P, Cat, t_max=20) A = solution[:, 0] B = solution[:, 1] C = solution[:, 2] final_B = B[-1] final_C = C[-1] conversion = 1 - A / A[0] idx_90 = np.where(conversion >= 0.9)[0] if len(idx_90) > 0: time_90 = t[idx_90[0]] else: time_90 = 20 selectivity = final_B / (final_C + 1e-10) objective = -final_B + 0.5 * time_90 - 0.3 * selectivity + 2 * final_C return objective
print("=" * 60) print("CHEMICAL REACTION OPTIMIZATION") print("=" * 60) print("\nOptimizing reaction conditions...") print("Parameters: Temperature (50-100°C), Pressure (1-10 atm), Catalyst (0.1-1.0 M)") print("\nRunning global optimization...\n")
bounds = [(50, 100), (1, 10), (0.1, 1.0)]
result = differential_evolution(objective_function, bounds, seed=42, maxiter=100, popsize=15, tol=1e-6, atol=1e-6)
optimal_T, optimal_P, optimal_Cat = result.x
print("Optimization Complete!") print("-" * 60) print(f"Optimal Temperature: {optimal_T:.2f} °C") print(f"Optimal Pressure: {optimal_P:.2f} atm") print(f"Optimal Catalyst Concentration: {optimal_Cat:.3f} mol/L") print("-" * 60)
t_opt, sol_opt = simulate_reaction(optimal_T, optimal_P, optimal_Cat, t_max=15) A_opt = sol_opt[:, 0] B_opt = sol_opt[:, 1] C_opt = sol_opt[:, 2]
final_yield_B = B_opt[-1] final_C = C_opt[-1] selectivity = final_yield_B / (final_C + 1e-10) conversion = 1 - A_opt / A_opt[0] idx_90_opt = np.where(conversion >= 0.9)[0] time_90_opt = t_opt[idx_90_opt[0]] if len(idx_90_opt) > 0 else 15
print(f"\nPerformance Metrics (Optimal Conditions):") print(f" Final Yield of B: {final_yield_B:.4f} mol/L ({final_yield_B*100:.2f}%)") print(f" Final Byproduct C: {final_C:.4f} mol/L ({final_C*100:.2f}%)") print(f" Selectivity (B/C): {selectivity:.2f}") print(f" Time to 90% conversion: {time_90_opt:.2f} hours") print("=" * 60)
suboptimal_conditions = [ (60, 2, 0.2, "Low T, Low P, Low Cat"), (80, 5, 0.5, "Medium conditions"), (95, 9, 0.9, "High T, High P, High Cat") ]
fig = plt.figure(figsize=(16, 12))
ax1 = plt.subplot(3, 3, 1) ax1.plot(t_opt, A_opt, 'b-', linewidth=2, label='[A] - Reactant') ax1.plot(t_opt, B_opt, 'g-', linewidth=2, label='[B] - Desired Product') ax1.plot(t_opt, C_opt, 'r-', linewidth=2, label='[C] - Byproduct') ax1.axvline(time_90_opt, color='gray', linestyle='--', alpha=0.7, label='90% Conversion') ax1.set_xlabel('Time (hours)', fontsize=11) ax1.set_ylabel('Concentration (mol/L)', fontsize=11) ax1.set_title('Optimal Conditions: Concentration Profiles', fontsize=12, fontweight='bold') ax1.legend(loc='best', fontsize=9) ax1.grid(True, alpha=0.3)
ax2 = plt.subplot(3, 3, 2) conversion_opt = (1 - A_opt / A_opt[0]) * 100 selectivity_time = B_opt / (C_opt + 1e-10) ax2_twin = ax2.twinx() ax2.plot(t_opt, conversion_opt, 'b-', linewidth=2, label='Conversion of A') ax2_twin.plot(t_opt, selectivity_time, 'g-', linewidth=2, label='Selectivity (B/C)') ax2.set_xlabel('Time (hours)', fontsize=11) ax2.set_ylabel('Conversion (%)', color='b', fontsize=11) ax2_twin.set_ylabel('Selectivity', color='g', fontsize=11) ax2.set_title('Conversion and Selectivity vs Time', fontsize=12, fontweight='bold') ax2.tick_params(axis='y', labelcolor='b') ax2_twin.tick_params(axis='y', labelcolor='g') ax2.grid(True, alpha=0.3) lines1, labels1 = ax2.get_legend_handles_labels() lines2, labels2 = ax2_twin.get_legend_handles_labels() ax2.legend(lines1 + lines2, labels1 + labels2, loc='center right', fontsize=9)
ax3 = plt.subplot(3, 3, 3) colors = ['orange', 'purple', 'brown'] ax3.plot(t_opt, B_opt, 'g-', linewidth=3, label=f'Optimal: T={optimal_T:.1f}°C', alpha=0.9) for i, (T, P, Cat, label) in enumerate(suboptimal_conditions): t_sub, sol_sub = simulate_reaction(T, P, Cat, t_max=15) B_sub = sol_sub[:, 1] ax3.plot(t_sub, B_sub, linestyle='--', linewidth=2, label=label, color=colors[i], alpha=0.7) ax3.set_xlabel('Time (hours)', fontsize=11) ax3.set_ylabel('[B] Desired Product (mol/L)', fontsize=11) ax3.set_title('Yield Comparison: Optimal vs Suboptimal', fontsize=12, fontweight='bold') ax3.legend(loc='best', fontsize=9) ax3.grid(True, alpha=0.3)
ax4 = plt.subplot(3, 3, 4) T_range = np.linspace(50, 100, 30) yields_T = [] C_T = [] for T in T_range: _, sol = simulate_reaction(T, optimal_P, optimal_Cat, t_max=15) yields_T.append(sol[-1, 1]) C_T.append(sol[-1, 2]) ax4_twin = ax4.twinx() ax4.plot(T_range, yields_T, 'g-', linewidth=2, label='[B] Yield') ax4_twin.plot(T_range, C_T, 'r--', linewidth=2, label='[C] Byproduct') ax4.axvline(optimal_T, color='blue', linestyle=':', linewidth=2, alpha=0.7) ax4.set_xlabel('Temperature (°C)', fontsize=11) ax4.set_ylabel('[B] Yield (mol/L)', color='g', fontsize=11) ax4_twin.set_ylabel('[C] Byproduct (mol/L)', color='r', fontsize=11) ax4.set_title('Effect of Temperature', fontsize=12, fontweight='bold') ax4.tick_params(axis='y', labelcolor='g') ax4_twin.tick_params(axis='y', labelcolor='r') ax4.grid(True, alpha=0.3)
ax5 = plt.subplot(3, 3, 5) P_range = np.linspace(1, 10, 30) yields_P = [] time_90_P = [] for P in P_range: t, sol = simulate_reaction(optimal_T, P, optimal_Cat, t_max=20) yields_P.append(sol[-1, 1]) conv = 1 - sol[:, 0] / sol[0, 0] idx = np.where(conv >= 0.9)[0] time_90_P.append(t[idx[0]] if len(idx) > 0 else 20) ax5_twin = ax5.twinx() ax5.plot(P_range, yields_P, 'g-', linewidth=2, label='[B] Yield') ax5_twin.plot(P_range, time_90_P, 'orange', linewidth=2, label='Time to 90%') ax5.axvline(optimal_P, color='blue', linestyle=':', linewidth=2, alpha=0.7) ax5.set_xlabel('Pressure (atm)', fontsize=11) ax5.set_ylabel('[B] Yield (mol/L)', color='g', fontsize=11) ax5_twin.set_ylabel('Reaction Time (hours)', color='orange', fontsize=11) ax5.set_title('Effect of Pressure', fontsize=12, fontweight='bold') ax5.tick_params(axis='y', labelcolor='g') ax5_twin.tick_params(axis='y', labelcolor='orange') ax5.grid(True, alpha=0.3)
ax6 = plt.subplot(3, 3, 6) Cat_range = np.linspace(0.1, 1.0, 30) yields_Cat = [] selectivity_Cat = [] for Cat in Cat_range: _, sol = simulate_reaction(optimal_T, optimal_P, Cat, t_max=15) yields_Cat.append(sol[-1, 1]) selectivity_Cat.append(sol[-1, 1] / (sol[-1, 2] + 1e-10)) ax6_twin = ax6.twinx() ax6.plot(Cat_range, yields_Cat, 'g-', linewidth=2, label='[B] Yield') ax6_twin.plot(Cat_range, selectivity_Cat, 'purple', linewidth=2, label='Selectivity') ax6.axvline(optimal_Cat, color='blue', linestyle=':', linewidth=2, alpha=0.7) ax6.set_xlabel('Catalyst Concentration (mol/L)', fontsize=11) ax6.set_ylabel('[B] Yield (mol/L)', color='g', fontsize=11) ax6_twin.set_ylabel('Selectivity (B/C)', color='purple', fontsize=11) ax6.set_title('Effect of Catalyst Concentration', fontsize=12, fontweight='bold') ax6.tick_params(axis='y', labelcolor='g') ax6_twin.tick_params(axis='y', labelcolor='purple') ax6.grid(True, alpha=0.3)
ax7 = plt.subplot(3, 3, 7, projection='3d') T_grid = np.linspace(50, 100, 20) P_grid = np.linspace(1, 10, 20) T_mesh, P_mesh = np.meshgrid(T_grid, P_grid) Yield_mesh = np.zeros_like(T_mesh) for i in range(len(T_grid)): for j in range(len(P_grid)): _, sol = simulate_reaction(T_mesh[j, i], P_mesh[j, i], optimal_Cat, t_max=15) Yield_mesh[j, i] = sol[-1, 1] surf = ax7.plot_surface(T_mesh, P_mesh, Yield_mesh, cmap='viridis', alpha=0.8) ax7.scatter([optimal_T], [optimal_P], [final_yield_B], color='red', s=100, marker='*', label='Optimum') ax7.set_xlabel('Temperature (°C)', fontsize=10) ax7.set_ylabel('Pressure (atm)', fontsize=10) ax7.set_zlabel('[B] Yield (mol/L)', fontsize=10) ax7.set_title('Yield Surface: T vs P', fontsize=12, fontweight='bold') fig.colorbar(surf, ax=ax7, shrink=0.5)
ax8 = plt.subplot(3, 3, 8) conditions_labels = ['Optimal'] + [label for _, _, _, label in suboptimal_conditions] B_values = [final_yield_B] C_values = [final_C] for T, P, Cat, _ in suboptimal_conditions: _, sol = simulate_reaction(T, P, Cat, t_max=15) B_values.append(sol[-1, 1]) C_values.append(sol[-1, 2]) x_pos = np.arange(len(conditions_labels)) width = 0.35 ax8.bar(x_pos - width/2, B_values, width, label='[B] Desired', color='green', alpha=0.7) ax8.bar(x_pos + width/2, C_values, width, label='[C] Byproduct', color='red', alpha=0.7) ax8.set_xlabel('Conditions', fontsize=11) ax8.set_ylabel('Concentration (mol/L)', fontsize=11) ax8.set_title('Product Distribution Comparison', fontsize=12, fontweight='bold') ax8.set_xticks(x_pos) ax8.set_xticklabels(conditions_labels, rotation=15, ha='right', fontsize=9) ax8.legend(loc='best', fontsize=9) ax8.grid(True, alpha=0.3, axis='y')
ax9 = plt.subplot(3, 3, 9, projection='polar') categories = ['Yield\n(normalized)', 'Selectivity\n(normalized)', 'Speed\n(1/time)', 'Purity\n(B/(B+C))'] N = len(categories)
metrics_opt = [ final_yield_B, selectivity / 10, 1 / time_90_opt, final_yield_B / (final_yield_B + final_C) ]
metrics_opt_norm = np.array(metrics_opt) / np.max(metrics_opt)
T_sub, P_sub, Cat_sub, _ = suboptimal_conditions[1] t_sub, sol_sub = simulate_reaction(T_sub, P_sub, Cat_sub, t_max=15) B_sub = sol_sub[-1, 1] C_sub = sol_sub[-1, 2] sel_sub = B_sub / (C_sub + 1e-10) conv_sub = 1 - sol_sub[:, 0] / sol_sub[0, 0] idx_sub = np.where(conv_sub >= 0.9)[0] time_sub = t_sub[idx_sub[0]] if len(idx_sub) > 0 else 15
metrics_sub = [ B_sub, sel_sub / 10, 1 / time_sub, B_sub / (B_sub + C_sub) ] metrics_sub_norm = np.array(metrics_sub) / np.max(metrics_opt)
angles = np.linspace(0, 2 * np.pi, N, endpoint=False).tolist() metrics_opt_norm = np.concatenate((metrics_opt_norm, [metrics_opt_norm[0]])) metrics_sub_norm = np.concatenate((metrics_sub_norm, [metrics_sub_norm[0]])) angles += angles[:1]
ax9.plot(angles, metrics_opt_norm, 'g-', linewidth=2, label='Optimal') ax9.fill(angles, metrics_opt_norm, 'g', alpha=0.25) ax9.plot(angles, metrics_sub_norm, 'r--', linewidth=2, label='Suboptimal') ax9.fill(angles, metrics_sub_norm, 'r', alpha=0.15) ax9.set_xticks(angles[:-1]) ax9.set_xticklabels(categories, fontsize=9) ax9.set_ylim(0, 1) ax9.set_title('Performance Comparison (Normalized)', fontsize=12, fontweight='bold', pad=20) ax9.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1), fontsize=9) ax9.grid(True)
plt.tight_layout() plt.savefig('reaction_optimization.png', dpi=150, bbox_inches='tight') print("\n✓ Visualization saved as 'reaction_optimization.png'") plt.show()
print("\n" + "=" * 60) print("COMPARATIVE ANALYSIS") print("=" * 60) print(f"{'Condition':<25} {'[B] Yield':<12} {'[C] Byprod':<12} {'B/C Ratio':<12} {'Time(h)':<10}") print("-" * 60) print(f"{'Optimal':<25} {final_yield_B:<12.4f} {final_C:<12.4f} {selectivity:<12.2f} {time_90_opt:<10.2f}") for T, P, Cat, label in suboptimal_conditions: t_s, sol_s = simulate_reaction(T, P, Cat, t_max=15) B_s = sol_s[-1, 1] C_s = sol_s[-1, 2] sel_s = B_s / (C_s + 1e-10) conv_s = 1 - sol_s[:, 0] / sol_s[0, 0] idx_s = np.where(conv_s >= 0.9)[0] time_s = t_s[idx_s[0]] if len(idx_s) > 0 else 15 print(f"{label:<25} {B_s:<12.4f} {C_s:<12.4f} {sel_s:<12.2f} {time_s:<10.2f}") print("=" * 60) print("\nAnalysis complete! Check the visualization above for detailed insights.")
|