Skip to content
wtsi-hgiPublic

About

a versatile package of associating barcode sequence with target sequence

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

17 Commits

Folders and files

Repository files navigation

barcodex

Fast, out-of-core and quality-aware association of barcodes with the targets they tag

barcodex workflow

Table of Contents

Catalogue
  1. Description
  2. Dependencies
  3. Installation
  4. Input Files
  5. Usage
  6. Outputs
  7. Methods
  8. Resuming and re-running
  9. Tests
  10. Code conventions

Description

barcodex (version 0.1) links barcodes to the sequences they tag (targets: enhancers, promoters, splicing variants, ...) in very large sequencing data sets (> 10^9 read pairs). The barcode and the target are extracted from their reads (whole read, fixed position or between flanking sequences), then both barcodes and targets are clustered, using the base qualities, to remove sequencing and PCR errors. Finally ONE target is chosen per barcode. No step keeps all barcodes or reads in Python memory: the heavy work is done out-of-core by DuckDB.

The final map follows two rules: one barcode -> exactly ONE target; one target -> MANY barcodes.


Dependencies

Python
python = 3.11 (>= 3.11; tested with 3.11.2, DuckDB 2 needs >= 3.11)
Python Libraries
duckdb = 2.0.0   (>= 2.0) all out-of-core work: compaction (S1), barcode clustering (S2),
                          sharding (S3), reading the shards (S4), target assignment and output files (S5).
                          DuckDB 1.2.2 corrupted strings when S5 spilled to disk on a 400M-pair data set.
edlib  = 1.3.9   (>= 1.3) flank method: flanks that are not an exact match are found by an
                          edlib infix alignment (substitutions and indels)
pytest = 7       (optional) the tests use only unittest; pytest can run them too
Software (optional)
pigz = 2.6       parallel gunzip of .fastq.gz input; without it, or with --no_pigz, Python's gzip is used

Everything else is the Python standard library (argparse, multiprocessing, gzip, json, ...). The details are in pyproject.toml.


Installation

On the Sanger farm, the HGI module has everything:

module load HGI/softpack/users/fs18/nf_starr_seq

Elsewhere:

git clone https://github.com/wtsi-hgi/barcodex.git
cd barcodex
pip install .                 # installs the package and a `barcodex` command

barcodex can also be run without installation, with python run_barcodex.py ... (from any directory) or python -m barcodex ... (from the repository directory).


Input Files

barcodex reads FASTQ files (plain or .gz), given in two roles:

option content
--barcode_read the reads that carry the barcode
--target_read the reads that carry the target

Important

  1. Several files can be given per role (e.g. lanes): --barcode_read L1_R2.fq.gz L2_R2.fq.gz --target_read L1_R1.fq.gz L2_R1.fq.gz. Both roles need the same number of files.
  2. The two files of a role pair are read in parallel, record by record: record n of the barcode file must be the mate of record n of the target file.
  3. When the barcode and the target are in the same read (merged reads, PacBio HiFi reads), give the same file to both roles.
  4. The Phred offset is 33 by default (--phred_offset).

Usage

Run -- Sanger farm

#!/bin/bash
#BSUB -J barcodex
#BSUB -q normal
#BSUB -n 40
#BSUB -R "span[hosts=1] select[mem>80000] rusage[mem=80000]"
#BSUB -M 80000
#BSUB -o barcodex.%J.out
#BSUB -e barcodex.%J.err

#--------------#
# environment  #
#--------------#
module load HGI/softpack/users/fs18/nf_starr_seq

#--------------#
# barcodex     #
#--------------#
python /path/of/barcodex/run_barcodex.py \
    --barcode_read R2.fastq.gz --target_read R1.fastq.gz \
    --out results/sample1 \
    --method flank none \
    --barcode_up GTCCTCTTCCCATCT --barcode_down TGGTGGAAGCTACTGTACACCA \
    --barcode_allowed_lens 19,20,21 \
    --threads 40 --mem_gb 70

--threads and --mem_gb default to the slots of the LSF / SLURM / SGE / PBS job and 85% of the container memory limit (32 GB if there is none). Give --mem_gb a little below the memory requested from the scheduler.

Other ways to run it:

