selexprep
Accession-first preprocessing for public HT-SELEX, with primer auto-inference and safe failure modes.
Give selexprep a public accession (or your own FASTQs) and it infers the
primer/constant regions from the reads, strips them, and emits clean per-round
random-region FASTAs + count tables — with an explicit confidence level and a
reproducible manifest. When it can't infer the library with confidence, it
says so and refuses to guess rather than emitting fabricated primers.
In the commands, options and output fields (--override-primer-5p,
primer_5p, ...), primer means the library constant flanking the random
region, which usually contains the primer-binding site.
It's the step before the existing SELEX toolchain. Tools like FASTAptameR,
AptaSUITE, RaptGen, and AptaTrans assume you already have trimmed reads and
already know your primers. selexprep produces exactly those inputs, starting
from a raw public deposit.
accession ──▶ fetch ──▶ detect ────▶ extract ───▶ count ────▶ qc
(or local (infer (trim per (unique (flags +
FASTQs) primers) round) seqs) 4 plots)
run chains the whole thing for you; the individual verbs (fetch, detect,
extract, count, qc) are there for when you need to drive one stage by hand.
Status — beta. The core accession/local-FASTQ preprocessing pipeline is feature-complete and CI-tested (Python 3.10 / 3.11 / 3.12). The CLI commands and the primary output schemas (
library_report.json,selexprep_manifest.json,counts.parquet) are treated as stable within the 0.x series; experimental features are listed separately. SeeSTABILITY.mdfor the full stable-vs-experimental surface.
Install
pip install selexprep # pulls in cutadapt, the only external dependency
selexprep --version
Python 3.10+. The only external tool is cutadapt, installed automatically.
Working from a clone instead? uv pip install -e . from the repo root.
Quick start
One accession, no primers supplied. The whole pipeline is one command.
Write a TSV listing one or more accessions, then point run at it. It fetches
each dataset, infers the primers from the read content, then extracts, counts,
and QCs — with nothing about the library supplied by you:
printf 'accession\nPRJNA615076\n' > accessions.tsv
selexprep run accessions.tsv --outdir out
That's the happy path. Everything for each accession lands under
out/<accession>/:
| Output | What it is |
|---|---|
library_report.json |
inferred primers + status (HIGH / MEDIUM / LOW / UNABLE_TO_INFER) |
round_NN/extracted.fasta.gz |
primer-stripped random region, one folder per round |
round_NN/counts.parquet |
unique sequences per round (reads, rank, RPM) |
qc/flags.yaml + 4 PNGs |
depth-aware QC flags + diagnostic plots |
selexprep_manifest.json |
reproducibility manifest (output hashes, dependency versions, CLI argv) |
A corpus-level out/run_summary.tsv spans every accession. If a batch is
interrupted, re-run the same command with --resume and finished datasets
are skipped.
Watch it run, offline, in under a minute.
examples/01_offline_toy_pipeline.ipynbexecutes the fulldetect → extract → count → qcpath on a tiny synthetic library — no network, no accession, no HPC. It's the fastest way to see what each stage produces before pointing the tool at real data.
Common situations
The situations people actually hit. Find yours.
"I don't have an accession yet"
Browse the bundled catalog of public SELEX deposits, then feed the hits to run:
selexprep catalog list --target IL-10RA --insdc-only
selexprep catalog show PRJNA315881
INSDC accessions are fetchable; figshare/zenodo rows are discovery-only pointers
(flagged in the fetchable column) that run can't retrieve yet —
--insdc-only filters the list to just the retrievable ones.
"I only have my own local FASTQs"
run is for accessions; for files already on disk, drive the stages yourself.
This is also how you inspect an intermediate or re-extract with corrected
primers:
# detect needs a round map: it infers the boundary on the earliest round and checks it on the others
printf 'file\tround_number\nround_00.fastq.gz\t0\nround_01.fastq.gz\t1\nround_02.fastq.gz\t2\n' > rounds.tsv
selexprep detect round_00.fastq.gz round_01.fastq.gz round_02.fastq.gz \
--round-map rounds.tsv --outdir ./out
selexprep extract round_00.fastq.gz round_01.fastq.gz round_02.fastq.gz \
--library-report ./out/library_report.json --round-map rounds.tsv --outdir ./out
for r in 0 1 2; do
selexprep count ./out/round_$(printf '%02d' $r)/extracted.fasta.gz --round R$r --outdir ./out
done
selexprep qc ./out/selexprep_manifest.json
The runnable, annotated version of exactly this path is
examples/01_offline_toy_pipeline.ipynb;
every flag and the --round-map contract are in the CLI reference.
Input FASTQ files can be gzip-compressed or not. Files that share a
round_number are pooled into one round_NN/; to keep replicates apart, run
extract and count once per replicate, each with its own round map and
--outdir, reusing the same library_report.json.
Using your own reads: what to check
detect infers the primers from the reads alone, so look at what it called
before counting anything:
python -c "import json; r = json.load(open('out/library_report.json')); print({k: r[k] for k in ('status', 'extraction_mode', 'orientation', 'primer_5p', 'primer_3p', 'n_length_mode')})"
primer_5p, primer_3p and n_length_mode (the most common random-region
length) should match your library design. Three situations are common on real
runs.
Reads longer than the construct. If the read length exceeds 5' constant +
random region + 3' constant, the reads run into the sequencing adapter.
detect can then call the adapter as the 3' primer, or report a one-sided
extraction_mode (FIVE_PRIME_ONLY, THREE_PRIME_ONLY), whose
partial_*_extracted.fasta.gz output keeps the other constant and the adapter.
It prints a warning in both cases. Give your own primers:
selexprep extract round_*.fastq.gz \
--library-report ./out/library_report.json --round-map rounds.tsv \
--override-primer-5p ATCCAGAGTGACGCAGCATTGC \
--override-primer-3p TGGACACGGTGGCTTAGTCAA \
--extraction-mode BOTH_PRIMERS_SINGLE_READ \
--outdir ./out
- Write both primers as they read in the FASTQ, left to right. The 3' primer is
what follows the random region in the read; a reverse primer as ordered is its
reverse complement.
extractwarns when a supplied primer is in under 5% of the reads, and says so if its reverse complement is there instead. - A primer override replaces a primer but keeps the report's
extraction_mode. Ifdetectreported a one-sided mode,extractwould still trim one side only (it warns):--extraction-mode BOTH_PRIMERS_SINGLE_READmakes it trim both. The other values areFIVE_PRIME_ONLY,THREE_PRIME_ONLYandPAIRED_END_SPLIT_PRIMERS.
Reads in both orientations. Ligation-based preps sequence each molecule
from either end. With orientation: MIXED, extract keeps the reads in the
forward orientation and drops the others: strand_report.tsv counts both, and
qc raises strand_mix. With an even mix and no early round to anchor on,
detect returns UNABLE_TO_INFER. To keep both orientations, trim with
cutadapt directly and count the result:
cutadapt --revcomp -g "ATCCAGAGTGACGCAGCATTGC...TGGACACGGTGGCTTAGTCAA" \
--discard-untrimmed -o round_00.trimmed.fastq.gz round_00.fastq.gz
selexprep count round_00.trimmed.fastq.gz --from-pretrimmed-fastq --round 0 --outdir ./out
After counting. Each round_NN/counts.parquet has one row per unique
sequence (sequence, reads, rank, rpm). To follow sequences across
rounds:
import pandas as pd
rounds = (0, 3, 6)
rpm = pd.DataFrame(
{r: pd.read_parquet(f"out/round_{r:02d}/counts.parquet").set_index("sequence")["rpm"] for r in rounds}
).fillna(0)
rpm["enrichment"] = (rpm[rounds[-1]] + 1) / (rpm[rounds[0]] + 1)
rpm.sort_values("enrichment", ascending=False).head(20).to_csv("top_enriched.tsv", sep="\t")
qc/flags.yaml lists what qc found suspicious:
| Flag | Raised when |
|---|---|
low_total_reads |
a round has fewer than 10,000 reads |
low_primer_match |
the primers are found in too few reads |
adapter_contamination_high |
a known sequencing adapter is in more than 5% of the reads |
strand_mix |
more than 20% of a round's reads are in the reverse orientation |
n_length_variation_across_rounds |
the rounds have more than two different most-common random-region lengths |
unexpected_rarefied_diversity_increase |
diversity at equal depth goes up in a later round |
extraction_mode_changed_across_rounds |
datasets of one project were extracted in different modes |
requires_read_merging_for_full_insert |
the primers are split between R1 and R2 |
"My reads are paired-end (R1 + R2)"
Common for modern Illumina SELEX — and handled for you from an accession:
run detects the paired layout at fetch time and threads R2 through with no
extra flags. By hand on local files, list both R1 and R2 files in the round
map, pass the R1 files as arguments and each R2 file with its own --paired-r2,
one R2 per R1:
printf 'file\tround_number\nr0_R1.fastq.gz\t0\nr0_R2.fastq.gz\t0\nr1_R1.fastq.gz\t1\nr1_R2.fastq.gz\t1\n' > rounds.tsv
selexprep detect r0_R1.fastq.gz r1_R1.fastq.gz \
--paired-r2 r0_R2.fastq.gz --paired-r2 r1_R2.fastq.gz \
--round-map rounds.tsv --outdir ./out
selexprep extract r0_R1.fastq.gz r1_R1.fastq.gz \
--paired-r2 r0_R2.fastq.gz --paired-r2 r1_R2.fastq.gz \
--library-report ./out/library_report.json --round-map rounds.tsv --outdir ./out
If the 5' primer sits on R1 and the 3' on R2, detect reports
extraction_mode: PAIRED_END_SPLIT_PRIMERS and extract writes the two trimmed
sides separately (partial_5p_extracted_R1… + partial_3p_extracted_R2…). It
stops there on purpose: stitching the sides into one full-length insert is read
merging, not yet implemented, so count/qc are skipped for split-primer rounds
rather than counting half-inserts.
"I only have the final enriched pool (a single round)"
The common case — HT-SELEX is costly, so many experiments sequence only the
final pool. selexprep still works; pass a one-row round map:
printf 'file\tround_number\nfinal_pool.fastq.gz\t0\n' > rounds.tsv
selexprep detect final_pool.fastq.gz --round-map rounds.tsv --outdir ./out
The one difference: confidence is capped at MEDIUM, because cross-round
persistence (the strongest SELEX-specific primer signal) needs ≥2 rounds.
detect warns and falls back to within-round signals (primer match rate, flank
position, low-entropy region, adapter blacklist). Verify the inferred primers
before trusting extraction — or, if you designed the library and know the
primers, pass them with --override-primer-5p/3p and the confidence cap no
longer applies (you're not inferring anything).
"detect returned UNABLE_TO_INFER"
By design, extract then refuses rather than guessing. Supply the primers
explicitly:
selexprep extract round_*.fastq.gz \
--library-report ./out/library_report.json --round-map rounds.tsv \
--override-primer-5p GGTAATACGACTCACTATAGGG \
--override-primer-3p CCATGCATGCATGCATGCAT \
--rebuild --outdir ./out
# With --rebuild the outputs go to ./out; without it, to ./out/overridden/ so an
# earlier extraction is kept. If ./out already holds an extraction, --rebuild also
# writes extract_diff.tsv comparing it with the new one, round by round.
You can also edit library_report.json by hand and re-run without overrides.
Multiplexed deposit (several samples or targets pooled in one FASTQ)?
selexprepdoesn't split them automatically — pass a--sample-sheettoextractin place of--round-map.
CLI reference
The core pipeline is inspect → fetch → detect → extract → count → qc; run
batches it and catalog browses the discovery catalog. Every command supports
--help; full reference in docs/cli.md.
| Command | What it does |
|---|---|
selexprep inspect <ACC> |
ENA metadata preview — runs with read and base counts, library_strategy (SRA verbatim), file sizes (MD5s in inspect.json). No download. |
selexprep fetch <ACC> --outdir OUT |
Download FASTQ + auto-populate rounds.tsv. Unassigned runs go to round_unknown/ only with --allow-manual-review. |
selexprep detect <fastq...> --round-map rounds.tsv --outdir OUT |
Auto-infer primers + library structure → library_report.json. |
selexprep extract <fastq...> --library-report LR.json --round-map rounds.tsv --outdir OUT |
Cutadapt trim + per-round FASTA + manifest; reads of a library sequenced on the reverse strand (orientation: REVERSE) are reverse-complemented first. Accepts --paired-r2, --sample-sheet, --override-primer-{5p,3p}, --extraction-mode, --rebuild. |
selexprep count <extracted.fasta.gz> --round R0 --outdir OUT |
FASTA → counts.parquet (sequence, reads, rank, RPM). |
selexprep qc <manifest> --outdir OUT |
Depth-aware suspicion flags (YAML) + 4 PNG plots. |
selexprep run <accessions.tsv> --outdir OUT [--resume] |
Batch driver across many accessions; emits run_summary.tsv + per-accession outputs. |
selexprep catalog list | show | version | refresh |
Browse / refresh the bundled discovery catalog (240 entries; refresh hits live ENA). |
Full output layout
After a complete single-dataset run:
out/
├── library_report.json # primer inference + extraction_mode
├── selexprep_manifest.json # reproducibility anchor
├── trim_reports.json # cutadapt argv + n_in/n_out per round
├── strand_report.tsv # only if orientation ∈ {MIXED, REVERSE}
├── extract_diff.tsv # only with --rebuild + --override-primer-*
├── round_00/
│ ├── extracted.fasta.gz # full-insert recovery (BOTH_PRIMERS_SINGLE_READ)
│ │ # or partial_5p_extracted.fasta.gz (FIVE_PRIME_ONLY)
│ │ # or partial_3p_extracted.fasta.gz (THREE_PRIME_ONLY)
│ │ # or partial_5p_extracted_R1.fasta.gz + partial_3p_extracted_R2.fasta.gz (PAIRED_END_SPLIT_PRIMERS)
│ └── counts.parquet # unique sequences
├── round_NN/...
└── qc/
├── flags.yaml # depth-aware suspicion flags
├── read_retention.png # input vs extracted per round
├── primer_match_per_round.png
├── n_length_distribution.png # per-round N-region histograms (faceted)
└── per_round_panel.png # unique seqs + Shannon entropy + top-100 coverage
Output filenames deliberately distinguish full inserts (extracted.fasta.gz)
from one-sided partials (partial_5p_… / partial_3p_…) so downstream ML
pipelines never accidentally mix them.
Why it exists (the gap)
No maintained, pip-installable Python tool takes a public HT-SELEX accession or local FASTQ and produces trimmed per-round FASTAs + count tables + a provenance manifest without requiring the user to supply primers.
| Tool | Accession fetch? | Primer auto-inference? | Safe failure mode? |
|---|---|---|---|
| AptaSUITE (CLI + GUI) | ✗ | ✗ — user supplies | ✗ |
| FASTAptameR | ✗ — consumes already-trimmed | ✗ | ✗ |
| EasyDIVER+ (2025) | ✗ | ✗ — paired-end with known primers | ✗ |
| ht-selex-demo | ✗ | ✗ — Illumina adapters only (a trap selexprep guards against via known_adapter_hits) |
✗ |
| nf-core | ✗ (no SELEX pipelines exist) | — | — |
selexprep |
✓ — INSDC (figshare/Zenodo deferred) | ✓ — positional conservation, checked across rounds + adapter blacklist | ✓ — explicit LibraryReport.status ∈ {HIGH, MEDIUM, LOW, UNABLE_TO_INFER} |
The core inference idea: the constants are conserved at a fixed position in
every read, while the random region is still diverse in the earliest round.
detect places the boundary where positional conservation falls in the earliest
round provided, keeps only the part of the constant that every round shares, and
scores the call by its consistency, persistence across rounds, match rate and
adapter matches. It reports its confidence in a typed LibraryReport (pydantic,
strict-mypy) with explicit
extraction_mode, read_source, required_action, full_insert_recovered,
and status. status rates how well the reads support the inferred primers, not
a verified boundary: sequence conserved inside the random region itself can be
taken for constant (see Known limits).
Benchmark headline: on a curated, paper-grounded set, selexprep recovers
SELEX primers directly from raw reads — with none supplied — and fails safe (no
fabricated primers) where inference is ambiguous. See
Benchmarks.
What selexprep ships
catalog (240 public SELEX entries: 127 INSDC + 113 figshare/Zenodo
passthrough; documented exclusions in bioprojects_excluded.csv) · inspect
(ENA metadata preview) · fetch (accession download with relaxed
partial-parseability contract) · detect (primer inference) · extract
(cutadapt-driven trimming + paired-end + strand handling) · count (per-round
unique sequences) · qc (suspicion flags + 4 PNG plots) · run (batch driver
with --resume).
Catalog discovery completeness is auditable via
benchmarks/catalog_completeness_audit.py (it re-queries live ENA): as of the
v0.2.1 snapshot (2026-07-03) every ENA-typed-SELEX study is accounted for —
either included, or documented in bioprojects_excluded.csv (mis-labeled and
gSELEX/genomic-fragment variants). Because ENA grows over time, the audit is the
source of truth rather than a frozen percentage.
Not yet implemented (deferred to a future release): read merging for
paired-end full-insert recovery · multiplex auto-detection (currently needs a
user-supplied sample sheet) · figshare/Zenodo fetch backends ·
SELEXPREP_CATALOG_PATH env var for user-supplied catalogs · AnnData export ·
BibTeX auto-citation · library-type classification.
Curated metadata layer
Curated metadata layer (selexprep.catalog.load_metadata /
load_metadata_records) — each of the 240 catalog deposits ships with curated
experimental metadata: study_type, target, target_class, chemistry,
n_random, n_rounds, selection_format, counter_selection (240 × 8 = 1920
cells, 1491 populated). Built by two
independent LLM extractions (Claude + Codex/GPT), reconciled, with every value
source-cited (evidence quote + DOI/URL + location); where the two extractions
disagreed, both readings are kept. Bundled as curated_metadata.json (canonical,
provenance-rich) + curated_metadata.csv (flat view) under catalog/data/, accessed
via the API above. Each value records whether the two extractions agreed, one
found it, or a disagreement was resolved against the sources; agreement is
recorded as concordance, not as verification. The extraction contract, both raw arms, and the reconciliation
live under benchmarks/dual_extraction/ in the source repository.
What selexprep does not do
By design — these are handled by mature tools that consume selexprep's outputs:
| Step | Use |
|---|---|
| Clustering | FASTAptameR |
| Motif discovery | MEME · RaptGen-UI |
| Sequence–structure motif scoring, aptamer ranking | APTANI2 — takes the raw FASTQ of one round, not the extracted FASTA, with the flanking constants and read length as parameters; detect reports both |
| Binding-affinity prediction | RaptGen · DeepSELEX · AptaTrans |
| 3D structure | ViennaRNA · RNAfold |
| Aptamer design | MAWS · RNAtranslator |
| Read merging (paired-end full-insert recovery) | bbmerge · vsearch · pear (planned hook) |
Determinism + reproducibility
All .fasta.gz, .tsv, and .json outputs are byte-deterministic given
the same --sampling-seed: gzip headers use mtime=0, JSON keys are sorted
(int keys in numeric order), TSV rows are sorted. Two runs with identical inputs
- seed produce identical SHA256s; the manifest's
output_sha256is the audit anchor. The one exception istrim_reports.json, which records the cutadapt command with its file paths, so its hash also depends on the output directory.
Parquet hashes are advisory (not guaranteed across pyarrow versions — the
manifest pins pyarrow_version instead). PNG plots are informational
(matplotlib output isn't byte-deterministic) and don't contribute to
output_sha256.
Benchmarks
Benchmarks under benchmarks/:
- Tier 1 — primer-recovery scorecard (
Snakefile+ground_truth.tsv): curated primer-recovery validation against paper-reported primers (N=21 source-verified accessions, modality-diverse, in three arms: 7 recovery, 8 pre-trimmed specificity controls, 6 adapter controls), reported as a per-deposit table. - Semi-synthetic benchmark (
synthetic/): real random regions placed between the published constants of other libraries, so the true boundary is known in every read. 52 conditions (constant length, sequencing errors, run-specific tags, adapters, rounds provided, a dominant clone, depth, …); the design and expectations were registered before any library was generated, and the test set was run once at a frozen version. - Tier 2 — corpus audit (
audit.smk): corpus utility audit over a random sample of audit-eligible INSDC catalog rows. Shipped artifacts underbenchmarks/audit_results/; the reproducibility envelope (catalog version + sample sha256 + seed) is committed. - Catalog completeness audit (
catalog_completeness_audit.py): re-runnable script diffingbioprojects.csvagainst ENA'slibrary_strategy="SELEX"set, so coverage can be re-verified against a current, dated snapshot rather than a frozen figure (ENA grows over time).
Development
uv run pytest # full suite + 1 reserved xfail
uv run ruff check src/ tests/
uv run ruff format --check src/ tests/
uv run mypy src/ # strict on library.report
CI matrix: Python 3.10 / 3.11 / 3.12.
Citation
If you use selexprep, cite the archived release you ran:
doi:10.5281/zenodo.21240947 resolves to
the latest version and lists the DOI of every release (0.4.7 is
doi:10.5281/zenodo.23964802). Citation metadata is in CITATION.cff.
License
MIT. See LICENSE. Full development log in CHANGELOG.md.
Metadata
Release files for selexprep 0.4.8
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| selexprep-0.4.8.tar.gz | 1.8 MB | With provenance | Details for selexprep-0.4.8.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| selexprep-0.4.8-py3-none-any.whl | Python 3 | none | any | Details for selexprep-0.4.8-py3-none-any.whl |
Total release size: 2.2 MB
Release files / selexprep-0.4.8.tar.gz
| Download URL | selexprep-0.4.8.tar.gz |
|---|---|
| Size | 1.8 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2b5e7cac4242453ef95f0a81cdaf15f3ee1c9d87d87853a8fca9a2e6632d3038
|
|
BLAKE2b-256 checksum How to use checksums |
5239cbac8475da23a7e4b72b88cd5962c8eafe81496295db6de79b1b9f40ca70
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.
Transparency logRelease files / selexprep-0.4.8-py3-none-any.whl
| Download URL | selexprep-0.4.8-py3-none-any.whl |
|---|---|
| Size | 410.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2bf9fac4f09092dc5242b20f9c18de3b8f8d20b44fc1b2d99a544c1cc1b20801
|
|
BLAKE2b-256 checksum How to use checksums |
e371a369f35c4eec5f95672aebd032af137f05706d1a13ea6f8d10f6a2a97a92
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.
Transparency logSecurity for selexprep 0.4.8
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for selexprep-0.4.8.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.