Skip to content

just_dna_enricher.opentargets

just_dna_enricher.opentargets

opentargets enrich: fill the Open Targets lane's tables from the provisioned snapshot (0.8, RM333).

One pass, four writes, one licence row per write:

table grain from the snapshot
locus_to_gene.csv (study locus, gene, variant) the L2G score of every GWAS credible set a module variant is a member of
colocalisations.csv (study locus, right study locus, variant) those credible sets' molecular-QTL colocalisations
consequences.csv (variant, transcript) every module variant's per-transcript VEP consequence (RM236)
gwas_effects.csv (association) RM239's posterior_probability and fine_mapping_method, filled on rows another pass wrote

Coordinates in, from resolution.csv, like frequencies: a posterior and a consequence are per allele, and the resolution table is where an rsID has already become chrom-pos-ref-alt, which is exactly how the snapshot keys its variants (its alleles come from columns; its variantId is never parsed). Open Targets is GRCh38-only, so a row on another build is skipped and counted.

The pass never fetches. It reads the snapshot opentargets build provisioned, and with none it skips with a warning and writes nothing: nobody asked, which is not "Open Targets holds nothing" (@unreachable-not-absent). There is no --offline flag for that reason: the off switch would be a flag the pass never sees.

Members, not lead-only (RM333, decided 2026-11-04). A variant gets the L2G and coloc rows of every GWAS credible set it sits in, whether or not it leads it: HFE C282Y (rs1800562) is in 82 sets of the 26.09 release and leads none, so a lead-only table would be empty for the module the lane exists for. variant_key is the module variant asked about and is in both tables' keys; lead_variant_id still names the source's lead, and the member's own weight in the set is its posterior on gwas_effects.csv. The snapshot holds GWAS sets only (the builder filters on studyType), so a member of a molecular-QTL set gets no row here; that side arrives as the right half of a colocalisation.

Three answers per question, kept apart. For each gwas_effects.csv row the posterior is filled only when exactly one value answers; otherwise it is left empty and the reason is counted: the study has no credible set in the release, the variant is not in the study's set, or the variant sits in several of the study's sets with different values (@multiplicity-is-a-finding, never a winner).

A row with no ALT gets the release's allele, only when the release names exactly one (RM333, decided 2026-11-04). resolution.csv may hold an rsID at (chrom, start, ref) with alts empty (an authored rsID-only row, apoe_epsilon's two). The pass then reads every allele of the release at that position and its rsIds: an allele carrying the row's rsID (or its rsid_current) is a candidate on any REF, an allele on the row's REF carrying none is a candidate too (unknown, never "not this one": at 6:26091590 G the release states rs773443949 on G>T and nothing on G>A, while dbSNP, through ClinVar, names both), and an allele carrying only other rsIDs is not. Exactly one candidate, carrying the rsID on the row's REF, supplies the ALT, and the key is named in allele_supplied; any other non-empty set withholds the key (allele_unstated_withheld, never a pick: @multiplicity-is-a-finding), as does a row whose rsID is itself the back-fill's pick (status="ambiguous"); no candidate is the ordinary not-in-release answer. A row with no rsID either is withheld (allele_unstated_no_rsid): a position alone is not an identity (@rsid-not-per-allele). The supplied ALT is never written back to resolution.csv (@enrichment-is-validation), and no derived row says which ALT it used: the named key lists and the counts are the record. A snapshot built before the allele table carried rs_ids cannot answer the question at all: those keys are nobody-asked (allele_unstated_unasked), and strict refuses.

Answered replaces, could-not-ask keeps (@rederive-never-shortens): a variant this run looked up has its rows replaced by the snapshot's answer, and a variant it could not look up (off-build, unresolved) keeps whatever rows it had.

An answer is only as complete as the parts it was read from (RM361). READS names the source datasets each table and the posterior are read from, and read_is_complete asks the snapshot's release.json whether every one of them was read whole: True only when parts_read equals parts_total for each, False when one was partial, and None when the record cannot say (no parts_total, a dataset missing from it, a count that is not a number). Anything but True means an absent row may be a part nobody opened, so no key is answered for that table: rows the snapshot did yield are merged in, and every existing row is kept. A key that did not join the allele table is then not_read rather than not_in_release, and the posterior on gwas_effects.csv is left as it was. strict refuses such a snapshot before anything is read.

