Skip to main content

Fastasma

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: {}

Joining files and setting output width

Join appends additional FASTA files after the incoming source (the -i file from the CLI). Wrap sets the FASTA line width and takes precedence over the CLI --wrap flag; place it last.

steps:
  - Join:
      filepaths: [extra1.fasta, extra2.fasta]

  - Wrap: {width: 60}

Join also accepts a directory:

steps:
  - Join:
      directory: additional_fastas/

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.
Join(source, filepaths=None, directory=None) Appends one or more FASTA files (list or directory) after the incoming source.

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
Wrap(source, width=80) Marks the output line width for WriteFasta. Does not alter sequences. Use as the final pipeline step.
WriteFasta(source, output_path, wrap=80) Writes to FASTA file. A preceding Wrap step overrides wrap.
WriteTSV(source, output_path, sep="\t") Writes to TSV file.
WriteDB(source, db_path) Writes to SQLite database.

Metadata

Release files for fastasma 0.1.11

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastasma 0.1.11
File Size Uploaded Provenance Actions
fastasma-0.1.11.tar.gz 16.3 kB Without provenance Details for fastasma-0.1.11.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastasma 0.1.11
File Interpreter ABI Platform Actions
fastasma-0.1.11-py3-none-any.whl Python 3 none any Details for fastasma-0.1.11-py3-none-any.whl

Total release size: 33.2 kB

Release files / fastasma-0.1.11.tar.gz

Download URL fastasma-0.1.11.tar.gz
Size 16.3 kB
Tags Source
SHA-256 checksum
How to use checksums
df3d90906048d617528c44399f3f5ceb3fd0cc7f882a28a2b480c137bb78c06e
BLAKE2b-256 checksum
How to use checksums
c7907c7944638e0fee5e20d4187efd39259cd8000c847655dcbdb870b2d7d0aa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.11

Release files / fastasma-0.1.11-py3-none-any.whl

Download URL fastasma-0.1.11-py3-none-any.whl
Size 16.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d380a28bcb0099e761bb70c58a8a46cdfa2ad0f7f1da950e83506c9ae65923bf
BLAKE2b-256 checksum
How to use checksums
97c462d2e902fe75a0eb44464a89058077e38631e3c77c918b15bec6ab13fe8b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.11

Security for fastasma 0.1.11

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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