File size: 49,788 Bytes
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1388bd
1cb676d
 
 
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6301da1
223f3ee
 
 
 
 
 
 
 
 
6301da1
 
223f3ee
 
 
 
6301da1
 
 
 
223f3ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6301da1
 
 
 
 
 
 
 
 
 
 
9dc030e
 
 
6301da1
 
 
 
 
 
 
673d45d
6301da1
 
 
673d45d
 
6301da1
 
 
 
 
 
9dc030e
 
 
 
 
673d45d
 
9dc030e
 
6301da1
 
 
 
 
 
 
 
 
 
 
9dc030e
 
6301da1
9dc030e
 
 
6301da1
9dc030e
 
 
6301da1
 
 
 
 
9dc030e
6301da1
 
9dc030e
6301da1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673d45d
 
6301da1
673d45d
6301da1
 
 
673d45d
 
 
6301da1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673d45d
6301da1
 
 
 
 
 
673d45d
 
 
 
 
 
 
 
6301da1
 
 
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6301da1
 
 
 
 
 
 
 
673d45d
 
 
6301da1
673d45d
 
 
 
 
 
 
 
 
 
 
6301da1
e1388bd
 
 
673d45d
 
 
 
 
 
 
 
fd4c128
 
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ceceec
fd4c128
 
 
2ceceec
 
 
 
 
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4c128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673d45d
2ceceec
 
 
 
 
 
 
 
 
 
673d45d
 
 
 
 
2ceceec
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4c128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673d45d
2ceceec
 
673d45d
2ceceec
 
 
 
 
 
 
 
fd4c128
 
 
 
 
 
 
2ceceec
 
 
673d45d
 
 
 
 
 
2ceceec
673d45d
 
 
 
 
 
 
2ceceec
 
 
 
 
 
 
 
 
 
 
 
 
e1388bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ceceec
 
 
 
 
e1388bd
 
 
 
2ceceec
e1388bd
 
 
 
 
2ceceec
 
 
 
 
e1388bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fbd9d0
 
 
 
 
e1388bd
 
 
 
2fbd9d0
df22bef
 
 
e1388bd
 
 
 
 
 
 
 
 
 
 
 
2ceceec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1388bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673d45d
 
 
 
 
 
 
 
 
 
 
2ceceec
 
e1388bd
 
673d45d
 
 
1cb676d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e304570
1cb676d
 
 
 
 
e304570
1cb676d
 
 
 
 
 
 
 
 
e304570
 
1cb676d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e304570
1cb676d
 
 
 
673d45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dc030e
 
 
 
 
673d45d
9dc030e
6301da1
673d45d
 
 
 
 
 
 
 
1cb676d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e304570
 
1cb676d
 
 
 
 
 
 
 
 
673d45d
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
"""`biotool` -- structured biological tools for an agent that only has a shell.

The harness this targets (codex, Biomni, or our own loop) executes shell commands, so the
cleanest way to give it structured tools is a command-line entry point rather than a
change to the harness itself. That keeps the contribution harness-agnostic: the same
tools are reachable from any agent that can run a command.

Two families:

* **`call`** -- ToolUniverse annotation tools, filtered by `vera.tools` so that dataset,
  accession and literature lookups can never be reached. That filter is not advisory:
  BioMysteryBench forbids identifying the source dataset, and ToolUniverse ships 422 tools
  that would do exactly that.
* **`celltype`** -- Cell2Sentence inference, i.e. a pretrained biological model answering
  a question the benchmark actually asks, from the expression data rather than from the
  agent's opinion.

Model files resolve through `vera.models`, so this runs on another machine with one
environment variable or none.

    biotool list
    biotool call Alliance_get_gene '{"gene_id": "HGNC:11998"}'
    biotool celltype --genes ACTB,GAPDH,CD3E,... --organism human
"""

from __future__ import annotations

import argparse
import re
import json
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from vera import models, tools  # noqa: E402
from vera.competence import bounded  # noqa: E402
from vera import references  # noqa: E402
from vera import breakpoints  # noqa: E402
from vera import variants  # noqa: E402

# The vendored Cell2Sentence source, overridable for another machine.
C2S_SRC = os.environ.get(
    "C2S_SRC", "/home/pengchx3/text-dna/scdistill/repos/cell2sentence/src")


def cmd_list(args: argparse.Namespace) -> int:
    """Print the tools and models an agent may use."""
    print(tools.describe())
    print()
    print("Pretrained models, callable directly:")
    print(models.describe())
    return 0


def cmd_call(args: argparse.Namespace) -> int:
    """Invoke one permitted ToolUniverse tool and print its JSON result."""
    try:
        arguments = json.loads(args.arguments) if args.arguments else {}
    except json.JSONDecodeError as exc:
        print(f"arguments must be JSON: {exc}", file=sys.stderr)
        return 2
    try:
        result = tools.call_tool(args.name, arguments)
    except tools.ToolNotPermitted as exc:
        print(str(exc), file=sys.stderr)
        return 3
    print(json.dumps(result, default=str)[: args.max_chars])
    return 0


def predict_cell_type(genes: list[str], organism: str = "human",
                      max_new_tokens: int = 12) -> str:
    """Predict a cell type from genes ordered by descending expression.

    Uses Cell2Sentence's own prompt templates rather than an invented format: the model
    was trained on those strings, and a paraphrase silently degrades it in a way that
    looks like the model being wrong about biology.

    Args:
        genes: Gene symbols, highest expression first.
        organism: Organism word used in the prompt template.
        max_new_tokens: Generation cap; cell-type names are short.

    Returns:
        The predicted cell type, stripped of the template's trailing period.

    Raises:
        RuntimeError: If Cell2Sentence or the model cannot be loaded, so a caller can
            fall back rather than record a confident wrong answer.
    """
    if C2S_SRC not in sys.path:
        sys.path.insert(0, C2S_SRC)
    try:
        from cell2sentence.prompt_formatter import C2SPromptFormatter
    except ImportError as exc:
        raise RuntimeError(f"cell2sentence not importable from {C2S_SRC}") from exc
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer

    target, _ = models.resolve("c2s-celltype")
    tok_target, _ = models.resolve_tokenizer("c2s-celltype")
    formatter = C2SPromptFormatter(task="cell_type_prediction", top_k_genes=len(genes))
    template = formatter.prompts_dict["model_input"][0]
    prompt = template.format(num_genes=len(genes), organism=organism,
                             cell_sentence=" ".join(genes))

    tok = AutoTokenizer.from_pretrained(tok_target)
    model = AutoModelForCausalLM.from_pretrained(target, torch_dtype=torch.float32)
    model.eval()
    inputs = tok(prompt, return_tensors="pt")
    # A tokenizer loaded from a directory with no vocabulary encodes to nothing and the
    # failure surfaces as an unrelated reshape error inside generate(). Fail here instead.
    if inputs["input_ids"].numel() == 0:
        raise RuntimeError(
            f"tokenizer from {tok_target} produced 0 tokens for a {len(prompt)}-char "
            f"prompt; the weights directory likely ships no tokenizer")
    with torch.no_grad():
        out = model.generate(**inputs, max_new_tokens=max_new_tokens,
                             do_sample=False, pad_token_id=tok.eos_token_id)
    text = tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
    return text.strip().rstrip(".").strip()