python -m barcodex ...                        # the same, from the repository directory
barcodex ...                                  # after pip install
python -m barcodex --version
python -m barcodex --selftest                 # synthetic data, all steps, pass / fail

Every run (and every --resolve_only) appends its command to cmd.log in the output directory. Each entry has the date, version, host, working directory, and the command with one option per line, so it can be copied and run again.

Options

All options are long options (--barcode_read, --threads, ...); there are no short forms. * stands for barcode or target.

Mandatory arguments

--barcode_read                FASTQ file(s) carrying the barcodes
--target_read                 FASTQ file(s) carrying the targets (same number of files as --barcode_read)
--out                         output prefix, e.g. results/sample1 (the directory is created)
--method BARCODE TARGET       extraction method of the barcode, then of the target:
                              none (whole read), pos (by position) or flank (between flanking sequences),
                              e.g. --method flank none

Optional arguments

Extraction (both roles):
--flank_mismatch              max edits (substitutions + indels) in a flank, method flank, default: 2
--do_rc                       retry failed pairs with BOTH reads reverse-complemented, default: off

Barcode extraction:
--barcode_start               method pos: 0-based start, default: 0
--barcode_len                 method pos: length, 0 = to the end of the read, default: 0
--barcode_up                  method flank: upstream flanking sequence
--barcode_down                method flank: downstream flanking sequence
--barcode_min_len             reject shorter barcodes, default: not set (no minimum)
--barcode_allowed_lens        keep only these lengths, e.g. 19,20,21 or 19-21, default: not set
--barcode_temp                barcode template, e.g. NNNNATNNNNATNNNNATNN, default: not set
--barcode_temp_mismatch       max mismatches at the fixed (non-N) template bases, default: 1

Target extraction:
--target_start                method pos: 0-based start, default: 0
--target_len                  method pos: length, 0 = to the end of the read, default: 0
--target_up                   method flank: upstream flanking sequence
--target_down                 method flank: downstream flanking sequence
--target_min_len              reject shorter targets, default: not set (no minimum)
--target_max_len              reject longer targets, default: not set (no maximum)
--target_allowed_lens         keep only these lengths, default: not set

Barcode clustering (S2):
--barcode_dist                max hard mismatches / edits between a barcode and its parent, default: 1
--barcode_max_lowq            max mismatches at low-quality bases, 0 = ignore quality, default: 1
--barcode_min_qual            min Phred score of a high-quality base, default: 20
--barcode_indel               max indels between a barcode and its parent (0 = Hamming), default: 0
--barcode_ratio               parent reads >= ratio x child reads; also the min reads of a parent, default: 5.0
--min_child_reads             speed-up: barcodes with fewer reads are not clustered, default: 1
--min_barcode_reads           drop unmatched barcodes with fewer reads, default: --min_pair_reads

Target clustering (S4):
--target_dist                 max hard edits between a target and its parent, default: 2
--target_max_lowq             max mismatches at low-quality bases, 0 = ignore quality, default: 5
--target_min_qual             min Phred score of a high-quality base, default: 20
--target_max_indel            max indels between a target and its parent, default: 1
--target_ratio                parent reads >= ratio x child reads, default: 5.0
--target_lowq_ratio           the same, when the differences are only at low-quality bases, default: 1.0

Target assignment (S5):
--min_pair_reads              min reads of the (barcode, top target) pair, default: 2
--min_purity                  min fraction of the barcode's purity reads on its top target, default: 0.8
--min_purity_reads            purity counts only the targets with >= X reads, default: 1 (all)

Run control:
--resolve_only                skip S1-S4, re-run S5 on the existing <out>.meta/ files
--no_resolve                  stop after S4 (writes only <out>.meta/target_pairs.tsv)
--resume                      skip the steps already finished in the work directory
--clean_meta                  delete <out>.meta/ at the end
--keep_tmp                    keep the work directory <out>.work/
--tmp                         parent directory of the work directory, default: next to --out
--db                          DuckDB file of S5 to keep, default: in memory, spills to <out>.duckdb.tmp
--max_reads                   pilot run: use only the first X read pairs, 0 = all, default: 0

