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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
|
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from mpl_toolkits.mplot3d import Axes3D from itertools import combinations import random import time from matplotlib.gridspec import GridSpec import warnings warnings.filterwarnings('ignore')
np.random.seed(42) random.seed(42)
N_DRUGS = 10 LAMBDA = 0.6
drug_names = [f"Drug-{chr(65+i)}" for i in range(N_DRUGS)]
efficacy = np.array([0.82, 0.65, 0.91, 0.74, 0.58, 0.87, 0.70, 0.63, 0.79, 0.55])
toxicity = np.array([0.45, 0.30, 0.70, 0.40, 0.25, 0.60, 0.35, 0.50, 0.55, 0.20])
synergy_raw = np.array([ [ 0.00, 0.15, -0.10, 0.20, 0.05, -0.05, 0.25, 0.10, -0.15, 0.08], [ 0.15, 0.00, 0.30, -0.05, 0.18, 0.12, -0.08, 0.22, 0.07, -0.10], [-0.10, 0.30, 0.00, 0.15, -0.12, 0.40, 0.10, -0.05, 0.28, 0.05], [ 0.20, -0.05, 0.15, 0.00, 0.35, -0.10, 0.18, 0.12, -0.08, 0.22], [ 0.05, 0.18, -0.12, 0.35, 0.00, 0.25, -0.15, 0.30, 0.10, -0.05], [-0.05, 0.12, 0.40, -0.10, 0.25, 0.00, 0.20, -0.08, 0.35, 0.15], [ 0.25, -0.08, 0.10, 0.18, -0.15, 0.20, 0.00, 0.28, -0.10, 0.12], [ 0.10, 0.22, -0.05, 0.12, 0.30, -0.08, 0.28, 0.00, 0.15, -0.12], [-0.15, 0.07, 0.28, -0.08, 0.10, 0.35, -0.10, 0.15, 0.00, 0.20], [ 0.08, -0.10, 0.05, 0.22, -0.05, 0.15, 0.12, -0.12, 0.20, 0.00], ]) synergy = (synergy_raw + synergy_raw.T) / 2
def score(subset, efficacy, toxicity, synergy, lam=LAMBDA): """ Compute the composite score for a drug subset. subset: list or array of drug indices """ if len(subset) == 0: return -np.inf
s = list(subset) eff_sum = np.sum(efficacy[s]) tox_sum = np.sum(toxicity[s])
syn_sum = 0.0 for i in range(len(s)): for j in range(i+1, len(s)): syn_sum += synergy[s[i], s[j]]
return eff_sum - lam * tox_sum + syn_sum
def brute_force(n_drugs, efficacy, toxicity, synergy, max_combo_size=None): best_score = -np.inf best_subset = [] all_scores = [] all_subsets = []
max_k = max_combo_size if max_combo_size else n_drugs
for k in range(1, max_k + 1): for combo in combinations(range(n_drugs), k): sc = score(combo, efficacy, toxicity, synergy) all_scores.append(sc) all_subsets.append(combo) if sc > best_score: best_score = sc best_subset = combo
return best_subset, best_score, all_scores, all_subsets
def genetic_algorithm(n_drugs, efficacy, toxicity, synergy, pop_size=100, n_generations=300, mutation_rate=0.05, lam=LAMBDA):
def random_individual(): return np.random.randint(0, 2, n_drugs).astype(bool)
def fitness(ind): subset = np.where(ind)[0] return score(subset, efficacy, toxicity, synergy, lam)
def crossover(p1, p2): point = random.randint(1, n_drugs - 1) child = np.concatenate([p1[:point], p2[point:]]) return child
def mutate(ind): ind = ind.copy() for i in range(n_drugs): if random.random() < mutation_rate: ind[i] = not ind[i] return ind
population = [random_individual() for _ in range(pop_size)] best_history = []
for gen in range(n_generations): fitnesses = np.array([fitness(ind) for ind in population]) best_idx = np.argmax(fitnesses) best_history.append(fitnesses[best_idx])
new_pop = [] for _ in range(pop_size): i1, i2 = random.sample(range(pop_size), 2) winner = population[i1] if fitnesses[i1] >= fitnesses[i2] else population[i2] new_pop.append(winner.copy())
children = [] for i in range(0, pop_size, 2): p1, p2 = new_pop[i], new_pop[min(i+1, pop_size-1)] c1 = mutate(crossover(p1, p2)) c2 = mutate(crossover(p2, p1)) children.extend([c1, c2])
population = children[:pop_size]
fitnesses = np.array([fitness(ind) for ind in population]) best_idx = np.argmax(fitnesses) best_ind = population[best_idx] best_subset = tuple(np.where(best_ind)[0]) return best_subset, fitness(best_ind), best_history
def simulated_annealing(n_drugs, efficacy, toxicity, synergy, T_start=5.0, T_end=0.001, n_steps=10000, lam=LAMBDA):
current = np.random.randint(0, 2, n_drugs).astype(bool) current_score = score(np.where(current)[0], efficacy, toxicity, synergy, lam)
best = current.copy() best_sc = current_score
history = [] temp_history = []
for step in range(n_steps): T = T_start * (T_end / T_start) ** (step / n_steps)
neighbor = current.copy() idx = random.randint(0, n_drugs - 1) neighbor[idx] = not neighbor[idx]
n_score = score(np.where(neighbor)[0], efficacy, toxicity, synergy, lam) delta = n_score - current_score
if delta > 0 or random.random() < np.exp(delta / T): current = neighbor current_score = n_score
if current_score > best_sc: best = current.copy() best_sc = current_score
history.append(best_sc) temp_history.append(T)
best_subset = tuple(np.where(best)[0]) return best_subset, best_sc, history, temp_history
print("=" * 55) print(" Multi-Drug Combination Optimization") print("=" * 55)
t0 = time.time() bf_subset, bf_score, all_scores, all_subsets = brute_force(N_DRUGS, efficacy, toxicity, synergy) bf_time = time.time() - t0 print(f"\n[Brute Force]") print(f" Best subset : {[drug_names[i] for i in bf_subset]}") print(f" Score : {bf_score:.4f}") print(f" Time : {bf_time:.3f}s")
t0 = time.time() ga_subset, ga_score_val, ga_history = genetic_algorithm(N_DRUGS, efficacy, toxicity, synergy) ga_time = time.time() - t0 print(f"\n[Genetic Algorithm]") print(f" Best subset : {[drug_names[i] for i in ga_subset]}") print(f" Score : {ga_score_val:.4f}") print(f" Time : {ga_time:.3f}s")
t0 = time.time() sa_subset, sa_score_val, sa_history, temp_history = simulated_annealing(N_DRUGS, efficacy, toxicity, synergy) sa_time = time.time() - t0 print(f"\n[Simulated Annealing]") print(f" Best subset : {[drug_names[i] for i in sa_subset]}") print(f" Score : {sa_score_val:.4f}") print(f" Time : {sa_time:.3f}s")
fig = plt.figure(figsize=(20, 18)) fig.patch.set_facecolor('#0f0f1a') gs = GridSpec(3, 3, figure=fig, hspace=0.45, wspace=0.38)
COLORS = { 'bg': '#0f0f1a', 'panel': '#1a1a2e', 'accent': '#e94560', 'blue': '#0f3460', 'gold': '#f5a623', 'green': '#00d4aa', 'purple': '#9b59b6', 'text': '#e0e0e0', 'grid': '#2a2a3e', }
def style_ax(ax, title): ax.set_facecolor(COLORS['panel']) ax.tick_params(colors=COLORS['text'], labelsize=9) for spine in ax.spines.values(): spine.set_edgecolor(COLORS['grid']) ax.set_title(title, color=COLORS['gold'], fontsize=11, fontweight='bold', pad=10) ax.xaxis.label.set_color(COLORS['text']) ax.yaxis.label.set_color(COLORS['text']) ax.grid(True, color=COLORS['grid'], linewidth=0.5, alpha=0.7)
ax1 = fig.add_subplot(gs[0, 0]) style_ax(ax1, "Score Distribution\n(All 1023 Combinations)") combo_sizes = [len(s) for s in all_subsets] sc_arr = np.array(all_scores) scatter = ax1.scatter(combo_sizes, sc_arr, c=sc_arr, cmap='plasma', alpha=0.5, s=18, linewidths=0) ax1.axhline(bf_score, color=COLORS['accent'], lw=1.8, linestyle='--', label=f'Best={bf_score:.3f}') ax1.set_xlabel("Number of Drugs in Combo") ax1.set_ylabel("Composite Score") ax1.legend(fontsize=8, facecolor=COLORS['panel'], edgecolor=COLORS['grid'], labelcolor=COLORS['text']) plt.colorbar(scatter, ax=ax1, label='Score').ax.yaxis.label.set_color(COLORS['text'])
ax2 = fig.add_subplot(gs[0, 1]) style_ax(ax2, "Genetic Algorithm\nConvergence") ax2.plot(ga_history, color=COLORS['green'], lw=1.5) ax2.axhline(bf_score, color=COLORS['accent'], lw=1.5, linestyle='--', label=f'BF Optimal={bf_score:.3f}') ax2.set_xlabel("Generation") ax2.set_ylabel("Best Score") ax2.legend(fontsize=8, facecolor=COLORS['panel'], edgecolor=COLORS['grid'], labelcolor=COLORS['text'])
ax3 = fig.add_subplot(gs[0, 2]) style_ax(ax3, "Simulated Annealing\nConvergence & Temperature") steps = np.arange(len(sa_history)) ax3.plot(steps, sa_history, color=COLORS['purple'], lw=1.2, label='Best Score') ax3.axhline(bf_score, color=COLORS['accent'], lw=1.5, linestyle='--', label=f'BF Optimal={bf_score:.3f}') ax3_twin = ax3.twinx() ax3_twin.plot(steps, temp_history, color=COLORS['gold'], lw=0.8, alpha=0.5, label='Temperature') ax3_twin.set_ylabel("Temperature", color=COLORS['gold'], fontsize=9) ax3_twin.tick_params(colors=COLORS['gold'], labelsize=8) ax3.set_xlabel("Step") ax3.set_ylabel("Best Score") lines1, labels1 = ax3.get_legend_handles_labels() lines2, labels2 = ax3_twin.get_legend_handles_labels() ax3.legend(lines1+lines2, labels1+labels2, fontsize=7, facecolor=COLORS['panel'], edgecolor=COLORS['grid'], labelcolor=COLORS['text'])
ax4 = fig.add_subplot(gs[1, 0]) style_ax(ax4, "Drug Properties\n(Efficacy vs Toxicity)") x = np.arange(N_DRUGS) width = 0.38 bars_e = ax4.bar(x - width/2, efficacy, width, color=COLORS['green'], alpha=0.85, label='Efficacy') bars_t = ax4.bar(x + width/2, toxicity, width, color=COLORS['accent'], alpha=0.85, label='Toxicity') in_best = set(bf_subset) for i in range(N_DRUGS): if i in in_best: ax4.annotate('★', (i, max(efficacy[i], toxicity[i]) + 0.04), ha='center', color=COLORS['gold'], fontsize=12) ax4.set_xticks(x) ax4.set_xticklabels([f'{d[-1]}' for d in drug_names], fontsize=8) ax4.set_xlabel("Drug") ax4.set_ylabel("Score (0–1)") ax4.legend(fontsize=8, facecolor=COLORS['panel'], edgecolor=COLORS['grid'], labelcolor=COLORS['text'])
ax5 = fig.add_subplot(gs[1, 1]) style_ax(ax5, "Drug-Drug Synergy Matrix") im = ax5.imshow(synergy, cmap='RdYlGn', vmin=-0.5, vmax=0.5, aspect='auto') ax5.set_xticks(range(N_DRUGS)) ax5.set_yticks(range(N_DRUGS)) labels_short = [d[-1] for d in drug_names] ax5.set_xticklabels(labels_short, fontsize=8) ax5.set_yticklabels(labels_short, fontsize=8) plt.colorbar(im, ax=ax5, label='Synergy').ax.yaxis.label.set_color(COLORS['text'])
for i in bf_subset: for j in bf_subset: rect = plt.Rectangle((j-0.5, i-0.5), 1, 1, fill=False, edgecolor=COLORS['gold'], lw=2) ax5.add_patch(rect)
ax6 = fig.add_subplot(gs[1, 2]) style_ax(ax6, "Score by Combination Size\n(Box Plot)") size_scores = {} for s, sc in zip(all_subsets, all_scores): k = len(s) size_scores.setdefault(k, []).append(sc) keys = sorted(size_scores.keys()) data_bp = [size_scores[k] for k in keys] bp = ax6.boxplot(data_bp, patch_artist=True, medianprops=dict(color=COLORS['gold'], lw=2), whiskerprops=dict(color=COLORS['text']), capprops=dict(color=COLORS['text']), flierprops=dict(markerfacecolor=COLORS['accent'], marker='o', markersize=3)) for patch in bp['boxes']: patch.set_facecolor(COLORS['blue']) patch.set_alpha(0.8) ax6.set_xlabel("Number of Drugs") ax6.set_ylabel("Composite Score") ax6.set_xticks(range(1, len(keys)+1)) ax6.set_xticklabels(keys, fontsize=9)
ax7 = fig.add_subplot(gs[2, 0], projection='3d') ax7.set_facecolor(COLORS['panel']) ax7.set_title("3D Drug Space\n(Efficacy / Toxicity / Net Synergy)", color=COLORS['gold'], fontsize=10, fontweight='bold', pad=10)
net_synergy = np.array([synergy[i].sum() for i in range(N_DRUGS)]) colors_3d = [COLORS['gold'] if i in set(bf_subset) else COLORS['blue'] for i in range(N_DRUGS)] sizes_3d = [180 if i in set(bf_subset) else 60 for i in range(N_DRUGS)]
ax7.scatter(efficacy, toxicity, net_synergy, c=colors_3d, s=sizes_3d, alpha=0.9, edgecolors='white', lw=0.5) for i in range(N_DRUGS): ax7.text(efficacy[i], toxicity[i], net_synergy[i]+0.01, drug_names[i][-1], color=COLORS['text'], fontsize=7, ha='center')
ax7.set_xlabel("Efficacy", color=COLORS['text'], fontsize=8) ax7.set_ylabel("Toxicity", color=COLORS['text'], fontsize=8) ax7.set_zlabel("Net Synergy", color=COLORS['text'], fontsize=8) ax7.tick_params(colors=COLORS['text'], labelsize=7) ax7.xaxis.pane.fill = False ax7.yaxis.pane.fill = False ax7.zaxis.pane.fill = False legend_patches = [ mpatches.Patch(color=COLORS['gold'], label='In Best Combo'), mpatches.Patch(color=COLORS['blue'], label='Not Selected'), ] ax7.legend(handles=legend_patches, fontsize=7, facecolor=COLORS['panel'], edgecolor=COLORS['grid'], labelcolor=COLORS['text'])
ax8 = fig.add_subplot(gs[2, 1], projection='3d') ax8.set_facecolor(COLORS['panel']) ax8.set_title("3D Score Landscape\n(Size / Synergy Sum / Score)", color=COLORS['gold'], fontsize=10, fontweight='bold', pad=10)
combo_size_arr = np.array([len(s) for s in all_subsets]) syn_contrib_arr = np.array([ sum(synergy[s[i], s[j]] for i in range(len(s)) for j in range(i+1, len(s))) for s in all_subsets ]) sc_arr2 = np.array(all_scores)
sc_norm = (sc_arr2 - sc_arr2.min()) / (sc_arr2.max() - sc_arr2.min() + 1e-9) ax8.scatter(combo_size_arr, syn_contrib_arr, sc_arr2, c=sc_norm, cmap='plasma', s=8, alpha=0.4) ax8.scatter([len(bf_subset)], [sum(synergy[bf_subset[i], bf_subset[j]] for i in range(len(bf_subset)) for j in range(i+1, len(bf_subset)))], [bf_score], color=COLORS['accent'], s=200, marker='*', label='Global Best', zorder=5)
ax8.set_xlabel("# Drugs", color=COLORS['text'], fontsize=8) ax8.set_ylabel("Synergy Sum", color=COLORS['text'], fontsize=8) ax8.set_zlabel("Score", color=COLORS['text'], fontsize=8) ax8.tick_params(colors=COLORS['text'], labelsize=7) ax8.xaxis.pane.fill = False ax8.yaxis.pane.fill = False ax8.zaxis.pane.fill = False ax8.legend(fontsize=7, facecolor=COLORS['panel'], edgecolor=COLORS['grid'], labelcolor=COLORS['text'])
ax9 = fig.add_subplot(gs[2, 2]) style_ax(ax9, "Method Comparison\n(Score & Runtime)") methods = ['Brute\nForce', 'Genetic\nAlgorithm', 'Simulated\nAnnealing'] scores_cmp = [bf_score, ga_score_val, sa_score_val] times_cmp = [bf_time, ga_time, sa_time] colors_cmp = [COLORS['green'], COLORS['purple'], COLORS['blue']] x_pos = np.arange(len(methods))
bars = ax9.bar(x_pos, scores_cmp, color=colors_cmp, alpha=0.85, width=0.5) for bar, sc in zip(bars, scores_cmp): ax9.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.005, f'{sc:.4f}', ha='center', color=COLORS['text'], fontsize=9, fontweight='bold')
ax9_twin = ax9.twinx() ax9_twin.plot(x_pos, times_cmp, color=COLORS['gold'], marker='D', markersize=8, lw=2, label='Time (s)') for xi, ti in zip(x_pos, times_cmp): ax9_twin.text(xi, ti + 0.002, f'{ti:.3f}s', ha='center', color=COLORS['gold'], fontsize=8) ax9_twin.set_ylabel("Runtime (s)", color=COLORS['gold'], fontsize=9) ax9_twin.tick_params(colors=COLORS['gold'], labelsize=8)
ax9.set_xticks(x_pos) ax9.set_xticklabels(methods, fontsize=9) ax9.set_ylabel("Composite Score") ax9.set_ylim(0, max(scores_cmp) * 1.18) ax9_twin.set_ylim(0, max(times_cmp) * 2.5)
fig.suptitle("Multi-Drug Combination Therapy Optimization", fontsize=16, fontweight='bold', color=COLORS['gold'], y=0.98)
plt.savefig("multi_drug_optimization.png", dpi=150, bbox_inches='tight', facecolor=fig.get_facecolor()) plt.show() print("\nVisualization complete.")
|