def load_matrix(matrix_path: Path):
    """Read an expression matrix into AnnData, normalised to 10k counts.

    Accepts ``.h5ad``, a canonical 10x directory, and -- importantly here -- a directory
    using the benchmark's own names. BioMysteryBench ships
    ``counts.mtx.gz`` / ``genes.tsv.gz`` / ``cells.tsv.gz``, which `read_10x_mtx` rejects
    because it insists on ``matrix``/``features``/``barcodes``. A live solver hit exactly
    that, then created a renamed copy of the data to satisfy the tool -- work the tool
    should be doing, and a step of the agent's budget spent on our file conventions.
    """
    import scanpy as sc

    if matrix_path.suffix == ".h5ad":
        adata = sc.read_h5ad(str(matrix_path))
    else:
        adata = _read_mtx_dir(matrix_path)
    sc.pp.normalize_total(adata, target_sum=1e4)
    return adata


def _find_one(directory: Path, patterns: tuple[str, ...]) -> Path | None:
    """First file in `directory` matching any pattern, in pattern order."""
    for pattern in patterns:
        hits = sorted(directory.glob(pattern))
        if hits:
            return hits[0]
    return None


def _read_mtx_dir(directory: Path):
    """Build AnnData from a matrix directory whatever its files are called.

    Tries the canonical 10x reader first, then falls back to locating the Matrix Market
    file and its two axis labellings by shape rather than by name.

    Raises:
        RuntimeError: If no matrix can be found, naming what was present, so the caller
            sees why rather than an opaque scanpy error.
    """
    import scanpy as sc

    try:
        return sc.read_10x_mtx(str(directory))
    except Exception:
        pass

    import anndata
    import numpy as np
    import pandas as pd
    from scipy.io import mmread

    mtx = _find_one(directory, ("*.mtx.gz", "*.mtx"))
    if mtx is None:
        present = ", ".join(sorted(p.name for p in directory.iterdir())[:12]) or "nothing"
        raise RuntimeError(f"no .mtx file in {directory} (found: {present})")

    matrix = mmread(str(mtx)).tocsr()
    labels = [p for p in sorted(directory.iterdir())
              if p.name != mtx.name and p.suffix in {".tsv", ".gz", ".csv", ".txt"}]

    def _read_labels(path: Path) -> list[str]:
        frame = pd.read_csv(path, sep="\t", header=None,
                            compression="gzip" if path.suffix == ".gz" else None)
        # 10x features files carry id, symbol, type; the symbol is the useful column.
        column = 1 if frame.shape[1] > 1 else 0
        return [str(v) for v in frame.iloc[:, column]]

    # Matrix Market from 10x is genes x cells; assign each label file by matching length.
    axes: dict[int, list[str]] = {}
    for path in labels:
        try:
            values = _read_labels(path)
        except Exception:
            continue
        for axis, size in enumerate(matrix.shape):
            if len(values) == size and axis not in axes:
                axes[axis] = values
                break

    genes = axes.get(0) or [f"g{i}" for i in range(matrix.shape[0])]
    cells = axes.get(1) or [f"c{i}" for i in range(matrix.shape[1])]
    # AnnData is cells x genes.
    adata = anndata.AnnData(X=matrix.T.tocsr())
    adata.var_names = pd.Index(genes).astype(str)
    adata.obs_names = pd.Index(cells).astype(str)
    adata.var_names_make_unique()
    return adata


def ranked_genes_for_cell(adata, index: int, top: int = 100) -> list[str]:
    """Gene symbols for ONE cell, ordered by descending expression."""
    import numpy as np

    row = adata.X[index]
    values = np.asarray(row.todense()).ravel() if hasattr(row, "todense") \
        else np.asarray(row).ravel()
    order = np.argsort(-values)[:top]
    return [str(adata.var_names[i]) for i in order if values[i] > 0]