Resources and tuning:
--threads                     worker processes / DuckDB threads, default: job slots
--mem_gb                      RAM budget in GB, default: 85% of the memory limit, else 32
--shards                      number of S3 / S4 shards, default: 64
--chunk                       reads per parse chunk, default: 100000
--agg_entries                 max (barcode, target) entries per worker before a part is written,
                              0 = derive from --mem_gb, default: 0
--compact_parts               compact text parts into Parquet when X are pending, default: 12
--merge_files                 merge X same-level Parquet files into the next level, default: 6
--max_cand                    seeds shared by more than X heavy barcodes are ignored, default: 5000
--max_dp_group                barcodes with more target variants than X use Hamming only (no indels), default: 1000
--max_parents                 within one barcode, compare each target only with the X most abundant, default: 200
--no_pigz                     read .gz with Python's gzip instead of pigz

Other:
--phred_offset                Phred offset of the qualities, default: 33
--barcode_map                 also write <out>.barcode_map.tsv (raw barcode -> cluster centre)
--fastq                       also write <out>_barcode.fastq / <out>_target.fastq
--selftest                    run all steps on synthetic data and exit
--version                     print the version and exit

An option of another method is an error, for example --method none none --barcode_len 16.

Examples

Promoter library (STARR-seq), with the same settings as run_asso_promoter.sh:

python run_barcodex.py --barcode_read Adept_SS_L1_R2.fastq.gz --target_read Adept_SS_L1_R1.fastq.gz \
    --out GP_input --method flank none \
    --barcode_up GTCCTCTTCCCATCT --barcode_down TGGTGGAAGCTACTGTACACCA --barcode_allowed_lens 19,20,21 \
    --threads 40 --mem_gb 80

Splicing library combi_6 (merged reads, so both roles read the same file), with the same settings as associate_variant_barcode.py in run_bc.sh:

python run_barcodex.py --barcode_read combi_6.extendedFrags.fastq.gz \
    --target_read combi_6.extendedFrags.fastq.gz --out combi_6 \
    --method flank flank --flank_mismatch 2 \
    --target_up tccaatgttccaacctacag --target_down tctttgttctttcagTGAAG --target_min_len 170 \
    --barcode_up GCAGAAAGCACAGAAAGGAA --barcode_down CTACTGATTCGATGCAAGCTT \
    --barcode_temp NNNNATNNNNATNNNNATNNNNATNNNNATNNNNATNN --barcode_temp_mismatch 1 \
    --min_pair_reads 3 --threads 40 --mem_gb 70
associate_variant_barcode.py barcodex
--read1 (variant) / --read2 (barcode) --target_read / --barcode_read
flanks for both --method flank flank
--variant_up / --variant_down --target_up / --target_down
--variant_check --variant_len 170 --target_min_len 170
--barcode_check --barcode_temp T --barcode_temp T
--barcode_mismatch 1 --barcode_temp_mismatch 1
--max_mismatches 2 --flank_mismatch 2
--min_barcov 3 --min_pair_reads 3 (applied after the clustering)

PacBio HiFi reads (barcode and long target in the same read, either strand):

python run_barcodex.py --barcode_read hifi.fastq.gz --target_read hifi.fastq.gz --out hifi \
    --method flank flank --do_rc \
    --barcode_up <UP> --barcode_down <DOWN> --barcode_allowed_lens 20 \
    --target_up <UP> --target_down <DOWN> --target_min_len 500

Outputs

Structure

📁 <output dir>
├───📄 cmd.log                                   # commands of all runs
├───📄 <prefix>.barcode_target.details.tsv       # final map: one row per (barcode, target)
├───📄 <prefix>.stats.tsv                        # read and sequence counts of every step
├───📄 <prefix>.barcode_map.tsv                  # optional, --barcode_map
├───📄 <prefix>_barcode.fastq                    # optional, --fastq
├───📄 <prefix>_target.fastq                     # optional, --fastq
├───📁 <prefix>.meta                             # intermediate files for --resolve_only (--clean_meta deletes it)
│   ├───📄 ingest_stats.json                     #   S1 read counts and reject reasons
│   ├───📄 raw_stats.json                        #   S2 raw barcode / target counts
│   ├───📄 barcode_clusters.parquet              #   S2 statistics of every barcode cluster
│   └───📄 target_pairs.tsv                      #   S4 (barcode cluster, target cluster) rows
└───📁 <prefix>.work                             # work directory while running (--tmp, --keep_tmp)

