Skip to main content

Crate mafft

Crate mafft 

Source
Expand description

MAFFT multiple sequence alignment — high-level Rust API.

This is the ergonomic entry point. Add it to your project with:

cargo add mafft

and write:

use mafft::{MafftEngine, AlignmentMode, SequenceSet, read_fasta};

let input: SequenceSet = read_fasta("input.fasta").unwrap();
let engine = MafftEngine::new(AlignmentMode::FftNs2);
let msa = engine.align(&input);
for (name, seq) in msa.names.iter().zip(msa.sequences.iter()) {
    println!(">{name}");
    println!("{}", std::str::from_utf8(seq).unwrap());
}

§What this crate re-exports

  • mafft_core — alignment engine, modes, MSA result types
  • mafft_typesSequence, SequenceSet, scoring models, segment types
  • mafft_io — FASTA / hat2 / localhom readers and writers

Items from these crates are flattened into the root namespace below, so most callers never need to write mafft::core:: / mafft::io:: paths — use mafft::* is enough.

§When to depend on the sub-crates directly

Reach for mafft-core / mafft-align / mafft-tree / mafft-scoring / mafft-fft directly only if you need to:

  • cut compile time by avoiding the I/O layer,
  • pin a sub-crate to a specific version independently of the rest, or
  • extend internals (e.g. custom guide trees, custom scoring matrices).

For everything else, depend on mafft.

§The command line’s flag layer, in-process (cli feature)

MafftEngine takes an AlignmentMode; the command line chooses one (--auto from sequence count and length) and does more before the engine runs (--adjustdirection strand detection, --nuc / --amino type forcing, the residue case fold). Re-deriving any of that in a caller is how it silently diverges from C MAFFT. With features = ["cli"] the [cli] module re-exports the mafft-rs crate, whose entry points take the same argv the shell would and go through the same code as the binary:

use mafft::cli::{run_from_seqs, SilentProgress};
use mafft::{Sequence, SequenceSet, SeqType};

let input = SequenceSet {
    sequences: vec![
        Sequence { name: "a".into(), data: b"atggctagcttggacc".to_vec() },
        Sequence { name: "b".into(), data: b"atggctagcttgcacc".to_vec() },
    ],
    seq_type: SeqType::Dna,
};
// Same flags as `mafft --auto --adjustdirection --thread 1 --nuc FILE`,
// but the sequences stay in memory and the rows come back as a value.
let msa = run_from_seqs(
    ["mafft", "--auto", "--adjustdirection", "--thread", "1", "--nuc"],
    &input,
    &SilentProgress,
)?;
assert_eq!(msa.names.len(), 2);

run_from(argv, &mut out) is the same thing with a FASTA file in and formatted text out; Mafft::new().auto().nuc().run_seqs(&input) is the typed builder over either.

  • mafft-rs — standalone CLI: cargo install mafft-rs; also the crate behind the cli feature
  • pymafft — Python bindings (pip install pymafft)

Modules§

adjust_direction
Port of C MAFFT’s --adjustdirection strand-detection preprocessing.
core
Sub-crate re-exports under explicit names, for callers who prefer disambiguation over the flattened root namespace.
external
fp
Floating-point contraction policy: mirror the reference C build of the target you run on.
io
FASTA / hat2 / localhom I/O.
progressive
types
Sequence / scoring / segment types.

Structs§

AlignmentSegment
An aligned segment region.
GapPenalties
Gap penalty parameters.
Hat2Matrix
MAFFT’s hat2 distance matrix format.
HomologyRegion
A single local homology region between two sequences.
IllegalResidue
The first residue seqcheck would reject, in reading order.
LocalHomologyTable
Table of pairwise local homology information.
MafftEngine
The main MAFFT alignment engine.
MultipleAlignment
RefinementParams
Parameters controlling iterative refinement.
RnaBasePair
An RNA base pair probability.
ScoringContext
The complete scoring context needed by alignment algorithms.
SegmentPair
A pair of segments from two groups being aligned.
Sequence
A named biological sequence.
SequenceSet
A collection of sequences to be aligned.
StepTrace

Enums§

AlignmentMode
Alignment mode (strategy).
IoError
ScoringModel
Which substitution matrix model to use.
SeqType
The type of biological sequences being aligned.

Constants§

CONTRACTS_FMA
true when this build fuses a * b + c into a single-rounding FMA at every fmadd site, false when it rounds twice.

Functions§

