strgrp.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*
  2. Group similar strings
  3. Copyright (C) 2014 Andrew Jeffery <andrew@aj.id.au>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include <assert.h>
  16. #include <limits.h>
  17. #include <math.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include "ccan/darray/darray.h"
  24. #include "ccan/stringmap/stringmap.h"
  25. #include "ccan/tal/tal.h"
  26. #include "ccan/tal/str/str.h"
  27. #include "strgrp.h"
  28. #include "config.h"
  29. #define CHAR_N_VALUES (1 << CHAR_BIT)
  30. typedef darray(struct strgrp_grp *) darray_grp;
  31. typedef darray(struct strgrp_item *) darray_item;
  32. typedef stringmap(struct strgrp_grp *) stringmap_grp;
  33. struct grp_score {
  34. struct strgrp_grp *grp;
  35. double score;
  36. };
  37. typedef darray(struct grp_score *) darray_score;
  38. struct strgrp {
  39. double threshold;
  40. stringmap_grp known;
  41. unsigned int n_grps;
  42. darray_grp grps;
  43. struct grp_score *scores;
  44. int16_t pop[CHAR_N_VALUES];
  45. };
  46. struct strgrp_iter {
  47. const struct strgrp *ctx;
  48. int i;
  49. };
  50. struct strgrp_grp {
  51. const char *key;
  52. size_t key_len;
  53. darray_item items;
  54. int32_t n_items;
  55. int16_t pop[CHAR_N_VALUES];
  56. };
  57. struct strgrp_grp_iter {
  58. const struct strgrp_grp *grp;
  59. int i;
  60. };
  61. struct strgrp_item {
  62. const char *key;
  63. void *value;
  64. };
  65. /* String vector cosine similarity[1]
  66. *
  67. * [1] http://blog.nishtahir.com/2015/09/19/fuzzy-string-matching-using-cosine-similarity/
  68. */
  69. static inline void
  70. strpopcnt(const char *const str, int16_t pop[CHAR_N_VALUES]) {
  71. const char *c;
  72. memset(pop, 0, CHAR_N_VALUES * sizeof(*pop));
  73. for(c = str; *c; c++) {
  74. assert(*c >= 0);
  75. pop[(unsigned char)*c]++;
  76. }
  77. }
  78. static inline double
  79. strcossim(const int16_t ref[CHAR_N_VALUES], const int16_t key[CHAR_N_VALUES]) {
  80. int32_t saibi = 0;
  81. int32_t sai2 = 0;
  82. int32_t sbi2 = 0;
  83. size_t i;
  84. for (i = 0; i < CHAR_N_VALUES; i++) {
  85. saibi += ref[i] * key[i];
  86. sai2 += ref[i] * ref[i];
  87. sbi2 += key[i] * key[i];
  88. }
  89. return 1.0 - (2 * acos(saibi / sqrt(sai2 * sbi2)) / M_PI);
  90. }
  91. /* Low-cost filter functions */
  92. static inline double
  93. cossim_correction(const double s)
  94. {
  95. return -((s - 0.5) * (s - 0.5)) + 0.33;
  96. }
  97. static inline bool
  98. should_grp_score_cos(const struct strgrp *const ctx,
  99. struct strgrp_grp *const grp, const char *const str) {
  100. const double s1 = strcossim(ctx->pop, grp->pop);
  101. const double s2 = s1 + cossim_correction(s1);
  102. return ctx->threshold <= s2;
  103. }
  104. static inline bool
  105. should_grp_score_len(const struct strgrp *const ctx,
  106. const struct strgrp_grp *const grp, const char *const str) {
  107. const double lstr = (double) strlen(str);
  108. const double lkey = (double) grp->key_len;
  109. const double lmin = (lstr > lkey) ? lkey : lstr;
  110. const double s = sqrt((2 * lmin * lmin) / (1.0 * lstr * lstr + lkey * lkey));
  111. return ctx->threshold <= s;
  112. }
  113. /* Scoring - Longest Common Subsequence[2]
  114. *
  115. * [2] https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
  116. */
  117. #define ROWS 2
  118. static inline int cmi(int i, int j) {
  119. return ROWS * j + i;
  120. }
  121. static inline int16_t
  122. lcs(const char *const a, const char *const b) {
  123. const int lb = strlen(b);
  124. const int lbp1 = lb + 1;
  125. int16_t *const lookup = calloc(ROWS * lbp1, sizeof(int16_t));
  126. if (!lookup) {
  127. return -1;
  128. }
  129. int ia, ib;
  130. for (ia = (strlen(a) - 1); ia >= 0; ia--) {
  131. const char iav = a[ia];
  132. const int ial = (ia + 1) & 1; // ia last
  133. for (ib = lb - 1; ib >= 0; ib--) {
  134. const char ibv = b[ib];
  135. const int iac = ia & 1; // ia current
  136. const int ibl = ib + 1; // ib last
  137. // don't need separate "ib current" as it's just ib
  138. if (iav == ibv) {
  139. lookup[cmi(iac, ib)] = 1 + lookup[cmi(ial, ibl)];
  140. } else {
  141. const int16_t valb = lookup[cmi(ial, ib)];
  142. const int16_t vabl = lookup[cmi(iac, ibl)];
  143. lookup[cmi(iac, ib)] = (valb > vabl) ? valb : vabl;
  144. }
  145. }
  146. }
  147. int16_t result = lookup[0];
  148. free(lookup);
  149. return result;
  150. }
  151. #undef ROWS
  152. static inline double
  153. nlcs(const char *const a, const char *const b) {
  154. const double lcss = lcs(a, b);
  155. const double la = (double) strlen(a);
  156. const double lb = (double) strlen(b);
  157. const double s = sqrt((2 * lcss * lcss) / (la * la + lb * lb));
  158. return s;
  159. }
  160. static inline double
  161. grp_score(const struct strgrp_grp *const grp, const char *const str) {
  162. return nlcs(grp->key, str);
  163. }
  164. /* Structure management */
  165. static struct strgrp_item *
  166. new_item(tal_t *const tctx, const char *const str, void *const data) {
  167. struct strgrp_item *i = talz(tctx, struct strgrp_item);
  168. if (!i) {
  169. return NULL;
  170. }
  171. i->key = tal_strdup(i, str);
  172. i->value = data;
  173. return i;
  174. }
  175. static bool
  176. add_item(struct strgrp_grp *const ctx, const char *const str,
  177. void *const data) {
  178. struct strgrp_item *i = new_item(ctx, str, data);
  179. if (!i) {
  180. return false;
  181. }
  182. darray_push(ctx->items, i);
  183. ctx->n_items++;
  184. return true;
  185. }
  186. static void
  187. free_grp(struct strgrp_grp *grp) {
  188. darray_free(grp->items);
  189. }
  190. static struct strgrp_grp *
  191. new_grp(tal_t *const tctx, const char *const str, void *const data) {
  192. struct strgrp_grp *b = talz(tctx, struct strgrp_grp);
  193. if (!b) {
  194. return NULL;
  195. }
  196. b->key = tal_strdup(b, str);
  197. b->key_len = strlen(str);
  198. b->n_items = 0;
  199. darray_init(b->items);
  200. tal_add_destructor(b, free_grp);
  201. if (!add_item(b, str, data)) {
  202. return tal_free(b);
  203. }
  204. return b;
  205. }
  206. static struct strgrp_grp *
  207. add_grp(struct strgrp *const ctx, const char *const str,
  208. void *const data) {
  209. struct strgrp_grp *b = new_grp(ctx, str, data);
  210. if (!b) {
  211. return NULL;
  212. }
  213. memcpy(b->pop, ctx->pop, sizeof(ctx->pop));
  214. darray_push(ctx->grps, b);
  215. ctx->n_grps++;
  216. if (ctx->scores) {
  217. if (!tal_resize(&ctx->scores, ctx->n_grps)) {
  218. return NULL;
  219. }
  220. } else {
  221. ctx->scores = tal_arr(ctx, struct grp_score, ctx->n_grps);
  222. if (!ctx->scores) {
  223. return NULL;
  224. }
  225. }
  226. return b;
  227. }
  228. struct strgrp *
  229. strgrp_new(const double threshold) {
  230. struct strgrp *ctx = talz(NULL, struct strgrp);
  231. ctx->threshold = threshold;
  232. stringmap_init(ctx->known, NULL);
  233. // n threads compare strings
  234. darray_init(ctx->grps);
  235. return ctx;
  236. }
  237. static inline void
  238. cache(struct strgrp *const ctx, struct strgrp_grp *const grp,
  239. const char *const str) {
  240. *(stringmap_enter(ctx->known, str)) = grp;
  241. }
  242. static struct strgrp_grp *
  243. grp_for(struct strgrp *const ctx, const char *const str) {
  244. // Ensure ctx->pop is always populated. Returning null here indicates a new
  245. // group should be created, at which point add_grp() copies ctx->pop into
  246. // the new group's struct.
  247. strpopcnt(str, ctx->pop);
  248. if (!ctx->n_grps) {
  249. return NULL;
  250. }
  251. {
  252. struct strgrp_grp **const grp = stringmap_lookup(ctx->known, str);
  253. if (grp) {
  254. return *grp;
  255. }
  256. }
  257. int i;
  258. // Keep ccanlint happy in reduced feature mode
  259. #if HAVE_OPENMP
  260. #pragma omp parallel for schedule(dynamic)
  261. #endif
  262. for (i = 0; i < ctx->n_grps; i++) {
  263. struct strgrp_grp *grp = darray_item(ctx->grps, i);
  264. ctx->scores[i].grp = grp;
  265. ctx->scores[i].score = 0;
  266. if (should_grp_score_len(ctx, grp, str)) {
  267. if (should_grp_score_cos(ctx, grp, str)) {
  268. ctx->scores[i].score = grp_score(grp, str);
  269. }
  270. }
  271. }
  272. struct grp_score *max = NULL;
  273. for (i = 0; i < ctx->n_grps; i++) {
  274. if (!max || ctx->scores[i].score > max->score) {
  275. max = &(ctx->scores[i]);
  276. }
  277. }
  278. return (max && max->score >= ctx->threshold) ? max->grp : NULL;
  279. }
  280. const struct strgrp_grp *
  281. strgrp_grp_for(struct strgrp *const ctx, const char *const str) {
  282. return grp_for(ctx, str);
  283. }
  284. const struct strgrp_grp *
  285. strgrp_add(struct strgrp *const ctx, const char *const str,
  286. void *const data) {
  287. bool inserted = false;
  288. // grp_for() populates the ctx->pop memory. add_grp() copies this memory
  289. // into the strgrp_grp that it creates. It's assumed the ctx->pop memory
  290. // has not been modified between the grp_for() and add_grp() calls.
  291. struct strgrp_grp *pick = grp_for(ctx, str);
  292. if (pick) {
  293. inserted = add_item(pick, str, data);
  294. } else {
  295. pick = add_grp(ctx, str, data);
  296. inserted = (NULL != pick);
  297. }
  298. if (inserted) {
  299. assert(NULL != pick);
  300. cache(ctx, pick, str);
  301. }
  302. return pick;
  303. }
  304. struct strgrp_iter *
  305. strgrp_iter_new(struct strgrp *const ctx) {
  306. struct strgrp_iter *iter = talz(ctx, struct strgrp_iter);
  307. if (!iter) {
  308. return NULL;
  309. }
  310. iter->ctx = ctx;
  311. iter->i = 0;
  312. return iter;
  313. }
  314. const struct strgrp_grp *
  315. strgrp_iter_next(struct strgrp_iter *const iter) {
  316. return (iter->ctx->n_grps == iter->i) ?
  317. NULL : darray_item(iter->ctx->grps, iter->i++);
  318. }
  319. void
  320. strgrp_iter_free(struct strgrp_iter *const iter) {
  321. tal_free(iter);
  322. }
  323. struct strgrp_grp_iter *
  324. strgrp_grp_iter_new(const struct strgrp_grp *const grp) {
  325. struct strgrp_grp_iter *iter = talz(grp, struct strgrp_grp_iter);
  326. if (!iter) {
  327. return NULL;
  328. }
  329. iter->grp = grp;
  330. iter->i = 0;
  331. return iter;
  332. }
  333. const struct strgrp_item *
  334. strgrp_grp_iter_next(struct strgrp_grp_iter *const iter) {
  335. return (iter->grp->n_items == iter->i) ?
  336. NULL : darray_item(iter->grp->items, iter->i++);
  337. }
  338. void
  339. strgrp_grp_iter_free(struct strgrp_grp_iter *iter) {
  340. tal_free(iter);
  341. }
  342. const char *
  343. strgrp_grp_key(const struct strgrp_grp *const grp) {
  344. return grp->key;
  345. }
  346. const char *
  347. strgrp_item_key(const struct strgrp_item *const item) {
  348. return item->key;
  349. }
  350. void *
  351. strgrp_item_value(const struct strgrp_item *const item) {
  352. return item->value;
  353. }
  354. void
  355. strgrp_free(struct strgrp *const ctx) {
  356. darray_free(ctx->grps);
  357. stringmap_free(ctx->known);
  358. tal_free(ctx);
  359. }
  360. void
  361. strgrp_free_cb(struct strgrp *const ctx, void (*cb)(void *data)) {
  362. struct strgrp_grp **grp;
  363. struct strgrp_item **item;
  364. darray_foreach(grp, ctx->grps) {
  365. darray_foreach(item, (*grp)->items) {
  366. cb((*item)->value);
  367. }
  368. }
  369. strgrp_free(ctx);
  370. }
  371. static void
  372. print_item(const struct strgrp_item *item) {
  373. printf("\t%s\n", item->key);
  374. }
  375. static void
  376. print_grp(const struct strgrp_grp *const grp) {
  377. struct strgrp_item **item;
  378. printf("%s:\n", grp->key);
  379. darray_foreach(item, grp->items) {
  380. print_item(*item);
  381. }
  382. printf("\n");
  383. }
  384. void
  385. strgrp_print(const struct strgrp *const ctx) {
  386. struct strgrp_grp **grp;
  387. darray_foreach(grp, ctx->grps) {
  388. print_grp(*grp);
  389. }
  390. }