Skip to main content

fastasma

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

Installation

pip install fastasma

Core concepts

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

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

CLI

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.

# 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

# 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

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

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

Python API

Quick start

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

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

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

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastasma-0.1.8.tar.gz (15.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastasma-0.1.8-py3-none-any.whl (16.0 kB view details)

Uploaded Python 3

File details

Details for the file fastasma-0.1.8.tar.gz.

File metadata

  • Download URL: fastasma-0.1.8.tar.gz
  • Upload date:
  • Size: 15.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for fastasma-0.1.8.tar.gz
Algorithm Hash digest
SHA256 77d96869575f4f18876c9f8da4a8bd81b5591dccbc7dcf63ad261caf1338226a
MD5 518bc51b9a46dbe2cc81268a62f0694e
BLAKE2b-256 21e0257fa3987e7fad77638090deaf330b4a1d604a623846b3c54bb088539f99

See more details on using hashes here.

File details

Details for the file fastasma-0.1.8-py3-none-any.whl.

File metadata

  • Download URL: fastasma-0.1.8-py3-none-any.whl
  • Upload date:
  • Size: 16.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for fastasma-0.1.8-py3-none-any.whl
Algorithm Hash digest
SHA256 f454b20252aa388ca1a409ff92ca83a787133cb5bb87dfbd36fc0e74b6382adf
MD5 c75382f70910a7841b23013967f8d2b0
BLAKE2b-256 7d8ca0b87ab3d1ccdd0980676a44b5b472f1ae5faee6e7e04cc59fef1847bf5e

See more details on using hashes here.

Release history Release notifications | RSS feed

0.1.10

2 files

0.1.9

2 files

This release

0.1.8 This release

2 files

0.1.7

2 files

0.1.6

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page