blob: f19443f91f16e92889bebf6c3832329b0045ae0e [file] [log] [blame]
Marc Kupietzf11d20c2019-08-02 15:42:04 +02001#include <stdio.h>
2#include <string.h>
3#include <math.h>
4#include <malloc.h>
5#include <stdlib.h> //strlen
6#include <sys/mman.h>
7#include <pthread.h>
8#include <collocatordb.h>
9
10#define max_size 2000
11#define max_w 50
12#define MAX_NEIGHBOURS 1000
13#define MAX_WORDS -1
14#define MAX_THREADS 100
15#define MAX_CC 50
16#define EXP_TABLE_SIZE 1000
17#define MAX_EXP 6
18#define MIN_RESP 0.50
19
20//the thread function
21void *connection_handler(void *);
22
23typedef struct {
24 long long wordi;
25 long position;
26 float activation;
27 float average;
28 float cprobability; // column wise probability
29 float cprobability_sum;
30 float probability;
31 float activation_sum;
32 float max_activation;
33 float heat[16];
34} collocator;
35
36typedef struct {
37 collocator *best;
38 int length;
39} knn;
40
41typedef struct {
42 long long wordi[MAX_NEIGHBOURS];
43 char sep[MAX_NEIGHBOURS];
44 int length;
45} wordlist;
46
47typedef struct {
48 long cutoff;
49 wordlist *wl;
50 char *token;
51 int N;
52 long from;
53 unsigned long upto;
54 collocator *best;
55 float *target_sums;
56 float *window_sums;
57 float threshold;
58} knnpars;
59
60typedef struct {
61 uint32_t index;
62 float value;
63} sparse_t;
64
65typedef struct {
66 uint32_t len;
67 sparse_t nbr[100];
68} profile_t;
69
70float *M, *M2=0L, *syn1neg_window, *expTable;
71float *window_sums;
72char *vocab;
73char *garbage = NULL;
74COLLOCATORDB *cdb = NULL;
75profile_t *sprofiles = NULL;
76size_t sprofiles_qty = 0;
77
78long long words, size, merged_end;
79long long merge_words = 0;
80int num_threads=20;
81int latin_enc=0;
82int window;
83
84/* load collocation profiles if file exists */
85int load_sprofiles(char *vecsname) {
86 char *basename = strdup(vecsname);
87 char *pos = strstr(basename, ".vecs");
88 if(pos)
89 *pos=0;
90
91 char binsprofiles_fname[256];
92 strcpy(binsprofiles_fname, basename);
93 strcat(binsprofiles_fname, ".sprofiles.bin");
94 FILE *fp = fopen(binsprofiles_fname, "rb");
95 if (fp == NULL) {
96 printf("Collocation profiles %s not found. No problem.\n", binsprofiles_fname);
97 return 0;
98 }
99 fseek(fp, 0L, SEEK_END);
100 size_t sz = ftell(fp);
101 fclose(fp);
102
103 int fd = open(binsprofiles_fname, O_RDONLY);
104 sprofiles = mmap(0, sz, PROT_READ, MAP_SHARED, fd, 0);
105 if (sprofiles == MAP_FAILED) {
106 close(fd);
107 fprintf(stderr, "Cannot mmap %s\n", binsprofiles_fname);
108 sprofiles = NULL;
109 return 0;
110 } else {
111 sprofiles_qty = sz / sizeof(profile_t);
112 fprintf(stderr, "Successfully mmaped %s containing similar profiles for %ld word forms.\n", binsprofiles_fname, sprofiles_qty);
113 }
114 return 1;
115}
116
117int init_net(char *file_name, char *net_name, int latin) {
118 FILE *f, *binvecs, *binwords;
119 int binwords_fd, binvecs_fd, net_fd, i;
120 long long a, b, c, d, cn;
121 float len;
122 double val;
123
124 char binvecs_fname[256], binwords_fname[256];
125 strcpy(binwords_fname, file_name);
126 strcat(binwords_fname, ".words");
127 strcpy(binvecs_fname, file_name);
128 strcat(binvecs_fname, ".vecs");
129
130 latin_enc = latin;
131 f = fopen(file_name, "rb");
132 if (f == NULL) {
133 printf("Input file %s not found\n", file_name);
134 return -1;
135 }
136 fscanf(f, "%lld", &words);
137 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
138 fscanf(f, "%lld", &size);
139 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
140 printf("Converting %s to memory mappable structures\n", file_name);
141 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
142 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
143 if (M == NULL) {
144 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
145 return -1;
146 }
147 if(strstr(file_name, ".txt")) {
148 for (b = 0; b < words; b++) {
149 a = 0;
150 while (1) {
151 vocab[b * max_w + a] = fgetc(f);
152 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
153 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
154 }
155 vocab[b * max_w + a] = 0;
156 len = 0;
157 for (a = 0; a < size; a++) {
158 fscanf(f, "%lf", &val);
159 M[a + b * size] = val;
160 len += val * val;
161 }
162 len = sqrt(len);
163 for (a = 0; a < size; a++) M[a + b * size] /= len;
164 }
165 } else {
166 for (b = 0; b < words; b++) {
167 a = 0;
168 while (1) {
169 vocab[b * max_w + a] = fgetc(f);
170 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
171 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
172 }
173 vocab[b * max_w + a] = 0;
174 fread(&M[b * size], sizeof(float), size, f);
175 len = 0;
176 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
177 len = sqrt(len);
178 for (a = 0; a < size; a++) M[a + b * size] /= len;
179 }
180 }
181 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
182 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
183 fclose(binvecs);
184 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
185 fclose(binwords);
186 }
187 }
188 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
189 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
190 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
191 if (M == MAP_FAILED || vocab == MAP_FAILED) {
192 close(binvecs_fd);
193 close(binwords_fd);
194 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
195 exit(-1);
196 }
197 } else {
198 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
199 exit(-1);
200 }
201 fclose(f);
202
203 if(net_name && strlen(net_name) > 0) {
204 if( (net_fd = open(net_name, O_RDONLY)) >= 0) {
205 window = (lseek(net_fd, 0, SEEK_END) - sizeof(float) * words * size) / words / size / sizeof(float) / 2;
206 // lseek(net_fd, sizeof(float) * words * size, SEEK_SET);
207 // munmap(M, sizeof(float) * words * size);
208 M2 = mmap(0, sizeof(float) * words * size + sizeof(float) * 2 * window * size * words, PROT_READ, MAP_SHARED, net_fd, 0);
209 if (M2 == MAP_FAILED) {
210 close(net_fd);
211 fprintf(stderr, "Cannot mmap %s\n", net_name);
212 exit(-1);
213 }
214 syn1neg_window = M2 + words * size;
215 } else {
216 fprintf(stderr, "Cannot open %s\n", net_name);
217 exit(-1);
218 }
219 fprintf(stderr, "Successfully memmaped %s. Determined window size: %d\n", net_name, window);
220
221 char collocatordb_name[2048];
222 strcpy(collocatordb_name, net_name);
223 char *ext = rindex(collocatordb_name, '.');
224 if(ext) {
225 strcpy(ext, ".rocksdb");
226 if(access(collocatordb_name, R_OK) == 0) {
227 *ext = 0;
228 fprintf(stderr, "Opening collocator DB %s\n", collocatordb_name);
229 cdb = open_collocatordb(collocatordb_name);
230 }
231 }
232 }
233
234 expTable = (float *) malloc((EXP_TABLE_SIZE + 1) * sizeof(float));
235 for (i = 0; i < EXP_TABLE_SIZE; i++) {
236 expTable[i] = exp((i / (float) EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
237 expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
238 }
239 window_sums = malloc(sizeof(float) * (window+1) * 2);
240
241 return 0;
242}
243
244long mergeVectors(char *file_name){
245 FILE *f, *binvecs, *binwords;
246 int binwords_fd, binvecs_fd, net_fd, i;
247 long long a, b, c, d, cn;
248 float len;
249 float *merge_vecs;
250 char *merge_vocab;
251 /* long long merge_words, merge_size; */
252 long long merge_size;
253
254 char binvecs_fname[256], binwords_fname[256];
255 strcpy(binwords_fname, file_name);
256 strcat(binwords_fname, ".words");
257 strcpy(binvecs_fname, file_name);
258 strcat(binvecs_fname, ".vecs");
259
260 f = fopen(file_name, "rb");
261 if (f == NULL) {
262 printf("Input file %s not found\n", file_name);
263 exit -1;
264 }
265 fscanf(f, "%lld", &merge_words);
266 fscanf(f, "%lld", &merge_size);
267 if(merge_size != size){
268 fprintf(stderr, "vectors must have the same length\n");
269 exit(-1);
270 }
271 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
272 merge_vecs = malloc(sizeof(float) * (words + merge_words) * size);
273 merge_vocab = malloc(sizeof(char) * (words + merge_words) * max_w);
274 if (merge_vecs == NULL || merge_vocab == NULL) {
275 close(binvecs_fd);
276 close(binwords_fd);
277 fprintf(stderr, "Cannot reserve memory for %s or %s\n", binwords_fname, binvecs_fname);
278 exit(-1);
279 }
280 read(binvecs_fd, merge_vecs, merge_words * size * sizeof(float));
281 read(binwords_fd, merge_vocab, merge_words * max_w);
282 } else {
283 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
284 exit(-1);
285 }
286 printf("Successfully reallocated memory\nMerging...\n");
287 fflush(stdout);
288 memcpy(merge_vecs + merge_words * size, M, words * size * sizeof(float));
289 memcpy(merge_vocab + merge_words * max_w, vocab, words * max_w);
290 munmap(M, words * size * sizeof(float));
291 munmap(vocab, words * max_w);
292 M = merge_vecs;
293 vocab = merge_vocab;
294 merged_end = merge_words;
295 words += merge_words;
296 fclose(f);
297 printf("merged_end: %lld, words: %lld\n", merged_end, words);
298 //printBiggestMergedDifferences();
299 return((long) merged_end);
300}
301
302void filter_garbage() {
303 long i;
304 unsigned char *w, previous, c;
305 garbage = malloc(words);
306 memset(garbage, 0, words);
307 for (i = 0; i < words; i++) {
308 w = vocab + i * max_w;
309 previous = 0;
310 if(strncmp("quot", w, 4) == 0) {
311 garbage[i]=1;
312// printf("Gargabe: %s\n", vocab + i * max_w);
313 } else {
314 while((c = *w++) && !garbage[i]) {
315 if( ((c <= 90 && c >= 65) && (previous >= 97 && previous <= 122)) ||
316 (previous == '-' && (c & 32)) ||
317 (previous == 0xc2 && (c == 0xa4 || c == 0xb6 )) ||
318 (previous == 'q' && c == 'u' && *(w) == 'o' && *(w+1) == 't') || /* quot */
319 c == '<'
320 ) {
321 garbage[i]=1;
322 continue;
323 }
324 previous = c;
325 }
326 }
327 }
328 return;
329}
330
331
332knn *simpleGetCollocators(int word, int number, long cutoff, int *result) {
333 knnpars *pars = calloc(sizeof(knnpars), 1);
334 float *target_sums;
335 float *window_sums = malloc(sizeof(float) * (window+1) * 2);
336 pars->cutoff = (cutoff? cutoff : 300000);
337 long a = posix_memalign((void **) &target_sums, 128, pars->cutoff * sizeof(float));
338 for(a = 0; a < cutoff; a++)
339 target_sums[a] = 0;
340 pars->target_sums = target_sums;
341 pars->window_sums = window_sums;
342 pars->N = (number? number : 20);
343 pars->from = 0;
344 pars->upto = window * 2 -1;
345 knn *syn_nbs = NULL; // = (knn*) getCollocators(pars);
346 free(pars);
347 free(window_sums);
348 free(target_sums);
349 return syn_nbs;
350}
351
352void *getCollocators(void *args) {
353 knnpars *pars = args;
354 int N = pars->N;
355
356 int cc = pars->wl->wordi[0];
357 knn *nbs = NULL;
358 long window_layer_size = size * window * 2;
359 long a, b, c, d, e, window_offset, target, max_target=0, maxmax_target;
360 float f, max_f, maxmax_f;
361 float *target_sums=NULL, worstbest, wpos_sum;
362 collocator *best;
363
364 if(M2 == NULL || cc == -1)
365 return NULL;
366
367 a = posix_memalign((void **) &target_sums, 128, pars->cutoff * sizeof(float));
368 memset(target_sums, 0, pars->cutoff * sizeof(float));
369 best = malloc((N>200?N:200) * sizeof(collocator));
370 memset(best, 0, (N>200?N:200) * sizeof(collocator));
371 worstbest = pars->threshold;
372
373 for (b = 0; b < pars->cutoff; b++)
374 target_sums[b]=0;
375 for (b = 0; b < N; b++) {
376 best[b].wordi = -1;
377 best[b].probability = 1;
378 best[b].activation = worstbest;
379 }
380
381 d = cc;
382 maxmax_f = -1;
383 maxmax_target = 0;
384
385 for (a = pars->from; a < pars->upto; a++) {
386 if(a >= window)
387 a++;
388 wpos_sum = 0;
389 printf("window pos: %ld\n", a);
390 if (a != window) {
391 max_f = -1;
392 window_offset = a * size;
393 if (a > window)
394 window_offset -= size;
395 for(target = 0; target < pars->cutoff; target ++) {
396 if(garbage && garbage[target]) continue;
397 if(target == d)
398 continue;
399 f = 0;
400 for (c = 0; c < size; c++)
401 f += M2[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
402 if (f < -MAX_EXP)
403 continue;
404 else if (f > MAX_EXP)
405 continue;
406 else
407 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
408 wpos_sum += f;
409
410 target_sums[target] += f;
411 if(f > worstbest) {
412 for (b = 0; b < N; b++) {
413 if (f > best[b].activation) {
414 memmove(best + b + 1, best + b, (N - b -1) * sizeof(collocator));
415 best[b].activation = f;
416 best[b].wordi = target;
417 best[b].position = window-a;
418 break;
419 }
420 }
421 if(b == N - 1)
422 worstbest = best[N-1].activation;
423 }
424 }
425 printf("%d %.2f\n", max_target, max_f);
426 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
427 if(max_f > maxmax_f) {
428 maxmax_f = max_f;
429 maxmax_target = max_target;
430 }
431 for (b = 0; b < N; b++)
432 if(best[b].position == window-a)
433 best[b].cprobability = best[b].activation / wpos_sum;
434 } else {
435 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
436 }
437 pars->window_sums[a] = wpos_sum;
438 }
439 for (b = 0; b < pars->cutoff; b++)
440 pars->target_sums[b] += target_sums[b]; //(target_sums[b] / wpos_sum ) / (window * 2);
441
442 free(target_sums);
443 for(b=0; b<N && best[b].wordi >= 0; b++);; // THIS LOOP IS NEEDED (b...)
444// printf("%d: best syn: %s %.2f %.5f\n", b, &vocab[best[b].wordi*max_w], best[b].activation, best[b].probability);
445// printf("\n");
446 nbs = malloc(sizeof(knn));
447 nbs->best = best;
448 nbs->length = b-1;
449 pthread_exit(nbs);
450}
451
452
453AV *getVecs(AV *array) {
454 int i, b;
455 AV *result = newAV();
456 for (i=0; i<=av_len(array); i++) {
457 SV** elem = av_fetch(array, i, 0);
458 if (elem != NULL) {
459 long j = (long) SvNV(*elem);
460 AV *vector = newAV();
461 for (b = 0; b < size; b++) {
462 av_push(vector, newSVnv(M[b + j * size]));
463 }
464 av_push(result, newRV_noinc(vector));
465 }
466 }
467 return result;
468}
469
470char *getSimilarProfiles(long node) {
471 int i;
472 char buffer[120000];
473 char pair_buffer[2048];
474 buffer[0]='[';
475 buffer[1]=0;
476 if(node >= sprofiles_qty) {
477 printf("Not available in precomputed profile\n");
478 return(strdup("[{\"w\":\"not available\", \"v\":0}]\n"));
479 }
480
481 printf("******* %s ******\n", &vocab[max_w * node]);
482
483 for(i=0; i < 100 && i < sprofiles[node].len; i++) {
484 sprintf(pair_buffer, "{\"w\":\"%s\", \"v\":%f},", &vocab[max_w * (sprofiles[node].nbr[i].index)], sprofiles[node].nbr[i].value);
485 strcat(buffer, pair_buffer);
486 }
487 buffer[strlen(buffer)-1]=']';
488 strcat(buffer, "\n");
489 printf(buffer);
490 return(strdup(buffer));
491}
492
493char *getClassicCollocators(long node) {
494 char *res = (cdb? strdup(get_collocators_as_json(cdb, node)) : "[]");
495 return res;
496}
497
498wordlist *getTargetWords(char *st1, int search_backw) {
499 wordlist *wl = malloc(sizeof(wordlist));
500 char st[100][max_size], sep[100];
501 long a, b=0, c=0, cn=0;
502 int unmerged;
503
504 while (1) {
505 st[cn][b] = st1[c];
506 b++;
507 c++;
508 st[cn][b] = 0;
509 if (st1[c] == 0) break;
510 if (st1[c] == ' ' || st1[c] == '-') {
511 sep[cn++] = st1[c];
512 b = 0;
513 c++;
514 }
515 }
516 cn++;
517 for (a = 0; a < cn; a++) {
518 if (search_backw) {
519 for (b = words - 1; b >= (merge_words? merge_words : 0) && strcmp(&vocab[b * max_w], st[a]) !=0; b--);
520 } else {
521 for (b = 0; b < (merge_words? merge_words : words) && strcmp(&vocab[b * max_w], st[a]) != 0; b++);
522 }
523 if (b == words) b = -1;
524 wl->wordi[a] = b;
525 if (b == -1) {
526 fprintf(stderr, "Out of dictionary word!\n");
527 cn--;
528 } else {
529 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", &vocab[wl->wordi[a]*max_w], wl->wordi[a]);
530 }
531 }
532 wl->length=cn;
533 return(wl);
534}
535
536float get_distance(long b, long c) {
537 long a;
538 float dist = 0;
539 for (a = 0; a < size; a++) dist += M[a + c * size] * M[a + b * size];
540 return dist;
541}
542
543char *getBiggestMergedDifferences() {
544 static char *result = NULL;
545 float dist, len, vec[max_size];
546 long long a, b, c, d, cn, *bi;
547 char ch;
548 knn *nbs = NULL;
549 int N = 1000;
550
551 if(merged_end == 0)
552 result = "[]";
553
554 if(result != NULL)
555 return result;
556
557 printf("Looking for biggest distances between main and merged vectors ...\n");
558 collocator *best;
559 best = malloc(N * sizeof(collocator));
560 memset(best, 0, N * sizeof(collocator));
561
562 float worstbest=1000000;
563
564 for (a = 0; a < N; a++) best[a].activation = worstbest;
565
566 for (c = 0; c < 500000; c++) {
567 if(garbage && garbage[c]) continue;
568 a = 0;
569 dist = 0;
570 for (a = 0; a < size; a++) dist += M[a + c * size] * M[a + (c+merged_end) * size];
571 if(dist < worstbest) {
572 for (a = 0; a < N; a++) {
573 if (dist < best[a].activation) {
574 memmove(best + a + 1, best + a, (N - a -1) * sizeof(collocator));
575 best[a].activation = dist;
576 best[a].wordi = c;
577 break;
578 }
579 }
580 worstbest = best[N-1].activation;
581 }
582 }
583
584 result = malloc(N*max_w);
585 char *p = result;
586 *p++ = '['; *p = 0;
587 for (a = 0; a < N; a++) {
588 p += sprintf(p, "{\"rank\":%d,\"word\":\"%s\",\"dist\":%.3f},", a, &vocab[best[a].wordi * max_w], 1-best[a].activation);
589 }
590 *--p = ']';
591 return(result);
592}
593
594
595float cos_similarity(long b, long c) {
596 float dist=0;
597 long a;
598 for (a = 0; a < size; a++) dist += M[b * size + a] * M[c * size + a];
599 return dist;
600}
601
602char *cos_similarity_as_json(char *w1, char *w2) {
603 wordlist *a, *b;
604 float res;
605 a = getTargetWords(w1, 0);
606 b = getTargetWords(w2, 0);
607 if (a == NULL || b==NULL || a->length != 1 || b->length != 1)
608 res = -1;
609 else
610 res = cos_similarity(a->wordi[0], b->wordi[0]);
611 fprintf(stderr, "a: %lld b: %lld res:%f\n", a->wordi[0], b->wordi[0], res);
612 char *json = malloc(16);
613 sprintf(json, "%.5f", res);
614 return json;
615}
616
617void *_get_neighbours(void *arg) {
618 knnpars *pars = arg;
619 char *st1 = pars->token;
620 int N = pars->N;
621 long from = pars -> from;
622 unsigned long upto = pars -> upto;
623 char file_name[max_size], st[100][max_size], *sep;
624 float dist, len, vec[max_size];
625 long long a, b, c, d, cn, *bi;
626 char ch;
627 knn *nbs = NULL;
628 wordlist *wl = pars->wl;
629
630 collocator *best = pars->best;
631
632 float worstbest=-1;
633
634 for (a = 0; a < N; a++) best[a].activation = 0;
635 a = 0;
636 bi = wl->wordi;
637 cn = wl->length;
638 sep = wl->sep;
639 b = bi[0];
640 c = 0;
641 if (b == -1) {
642 N = 0;
643 goto end;
644 }
645 for (a = 0; a < size; a++) vec[a] = 0;
646 for (b = 0; b < cn; b++) {
647 if (bi[b] == -1) continue;
648 if(b>0 && sep[b-1] == '-')
649 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
650 else
651 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
652 }
653 len = 0;
654 for (a = 0; a < size; a++) len += vec[a] * vec[a];
655 len = sqrt(len);
656 for (a = 0; a < size; a++) vec[a] /= len;
657 for (a = 0; a < N; a++) best[a].activation = -1;
658 for (c = from; c < upto; c++) {
659 if(garbage && garbage[c]) continue;
660 a = 0;
661// do not skip taget word
662// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
663// if (a == 1) continue;
664 dist = 0;
665 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
666 if(dist > worstbest) {
667 for (a = 0; a < N; a++) {
668 if (dist > best[a].activation) {
669 memmove(best + a + 1, best + a, (N - a -1) * sizeof(collocator));
670 best[a].activation = dist;
671 best[a].wordi = c;
672 break;
673 }
674 }
675 worstbest = best[N-1].activation;
676 }
677 }
678
679end:
680 pthread_exit(nbs);
681}
682
683int cmp_activation (const void * a, const void * b) {
684 float fb = ((collocator *)a)->activation;
685 float fa = ((collocator *)b)->activation;
686 return (fa > fb) - (fa < fb);
687}
688
689int cmp_probability (const void * a, const void * b) {
690 float fb = ((collocator *)a)->probability;
691 float fa = ((collocator *)b)->probability;
692 return (fa > fb) - (fa < fb);
693}
694
695char* getPosWiseW2VCollocatorsAsTsv(char *word, long maxPerPos, long cutoff, float threshold) {
696 HV *result = newHV();
697 float *target_sums=NULL, vec[max_size];
698 long long old_words;
699 long a, b, c, d;
700 knn *para_nbs[MAX_THREADS];
701 knn *syn_nbs[MAX_THREADS];
702 knnpars pars[MAX_THREADS];
703 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
704 wordlist *wl;
705 int syn_threads = (M2? window * 2 : 0);
706 int search_backw = 0;
707 collocator *best = NULL;
708 posix_memalign((void **) &best, 128, 10 * (maxPerPos>=200? maxPerPos : 200) * sizeof(collocator));
709 memset(best, 0, (maxPerPos>=200? maxPerPos : 200) * sizeof(collocator));
710
711
712 if(cutoff < 1 || cutoff > words)
713 cutoff=words;
714
715 wl = getTargetWords(word, search_backw);
716 if(wl == NULL || wl->length < 1)
717 return "";
718
719 a = posix_memalign((void **) &target_sums, 128, cutoff * sizeof(float));
720 memset(target_sums, 0, cutoff * sizeof(float));
721
722 printf("Starting %d threads\n", syn_threads);
723 fflush(stdout);
724 for(a=0; a < syn_threads; a++) {
725 pars[a].cutoff = cutoff;
726 pars[a].target_sums = target_sums;
727 pars[a].window_sums = window_sums;
728 pars[a].wl = wl;
729 pars[a].N = maxPerPos;
730 pars[a].threshold = threshold;
731 pars[a].from = a;
732 pars[a].upto = a+1;
733 pthread_create(&pt[a], NULL, getCollocators, (void *) &pars[a]);
734 }
735 printf("Waiting for syn threads to join\n");
736 fflush(stdout);
737 for (a = 0; a < syn_threads; a++) pthread_join(pt[a], (void *) &syn_nbs[a]);
738 printf("Syn threads joint\n");
739 fflush(stdout);
740 result = malloc(maxPerPos*80*syn_threads);
741 char *p = result;
742 *p = 0;
743 for (a = syn_threads -1; a >= 0; a--) {
744 for (b=0; b < syn_nbs[a]->length; b++) {
745 p += sprintf(p, "%ld\t%s\t%f\n", syn_nbs[a]->best[b].position, &vocab[syn_nbs[a]->best[b].wordi * max_w], syn_nbs[a]->best[b].activation);
746 }
747 }
748 return(result);
749}
750
751SV *get_neighbours(char *st1, int N, int sort_by, int search_backw, long cutoff, int dedupe, int no_similar_profiles) {
752 HV *result = newHV();
753 float *target_sums=NULL, vec[max_size];
754 long long old_words;
755 long a, b, c, d, slice;
756 knn *para_nbs[MAX_THREADS];
757 knn *syn_nbs[MAX_THREADS];
758 knnpars pars[MAX_THREADS];
759 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
760 wordlist *wl;
761 int syn_threads = (M2? window * 2 : 0);
762 int para_threads = (no_similar_profiles? 0 : num_threads - syn_threads);
763
764 collocator *best = NULL;
765 posix_memalign((void **) &best, 128, 10 * (N>=200? N : 200) * sizeof(collocator));
766 memset(best, 0, (N>=200? N : 200) * sizeof(collocator));
767
768 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
769
770 if(cutoff < 1 || cutoff > words)
771 cutoff=words;
772
773 wl = getTargetWords(st1, search_backw);
774 if(wl == NULL || wl->length < 1)
775 goto end;
776
777 old_words = cutoff;
778 slice = cutoff / para_threads;
779
780 a = posix_memalign((void **) &target_sums, 128, cutoff * sizeof(float));
781 memset(target_sums, 0, cutoff * sizeof(float));
782
783 printf("Starting %d threads\n", para_threads);
784 fflush(stdout);
785 for(a=0; a < para_threads; a++) {
786 pars[a].cutoff = cutoff;
787 pars[a].token = st1;
788 pars[a].wl = wl;
789 pars[a].N = N;
790 pars[a].best = &best[N*a];
791 if(merge_words == 0 || search_backw == 0) {
792 pars[a].from = a*slice;
793 pars[a].upto = ((a+1)*slice > cutoff? cutoff : (a+1) * slice);
794 } else {
795 pars[a].from = merge_words + a * slice;
796 pars[a].upto = merge_words + ((a+1)*slice > cutoff? cutoff : (a+1) * slice);
797 }
798 printf("From: %ld, Upto: %ld\n", pars[a].from, pars[a].upto);
799 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
800 }
801 if(M2) {
802 for(a=0; a < syn_threads; a++) {
803 pars[a + para_threads].cutoff = cutoff;
804 pars[a + para_threads].target_sums = target_sums;
805 pars[a + para_threads].window_sums = window_sums;
806 pars[a + para_threads].wl = wl;
807 pars[a + para_threads].N = N;
808 pars[a + para_threads].threshold = MIN_RESP;
809 pars[a + para_threads].from = a;
810 pars[a + para_threads].upto = a+1;
811 pthread_create(&pt[a + para_threads], NULL, getCollocators, (void *) &pars[a + para_threads]);
812 }
813 }
814 printf("Waiting for para threads to join\n");
815 fflush(stdout);
816 for (a = 0; a < para_threads; a++) pthread_join(pt[a], (void *) &para_nbs[a]);
817 printf("Para threads joint\n");
818 fflush(stdout);
819
820 /* if(!syn_nbs[0]) */
821 /* goto end; */
822
823 qsort(best, N*para_threads, sizeof(collocator), cmp_activation);
824
825
826 long long chosen[MAX_NEIGHBOURS];
827 printf("N: %ld\n", N);
828
829 AV* array = newAV();
830 int i, j;
831 int l1_words=0, l2_words=0;
832
833 for (a = 0, i = 0; i < N && a < N*para_threads; a++) {
834 int filtered=0;
835 long long c = best[a].wordi;
836 if ((merge_words && dedupe && i > 1) || (!merge_words && dedupe && i > 0)) {
837 for (j=0; j<i && !filtered; j++)
838 if (strcasestr(&vocab[c * max_w], &vocab[chosen[j] * max_w]) ||
839 strcasestr(&vocab[chosen[j] * max_w], &vocab[c * max_w])) {
840 printf("filtering %s %s\n", &vocab[chosen[j] * max_w], &vocab[c * max_w]);
841 filtered = 1;
842 }
843 if(filtered)
844 continue;
845 }
846
847
848 if(0 && merge_words > 0) {
849 if(c >= merge_words) {
850 if(l1_words > N / 2)
851 continue;
852 else
853 l1_words++;
854 } else {
855 if(l2_words > N / 2)
856 continue;
857 else
858 l2_words++;
859 }
860 }
861
862// printf("%s l1:%d l2:%d i:%d a:%ld\n", &vocab[c * max_w], l1_words, l2_words, i, a);
863// fflush(stdout);
864 HV* hash = newHV();
865 SV* word = newSVpvf(&vocab[c * max_w], 0);
866 chosen[i] = c;
867 if(latin_enc == 0) SvUTF8_on(word);
868 fflush(stdout);
869 hv_store(hash, "word", strlen("word"), word , 0);
870 hv_store(hash, "dist", strlen("dist"), newSVnv(best[a].activation), 0);
871 hv_store(hash, "rank", strlen("rank"), newSVuv(best[a].wordi), 0);
872 AV *vector = newAV();
873 for (b = 0; b < size; b++) {
874 av_push(vector, newSVnv(M[b + best[a].wordi * size]));
875 }
876 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
877 av_push(array, newRV_noinc((SV*)hash));
878 i++;
879 }
880 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
881
882 for(b=0; b < MAX_NEIGHBOURS; b++) {
883 best[b].wordi = -1L;
884 best[b].activation = 0;
885 best[b].probability = 0;
886 best[b].position = 0;
887 best[b].activation_sum = 0;
888 memset(best[b].heat, 0, sizeof(float)*16);
889 }
890
891 float total_activation = 0;
892
893 if (M2) {
894 printf("Waiting for syn threads to join\n");
895 fflush(stdout);
896 for (a = 0; a < syn_threads; a++) pthread_join(pt[a+para_threads], (void *) &syn_nbs[a]);
897 for (a = 0; a <= syn_threads; a++) {
898 if(a == window) continue;
899 total_activation += window_sums[a];
900 printf("window pos: %d, sum: %f\n", a, window_sums[a]);
901 }
902 printf("syn threads joint\n");
903 fflush(stdout);
904
905 for(b=0; b < syn_nbs[0]->length; b++) {
906 memcpy(best + b, &syn_nbs[0]->best[b], sizeof(collocator));
907 best[b].position = -1; // syn_nbs[0]->pos[b];
908 best[b].activation_sum = target_sums[syn_nbs[0]->best[b].wordi];
909 best[b].max_activation = 0.0;
910 best[b].average = 0.0;
911 best[b].probability = 0.0;
912 best[b].cprobability = syn_nbs[0]->best[b].cprobability;
913 memset(best[b].heat, 0, sizeof(float)*16);
914 }
915
916 float best_window_sum[MAX_NEIGHBOURS];
917 int found_index=0, i=0, j, w;
918 for(a=0; a < syn_threads; a++) {
919 for(b=0; b < syn_nbs[a]->length; b++) {
920 for(i=0; i < found_index; i++)
921 if(best[i].wordi == syn_nbs[a]->best[b].wordi)
922 break;
923 if(i >= found_index) {
924 best[found_index].max_activation = 0.0;
925 best[found_index].average = 0.0;
926 best[found_index].probability = 0.0;
927 memset(best[found_index].heat, 0, sizeof(float)*16);
928 best[found_index].cprobability = syn_nbs[a]->best[b].cprobability;
929 best[found_index].activation_sum = target_sums[syn_nbs[a]->best[b].wordi]; // syn_nbs[a]->best[b].activation_sum;
930 best[found_index++].wordi = syn_nbs[a]->best[b].wordi;
931 // printf("found: %s\n", &vocab[syn_nbs[a]->index[b] * max_w]);
932 }
933 }
934 }
935 sort_by =0; // ALWAYS AUTO-FOCUS
936 if(sort_by != 1 && sort_by != 2) { // sort by auto focus mean
937 printf("window: %d - syn_threads: %d, %d\n", window, syn_threads, (1 << syn_threads) -1);
938 int wpos;
939 int bits_set = 0;
940 for(i=0; i < found_index; i++) {
941 best[i].activation = best[i].probability = best[i].average = best[i].cprobability_sum = 0;
942 for(w=1; w < (1 << syn_threads); w++) { // loop through all possible windows
943 float word_window_sum = 0, word_window_average=0, word_cprobability_sum=0, word_activation_sum = 0, total_window_sum = 0;
944 bits_set = 0;
945 for(a=0; a < syn_threads; a++) {
946 if((1 << a) & w) {
947 wpos = (a >= window? a+1 : a);
948 total_window_sum += window_sums[wpos];
949 }
950 }
951// printf("%d window-sum %f\n", w, total_window_sum);
952 for(a=0; a < syn_threads; a++) {
953 if((1 << a) & w) {
954 wpos = (a >= window? a+1 : a);
955 bits_set++;
956 for(b=0; b < syn_nbs[a]->length; b++)
957 if(best[i].wordi == syn_nbs[a]->best[b].wordi) {
958// float acti = syn_nbs[a]->best[b].activation / total_window_sum;
959// word_window_sum += syn_nbs[a]->dist[b] * syn_nbs[a]->norm[b]; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
960// word_window_sum += syn_nbs[a]->norm[b]; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
961// word_window_sum = (word_window_sum + syn_nbs[a]->norm[b]) - (word_window_sum * syn_nbs[a]->norm[b]); // syn_nbs[a]->norm[b];
962
963 word_window_sum += syn_nbs[a]->best[b].activation; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
964// word_window_sum += acti - (word_window_sum * acti); syn_nbs[a]->best[b].activation; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
965
966 word_window_average += syn_nbs[a]->best[b].activation; // - word_window_average * syn_nbs[a]->best[b].activation; // conormalied activation sum
967 word_cprobability_sum += syn_nbs[a]->best[b].cprobability - word_cprobability_sum * syn_nbs[a]->best[b].cprobability; // conormalied column probability sum
968 word_activation_sum += syn_nbs[a]->best[b].activation;
969 if(syn_nbs[a]->best[b].activation > best[i].max_activation)
970 best[i].max_activation = syn_nbs[a]->best[b].activation;
971 if(syn_nbs[a]->best[b].activation > best[i].heat[wpos] )
972 best[i].heat[wpos] = syn_nbs[a]->best[b].activation;
973 }
974 }
975 }
976 if(bits_set) {
977 word_window_average /= bits_set;
978// word_activation_sum /= bits_set;
979// word_window_sum /= bits_set;
980 }
981
982 word_window_sum /= total_window_sum;
983
984 if(word_window_sum > best[i].probability) {
985// best[i].position = w;
986 best[i].probability = word_window_sum;
987 }
988
989 if(word_cprobability_sum > best[i].cprobability_sum) {
990 best[i].position = w;
991 best[i].cprobability_sum = word_cprobability_sum;
992 }
993
994 best[i].average = word_window_average;
995// best[i].activation = word_activation_sum;
996 }
997 }
998 qsort(best, found_index, sizeof(collocator), cmp_probability);
999// for(i=0; i < found_index; i++) {
1000// printf("found: %s - sum: %f - window: %d\n", &vocab[best[i].wordi * max_w], best[i].activation, best[i].position);
1001// }
1002
1003 } else if(sort_by == 1) { // responsiveness any window position
1004 int wpos;
1005 for(i=0; i < found_index; i++) {
1006 float word_window_sum = 0, word_activation_sum = 0, total_window_sum = 0;
1007 for(a=0; a < syn_threads; a++) {
1008 wpos = (a >= window? a+1 : a);
1009 for(b=0; b < syn_nbs[a]->length; b++)
1010 if(best[i].wordi == syn_nbs[a]->best[b].wordi) {
1011 best[i].probability += syn_nbs[a]->best[b].probability;
1012 if(syn_nbs[a]->best[b].activation > 0.25)
1013 best[i].position |= 1 << wpos;
1014 if(syn_nbs[a]->best[b].activation > best[i].activation) {
1015 best[i].activation = syn_nbs[a]->best[b].activation;
1016 }
1017 }
1018 }
1019 }
1020 qsort(best, found_index, sizeof(collocator), cmp_activation);
1021 } else if(sort_by == 2) { // single window position
1022 for(a=1; a < syn_threads; a++) {
1023 for(b=0; b < syn_nbs[a]->length; b++) {
1024 for(c=0; c < MAX_NEIGHBOURS; c++) {
1025 if(syn_nbs[a]->best[b].activation > best[c].activation) {
1026 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
1027 memmove(best + d, best + d - 1, sizeof(collocator));
1028 }
1029 memcpy(best + c, &syn_nbs[a]->best[b], sizeof(collocator));
1030 best[c].position = 1 << (-syn_nbs[a]->best[b].position+window - (syn_nbs[a]->best[b].position < 0 ? 1:0));
1031 break;
1032 }
1033 }
1034 }
1035 }
1036 } else { // sort by mean p
1037 for(a=1; a < syn_threads; a++) {
1038 for(b=0; b < syn_nbs[a]->length; b++) {
1039 for(c=0; c < MAX_NEIGHBOURS; c++) {
1040 if(target_sums[syn_nbs[a]->best[b].wordi] > best[c].activation_sum) {
1041 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
1042 memmove(best + d, best + d - 1, sizeof(collocator));
1043 }
1044 memcpy(best + c, &syn_nbs[a]->best[b], sizeof(collocator));
1045 best[c].position = (1 << 2*window) - 1; // syn_nbs[a]->pos[b];
1046 best[c].activation_sum = target_sums[syn_nbs[a]->best[b].wordi];
1047 break;
1048 }
1049 }
1050 }
1051 }
1052 }
1053 array = newAV();
1054 for (a = 0, i=0; a < MAX_NEIGHBOURS && best[a].wordi >= 0; a++) {
1055 long long c = best[a].wordi;
1056/*
1057 if (dedupe) {
1058 int filtered=0;
1059 for (j=0; j<i; j++)
1060 if (strcasestr(&vocab[c * max_w], chosen[j]) ||
1061 strcasestr(chosen[j], &vocab[c * max_w])) {
1062 printf("filtering %s %s\n", chosen[j], &vocab[c * max_w]);
1063 filtered = 1;
1064 }
1065 if(filtered)
1066 continue;
1067 }
1068*/
1069 chosen[i++]=c;
1070 HV* hash = newHV();
1071 SV* word = newSVpvf(&vocab[best[a].wordi * max_w], 0);
1072 AV* heat = newAV();
1073 if(latin_enc == 0) SvUTF8_on(word);
1074 hv_store(hash, "word", strlen("word"), word , 0);
1075 hv_store(hash, "rank", strlen("rank"), newSVuv(best[a].wordi), 0);
1076 hv_store(hash, "average", strlen("average"), newSVnv(best[a].average), 0);
1077 hv_store(hash, "prob", strlen("prob"), newSVnv(best[a].probability), 0);
1078 hv_store(hash, "cprob", strlen("cprob"), newSVnv(best[a].cprobability_sum), 0);
1079 hv_store(hash, "max", strlen("max"), newSVnv(best[a].max_activation), 0); // newSVnv(target_sums[best[a].wordi]), 0);
1080 hv_store(hash, "overall", strlen("overall"), newSVnv(best[a].activation_sum/total_activation), 0); // newSVnv(target_sums[best[a].wordi]), 0);
1081 hv_store(hash, "pos", strlen("pos"), newSVnv(best[a].position), 0);
1082 best[a].heat[5]=0;
1083 for(i=10; i >= 0; i--) av_push(heat, newSVnv(best[a].heat[i]));
1084 hv_store(hash, "heat", strlen("heat"), newRV_noinc((SV*)heat), 0);
1085 av_push(array, newRV_noinc((SV*)hash));
1086 }
1087 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
1088 }
1089end:
1090 // words = old_words; // why was this here?
1091 free(best);
1092 return newRV_noinc((SV*)result);
1093}
1094
1095int dump_vecs(char *fname) {
1096 long i, j;
1097 FILE *f;
1098/* if(words>100000)
1099 words=100000;
1100*/
1101 if((f=fopen(fname, "w")) == NULL) {
1102 fprintf(stderr, "cannot open %s for writing\n", fname);
1103 return(-1);
1104 }
1105 fprintf(f, "%lld %lld\n", words, size);
1106 for (i=0; i < words; i++) {
1107 fprintf(f, "%s ", &vocab[i * max_w]);
1108 for(j=0; j < size - 1; j++)
1109 fprintf(f, "%f ", M[i*size + j]);
1110 fprintf(f, "%f\n", M[i*size + j]);
1111 }
1112 fclose(f);
1113 return(0);
1114}
1115
1116int dump_for_numpy(char *fname) {
1117 long i, j;
1118 FILE *f;
1119 int max = 300000;
1120
1121 if((f=fopen(fname, "w")) == NULL) {
1122 fprintf(stderr, "cannot open %s for writing\n", fname);
1123 return(-1);
1124 }
1125 for (i=0; i < max; i++) {
1126 for(j=0; j < size - 1; j++)
1127 fprintf(f, "%f\t", M[i*size + j]);
1128 fprintf(f, "%f\n", M[i*size + j]);
1129 printf("%s\r\n", &vocab[i * max_w]);
1130 }
1131 if(merged_end > 0) {
1132 for (i=0; i < max; i++) {
1133 for(j=0; j < size - 1; j++)
1134 fprintf(f, "%f\t", M[(merged_end + i)*size + j]);
1135 fprintf(f, "%f\n", M[(merged_end + i)*size + j]);
1136 printf("_%s\r\n", &vocab[i * max_w]);
1137 }
1138 }
1139 fclose(f);
1140 return(0);
1141}