def cell_type_composition(matrix_path: Path, *, n_cells: int = 8, top: int = 100,
                          organism: str = "human", seed: int = 0,
                          budget_seconds: float = 90.0) -> dict:
    """Predict a cell type per sampled cell and return the composition.

    Replaces an averaging bug that made the whole path unsound: the first version ranked
    genes by their MEAN across every cell and asked Cell2Sentence to name that. C2S is
    trained on one cell's ranked genes, so averaging a heterogeneous sample produces a
    pseudo-cell belonging to no population -- on a real lung sample it returned
    "erythrocyte", which is a real constituent but not the answer to any question asked.

    A composition is also the right evidence for the question the benchmark actually
    poses. Tissue identity follows from which populations are present and in what
    proportion, not from a single label; a lung sample legitimately contains erythrocytes.

    Args:
        matrix_path: 10x directory or ``.h5ad``.
        n_cells: Cells to sample. Each is a separate forward pass, so this trades
            resolution against time.
        top: Genes per cell sentence.
        organism: Organism word for the prompt template.
        seed: Sampling seed, so a reported composition is reproducible.
        budget_seconds: Stop sampling once this much wall clock has been spent and return
            what was gathered. An agent that waits is an agent not solving the problem:
            at 24 cells and ~40s per generation this took ~16 minutes on CPU, and a real
            solver killed it mid-run and answered correctly by grepping marker genes
            instead. A partial composition beats a tool the caller has to abandon.

    Returns:
        ``{"composition": {label: count}, "n_cells": int, "dominant": label,
        "truncated": bool}`` where `n_cells` is how many were actually scored.
    """
    import random

    adata = load_matrix(matrix_path)
    detected = detect_species(list(adata.var_names))
    if detected != "unknown":
        organism = detected
    total = adata.shape[0]
    rng = random.Random(seed)
    picks = rng.sample(range(total), min(n_cells, total))

    import time

    counts: dict[str, int] = {}
    started = time.monotonic()
    scored = 0
    truncated = False
    for index in picks:
        if time.monotonic() - started > budget_seconds:
            truncated = True
            break
        genes = ranked_genes_for_cell(adata, index, top=top)
        if not genes:
            continue
        label = predict_cell_type(genes, organism=organism)
        counts[label] = counts.get(label, 0) + 1
        scored += 1
    dominant = max(counts, key=counts.get) if counts else ""
    return {"composition": dict(sorted(counts.items(), key=lambda kv: -kv[1])),
            "n_cells": scored, "dominant": dominant, "truncated": truncated}


# Species-specific reference panels. Selecting a reference before knowing the species is
# how this went wrong: hb001 is MOUSE (mt-Cytb, Gm31793, 7530416G11Rik) and every
# reference scored was human, so all seven fits collapsed to ~0.08 and the ranking was
# noise. Cell2Sentence was likewise prompted with organism="human". Neither model failed;
# both were fed the wrong species.
HUMAN_MARKERS = ("GAPDH", "ACTB", "MT-CO1", "PTPRC", "CD3E", "EPCAM")
MOUSE_MARKERS = ("Gapdh", "Actb", "mt-Co1", "Ptprc", "Cd3e", "Epcam")

MOUSE_REFERENCES = (
    "Adult_Mouse_Gut.pkl",
    "Healthy_Mouse_Liver.pkl",
    "Mouse_Whole_Brain.pkl",
    "Mouse_Isocortex_Hippocampus.pkl",
    "Adult_Mouse_OlfactoryBulb.pkl",
    "Developing_Mouse_Brain.pkl",
)


def detect_species(gene_symbols) -> str:
    """Infer the organism from gene-symbol casing and species-specific prefixes.

    Human symbols are upper case (``GAPDH``); mouse symbols are title case (``Gapdh``) and
    the annotation carries giveaways no human set has -- ``Gm`` predicted models and
    ``Rik`` RIKEN clones. Returns ``"human"``, ``"mouse"`` or ``"unknown"``; the caller
    must treat ``"unknown"`` as a reason to widen the panel, never as a default to human.
    """
    symbols = [str(g).strip() for g in gene_symbols if str(g).strip()]
    if not symbols:
        return "unknown"
    alpha = [g for g in symbols if g[:1].isalpha()]
    if not alpha:
        return "unknown"
    mouse_specific = sum(1 for g in alpha if g.startswith("Gm") and g[2:3].isdigit())
    mouse_specific += sum(1 for g in alpha if g.endswith("Rik"))
    upper = sum(1 for g in alpha if g.isupper() and len(g) > 2)
    title = sum(1 for g in alpha if len(g) > 2 and g[0].isupper() and g[1:].islower())
    if mouse_specific >= 5 or title > upper * 2:
        return "mouse"
    if upper > title * 2:
        return "human"
    return "unknown"


def references_for(species: str) -> tuple[str, ...]:
    """Reference panel appropriate to a species; both panels when it is unknown."""
    if species == "mouse":
        return MOUSE_REFERENCES
    if species == "human":
        return REFERENCE_PANEL
    return REFERENCE_PANEL + MOUSE_REFERENCES


# A spread of human tissue references. Which one FITS is the evidence: CellTypist models are
# tissue-specific, so applying one out of domain forces every cell into a label it does
# know. On a lung sample the immune-only reference called 91% of cells "Double-positive
# thymocytes" -- confident, concentrated, and wrong. Comparing fit across references turns
# that failure mode into a measurement.
REFERENCE_PANEL = (
    "Human_Lung_Atlas.pkl",
    "Healthy_COVID19_PBMC.pkl",
    "Healthy_Human_Liver.pkl",
    "Healthy_Adult_Heart.pkl",
    "Cells_Intestinal_Tract.pkl",
    "Developing_Human_Thymus.pkl",
    "Immune_All_High.pkl",
)


