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 |
dada¶
dada(derep, err=None, error_estimation_function=None, self_consist=False, 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
|
|
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_WORKERS: number of parallel workers (0 = auto-detect, default) OMP_NUM_THREADS: set to 1 before importing for best multi-sample performance
Source code in papa2/dada.py
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 | |
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
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)
¶
Dereplicate a FASTQ file.
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.
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
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 | |
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=None, 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, 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¶
fwd : str or list of str
Path(s) to forward (or single-end) input FASTQ file(s).
filt : str or list of str
Path(s) to filtered output FASTQ file(s). Must be the same length
as fwd.
rev : str, list of str, or None
Path(s) to reverse-read input FASTQ file(s). None for
single-end mode.
filt_rev : str, list of str, or None
Path(s) to filtered reverse-read output FASTQ file(s). Required
when rev is not None.
trim_left, trim_right, trunc_len, trunc_q, max_len, min_len,
max_n, min_q, max_ee, rm_phix, rm_lowcomplex, orient_fwd, compress
See :func:fastq_filter and :func:fastq_paired_filter.
multithread : bool or int
If True, use all available cores. If an integer > 1, use
that many worker processes. False or 1 disables
parallelism.
verbose : bool
Print per-file summaries.
Returns¶
numpy.ndarray
Integer array of shape (n_files, 2) with columns
[reads_in, reads_out].
Source code in papa2/filter.py
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 | |
fastq_filter¶
fastq_filter(fn, fout, *, trim_left=0, trim_right=0, trunc_len=0, trunc_q=None, 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, verbose=False)
¶
Filter and trim a single FASTQ file.
Parameters¶
fn : str
Path to input FASTQ file (plain or gzipped).
fout : str
Path to output FASTQ file.
trim_left : int
Number of bases to trim from the 5' end.
trim_right : int
Number of bases to trim from the 3' end.
trunc_len : int
Truncate reads to exactly this length after trimming. Reads
shorter than trunc_len after left/right trimming are discarded.
Set to 0 to disable.
trunc_q : int or None
Truncate at the first quality score <= this value. None
disables quality truncation.
max_len : int
Discard reads longer than this before trimming. 0 disables.
min_len : int
Discard reads shorter than this after all trimming.
max_n : int
Maximum number of ambiguous (non-ACGT) bases allowed.
min_q : int
Discard reads containing any quality score below this value.
max_ee : float
Maximum expected errors (sum(10^(-Q/10))).
rm_phix : bool
Remove reads matching the PhiX genome.
rm_lowcomplex : float
Remove reads with sequence complexity below this threshold.
0 disables.
orient_fwd : str or None
If set, orient reads so they begin with this primer sequence.
Reads that match neither in the forward nor reverse-complement
orientation are discarded.
compress : bool
Gzip-compress the output file.
verbose : bool
Print a summary line when done.
Returns¶
tuple of (int, int)
(reads_in, reads_out)
Source code in papa2/filter.py
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 | |
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=(None, None), 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, compress=True, verbose=False)
¶
Filter and trim paired FASTQ files.
Both reads in a pair must pass all filters for either to be kept, preserving read-pair synchronisation.
Parameters accept scalars (applied to both reads) or length-2 tuples
(forward_value, reverse_value).
Parameters¶
fwd : str
Path to forward-read input FASTQ.
filt_fwd : str
Path to filtered forward-read output FASTQ.
rev : str
Path to reverse-read input FASTQ.
filt_rev : str
Path to filtered reverse-read output FASTQ.
trim_left, trim_right, trunc_len, trunc_q, max_len, min_len,
max_n, min_q, max_ee, rm_lowcomplex
See :func:fastq_filter for per-parameter documentation. Each
accepts a scalar or a (fwd, rev) tuple.
rm_phix : bool
Remove reads matching PhiX.
orient_fwd : str or None
If set, orient forward reads to start with this sequence (reverse
reads are reverse-complemented accordingly).
compress : bool
Gzip-compress output files.
verbose : bool
Print a summary.
Returns¶
tuple of (int, int)
(reads_in, reads_out)
Source code in papa2/filter.py
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 | |
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, 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
|
|
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 'accept': whether the pair passed the overlap/mismatch criteria |
Source code in papa2/paired.py
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 | |
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=1.5, min_abund=2, 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. |
1.5
|
|
min_abund
|
parent minimum absolute abundance. |
2
|
|
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
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=1.5, min_abund=2, 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 this-fold more abundant than the query. |
1.5
|
|
min_abund
|
parent minimum absolute abundance. |
2
|
|
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)
¶
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
|
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 | |
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 |
|---|---|
|
A pandas DataFrame with samples as rows and sequences as columns. |
Source code in papa2/utils.py
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 | |
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
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 | |
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
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 | |
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
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 | |
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)
¶
Check sequences against the PhiX genome using kmer matching.
For each query sequence, kmers of size word_size are extracted and
compared to the PhiX reference (forward and reverse complement). A
sequence is flagged as PhiX if at least min_matches kmers hit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seqs
|
Sequences to check (any type accepted by |
required | |
ref_path
|
Optional[str]
|
Path to a FASTA file containing the PhiX genome. If None, a built-in 100 bp snippet is used for matching. |
None
|
word_size
|
int
|
Kmer size for matching. |
16
|
min_matches
|
int
|
Minimum number of kmer hits to call PhiX. |
2
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A boolean numpy array, True where a sequence matches PhiX. |
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
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
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 | |
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
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 | |
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
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 | |
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
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 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 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 | |
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
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 1848 1849 1850 1851 1852 1853 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 | |
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
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 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 | |
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
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 | |
remove_primers¶
remove_primers(fn, fout, primer_fwd, primer_rev=None, max_mismatch=2, trim_fwd=True, trim_rev=True, orient=True, compress=True, verbose=False)
¶
Match and trim primer sequences from FASTQ reads.
Reads the input FASTQ file, matches the forward primer at the start
of each read and the reverse-complement of the reverse primer at
the end. Reads that match are trimmed (if trim_fwd / trim_rev)
and written to the output file.
If orient=True, reads that don't match in forward orientation
are checked in reverse-complement and flipped if they match.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
str
|
Input FASTQ file path (may be gzipped). |
required |
fout
|
str
|
Output FASTQ file path. |
required |
primer_fwd
|
str
|
Forward primer sequence (5' to 3'). |
required |
primer_rev
|
Optional[str]
|
Reverse primer sequence (5' to 3'), optional. Its reverse complement is matched at the 3' end of reads. |
None
|
max_mismatch
|
int
|
Maximum allowed mismatches per primer match. |
2
|
trim_fwd
|
bool
|
If True, trim the matched forward primer region. |
True
|
trim_rev
|
bool
|
If True, trim the matched reverse primer region. |
True
|
orient
|
bool
|
If True, check reverse complement of reads and flip if primers match in that orientation. |
True
|
compress
|
bool
|
If True and output path ends with |
True
|
verbose
|
bool
|
If True, log progress and match statistics. |
False
|
Returns:
| Type | Description |
|---|---|
int
|
Tuple |
int
|
and the number of reads written. |
Source code in papa2/utils.py
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 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 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 | |
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
|
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 | |
run_taxonomy¶
run_taxonomy(seqs, refs, ref_to_genus, genusmat, ngenus, nlevel, verbose=True)
¶
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
|
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.