{
  "filename": "plot_2.png",
  "iteration": 2,
  "description": "SERPINA6 population genetics from gnomAD v4: summed pLoF frequency, carrier and biallelic prevalence estimates, named missense variants, and constraint visualisation",
  "timestamp": "2026-11-28 09:01:38",
  "code": "\nimport requests, json\nimport numpy as np, matplotlib.pyplot as plt\n\nGQL = \"https://gnomad.broadinstitute.org/api\"\nq = \"\"\"query G($gid: String!) { gene(gene_id: $gid, reference_genome: GRCh38) {\n  gnomad_constraint { pLI oe_lof oe_lof_lower oe_lof_upper oe_mis oe_mis_lower oe_mis_upper\n                      exp_lof obs_lof exp_mis obs_mis lof_z mis_z }\n  variants(dataset: gnomad_r4) { variant_id rsids consequence hgvsp\n      genome { ac an af homozygote_count } exome { ac an af homozygote_count } } } }\"\"\"\ng = requests.post(GQL, json={\"query\": q, \"variables\": {\"gid\": \"ENSG00000170099\"}},\n                  headers={\"Content-Type\": \"application/json\"}, timeout=120).json()[\"data\"][\"gene\"]\nvs, con = g[\"variants\"], g[\"gnomad_constraint\"]\n\nLOF = {\"frameshift_variant\",\"stop_gained\",\"splice_acceptor_variant\",\n       \"splice_donor_variant\",\"start_lost\",\"stop_lost\"}\ndef afreq(v):\n    a = c = 0\n    for s in (\"exome\",\"genome\"):\n        d = v.get(s)\n        if d: a += d.get(\"ac\") or 0; c += d.get(\"an\") or 0\n    return a, c, (a/c if c else 0.0)\n\nlofs = [v for v in vs if v[\"consequence\"] in LOF]\nsum_af = sum(afreq(v)[2] for v in lofs)\nhom_lof = sum((v.get(s) or {}).get(\"homozygote_count\") or 0 for v in lofs for s in (\"exome\",\"genome\"))\n\nprint(\"=== SERPINA6 population genetics, gnomAD v4 ===\")\nprint(f\"pLoF variants catalogued            : {len(lofs)}\")\nprint(f\"Summed pLoF allele frequency (q)    : {sum_af:.3e}\")\nprint(f\"Predicted heterozygous carriers 2q  : {2*sum_af:.3e}   (about 1 in {1/(2*sum_af):,.0f})\")\nprint(f\"Predicted biallelic prevalence q^2  : {sum_af**2:.3e}   (about 1 in {1/sum_af**2:,.0f})\")\nprint(f\"Observed pLoF homozygotes in gnomAD : {hom_lof}\")\nprint(f\"\\nConstraint: pLI={con['pLI']:.2e}  o/e LoF={con['oe_lof']:.3f} \"\n      f\"(90% CI {con['oe_lof_lower']:.3f}-{con['oe_lof_upper']:.3f}, LOEUF={con['oe_lof_upper']:.3f})\")\nprint(f\"            observed/expected LoF = {con['obs_lof']}/{con['exp_lof']:.1f};  \"\n      f\"missense o/e={con['oe_mis']:.3f} ({con['obs_mis']}/{con['exp_mis']:.0f})\")\n\nprint(\"\\n--- Named clinical missense variants ---\")\ntargets = [\"Asp389Asn\",\"Asp367Asn\",\"Trp393Ser\",\"Trp371Ser\",\"Leu93His\",\"Leu115His\",\n           \"Ala224Ser\",\"Ala246Ser\",\"Gly335Val\",\"Gly357Val\",\"Thr342Ala\",\"Thr364Ala\",\n           \"Gln232Arg\",\"Gln254Arg\"]\nfor v in vs:\n    hp = v.get(\"hgvsp\") or \"\"\n    if any(t in hp for t in targets):\n        a, c, f = afreq(v)\n        hom = sum((v.get(s) or {}).get(\"homozygote_count\") or 0 for s in (\"exome\",\"genome\"))\n        print(f\"  {v['variant_id']:<22} {hp:<22} AC={a:<7} AN={c:<9} AF={f:.4e} hom={hom:<5} {v['rsids']}\")\n\nmis = [v for v in vs if v[\"consequence\"] == \"missense_variant\"]\ncommon = []\nfor v in mis:\n    a, c, f = afreq(v)\n    if f > 0.005:\n        hom = sum((v.get(s) or {}).get(\"homozygote_count\") or 0 for s in (\"exome\",\"genome\"))\n        common.append((v[\"variant_id\"], v.get(\"hgvsp\"), f, hom, v[\"rsids\"]))\nprint(f\"\\n--- Common missense alleles (AF > 0.5%), n={len(common)} of {len(mis)} missense ---\")\nfor r in sorted(common, key=lambda x: -x[2])[:12]:\n    print(f\"  {r[0]:<22} {str(r[1]):<22} AF={r[2]:.4e} hom={r[3]:<7} {r[4]}\")\n\n# ---------------- figure ----------------\nfig, axes = plt.subplots(1, 3, figsize=(15, 4.6))\n\nax = axes[0]\ncats = [\"LoF\", \"Missense\"]\nobs = [con[\"obs_lof\"], con[\"obs_mis\"]]\nexp = [con[\"exp_lof\"], con[\"exp_mis\"]]\nx = np.arange(2); w = 0.36\nax.bar(x - w/2, exp, w, label=\"Expected\", color=\"#4C72B0\", edgecolor=\"black\", linewidth=0.6)\nax.bar(x + w/2, obs, w, label=\"Observed\", color=\"#C44E52\", edgecolor=\"black\", linewidth=0.6)\nax.set_yscale(\"log\"); ax.set_xticks(x); ax.set_xticklabels(cats)\nax.set_ylabel(\"Variant count (log scale)\"); ax.legend(fontsize=8)\nax.set_title(f\"A. SERPINA6 is unconstrained\\npLI={con['pLI']:.1e}, LOEUF={con['oe_lof_upper']:.2f}\", fontsize=10)\nfor i, (o, e) in enumerate(zip(obs, exp)):\n    ax.text(i, max(o, e)*1.5, f\"o/e={o/e:.2f}\", ha=\"center\", fontsize=9)\n\nax = axes[1]\nlof_afs = sorted([afreq(v)[2] for v in lofs if afreq(v)[2] > 0], reverse=True)\nax.bar(range(len(lof_afs)), lof_afs, color=\"#DD8452\", edgecolor=\"none\")\nax.set_yscale(\"log\"); ax.set_xlabel(\"pLoF variant rank\")\nax.set_ylabel(\"Allele frequency\")\nax.set_title(f\"B. {len(lofs)} pLoF alleles, all ultra-rare\\nsummed q = {sum_af:.1e}\", fontsize=10)\nax.axhline(sum_af, color=\"black\", ls=\"--\", lw=1)\nax.text(len(lof_afs)*0.45, sum_af*1.4, \"summed q\", fontsize=8)\n\nax = axes[2]\nlabels = [\"Heterozygous\\ncarrier (2q)\", \"Biallelic\\n(q\u00b2)\"]\nfreqs = [2*sum_af, sum_af**2]\nax.bar(labels, freqs, color=[\"#DD8452\", \"#C44E52\"], edgecolor=\"black\", linewidth=0.6)\nax.set_yscale(\"log\"); ax.set_ylabel(\"Predicted population frequency\")\nfor i, f in enumerate(freqs):\n    ax.text(i, f*1.8, f\"1 in {1/f:,.0f}\", ha=\"center\", fontsize=9)\nax.set_ylim(1e-9, 1e-2)\nax.set_title(\"C. Predicted frequency of SERPINA6\\nnull genotypes (Hardy-Weinberg)\", fontsize=10)\n\nplt.tight_layout(); plt.show()\n",
  "plot_number": 2
}