def identify_reference(matrix_path: Path, panel: tuple[str, ...] | None = None,
                       max_cells: int = 3000) -> dict:
    """Find which tissue reference best explains the data, and report the ranking.

    Rationale. Every CellTypist model is tissue-specific, so a caller who already knew the
    tissue would not need the tool. Scoring several references by how confidently they
    explain the cells inverts the problem: the best-fitting reference names the tissue,
    and the *margin* over the runner-up says how much to trust that.

    Mean maximum probability is the fit statistic. A reference that must stretch to label
    out-of-domain cells does so with low per-cell confidence even when its modal label
    looks decisive, which is exactly the failure this replaces.

    Args:
        matrix_path: 10x directory or ``.h5ad``.
        panel: References to compare. Defaults to the panel matching the species
            detected from the gene symbols, because scoring human references against
            mouse data produces a ranking that is pure noise.
        max_cells: Subsample size, since fit is a population statistic and running seven
            references over 34k cells is needlessly slow.

    Returns:
        ``{"best": name, "margin": float, "ranking": [(name, fit), ...],
        "composition": {label: count}}`` for the winning reference.

    Raises:
        RuntimeError: If no reference could be scored, rather than returning a guess.
    """
    import numpy as np
    import scanpy as sc

    try:
        import celltypist
    except ImportError as exc:
        raise RuntimeError("celltypist not installed") from exc

    adata = load_matrix(matrix_path)
    species = detect_species(list(adata.var_names))
    if panel is None:
        panel = references_for(species)
    sc.pp.log1p(adata)
    if adata.shape[0] > max_cells:
        sc.pp.subsample(adata, n_obs=max_cells, random_state=0)

    scored: list[tuple[str, float, dict]] = []
    for name in panel:
        try:
            celltypist.models.download_models(model=name)
            result = celltypist.annotate(adata, model=name, majority_voting=False)
            probs = getattr(result, "probability_matrix", None)
            fit = float(np.asarray(probs).max(axis=1).mean()) if probs is not None else 0.0
            labels = result.predicted_labels
            column = labels.iloc[:, 0] if hasattr(labels, "iloc") else labels
            counts = column.value_counts()
            scored.append((name, fit,
                           {str(k): int(v) for k, v in counts.head(8).items()}))
        except Exception:
            continue  # a reference that will not load is not evidence either way

    if not scored:
        raise RuntimeError("no reference could be scored")
    scored.sort(key=lambda x: -x[1])
    best, best_fit, composition = scored[0]
    margin = best_fit - (scored[1][1] if len(scored) > 1 else 0.0)
    # The winner is the closest AVAILABLE reference, which is not the same as the true
    # tissue: CellTypist has no mouse lung panel, so a mouse lung sample lands on an
    # olfactory-bulb reference at 0.885 with a 0.013 margin over a hippocampus one. A
    # small margin between unrelated tissues means nothing in the panel fits, and the
    # per-cell composition is then the more reliable evidence than the reference name.
    trustworthy = best_fit >= 0.5 and margin >= 0.05
    return {"best": best, "fit": round(best_fit, 4), "margin": round(margin, 4),
            "species": species,
            "reference_is_conclusive": trustworthy,
            "caveat": ("" if trustworthy else
                       "closest available reference only: low fit or a narrow margin "
                       "means the true tissue may be absent from the panel -- read the "
                       "composition, not this name"),
            "ranking": [(n, round(f, 4)) for n, f, _ in scored],
            "composition": composition}


def celltypist_composition(matrix_path: Path,
                           model_name: str = "Immune_All_Low.pkl") -> dict:
    """Per-cell CellTypist labels under ONE named reference.

    Prefer `identify_reference` unless the tissue is already known: this applies whatever
    reference it is given, including out of domain, where it is confidently wrong.
    """
    try:
        import celltypist
    except ImportError as exc:
        raise RuntimeError("celltypist not installed") from exc
    import scanpy as sc

    adata = load_matrix(matrix_path)
    sc.pp.log1p(adata)
    try:
        celltypist.models.download_models(model=model_name)
        result = celltypist.annotate(adata, model=model_name, majority_voting=False)
    except Exception as exc:
        raise RuntimeError(f"celltypist failed: {exc}") from exc
    labels = result.predicted_labels
    column = labels.iloc[:, 0] if hasattr(labels, "iloc") else labels
    counts = column.value_counts()
    return {"composition": {str(k): int(v) for k, v in counts.head(10).items()},
            "n_cells": int(counts.sum()), "dominant": str(counts.idxmax())}


def cmd_celltype(args: argparse.Namespace) -> int:
    """Predict a cell type from a comma-separated ranked gene list."""
    if not args.genes and not args.matrix:
        print("give --genes or --matrix", file=sys.stderr)
        return 2

    wanted = ([s.key for s in models.models_for_task(models.CELL_TYPE)]
              if args.model == "all" else [args.model])
    predictions: dict[str, str] = {}
    errors: dict[str, str] = {}

    for key in wanted:
        try:
            if key == "c2s-celltype":
                genes = [g.strip() for g in (args.genes or "").split(",") if g.strip()]
                if genes:
                    predictions[key] = {"dominant": predict_cell_type(
                        genes, organism=args.organism), "composition": {}, "n_cells": 1}
                else:
                    predictions[key] = cell_type_composition(
                        Path(args.matrix), n_cells=args.n_cells,
                        organism=args.organism)
            elif key == "celltypist":
                if not args.matrix:
                    raise RuntimeError("celltypist needs --matrix, not a ranked list")
                predictions[key] = celltypist_composition(Path(args.matrix))
            else:
                raise RuntimeError(f"no cell-type path for {key}")
        except (RuntimeError, OSError) as exc:
            errors[key] = str(exc)[:200]

    if not predictions:
        for key, msg in errors.items():
            print(f"{key}: {msg}", file=sys.stderr)
        return 4
    # Agreement is reported, never resolved by a vote of one: a single opinion labelled
    # "consensus" would overstate what two disagreeing models actually support.
    distinct = {str(v.get("dominant", "")).lower().strip() for v in predictions.values()}
    emit({"predictions": predictions,
          "agree": len(distinct) == 1 and len(predictions) > 1,
          "n_models": len(predictions), "errors": errors})
    return 0


NCBI_BLAST_URL = "https://blast.ncbi.nlm.nih.gov/Blast.cgi"


