Metadata-Version: 2.4
Name: norvara-seq-format
Version: 1.0.0rc5
Summary: Convert sequence files between FASTA, FASTQ, GenBank and tabular formats, with no third-party dependencies
Author-email: Norvara Therapeutics <research@norvaratx.com>
Maintainer-email: Norvara Therapeutics <research@norvaratx.com>
License-Expression: PolyForm-Noncommercial-1.0.0
Project-URL: Homepage, https://github.com/Norvara-Therapeutics/seq-format
Project-URL: Repository, https://github.com/Norvara-Therapeutics/seq-format.git
Project-URL: Issues, https://github.com/Norvara-Therapeutics/seq-format/issues
Keywords: bioinformatics,fasta,fastq,genbank,file-format,sequence-analysis
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pyflakes>=3; extra == "dev"
Dynamic: license-file

# seq-format

Convert sequence files between FASTA, FASTQ, GenBank flat files and tabular
JSON, CSV and TSV, filtering records on the way. Every conversion reports what
the target format could not carry, so nothing is lost quietly. Pure Python with
no third-party dependencies.

## Install

Install the prerelease from PyPI:

```bash
python -m pip install --pre norvara-seq-format
```

The Python package and command keep the shorter project name:

```python
import seq_format
```

```bash
seq-format --version
```

## Quickstart

```bash
seq-format convert -i examples/phix174.gb --to fasta -o phix174.fasta
```

```
  read     1 record  genbank  examples/phix174.gb
  wrote    1 record  fasta
  note     1 annotation dropped: FASTA output does not carry them
```

The converted data goes to standard output unless `-o` names a file; the
summary always goes to standard error, so `seq-format` sits in a pipe without
a reader having to strip a report out of the data.

Filters are reported the same way, filter by filter:

```bash
seq-format convert -i examples/phix174_reads.fastq --to fasta -m 100 --min-quality 28
```

```
  read     50 records  fastq  examples/phix174_reads.fastq
  filtered         2 dropped  length < 100
  filtered        15 dropped  mean quality < Q28
  dropped  17 records of 50 (34.0%)
  wrote    33 records  fasta
  note     33 quality strings dropped: FASTA output does not carry them
```

A record is counted against the first filter that rejects it, so the counts
sum to the number dropped.

## Options

```
-i, --input PATH         file to convert, or '-' for standard input;
                         repeat to concatenate
-o, --output PATH        where to write; '-' is standard output (default: -)
    --from FORMAT        auto | fasta | fastq | genbank | json | csv | tsv
    --to FORMAT          output format; taken from the --output name when
                         not given, and FASTA when that says nothing
    --alphabet           auto | nucleotide | protein | any (default: auto)
```

Filtering:

```
-m, --min-length N       drop records shorter than N residues
-M, --max-length N       drop records longer than N residues
    --max-ambiguous N    drop records with more than N ambiguity codes;
                         a trailing '%' makes it a share, as in '2%'
    --no-ambiguous       drop records containing any ambiguity code
    --min-quality Q      drop records whose mean Phred score is below Q
                         (--phred sets the offset the input is written in)
    --id ID              keep only this identifier; repeat for several
    --exclude-id ID      drop this identifier; repeat for several
    --limit N            stop after the first N records of each input
```

`--id-file` and `--exclude-id-file` take the same identifiers from a file, one
per line.

Output shaping:

```
    --line-width N       wrap FASTA at N characters; 0 writes one line
                         (default: 60)
    --case               preserve | upper | lower (default: preserve)
    --columns LIST       columns for CSV and TSV output (default: auto)
    --fill-quality CHAR  give records with no quality string one made of
                         this character, so FASTQ output is possible
    --on-duplicate       keep | rename | drop | error (default: keep)
    --summary PATH       write the summary to PATH as JSON
-q, --quiet              do not write the summary to standard error
```

`seq-format formats` prints which format carries what, and `--indent` sets the
JSON indent.

## Formats

| Format | Description | Quality | Annotations | Extensions |
| --- | --- | --- | --- | --- |
| `fasta` | yes | no | no | `.fasta` `.fa` `.fna` `.faa` `.ffn` `.frn` `.fas` `.seq` |
| `fastq` | yes | yes | no | `.fastq` `.fq` |
| `genbank` | yes | no | yes | `.gb` `.gbk` `.genbank` `.gbff` |
| `json` | yes | yes | yes | `.json` |
| `csv` | yes | yes | no | `.csv` |
| `tsv` | yes | yes | no | `.tsv` `.tab` |

Compressed input is recognised from its magic bytes, so gzip, bzip2 and xz
files need no flag and no particular name; compressed output is chosen from the
output name. Gzip output carries neither a timestamp nor the file name, so the
same input gives the same bytes.

## Reading the output

- **Round trip.** A conversion into a format that carries every field of the
  source and back again returns the original bytes. The test suite asserts
  this for an NCBI GenBank record through JSON and back, feature table and
  citations included, and for anything this tool writes as GenBank being read
  by it again.
- **Loss reporting.** What a target cannot carry is counted and named;
  `--summary` writes the same account as JSON, with a per-filter breakdown and
  unrounded figures. `json` is the only format that carries everything, and
  `genbank` the only one that carries a feature table.
- **Columns.** `auto` writes `id`, `description` and `sequence`, plus
  `quality` when the input has some or `--fill-quality` will supply it;
  `--help` lists the twenty that can be named, from `length` and `ambiguous`
  to `organism` and `feature_count`. A list that leaves out the sequence or
  the identifier is allowed — a table of accessions and lengths is a
  reasonable thing to want — but both are counted, and the summary says such a
  table cannot be read back as sequence data.
