blob: a255b2ffab7492030e4676dd8da0d914386024b7 [file] [log] [blame]
Marc Kupietzdc22b982015-10-09 09:19:34 +02001#!/usr/local/bin/perl
2use Inline C;
Marc Kupietza2e64502016-04-27 09:53:51 +02003#use Inline C => Config => BUILD_NOISY => 1, CFLAGS => $Config{cflags}." -O4 -mtune k9";
4use Inline C => Config => CLEAN_AFTER_BUILD => 0, ccflags => $Config{ccflags}." -O4";
Marc Kupietzdc22b982015-10-09 09:19:34 +02005use Mojolicious::Lite;
Marc Kupietzc4893362016-02-25 08:04:46 +01006use Mojo::JSON qw(decode_json encode_json to_json);
Marc Kupietz247500f2015-10-09 11:29:01 +02007use Encode qw(decode encode);
Marc Kupietza5b90152016-03-15 17:39:19 +01008use Getopt::Std;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +01009use Mojo::Server::Daemon;
Marc Kupietzd4227392016-03-01 16:45:12 +010010plugin 'Log::Access';
Marc Kupietzdc22b982015-10-09 09:19:34 +020011
Marc Kupietza5b90152016-03-15 17:39:19 +010012our $opt_i = 0; # latin1-input?
13our $opt_l = undef;
14our $opt_p = 5676;
Marc Kupietza2e64502016-04-27 09:53:51 +020015our $opt_m;
Marc Kupietz43ee87e2016-04-25 10:50:08 +020016our $opt_n = '';
17our $opt_d;
Marc Kupietza5b90152016-03-15 17:39:19 +010018
Marc Kupietz793413b2016-04-02 21:48:57 +020019my $training_args="";
Marc Kupietza2e64502016-04-27 09:53:51 +020020my $mergedEnd=0;
Marc Kupietz793413b2016-04-02 21:48:57 +020021
Marc Kupietza2e64502016-04-27 09:53:51 +020022getopt('d:il:p:m:');
Marc Kupietza5b90152016-03-15 17:39:19 +010023
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010024# -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 +010025if(!$ARGV[0]) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010026 init_net("vectors15.bin", $opt_n, ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010027} else {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010028 init_net($ARGV[0], $opt_n, ($opt_i? 1 : 0));
Marc Kupietz793413b2016-04-02 21:48:57 +020029 if(open(FILE, "$ARGV[0].args")) {
30 $training_args = <FILE>;
31 }
32 close(FILE);
Marc Kupietz2cb667e2016-03-10 09:44:12 +010033}
Marc Kupietzdc22b982015-10-09 09:19:34 +020034
Marc Kupietza2e64502016-04-27 09:53:51 +020035if($opt_m) {
36 $mergedEnd = mergeVectors($opt_m);
37}
38
Marc Kupietz43ee87e2016-04-25 10:50:08 +020039if($opt_d) { # -d: dump vecs and exit
40 dump_vecs($opt_d);
41 exit;
42}
43
Marc Kupietza5b90152016-03-15 17:39:19 +010044my $daemon = Mojo::Server::Daemon->new(
45 app => app,
46 listen => ['http://'.($opt_l ? $opt_l : '*').":$opt_p"]
47);
48
Marc Kupietzdc22b982015-10-09 09:19:34 +020049get '/' => sub {
50 my $c = shift;
51 my $word=$c->param('word');
Marc Kupietz44bee3c2016-02-25 16:26:29 +010052 my $no_nbs=$c->param('n') || 100;
53 my $no_iterations=$c->param('N') || 2000;
Marc Kupietzd4227392016-03-01 16:45:12 +010054 my $perplexity=$c->param('perplexity') || 20;
Marc Kupietzc4d62f82016-03-01 11:04:24 +010055 my $epsilon=$c->param('epsilon') || 5;
Marc Kupietzd7aea722016-03-02 11:59:12 +010056 my $som=$c->param('som') || 0;
Marc Kupietza2e64502016-04-27 09:53:51 +020057 my $searchBaseVocabFirst=$c->param('sbf') || 0;
Marc Kupietz6d9a6782016-03-23 17:25:25 +010058 my $sort=$c->param('sort') || 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010059 my $res;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010060 my @lists;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010061 my @collocations;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010062 if(defined($word) && $word !~ /^\s*$/) {
63 $c->inactivity_timeout(300);
Marc Kupietz44bee3c2016-02-25 16:26:29 +010064 $word =~ s/\s+/ /g;
65 for my $w (split(' *\| *', $word)) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010066 $c->app->log->debug('Looking for neighbours of '.$w);
Marc Kupietza5b90152016-03-15 17:39:19 +010067 if($opt_i) {
Marc Kupietza2e64502016-04-27 09:53:51 +020068 $res = get_neighbours(encode("iso-8859-1", $w), $no_nbs, $sort, $searchBaseVocabFirst);
Marc Kupietza5b90152016-03-15 17:39:19 +010069 } else {
Marc Kupietza2e64502016-04-27 09:53:51 +020070 $res = get_neighbours($w, $no_nbs, $sort, $searchBaseVocabFirst);
Marc Kupietza5b90152016-03-15 17:39:19 +010071 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +010072 push(@lists, $res->{paradigmatic});
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010073 }
Marc Kupietz247500f2015-10-09 11:29:01 +020074 }
Marc Kupietz000ad862016-02-26 14:59:12 +010075 $word =~ s/ *\| */ | /g;
Marc Kupietza2e64502016-04-27 09:53:51 +020076 $c->render(template=>"index", word=>$word, no_nbs=>$no_nbs, no_iterations => $no_iterations, epsilon=> $epsilon, perplexity=> $perplexity, show_som=>$som, searchBaseVocabFirst=>$searchBaseVocabFirst, sort=>$sort, training_args=>$training_args, mergedEnd=> $mergedEnd, lists=> \@lists, collocators=> $res->{syntagmatic});
Marc Kupietzdc22b982015-10-09 09:19:34 +020077};
78
Marc Kupietza5b90152016-03-15 17:39:19 +010079$daemon->run; # app->start;
Marc Kupietzdc22b982015-10-09 09:19:34 +020080
81exit;
82
83__END__
84
85__C__
86#include <stdio.h>
87#include <string.h>
88#include <math.h>
89#include <malloc.h>
90#include <stdlib.h> //strlen
Marc Kupietzf0809762016-02-26 10:13:47 +010091#include <sys/mman.h>
Marc Kupietz000ad862016-02-26 14:59:12 +010092#include <pthread.h>
Marc Kupietzdc22b982015-10-09 09:19:34 +020093
94#define max_size 2000
95#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010096#define MAX_NEIGHBOURS 1000
Marc Kupietz44bee3c2016-02-25 16:26:29 +010097#define MAX_WORDS -1
Marc Kupietz000ad862016-02-26 14:59:12 +010098#define MAX_THREADS 100
Marc Kupietz6b2975c2016-03-18 21:59:33 +010099#define MAX_CC 50
100#define EXP_TABLE_SIZE 1000
101#define MAX_EXP 6
Marc Kupietz271e2a42016-03-22 11:37:43 +0100102#define MIN_RESP 0.50
Marc Kupietzdc22b982015-10-09 09:19:34 +0200103
104//the thread function
105void *connection_handler(void *);
Marc Kupietz000ad862016-02-26 14:59:12 +0100106
107typedef struct {
108 long long *index;
109 float *dist;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100110 float *norm;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100111 long long *pos;
Marc Kupietz80abb442016-03-23 21:04:08 +0100112 int length;
Marc Kupietz000ad862016-02-26 14:59:12 +0100113} knn;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100114
Marc Kupietz000ad862016-02-26 14:59:12 +0100115typedef struct {
Marc Kupietz48c29682016-03-19 11:30:43 +0100116 long long wordi[MAX_NEIGHBOURS];
117 char sep[MAX_NEIGHBOURS];
118 int length;
119} wordlist;
120
121typedef struct {
122 wordlist *wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100123 char *token;
124 int N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100125 long from;
Marc Kupietz000ad862016-02-26 14:59:12 +0100126 unsigned long upto;
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100127 float *target_sums;
Marc Kupietz000ad862016-02-26 14:59:12 +0100128} knnpars;
129
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200130float *M, *M2=0L, *syn1neg_window, *expTable;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200131char *vocab;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100132
Marc Kupietza2e64502016-04-27 09:53:51 +0200133long long words, size, merged_end;
Marc Kupietz000ad862016-02-26 14:59:12 +0100134int num_threads=20;
Marc Kupietza5b90152016-03-15 17:39:19 +0100135int latin_enc=0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100136int window;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200137
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100138int init_net(char *file_name, char *net_name, int latin) {
Marc Kupietz67c20282016-02-26 09:42:00 +0100139 FILE *f, *binvecs, *binwords;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100140 int binwords_fd, binvecs_fd, net_fd, i;
Marc Kupietz82b02672016-02-26 12:32:25 +0100141 long long a, b, c, d, cn;
142 float len;
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200143 double val;
Marc Kupietz82b02672016-02-26 12:32:25 +0100144
Marc Kupietz67c20282016-02-26 09:42:00 +0100145 char binvecs_fname[256], binwords_fname[256];
146 strcpy(binwords_fname, file_name);
147 strcat(binwords_fname, ".words");
148 strcpy(binvecs_fname, file_name);
149 strcat(binvecs_fname, ".vecs");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200150
Marc Kupietza5b90152016-03-15 17:39:19 +0100151 latin_enc = latin;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200152 f = fopen(file_name, "rb");
153 if (f == NULL) {
154 printf("Input file %s not found\n", file_name);
155 return -1;
156 }
157 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100158 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200159 fscanf(f, "%lld", &size);
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100160 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
161 printf("Converting %s to memory mappable structures\n", file_name);
Marc Kupietzf0809762016-02-26 10:13:47 +0100162 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
163 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
164 if (M == NULL) {
165 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
166 return -1;
167 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200168 if(strstr(file_name, ".txt")) {
169 for (b = 0; b < words; b++) {
170 a = 0;
171 while (1) {
172 vocab[b * max_w + a] = fgetc(f);
173 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
174 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
175 }
176 vocab[b * max_w + a] = 0;
177 len = 0;
178 for (a = 0; a < size; a++) {
179 fscanf(f, "%lf", &val);
180 M[a + b * size] = val;
181 len += val * val;
182 }
183 len = sqrt(len);
184 for (a = 0; a < size; a++) M[a + b * size] /= len;
185 }
186 } else {
187 for (b = 0; b < words; b++) {
188 a = 0;
189 while (1) {
190 vocab[b * max_w + a] = fgetc(f);
191 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
192 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
193 }
194 vocab[b * max_w + a] = 0;
195 fread(&M[b * size], sizeof(float), size, f);
196 len = 0;
197 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
198 len = sqrt(len);
199 for (a = 0; a < size; a++) M[a + b * size] /= len;
200 }
201 }
Marc Kupietz67c20282016-02-26 09:42:00 +0100202 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
203 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
204 fclose(binvecs);
205 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
206 fclose(binwords);
207 }
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100208 }
209 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
210 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
211 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
212 if (M == MAP_FAILED || vocab == MAP_FAILED) {
213 close(binvecs_fd);
214 close(binwords_fd);
215 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
216 exit(-1);
217 }
218 } else {
219 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
220 exit(-1);
Marc Kupietz67c20282016-02-26 09:42:00 +0100221 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200222 fclose(f);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100223
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200224 if(net_name && strlen(net_name) > 0) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100225 if( (net_fd = open(net_name, O_RDONLY)) >= 0) {
226 window = (lseek(net_fd, 0, SEEK_END) - sizeof(float) * words * size) / words / size / sizeof(float) / 2;
227 // lseek(net_fd, sizeof(float) * words * size, SEEK_SET);
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100228 // munmap(M, sizeof(float) * words * size);
229 M2 = mmap(0, sizeof(float) * words * size + sizeof(float) * 2 * window * size * words, PROT_READ, MAP_SHARED, net_fd, 0);
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200230 if (M2 == MAP_FAILED) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100231 close(net_fd);
232 fprintf(stderr, "Cannot mmap %s\n", net_name);
233 exit(-1);
234 }
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100235 syn1neg_window = M2 + words * size;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100236 } else {
237 fprintf(stderr, "Cannot open %s\n", net_name);
238 exit(-1);
239 }
240 fprintf(stderr, "Successfully memmaped %s. Determined window size: %d\n", net_name, window);
241 }
242
243 expTable = (float *) malloc((EXP_TABLE_SIZE + 1) * sizeof(float));
244 for (i = 0; i < EXP_TABLE_SIZE; i++) {
245 expTable[i] = exp((i / (float) EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
246 expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
247 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200248 return 0;
249}
250
Marc Kupietza2e64502016-04-27 09:53:51 +0200251long mergeVectors(char *file_name){
252 FILE *f, *binvecs, *binwords;
253 int binwords_fd, binvecs_fd, net_fd, i;
254 long long a, b, c, d, cn;
255 float len;
256 float *merge_vecs;
257 char *merge_vocab;
258 long long merge_words, merge_size;
259
260 char binvecs_fname[256], binwords_fname[256];
261 strcpy(binwords_fname, file_name);
262 strcat(binwords_fname, ".words");
263 strcpy(binvecs_fname, file_name);
264 strcat(binvecs_fname, ".vecs");
265
266 f = fopen(file_name, "rb");
267 if (f == NULL) {
268 printf("Input file %s not found\n", file_name);
269 exit -1;
270 }
271 fscanf(f, "%lld", &merge_words);
272 fscanf(f, "%lld", &merge_size);
273 if(merge_size != size){
274 fprintf(stderr, "vectors must have the same length\n");
275 exit(-1);
276 }
277 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
278 merge_vecs = malloc(sizeof(float) * (words + merge_words) * size);
279 merge_vocab = malloc(sizeof(char) * (words + merge_words) * max_w);
280 if (merge_vecs == NULL || merge_vocab == NULL) {
281 close(binvecs_fd);
282 close(binwords_fd);
283 fprintf(stderr, "Cannot reserve memory for %s or %s\n", binwords_fname, binvecs_fname);
284 exit(-1);
285 }
286 read(binvecs_fd, merge_vecs, merge_words * size * sizeof(float));
287 read(binwords_fd, merge_vocab, merge_words * max_w);
288 } else {
289 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
290 exit(-1);
291 }
292 printf("Successfully reallocated memory\nMerging...\n");
293 fflush(stdout);
294 memcpy(merge_vecs + merge_words * size, M, words * size * sizeof(float));
295 memcpy(merge_vocab + merge_words * max_w, vocab, words * max_w);
296 munmap(M, words * size * sizeof(float));
297 munmap(vocab, words * max_w);
298 M = merge_vecs;
299 vocab = merge_vocab;
300 merged_end = merge_words;
301 words += merge_words;
302 fclose(f);
303 printf("merged_end: %lld, words: %lld\n", merged_end, words);
304 return((long) merged_end);
305}
306
Marc Kupietz271e2a42016-03-22 11:37:43 +0100307void *getCollocators(knnpars *pars) {
308 int N = pars->N;
309 int cc = pars->wl->wordi[0];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100310 knn *nbs = NULL;
311 long window_layer_size = size * window * 2;
312 long a, b, c, d, e, window_offset, target, max_target=0, maxmax_target;
313 float f, max_f, maxmax_f;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100314 float *target_sums, *bestf, *bestn, worstbest, wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100315 long long *besti, *bestp;
Marc Kupietzd5642582016-03-19 22:23:13 +0100316
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200317 if(M2 == NULL || cc == -1)
Marc Kupietzd5642582016-03-19 22:23:13 +0100318 return NULL;
319
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100320 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
321 besti = malloc(N * sizeof(long long));
322 bestp = malloc(N * sizeof(long long));
323 bestf = malloc(N * sizeof(float));
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100324 bestn = malloc(N * sizeof(float));
325
Marc Kupietz271e2a42016-03-22 11:37:43 +0100326 worstbest = MIN_RESP;
327
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100328 for (b = 0; b < words; b++)
329 target_sums[b]=0;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100330 for (b = 0; b < N; b++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100331 besti[b] = -1;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100332 bestn[b] = 1;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100333 bestf[b] = worstbest;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100334 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100335
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100336 d = cc;
337 maxmax_f = -1;
338 maxmax_target = 0;
339
Marc Kupietz271e2a42016-03-22 11:37:43 +0100340 for (a = pars->from; a < pars->upto; a++) {
341 if(a >= window)
342 a++;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100343 wpos_sum = 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100344 printf("window pos: %ld\n", a);
345 if (a != window) {
346 max_f = -1;
347 window_offset = a * size;
348 if (a > window)
349 window_offset -= size;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100350 for(target = 0; target < words; target ++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100351 if(target == d)
352 continue;
353 f = 0;
354 for (c = 0; c < size; c++)
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100355 f += M2[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100356 if (f < -MAX_EXP)
357 continue;
358 else if (f > MAX_EXP)
359 continue;
360 else
361 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100362 wpos_sum += f;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100363
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100364 target_sums[target] += f;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100365 if(f > worstbest) {
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100366 for (b = 0; b < N; b++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100367 if (f > bestf[b]) {
Marc Kupietz33679a32016-03-22 08:49:39 +0100368 memmove(bestf + b + 1, bestf + b, (N - b -1) * sizeof(float));
369 memmove(besti + b + 1, besti + b, (N - b -1) * sizeof(long long));
370 memmove(bestp + b + 1, bestp + b, (N - b -1) * sizeof(long long));
371 bestf[b] = f;
372 besti[b] = target;
373 bestp[b] = window-a;
374 break;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100375 }
376 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100377 if(b == N - 1)
378 worstbest = bestf[N-1];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100379 }
380 }
381 printf("%d %.2f\n", max_target, max_f);
382 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
383 if(max_f > maxmax_f) {
384 maxmax_f = max_f;
385 maxmax_target = max_target;
386 }
Marc Kupietz33679a32016-03-22 08:49:39 +0100387 for (b = 0; b < N; b++)
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100388 if(bestp[b] == window-a)
389 bestn[b] = bestf[b] / wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100390 } else {
391 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
392 }
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100393
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100394 }
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100395 for (b = 0; b < words; b++)
396 pars->target_sums[b] += (target_sums[b] / wpos_sum ) / (window * 2);
397 free(target_sums);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100398 for(b=0; b<N && besti[b] >= 0; b++) // THIS LOOP IS NEEDED (b...)
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100399 printf("%s %.2f %d * ", &vocab[besti[b]*max_w], bestf[b], bestp[b]);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100400 printf("\n");
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100401 nbs = malloc(sizeof(knn));
402 nbs->index = besti;
403 nbs->dist = bestf;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100404 nbs->norm = bestn;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100405 nbs->pos = bestp;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100406 nbs->length = b-1;
407 pthread_exit(nbs);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100408}
409
Marc Kupietza2e64502016-04-27 09:53:51 +0200410wordlist *getTargetWords(char *st1, int search_backw) {
Marc Kupietz48c29682016-03-19 11:30:43 +0100411 wordlist *wl = malloc(sizeof(wordlist));
412 char st[100][max_size], sep[100];
413 long a, b=0, c=0, cn=0;
Marc Kupietza2e64502016-04-27 09:53:51 +0200414 int unmerged;
415
Marc Kupietzdc22b982015-10-09 09:19:34 +0200416 while (1) {
417 st[cn][b] = st1[c];
418 b++;
419 c++;
420 st[cn][b] = 0;
421 if (st1[c] == 0) break;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100422 if (st1[c] == ' ' || st1[c] == '-') {
423 sep[cn++] = st1[c];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200424 b = 0;
425 c++;
426 }
427 }
428 cn++;
429 for (a = 0; a < cn; a++) {
Marc Kupietza2e64502016-04-27 09:53:51 +0200430 if(search_backw) {
431 for (b = words - 1; b >= 0; b--) if (!strcmp(&vocab[b * max_w], st[a])) break;
432 } else {
433 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
434 }
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100435 if (b == words) b = -1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100436 wl->wordi[a] = b;
437 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], wl->wordi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200438 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100439 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100440 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200441 break;
442 }
443 }
Marc Kupietz48c29682016-03-19 11:30:43 +0100444 wl->length=cn;
445 return(wl);
446}
447
448void *_get_neighbours(knnpars *pars) {
449 char *st1 = pars->token;
450 int N = pars->N;
451 long from = pars -> from;
452 unsigned long upto = pars -> upto;
453 char file_name[max_size], st[100][max_size], *sep;
454 float dist, len, *bestd, vec[max_size];
455 long long a, b, c, d, cn, *bi, *besti;
456 char ch;
457 knn *nbs = NULL;
458 wordlist *wl = pars->wl;
459
460 besti = malloc(N * sizeof(long long));
461 bestd = malloc(N * sizeof(float));
462
463 float worstbest=-1;
464
465 for (a = 0; a < N; a++) bestd[a] = 0;
466 a = 0;
467 bi = wl->wordi;
468 cn = wl->length;
469 sep = wl->sep;
470 b = bi[0];
471 c = 0;
Marc Kupietz000ad862016-02-26 14:59:12 +0100472 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100473 N = 0;
474 goto end;
475 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200476 for (a = 0; a < size; a++) vec[a] = 0;
477 for (b = 0; b < cn; b++) {
478 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100479 if(b>0 && sep[b-1] == '-')
480 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
481 else
482 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200483 }
484 len = 0;
485 for (a = 0; a < size; a++) len += vec[a] * vec[a];
486 len = sqrt(len);
487 for (a = 0; a < size; a++) vec[a] /= len;
488 for (a = 0; a < N; a++) bestd[a] = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100489 for (c = from; c < upto; c++) {
Marc Kupietzdc22b982015-10-09 09:19:34 +0200490 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100491// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100492// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
493// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200494 dist = 0;
495 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100496 if(dist > worstbest) {
497 for (a = 0; a < N; a++) {
498 if (dist > bestd[a]) {
Marc Kupietz33679a32016-03-22 08:49:39 +0100499 memmove(bestd + a + 1, bestd + a, (N - a -1) * sizeof(float));
500 memmove(besti + a + 1, besti + a, (N - a -1) * sizeof(long long));
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100501 bestd[a] = dist;
502 besti[a] = c;
503 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200504 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200505 }
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100506 worstbest = bestd[N-1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200507 }
508 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100509
Marc Kupietz000ad862016-02-26 14:59:12 +0100510 nbs = malloc(sizeof(knn));
511 nbs->index = besti;
512 nbs->dist = bestd;
513 nbs->length = N;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100514end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100515 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200516}
517
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100518
Marc Kupietza2e64502016-04-27 09:53:51 +0200519SV *get_neighbours(char *st1, int N, int sort_by, int search_backw) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100520 HV *result = newHV();
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100521 float *target_sums, bestd[MAX_NEIGHBOURS], bestn[MAX_NEIGHBOURS], bests[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietz50485ba2016-03-23 09:13:14 +0100522 long besti[MAX_NEIGHBOURS], bestp[MAX_NEIGHBOURS], a, b, c, d, slice;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100523 knn *para_nbs[MAX_THREADS];
524 knn *syn_nbs[MAX_THREADS];
Marc Kupietz000ad862016-02-26 14:59:12 +0100525 knnpars pars[MAX_THREADS];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100526 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
Marc Kupietz48c29682016-03-19 11:30:43 +0100527 wordlist *wl;
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200528 int syn_threads = (M2? window * 2 : 0);
529 int para_threads = num_threads - syn_threads;
Marc Kupietz48c29682016-03-19 11:30:43 +0100530
Marc Kupietz000ad862016-02-26 14:59:12 +0100531 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
532
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200533 slice = words / para_threads;
534
Marc Kupietza2e64502016-04-27 09:53:51 +0200535 wl = getTargetWords(st1, search_backw);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100536 if(wl->length < 1)
537 goto end;
Marc Kupietz48c29682016-03-19 11:30:43 +0100538
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100539 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
540 for(a = 0; a < words; a++)
541 target_sums[a] = 0;
542
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200543 printf("Starting %d threads\n", para_threads);
544 fflush(stdout);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100545 for(a=0; a < para_threads; a++) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100546 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100547 pars[a].wl = wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100548 pars[a].N = N;
549 pars[a].from = a*slice;
550 pars[a].upto = ((a+1)*slice > words? words:(a+1)*slice);
551 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
552 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200553 if(M2) {
554 for(a=0; a < syn_threads; a++) {
555 pars[a + para_threads].target_sums = target_sums;
556 pars[a + para_threads].wl = wl;
557 pars[a + para_threads].N = N;
558 pars[a + para_threads].from = a;
559 pars[a + para_threads].upto = a+1;
560 pthread_create(&pt[a + para_threads], NULL, getCollocators, (void *) &pars[a + para_threads]);
561 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100562 }
563 printf("Waiting for para threads to join\n");
564 fflush(stdout);
565 for (a = 0; a < para_threads; a++) pthread_join(pt[a], &para_nbs[a]);
566 printf("Para threads joint\n");
567 fflush(stdout);
Marc Kupietz000ad862016-02-26 14:59:12 +0100568
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200569 /* if(!syn_nbs[0]) */
570 /* goto end; */
Marc Kupietz000ad862016-02-26 14:59:12 +0100571
572 for(b=0; b < N; b++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100573 besti[b] = para_nbs[0]->index[b];
574 bestd[b] = para_nbs[0]->dist[b];
Marc Kupietz000ad862016-02-26 14:59:12 +0100575 }
576
Marc Kupietz271e2a42016-03-22 11:37:43 +0100577 for(a=1; a < para_threads; a++) {
578 for(b=0; b < para_nbs[a]->length && para_nbs[a]->index[b] >= 0; b++) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100579 for(c=0; c < N; c++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100580 if(para_nbs[a]->dist[b] > bestd[c]) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100581 for(d=N-1; d>c; d--) {
582 bestd[d] = bestd[d-1];
583 besti[d] = besti[d-1];
584 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100585 besti[c] = para_nbs[a]->index[b];
586 bestd[c] = para_nbs[a]->dist[b];
Marc Kupietz000ad862016-02-26 14:59:12 +0100587 break;
588 }
589 }
590 }
591 }
592
Marc Kupietz271e2a42016-03-22 11:37:43 +0100593 AV* array = newAV();
594 for (a = 0; a < N; a++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100595 HV* hash = newHV();
Marc Kupietz50485ba2016-03-23 09:13:14 +0100596 SV* word = newSVpvf(&vocab[besti[a] * max_w], 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100597 if(latin_enc == 0) SvUTF8_on(word);
598 hv_store(hash, "word", strlen("word"), word , 0);
599 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
600 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
601 AV *vector = newAV();
602 for (b = 0; b < size; b++) {
603 av_push(vector, newSVnv(M[b + besti[a] * size]));
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100604 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100605 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
606 av_push(array, newRV_noinc((SV*)hash));
607 }
608 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
609
Marc Kupietz50485ba2016-03-23 09:13:14 +0100610 for(b=0; b < MAX_NEIGHBOURS; b++) {
611 besti[b] = -1L;
612 bestd[b] = 0;
613 bestn[b] = 0;
614 bestp[b] = 0;
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100615 bests[b] = 0;
Marc Kupietz50485ba2016-03-23 09:13:14 +0100616 }
617
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200618 if (M2) {
619 printf("Waiting for syn threads to join\n");
620 fflush(stdout);
621 for (a = 0; a < syn_threads; a++) pthread_join(pt[a+para_threads], &syn_nbs[a]);
622 printf("syn threads joint\n");
623 fflush(stdout);
Marc Kupietz50485ba2016-03-23 09:13:14 +0100624
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200625 for(b=0; b < syn_nbs[0]->length; b++) {
626 besti[b] = syn_nbs[0]->index[b];
627 bestd[b] = syn_nbs[0]->dist[b];
628 bestn[b] = syn_nbs[0]->norm[b];
629 bestp[b] = syn_nbs[0]->pos[b];
630 bests[b] = target_sums[syn_nbs[0]->index[b]];
631 }
632
633 if(sort_by != 1) { // sort by responsiveness
634 for(a=1; a < syn_threads; a++) {
635 for(b=0; b < syn_nbs[a]->length; b++) {
636 for(c=0; c < MAX_NEIGHBOURS; c++) {
637 if(syn_nbs[a]->dist[b] > bestd[c]) {
638 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
639 bestd[d] = bestd[d-1];
640 besti[d] = besti[d-1];
641 bestn[d] = bestn[d-1];
642 bestp[d] = bestp[d-1];
643 }
644 besti[c] = syn_nbs[a]->index[b];
645 bestd[c] = syn_nbs[a]->dist[b];
646 bestn[c] = syn_nbs[a]->norm[b];
647 bestp[c] = syn_nbs[a]->pos[b];
648 break;
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100649 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200650 }
651 }
652 }
653 } else { // sort by mean p
654 for(a=1; a < syn_threads; a++) {
655 for(b=0; b < syn_nbs[a]->length; b++) {
656 for(c=0; c < MAX_NEIGHBOURS; c++) {
657 if(target_sums[syn_nbs[a]->index[b]] > bests[c]) {
658 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
659 bestd[d] = bestd[d-1];
660 besti[d] = besti[d-1];
661 bestn[d] = bestn[d-1];
662 bestp[d] = bestp[d-1];
663 bests[d] = bests[d-1];
664 }
665 besti[c] = syn_nbs[a]->index[b];
666 bestd[c] = syn_nbs[a]->dist[b];
667 bestn[c] = syn_nbs[a]->norm[b];
668 bestp[c] = syn_nbs[a]->pos[b];
669 bests[c] = target_sums[syn_nbs[a]->index[b]];
670 break;
671 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100672 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100673 }
674 }
675 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200676 array = newAV();
677 for (a = 0; a < MAX_NEIGHBOURS && besti[a] >= 0; a++) {
678 HV* hash = newHV();
679 SV* word = newSVpvf(&vocab[besti[a] * max_w], 0);
680 if(latin_enc == 0) SvUTF8_on(word);
681 hv_store(hash, "word", strlen("word"), word , 0);
682 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
683 hv_store(hash, "norm", strlen("norm"), newSVnv(bestn[a]), 0);
684 hv_store(hash, "sum", strlen("sum"), newSVnv(target_sums[besti[a]]), 0);
685 hv_store(hash, "pos", strlen("pos"), newSVnv(bestp[a]), 0);
686 av_push(array, newRV_noinc((SV*)hash));
Marc Kupietz271e2a42016-03-22 11:37:43 +0100687 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200688 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100689 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100690end:
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100691 return newRV_noinc((SV*)result);
Marc Kupietz000ad862016-02-26 14:59:12 +0100692}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100693
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200694int dump_vecs(char *fname) {
695 long i, j;
696 FILE *f;
697 /* if(words>200000) */
698 /* words=200000; */
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100699
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200700 if((f=fopen(fname, "w")) == NULL) {
701 fprintf(stderr, "cannot open %s for writing\n", fname);
702 return(-1);
703 }
704 fprintf(f, "%lld %lld\n", words, size);
705 for (i=0; i < words; i++) {
706 fprintf(f, "%s ", &vocab[i * max_w]);
707 for(j=0; j < size - 1; j++)
708 fprintf(f, "%f ", M[i*size + j]);
709 fprintf(f, "%f\n", M[i*size + j]);
710 }
711 fclose(f);
712 return(0);
713}
Marc Kupietzdc22b982015-10-09 09:19:34 +0200714__DATA__
715
716@@ index.html.ep
717<!DOCTYPE html>
718<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100719<head>
720 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100721 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100722 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100723 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
724 <script>
725 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100726 $( document ).tooltip({
727 content: function() {
728 return $(this).attr('title');
729 }}
730 )
731 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100732 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100733 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
734 <script src="http://klinux10/word2vec/tsne.js"></script>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100735 <script src="http://klinux10/word2vec/som.js"></script>
Marc Kupietzc5990da2016-02-26 08:47:12 +0100736 <script src="http://klinux10/word2vec/labeler.js"></script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100737<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100738body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100739 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100740 font-size: 11pt;
741}
742
743.ui-tooltip-content {
744 font-size: 9pt;
Marc Kupietza2e64502016-04-27 09:53:51 +0200745 color: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100746}
Marc Kupietz5f780672016-02-25 17:15:54 +0100747
748svg > .ui-tooltip-content {
Marc Kupietzb1029362016-02-27 21:38:55 +0100749 font-size: 8pt;
Marc Kupietza2e64502016-04-27 09:53:51 +0200750 color: #222222;
751}
752
753a.merged {
754 color: green;
755 fill: green;
756}
757
758a.marked {
759 color: orange;
760 fill: orange;
761}
762
763a.target {
764 color: red;
765 fill: red;
Marc Kupietz5f780672016-02-25 17:15:54 +0100766}
767
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100768#collocators {
769 margin-bottom: 15px;
770}
771
Marc Kupietzc4893362016-02-25 08:04:46 +0100772#wrapper {
773 width: 100%;
774// border: 1px solid red;
775 overflow: hidden; /* will contain if #first is longer than #second */
776}
777#first {
Marc Kupietzb1029362016-02-27 21:38:55 +0100778 margin-right: 20px;
779 float: left;
780 // border: 1px solid green;
Marc Kupietzc4893362016-02-25 08:04:46 +0100781}
782#second {
783 border: 1px solid #333;
784 overflow: hidden; /* if you don't want #second to wrap below #first */
785}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100786#som2 svg {
787 border: 1px solid #333;
788}
789
Marc Kupietz4aa62172016-02-25 10:39:27 +0100790#cost {
Marc Kupietzb1029362016-02-27 21:38:55 +0100791 font-size: 8pt;
792 color: #222222;
793 margin-top: 4px;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100794 margin-bottom: 12px;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100795}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100796
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100797#sominfo1, #sominfo {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100798 font-size: 8pt;
799 color: #222222;
800 margin-top: 0px;
801}
802
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100803#somcolor1, #somcolor2, #somcolor3 {
804 display: inline-block;
805 height: 10px;
806 width: 10px;
807}
808
Marc Kupietzd7aea722016-03-02 11:59:12 +0100809#third {
810 border: 1px solid #333;
811}
812
Marc Kupietzc4893362016-02-25 08:04:46 +0100813</style>
814<script>
815
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100816var opt = {epsilon: <%= $epsilon %>, perplexity: <%= $perplexity %>},
Marc Kupietz9fca1732016-02-29 09:07:04 +0100817 mapWidth = 800, // width map
818 mapHeight = 800,
819 jitterRadius = 7;
820
Marc Kupietzc4893362016-02-25 08:04:46 +0100821var T = new tsnejs.tSNE(opt); // create a tSNE instance
822
823var Y;
824
825var data;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100826var labeler;
Marc Kupietzc4893362016-02-25 08:04:46 +0100827
Marc Kupietzc5990da2016-02-26 08:47:12 +0100828
829function applyJitter() {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100830 svg.selectAll('.tsnet')
Marc Kupietzc5990da2016-02-26 08:47:12 +0100831 .data(labels)
832 .transition()
833 .duration(50)
834 .attr("transform", function(d, i) {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100835 T.Y[i][0] = (d.x - mapWidth/2 - tx)/ss/20;
836 T.Y[i][1] = (d.y - mapHeight/2 - ty)/ss/20;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100837 return "translate(" +
838 (d.x) + "," +
839 (d.y) + ")";
840 });
841}
842
Marc Kupietzc4893362016-02-25 08:04:46 +0100843function updateEmbedding() {
844 var Y = T.getSolution();
Marc Kupietzd7aea722016-03-02 11:59:12 +0100845 svg.selectAll('.tsnet')
Marc Kupietz9fca1732016-02-29 09:07:04 +0100846 .data(data.words)
847 .attr("transform", function(d, i) {
848 return "translate(" +
849 ((Y[i][0]*20*ss + tx) + mapWidth/2) + "," +
850 ((Y[i][1]*20*ss + ty) + mapHeight/2) + ")"; });
Marc Kupietzc4893362016-02-25 08:04:46 +0100851}
852
853var svg;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100854var labels = [];
855var anchor_array = [];
856var text;
857
Marc Kupietzc4893362016-02-25 08:04:46 +0100858function drawEmbedding() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100859 $("#embed").empty();
860 var div = d3.select("#embed");
861
862 // get min and max in each column of Y
863 var Y = T.Y;
864
865 svg = div.append("svg") // svg is global
866 .attr("width", mapWidth)
867 .attr("height", mapHeight);
868
869 var g = svg.selectAll(".b")
870 .data(data.words)
871 .enter().append("g")
Marc Kupietzd7aea722016-03-02 11:59:12 +0100872 .attr("class", "tsnet");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100873
874 g.append("a")
875 .attr("xlink:href", function(word) {return "/?word="+word;})
Marc Kupietza2e64502016-04-27 09:53:51 +0200876 .attr("class", function(d, i) {
877 if(data.target.indexOf(" "+d+" ") >= 0) {
878 return "target";
879 } else if(data.mergedEnd > 0 && data.ranks[i] < data.mergedEnd) {
880 return "merged";
881 } else {
882 return ""
883 }
884 })
Marc Kupietz9fca1732016-02-29 09:07:04 +0100885 .attr("title", function(d, i) {
Marc Kupietza2e64502016-04-27 09:53:51 +0200886 if(data.mergedEnd > 0) {
887 if(data.ranks[i] >= data.mergedEnd) {
888 return "rank: "+i +" "+"freq. rank: "+(data.ranks[i]).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
889 } else {
890 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " (merged vocab)";
891 }
892 } else {
893 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
894 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100895 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100896 .append("text")
Marc Kupietz9fca1732016-02-29 09:07:04 +0100897 .attr("text-anchor", "top")
898 .attr("font-size", 12)
Marc Kupietz9fca1732016-02-29 09:07:04 +0100899 .text(function(d) { return d; });
900
901 var zoomListener = d3.behavior.zoom()
902 .scaleExtent([0.1, 10])
903 .center([0,0])
904 .on("zoom", zoomHandler);
905 zoomListener(svg);
906}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100907
Marc Kupietz9fca1732016-02-29 09:07:04 +0100908var tx=0, ty=0;
909var ss=1;
910var iter_id=-1;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100911
Marc Kupietz9fca1732016-02-29 09:07:04 +0100912function zoomHandler() {
913 tx = d3.event.translate[0];
914 ty = d3.event.translate[1];
915 ss = d3.event.scale;
916 updateEmbedding();
917}
918
919var stepnum = 0;
920
921function stopStep() {
922 clearInterval(iter_id);
923 text = svg.selectAll("text");
924
925 // jitter function needs different data and co-ordinate representation
926 labels = d3.range(data.words.length).map(function(i) {
927 var x = (T.Y[i][0]*20*ss + tx) + mapWidth/2;
928 var y = (T.Y[i][1]*20*ss + ty) + mapHeight/2;
929 anchor_array.push({x: x, y: y, r: jitterRadius});
930 return {
931 x: x,
932 y: y,
933 name: data.words[i]
934 };
935 });
936
937 // get the actual label bounding boxes for the jitter function
938 var index = 0;
939 text.each(function() {
940 labels[index].width = this.getBBox().width;
941 labels[index].height = this.getBBox().height;
942 index += 1;
943 });
Marc Kupietzc5990da2016-02-26 08:47:12 +0100944
945
946// setTimeout(updateEmbedding, 1);
947// setTimeout(
Marc Kupietz9fca1732016-02-29 09:07:04 +0100948 labeler = d3.labeler()
949 .label(labels)
950 .anchor(anchor_array)
951 .width(mapWidth)
952 .height(mapHeight)
953 .update(applyJitter);
954 // .start(1000);
Marc Kupietzc5990da2016-02-26 08:47:12 +0100955
Marc Kupietz9fca1732016-02-29 09:07:04 +0100956 iter_id = setInterval(jitterStep, 1);
957}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100958
Marc Kupietz9fca1732016-02-29 09:07:04 +0100959var jitter_i=0;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100960
961function jitterStep() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100962 if(jitter_i++ > 100) {
963 clearInterval(iter_id);
964 } else {
965 labeler.start2(10);
966 applyJitter();
967 }
Marc Kupietzc5990da2016-02-26 08:47:12 +0100968}
Marc Kupietzb1029362016-02-27 21:38:55 +0100969
970var last_cost=1000;
971
Marc Kupietz9fca1732016-02-29 09:07:04 +0100972function step() {
973 var i = T.iter;
974
975 if(i > <%= $no_iterations %>) {
976 stopStep();
977 } else {
978 var cost = Math.round(T.step() * 100000) / 100000; // do a few steps
979 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(5));
980 if(i % 250 == 0 && cost >= last_cost) {
981 stopStep();
982 } else {
983 last_cost = cost;
984 updateEmbedding();
985 }
986 }
987}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100988
Marc Kupietz9fca1732016-02-29 09:07:04 +0100989function showMap(j) {
990 data=j;
991 T.iter=0;
992 T.initDataRaw(data.vecs); // init embedding
993 drawEmbedding(); // draw initial embedding
994
995 if(iter_id >= 0) {
996 clearInterval(iter_id);
997 }
998 //T.debugGrad();
999 iter_id = setInterval(step, 1);
Marc Kupietzd7aea722016-03-02 11:59:12 +01001000 if(<%= $show_som %>) {
1001 makeSOM(j, <%= $no_iterations %>);
1002 }
Marc Kupietz9fca1732016-02-29 09:07:04 +01001003}
Marc Kupietza350bce2016-02-25 09:34:25 +01001004
Marc Kupietzc4893362016-02-25 08:04:46 +01001005</script>
1006</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +02001007<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +01001008 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +01001009 word(s):
1010 <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.">
Marc Kupietza2e64502016-04-27 09:53:51 +02001011 % if($mergedEnd > 0) {
1012 backw. <input type="checkbox" name="sbf" value="1" <%= ($searchBaseVocabFirst ? "checked" : "") %> title="If checkecked base vocabulary will be searched first. Otherwise merged vocabulray will be searched first.">
1013 % }
Marc Kupietz44bee3c2016-02-25 16:26:29 +01001014 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
Marc Kupietzd7aea722016-03-02 11:59:12 +01001015 max. iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
1016 SOM <input type="checkbox" name="som" value="1" <%= ($show_som ? "checked" : "") %>>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001017 % if($collocators) {
Marc Kupietz6d9a6782016-03-23 17:25:25 +01001018 <span> </span>sort collocators by
1019 <select name="sort">
1020 <option value="0" <%= ($sort!=1? "selected":"") %>>responsiveness</option>
1021 <option value="1" <%= ($sort==1? "selected":"") %>>mean p</option>
1022 </select>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001023 % }
Marc Kupietzd7aea722016-03-02 11:59:12 +01001024 <span> </span><input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +01001025 </form>
1026 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +01001027 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +01001028 <div id="wrapper">
1029 <table id="first">
1030 <tr>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001031 <th align="right">#</th><th align="right">cos</th><th align="left">paradigmatic</th>
1032 % if($collocators) {
1033 <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 title="Probability of the collocator at window location @."align="right">p(c<sub><small>@</small></sub>)</th><th align="right"p(c<sub><small>@</small></sub>)/|w|</th><th align="left">syntagmatic</th>
1034 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001035 </tr>
Marc Kupietz5f780672016-02-25 17:15:54 +01001036 % my $j=0; my @words; my @vecs; my @ranks; for my $list (@$lists) {
Marc Kupietzc47b3902016-04-22 10:29:44 +02001037 % my $i=0; while($list) {
Marc Kupietz50485ba2016-03-23 09:13:14 +01001038 % my $item = (@$list)[$i];
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001039 % my $c = ($collocators? (@$collocators)[$i] : 0);
Marc Kupietz50485ba2016-03-23 09:13:14 +01001040 % last if(!$c && !$item);
Marc Kupietz4aa62172016-02-25 10:39:27 +01001041 <tr>
1042 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +01001043 <%= ++$i %>.
Marc Kupietz4aa62172016-02-25 10:39:27 +01001044 </td>
Marc Kupietz50485ba2016-03-23 09:13:14 +01001045 % if($item) {
1046 % if(!grep{$_ eq $item->{word}} @words) {
1047 % push @vecs, $item->{vector};
1048 % push @words, $item->{word};
1049 % push @ranks, $item->{rank};
1050 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001051 <td align="right">
1052 <%= sprintf("%.3f", $item->{dist}) %>
1053 </td>
Marc Kupietzd5642582016-03-19 22:23:13 +01001054 <td>
Marc Kupietza2e64502016-04-27 09:53:51 +02001055 % my $class = "";
1056 % my $r = $item->{rank};
1057 % if($r < $mergedEnd) {
1058 % $class="merged";
1059 % $r .= " (merged vocab)";
1060 % } elsif($mergedEnd!=0 && $r > $mergedEnd) {
1061 % $r -= $mergedEnd;
1062 % }
1063 <a class="<%= $class %>" title="freq. rank: <%= $r %>" href="/?word=<%= $item->{word} %>"><%= $item->{word} %></a>
Marc Kupietzd5642582016-03-19 22:23:13 +01001064 </td>
Marc Kupietz50485ba2016-03-23 09:13:14 +01001065 % } else {
1066 <td colspan="2"/>
1067 % }
Marc Kupietz271e2a42016-03-22 11:37:43 +01001068 % if($c) {
Marc Kupietz5f780672016-02-25 17:15:54 +01001069 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +01001070 <%= $c->{pos} %>:
1071 </td>
1072 <td align="right">
1073 <%= sprintf("%.3f", $c->{dist}) %>
1074 </td>
Marc Kupietzb864ccf2016-03-21 22:40:03 +01001075 <td align="right">
1076 <%= sprintf("%.3e", $c->{norm}) %>
1077 </td>
Marc Kupietzce3d4c62016-03-23 16:11:25 +01001078 <td align="right">
1079 <%= sprintf("%.3e", $c->{sum}) %>
1080 </td>
Marc Kupietzd5642582016-03-19 22:23:13 +01001081 <td align="left">
1082 <a href="/?word=<%= $c->{word} %>">
1083 <%= $c->{word} %>
Marc Kupietz5f780672016-02-25 17:15:54 +01001084 </td>
Marc Kupietz271e2a42016-03-22 11:37:43 +01001085 % } else {
Marc Kupietzce3d4c62016-03-23 16:11:25 +01001086 <td colspan="5"/>
Marc Kupietz271e2a42016-03-22 11:37:43 +01001087 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001088 </tr>
1089 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +01001090 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001091 </table>
1092 <script>
1093 % use Mojo::ByteStream 'b';
1094 $(window).load(function() {
Marc Kupietza2e64502016-04-27 09:53:51 +02001095 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", mergedEnd=> $mergedEnd, words => \@words, vecs => \@vecs, ranks => \@ranks})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +01001096 });
1097 </script>
1098 % }
1099 <div id="second" style="width:800px; height:800px; font-family: arial;">
1100 <div id="embed">
1101 </div>
Marc Kupietz4aa62172016-02-25 10:39:27 +01001102 </div>
Marc Kupietzb1029362016-02-27 21:38:55 +01001103 <div id="cost"></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +01001104 % if($show_som) {
1105 <div id="som2">
1106 </div>
Marc Kupietz6c1ca442016-03-03 09:35:18 +01001107 <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 +01001108 <div id="sominfo">SOM iteration <span id="iterations">0</span></div>
1109 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001110 </div>
Marc Kupietz793413b2016-04-02 21:48:57 +02001111 % if($training_args) {
1112 <p>
1113 Word vector model trained with <a href="https://code.google.com/p/word2vec/">word2vec</a> using the following parameters: <pre><%= $training_args %></pre>
1114 </p>
1115 % }
1116 </body>
Marc Kupietzdc22b982015-10-09 09:19:34 +02001117</html>
1118