├── .gitignore ├── Cargo.toml ├── examples ├── seqalign.rs └── seqalign_plain.rs ├── LICENSE ├── Readme.md └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | test_data 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "seqalign_pathing" 3 | version = "0.1.0" 4 | authors = ["Tristan Hume "] 5 | 6 | [dependencies] 7 | 8 | [dev-dependencies] 9 | bio = "*" 10 | 11 | # [profile.release] 12 | # debug = true 13 | -------------------------------------------------------------------------------- /examples/seqalign.rs: -------------------------------------------------------------------------------- 1 | extern crate seqalign_pathing; 2 | extern crate bio; 3 | 4 | use bio::io::fasta::Reader; 5 | use seqalign_pathing::alignment_score; 6 | use std::cmp::min; 7 | 8 | fn main() { 9 | let args: Vec = std::env::args().collect(); 10 | assert_eq!(args.len(), 4); 11 | let af = Reader::from_file(&args[1]).unwrap().records().next().unwrap().unwrap(); 12 | let bf = Reader::from_file(&args[2]).unwrap().records().next().unwrap().unwrap(); 13 | let ab = af.seq(); 14 | let bb = bf.seq(); 15 | let prefix: usize = args[3].parse().unwrap(); 16 | let score = alignment_score(&ab[0..min(prefix,ab.len())], &bb[0..min(prefix,bb.len())]); 17 | println!("{:?}", score); 18 | } 19 | -------------------------------------------------------------------------------- /examples/seqalign_plain.rs: -------------------------------------------------------------------------------- 1 | extern crate seqalign_pathing; 2 | 3 | use std::io; 4 | use std::io::prelude::*; 5 | use std::fs::File; 6 | use seqalign_pathing::alignment_score; 7 | use std::cmp::min; 8 | 9 | fn file_bytes(path: &str) -> io::Result> { 10 | let mut f = File::open(path)?; 11 | let mut buffer = Vec::new(); 12 | // read the whole file 13 | f.read_to_end(&mut buffer)?; 14 | Ok(buffer) 15 | } 16 | 17 | fn main() { 18 | let args: Vec = std::env::args().collect(); 19 | assert_eq!(args.len(), 4); 20 | let af = file_bytes(&args[1]).unwrap(); 21 | let bf = file_bytes(&args[2]).unwrap(); 22 | let prefix: usize = args[3].parse().unwrap(); 23 | let score = alignment_score(&af[0..min(prefix,af.len())], &bf[0..min(prefix,bf.len())]); 24 | println!("{:?}", score); 25 | } 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Tristan Hume 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Sequence Alignment With A* Example 2 | 3 | This is an example of using A* path finding to accelerate a dynamic programming algorithm, in this case the [sequence alignment problem](https://en.wikipedia.org/wiki/Sequence_alignment), which [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) is a specific instance of. 4 | 5 | Unlike the standard Levenshtein distance algorithm, this runs in something like `O(n * e^2)` time where `n` is the input length and `e` is the edit distance. It does this by using a heuristic like A* to explore only promising states along the diagonal of the grid and not the whole `O(n^2)` grid. 6 | 7 | It is substantially faster for large files with few edits than the naive `O(n^2)` dynamic programming algorithm it is based on, but is still much slower than specialized and highly optimized global sequence alignment programs like [Edlib](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5408825/). The difference is I wrote this in two hours and it's 150 lines of code including tests, debugging routines and examples. 8 | 9 | It is written in Rust and contains two example programs: 10 | 11 | - `seqalign`: Reads to FASTA format genetic sequence files and prints the alignment distance. 12 | - `seqalign_plain`: Reads two plain text files and prints the alignment distance. 13 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::collections::hash_map::{HashMap, Entry}; 2 | use std::collections::binary_heap::BinaryHeap; 3 | use std::cmp::max; 4 | 5 | type Pos = (usize,usize); 6 | pub type Score = i32; 7 | 8 | /// The score for inserting or deleting a character, higher is better 9 | pub const INDEL: Score = -1; 10 | /// The score for two characters not changing 11 | pub const MATCH: Score = 0; 12 | /// The score for one character changing into another 13 | pub const MISMATCH: Score = -1; 14 | 15 | fn diag(pos: &Pos) -> i32 { 16 | (pos.1 as i32) - (pos.0 as i32) 17 | } 18 | 19 | /// find the distance from the diagonal of `goal` times INDEL 20 | fn heuristic(pos: &Pos, goal: &Pos) -> Score { 21 | let goal_diag = diag(goal); 22 | let our_diag = diag(pos); 23 | let indel_dist = (our_diag - goal_diag).abs(); 24 | // support non-zero MATCH cost 25 | let total_dist = max(goal.0 - pos.0, goal.1 - pos.1) as i32; 26 | let match_dist = total_dist - indel_dist; 27 | return (indel_dist * INDEL) + (match_dist * MATCH); 28 | } 29 | 30 | /// Explore a successor state if we aren't already set to explore it 31 | fn add_state(scores: &mut HashMap, q: &mut BinaryHeap<(Score,Pos)>, goal: &Pos, new_score: Score, pos: Pos) { 32 | match scores.entry(pos) { 33 | Entry::Vacant(e) => { e.insert(new_score); }, 34 | Entry::Occupied(ref mut e) => { 35 | if *(e.get()) >= new_score { return; } // obsolete 36 | e.insert(new_score); 37 | } 38 | } 39 | 40 | let priority = new_score + heuristic(&pos, goal); 41 | q.push((priority, pos)); 42 | } 43 | 44 | /// Helper function to print an ASCII representation of which grid cells were explored 45 | #[allow(dead_code)] 46 | fn debug_print_table(scores: &HashMap, size: Pos) { 47 | let (am, bm) = size; 48 | for ai in 0..am { 49 | for bi in 0..bm { 50 | let inside = scores.contains_key(&(ai,bi)); 51 | let chr = if inside { 'X' } else { ' ' }; 52 | print!("{}", chr); 53 | } 54 | println!(""); 55 | } 56 | } 57 | 58 | /// Find the score for aligning `a` and `b` based on the costs given by INDEL, 59 | /// MATCH and MISMATCH. If INDEL and MISMATCH are -1 and MATCH is 0 then the 60 | /// result is the negative of the Levenshtein distance of the two inputs. 61 | pub fn alignment_score(a: &[u8], b: &[u8]) -> Score { 62 | let start = (0,0); 63 | let goal = (a.len(),b.len()); 64 | let mut q = BinaryHeap::with_capacity(a.len()+b.len()); 65 | q.push((heuristic(&start, &goal), start)); 66 | 67 | let mut scores: HashMap = HashMap::with_capacity(a.len()+b.len()); 68 | scores.insert(start,0); 69 | 70 | let mut pop_count: usize = 0; 71 | let mut eval_count: usize = 0; 72 | loop { 73 | let (score, pos) = q.pop().expect("should always reach goal"); 74 | let score = score - heuristic(&pos, &goal); 75 | pop_count += 1; 76 | 77 | if pos == goal { 78 | println!("scores: {:?}", scores.len()); 79 | println!("pops: {:?}", pop_count); 80 | println!("evals: {:?}", eval_count); 81 | // debug_print_table(&scores, goal.clone()); 82 | return score; // found it! 83 | } 84 | 85 | // this should be the best score we've found so far for this position 86 | let best_score = scores[&pos]; 87 | if score > best_score { 88 | panic!("loop in DAG scores: {} < {}", score, best_score); 89 | } else if score < best_score { 90 | continue; // we've been here before, but better 91 | } 92 | 93 | eval_count += 1; 94 | 95 | // explore successor states 96 | let (ai,bi) = pos; 97 | 98 | // indel 99 | if ai < a.len() { 100 | add_state(&mut scores, &mut q, &goal, score + INDEL, (ai+1, bi)); 101 | } 102 | if bi < b.len() { 103 | add_state(&mut scores, &mut q, &goal, score + INDEL, (ai, bi+1)); 104 | } 105 | if ai < a.len() && bi < b.len() { 106 | let diag_score = if a[ai] == b[bi] { 107 | MATCH 108 | } else { 109 | MISMATCH 110 | }; 111 | add_state(&mut scores, &mut q, &goal, score + diag_score, (ai+1, bi+1)); 112 | } 113 | } 114 | } 115 | 116 | 117 | #[cfg(test)] 118 | mod tests { 119 | use super::*; 120 | #[test] 121 | fn it_works() { 122 | let a = "GCATGCU"; 123 | let b = "GATTACA"; 124 | let score = alignment_score(a.as_bytes(), b.as_bytes()); 125 | assert_eq!(2*MISMATCH+4*MATCH+2*INDEL, score); 126 | } 127 | 128 | #[test] 129 | fn heuristic_1() { 130 | let tests = vec![ 131 | ((0,0), (4,4), 0*INDEL+4*MATCH), 132 | ((4,3), (4,7), 4*INDEL), 133 | ((1,0), (4,4), 1*INDEL+3*MATCH), 134 | ((1,2), (4,4), 1*INDEL+2*MATCH), 135 | ]; 136 | for (pos, goal, correct) in tests.into_iter() { 137 | assert_eq!(correct, heuristic(&pos, &goal), "{:?} to {:?}", pos, goal); 138 | } 139 | } 140 | } 141 | --------------------------------------------------------------------------------