Debian Codegraph @

src/align.rs

raw symbols SCIP
1 use std::cmp::max;
2 use std::collections::VecDeque;
3
4 const DELETION_COST: usize = 2;
5 const INSERTION_COST: usize = 2;
6 // extra cost for starting a new group of changed tokens
7 const INITIAL_MISMATCH_PENALTY: usize = 1;
8
9 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
10 pub enum Operation {
11 NoOp,
12 Deletion,
13 Insertion,
14 }
15
16 use Operation::*;
17
18 /// Needleman-Wunsch / Wagner-Fischer table for computation of edit distance and associated
19 /// alignment.
20 #[derive(Clone, Debug)]
21 struct Cell {
22 parent: usize,
23 operation: Operation,
24 cost: usize,
25 }
26
27 #[derive(Debug)]
28 pub struct Alignment<'a> {
29 pub x: Vec<&'a str>,
30 pub y: Vec<&'a str>,
31 table: Vec<Cell>,
32 dim: [usize; 2],
33 }
34
35 impl<'a> Alignment<'a> {
36 /// Fill table for Levenshtein distance / alignment computation
37 pub fn new(x: Vec<&'a str>, y: Vec<&'a str>) -> Self {
38 // TODO: Something downstream of the alignment algorithm requires that the first token in
39 // both x and y is "", so this is explicitly inserted in `tokenize()`.
40 let dim = [y.len() + 1, x.len() + 1];
41 let table = vec![
42 Cell {
43 parent: 0,
44 operation: NoOp,
45 cost: 0
46 };
47 dim[0] * dim[1]
48 ];
49 let mut alignment = Self { x, y, table, dim };
50 alignment.fill();
51 alignment
52 }
53
54 /// Fill table for Levenshtein distance / alignment computation
55 pub fn fill(&mut self) {
56 // x is written along the top of the table; y is written down the left side of the
57 // table. Also, we insert a 0 in cell (0, 0) of the table, so x and y are shifted by one
58 // position. Therefore, the element corresponding to (x[i], y[j]) is in column (i + 1) and
59 // row (j + 1); the index of this element is given by index(i, j).
60 for i in 1..self.dim[1] {
61 self.table[i] = Cell {
62 parent: 0,
63 operation: Deletion,
64 cost: i * DELETION_COST + INITIAL_MISMATCH_PENALTY,
65 };
66 }
67 for j in 1..self.dim[0] {
68 self.table[j * self.dim[1]] = Cell {
69 parent: 0,
70 operation: Insertion,
71 cost: j * INSERTION_COST + INITIAL_MISMATCH_PENALTY,
72 };
73 }
74
75 for (i, x_i) in self.x.iter().enumerate() {
76 for (j, y_j) in self.y.iter().enumerate() {
77 let (left, diag, up) =
78 (self.index(i, j + 1), self.index(i, j), self.index(i + 1, j));
79 // The order of the candidates matters if two of them have the
80 // same cost as in that case we choose the first one. Consider
81 // insertions and deletions before matches in order to group
82 // changes together. Insertions are preferred to deletions in
83 // order to highlight moved tokens as a deletion followed by an
84 // insertion (as the edit sequence is read backwards we need to
85 // choose the insertion first)
86 let candidates = [
87 Cell {
88 parent: up,
89 operation: Insertion,
90 cost: self.mismatch_cost(up, INSERTION_COST),
91 },
92 Cell {
93 parent: left,
94 operation: Deletion,
95 cost: self.mismatch_cost(left, DELETION_COST),
96 },
97 Cell {
98 parent: diag,
99 operation: NoOp,
100 cost: if x_i == y_j {
101 self.table[diag].cost
102 } else {
103 usize::MAX
104 },
105 },
106 ];
107 let index = self.index(i + 1, j + 1);
108 self.table[index] = candidates
109 .iter()
110 .min_by_key(|cell| cell.cost)
111 .unwrap()
112 .clone();
113 }
114 }
115 }
116
117 fn mismatch_cost(&self, parent: usize, basic_cost: usize) -> usize {
118 self.table[parent].cost
119 + basic_cost
120 + if self.table[parent].operation == NoOp {
121 INITIAL_MISMATCH_PENALTY
122 } else {
123 0
124 }
125 }
126
127 /// Read edit operations from the table.
128 pub fn operations(&self) -> Vec<Operation> {
129 let mut ops = VecDeque::with_capacity(max(self.x.len(), self.y.len()));
130 let mut cell = &self.table[self.index(self.x.len(), self.y.len())];
131 loop {
132 ops.push_front(cell.operation);
133 if cell.parent == 0 {
134 break;
135 }
136 cell = &self.table[cell.parent];
137 }
138 Vec::from(ops)
139 }
140
141 pub fn coalesced_operations(&self) -> Vec<(Operation, usize)> {
142 run_length_encode(self.operations())
143 }
144
145 // Row-major storage of 2D array.
146 fn index(&self, i: usize, j: usize) -> usize {
147 j * self.dim[1] + i
148 }
149 }
150
151 fn run_length_encode<T>(sequence: Vec<T>) -> Vec<(T, usize)>
152 where
153 T: Copy,
154 T: PartialEq,
155 {
156 let mut encoded = Vec::with_capacity(sequence.len());
157
158 if sequence.is_empty() {
159 return encoded;
160 }
161
162 let end = sequence.len();
163 let (mut i, mut j) = (0, 1);
164 let mut curr = &sequence[i];
165 loop {
166 if j == end || sequence[j] != *curr {
167 encoded.push((*curr, j - i));
168 if j == end {
169 return encoded;
170 } else {
171 curr = &sequence[j];
172 i = j;
173 }
174 }
175 j += 1;
176 }
177 }
178
179 #[cfg(test)]
180 mod tests {
181 use super::*;
182
183 use unicode_segmentation::UnicodeSegmentation;
184
185 #[test]
186 fn test_run_length_encode() {
187 assert_eq!(run_length_encode::<usize>(vec![]), vec![]);
188 assert_eq!(run_length_encode(vec![0]), vec![(0, 1)]);
189 assert_eq!(run_length_encode(vec!["0", "0"]), vec![("0", 2)]);
190 assert_eq!(
191 run_length_encode(vec![0, 0, 1, 2, 2, 2, 3, 4, 4, 4]),
192 vec![(0, 2), (1, 1), (2, 3), (3, 1), (4, 3)]
193 );
194 }
195
196 #[test]
197 fn test_0() {
198 TestCase {
199 before: "aaa",
200 after: "aba",
201 distance: 5,
202 parts: (2, 4),
203 operations: vec![NoOp, Deletion, Insertion, NoOp],
204 }
205 .run();
206 }
207
208 #[test]
209 fn test_0_nonascii() {
210 TestCase {
211 before: "ááb",
212 after: "áaa",
213 distance: 9,
214 parts: (4, 5),
215 operations: vec![NoOp, Deletion, Deletion, Insertion, Insertion],
216 }
217 .run();
218 }
219
220 #[test]
221 fn test_1() {
222 TestCase {
223 before: "kitten",
224 after: "sitting",
225 distance: 13,
226 parts: (5, 9),
227 operations: vec![
228 Deletion, // K -
229 Insertion, // - S
230 NoOp, // I I
231 NoOp, // T T
232 NoOp, // T T
233 Deletion, // E -
234 Insertion, // - I
235 NoOp, // N N
236 Insertion, // - G
237 ],
238 }
239 .run();
240 }
241
242 #[test]
243 fn test_2() {
244 TestCase {
245 before: "saturday",
246 after: "sunday",
247 distance: 10,
248 parts: (4, 9),
249 operations: vec![
250 NoOp, // S S
251 Deletion, // A -
252 Deletion, // T -
253 NoOp, // U U
254 Deletion, // R -
255 Insertion, // - N
256 NoOp, // D D
257 NoOp, // A A
258 NoOp, // Y Y
259 ],
260 }
261 .run();
262 }
263
264 #[test]
265 fn test_3() {
266 TestCase {
267 // Prefer [Deletion NoOp Insertion] over [Insertion NoOp Deletion]
268 before: "ab",
269 after: "ba",
270 distance: 6,
271 parts: (2, 3),
272 operations: vec![
273 Deletion, // a -
274 NoOp, // b b
275 Insertion, // - a
276 ],
277 }
278 .run();
279 }
280
281 #[test]
282 fn test_4() {
283 // Deletions are grouped together.
284 TestCase {
285 before: "AABB",
286 after: "AB",
287 distance: 5,
288 parts: (2, 4),
289 operations: vec![
290 NoOp, // A A
291 Deletion, // A -
292 Deletion, // B -
293 NoOp, // B B
294 ],
295 }
296 .run();
297 }
298
299 #[test]
300 fn test_5() {
301 // Insertions are grouped together.
302 TestCase {
303 before: "AB",
304 after: "AABB",
305 distance: 5,
306 parts: (2, 4),
307 operations: vec![
308 NoOp, // A A
309 Insertion, // - A
310 Insertion, // - B
311 NoOp, // B B
312 ],
313 }
314 .run();
315 }
316
317 #[test]
318 fn test_6() {
319 // Insertion and Deletion are grouped together.
320 TestCase {
321 before: "AAABBB",
322 after: "ACB",
323 distance: 11,
324 parts: (5, 7),
325 operations: vec![
326 NoOp, // A A
327 Deletion, // A -
328 Deletion, // A -
329 Deletion, // B -
330 Deletion, // B -
331 Insertion, // - C
332 NoOp, // B B
333 ],
334 }
335 .run();
336 }
337
338 struct TestCase<'a> {
339 before: &'a str,
340 after: &'a str,
341 distance: usize,
342 parts: (usize, usize),
343 operations: Vec<Operation>,
344 }
345
346 impl<'a> TestCase<'a> {
347 pub fn run(&self) {
348 self.assert_string_distance_parts();
349 assert_eq!(operations(self.before, self.after), self.operations);
350 }
351
352 fn assert_string_distance_parts(&self) {
353 self.assert_string_levenshtein_distance();
354 assert_eq!(string_distance_parts(self.before, self.after), self.parts);
355 assert_eq!(string_distance_parts(self.after, self.before), self.parts);
356 }
357
358 fn assert_string_levenshtein_distance(&self) {
359 assert_eq!(
360 string_levenshtein_distance(self.before, self.after),
361 self.distance
362 );
363 assert_eq!(
364 string_levenshtein_distance(self.after, self.before),
365 self.distance
366 );
367 }
368 }
369
370 fn string_distance_parts(x: &str, y: &str) -> (usize, usize) {
371 let (x, y) = (
372 x.graphemes(true).collect::<Vec<&str>>(),
373 y.graphemes(true).collect::<Vec<&str>>(),
374 );
375 Alignment::new(x, y).distance_parts()
376 }
377
378 fn string_levenshtein_distance(x: &str, y: &str) -> usize {
379 let (x, y) = (
380 x.graphemes(true).collect::<Vec<&str>>(),
381 y.graphemes(true).collect::<Vec<&str>>(),
382 );
383 Alignment::new(x, y).levenshtein_distance()
384 }
385
386 fn operations<'a>(x: &'a str, y: &'a str) -> Vec<Operation> {
387 let (x, y) = (
388 x.graphemes(true).collect::<Vec<&str>>(),
389 y.graphemes(true).collect::<Vec<&str>>(),
390 );
391 Alignment::new(x, y).operations()
392 }
393
394 impl<'a> Alignment<'a> {
395 pub fn distance_parts(&self) -> (usize, usize) {
396 let (mut numer, mut denom) = (0, 0);
397 for op in self.operations() {
398 if op != NoOp {
399 numer += 1;
400 }
401 denom += 1;
402 }
403 (numer, denom)
404 }
405
406 /// Compute levenshtein distance from the filled table.
407 pub fn levenshtein_distance(&self) -> usize {
408 self.table[self.index(self.x.len(), self.y.len())].cost
409 }
410
411 #[allow(dead_code)]
412 fn format_cell(&self, cell: &Cell) -> String {
413 let parent = &self.table[cell.parent];
414 let op = match cell.operation {
415 Deletion => "-",
416 Insertion => "+",
417 NoOp => ".",
418 };
419 format!("{}{}{}", parent.cost, op, cell.cost)
420 }
421
422 #[allow(dead_code)]
423 fn print(&self) {
424 println!("x: {:?}", self.x);
425 println!("y: {:?}", self.y);
426 println!();
427 print!(" ");
428 for j in 0..self.dim[1] {
429 print!("{} ", if j > 0 { self.x[j - 1] } else { " " })
430 }
431 println!();
432
433 for i in 0..self.dim[0] {
434 for j in 0..self.dim[1] {
435 if j == 0 {
436 print!("{} ", if i > 0 { self.y[i - 1] } else { " " })
437 }
438 let cell = &self.table[self.index(j, i)];
439 print!("{} ", self.format_cell(cell));
440 }
441 println!();
442 }
443 println!();
444 }
445 }
446 }