blob: 381e81bc3285d40743fada8b23cc7315a41d1d64 [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 Kupietz6ed81872016-04-27 14:04:04 +020016our $opt_M;
Marc Kupietz43ee87e2016-04-25 10:50:08 +020017our $opt_n = '';
18our $opt_d;
Marc Kupietza5b90152016-03-15 17:39:19 +010019
Marc Kupietz6ed81872016-04-27 14:04:04 +020020my %marked;
Marc Kupietz793413b2016-04-02 21:48:57 +020021my $training_args="";
Marc Kupietza2e64502016-04-27 09:53:51 +020022my $mergedEnd=0;
Marc Kupietz793413b2016-04-02 21:48:57 +020023
Marc Kupietz6ed81872016-04-27 14:04:04 +020024getopt('d:il:p:m:M:');
25
26if($opt_M) {
Marc Kupietzed930212016-04-27 15:42:38 +020027 open my $handle, '<:encoding(UTF-8)', $opt_M
28 or die "Can't open '$opt_M' for reading: $!";
29 while(<$handle>) {
Marc Kupietz6ed81872016-04-27 14:04:04 +020030 foreach my $mw (split /\s+/) {
31 $marked{$mw}=1
32 }
33 }
Marc Kupietzed930212016-04-27 15:42:38 +020034 close($handle);
Marc Kupietz6ed81872016-04-27 14:04:04 +020035}
Marc Kupietza5b90152016-03-15 17:39:19 +010036
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010037# -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 +010038if(!$ARGV[0]) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010039 init_net("vectors15.bin", $opt_n, ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010040} else {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010041 init_net($ARGV[0], $opt_n, ($opt_i? 1 : 0));
Marc Kupietz793413b2016-04-02 21:48:57 +020042 if(open(FILE, "$ARGV[0].args")) {
43 $training_args = <FILE>;
44 }
45 close(FILE);
Marc Kupietz2cb667e2016-03-10 09:44:12 +010046}
Marc Kupietzdc22b982015-10-09 09:19:34 +020047
Marc Kupietza2e64502016-04-27 09:53:51 +020048if($opt_m) {
49 $mergedEnd = mergeVectors($opt_m);
50}
51
Marc Kupietz6ed81872016-04-27 14:04:04 +020052
Marc Kupietz43ee87e2016-04-25 10:50:08 +020053if($opt_d) { # -d: dump vecs and exit
54 dump_vecs($opt_d);
55 exit;
56}
57
Marc Kupietza5b90152016-03-15 17:39:19 +010058my $daemon = Mojo::Server::Daemon->new(
59 app => app,
60 listen => ['http://'.($opt_l ? $opt_l : '*').":$opt_p"]
61);
62
Marc Kupietzdc22b982015-10-09 09:19:34 +020063get '/' => sub {
64 my $c = shift;
65 my $word=$c->param('word');
Marc Kupietz44bee3c2016-02-25 16:26:29 +010066 my $no_nbs=$c->param('n') || 100;
67 my $no_iterations=$c->param('N') || 2000;
Marc Kupietzd4227392016-03-01 16:45:12 +010068 my $perplexity=$c->param('perplexity') || 20;
Marc Kupietzc4d62f82016-03-01 11:04:24 +010069 my $epsilon=$c->param('epsilon') || 5;
Marc Kupietzd7aea722016-03-02 11:59:12 +010070 my $som=$c->param('som') || 0;
Marc Kupietza2e64502016-04-27 09:53:51 +020071 my $searchBaseVocabFirst=$c->param('sbf') || 0;
Marc Kupietz6d9a6782016-03-23 17:25:25 +010072 my $sort=$c->param('sort') || 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010073 my $res;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010074 my @lists;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010075 my @collocations;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010076 if(defined($word) && $word !~ /^\s*$/) {
77 $c->inactivity_timeout(300);
Marc Kupietz44bee3c2016-02-25 16:26:29 +010078 $word =~ s/\s+/ /g;
79 for my $w (split(' *\| *', $word)) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010080 $c->app->log->debug('Looking for neighbours of '.$w);
Marc Kupietza5b90152016-03-15 17:39:19 +010081 if($opt_i) {
Marc Kupietza2e64502016-04-27 09:53:51 +020082 $res = get_neighbours(encode("iso-8859-1", $w), $no_nbs, $sort, $searchBaseVocabFirst);
Marc Kupietza5b90152016-03-15 17:39:19 +010083 } else {
Marc Kupietza2e64502016-04-27 09:53:51 +020084 $res = get_neighbours($w, $no_nbs, $sort, $searchBaseVocabFirst);
Marc Kupietza5b90152016-03-15 17:39:19 +010085 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +010086 push(@lists, $res->{paradigmatic});
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010087 }
Marc Kupietz247500f2015-10-09 11:29:01 +020088 }
Marc Kupietz000ad862016-02-26 14:59:12 +010089 $word =~ s/ *\| */ | /g;
Marc Kupietz6ed81872016-04-27 14:04:04 +020090 $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, marked=>\%marked, lists=> \@lists, collocators=> $res->{syntagmatic});
Marc Kupietzdc22b982015-10-09 09:19:34 +020091};
92
Marc Kupietza5b90152016-03-15 17:39:19 +010093$daemon->run; # app->start;
Marc Kupietzdc22b982015-10-09 09:19:34 +020094
95exit;
96
97__END__
98
99__C__
100#include <stdio.h>
101#include <string.h>
102#include <math.h>
103#include <malloc.h>
104#include <stdlib.h> //strlen
Marc Kupietzf0809762016-02-26 10:13:47 +0100105#include <sys/mman.h>
Marc Kupietz000ad862016-02-26 14:59:12 +0100106#include <pthread.h>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200107
108#define max_size 2000
109#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100110#define MAX_NEIGHBOURS 1000
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100111#define MAX_WORDS -1
Marc Kupietz000ad862016-02-26 14:59:12 +0100112#define MAX_THREADS 100
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100113#define MAX_CC 50
114#define EXP_TABLE_SIZE 1000
115#define MAX_EXP 6
Marc Kupietz271e2a42016-03-22 11:37:43 +0100116#define MIN_RESP 0.50
Marc Kupietzdc22b982015-10-09 09:19:34 +0200117
118//the thread function
119void *connection_handler(void *);
Marc Kupietz000ad862016-02-26 14:59:12 +0100120
121typedef struct {
122 long long *index;
123 float *dist;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100124 float *norm;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100125 long long *pos;
Marc Kupietz80abb442016-03-23 21:04:08 +0100126 int length;
Marc Kupietz000ad862016-02-26 14:59:12 +0100127} knn;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100128
Marc Kupietz000ad862016-02-26 14:59:12 +0100129typedef struct {
Marc Kupietz48c29682016-03-19 11:30:43 +0100130 long long wordi[MAX_NEIGHBOURS];
131 char sep[MAX_NEIGHBOURS];
132 int length;
133} wordlist;
134
135typedef struct {
136 wordlist *wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100137 char *token;
138 int N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100139 long from;
Marc Kupietz000ad862016-02-26 14:59:12 +0100140 unsigned long upto;
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100141 float *target_sums;
Marc Kupietz000ad862016-02-26 14:59:12 +0100142} knnpars;
143
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200144float *M, *M2=0L, *syn1neg_window, *expTable;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200145char *vocab;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100146
Marc Kupietza2e64502016-04-27 09:53:51 +0200147long long words, size, merged_end;
Marc Kupietz000ad862016-02-26 14:59:12 +0100148int num_threads=20;
Marc Kupietza5b90152016-03-15 17:39:19 +0100149int latin_enc=0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100150int window;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200151
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100152int init_net(char *file_name, char *net_name, int latin) {
Marc Kupietz67c20282016-02-26 09:42:00 +0100153 FILE *f, *binvecs, *binwords;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100154 int binwords_fd, binvecs_fd, net_fd, i;
Marc Kupietz82b02672016-02-26 12:32:25 +0100155 long long a, b, c, d, cn;
156 float len;
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200157 double val;
Marc Kupietz82b02672016-02-26 12:32:25 +0100158
Marc Kupietz67c20282016-02-26 09:42:00 +0100159 char binvecs_fname[256], binwords_fname[256];
160 strcpy(binwords_fname, file_name);
161 strcat(binwords_fname, ".words");
162 strcpy(binvecs_fname, file_name);
163 strcat(binvecs_fname, ".vecs");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200164
Marc Kupietza5b90152016-03-15 17:39:19 +0100165 latin_enc = latin;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200166 f = fopen(file_name, "rb");
167 if (f == NULL) {
168 printf("Input file %s not found\n", file_name);
169 return -1;
170 }
171 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100172 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200173 fscanf(f, "%lld", &size);
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100174 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
175 printf("Converting %s to memory mappable structures\n", file_name);
Marc Kupietzf0809762016-02-26 10:13:47 +0100176 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
177 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
178 if (M == NULL) {
179 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
180 return -1;
181 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200182 if(strstr(file_name, ".txt")) {
183 for (b = 0; b < words; b++) {
184 a = 0;
185 while (1) {
186 vocab[b * max_w + a] = fgetc(f);
187 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
188 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
189 }
190 vocab[b * max_w + a] = 0;
191 len = 0;
192 for (a = 0; a < size; a++) {
193 fscanf(f, "%lf", &val);
194 M[a + b * size] = val;
195 len += val * val;
196 }
197 len = sqrt(len);
198 for (a = 0; a < size; a++) M[a + b * size] /= len;
199 }
200 } else {
201 for (b = 0; b < words; b++) {
202 a = 0;
203 while (1) {
204 vocab[b * max_w + a] = fgetc(f);
205 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
206 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
207 }
208 vocab[b * max_w + a] = 0;
209 fread(&M[b * size], sizeof(float), size, f);
210 len = 0;
211 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
212 len = sqrt(len);
213 for (a = 0; a < size; a++) M[a + b * size] /= len;
214 }
215 }
Marc Kupietz67c20282016-02-26 09:42:00 +0100216 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
217 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
218 fclose(binvecs);
219 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
220 fclose(binwords);
221 }
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100222 }
223 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
224 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
225 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
226 if (M == MAP_FAILED || vocab == MAP_FAILED) {
227 close(binvecs_fd);
228 close(binwords_fd);
229 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
230 exit(-1);
231 }
232 } else {
233 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
234 exit(-1);
Marc Kupietz67c20282016-02-26 09:42:00 +0100235 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200236 fclose(f);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100237
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200238 if(net_name && strlen(net_name) > 0) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100239 if( (net_fd = open(net_name, O_RDONLY)) >= 0) {
240 window = (lseek(net_fd, 0, SEEK_END) - sizeof(float) * words * size) / words / size / sizeof(float) / 2;
241 // lseek(net_fd, sizeof(float) * words * size, SEEK_SET);
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100242 // munmap(M, sizeof(float) * words * size);
243 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 +0200244 if (M2 == MAP_FAILED) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100245 close(net_fd);
246 fprintf(stderr, "Cannot mmap %s\n", net_name);
247 exit(-1);
248 }
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100249 syn1neg_window = M2 + words * size;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100250 } else {
251 fprintf(stderr, "Cannot open %s\n", net_name);
252 exit(-1);
253 }
254 fprintf(stderr, "Successfully memmaped %s. Determined window size: %d\n", net_name, window);
255 }
256
257 expTable = (float *) malloc((EXP_TABLE_SIZE + 1) * sizeof(float));
258 for (i = 0; i < EXP_TABLE_SIZE; i++) {
259 expTable[i] = exp((i / (float) EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
260 expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
261 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200262 return 0;
263}
264
Marc Kupietza2e64502016-04-27 09:53:51 +0200265long mergeVectors(char *file_name){
266 FILE *f, *binvecs, *binwords;
267 int binwords_fd, binvecs_fd, net_fd, i;
268 long long a, b, c, d, cn;
269 float len;
270 float *merge_vecs;
271 char *merge_vocab;
272 long long merge_words, merge_size;
273
274 char binvecs_fname[256], binwords_fname[256];
275 strcpy(binwords_fname, file_name);
276 strcat(binwords_fname, ".words");
277 strcpy(binvecs_fname, file_name);
278 strcat(binvecs_fname, ".vecs");
279
280 f = fopen(file_name, "rb");
281 if (f == NULL) {
282 printf("Input file %s not found\n", file_name);
283 exit -1;
284 }
285 fscanf(f, "%lld", &merge_words);
286 fscanf(f, "%lld", &merge_size);
287 if(merge_size != size){
288 fprintf(stderr, "vectors must have the same length\n");
289 exit(-1);
290 }
291 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
292 merge_vecs = malloc(sizeof(float) * (words + merge_words) * size);
293 merge_vocab = malloc(sizeof(char) * (words + merge_words) * max_w);
294 if (merge_vecs == NULL || merge_vocab == NULL) {
295 close(binvecs_fd);
296 close(binwords_fd);
297 fprintf(stderr, "Cannot reserve memory for %s or %s\n", binwords_fname, binvecs_fname);
298 exit(-1);
299 }
300 read(binvecs_fd, merge_vecs, merge_words * size * sizeof(float));
301 read(binwords_fd, merge_vocab, merge_words * max_w);
302 } else {
303 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
304 exit(-1);
305 }
306 printf("Successfully reallocated memory\nMerging...\n");
307 fflush(stdout);
308 memcpy(merge_vecs + merge_words * size, M, words * size * sizeof(float));
309 memcpy(merge_vocab + merge_words * max_w, vocab, words * max_w);
310 munmap(M, words * size * sizeof(float));
311 munmap(vocab, words * max_w);
312 M = merge_vecs;
313 vocab = merge_vocab;
314 merged_end = merge_words;
315 words += merge_words;
316 fclose(f);
317 printf("merged_end: %lld, words: %lld\n", merged_end, words);
318 return((long) merged_end);
319}
320
Marc Kupietz271e2a42016-03-22 11:37:43 +0100321void *getCollocators(knnpars *pars) {
322 int N = pars->N;
323 int cc = pars->wl->wordi[0];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100324 knn *nbs = NULL;
325 long window_layer_size = size * window * 2;
326 long a, b, c, d, e, window_offset, target, max_target=0, maxmax_target;
327 float f, max_f, maxmax_f;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100328 float *target_sums, *bestf, *bestn, worstbest, wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100329 long long *besti, *bestp;
Marc Kupietzd5642582016-03-19 22:23:13 +0100330
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200331 if(M2 == NULL || cc == -1)
Marc Kupietzd5642582016-03-19 22:23:13 +0100332 return NULL;
333
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100334 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
335 besti = malloc(N * sizeof(long long));
336 bestp = malloc(N * sizeof(long long));
337 bestf = malloc(N * sizeof(float));
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100338 bestn = malloc(N * sizeof(float));
339
Marc Kupietz271e2a42016-03-22 11:37:43 +0100340 worstbest = MIN_RESP;
341
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100342 for (b = 0; b < words; b++)
343 target_sums[b]=0;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100344 for (b = 0; b < N; b++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100345 besti[b] = -1;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100346 bestn[b] = 1;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100347 bestf[b] = worstbest;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100348 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100349
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100350 d = cc;
351 maxmax_f = -1;
352 maxmax_target = 0;
353
Marc Kupietz271e2a42016-03-22 11:37:43 +0100354 for (a = pars->from; a < pars->upto; a++) {
355 if(a >= window)
356 a++;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100357 wpos_sum = 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100358 printf("window pos: %ld\n", a);
359 if (a != window) {
360 max_f = -1;
361 window_offset = a * size;
362 if (a > window)
363 window_offset -= size;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100364 for(target = 0; target < words; target ++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100365 if(target == d)
366 continue;
367 f = 0;
368 for (c = 0; c < size; c++)
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100369 f += M2[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100370 if (f < -MAX_EXP)
371 continue;
372 else if (f > MAX_EXP)
373 continue;
374 else
375 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100376 wpos_sum += f;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100377
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100378 target_sums[target] += f;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100379 if(f > worstbest) {
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100380 for (b = 0; b < N; b++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100381 if (f > bestf[b]) {
Marc Kupietz33679a32016-03-22 08:49:39 +0100382 memmove(bestf + b + 1, bestf + b, (N - b -1) * sizeof(float));
383 memmove(besti + b + 1, besti + b, (N - b -1) * sizeof(long long));
384 memmove(bestp + b + 1, bestp + b, (N - b -1) * sizeof(long long));
385 bestf[b] = f;
386 besti[b] = target;
387 bestp[b] = window-a;
388 break;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100389 }
390 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100391 if(b == N - 1)
392 worstbest = bestf[N-1];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100393 }
394 }
395 printf("%d %.2f\n", max_target, max_f);
396 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
397 if(max_f > maxmax_f) {
398 maxmax_f = max_f;
399 maxmax_target = max_target;
400 }
Marc Kupietz33679a32016-03-22 08:49:39 +0100401 for (b = 0; b < N; b++)
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100402 if(bestp[b] == window-a)
403 bestn[b] = bestf[b] / wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100404 } else {
405 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
406 }
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100407
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100408 }
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100409 for (b = 0; b < words; b++)
410 pars->target_sums[b] += (target_sums[b] / wpos_sum ) / (window * 2);
411 free(target_sums);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100412 for(b=0; b<N && besti[b] >= 0; b++) // THIS LOOP IS NEEDED (b...)
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100413 printf("%s %.2f %d * ", &vocab[besti[b]*max_w], bestf[b], bestp[b]);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100414 printf("\n");
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100415 nbs = malloc(sizeof(knn));
416 nbs->index = besti;
417 nbs->dist = bestf;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100418 nbs->norm = bestn;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100419 nbs->pos = bestp;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100420 nbs->length = b-1;
421 pthread_exit(nbs);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100422}
423
Marc Kupietza2e64502016-04-27 09:53:51 +0200424wordlist *getTargetWords(char *st1, int search_backw) {
Marc Kupietz48c29682016-03-19 11:30:43 +0100425 wordlist *wl = malloc(sizeof(wordlist));
426 char st[100][max_size], sep[100];
427 long a, b=0, c=0, cn=0;
Marc Kupietza2e64502016-04-27 09:53:51 +0200428 int unmerged;
429
Marc Kupietzdc22b982015-10-09 09:19:34 +0200430 while (1) {
431 st[cn][b] = st1[c];
432 b++;
433 c++;
434 st[cn][b] = 0;
435 if (st1[c] == 0) break;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100436 if (st1[c] == ' ' || st1[c] == '-') {
437 sep[cn++] = st1[c];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200438 b = 0;
439 c++;
440 }
441 }
442 cn++;
443 for (a = 0; a < cn; a++) {
Marc Kupietza2e64502016-04-27 09:53:51 +0200444 if(search_backw) {
445 for (b = words - 1; b >= 0; b--) if (!strcmp(&vocab[b * max_w], st[a])) break;
446 } else {
447 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
448 }
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100449 if (b == words) b = -1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100450 wl->wordi[a] = b;
451 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], wl->wordi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200452 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100453 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100454 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200455 break;
456 }
457 }
Marc Kupietz48c29682016-03-19 11:30:43 +0100458 wl->length=cn;
459 return(wl);
460}
461
462void *_get_neighbours(knnpars *pars) {
463 char *st1 = pars->token;
464 int N = pars->N;
465 long from = pars -> from;
466 unsigned long upto = pars -> upto;
467 char file_name[max_size], st[100][max_size], *sep;
468 float dist, len, *bestd, vec[max_size];
469 long long a, b, c, d, cn, *bi, *besti;
470 char ch;
471 knn *nbs = NULL;
472 wordlist *wl = pars->wl;
473
474 besti = malloc(N * sizeof(long long));
475 bestd = malloc(N * sizeof(float));
476
477 float worstbest=-1;
478
479 for (a = 0; a < N; a++) bestd[a] = 0;
480 a = 0;
481 bi = wl->wordi;
482 cn = wl->length;
483 sep = wl->sep;
484 b = bi[0];
485 c = 0;
Marc Kupietz000ad862016-02-26 14:59:12 +0100486 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100487 N = 0;
488 goto end;
489 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200490 for (a = 0; a < size; a++) vec[a] = 0;
491 for (b = 0; b < cn; b++) {
492 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100493 if(b>0 && sep[b-1] == '-')
494 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
495 else
496 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200497 }
498 len = 0;
499 for (a = 0; a < size; a++) len += vec[a] * vec[a];
500 len = sqrt(len);
501 for (a = 0; a < size; a++) vec[a] /= len;
502 for (a = 0; a < N; a++) bestd[a] = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100503 for (c = from; c < upto; c++) {
Marc Kupietzdc22b982015-10-09 09:19:34 +0200504 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100505// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100506// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
507// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200508 dist = 0;
509 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100510 if(dist > worstbest) {
511 for (a = 0; a < N; a++) {
512 if (dist > bestd[a]) {
Marc Kupietz33679a32016-03-22 08:49:39 +0100513 memmove(bestd + a + 1, bestd + a, (N - a -1) * sizeof(float));
514 memmove(besti + a + 1, besti + a, (N - a -1) * sizeof(long long));
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100515 bestd[a] = dist;
516 besti[a] = c;
517 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200518 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200519 }
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100520 worstbest = bestd[N-1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200521 }
522 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100523
Marc Kupietz000ad862016-02-26 14:59:12 +0100524 nbs = malloc(sizeof(knn));
525 nbs->index = besti;
526 nbs->dist = bestd;
527 nbs->length = N;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100528end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100529 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200530}
531
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100532
Marc Kupietza2e64502016-04-27 09:53:51 +0200533SV *get_neighbours(char *st1, int N, int sort_by, int search_backw) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100534 HV *result = newHV();
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100535 float *target_sums, bestd[MAX_NEIGHBOURS], bestn[MAX_NEIGHBOURS], bests[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietz50485ba2016-03-23 09:13:14 +0100536 long besti[MAX_NEIGHBOURS], bestp[MAX_NEIGHBOURS], a, b, c, d, slice;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100537 knn *para_nbs[MAX_THREADS];
538 knn *syn_nbs[MAX_THREADS];
Marc Kupietz000ad862016-02-26 14:59:12 +0100539 knnpars pars[MAX_THREADS];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100540 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
Marc Kupietz48c29682016-03-19 11:30:43 +0100541 wordlist *wl;
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200542 int syn_threads = (M2? window * 2 : 0);
543 int para_threads = num_threads - syn_threads;
Marc Kupietz48c29682016-03-19 11:30:43 +0100544
Marc Kupietz000ad862016-02-26 14:59:12 +0100545 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
546
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200547 slice = words / para_threads;
548
Marc Kupietza2e64502016-04-27 09:53:51 +0200549 wl = getTargetWords(st1, search_backw);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100550 if(wl->length < 1)
551 goto end;
Marc Kupietz48c29682016-03-19 11:30:43 +0100552
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100553 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
554 for(a = 0; a < words; a++)
555 target_sums[a] = 0;
556
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200557 printf("Starting %d threads\n", para_threads);
558 fflush(stdout);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100559 for(a=0; a < para_threads; a++) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100560 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100561 pars[a].wl = wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100562 pars[a].N = N;
563 pars[a].from = a*slice;
564 pars[a].upto = ((a+1)*slice > words? words:(a+1)*slice);
565 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
566 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200567 if(M2) {
568 for(a=0; a < syn_threads; a++) {
569 pars[a + para_threads].target_sums = target_sums;
570 pars[a + para_threads].wl = wl;
571 pars[a + para_threads].N = N;
572 pars[a + para_threads].from = a;
573 pars[a + para_threads].upto = a+1;
574 pthread_create(&pt[a + para_threads], NULL, getCollocators, (void *) &pars[a + para_threads]);
575 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100576 }
577 printf("Waiting for para threads to join\n");
578 fflush(stdout);
579 for (a = 0; a < para_threads; a++) pthread_join(pt[a], &para_nbs[a]);
580 printf("Para threads joint\n");
581 fflush(stdout);
Marc Kupietz000ad862016-02-26 14:59:12 +0100582
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200583 /* if(!syn_nbs[0]) */
584 /* goto end; */
Marc Kupietz000ad862016-02-26 14:59:12 +0100585
586 for(b=0; b < N; b++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100587 besti[b] = para_nbs[0]->index[b];
588 bestd[b] = para_nbs[0]->dist[b];
Marc Kupietz000ad862016-02-26 14:59:12 +0100589 }
590
Marc Kupietz271e2a42016-03-22 11:37:43 +0100591 for(a=1; a < para_threads; a++) {
592 for(b=0; b < para_nbs[a]->length && para_nbs[a]->index[b] >= 0; b++) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100593 for(c=0; c < N; c++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100594 if(para_nbs[a]->dist[b] > bestd[c]) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100595 for(d=N-1; d>c; d--) {
596 bestd[d] = bestd[d-1];
597 besti[d] = besti[d-1];
598 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100599 besti[c] = para_nbs[a]->index[b];
600 bestd[c] = para_nbs[a]->dist[b];
Marc Kupietz000ad862016-02-26 14:59:12 +0100601 break;
602 }
603 }
604 }
605 }
606
Marc Kupietz271e2a42016-03-22 11:37:43 +0100607 AV* array = newAV();
608 for (a = 0; a < N; a++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100609 HV* hash = newHV();
Marc Kupietz50485ba2016-03-23 09:13:14 +0100610 SV* word = newSVpvf(&vocab[besti[a] * max_w], 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100611 if(latin_enc == 0) SvUTF8_on(word);
612 hv_store(hash, "word", strlen("word"), word , 0);
613 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
614 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
615 AV *vector = newAV();
616 for (b = 0; b < size; b++) {
617 av_push(vector, newSVnv(M[b + besti[a] * size]));
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100618 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100619 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
620 av_push(array, newRV_noinc((SV*)hash));
621 }
622 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
623
Marc Kupietz50485ba2016-03-23 09:13:14 +0100624 for(b=0; b < MAX_NEIGHBOURS; b++) {
625 besti[b] = -1L;
626 bestd[b] = 0;
627 bestn[b] = 0;
628 bestp[b] = 0;
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100629 bests[b] = 0;
Marc Kupietz50485ba2016-03-23 09:13:14 +0100630 }
631
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200632 if (M2) {
633 printf("Waiting for syn threads to join\n");
634 fflush(stdout);
635 for (a = 0; a < syn_threads; a++) pthread_join(pt[a+para_threads], &syn_nbs[a]);
636 printf("syn threads joint\n");
637 fflush(stdout);
Marc Kupietz50485ba2016-03-23 09:13:14 +0100638
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200639 for(b=0; b < syn_nbs[0]->length; b++) {
640 besti[b] = syn_nbs[0]->index[b];
641 bestd[b] = syn_nbs[0]->dist[b];
642 bestn[b] = syn_nbs[0]->norm[b];
643 bestp[b] = syn_nbs[0]->pos[b];
644 bests[b] = target_sums[syn_nbs[0]->index[b]];
645 }
646
647 if(sort_by != 1) { // sort by responsiveness
648 for(a=1; a < syn_threads; a++) {
649 for(b=0; b < syn_nbs[a]->length; b++) {
650 for(c=0; c < MAX_NEIGHBOURS; c++) {
651 if(syn_nbs[a]->dist[b] > bestd[c]) {
652 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
653 bestd[d] = bestd[d-1];
654 besti[d] = besti[d-1];
655 bestn[d] = bestn[d-1];
656 bestp[d] = bestp[d-1];
657 }
658 besti[c] = syn_nbs[a]->index[b];
659 bestd[c] = syn_nbs[a]->dist[b];
660 bestn[c] = syn_nbs[a]->norm[b];
661 bestp[c] = syn_nbs[a]->pos[b];
662 break;
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100663 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200664 }
665 }
666 }
667 } else { // sort by mean p
668 for(a=1; a < syn_threads; a++) {
669 for(b=0; b < syn_nbs[a]->length; b++) {
670 for(c=0; c < MAX_NEIGHBOURS; c++) {
671 if(target_sums[syn_nbs[a]->index[b]] > bests[c]) {
672 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
673 bestd[d] = bestd[d-1];
674 besti[d] = besti[d-1];
675 bestn[d] = bestn[d-1];
676 bestp[d] = bestp[d-1];
677 bests[d] = bests[d-1];
678 }
679 besti[c] = syn_nbs[a]->index[b];
680 bestd[c] = syn_nbs[a]->dist[b];
681 bestn[c] = syn_nbs[a]->norm[b];
682 bestp[c] = syn_nbs[a]->pos[b];
683 bests[c] = target_sums[syn_nbs[a]->index[b]];
684 break;
685 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100686 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100687 }
688 }
689 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200690 array = newAV();
691 for (a = 0; a < MAX_NEIGHBOURS && besti[a] >= 0; a++) {
692 HV* hash = newHV();
693 SV* word = newSVpvf(&vocab[besti[a] * max_w], 0);
694 if(latin_enc == 0) SvUTF8_on(word);
695 hv_store(hash, "word", strlen("word"), word , 0);
696 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
697 hv_store(hash, "norm", strlen("norm"), newSVnv(bestn[a]), 0);
698 hv_store(hash, "sum", strlen("sum"), newSVnv(target_sums[besti[a]]), 0);
699 hv_store(hash, "pos", strlen("pos"), newSVnv(bestp[a]), 0);
700 av_push(array, newRV_noinc((SV*)hash));
Marc Kupietz271e2a42016-03-22 11:37:43 +0100701 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200702 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100703 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100704end:
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100705 return newRV_noinc((SV*)result);
Marc Kupietz000ad862016-02-26 14:59:12 +0100706}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100707
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200708int dump_vecs(char *fname) {
709 long i, j;
710 FILE *f;
711 /* if(words>200000) */
712 /* words=200000; */
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100713
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200714 if((f=fopen(fname, "w")) == NULL) {
715 fprintf(stderr, "cannot open %s for writing\n", fname);
716 return(-1);
717 }
718 fprintf(f, "%lld %lld\n", words, size);
719 for (i=0; i < words; i++) {
720 fprintf(f, "%s ", &vocab[i * max_w]);
721 for(j=0; j < size - 1; j++)
722 fprintf(f, "%f ", M[i*size + j]);
723 fprintf(f, "%f\n", M[i*size + j]);
724 }
725 fclose(f);
726 return(0);
727}
Marc Kupietzdc22b982015-10-09 09:19:34 +0200728__DATA__
729
730@@ index.html.ep
731<!DOCTYPE html>
732<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100733<head>
734 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100735 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100736 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100737 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
738 <script>
739 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100740 $( document ).tooltip({
741 content: function() {
742 return $(this).attr('title');
743 }}
744 )
745 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100746 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100747 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
748 <script src="http://klinux10/word2vec/tsne.js"></script>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100749 <script src="http://klinux10/word2vec/som.js"></script>
Marc Kupietzc5990da2016-02-26 08:47:12 +0100750 <script src="http://klinux10/word2vec/labeler.js"></script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100751<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100752body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100753 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100754 font-size: 11pt;
755}
756
757.ui-tooltip-content {
758 font-size: 9pt;
Marc Kupietza2e64502016-04-27 09:53:51 +0200759 color: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100760}
Marc Kupietz5f780672016-02-25 17:15:54 +0100761
762svg > .ui-tooltip-content {
Marc Kupietzb1029362016-02-27 21:38:55 +0100763 font-size: 8pt;
Marc Kupietza2e64502016-04-27 09:53:51 +0200764 color: #222222;
765}
766
767a.merged {
768 color: green;
769 fill: green;
770}
771
Marc Kupietz6ed81872016-04-27 14:04:04 +0200772#first a {
773 text-decoration: none;
774}
775
Marc Kupietza2e64502016-04-27 09:53:51 +0200776a.marked {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200777 text-decoration: underline;
Marc Kupietza2e64502016-04-27 09:53:51 +0200778}
779
780a.target {
781 color: red;
782 fill: red;
Marc Kupietz5f780672016-02-25 17:15:54 +0100783}
784
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100785#collocators {
786 margin-bottom: 15px;
787}
788
Marc Kupietzc4893362016-02-25 08:04:46 +0100789#wrapper {
790 width: 100%;
791// border: 1px solid red;
792 overflow: hidden; /* will contain if #first is longer than #second */
793}
794#first {
Marc Kupietzb1029362016-02-27 21:38:55 +0100795 margin-right: 20px;
796 float: left;
797 // border: 1px solid green;
Marc Kupietzc4893362016-02-25 08:04:46 +0100798}
799#second {
800 border: 1px solid #333;
801 overflow: hidden; /* if you don't want #second to wrap below #first */
802}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100803#som2 svg {
804 border: 1px solid #333;
805}
806
Marc Kupietz4aa62172016-02-25 10:39:27 +0100807#cost {
Marc Kupietzb1029362016-02-27 21:38:55 +0100808 font-size: 8pt;
809 color: #222222;
810 margin-top: 4px;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100811 margin-bottom: 12px;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100812}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100813
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100814#sominfo1, #sominfo {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100815 font-size: 8pt;
816 color: #222222;
817 margin-top: 0px;
818}
819
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100820#somcolor1, #somcolor2, #somcolor3 {
821 display: inline-block;
822 height: 10px;
823 width: 10px;
824}
825
Marc Kupietzd7aea722016-03-02 11:59:12 +0100826#third {
827 border: 1px solid #333;
828}
829
Marc Kupietzc4893362016-02-25 08:04:46 +0100830</style>
831<script>
832
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100833var opt = {epsilon: <%= $epsilon %>, perplexity: <%= $perplexity %>},
Marc Kupietz9fca1732016-02-29 09:07:04 +0100834 mapWidth = 800, // width map
835 mapHeight = 800,
836 jitterRadius = 7;
837
Marc Kupietzc4893362016-02-25 08:04:46 +0100838var T = new tsnejs.tSNE(opt); // create a tSNE instance
839
840var Y;
841
842var data;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100843var labeler;
Marc Kupietzc4893362016-02-25 08:04:46 +0100844
Marc Kupietzc5990da2016-02-26 08:47:12 +0100845
846function applyJitter() {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100847 svg.selectAll('.tsnet')
Marc Kupietzc5990da2016-02-26 08:47:12 +0100848 .data(labels)
849 .transition()
850 .duration(50)
851 .attr("transform", function(d, i) {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100852 T.Y[i][0] = (d.x - mapWidth/2 - tx)/ss/20;
853 T.Y[i][1] = (d.y - mapHeight/2 - ty)/ss/20;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100854 return "translate(" +
855 (d.x) + "," +
856 (d.y) + ")";
857 });
858}
859
Marc Kupietzc4893362016-02-25 08:04:46 +0100860function updateEmbedding() {
861 var Y = T.getSolution();
Marc Kupietzd7aea722016-03-02 11:59:12 +0100862 svg.selectAll('.tsnet')
Marc Kupietz9fca1732016-02-29 09:07:04 +0100863 .data(data.words)
864 .attr("transform", function(d, i) {
865 return "translate(" +
866 ((Y[i][0]*20*ss + tx) + mapWidth/2) + "," +
867 ((Y[i][1]*20*ss + ty) + mapHeight/2) + ")"; });
Marc Kupietzc4893362016-02-25 08:04:46 +0100868}
869
870var svg;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100871var labels = [];
872var anchor_array = [];
873var text;
874
Marc Kupietzc4893362016-02-25 08:04:46 +0100875function drawEmbedding() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100876 $("#embed").empty();
877 var div = d3.select("#embed");
878
879 // get min and max in each column of Y
880 var Y = T.Y;
881
882 svg = div.append("svg") // svg is global
883 .attr("width", mapWidth)
884 .attr("height", mapHeight);
885
886 var g = svg.selectAll(".b")
887 .data(data.words)
888 .enter().append("g")
Marc Kupietzd7aea722016-03-02 11:59:12 +0100889 .attr("class", "tsnet");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100890
891 g.append("a")
892 .attr("xlink:href", function(word) {return "/?word="+word;})
Marc Kupietza2e64502016-04-27 09:53:51 +0200893 .attr("class", function(d, i) {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200894 var res="";
895 if(data.marked[i]) {
896 res="marked ";
897 }
Marc Kupietza2e64502016-04-27 09:53:51 +0200898 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200899 return res+"target";
900 } else if(data.ranks[i] < data.mergedEnd) {
901 return res+"merged";
Marc Kupietza2e64502016-04-27 09:53:51 +0200902 } else {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200903 return res;
Marc Kupietza2e64502016-04-27 09:53:51 +0200904 }
905 })
Marc Kupietz9fca1732016-02-29 09:07:04 +0100906 .attr("title", function(d, i) {
Marc Kupietza2e64502016-04-27 09:53:51 +0200907 if(data.mergedEnd > 0) {
908 if(data.ranks[i] >= data.mergedEnd) {
909 return "rank: "+i +" "+"freq. rank: "+(data.ranks[i]).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
910 } else {
911 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " (merged vocab)";
912 }
913 } else {
914 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
915 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100916 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100917 .append("text")
Marc Kupietz9fca1732016-02-29 09:07:04 +0100918 .attr("text-anchor", "top")
919 .attr("font-size", 12)
Marc Kupietz9fca1732016-02-29 09:07:04 +0100920 .text(function(d) { return d; });
921
922 var zoomListener = d3.behavior.zoom()
923 .scaleExtent([0.1, 10])
924 .center([0,0])
925 .on("zoom", zoomHandler);
926 zoomListener(svg);
927}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100928
Marc Kupietz9fca1732016-02-29 09:07:04 +0100929var tx=0, ty=0;
930var ss=1;
931var iter_id=-1;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100932
Marc Kupietz9fca1732016-02-29 09:07:04 +0100933function zoomHandler() {
934 tx = d3.event.translate[0];
935 ty = d3.event.translate[1];
936 ss = d3.event.scale;
937 updateEmbedding();
938}
939
940var stepnum = 0;
941
942function stopStep() {
943 clearInterval(iter_id);
944 text = svg.selectAll("text");
945
946 // jitter function needs different data and co-ordinate representation
947 labels = d3.range(data.words.length).map(function(i) {
948 var x = (T.Y[i][0]*20*ss + tx) + mapWidth/2;
949 var y = (T.Y[i][1]*20*ss + ty) + mapHeight/2;
950 anchor_array.push({x: x, y: y, r: jitterRadius});
951 return {
952 x: x,
953 y: y,
954 name: data.words[i]
955 };
956 });
957
958 // get the actual label bounding boxes for the jitter function
959 var index = 0;
960 text.each(function() {
961 labels[index].width = this.getBBox().width;
962 labels[index].height = this.getBBox().height;
963 index += 1;
964 });
Marc Kupietzc5990da2016-02-26 08:47:12 +0100965
966
967// setTimeout(updateEmbedding, 1);
968// setTimeout(
Marc Kupietz9fca1732016-02-29 09:07:04 +0100969 labeler = d3.labeler()
970 .label(labels)
971 .anchor(anchor_array)
972 .width(mapWidth)
973 .height(mapHeight)
974 .update(applyJitter);
975 // .start(1000);
Marc Kupietzc5990da2016-02-26 08:47:12 +0100976
Marc Kupietz9fca1732016-02-29 09:07:04 +0100977 iter_id = setInterval(jitterStep, 1);
978}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100979
Marc Kupietz9fca1732016-02-29 09:07:04 +0100980var jitter_i=0;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100981
982function jitterStep() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100983 if(jitter_i++ > 100) {
984 clearInterval(iter_id);
985 } else {
986 labeler.start2(10);
987 applyJitter();
988 }
Marc Kupietzc5990da2016-02-26 08:47:12 +0100989}
Marc Kupietzb1029362016-02-27 21:38:55 +0100990
991var last_cost=1000;
992
Marc Kupietz9fca1732016-02-29 09:07:04 +0100993function step() {
994 var i = T.iter;
995
996 if(i > <%= $no_iterations %>) {
997 stopStep();
998 } else {
999 var cost = Math.round(T.step() * 100000) / 100000; // do a few steps
1000 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(5));
1001 if(i % 250 == 0 && cost >= last_cost) {
1002 stopStep();
1003 } else {
1004 last_cost = cost;
1005 updateEmbedding();
1006 }
1007 }
1008}
Marc Kupietzc5990da2016-02-26 08:47:12 +01001009
Marc Kupietz9fca1732016-02-29 09:07:04 +01001010function showMap(j) {
1011 data=j;
1012 T.iter=0;
1013 T.initDataRaw(data.vecs); // init embedding
1014 drawEmbedding(); // draw initial embedding
1015
1016 if(iter_id >= 0) {
1017 clearInterval(iter_id);
1018 }
1019 //T.debugGrad();
1020 iter_id = setInterval(step, 1);
Marc Kupietzd7aea722016-03-02 11:59:12 +01001021 if(<%= $show_som %>) {
1022 makeSOM(j, <%= $no_iterations %>);
1023 }
Marc Kupietz9fca1732016-02-29 09:07:04 +01001024}
Marc Kupietza350bce2016-02-25 09:34:25 +01001025
Marc Kupietzc4893362016-02-25 08:04:46 +01001026</script>
1027</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +02001028<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +01001029 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +01001030 word(s):
1031 <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 +02001032 % if($mergedEnd > 0) {
1033 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.">
1034 % }
Marc Kupietz44bee3c2016-02-25 16:26:29 +01001035 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
Marc Kupietzd7aea722016-03-02 11:59:12 +01001036 max. iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
1037 SOM <input type="checkbox" name="som" value="1" <%= ($show_som ? "checked" : "") %>>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001038 % if($collocators) {
Marc Kupietz6d9a6782016-03-23 17:25:25 +01001039 <span> </span>sort collocators by
1040 <select name="sort">
1041 <option value="0" <%= ($sort!=1? "selected":"") %>>responsiveness</option>
1042 <option value="1" <%= ($sort==1? "selected":"") %>>mean p</option>
1043 </select>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001044 % }
Marc Kupietzd7aea722016-03-02 11:59:12 +01001045 <span> </span><input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +01001046 </form>
1047 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +01001048 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +01001049 <div id="wrapper">
1050 <table id="first">
1051 <tr>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001052 <th align="right">#</th><th align="right">cos</th><th align="left">paradigmatic</th>
1053 % if($collocators) {
1054 <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>
1055 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001056 </tr>
Marc Kupietz6ed81872016-04-27 14:04:04 +02001057 % my $j=0; my @words; my @vecs; my @ranks; my @marked; for my $list (@$lists) {
Marc Kupietzc47b3902016-04-22 10:29:44 +02001058 % my $i=0; while($list) {
Marc Kupietz50485ba2016-03-23 09:13:14 +01001059 % my $item = (@$list)[$i];
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001060 % my $c = ($collocators? (@$collocators)[$i] : 0);
Marc Kupietz50485ba2016-03-23 09:13:14 +01001061 % last if(!$c && !$item);
Marc Kupietz4aa62172016-02-25 10:39:27 +01001062 <tr>
1063 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +01001064 <%= ++$i %>.
Marc Kupietz4aa62172016-02-25 10:39:27 +01001065 </td>
Marc Kupietz50485ba2016-03-23 09:13:14 +01001066 % if($item) {
1067 % if(!grep{$_ eq $item->{word}} @words) {
1068 % push @vecs, $item->{vector};
1069 % push @words, $item->{word};
1070 % push @ranks, $item->{rank};
Marc Kupietz6ed81872016-04-27 14:04:04 +02001071 % push @marked, ($marked->{$item->{word}}? 1 : 0);
Marc Kupietz50485ba2016-03-23 09:13:14 +01001072 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001073 <td align="right">
1074 <%= sprintf("%.3f", $item->{dist}) %>
1075 </td>
Marc Kupietzd5642582016-03-19 22:23:13 +01001076 <td>
Marc Kupietz6ed81872016-04-27 14:04:04 +02001077 % my $class = ($marked->{$item->{word}}? "marked " : "");
Marc Kupietza2e64502016-04-27 09:53:51 +02001078 % my $r = $item->{rank};
1079 % if($r < $mergedEnd) {
Marc Kupietz6ed81872016-04-27 14:04:04 +02001080 % $class .= "merged";
Marc Kupietza2e64502016-04-27 09:53:51 +02001081 % $r .= " (merged vocab)";
1082 % } elsif($mergedEnd!=0 && $r > $mergedEnd) {
1083 % $r -= $mergedEnd;
1084 % }
1085 <a class="<%= $class %>" title="freq. rank: <%= $r %>" href="/?word=<%= $item->{word} %>"><%= $item->{word} %></a>
Marc Kupietzd5642582016-03-19 22:23:13 +01001086 </td>
Marc Kupietz50485ba2016-03-23 09:13:14 +01001087 % } else {
1088 <td colspan="2"/>
1089 % }
Marc Kupietz271e2a42016-03-22 11:37:43 +01001090 % if($c) {
Marc Kupietz5f780672016-02-25 17:15:54 +01001091 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +01001092 <%= $c->{pos} %>:
1093 </td>
1094 <td align="right">
1095 <%= sprintf("%.3f", $c->{dist}) %>
1096 </td>
Marc Kupietzb864ccf2016-03-21 22:40:03 +01001097 <td align="right">
1098 <%= sprintf("%.3e", $c->{norm}) %>
1099 </td>
Marc Kupietzce3d4c62016-03-23 16:11:25 +01001100 <td align="right">
1101 <%= sprintf("%.3e", $c->{sum}) %>
1102 </td>
Marc Kupietzd5642582016-03-19 22:23:13 +01001103 <td align="left">
1104 <a href="/?word=<%= $c->{word} %>">
1105 <%= $c->{word} %>
Marc Kupietz5f780672016-02-25 17:15:54 +01001106 </td>
Marc Kupietz271e2a42016-03-22 11:37:43 +01001107 % } else {
Marc Kupietzce3d4c62016-03-23 16:11:25 +01001108 <td colspan="5"/>
Marc Kupietz271e2a42016-03-22 11:37:43 +01001109 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001110 </tr>
1111 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +01001112 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001113 </table>
1114 <script>
1115 % use Mojo::ByteStream 'b';
1116 $(window).load(function() {
Marc Kupietz6ed81872016-04-27 14:04:04 +02001117 showMap(<%= b(Mojo::JSON::to_json({target => " $word ", mergedEnd=> $mergedEnd, words => \@words, vecs => \@vecs, ranks => \@ranks, marked => \@marked})); %>);
Marc Kupietz4aa62172016-02-25 10:39:27 +01001118 });
1119 </script>
1120 % }
1121 <div id="second" style="width:800px; height:800px; font-family: arial;">
1122 <div id="embed">
1123 </div>
Marc Kupietz4aa62172016-02-25 10:39:27 +01001124 </div>
Marc Kupietzb1029362016-02-27 21:38:55 +01001125 <div id="cost"></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +01001126 % if($show_som) {
1127 <div id="som2">
1128 </div>
Marc Kupietz6c1ca442016-03-03 09:35:18 +01001129 <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 +01001130 <div id="sominfo">SOM iteration <span id="iterations">0</span></div>
1131 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001132 </div>
Marc Kupietz793413b2016-04-02 21:48:57 +02001133 % if($training_args) {
1134 <p>
1135 Word vector model trained with <a href="https://code.google.com/p/word2vec/">word2vec</a> using the following parameters: <pre><%= $training_args %></pre>
1136 </p>
1137 % }
1138 </body>
Marc Kupietzdc22b982015-10-09 09:19:34 +02001139</html>
1140