-
Notifications
You must be signed in to change notification settings - Fork 229
/
Levenshtein.c
6789 lines (6258 loc) · 187 KB
/
Levenshtein.c
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Levenshtein.c
* @(#) $Id: Levenshtein.c,v 1.41 2005/01/13 20:05:36 yeti Exp $
* Python extension computing Levenshtein distances, string similarities,
* median strings and other goodies.
*
* Copyright (C) 2002-2003 David Necas (Yeti) <yeti@physics.muni.cz>.
*
* The Taus113 random generator:
* Copyright (C) 2002 Atakan Gurkan
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
* (see below for more)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
**/
/**
* TODO:
*
* - Implement weighted string averaging, see:
* H. Bunke et. al.: On the Weighted Mean of a Pair of Strings,
* Pattern Analysis and Applications 2002, 5(1): 23-30.
* X. Jiang et. al.: Dynamic Computations of Generalized Median Strings,
* Pattern Analysis and Applications 2002, ???.
* The latter also contains an interesting median-search algorithm.
*
* - Deal with stray symbols in greedy median() and median_improve().
* There are two possibilities:
* (i) Remember which strings contain which symbols. This allows certain
* small optimizations when processing them.
* (ii) Use some overall heuristics to find symbols which don't worth
* trying. This is very appealing, but hard to do properly
* (requires some inequality strong enough to allow practical exclusion
* of certain symbols -- at certain positions)
*
* - Editops should be an object that only *looks* like a list (which means
* it is a list in duck typing) to avoid never-ending conversions from
* Python lists to LevEditOp arrays and back
*
* - Optimize munkers_blackman(), it's pretty dumb (no memory of visited
* columns/rows)
*
* - Make it really usable as a C library (needs some wrappers, headers, ...,
* and maybe even documentation ;-)
*
* - Add interface to various interesting auxiliary results, namely
* set and sequence distance (only ratio is exported), the map from
* munkers_blackman() itself, ...
*
* - Generalizations:
* - character weight matrix/function
* - arbitrary edit operation costs, decomposable edit operations
*
* - Create a test suite
*
* - Add more interesting algorithms ;-)
*
* Postponed TODO (investigated, and a big `but' was found):
*
* - A linear approximate set median algorithm:
* P. Indyk: Sublinear time algorithms for metric space problems,
* STOC 1999, http://citeseer.nj.nec.com/indyk00sublinear.html.
* BUT: The algorithm seems to be advantageous only in the case of very
* large sets -- if my estimates are correct (the article itself is quite
* `asymptotic'), say 10^5 at least. On smaller sets either one would get
* only an extermely rough median estimate, or the number of distance
* computations would be in fact higher than in the dumb O(n^2) algorithm.
*
* - Improve setmedian() speed with triangular inequality, see:
* Juan, A., E. Vidal: An Algorithm for Fast Median Search,
* 1997, http://citeseer.nj.nec.com/article/juan97algorithm.html
* BUT: It doesn't seem to help much in spaces of high dimension (see the
* discussion and graphs in the article itself), a few percents at most,
* and strings behave like a space with a very high dimension (locally), so
* who knows, it probably wouldn't help much.
*
**/
#ifdef NO_PYTHON
#define _GNU_SOURCE
#include <string.h>
#include <math.h>
/* for debugging */
#include <stdio.h>
#else /* NO_PYTHON */
#define _LEV_STATIC_PY static
#define lev_wchar Py_UNICODE
#include <Python.h>
#endif /* NO_PYTHON */
#if PY_MAJOR_VERSION >= 3
#define PyString_Type PyBytes_Type
#define PyString_GET_SIZE PyBytes_GET_SIZE
#define PyString_AS_STRING PyBytes_AS_STRING
#define PyString_Check PyBytes_Check
#define PyString_FromStringAndSize PyBytes_FromStringAndSize
#define PyString_InternFromString PyUnicode_InternFromString
#define PyInt_AS_LONG PyLong_AsLong
#define PyInt_FromLong PyLong_FromLong
#define PyInt_Check PyLong_Check
#define PY_INIT_MOD(module, name, doc, methods) \
static struct PyModuleDef moduledef = { \
PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
module = PyModule_Create(&moduledef);
#define PY_MOD_INIT_FUNC_DEF(name) PyObject* PyInit_##name(void)
#else
#define PY_INIT_MOD(module, name, doc, methods) \
module = Py_InitModule3(name, methods, doc);
#define PY_MOD_INIT_FUNC_DEF(name) void init##name(void)
#endif /* PY_MAJOR_VERSION */
#include <assert.h>
#include "Levenshtein.h"
/* FIXME: inline avaliability should be solved in setup.py, somehow, or
* even better in Python.h, like const is...
* this should inline at least with gcc and msvc */
#ifndef __GNUC__
# ifdef _MSC_VER
# define inline __inline
# else
# define inline /* */
# endif
# define __attribute__(x) /* */
#endif
#define LEV_EPSILON 1e-14
#define LEV_INFINITY 1e100
/* Me thinks the second argument of PyArg_UnpackTuple() should be const.
* Anyway I habitually pass a constant string.
* A cast to placate the compiler. */
#define PYARGCFIX(x) (char*)(x)
/* local functions */
static size_t*
munkers_blackman(size_t n1,
size_t n2,
double *dists);
#define TAUS113_LCG(n) ((69069UL * n) & 0xffffffffUL)
#define TAUS113_MASK 0xffffffffUL
typedef struct {
unsigned long int z1, z2, z3, z4;
} taus113_state_t;
static inline unsigned long int
taus113_get(taus113_state_t *state);
static void
taus113_set(taus113_state_t *state,
unsigned long int s);
#ifndef NO_PYTHON
/* python interface and wrappers */
/* declarations and docstrings {{{ */
static PyObject* distance_py(PyObject *self, PyObject *args);
static PyObject* ratio_py(PyObject *self, PyObject *args);
static PyObject* hamming_py(PyObject *self, PyObject *args);
static PyObject* jaro_py(PyObject *self, PyObject *args);
static PyObject* jaro_winkler_py(PyObject *self, PyObject *args);
static PyObject* median_py(PyObject *self, PyObject *args);
static PyObject* median_improve_py(PyObject *self, PyObject *args);
static PyObject* quickmedian_py(PyObject *self, PyObject *args);
static PyObject* setmedian_py(PyObject *self, PyObject *args);
static PyObject* seqratio_py(PyObject *self, PyObject *args);
static PyObject* setratio_py(PyObject *self, PyObject *args);
static PyObject* editops_py(PyObject *self, PyObject *args);
static PyObject* opcodes_py(PyObject *self, PyObject *args);
static PyObject* inverse_py(PyObject *self, PyObject *args);
static PyObject* apply_edit_py(PyObject *self, PyObject *args);
static PyObject* matching_blocks_py(PyObject *self, PyObject *args);
static PyObject* subtract_edit_py(PyObject *self, PyObject *args);
#define Levenshtein_DESC \
"A C extension module for fast computation of:\n" \
"- Levenshtein (edit) distance and edit sequence manipluation\n" \
"- string similarity\n" \
"- approximate median strings, and generally string averaging\n" \
"- string sequence and set similarity\n" \
"\n" \
"Levenshtein has a some overlap with difflib (SequenceMatcher). It\n" \
"supports only strings, not arbitrary sequence types, but on the\n" \
"other hand it's much faster.\n" \
"\n" \
"It supports both normal and Unicode strings, but can't mix them, all\n" \
"arguments to a function (method) have to be of the same type (or its\n" \
"subclasses).\n"
#define distance_DESC \
"Compute absolute Levenshtein distance of two strings.\n" \
"\n" \
"distance(string1, string2)\n" \
"\n" \
"Examples (it's hard to spell Levenshtein correctly):\n" \
">>> distance('Levenshtein', 'Lenvinsten')\n" \
"4\n" \
">>> distance('Levenshtein', 'Levensthein')\n" \
"2\n" \
">>> distance('Levenshtein', 'Levenshten')\n" \
"1\n" \
">>> distance('Levenshtein', 'Levenshtein')\n" \
"0\n" \
"\n" \
"Yeah, we've managed it at last.\n"
#define ratio_DESC \
"Compute similarity of two strings.\n" \
"\n" \
"ratio(string1, string2)\n" \
"\n" \
"The similarity is a number between 0 and 1, it's usually equal or\n" \
"somewhat higher than difflib.SequenceMatcher.ratio(), becuase it's\n" \
"based on real minimal edit distance.\n" \
"\n" \
"Examples:\n" \
">>> ratio('Hello world!', 'Holly grail!')\n" \
"0.58333333333333337\n" \
">>> ratio('Brian', 'Jesus')\n" \
"0.0\n" \
"\n" \
"Really? I thought there was some similarity.\n"
#define hamming_DESC \
"Compute Hamming distance of two strings.\n" \
"\n" \
"hamming(string1, string2)\n" \
"\n" \
"The Hamming distance is simply the number of differing characters.\n" \
"That means the length of the strings must be the same.\n" \
"\n" \
"Examples:\n" \
">>> hamming('Hello world!', 'Holly grail!')\n" \
"7\n" \
">>> hamming('Brian', 'Jesus')\n" \
"5\n"
#define jaro_DESC \
"Compute Jaro string similarity metric of two strings.\n" \
"\n" \
"jaro(string1, string2)\n" \
"\n" \
"The Jaro string similarity metric is intended for short strings like\n" \
"personal last names. It is 0 for completely different strings and\n" \
"1 for identical strings.\n" \
"\n" \
"Examples:\n" \
">>> jaro('Brian', 'Jesus')\n" \
"0.0\n" \
">>> jaro('Thorkel', 'Thorgier')\n" \
"0.77976190476190477\n" \
">>> jaro('Dinsdale', 'D')\n" \
"0.70833333333333337\n"
#define jaro_winkler_DESC \
"Compute Jaro string similarity metric of two strings.\n" \
"\n" \
"jaro_winkler(string1, string2[, prefix_weight])\n" \
"\n" \
"The Jaro-Winkler string similarity metric is a modification of Jaro\n" \
"metric giving more weight to common prefix, as spelling mistakes are\n" \
"more likely to occur near ends of words.\n" \
"\n" \
"The prefix weight is inverse value of common prefix length sufficient\n" \
"to consider the strings `identical'. If no prefix weight is\n" \
"specified, 1/10 is used.\n" \
"\n" \
"Examples:\n" \
">>> jaro_winkler('Brian', 'Jesus')\n" \
"0.0\n" \
">>> jaro_winkler('Thorkel', 'Thorgier')\n" \
"0.86785714285714288\n" \
">>> jaro_winkler('Dinsdale', 'D')\n" \
"0.73750000000000004\n" \
">>> jaro_winkler('Thorkel', 'Thorgier', 0.25)\n" \
"1.0\n"
#define median_DESC \
"Find an approximate generalized median string using greedy algorithm.\n" \
"\n" \
"median(string_sequence[, weight_sequence])\n" \
"\n" \
"You can optionally pass a weight for each string as the second\n" \
"argument. The weights are interpreted as item multiplicities,\n" \
"although any non-negative real numbers are accepted. Use them to\n" \
"improve computation speed when strings often appear multiple times\n" \
"in the sequence.\n" \
"\n" \
"Examples:\n" \
">>> median(['SpSm', 'mpamm', 'Spam', 'Spa', 'Sua', 'hSam'])\n" \
"'Spam'\n" \
">>> fixme = ['Levnhtein', 'Leveshein', 'Leenshten',\n" \
"... 'Leveshtei', 'Lenshtein', 'Lvenstein',\n" \
"... 'Levenhtin', 'evenshtei']\n" \
">>> median(fixme)\n" \
"'Levenshtein'\n" \
"\n" \
"Hm. Even a computer program can spell Levenshtein better than me.\n"
#define median_improve_DESC \
"Improve an approximate generalized median string by perturbations.\n" \
"\n" \
"median_improve(string, string_sequence[, weight_sequence])\n" \
"\n" \
"The first argument is the estimated generalized median string you\n" \
"want to improve, the others are the same as in median(). It returns\n" \
"a string with total distance less or equal to that of the given string.\n" \
"\n" \
"Note this is much slower than median(). Also note it performs only\n" \
"one improvement step, calling median_improve() again on the result\n" \
"may improve it further, though this is unlikely to happen unless the\n" \
"given string was not very similar to the actual generalized median.\n" \
"\n" \
"Examples:\n" \
">>> fixme = ['Levnhtein', 'Leveshein', 'Leenshten',\n" \
"... 'Leveshtei', 'Lenshtein', 'Lvenstein',\n" \
"... 'Levenhtin', 'evenshtei']\n" \
">>> median_improve('spam', fixme)\n" \
"'enhtein'\n" \
">>> median_improve(median_improve('spam', fixme), fixme)\n" \
"'Levenshtein'\n" \
"\n" \
"It takes some work to change spam to Levenshtein.\n"
#define quickmedian_DESC \
"Find a very approximate generalized median string, but fast.\n" \
"\n" \
"quickmedian(string[, weight_sequence])\n" \
"\n" \
"See median() for argument description.\n" \
"\n" \
"This method is somewhere between setmedian() and picking a random\n" \
"string from the set; both speedwise and quality-wise.\n" \
"\n" \
"Examples:\n" \
">>> fixme = ['Levnhtein', 'Leveshein', 'Leenshten',\n" \
"... 'Leveshtei', 'Lenshtein', 'Lvenstein',\n" \
"... 'Levenhtin', 'evenshtei']\n" \
">>> quickmedian(fixme)\n" \
"'Levnshein'\n"
#define setmedian_DESC \
"Find set median of a string set (passed as a sequence).\n" \
"\n" \
"setmedian(string[, weight_sequence])\n" \
"\n" \
"See median() for argument description.\n" \
"\n" \
"The returned string is always one of the strings in the sequence.\n" \
"\n" \
"Examples:\n" \
">>> setmedian(['ehee', 'cceaes', 'chees', 'chreesc',\n" \
"... 'chees', 'cheesee', 'cseese', 'chetese'])\n" \
"'chees'\n" \
"\n" \
"You haven't asked me about Limburger, sir.\n"
#define seqratio_DESC \
"Compute similarity ratio of two sequences of strings.\n" \
"\n" \
"seqratio(string_sequence1, string_sequence2)\n" \
"\n" \
"This is like ratio(), but for string sequences. A kind of ratio()\n" \
"is used to to measure the cost of item change operation for the\n" \
"strings.\n" \
"\n" \
"Examples:\n" \
">>> seqratio(['newspaper', 'litter bin', 'tinny', 'antelope'],\n" \
"... ['caribou', 'sausage', 'gorn', 'woody'])\n" \
"0.21517857142857144\n"
#define setratio_DESC \
"Compute similarity ratio of two strings sets (passed as sequences).\n" \
"\n" \
"setratio(string_sequence1, string_sequence2)\n" \
"\n" \
"The best match between any strings in the first set and the second\n" \
"set (passed as sequences) is attempted. I.e., the order doesn't\n" \
"matter here.\n" \
"\n" \
"Examples:\n" \
">>> setratio(['newspaper', 'litter bin', 'tinny', 'antelope'],\n" \
"... ['caribou', 'sausage', 'gorn', 'woody'])\n" \
"0.28184523809523809\n" \
"\n" \
"No, even reordering doesn't help the tinny words to match the\n" \
"woody ones.\n"
#define editops_DESC \
"Find sequence of edit operations transforming one string to another.\n" \
"\n" \
"editops(source_string, destination_string)\n" \
"editops(edit_operations, source_length, destination_length)\n" \
"\n" \
"The result is a list of triples (operation, spos, dpos), where\n" \
"operation is one of `equal', `replace', `insert', or `delete'; spos\n" \
"and dpos are position of characters in the first (source) and the\n" \
"second (destination) strings. These are operations on single\n" \
"characters. In fact the returned list doesn't contain the `equal',\n" \
"but all the related functions accept both lists with and without\n" \
"`equal's.\n" \
"\n" \
"Examples:\n" \
">>> editops('spam', 'park')\n" \
"[('delete', 0, 0), ('insert', 3, 2), ('replace', 3, 3)]\n" \
"\n" \
"The alternate form editops(opcodes, source_string, destination_string)\n" \
"can be used for conversion from opcodes (5-tuples) to editops (you can\n" \
"pass strings or their lengths, it doesn't matter).\n"
#define opcodes_DESC \
"Find sequence of edit operations transforming one string to another.\n" \
"\n" \
"opcodes(source_string, destination_string)\n" \
"opcodes(edit_operations, source_length, destination_length)\n" \
"\n" \
"The result is a list of 5-tuples with the same meaning as in\n" \
"SequenceMatcher's get_opcodes() output. But since the algorithms\n" \
"differ, the actual sequences from Levenshtein and SequenceMatcher\n" \
"may differ too.\n" \
"\n" \
"Examples:\n" \
">>> for x in opcodes('spam', 'park'):\n" \
"... print x\n" \
"...\n" \
"('delete', 0, 1, 0, 0)\n" \
"('equal', 1, 3, 0, 2)\n" \
"('insert', 3, 3, 2, 3)\n" \
"('replace', 3, 4, 3, 4)\n" \
"\n" \
"The alternate form opcodes(editops, source_string, destination_string)\n" \
"can be used for conversion from editops (triples) to opcodes (you can\n" \
"pass strings or their lengths, it doesn't matter).\n"
#define inverse_DESC \
"Invert the sense of an edit operation sequence.\n" \
"\n" \
"inverse(edit_operations)\n" \
"\n" \
"In other words, it returns a list of edit operations transforming the\n" \
"second (destination) string to the first (source). It can be used\n" \
"with both editops and opcodes.\n" \
"\n" \
"Examples:\n" \
">>> inverse(editops('spam', 'park'))\n" \
"[('insert', 0, 0), ('delete', 2, 3), ('replace', 3, 3)]\n" \
">>> editops('park', 'spam')\n" \
"[('insert', 0, 0), ('delete', 2, 3), ('replace', 3, 3)]\n"
#define apply_edit_DESC \
"Apply a sequence of edit operations to a string.\n" \
"\n" \
"apply_edit(edit_operations, source_string, destination_string)\n" \
"\n" \
"In the case of editops, the sequence can be arbitrary ordered subset\n" \
"of the edit sequence transforming source_string to destination_string.\n" \
"\n" \
"Examples:\n" \
">>> e = editops('man', 'scotsman')\n" \
">>> apply_edit(e, 'man', 'scotsman')\n" \
"'scotsman'\n" \
">>> apply_edit(e[:3], 'man', 'scotsman')\n" \
"'scoman'\n" \
"\n" \
"The other form of edit operations, opcodes, is not very suitable for\n" \
"such a tricks, because it has to always span over complete strings,\n" \
"subsets can be created by carefully replacing blocks with `equal'\n" \
"blocks, or by enlarging `equal' block at the expense of other blocks\n" \
"and adjusting the other blocks accordingly.\n" \
"\n" \
"Examples:\n" \
">>> a, b = 'spam and eggs', 'foo and bar'\n" \
">>> e = opcodes(a, b)\n" \
">>> apply_edit(inverse(e), b, a)\n" \
"'spam and eggs'\n" \
">>> e[4] = ('equal', 10, 13, 8, 11)\n" \
">>> apply_edit(e, a, b)\n" \
"'foo and ggs'\n"
#define matching_blocks_DESC \
"Find identical blocks in two strings.\n" \
"\n" \
"matching_blocks(edit_operations, source_length, destination_length)\n" \
"\n" \
"The result is a list of triples with the same meaning as in\n" \
"SequenceMatcher's get_matching_blocks() output. It can be used with\n" \
"both editops and opcodes. The second and third arguments don't\n" \
"have to be actually strings, their lengths are enough.\n" \
"\n" \
"Examples:\n" \
">>> a, b = 'spam', 'park'\n" \
">>> matching_blocks(editops(a, b), a, b)\n" \
"[(1, 0, 2), (4, 4, 0)]\n" \
">>> matching_blocks(editops(a, b), len(a), len(b))\n" \
"[(1, 0, 2), (4, 4, 0)]\n" \
"\n" \
"The last zero-length block is not an error, but it's there for\n" \
"compatibility with difflib which always emits it.\n" \
"\n" \
"One can join the matching blocks to get two identical strings:\n" \
">>> a, b = 'dog kennels', 'mattresses'\n" \
">>> mb = matching_blocks(editops(a,b), a, b)\n" \
">>> ''.join([a[x[0]:x[0]+x[2]] for x in mb])\n" \
"'ees'\n" \
">>> ''.join([b[x[1]:x[1]+x[2]] for x in mb])\n" \
"'ees'\n"
#define subtract_edit_DESC \
"Subtract an edit subsequence from a sequence.\n" \
"\n" \
"subtract_edit(edit_operations, subsequence)\n" \
"\n" \
"The result is equivalent to\n" \
"editops(apply_edit(subsequence, s1, s2), s2), except that is\n" \
"constructed directly from the edit operations. That is, if you apply\n" \
"it to the result of subsequence application, you get the same final\n" \
"string as from application complete edit_operations. It may be not\n" \
"identical, though (in amibuous cases, like insertion of a character\n" \
"next to the same character).\n" \
"\n" \
"The subtracted subsequence must be an ordered subset of\n" \
"edit_operations.\n" \
"\n" \
"Note this function does not accept difflib-style opcodes as no one in\n" \
"his right mind wants to create subsequences from them.\n" \
"\n" \
"Examples:\n" \
">>> e = editops('man', 'scotsman')\n" \
">>> e1 = e[:3]\n" \
">>> bastard = apply_edit(e1, 'man', 'scotsman')\n" \
">>> bastard\n" \
"'scoman'\n" \
">>> apply_edit(subtract_edit(e, e1), bastard, 'scotsman')\n" \
"'scotsman'\n" \
#define METHODS_ITEM(x) { #x, x##_py, METH_VARARGS, x##_DESC }
static PyMethodDef methods[] = {
METHODS_ITEM(distance),
METHODS_ITEM(ratio),
METHODS_ITEM(hamming),
METHODS_ITEM(jaro),
METHODS_ITEM(jaro_winkler),
METHODS_ITEM(median),
METHODS_ITEM(median_improve),
METHODS_ITEM(quickmedian),
METHODS_ITEM(setmedian),
METHODS_ITEM(seqratio),
METHODS_ITEM(setratio),
METHODS_ITEM(editops),
METHODS_ITEM(opcodes),
METHODS_ITEM(inverse),
METHODS_ITEM(apply_edit),
METHODS_ITEM(matching_blocks),
METHODS_ITEM(subtract_edit),
{ NULL, NULL, 0, NULL },
};
/* opcode names, these are to be initialized in the init func,
* indexed by LevEditType values */
struct {
PyObject* pystring;
const char *cstring;
size_t len;
}
static opcode_names[] = {
{ NULL, "equal", 0 },
{ NULL, "replace", 0 },
{ NULL, "insert", 0 },
{ NULL, "delete", 0 },
};
#define N_OPCODE_NAMES ((sizeof(opcode_names)/sizeof(opcode_names[0])))
typedef lev_byte *(*MedianFuncString)(size_t n,
const size_t *lengths,
const lev_byte *strings[],
const double *weights,
size_t *medlength);
typedef Py_UNICODE *(*MedianFuncUnicode)(size_t n,
const size_t *lengths,
const Py_UNICODE *strings[],
const double *weights,
size_t *medlength);
typedef struct {
MedianFuncString s;
MedianFuncUnicode u;
} MedianFuncs;
typedef lev_byte *(*MedianImproveFuncString)(size_t len, const lev_byte *s,
size_t n,
const size_t *lengths,
const lev_byte *strings[],
const double *weights,
size_t *medlength);
typedef Py_UNICODE *(*MedianImproveFuncUnicode)(size_t len, const Py_UNICODE *s,
size_t n,
const size_t *lengths,
const Py_UNICODE *strings[],
const double *weights,
size_t *medlength);
typedef struct {
MedianImproveFuncString s;
MedianImproveFuncUnicode u;
} MedianImproveFuncs;
typedef double (*SetSeqFuncString)(size_t n1,
const size_t *lengths1,
const lev_byte *strings1[],
size_t n2,
const size_t *lengths2,
const lev_byte *strings2[]);
typedef double (*SetSeqFuncUnicode)(size_t n1,
const size_t *lengths1,
const Py_UNICODE *strings1[],
size_t n2,
const size_t *lengths2,
const Py_UNICODE *strings2[]);
typedef struct {
SetSeqFuncString s;
SetSeqFuncUnicode u;
} SetSeqFuncs;
static long int
levenshtein_common(PyObject *args,
const char *name,
size_t xcost,
size_t *lensum);
static int
extract_stringlist(PyObject *list,
const char *name,
size_t n,
size_t **sizelist,
void *strlist);
static double*
extract_weightlist(PyObject *wlist,
const char *name,
size_t n);
static PyObject*
median_common(PyObject *args,
const char *name,
MedianFuncs foo);
static PyObject*
median_improve_common(PyObject *args,
const char *name,
MedianImproveFuncs foo);
static double
setseq_common(PyObject *args,
const char *name,
SetSeqFuncs foo,
size_t *lensum);
/* }}} */
/****************************************************************************
*
* Python interface and subroutines
*
****************************************************************************/
/* {{{ */
static long int
levenshtein_common(PyObject *args, const char *name, size_t xcost,
size_t *lensum)
{
PyObject *arg1, *arg2;
size_t len1, len2;
if (!PyArg_UnpackTuple(args, PYARGCFIX(name), 2, 2, &arg1, &arg2))
return -1;
if (PyObject_TypeCheck(arg1, &PyString_Type)
&& PyObject_TypeCheck(arg2, &PyString_Type)) {
lev_byte *string1, *string2;
len1 = PyString_GET_SIZE(arg1);
len2 = PyString_GET_SIZE(arg2);
*lensum = len1 + len2;
string1 = PyString_AS_STRING(arg1);
string2 = PyString_AS_STRING(arg2);
{
size_t d = lev_edit_distance(len1, string1, len2, string2, xcost);
if (d == (size_t)(-1)) {
PyErr_NoMemory();
return -1;
}
return d;
}
}
else if (PyObject_TypeCheck(arg1, &PyUnicode_Type)
&& PyObject_TypeCheck(arg2, &PyUnicode_Type)) {
Py_UNICODE *string1, *string2;
len1 = PyUnicode_GET_SIZE(arg1);
len2 = PyUnicode_GET_SIZE(arg2);
*lensum = len1 + len2;
string1 = PyUnicode_AS_UNICODE(arg1);
string2 = PyUnicode_AS_UNICODE(arg2);
{
size_t d = lev_u_edit_distance(len1, string1, len2, string2, xcost);
if (d == (size_t)(-1)) {
PyErr_NoMemory();
return -1;
}
return d;
}
}
else {
PyErr_Format(PyExc_TypeError,
"%s expected two Strings or two Unicodes", name);
return -1;
}
}
static PyObject*
distance_py(PyObject *self, PyObject *args)
{
size_t lensum;
long int ldist;
if ((ldist = levenshtein_common(args, "distance", 0, &lensum)) < 0)
return NULL;
return PyInt_FromLong((long)ldist);
}
static PyObject*
ratio_py(PyObject *self, PyObject *args)
{
size_t lensum;
long int ldist;
if ((ldist = levenshtein_common(args, "ratio", 1, &lensum)) < 0)
return NULL;
if (lensum == 0)
return PyFloat_FromDouble(1.0);
return PyFloat_FromDouble((double)(lensum - ldist)/(lensum));
}
static PyObject*
hamming_py(PyObject *self, PyObject *args)
{
PyObject *arg1, *arg2;
const char *name = "hamming";
size_t len1, len2;
long int dist;
if (!PyArg_UnpackTuple(args, PYARGCFIX(name), 2, 2, &arg1, &arg2))
return NULL;
if (PyObject_TypeCheck(arg1, &PyString_Type)
&& PyObject_TypeCheck(arg2, &PyString_Type)) {
lev_byte *string1, *string2;
len1 = PyString_GET_SIZE(arg1);
len2 = PyString_GET_SIZE(arg2);
if (len1 != len2) {
PyErr_Format(PyExc_ValueError,
"%s expected two strings of the same length", name);
return NULL;
}
string1 = PyString_AS_STRING(arg1);
string2 = PyString_AS_STRING(arg2);
dist = lev_hamming_distance(len1, string1, string2);
return PyInt_FromLong(dist);
}
else if (PyObject_TypeCheck(arg1, &PyUnicode_Type)
&& PyObject_TypeCheck(arg2, &PyUnicode_Type)) {
Py_UNICODE *string1, *string2;
len1 = PyUnicode_GET_SIZE(arg1);
len2 = PyUnicode_GET_SIZE(arg2);
if (len1 != len2) {
PyErr_Format(PyExc_ValueError,
"%s expected two unicodes of the same length", name);
return NULL;
}
string1 = PyUnicode_AS_UNICODE(arg1);
string2 = PyUnicode_AS_UNICODE(arg2);
dist = lev_u_hamming_distance(len1, string1, string2);
return PyInt_FromLong(dist);
}
else {
PyErr_Format(PyExc_TypeError,
"%s expected two Strings or two Unicodes", name);
return NULL;
}
}
static PyObject*
jaro_py(PyObject *self, PyObject *args)
{
PyObject *arg1, *arg2;
const char *name = "jaro";
size_t len1, len2;
if (!PyArg_UnpackTuple(args, PYARGCFIX(name), 2, 2, &arg1, &arg2))
return NULL;
if (PyObject_TypeCheck(arg1, &PyString_Type)
&& PyObject_TypeCheck(arg2, &PyString_Type)) {
lev_byte *string1, *string2;
len1 = PyString_GET_SIZE(arg1);
len2 = PyString_GET_SIZE(arg2);
string1 = PyString_AS_STRING(arg1);
string2 = PyString_AS_STRING(arg2);
return PyFloat_FromDouble(lev_jaro_ratio(len1, string1, len2, string2));
}
else if (PyObject_TypeCheck(arg1, &PyUnicode_Type)
&& PyObject_TypeCheck(arg2, &PyUnicode_Type)) {
Py_UNICODE *string1, *string2;
len1 = PyUnicode_GET_SIZE(arg1);
len2 = PyUnicode_GET_SIZE(arg2);
string1 = PyUnicode_AS_UNICODE(arg1);
string2 = PyUnicode_AS_UNICODE(arg2);
return PyFloat_FromDouble(lev_u_jaro_ratio(len1, string1, len2, string2));
}
else {
PyErr_Format(PyExc_TypeError,
"%s expected two Strings or two Unicodes", name);
return NULL;
}
}
static PyObject*
jaro_winkler_py(PyObject *self, PyObject *args)
{
PyObject *arg1, *arg2, *arg3 = NULL;
double pfweight = 0.1;
const char *name = "jaro_winkler";
size_t len1, len2;
if (!PyArg_UnpackTuple(args, PYARGCFIX(name), 2, 3, &arg1, &arg2, &arg3))
return NULL;
if (arg3) {
if (!PyObject_TypeCheck(arg3, &PyFloat_Type)) {
PyErr_Format(PyExc_TypeError, "%s third argument must be a Float", name);
return NULL;
}
pfweight = PyFloat_AS_DOUBLE(arg3);
if (pfweight < 0.0) {
PyErr_Format(PyExc_ValueError, "%s negative prefix weight", name);
return NULL;
}
}
if (PyObject_TypeCheck(arg1, &PyString_Type)
&& PyObject_TypeCheck(arg2, &PyString_Type)) {
lev_byte *string1, *string2;
len1 = PyString_GET_SIZE(arg1);
len2 = PyString_GET_SIZE(arg2);
string1 = PyString_AS_STRING(arg1);
string2 = PyString_AS_STRING(arg2);
return PyFloat_FromDouble(lev_jaro_winkler_ratio(len1, string1,
len2, string2,
pfweight));
}
else if (PyObject_TypeCheck(arg1, &PyUnicode_Type)
&& PyObject_TypeCheck(arg2, &PyUnicode_Type)) {
Py_UNICODE *string1, *string2;
len1 = PyUnicode_GET_SIZE(arg1);
len2 = PyUnicode_GET_SIZE(arg2);
string1 = PyUnicode_AS_UNICODE(arg1);
string2 = PyUnicode_AS_UNICODE(arg2);
return PyFloat_FromDouble(lev_u_jaro_winkler_ratio(len1, string1,
len2, string2,
pfweight));
}
else {
PyErr_Format(PyExc_TypeError,
"%s expected two Strings or two Unicodes", name);
return NULL;
}
}
static PyObject*
median_py(PyObject *self, PyObject *args)
{
MedianFuncs engines = { lev_greedy_median, lev_u_greedy_median };
return median_common(args, "median", engines);
}
static PyObject*
median_improve_py(PyObject *self, PyObject *args)
{
MedianImproveFuncs engines = { lev_median_improve, lev_u_median_improve };
return median_improve_common(args, "median_improve", engines);
}
static PyObject*
quickmedian_py(PyObject *self, PyObject *args)
{
MedianFuncs engines = { lev_quick_median, lev_u_quick_median };
return median_common(args, "quickmedian", engines);
}
static PyObject*
setmedian_py(PyObject *self, PyObject *args)
{
MedianFuncs engines = { lev_set_median, lev_u_set_median };
return median_common(args, "setmedian", engines);
}
static PyObject*
median_common(PyObject *args, const char *name, MedianFuncs foo)
{
size_t n, len;
void *strings = NULL;
size_t *sizes = NULL;
PyObject *strlist = NULL;
PyObject *wlist = NULL;
PyObject *strseq = NULL;
double *weights;
int stringtype;
PyObject *result = NULL;
if (!PyArg_UnpackTuple(args, PYARGCFIX(name), 1, 2, &strlist, &wlist))
return NULL;
if (!PySequence_Check(strlist)) {
PyErr_Format(PyExc_TypeError,
"%s first argument must be a Sequence", name);
return NULL;
}
strseq = PySequence_Fast(strlist, name);
n = PySequence_Fast_GET_SIZE(strseq);
if (n == 0) {
Py_INCREF(Py_None);
Py_DECREF(strseq);
return Py_None;
}
/* get (optional) weights, use 1 if none specified. */
weights = extract_weightlist(wlist, name, n);
if (!weights) {
Py_DECREF(strseq);
return NULL;
}
stringtype = extract_stringlist(strseq, name, n, &sizes, &strings);
Py_DECREF(strseq);
if (stringtype < 0) {
free(weights);
return NULL;
}
if (stringtype == 0) {
lev_byte *medstr = foo.s(n, sizes, strings, weights, &len);
if (!medstr && len)
result = PyErr_NoMemory();
else {
result = PyString_FromStringAndSize(medstr, len);
free(medstr);
}
}
else if (stringtype == 1) {
Py_UNICODE *medstr = foo.u(n, sizes, strings, weights, &len);
if (!medstr && len)
result = PyErr_NoMemory();
else {
result = PyUnicode_FromUnicode(medstr, len);
free(medstr);
}
}
else
PyErr_Format(PyExc_SystemError, "%s internal error", name);
free(strings);
free(weights);
free(sizes);
return result;
}
static PyObject*
median_improve_common(PyObject *args, const char *name, MedianImproveFuncs foo)
{
size_t n, len;