File Description

Final map

📄 <prefix>.barcode_target.details.tsv

Note

One row per final (barcode, target) pair. Every final barcode has exactly one target, so each row describes one barcode, one target and that pair. The rows are sorted by barcode_reads (most first).

column meaning
barcode, target barcode (centre of its cluster) and its target (centre of its cluster under this barcode)
barcode_reads reads of the barcode cluster: the sum of the reads of all raw barcodes clustered into this barcode
n_diff_barcodes number of different raw barcodes clustered into this barcode
first_barcode_cov, first_barcode_ratio reads of the most abundant raw barcode, and first_barcode_cov / barcode_reads
second_barcode_cov, second_barcode_ratio the same for the second most abundant raw barcode (0 if none)
target_reads reads of this target under this barcode: the sum of the reads of all raw target sequences clustered into it
n_diff_targets number of different raw target sequences clustered into this target under this barcode
first_target_cov, first_target_ratio reads of the most abundant target sequence, and first_target_cov / target_reads
second_target_cov, second_target_ratio the same for the second most abundant target sequence (0 if none)

Example: barcode 1 is a cluster of 4 raw barcodes barA, barB, barC, barD with readA >= readB >= readC >= readD reads. Then barcode_reads = readA + readB + readC + readD, first_barcode_ratio = readA / barcode_reads and second_barcode_ratio = readB / barcode_reads. A second ratio far below the first means barA is the real barcode and the others are sequencing errors or noise. The target columns work the same way for the target sequences clustered into the target under this barcode. target_reads can be smaller than barcode_reads: reads of the barcode that support other (minor) targets are not counted.

Example (combi_6; the 180 bp targets are shortened here with ...):

barcode	target	barcode_reads	n_diff_barcodes	first_barcode_cov	first_barcode_ratio	second_barcode_cov	second_barcode_ratio	target_reads	n_diff_targets	first_target_cov	first_target_ratio	second_target_cov	second_target_ratio
ATACATTGTTATTGTGATTAACATTAGGATAGATATTT	GATACACTATGG...GGCACGGGTGAGG	7515	36	7436	0.9895	19	0.0025	7392	720	6283	0.85	55	0.0074
ATAGATTGTTATTTATATGAAAATTGCGATCGGCATAA	GAATGTCACGGT...GCTCACGGATTTTACT	4319	24	4285	0.9921	6	0.0014	4206	442	3511	0.8348	33	0.0078
CTTGATTCACATTTTTATGTGAATCTGCATATGGATAT	GAGTAGTCTTCG...GCCGAGGCATAGGGCGTGGG	3793	10	3781	0.9968	2	0.0005	3779	257	3310	0.8759	34	0.009

Statistics

📄 <prefix>.stats.tsv

Note

Columns step, stat, count, percent and description; the rows are ordered by step. Stat names start with reads_ (read-pair counts), num_ (numbers of sequences / barcodes / targets) or mean_ / median_. percent is filled for reads_* rows (count / reads_raw_input x 100) and is NA otherwise.