OpenTargetsError

Bases: RuntimeError

The Open Targets pass failed; its own type, so the CLI prints a diagnosis rather than a traceback.

PosteriorCounts dataclass

PosteriorCounts(
    filled: int = 0,
    no_study: int = 0,
    not_looked_up: int = 0,
    variant_not_in_release: int = 0,
    study_without_credible_set: int = 0,
    not_in_credible_set: int = 0,
    contested: int = 0,
    method_missing: int = 0,
    not_read: int = 0,
    allele_withheld: int = 0,
)

What happened to each gwas_effects.csv row the pass looked at. Every bucket is a different answer.

OpenTargetsResult dataclass

OpenTargetsResult(
    skipped: str | None = None,
    dataset: str | None = None,
    locus_to_gene: list[LocusToGeneRow] = list(),
    colocalisations: list[ColocalisationRow] = list(),
    consequences: list[ConsequenceRow] = list(),
    gwas_effects: list[GwasEffectRow] = list(),
    posterior: PosteriorCounts = PosteriorCounts(),
    asked: list[str] = list(),
    not_in_release: list[str] = list(),
    not_read: list[str] = list(),
    off_build: list[str] = list(),
    allele_ambiguous: list[str] = list(),
    shared_allele_keys: list[str] = list(),
    allele_supplied: list[str] = list(),
    allele_unstated_withheld: list[str] = list(),
    allele_unstated_no_rsid: list[str] = list(),
    allele_unstated_unasked: list[str] = list(),
    partial: dict[str, tuple[int, int]] = dict(),
)

Outcome of one pass. skipped names why nothing was read, when nothing was.

dataset_complete

dataset_complete(
    release: SnapshotRelease, dataset: str
) -> bool | None

Whether the snapshot read every part of dataset: None when its record cannot say (RM361).

Source code in enricher/src/just_dna_enricher/opentargets.py
def dataset_complete(release: SnapshotRelease, dataset: str) -> bool | None:
    """Whether the snapshot read every part of `dataset`: `None` when its record cannot say (RM361)."""
    counts = _part_counts(release, dataset)
    return None if counts is None else counts[0] >= counts[1]

read_is_complete

read_is_complete(
    release: SnapshotRelease, datasets: frozenset[str]
) -> bool | None

Kleene AND of dataset_complete over datasets: one partial dataset is False whatever the rest say, and otherwise one the record cannot speak for is None (RM361).

Source code in enricher/src/just_dna_enricher/opentargets.py
def read_is_complete(release: SnapshotRelease, datasets: frozenset[str]) -> bool | None:
    """Kleene AND of `dataset_complete` over `datasets`: one partial dataset is `False` whatever the rest
    say, and otherwise one the record cannot speak for is `None` (RM361)."""
    answers = [dataset_complete(release, dataset) for dataset in sorted(datasets)]
    if False in answers:
        return False
    return None if None in answers else True

enrich_opentargets

enrich_opentargets(
    spec_dir: Path,
    *,
    mode: str = "best_effort",
    write: bool = True,
    snapshot: Path | None = None,
    declared_use: str = "unstated",
) -> OpenTargetsResult

Fill the three Open Targets tables and RM239's posterior from the provisioned snapshot.

mode="strict" refuses a partial snapshot (one built from some parts of a dataset), because an absent coloc or L2G row from it may mean "not read" rather than "not published", and a strict run owes an artifact holding everything the release says. best_effort writes and warns.

