API Reference¶
This page documents all public functions and objects in papa2. Each module's docstrings are rendered directly from the source.
papa2.dada — Core Denoising¶
The main denoising module. Provides the high-level dada() and learn_errors()
functions as well as the global options dictionary.
DADA_OPTS¶
Global dictionary of algorithmic parameters used by dada(). Modify with
set_dada_opt() or pass keyword arguments directly to dada().
| Parameter | Default | Description |
|---|---|---|
OMEGA_A |
1e-40 |
Significance threshold for accepting new ASVs |
OMEGA_P |
1e-4 |
Significance threshold for prior-guided detection |
OMEGA_C |
1e-40 |
Significance threshold for combining ASVs |
DETECT_SINGLETONS |
False |
Detect singleton ASVs |
USE_KMERS |
True |
Use k-mer screen before alignment |
KDIST_CUTOFF |
0.42 |
K-mer distance cutoff |
MAX_CONSIST |
10 |
Maximum self-consistency iterations |
MATCH |
5 |
NW match score |
MISMATCH |
-4 |
NW mismatch penalty |
GAP_PENALTY |
-8 |
NW gap penalty |
BAND_SIZE |
16 |
Banded alignment width |
VECTORIZED_ALIGNMENT |
True |
Use vectorized (SSE) alignment |
MAX_CLUST |
0 |
Maximum clusters (0 = unlimited) |
MIN_FOLD |
1 |
Minimum fold-abundance for parent |
MIN_HAMMING |
1 |
Minimum Hamming distance from parent |
MIN_ABUNDANCE |
1 |
Minimum read abundance to consider |
USE_QUALS |
True |
Incorporate quality scores |
HOMOPOLYMER_GAP_PENALTY |
None |
Override gap penalty in homopolymer runs |
SSE |
2 |
SSE level (0=off, 1=SSE2, 2=SSE4.1) |
GAPLESS |
True |
Prefer gapless alignments |
GREEDY |
True |
Use greedy clustering |
PSEUDO_ABUNDANCE |
inf |
Total abundance for a sequence to become a pseudo-pooling prior |
PSEUDO_PREVALENCE |
2 |
Number of samples a sequence must appear in to become a pseudo-pooling prior |
dada¶
dada(derep, err=None, error_estimation_function=None, self_consist=False, pool=False, priors=None, verbose=True, **opts)
¶
Run DADA2 denoising on one or more dereplicated samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
derep
|
dict from derep_fastq(), or list of dicts, or FASTQ filepath(s) |
required | |
err
|
numpy array (16, ncol) error matrix, or None for self-consistent learning |
None
|
|
error_estimation_function
|
callable(trans) -> err_matrix, default loess_errfun |
None
|
|
self_consist
|
bool, iterate until error model converges |
False
|
|
pool
|
False (default) processes samples independently; True pools all samples into one inference (R's pool=TRUE, including the per-sample expansion of the pooled result); "pseudo" runs R's pseudo-pooling (a second pass with the first pass's consistently-observed sequences as priors, controlled by PSEUDO_PREVALENCE / PSEUDO_ABUNDANCE). |
False
|
|
priors
|
sequences with prior evidence of existence (R's priors); they are evaluated against OMEGA_P instead of OMEGA_A |
None
|
|
verbose
|
bool |
True
|
Returns:
| Type | Description |
|---|---|
|
dict (single sample) or list of dicts, each with: denoised: dict {seq: abundance} cluster_seqs, cluster_abunds, trans, map, pval, err_in, err_out |
Environment variables
DADA2_CORES: total cores to plan for (default: os.cpu_count(); set this under containers/schedulers that allocate fewer) DADA2_WORKERS: number of sample-level worker processes (0 = auto-detect, default) DADA2_OMP_THREADS: OpenMP threads per worker for the within-sample comparison loop (0 = auto: cores split evenly across workers)
Source code in papa2/dada.py
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 | |
learn_errors¶
learn_errors(fastq_files, nbases=100000000.0, error_estimation_function=None, verbose=True, **opts)
¶
Learn error rates from FASTQ files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fastq_files
|
list of FASTQ file paths |
required | |
nbases
|
target number of bases to use for learning |
100000000.0
|
|
error_estimation_function
|
callable, default loess_errfun |
None
|
|
verbose
|
bool |
True
|
Returns:
| Type | Description |
|---|---|
|
numpy array (16, ncol) of learned error rates |
Source code in papa2/dada.py
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 | |
set_dada_opt¶
set_dada_opt(**kwargs)
¶
get_dada_opt¶
get_dada_opt(key=None)
¶
papa2.io — FASTQ I/O¶
FASTQ reading and dereplication.
derep_fastq¶
derep_fastq(filepath, verbose=False, with_map=False, multithread=True, quality_type='Auto')
¶
Dereplicate a FASTQ file (or a list of them).
Uses C implementation (zlib) when available for ~2x speedup. Always returns the per-read map (read_idx -> unique_idx). The with_map parameter is accepted for backward compatibility but ignored.
A list of paths returns a list of results; with multithread (default) the files are processed in a worker pool.
quality_type follows R: "Auto" (default) detects Phred+33 vs Phred+64 per file with ShortRead's rule; "FastqQuality" and "SFastqQuality" force the offset.
Returns:
| Type | Description |
|---|---|
|
dict with keys: seqs: list[str], unique sequences sorted by abundance (descending) abundances: numpy int32 array quals: numpy float64 array (n_uniques x max_seqlen), average quality map: numpy int32 array, maps each read to its unique index (0-indexed) |
Source code in papa2/io.py
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 | |
combine_dereps¶
combine_dereps(dereps)
¶
Combine multiple derep results into one pooled derep.
Exact port of R's dada2:::combineDereps2: unique sequences keep first-appearance order across samples, counts are summed, quality profiles are abundance-weighted means accumulated in sample order, the combined uniques are re-sorted by decreasing abundance (stable, like R's order()), and the concatenated per-read map is remapped accordingly.
Source code in papa2/io.py
papa2.filter — Filtering and Trimming¶
Quality filtering, trimming, and PhiX removal for FASTQ files.
filter_and_trim¶
filter_and_trim(fwd, filt, rev=None, filt_rev=None, *, trim_left=0, trim_right=0, trunc_len=0, trunc_q=2, max_len=0, min_len=20, max_n=0, min_q=0, max_ee=float('inf'), rm_phix=True, rm_lowcomplex=0.0, orient_fwd=None, match_ids=False, id_sep='\\s', id_field=None, compress=True, n=1000000, quality_type='Auto', multithread=False, verbose=False)
¶
Filter and trim FASTQ files (single- or paired-end).
This is a convenience wrapper around :func:fastq_filter (single-end)
and :func:fastq_paired_filter (paired-end). It dispatches to the
appropriate function based on whether rev is provided and optionally
parallelises across files with
:class:~concurrent.futures.ProcessPoolExecutor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fwd
|
Union[str, Sequence[str]]
|
Path(s) to forward (or single-end) input FASTQ file(s). |
required |
filt
|
Union[str, Sequence[str]]
|
Path(s) to filtered output FASTQ file(s), same length as
|
required |
rev
|
Optional[Union[str, Sequence[str]]]
|
Path(s) to reverse-read input FASTQ file(s), or |
None
|
filt_rev
|
Optional[Union[str, Sequence[str]]]
|
Path(s) to filtered reverse-read output FASTQ file(s).
Required when |
None
|
multithread
|
Union[bool, int]
|
|
False
|
verbose
|
bool
|
Print per-file summaries. |
False
|
All other parameters are forwarded — see :func:fastq_filter and
:func:fastq_paired_filter. Defaults match R's filterAndTrim
(in particular trunc_q=2).
Returns:
| Type | Description |
|---|---|
ndarray
|
Integer array of shape |
ndarray
|
|
Source code in papa2/filter.py
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 | |
fastq_filter¶
fastq_filter(fn, fout, *, trim_left=0, trim_right=0, trunc_len=0, trunc_q=2, max_len=0, min_len=20, max_n=0, min_q=0, max_ee=float('inf'), rm_phix=True, rm_lowcomplex=0.0, orient_fwd=None, compress=True, n=1000000, quality_type='Auto', verbose=False)
¶
Filter and trim a single FASTQ file (mirrors R's fastqFilter).
Order of operations (identical to R): orient_fwd, max_len, trim_left,
trim_right, trunc_q, trunc_len, min_len, max_n, min_q, max_ee,
rm_phix, rm_lowcomplex. Note that trunc_len counts bases from the
original 5' end of the read: with trim_left=10, trunc_len=240
the output reads are 230 bases long.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
str
|
Input FASTQ path (plain or gzipped). |
required |
fout
|
str
|
Output FASTQ path. |
required |
trim_left
|
int
|
Bases to trim from the 5' end. Reads shorter than
|
0
|
trim_right
|
int
|
Bases to trim from the 3' end. Reads with no bases left are discarded. |
0
|
trunc_len
|
int
|
Truncate reads at this position (counted from the original 5' end). Shorter reads are discarded. 0 disables. |
0
|
trunc_q
|
Optional[int]
|
Truncate at the first base with quality <= this value.
|
2
|
max_len
|
float
|
Discard reads longer than this before trimming. 0 or
|
0
|
min_len
|
int
|
Discard reads shorter than this after all trimming. |
20
|
max_n
|
int
|
Maximum number of non-ACGT bases allowed. |
0
|
min_q
|
int
|
After truncation, discard reads whose minimum quality is
not strictly greater than this. Only applied when
|
0
|
max_ee
|
float
|
Maximum expected errors ( |
float('inf')
|
rm_phix
|
bool
|
Remove reads matching the PhiX genome. |
True
|
rm_lowcomplex
|
float
|
Remove reads with sequence complexity below this. 0 disables. |
0.0
|
orient_fwd
|
Optional[str]
|
If set, keep only reads that begin with this sequence in forward or reverse-complement orientation, re-orienting the latter. Within each chunk, forward-matching reads are output before re-oriented ones (R's behaviour). |
None
|
compress
|
bool
|
Gzip-compress the output. |
True
|
n
|
int
|
Number of records processed per chunk (R's |
1000000
|
quality_type
|
str
|
"Auto" (default; per-chunk detection matching ShortRead), "FastqQuality" (Phred+33) or "SFastqQuality" (Phred+64). |
'Auto'
|
verbose
|
bool
|
Print a summary line when done. |
False
|
Returns:
| Type | Description |
|---|---|
Tuple[int, int]
|
|
Source code in papa2/filter.py
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 | |
fastq_paired_filter¶
fastq_paired_filter(fwd, filt_fwd, rev, filt_rev, *, trim_left=(0, 0), trim_right=(0, 0), trunc_len=(0, 0), trunc_q=2, max_len=(0, 0), min_len=(20, 20), max_n=(0, 0), min_q=(0, 0), max_ee=(float('inf'), float('inf')), rm_phix=True, rm_lowcomplex=(0.0, 0.0), orient_fwd=None, match_ids=False, id_sep='\\s', id_field=None, compress=True, n=1000000, quality_type='Auto', verbose=False)
¶
Filter and trim paired FASTQ files (mirrors R's fastqPairedFilter).
With match_ids (R's matchIDs), reads are re-paired by sequence
identifier: the id field (auto-detected CASAVA format, or
id_field, 0-based) is compared between files, reads present in
only one file are dropped, and unmatched tails of each chunk carry
over to the next chunk exactly as in R.
Both reads of a pair must pass all filters for the pair to be kept.
Parameters accept scalars (applied to both) or (fwd, rev) tuples.
See :func:fastq_filter for per-parameter documentation; the order of
operations and boundary behaviour match R exactly, including:
trunc_lencounting from the original 5' end of each read.orient_fwd: pairs whose reverse read starts with the primer have their forward/reverse reads swapped (not reverse-complemented); pairs matching in neither read are discarded. Within each chunk, forward-matching pairs are output before swapped pairs.rm_phix: a pair is discarded when either read matches PhiX (when enabled for both reads).
Returns:
| Type | Description |
|---|---|
Tuple[int, int]
|
|
Source code in papa2/filter.py
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 1075 1076 1077 1078 1079 1080 | |
papa2.error — Error Models¶
Functions for estimating and manipulating the DADA2 error rate matrix.
loess_errfun¶
loess_errfun(trans)
¶
Estimate error rates from transition counts using LOESS smoothing.
Mirrors R's loessErrfun from errorModels.R.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trans
|
numpy array (16, ncol), transition counts. Rows are transitions (A2A,A2C,...,T2T), columns are quality scores. |
required |
Returns:
| Type | Description |
|---|---|
|
numpy array (16, ncol), estimated error rates. |
Source code in papa2/error.py
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 | |
noqual_errfun¶
noqual_errfun(trans)
¶
Error estimation ignoring quality scores (constant across Q).
Source code in papa2/error.py
inflate_err¶
inflate_err(err, inflation)
¶
Inflate error rates by a factor (prevents premature convergence).
Mirrors R's inflateErr.
pacbio_errfun¶
pacbio_errfun(trans)
¶
PacBio-specific error function.
Mirrors R's PacBioErrfun from errorModels.R.
Quality score 93 (the last column, if present) is handled separately
using a simple MLE with pseudocount: (count + 1) / (total + 4).
All other quality scores are fit using loess_errfun.
If Q93 is not present (i.e. the transition matrix does not extend to
quality 93), the function falls back entirely to loess_errfun.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trans
|
numpy array (16, ncol), transition counts. |
required |
Returns:
| Type | Description |
|---|---|
|
numpy array (16, ncol), estimated error rates. |
Source code in papa2/error.py
make_binned_qual_errfun¶
make_binned_qual_errfun(binned_q)
¶
Return an error function that uses piecewise linear interpolation.
Mirrors R's dada2:::make.binned.qual.errfun.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binned_q
|
array-like of quality score bin boundaries (sorted, ascending). These are the quality score values at which the error rates are "known" (from the transition matrix columns). Between bins, error rates are linearly interpolated. |
required |
Returns:
| Type | Description |
|---|---|
|
A callable |
|
|
matrix and returns a 16-row error rate matrix, using piecewise |
|
|
linear interpolation between the binned quality scores. |
Source code in papa2/error.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 | |
get_initial_err¶
get_initial_err(ncol=41)
¶
papa2.paired — Paired-End Merging¶
High-level paired-read merging, mirroring R's mergePairs().
merge_pairs¶
merge_pairs(dadaF, derepF, dadaR, derepR, min_overlap=12, max_mismatch=0, return_rejects=False, trim_overhang=False, just_concatenate=False, verbose=False)
¶
Merge denoised forward and reverse reads into full amplicon sequences.
Mirrors the R dada2::mergePairs() function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dadaF
|
dict from dada() with keys 'denoised', 'cluster_seqs', 'cluster_abunds', 'map' (0-indexed cluster assignment per unique). |
required | |
derepF
|
dict from derep_fastq() with key 'map' (0-indexed unique assignment per read). |
required | |
dadaR
|
same structure as dadaF, for reverse reads. |
required | |
derepR
|
same structure as derepF, for reverse reads. |
required | |
min_overlap
|
minimum overlap required for merging (default 12). |
12
|
|
max_mismatch
|
maximum mismatches allowed in the overlap (default 0). |
0
|
|
return_rejects
|
if True, rejected pairs are kept in the output with 'accept': False and an empty sequence (R's returnRejects). |
False
|
|
trim_overhang
|
if True, trim overhanging ends of the merged sequence (default False). |
False
|
|
just_concatenate
|
if True, concatenate rather than merge (inserts 10 Ns between forward and reverse; default False). |
False
|
|
verbose
|
print progress information (default False). |
False
|
Returns:
| Type | Description |
|---|---|
|
List of dicts sorted by abundance (descending), each with keys: 'sequence': merged sequence (str) 'abundance': number of reads supporting this pair 'forward': 0-indexed forward cluster index 'reverse': 0-indexed reverse cluster index 'nmatch': number of matches in overlap 'nmismatch': number of mismatches in overlap 'nindel': number of indels in overlap 'prefer': which read's base wins mismatch positions (1=forward, 2=reverse), chosen by the larger denoised n0 (R's mergePairs behaviour); None when concatenating 'accept': whether the pair passed the overlap/mismatch criteria |
Only accepted pairs are returned unless return_rejects is True.
Like R's mergePairs, all four leading arguments may be lists (one entry per sample); a list of per-sample results is then returned, computed in parallel across samples.
Source code in papa2/paired.py
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 | |
papa2.chimera — Chimera Removal¶
Chimera detection and removal functions matching R's dada2 interface.
remove_bimera_denovo¶
remove_bimera_denovo(seqtab, method='consensus', min_fold=None, min_abund=None, allow_one_off=False, min_one_off_par_dist=4, min_sample_fraction=0.9, ignore_n_negatives=1, match=5, mismatch=-4, gap_p=-8, max_shift=16, verbose=False)
¶
Remove bimeric sequences from a sequence table.
Mirrors R's removeBimeraDenovo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqtab
|
dict with keys: "table": numpy int32 array (samples x ASVs), column-major preferred. "seqs": list of ASV sequences (str, ACGT), length = ncol. |
required | |
method
|
"consensus" (default), "pooled", or "per-sample". - "consensus": flag per-sample, then remove ASVs flagged in enough samples (controlled by min_sample_fraction and ignore_n_negatives). - "pooled": sum across samples, treat as single sample. - "per-sample": zero only the sample/ASV cells flagged as chimeric, then drop all-zero ASV columns. |
'consensus'
|
|
min_fold
|
parent fold-abundance threshold. Default matches R's per-method defaults: 1.5 for "consensus", 2 for "pooled" and "per-sample". |
None
|
|
min_abund
|
parent minimum absolute abundance. Default matches R's per-method defaults: 2 for "consensus", 8 for "pooled" and "per-sample". |
None
|
|
allow_one_off
|
allow one mismatch in chimera model. |
False
|
|
min_one_off_par_dist
|
min hamming distance for one-off parents. |
4
|
|
min_sample_fraction
|
fraction of present samples that must flag chimeric for consensus removal (default 0.9). |
0.9
|
|
ignore_n_negatives
|
ignore this many non-flagging samples (default 1). An ASV is chimeric if nflag >= nsam - ignore_n_negatives, provided nflag/nsam >= min_sample_fraction. |
1
|
|
match, mismatch, gap_p, max_shift
|
NW alignment parameters. |
required | |
verbose
|
print progress information. |
False
|
Returns:
| Type | Description |
|---|---|
|
dict with: "table": numpy int32 array with chimeric columns removed. "seqs": list of non-chimeric ASV sequences. "is_chimera": numpy bool array (ncol,) for "pooled"/"consensus", or numpy bool array (nrow, ncol) for "per-sample". |
Source code in papa2/chimera.py
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 | |
is_bimera_denovo¶
is_bimera_denovo(seqtab_row, seqs, allow_one_off=False, min_one_off_par_dist=4, min_fold=2, min_abund=8, match=5, mismatch=-4, gap_p=-8, max_shift=16)
¶
Check whether a single sequence is a bimera of more-abundant parents.
This mirrors R's isBimeraDenovo for a single sample (one row of the sequence table).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqtab_row
|
1-D array-like of int abundances, one per ASV. |
required | |
seqs
|
list of ASV sequences (str, ACGT), same length as seqtab_row. |
required | |
allow_one_off
|
allow one mismatch in chimera model. |
False
|
|
min_one_off_par_dist
|
min hamming distance between parents for one-off. |
4
|
|
min_fold
|
parent must be strictly more than this-fold more abundant than the query. |
2
|
|
min_abund
|
parents must be strictly more abundant than this. |
8
|
|
match, mismatch, gap_p, max_shift
|
NW alignment parameters. |
required |
Returns:
| Type | Description |
|---|---|
|
numpy bool array (n_seqs,): True where ASV is flagged as bimera. |
Source code in papa2/chimera.py
papa2.taxonomy — Taxonomic Classification¶
Bayesian k-mer classifier for taxonomic assignment.
assign_taxonomy¶
assign_taxonomy(seqs, ref_fasta, min_boot=50, try_rc=False, output_bootstraps=False, tax_levels=('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species'), verbose=False, seed=None)
¶
Classify sequences against a reference taxonomy using the RDP Naive Bayesian Classifier method.
This is a Python port of dada2's assignTaxonomy() R function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
Query sequences -- any type accepted by
:func: |
required | |
ref_fasta
|
str
|
Path to a reference FASTA file (may be gzipped). Headers must contain semicolon-delimited taxonomy. UNITE-formatted databases are detected and parsed automatically. |
required |
min_boot
|
int
|
Minimum bootstrap confidence (0--100) for retaining a
taxonomic assignment at each rank. Ranks below this threshold
are set to |
50
|
try_rc
|
bool
|
If |
False
|
output_bootstraps
|
bool
|
If |
False
|
tax_levels
|
Sequence[str]
|
Column names for the taxonomic ranks in the output
DataFrame. Must match the number of semicolon-delimited levels
in the reference database headers (shorter reference taxonomies
are padded with |
('Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species')
|
verbose
|
bool
|
Print progress messages. |
False
|
seed
|
Optional[int]
|
Bootstrap RNG seed. With an integer seed the bootstrap
values are identical to an R session that calls
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
Union[DataFrame, Dict[str, DataFrame]]
|
class: |
Union[DataFrame, Dict[str, DataFrame]]
|
|
|
Union[DataFrame, Dict[str, DataFrame]]
|
returns a dict |
Source code in papa2/taxonomy.py
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 | |
papa2.utils — Utilities¶
Utility functions for taxonomy assignment, sequence table operations, quality profiling, FASTA I/O, PhiX detection, and sequence complexity analysis.
make_sequence_table¶
make_sequence_table(samples_dict, order_by='abundance')
¶
Construct a sample-by-sequence observation matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples_dict
|
Dict[str, Dict[str, int]]
|
|
required |
order_by
|
str
|
How to order the columns. |
'abundance'
|
Returns:
| Type | Description |
|---|---|
|
dict with keys |
|
|
|
Source code in papa2/utils.py
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 | |
assign_species¶
assign_species(seqs, ref_fasta, allow_multiple=False, try_rc=False)
¶
Taxonomic assignment to species level by exact matching.
Each query sequence is searched as a substring against reference sequences. Reference FASTA headers must be in the format::
>SeqID Genus species
ACGAATGTGAAGTAA...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
Sequences to classify (any type accepted by |
required | |
ref_fasta
|
str
|
Path to reference FASTA file (may be gzipped). |
required |
allow_multiple
|
Union[bool, int]
|
If False, only unambiguous (single) species matches
are returned. If True, all matching species are returned
(concatenated with |
False
|
try_rc
|
bool
|
If True, also search the reverse complement of each query. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A numpy character array of shape |
ndarray
|
|
ndarray
|
|
Source code in papa2/utils.py
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 | |
add_species¶
add_species(tax_table, ref_fasta, allow_multiple=False, try_rc=False)
¶
Add species-level annotation to an existing taxonomy DataFrame.
Wraps assign_species and appends a "Species" column. Only species
assignments whose genus is consistent with the genus already present in
tax_table are kept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tax_table
|
A pandas DataFrame with sequences as the index and
taxonomic levels as columns. Must include a |
required | |
ref_fasta
|
str
|
Path to species-level reference FASTA. |
required |
allow_multiple
|
Union[bool, int]
|
Passed to |
False
|
try_rc
|
bool
|
Passed to |
False
|
Returns:
| Type | Description |
|---|---|
|
The input DataFrame with an added |
Source code in papa2/utils.py
collapse_no_mismatch¶
collapse_no_mismatch(seqtab)
¶
Merge ASVs whose sequences are identical except for length differences.
If sequence A is a substring of sequence B (allowing only leading/trailing gaps, i.e. one is a prefix or suffix or internal subsequence with no mismatches), their abundances are merged under the longer sequence.
Sequences are processed in decreasing order of total abundance. For each query, if it is found as a substring of an already-accepted sequence (or vice versa), it is collapsed into that representative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqtab
|
Either a |
required |
Returns:
| Type | Description |
|---|---|
dict
|
If input was a dict, returns a collapsed |
dict
|
dict. If input was a DataFrame, returns a collapsed DataFrame. |
Source code in papa2/utils.py
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 | |
plot_quality_profile¶
plot_quality_profile(fastq_files, n=500000, output_pdf=None)
¶
Plot mean quality score per cycle position from FASTQ file(s).
Reads up to n records from each file, computes per-position quality
statistics, and produces a matplotlib figure with mean (green), median
(orange), and 25th/75th percentile (dashed orange) quality lines,
similar to the R plotQualityProfile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fastq_files
|
Union[str, List[str]]
|
One or more FASTQ file paths (may be gzipped). |
required |
n
|
int
|
Maximum number of reads to sample per file. |
500000
|
output_pdf
|
Optional[str]
|
If provided, save the figure to this PDF path. |
None
|
Returns:
| Type | Description |
|---|---|
|
A numpy array of quality scores with shape |
|
|
(values are NaN where reads are shorter than max_len). |
Source code in papa2/utils.py
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 | |
uniquesto_fasta¶
uniquesto_fasta(uniques, fasta_path, ids=None)
¶
Write a uniques dict or list of sequences to a FASTA file.
If uniques is a dict {seq: abundance}, headers are formatted as
>sq1;size=1234; (uchime-compatible) unless custom ids are given.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uniques
|
A dict |
required | |
fasta_path
|
str
|
Output FASTA file path. |
required |
ids
|
Optional[List[str]]
|
Optional custom sequence identifiers. |
None
|
Source code in papa2/utils.py
write_fasta¶
write_fasta(seqs, fasta_path, ids=None)
¶
Write a list of sequences to a FASTA file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
Sequence[str]
|
Iterable of DNA sequence strings. |
required |
fasta_path
|
str
|
Output file path. |
required |
ids
|
Optional[List[str]]
|
Optional list of identifiers (one per sequence).
Defaults to |
None
|
Source code in papa2/utils.py
is_phix¶
is_phix(seqs, ref_path=None, word_size=16, min_matches=2, non_overlapping=True)
¶
Check sequences against the PhiX genome (port of R's isPhiX).
Kmers of each query are matched against the full circular PhiX genome
and, separately, its reverse complement; a sequence is flagged when
either strand accumulates at least min_matches hits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
Sequences to check (any type accepted by |
required | |
ref_path
|
Optional[str]
|
Path to a FASTA reference. Default: the PhiX genome shipped with the package (identical to R dada2's). |
None
|
word_size
|
int
|
Kmer size for matching. |
16
|
min_matches
|
int
|
Minimum kmer hits on a single strand to call PhiX. |
2
|
non_overlapping
|
bool
|
Count non-overlapping hits (R default). |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A boolean numpy array, True where a sequence matches PhiX. |
Source code in papa2/utils.py
match_ref¶
match_ref(seqs, ref, word_size=16, non_overlapping=True)
¶
Count reference kmer hits per sequence (port of R's C_matchRef).
The reference is treated as circular: kmers starting at every position,
wrapping around the end, are hashed. Each query position that hits the
hash increments the count; with non_overlapping the scan then skips
word_size positions (R's exact behaviour).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
Sequences (any type accepted by |
required | |
ref
|
str
|
Reference sequence. |
required |
word_size
|
int
|
Kmer length (<= 32). |
16
|
non_overlapping
|
bool
|
Skip ahead after each hit. |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Integer numpy array of per-sequence hit counts. |
Source code in papa2/utils.py
seq_complexity¶
seq_complexity(seqs, kmer_size=2, window=None, by=5)
¶
Calculate sequence complexity as Shannon effective number of kmers.
Complexity is the exponential of the Shannon entropy of kmer frequencies.
A perfectly random sequence of sufficient length will approach
4**kmer_size. Repetitive / low-complexity sequences will have values
well below this maximum.
If a window is provided, the minimum complexity observed over a sliding window along each sequence is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
Sequences (any type accepted by |
required | |
kmer_size
|
int
|
Size of kmers to count. Default 2 (dinucleotides). |
2
|
window
|
Optional[int]
|
Width of sliding window in nucleotides. If None, the whole sequence is used. |
None
|
by
|
int
|
Step size for the sliding window. |
5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A numpy array of complexity values, one per input sequence. |
Source code in papa2/utils.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 | |
get_sequences¶
get_sequences(obj, collapse=False)
¶
Extract a list of sequences from various dada2 object types.
Supported inputs
- list / tuple of strings (returned as-is, upper-cased)
- dict
{seq: abundance}(keys returned) - pandas DataFrame with a
"sequence"column - pandas DataFrame where column names are sequences (sequence table)
- numpy character matrix with row names (taxonomy table -- not common in Python, included for completeness)
- a single file path to a FASTA/FASTQ file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Input object. |
required | |
collapse
|
bool
|
If True, remove duplicate sequences. |
False
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List of upper-case DNA sequence strings. |
Source code in papa2/utils.py
get_uniques¶
get_uniques(obj, collapse=True)
¶
Extract a {sequence: abundance} dictionary from various types.
Supported inputs
- dict
{seq: abundance}-- returned directly (optionally collapsed) - list / tuple of strings -- each occurrence counted
- pandas DataFrame with
"sequence"and"abundance"columns - pandas DataFrame where columns are sequences (sequence table) -- column sums used as abundances
- a single FASTA file path (each record gets abundance 1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Input object. |
required | |
collapse
|
bool
|
If True, merge duplicate sequences by summing abundances. |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, int]
|
Dictionary mapping upper-case sequence strings to integer abundances. |
Source code in papa2/utils.py
get_errors¶
get_errors(obj, detailed=False, enforce=True)
¶
Extract error rate information from various dada2 object types.
Mirrors R's getErrors.
Supported inputs
- numpy array: used directly as
err_out. - dada result dict: extracts
err_out,err_in,trans. - list of dada result dicts: verifies all share the same
err_out, accumulatestransacross samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Input object containing error information. |
required | |
detailed
|
bool
|
If True, return a dict with |
False
|
enforce
|
bool
|
If True, validate that the error matrix has 16 rows, is numeric, and all values are in [0, 1]. |
True
|
Returns:
| Type | Description |
|---|---|
|
numpy array (16, ncol) if |
|
|
|
Source code in papa2/utils.py
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 | |
merge_sequence_tables¶
merge_sequence_tables(*tables, order_by='abundance', try_rc=False)
¶
Merge multiple sequence tables into one.
Mirrors R's mergeSequenceTables.
Each table is a dict with
'table': numpy array (nsamples x nseqs)'seqs': list of sequence strings
Sequences present in multiple tables have their counts summed.
If try_rc is True, reverse-complement sequences are detected
and re-oriented to match the majority orientation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*tables
|
Variable number of sequence table dicts. |
()
|
|
order_by
|
str
|
Column ordering: |
'abundance'
|
try_rc
|
bool
|
If True, check for reverse-complement sequences across tables and re-orient them before merging. |
False
|
Returns:
| Type | Description |
|---|---|
|
A dict with |
Source code in papa2/utils.py
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 | |
nwhamming¶
nwhamming(s1, s2, **kwargs)
¶
Compute Hamming distance between sequences via NW alignment.
Aligns the two sequences using nwalign and then counts mismatches
and indels using eval_pair.
Vectorized: if s1 and s2 are both lists (of the same length), returns a list of distances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s1
|
DNA sequence string, or list of strings. |
required | |
s2
|
DNA sequence string, or list of strings. |
required | |
**kwargs
|
Additional keyword arguments passed to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
scalar inputs) or list of int (list inputs
|
mismatch + indel |
|
count for each pair. |
Source code in papa2/utils.py
is_shift_denovo¶
is_shift_denovo(unqs, min_overlap=20, verbose=False)
¶
Check if sequences are shifted versions of more-abundant sequences.
For each sequence (sorted by decreasing abundance), check whether it is a "shift" of any more-abundant sequence. A shifted pair has:
match < len(sq1)ANDmatch < len(sq2)match >= min_overlapmismatch == 0ANDindel == 0
This identifies reads that are identical subsequences but offset (shifted) relative to each other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unqs
|
dict |
required | |
min_overlap
|
int
|
Minimum overlap (match) length to call a shift. |
20
|
verbose
|
bool
|
If True, log details about detected shifts. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean numpy array, True where a sequence is a shifted duplicate |
ndarray
|
of a more-abundant sequence. |
Source code in papa2/utils.py
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 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 | |
plot_errors¶
plot_errors(dq, nti=('A', 'C', 'G', 'T'), ntj=('A', 'C', 'G', 'T'), obs=True, err_out=True, err_in=False, nominal_q=False, output=None)
¶
Error rate diagnostic plot using plotly.
Mirrors R's plotErrors.
Creates a faceted plot showing error rates for each nucleotide transition (from_nuc -> to_nuc). Self-transitions are blanked out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dq
|
A dada result dict (with |
required | |
nti
|
Tuple[str, ...]
|
Tuple of source nucleotides to include. |
('A', 'C', 'G', 'T')
|
ntj
|
Tuple[str, ...]
|
Tuple of target nucleotides to include. |
('A', 'C', 'G', 'T')
|
obs
|
bool
|
If True, show observed error rates as scatter points. |
True
|
err_out
|
bool
|
If True, show the estimated (output) error rates as a line. |
True
|
err_in
|
bool
|
If True, show the input error rates as a dashed line. |
False
|
nominal_q
|
bool
|
If True, show nominal Q-score error rates as a red line. |
False
|
output
|
Optional[str]
|
If given, save to this path (.html for interactive, .png/.svg/.pdf require kaleido). If None, returns the plotly Figure object. |
None
|
Returns:
| Type | Description |
|---|---|
|
plotly.graph_objects.Figure if output is None, else None. |
Source code in papa2/utils.py
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 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 | |
plot_complexity¶
plot_complexity(files, kmer_size=2, n=100000, bins=100, output=None)
¶
Sequence complexity histogram using plotly.
Samples n reads from each FASTQ file, computes sequence complexity (Shannon effective number of kmers), and plots a faceted histogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
files
|
Union[str, List[str]]
|
One or more FASTQ file paths (may be gzipped). |
required |
kmer_size
|
int
|
Kmer size for complexity calculation (default 2). |
2
|
n
|
int
|
Maximum number of reads to sample per file. |
100000
|
bins
|
int
|
Number of histogram bins. |
100
|
output
|
Optional[str]
|
If given, save to this path (.html for interactive, .png/.svg/.pdf require kaleido). If None, returns the plotly Figure object. |
None
|
Returns:
| Type | Description |
|---|---|
|
plotly.graph_objects.Figure if output is None, else None. |
Source code in papa2/utils.py
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 | |
plot_sankey¶
plot_sankey(track, title='Read tracking through papa2 pipeline', output=None, width=900, height=500)
¶
Create a Sankey diagram showing read flow through pipeline stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
track
|
dict
|
Dict mapping stage names to read/sequence counts.
Typical keys (in order):
Can also be a list of such dicts (one per sample) — values will be summed across samples. Or a pandas DataFrame with stage columns and sample rows (as produced by a read-tracking table). |
required |
title
|
str
|
Plot title. |
'Read tracking through papa2 pipeline'
|
output
|
Optional[str]
|
If given, save to this path (.html for interactive, .png/.svg/.pdf require kaleido). If None, returns the plotly Figure object. |
None
|
width
|
int
|
Figure width in pixels. |
900
|
height
|
int
|
Figure height in pixels. |
500
|
Returns:
| Type | Description |
|---|---|
|
plotly.graph_objects.Figure if output is None, else None. |
Source code in papa2/utils.py
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 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 | |
track_reads¶
track_reads(dereps=None, dadas=None, mergers=None, seqtab=None, seqtab_nochim=None, taxa=None)
¶
Build a read-tracking dict from pipeline stage outputs.
Pass whichever stages you have — earlier stages are required for later ones to make sense, but all are optional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dereps
|
List of derep dicts (from derep_fastq) |
None
|
|
dadas
|
List of dada result dicts |
None
|
|
mergers
|
List of merger lists (from merge_pairs) |
None
|
|
seqtab
|
Sequence table (dict with 'table'/'seqs', DataFrame, or array) |
None
|
|
seqtab_nochim
|
Chimera-filtered sequence table (same formats as seqtab) |
None
|
|
taxa
|
Taxonomy array from assign_species / add_species, shape (N, K). Used together with seqtab_nochim (or seqtab) to count reads assigned to classified ASVs. |
None
|
Returns:
| Type | Description |
|---|---|
|
Dict mapping stage names to total read counts. |
|
|
Pass directly to plot_sankey(). |
Source code in papa2/utils.py
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 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 | |
remove_primers¶
remove_primers(fn, fout, primer_fwd, primer_rev=None, max_mismatch=2, allow_indels=False, trim_fwd=True, trim_rev=True, orient=True, compress=True, verbose=False)
¶
Remove primers from reads and orient them (port of R's removePrimers).
The forward primer is matched anywhere in each read (Biostrings
vmatchPattern semantics: mismatches only, IUPAC degenerate codes in
the primer match their base sets). Reads without a forward-primer
match are dropped; with orient, reads whose reverse complement
matches are reverse-complemented first. primer_rev (as it would
appear at the end of the read, i.e. already complemented) is
required to match when provided. trim_fwd trims through the end
of the forward match, trim_rev trims from the start of the
reverse match; reads must retain at least two bases (R's strict
last > first).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Input FASTQ path(s). |
required | |
fout
|
Output FASTQ path(s), same length as |
required | |
primer_fwd
|
str
|
Forward primer (may contain IUPAC codes). |
required |
primer_rev
|
Optional[str]
|
Reverse primer as it appears at the read's end. |
None
|
max_mismatch
|
int
|
Maximum mismatching positions in a primer match. |
2
|
allow_indels
|
bool
|
R supports indel-tolerant matching; not yet implemented here. |
False
|
trim_fwd / trim_rev
|
Trim the matched primer(s) off. |
required | |
orient
|
bool
|
Try the reverse complement of unmatched reads. |
True
|
compress
|
bool
|
Gzip the output. |
True
|
verbose
|
bool
|
Print per-file summaries. |
False
|
Returns:
| Type | Description |
|---|---|
|
|
|
|
shape |
Source code in papa2/utils.py
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 | |
Threading¶
set_num_threads¶
set_num_threads(n)
¶
Set the default OpenMP thread count for papa2's parallel C code (chimera tables, taxonomy, PhiX matching, within-sample denoising).
Setting the OMP_NUM_THREADS environment variable after papa2 has been imported has no effect — libgomp reads it at load time — so callers running under a CPU allocation (containers, schedulers) should call this instead.
Source code in papa2/_cdada.py
Environment variables DADA2_CORES, DADA2_WORKERS, and
DADA2_OMP_THREADS control the worker/thread split — see
Parity & Performance.
papa2._cdada — C Bindings¶
Low-level ctypes bindings to the libpapa2.so shared library. Most users should
not call these directly — they are used internally by the higher-level functions
above.
run_dada¶
run_dada(seqs, abundances, err_mat, quals=None, priors=None, match=5, mismatch=-4, gap_pen=-8, use_kmers=True, kdist_cutoff=0.42, band_size=16, omega_a=1e-40, omega_p=0.0001, omega_c=1e-40, detect_singletons=False, max_clust=0, min_fold=1, min_hamming=1, min_abund=1, use_quals=True, vectorized_alignment=True, homo_gap_pen=-8, multithread=True, verbose=False, sse=2, gapless=True, greedy=True)
¶
Call the C++ dada2 algorithm on dereplicated sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
list of str, unique DNA sequences (ACGT only) |
required | |
abundances
|
array-like of int, abundance per unique sequence |
required | |
err_mat
|
numpy array (16, ncol), error rate matrix, row-major |
required | |
quals
|
numpy array (nraw, maxlen) of avg quality scores, or None |
None
|
|
priors
|
array-like of int (0/1), or None |
None
|
|
multithread
|
True = all cores, False = single-threaded, or an int thread count for the within-sample OpenMP comparison loop |
True
|
Returns:
| Type | Description |
|---|---|
|
dict with keys: cluster_seqs, cluster_abunds, trans, map, pval, etc. |
Source code in papa2/_cdada.py
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 | |
run_taxonomy¶
run_taxonomy(seqs, refs, ref_to_genus, genusmat, ngenus, nlevel, verbose=True, seed=None)
¶
Run dada2 taxonomy assignment via C library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
list of query sequences (str) |
required | |
refs
|
list of reference sequences (str) |
required | |
ref_to_genus
|
numpy array (nref,) int32, 0-indexed genus ID per ref |
required | |
genusmat
|
numpy array (ngenus, nlevel) int32, genus-to-level mapping |
required | |
ngenus
|
int |
required | |
nlevel
|
int |
required | |
verbose
|
bool |
True
|
|
seed
|
int or None. With an integer seed, bootstrap subsampling uses R's RNG stream, so results match an R session that ran set.seed(seed) before assignTaxonomy(). None draws a nondeterministic seed (R's tie-breaking behaviour). |
None
|
Returns:
| Type | Description |
|---|---|
|
dict with: rval: numpy array (nseq,) int32, 1-indexed best genus per query (0=NA) rboot: numpy array (nseq, nlevel) int32, bootstrap counts |
Source code in papa2/_cdada.py
nwalign¶
nwalign(s1, s2, match=5, mismatch=-4, gap_p=-8, band=-1)
¶
NW ends-free alignment of two ACGT strings.
Returns:
| Type | Description |
|---|---|
(al1, al2)
|
tuple of aligned strings. |
Source code in papa2/_cdada.py
eval_pair¶
eval_pair(al1, al2)
¶
Evaluate an alignment: count matches, mismatches, indels (skipping end gaps).
Returns:
| Type | Description |
|---|---|
(nmatch, nmismatch, nindel)
|
tuple of ints. |
Source code in papa2/_cdada.py
pair_consensus¶
pair_consensus(al1, al2, prefer=1, trim_overhang=True)
¶
Build consensus from two aligned strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefer
|
1 = al1 wins mismatches, 2 = al2 wins. |
1
|
|
trim_overhang
|
if True, trim overhanging ends. |
True
|
Returns:
| Type | Description |
|---|---|
|
consensus string. |
Source code in papa2/_cdada.py
rc¶
rc(seq)
¶
Reverse complement an ACGT string.