~ubuntu-branches/ubuntu/vivid/phabricator/vivid-proposed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php

/**
 * Compute edit distance between two scalar sequences. This class uses
 * Levenshtein (or Damerau-Levenshtein) to compute the edit distance between
 * two inputs. The inputs are arrays containing any scalars (not just strings)
 * so it can be used with, e.g., utf8 sequences.
 *
 *  $matrix = id(new PhutilEditDistanceMatrix())
 *    ->setSequences(str_split('ran'), str_split('rat'));
 *
 *  $cost = $matrix->getEditDistance();
 *
 * Edit distance computation is slow and requires a large amount of memory;
 * both are roughly O(N * M) in the length of the strings.
 *
 * You can customize the cost of insertions, deletions and replacements. By
 * default, each has a cost of 1.
 *
 *   $matrix->setReplaceCost(1);
 *
 * By default, transpositions are not evaluated (i.e., the algorithm is
 * Levenshtein). You can cause transpositions to be evaluated by setting a
 * transpose cost (which will change the algorithm to Damerau-Levenshtein):
 *
 *   $matrix->setTransposeCost(1);
 *
 * You can also provide a cost to alter the type of operation being applied.
 * Many strings have several equivalently expensive edit sequences, but one
 * some sequences are more readable to humans than others. Providing a small
 * cost to alter operation type tends to smooth out the sequence and produce
 * long runs of a single operation, which are generally more readable. For
 * example, these strings:
 *
 *   (x)
 *   ((x))
 *
 * ...have edit strings "issis" and "isssi", which describe edit operations with
 * the same cost, but the latter string is more comprehensible to human viewers.
 *
 * If you set an alter cost, you must call @{method:setComputeString} to enable
 * type computation. The alter cost should generally be smaller than `c / N`,
 * where `c` is the smallest operational cost and `N` is the length of the
 * longest string. For example, if you are using the default costs (insert = 1,
 * delete = 1, replace = 1) and computing edit distances for strings of fewer
 * than 1,000 characters, you might set the alter cost to 0.001.
 */
final class PhutilEditDistanceMatrix {

  private $insertCost    = 1;
  private $deleteCost    = 1;
  private $replaceCost   = 1;
  private $transposeCost = null;
  private $alterCost     = 0;
  private $maximumLength;
  private $computeString;

  private $x;
  private $y;
  private $prefix;
  private $suffix;

  private $distanceMatrix = null;
  private $typeMatrix = null;

  public function setMaximumLength($maximum_length) {
    $this->maximumLength = $maximum_length;
    return $this;
  }

  public function getMaximumLength() {
    return coalesce($this->maximumLength, $this->getInfinity());
  }

  public function setComputeString($compute_string) {
    $this->computeString = $compute_string;
    return $this;
  }

  public function getComputeString() {
    return $this->computeString;
  }

  public function setTransposeCost($transpose_cost) {
    $this->transposeCost = $transpose_cost;
    return $this;
  }

  public function getTransposeCost() {
    return $this->transposeCost;
  }

  public function setReplaceCost($replace_cost) {
    $this->replaceCost = $replace_cost;
    return $this;
  }

  public function getReplaceCost() {
    return $this->replaceCost;
  }

  public function setDeleteCost($delete_cost) {
    $this->deleteCost = $delete_cost;
    return $this;
  }

  public function getDeleteCost() {
    return $this->deleteCost;
  }

  public function setInsertCost($insert_cost) {
    $this->insertCost = $insert_cost;
    return $this;
  }

  public function getInsertCost() {
    return $this->insertCost;
  }

  public function setAlterCost($alter_cost) {
    $this->alterCost = $alter_cost;
    return $this;
  }

  public function getAlterCost() {
    return $this->alterCost;
  }

  public function setSequences(array $x, array $y) {

    // NOTE: We strip common prefixes and suffixes from the inputs because
    // the runtime of the edit distance algorithm is large and it is common
    // to diff similar strings.

    $xl = count($x);
    $yl = count($y);
    $l = min($xl, $yl);

    $prefix_l = 0;
    $suffix_l = 0;

    for ($ii = 0; $ii < $l; $ii++) {
      if ($x[$ii] !== $y[$ii]) {
        break;
      }
      $prefix_l++;
    }

    for ($ii = 1; $ii <= ($l - $prefix_l); $ii++) {
      if ($x[$xl - $ii] !== $y[$yl - $ii]) {
        break;
      }
      $suffix_l++;
    }

    $this->prefix = array_slice($x, 0, $prefix_l);
    $this->suffix = array_slice($x, $xl - $suffix_l);

    $this->x = array_slice($x, $prefix_l, $xl - ($suffix_l + $prefix_l));
    $this->y = array_slice($y, $prefix_l, $yl - ($suffix_l + $prefix_l));
    $this->distanceMatrix = null;

    return $this;
  }