def classify_taxonomy(fasta: Path, *, top: int = 5, timeout: int = 600,
                      program: str = "blastn", database: str = "nt",
                      poll_seconds: int = 15, hits_per_query: int = 3,
                      max_per_batch: int = 40, fetch=None) -> list[dict]:
    """Identify the source organism of a sequence by BLAST against NCBI.

    Covers the largest capability gap measured on this benchmark: 10 of 73 problems turn
    on *which organism or contaminant* the data came from, and no local model or database
    answers that.

    **Rule compliance.** The benchmark permits "gene ID lookup, sequence annotation,
    reference genome download, BLAST" by name, and forbids using GEO/SRA/ENA/BioProject
    accessions to identify the originating *dataset*. Asking what species a sequence is
    annotates the sequence the solver was given rather than locating the study it came
    from. Only taxonomic and alignment fields are returned, so a dataset accession cannot
    travel back to the caller.

    Uses NCBI's URL API over plain HTTPS rather than `blastn -remote`: the packaged BLAST
    client's RPC transport fails here ("Connection stream is in bad state") even though
    the same host answers HTTPS with 200, and HTTPS is also the more portable dependency.

    Args:
        fasta: Query sequences. Keep this small -- the public service is rate-limited.
        top: Hits to return in total, across all queries.
        max_per_batch: Queries per submission. Above this the search is split, because
            the public service caps a large submission silently -- 1,200 queries returned
            zero hits where 400 had returned 42.
        hits_per_query: Hits NCBI returns for EACH query sequence. Kept small and
            independent of `top`: setting it from the query count once asked for 400 hits
            on each of 400 reads, and the 200 MB reply arrived truncated mid-JSON. What a
            caller wants from many reads is which organisms appear, not a deep alignment
            list for every one.
        timeout: Total wall clock, seconds. Public BLAST commonly takes minutes.
        program: BLAST program.
        database: Remote database name.
        poll_seconds: Delay between status polls.
        fetch: Optional ``params -> text`` callable replacing the HTTP layer. Injected so
            the protocol (request-id parsing, polling, report parsing) can be tested
            without touching a rate-limited public service.

    Returns:
        One dict per hit with ``scientific_name``, ``bitscore``, ``percent_identity``
        and ``alignment_length``, best first.

    Raises:
        RuntimeError: On submission failure, search failure or timeout, so a caller can
            fall back rather than silently report no organism.
    """
    import time
    import urllib.parse
    import urllib.request

    query = fasta.read_text(errors="replace")
    if not query.strip():
        raise RuntimeError(f"{fasta} is empty")

    # The public service silently caps a large submission. Rather than lose the whole
    # search, split into batches and concatenate -- depth is the variable that decides
    # whether a minority organism is visible, so it must not be bounded by a transport
    # limit the caller cannot see.
    records = [r for r in query.split(">") if r.strip()]
    if len(records) > max_per_batch:
        merged: list[dict] = []
        for start in range(0, len(records), max_per_batch):
            chunk = "".join(f">{r}" for r in records[start:start + max_per_batch])
            batch_file = fasta.with_suffix(f".batch{start}.fa")
            batch_file.write_text(chunk)
            try:
                merged.extend(classify_taxonomy(
                    batch_file, top=top, timeout=timeout, program=program,
                    database=database, poll_seconds=poll_seconds,
                    hits_per_query=hits_per_query, fetch=fetch,
                    max_per_batch=max_per_batch))
            finally:
                batch_file.unlink(missing_ok=True)
        return merged[:top] if top else merged

    def _http(params: dict) -> str:
        # Submission goes by POST: the query sequences live in the parameters, and a GET
        # caps them at the URI limit -- 400 reads returned "HTTP 414 Request-URI Too
        # Long", silently bounding how deeply the sample could be searched. Status polls
        # and result fetches carry only a request id, so they stay GET.
        body = urllib.parse.urlencode(params).encode()
        if params.get("CMD") == "Put":
            request = urllib.request.Request(NCBI_BLAST_URL, data=body)
        else:
            request = urllib.request.Request(f"{NCBI_BLAST_URL}?{body.decode()}")
        with urllib.request.urlopen(request, timeout=180) as resp:
            return resp.read().decode(errors="replace")

    _get = fetch or _http

    submitted = _get({"CMD": "Put", "PROGRAM": program, "DATABASE": database,
                      "QUERY": query, "HITLIST_SIZE": hits_per_query,
                      "FORMAT_TYPE": "JSON2_S"})
    match = re.search(r"^\s*RID = (\S+)", submitted, re.M)
    if not match:
        raise RuntimeError("NCBI did not return a request id; the service may be busy")
    rid = match.group(1)

    deadline = time.time() + timeout
    while time.time() < deadline:
        time.sleep(poll_seconds)
        info = _get({"CMD": "Get", "FORMAT_OBJECT": "SearchInfo", "RID": rid})
        if "Status=READY" in info:
            break
        if "Status=FAILED" in info or "Status=UNKNOWN" in info:
            raise RuntimeError(f"NCBI BLAST reported failure for {rid}")
    else:
        raise RuntimeError(f"NCBI BLAST did not finish within {timeout}s (RID {rid})")

    payload = _get({"CMD": "Get", "FORMAT_TYPE": "JSON2_S", "RID": rid})
    try:
        report = json.loads(payload)
    except json.JSONDecodeError as exc:
        # Say what actually arrived. "Unparseable" alone cannot distinguish a truncated
        # reply from an HTML rate-limit page, and both look identical to the caller.
        head = (payload or "")[:160].replace("\n", " ")
        truncated = head.lstrip().startswith("{") and len(payload or "") > 1_000_000
        if truncated and max_per_batch > 10:
            # NCBI caps the reply size and JSON2_S carries full alignment data per hit,
            # so a batch that is too large arrives as valid JSON cut off mid-structure.
            # Halve and retry rather than fail: the caller asked for depth, and the limit
            # is a transport property they cannot see or plan around.
            return classify_taxonomy(
                fasta, top=top, timeout=timeout, program=program, database=database,
                poll_seconds=poll_seconds, hits_per_query=hits_per_query,
                max_per_batch=max(10, max_per_batch // 2), fetch=fetch)
        kind = ("an HTML page (rate limit or error)" if head.lstrip()[:1] == "<"
                else f"{len(payload or '')} bytes of non-JSON")
        raise RuntimeError(
            f"unparseable BLAST report for {rid}: got {kind}. Starts: {head!r}") from exc

    # Every query gets its own report; reading only the first would describe one read.
    searches = []
    try:
        for entry in report.get("BlastOutput2") or []:
            found = (entry.get("report") or {}).get("results", {}).get("search")
            if found:
                searches.append(found)
    except (AttributeError, TypeError):
        searches = []
    # A shape we do not recognise yields no hits, never an organism: a wrong species is
    # worse for the caller than an admitted blank.
    # A report with no search records at all is a failed or truncated search, not a
    # sample with nothing in it. 1,200 queries came back with zero hits in three minutes
    # while 400 had produced 42, and the empty list was returned as if it were a finding.
    if not searches:
        raise RuntimeError(
            f"BLAST report for {rid} contains no search records; the submission was "
            f"likely rejected or truncated. Try fewer queries per submission.")
    all_hits = [h for s in searches for h in (s.get("hits") or [])]
    hits: list[dict] = []
    for hit in all_hits[:top]:
        desc = (hit.get("description") or [{}])[0]
        hsp = (hit.get("hsps") or [{}])[0]
        align_len = hsp.get("align_len") or 0
        identity = hsp.get("identity") or 0
        hits.append({
            "scientific_name": desc.get("sciname") or desc.get("title", "")[:80],
            "title": (desc.get("title") or "")[:200],
            "bitscore": hsp.get("bit_score"),
            "percent_identity": round(100.0 * identity / align_len, 2) if align_len else None,
            "alignment_length": align_len,
        })
    return hits


# Influenza carries eight segments, and only two of them determine the subtype:
# hemagglutinin (segment 4) fixes H, neuraminidase (segment 6) fixes N. A read from an
# internal segment still carries its source strain's subtype in the organism NAME, but
# that label is a property of the strain, not something the read establishes. Reading
# subtypes off every hit is therefore wrong, and it is exactly where the H4N8 and H6N1
# false positives came from.
_HA = re.compile(r"\b(h(?:a)?emagglutinin|segment 4|\bHA\b)", re.I)
_NA = re.compile(r"\b(neuraminidase|segment 6|\bNA\b)", re.I)
_H_TYPE = re.compile(r"\bH(\d{1,2})N\d{1,2}\b|\bH(\d{1,2})\b")
_N_TYPE = re.compile(r"\bH\d{1,2}N(\d{1,2})\b|\bN(\d{1,2})\b")


def influenza_subtypes(hits: list[dict]) -> dict:
    """Determine influenza subtypes, separating strong evidence from weak.

    Two earlier designs were each wrong in one direction, measured on the same sample
    (truth: H1N1, H2N2, H3N2, H5N1, H7N9, H9N2):

        count every hit's strain label : 4 correct, 1 false   -- recall, no discipline
        use HA/NA hits only            : 1 correct, 0 false   -- discipline, no recall

    The domain fact -- only hemagglutinin and neuraminidase determine subtype -- is right
    about what a read PROVES and wrong about what it INDICATES. A read matching an H2N2
    strain's nucleoprotein does not establish the subtype, but the database entry it
    matched belongs to an H2N2 strain, so it is evidence that strain is present. Internal
    segments are weak evidence, not none, and discarding 36 of 47 hits discarded most of
    the signal.

    So evidence is tiered rather than filtered. A caller can take the strong set as
    established and the weak set as candidates to check, which is the distinction the
    single flat list destroyed.

    Args:
        hits: Hits from `classify_taxonomy`, carrying `title`.

    Returns:
        ``{"strong": {...}, "weak": {...}, "candidates": [...], "competence": Competence}``
        where `strong` comes from HA/NA hits and `weak` from internal-segment strain
        labels. H and N are reported separately as well as paired, since reads do not
        pair them.
    """
    strong_h: set[str] = set()
    strong_n: set[str] = set()
    weak_subtypes: set[str] = set()
    n_strong = n_weak = 0

    for hit in hits:
        title = f"{hit.get('title','')} {hit.get('scientific_name','')}"
        if "nfluenza" not in title:
            continue
        is_ha, is_na = bool(_HA.search(title)), bool(_NA.search(title))
        if is_ha or is_na:
            n_strong += 1
            if is_ha:
                for a, b in _H_TYPE.findall(title):
                    strong_h.add(f"H{int(a or b)}")
            if is_na:
                for a, b in _N_TYPE.findall(title):
                    strong_n.add(f"N{int(a or b)}")
        else:
            n_weak += 1
            for m in re.findall(r"\bH\d{1,2}N\d{1,2}\b", title):
                weak_subtypes.add(m.upper())

    strong_subtypes = sorted(f"{h}{n}" for h in sorted(strong_h) for n in sorted(strong_n))
    candidates = sorted(set(strong_subtypes) | weak_subtypes)
    # Strong evidence alone is rarely complete here: HA and NA are 2 of 8 segments, so
    # most influenza reads are uninformative about subtype by construction. Reporting
    # this as conclusive would repeat the failure the tiering exists to prevent.
    # This tool had already reinvented the uniqueness condition in its own idiom: the
    # margin above is 1.0 exactly when no candidate sits outside the strong set. Reporting
    # the rival count as well puts it in the shared vocabulary, which is the whole point
    # of having one -- and this tool has no ranking axis at all, so for a caller forced to
    # answer, the size of the candidate set is the only thing that decides accuracy.
    competence = bounded(
        confidence=min(1.0, n_strong / 10.0),
        margin=(1.0 if strong_subtypes and not weak_subtypes - set(strong_subtypes)
                else 0.0),
        alternatives=max(0, len(candidates) - 1),
        # No ranking axis at all, so nothing can be ordered below anything: every
        # candidate beyond the first is tied by construction.
        ties=max(0, len(candidates) - 1),
        blind_spots=(("subtypes seen only in internal-segment hits are unconfirmed",)
                     if weak_subtypes - set(strong_subtypes) else ())
        + (("subtypes below the read-depth floor are unobserved",) if n_strong < 20 else ()),
        remedy="type HA and NA against a curated influenza database, or sample deeper",
    )
    return {
        "strong": {"h_types": sorted(strong_h), "n_types": sorted(strong_n),
                   "subtypes": strong_subtypes, "n_hits": n_strong},
        "weak": {"subtypes": sorted(weak_subtypes), "n_hits": n_weak},
        "candidates": candidates,
        "competence": competence,
    }


def summarise_taxonomy(hits: list[dict], n_queries: int) -> dict:
    """Describe what a BLAST result can and cannot establish.

    Written because the tool failed silently in the way that matters. Asked to find
    influenza subtypes in a 405 MB FASTQ, a 40-read sample returned 23 *Homo sapiens*,
    8 *Macaca mulatta* and no virus at all: the host dominates and a minority organism is
    simply invisible at that depth. The output was confident, well formed, and about the
    wrong organism.

    So the summary states the detection floor explicitly. With `n` queries, an organism
    present in fewer than roughly 1/n of reads is not expected to appear, and a result
    dominated by one taxon is evidence about the majority only.

    Args:
        hits: Hits from `classify_taxonomy`.
        n_queries: Number of query sequences searched.

    Returns:
        ``{"dominant": name, "dominant_fraction": float, "detection_floor": float,
        "can_see_minority": bool, "caveat": str}``.
    """
    from collections import Counter

    names = Counter(h.get("scientific_name", "") for h in hits if h.get("scientific_name"))
    if not names:
        return {"dominant": "", "dominant_fraction": 0.0,
                "detection_floor": 1.0, "can_see_minority": False,
                "caveat": "no named hits; this establishes nothing about the sample"}
    dominant, count = names.most_common(1)[0]
    fraction = count / sum(names.values())
    floor = 1.0 / max(n_queries, 1)
    # One taxon holding most hits means everything rarer than the floor is unobserved,
    # not absent. Calling that "the organism" is the error this exists to prevent.
    can_see_minority = fraction < 0.5 and n_queries >= 200
    caveat = "" if can_see_minority else (
        f"{dominant} accounts for {fraction:.0%} of hits over {n_queries} queries. "
        f"Anything present below ~{floor:.1%} of reads is UNOBSERVED, not absent. "
        f"To find a minority organism, deplete the dominant one first (map to it and "
        f"keep the unmapped reads) or search far more reads.")
    return {"dominant": dominant, "dominant_fraction": round(fraction, 3),
            "detection_floor": round(floor, 4),
            "can_see_minority": can_see_minority, "caveat": caveat}


# The experimental variable. With competence reporting off, a tool answers the way most
# tool APIs do: the finding alone, no statement of what it could not see. With it on, the
# same finding carries applicability, confidence, margin and blind spots. The claim under
# test is that this changes what the agent concludes -- an untested assumption behind
# every "tools should be honest" argument.
CONFIDENT_MODE = os.environ.get("BIOTOOL_CONFIDENT", "") == "1"


def _strip_competence(payload: dict) -> dict:
    """Remove competence fields, emulating a conventional tool that reports only findings."""
    hidden = {"caveat", "can_see_minority", "detection_floor", "dominant_fraction",
              "competence", "reference_is_conclusive", "blind_spots", "margin"}
    return {k: v for k, v in payload.items() if k not in hidden}


def emit(payload: dict) -> None:
    """Print a tool result, honouring the competence-reporting mode."""
    print(json.dumps(_strip_competence(payload) if CONFIDENT_MODE else payload,
                     default=str))


def cmd_taxonomy(args: argparse.Namespace) -> int:
    """Report the most likely source organism for a FASTA of query sequences."""
    fasta = Path(args.fasta)
    if not fasta.is_file():
        print(f"no such file: {fasta}", file=sys.stderr)
        return 2
    try:
        hits = classify_taxonomy(fasta, top=args.top, timeout=args.timeout)
    except RuntimeError as exc:
        print(str(exc), file=sys.stderr)
        return 4
    n_queries = sum(1 for line in fasta.read_text(errors="replace").splitlines()
                    if line.startswith(">"))
    emit({"hits": hits[:args.top], "n": len(hits),
          **summarise_taxonomy(hits, n_queries)})
    return 0


def cmd_references(args: argparse.Namespace) -> int:
    """List reference genomes staged on this machine and whether they are usable."""
    emit({"references": references.available()})
    return 0


def cmd_align(args: argparse.Namespace) -> int:
    """Align a sample of reads to a staged reference and report where they land.

    Saves the agent an index build, which is the expensive part: on these problems they
    already install minimap2 and run `bwa index`, `bwa mem`, `bowtie2` and `kallisto`
    successfully, so this is a convenience rather than a capability. The capability is
    `breakpoints`, which computes a statistic they get wrong by hand.
    """
    fastq = Path(args.fastq)
    if not fastq.is_file():
        print(f"no such file: {fastq}", file=sys.stderr)
        return 2
    try:
        result = references.align_reads(fastq, args.reference, n_reads=args.n_reads)
    except RuntimeError as exc:
        print(str(exc), file=sys.stderr)
        return 4
    mapped = result["mapped"]
    # Report the same competence contract the other tools use: a locus supported by a
    # handful of reads is a candidate, not a finding.
    top = result["top_loci"][0]["reads"] if result["top_loci"] else 0
    result["competence"] = bounded(
        confidence=min(1.0, mapped / max(args.n_reads, 1) * 2),
        margin=(top / mapped) if mapped else 0.0,
        blind_spots=(("loci below the sampled depth are unobserved",) if mapped < 100
                     else ()),
        remedy="raise --n-reads, or align the full library outside the step budget",
    ).explain()
    emit(result)
    return 0


def cmd_breakpoints(args: argparse.Namespace) -> int:
    """Report where sequenced molecules stop, at base resolution.

    The Cas9 problem is the reason this exists, and not for the reason it first appears.
    The baseline aligned the whole library itself and planned exactly this analysis in its
    own words. It then wrote `R[$4+ref]++` for a trailing soft clip, where the last aligned
    base is `$4+ref-1`. Its measurement therefore landed on 46,373,179; so did its
    independent PAM calculation; the two agreed and neither was checked. Computed
    correctly, every signature falls on 46,373,178: 108 reads begin there, 121 end there,
    188 are clipped there.

    The failure is not knowing what to compute. It is re-deriving it in awk under a step
    budget, where an off-by-one is invisible and a second method carrying a compatible
    error looks like confirmation.

    The same statistic locates fusion junctions, viral integration sites and structural
    variants: all of them are questions about where reads stop agreeing with the
    reference, and none of them can be answered without one.
    """
    fastqs = [Path(f) for f in args.fastq]
    missing = [str(f) for f in fastqs if not f.is_file()]
    if missing:
        print(f"no such file: {', '.join(missing)}", file=sys.stderr)
        return 2
    try:
        bam = references.align_to_bam(fastqs, args.reference, threads=args.threads,
                                      timeout=args.timeout)
        evidence = breakpoints.scan_bam(bam, region=args.region,
                                        min_mapq=args.min_mapq)
    except RuntimeError as exc:
        print(str(exc), file=sys.stderr)
        return 4

    found = breakpoints.consensus(evidence, k=args.top)
    result = {
        "bam": str(bam),
        "reference": args.reference,
        "reads_scanned": evidence["n_reads"],
        "breakpoints": found,
        "note": ("positions are 1-based; `pos` is the last reference base covered before "
                 "the break. A blunt cut is named either by that base or by the next "
                 "one, so state which convention you used."),
    }
    result["competence"] = breakpoints.competence_for(found).explain()
    emit(result)
    return 0


def cmd_variants(args: argparse.Namespace) -> int:
    """Report the substitutions and indels the reads support, with depth and fraction.

    The companion failure to `breakpoints`. On the TP53 problem the baseline ran bwa,
    `samtools mpileup` and `bcftools` correctly, then selected a substitution carried by
    two reads in a library averaging 21.5x over the gene, annotated it correctly as
    `c.128T>A (p.Leu43Ter)` and answered codon 43. Its annotation was right; two reads is
    the sequencing-error floor. Ten positions in the same gene exceed a fraction of 0.15.

    So candidates are ranked by support and anything below the floor is not shown, and the
    competence field says when depth is too low for the question to be answerable at all.
    Indels are ranked alongside substitutions, because a frameshift is the most common way
    a coding sequence is truncated and a substitution-only caller cannot see one.
    """
    fastqs = [Path(f) for f in args.fastq]
    missing = [str(f) for f in fastqs if not f.is_file()]
    if missing:
        print(f"no such file: {', '.join(missing)}", file=sys.stderr)
        return 2
    try:
        reference = references.find_reference(args.reference)
        if reference is None:
            raise RuntimeError(f"reference {args.reference!r} is not staged here")
        bam = references.align_to_bam(fastqs, args.reference, threads=args.threads,
                                      timeout=args.timeout)
        lines = variants.pileup(bam, reference, region=args.region)
    except RuntimeError as exc:
        print(str(exc), file=sys.stderr)
        return 4

    calls = variants.call_variants(lines, min_depth=args.min_depth, min_af=args.min_af)
    depths = [int(l.split("\t")[3]) for l in lines if len(l.split("\t")) > 3]
    median_depth = sorted(depths)[len(depths) // 2] if depths else 0
    result = {
        "bam": str(bam), "region": args.region or "whole genome",
        "positions_examined": len(lines), "median_depth": median_depth,
        "variants": calls[:args.top],
        "note": (f"allele fraction is alt reads over reads actually called at that base; "
                 f"calls below {args.min_af} fraction or {args.min_depth}x depth are not "
                 f"shown because they are not separable from sequencing error"),
    }
    result["competence"] = variants.competence_for(calls, median_depth).explain()
    emit(result)
    return 0


def build_parser() -> argparse.ArgumentParser:
    """Command-line interface. Kept flat so an agent can discover it from `--help`."""
    ap = argparse.ArgumentParser(prog="biotool", description=__doc__.split("\n")[0])
    sub = ap.add_subparsers(dest="cmd", required=True)

    p_list = sub.add_parser("list", help="show permitted tools and models")
    p_list.set_defaults(func=cmd_list)

    p_call = sub.add_parser("call", help="invoke a permitted annotation tool")
    p_call.add_argument("name")
    p_call.add_argument("arguments", nargs="?", default="{}")
    p_call.add_argument("--max-chars", type=int, default=4000)
    p_call.set_defaults(func=cmd_call)

    p_ct = sub.add_parser("celltype", help="predict a cell type with Cell2Sentence")
    p_ct.add_argument("--genes",
                      help="comma-separated gene symbols, highest expression first")
    p_ct.add_argument("--matrix", help=".h5ad file or 10x matrix directory")
    p_ct.add_argument("--model", default="celltypist",
                      help="celltypist (default; scores every cell in seconds), "
                           "c2s-celltype (one forward pass per cell -- slow), or all. "
                           "A second opinion is valuable but c2s costs ~40s per cell, so "
                           "it is opt-in rather than default.")
    p_ct.add_argument("--organism", default="human")
    p_ct.add_argument("--n-cells", type=int, default=8,
                      help="cells to sample for the per-cell composition")
    p_ct.set_defaults(func=cmd_celltype)

    p_tx = sub.add_parser("taxonomy",
                          help="identify the source organism of sequences by BLAST")
    p_tx.add_argument("--fasta", required=True, help="query sequences (keep it small)")
    p_tx.add_argument("--top", type=int, default=5)
    p_tx.add_argument("--timeout", type=int, default=600)
    p_tx.set_defaults(func=cmd_taxonomy)

    p_ref = sub.add_parser("references", help="list staged reference genomes")
    p_ref.set_defaults(func=cmd_references)

    p_al = sub.add_parser("align",
                          help="align reads to a staged reference and report top loci")
    p_al.add_argument("--fastq", required=True)
    p_al.add_argument("--reference", default="hg38-ml")
    p_al.add_argument("--n-reads", type=int, default=20_000)
    p_al.set_defaults(func=cmd_align)

    p_bp = sub.add_parser(
        "breakpoints",
        help="find where reads stop matching the reference (cut sites, fusions)")
    p_bp.add_argument("--fastq", required=True, nargs="+",
                      help="one or two read files; pairs improve junction support")
    p_bp.add_argument("--reference", default="hg38-ml")
    p_bp.add_argument("--region", help="chr:start-end; omit to search the whole genome")
    p_bp.add_argument("--top", type=int, default=10)
    p_bp.add_argument("--threads", type=int, default=8)
    p_bp.add_argument("--min-mapq", type=int, default=20)
    p_bp.add_argument("--timeout", type=int, default=7200)
    p_bp.set_defaults(func=cmd_breakpoints)

    p_var = sub.add_parser(
        "variants",
        help="substitutions and indels the reads support, ranked by depth and "
             "allele fraction")
    p_var.add_argument("--fastq", required=True, nargs="+")
    p_var.add_argument("--reference", default="hg38-ml")
    p_var.add_argument("--region", help="chr:start-end; strongly recommended")
    p_var.add_argument("--min-depth", type=int, default=10)
    p_var.add_argument("--min-af", type=float, default=0.2)
    p_var.add_argument("--top", type=int, default=25)
    p_var.add_argument("--threads", type=int, default=8)
    p_var.add_argument("--timeout", type=int, default=7200)
    p_var.set_defaults(func=cmd_variants)
    return ap


def main(argv: list[str] | None = None) -> int:
    """Entry point."""
    args = build_parser().parse_args(argv)
    return args.func(args)


if __name__ == "__main__":
    raise SystemExit(main())