step	stat	count	percent	description
1_input	reads_raw_input	93586470	100.00	read pairs in the FASTQ files
2_extraction	reads_target_upstream_not_found	7871550	8.41	read pairs rejected: upstream flank (--target_up) not found
2_extraction	reads_barcode_incorrect_template	3820737	4.08	read pairs rejected: barcode does not match --barcode_temp NNNNATNNNNATNNNNATNNNNATNNNNATNNNNATNN
2_extraction	num_raw_barcodes	3810485	NA	distinct barcode sequences extracted (before barcode clustering)
3_barcode_clustering	num_barcodes_after_clustering	2581082	NA	barcodes (barcode clusters) after clustering
5_target_assignment	num_barcodes_ambiguous	36442	NA	multi-target barcodes NOT resolved: their top target has >= 3 reads (--min_pair_reads) but < 0.8 of the barcode's reads (--min_purity), no dominant target; dropped
6_final_map	reads_final_effective	69897106	74.69	reads supporting the final (barcode, target) pairs
6_final_map	median_barcode_coverage	23	NA	median reads per final barcode (after clustering)
step stats
1_input reads_raw_input
2_extraction one reads_<target|barcode>_<reason> row per reject reason (target rows first), reads_reverse_complemented (with --do_rc), then num_raw_barcodes, num_raw_targets, num_raw_barcode_target_pairs
3_barcode_clustering reads_dropped_barcode_clustering, reads_in_barcode_clustering, num_barcodes_after_clustering
4_target_clustering reads_dropped_target_clustering, reads_in_target_clustering, num_target_after_clustering
5_target_assignment reads_ / num_barcodes_multi_targets, reads_ / num_barcodes_resolved, reads_ / num_barcodes_ambiguous, reads_ / num_barcodes_low_coverage
6_final_map num_final_barcodes, num_final_targets, num_final_barcode_target_pairs, reads_final_effective, mean_ / median_barcode_coverage, mean_ / median_target_coverage, mean_barcodes_per_target

Important

The read counts add up:

  • reads_raw_input = the reject rows of 2_extraction + reads_dropped_barcode_clustering + reads_in_barcode_clustering
  • reads_in_barcode_clustering = reads_dropped_target_clustering + reads_in_target_clustering
  • reads_in_target_clustering = reads_barcodes_low_coverage + reads_barcodes_ambiguous + reads_final_effective + the reads of resolved barcodes that support a minor target

Reject rows appear only for the reasons that the chosen settings can produce: *_upstream_not_found, *_downstream_not_found, *_missing (empty sequence), barcode_read_too_short (pos method), target_too_long (--target_max_len), *_incorrect_length (--*_min_len), *_length_not_allowed (--*_allowed_lens) and *_incorrect_template (--barcode_temp). Each rejected pair is counted once, under the first reason that applies. The checks run in the same order as in the associate_*.py scripts: target extraction, barcode extraction, target filters, barcode filters.

Optional files

📄 <prefix>.barcode_map.tsv (--barcode_map)

Note

One row per raw barcode kept by the barcode clustering (dropped barcodes are not listed).

barcode reads centre_barcode
raw barcode its reads the cluster centre it was merged into

📄 <prefix>_barcode.fastq, <prefix>_target.fastq (--fastq): a representative FASTQ pair of the clustered barcodes and targets.


Methods

Steps

step module what it does
S1 ingest fastq.py, extract.py, ingest.py, compaction.py One reader process per FASTQ role passes chunks to the parse workers. The workers extract the barcode and the target, count rejects, and aggregate (barcode, target) -> count + low-quality masks in a bounded dict. The dict is written to gz parts, which a background DuckDB compactor merges into Parquet.
S2 barcodes barcodes.py DuckDB barcode census. Barcodes with at least --barcode_ratio reads ("heavy" barcodes) can be parents. Each barcode is matched to a parent with a pigeonhole seed join and a quality-aware Hamming or Levenshtein distance. Chains of parents are followed to the root by pointer jumping.
S3 shards shards.py Replaces each barcode by its cluster centre, merges identical (centre, target) rows and writes Hive-partitioned shards by hash(centre), so all rows of one barcode cluster are in one shard.
S4 targets distance.py, targets.py Clusters the targets of each barcode, quality-aware, with one process per shard.
S5 resolve resolve.py, stats.py Chooses one target per barcode and writes the result files and the stats. Its tables hold no sequences: barcodes and targets are keyed by md5_number(), and the sequences are read again from target_pairs.tsv only while the result files are written.

Other modules:

  • cli.py: options, validation, cmd.log, main
  • steps.py: order of the steps and --resume
  • common.py: logging, SQL quoting, resources, meta paths
  • constants.py
  • selftest.py

Extraction methods

--method takes two values: first the barcode method, then the target method. They are independent: for example, --method pos flank takes the barcode by position and the target between flanks, and --method flank none uses the whole target read.

