Metadata-Version: 2.4
Name: ferroseq
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Operating System :: OS Independent
Requires-Dist: polars>=2.2
Requires-Dist: pandas>=2.0 ; extra == 'pandas'
Requires-Dist: pyarrow>=14 ; extra == 'pandas'
Requires-Dist: pytest>=8 ; extra == 'test'
Requires-Dist: biopython>=1.80 ; extra == 'test'
Requires-Dist: pandas>=2.0 ; extra == 'test'
Requires-Dist: pyarrow>=14 ; extra == 'test'
Provides-Extra: pandas
Provides-Extra: test
License-File: LICENSE
Summary: Fast, vectorised biological sequence analysis for Polars and pandas, powered by Rust.
Keywords: bioinformatics,polars,pandas,dna,fasta,fastq,genomics,rust
Author: ferroseq contributors
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/cblly/ferroseq
Project-URL: Issues, https://github.com/cblly/ferroseq/issues

# ferroseq

**Fast, vectorised biological-sequence analysis for Polars and pandas, written in Rust — plus a seqkit-style command line.**

pandas gave Python a table you can compute on column by column. ferroseq does the same for DNA, RNA
and protein sequences: it adds a `.seq` namespace to Polars and pandas whose methods (GC content,
reverse complement, translation, IUPAC motif search with mismatches, k-mers, quality scores, and more)
run as compiled Rust across every row at once, in parallel, without a Python loop. Files of any size
stream through lazily, and a `ferroseq` command covers the everyday FASTA/FASTQ jobs.

```python
import polars as pl
import ferroseq as fs   # importing registers `.seq`

clean = (
    fs.scan_fastq("reads.fastq.gz")                     # lazy + streaming: any file size
    .pipe(fs.quality_trim, 20)                          # BWA/cutadapt 3' trimming
    .with_columns(
        gc=pl.col("sequence").seq.gc_content(),
        ee=pl.col("quality").seq.expected_errors(),
        has_site=pl.col("sequence").seq.contains_motif("GAATTC", max_mismatches=1),
    )
    .filter(pl.col("ee") <= 1.0)
    .collect(engine="streaming")
)
fs.write_fasta(clean, "clean.fa.gz")
fs.stats("reads.fastq.gz")                              # seqkit-stats-compatible summary
```

```bash
ferroseq stats *.fastq.gz                               # N50, Q20/Q30, GC, quartiles, ...
ferroseq grep -s GATTACA -m 1 -B reads.fq.gz -o hits.fq.gz
ferroseq trim -q 20 --min-len 50 reads.fq.gz | ferroseq filter --max-ee 1 -o clean.fq.gz
```

The same methods work on a pandas Series:

```python
import pandas as pd, ferroseq
pd.Series(["ATGGCCTAA", "GGNNATRY"]).seq.reverse_complement()   # index preserved
```

## Why another library?

