Metadata-Version: 2.4
Name: fastasma
Version: 0.1.8
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
Requires-Dist: pyyaml
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"))))
```

## CLI

```bash
fastasma -i input.fasta -o output.fasta -p pipeline.yaml

# Multiple pipelines applied in order
fastasma -i input.fasta -o output.tsv -p clean.yaml -p annotate.yaml

# Auto-detects output format by extension (.fasta, .tsv, .db)
fastasma -i input.fasta -o results.tsv -p pipeline.yaml
```

## YAML pipelines

Define reusable, shareable workflows in YAML. Each step is a registered class name with its keyword arguments.

```yaml
# pipeline.yaml
steps:
  - DropAnnotationKeys:
      keys_to_remove: [length, annotated]

  - Group:
      filter:
        And:
          filters:
            - SequenceLength: {is_: greater, length: 200}
            - ContainsMotif: {motif: ATTG}
      do:
        - DeduplicateHeaders: {separator: _}
        - AddAnnotationToHeader: {annotation_key: organism, separator: _, position: suffix}

  - Sample: {k: 50, seed: 42}
```

### Compound filters in YAML

```yaml
# Negation
Not:
  filter_:
    ContainsMotif: {motif: TAG}

# Logical AND (all must match)
And:
  filters:
    - ContainsMotif: {motif: ATTG}
    - SequenceLength: {is_: less, length: 300}

# Logical OR (any must match)
Or:
  filters:
    - HasAnnotation: {key: organism, value: Homo sapiens}
    - HeaderMatches: {pattern: "^seq\d+"}
```

### Group without transforms

```yaml
steps:
  - Group:
      filter:
        Or:
          filters:
            - ContainsMotif: {motif: ATTG}
            - ContainsMotif: {motif: CGGT}
```

When no `do` block is given, Group returns only matched sequences (equivalent to `.matched`).

### Nested groups

```yaml
steps:
  - Group:
      filter:
        SequenceLength: {is_: greater, length: 100}
      do:
        - Group:
            filter:
              ContainsMotif: {motif: ATTG}
            do:
              - DeduplicateHeaders: {}
```

## Python API

### 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. |

### Filters

Boolean conditions testable on a single `Sequence`.

| 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
fastasma.ContainsMotif("ATTG")
fastasma.HasAnnotation("organism", "Homo sapiens")
fastasma.HeaderMatches(r"^seq")
fastasma.SequenceLength(is_="greater", length=200)
fastasma.And(fastasma.ContainsMotif("ATTG"), fastasma.SequenceLength(is_="less", length=100))
fastasma.Not(fastasma.ContainsMotif("TAG"))
```

### Groups

Apply operations selectively to matched sequences, preserving original order.

| Class | Description |
|---|---|
| `Group(source, filter_)` | Splits source by filter. |
| `.then(op_class, *args, **kwargs)` | Queues an operation on matched sequences. Returns `self`. |
| `.matched` | SequenceSource of matched sequences only (no transforms). |
| `.ungroup()` | Full SequenceSource with transforms applied to matched items. |

```python
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")
```

### Registry

Use `@register("Name")` to make custom classes available in YAML pipelines.

```python
from fastasma.Registry import register
from fastasma.Types import Sequence, SequenceSource

@register("ReverseSequence")
class ReverseSequence:
    def __init__(self, source):
        self._source = source
    def __iter__(self):
        return self.yield_sequence()
    def yield_sequence(self):
        for seq in self._source:
            yield Sequence(seq.header, seq.sequence[::-1], seq.annotation)
```

```yaml
steps:
  - ReverseSequence: {}
```

### Writers

| Class | Description |
|---|---|
| `WriteFasta(source, output_path, wrap=80)` | Writes to FASTA file. |
| `WriteTSV(source, output_path, sep="\t")` | Writes to TSV file. |
| `WriteDB(source, db_path)` | Writes to SQLite database. |