  private function requireSequences() {
    if ($this->x === null) {
      throw new Exception(
        'Call setSequences() before performing useful work!');
    }
  }

  public function getEditDistance() {
    $this->requireSequences();

    $x = $this->x;
    $y = $this->y;

    if (!$x) {
      return $this->insertCost * count($y);
    }

    if (!$y) {
      return $this->deleteCost * count($x);
    }

    $max = $this->getMaximumLength();
    if (count($x) > $max || count($y) > $max) {
      return ($this->insertCost * count($y)) + ($this->deleteCost * count($x));
    }

    if ($x === $y) {
      return 0;
    }

    $matrix = $this->getDistanceMatrix();

    return $matrix[count($x)][count($y)];
  }

  /**
   * Return a string representing the edits between the sequences. The string
   * has these characters:
   *
   *   - s (same): Same character in both strings.
   *   - i (insert): Character inserted.
   *   - d (delete): Character deleted.
   *   - x (replace): Character replaced.
   *   - t (transpose): Character transposed.
   */
  public function getEditString() {
    $this->requireSequences();

    $x = $this->x;
    $y = $this->y;

    if (!$x && !$y) {
      return $this->padEditString('');
    }

    if (!$x) {
      return $this->padEditString(str_repeat('i', count($y)));
    }

    if (!$y) {
      return $this->padEditString(str_repeat('d', count($x)));
    }

    if ($x === $y) {
      return $this->padEditString(str_repeat('s', count($x)));
    }

    $max = $this->getMaximumLength();
    if (count($x) > $max || count($y) > $max) {
      return $this->padEditString(
        str_repeat('d', count($x)).
        str_repeat('i', count($y)));
    }

    $matrix = $this->getTypeMatrix();

    $xx = count($x);
    $yy = count($y);

    $transposes = array();
    $str = '';
    while (true) {
      $type = $matrix[$xx][$yy];

      if (is_array($type)) {
        $chr = 't';
        $transposes[$type[0]][$type[1]] = true;
        $type = $type[2];
      } else {
        $chr = $type;
      }

      if (isset($transposes[$xx][$yy])) {
        $chr = 't';
      }

      if ($type == 's' || $type == 'x') {
        $xx -= 1;
        $yy -= 1;
      } else if ($type == 'i') {
        $yy -= 1;
      } else if ($type == 'd') {
        $xx -= 1;
      } else {
        throw new Exception("Unknown type '{$type}' in type matrix.");
      }

      $str .= $chr;

      if ($xx <= 0 && $yy <= 0) {
        break;
      }
    }

    return $this->padEditString(strrev($str));
  }

  private function padEditString($str) {
    if ($this->prefix) {
      $str = str_repeat('s', count($this->prefix)).$str;
    }
    if ($this->suffix) {
      $str = $str.str_repeat('s', count($this->suffix));
    }
    return $str;
  }

  private function getTypeMatrix() {
    if (!$this->computeString) {
      throw new Exception(
        'Call setComputeString() before getTypeMatrix().');
    }
    if ($this->typeMatrix === null) {
      $this->computeMatrix($this->x, $this->y);
    }
    return $this->typeMatrix;
  }

  private function getDistanceMatrix() {
    if ($this->distanceMatrix === null) {
      $this->computeMatrix($this->x, $this->y);
    }
    return $this->distanceMatrix;
  }

