Minimap2
Pure-Crystal port of minimap2, a versatile pairwise sequence aligner for nucleotide sequences.
All algorithms are implemented directly in Crystal — no C bindings.
Quick start:
aligner = Minimap2::Aligner.from_strings(["ACGT" * 100], ["ref"], "map-ont")
aligner.map("ACGTACGT...") do |hit|
puts "#{hit.rid}\t#{hit.rs}-#{hit.re}\t#{hit.rev ? '-' : '+'}"
end
Constants
CIGAR operation codes
Debug flags
Mapping / output flags (MM_F_*)
Index flags (MM_I_*)
Index magic
Junction flags
Library version
Internal parent sentinels
Internal seed flags
Complement table for seq_comp_table (used when reversing sequences)
Nucleotide encoding table: A=0, C=1, G=2, T=3, other=4
Class methods
Alignment skeleton: align all regions with CIGAR output. Mirrors mm_align_skeleton().
Multi-file fragment reader (mirrors mm_bseq_read_frag2)
mg_chain_backtrack: extract chains from the DP arrays. Returns (u, v) or (nil, nil) if no chains found. u[i] = score<<32 | count; v[] = anchor indices (reversed)
Validate option combination; returns 0 on success (mirrors mm_check_opt).
Full seed collection pipeline (mirrors mm_collect_matches). Returns: seeds — filtered MmSeed array n_a — total reference anchor count rep_len — repetitive region length in query mini_pos — (q_span<<32 | q_pos) for each non-filtered seed
Encode a query string (ASCII) into 4-bit bases using SEQ_NT4_TABLE.
estimate divergence from chaining
Filter out low-quality hits.
Filter hits where strand_retained quality is poor.
Convert chains (u[], a[]) to an Array(MmReg1), sorted by descending score. Mirrors mm_gen_regs().
Sort hits by score (descending), removing cnt==0 entries. Mirrors mm_hit_sort().
Initialise MmIdxOpt with default values (mirrors mm_idxopt_init).
Utility: round x up to the next power of two (32-bit version of kroundup32 from ksort.h / mmpriv.h)
k-th smallest element (in-place sort, no .dup needed for callers)
ksw_extd2: scalar dual-gap-penalty banded extension alignment. Mirrors ksw_extd2_sse().
query, target: UInt8 arrays with encoded bases (0..m-1; m-1 = wildcard) mat: m×m scoring matrix (linearised row-major) q, e, q2, e2: primary and secondary gap open/extend penalties (positive) w: band width (<0 = no band) zdrop: Z-drop threshold (<0 = no zdrop) end_bonus: bonus when alignment reaches end of query/target flag: KSW_EZ_* flags
ksw_exts2: splice-aware extension — simplified scalar implementation. Mirrors ksw_exts2_sse().
ksw_extz2: single-gap extension — wraps ksw_extd2 with large secondary gap. Mirrors ksw_extz2_sse().
ksw_gen_simple_mat: build m×m substitution matrix
Variant with transition penalty (A<->G and C<->T transitions penalized differently)
ksw_gg2: global alignment returning CIGAR. Simplified scalar implementation.
mg_lchain_dp: DP-based linear chaining (mirrors mg_lchain_dp in lchain.c).
Input: a[].x = rev<<63 | tid<<32 | tpos a[].y = flags<<40 | q_span<<32 | q_pos Output: n_u (via return value): number of chains u[i] = score<<32 | #anchors returns rearranged a[] (may be empty if no chains)
Map a single query string against the index. Mirrors mm_map().
Map multiple query sequences (e.g. for fragment mode).
Map a single query fragment (internal core).
Initialise MmMapOpt with default values (mirrors mm_mapopt_init).
Set bw/bw_long/max_gap_ref based on intron length (mirrors mm_mapopt_max_intron_len).
Update mid_occ in opt based on the index mi (mirrors mm_mapopt_update).
Set SAM primary flag; returns number of primary hits.
Maximum supplementary-chain bonus (mirrors mm_max_spsc_bonus).
Fast log₂ approximation (mg_log2 from mmpriv.h) Only works for x >= 2.
Compute (w,k)-minimizers on a DNA sequence, appending to p.
Encoding: p[i].x = hash<<8 | kmer_span p[i].y = rid<<32 | last_pos<<1 | strand
Equivalent to mm_sketch() in sketch.c.
Overload accepting Slice(UInt8) directly (internal use)
push_cigar helper: append an operation, merging with previous if same op.
Seconds elapsed since program start on the monotonic clock (equivalent to realtime() in C — used only for logging, not wall time).
Build reverse complement of a 4-bit encoded sequence. Delegates to ksw2.seq_rev_comp (shared implementation).
Command-line interface — mirrors the minimap2 main() options
sdust: allocate a buffer, run sdust_core, return results. Equivalent to sdust() in sdust.c.
sdust_core: run DUST on one sequence, using a reusable buffer. Returns a Slice view into buf.res.
Collect all seed matches between query minimizers and the index. Mirrors mm_seed_collect_all(). Returns an Array(MmSeed) with all matches (including high-freq ones).
Filter overly-frequent minimizers from a query minimizer set. Mirrors mm_seed_mz_flt().
Select up to max_high_occ high-frequency minimizers per streak. Mirrors mm_seed_select().
Generate per-segment chains from the full (concatenated) chain set. Mirrors mm_seg_gen().
Select secondary hits up to best_n.
Reverse complement a 4-bit encoded sequence.
Set MAPQ scores for hits. Simplified version of mm_set_mapq2 from hit.c.
Apply preset on top of already-initialised io and mo. Mirrors mm_set_opt(). When preset is nil the options are first reset to defaults (equivalent to calling mm_set_opt(NULL,...) in C). Returns 0 on success, -1 if the preset is unknown.
Set parent/secondary relationships. Mirrors mm_set_parent().
Split region r at anchor position n, creating r2 as the second half.
Compact the anchor array to only include anchors referenced by regs.
Truncate UInt64 to lower 32 bits and reinterpret as Int32. Equivalent to the C cast (int32_t)v — truncates without raising.
Write one PAF record. Mirrors mm_write_paf4().