method the sequence is options (* = barcode or target)
none the whole read none
pos a fixed window --*_start (0-based), --*_len (0 = to the end of the read)
flank between two flanking sequences --*_up, --*_down, and --flank_mismatch (default 2, shared by barcode and target)
  • pos: a barcode read that is too short is rejected (barcode_read_too_short). A short target is kept as it is.
  • flank: the flanks are found on the sequence only, without base qualities. The upstream flank is searched first. The barcode / target starts where the upstream flank match ends and ends where the downstream flank match starts (searched after the upstream flank). Each flank is found in two steps (find_flank):
    1. an exact match (bytes.find, C speed; most reads);
    2. otherwise the best edlib infix alignment with at most --flank_mismatch edits (substitutions and indels, match_edlib). The match boundaries are the alignment boundaries, so an indel inside a flank does not shift the barcode / target. When several alignments have the same number of edits, one of the flank length (substitutions) is preferred, then the leftmost.
Comparison with the Hamming window search of nf_starr_seq

This replaced the Hamming window search (match_hamming_numpy) and the fixed-length Levenshtein window search (match_levenshtein) of nf_starr_seq/scripts/sequence_utils.py, and the option --flank_distance that chose between them. An indel near the inner end of a flank (next to the barcode / target) shifts only the last flank bases, so the Hamming window is accepted with 1-2 mismatches and the sequence comes out shifted by one base; the old Levenshtein window search shifted the sequence even for exact flanks (with --flank_mismatch 2 the window one base before an exact flank already matches). Simulated reads with the hek16 barcode flanks (21 / 20 bp, 38 bp barcode, --flank_mismatch 2), 5,000 reads per row, % correct / wrong barcode / lost:

upstream flank old Hamming barcodex
exact 100 / 0 / 0 100 / 0 / 0
1 substitution 100 / 0 / 0 100 / 0 / 0
2 substitutions 100 / 0 / 0 99.9 / 0.1 / 0
1 indel 14.4 / 6.4 / 79.2 98.1 / 1.9 / 0
1 indel 2-3 bases from the barcode 0 / 62.8 / 37.2 80.8 / 19.2 / 0

The remaining "wrong" cases are ties: another explanation with the same number of edits (e.g. an insertion next to the barcode = a substitution + a 1-base shift); no method can tell them apart. Speed (95% exact, 4% 1 substitution, 1% 1 indel): 1.5 µs per read, the Hamming window search 83 µs.

Filters

For any method:

  • --*_min_len N rejects shorter sequences, for example --target_min_len 170. Not set (the default) = no minimum.
  • --target_max_len N rejects longer targets (target_too_long). Not set (the default) = no maximum: targets of any length are kept, for example 500-1000 bp inserts in PacBio reads.
  • --*_allowed_lens 19,20,21 (or 19-21) keeps only these lengths.
  • --barcode_temp NNNNATNN... applies to barcodes only. The barcode must have the template length, and its fixed (non-N) bases may differ in at most --barcode_temp_mismatch positions (default 1). This is the same rule as check_barcode in the splicing pipeline. A barcode that passes with mismatching fixed bases is then corrected: those bases are set to the template base (template NNNNATNNNNATNNNNATNN, barcode CCCCCTGGGGATCCCCATGG -> CCCCATGGGGATCCCCATGG), so it is counted with the error-free barcode already in S1. Most barcodes match the template exactly and are passed through after one regex match; only the others are rebuilt (0.4 µs per barcode, 7x faster than a per-base loop over the whole barcode, same result).

Important

With the flank method, use one of these filters for barcodes. Very short barcodes stop S2 with "barcodes too short" (the pigeonhole seeds need at least 4 bases each).

Reads of either strand

  • Without --do_rc the barcode and the target are searched on the forward strand only.
  • With --do_rc, a read pair that fails on the forward strand (any extraction or filter reject) is tried again with BOTH reads reverse-complemented (sequences and qualities). A pair that passes on the forward strand is never reverse-complemented. The barcode and the target always come from the same strand: a forward barcode is never combined with a reverse-complemented target, or the other way round.
  • If both orientations fail, the pair is counted under the reject reason of the orientation that got further in the check order.
  • The stats file reports the pairs found on the reverse complement as reads_reverse_complemented (kept pairs, not a reject row).
  • Use it for reads that come from either strand, for example PacBio HiFi reads, where the barcode and the target are in the same read (--barcode_read and --target_read are the same file).

