blob: edd04a477c76288a6fc3123df805a33c123b6116 [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) {
27 open(FILE, "<$opt_M") or die "cannot open $opt_M";
28 while(<FILE>) {
29 foreach my $mw (split /\s+/) {
30 $marked{$mw}=1
31 }
32 }
33 close(FILE);
34}
Marc Kupietza5b90152016-03-15 17:39:19 +010035
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010036# -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 +010037if(!$ARGV[0]) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010038 init_net("vectors15.bin", $opt_n, ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010039} else {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010040 init_net($ARGV[0], $opt_n, ($opt_i? 1 : 0));
Marc Kupietz793413b2016-04-02 21:48:57 +020041 if(open(FILE, "$ARGV[0].args")) {
42 $training_args = <FILE>;
43 }
44 close(FILE);
Marc Kupietz2cb667e2016-03-10 09:44:12 +010045}
Marc Kupietzdc22b982015-10-09 09:19:34 +020046
Marc Kupietza2e64502016-04-27 09:53:51 +020047if($opt_m) {
48 $mergedEnd = mergeVectors($opt_m);
49}
50
Marc Kupietz6ed81872016-04-27 14:04:04 +020051
Marc Kupietz43ee87e2016-04-25 10:50:08 +020052if($opt_d) { # -d: dump vecs and exit
53 dump_vecs($opt_d);
54 exit;
55}
56
Marc Kupietza5b90152016-03-15 17:39:19 +010057my $daemon = Mojo::Server::Daemon->new(
58 app => app,
59 listen => ['http://'.($opt_l ? $opt_l : '*').":$opt_p"]
60);
61
Marc Kupietzdc22b982015-10-09 09:19:34 +020062get '/' => sub {
63 my $c = shift;
64 my $word=$c->param('word');
Marc Kupietz44bee3c2016-02-25 16:26:29 +010065 my $no_nbs=$c->param('n') || 100;
66 my $no_iterations=$c->param('N') || 2000;
Marc Kupietzd4227392016-03-01 16:45:12 +010067 my $perplexity=$c->param('perplexity') || 20;
Marc Kupietzc4d62f82016-03-01 11:04:24 +010068 my $epsilon=$c->param('epsilon') || 5;
Marc Kupietzd7aea722016-03-02 11:59:12 +010069 my $som=$c->param('som') || 0;
Marc Kupietza2e64502016-04-27 09:53:51 +020070 my $searchBaseVocabFirst=$c->param('sbf') || 0;
Marc Kupietz6d9a6782016-03-23 17:25:25 +010071 my $sort=$c->param('sort') || 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010072 my $res;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010073 my @lists;
Marc Kupietz6b2975c2016-03-18 21:59:33 +010074 my @collocations;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010075 if(defined($word) && $word !~ /^\s*$/) {
76 $c->inactivity_timeout(300);
Marc Kupietz44bee3c2016-02-25 16:26:29 +010077 $word =~ s/\s+/ /g;
78 for my $w (split(' *\| *', $word)) {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010079 $c->app->log->debug('Looking for neighbours of '.$w);
Marc Kupietza5b90152016-03-15 17:39:19 +010080 if($opt_i) {
Marc Kupietza2e64502016-04-27 09:53:51 +020081 $res = get_neighbours(encode("iso-8859-1", $w), $no_nbs, $sort, $searchBaseVocabFirst);
Marc Kupietza5b90152016-03-15 17:39:19 +010082 } else {
Marc Kupietza2e64502016-04-27 09:53:51 +020083 $res = get_neighbours($w, $no_nbs, $sort, $searchBaseVocabFirst);
Marc Kupietza5b90152016-03-15 17:39:19 +010084 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +010085 push(@lists, $res->{paradigmatic});
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +010086 }
Marc Kupietz247500f2015-10-09 11:29:01 +020087 }
Marc Kupietz000ad862016-02-26 14:59:12 +010088 $word =~ s/ *\| */ | /g;
Marc Kupietz6ed81872016-04-27 14:04:04 +020089 $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 +020090};
91
Marc Kupietza5b90152016-03-15 17:39:19 +010092$daemon->run; # app->start;
Marc Kupietzdc22b982015-10-09 09:19:34 +020093
94exit;
95
96__END__
97
98__C__
99#include <stdio.h>
100#include <string.h>
101#include <math.h>
102#include <malloc.h>
103#include <stdlib.h> //strlen
Marc Kupietzf0809762016-02-26 10:13:47 +0100104#include <sys/mman.h>
Marc Kupietz000ad862016-02-26 14:59:12 +0100105#include <pthread.h>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200106
107#define max_size 2000
108#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100109#define MAX_NEIGHBOURS 1000
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100110#define MAX_WORDS -1
Marc Kupietz000ad862016-02-26 14:59:12 +0100111#define MAX_THREADS 100
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100112#define MAX_CC 50
113#define EXP_TABLE_SIZE 1000
114#define MAX_EXP 6
Marc Kupietz271e2a42016-03-22 11:37:43 +0100115#define MIN_RESP 0.50
Marc Kupietzdc22b982015-10-09 09:19:34 +0200116
117//the thread function
118void *connection_handler(void *);
Marc Kupietz000ad862016-02-26 14:59:12 +0100119
120typedef struct {
121 long long *index;
122 float *dist;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100123 float *norm;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100124 long long *pos;
Marc Kupietz80abb442016-03-23 21:04:08 +0100125 int length;
Marc Kupietz000ad862016-02-26 14:59:12 +0100126} knn;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100127
Marc Kupietz000ad862016-02-26 14:59:12 +0100128typedef struct {
Marc Kupietz48c29682016-03-19 11:30:43 +0100129 long long wordi[MAX_NEIGHBOURS];
130 char sep[MAX_NEIGHBOURS];
131 int length;
132} wordlist;
133
134typedef struct {
135 wordlist *wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100136 char *token;
137 int N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100138 long from;
Marc Kupietz000ad862016-02-26 14:59:12 +0100139 unsigned long upto;
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100140 float *target_sums;
Marc Kupietz000ad862016-02-26 14:59:12 +0100141} knnpars;
142
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200143float *M, *M2=0L, *syn1neg_window, *expTable;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200144char *vocab;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100145
Marc Kupietza2e64502016-04-27 09:53:51 +0200146long long words, size, merged_end;
Marc Kupietz000ad862016-02-26 14:59:12 +0100147int num_threads=20;
Marc Kupietza5b90152016-03-15 17:39:19 +0100148int latin_enc=0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100149int window;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200150
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100151int init_net(char *file_name, char *net_name, int latin) {
Marc Kupietz67c20282016-02-26 09:42:00 +0100152 FILE *f, *binvecs, *binwords;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100153 int binwords_fd, binvecs_fd, net_fd, i;
Marc Kupietz82b02672016-02-26 12:32:25 +0100154 long long a, b, c, d, cn;
155 float len;
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200156 double val;
Marc Kupietz82b02672016-02-26 12:32:25 +0100157
Marc Kupietz67c20282016-02-26 09:42:00 +0100158 char binvecs_fname[256], binwords_fname[256];
159 strcpy(binwords_fname, file_name);
160 strcat(binwords_fname, ".words");
161 strcpy(binvecs_fname, file_name);
162 strcat(binvecs_fname, ".vecs");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200163
Marc Kupietza5b90152016-03-15 17:39:19 +0100164 latin_enc = latin;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200165 f = fopen(file_name, "rb");
166 if (f == NULL) {
167 printf("Input file %s not found\n", file_name);
168 return -1;
169 }
170 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100171 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200172 fscanf(f, "%lld", &size);
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100173 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
174 printf("Converting %s to memory mappable structures\n", file_name);
Marc Kupietzf0809762016-02-26 10:13:47 +0100175 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
176 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
177 if (M == NULL) {
178 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
179 return -1;
180 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200181 if(strstr(file_name, ".txt")) {
182 for (b = 0; b < words; b++) {
183 a = 0;
184 while (1) {
185 vocab[b * max_w + a] = fgetc(f);
186 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
187 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
188 }
189 vocab[b * max_w + a] = 0;
190 len = 0;
191 for (a = 0; a < size; a++) {
192 fscanf(f, "%lf", &val);
193 M[a + b * size] = val;
194 len += val * val;
195 }
196 len = sqrt(len);
197 for (a = 0; a < size; a++) M[a + b * size] /= len;
198 }
199 } else {
200 for (b = 0; b < words; b++) {
201 a = 0;
202 while (1) {
203 vocab[b * max_w + a] = fgetc(f);
204 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
205 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
206 }
207 vocab[b * max_w + a] = 0;
208 fread(&M[b * size], sizeof(float), size, f);
209 len = 0;
210 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
211 len = sqrt(len);
212 for (a = 0; a < size; a++) M[a + b * size] /= len;
213 }
214 }
Marc Kupietz67c20282016-02-26 09:42:00 +0100215 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
216 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
217 fclose(binvecs);
218 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
219 fclose(binwords);
220 }
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100221 }
222 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
223 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
224 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
225 if (M == MAP_FAILED || vocab == MAP_FAILED) {
226 close(binvecs_fd);
227 close(binwords_fd);
228 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
229 exit(-1);
230 }
231 } else {
232 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
233 exit(-1);
Marc Kupietz67c20282016-02-26 09:42:00 +0100234 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200235 fclose(f);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100236
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200237 if(net_name && strlen(net_name) > 0) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100238 if( (net_fd = open(net_name, O_RDONLY)) >= 0) {
239 window = (lseek(net_fd, 0, SEEK_END) - sizeof(float) * words * size) / words / size / sizeof(float) / 2;
240 // lseek(net_fd, sizeof(float) * words * size, SEEK_SET);
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100241 // munmap(M, sizeof(float) * words * size);
242 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 +0200243 if (M2 == MAP_FAILED) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100244 close(net_fd);
245 fprintf(stderr, "Cannot mmap %s\n", net_name);
246 exit(-1);
247 }
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100248 syn1neg_window = M2 + words * size;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100249 } else {
250 fprintf(stderr, "Cannot open %s\n", net_name);
251 exit(-1);
252 }
253 fprintf(stderr, "Successfully memmaped %s. Determined window size: %d\n", net_name, window);
254 }
255
256 expTable = (float *) malloc((EXP_TABLE_SIZE + 1) * sizeof(float));
257 for (i = 0; i < EXP_TABLE_SIZE; i++) {
258 expTable[i] = exp((i / (float) EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
259 expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
260 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200261 return 0;
262}
263
Marc Kupietza2e64502016-04-27 09:53:51 +0200264long mergeVectors(char *file_name){
265 FILE *f, *binvecs, *binwords;
266 int binwords_fd, binvecs_fd, net_fd, i;
267 long long a, b, c, d, cn;
268 float len;
269 float *merge_vecs;
270 char *merge_vocab;
271 long long merge_words, merge_size;
272
273 char binvecs_fname[256], binwords_fname[256];
274 strcpy(binwords_fname, file_name);
275 strcat(binwords_fname, ".words");
276 strcpy(binvecs_fname, file_name);
277 strcat(binvecs_fname, ".vecs");
278
279 f = fopen(file_name, "rb");
280 if (f == NULL) {
281 printf("Input file %s not found\n", file_name);
282 exit -1;
283 }
284 fscanf(f, "%lld", &merge_words);
285 fscanf(f, "%lld", &merge_size);
286 if(merge_size != size){
287 fprintf(stderr, "vectors must have the same length\n");
288 exit(-1);
289 }
290 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
291 merge_vecs = malloc(sizeof(float) * (words + merge_words) * size);
292 merge_vocab = malloc(sizeof(char) * (words + merge_words) * max_w);
293 if (merge_vecs == NULL || merge_vocab == NULL) {
294 close(binvecs_fd);
295 close(binwords_fd);
296 fprintf(stderr, "Cannot reserve memory for %s or %s\n", binwords_fname, binvecs_fname);
297 exit(-1);
298 }
299 read(binvecs_fd, merge_vecs, merge_words * size * sizeof(float));
300 read(binwords_fd, merge_vocab, merge_words * max_w);
301 } else {
302 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
303 exit(-1);
304 }
305 printf("Successfully reallocated memory\nMerging...\n");
306 fflush(stdout);
307 memcpy(merge_vecs + merge_words * size, M, words * size * sizeof(float));
308 memcpy(merge_vocab + merge_words * max_w, vocab, words * max_w);
309 munmap(M, words * size * sizeof(float));
310 munmap(vocab, words * max_w);
311 M = merge_vecs;
312 vocab = merge_vocab;
313 merged_end = merge_words;
314 words += merge_words;
315 fclose(f);
316 printf("merged_end: %lld, words: %lld\n", merged_end, words);
317 return((long) merged_end);
318}
319
Marc Kupietz271e2a42016-03-22 11:37:43 +0100320void *getCollocators(knnpars *pars) {
321 int N = pars->N;
322 int cc = pars->wl->wordi[0];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100323 knn *nbs = NULL;
324 long window_layer_size = size * window * 2;
325 long a, b, c, d, e, window_offset, target, max_target=0, maxmax_target;
326 float f, max_f, maxmax_f;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100327 float *target_sums, *bestf, *bestn, worstbest, wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100328 long long *besti, *bestp;
Marc Kupietzd5642582016-03-19 22:23:13 +0100329
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200330 if(M2 == NULL || cc == -1)
Marc Kupietzd5642582016-03-19 22:23:13 +0100331 return NULL;
332
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100333 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
334 besti = malloc(N * sizeof(long long));
335 bestp = malloc(N * sizeof(long long));
336 bestf = malloc(N * sizeof(float));
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100337 bestn = malloc(N * sizeof(float));
338
Marc Kupietz271e2a42016-03-22 11:37:43 +0100339 worstbest = MIN_RESP;
340
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100341 for (b = 0; b < words; b++)
342 target_sums[b]=0;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100343 for (b = 0; b < N; b++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100344 besti[b] = -1;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100345 bestn[b] = 1;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100346 bestf[b] = worstbest;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100347 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100348
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100349 d = cc;
350 maxmax_f = -1;
351 maxmax_target = 0;
352
Marc Kupietz271e2a42016-03-22 11:37:43 +0100353 for (a = pars->from; a < pars->upto; a++) {
354 if(a >= window)
355 a++;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100356 wpos_sum = 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100357 printf("window pos: %ld\n", a);
358 if (a != window) {
359 max_f = -1;
360 window_offset = a * size;
361 if (a > window)
362 window_offset -= size;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100363 for(target = 0; target < words; target ++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100364 if(target == d)
365 continue;
366 f = 0;
367 for (c = 0; c < size; c++)
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100368 f += M2[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100369 if (f < -MAX_EXP)
370 continue;
371 else if (f > MAX_EXP)
372 continue;
373 else
374 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100375 wpos_sum += f;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100376
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100377 target_sums[target] += f;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100378 if(f > worstbest) {
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100379 for (b = 0; b < N; b++) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100380 if (f > bestf[b]) {
Marc Kupietz33679a32016-03-22 08:49:39 +0100381 memmove(bestf + b + 1, bestf + b, (N - b -1) * sizeof(float));
382 memmove(besti + b + 1, besti + b, (N - b -1) * sizeof(long long));
383 memmove(bestp + b + 1, bestp + b, (N - b -1) * sizeof(long long));
384 bestf[b] = f;
385 besti[b] = target;
386 bestp[b] = window-a;
387 break;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100388 }
389 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100390 if(b == N - 1)
391 worstbest = bestf[N-1];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100392 }
393 }
394 printf("%d %.2f\n", max_target, max_f);
395 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
396 if(max_f > maxmax_f) {
397 maxmax_f = max_f;
398 maxmax_target = max_target;
399 }
Marc Kupietz33679a32016-03-22 08:49:39 +0100400 for (b = 0; b < N; b++)
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100401 if(bestp[b] == window-a)
402 bestn[b] = bestf[b] / wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100403 } else {
404 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
405 }
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100406
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100407 }
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100408 for (b = 0; b < words; b++)
409 pars->target_sums[b] += (target_sums[b] / wpos_sum ) / (window * 2);
410 free(target_sums);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100411 for(b=0; b<N && besti[b] >= 0; b++) // THIS LOOP IS NEEDED (b...)
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100412 printf("%s %.2f %d * ", &vocab[besti[b]*max_w], bestf[b], bestp[b]);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100413 printf("\n");
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100414 nbs = malloc(sizeof(knn));
415 nbs->index = besti;
416 nbs->dist = bestf;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100417 nbs->norm = bestn;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100418 nbs->pos = bestp;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100419 nbs->length = b-1;
420 pthread_exit(nbs);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100421}
422
Marc Kupietza2e64502016-04-27 09:53:51 +0200423wordlist *getTargetWords(char *st1, int search_backw) {
Marc Kupietz48c29682016-03-19 11:30:43 +0100424 wordlist *wl = malloc(sizeof(wordlist));
425 char st[100][max_size], sep[100];
426 long a, b=0, c=0, cn=0;
Marc Kupietza2e64502016-04-27 09:53:51 +0200427 int unmerged;
428
Marc Kupietzdc22b982015-10-09 09:19:34 +0200429 while (1) {
430 st[cn][b] = st1[c];
431 b++;
432 c++;
433 st[cn][b] = 0;
434 if (st1[c] == 0) break;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100435 if (st1[c] == ' ' || st1[c] == '-') {
436 sep[cn++] = st1[c];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200437 b = 0;
438 c++;
439 }
440 }
441 cn++;
442 for (a = 0; a < cn; a++) {
Marc Kupietza2e64502016-04-27 09:53:51 +0200443 if(search_backw) {
444 for (b = words - 1; b >= 0; b--) if (!strcmp(&vocab[b * max_w], st[a])) break;
445 } else {
446 for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st[a])) break;
447 }
Marc Kupietz34a3ee92016-02-27 22:43:16 +0100448 if (b == words) b = -1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100449 wl->wordi[a] = b;
450 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", st[a], wl->wordi[a]);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200451 if (b == -1) {
Marc Kupietze8da3062016-02-25 08:37:53 +0100452 fprintf(stderr, "Out of dictionary word!\n");
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100453 cn--;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200454 break;
455 }
456 }
Marc Kupietz48c29682016-03-19 11:30:43 +0100457 wl->length=cn;
458 return(wl);
459}
460
461void *_get_neighbours(knnpars *pars) {
462 char *st1 = pars->token;
463 int N = pars->N;
464 long from = pars -> from;
465 unsigned long upto = pars -> upto;
466 char file_name[max_size], st[100][max_size], *sep;
467 float dist, len, *bestd, vec[max_size];
468 long long a, b, c, d, cn, *bi, *besti;
469 char ch;
470 knn *nbs = NULL;
471 wordlist *wl = pars->wl;
472
473 besti = malloc(N * sizeof(long long));
474 bestd = malloc(N * sizeof(float));
475
476 float worstbest=-1;
477
478 for (a = 0; a < N; a++) bestd[a] = 0;
479 a = 0;
480 bi = wl->wordi;
481 cn = wl->length;
482 sep = wl->sep;
483 b = bi[0];
484 c = 0;
Marc Kupietz000ad862016-02-26 14:59:12 +0100485 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100486 N = 0;
487 goto end;
488 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200489 for (a = 0; a < size; a++) vec[a] = 0;
490 for (b = 0; b < cn; b++) {
491 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100492 if(b>0 && sep[b-1] == '-')
493 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
494 else
495 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200496 }
497 len = 0;
498 for (a = 0; a < size; a++) len += vec[a] * vec[a];
499 len = sqrt(len);
500 for (a = 0; a < size; a++) vec[a] /= len;
501 for (a = 0; a < N; a++) bestd[a] = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100502 for (c = from; c < upto; c++) {
Marc Kupietzdc22b982015-10-09 09:19:34 +0200503 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100504// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100505// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
506// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200507 dist = 0;
508 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100509 if(dist > worstbest) {
510 for (a = 0; a < N; a++) {
511 if (dist > bestd[a]) {
Marc Kupietz33679a32016-03-22 08:49:39 +0100512 memmove(bestd + a + 1, bestd + a, (N - a -1) * sizeof(float));
513 memmove(besti + a + 1, besti + a, (N - a -1) * sizeof(long long));
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100514 bestd[a] = dist;
515 besti[a] = c;
516 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200517 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200518 }
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100519 worstbest = bestd[N-1];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200520 }
521 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100522
Marc Kupietz000ad862016-02-26 14:59:12 +0100523 nbs = malloc(sizeof(knn));
524 nbs->index = besti;
525 nbs->dist = bestd;
526 nbs->length = N;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100527end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100528 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200529}
530
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100531
Marc Kupietza2e64502016-04-27 09:53:51 +0200532SV *get_neighbours(char *st1, int N, int sort_by, int search_backw) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100533 HV *result = newHV();
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100534 float *target_sums, bestd[MAX_NEIGHBOURS], bestn[MAX_NEIGHBOURS], bests[MAX_NEIGHBOURS], vec[max_size];
Marc Kupietz50485ba2016-03-23 09:13:14 +0100535 long besti[MAX_NEIGHBOURS], bestp[MAX_NEIGHBOURS], a, b, c, d, slice;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100536 knn *para_nbs[MAX_THREADS];
537 knn *syn_nbs[MAX_THREADS];
Marc Kupietz000ad862016-02-26 14:59:12 +0100538 knnpars pars[MAX_THREADS];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100539 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
Marc Kupietz48c29682016-03-19 11:30:43 +0100540 wordlist *wl;
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200541 int syn_threads = (M2? window * 2 : 0);
542 int para_threads = num_threads - syn_threads;
Marc Kupietz48c29682016-03-19 11:30:43 +0100543
Marc Kupietz000ad862016-02-26 14:59:12 +0100544 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
545
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200546 slice = words / para_threads;
547
Marc Kupietza2e64502016-04-27 09:53:51 +0200548 wl = getTargetWords(st1, search_backw);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100549 if(wl->length < 1)
550 goto end;
Marc Kupietz48c29682016-03-19 11:30:43 +0100551
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100552 a = posix_memalign((void **) &target_sums, 128, words * sizeof(float));
553 for(a = 0; a < words; a++)
554 target_sums[a] = 0;
555
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200556 printf("Starting %d threads\n", para_threads);
557 fflush(stdout);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100558 for(a=0; a < para_threads; a++) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100559 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +0100560 pars[a].wl = wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100561 pars[a].N = N;
562 pars[a].from = a*slice;
563 pars[a].upto = ((a+1)*slice > words? words:(a+1)*slice);
564 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
565 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200566 if(M2) {
567 for(a=0; a < syn_threads; a++) {
568 pars[a + para_threads].target_sums = target_sums;
569 pars[a + para_threads].wl = wl;
570 pars[a + para_threads].N = N;
571 pars[a + para_threads].from = a;
572 pars[a + para_threads].upto = a+1;
573 pthread_create(&pt[a + para_threads], NULL, getCollocators, (void *) &pars[a + para_threads]);
574 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100575 }
576 printf("Waiting for para threads to join\n");
577 fflush(stdout);
578 for (a = 0; a < para_threads; a++) pthread_join(pt[a], &para_nbs[a]);
579 printf("Para threads joint\n");
580 fflush(stdout);
Marc Kupietz000ad862016-02-26 14:59:12 +0100581
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200582 /* if(!syn_nbs[0]) */
583 /* goto end; */
Marc Kupietz000ad862016-02-26 14:59:12 +0100584
585 for(b=0; b < N; b++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100586 besti[b] = para_nbs[0]->index[b];
587 bestd[b] = para_nbs[0]->dist[b];
Marc Kupietz000ad862016-02-26 14:59:12 +0100588 }
589
Marc Kupietz271e2a42016-03-22 11:37:43 +0100590 for(a=1; a < para_threads; a++) {
591 for(b=0; b < para_nbs[a]->length && para_nbs[a]->index[b] >= 0; b++) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100592 for(c=0; c < N; c++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100593 if(para_nbs[a]->dist[b] > bestd[c]) {
Marc Kupietz000ad862016-02-26 14:59:12 +0100594 for(d=N-1; d>c; d--) {
595 bestd[d] = bestd[d-1];
596 besti[d] = besti[d-1];
597 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100598 besti[c] = para_nbs[a]->index[b];
599 bestd[c] = para_nbs[a]->dist[b];
Marc Kupietz000ad862016-02-26 14:59:12 +0100600 break;
601 }
602 }
603 }
604 }
605
Marc Kupietz271e2a42016-03-22 11:37:43 +0100606 AV* array = newAV();
607 for (a = 0; a < N; a++) {
Marc Kupietz271e2a42016-03-22 11:37:43 +0100608 HV* hash = newHV();
Marc Kupietz50485ba2016-03-23 09:13:14 +0100609 SV* word = newSVpvf(&vocab[besti[a] * max_w], 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100610 if(latin_enc == 0) SvUTF8_on(word);
611 hv_store(hash, "word", strlen("word"), word , 0);
612 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
613 hv_store(hash, "rank", strlen("rank"), newSVuv(besti[a]), 0);
614 AV *vector = newAV();
615 for (b = 0; b < size; b++) {
616 av_push(vector, newSVnv(M[b + besti[a] * size]));
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100617 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100618 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
619 av_push(array, newRV_noinc((SV*)hash));
620 }
621 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
622
Marc Kupietz50485ba2016-03-23 09:13:14 +0100623 for(b=0; b < MAX_NEIGHBOURS; b++) {
624 besti[b] = -1L;
625 bestd[b] = 0;
626 bestn[b] = 0;
627 bestp[b] = 0;
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100628 bests[b] = 0;
Marc Kupietz50485ba2016-03-23 09:13:14 +0100629 }
630
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200631 if (M2) {
632 printf("Waiting for syn threads to join\n");
633 fflush(stdout);
634 for (a = 0; a < syn_threads; a++) pthread_join(pt[a+para_threads], &syn_nbs[a]);
635 printf("syn threads joint\n");
636 fflush(stdout);
Marc Kupietz50485ba2016-03-23 09:13:14 +0100637
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200638 for(b=0; b < syn_nbs[0]->length; b++) {
639 besti[b] = syn_nbs[0]->index[b];
640 bestd[b] = syn_nbs[0]->dist[b];
641 bestn[b] = syn_nbs[0]->norm[b];
642 bestp[b] = syn_nbs[0]->pos[b];
643 bests[b] = target_sums[syn_nbs[0]->index[b]];
644 }
645
646 if(sort_by != 1) { // sort by responsiveness
647 for(a=1; a < syn_threads; a++) {
648 for(b=0; b < syn_nbs[a]->length; b++) {
649 for(c=0; c < MAX_NEIGHBOURS; c++) {
650 if(syn_nbs[a]->dist[b] > bestd[c]) {
651 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
652 bestd[d] = bestd[d-1];
653 besti[d] = besti[d-1];
654 bestn[d] = bestn[d-1];
655 bestp[d] = bestp[d-1];
656 }
657 besti[c] = syn_nbs[a]->index[b];
658 bestd[c] = syn_nbs[a]->dist[b];
659 bestn[c] = syn_nbs[a]->norm[b];
660 bestp[c] = syn_nbs[a]->pos[b];
661 break;
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100662 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200663 }
664 }
665 }
666 } else { // sort by mean p
667 for(a=1; a < syn_threads; a++) {
668 for(b=0; b < syn_nbs[a]->length; b++) {
669 for(c=0; c < MAX_NEIGHBOURS; c++) {
670 if(target_sums[syn_nbs[a]->index[b]] > bests[c]) {
671 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
672 bestd[d] = bestd[d-1];
673 besti[d] = besti[d-1];
674 bestn[d] = bestn[d-1];
675 bestp[d] = bestp[d-1];
676 bests[d] = bests[d-1];
677 }
678 besti[c] = syn_nbs[a]->index[b];
679 bestd[c] = syn_nbs[a]->dist[b];
680 bestn[c] = syn_nbs[a]->norm[b];
681 bestp[c] = syn_nbs[a]->pos[b];
682 bests[c] = target_sums[syn_nbs[a]->index[b]];
683 break;
684 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100685 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100686 }
687 }
688 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200689 array = newAV();
690 for (a = 0; a < MAX_NEIGHBOURS && besti[a] >= 0; a++) {
691 HV* hash = newHV();
692 SV* word = newSVpvf(&vocab[besti[a] * max_w], 0);
693 if(latin_enc == 0) SvUTF8_on(word);
694 hv_store(hash, "word", strlen("word"), word , 0);
695 hv_store(hash, "dist", strlen("dist"), newSVnv(bestd[a]), 0);
696 hv_store(hash, "norm", strlen("norm"), newSVnv(bestn[a]), 0);
697 hv_store(hash, "sum", strlen("sum"), newSVnv(target_sums[besti[a]]), 0);
698 hv_store(hash, "pos", strlen("pos"), newSVnv(bestp[a]), 0);
699 av_push(array, newRV_noinc((SV*)hash));
Marc Kupietz271e2a42016-03-22 11:37:43 +0100700 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200701 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +0100702 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100703end:
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100704 return newRV_noinc((SV*)result);
Marc Kupietz000ad862016-02-26 14:59:12 +0100705}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100706
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200707int dump_vecs(char *fname) {
708 long i, j;
709 FILE *f;
710 /* if(words>200000) */
711 /* words=200000; */
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100712
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200713 if((f=fopen(fname, "w")) == NULL) {
714 fprintf(stderr, "cannot open %s for writing\n", fname);
715 return(-1);
716 }
717 fprintf(f, "%lld %lld\n", words, size);
718 for (i=0; i < words; i++) {
719 fprintf(f, "%s ", &vocab[i * max_w]);
720 for(j=0; j < size - 1; j++)
721 fprintf(f, "%f ", M[i*size + j]);
722 fprintf(f, "%f\n", M[i*size + j]);
723 }
724 fclose(f);
725 return(0);
726}
Marc Kupietzdc22b982015-10-09 09:19:34 +0200727__DATA__
728
729@@ index.html.ep
730<!DOCTYPE html>
731<html>
Marc Kupietzc4893362016-02-25 08:04:46 +0100732<head>
733 <title>DeReKo-Word-Vector-Distances</title>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100734 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
Marc Kupietzc4893362016-02-25 08:04:46 +0100735 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100736 <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
737 <script>
738 $(function() {
Marc Kupietz5f780672016-02-25 17:15:54 +0100739 $( document ).tooltip({
740 content: function() {
741 return $(this).attr('title');
742 }}
743 )
744 })
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100745 </script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100746 <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
747 <script src="http://klinux10/word2vec/tsne.js"></script>
Marc Kupietzd7aea722016-03-02 11:59:12 +0100748 <script src="http://klinux10/word2vec/som.js"></script>
Marc Kupietzc5990da2016-02-26 08:47:12 +0100749 <script src="http://klinux10/word2vec/labeler.js"></script>
Marc Kupietzc4893362016-02-25 08:04:46 +0100750<style>
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100751body, input {
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100752 font-family: Arial, sans-serif;
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100753 font-size: 11pt;
754}
755
756.ui-tooltip-content {
757 font-size: 9pt;
Marc Kupietza2e64502016-04-27 09:53:51 +0200758 color: #222222;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100759}
Marc Kupietz5f780672016-02-25 17:15:54 +0100760
761svg > .ui-tooltip-content {
Marc Kupietzb1029362016-02-27 21:38:55 +0100762 font-size: 8pt;
Marc Kupietza2e64502016-04-27 09:53:51 +0200763 color: #222222;
764}
765
766a.merged {
767 color: green;
768 fill: green;
769}
770
Marc Kupietz6ed81872016-04-27 14:04:04 +0200771#first a {
772 text-decoration: none;
773}
774
Marc Kupietza2e64502016-04-27 09:53:51 +0200775a.marked {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200776 text-decoration: underline;
Marc Kupietza2e64502016-04-27 09:53:51 +0200777}
778
779a.target {
780 color: red;
781 fill: red;
Marc Kupietz5f780672016-02-25 17:15:54 +0100782}
783
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100784#collocators {
785 margin-bottom: 15px;
786}
787
Marc Kupietzc4893362016-02-25 08:04:46 +0100788#wrapper {
789 width: 100%;
790// border: 1px solid red;
791 overflow: hidden; /* will contain if #first is longer than #second */
792}
793#first {
Marc Kupietzb1029362016-02-27 21:38:55 +0100794 margin-right: 20px;
795 float: left;
796 // border: 1px solid green;
Marc Kupietzc4893362016-02-25 08:04:46 +0100797}
798#second {
799 border: 1px solid #333;
800 overflow: hidden; /* if you don't want #second to wrap below #first */
801}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100802#som2 svg {
803 border: 1px solid #333;
804}
805
Marc Kupietz4aa62172016-02-25 10:39:27 +0100806#cost {
Marc Kupietzb1029362016-02-27 21:38:55 +0100807 font-size: 8pt;
808 color: #222222;
809 margin-top: 4px;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100810 margin-bottom: 12px;
Marc Kupietz4aa62172016-02-25 10:39:27 +0100811}
Marc Kupietzd7aea722016-03-02 11:59:12 +0100812
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100813#sominfo1, #sominfo {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100814 font-size: 8pt;
815 color: #222222;
816 margin-top: 0px;
817}
818
Marc Kupietz6c1ca442016-03-03 09:35:18 +0100819#somcolor1, #somcolor2, #somcolor3 {
820 display: inline-block;
821 height: 10px;
822 width: 10px;
823}
824
Marc Kupietzd7aea722016-03-02 11:59:12 +0100825#third {
826 border: 1px solid #333;
827}
828
Marc Kupietzc4893362016-02-25 08:04:46 +0100829</style>
830<script>
831
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100832var opt = {epsilon: <%= $epsilon %>, perplexity: <%= $perplexity %>},
Marc Kupietz9fca1732016-02-29 09:07:04 +0100833 mapWidth = 800, // width map
834 mapHeight = 800,
835 jitterRadius = 7;
836
Marc Kupietzc4893362016-02-25 08:04:46 +0100837var T = new tsnejs.tSNE(opt); // create a tSNE instance
838
839var Y;
840
841var data;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100842var labeler;
Marc Kupietzc4893362016-02-25 08:04:46 +0100843
Marc Kupietzc5990da2016-02-26 08:47:12 +0100844
845function applyJitter() {
Marc Kupietzd7aea722016-03-02 11:59:12 +0100846 svg.selectAll('.tsnet')
Marc Kupietzc5990da2016-02-26 08:47:12 +0100847 .data(labels)
848 .transition()
849 .duration(50)
850 .attr("transform", function(d, i) {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100851 T.Y[i][0] = (d.x - mapWidth/2 - tx)/ss/20;
852 T.Y[i][1] = (d.y - mapHeight/2 - ty)/ss/20;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100853 return "translate(" +
854 (d.x) + "," +
855 (d.y) + ")";
856 });
857}
858
Marc Kupietzc4893362016-02-25 08:04:46 +0100859function updateEmbedding() {
860 var Y = T.getSolution();
Marc Kupietzd7aea722016-03-02 11:59:12 +0100861 svg.selectAll('.tsnet')
Marc Kupietz9fca1732016-02-29 09:07:04 +0100862 .data(data.words)
863 .attr("transform", function(d, i) {
864 return "translate(" +
865 ((Y[i][0]*20*ss + tx) + mapWidth/2) + "," +
866 ((Y[i][1]*20*ss + ty) + mapHeight/2) + ")"; });
Marc Kupietzc4893362016-02-25 08:04:46 +0100867}
868
869var svg;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100870var labels = [];
871var anchor_array = [];
872var text;
873
Marc Kupietzc4893362016-02-25 08:04:46 +0100874function drawEmbedding() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100875 $("#embed").empty();
876 var div = d3.select("#embed");
877
878 // get min and max in each column of Y
879 var Y = T.Y;
880
881 svg = div.append("svg") // svg is global
882 .attr("width", mapWidth)
883 .attr("height", mapHeight);
884
885 var g = svg.selectAll(".b")
886 .data(data.words)
887 .enter().append("g")
Marc Kupietzd7aea722016-03-02 11:59:12 +0100888 .attr("class", "tsnet");
Marc Kupietz9fca1732016-02-29 09:07:04 +0100889
890 g.append("a")
891 .attr("xlink:href", function(word) {return "/?word="+word;})
Marc Kupietza2e64502016-04-27 09:53:51 +0200892 .attr("class", function(d, i) {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200893 var res="";
894 if(data.marked[i]) {
895 res="marked ";
896 }
Marc Kupietza2e64502016-04-27 09:53:51 +0200897 if(data.target.indexOf(" "+d+" ") >= 0) {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200898 return res+"target";
899 } else if(data.ranks[i] < data.mergedEnd) {
900 return res+"merged";
Marc Kupietza2e64502016-04-27 09:53:51 +0200901 } else {
Marc Kupietz6ed81872016-04-27 14:04:04 +0200902 return res;
Marc Kupietza2e64502016-04-27 09:53:51 +0200903 }
904 })
Marc Kupietz9fca1732016-02-29 09:07:04 +0100905 .attr("title", function(d, i) {
Marc Kupietza2e64502016-04-27 09:53:51 +0200906 if(data.mergedEnd > 0) {
907 if(data.ranks[i] >= data.mergedEnd) {
908 return "rank: "+i +" "+"freq. rank: "+(data.ranks[i]).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
909 } else {
910 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " (merged vocab)";
911 }
912 } else {
913 return "rank: "+i +" "+"freq. rank: "+data.ranks[i].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
914 }
Marc Kupietz9fca1732016-02-29 09:07:04 +0100915 })
Marc Kupietza350bce2016-02-25 09:34:25 +0100916 .append("text")
Marc Kupietz9fca1732016-02-29 09:07:04 +0100917 .attr("text-anchor", "top")
918 .attr("font-size", 12)
Marc Kupietz9fca1732016-02-29 09:07:04 +0100919 .text(function(d) { return d; });
920
921 var zoomListener = d3.behavior.zoom()
922 .scaleExtent([0.1, 10])
923 .center([0,0])
924 .on("zoom", zoomHandler);
925 zoomListener(svg);
926}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100927
Marc Kupietz9fca1732016-02-29 09:07:04 +0100928var tx=0, ty=0;
929var ss=1;
930var iter_id=-1;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100931
Marc Kupietz9fca1732016-02-29 09:07:04 +0100932function zoomHandler() {
933 tx = d3.event.translate[0];
934 ty = d3.event.translate[1];
935 ss = d3.event.scale;
936 updateEmbedding();
937}
938
939var stepnum = 0;
940
941function stopStep() {
942 clearInterval(iter_id);
943 text = svg.selectAll("text");
944
945 // jitter function needs different data and co-ordinate representation
946 labels = d3.range(data.words.length).map(function(i) {
947 var x = (T.Y[i][0]*20*ss + tx) + mapWidth/2;
948 var y = (T.Y[i][1]*20*ss + ty) + mapHeight/2;
949 anchor_array.push({x: x, y: y, r: jitterRadius});
950 return {
951 x: x,
952 y: y,
953 name: data.words[i]
954 };
955 });
956
957 // get the actual label bounding boxes for the jitter function
958 var index = 0;
959 text.each(function() {
960 labels[index].width = this.getBBox().width;
961 labels[index].height = this.getBBox().height;
962 index += 1;
963 });
Marc Kupietzc5990da2016-02-26 08:47:12 +0100964
965
966// setTimeout(updateEmbedding, 1);
967// setTimeout(
Marc Kupietz9fca1732016-02-29 09:07:04 +0100968 labeler = d3.labeler()
969 .label(labels)
970 .anchor(anchor_array)
971 .width(mapWidth)
972 .height(mapHeight)
973 .update(applyJitter);
974 // .start(1000);
Marc Kupietzc5990da2016-02-26 08:47:12 +0100975
Marc Kupietz9fca1732016-02-29 09:07:04 +0100976 iter_id = setInterval(jitterStep, 1);
977}
Marc Kupietzc5990da2016-02-26 08:47:12 +0100978
Marc Kupietz9fca1732016-02-29 09:07:04 +0100979var jitter_i=0;
Marc Kupietzc5990da2016-02-26 08:47:12 +0100980
981function jitterStep() {
Marc Kupietz9fca1732016-02-29 09:07:04 +0100982 if(jitter_i++ > 100) {
983 clearInterval(iter_id);
984 } else {
985 labeler.start2(10);
986 applyJitter();
987 }
Marc Kupietzc5990da2016-02-26 08:47:12 +0100988}
Marc Kupietzb1029362016-02-27 21:38:55 +0100989
990var last_cost=1000;
991
Marc Kupietz9fca1732016-02-29 09:07:04 +0100992function step() {
993 var i = T.iter;
994
995 if(i > <%= $no_iterations %>) {
996 stopStep();
997 } else {
998 var cost = Math.round(T.step() * 100000) / 100000; // do a few steps
999 $("#cost").html("tsne iteration " + i + ", cost: " + cost.toFixed(5));
1000 if(i % 250 == 0 && cost >= last_cost) {
1001 stopStep();
1002 } else {
1003 last_cost = cost;
1004 updateEmbedding();
1005 }
1006 }
1007}
Marc Kupietzc5990da2016-02-26 08:47:12 +01001008
Marc Kupietz9fca1732016-02-29 09:07:04 +01001009function showMap(j) {
1010 data=j;
1011 T.iter=0;
1012 T.initDataRaw(data.vecs); // init embedding
1013 drawEmbedding(); // draw initial embedding
1014
1015 if(iter_id >= 0) {
1016 clearInterval(iter_id);
1017 }
1018 //T.debugGrad();
1019 iter_id = setInterval(step, 1);
Marc Kupietzd7aea722016-03-02 11:59:12 +01001020 if(<%= $show_som %>) {
1021 makeSOM(j, <%= $no_iterations %>);
1022 }
Marc Kupietz9fca1732016-02-29 09:07:04 +01001023}
Marc Kupietza350bce2016-02-25 09:34:25 +01001024
Marc Kupietzc4893362016-02-25 08:04:46 +01001025</script>
1026</head>
Marc Kupietzdc22b982015-10-09 09:19:34 +02001027<body>
Marc Kupietz4aa62172016-02-25 10:39:27 +01001028 <form action="<%=url_for('/')->to_abs%>" method="GET">
Marc Kupietz44bee3c2016-02-25 16:26:29 +01001029 word(s):
1030 <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 +02001031 % if($mergedEnd > 0) {
1032 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.">
1033 % }
Marc Kupietz44bee3c2016-02-25 16:26:29 +01001034 max. neighbours: <input type="text" size="8" name="n" value="<%= $no_nbs %>">
Marc Kupietzd7aea722016-03-02 11:59:12 +01001035 max. iterations: <input type="text" name="N" size="8" value="<%= $no_iterations %>">
1036 SOM <input type="checkbox" name="som" value="1" <%= ($show_som ? "checked" : "") %>>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001037 % if($collocators) {
Marc Kupietz6d9a6782016-03-23 17:25:25 +01001038 <span> </span>sort collocators by
1039 <select name="sort">
1040 <option value="0" <%= ($sort!=1? "selected":"") %>>responsiveness</option>
1041 <option value="1" <%= ($sort==1? "selected":"") %>>mean p</option>
1042 </select>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001043 % }
Marc Kupietzd7aea722016-03-02 11:59:12 +01001044 <span> </span><input type="submit" value="Show">
Marc Kupietz4aa62172016-02-25 10:39:27 +01001045 </form>
1046 <br>
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +01001047 % if($lists) {
Marc Kupietz4aa62172016-02-25 10:39:27 +01001048 <div id="wrapper">
1049 <table id="first">
1050 <tr>
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001051 <th align="right">#</th><th align="right">cos</th><th align="left">paradigmatic</th>
1052 % if($collocators) {
1053 <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>
1054 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001055 </tr>
Marc Kupietz6ed81872016-04-27 14:04:04 +02001056 % my $j=0; my @words; my @vecs; my @ranks; my @marked; for my $list (@$lists) {
Marc Kupietzc47b3902016-04-22 10:29:44 +02001057 % my $i=0; while($list) {
Marc Kupietz50485ba2016-03-23 09:13:14 +01001058 % my $item = (@$list)[$i];
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001059 % my $c = ($collocators? (@$collocators)[$i] : 0);
Marc Kupietz50485ba2016-03-23 09:13:14 +01001060 % last if(!$c && !$item);
Marc Kupietz4aa62172016-02-25 10:39:27 +01001061 <tr>
1062 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +01001063 <%= ++$i %>.
Marc Kupietz4aa62172016-02-25 10:39:27 +01001064 </td>
Marc Kupietz50485ba2016-03-23 09:13:14 +01001065 % if($item) {
1066 % if(!grep{$_ eq $item->{word}} @words) {
1067 % push @vecs, $item->{vector};
1068 % push @words, $item->{word};
1069 % push @ranks, $item->{rank};
Marc Kupietz6ed81872016-04-27 14:04:04 +02001070 % push @marked, ($marked->{$item->{word}}? 1 : 0);
Marc Kupietz50485ba2016-03-23 09:13:14 +01001071 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001072 <td align="right">
1073 <%= sprintf("%.3f", $item->{dist}) %>
1074 </td>
Marc Kupietzd5642582016-03-19 22:23:13 +01001075 <td>
Marc Kupietz6ed81872016-04-27 14:04:04 +02001076 % my $class = ($marked->{$item->{word}}? "marked " : "");
Marc Kupietza2e64502016-04-27 09:53:51 +02001077 % my $r = $item->{rank};
1078 % if($r < $mergedEnd) {
Marc Kupietz6ed81872016-04-27 14:04:04 +02001079 % $class .= "merged";
Marc Kupietza2e64502016-04-27 09:53:51 +02001080 % $r .= " (merged vocab)";
1081 % } elsif($mergedEnd!=0 && $r > $mergedEnd) {
1082 % $r -= $mergedEnd;
1083 % }
1084 <a class="<%= $class %>" title="freq. rank: <%= $r %>" href="/?word=<%= $item->{word} %>"><%= $item->{word} %></a>
Marc Kupietzd5642582016-03-19 22:23:13 +01001085 </td>
Marc Kupietz50485ba2016-03-23 09:13:14 +01001086 % } else {
1087 <td colspan="2"/>
1088 % }
Marc Kupietz271e2a42016-03-22 11:37:43 +01001089 % if($c) {
Marc Kupietz5f780672016-02-25 17:15:54 +01001090 <td align="right">
Marc Kupietzd5642582016-03-19 22:23:13 +01001091 <%= $c->{pos} %>:
1092 </td>
1093 <td align="right">
1094 <%= sprintf("%.3f", $c->{dist}) %>
1095 </td>
Marc Kupietzb864ccf2016-03-21 22:40:03 +01001096 <td align="right">
1097 <%= sprintf("%.3e", $c->{norm}) %>
1098 </td>
Marc Kupietzce3d4c62016-03-23 16:11:25 +01001099 <td align="right">
1100 <%= sprintf("%.3e", $c->{sum}) %>
1101 </td>
Marc Kupietzd5642582016-03-19 22:23:13 +01001102 <td align="left">
1103 <a href="/?word=<%= $c->{word} %>">
1104 <%= $c->{word} %>
Marc Kupietz5f780672016-02-25 17:15:54 +01001105 </td>
Marc Kupietz271e2a42016-03-22 11:37:43 +01001106 % } else {
Marc Kupietzce3d4c62016-03-23 16:11:25 +01001107 <td colspan="5"/>
Marc Kupietz271e2a42016-03-22 11:37:43 +01001108 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001109 </tr>
1110 % }
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +01001111 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001112 </table>
1113 <script>
1114 % use Mojo::ByteStream 'b';
1115 $(window).load(function() {
Marc Kupietz6ed81872016-04-27 14:04:04 +02001116 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 +01001117 });
1118 </script>
1119 % }
1120 <div id="second" style="width:800px; height:800px; font-family: arial;">
1121 <div id="embed">
1122 </div>
Marc Kupietz4aa62172016-02-25 10:39:27 +01001123 </div>
Marc Kupietzb1029362016-02-27 21:38:55 +01001124 <div id="cost"></div>
Marc Kupietzd7aea722016-03-02 11:59:12 +01001125 % if($show_som) {
1126 <div id="som2">
1127 </div>
Marc Kupietz6c1ca442016-03-03 09:35:18 +01001128 <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 +01001129 <div id="sominfo">SOM iteration <span id="iterations">0</span></div>
1130 % }
Marc Kupietz4aa62172016-02-25 10:39:27 +01001131 </div>
Marc Kupietz793413b2016-04-02 21:48:57 +02001132 % if($training_args) {
1133 <p>
1134 Word vector model trained with <a href="https://code.google.com/p/word2vec/">word2vec</a> using the following parameters: <pre><%= $training_args %></pre>
1135 </p>
1136 % }
1137 </body>
Marc Kupietzdc22b982015-10-09 09:19:34 +02001138</html>
1139