- **Tabular input** needs a header row; `id`, `name`, `seq`, `bases`,
  `quality` and the other usual titles are recognised. A table with no
  identifier column has its records numbered `seq_1`, `seq_2`, and the summary
  says so. An empty quality cell means no quality, except for a zero-length
  read, where it is the quality.
- **FASTQ** output needs a quality string for every record. Where the input
  has none the conversion is refused before anything is written, rather than
  filled with a placeholder a reader would take for a measurement;
  `--fill-quality` supplies one deliberately and is reported as synthetic.
- **A GenBank header has to hold together.** The lineage is nested under
  ORGANISM under SOURCE, so an organism with no SOURCE is given one and a
  lineage with no organism is refused rather than written as a bare
  continuation of SOURCE. A LOCUS line built from an input that is not a flat
  file carries only the name, length and unit: no topology, division or date
  is invented. A record that declares its sequence by reference keeps its
  CONTIG block and the length LOCUS gave, and gets no empty ORIGIN block.
- **Nothing is quietly corrected.** A FASTQ `+` line naming a different read,
  a quality character outside printable ASCII, and a LOCUS line declaring a
  length the ORIGIN block does not hold are all refused. No option is silently
  ignored either: several apply to one target only, and one that was set and
  cannot be honoured is reported on standard error.
- **An output replaces its target only once it is complete.** A conversion to
  a file writes a neighbour and renames it into place, so a run that fails —
  even partway through — leaves whatever was there before, and everything that
  can be judged up front is judged before a byte is written. A device such as
  `/dev/null` is written directly, having nothing to protect.
- **An unrecognised column or JSON key is named** in the summary, since a
  record has nowhere to keep it. Every column the writer offers that holds a
  stored field can be read back; `length`, `ambiguous`, `gaps` and
  `feature_count` are computed from the record, so reading them would be
  meaningless rather than lossy.
- **Nothing is quietly destroyed.** An output path is refused when it names
  any file the conversion still has to read — a sequence input, `--id-file`,
  `--exclude-id-file` — including by a hard link, which comparing resolved
  paths does not reveal. `--id-file` asks to keep only what it lists, so a
  file of only comments selects nothing; not passing the option is what keeps
  everything. `--on-duplicate rename` suffixes the LOCUS name and whichever of
  VERSION or ACCESSION the identifier came from, so a renamed record is
  distinct when the output is read back, not only in the summary.
- **Text that cannot be a line** is flattened: a header spanning lines would
  be read back as a new record or a new keyword, so it is written as one line
  and the records affected are counted. `--case lower` writes the lowercase
  ORIGIN block a flat file conventionally carries; the default preserves
  whatever the input had.
- **Ambiguity** means the IUPAC ambiguity codes — N and friends for
  nucleotides, X and friends for amino acids. Alignment gaps are counted
  separately and a translation terminator is not ambiguity.

## Performance

One streaming pass, with memory set by the longest single record rather than
the file: a 155 MB FASTQ of 500,000 reads converts to FASTA in 1.4 s and to
JSON in 3.0 s, both at a peak RSS of 17 MB.

## Limitations

- JSON input is the exception to the streaming: a document is a single value,
  and a parser that stopped halfway could not tell a truncated file from a
  complete one. Reading a 201 MB JSON document peaks at 775 MB. JSON output
  streams like everything else.
- Output to standard output is written as records are read, so an input that
  fails partway has already emitted the records before it. A conversion to a
  named file does not have that problem: it is renamed into place only on
  success.
- A GenBank value longer than one line is rejoined with a space when read,
  which is how the format wraps prose and how every reader of it puts prose
  back together. A word too long to fit — over 67 characters in a DEFINITION,
  58 in a qualifier — therefore cannot be written faithfully and is refused.
  A location and a `/translation` are rejoined with nothing between them, so
  those wrap at any length; reading a file that already breaks such a word
  gains the space, and writing it back reproduces the file exactly.
- REFERENCE, COMMENT and DBLINK blocks are carried verbatim and replayed in
  place rather than parsed, which is what makes the round trip exact. Feature
  locations are likewise kept as written: `join(3981..5386,1..136)` survives a
  round trip but is never resolved, so no feature is extracted or translated.
- Line-wrapped FASTQ is refused rather than guessed at. The format gives no
  reliable way to tell a wrapped quality line from the next header.
- Zstandard is neither read nor written: there is no standard-library support
  for it before Python 3.14. A `.zst` input or output is refused by name
  rather than silently handled as plain text.
- With `--alphabet auto`, text that happens to spell amino acids is accepted as
  protein: `Helloworld` is H-E-L-L-O-W-O-R-L-D. `--alphabet nucleotide`
  refuses what was never meant to be a sequence.
- Sequences are never translated, complemented or transcribed. This converts
  between file formats, not between molecules.

## Examples

`examples/phix174.fasta` and `examples/phix174.gb` are the NCBI record
NC_001422.1. `phix174_cds.csv` is cut from that genome at the coordinates of
its simple-span coding sequences, and `phix174_reads.fastq` is a simulated read
set written by `examples/make_examples.py` on a fixed seed — it is not
sequencing data. A test regenerates both byte for byte.

## Development

```bash
pip install -e ".[dev]"
pytest -q
python -m pyflakes src/seq_format tests
```

## License

Licensed under the
[PolyForm Noncommercial License 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0).
See [LICENSE](LICENSE) for the complete terms.
