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
| import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.stats import chi2_contingency import seaborn as sns
np.random.seed(42)
def simulate_cross(genotype1, genotype2, num_offspring=1000): """ Simulate a genetic cross between two genotypes. Parameters: genotype1, genotype2: Strings representing parental genotypes (e.g., 'Aa', 'BB') num_offspring: Number of offspring to simulate Returns: Dictionary with genotype counts and phenotype counts """ alleles1 = [genotype1[0], genotype1[1]] alleles2 = [genotype2[0], genotype2[1]] gametes1 = np.random.choice(alleles1, size=num_offspring) gametes2 = np.random.choice(alleles2, size=num_offspring) offspring_genotypes = np.array([g1 + g2 for g1, g2 in zip(gametes1, gametes2)]) unique_genotypes, genotype_counts = np.unique(offspring_genotypes, return_counts=True) genotype_freqs = {gt: count/num_offspring for gt, count in zip(unique_genotypes, genotype_counts)} phenotypes = [] for gt in offspring_genotypes: if gt[0].isupper() or gt[1].isupper(): phenotypes.append("Dominant") else: phenotypes.append("Recessive") unique_phenotypes, phenotype_counts = np.unique(phenotypes, return_counts=True) phenotype_freqs = {pt: count/num_offspring for pt, count in zip(unique_phenotypes, phenotype_counts)} return { "genotype_counts": {gt: count for gt, count in zip(unique_genotypes, genotype_counts)}, "genotype_freqs": genotype_freqs, "phenotype_counts": {pt: count for pt, count in zip(unique_phenotypes, phenotype_counts)}, "phenotype_freqs": phenotype_freqs, "raw_genotypes": offspring_genotypes, "raw_phenotypes": phenotypes }
print("Simulating monohybrid cross: Aa × Aa") monohybrid_results = simulate_cross("Aa", "Aa", 1000)
print("\nGenotype counts:") for genotype, count in monohybrid_results["genotype_counts"].items(): print(f"{genotype}: {count} ({count/10:.1f}%)")
print("\nPhenotype counts:") for phenotype, count in monohybrid_results["phenotype_counts"].items(): print(f"{phenotype}: {count} ({count/10:.1f}%)")
expected_genotype_ratio = {"AA": 0.25, "Aa": 0.5, "aA": 0, "aa": 0.25}
if "Aa" in monohybrid_results["genotype_counts"] and "aA" in monohybrid_results["genotype_counts"]: expected_genotype_ratio["Aa"] = 0.5 elif "aA" in monohybrid_results["genotype_counts"]: expected_genotype_ratio["aA"] = 0.5
observed = [] expected = [] for genotype in monohybrid_results["genotype_counts"]: if genotype in expected_genotype_ratio: observed.append(monohybrid_results["genotype_counts"][genotype]) expected.append(expected_genotype_ratio[genotype] * 1000)
chi2, p, dof, ex = chi2_contingency([observed, expected]) print(f"\nChi-square test p-value: {p:.4f}") if p > 0.05: print("The observed results are consistent with Mendelian inheritance.") else: print("The observed results differ significantly from Mendelian inheritance.")
def simulate_dihybrid_cross(genotype1, genotype2, num_offspring=1000): """Simulate a dihybrid cross between two genotypes""" gene1_p1, gene2_p1 = genotype1[:2], genotype1[2:] gene1_p2, gene2_p2 = genotype2[:2], genotype2[2:] gene1_results = simulate_cross(gene1_p1, gene1_p2, num_offspring) gene2_results = simulate_cross(gene2_p1, gene2_p2, num_offspring) dihybrid_genotypes = np.array([g1 + g2 for g1, g2 in zip(gene1_results["raw_genotypes"], gene2_results["raw_genotypes"])]) unique_genotypes, genotype_counts = np.unique(dihybrid_genotypes, return_counts=True) genotype_freqs = {gt: count/num_offspring for gt, count in zip(unique_genotypes, genotype_counts)} phenotypes = [] for gt in dihybrid_genotypes: p1 = "A_dominant" if (gt[0].isupper() or gt[1].isupper()) else "a_recessive" p2 = "B_dominant" if (gt[2].isupper() or gt[3].isupper()) else "b_recessive" phenotypes.append(f"{p1}_{p2}") unique_phenotypes, phenotype_counts = np.unique(phenotypes, return_counts=True) phenotype_freqs = {pt: count/num_offspring for pt, count in zip(unique_phenotypes, phenotype_counts)} simplified_phenotypes = [] for p in phenotypes: if p == "A_dominant_B_dominant": simplified_phenotypes.append("A-B") elif p == "A_dominant_b_recessive": simplified_phenotypes.append("A-b") elif p == "a_recessive_B_dominant": simplified_phenotypes.append("a-B") elif p == "a_recessive_b_recessive": simplified_phenotypes.append("a-b") unique_simple_phenotypes, simple_phenotype_counts = np.unique(simplified_phenotypes, return_counts=True) simple_phenotype_freqs = {pt: count/num_offspring for pt, count in zip(unique_simple_phenotypes, simple_phenotype_counts)} return { "genotype_counts": {gt: count for gt, count in zip(unique_genotypes, genotype_counts)}, "genotype_freqs": genotype_freqs, "phenotype_counts": {pt: count for pt, count in zip(unique_phenotypes, phenotype_counts)}, "phenotype_freqs": phenotype_freqs, "simplified_phenotype_counts": {pt: count for pt, count in zip(unique_simple_phenotypes, simple_phenotype_counts)}, "simplified_phenotype_freqs": simple_phenotype_freqs }
print("\n\nSimulating dihybrid cross: AaBb × AaBb") dihybrid_results = simulate_dihybrid_cross("AaBb", "AaBb", 1000)
plt.figure(figsize=(14, 10))
plt.subplot(2, 2, 1) genotypes = list(monohybrid_results["genotype_counts"].keys()) counts = list(monohybrid_results["genotype_counts"].values()) plt.bar(genotypes, counts, color='skyblue') plt.title('Monohybrid Cross (Aa × Aa)\nGenotype Frequencies') plt.ylabel('Count') for i, v in enumerate(counts): plt.text(i, v + 5, f"{v}", ha='center')
plt.subplot(2, 2, 2) phenotypes = list(monohybrid_results["phenotype_counts"].keys()) counts = list(monohybrid_results["phenotype_counts"].values()) plt.bar(phenotypes, counts, color='lightgreen') plt.title('Monohybrid Cross (Aa × Aa)\nPhenotype Frequencies') plt.ylabel('Count') for i, v in enumerate(counts): plt.text(i, v + 5, f"{v} ({v/10:.1f}%)", ha='center')
plt.subplot(2, 2, 3) labels = list(dihybrid_results["simplified_phenotype_counts"].keys()) sizes = list(dihybrid_results["simplified_phenotype_counts"].values()) explode = (0.1, 0, 0, 0) colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99'] plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90) plt.axis('equal') plt.title('Dihybrid Cross (AaBb × AaBb)\nPhenotype Ratio')
plt.subplot(2, 2, 4) phenotypes = list(dihybrid_results["simplified_phenotype_counts"].keys()) observed = list(dihybrid_results["simplified_phenotype_counts"].values())
expected = [9/16*1000, 3/16*1000, 3/16*1000, 1/16*1000]
expected_labels = [f"{phenotypes[i]}\n(Exp: {expected[i]:.1f})" for i in range(len(phenotypes))]
x = np.arange(len(phenotypes)) width = 0.35
plt.bar(x - width/2, observed, width, label='Observed', color='royalblue') plt.bar(x + width/2, expected, width, label='Expected (9:3:3:1)', color='lightcoral') plt.title('Dihybrid Cross: Observed vs Expected') plt.xticks(x, expected_labels, rotation=45, ha='right') plt.ylabel('Count') plt.legend()
plt.tight_layout() plt.savefig('genetic_crosses.png', dpi=300) plt.show()
def simulate_linkage(recombination_rate, num_offspring=1000): """ Simulate genetic linkage between two genes with a given recombination rate. Parameters: recombination_rate: Probability of recombination between loci (0-0.5) num_offspring: Number of offspring to simulate Returns: Dictionary with gamete types and their frequencies """ recombination = np.random.random(num_offspring) < recombination_rate gametes = [] for r in recombination: if r: if np.random.random() < 0.5: gametes.append("Ab") else: gametes.append("aB") else: if np.random.random() < 0.5: gametes.append("AB") else: gametes.append("ab") unique_gametes, gamete_counts = np.unique(gametes, return_counts=True) gamete_freqs = {gt: count/num_offspring for gt, count in zip(unique_gametes, gamete_counts)} return { "gamete_counts": {gt: count for gt, count in zip(unique_gametes, gamete_counts)}, "gamete_freqs": gamete_freqs, "raw_gametes": gametes }
recom_rates = [0.01, 0.1, 0.2, 0.3, 0.4, 0.5] linkage_results = []
for rate in recom_rates: result = simulate_linkage(rate, 1000) linkage_results.append(result)
plt.figure(figsize=(14, 6))
plt.subplot(1, 2, 1) parental_freqs = [] recombinant_freqs = []
for i, rate in enumerate(recom_rates): result = linkage_results[i] parental = sum([result["gamete_counts"].get("AB", 0), result["gamete_counts"].get("ab", 0)]) / 1000 recombinant = sum([result["gamete_counts"].get("Ab", 0), result["gamete_counts"].get("aB", 0)]) / 1000 parental_freqs.append(parental) recombinant_freqs.append(recombinant)
plt.plot(recom_rates, parental_freqs, 'o-', label='Parental Gametes (AB, ab)') plt.plot(recom_rates, recombinant_freqs, 's-', label='Recombinant Gametes (Ab, aB)') plt.axhline(y=0.5, color='gray', linestyle='--', alpha=0.5) plt.title('Effect of Recombination Rate on Gamete Frequencies') plt.xlabel('Recombination Rate') plt.ylabel('Frequency') plt.xticks(recom_rates) plt.ylim(0, 1) plt.legend() plt.grid(alpha=0.3)
plt.subplot(1, 2, 2) gamete_types = ["AB", "ab", "Ab", "aB"] data = []
for i, rate in enumerate(recom_rates): result = linkage_results[i] row = [result["gamete_counts"].get(gt, 0)/1000 for gt in gamete_types] data.append(row)
df = pd.DataFrame(data, columns=gamete_types, index=[f"{rate*100:.0f}%" for rate in recom_rates]) sns.heatmap(df, annot=True, cmap="YlGnBu", fmt=".2f", cbar_kws={'label': 'Frequency'}) plt.title('Gamete Frequencies at Different Recombination Rates') plt.xlabel('Gamete Type') plt.ylabel('Recombination Rate')
plt.tight_layout() plt.savefig('genetic_linkage.png', dpi=300) plt.show()
def simulate_hardy_weinberg(p_initial, num_generations=10, population_size=1000, selection_coefficient=0): """ Simulate Hardy-Weinberg equilibrium over generations. Parameters: p_initial: Initial frequency of dominant allele A num_generations: Number of generations to simulate population_size: Size of the population in each generation selection_coefficient: Selection against the recessive homozygote (aa) Returns: Dictionary with allele and genotype frequencies over generations """ q_initial = 1 - p_initial p_values = [p_initial] q_values = [q_initial] AA_freqs = [p_initial**2] Aa_freqs = [2 * p_initial * q_initial] aa_freqs = [q_initial**2] p = p_initial q = q_initial for gen in range(1, num_generations): AA_freq = p**2 Aa_freq = 2 * p * q aa_freq = q**2 if selection_coefficient > 0: w_AA = 1 w_Aa = 1 w_aa = 1 - selection_coefficient w_bar = w_AA * AA_freq + w_Aa * Aa_freq + w_aa * aa_freq AA_freq = (w_AA * AA_freq) / w_bar Aa_freq = (w_Aa * Aa_freq) / w_bar aa_freq = (w_aa * aa_freq) / w_bar p = AA_freq + (Aa_freq / 2) q = aa_freq + (Aa_freq / 2) genotype_counts = np.random.multinomial(population_size, [AA_freq, Aa_freq, aa_freq]) AA_count, Aa_count, aa_count = genotype_counts AA_freq = AA_count / population_size Aa_freq = Aa_count / population_size aa_freq = aa_count / population_size p = AA_freq + (Aa_freq / 2) q = aa_freq + (Aa_freq / 2) p_values.append(p) q_values.append(q) AA_freqs.append(AA_freq) Aa_freqs.append(Aa_freq) aa_freqs.append(aa_freq) return { "p_values": p_values, "q_values": q_values, "AA_freqs": AA_freqs, "Aa_freqs": Aa_freqs, "aa_freqs": aa_freqs }
hw_results_no_selection = simulate_hardy_weinberg(0.3, num_generations=20, population_size=1000, selection_coefficient=0) hw_results_with_selection = simulate_hardy_weinberg(0.3, num_generations=20, population_size=1000, selection_coefficient=0.2)
plt.figure(figsize=(14, 10))
plt.subplot(2, 2, 1) generations = range(len(hw_results_no_selection["p_values"])) plt.plot(generations, hw_results_no_selection["p_values"], 'b-', label='p (A allele)') plt.plot(generations, hw_results_no_selection["q_values"], 'r-', label='q (a allele)') plt.title('Allele Frequencies Over Generations\n(No Selection)') plt.xlabel('Generation') plt.ylabel('Frequency') plt.legend() plt.grid(alpha=0.3)
plt.subplot(2, 2, 2) plt.plot(generations, hw_results_no_selection["AA_freqs"], 'g-', label='AA') plt.plot(generations, hw_results_no_selection["Aa_freqs"], 'b-', label='Aa') plt.plot(generations, hw_results_no_selection["aa_freqs"], 'r-', label='aa') plt.title('Genotype Frequencies Over Generations\n(No Selection)') plt.xlabel('Generation') plt.ylabel('Frequency') plt.legend() plt.grid(alpha=0.3)
plt.subplot(2, 2, 3) plt.plot(generations, hw_results_with_selection["p_values"], 'b-', label='p (A allele)') plt.plot(generations, hw_results_with_selection["q_values"], 'r-', label='q (a allele)') plt.title('Allele Frequencies Over Generations\n(Selection Against aa, s=0.2)') plt.xlabel('Generation') plt.ylabel('Frequency') plt.legend() plt.grid(alpha=0.3)
plt.subplot(2, 2, 4) plt.plot(generations, hw_results_with_selection["AA_freqs"], 'g-', label='AA') plt.plot(generations, hw_results_with_selection["Aa_freqs"], 'b-', label='Aa') plt.plot(generations, hw_results_with_selection["aa_freqs"], 'r-', label='aa') plt.title('Genotype Frequencies Over Generations\n(Selection Against aa, s=0.2)') plt.xlabel('Generation') plt.ylabel('Frequency') plt.legend() plt.grid(alpha=0.3)
plt.tight_layout() plt.savefig('hardy_weinberg.png', dpi=300) plt.show()
|