blob: fa8e652ef2705cb200561fdd44279e695e538ae1 [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 Kupietz6b2975c2016-03-18 21:59:33 +0100206knn *getCollocators(int cc) {
207 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;
213 int N = 10;
214 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
215 besti = malloc(N * sizeof(long long));
216 bestp = malloc(N * sizeof(long long));
217 bestf = malloc(N * sizeof(float));
218 for (b = 0; b < words; b++)
219 target_sums[b]=0;
220 for (b = 0; b < N; b++)
221 bestf[b]=-1;
222 worstbest = -1;
223 d = cc;
224 maxmax_f = -1;
225 maxmax_target = 0;
226
Marc Kupietzda9db6f2016-03-19 20:36:20 +0100227 if(cc == -1)
228 return NULL;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100229 for (a = window * 2 + 1; a >=0; a--) {
230 printf("window pos: %ld\n", a);
231 if (a != window) {
232 max_f = -1;
233 window_offset = a * size;
234 if (a > window)
235 window_offset -= size;
Marc Kupietz48c29682016-03-19 11:30:43 +0100236 for(target = 0; target < words / 2; target ++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100237 if(target == d)
238 continue;
239 f = 0;
240 for (c = 0; c < size; c++)
241 f += M[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
242 if (f < -MAX_EXP)
243 continue;
244 else if (f > MAX_EXP)
245 continue;
246 else
247 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
248 if(f > max_f) {
249 max_f = f;
250 max_target = target;
251 }
252 target_sums[target] += (1-target_sums[target]) * f;
253 if(f > worstbest) {
254 for (b = 0; b < N; b++) {
255 if (f > bestf[b]) {
256 for (e = N - 1; e > b; e--) {
257 bestf[e] = bestf[e - 1];
258 besti[e] = besti[e - 1];
259 bestp[e] = bestp[e - 1];
260 }
261 bestf[b] = f;
262 besti[b] = target;
263 bestp[b] = window-a;
264 break;
265 }
266 }
267 worstbest = bestf[N-1];
268 }
269 }
270 printf("%d %.2f\n", max_target, max_f);
271 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
272 if(max_f > maxmax_f) {
273 maxmax_f = max_f;
274 maxmax_target = max_target;
275 }
276 } else {
277 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
278 }
279 }
280 max_f = -1;
281 for (b = 0; b < words; b++) {
282 if(target_sums[b] > max_f) {
283 max_f = target_sums[b];
284 max_target = b;
285 }
286 }
287 printf(" -- max sum: %s (%.2f), max resp.: \x1b[1m%s\x1b[0m (%.2f)\n",
288 &vocab[max_target * max_w], max_f,
289 &vocab[maxmax_target * max_w], maxmax_f);
Marc Kupietzda9db6f2016-03-19 20:36:20 +0100290 for(b=0; b<N && bestf[b]>0.2; b++)
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100291 printf("%-32s %.2f %d\n", &vocab[besti[b]*max_w], bestf[b], bestp[b]);
292 printf("\n");
293 free(target_sums);
294 nbs = malloc(sizeof(knn));
295 nbs->index = besti;
296 nbs->dist = bestf;
297 nbs->pos = bestp;
Marc Kupietzda9db6f2016-03-19 20:36:20 +0100298 nbs->length = b;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100299 return(nbs);
300}
301
Marc Kupietz48c29682016-03-19 11:30:43 +0100302wordlist *getTargetWords(char *st1) {
303 wordlist *wl = malloc(sizeof(wordlist));
304 char st[100][max_size], sep[100];
305 long a, b=0, c=0, cn=0;
306
Marc Kupietzdc22b982015-10-09 09:19:34 +0200307 while (1) {
308 st[cn][b] = st1[c];
309 b++;
310 c++;
311 st[cn][b] = 0;
312 if (st1[c] == 0) break;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100313 if (st1[c] == ' ' || st1[c] == '-') {
314 sep[cn++] = st1[c];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200315 b = 0;
316 c++;
317 }
318 }
319 cn++;
320 for (a = 0; a < cn; a++) {
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100321 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
322 if (b == words) b = -1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100323 wl->wordi[a] = b;
324 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], wl->wordi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200325 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100326 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100327 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200328 break;
329 }
330 }
Marc Kupietz48c29682016-03-19 11:30:43 +0100331 wl->length=cn;
332 return(wl);
333}
334
335void *_get_neighbours(knnpars *pars) {
336 char *st1 = pars->token;
337 int N = pars->N;
338 long from = pars -> from;
339 unsigned long upto = pars -> upto;
340 char file_name[max_size], st[100][max_size], *sep;
341 float dist, len, *bestd, vec[max_size];
342 long long a, b, c, d, cn, *bi, *besti;
343 char ch;
344 knn *nbs = NULL;
345 wordlist *wl = pars->wl;
346
347 besti = malloc(N * sizeof(long long));
348 bestd = malloc(N * sizeof(float));
349
350 float worstbest=-1;
351
352 for (a = 0; a < N; a++) bestd[a] = 0;
353 a = 0;
354 bi = wl->wordi;
355 cn = wl->length;
356 sep = wl->sep;
357 b = bi[0];
358 c = 0;
359
360 if(from < 0) {
361 nbs = getCollocators(b);
362 pthread_exit(nbs);
363 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100364 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100365 N = 0;
366 goto end;
367 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200368 for (a = 0; a < size; a++) vec[a] = 0;
369 for (b = 0; b < cn; b++) {
370 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100371 if(b>0 && sep[b-1] == '-')
372 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
373 else
374 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200375 }
376 len = 0;
377 for (a = 0; a < size; a++) len += vec[a] * vec[a];
378 len = sqrt(len);
379 for (a = 0; a < size; a++) vec[a] /= len;
380 for (a = 0; a < N; a++) bestd[a] = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100381 for (c = from; c < upto; c++) {
Marc Kupietzdc22b982015-10-09 09:19:34 +0200382 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100383// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100384// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
385// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200386 dist = 0;
387 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100388 if(dist > worstbest) {
389 for (a = 0; a < N; a++) {
390 if (dist > bestd[a]) {
391 for (d = N - 1; d > a; d--) {
392 bestd[d] = bestd[d - 1];
393 besti[d] = besti[d - 1];
394 }
395 bestd[a] = dist;
396 besti[a] = c;
397 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200398 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200399 }
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100400 worstbest = bestd[N-1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200401 }
402 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100403
Marc Kupietz000ad862016-02-26 14:59:12 +0100404 nbs = malloc(sizeof(knn));
405 nbs->index = besti;
406 nbs->dist = bestd;
407 nbs->length = N;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100408end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100409 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200410}
411
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100412
Marc Kupietz000ad862016-02-26 14:59:12 +0100413SV *get_neighbours(char *st1, int N) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100414 HV *result = newHV();
Marc Kupietz000ad862016-02-26 14:59:12 +0100415 float bestd[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100416 long long besti[MAX_NEIGHBOURS], bestp[MAX_NEIGHBOURS], a, b, c, d, slice;
Marc Kupietz000ad862016-02-26 14:59:12 +0100417 char *bestw[MAX_NEIGHBOURS];
418 knn *nbs[MAX_THREADS];
419 knnpars pars[MAX_THREADS];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100420 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
Marc Kupietz48c29682016-03-19 11:30:43 +0100421 wordlist *wl;
422
Marc Kupietz000ad862016-02-26 14:59:12 +0100423 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
424
425 slice = words / num_threads;
426
Marc Kupietz48c29682016-03-19 11:30:43 +0100427 wl = getTargetWords(st1);
428
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100429 a = num_threads;
430 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100431 pars[a].wl = wl;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100432 pars[a].N = N;
433 pars[a].from = -1;
434 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
435
Marc Kupietz000ad862016-02-26 14:59:12 +0100436 for(a=0; a < num_threads; a++) {
437 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100438 pars[a].wl = wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100439 pars[a].N = N;
440 pars[a].from = a*slice;
441 pars[a].upto = ((a+1)*slice > words? words:(a+1)*slice);
442 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
443 }
444 for (a = 0; a < num_threads; a++) pthread_join(pt[a], &nbs[a]);
445
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100446 pthread_join(pt[a], &nbs[a]);
447
Marc Kupietz000ad862016-02-26 14:59:12 +0100448 if(!nbs[0])
449 goto end;
450
451 for(b=0; b < N; b++) {
452 besti[b] = nbs[0]->index[b];
453 bestd[b] = nbs[0]->dist[b];
454 }
455
456 for(a=1; a < num_threads; a++) {
457 for(b=0; b < N; b++) {
458 for(c=0; c < N; c++) {
459 if(nbs[a]->dist[b] > bestd[c]) {
460 for(d=N-1; d>c; d--) {
461 bestd[d] = bestd[d-1];
462 besti[d] = besti[d-1];
463 }
464 besti[c] = nbs[a]->index[b];
465 bestd[c] = nbs[a]->dist[b];
466 break;
467 }
468 }
469 }
470 }
471
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100472
Marc Kupietz000ad862016-02-26 14:59:12 +0100473 if(nbs) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100474 AV* array = newAV();
Marc Kupietz000ad862016-02-26 14:59:12 +0100475 for (a = 0; a < N; a++) {
476 bestw[a] = (char *)malloc(max_size * sizeof(char));
477 }
478 for (a = 0; a < N; a++) {
479 strcpy(bestw[a], &vocab[besti[a] * max_w]);
480 HV* hash = newHV();
Marc Kupietza5b90152016-03-15 17:39:19 +0100481 SV* word = newSVpvf(bestw[a], 0);
482 if(latin_enc == 0) SvUTF8_on(word);
483 hv_store(hash, "word", strlen("word"), word , 0);
Marc Kupietz000ad862016-02-26 14:59:12 +0100484 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
485 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
486 AV *vector = newAV();
487 for (b = 0; b < size; b++) {
488 av_push(vector, newSVnv(M[b + besti[a] * size]));
489 }
490 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
491 av_push(array, newRV_noinc((SV*)hash));
492 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100493 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
494
495 for(b=0; b < 10; b++) {
496 besti[b] = nbs[num_threads]->index[b];
497 bestd[b] = nbs[num_threads]->dist[b];
498 bestp[b] = nbs[num_threads]->pos[b];
499 }
500 array = newAV();
Marc Kupietzda9db6f2016-03-19 20:36:20 +0100501 for (a = 0; a < nbs[num_threads]->length; a++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100502 strcpy(bestw[a], &vocab[besti[a] * max_w]);
503 HV* hash = newHV();
504 SV* word = newSVpvf(bestw[a], 0);
505 if(latin_enc == 0) SvUTF8_on(word);
506 hv_store(hash, "word", strlen("word"), word , 0);
507 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
508 hv_store(hash, "pos", strlen("pos"), newSVnv(bestp[a]), 0);
509 av_push(array, newRV_noinc((SV*)hash));
510 }
511 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz000ad862016-02-26 14:59:12 +0100512 }
513end:
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100514 return newRV_noinc((SV*)result);
Marc Kupietz000ad862016-02-26 14:59:12 +0100515}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100516
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100517
Marc Kupietzdc22b982015-10-09 09:19:34 +0200518__DATA__
519
520@@ index.html.ep
521<!DOCTYPE html>
522<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100523<head>
524 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100525 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100526 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100527 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
528 <script>
529 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100530 $( document ).tooltip({
531 content: function() {
532 return $(this).attr('title');
533 }}
534 )
535 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100536 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100537 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
538 <script src="http://klinux10/word2vec/tsne.js"></script>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100539 <script src="http://klinux10/word2vec/som.js"></script>
Marc Kupietzc5990da2016-02-26 08:47:12 +0100540 <script src="http://klinux10/word2vec/labeler.js"></script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100541<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100542body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100543 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100544 font-size: 11pt;
545}
546
547.ui-tooltip-content {
548 font-size: 9pt;
549 colour: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100550}
Marc Kupietz5f780672016-02-25 17:15:54 +0100551
552svg > .ui-tooltip-content {
Marc Kupietzb1029362016-02-27 21:38:55 +0100553 font-size: 8pt;
Marc Kupietz5f780672016-02-25 17:15:54 +0100554 colour: #222222;
555}
556
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100557#collocators {
558 margin-bottom: 15px;
559}
560
Marc Kupietzc4893362016-02-25 08:04:46 +0100561#wrapper {
562 width: 100%;
563// border: 1px solid red;
564 overflow: hidden; /* will contain if #first is longer than #second */
565}
566#first {
Marc Kupietzb1029362016-02-27 21:38:55 +0100567 margin-right: 20px;
568 float: left;
569 // border: 1px solid green;
Marc Kupietzc4893362016-02-25 08:04:46 +0100570}
571#second {
572 border: 1px solid #333;
573 overflow: hidden; /* if you don't want #second to wrap below #first */
574}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100575#som2 svg {
576 border: 1px solid #333;
577}
578
Marc Kupietz4aa62172016-02-25 10:39:27 +0100579#cost {
Marc Kupietzb1029362016-02-27 21:38:55 +0100580 font-size: 8pt;
581 color: #222222;
582 margin-top: 4px;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100583 margin-bottom: 12px;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100584}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100585
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100586#sominfo1, #sominfo {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100587 font-size: 8pt;
588 color: #222222;
589 margin-top: 0px;
590}
591
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100592#somcolor1, #somcolor2, #somcolor3 {
593 display: inline-block;
594 height: 10px;
595 width: 10px;
596}
597
Marc Kupietzd7aea722016-03-02 11:59:12 +0100598#third {
599 border: 1px solid #333;
600}
601
Marc Kupietzc4893362016-02-25 08:04:46 +0100602</style>
603<script>
604
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100605var opt = {epsilon: <%= $epsilon %>, perplexity: <%= $perplexity %>},
Marc Kupietz9fca1732016-02-29 09:07:04 +0100606 mapWidth = 800, // width map
607 mapHeight = 800,
608 jitterRadius = 7;
609
Marc Kupietzc4893362016-02-25 08:04:46 +0100610var T = new tsnejs.tSNE(opt); // create a tSNE instance
611
612var Y;
613
614var data;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100615var labeler;
Marc Kupietzc4893362016-02-25 08:04:46 +0100616
Marc Kupietzc5990da2016-02-26 08:47:12 +0100617
618function applyJitter() {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100619 svg.selectAll('.tsnet')
Marc Kupietzc5990da2016-02-26 08:47:12 +0100620 .data(labels)
621 .transition()
622 .duration(50)
623 .attr("transform", function(d, i) {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100624 T.Y[i][0] = (d.x - mapWidth/2 - tx)/ss/20;
625 T.Y[i][1] = (d.y - mapHeight/2 - ty)/ss/20;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100626 return "translate(" +
627 (d.x) + "," +
628 (d.y) + ")";
629 });
630}
631
Marc Kupietzc4893362016-02-25 08:04:46 +0100632function updateEmbedding() {
633 var Y = T.getSolution();
Marc Kupietzd7aea722016-03-02 11:59:12 +0100634 svg.selectAll('.tsnet')
Marc Kupietz9fca1732016-02-29 09:07:04 +0100635 .data(data.words)
636 .attr("transform", function(d, i) {
637 return "translate(" +
638 ((Y[i][0]*20*ss + tx) + mapWidth/2) + "," +
639 ((Y[i][1]*20*ss + ty) + mapHeight/2) + ")"; });
Marc Kupietzc4893362016-02-25 08:04:46 +0100640}
641
642var svg;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100643var labels = [];
644var anchor_array = [];
645var text;
646
Marc Kupietzc4893362016-02-25 08:04:46 +0100647function drawEmbedding() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100648 $("#embed").empty();
649 var div = d3.select("#embed");
650
651 // get min and max in each column of Y
652 var Y = T.Y;
653
654 svg = div.append("svg") // svg is global
655 .attr("width", mapWidth)
656 .attr("height", mapHeight);
657
658 var g = svg.selectAll(".b")
659 .data(data.words)
660 .enter().append("g")
Marc Kupietzd7aea722016-03-02 11:59:12 +0100661 .attr("class", "tsnet");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100662
663 g.append("a")
664 .attr("xlink:href", function(word) {return "/?word="+word;})
665 .attr("title", function(d, i) {
Marc Kupietze50c8162016-03-01 10:24:43 +0100666 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100667 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100668 .append("text")
Marc Kupietz9fca1732016-02-29 09:07:04 +0100669 .attr("text-anchor", "top")
670 .attr("font-size", 12)
671 .attr("fill", function(d) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100672 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100673 return "red";
674 } else {
675 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100676 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100677 })
678 .text(function(d) { return d; });
679
680 var zoomListener = d3.behavior.zoom()
681 .scaleExtent([0.1, 10])
682 .center([0,0])
683 .on("zoom", zoomHandler);
684 zoomListener(svg);
685}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100686
Marc Kupietz9fca1732016-02-29 09:07:04 +0100687var tx=0, ty=0;
688var ss=1;
689var iter_id=-1;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100690
Marc Kupietz9fca1732016-02-29 09:07:04 +0100691function zoomHandler() {
692 tx = d3.event.translate[0];
693 ty = d3.event.translate[1];
694 ss = d3.event.scale;
695 updateEmbedding();
696}
697
698var stepnum = 0;
699
700function stopStep() {
701 clearInterval(iter_id);
702 text = svg.selectAll("text");
703
704 // jitter function needs different data and co-ordinate representation
705 labels = d3.range(data.words.length).map(function(i) {
706 var x = (T.Y[i][0]*20*ss + tx) + mapWidth/2;
707 var y = (T.Y[i][1]*20*ss + ty) + mapHeight/2;
708 anchor_array.push({x: x, y: y, r: jitterRadius});
709 return {
710 x: x,
711 y: y,
712 name: data.words[i]
713 };
714 });
715
716 // get the actual label bounding boxes for the jitter function
717 var index = 0;
718 text.each(function() {
719 labels[index].width = this.getBBox().width;
720 labels[index].height = this.getBBox().height;
721 index += 1;
722 });
Marc Kupietzc5990da2016-02-26 08:47:12 +0100723
724
725// setTimeout(updateEmbedding, 1);
726// setTimeout(
Marc Kupietz9fca1732016-02-29 09:07:04 +0100727 labeler = d3.labeler()
728 .label(labels)
729 .anchor(anchor_array)
730 .width(mapWidth)
731 .height(mapHeight)
732 .update(applyJitter);
733 // .start(1000);
Marc Kupietzc5990da2016-02-26 08:47:12 +0100734
Marc Kupietz9fca1732016-02-29 09:07:04 +0100735 iter_id = setInterval(jitterStep, 1);
736}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100737
Marc Kupietz9fca1732016-02-29 09:07:04 +0100738var jitter_i=0;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100739
740function jitterStep() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100741 if(jitter_i++ > 100) {
742 clearInterval(iter_id);
743 } else {
744 labeler.start2(10);
745 applyJitter();
746 }
Marc Kupietzc5990da2016-02-26 08:47:12 +0100747}
Marc Kupietzb1029362016-02-27 21:38:55 +0100748
749var last_cost=1000;
750
Marc Kupietz9fca1732016-02-29 09:07:04 +0100751function step() {
752 var i = T.iter;
753
754 if(i > <%= $no_iterations %>) {
755 stopStep();
756 } else {
757 var cost = Math.round(T.step() * 100000) / 100000; // do a few steps
758 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(5));
759 if(i % 250 == 0 && cost >= last_cost) {
760 stopStep();
761 } else {
762 last_cost = cost;
763 updateEmbedding();
764 }
765 }
766}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100767
Marc Kupietz9fca1732016-02-29 09:07:04 +0100768function showMap(j) {
769 data=j;
770 T.iter=0;
771 T.initDataRaw(data.vecs); // init embedding
772 drawEmbedding(); // draw initial embedding
773
774 if(iter_id >= 0) {
775 clearInterval(iter_id);
776 }
777 //T.debugGrad();
778 iter_id = setInterval(step, 1);
Marc Kupietzd7aea722016-03-02 11:59:12 +0100779 if(<%= $show_som %>) {
780 makeSOM(j, <%= $no_iterations %>);
781 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100782}
Marc Kupietza350bce2016-02-25 09:34:25 +0100783
Marc Kupietzc4893362016-02-25 08:04:46 +0100784</script>
785</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200786<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100787 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100788 word(s):
789 <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.">
790 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
Marc Kupietzd7aea722016-03-02 11:59:12 +0100791 max. iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
792 SOM <input type="checkbox" name="som" value="1" <%= ($show_som ? "checked" : "") %>>
793 <span> </span><input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +0100794 </form>
795 <br>
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100796 % if($collocators) {
797 <div id="collocators">
798 % for my $item (@$collocators) {
799 <i><%= $item->{word} %></i> (<%= $item->{pos} %>: <%= sprintf("%.2f", $item->{dist}) %>)
800 % }
801 </div>
802 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100803 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100804 <div id="wrapper">
805 <table id="first">
806 <tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100807 <th align="right">Pos.</th><th align="left">Word</th><th align="right">Cosine dist.</th><th>Freq. rank</th>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100808 </tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100809 % my $j=0; my @words; my @vecs; my @ranks; for my $list (@$lists) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100810 % my $i=1; for my $item (@$list) {
811 % if(!grep{$_ eq $item->{word}} @words) {
812 % push @vecs, $item->{vector};
813 % push @words, $item->{word};
Marc Kupietz5f780672016-02-25 17:15:54 +0100814 % push @ranks, $item->{rank};
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100815 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100816 <tr>
817 <td align="right">
818 <%= $i++ %>.
819 </td>
820 <td>
821 <a href="/?word=<%= $item->{word} %>">
822 <%= $item->{word} %>
823 </a>
824 </td>
825 <td align="right">
826 <%= sprintf("%.3f", $item->{dist}) %>
827 </td>
Marc Kupietz5f780672016-02-25 17:15:54 +0100828 <td align="right">
829 <%= $item->{rank} %>
830 </td>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100831 </tr>
832 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100833 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100834 </table>
835 <script>
836 % use Mojo::ByteStream 'b';
837 $(window).load(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100838 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", words => \@words, vecs => \@vecs, ranks => \@ranks})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +0100839 });
840 </script>
841 % }
842 <div id="second" style="width:800px; height:800px; font-family: arial;">
843 <div id="embed">
844 </div>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100845 </div>
Marc Kupietzb1029362016-02-27 21:38:55 +0100846 <div id="cost"></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100847 % if($show_som) {
848 <div id="som2">
849 </div>
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100850 <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 +0100851 <div id="sominfo">SOM iteration <span id="iterations">0</span></div>
852 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100853 </div>
854 <p>
855 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 +0200856 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100857-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 +0100858 </pre>
859 </p>
860</body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200861</html>
862