blob: c35095fe083c157e7790879287eb0bca6e437771 [file] [log] [blame]
Marc Kupietzdc22b982015-10-09 09:19:34 +02001#!/usr/local/bin/perl
2use Inline C;
3use Mojolicious::Lite;
Marc Kupietzc4893362016-02-25 08:04:46 +01004use Mojo::JSON qw(decode_json encode_json to_json);
Marc Kupietz247500f2015-10-09 11:29:01 +02005use Encode qw(decode encode);
Marc Kupietza5b90152016-03-15 17:39:19 +01006use Getopt::Std;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +01007use Mojo::Server::Daemon;
Marc Kupietzd4227392016-03-01 16:45:12 +01008plugin 'Log::Access';
Marc Kupietzdc22b982015-10-09 09:19:34 +02009
Marc Kupietza5b90152016-03-15 17:39:19 +010010our $opt_i = 0; # latin1-input?
11our $opt_l = undef;
12our $opt_p = 5676;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010013our $opt_n = undef;
Marc Kupietza5b90152016-03-15 17:39:19 +010014
Marc Kupietz6b2975c2016-03-18 21:59:33 +010015getopt('il:p:n:');
Marc Kupietza5b90152016-03-15 17:39:19 +010016
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010017# -cbow 1 -size 200 -window 8 -negative 25 -hs 0 -sample 1e-4 -threads 40 -binary 1 -iter 15
Marc Kupietza5b90152016-03-15 17:39:19 +010018if(!$ARGV[0]) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010019 init_net("vectors15.bin", $opt_n, ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010020} else {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010021 init_net($ARGV[0], $opt_n, ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010022}
Marc Kupietzdc22b982015-10-09 09:19:34 +020023
Marc Kupietza5b90152016-03-15 17:39:19 +010024my $daemon = Mojo::Server::Daemon->new(
25 app => app,
26 listen => ['http://'.($opt_l ? $opt_l : '*').":$opt_p"]
27);
28
Marc Kupietzdc22b982015-10-09 09:19:34 +020029get '/' => sub {
30 my $c = shift;
31 my $word=$c->param('word');
Marc Kupietz44bee3c2016-02-25 16:26:29 +010032 my $no_nbs=$c->param('n') || 100;
33 my $no_iterations=$c->param('N') || 2000;
Marc Kupietzd4227392016-03-01 16:45:12 +010034 my $perplexity=$c->param('perplexity') || 20;
Marc Kupietzc4d62f82016-03-01 11:04:24 +010035 my $epsilon=$c->param('epsilon') || 5;
Marc Kupietzd7aea722016-03-02 11:59:12 +010036 my $som=$c->param('som') || 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010037 my $res;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010038 my @lists;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010039 my @collocations;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010040 if(defined($word) && $word !~ /^\s*$/) {
41 $c->inactivity_timeout(300);
Marc Kupietz44bee3c2016-02-25 16:26:29 +010042 $word =~ s/\s+/ /g;
43 for my $w (split(' *\| *', $word)) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010044 $c->app->log->debug('Looking for neighbours of '.$w);
Marc Kupietza5b90152016-03-15 17:39:19 +010045 if($opt_i) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010046 $res = get_neighbours(encode("iso-8859-1", $w), $no_nbs);
Marc Kupietza5b90152016-03-15 17:39:19 +010047 } else {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010048 $res = get_neighbours($w, $no_nbs);
Marc Kupietza5b90152016-03-15 17:39:19 +010049 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +010050 push(@lists, $res->{paradigmatic});
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010051 }
Marc Kupietz247500f2015-10-09 11:29:01 +020052 }
Marc Kupietz000ad862016-02-26 14:59:12 +010053 $word =~ s/ *\| */ | /g;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010054 $c->render(template=>"index", word=>$word, no_nbs=>$no_nbs, no_iterations => $no_iterations, epsilon=> $epsilon, perplexity=> $perplexity, show_som=>$som, lists=> \@lists, collocators=> $res->{syntagmatic});
Marc Kupietzdc22b982015-10-09 09:19:34 +020055};
56
Marc Kupietza5b90152016-03-15 17:39:19 +010057$daemon->run; # app->start;
Marc Kupietzdc22b982015-10-09 09:19:34 +020058
59exit;
60
61__END__
62
63__C__
64#include <stdio.h>
65#include <string.h>
66#include <math.h>
67#include <malloc.h>
68#include <stdlib.h> //strlen
Marc Kupietzf0809762016-02-26 10:13:47 +010069#include <sys/mman.h>
Marc Kupietz000ad862016-02-26 14:59:12 +010070#include <pthread.h>
Marc Kupietzdc22b982015-10-09 09:19:34 +020071
72#define max_size 2000
73#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010074#define MAX_NEIGHBOURS 1000
Marc Kupietz44bee3c2016-02-25 16:26:29 +010075#define MAX_WORDS -1
Marc Kupietz000ad862016-02-26 14:59:12 +010076#define MAX_THREADS 100
Marc Kupietz6b2975c2016-03-18 21:59:33 +010077#define MAX_CC 50
78#define EXP_TABLE_SIZE 1000
79#define MAX_EXP 6
Marc Kupietzdc22b982015-10-09 09:19:34 +020080
81//the thread function
82void *connection_handler(void *);
Marc Kupietz000ad862016-02-26 14:59:12 +010083
84typedef struct {
85 long long *index;
86 float *dist;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010087 long long *pos;
Marc Kupietz000ad862016-02-26 14:59:12 +010088 unsigned int length;
89} knn;
90
91
92typedef struct {
Marc Kupietz48c29682016-03-19 11:30:43 +010093 long long wordi[MAX_NEIGHBOURS];
94 char sep[MAX_NEIGHBOURS];
95 int length;
96} wordlist;
97
98typedef struct {
99 wordlist *wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100100 char *token;
101 int N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100102 long from;
Marc Kupietz000ad862016-02-26 14:59:12 +0100103 unsigned long upto;
104} knnpars;
105
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100106float *M, *syn1neg_window, *expTable;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200107char *vocab;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100108
Marc Kupietz82b02672016-02-26 12:32:25 +0100109long long words, size;
Marc Kupietz000ad862016-02-26 14:59:12 +0100110int num_threads=20;
Marc Kupietza5b90152016-03-15 17:39:19 +0100111int latin_enc=0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100112int window;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200113
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100114int init_net(char *file_name, char *net_name, int latin) {
Marc Kupietz67c20282016-02-26 09:42:00 +0100115 FILE *f, *binvecs, *binwords;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100116 int binwords_fd, binvecs_fd, net_fd, i;
Marc Kupietz82b02672016-02-26 12:32:25 +0100117 long long a, b, c, d, cn;
118 float len;
119
Marc Kupietz67c20282016-02-26 09:42:00 +0100120 char binvecs_fname[256], binwords_fname[256];
121 strcpy(binwords_fname, file_name);
122 strcat(binwords_fname, ".words");
123 strcpy(binvecs_fname, file_name);
124 strcat(binvecs_fname, ".vecs");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200125
Marc Kupietza5b90152016-03-15 17:39:19 +0100126 latin_enc = latin;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200127 f = fopen(file_name, "rb");
128 if (f == NULL) {
129 printf("Input file %s not found\n", file_name);
130 return -1;
131 }
132 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100133 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200134 fscanf(f, "%lld", &size);
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100135 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
136 printf("Converting %s to memory mappable structures\n", file_name);
Marc Kupietzf0809762016-02-26 10:13:47 +0100137 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
138 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
139 if (M == NULL) {
140 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
141 return -1;
142 }
Marc Kupietz67c20282016-02-26 09:42:00 +0100143 for (b = 0; b < words; b++) {
144 a = 0;
145 while (1) {
146 vocab[b * max_w + a] = fgetc(f);
147 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
148 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
149 }
150 vocab[b * max_w + a] = 0;
151 fread(&M[b * size], sizeof(float), size, f);
152 len = 0;
153 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
154 len = sqrt(len);
155 for (a = 0; a < size; a++) M[a + b * size] /= len;
156 }
157 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
158 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
159 fclose(binvecs);
160 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
161 fclose(binwords);
162 }
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100163 }
164 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
165 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
166 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
167 if (M == MAP_FAILED || vocab == MAP_FAILED) {
168 close(binvecs_fd);
169 close(binwords_fd);
170 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
171 exit(-1);
172 }
173 } else {
174 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
175 exit(-1);
Marc Kupietz67c20282016-02-26 09:42:00 +0100176 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200177 fclose(f);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100178
179 if(net_name) {
180 if( (net_fd = open(net_name, O_RDONLY)) >= 0) {
181 window = (lseek(net_fd, 0, SEEK_END) - sizeof(float) * words * size) / words / size / sizeof(float) / 2;
182 // lseek(net_fd, sizeof(float) * words * size, SEEK_SET);
183 munmap(M, sizeof(float) * words * size);
184 M = mmap(0, sizeof(float) * words * size + sizeof(float) * 2 * window * size * words, PROT_READ, MAP_SHARED, net_fd, 0);
185 if (M == MAP_FAILED) {
186 close(net_fd);
187 fprintf(stderr, "Cannot mmap %s\n", net_name);
188 exit(-1);
189 }
190 syn1neg_window = M + words * size;
191 } else {
192 fprintf(stderr, "Cannot open %s\n", net_name);
193 exit(-1);
194 }
195 fprintf(stderr, "Successfully memmaped %s. Determined window size: %d\n", net_name, window);
196 }
197
198 expTable = (float *) malloc((EXP_TABLE_SIZE + 1) * sizeof(float));
199 for (i = 0; i < EXP_TABLE_SIZE; i++) {
200 expTable[i] = exp((i / (float) EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
201 expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
202 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200203 return 0;
204}
205
Marc Kupietzd5642582016-03-19 22:23:13 +0100206knn *getCollocators(int cc, int N) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100207 knn *nbs = NULL;
208 long window_layer_size = size * window * 2;
209 long a, b, c, d, e, window_offset, target, max_target=0, maxmax_target;
210 float f, max_f, maxmax_f;
211 float *target_sums, *bestf, worstbest;
212 long long *besti, *bestp;
Marc Kupietzd5642582016-03-19 22:23:13 +0100213
214 if(cc == -1)
215 return NULL;
216
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100217 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
218 besti = malloc(N * sizeof(long long));
219 bestp = malloc(N * sizeof(long long));
220 bestf = malloc(N * sizeof(float));
221 for (b = 0; b < words; b++)
222 target_sums[b]=0;
223 for (b = 0; b < N; b++)
224 bestf[b]=-1;
225 worstbest = -1;
226 d = cc;
227 maxmax_f = -1;
228 maxmax_target = 0;
229
Marc Kupietzd5642582016-03-19 22:23:13 +0100230 besti[0]=d;
231 bestf[0]=1.0;
232 bestp[0]=0;
233
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100234 for (a = window * 2 + 1; a >=0; a--) {
235 printf("window pos: %ld\n", a);
236 if (a != window) {
237 max_f = -1;
238 window_offset = a * size;
239 if (a > window)
240 window_offset -= size;
Marc Kupietz48c29682016-03-19 11:30:43 +0100241 for(target = 0; target < words / 2; target ++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100242 if(target == d)
243 continue;
244 f = 0;
245 for (c = 0; c < size; c++)
246 f += M[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
247 if (f < -MAX_EXP)
248 continue;
249 else if (f > MAX_EXP)
250 continue;
251 else
252 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
253 if(f > max_f) {
254 max_f = f;
255 max_target = target;
256 }
257 target_sums[target] += (1-target_sums[target]) * f;
258 if(f > worstbest) {
259 for (b = 0; b < N; b++) {
260 if (f > bestf[b]) {
261 for (e = N - 1; e > b; e--) {
262 bestf[e] = bestf[e - 1];
263 besti[e] = besti[e - 1];
264 bestp[e] = bestp[e - 1];
265 }
266 bestf[b] = f;
267 besti[b] = target;
268 bestp[b] = window-a;
269 break;
270 }
271 }
272 worstbest = bestf[N-1];
273 }
274 }
275 printf("%d %.2f\n", max_target, max_f);
276 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
277 if(max_f > maxmax_f) {
278 maxmax_f = max_f;
279 maxmax_target = max_target;
280 }
281 } else {
282 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
283 }
284 }
285 max_f = -1;
286 for (b = 0; b < words; b++) {
287 if(target_sums[b] > max_f) {
288 max_f = target_sums[b];
289 max_target = b;
290 }
291 }
292 printf(" -- max sum: %s (%.2f), max resp.: \x1b[1m%s\x1b[0m (%.2f)\n",
293 &vocab[max_target * max_w], max_f,
294 &vocab[maxmax_target * max_w], maxmax_f);
Marc Kupietzd5642582016-03-19 22:23:13 +0100295 for(b=0; b<N; b++)
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100296 printf("%-32s %.2f %d\n", &vocab[besti[b]*max_w], bestf[b], bestp[b]);
297 printf("\n");
298 free(target_sums);
299 nbs = malloc(sizeof(knn));
300 nbs->index = besti;
301 nbs->dist = bestf;
302 nbs->pos = bestp;
Marc Kupietzd5642582016-03-19 22:23:13 +0100303 nbs->length = N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100304 return(nbs);
305}
306
Marc Kupietz48c29682016-03-19 11:30:43 +0100307wordlist *getTargetWords(char *st1) {
308 wordlist *wl = malloc(sizeof(wordlist));
309 char st[100][max_size], sep[100];
310 long a, b=0, c=0, cn=0;
311
Marc Kupietzdc22b982015-10-09 09:19:34 +0200312 while (1) {
313 st[cn][b] = st1[c];
314 b++;
315 c++;
316 st[cn][b] = 0;
317 if (st1[c] == 0) break;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100318 if (st1[c] == ' ' || st1[c] == '-') {
319 sep[cn++] = st1[c];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200320 b = 0;
321 c++;
322 }
323 }
324 cn++;
325 for (a = 0; a < cn; a++) {
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100326 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
327 if (b == words) b = -1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100328 wl->wordi[a] = b;
329 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], wl->wordi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200330 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100331 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100332 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200333 break;
334 }
335 }
Marc Kupietz48c29682016-03-19 11:30:43 +0100336 wl->length=cn;
337 return(wl);
338}
339
340void *_get_neighbours(knnpars *pars) {
341 char *st1 = pars->token;
342 int N = pars->N;
343 long from = pars -> from;
344 unsigned long upto = pars -> upto;
345 char file_name[max_size], st[100][max_size], *sep;
346 float dist, len, *bestd, vec[max_size];
347 long long a, b, c, d, cn, *bi, *besti;
348 char ch;
349 knn *nbs = NULL;
350 wordlist *wl = pars->wl;
351
352 besti = malloc(N * sizeof(long long));
353 bestd = malloc(N * sizeof(float));
354
355 float worstbest=-1;
356
357 for (a = 0; a < N; a++) bestd[a] = 0;
358 a = 0;
359 bi = wl->wordi;
360 cn = wl->length;
361 sep = wl->sep;
362 b = bi[0];
363 c = 0;
364
365 if(from < 0) {
Marc Kupietzd5642582016-03-19 22:23:13 +0100366 nbs = getCollocators(b, pars->N);
Marc Kupietz48c29682016-03-19 11:30:43 +0100367 pthread_exit(nbs);
368 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100369 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100370 N = 0;
371 goto end;
372 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200373 for (a = 0; a < size; a++) vec[a] = 0;
374 for (b = 0; b < cn; b++) {
375 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100376 if(b>0 && sep[b-1] == '-')
377 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
378 else
379 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200380 }
381 len = 0;
382 for (a = 0; a < size; a++) len += vec[a] * vec[a];
383 len = sqrt(len);
384 for (a = 0; a < size; a++) vec[a] /= len;
385 for (a = 0; a < N; a++) bestd[a] = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100386 for (c = from; c < upto; c++) {
Marc Kupietzdc22b982015-10-09 09:19:34 +0200387 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100388// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100389// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
390// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200391 dist = 0;
392 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100393 if(dist > worstbest) {
394 for (a = 0; a < N; a++) {
395 if (dist > bestd[a]) {
396 for (d = N - 1; d > a; d--) {
397 bestd[d] = bestd[d - 1];
398 besti[d] = besti[d - 1];
399 }
400 bestd[a] = dist;
401 besti[a] = c;
402 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200403 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200404 }
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100405 worstbest = bestd[N-1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200406 }
407 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100408
Marc Kupietz000ad862016-02-26 14:59:12 +0100409 nbs = malloc(sizeof(knn));
410 nbs->index = besti;
411 nbs->dist = bestd;
412 nbs->length = N;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100413end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100414 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200415}
416
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100417
Marc Kupietz000ad862016-02-26 14:59:12 +0100418SV *get_neighbours(char *st1, int N) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100419 HV *result = newHV();
Marc Kupietz000ad862016-02-26 14:59:12 +0100420 float bestd[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100421 long long besti[MAX_NEIGHBOURS], bestp[MAX_NEIGHBOURS], a, b, c, d, slice;
Marc Kupietz000ad862016-02-26 14:59:12 +0100422 char *bestw[MAX_NEIGHBOURS];
423 knn *nbs[MAX_THREADS];
424 knnpars pars[MAX_THREADS];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100425 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
Marc Kupietz48c29682016-03-19 11:30:43 +0100426 wordlist *wl;
427
Marc Kupietz000ad862016-02-26 14:59:12 +0100428 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
429
430 slice = words / num_threads;
431
Marc Kupietz48c29682016-03-19 11:30:43 +0100432 wl = getTargetWords(st1);
433
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100434 a = num_threads;
435 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100436 pars[a].wl = wl;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100437 pars[a].N = N;
438 pars[a].from = -1;
439 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
440
Marc Kupietz000ad862016-02-26 14:59:12 +0100441 for(a=0; a < num_threads; a++) {
442 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100443 pars[a].wl = wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100444 pars[a].N = N;
445 pars[a].from = a*slice;
446 pars[a].upto = ((a+1)*slice > words? words:(a+1)*slice);
447 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
448 }
449 for (a = 0; a < num_threads; a++) pthread_join(pt[a], &nbs[a]);
450
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100451 pthread_join(pt[a], &nbs[a]);
452
Marc Kupietz000ad862016-02-26 14:59:12 +0100453 if(!nbs[0])
454 goto end;
455
456 for(b=0; b < N; b++) {
457 besti[b] = nbs[0]->index[b];
458 bestd[b] = nbs[0]->dist[b];
459 }
460
461 for(a=1; a < num_threads; a++) {
462 for(b=0; b < N; b++) {
463 for(c=0; c < N; c++) {
464 if(nbs[a]->dist[b] > bestd[c]) {
465 for(d=N-1; d>c; d--) {
466 bestd[d] = bestd[d-1];
467 besti[d] = besti[d-1];
468 }
469 besti[c] = nbs[a]->index[b];
470 bestd[c] = nbs[a]->dist[b];
471 break;
472 }
473 }
474 }
475 }
476
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100477
Marc Kupietz000ad862016-02-26 14:59:12 +0100478 if(nbs) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100479 AV* array = newAV();
Marc Kupietz000ad862016-02-26 14:59:12 +0100480 for (a = 0; a < N; a++) {
481 bestw[a] = (char *)malloc(max_size * sizeof(char));
482 }
483 for (a = 0; a < N; a++) {
484 strcpy(bestw[a], &vocab[besti[a] * max_w]);
485 HV* hash = newHV();
Marc Kupietza5b90152016-03-15 17:39:19 +0100486 SV* word = newSVpvf(bestw[a], 0);
487 if(latin_enc == 0) SvUTF8_on(word);
488 hv_store(hash, "word", strlen("word"), word , 0);
Marc Kupietz000ad862016-02-26 14:59:12 +0100489 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
490 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
491 AV *vector = newAV();
492 for (b = 0; b < size; b++) {
493 av_push(vector, newSVnv(M[b + besti[a] * size]));
494 }
495 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
496 av_push(array, newRV_noinc((SV*)hash));
497 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100498 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
499
Marc Kupietzd5642582016-03-19 22:23:13 +0100500 for(b=0; b < nbs[num_threads]->length; b++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100501 besti[b] = nbs[num_threads]->index[b];
502 bestd[b] = nbs[num_threads]->dist[b];
503 bestp[b] = nbs[num_threads]->pos[b];
504 }
505 array = newAV();
Marc Kupietzda9db6f2016-03-19 20:36:20 +0100506 for (a = 0; a < nbs[num_threads]->length; a++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100507 strcpy(bestw[a], &vocab[besti[a] * max_w]);
508 HV* hash = newHV();
509 SV* word = newSVpvf(bestw[a], 0);
510 if(latin_enc == 0) SvUTF8_on(word);
511 hv_store(hash, "word", strlen("word"), word , 0);
512 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
513 hv_store(hash, "pos", strlen("pos"), newSVnv(bestp[a]), 0);
514 av_push(array, newRV_noinc((SV*)hash));
515 }
516 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz000ad862016-02-26 14:59:12 +0100517 }
518end:
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100519 return newRV_noinc((SV*)result);
Marc Kupietz000ad862016-02-26 14:59:12 +0100520}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100521
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100522
Marc Kupietzdc22b982015-10-09 09:19:34 +0200523__DATA__
524
525@@ index.html.ep
526<!DOCTYPE html>
527<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100528<head>
529 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100530 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100531 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100532 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
533 <script>
534 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100535 $( document ).tooltip({
536 content: function() {
537 return $(this).attr('title');
538 }}
539 )
540 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100541 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100542 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
543 <script src="http://klinux10/word2vec/tsne.js"></script>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100544 <script src="http://klinux10/word2vec/som.js"></script>
Marc Kupietzc5990da2016-02-26 08:47:12 +0100545 <script src="http://klinux10/word2vec/labeler.js"></script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100546<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100547body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100548 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100549 font-size: 11pt;
550}
551
552.ui-tooltip-content {
553 font-size: 9pt;
554 colour: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100555}
Marc Kupietz5f780672016-02-25 17:15:54 +0100556
557svg > .ui-tooltip-content {
Marc Kupietzb1029362016-02-27 21:38:55 +0100558 font-size: 8pt;
Marc Kupietz5f780672016-02-25 17:15:54 +0100559 colour: #222222;
560}
561
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100562#collocators {
563 margin-bottom: 15px;
564}
565
Marc Kupietzc4893362016-02-25 08:04:46 +0100566#wrapper {
567 width: 100%;
568// border: 1px solid red;
569 overflow: hidden; /* will contain if #first is longer than #second */
570}
571#first {
Marc Kupietzb1029362016-02-27 21:38:55 +0100572 margin-right: 20px;
573 float: left;
574 // border: 1px solid green;
Marc Kupietzc4893362016-02-25 08:04:46 +0100575}
576#second {
577 border: 1px solid #333;
578 overflow: hidden; /* if you don't want #second to wrap below #first */
579}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100580#som2 svg {
581 border: 1px solid #333;
582}
583
Marc Kupietz4aa62172016-02-25 10:39:27 +0100584#cost {
Marc Kupietzb1029362016-02-27 21:38:55 +0100585 font-size: 8pt;
586 color: #222222;
587 margin-top: 4px;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100588 margin-bottom: 12px;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100589}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100590
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100591#sominfo1, #sominfo {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100592 font-size: 8pt;
593 color: #222222;
594 margin-top: 0px;
595}
596
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100597#somcolor1, #somcolor2, #somcolor3 {
598 display: inline-block;
599 height: 10px;
600 width: 10px;
601}
602
Marc Kupietzd7aea722016-03-02 11:59:12 +0100603#third {
604 border: 1px solid #333;
605}
606
Marc Kupietzc4893362016-02-25 08:04:46 +0100607</style>
608<script>
609
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100610var opt = {epsilon: <%= $epsilon %>, perplexity: <%= $perplexity %>},
Marc Kupietz9fca1732016-02-29 09:07:04 +0100611 mapWidth = 800, // width map
612 mapHeight = 800,
613 jitterRadius = 7;
614
Marc Kupietzc4893362016-02-25 08:04:46 +0100615var T = new tsnejs.tSNE(opt); // create a tSNE instance
616
617var Y;
618
619var data;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100620var labeler;
Marc Kupietzc4893362016-02-25 08:04:46 +0100621
Marc Kupietzc5990da2016-02-26 08:47:12 +0100622
623function applyJitter() {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100624 svg.selectAll('.tsnet')
Marc Kupietzc5990da2016-02-26 08:47:12 +0100625 .data(labels)
626 .transition()
627 .duration(50)
628 .attr("transform", function(d, i) {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100629 T.Y[i][0] = (d.x - mapWidth/2 - tx)/ss/20;
630 T.Y[i][1] = (d.y - mapHeight/2 - ty)/ss/20;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100631 return "translate(" +
632 (d.x) + "," +
633 (d.y) + ")";
634 });
635}
636
Marc Kupietzc4893362016-02-25 08:04:46 +0100637function updateEmbedding() {
638 var Y = T.getSolution();
Marc Kupietzd7aea722016-03-02 11:59:12 +0100639 svg.selectAll('.tsnet')
Marc Kupietz9fca1732016-02-29 09:07:04 +0100640 .data(data.words)
641 .attr("transform", function(d, i) {
642 return "translate(" +
643 ((Y[i][0]*20*ss + tx) + mapWidth/2) + "," +
644 ((Y[i][1]*20*ss + ty) + mapHeight/2) + ")"; });
Marc Kupietzc4893362016-02-25 08:04:46 +0100645}
646
647var svg;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100648var labels = [];
649var anchor_array = [];
650var text;
651
Marc Kupietzc4893362016-02-25 08:04:46 +0100652function drawEmbedding() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100653 $("#embed").empty();
654 var div = d3.select("#embed");
655
656 // get min and max in each column of Y
657 var Y = T.Y;
658
659 svg = div.append("svg") // svg is global
660 .attr("width", mapWidth)
661 .attr("height", mapHeight);
662
663 var g = svg.selectAll(".b")
664 .data(data.words)
665 .enter().append("g")
Marc Kupietzd7aea722016-03-02 11:59:12 +0100666 .attr("class", "tsnet");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100667
668 g.append("a")
669 .attr("xlink:href", function(word) {return "/?word="+word;})
670 .attr("title", function(d, i) {
Marc Kupietze50c8162016-03-01 10:24:43 +0100671 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100672 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100673 .append("text")
Marc Kupietz9fca1732016-02-29 09:07:04 +0100674 .attr("text-anchor", "top")
675 .attr("font-size", 12)
676 .attr("fill", function(d) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100677 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100678 return "red";
679 } else {
680 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100681 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100682 })
683 .text(function(d) { return d; });
684
685 var zoomListener = d3.behavior.zoom()
686 .scaleExtent([0.1, 10])
687 .center([0,0])
688 .on("zoom", zoomHandler);
689 zoomListener(svg);
690}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100691
Marc Kupietz9fca1732016-02-29 09:07:04 +0100692var tx=0, ty=0;
693var ss=1;
694var iter_id=-1;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100695
Marc Kupietz9fca1732016-02-29 09:07:04 +0100696function zoomHandler() {
697 tx = d3.event.translate[0];
698 ty = d3.event.translate[1];
699 ss = d3.event.scale;
700 updateEmbedding();
701}
702
703var stepnum = 0;
704
705function stopStep() {
706 clearInterval(iter_id);
707 text = svg.selectAll("text");
708
709 // jitter function needs different data and co-ordinate representation
710 labels = d3.range(data.words.length).map(function(i) {
711 var x = (T.Y[i][0]*20*ss + tx) + mapWidth/2;
712 var y = (T.Y[i][1]*20*ss + ty) + mapHeight/2;
713 anchor_array.push({x: x, y: y, r: jitterRadius});
714 return {
715 x: x,
716 y: y,
717 name: data.words[i]
718 };
719 });
720
721 // get the actual label bounding boxes for the jitter function
722 var index = 0;
723 text.each(function() {
724 labels[index].width = this.getBBox().width;
725 labels[index].height = this.getBBox().height;
726 index += 1;
727 });
Marc Kupietzc5990da2016-02-26 08:47:12 +0100728
729
730// setTimeout(updateEmbedding, 1);
731// setTimeout(
Marc Kupietz9fca1732016-02-29 09:07:04 +0100732 labeler = d3.labeler()
733 .label(labels)
734 .anchor(anchor_array)
735 .width(mapWidth)
736 .height(mapHeight)
737 .update(applyJitter);
738 // .start(1000);
Marc Kupietzc5990da2016-02-26 08:47:12 +0100739
Marc Kupietz9fca1732016-02-29 09:07:04 +0100740 iter_id = setInterval(jitterStep, 1);
741}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100742
Marc Kupietz9fca1732016-02-29 09:07:04 +0100743var jitter_i=0;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100744
745function jitterStep() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100746 if(jitter_i++ > 100) {
747 clearInterval(iter_id);
748 } else {
749 labeler.start2(10);
750 applyJitter();
751 }
Marc Kupietzc5990da2016-02-26 08:47:12 +0100752}
Marc Kupietzb1029362016-02-27 21:38:55 +0100753
754var last_cost=1000;
755
Marc Kupietz9fca1732016-02-29 09:07:04 +0100756function step() {
757 var i = T.iter;
758
759 if(i > <%= $no_iterations %>) {
760 stopStep();
761 } else {
762 var cost = Math.round(T.step() * 100000) / 100000; // do a few steps
763 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(5));
764 if(i % 250 == 0 && cost >= last_cost) {
765 stopStep();
766 } else {
767 last_cost = cost;
768 updateEmbedding();
769 }
770 }
771}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100772
Marc Kupietz9fca1732016-02-29 09:07:04 +0100773function showMap(j) {
774 data=j;
775 T.iter=0;
776 T.initDataRaw(data.vecs); // init embedding
777 drawEmbedding(); // draw initial embedding
778
779 if(iter_id >= 0) {
780 clearInterval(iter_id);
781 }
782 //T.debugGrad();
783 iter_id = setInterval(step, 1);
Marc Kupietzd7aea722016-03-02 11:59:12 +0100784 if(<%= $show_som %>) {
785 makeSOM(j, <%= $no_iterations %>);
786 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100787}
Marc Kupietza350bce2016-02-25 09:34:25 +0100788
Marc Kupietzc4893362016-02-25 08:04:46 +0100789</script>
790</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200791<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100792 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100793 word(s):
794 <input type="text" name="word" size="20" value="<%= $word %>" title="When looking for multiple words use spaces as separators to search around the average vector and | as separator to get the neighbours for each word.">
795 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
Marc Kupietzd7aea722016-03-02 11:59:12 +0100796 max. iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
797 SOM <input type="checkbox" name="som" value="1" <%= ($show_som ? "checked" : "") %>>
798 <span> </span><input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +0100799 </form>
800 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100801 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100802 <div id="wrapper">
803 <table id="first">
804 <tr>
Marc Kupietzd5642582016-03-19 22:23:13 +0100805 <th align="right">#</th><th align="right">cos</th><th align="left">paradigmatic</th><th title="Position in winodw around target word. Absolute value can be too low because of sub-sampling frequent words.">@</th><th align="right" title="&#34;Responsivenes&#34; of the collocator at the relative position @. Approximation of the probability that the combination of the target word and the collocator at the relative position @ come from the corpus.">resp.</th><th align="left">syntagmatic</th>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100806 </tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100807 % my $j=0; my @words; my @vecs; my @ranks; for my $list (@$lists) {
Marc Kupietzd5642582016-03-19 22:23:13 +0100808 % my $i=0; for my $item (@$list) {
809 % my $c = (@$collocators)[$i];
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100810 % if(!grep{$_ eq $item->{word}} @words) {
811 % push @vecs, $item->{vector};
812 % push @words, $item->{word};
Marc Kupietz5f780672016-02-25 17:15:54 +0100813 % push @ranks, $item->{rank};
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100814 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100815 <tr>
816 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +0100817 <%= ++$i %>.
Marc Kupietz4aa62172016-02-25 10:39:27 +0100818 </td>
819 <td align="right">
820 <%= sprintf("%.3f", $item->{dist}) %>
821 </td>
Marc Kupietzd5642582016-03-19 22:23:13 +0100822 <td>
823 <a title="freq. rank: <%= $item->{rank} %>" href="/?word=<%= $item->{word} %>">
824 <%= $item->{word} %>
825 </a>
826 </td>
Marc Kupietz5f780672016-02-25 17:15:54 +0100827 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +0100828 <%= $c->{pos} %>:
829 </td>
830 <td align="right">
831 <%= sprintf("%.3f", $c->{dist}) %>
832 </td>
833 <td align="left">
834 <a href="/?word=<%= $c->{word} %>">
835 <%= $c->{word} %>
Marc Kupietz5f780672016-02-25 17:15:54 +0100836 </td>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100837 </tr>
838 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100839 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100840 </table>
841 <script>
842 % use Mojo::ByteStream 'b';
843 $(window).load(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100844 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", words => \@words, vecs => \@vecs, ranks => \@ranks})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +0100845 });
846 </script>
847 % }
848 <div id="second" style="width:800px; height:800px; font-family: arial;">
849 <div id="embed">
850 </div>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100851 </div>
Marc Kupietzb1029362016-02-27 21:38:55 +0100852 <div id="cost"></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100853 % if($show_som) {
854 <div id="som2">
855 </div>
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100856 <div id="sominfo1"><span id="somcolor1"> </span> <span id="somword1"> </span> <span id="somcolor2"> </span> <span id="somword2"> </span> <span id="somcolor3"> </span></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100857 <div id="sominfo">SOM iteration <span id="iterations">0</span></div>
858 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100859 </div>
860 <p>
861 Word vector model based on DeReKo-2015-II. Trained with <a href="https://code.google.com/p/word2vec/">word2vec</a> using the following parameters:</p>
Marc Kupietz247500f2015-10-09 11:29:01 +0200862 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100863-cbow 1 -size 300 -window 7 -negative 5 -hs 0 -sample 1e-5 -threads 44 -binary 1 -iter 5
Marc Kupietz4aa62172016-02-25 10:39:27 +0100864 </pre>
865 </p>
866</body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200867</html>
868