Metadata-Version: 2.4
Name: fastasma
Version: 0.1.6
Summary: A collection of tools for working with FASTA files.
Author-email: Daniel Pérez-Rodríguez <daniel.perez.rodriguez@uvigo.es>
License: MIT License
        
        Copyright (c) 2026 Daniel Pérez Rodríguez
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Dynamic: license-file

# fastasma

A modular toolkit for FASTA file processing, built around a pipeline of composable operations.

## Installation

```bash
pip install fastasma
```

## Core concepts

All modules implement the `SequenceSource` protocol — an iterable that yields `Sequence` objects (`header`, `sequence`, `annotation`). This allows arbitrary chaining:

```python
output = LastStep(Step2(Step1(ImportFasta("input.fasta"))))
```

## Quick start

```python
import fastasma

source = fastasma.ImportFasta("input.fasta")
source = fastasma.DropAnnotationKeys(source, keys_to_remove=["length"])
source = fastasma.AddAnnotationToHeader(source, annotation_key="organism", position="suffix")
source = fastasma.Head(source, n=10)
fastasma.WriteFasta(source, output_path="output.fasta")
```

## Modules

### Importers

| Class | Description |
|---|---|
| `ImportFasta(filepath)` | Reads a single FASTA file. Parses header annotations in `[key=value]` format. |
| `ImportFastas(filepaths=None, directory=None)` | Reads multiple FASTA files from a list or directory. |
| `ImportTSV(filepath, header_idx=0, seq_idx=1, annotation_idx=None, header=True)` | Reads sequences from a TSV file with configurable column indices. |

### Annotators

Transform sequence annotations or headers.

| Class | Description |
|---|---|
| `DropAnnotations(source)` | Removes all annotations from every sequence. |
| `DropAnnotationKeys(source, keys_to_remove)` | Removes specific annotation keys by name. |
| `AddTaxonomyFromFilename(source, key, header_formatter=None)` | Extracts a taxon from the source filename and adds it to the header. |
| `AddTaxidFromName(source, taxonomy_db, organism_field="organism")` | Looks up organism names in a SQLite taxonomy DB and adds the corresponding `taxid`. |
| `AddNameFromTaxid(source, taxonomy_db, taxid_field="taxid", name_field="organism")` | Converts taxid values to scientific names using a taxonomy DB. |
| `AddTaxonomicRankFromTaxid(source, taxonomy_db, taxid_field="taxid", rank="species")` | Traverses NCBI taxonomy tree to find a given rank (e.g., `"order"`) for each taxid. |
| `AddAnnotationToHeader(source, annotation_key, separator="_", position="suffix")` | Adds an annotation value as prefix or suffix to the sequence header. |

### Mutators

Filter, sample, or rename sequences in the stream.

| Class | Description |
|---|---|
| `Head(source, n)` | Yields the first `n` sequences. |
| `Tail(source, n)` | Yields the last `n` sequences. |
| `Sample(source, k, seed=None)` | Randomly samples `k` sequences using reservoir sampling. |
| `DeduplicateHeaders(source, separator="_", position="suffix", start=1)` | Renames duplicate headers by appending a counter (e.g., `seq01`, `seq01_1`, `seq01_2`). |

### Filters

Boolean conditions testable on a single `Sequence`. Used standalone or combined with `Group`.

| Class | Description |
|---|---|
| `ContainsMotif(motif)` | Sequence contains the given substring. |
| `HasAnnotation(key, value=None)` | Annotation `key` exists; optionally match its `value`. |
| `HeaderMatches(pattern)` | Header matches a regex pattern. |
| `SequenceLength(is_, length)` | Sequence length comparison. `is_`: `"greater"`, `"greater_equal"`, `"less"`, `"less_equal"`, `"equal"`. |
| `Not(filter_)` | Negates another filter. |
| `And(*filters)` | All filters must pass. |
| `Or(*filters)` | At least one filter must pass. |

#### Filter examples

```python
# Sequences containing a motif
fastasma.ContainsMotif("ATTG")

# Sequences with organism annotation set to "Homo sapiens"
fastasma.HasAnnotation("organism", "Homo sapiens")

# Sequences whose header starts with "seq"
fastasma.HeaderMatches(r"^seq")

# Sequences longer than 200 bp
fastasma.SequenceLength(is_="greater", length=200)

# Short sequences (less than 100 bp) containing a motif
fastasma.And(fastasma.ContainsMotif("ATTG"), fastasma.SequenceLength(is_="less", length=100))

# Sequences that do NOT contain a stop codon
fastasma.Not(fastasma.ContainsMotif("TAG"))
```

### Groups

`Group` splits a `SequenceSource` into matched and unmatched subsets based on a `Filter`, then lets you apply operations only to the matched subset before reuniting them.

| Class | Description |
|---|---|
| `Group(source, filter_)` | Evaluates filter on each sequence. Stores matched/unmatched status. |
| `.then(op_class, *args, **kwargs)` | Queues an operation to apply to matched sequences. Returns `self` for chaining. |
| `.matched` | Returns a `SequenceSource` of only the matched sequences (no transforms applied). |
| `.ungroup()` | Returns a `SequenceSource` with all sequences in original order; matched items are processed through the queued transforms. |

Any class that accepts a `SequenceSource` as first argument (Annotators, Mutators, Writers, even another `Group`) can be used with `.then()`.

#### Group examples

```python
# Find sequences containing "ATTG" and add a suffix to their header
result = (fastasma.Group(fastasma.ImportFasta("input.fasta"),
                         fastasma.ContainsMotif("ATTG"))
          .then(fastasma.AddAnnotationToHeader, annotation_key="organism",
                separator="_", position="suffix")
          .ungroup())
fastasma.WriteFasta(result, output_path="output.fasta")

# Chain multiple operations on the matched group
result = (fastasma.Group(source, fastasma.SequenceLength(is_="greater", length=200))
          .then(fastasma.DeduplicateHeaders, separator="_")
          .then(fastasma.DropAnnotationKeys, keys_to_remove=["length"])
          .ungroup())

# Use Group as a simple filter (no transforms)
source = fastasma.Group(
    fastasma.ImportFasta("input.fasta"),
    fastasma.Or(fastasma.ContainsMotif("ATTG"), fastasma.ContainsMotif("CGGT"))
).matched
fastasma.WriteFasta(source, output_path="filtered.fasta")
```

### Writers

Write sequences to files or databases.

| Class | Description |
|---|---|
| `WriteFasta(source, output_path, wrap=80)` | Writes sequences to a FASTA file with configurable line wrapping. |
| `WriteTSV(source, output_path, sep="\t")` | Writes sequences to a TSV file with annotations as columns. |
| `WriteDB(source, db_path)` | Writes sequences to a SQLite database with normalized annotation tables. |