Quality-aware clustering

Barcodes (S2) and the targets of each barcode (S4) are clustered the same way: sequences are sorted by reads, and a sequence is merged into a more abundant parent when they are close enough and the parent has at least --*_ratio times its reads. Chains of parents end at their root, the cluster centre.

  • A mismatch is hard when both bases are confident (Phred >= --*_min_qual, ACGT); it counts towards --barcode_dist / --target_dist.
  • It is low when one of the two bases has low quality or is N; it counts towards --*_max_lowq. For targets that differ only at low-quality bases, --target_lowq_ratio replaces --target_ratio.
  • A base is low quality only if it was low quality in every read that carried that sequence.
  • Set --barcode_max_lowq 0 or --target_max_lowq 0 to turn quality off. Barcodes longer than 32 bp are clustered without quality (their quality mask is packed in one 64-bit word).
  • Barcodes: Hamming distance, or Levenshtein with --barcode_indel > 0. Unmatched barcodes with fewer than --min_barcode_reads reads are dropped.
  • Targets: banded edit distance with up to --target_max_indel indels. Barcodes with more than --max_dp_group target variants use Hamming only, and each target is compared with at most the --max_parents most abundant targets of its barcode.

Target assignment

S5 takes the target with the most reads of each barcode cluster (the top target) and gives the barcode a status:

status rule kept
unique a single target, with >= --min_pair_reads reads yes
resolved several targets; the top target has >= --min_pair_reads reads and a purity >= --min_purity yes, with the top target
ambiguous several targets; the top target has enough reads but a purity < --min_purity (no dominant target) no
low_coverage the top target has < --min_pair_reads reads no
  • purity = top target reads / purity reads. Purity reads = the barcode's reads minus the reads of its other targets with < --min_purity_reads reads (after target clustering; the top target always counts).
  • --min_purity_reads 1 (default): all of the barcode's reads. --min_purity_reads 2: 1-read targets, mostly noise, do not lower the purity.
  • num_final_barcodes = unique + resolved barcodes.

Resuming and re-running

  • --resume: S1-S3 write a marker file in <prefix>.work/ (ingest.done, bcmap.done, shards.done); with --resume, finished steps are skipped. Use it with --keep_tmp or after a crash (the work directory is deleted only at the end of S4).
  • --resolve_only: re-runs only S5 on <prefix>.meta/, e.g. to try other --min_pair_reads, --min_purity or --min_purity_reads values in minutes instead of hours.
  • --no_resolve: stops after S4.
  • --max_reads N: a quick pilot run on the first N read pairs, to check the extraction settings and the reject reasons in the stats file before the full run.

Tests

python -m barcodex --selftest                 # synthetic data, all steps, pass / fail
python -m unittest discover -s tests          # unit tests, one file per step

The tests write to the system temp directory; set TMPDIR to put them elsewhere.

test file what it covers
test_extract.py none / pos / flank extraction (exact-then-edlib flanks, indels, ties), length and template filters, template correction, reject order
test_cli.py options, --method, validation, cmd.log, --version
test_s1_ingest.py FASTQ reader, read parsing and reject order, part files, compaction, step S1
test_s2_s3_barcodes_shards.py barcode clustering (S2) and sharding (S3)
test_s4_targets.py edit distance, target clustering within a barcode, step S4
test_s5_resolve.py one target per barcode, output columns, stats file by step, --min_purity_reads
test_long_targets_rc.py targets longer than 256 bp (--target_max_len), --do_rc
test_all_steps.py all steps on synthetic data (pos none and flank pos scenarios)

Code conventions

  • Every function has a docstring with a description, Parameters and Returns.
  • Steps inside a function are marked # stepN : text, and their parts # |---- substep text.
  • Options are long snake_case options with the same name as the variable: --max_reads -> args.max_reads.
  • The workflow figure is drawn with Graphviz from image/barcodex_workflow.dot: dot -Tpng -Gdpi=130 image/barcodex_workflow.dot -o image/barcodex_workflow.png.

About

a versatile package of associating barcode sequence with target sequence

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages