blob: 4b43c49dfbb4ad2ecb01cf68152606e1ef3025f2 [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 {
93 char *token;
94 int N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010095 long from;
Marc Kupietz000ad862016-02-26 14:59:12 +010096 unsigned long upto;
97} knnpars;
98
Marc Kupietz6b2975c2016-03-18 21:59:33 +010099float *M, *syn1neg_window, *expTable;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200100char *vocab;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100101
Marc Kupietz82b02672016-02-26 12:32:25 +0100102long long words, size;
Marc Kupietz000ad862016-02-26 14:59:12 +0100103int num_threads=20;
Marc Kupietza5b90152016-03-15 17:39:19 +0100104int latin_enc=0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100105int window;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200106
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100107int init_net(char *file_name, char *net_name, int latin) {
Marc Kupietz67c20282016-02-26 09:42:00 +0100108 FILE *f, *binvecs, *binwords;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100109 int binwords_fd, binvecs_fd, net_fd, i;
Marc Kupietz82b02672016-02-26 12:32:25 +0100110 long long a, b, c, d, cn;
111 float len;
112
Marc Kupietz67c20282016-02-26 09:42:00 +0100113 char binvecs_fname[256], binwords_fname[256];
114 strcpy(binwords_fname, file_name);
115 strcat(binwords_fname, ".words");
116 strcpy(binvecs_fname, file_name);
117 strcat(binvecs_fname, ".vecs");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200118
Marc Kupietza5b90152016-03-15 17:39:19 +0100119 latin_enc = latin;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200120 f = fopen(file_name, "rb");
121 if (f == NULL) {
122 printf("Input file %s not found\n", file_name);
123 return -1;
124 }
125 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100126 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200127 fscanf(f, "%lld", &size);
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100128 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
129 printf("Converting %s to memory mappable structures\n", file_name);
Marc Kupietzf0809762016-02-26 10:13:47 +0100130 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
131 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
132 if (M == NULL) {
133 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
134 return -1;
135 }
Marc Kupietz67c20282016-02-26 09:42:00 +0100136 for (b = 0; b < words; b++) {
137 a = 0;
138 while (1) {
139 vocab[b * max_w + a] = fgetc(f);
140 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
141 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
142 }
143 vocab[b * max_w + a] = 0;
144 fread(&M[b * size], sizeof(float), size, f);
145 len = 0;
146 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
147 len = sqrt(len);
148 for (a = 0; a < size; a++) M[a + b * size] /= len;
149 }
150 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
151 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
152 fclose(binvecs);
153 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
154 fclose(binwords);
155 }
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100156 }
157 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
158 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
159 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
160 if (M == MAP_FAILED || vocab == MAP_FAILED) {
161 close(binvecs_fd);
162 close(binwords_fd);
163 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
164 exit(-1);
165 }
166 } else {
167 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
168 exit(-1);
Marc Kupietz67c20282016-02-26 09:42:00 +0100169 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200170 fclose(f);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100171
172 if(net_name) {
173 if( (net_fd = open(net_name, O_RDONLY)) >= 0) {
174 window = (lseek(net_fd, 0, SEEK_END) - sizeof(float) * words * size) / words / size / sizeof(float) / 2;
175 // lseek(net_fd, sizeof(float) * words * size, SEEK_SET);
176 munmap(M, sizeof(float) * words * size);
177 M = mmap(0, sizeof(float) * words * size + sizeof(float) * 2 * window * size * words, PROT_READ, MAP_SHARED, net_fd, 0);
178 if (M == MAP_FAILED) {
179 close(net_fd);
180 fprintf(stderr, "Cannot mmap %s\n", net_name);
181 exit(-1);
182 }
183 syn1neg_window = M + words * size;
184 } else {
185 fprintf(stderr, "Cannot open %s\n", net_name);
186 exit(-1);
187 }
188 fprintf(stderr, "Successfully memmaped %s. Determined window size: %d\n", net_name, window);
189 }
190
191 expTable = (float *) malloc((EXP_TABLE_SIZE + 1) * sizeof(float));
192 for (i = 0; i < EXP_TABLE_SIZE; i++) {
193 expTable[i] = exp((i / (float) EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
194 expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
195 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200196 return 0;
197}
198
Marc Kupietz000ad862016-02-26 14:59:12 +0100199
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100200knn *getCollocators(int cc) {
201 knn *nbs = NULL;
202 long window_layer_size = size * window * 2;
203 long a, b, c, d, e, window_offset, target, max_target=0, maxmax_target;
204 float f, max_f, maxmax_f;
205 float *target_sums, *bestf, worstbest;
206 long long *besti, *bestp;
207 int N = 10;
208 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
209 besti = malloc(N * sizeof(long long));
210 bestp = malloc(N * sizeof(long long));
211 bestf = malloc(N * sizeof(float));
212 for (b = 0; b < words; b++)
213 target_sums[b]=0;
214 for (b = 0; b < N; b++)
215 bestf[b]=-1;
216 worstbest = -1;
217 d = cc;
218 maxmax_f = -1;
219 maxmax_target = 0;
220
221
222 for (a = window * 2 + 1; a >=0; a--) {
223 printf("window pos: %ld\n", a);
224 if (a != window) {
225 max_f = -1;
226 window_offset = a * size;
227 if (a > window)
228 window_offset -= size;
229 for(target = 0; target < words; target ++) {
230 if(target == d)
231 continue;
232 f = 0;
233 for (c = 0; c < size; c++)
234 f += M[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
235 if (f < -MAX_EXP)
236 continue;
237 else if (f > MAX_EXP)
238 continue;
239 else
240 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
241 if(f > max_f) {
242 max_f = f;
243 max_target = target;
244 }
245 target_sums[target] += (1-target_sums[target]) * f;
246 if(f > worstbest) {
247 for (b = 0; b < N; b++) {
248 if (f > bestf[b]) {
249 for (e = N - 1; e > b; e--) {
250 bestf[e] = bestf[e - 1];
251 besti[e] = besti[e - 1];
252 bestp[e] = bestp[e - 1];
253 }
254 bestf[b] = f;
255 besti[b] = target;
256 bestp[b] = window-a;
257 break;
258 }
259 }
260 worstbest = bestf[N-1];
261 }
262 }
263 printf("%d %.2f\n", max_target, max_f);
264 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
265 if(max_f > maxmax_f) {
266 maxmax_f = max_f;
267 maxmax_target = max_target;
268 }
269 } else {
270 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
271 }
272 }
273 max_f = -1;
274 for (b = 0; b < words; b++) {
275 if(target_sums[b] > max_f) {
276 max_f = target_sums[b];
277 max_target = b;
278 }
279 }
280 printf(" -- max sum: %s (%.2f), max resp.: \x1b[1m%s\x1b[0m (%.2f)\n",
281 &vocab[max_target * max_w], max_f,
282 &vocab[maxmax_target * max_w], maxmax_f);
283 for(b=0; b<N && bestf[b]>-1; b++)
284 printf("%-32s %.2f %d\n", &vocab[besti[b]*max_w], bestf[b], bestp[b]);
285 printf("\n");
286 free(target_sums);
287 nbs = malloc(sizeof(knn));
288 nbs->index = besti;
289 nbs->dist = bestf;
290 nbs->pos = bestp;
291 nbs->length = N;
292 return(nbs);
293}
294
Marc Kupietz000ad862016-02-26 14:59:12 +0100295void *_get_neighbours(knnpars *pars) {
296 char *st1 = pars->token;
297 int N = pars->N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100298 long from = pars -> from;
Marc Kupietz000ad862016-02-26 14:59:12 +0100299 unsigned long upto = pars -> upto;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100300 char file_name[max_size], st[100][max_size], sep[100];
Marc Kupietz000ad862016-02-26 14:59:12 +0100301 float dist, len, *bestd, vec[max_size];
302 long long a, b, c, d, cn, bi[100], *besti;
Marc Kupietz82b02672016-02-26 12:32:25 +0100303 char ch;
Marc Kupietz000ad862016-02-26 14:59:12 +0100304 knn *nbs = NULL;
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100305
Marc Kupietz000ad862016-02-26 14:59:12 +0100306 besti = malloc(N * sizeof(long long));
307 bestd = malloc(N * sizeof(float));
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100308
Marc Kupietz000ad862016-02-26 14:59:12 +0100309 float worstbest=-1;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200310
311 for (a = 0; a < N; a++) bestd[a] = 0;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200312 a = 0;
313 cn = 0;
314 b = 0;
315 c = 0;
316 while (1) {
317 st[cn][b] = st1[c];
318 b++;
319 c++;
320 st[cn][b] = 0;
321 if (st1[c] == 0) break;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100322 if (st1[c] == ' ' || st1[c] == '-') {
323 sep[cn++] = st1[c];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200324 b = 0;
325 c++;
326 }
327 }
328 cn++;
329 for (a = 0; a < cn; a++) {
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100330 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
331 if (b == words) b = -1;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200332 bi[a] = b;
Marc Kupietze8da3062016-02-25 08:37:53 +0100333 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], bi[a]);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100334 if(from < 0) {
335 nbs = getCollocators(b);
336 pthread_exit(nbs);
337 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200338 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100339 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100340 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200341 break;
342 }
343 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100344 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100345 N = 0;
346 goto end;
347 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200348 for (a = 0; a < size; a++) vec[a] = 0;
349 for (b = 0; b < cn; b++) {
350 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100351 if(b>0 && sep[b-1] == '-')
352 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
353 else
354 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200355 }
356 len = 0;
357 for (a = 0; a < size; a++) len += vec[a] * vec[a];
358 len = sqrt(len);
359 for (a = 0; a < size; a++) vec[a] /= len;
360 for (a = 0; a < N; a++) bestd[a] = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100361 for (c = from; c < upto; c++) {
Marc Kupietzdc22b982015-10-09 09:19:34 +0200362 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100363// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100364// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
365// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200366 dist = 0;
367 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100368 if(dist > worstbest) {
369 for (a = 0; a < N; a++) {
370 if (dist > bestd[a]) {
371 for (d = N - 1; d > a; d--) {
372 bestd[d] = bestd[d - 1];
373 besti[d] = besti[d - 1];
374 }
375 bestd[a] = dist;
376 besti[a] = c;
377 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200378 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200379 }
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100380 worstbest = bestd[N-1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200381 }
382 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100383
Marc Kupietz000ad862016-02-26 14:59:12 +0100384 nbs = malloc(sizeof(knn));
385 nbs->index = besti;
386 nbs->dist = bestd;
387 nbs->length = N;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100388end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100389 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200390}
391
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100392
Marc Kupietz000ad862016-02-26 14:59:12 +0100393SV *get_neighbours(char *st1, int N) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100394 HV *result = newHV();
Marc Kupietz000ad862016-02-26 14:59:12 +0100395 float bestd[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100396 long long besti[MAX_NEIGHBOURS], bestp[MAX_NEIGHBOURS], a, b, c, d, slice;
Marc Kupietz000ad862016-02-26 14:59:12 +0100397 char *bestw[MAX_NEIGHBOURS];
398 knn *nbs[MAX_THREADS];
399 knnpars pars[MAX_THREADS];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100400 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
Marc Kupietz000ad862016-02-26 14:59:12 +0100401
402 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
403
404 slice = words / num_threads;
405
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100406 a = num_threads;
407 pars[a].token = st1;
408 pars[a].N = N;
409 pars[a].from = -1;
410 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
411
Marc Kupietz000ad862016-02-26 14:59:12 +0100412 for(a=0; a < num_threads; a++) {
413 pars[a].token = st1;
414 pars[a].N = N;
415 pars[a].from = a*slice;
416 pars[a].upto = ((a+1)*slice > words? words:(a+1)*slice);
417 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
418 }
419 for (a = 0; a < num_threads; a++) pthread_join(pt[a], &nbs[a]);
420
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100421 pthread_join(pt[a], &nbs[a]);
422
Marc Kupietz000ad862016-02-26 14:59:12 +0100423 if(!nbs[0])
424 goto end;
425
426 for(b=0; b < N; b++) {
427 besti[b] = nbs[0]->index[b];
428 bestd[b] = nbs[0]->dist[b];
429 }
430
431 for(a=1; a < num_threads; a++) {
432 for(b=0; b < N; b++) {
433 for(c=0; c < N; c++) {
434 if(nbs[a]->dist[b] > bestd[c]) {
435 for(d=N-1; d>c; d--) {
436 bestd[d] = bestd[d-1];
437 besti[d] = besti[d-1];
438 }
439 besti[c] = nbs[a]->index[b];
440 bestd[c] = nbs[a]->dist[b];
441 break;
442 }
443 }
444 }
445 }
446
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100447
Marc Kupietz000ad862016-02-26 14:59:12 +0100448 if(nbs) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100449 AV* array = newAV();
Marc Kupietz000ad862016-02-26 14:59:12 +0100450 for (a = 0; a < N; a++) {
451 bestw[a] = (char *)malloc(max_size * sizeof(char));
452 }
453 for (a = 0; a < N; a++) {
454 strcpy(bestw[a], &vocab[besti[a] * max_w]);
455 HV* hash = newHV();
Marc Kupietza5b90152016-03-15 17:39:19 +0100456 SV* word = newSVpvf(bestw[a], 0);
457 if(latin_enc == 0) SvUTF8_on(word);
458 hv_store(hash, "word", strlen("word"), word , 0);
Marc Kupietz000ad862016-02-26 14:59:12 +0100459 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
460 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
461 AV *vector = newAV();
462 for (b = 0; b < size; b++) {
463 av_push(vector, newSVnv(M[b + besti[a] * size]));
464 }
465 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
466 av_push(array, newRV_noinc((SV*)hash));
467 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100468 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
469
470 for(b=0; b < 10; b++) {
471 besti[b] = nbs[num_threads]->index[b];
472 bestd[b] = nbs[num_threads]->dist[b];
473 bestp[b] = nbs[num_threads]->pos[b];
474 }
475 array = newAV();
476 for (a = 0; a < 10; a++) {
477 strcpy(bestw[a], &vocab[besti[a] * max_w]);
478 HV* hash = newHV();
479 SV* word = newSVpvf(bestw[a], 0);
480 if(latin_enc == 0) SvUTF8_on(word);
481 hv_store(hash, "word", strlen("word"), word , 0);
482 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
483 hv_store(hash, "pos", strlen("pos"), newSVnv(bestp[a]), 0);
484 av_push(array, newRV_noinc((SV*)hash));
485 }
486 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz000ad862016-02-26 14:59:12 +0100487 }
488end:
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100489 return newRV_noinc((SV*)result);
Marc Kupietz000ad862016-02-26 14:59:12 +0100490}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100491
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100492
Marc Kupietzdc22b982015-10-09 09:19:34 +0200493__DATA__
494
495@@ index.html.ep
496<!DOCTYPE html>
497<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100498<head>
499 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100500 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100501 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100502 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
503 <script>
504 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100505 $( document ).tooltip({
506 content: function() {
507 return $(this).attr('title');
508 }}
509 )
510 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100511 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100512 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
513 <script src="http://klinux10/word2vec/tsne.js"></script>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100514 <script src="http://klinux10/word2vec/som.js"></script>
Marc Kupietzc5990da2016-02-26 08:47:12 +0100515 <script src="http://klinux10/word2vec/labeler.js"></script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100516<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100517body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100518 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100519 font-size: 11pt;
520}
521
522.ui-tooltip-content {
523 font-size: 9pt;
524 colour: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100525}
Marc Kupietz5f780672016-02-25 17:15:54 +0100526
527svg > .ui-tooltip-content {
Marc Kupietzb1029362016-02-27 21:38:55 +0100528 font-size: 8pt;
Marc Kupietz5f780672016-02-25 17:15:54 +0100529 colour: #222222;
530}
531
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100532#collocators {
533 margin-bottom: 15px;
534}
535
Marc Kupietzc4893362016-02-25 08:04:46 +0100536#wrapper {
537 width: 100%;
538// border: 1px solid red;
539 overflow: hidden; /* will contain if #first is longer than #second */
540}
541#first {
Marc Kupietzb1029362016-02-27 21:38:55 +0100542 margin-right: 20px;
543 float: left;
544 // border: 1px solid green;
Marc Kupietzc4893362016-02-25 08:04:46 +0100545}
546#second {
547 border: 1px solid #333;
548 overflow: hidden; /* if you don't want #second to wrap below #first */
549}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100550#som2 svg {
551 border: 1px solid #333;
552}
553
Marc Kupietz4aa62172016-02-25 10:39:27 +0100554#cost {
Marc Kupietzb1029362016-02-27 21:38:55 +0100555 font-size: 8pt;
556 color: #222222;
557 margin-top: 4px;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100558 margin-bottom: 12px;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100559}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100560
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100561#sominfo1, #sominfo {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100562 font-size: 8pt;
563 color: #222222;
564 margin-top: 0px;
565}
566
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100567#somcolor1, #somcolor2, #somcolor3 {
568 display: inline-block;
569 height: 10px;
570 width: 10px;
571}
572
Marc Kupietzd7aea722016-03-02 11:59:12 +0100573#third {
574 border: 1px solid #333;
575}
576
Marc Kupietzc4893362016-02-25 08:04:46 +0100577</style>
578<script>
579
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100580var opt = {epsilon: <%= $epsilon %>, perplexity: <%= $perplexity %>},
Marc Kupietz9fca1732016-02-29 09:07:04 +0100581 mapWidth = 800, // width map
582 mapHeight = 800,
583 jitterRadius = 7;
584
Marc Kupietzc4893362016-02-25 08:04:46 +0100585var T = new tsnejs.tSNE(opt); // create a tSNE instance
586
587var Y;
588
589var data;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100590var labeler;
Marc Kupietzc4893362016-02-25 08:04:46 +0100591
Marc Kupietzc5990da2016-02-26 08:47:12 +0100592
593function applyJitter() {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100594 svg.selectAll('.tsnet')
Marc Kupietzc5990da2016-02-26 08:47:12 +0100595 .data(labels)
596 .transition()
597 .duration(50)
598 .attr("transform", function(d, i) {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100599 T.Y[i][0] = (d.x - mapWidth/2 - tx)/ss/20;
600 T.Y[i][1] = (d.y - mapHeight/2 - ty)/ss/20;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100601 return "translate(" +
602 (d.x) + "," +
603 (d.y) + ")";
604 });
605}
606
Marc Kupietzc4893362016-02-25 08:04:46 +0100607function updateEmbedding() {
608 var Y = T.getSolution();
Marc Kupietzd7aea722016-03-02 11:59:12 +0100609 svg.selectAll('.tsnet')
Marc Kupietz9fca1732016-02-29 09:07:04 +0100610 .data(data.words)
611 .attr("transform", function(d, i) {
612 return "translate(" +
613 ((Y[i][0]*20*ss + tx) + mapWidth/2) + "," +
614 ((Y[i][1]*20*ss + ty) + mapHeight/2) + ")"; });
Marc Kupietzc4893362016-02-25 08:04:46 +0100615}
616
617var svg;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100618var labels = [];
619var anchor_array = [];
620var text;
621
Marc Kupietzc4893362016-02-25 08:04:46 +0100622function drawEmbedding() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100623 $("#embed").empty();
624 var div = d3.select("#embed");
625
626 // get min and max in each column of Y
627 var Y = T.Y;
628
629 svg = div.append("svg") // svg is global
630 .attr("width", mapWidth)
631 .attr("height", mapHeight);
632
633 var g = svg.selectAll(".b")
634 .data(data.words)
635 .enter().append("g")
Marc Kupietzd7aea722016-03-02 11:59:12 +0100636 .attr("class", "tsnet");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100637
638 g.append("a")
639 .attr("xlink:href", function(word) {return "/?word="+word;})
640 .attr("title", function(d, i) {
Marc Kupietze50c8162016-03-01 10:24:43 +0100641 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100642 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100643 .append("text")
Marc Kupietz9fca1732016-02-29 09:07:04 +0100644 .attr("text-anchor", "top")
645 .attr("font-size", 12)
646 .attr("fill", function(d) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100647 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietza350bce2016-02-25 09:34:25 +0100648 return "red";
649 } else {
650 return "#333"
Marc Kupietzc4893362016-02-25 08:04:46 +0100651 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100652 })
653 .text(function(d) { return d; });
654
655 var zoomListener = d3.behavior.zoom()
656 .scaleExtent([0.1, 10])
657 .center([0,0])
658 .on("zoom", zoomHandler);
659 zoomListener(svg);
660}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100661
Marc Kupietz9fca1732016-02-29 09:07:04 +0100662var tx=0, ty=0;
663var ss=1;
664var iter_id=-1;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100665
Marc Kupietz9fca1732016-02-29 09:07:04 +0100666function zoomHandler() {
667 tx = d3.event.translate[0];
668 ty = d3.event.translate[1];
669 ss = d3.event.scale;
670 updateEmbedding();
671}
672
673var stepnum = 0;
674
675function stopStep() {
676 clearInterval(iter_id);
677 text = svg.selectAll("text");
678
679 // jitter function needs different data and co-ordinate representation
680 labels = d3.range(data.words.length).map(function(i) {
681 var x = (T.Y[i][0]*20*ss + tx) + mapWidth/2;
682 var y = (T.Y[i][1]*20*ss + ty) + mapHeight/2;
683 anchor_array.push({x: x, y: y, r: jitterRadius});
684 return {
685 x: x,
686 y: y,
687 name: data.words[i]
688 };
689 });
690
691 // get the actual label bounding boxes for the jitter function
692 var index = 0;
693 text.each(function() {
694 labels[index].width = this.getBBox().width;
695 labels[index].height = this.getBBox().height;
696 index += 1;
697 });
Marc Kupietzc5990da2016-02-26 08:47:12 +0100698
699
700// setTimeout(updateEmbedding, 1);
701// setTimeout(
Marc Kupietz9fca1732016-02-29 09:07:04 +0100702 labeler = d3.labeler()
703 .label(labels)
704 .anchor(anchor_array)
705 .width(mapWidth)
706 .height(mapHeight)
707 .update(applyJitter);
708 // .start(1000);
Marc Kupietzc5990da2016-02-26 08:47:12 +0100709
Marc Kupietz9fca1732016-02-29 09:07:04 +0100710 iter_id = setInterval(jitterStep, 1);
711}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100712
Marc Kupietz9fca1732016-02-29 09:07:04 +0100713var jitter_i=0;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100714
715function jitterStep() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100716 if(jitter_i++ > 100) {
717 clearInterval(iter_id);
718 } else {
719 labeler.start2(10);
720 applyJitter();
721 }
Marc Kupietzc5990da2016-02-26 08:47:12 +0100722}
Marc Kupietzb1029362016-02-27 21:38:55 +0100723
724var last_cost=1000;
725
Marc Kupietz9fca1732016-02-29 09:07:04 +0100726function step() {
727 var i = T.iter;
728
729 if(i > <%= $no_iterations %>) {
730 stopStep();
731 } else {
732 var cost = Math.round(T.step() * 100000) / 100000; // do a few steps
733 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(5));
734 if(i % 250 == 0 && cost >= last_cost) {
735 stopStep();
736 } else {
737 last_cost = cost;
738 updateEmbedding();
739 }
740 }
741}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100742
Marc Kupietz9fca1732016-02-29 09:07:04 +0100743function showMap(j) {
744 data=j;
745 T.iter=0;
746 T.initDataRaw(data.vecs); // init embedding
747 drawEmbedding(); // draw initial embedding
748
749 if(iter_id >= 0) {
750 clearInterval(iter_id);
751 }
752 //T.debugGrad();
753 iter_id = setInterval(step, 1);
Marc Kupietzd7aea722016-03-02 11:59:12 +0100754 if(<%= $show_som %>) {
755 makeSOM(j, <%= $no_iterations %>);
756 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100757}
Marc Kupietza350bce2016-02-25 09:34:25 +0100758
Marc Kupietzc4893362016-02-25 08:04:46 +0100759</script>
760</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200761<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100762 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100763 word(s):
764 <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.">
765 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
Marc Kupietzd7aea722016-03-02 11:59:12 +0100766 max. iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
767 SOM <input type="checkbox" name="som" value="1" <%= ($show_som ? "checked" : "") %>>
768 <span> </span><input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +0100769 </form>
770 <br>
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100771 % if($collocators) {
772 <div id="collocators">
773 % for my $item (@$collocators) {
774 <i><%= $item->{word} %></i> (<%= $item->{pos} %>: <%= sprintf("%.2f", $item->{dist}) %>)
775 % }
776 </div>
777 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100778 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +0100779 <div id="wrapper">
780 <table id="first">
781 <tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100782 <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 +0100783 </tr>
Marc Kupietz5f780672016-02-25 17:15:54 +0100784 % my $j=0; my @words; my @vecs; my @ranks; for my $list (@$lists) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100785 % my $i=1; for my $item (@$list) {
786 % if(!grep{$_ eq $item->{word}} @words) {
787 % push @vecs, $item->{vector};
788 % push @words, $item->{word};
Marc Kupietz5f780672016-02-25 17:15:54 +0100789 % push @ranks, $item->{rank};
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100790 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100791 <tr>
792 <td align="right">
793 <%= $i++ %>.
794 </td>
795 <td>
796 <a href="/?word=<%= $item->{word} %>">
797 <%= $item->{word} %>
798 </a>
799 </td>
800 <td align="right">
801 <%= sprintf("%.3f", $item->{dist}) %>
802 </td>
Marc Kupietz5f780672016-02-25 17:15:54 +0100803 <td align="right">
804 <%= $item->{rank} %>
805 </td>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100806 </tr>
807 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100808 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100809 </table>
810 <script>
811 % use Mojo::ByteStream 'b';
812 $(window).load(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100813 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", words => \@words, vecs => \@vecs, ranks => \@ranks})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +0100814 });
815 </script>
816 % }
817 <div id="second" style="width:800px; height:800px; font-family: arial;">
818 <div id="embed">
819 </div>
Marc Kupietz4aa62172016-02-25 10:39:27 +0100820 </div>
Marc Kupietzb1029362016-02-27 21:38:55 +0100821 <div id="cost"></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100822 % if($show_som) {
823 <div id="som2">
824 </div>
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100825 <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 +0100826 <div id="sominfo">SOM iteration <span id="iterations">0</span></div>
827 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +0100828 </div>
829 <p>
830 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 +0200831 <pre>
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100832-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 +0100833 </pre>
834 </p>
835</body>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200836</html>
837