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
| import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats import pandas as pd from typing import List, Tuple import math
plt.style.use('seaborn-v0_8') sns.set_palette("husl")
class MateSelectionOptimizer: """ A class to simulate and optimize mate selection strategies using the Secretary Problem framework applied to evolutionary biology. """ def __init__(self, population_size: int = 100): """ Initialize the optimizer with a given population size. Parameters: ----------- population_size : int Total number of potential mates in the population """ self.population_size = population_size self.optimal_threshold = int(population_size / math.e) def generate_population(self, distribution: str = 'normal') -> np.ndarray: """ Generate a population with genetic fitness scores. Parameters: ----------- distribution : str Distribution type for fitness scores ('normal', 'exponential', 'uniform') Returns: -------- np.ndarray : Array of fitness scores """ np.random.seed(42) if distribution == 'normal': fitness_scores = np.random.normal(50, 15, self.population_size) elif distribution == 'exponential': fitness_scores = np.random.exponential(30, self.population_size) elif distribution == 'uniform': fitness_scores = np.random.uniform(0, 100, self.population_size) else: raise ValueError("Distribution must be 'normal', 'exponential', or 'uniform'") return np.maximum(fitness_scores, 0) def simulate_random_strategy(self, fitness_scores: np.ndarray, num_simulations: int = 1000) -> List[float]: """ Simulate random mate selection strategy. Parameters: ----------- fitness_scores : np.ndarray Population fitness scores num_simulations : int Number of simulation runs Returns: -------- List[float] : Selected fitness scores from each simulation """ selected_scores = [] for _ in range(num_simulations): shuffled_scores = np.random.permutation(fitness_scores) stop_position = np.random.randint(1, len(shuffled_scores) + 1) selected_scores.append(shuffled_scores[stop_position - 1]) return selected_scores def simulate_optimal_strategy(self, fitness_scores: np.ndarray, num_simulations: int = 1000) -> List[float]: """ Simulate optimal mate selection strategy (Secretary Problem solution). Parameters: ----------- fitness_scores : np.ndarray Population fitness scores num_simulations : int Number of simulation runs Returns: -------- List[float] : Selected fitness scores from each simulation """ selected_scores = [] for _ in range(num_simulations): shuffled_scores = np.random.permutation(fitness_scores) observation_phase = shuffled_scores[:self.optimal_threshold] if len(observation_phase) == 0: selected_scores.append(shuffled_scores[0]) continue observation_max = np.max(observation_phase) selected = None for i in range(self.optimal_threshold, len(shuffled_scores)): if shuffled_scores[i] > observation_max: selected = shuffled_scores[i] break if selected is None: selected = shuffled_scores[-1] selected_scores.append(selected) return selected_scores def simulate_threshold_strategy(self, fitness_scores: np.ndarray, threshold_percentile: float = 80, num_simulations: int = 1000) -> List[float]: """ Simulate threshold-based strategy (accept first candidate above percentile). Parameters: ----------- fitness_scores : np.ndarray Population fitness scores threshold_percentile : float Percentile threshold (0-100) num_simulations : int Number of simulation runs Returns: -------- List[float] : Selected fitness scores from each simulation """ selected_scores = [] threshold_value = np.percentile(fitness_scores, threshold_percentile) for _ in range(num_simulations): shuffled_scores = np.random.permutation(fitness_scores) selected = None for score in shuffled_scores: if score >= threshold_value: selected = score break if selected is None: selected = shuffled_scores[-1] selected_scores.append(selected) return selected_scores def calculate_success_probability(self, selected_scores: List[float], true_maximum: float) -> float: """ Calculate the probability of selecting the true best mate. Parameters: ----------- selected_scores : List[float] Scores selected by the strategy true_maximum : float True maximum fitness in the population Returns: -------- float : Success probability """ successes = sum(1 for score in selected_scores if abs(score - true_maximum) < 1e-10) return successes / len(selected_scores)
optimizer = MateSelectionOptimizer(population_size=100)
population_fitness = optimizer.generate_population('normal') true_best_fitness = np.max(population_fitness)
print(f"Population size: {len(population_fitness)}") print(f"Optimal observation threshold: {optimizer.optimal_threshold}") print(f"True best fitness score: {true_best_fitness:.2f}") print(f"Population mean fitness: {np.mean(population_fitness):.2f}") print(f"Population std fitness: {np.std(population_fitness):.2f}")
num_sims = 10000
print("\n" + "="*50) print("Running simulations...") print("="*50)
random_results = optimizer.simulate_random_strategy(population_fitness, num_sims) random_success_prob = optimizer.calculate_success_probability(random_results, true_best_fitness)
optimal_results = optimizer.simulate_optimal_strategy(population_fitness, num_sims) optimal_success_prob = optimizer.calculate_success_probability(optimal_results, true_best_fitness)
threshold_70_results = optimizer.simulate_threshold_strategy(population_fitness, 70, num_sims) threshold_70_success = optimizer.calculate_success_probability(threshold_70_results, true_best_fitness)
threshold_80_results = optimizer.simulate_threshold_strategy(population_fitness, 80, num_sims) threshold_80_success = optimizer.calculate_success_probability(threshold_80_results, true_best_fitness)
threshold_90_results = optimizer.simulate_threshold_strategy(population_fitness, 90, num_sims) threshold_90_success = optimizer.calculate_success_probability(threshold_90_results, true_best_fitness)
print(f"\nRandom Strategy:") print(f" Average selected fitness: {np.mean(random_results):.2f}") print(f" Success probability: {random_success_prob:.4f}")
print(f"\nOptimal Strategy (Secretary Problem):") print(f" Average selected fitness: {np.mean(optimal_results):.2f}") print(f" Success probability: {optimal_success_prob:.4f}") print(f" Theoretical success probability: {1/math.e:.4f}")
print(f"\nThreshold Strategy (70th percentile):") print(f" Average selected fitness: {np.mean(threshold_70_results):.2f}") print(f" Success probability: {threshold_70_success:.4f}")
print(f"\nThreshold Strategy (80th percentile):") print(f" Average selected fitness: {np.mean(threshold_80_results):.2f}") print(f" Success probability: {threshold_80_success:.4f}")
print(f"\nThreshold Strategy (90th percentile):") print(f" Average selected fitness: {np.mean(threshold_90_results):.2f}") print(f" Success probability: {threshold_90_success:.4f}")
fig, axes = plt.subplots(2, 3, figsize=(18, 12)) fig.suptitle('Mate Selection Optimization: Comparison of Strategies', fontsize=16, fontweight='bold')
axes[0, 0].hist(population_fitness, bins=30, alpha=0.7, color='skyblue', edgecolor='black') axes[0, 0].axvline(true_best_fitness, color='red', linestyle='--', linewidth=2, label=f'True Best: {true_best_fitness:.1f}') axes[0, 0].axvline(np.mean(population_fitness), color='green', linestyle='--', linewidth=2, label=f'Mean: {np.mean(population_fitness):.1f}') axes[0, 0].set_title('Population Fitness Distribution') axes[0, 0].set_xlabel('Fitness Score') axes[0, 0].set_ylabel('Frequency') axes[0, 0].legend() axes[0, 0].grid(True, alpha=0.3)
strategies = ['Random', 'Optimal\n(Secretary)', 'Threshold\n(70%)', 'Threshold\n(80%)', 'Threshold\n(90%)'] avg_scores = [np.mean(random_results), np.mean(optimal_results), np.mean(threshold_70_results), np.mean(threshold_80_results), np.mean(threshold_90_results)] colors = ['gray', 'gold', 'lightcoral', 'lightgreen', 'lightblue']
bars = axes[0, 1].bar(strategies, avg_scores, color=colors, edgecolor='black', linewidth=1) axes[0, 1].axhline(true_best_fitness, color='red', linestyle='--', linewidth=2, label=f'True Best: {true_best_fitness:.1f}') axes[0, 1].axhline(np.mean(population_fitness), color='green', linestyle='--', linewidth=2, label=f'Population Mean: {np.mean(population_fitness):.1f}') axes[0, 1].set_title('Average Selected Fitness by Strategy') axes[0, 1].set_ylabel('Average Fitness Score') axes[0, 1].legend() axes[0, 1].grid(True, alpha=0.3)
for i, (bar, score) in enumerate(zip(bars, avg_scores)): axes[0, 1].text(bar.get_x() + bar.get_width()/2, bar.get_height() + 1, f'{score:.1f}', ha='center', va='bottom', fontweight='bold')
success_probs = [random_success_prob, optimal_success_prob, threshold_70_success, threshold_80_success, threshold_90_success]
bars2 = axes[0, 2].bar(strategies, success_probs, color=colors, edgecolor='black', linewidth=1) axes[0, 2].axhline(1/math.e, color='red', linestyle='--', linewidth=2, label=f'Theoretical Optimal: {1/math.e:.3f}') axes[0, 2].set_title('Probability of Selecting the Best Mate') axes[0, 2].set_ylabel('Success Probability') axes[0, 2].set_ylim(0, max(success_probs) * 1.2) axes[0, 2].legend() axes[0, 2].grid(True, alpha=0.3)
for i, (bar, prob) in enumerate(zip(bars2, success_probs)): axes[0, 2].text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.005, f'{prob:.3f}', ha='center', va='bottom', fontweight='bold')
data_for_plot = [random_results, optimal_results, threshold_80_results] labels_for_plot = ['Random', 'Optimal (Secretary)', 'Threshold (80%)'] colors_for_plot = ['gray', 'gold', 'lightgreen']
for i, (data, label, color) in enumerate(zip(data_for_plot, labels_for_plot, colors_for_plot)): axes[1, 0].hist(data, bins=30, alpha=0.6, label=label, color=color, density=True)
axes[1, 0].axvline(true_best_fitness, color='red', linestyle='--', linewidth=2, label=f'True Best: {true_best_fitness:.1f}') axes[1, 0].set_title('Distribution of Selected Fitness Scores') axes[1, 0].set_xlabel('Selected Fitness Score') axes[1, 0].set_ylabel('Density') axes[1, 0].legend() axes[1, 0].grid(True, alpha=0.3)
box_data = [random_results, optimal_results, threshold_70_results, threshold_80_results, threshold_90_results] bp = axes[1, 1].boxplot(box_data, labels=strategies, patch_artist=True)
for patch, color in zip(bp['boxes'], colors): patch.set_facecolor(color) patch.set_alpha(0.7)
axes[1, 1].axhline(true_best_fitness, color='red', linestyle='--', linewidth=2, label=f'True Best: {true_best_fitness:.1f}') axes[1, 1].set_title('Distribution Comparison (Box Plots)') axes[1, 1].set_ylabel('Selected Fitness Score') axes[1, 1].legend() axes[1, 1].grid(True, alpha=0.3)
population_sizes = range(10, 201, 10) optimal_performance = [] random_performance = []
for pop_size in population_sizes: temp_optimizer = MateSelectionOptimizer(pop_size) temp_population = temp_optimizer.generate_population('normal') temp_true_best = np.max(temp_population) temp_optimal = temp_optimizer.simulate_optimal_strategy(temp_population, 1000) temp_random = temp_optimizer.simulate_random_strategy(temp_population, 1000) optimal_performance.append(np.mean(temp_optimal)) random_performance.append(np.mean(temp_random))
axes[1, 2].plot(population_sizes, optimal_performance, 'o-', color='gold', linewidth=2, markersize=4, label='Optimal Strategy') axes[1, 2].plot(population_sizes, random_performance, 's-', color='gray', linewidth=2, markersize=4, label='Random Strategy') axes[1, 2].set_title('Strategy Performance vs Population Size') axes[1, 2].set_xlabel('Population Size') axes[1, 2].set_ylabel('Average Selected Fitness') axes[1, 2].legend() axes[1, 2].grid(True, alpha=0.3)
plt.tight_layout() plt.show()
print("\n" + "="*60) print("ANALYSIS: Effect of Different Observation Thresholds") print("="*60)
thresholds = range(1, min(50, optimizer.population_size), 2) threshold_performance = []
for threshold in thresholds: original_threshold = optimizer.optimal_threshold optimizer.optimal_threshold = threshold temp_results = optimizer.simulate_optimal_strategy(population_fitness, 2000) temp_success = optimizer.calculate_success_probability(temp_results, true_best_fitness) threshold_performance.append(temp_success) optimizer.optimal_threshold = original_threshold
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1) plt.plot(thresholds, threshold_performance, 'o-', color='blue', linewidth=2, markersize=6) plt.axvline(optimizer.population_size / math.e, color='red', linestyle='--', linewidth=2, label=f'Theoretical Optimal: {optimizer.population_size / math.e:.1f}') plt.axhline(1/math.e, color='red', linestyle=':', linewidth=2, label=f'Theoretical Success Rate: {1/math.e:.3f}') plt.title('Success Rate vs Observation Threshold') plt.xlabel('Observation Threshold (Number of Candidates)') plt.ylabel('Success Probability') plt.legend() plt.grid(True, alpha=0.3)
plt.subplot(1, 2, 2) x = np.linspace(0.1, 0.9, 100) y = -x * np.log(x)
plt.plot(x, y, 'purple', linewidth=3) plt.axvline(1/math.e, color='red', linestyle='--', linewidth=2, label=f'Optimal r = 1/e ≈ {1/math.e:.3f}') plt.axhline(1/math.e, color='red', linestyle=':', linewidth=2, label=f'Maximum Success Rate ≈ {1/math.e:.3f}') plt.title('Theoretical Success Probability Function\n' + r'$P(r) = -r \ln(r)$') plt.xlabel('Observation Ratio (r = threshold/population)') plt.ylabel('Success Probability') plt.legend() plt.grid(True, alpha=0.3)
plt.tight_layout() plt.show()
print(f"\nSUMMARY STATISTICS:") print(f"="*40) print(f"Population Statistics:") print(f" Size: {len(population_fitness)}") print(f" Mean: {np.mean(population_fitness):.2f}") print(f" Std Dev: {np.std(population_fitness):.2f}") print(f" Best Individual: {true_best_fitness:.2f}") print(f" 95th Percentile: {np.percentile(population_fitness, 95):.2f}")
print(f"\nStrategy Effectiveness Ranking:") strategy_results = [ ("Random", np.mean(random_results), random_success_prob), ("Optimal (Secretary)", np.mean(optimal_results), optimal_success_prob), ("Threshold (70%)", np.mean(threshold_70_results), threshold_70_success), ("Threshold (80%)", np.mean(threshold_80_results), threshold_80_success), ("Threshold (90%)", np.mean(threshold_90_results), threshold_90_success) ]
strategy_results.sort(key=lambda x: x[2], reverse=True)
for i, (strategy, avg_score, success_rate) in enumerate(strategy_results, 1): print(f" {i}. {strategy:20s} | Avg Score: {avg_score:6.2f} | Success Rate: {success_rate:.4f}")
print(f"\nKey Insights:") print(f" • The optimal strategy achieves {optimal_success_prob:.1%} success rate") print(f" • This is {optimal_success_prob/random_success_prob:.1f}x better than random selection") print(f" • High threshold strategies risk missing good candidates entirely") print(f" • The theoretical maximum success rate is {1/math.e:.1%}")
|