  private function computeMatrix(array $x, array $y) {
    $xl = count($x);
    $yl = count($y);

    $m = array();

    $infinity = $this->getInfinity();

    $use_damerau = ($this->transposeCost !== null);
    if ($use_damerau) {
      // Initialize the default cost of a transpose.
      $m[-1][-1] = $infinity;

      // Initialize the character position dictionary for Damerau.
      $d = array();
      foreach ($x as $c) {
        $d[$c] = -1;
      }
      foreach ($y as $c) {
        $d[$c] = -1;
      }

      // Initialize the transpose costs for Damerau.
      for ($xx = 0; $xx <= $xl; $xx++) {
        $m[$xx][-1] = $infinity;
      }

      for ($yy = 0; $yy <= $yl; $yy++) {
        $m[-1][$yy] = $infinity;
      }
    }

    // Initialize the top row of the matrix.
    for ($xx = 0; $xx <= $xl; $xx++) {
      $m[$xx][0] = $xx * $this->deleteCost;
    }

    // Initialize the left column of the matrix.
    $cost = 0;
    for ($yy = 0; $yy <= $yl; $yy++) {
      $m[0][$yy] = $yy * $this->insertCost;
    }

    $use_types = ($this->computeString);
    if ($use_types) {
      $t = array();
      for ($xx = 0; $xx <= $xl; $xx++) {
        $t[$xx][0] = 'd';
      }
      for ($yy = 0; $yy <= $yl; $yy++) {
        $t[0][$yy] = 'i';
      }
      $t[0][0] = 's';
    }

    $alt_cost = $this->getAlterCost();
    if ($alt_cost && !$use_types) {
      throw new Exception(
        'If you provide an alter cost with setAlterCost(), you must enable '.
        'type computation with setComputeStrings().');
    }

    // Build the edit distance matrix.
    for ($xx = 1; $xx <= $xl; $xx++) {
      $last_dy = -1;
      for ($yy = 1; $yy <= $yl; $yy++) {
        if ($use_damerau) {
          $dx = $d[$y[$yy - 1]];
          $dy = $last_dy;
        }

        if ($x[$xx - 1] === $y[$yy - 1]) {
          $rep_cost = $m[$xx - 1][$yy - 1] + 0;
          $rep_type = 's';
        } else {
          $rep_cost = $m[$xx - 1][$yy - 1] + $this->replaceCost;
          $rep_type = 'x';
        }

        $del_cost = $m[$xx - 1][$yy    ] + $this->deleteCost;
        $ins_cost = $m[$xx    ][$yy - 1] + $this->insertCost;
        if ($alt_cost) {
          $del_char = $t[$xx - 1][$yy    ];
          $ins_char = $t[$xx    ][$yy - 1];
          $rep_char = $t[$xx - 1][$yy - 1];

          if ($del_char !== 'd') {
            $del_cost += $alt_cost;
          }
          if ($ins_char !== 'i') {
            $ins_cost += $alt_cost;
          }
          if ($rep_char !== $rep_type) {
            $rep_cost += $alt_cost;
          }
        }

        if ($rep_cost <= $del_cost && $rep_cost <= $ins_cost) {
          $cost = $rep_cost;
          $type = $rep_type;
          if ($rep_type === 's') {
            $last_dy = $yy - 1;
          }
        } else if ($ins_cost <= $del_cost) {
          $cost = $ins_cost;
          $type = 'i';
        } else {
          $cost = $del_cost;
          $type = 'd';
        }

        if ($use_damerau) {
          $trn_count = (($xx - $dx - 2) + ($yy - $dy - 2) + 1);
          $trn_cost = $m[$dx][$dy] + ($trn_count * $this->transposeCost);
          if ($trn_cost < $cost) {
            $cost = $trn_cost;
            $type = array($dx + 1, $dy + 1, $type);
          }
        }

        $m[$xx][$yy] = $cost;
        if ($use_types) {
          $t[$xx][$yy] = $type;
        }
      }

      if ($use_damerau) {
        $d[$x[$xx - 1]] = ($xx - 1);
      }
    }

    $this->distanceMatrix = $m;
    if ($use_types) {
      $this->typeMatrix = $t;
    }
  }

  private function getInfinity() {
    return INF;
  }

  private function printMatrix(array $m) {
    $x = $this->x;
    $y = $this->y;

    $p = '% 8s ';
    printf($p, ' ');
    foreach (head($m) as $yk => $yv) {
      printf($p, idx($y, $yk - 1, '-'));
    }
    echo "\n";
    foreach ($m as $xk => $xv) {
      printf($p, idx($x, $xk - 1, '-'));
      foreach ($xv as $yk => $yv) {
        printf($p, ($yv == $this->getInfinity() ? 'inf' : $yv));
      }
      echo "\n";
    }
  }

  private function printTypeMatrix(array $t) {
    $x = $this->x;
    $y = $this->y;

    $p = '% 8s ';
    printf($p, ' ');
    foreach (head($t) as $yk => $yv) {
      printf($p, idx($y, $yk - 1, '-'));
    }
    echo "\n";
    foreach ($t as $xk => $xv) {
      printf($p, idx($x, $xk - 1, '-'));
      foreach ($xv as $yk => $yv) {
        printf($p, ($yv == $this->getInfinity() ? 'inf' : $yv));
      }
      echo "\n";
    }
  }

}