| Need | Use |
|---|---|
| Genomic **intervals**: overlap, nearest, coverage on BED/VCF/BAM | [polars-bio](https://github.com/biodatageeks/polars-bio), [pyranges1](https://github.com/pyranges/pyranges1) |
| Per-record **sequence** computation inside a dataframe, and fast FASTA/FASTQ chores | **ferroseq** |
| Alignment, phylogenetics, structures, a bit of everything | [Biopython](https://biopython.org), [Biotite](https://www.biotite-python.org) |

ferroseq complements these: it replaces the slow Python loop (`[gc_fraction(s) for s in seqs]`,
`[str(Seq(s).translate()) for s in seqs]`) and the shell-out to a CLI for routine read processing.

## Install

```bash
pip install ferroseq                                  # wheels: Linux, macOS, Windows; Python 3.11+
conda install -c conda-forge -c bioconda ferroseq     # once the Bioconda recipe is merged
pip install "ferroseq[pandas]"                        # with the pandas accessor dependencies
```

From source (needs a Rust toolchain): `pip install maturin && maturin develop --release`.

## Expression API

Every method is available as `pl.col(...).seq.<method>()`, `polars_series.seq.<method>()` and
`pandas_series.seq.<method>()`.

| Method | Returns | Notes |
|---|---|---|
| `gc_content()` | f64 | (G+C+S)/(G+C+S+A+T+U+W), case-insensitive; = Biopython `gc_fraction(ambiguous="remove")` |
| `gc_skew()` / `entropy()` | f64 | (G−C)/(G+C); Shannon entropy in bits |
| `is_valid(alphabet="dna", iupac=False, allow_gaps=False)` | bool | `"dna"`, `"rna"`, `"protein"` |
| `reverse_complement(rna=False)` / `complement()` / `transcribe()` / `back_transcribe()` | str | IUPAC aware, case preserving |
| `translate(table=1, to_stop=False)` | str | NCBI tables 1–6, 11; ambiguous codons as Biopython (`GCN`→A, `SAA`→Z, else X) |
| `count_motif(motif, both_strands=False, max_mismatches=0)` | u32 | IUPAC motif, overlapping matches, ≤k substitutions |
| `contains_motif` / `find_motif` / `motif_positions` (same arguments) | bool / u32 / list[u32] | 0-based starts |
| `kmers(k, canonical=False)` | list[str] | or `fs.kmer_counts(frame, k)` for a frequency table |
| `count_bases(letters)` | u32 | e.g. `"GCgc"`, `"Nn"`, `"- ."` |
| `hamming(other)` / `levenshtein(other)` | u32 | `other` is a column or a string literal |
| `mean_phred()` / `mean_error_phred()` / `expected_errors()` | f64 | arithmetic vs probability-averaged quality; USEARCH `maxee` |
| `count_quality_at_least(min_q)` | u32 | bases ≥ Q (Q20/Q30 counts) |
| `quality_trim_index(threshold=20)` | u32 | length to keep after 3' trimming |

## I/O, streaming and helpers

| Function | What it does |
|---|---|
| `read_fastx / read_fasta / read_fastq(source, columns=None, n_rows=None)` | eager read; `source` = path, `"-"` (stdin), bytes or file object; plain or gzip |
| `scan_fastx / scan_fasta / scan_fastq(source)` | **LazyFrame** with projection, limit and predicate pushdown; `collect(engine="streaming")` for files larger than memory |
| `iter_batches(source, batch_size)` | bounded-memory iteration over DataFrame batches |
| `write_fasta / write_fastq(frame, path)` | Polars/pandas DataFrame **or LazyFrame**; `"-"` = stdout; `.gz` = gzip; descriptions kept |
| `stats(*sources)` | one row per input, same definitions as `seqkit stats -a` |
| `quality_trim`, `filter_reads`, `kmer_counts`, `show_versions` | common read processing; version report for bug reports |

**`fs.stats` and seqkit.** Columns are `seqkit stats -a`'s in snake_case (`q20_pct` = `Q20(%)`,
`n50_num` = `N50_num`, …) with the same definitions; the test suite compares them against the real
seqkit on randomised files. Two things to know: seqkit's table printer sometimes rounds for display
(quartile 12.5 shows as `12`), and seqkit before 2.15 computed `N50_num` (L50) by counting distinct
lengths rather than records — ferroseq uses the corrected definition seqkit adopted in 2.15.

## Command line

`ferroseq <command> [input] [-o output]` — inputs and outputs default to stdin/stdout, `.gz` outputs
are compressed, FASTQ stays FASTQ unless the output name says FASTA. Every command streams in batches.

| Command | Does | seqkit analogue |
|---|---|---|
| `stats [-T] [-b] [--seqkit-names] files…` | summary statistics table | `stats -a` |
| `grep -s MOTIF [-m K] [-B] [-r ID_REGEX] [-v]` | keep records by IUPAC motif (≤K mismatches, both strands) and/or ID regex | `grep -s -m` |
| `filter [--min-len] [--max-len] [--max-ee] [--min-mean-q] [--max-n-frac] [--min-gc] [--max-gc]` | read filtering | `seq -m/-M` + others |
| `trim [-q 20] [--min-len 1]` | 3' quality trimming | — (cutadapt `-q`) |
| `convert [--to fasta\|fastq]` | FASTQ→FASTA, gzip ↔ plain | `fq2fa`, `seq` |
| `fx2tab [-l] [-g] [-q] [-H]` | FASTA/FASTQ → TSV with length, GC, mean quality | `fx2tab` |

`python -m ferroseq …` works too.

## Performance

**Python API** — 500,000 reads × 150 bp (75 Mbp), single thread (`POLARS_MAX_THREADS=1`), best of three,
on a 2-vCPU cloud VM (`python bench/bench.py`). Timings on a shared VM vary by ±30% between runs.

| Task | Alternative | Alternative | ferroseq | Speed-up |
|---|---|---:|---:|---:|
| GC content | Biopython `gc_fraction` loop | 1.223 s | 0.044 s | **28×** |
| GC content | pandas `.str.count` | 8.335 s | 0.044 s | **191×** |
| Reverse complement | Biopython loop | 0.480 s | 0.035 s | **14×** |
| Reverse complement | Python `str.translate()[::-1]` loop | 0.238 s | 0.035 s | **6.8×** |
| Translate (table 1) | Biopython `Seq.translate` loop | 6.651 s | 0.121 s | **55×** |
| Expected errors | NumPy (`join` + `reduceat`) | 0.415 s | 0.042 s | **10×** |
| Read FASTQ → DataFrame | Biopython `FastqGeneralIterator` → pandas | 1.058 s | 0.137 s | **7.7×** |
| IUPAC motif `RGATCY` | Python `re` loop | 1.150 s | 0.070 s | **16×** |
| IUPAC motif `RGATCY` | Polars regex `[AG]GATC[CT]` | 0.043 s | 0.070 s | 0.6× (slower) |

With two threads ferroseq times roughly halve.

**Command line vs seqkit 2.13** — same 500,000-read FASTQ (158 MB), wall clock including interpreter
start-up, best of three (`python bench/bench_cli.py`):

| Task | ferroseq | seqkit | |
|---|---:|---:|---:|
| `stats` (plain FASTQ) | 0.33 s | 0.67 s | **2.0× faster** |
| `stats` (gzip FASTQ) | 0.72 s | 0.99 s | **1.4× faster** |
| `grep` motif, both strands | 0.44 s | 1.00 s | **2.3× faster** |
| `grep` motif, ≤1 mismatch | 0.50 s | 18.13 s | **36× faster** |
| FASTQ → FASTA | 0.26 s | 0.16 s | 0.6× (slower) |

Where ferroseq is slower: a plain regex motif in Polars (SIMD prefilter, non-overlapping matches), and
FASTQ→FASTA conversion, where Python start-up (~0.14 s) is most of the gap.

## Design

```
python/ferroseq/          Python API: .seq namespaces (Polars + pandas), scan/read/write, stats, CLI
        │  Polars expression plugin + IO plugin (FFI, Arrow buffers)
src/                      PyO3 bindings: parallel batching, streaming FASTX reader/writer, stats histogram
        │
crates/ferroseq-core/     pure-Rust kernels on &[u8]; no Python dependency; usable as a Rust crate
```

- **Expression plugin, not Python callbacks**: methods run inside Polars' engine (lazy, streaming, `group_by`, no GIL).
- **Lookup tables and bit-parallel scans**: complement, GC and quality use 256-entry tables; motifs up to
  64 bp use shift-and (bitap), extended to k substitutions, so search cost doesn't grow with motif length.
- **Correctness against references**: GC, complements, all 64 codons × 7 tables and all 3,375 IUPAC codons
  are checked against Biopython; `stats` and `grep -m` against seqkit; motifs, k-mers, distances and
  quartiles against plain-Python reference implementations (300+ tests).

## Development

```bash
cargo test -p ferroseq-core
python -m venv .venv && . .venv/bin/activate
pip install maturin polars pytest biopython pandas pyarrow
maturin develop --release
pytest                                   # set SEQKIT=/path/to/seqkit to run the seqkit comparisons
python bench/bench.py 500000 && python bench/bench_cli.py 500000
```

See [CONTRIBUTING.md](CONTRIBUTING.md) to add a kernel (about 30 lines across three layers).

## Releasing

1. Bump the version in `Cargo.toml` and date the entry in `CHANGELOG.md`.
2. Tag and push, e.g. `git tag v0.2.0 && git push origin v0.2.0`. The release workflow builds and tests wheels
   and uploads them to PyPI via trusted publishing (workflow `release.yml`, environment `pypi`).
3. Bioconda's autobump bot opens the version-update PR for the recipe; see
   [packaging/bioconda/README.md](packaging/bioconda/README.md).

## License

MIT

