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

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.10.tar.gz (15.4 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.10-py3-none-any.whl (16.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastasma-0.1.10.tar.gz
  • Upload date:
  • Size: 15.4 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.10.tar.gz
Algorithm Hash digest
SHA256 7f75380930d067d66972fd942818d95547b042bc856cb078782eda33b9dff1d4
MD5 23a4e78952dc560e9d2ce0596700c4b6
BLAKE2b-256 009c02cf0e98780fbd359ee6b4fc6cf455616924441f18bb70bcbb01e87e3751

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fastasma-0.1.10-py3-none-any.whl
  • Upload date:
  • Size: 16.2 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.10-py3-none-any.whl
Algorithm Hash digest
SHA256 f9212390ef4d942ef42a0900451d5a69fa9b800dfaf98ba66a41f04a608bc0bd
MD5 f24f3249ecd1937e2cec8e099a154ee1
BLAKE2b-256 cb112fba6827b40f9460752bc090a327687867b9e103e4cbc6c9b2fbf6ac32a4

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.10 This release

2 files

0.1.9

2 files

0.1.8

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