Expand description
MAFFT multiple sequence alignment — high-level Rust API.
This is the ergonomic entry point. Add it to your project with:
cargo add mafftand 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 typesmafft_types—Sequence,SequenceSet, scoring models, segment typesmafft_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.
§Related crates
Modules§
- adjust_
direction - Port of C MAFFT’s
--adjustdirectionstrand-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§
- Alignment
Segment - An aligned segment region.
- GapPenalties
- Gap penalty parameters.
- Hat2
Matrix - MAFFT’s hat2 distance matrix format.
- Homology
Region - A single local homology region between two sequences.
- Illegal
Residue - The first residue
seqcheckwould reject, in reading order. - Local
Homology Table - Table of pairwise local homology information.
- Mafft
Engine - The main MAFFT alignment engine.
- Multiple
Alignment - Refinement
Params - Parameters controlling iterative refinement.
- RnaBase
Pair - An RNA base pair probability.
- Scoring
Context - The complete scoring context needed by alignment algorithms.
- Segment
Pair - A pair of segments from two groups being aligned.
- Sequence
- A named biological sequence.
- Sequence
Set - A collection of sequences to be aligned.
- Step
Trace
Enums§
- Alignment
Mode - Alignment mode (strategy).
- IoError
- Scoring
Model - Which substitution matrix model to use.
- SeqType
- The type of biological sequences being aligned.
Constants§
- CONTRACTS_
FMA truewhen this build fusesa * b + cinto a single-rounding FMA at everyfmaddsite,falsewhen 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 standardadd_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_keeplengthbut 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
dndpredoes, for the modes that have nopairlocalalignstep (FFT-NS-i and friends). - find_
illegal_ residue - Scan
setthe way Cseqcheckdoes and return the first residue that is not in the alphabet forset.seq_type, orNonewhen 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 Csplittbfast.c::fastconjuction_noweight’s behavior (used by--parttreebecausesplittbfast.c:6definesWEIGHT 0). - progressive_
align_ with_ weights_ override - Like
progressive_align_with_constraintsbut allows overriding the per-sequence weights. Whenweights_overrideisSome(w), eachw[i]is used directly (still normalized within each cluster at merge time). WhenNone, the weights come fromsequence_weights(topology)(the tree-derivedweightFromABranch-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’sreadData_pointer_casepreserve→charfilter,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_readerbut preserves case and non-standard residues (seeread_fasta_casepreserve). - read_
hat2 - Read a hat2 distance matrix.
- read_
localhom_ table - Read a local homology table (hat3 format).
- residues_
are_ normalized truewhennormalize_residueswould returnrawunchanged, 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 truewhenapply_case_conventionwould leavedataunchanged for a set of typeseq_type: no uppercase letters for nucleotides, no lowercase letters otherwise.- seqcheck_
alphabet - The alphabet
seqchecktestssetagainst —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
SequenceSetas FASTA to a file path. - write_
fasta_ to_ writer - Write a
SequenceSetas FASTA to any writer. - write_
fasta_ to_ writer_ with_ width - Write FASTA with a custom line width. Pass
0for 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>