add_sequences
Add new sequences to an existing alignment.
add_sequences_keeplength
Add sequences while preserving the existing alignment’s column structure (--add --keeplength). After running the standard add_sequences, deletes any columns that exist only because of new-sequence insertions, restoring the existing alignment to its original width. Columns where ANY new sequence had a residue but ALL existing sequences had gaps get the new-sequence residue dropped (truncated at that position).
add_sequences_keeplength_with_map
Like add_sequences_keeplength but also returns the per-added- sequence list of dropped insertion runs ((start_in_addbk_0based, run_length) pairs). Used by --mapout / --compactmapout.
apply_case_convention
Apply C MAFFT’s residue-case convention to an already-parsed set: lowercase for DNA/RNA, uppercase for everything else.
compute_clustal_marks
Compute CLUSTAL-format conservation marks per column.
detect_seq_type
Detect whether sequences are DNA/RNA or protein by ATGC frequency.
detect_seq_type_with_limit
dndpre_offset_shift
Matrix shift applied when rebuilding the refinement-tree distances the way C’s dndpre does, for the modes that have no pairlocalalign step (FFT-NS-i and friends).
find_illegal_residue
Scan set the way C seqcheck does and return the first residue that is not in the alphabet for set.seq_type, or None when every residue is legal. Gap characters (-) are part of both alphabets, so a gapped input passes.
fmadd
Policy-dependent multiply-add: a * b + c.
iterative_refine
Iteratively refine a multiple alignment.
normalize_residues
Apply the FASTA reader’s residue filter to residues that are already in memory, so an in-memory caller ends up with exactly the bytes a FASTA round trip would have produced — and fails exactly where the reader would.
pair_penalty_scales
Scale factors turning the pair-phase ppenalty-style integers (lgop * 1000, …) into DP units: (gap_scale, offset_scale).
progressive_align
progressive_align_partial
Run progressive alignment merges 0..n_steps and return the intermediate aligned[] state at that point.
progressive_align_unweighted
Run progressive alignment with all per-sequence weights set to 1.0. When normalized within each cluster, this yields uniform weights 1/clus_size — mirroring C splittbfast.c::fastconjuction_noweight’s behavior (used by --parttree because splittbfast.c:6 defines WEIGHT 0).
progressive_align_with_weights_override
Like progressive_align_with_constraints but allows overriding the per-sequence weights. When weights_override is Some(w), each w[i] is used directly (still normalized within each cluster at merge time). When None, the weights come from sequence_weights(topology) (the tree-derived weightFromABranch-based defaults).
read_fasta
Read a FASTA file from a path into a SequenceSet.
read_fasta_casepreserve
Read a FASTA file preserving case and non-standard residues — used by --anysymbol/--preservecase. Strips only newline, space and carriage return (matching C MAFFT’s readData_pointer_casepreservecharfilter, io.c:1329-1352); any other character — digits, tabs, punctuation, lowercase — is kept verbatim so the post-alignment restore pass can put the originals back.
read_fasta_from_reader
Read FASTA from any buffered reader.
read_fasta_from_reader_casepreserve
Like read_fasta_from_reader but preserves case and non-standard residues (see read_fasta_casepreserve).
read_hat2
Read a hat2 distance matrix.
read_localhom_table
Read a local homology table (hat3 format).
residues_are_normalized
true when normalize_residues would return raw unchanged, i.e. the residues already look like they came out of the FASTA reader. Lets a caller holding borrowed data skip the copy when nothing needs to change. Residues the reader would reject are not “unchanged”.
residues_follow_case_convention
true when apply_case_convention would leave data unchanged for a set of type seq_type: no uppercase letters for nucleotides, no lowercase letters otherwise.
seqcheck_alphabet
The alphabet seqcheck tests set against — mafft_scoring’s DNA alphabet for nucleotide sets, its protein alphabet otherwise.
write_clustal
Write an alignment in Clustal format.
write_clustal_full
Write an alignment in Clustal format with an optional header comment (e.g. the alignment-mode label FFT-NS-2).
write_fasta
Write a SequenceSet as FASTA to a file path.
write_fasta_to_writer
Write a SequenceSet as FASTA to any writer.
write_fasta_to_writer_with_width
Write FASTA with a custom line width. Pass 0 for unlimited (single line).
write_hat2
Write a hat2 distance matrix.
write_localhom_table
Write a local homology table (hat3 format).
write_phylip
Write an alignment in interleaved PHYLIP format.

Type Aliases§

Complex64
Alias for a Complex<f64>