Source code in enricher/src/just_dna_enricher/opentargets.py
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
def enrich_opentargets(
    spec_dir: Path,
    *,
    mode: str = "best_effort",
    write: bool = True,
    snapshot: Path | None = None,
    declared_use: str = "unstated",
) -> OpenTargetsResult:
    """Fill the three Open Targets tables and RM239's posterior from the provisioned snapshot.

    `mode="strict"` refuses a partial snapshot (one built from some parts of a dataset), because an
    absent coloc or L2G row from it may mean "not read" rather than "not published", and a strict run
    owes an artifact holding everything the release says. `best_effort` writes and warns.
    """
    spec_dir = Path(spec_dir)
    resolved = resolve_opentargets_reference(snapshot)
    if resolved is None:
        logger.warning(
            "Open Targets pass skipped: no snapshot is provisioned (set JUST_DNA_OPENTARGETS_CACHE or "
            "run `just-dna-enricher opentargets build`). Nothing was asked and nothing was written; "
            "this is not a finding that Open Targets holds nothing for these variants."
        )
        return OpenTargetsResult(skipped="no_snapshot")
    release = read_release(resolved) or SnapshotRelease()
    dataset = release.dataset or ""
    if not dataset:
        raise OpenTargetsError(
            f"the Open Targets snapshot at {resolved} has no release label in release.json"
        )
    partial = _partial_datasets(release)
    unstated = [name for name in OPENTARGETS_DATASETS if dataset_complete(release, name) is None]
    if unstated:
        if mode == "strict":
            raise OpenTargetsError(
                f"strict Open Targets enrichment: the snapshot at {resolved} does not record how many "
                f"parts {', '.join(unstated)} has, so whether it holds the whole release is unknown. "
                f"Build it with `opentargets build` (which records the totals), or use mode='best_effort'."
            )
        logger.warning(
            "Open Targets snapshot %s does not record how many parts %s has, so whether it is partial is "
            "unknown: an absent row below may mean a part was not read, and no existing row is replaced.",
            dataset,
            ", ".join(unstated),
        )
    if partial:
        described = ", ".join(f"{name} {got} of {total} parts" for name, (got, total) in partial.items())
        if mode == "strict":
            raise OpenTargetsError(
                f"strict Open Targets enrichment: the snapshot at {resolved} was built from part of the "
                f"release ({described}), so an absent row may mean 'not read' rather than 'not "
                f"published'. Build the whole release, or use mode='best_effort' and read the warning."
            )
        logger.warning(
            "Open Targets snapshot %s is partial (%s): an absent row below may mean the part holding it "
            "was not read, and no existing row is replaced.",
            dataset,
            described,
        )
    complete = {answer: read_is_complete(release, datasets) is True for answer, datasets in READS.items()}

    if write:
        require_sources_file(spec_dir, error=OpenTargetsError)
    resolution_path = sidecar_path(spec_dir, "resolution.csv", error=OpenTargetsError)
    if not resolution_path.exists():
        raise OpenTargetsError(
            f"no resolution.csv in {spec_dir}: this pass reads resolved coordinates, so run "
            f"`just-dna-enricher enrich` first."
        )
    resolution_rows = overlaid_input_rows(
        spec_dir, "resolution.csv", _existing(resolution_path, ResolutionRow), error=OpenTargetsError
    )
    alleles, unstated, unsettled, off_build = _alleles(resolution_rows)
    # A row with neither an ALT nor an rsID names a position, not an allele: nothing is asked for it.
    no_rsid = sorted({entry[0] for entry in unstated if not entry[1]})
    unstated = [entry for entry in unstated if entry[1]]
    if off_build:
        logger.warning(
            "Open Targets pass skipped %d variant(s) resolved on a build other than %s: the release is "
            "GRCh38-only, and a coordinate from another build would name a different variant. "
            "Examples: %s",
            len(off_build),
            OPENTARGETS_GENOME_BUILD,
            off_build[:3],
        )

    result = OpenTargetsResult(dataset=dataset, off_build=off_build, partial=partial)
    fetched_at = now_utc_iso()
    con = _connect(resolved)
    try:
        # ── rows that state no ALT: the release's allele, when it names exactly one for the rsID ──
        supplied: list[Allele] = []
        withheld: list[str] = []
        absent: list[str] = []
        unasked: list[str] = []
        if unstated:
            columns = {d[0] for d in con.execute("SELECT * FROM variants LIMIT 0").description}
            if "rs_ids" in columns:
                supplied, withheld, absent = _supply_alleles(con, unstated)
            elif mode == "strict":
                raise OpenTargetsError(
                    f"strict Open Targets enrichment: {len(unstated)} resolution row(s) state an rsID and "
                    f"no ALT, and the snapshot at {resolved} was built before its allele table carried "
                    f"rsIDs, so which allele they name cannot be asked. Rebuild it with `opentargets "
                    f"build`, or use mode='best_effort'."
                )
            else:
                unasked = sorted({key for key, *_ in unstated})
        withheld = sorted(set(withheld) | set(unsettled))
        # A key with a stated ALT on another of its rows is still answered for that allele, as it was
        # before no-ALT rows were read; only a key with nothing else to ask about is held back.
        blocked = set(no_rsid) | set(withheld) | set(unasked)
        supplied = [entry for entry in supplied if entry[0] not in blocked]
        stated = {entry[0] for entry in alleles}
        held = blocked - stated
        alleles = [entry for entry in dict.fromkeys(alleles + supplied) if entry[0] not in held]
        result.allele_supplied = sorted({entry[0] for entry in supplied})
        result.allele_unstated_withheld = withheld
        result.allele_unstated_no_rsid = no_rsid
        result.allele_unstated_unasked = unasked
        probe_table(
            con,
            "wanted",
            [
                ("variant_key", "VARCHAR"),
                ("chrom", "VARCHAR"),
                ("position", "BIGINT"),
                ("ref", "VARCHAR"),
                ("alt", "VARCHAR"),
            ],
            [(key, chrom, start, ref, alt) for key, _rsid, chrom, start, ref, alt in alleles],
        )
        matched = con.execute(
            "SELECT w.variant_key, v.variant_id FROM wanted w JOIN variants v "
            "ON v.chrom = w.chrom AND v.position = w.position AND v.ref = w.ref AND v.alt = w.alt "
            "ORDER BY w.variant_key, v.variant_id"
        ).fetchall()
        ids_by_key: dict[str, list[str]] = {}
        for key, variant_id in matched:
            ids_by_key.setdefault(key, []).append(variant_id)
        asked = sorted({key for key, *_ in alleles} | (set(absent) - held))
        rsid_by_key = {key: rsid for key, rsid, *_ in alleles if rsid}
        result.asked = asked
        unmatched = sorted(set(asked) - set(ids_by_key))
        if dataset_complete(release, "variant") is True:
            result.not_in_release = unmatched
        else:
            result.not_read = unmatched
        keys_by_id: dict[str, list[str]] = {}
        for key, ids in ids_by_key.items():
            for variant_id in ids:
                keys_by_id.setdefault(variant_id, []).append(key)

        # ── consequences: one release allele per module variant, or the variant's rows would collide ──
        single = {key: ids[0] for key, ids in ids_by_key.items() if len(ids) == 1}
        result.allele_ambiguous = sorted(key for key, ids in ids_by_key.items() if len(ids) > 1)
        if single:
            probe_table(
                con, "single", [("variant_key", "VARCHAR"), ("variant_id", "VARCHAR")], sorted(single.items())
            )
            for key, transcript, gene_id, gene, so_ids, impact, mane, canonical in con.execute(
                "SELECT s.variant_key, c.transcript, c.gene_id, c.gene, c.consequence_so_ids, c.impact, "
                "c.mane_select, c.canonical FROM single s JOIN consequences c ON c.variant_id = s.variant_id "
                "ORDER BY s.variant_key, c.transcript"
            ).fetchall():
                result.consequences.append(
                    ConsequenceRow(
                        variant_key=key,
                        transcript=transcript,
                        rsid=rsid_by_key.get(key),
                        gene_id=gene_id,
                        gene=gene,
                        consequence_so_ids=so_ids or None,
                        impact=impact,
                        mane_select=mane,
                        canonical=canonical,
                        dataset=dataset,
                        source=SOURCE_NAME,
                        fetched_at=fetched_at,
                    )
                )

        # ── the credible sets a module variant is a member of: L2G and coloc ──
        all_ids = sorted(keys_by_id)
        probe_table(con, "ids", [("variant_id", "VARCHAR")], [(i,) for i in all_ids])
        memberships_by_locus = con.execute(
            "SELECT DISTINCT m.study_locus_id, m.variant_id, cs.study_id, cs.lead_variant_id "
            "FROM members m JOIN ids ON ids.variant_id = m.variant_id "
            "JOIN credible_sets cs ON cs.study_locus_id = m.study_locus_id "
            "ORDER BY m.study_locus_id, m.variant_id"
        ).fetchall()
        # Two module keys naming one release allele are withheld rather than written twice, and counted,
        # whether or not that allele is in any set: in every set either key is in (a multi-ALT key's
        # other allele included). The other keys of a set keep their rows.
        shared = {key for keys in keys_by_id.values() if len(keys) > 1 for key in keys}
        # `locus_info` is `{study locus: (study, lead)}`, `member_keys` `{study locus: module keys that are
        # members, sorted}`. A key whose two release alleles sit in one set is one member of it, not two.
        locus_info: dict[str, tuple[str | None, str]] = {}
        member_sets: dict[str, set[str]] = {}
        for locus, variant_id, study, lead_id in memberships_by_locus:
            keys = set(keys_by_id.get(variant_id, [])) - shared
            if keys:
                locus_info[locus] = (study, lead_id)
                member_sets.setdefault(locus, set()).update(keys)
        member_keys = {locus: sorted(keys) for locus, keys in member_sets.items()}
        result.shared_allele_keys = sorted(shared)
        if locus_info:
            probe_table(
                con, "loci", [("study_locus_id", "VARCHAR")], [(locus,) for locus in sorted(locus_info)]
            )
            for locus, gene_id, score in con.execute(
                "SELECT l.study_locus_id, l.gene_id, l.l2g_score FROM l2g l "
                "JOIN loci ON loci.study_locus_id = l.study_locus_id ORDER BY l.study_locus_id, l.gene_id"
            ).fetchall():
                study, lead_id = locus_info[locus]
                for key in member_keys[locus]:
                    result.locus_to_gene.append(
                        LocusToGeneRow(
                            study_locus_id=locus,
                            gene_id=gene_id,
                            variant_key=key,
                            lead_variant_id=lead_id,
                            study_accession=study,
                            l2g_score=score,
                            dataset=dataset,
                            source=SOURCE_NAME,
                            fetched_at=fetched_at,
                        )
                    )
            for row in con.execute(
                "SELECT c.study_locus_id, c.right_study_locus_id, c.right_study_id, c.right_study_type, "
                "c.right_gene_id, c.right_biosample_id, c.method, c.h4, c.clpp, c.colocalising_variants "
                "FROM coloc c JOIN loci ON loci.study_locus_id = c.study_locus_id "
                "ORDER BY c.study_locus_id, c.right_study_locus_id"
            ).fetchall():
                (
                    locus,
                    right_locus,
                    right_study,
                    right_type,
                    right_gene,
                    biosample,
                    method,
                    h4,
                    clpp,
                    colocalising,
                ) = row
                study, _lead_id = locus_info[locus]
                if method is None:
                    # A statistic with no method is refused by `ColocalisationRow` (RM366); the pair is
                    # kept and its numbers withheld. The release that was measured has none (0 of
                    # 79,887,470 rows), so this is the shape the next release may take, not this one.
                    h4 = clpp = None
                for key in member_keys[locus]:
                    result.colocalisations.append(
                        ColocalisationRow(
                            study_locus_id=locus,
                            right_study_locus_id=right_locus,
                            variant_key=key,
                            study_accession=study,
                            right_study_id=right_study,
                            right_study_type=right_type,
                            right_gene_id=right_gene,
                            right_biosample_id=biosample,
                            method=method,
                            h4=h4,
                            clpp=clpp,
                            colocalising_variants=colocalising,
                            dataset=dataset,
                            source=SOURCE_NAME,
                            fetched_at=fetched_at,
                        )
                    )

        # ── RM239: the posterior on gwas_effects.csv ──
        gwas_path = sidecar_path(spec_dir, "gwas_effects.csv", error=OpenTargetsError)
        gwas_rows: list[GwasEffectRow] = _existing(gwas_path, GwasEffectRow)
        accessions = sorted({r.study_accession for r in gwas_rows if r.study_accession})
        studies_with_sets: set[str] = set()
        memberships: dict[tuple[str, str], set[tuple[float, str | None]]] = {}
        if accessions:
            probe_table(con, "studies", [("study_id", "VARCHAR")], [(a,) for a in accessions])
            studies_with_sets = {
                s
                for (s,) in con.execute(
                    "SELECT DISTINCT cs.study_id FROM credible_sets cs JOIN studies ON studies.study_id = cs.study_id"
                ).fetchall()
            }
            for variant_id, study, posterior, method in con.execute(
                "SELECT m.variant_id, cs.study_id, m.posterior_probability, cs.fine_mapping_method "
                "FROM members m JOIN ids ON ids.variant_id = m.variant_id "
                "JOIN credible_sets cs ON cs.study_locus_id = m.study_locus_id "
                "JOIN studies ON studies.study_id = cs.study_id "
                # A member with no posterior answers nothing; it is not a value to fill or to contest.
                "WHERE m.posterior_probability IS NOT NULL"
            ).fetchall():
                for key in keys_by_id.get(variant_id, []):
                    memberships.setdefault((key, study), set()).add((posterior, method))
    except duckdb.Error as exc:
        # A snapshot whose tables do not read (a file missing, a part truncated) is this pass's failure,
        # stated as one, never a duckdb traceback.
        raise OpenTargetsError(f"the Open Targets snapshot at {resolved} could not be read: {exc}") from exc
    finally:
        con.close()

    counts = result.posterior
    asked_keys = set(result.asked)
    updated: list[GwasEffectRow] = []
    for row in gwas_rows:
        if not row.study_accession:
            counts.no_study += 1
            updated.append(row)
            continue
        if row.variant_key in held:
            counts.allele_withheld += 1
            updated.append(row)
            continue
        if row.variant_key not in asked_keys:
            counts.not_looked_up += 1
            updated.append(row)
            continue
        if not complete["gwas_effects.csv"]:
            # Neither an absent value nor a single one is an answer from a snapshot not read whole: a
            # set in an unread part may hold the row's value, or contest the one read (RM361).
            counts.not_read += 1
            updated.append(row)
            continue
        values: set[tuple[float, str | None]] = set()
        if row.variant_key in result.not_in_release:
            counts.variant_not_in_release += 1
        elif row.study_accession not in studies_with_sets:
            counts.study_without_credible_set += 1
        else:
            values = memberships.get((row.variant_key, row.study_accession), set())
            if not values:
                counts.not_in_credible_set += 1
            elif len(values) > 1:
                counts.contested += 1
        if len(values) == 1 and next(iter(values))[1] is None:
            counts.method_missing += 1
            values = set()
        if len(values) == 1:
            posterior, method = next(iter(values))
            counts.filled += 1
            # Validated, not `model_copy`'d: the bounds and the finite check run on what is written.
            updated.append(
                GwasEffectRow.model_validate(
                    {**row.model_dump(), "posterior_probability": posterior, "fine_mapping_method": method}
                )
            )
        else:
            updated.append(
                GwasEffectRow.model_validate(
                    {**row.model_dump(), "posterior_probability": None, "fine_mapping_method": None}
                )
            )
    result.gwas_effects = updated
    if gwas_rows:
        logger.info(
            "Open Targets posterior on gwas_effects.csv: %d filled; left empty: %d study without a "
            "credible set, %d variant not in the study's set, %d contested (several sets, different "
            "values), %d with no fine-mapping method in the release, %d variant not in the release; "
            "untouched: %d naming no study, %d not looked up, %d against a snapshot not read whole.",
            counts.filled,
            counts.study_without_credible_set,
            counts.not_in_credible_set,
            counts.contested,
            counts.method_missing,
            counts.variant_not_in_release,
            counts.no_study,
            counts.not_looked_up,
            counts.not_read,
        )
    if result.shared_allele_keys:
        logger.warning(
            "Open Targets pass withheld the L2G and coloc rows of %d module key(s) that share one "
            "release allele with another key: one allele stated under two keys is a module defect to "
            "name, not a fact to write twice. Examples: %s",
            len(result.shared_allele_keys),
            result.shared_allele_keys[:3],
        )
    if result.allele_supplied:
        logger.warning(
            "Open Targets supplied the ALT of %d variant(s) whose resolution row states none: the release "
            "names exactly one allele carrying the row's rsID at its position, and every row written for "
            "them is of that allele, which the module did not author (resolution.csv is not changed). "
            "Examples: %s",
            len(result.allele_supplied),
            result.allele_supplied[:3],
        )
    if result.allele_unstated_withheld:
        logger.warning(
            "Open Targets pass withheld %d variant(s) whose resolution row states no ALT: the release holds "
            "several alleles at the position that may carry the row's rsID (or the only one states no "
            "rsID, or sits on another REF), or the row's rsID is itself a pick among several "
            "(status ambiguous); one is never picked. State the ALT in resolution.csv. Examples: %s",
            len(result.allele_unstated_withheld),
            result.allele_unstated_withheld[:3],
        )
    if result.allele_unstated_no_rsid:
        logger.warning(
            "Open Targets pass skipped %d variant(s) whose resolution row states neither an ALT nor an "
            "rsID: a position alone names no allele. Examples: %s",
            len(result.allele_unstated_no_rsid),
            result.allele_unstated_no_rsid[:3],
        )
    if result.allele_unstated_unasked:
        logger.warning(
            "Open Targets pass could not ask about %d variant(s) whose resolution row states an rsID and no "
            "ALT: the snapshot was built before its allele table carried rsIDs. Nothing was asked, which "
            "is not a finding that the release holds nothing; rebuild it with `opentargets build`. "
            "Examples: %s",
            len(result.allele_unstated_unasked),
            result.allele_unstated_unasked[:3],
        )
    if result.allele_ambiguous:
        logger.warning(
            "Open Targets pass withheld consequences for %d variant(s) that resolve to several of the "
            "release's alleles: their per-transcript rows would share one key. Examples: %s",
            len(result.allele_ambiguous),
            result.allele_ambiguous[:3],
        )

    if write:
        # Answered-and-withheld keeps what it had (`@rederive-never-shortens`): a key whose rows this run
        # withheld is not answered for that table, so its existing rows are not replaced with nothing.
        # Nor is any key answered from datasets the snapshot did not read whole (RM361, `READS`).
        asked = set(result.asked)
        answered = {
            "locus_to_gene.csv": asked - set(result.shared_allele_keys),
            "colocalisations.csv": asked - set(result.shared_allele_keys),
            "consequences.csv": asked - set(result.allele_ambiguous),
        }
        answered = {name: keys if complete[name] else set() for name, keys in answered.items()}
        fresh = {
            "locus_to_gene.csv": (
                result.locus_to_gene,
                lambda r: (r.variant_key, r.study_locus_id, r.gene_id),
            ),
            "colocalisations.csv": (
                result.colocalisations,
                lambda r: (r.variant_key, r.study_locus_id, r.right_study_locus_id),
            ),
            "consequences.csv": (result.consequences, lambda r: (r.variant_key, r.transcript)),
        }
        for csv_name, model, layer in OWNED_TABLES:
            rows, sort_key = fresh[csv_name]
            path = sidecar_path(spec_dir, csv_name, error=OpenTargetsError)
            existing = _existing(path, model)
            if not rows and not existing:
                continue
            merged = _replace_answered(existing, rows, answered[csv_name], sort_key)
            setattr(result, csv_name.removesuffix(".csv"), merged)
            # The licence row lands inside this table's commit, and only when this run contributed a
            # row to it (`@write-the-sourcerow`, `@licence-row-inside-the-commit`).
            this_run = {id(row) for row in rows}
            kept = sum(1 for row in merged if id(row) not in this_run)
            _write(
                merged,
                model,
                path,
                _licence(spec_dir, layer, dataset, declared_use, answered=len(merged) - kept, kept=kept)
                if rows
                else None,
            )
        if gwas_rows and updated != gwas_rows:
            # A posterior an earlier run filled and this one left alone states no release (`_licence`).
            untouched = {id(row) for row in gwas_rows}
            kept = sum(1 for row in updated if id(row) in untouched and row.posterior_probability is not None)
            _write(
                updated,
                GwasEffectRow,
                gwas_path,
                _licence(spec_dir, GWAS_LAYER, dataset, declared_use, answered=counts.filled, kept=kept)
                if counts.filled
                else None,
            )
    return result

summarise

summarise(result: OpenTargetsResult) -> dict

The counts a CLI prints, JSON-ready.

Source code in enricher/src/just_dna_enricher/opentargets.py
def summarise(result: OpenTargetsResult) -> dict:
    """The counts a CLI prints, JSON-ready."""
    return {
        "dataset": result.dataset,
        "skipped": result.skipped,
        "asked": len(result.asked),
        "not_in_release": len(result.not_in_release),
        "not_read": len(result.not_read),
        "off_build": len(result.off_build),
        "allele_ambiguous": len(result.allele_ambiguous),
        "shared_allele_keys": len(result.shared_allele_keys),
        "allele_supplied": len(result.allele_supplied),
        "allele_unstated_withheld": len(result.allele_unstated_withheld),
        "allele_unstated_no_rsid": len(result.allele_unstated_no_rsid),
        "allele_unstated_unasked": len(result.allele_unstated_unasked),
        "locus_to_gene": len(result.locus_to_gene),
        "colocalisations": len(result.colocalisations),
        "consequences": len(result.consequences),
        "posterior": result.posterior.__dict__,
        "partial": {name: list(pair) for name, pair in result.partial.items()},
    }