fasta_lake.entrapment_workflow#
fasta_lake.entrapment_workflow
#
End-to-end entrapment workflow: generate -> inject -> measure FDP.
This module is the file-level, streaming counterpart to :mod:fasta_lake.entrapment
(which holds the in-memory library primitives). It exists so that a user can run a
complete entrapment experiment from the command line::
fasta-lake entrapment classes
fasta-lake entrapment generate --class shuffled -i lake.fasta -o entrap.fasta
fasta-lake entrapment inject -d lake.fasta -e entrap.fasta -o augmented.fasta
# ... run the pipeline against augmented.fasta, then search ...
fasta-lake entrapment fdp --results-dir results/ --target-fasta lake.fasta
Injection stage is the whole ballgame
Entrapment can enter at four distinct points, and they answer different
questions. The stage is explicit everywhere: a CLI flag, a field in the manifest,
and a column in the per-sample output. See :mod:fasta_lake.entrapment_stages for
the full definitions and the run script implementing each.
prelake input lake, before the cohort evidence filter -- construction error
prebuild clustered lake + entrapment, re-clustered -- construction error
preselect clustered lake + entrapment, no re-clustering (DEFAULT) -- construction
appended finished per-sample database, after parsimony -- SEARCH error
prebuild and preselect are not the same stage under two names: they
differ by whether entrapment had to survive clustering. All are legitimate, none
are the same quantity; this module refuses to pool across stages (or across
entrapment classes) without an explicit override.
Prefix conventions are not uniform
This repository tags entrapment at least three incompatible ways --
ENTRAP_PFUR_/ENTRAP_SHUF_/… , ENTRAPHUMAN_ (SIHUMIx) and ENTRAPNN_
(near-neighbour). The latter two do not match ENTRAP_, so a matcher hard-coded
to that convention scores them as target and drives the FDP toward zero silently.
The matcher here defaults to the common denominator ENTRAP, is configurable,
records which pattern it used, and refuses to compute an FDP when a declared
entrapment partition is invisible to the configured pattern
(:class:PrefixMismatchError).
The conserved-peptide problem
A peptide attributed to an entrapment protein may also genuinely occur in the
target sequence space -- universally conserved machinery such as ribosomal
proteins, elongation factors, chaperones and glycolytic enzymes is shared across
all of life. Matching one of those is not a false discovery, and counting it as one
inflates the FDP of any class with real homology pressure. Every FDP this module
reports therefore comes in a pair: raw and conserved-corrected, always
together, never one alone. See :func:conserved_peptide_scan.
Estimators
Several FDP estimators are in circulation and their names collide across the
literature and across this codebase. Each is spelled out here, and each returns
None -- never 0.0 -- when its denominator is undefined.
fdp_uncorrected E / (E + T)
fdp_wen_equal_odds 2E / (E + T) -- valid only when r ~ 1
fdp_elias_gygi E(N_T/N_E) / (E(N_T/N_E) + T)
fdp_lower_bound E / T -- proves failure, never success
fdp_shared_sensitivity (E + S) / (E + S + T) -- S maps to both partitions
fdp_combined_noble E(1 + 1/r) / (T + E), r = N_E/N_T
References
- Wen B, Keich U, Noble WS et al. (2025). Nat Methods 22, 1454-1463.
- Elias JE & Gygi SP (2007). Nat Methods 4, 207-214.
PrefixMismatchError
#
Bases: ValueError
The configured entrapment prefix matched nothing that was declared present.
This is a distinct failure cause from "no entrapment was detected". A prefix mismatch silently reclassifies every entrapment record as target and drives the FDP toward zero while the run completes and the output looks like a pass. It must stop the pipeline, not produce a number.
Source code in fasta_lake/entrapment_workflow.py
GenerateStats
dataclass
#
Summary of an entrapment-generation run.
Source code in fasta_lake/entrapment_workflow.py
PsmCounts
dataclass
#
Entrapment / target / shared PSM counts for one search result file.
Source code in fasta_lake/entrapment_workflow.py
ConservedScan
dataclass
#
Which entrapment-attributed peptides also occur in the target space.
conserved maps a peptide to the target protein IDs it was found in, so a
user can see what is being shared rather than being handed a bare fraction.
control_conserved is the negative control: the same test run on the
reversed entrapment peptides. A reversed peptide has the same composition
and length but is not a real conserved sequence, so it should almost never be
found. If the control rate approaches the real rate, the matcher is picking up
chance matches and the correction is not trustworthy.
Source code in fasta_lake/entrapment_workflow.py
stage_measures
#
iter_fasta
#
Stream (header, sequence) pairs from a FASTA file.
The header is returned verbatim without the leading >. Nothing is held in
memory beyond one record, so this is safe on multi-hundred-million-sequence
lakes.
Source code in fasta_lake/entrapment_workflow.py
count_fasta_headers
#
Count proteins in a FASTA by counting header lines only.
This is deliberately not grep -cv '^>ENTRAP_'. That idiom counts every line
that is not an entrapment header -- including all sequence lines -- and inflates
protein counts by roughly the mean number of sequence lines per record
(measured at 8.45x on a real per-sample database in this project, 122,189 lines
against 14,465 proteins). Every count in this module goes through this function.
Source code in fasta_lake/entrapment_workflow.py
partition_counts
#
Return (n_target, n_entrapment) protein counts for a FASTA.
Both counts come from header lines only; n_target never counts sequence
lines.
Source code in fasta_lake/entrapment_workflow.py
detect_prefixes
#
Report the entrapment-like prefixes actually present in a FASTA.
Scans header accession tokens for any that contain candidate (case
insensitive) and reports the distinct prefixes found with their counts, so a
convention mismatch is visible before it becomes a published number rather
than after.
Returns n_headers, n_matching_default, observed (prefix -> count)
and known (which observed prefixes are conventions this repo already uses).
Source code in fasta_lake/entrapment_workflow.py
verify_prefix_matches
#
verify_prefix_matches(path: str | Path, prefix: str, declared_n_entrapment: int, context: str = '') -> int
Assert the configured prefix finds the entrapment partition that is declared.
Returns the observed entrapment header count. Raises
:class:PrefixMismatchError when declared_n_entrapment > 0 but scanning
with prefix finds none -- that combination can only mean the prefix is
wrong for this file, and continuing would report a spuriously low FDP.
Note what this does not flag: zero entrapment hits against a populated entrapment partition is a genuine, desirable 0% result and is left alone. The check is on the database partition, not on the discoveries.
Source code in fasta_lake/entrapment_workflow.py
shuffle_sequence
#
Shuffle a sequence, optionally holding K/R residues in place.
Holding lysine and arginine fixed keeps every tryptic cleavage site where it was, so each entrapment protein yields peptides whose lengths match its source protein's one for one, while sharing none of their order.
A naive full shuffle preserves the K/R count per protein, so the aggregate peptide-length distribution comes out about the same (measured on the 512-protein P. furiosus panel: mean tryptic length 6.80 source vs 6.79 naive). What it does not preserve is the per-protein match: the same measurement found the naive shuffle reproduced a protein's exact tryptic length multiset for 1 of 512 proteins (0.2%), against 512 of 512 (100%) when K/R are held. Per-protein matching is what makes each entrapment sequence a paired null for its source.
Source code in fasta_lake/entrapment_workflow.py
generate_entrapment_fasta
#
generate_entrapment_fasta(output_fasta: str | Path, entrap_class: str = 'shuffled', source_fasta: str | Path | None = None, seed: int = 42, n_proteins: int | None = None, prefix: str | None = None, preserve_cleavage_sites: bool = True) -> GenerateStats
Write an entrapment FASTA for one entrapment class.
Deterministic: the same class, seed and input file produce a byte-identical output file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_fasta
|
str | Path
|
Destination. Headers are written as |
required |
entrap_class
|
str
|
A key of :data: |
'shuffled'
|
source_fasta
|
str | Path | None
|
For |
None
|
seed
|
int
|
Random seed. Used for shuffling and for subsampling when |
42
|
n_proteins
|
int | None
|
If set, write only this many proteins, chosen by seeded random subsample.
If |
None
|
prefix
|
str | None
|
Override the class's header prefix. Defaults to the class prefix. |
None
|
preserve_cleavage_sites
|
bool
|
Hold K/R in place while shuffling. Default |
True
|
Source code in fasta_lake/entrapment_workflow.py
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 | |
inject_entrapment
#
inject_entrapment(database_fasta: str | Path, entrapment_fasta: str | Path, output_fasta: str | Path, stage: str = STAGE_PRESELECT, entrap_class: str | None = None, seed: int | None = None, prefix: str | None = None, manifest_path: str | Path | None = None, checksums: bool = True) -> dict
Concatenate entrapment into a database and record what was done.
Writes output_fasta (target records first, then entrapment) and a JSON
manifest recording the class, the stage, the seed, the entrapment:target ratio
and the counts. The manifest is what makes a downstream FDP number
interpretable -- without it, a result file cannot be told apart from one
produced at the other injection stage or from another class.
Returns the manifest as a dict.
Source code in fasta_lake/entrapment_workflow.py
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 | |
load_manifests
#
Load entrapment manifests, refusing to mix injection stages or classes.
Returns ({'stage': ..., 'class': ...}, manifests). Raises ValueError
when the manifests disagree, unless allow_mixed is set: pre-selection and
appended FDPs measure different quantities, and so do different entrapment
classes, so pooling them produces a number that means nothing.
Source code in fasta_lake/entrapment_workflow.py
strip_modifications
#
Reduce a modified peptide string to bare uppercase residues.
SAGE writes M[+15.9949]-style annotations in the peptide column; the
residue count and any sequence matching must be done on the stripped form.
Source code in fasta_lake/entrapment_workflow.py
classify_psms
#
classify_psms(results_tsv: str | Path, prefix: str = ENTRAP_PREFIX, q_threshold: float = 0.01, min_length: int = 9, q_column: str = 'peptide_q', decoy_prefix: str = 'rev_') -> PsmCounts
Classify accepted PSMs into target / entrapment / shared.
Decoys are identified from the search engine's own label column (SAGE
writes 1 for target, -1 for decoy) whenever that column exists. Only if
it is absent do we fall back to a header-prefix test, and then a warning is
emitted -- a hard-coded prefix assumption (DECOY_ where the engine actually
writes rev_) has silently corrupted results in this project before.
Decoys are counted separately and are never folded into the target count; doing so inflates the FDP denominator and biases the estimate down.
A PSM whose peptide maps to both an entrapment and a target protein is counted
as shared rather than being silently dropped, so a sensitivity bound that
treats shared as entrapment can be reported alongside the headline.
When a rank column is supplied, only positive-integer rank-one rows enter the counts. Legacy tables without rank remain supported; their caller must establish that the input contains only winning PSMs. Invalid q values are excluded from both target and control discoveries.
Source code in fasta_lake/entrapment_workflow.py
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 | |
conserved_peptide_scan
#
conserved_peptide_scan(peptides: set[str] | list[str], target_fasta: str | Path, normalize_il: bool = True, max_proteins_per_peptide: int = 5, run_control: bool = True, control_warn_ratio: float = 0.25) -> ConservedScan
Test entrapment-attributed peptides for occurrence in the target space.
Builds one Aho-Corasick automaton over the (small) peptide set and streams the (large) target FASTA past it, so cost is one pass over the database regardless of how many peptides are tested. Matching is exact substring on the stripped residue string, optionally with I/L normalised -- leucine and isoleucine are isobaric and indistinguishable by mass spectrometry, so treating them as distinct would call a genuinely shared peptide class-specific.
A peptide found in the target space is a conserved hit: it is a real identification that happens also to occur in the entrapment organism, not a false discovery. Subtracting these gives the conserved-corrected FDP.
The reversed-peptide negative control runs in the same pass.
Source code in fasta_lake/entrapment_workflow.py
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 | |
write_conserved_report
#
write_conserved_report(scan: ConservedScan, path: str | Path) -> Path
Write the conserved peptides and their target proteins to TSV.
Source code in fasta_lake/entrapment_workflow.py
fdp_estimates
#
fdp_estimates(entrap: int, target: int, shared: int = 0, db_target: int | None = None, db_entrap: int | None = None) -> dict
Compute every FDP estimator, returning None where undefined.
An FDP of 0.0 reported from an undefined denominator is not an "honest
zero" -- it is the most favourable value the statistic can take, standing in
for a measurement that was never possible. In this project 52.6% of samples in
one arm had zero entrapment sequences in the searched database and were
reported as 0.000%. Every estimator here returns None in that situation,
and callers report coverage separately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entrap
|
int
|
Accepted PSM (or peptide) counts by class. |
required |
target
|
int
|
Accepted PSM (or peptide) counts by class. |
required |
shared
|
int
|
Accepted PSM (or peptide) counts by class. |
required |
db_target
|
int | None
|
Protein counts of the two partitions of the searched database, from
header lines only. Needed for the size-corrected estimators; pass |
None
|
db_entrap
|
int | None
|
Protein counts of the two partitions of the searched database, from
header lines only. Needed for the size-corrected estimators; pass |
None
|
Source code in fasta_lake/entrapment_workflow.py
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 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 | |
bootstrap_median_ci
#
bootstrap_median_ci(values: list[float], seed: int = 42, n_draws: int = 2000, alpha: float = 0.05) -> tuple[float, float]
Seeded percentile bootstrap CI on the median.
Returns (nan, nan) when n <= 5 -- a bootstrap CI on five or fewer
observations is not informative and reporting one implies precision that is not
there. Deterministic for a given seed.
Source code in fasta_lake/entrapment_workflow.py
summarize
#
n, median, IQR and a seeded bootstrap CI for a list of per-sample values.
Source code in fasta_lake/entrapment_workflow.py
expected_results_subdir
#
The per-sample subdirectory the run templates write for an entrapment class.
tune and diagnose document the layout SAMPLE/entrapment/ for the
shuffled class and SAMPLE/entrapment_<class>/ for every other class.
Source code in fasta_lake/entrapment_workflow.py
find_sample_results
#
find_sample_results(results_dir: str | Path, results_name: str = 'results.sage.tsv', prefer_subdir: str | None = None) -> list[tuple[str, Path]]
Find (sample_id, results_tsv) under results_dir.
Accepts either results_dir/SAMPLE/results.sage.tsv or the same file one
level deeper (results_dir/SAMPLE/sage/results.sage.tsv), which is the layout
some cluster job layouts write.
A sample directory may hold several entrapment runs side by side
(entrapment/, entrapment_plant/, entrapment_archaea/). When more
than one nested candidate exists, the one in prefer_subdir is used; if
that does not single out one file the sample is refused with the candidates
listed, because silently taking the first would label one class's search
results with another class's name.
Source code in fasta_lake/entrapment_workflow.py
compute_fdp
#
compute_fdp(results_dir: str | Path, dataset: str = '', entrap_class: str | None = None, stage: str | None = None, prefix: str | None = None, target_fasta: str | Path | None = None, q_threshold: float = 0.01, min_length: int = 9, q_column: str = 'peptide_q', decoy_prefix: str = 'rev_', db_pattern: str | None = None, results_name: str = 'results.sage.tsv', seed: int = 42, n_draws: int = 2000, peptide_level: bool = False, allow_mixed: bool = False, conserved_check: bool = True, normalize_il: bool = True) -> dict
Compute one FDP record for a (dataset, class, stage) triple.
Reads any entrapment_manifest.json found beside the results to recover the
class and injection stage, and refuses to pool samples that differ in either.
Reports how many samples were evaluable and how many had an empty
entrapment partition, so an undefined estimate can never be read as a zero.
When target_fasta is given, every entrapment-attributed peptide is tested
for occurrence in the target sequence space and both the raw and the
conserved-corrected FDP are returned. For a class with real homology pressure
the correction is mandatory: reporting the raw number alone would present
genuinely conserved peptides as false discoveries.
Source code in fasta_lake/entrapment_workflow.py
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 | |
write_fdp_reports
#
Write the per-sample TSV, the (dataset, class, stage) record, and conserved peptides.
Source code in fasta_lake/entrapment_workflow.py
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 | |
prepare_from_config
#
Honour entrapment.enabled in a FastaLake JSON config.
Given a loaded :class:~fasta_lake.config.FastaLakeConfig (or anything with an
.entrapment attribute) and the database about to be used, generate the
configured entrapment and inject it, returning the manifest. Returns None
when entrapment is disabled, in which case the caller uses database_fasta
unchanged.
This is the function that makes "entrapment": {"enabled": true} in a config
JSON actually do something.