allelix 2.8.0__tar.gz → 2.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. {allelix-2.8.0/allelix.egg-info → allelix-2.9.0}/PKG-INFO +1 -1
  2. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/_resolution.py +9 -88
  3. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/alphamissense.py +2 -0
  4. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/cadd.py +2 -0
  5. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/gnomad.py +74 -0
  6. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/gwas.py +219 -32
  7. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/naming_chain.py +16 -176
  8. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/rsid_identity.py +7 -1
  9. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/transcripts.py +7 -1
  10. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/_helpers.py +8 -4
  11. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/db.py +1 -1
  12. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/focused.py +4 -4
  13. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/caller.py +21 -17
  14. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/hgvs.py +5 -0
  15. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/_versions.py +4 -1
  16. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/cache_state.py +156 -9
  17. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/gnomad_loader.py +2 -2
  18. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/gwas_loader.py +90 -10
  19. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/loader_utils.py +9 -0
  20. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/schema.py +2 -0
  21. {allelix-2.8.0 → allelix-2.9.0}/allelix/models.py +7 -5
  22. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/__init__.py +51 -9
  23. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/_pipeline.py +121 -81
  24. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/clinvar_text.py +1 -1
  25. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/diff.py +105 -18
  26. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/html.py +417 -74
  27. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/json_report.py +5 -1
  28. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/terminal.py +2 -2
  29. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/vcf.py +14 -5
  30. {allelix-2.8.0 → allelix-2.9.0}/allelix/utils/allele.py +35 -0
  31. {allelix-2.8.0 → allelix-2.9.0/allelix.egg-info}/PKG-INFO +1 -1
  32. {allelix-2.8.0 → allelix-2.9.0}/pyproject.toml +3 -2
  33. {allelix-2.8.0 → allelix-2.9.0}/LICENSE +0 -0
  34. {allelix-2.8.0 → allelix-2.9.0}/MANIFEST.in +0 -0
  35. {allelix-2.8.0 → allelix-2.9.0}/README.md +0 -0
  36. {allelix-2.8.0 → allelix-2.9.0}/allelix/__init__.py +0 -0
  37. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/__init__.py +0 -0
  38. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/_placement.py +0 -0
  39. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/alt_naming.py +0 -0
  40. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/base.py +0 -0
  41. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/clinvar.py +0 -0
  42. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/pharmgkb.py +0 -0
  43. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/rare_alleles.py +0 -0
  44. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/reference_fallback.py +0 -0
  45. {allelix-2.8.0 → allelix-2.9.0}/allelix/annotators/snpedia.py +0 -0
  46. {allelix-2.8.0 → allelix-2.9.0}/allelix/attribution.py +0 -0
  47. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/__init__.py +0 -0
  48. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/_options.py +0 -0
  49. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/analyze.py +0 -0
  50. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/config.py +0 -0
  51. {allelix-2.8.0 → allelix-2.9.0}/allelix/cli/utility.py +0 -0
  52. {allelix-2.8.0 → allelix-2.9.0}/allelix/compare.py +0 -0
  53. {allelix-2.8.0 → allelix-2.9.0}/allelix/config.py +0 -0
  54. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/__init__.py +0 -0
  55. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/cache.py +0 -0
  56. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/coding.py +0 -0
  57. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/codons.py +0 -0
  58. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/csq.py +0 -0
  59. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/lift37_source.py +0 -0
  60. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/location.py +0 -0
  61. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/mane_source.py +0 -0
  62. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/model.py +0 -0
  63. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/mt_source.py +0 -0
  64. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/report.py +0 -0
  65. {allelix-2.8.0 → allelix-2.9.0}/allelix/consequence/terms.py +0 -0
  66. {allelix-2.8.0 → allelix-2.9.0}/allelix/data/__init__.py +0 -0
  67. {allelix-2.8.0 → allelix-2.9.0}/allelix/data/clinvar_clnsig_snapshot.yaml +0 -0
  68. {allelix-2.8.0 → allelix-2.9.0}/allelix/data/high_value_snps.yaml +0 -0
  69. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/__init__.py +0 -0
  70. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/alphamissense_loader.py +0 -0
  71. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/cadd_loader.py +0 -0
  72. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/cpic_loader.py +0 -0
  73. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/manager.py +0 -0
  74. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/pharmgkb_loader.py +0 -0
  75. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/rsid_identity_loader.py +0 -0
  76. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/sidecar.py +0 -0
  77. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/snpedia_loader.py +0 -0
  78. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/snpedia_parser.py +0 -0
  79. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/staging.py +0 -0
  80. {allelix-2.8.0 → allelix-2.9.0}/allelix/databases/transcript_loader.py +0 -0
  81. {allelix-2.8.0 → allelix-2.9.0}/allelix/exporters/__init__.py +0 -0
  82. {allelix-2.8.0 → allelix-2.9.0}/allelix/exporters/plink.py +0 -0
  83. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/__init__.py +0 -0
  84. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/_helpers.py +0 -0
  85. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/ancestrydna.py +0 -0
  86. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/base.py +0 -0
  87. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/decodeme.py +0 -0
  88. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/ftdna.py +0 -0
  89. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/ftdna_famfinder.py +0 -0
  90. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/ftdna_illumina.py +0 -0
  91. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/genesforgood.py +0 -0
  92. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/livingdna.py +0 -0
  93. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/myhappygenes.py +0 -0
  94. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/myheritage.py +0 -0
  95. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/rsidlist.py +0 -0
  96. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/split_site.py +0 -0
  97. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/twentythreeandme.py +0 -0
  98. {allelix-2.8.0 → allelix-2.9.0}/allelix/parsers/vcf.py +0 -0
  99. {allelix-2.8.0 → allelix-2.9.0}/allelix/py.typed +0 -0
  100. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/_sources.py +0 -0
  101. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/association_text.py +0 -0
  102. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/build_text.py +0 -0
  103. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/high_value.py +0 -0
  104. {allelix-2.8.0 → allelix-2.9.0}/allelix/reports/methylation.py +0 -0
  105. {allelix-2.8.0 → allelix-2.9.0}/allelix/utils/__init__.py +0 -0
  106. {allelix-2.8.0 → allelix-2.9.0}/allelix/utils/build_detect.py +0 -0
  107. {allelix-2.8.0 → allelix-2.9.0}/allelix/utils/markup.py +0 -0
  108. {allelix-2.8.0 → allelix-2.9.0}/allelix/utils/numbers.py +0 -0
  109. {allelix-2.8.0 → allelix-2.9.0}/allelix/utils/plausibility.py +0 -0
  110. {allelix-2.8.0 → allelix-2.9.0}/allelix/utils/source_id.py +0 -0
  111. {allelix-2.8.0 → allelix-2.9.0}/allelix.egg-info/SOURCES.txt +0 -0
  112. {allelix-2.8.0 → allelix-2.9.0}/allelix.egg-info/dependency_links.txt +0 -0
  113. {allelix-2.8.0 → allelix-2.9.0}/allelix.egg-info/entry_points.txt +0 -0
  114. {allelix-2.8.0 → allelix-2.9.0}/allelix.egg-info/requires.txt +0 -0
  115. {allelix-2.8.0 → allelix-2.9.0}/allelix.egg-info/top_level.txt +0 -0
  116. {allelix-2.8.0 → allelix-2.9.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: allelix
3
- Version: 2.8.0
3
+ Version: 2.9.0
4
4
  Summary: Open-source genotype analysis toolkit. Format-agnostic ingestion, database-agnostic annotation, offline-first.
5
5
  Author: Allelix
6
6
  Maintainer-email: dial481 <dial481@users.noreply.github.com>
@@ -180,24 +180,18 @@ def resolve_batch(
180
180
  alt, chain_final = _plain_call(v, v.rsid)
181
181
  if alt is not None:
182
182
  alone[id(v)] = alt
183
- (final if chain_final and CHAIN_FINAL else rest).append(v)
183
+ (final if chain_final else rest).append(v)
184
184
  # A plain VCF call that carries an ALT is named by the naming chain alone,
185
- # which sets its rsID whatever the position lookups below would give it:
186
- # they are skipped for it. One the chain finds to be the whole-call conflict
187
- # keeps its read rsID there, so it takes the position lookups after the
188
- # chain, as it took them before it (``_plain_call``).
189
- plain = alone if FAST_PATH else {}
185
+ # skipping redundant pre-chain position lookups. A call the chain finds to
186
+ # be a whole-call conflict keeps its read rsID there and runs through the
187
+ # position lookups afterward so downstream conflict reporting stays exact.
188
+ _resolve_positions(rest, clinvar, gnomad, identity, resolved_coords)
189
+ name_by_chain(variants, before, clinvar=clinvar, gnomad=gnomad, identity=identity, alone=alone)
190
190
  if final:
191
- _resolve_positions(rest, clinvar, gnomad, identity, resolved_coords)
192
- name_by_chain(
193
- variants, before, clinvar=clinvar, gnomad=gnomad, identity=identity, alone=plain
194
- )
195
191
  conflicts = [v for v in final if v.naming_conflict]
196
192
  if conflicts:
197
193
  _resolve_positions(conflicts, clinvar, gnomad, identity, resolved_coords)
198
194
  if resolved_coords is not None:
199
- # the chain's final name of a plain call that had none is a recovered
200
- # rsID at the call's site, as the position lookups would record it
201
195
  for v in final:
202
196
  alt = alone.get(id(v))
203
197
  if (
@@ -209,14 +203,6 @@ def resolve_batch(
209
203
  resolved_coords.setdefault(
210
204
  v.rsid, (v.chromosome, v.position, (v.ref or "").upper(), alt)
211
205
  )
212
- return
213
- _resolve_positions(variants, clinvar, gnomad, identity, resolved_coords)
214
- name_by_chain(variants, before, clinvar=clinvar, gnomad=gnomad, identity=identity, alone=plain)
215
-
216
-
217
- # The naming chain alone names a plain VCF call that carries an ALT (``resolve_batch``);
218
- # False runs every call through the position lookups first, as the differential check does.
219
- CHAIN_FINAL = True
220
206
 
221
207
 
222
208
  def _plain_call(v: Variant, written0: str) -> tuple[str | None, bool]:
@@ -325,51 +311,6 @@ def _resolve_positions(
325
311
  _name_listed(listed, identity)
326
312
 
327
313
 
328
- def _name_by_lowest_placement(
329
- variants: list[Variant],
330
- identity: RsidIdentityAnnotator | None,
331
- resolved_coords: ResolvedCoords | None,
332
- ) -> None:
333
- """Name, in place, a call still without an rsID whose ALT the identity table places several on.
334
-
335
- The last step of the order: where no written, listed or single placed
336
- rsID named the carried ALT, and the identity table places more than one
337
- rsID on that same ALT, the lowest-numbered of them names it, so the
338
- choice does not depend on the table's row order. A split site's ALTs are
339
- named by ``alt_naming``, which applies the same order.
340
- """
341
- if identity is None or not identity.is_ready():
342
- return
343
- pending = [
344
- v
345
- for v in variants
346
- if not v.rsid.startswith("rs")
347
- and v.split_site is None
348
- and not v.rsid_view
349
- and v.ref is not None
350
- and (not v.is_no_call or v.is_half_call)
351
- and v.chromosome
352
- and v.position > 0
353
- and v.build in _IDENTITY_BUILDS
354
- ]
355
- coords: ResolvedCoords = resolved_coords if resolved_coords is not None else {}
356
- for build in {v.build for v in pending}:
357
- group = [v for v in pending if v.build == build]
358
- rows_at = identity.alleles_at_loci(build, {variant_locus(v) for v in group})
359
- for v in group:
360
- rows = rows_at.get(variant_locus(v))
361
- if not rows:
362
- continue
363
- hit = resolve_rsid_at_locus(v.ref, *v.carried_pair, rows, lowest_on_tie=True)
364
- if hit is None:
365
- continue
366
- rsid, pair = hit
367
- v.original_rsid = v.original_rsid or v.rsid
368
- v.rsid = rsid
369
- if pair is not None:
370
- coords[rsid] = (v.chromosome, v.position, *pair)
371
-
372
-
373
314
  def _name_listed_alleles(variants: list[Variant], identity: RsidIdentityAnnotator | None) -> None:
374
315
  """Name, in place, each unnamed ALT of a split-site call whose record lists rsIDs.
375
316
 
@@ -902,10 +843,7 @@ def name_by_chain(
902
843
  v.rsid = v.listed_rsids[0]
903
844
  continue
904
845
  written0 = before.get(id(v), "")
905
- if alone is not None:
906
- alt = alone.get(id(v))
907
- else:
908
- alt = _alone_alt(v, written0) if FAST_PATH else None
846
+ alt = alone.get(id(v)) if alone is not None else _plain_call(v, written0)[0]
909
847
  if alt is not None:
910
848
  plain.setdefault(v.build, []).append((v, alt))
911
849
  elif recs := _records_of(v, written0):
@@ -915,7 +853,7 @@ def name_by_chain(
915
853
  (v.record_index, variant_locus(v)[0], v.position, v.ref, alt) for v, alt in singles
916
854
  ]
917
855
  names = name_plain(
918
- items, # type: ignore[arg-type] # _alone_alt checked the index and REF
856
+ items, # type: ignore[arg-type] # _plain_call checked the index and REF
919
857
  build,
920
858
  clinvar=clinvar,
921
859
  identity=identity,
@@ -947,20 +885,8 @@ def name_by_chain(
947
885
  _apply_names(v, recs, named, before.get(id(v), v.rsid), split_named.get(i))
948
886
 
949
887
 
950
- # The one-record fast path (``name_alone``); False names every call by the general path, as
951
- # the equality check of the two does.
952
- FAST_PATH = True
953
-
954
-
955
- def _alone_alt(v: Variant, written0: str) -> str | None:
956
- """The ALT of a call ``name_plain`` names, else None (``_plain_call``)."""
957
- if v.rsid_view:
958
- return None
959
- return _plain_call(v, written0)[0]
960
-
961
-
962
888
  def _apply_alone(v: Variant, alt: str, named: Named, before: str) -> None:
963
- """``_apply_names`` for a call ``name_alone`` named: one record and ALT, no rsID of its own."""
889
+ """``_apply_names`` for a call ``name_plain`` named: one record and ALT, no rsID of its own."""
964
890
  carried = [a.upper() for a in (v.allele1, v.allele2) if a and a != NO_CALL_MARKER]
965
891
  # the whole-call conflict, as ``_whole_call_conflict`` reads a plain call with no written
966
892
  # rsID: ClinVar's own or a recovered (gnomAD) rsID for the ALT foreign to the call (placed,
@@ -1253,11 +1179,6 @@ def _judged(one: RecordIn, carried: set[str], r: RecordIn) -> bool:
1253
1179
  return bool(set(one.alts) & carried) or not set(r.alts) & carried
1254
1180
 
1255
1181
 
1256
- def _record_conflict(r: RecordIn, named: dict, carried: set[str]) -> bool:
1257
- """Whether any ALT the record's call carries is the identity conflict (``_conflict_alts``)."""
1258
- return bool(_conflict_alts(r, named, carried))
1259
-
1260
-
1261
1182
  def _whole_call_conflict(
1262
1183
  v: Variant, recs: list, named: dict, split_named: dict | None = None
1263
1184
  ) -> tuple[bool, set[tuple[int, str]]]:
@@ -131,6 +131,7 @@ class AlphaMissenseAnnotator(Annotator):
131
131
  gz_path,
132
132
  self._db_path,
133
133
  source_url=ALPHAMISSENSE_CACHE_URL,
134
+ remote_signal=f"sha256:{ALPHAMISSENSE_EXPECTED_SHA256}",
134
135
  )
135
136
 
136
137
  def is_ready(self) -> bool:
@@ -149,6 +150,7 @@ class AlphaMissenseAnnotator(Annotator):
149
150
  "alphamissense",
150
151
  tag=f"sv:{ALPHAMISSENSE_SCHEMA_VERSION}",
151
152
  tables=("alphamissense_scores",),
153
+ expected_source_sha256=ALPHAMISSENSE_EXPECTED_SHA256,
152
154
  )
153
155
 
154
156
  def version(self) -> str | None:
@@ -164,6 +164,7 @@ class CaddAnnotator(Annotator):
164
164
  gz_path,
165
165
  self._db_path,
166
166
  source_url=CADD_CACHE_URL,
167
+ remote_signal=f"sha256:{CADD_EXPECTED_SHA256}",
167
168
  )
168
169
 
169
170
  def is_ready(self) -> bool:
@@ -195,6 +196,7 @@ class CaddAnnotator(Annotator):
195
196
  "cadd",
196
197
  tag=f"sv:{CADD_SCHEMA_VERSION}",
197
198
  tables=("cadd_scores",),
199
+ expected_source_sha256=CADD_EXPECTED_SHA256,
198
200
  )
199
201
 
200
202
  def version(self) -> str | None:
@@ -63,6 +63,20 @@ def rsid_names(value: str) -> tuple[str, ...]:
63
63
  return tuple(dict.fromkeys(x.strip() for x in value.split(";") if x.strip()))
64
64
 
65
65
 
66
+ def point_outbred_af(af: float | None, af_popmax: float | None) -> float | None:
67
+ """Point outbred frequency ``max(af, af_popmax)`` for rarity and plausibility checks.
68
+
69
+ Never returns ``0.0`` when both values are absent: missing cache coverage
70
+ stays ``None`` so callers record ``no_frequency`` rather than treating an
71
+ unmeasured allele as zero.
72
+ """
73
+ if af is None:
74
+ return af_popmax
75
+ if af_popmax is None:
76
+ return af
77
+ return max(af, af_popmax)
78
+
79
+
66
80
  class GnomadAnnotator(Annotator):
67
81
  """Population frequency enrichment from gnomAD.
68
82
 
@@ -142,6 +156,7 @@ class GnomadAnnotator(Annotator):
142
156
  gz_path,
143
157
  self._db_path,
144
158
  source_url=GNOMAD_CACHE_URL,
159
+ remote_signal=f"sha256:{GNOMAD_EXPECTED_SHA256}",
145
160
  )
146
161
 
147
162
  def is_ready(self) -> bool:
@@ -161,6 +176,7 @@ class GnomadAnnotator(Annotator):
161
176
  "gnomad",
162
177
  tag=f"sv:{GNOMAD_SCHEMA_VERSION}",
163
178
  tables=("gnomad_frequencies",),
179
+ expected_source_sha256=GNOMAD_EXPECTED_SHA256,
164
180
  )
165
181
 
166
182
  def version(self) -> str | None:
@@ -428,6 +444,64 @@ class GnomadAnnotator(Annotator):
428
444
  result[(chrom, pos, ref, alt)] = af
429
445
  return result
430
446
 
447
+ def bulk_lookup_point_frequencies_by_position(
448
+ self, keys: set[tuple[str, int, str, str]]
449
+ ) -> dict[tuple[str, int, str, str], tuple[float | None, float | None]]:
450
+ """Return ``{(chrom, pos, ref, alt): (af, af_popmax)}`` via primary-key lookup.
451
+
452
+ Returns both the global ``af`` (for display enrichment) and the outbred
453
+ continental group maximum ``af_popmax`` (``AF_grpmax``) so rarity and
454
+ plausibility checks can use ``max(af, af_popmax)`` without diluting
455
+ ancestry-enriched alleles or conflating missing values with zero.
456
+ """
457
+ if not keys:
458
+ return {}
459
+ conn = self._connection()
460
+ result: dict[tuple[str, int, str, str], tuple[float | None, float | None]] = {}
461
+ key_list = list(keys)
462
+ batch_size = _BULK_BATCH_SIZE // 4
463
+ for i in range(0, len(key_list), batch_size):
464
+ batch = key_list[i : i + batch_size]
465
+ clauses = " OR ".join(["(chrom = ? AND pos = ? AND ref = ? AND alt = ?)"] * len(batch))
466
+ params = [v for k in batch for v in k]
467
+ rows = conn.execute(
468
+ "SELECT chrom, pos, ref, alt, af, af_popmax "
469
+ f"FROM gnomad_frequencies WHERE {clauses}",
470
+ params,
471
+ ).fetchall()
472
+ for chrom, pos, ref, alt, af, af_popmax in rows:
473
+ if af is not None or af_popmax is not None:
474
+ result[(chrom, pos, ref, alt)] = (af, af_popmax)
475
+ return result
476
+
477
+ def bulk_lookup_faf95_by_position(
478
+ self, keys: set[tuple[str, int, str, str]]
479
+ ) -> dict[tuple[str, int, str, str], float]:
480
+ """Return ``{(chrom, pos, ref, alt): faf95_max}`` via primary-key lookup.
481
+
482
+ Rows whose ``faf95_max`` is NULL (for example singletons with AC <= 1,
483
+ where gnomAD omits ``fafmax_faf95_max``) are omitted so BA1 callers
484
+ read absence as "not common" rather than 0.0.
485
+ """
486
+ if not keys:
487
+ return {}
488
+ conn = self._connection()
489
+ result: dict[tuple[str, int, str, str], float] = {}
490
+ key_list = list(keys)
491
+ batch_size = _BULK_BATCH_SIZE // 4
492
+ for i in range(0, len(key_list), batch_size):
493
+ batch = key_list[i : i + batch_size]
494
+ clauses = " OR ".join(["(chrom = ? AND pos = ? AND ref = ? AND alt = ?)"] * len(batch))
495
+ params = [v for k in batch for v in k]
496
+ rows = conn.execute(
497
+ f"SELECT chrom, pos, ref, alt, faf95_max FROM gnomad_frequencies WHERE {clauses}",
498
+ params,
499
+ ).fetchall()
500
+ for chrom, pos, ref, alt, faf95_max in rows:
501
+ if faf95_max is not None:
502
+ result[(chrom, pos, ref, alt)] = faf95_max
503
+ return result
504
+
431
505
  def bulk_rows_by_position(
432
506
  self, keys: set[tuple[str, int, str, str]]
433
507
  ) -> dict[tuple[str, int, str, str], dict[str, float | str | None]]:
@@ -6,13 +6,15 @@ from __future__ import annotations
6
6
 
7
7
  import contextlib
8
8
  import logging
9
+ import math
9
10
  import os
10
11
  import re
11
12
  import shutil
12
13
  import sqlite3
13
14
  import zipfile
15
+ from dataclasses import replace
14
16
  from pathlib import Path
15
- from typing import TYPE_CHECKING, ClassVar
17
+ from typing import TYPE_CHECKING, ClassVar, NamedTuple
16
18
 
17
19
  from allelix.annotators.base import (
18
20
  Annotator,
@@ -45,15 +47,18 @@ from allelix.databases.manager import (
45
47
  parse_baked_version,
46
48
  )
47
49
  from allelix.databases.staging import owned_directory
48
- from allelix.models import Annotation, diploid_label
50
+ from allelix.models import NO_CALL_MARKER, Annotation, diploid_label
49
51
  from allelix.utils.allele import (
50
52
  STRAND_ABSTAIN_REASONS,
51
53
  STRAND_COMPLEMENT,
52
54
  STRAND_DIRECT,
53
55
  STRAND_FORWARD_CONFLICT,
54
56
  STRAND_NOT_IN_IDENTITY,
57
+ base_at_ref_offset,
55
58
  complement,
56
59
  forward_strand_reading,
60
+ is_single_base,
61
+ trim_allele_pair,
57
62
  )
58
63
 
59
64
  _EXCLUDED_TRAIT_CATEGORIES = frozenset(
@@ -110,35 +115,83 @@ def _split_trait_and_phecode(raw_trait: str) -> tuple[str, str]:
110
115
  return raw_trait[: m.start()].rstrip(), m.group(1)
111
116
 
112
117
 
118
+ _MLOG_5E_100 = -math.log10(5e-100)
119
+ _MLOG_5E_20 = -math.log10(5e-20)
120
+ _MLOG_5E_8 = -math.log10(5e-8)
121
+ _MLOG_5E_6 = -math.log10(5e-6)
122
+ _MLOG_5E_4 = -math.log10(5e-4)
123
+
124
+
125
+ def _effective_mlog(p_value: float | None, pvalue_mlog: float | None) -> float | None:
126
+ """Return ``-log10(p)`` from ``pvalue_mlog`` when present, else from ``p_value``."""
127
+ if pvalue_mlog is not None and math.isfinite(pvalue_mlog) and pvalue_mlog >= 0.0:
128
+ return pvalue_mlog
129
+ if p_value is not None and math.isfinite(p_value) and p_value > 0.0:
130
+ return max(0.0, -math.log10(p_value))
131
+ return None
132
+
133
+
134
+ def format_gwas_pvalue(p_value: float | None, pvalue_mlog: float | None = None) -> str:
135
+ """Format a GWAS p-value without IEEE-754 underflow to ``0.0e+00``."""
136
+ if p_value is not None and math.isfinite(p_value) and p_value > 0.0:
137
+ return f"{p_value:.1e}"
138
+ if pvalue_mlog is not None and math.isfinite(pvalue_mlog) and pvalue_mlog >= 0.0:
139
+ if pvalue_mlog == 0.0:
140
+ return "1.0e+00"
141
+ exp = math.ceil(pvalue_mlog)
142
+ mantissa = 10.0 ** (exp - pvalue_mlog)
143
+ if round(mantissa, 1) >= 10.0:
144
+ mantissa = 1.0
145
+ exp -= 1
146
+ return f"{mantissa:.1f}e-{exp}"
147
+ return "N/A"
148
+
149
+
113
150
  def _magnitude(
114
151
  p_value: float | None,
115
152
  or_beta: float | None,
116
153
  ci_text: str | None = None,
154
+ *,
155
+ pvalue_mlog: float | None = None,
117
156
  ) -> float:
118
- """Derive magnitude from p-value and a confirmed odds ratio.
157
+ """Derive magnitude from p-value (or ``-log10(p)``) and a confirmed odds ratio.
119
158
 
120
- boundary comparisons are inclusive (``<=``) so the canonical
121
- genome-wide-significance threshold ``p = 5e-8`` lands inside the
122
- significant bucket rather than the suggestive bucket below it.
123
- Strict ``<`` made the exact threshold value fall a full magnitude
124
- below a barely-significant hit.
159
+ Boundary comparisons are inclusive (``<=`` on p-value, ``>=`` on
160
+ ``-log10(p)``) so the canonical genome-wide-significance threshold
161
+ ``p = 5e-8`` lands inside the significant bucket rather than the suggestive
162
+ bucket below it. Extreme p-values (``< 1e-308``) have ``p_value=None`` and
163
+ score from ``pvalue_mlog`` without underflowing to ``0.0``.
125
164
 
126
165
  ``or_beta`` is not interpreted as an odds ratio unless
127
166
  ``ci_text`` positively identifies the Catalog's ratio-interval shape.
128
167
  Beta coefficients are unit-dependent and receive no modifier.
129
168
  """
130
- if p_value is None:
131
- base = 2.0
132
- elif p_value <= 5e-100:
133
- base = 8.0
134
- elif p_value <= 5e-20:
135
- base = 7.0
136
- elif p_value <= 5e-8:
137
- base = 6.0
138
- elif p_value <= 5e-6:
139
- base = 4.0
140
- elif p_value <= 5e-4:
141
- base = 3.0
169
+ if p_value is not None:
170
+ if p_value <= 5e-100:
171
+ base = 8.0
172
+ elif p_value <= 5e-20:
173
+ base = 7.0
174
+ elif p_value <= 5e-8:
175
+ base = 6.0
176
+ elif p_value <= 5e-6:
177
+ base = 4.0
178
+ elif p_value <= 5e-4:
179
+ base = 3.0
180
+ else:
181
+ base = 2.0
182
+ elif pvalue_mlog is not None and math.isfinite(pvalue_mlog) and pvalue_mlog >= 0.0:
183
+ if pvalue_mlog >= _MLOG_5E_100:
184
+ base = 8.0
185
+ elif pvalue_mlog >= _MLOG_5E_20:
186
+ base = 7.0
187
+ elif pvalue_mlog >= _MLOG_5E_8:
188
+ base = 6.0
189
+ elif pvalue_mlog >= _MLOG_5E_6:
190
+ base = 4.0
191
+ elif pvalue_mlog >= _MLOG_5E_4:
192
+ base = 3.0
193
+ else:
194
+ base = 2.0
142
195
  else:
143
196
  base = 2.0
144
197
 
@@ -468,7 +521,7 @@ class GWASCatalogAnnotator(Annotator):
468
521
  return []
469
522
 
470
523
  sql = (
471
- "SELECT risk_allele, trait, p_value, or_beta, ci_text, gene, "
524
+ "SELECT risk_allele, trait, p_value, pvalue_mlog, or_beta, ci_text, gene, "
472
525
  "study_accession, pubmed_id, trait_category, mapped_trait_uri "
473
526
  "FROM gwas_associations WHERE rsid = ?"
474
527
  )
@@ -505,7 +558,7 @@ class GWASCatalogAnnotator(Annotator):
505
558
  chunk = rsids[start : start + _BATCH_CHUNK]
506
559
  placeholders = ",".join("?" * len(chunk))
507
560
  cursor = conn.execute(
508
- f"SELECT rsid, risk_allele, trait, p_value, or_beta, ci_text, gene, "
561
+ f"SELECT rsid, risk_allele, trait, p_value, pvalue_mlog, or_beta, ci_text, gene, "
509
562
  f"study_accession, pubmed_id, trait_category, mapped_trait_uri "
510
563
  f"FROM gwas_associations WHERE rsid IN ({placeholders})",
511
564
  chunk,
@@ -548,14 +601,21 @@ class GWASCatalogAnnotator(Annotator):
548
601
  reading where the call does not carry them (`prune_rare_alleles`).
549
602
  """
550
603
  user_diploid = diploid_label(variant)
551
- forward = forward_alleles_at_call(variant, sites) if sites is not None else None
552
- forward = prune_rare_alleles(forward, rare.get(variant.rsid, frozenset()), variant)
604
+ proj = _project_padded_call(variant, sites)
605
+ if proj is not None:
606
+ forward = prune_rare_alleles(
607
+ proj.forward, rare.get(variant.rsid, frozenset()), proj.prune_variant
608
+ )
609
+ else:
610
+ forward = forward_alleles_at_call(variant, sites) if sites is not None else None
611
+ forward = prune_rare_alleles(forward, rare.get(variant.rsid, frozenset()), variant)
553
612
  conflicted = _forward_conflicts(rows, forward if sites is not None else None, sites)
554
613
  for row in rows:
555
614
  (
556
615
  risk_allele,
557
616
  trait,
558
617
  p_value,
618
+ pvalue_mlog,
559
619
  or_beta,
560
620
  ci_text,
561
621
  gene,
@@ -564,6 +624,7 @@ class GWASCatalogAnnotator(Annotator):
564
624
  trait_category,
565
625
  mapped_trait_uri,
566
626
  ) = row
627
+ effective_mlog = _effective_mlog(p_value, pvalue_mlog)
567
628
 
568
629
  if (
569
630
  _raises_odds(risk_allele, or_beta, ci_text)
@@ -582,9 +643,14 @@ class GWASCatalogAnnotator(Annotator):
582
643
  risk_allele = self._forward_risk_allele(risk_allele, forward)
583
644
  if risk_allele is None:
584
645
  continue
585
- if variant.allele1 != risk_allele and variant.allele2 != risk_allele:
646
+ if proj is not None:
647
+ if risk_allele not in (proj.base1, proj.base2):
648
+ continue
649
+ elif (variant.ref_from_input and len(variant.ref or "") > 1) or (
650
+ variant.allele1 != risk_allele and variant.allele2 != risk_allele
651
+ ):
586
652
  continue
587
- mag = _magnitude(p_value, or_beta, ci_text)
653
+ mag = _magnitude(p_value, or_beta, ci_text, pvalue_mlog=effective_mlog)
588
654
  risk_note = ""
589
655
  else:
590
656
  # ADR-0024: unknown risk allele fires on rsID match alone
@@ -592,14 +658,14 @@ class GWASCatalogAnnotator(Annotator):
592
658
  # thresholds. Without knowing which allele is the risk allele,
593
659
  # we can't apply the carrier rule (ADR-0007).
594
660
  mag = min(
595
- _magnitude(p_value, or_beta, ci_text),
661
+ _magnitude(p_value, or_beta, ci_text, pvalue_mlog=effective_mlog),
596
662
  _UNKNOWN_RISK_ALLELE_MAG_CAP,
597
663
  )
598
664
  risk_note = " (risk allele not specified in study)"
599
665
 
600
666
  clean_trait, phecode = _split_trait_and_phecode(trait)
601
667
  phecode_suffix = f" (PheCode {phecode})" if phecode else ""
602
- p_str = f"p={p_value:.1e}" if p_value is not None else "p=N/A"
668
+ p_str = f"p={format_gwas_pvalue(p_value, effective_mlog)}"
603
669
  gene_str = gene or "—"
604
670
  description = (
605
671
  f"GWAS Catalog: {clean_trait}{phecode_suffix} "
@@ -613,6 +679,16 @@ class GWASCatalogAnnotator(Annotator):
613
679
  references.append(f"gwas:{study_accession}")
614
680
 
615
681
  direction, measure = _effect_direction(risk_allele, or_beta, ci_text)
682
+ if proj is not None:
683
+ locus = (variant_locus(variant)[0], proj.snp_pos)
684
+ locus_ref: str | None = proj.ref_base
685
+ carried = tuple(b for b in (proj.base1, proj.base2) if b is not None)
686
+ record_key = _padded_record_key(variant, proj, risk_allele)
687
+ else:
688
+ locus = variant_locus(variant)
689
+ locus_ref = variant.ref
690
+ carried = (variant.allele1, variant.allele2)
691
+ record_key = None
616
692
  yield Annotation(
617
693
  source=self.name,
618
694
  rsid=variant.rsid,
@@ -626,18 +702,129 @@ class GWASCatalogAnnotator(Annotator):
626
702
  condition=clean_trait,
627
703
  gene=gene or "",
628
704
  alt=risk_allele or "",
629
- locus_ref=variant.ref,
630
- carried_alleles=(variant.allele1, variant.allele2),
631
- locus=variant_locus(variant),
705
+ locus_ref=locus_ref,
706
+ carried_alleles=carried,
707
+ locus=locus,
708
+ record_key=record_key,
632
709
  is_must_include=variant.rsid in _MUST_INCLUDE_RSIDS,
633
710
  trait=clean_trait,
634
711
  p_value=p_value,
712
+ pvalue_mlog=effective_mlog,
635
713
  phecode=phecode,
636
714
  effect_direction=direction,
637
715
  effect_measure=measure,
638
716
  )
639
717
 
640
718
 
719
+ class _PaddedProjection(NamedTuple):
720
+ """A padded VCF call projected onto its rsID's single-base SNP position."""
721
+
722
+ snp_pos: int
723
+ ref_base: str
724
+ base1: str | None
725
+ base2: str | None
726
+ forward: frozenset[str] | None
727
+ prune_variant: Variant
728
+
729
+
730
+ def _project_padded_call(
731
+ variant: Variant, sites: dict[str, ForwardSite] | None
732
+ ) -> _PaddedProjection | None:
733
+ """Project a padded VCF call onto the rsID's single-base SNP position, or None.
734
+
735
+ Applies only to VCF calls (``ref_from_input=True``) whose REF or carried alleles
736
+ carry padding/indel bases (length > 1). Plain single-base calls, array calls, and
737
+ calls whose rsID is not placed inside the record's REF span return None so the
738
+ standard path handles them unchanged.
739
+ """
740
+ if (
741
+ not variant.ref_from_input
742
+ or not variant.ref
743
+ or variant.position <= 0
744
+ or (len(variant.ref) <= 1 and len(variant.allele1) <= 1 and len(variant.allele2) <= 1)
745
+ ):
746
+ return None
747
+ if sites is not None:
748
+ site = sites.get(variant.rsid)
749
+ if site is None:
750
+ return None
751
+ chrom, pos, alleles = site
752
+ if variant_locus(variant)[0] != chrom or not (
753
+ variant.position <= pos < variant.position + len(variant.ref)
754
+ ):
755
+ return None
756
+ snp_pos = pos
757
+ forward: frozenset[str] | None = alleles
758
+ else:
759
+ inferred = _infer_padded_snp_pos(variant)
760
+ if inferred is None:
761
+ return None
762
+ snp_pos = inferred
763
+ forward = None
764
+ offset = snp_pos - variant.position
765
+ ref_base = variant.ref[offset].upper()
766
+ base1 = base_at_ref_offset(variant.allele1, variant.ref, offset)
767
+ base2 = base_at_ref_offset(variant.allele2, variant.ref, offset)
768
+ prune_variant = replace(
769
+ variant,
770
+ position=snp_pos,
771
+ ref=ref_base,
772
+ allele1=base1 or NO_CALL_MARKER,
773
+ allele2=base2 or NO_CALL_MARKER,
774
+ )
775
+ return _PaddedProjection(
776
+ snp_pos=snp_pos,
777
+ ref_base=ref_base,
778
+ base1=base1,
779
+ base2=base2,
780
+ forward=forward,
781
+ prune_variant=prune_variant,
782
+ )
783
+
784
+
785
+ def _infer_padded_snp_pos(variant: Variant) -> int | None:
786
+ """Infer a single-base SNP position for a padded call when no identity table is wired.
787
+
788
+ For ``len(ref) == 1`` (an SNV beside an insertion), offset 0 is the only reference
789
+ base. For ``len(ref) > 1``, infer the unique single-base SNV position from carried
790
+ non-reference alleles via ``trim_allele_pair``; return None when no SNV is carried
791
+ or two carried SNVs sit at different offsets (avoiding false matches on a left
792
+ anchor base).
793
+ """
794
+ ref = variant.ref
795
+ if not ref:
796
+ return None
797
+ if len(ref) == 1:
798
+ return variant.position
799
+ snv_positions: set[int] = set()
800
+ for allele in (variant.allele1, variant.allele2):
801
+ if not allele or allele in (NO_CALL_MARKER, ref):
802
+ continue
803
+ pos, t_ref, t_alt = trim_allele_pair(variant.position, ref, allele)
804
+ if is_single_base(t_ref) and is_single_base(t_alt):
805
+ snv_positions.add(pos)
806
+ if len(snv_positions) != 1:
807
+ return None
808
+ return next(iter(snv_positions))
809
+
810
+
811
+ def _padded_record_key(
812
+ variant: Variant, proj: _PaddedProjection, risk_allele: str | None
813
+ ) -> tuple[str, int, str, str] | None:
814
+ """Record key linking a projected padded GWAS finding back to its input VCF record."""
815
+ if variant.ref is None:
816
+ return None
817
+ if risk_allele and risk_allele != proj.ref_base:
818
+ for raw, base in ((variant.allele1, proj.base1), (variant.allele2, proj.base2)):
819
+ if base == risk_allele and raw != variant.ref:
820
+ return (variant.chromosome, variant.position, variant.ref, raw)
821
+ if proj.snp_pos != variant.position:
822
+ # Keep the input record's position for ploidy/site attribution without
823
+ # matching an indel ALT in --vcf-out when the risk allele is REF or unknown.
824
+ return (variant.chromosome, variant.position, variant.ref, variant.ref)
825
+ return None
826
+
827
+
641
828
  def _trait_group(mapped_trait_uri: str | None, trait: str) -> tuple[str, str]:
642
829
  """One rsID's vote group (`gwas_loader._vote_group`): its exact URI, else its exact trait."""
643
830
  return ("uri", mapped_trait_uri) if mapped_trait_uri else ("trait", trait)
@@ -655,7 +842,7 @@ def _forward_conflicts(
655
842
  identity table (``sites`` None) the alleles are compared as written.
656
843
  """
657
844
  seen: dict[tuple[str, str], set[str]] = {}
658
- for risk_allele, trait, _p, or_beta, ci_text, *_rest, mapped_trait_uri in rows:
845
+ for risk_allele, trait, _p, _mlog, or_beta, ci_text, *_rest, mapped_trait_uri in rows:
659
846
  if not _raises_odds(risk_allele, or_beta, ci_text):
660
847
  continue
661
848
  allele = risk_allele