blob: 67bcba4e3c0a3ef91d14d809392b2ee54246fb57 [file] [log] [blame]
Marc Kupietzdc22b982015-10-09 09:19:34 +02001#!/usr/local/bin/perl
2use Inline C;
Marc Kupietz00eecb12019-01-24 16:08:44 +01003use Inline C => Config => CLEAN_AFTER_BUILD => 0, BUILD_NOISY => 1, ccflags => $Config{ccflags}." -I/vol/work/kupietz/Work2/kl/trunk/CollocatorDB -I, -L. -Wall -O4", libs => "-shared -lpthread -lcollocatordb -lrt -lsnappy -lz -lbz2 -llz4 -lzstd -lrocksdb -lgomp";
Marc Kupietza5f60042017-05-04 10:38:12 +02004#use Inline C => Config => BUILD_NOISY => 1, CFLAGS => $Config{cflags}." -O4 -mtune k9";
5#use Inline C => Config => CLEAN_AFTER_BUILD => 0, ccflags => $Config{ccflags}." -Ofast -march k8 -mtune k8 ";
Marc Kupietzdc22b982015-10-09 09:19:34 +02006use Mojolicious::Lite;
Marc Kupietzc4893362016-02-25 08:04:46 +01007use Mojo::JSON qw(decode_json encode_json to_json);
Marc Kupietz30ca4342017-11-22 21:21:20 +01008use base 'Mojolicious::Plugin';
9
Marc Kupietz247500f2015-10-09 11:29:01 +020010use Encode qw(decode encode);
Marc Kupietza5b90152016-03-15 17:39:19 +010011use Getopt::Std;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010012use Mojo::Server::Daemon;
Marc Kupietzffef9302017-11-07 15:58:01 +010013use Cwd;
Marc Kupietz66bfd952017-12-11 09:59:45 +010014
Marc Kupietzffef9302017-11-07 15:58:01 +010015app->static->paths->[0] = getcwd;
16
Marc Kupietzd4227392016-03-01 16:45:12 +010017plugin 'Log::Access';
Marc Kupietzb3422c12017-07-04 14:12:11 +020018plugin "RequestBase";
Marc Kupietzdc22b982015-10-09 09:19:34 +020019
Marc Kupietza5b90152016-03-15 17:39:19 +010020our $opt_i = 0; # latin1-input?
21our $opt_l = undef;
22our $opt_p = 5676;
Marc Kupietza2e64502016-04-27 09:53:51 +020023our $opt_m;
Marc Kupietz6ed81872016-04-27 14:04:04 +020024our $opt_M;
Marc Kupietz43ee87e2016-04-25 10:50:08 +020025our $opt_n = '';
26our $opt_d;
Marc Kupietzfa194262018-06-05 09:39:32 +020027our $opt_D;
Marc Kupietz5c3887d2016-04-28 08:53:35 +020028our $opt_G;
Marc Kupietza5b90152016-03-15 17:39:19 +010029
Marc Kupietz6ed81872016-04-27 14:04:04 +020030my %marked;
Marc Kupietzc053d972019-01-10 10:41:51 +010031my $title="";
Marc Kupietz793413b2016-04-02 21:48:57 +020032my $training_args="";
Marc Kupietza2e64502016-04-27 09:53:51 +020033my $mergedEnd=0;
Marc Kupietz15987412017-11-07 15:56:58 +010034my %cache;
Marc Kupietz19c68242018-03-12 09:42:21 +010035my %cccache; # classic collocator cache
Marc Kupietza51dcfa2018-03-19 16:22:05 +010036my %spcache; # similar profile cache
Marc Kupietz793413b2016-04-02 21:48:57 +020037
Marc Kupietzfa194262018-06-05 09:39:32 +020038getopts('d:D:Gil:p:m:n:M:');
Marc Kupietz6ed81872016-04-27 14:04:04 +020039
40if($opt_M) {
Marc Kupietzed930212016-04-27 15:42:38 +020041 open my $handle, '<:encoding(UTF-8)', $opt_M
42 or die "Can't open '$opt_M' for reading: $!";
43 while(<$handle>) {
Marc Kupietz6ed81872016-04-27 14:04:04 +020044 foreach my $mw (split /\s+/) {
45 $marked{$mw}=1
46 }
47 }
Marc Kupietzed930212016-04-27 15:42:38 +020048 close($handle);
Marc Kupietz6ed81872016-04-27 14:04:04 +020049}
Marc Kupietza5b90152016-03-15 17:39:19 +010050
Marc Kupietz7bc85fd2016-02-24 11:42:41 +010051# -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 +010052if(!$ARGV[0]) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010053 init_net("vectors15.bin", $opt_n, ($opt_i? 1 : 0));
Marc Kupietz2cb667e2016-03-10 09:44:12 +010054} else {
Marc Kupietz6b2975c2016-03-18 21:59:33 +010055 init_net($ARGV[0], $opt_n, ($opt_i? 1 : 0));
Marc Kupietz793413b2016-04-02 21:48:57 +020056 if(open(FILE, "$ARGV[0].args")) {
57 $training_args = <FILE>;
58 }
59 close(FILE);
Marc Kupietzc053d972019-01-10 10:41:51 +010060 $title = fname2corpusname($ARGV[0]);
Marc Kupietz2cb667e2016-03-10 09:44:12 +010061}
Marc Kupietzdc22b982015-10-09 09:19:34 +020062
Marc Kupietza51dcfa2018-03-19 16:22:05 +010063my $have_sprofiles = load_sprofiles($ARGV[0]);
64
Marc Kupietza2e64502016-04-27 09:53:51 +020065if($opt_m) {
66 $mergedEnd = mergeVectors($opt_m);
Marc Kupietzc053d972019-01-10 10:41:51 +010067 $title = "<span class=\"merged\">" . $title . "</span> vs. " . fname2corpusname($opt_m);
Marc Kupietza2e64502016-04-27 09:53:51 +020068}
69
Marc Kupietze5568a02018-12-20 11:42:02 +010070
Marc Kupietz43ee87e2016-04-25 10:50:08 +020071if($opt_d) { # -d: dump vecs and exit
72 dump_vecs($opt_d);
73 exit;
74}
75
Marc Kupietzfa194262018-06-05 09:39:32 +020076if($opt_D) { # -D: dump vecs for numpy and exit
77 dump_for_numpy($opt_D);
78 exit;
79}
80
Marc Kupietza5b90152016-03-15 17:39:19 +010081my $daemon = Mojo::Server::Daemon->new(
82 app => app,
83 listen => ['http://'.($opt_l ? $opt_l : '*').":$opt_p"]
84);
85
Marc Kupietz5c3887d2016-04-28 08:53:35 +020086if($opt_G) {
87 print "Filtering garbage\n";
88 filter_garbage();
89}
90
Marc Kupietz554aff52017-11-09 14:42:09 +010091get '*/js/*' => sub {
Marc Kupietzffef9302017-11-07 15:58:01 +010092 my $c = shift;
93 my $url = $c->req->url;
94 $url =~ s@/derekovecs@@g;
95 $c->app->log->info("GET: " . $url);
96 $c->reply->static($url);
97};
98
Marc Kupietza9270572018-03-17 15:17:07 +010099get '*/css/*' => sub {
100 my $c = shift;
101 my $url = $c->req->url;
102 $url =~ s@/derekovecs/@/@g;
103 $c->app->log->info("GET: " . $url);
104 $c->reply->static($url);
105};
106
Marc Kupietzc053d972019-01-10 10:41:51 +0100107sub fname2corpusname {
108 ($_) = @_;
109 s@.*/@@;
Marc Kupietz86b50292019-02-17 21:03:59 +0100110 s@\.en@-en@;
Marc Kupietzc053d972019-01-10 10:41:51 +0100111 s@\..*@@;
112 return $_;
113}
114
Marc Kupietz19c68242018-03-12 09:42:21 +0100115sub getClassicCollocatorsCached {
116 my ($c, $word) = @_;
Marc Kupietz81aeed22019-02-17 21:22:45 +0100117 my $s2 = "";
Marc Kupietz9ff3c992019-02-04 12:32:54 +0100118 if($word > $mergedEnd) {
119 $word-=$mergedEnd;
120 }
Marc Kupietz81aeed22019-02-17 21:22:45 +0100121
Marc Kupietz999ab8c2019-02-17 21:42:21 +0100122 if($opt_p >= 5000 && $opt_p < 5600) { # German non-reference
Marc Kupietz9ee3f412019-08-02 14:58:19 +0200123 open PIPE, "GET http://compute:5673/getClassicCollocators?w=$word |" or
124 open PIPE, "GET http://klinux10:5673/getClassicCollocators?w=$word |";
Marc Kupietz999ab8c2019-02-17 21:42:21 +0100125 }
Marc Kupietz19c68242018-03-12 09:42:21 +0100126 if(!$cccache{$word}) {
Marc Kupietz06d61292019-02-04 12:33:22 +0100127 $c->app->log->info("Getting classic collocates of $word.");
Marc Kupietz19c68242018-03-12 09:42:21 +0100128 $cccache{$word} = getClassicCollocators($word);
Marc Kupietz1d96a082019-02-18 09:29:06 +0100129 $cccache{$word} =~ s/:(-?)(nan|inf)/:"${1}${2}"/g;
Marc Kupietz19c68242018-03-12 09:42:21 +0100130 } else {
Marc Kupietz06d61292019-02-04 12:33:22 +0100131 $c->app->log->info("Getting classic collocates for $word from cache.");
Marc Kupietz19c68242018-03-12 09:42:21 +0100132 }
Marc Kupietz81aeed22019-02-17 21:22:45 +0100133 if($opt_p >= 5000 && $opt_p < 5600) { # German non-reference
Marc Kupietz999ab8c2019-02-17 21:42:21 +0100134 while(<PIPE>) {
135 $s2 .= $_;
136 }
137 close(PIPE);
Marc Kupietz81aeed22019-02-17 21:22:45 +0100138 }
Marc Kupietz999ab8c2019-02-17 21:42:21 +0100139
Marc Kupietz81aeed22019-02-17 21:22:45 +0100140 if(length($s2) > 2000) {
141 my $d1 = decode_json($cccache{$word});
142 my $d2 = decode_json($s2);
143 my %d2ld;
Marc Kupietz001bffd2019-02-21 08:52:41 +0100144 my $minLd = 14;
Marc Kupietz81aeed22019-02-17 21:22:45 +0100145 foreach my $i (@{$d2->{collocates}}) {
146 $d2ld{$i->{word}}=$i->{ld};
Marc Kupietz001bffd2019-02-21 08:52:41 +0100147 $minLd=$i->{ld} if($i->{ld} < $minLd);
Marc Kupietz81aeed22019-02-17 21:22:45 +0100148 }
149 foreach my $i (@{$d1->{collocates}}) {
150 my $w = $i->{word};
Marc Kupietz001bffd2019-02-21 08:52:41 +0100151 $i->{delta} = $i->{ld} - (defined $d2ld{$w} ? $d2ld{$w} : $minLd-0.1);
Marc Kupietz81aeed22019-02-17 21:22:45 +0100152 }
153 return(encode_json($d1));
154 } else {
155 my $d1 = decode_json($cccache{$word});
156 foreach my $i (@{$d1->{collocates}}) {
157 $i->{delta} = 0;
158 }
159 return(encode_json($d1));
160 }
Marc Kupietz19c68242018-03-12 09:42:21 +0100161}
162
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100163sub getSimilarProfilesCached {
164 my ($c, $word) = @_;
165 if(!$spcache{$word}) {
166 $spcache{$word} = getSimilarProfiles($word);
167 } else {
168 $c->app->log->info("Getting similar profiles for $word from cache:");
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100169 }
170 return $spcache{$word};
171}
172
Marc Kupietz66bfd952017-12-11 09:59:45 +0100173post '/derekovecs/getVecsByRanks' => sub {
174 my $self = shift;
175 my $vec = getVecs($self->req->json);
176 $self->render(json => $vec);
177};
178
Marc Kupietze13a3552018-01-25 08:48:34 +0100179any '*/getClassicCollocators' => sub {
Marc Kupietze243efd2018-01-11 22:19:24 +0100180 my $self = shift;
Marc Kupietz19c68242018-03-12 09:42:21 +0100181 $self->render(data => getClassicCollocatorsCached($self, $self->param("w") ? $self->param("w") : $self->req->json), format=>'json');
Marc Kupietze243efd2018-01-11 22:19:24 +0100182};
183
Marc Kupietze13a3552018-01-25 08:48:34 +0100184any '/getClassicCollocators' => sub {
Marc Kupietze243efd2018-01-11 22:19:24 +0100185 my $self = shift;
Marc Kupietz19c68242018-03-12 09:42:21 +0100186 $self->render(data => getClassicCollocatorsCached($self, $self->param("w") ? $self->param("w") : $self->req->json), format=>'json');
Marc Kupietze243efd2018-01-11 22:19:24 +0100187};
188
Marc Kupietzd7760b42019-02-21 09:01:44 +0100189any '/getBiggestVocabDistances' => sub {
190 my $self = shift;
191 $self->render(data => getBiggestMergedDifferences(), format=>'json');
192};
193
194any '*/getBiggestVocabDistances' => sub {
195 my $self = shift;
196 $self->render(data => getBiggestMergedDifferences(), format=>'json');
197};
198
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100199any '*/getSimilarProfiles' => sub {
200 my $self = shift;
201 $self->render(data => getSimilarProfilesCached($self, $self->param("w") ? $self->param("w") : $self->req->json), format=>'json');
202};
203
Marc Kupietzc987fa82018-03-21 12:14:25 +0100204any '/getSimilarProfiles' => sub {
205 my $self = shift;
206 $self->render(data => getSimilarProfilesCached($self, $self->param("w") ? $self->param("w") : $self->req->json), format=>'json');
207};
208
Marc Kupietz98ed1c02019-08-02 15:05:37 +0200209any '/getSimilarity' => sub {
210 my $self = shift;
211 my $w1 = $self->param("w1");
212 my $w2 = $self->param("w2");
213 $self->render(data => cos_similarity_as_json($w1, $w2), format=>'json');
214};
215
216any '*/getSimilarity' => sub {
217 my $self = shift;
218 my $w1 = $self->param("w1");
219 my $w2 = $self->param("w2");
220 $self->render(data => cos_similarity_as_json($w1, $w2), format=>'json');
221};
222
Marc Kupietzdf3d4b52017-11-29 16:57:27 +0100223get '*/img/*' => sub {
224 my $c = shift;
225 my $url = $c->req->url;
226 $url =~ s@/derekovecs@@g;
227 $c->app->log->info("GET: " . $url);
228 $c->reply->static($url);
229};
230
Marc Kupietzdc22b982015-10-09 09:19:34 +0200231get '/' => sub {
232 my $c = shift;
Marc Kupietza5f60042017-05-04 10:38:12 +0200233 $c->app->log->info("get: ".$c->req->url->to_abs);
Marc Kupietzdc22b982015-10-09 09:19:34 +0200234 my $word=$c->param('word');
Marc Kupietz2da2a812019-02-21 14:17:35 +0100235 my $no_nbs=$c->param('n') || ($opt_m? 50 : 100);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100236 my $no_iterations=$c->param('N') || 2000;
Marc Kupietzd4227392016-03-01 16:45:12 +0100237 my $perplexity=$c->param('perplexity') || 20;
Marc Kupietzc4d62f82016-03-01 11:04:24 +0100238 my $epsilon=$c->param('epsilon') || 5;
Marc Kupietzd7aea722016-03-02 11:59:12 +0100239 my $som=$c->param('som') || 0;
Marc Kupietza2e64502016-04-27 09:53:51 +0200240 my $searchBaseVocabFirst=$c->param('sbf') || 0;
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100241 my $sort=$c->param('sort') || 0;
Marc Kupietzc469f3b2017-11-13 14:07:36 +0100242 my $csv=$c->param('csv') || 0;
Marc Kupietzb613b052016-04-28 14:11:59 +0200243 my $json=$c->param('json') || 0;
Marc Kupietzdb2dc7e2017-12-02 12:04:03 +0100244 my $cutoff=$c->param('cutoff') || 500000;
Marc Kupietzd91212f2017-11-13 10:05:09 +0100245 my $dedupe=$c->param('dedupe') || 0;
Marc Kupietzac707b32018-12-20 11:36:38 +0100246 my $nosp=$c->param('nosp') || 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100247 my $res;
Marc Kupietz7b2cbeb2016-02-25 11:22:00 +0100248 my @lists;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100249 my @collocations;
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100250 if(defined($word) && $word !~ /^\s*$/) {
251 $c->inactivity_timeout(300);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100252 $word =~ s/\s+/ /g;
Marc Kupietz3082fd02019-01-09 14:54:06 +0100253 if($opt_m && $word !~ /\|/) {
254 $word .= "|$word";
255 }
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100256 for my $w (split(' *\| *', $word)) {
Marc Kupietz3082fd02019-01-09 14:54:06 +0100257 if($opt_m) {
258 if($searchBaseVocabFirst) {
259 $searchBaseVocabFirst=0;
260 } else {
261 $searchBaseVocabFirst=1;
262 }
263 }
264 if ($cache{$w.$cutoff.$no_nbs.$sort.$dedupe,$searchBaseVocabFirst}) {
Marc Kupietz15987412017-11-07 15:56:58 +0100265 $c->app->log->info("Getting $w results from cache");
Marc Kupietz3082fd02019-01-09 14:54:06 +0100266 $res = $cache{$w.$cutoff.$no_nbs.$sort.$dedupe.$searchBaseVocabFirst}
Marc Kupietza5b90152016-03-15 17:39:19 +0100267 } else {
Marc Kupietz15987412017-11-07 15:56:58 +0100268 $c->app->log->info('Looking for neighbours of '.$w);
269 if($opt_i) {
Marc Kupietzac707b32018-12-20 11:36:38 +0100270 $res = get_neighbours(encode("iso-8859-1", $w), $no_nbs, $sort, $searchBaseVocabFirst, $cutoff, $dedupe, $nosp);
Marc Kupietz15987412017-11-07 15:56:58 +0100271 } else {
Marc Kupietzac707b32018-12-20 11:36:38 +0100272 $res = get_neighbours($w, $no_nbs, $sort, $searchBaseVocabFirst, $cutoff, $dedupe, $nosp);
Marc Kupietz15987412017-11-07 15:56:58 +0100273 }
Marc Kupietz2dd2dd72017-12-01 22:08:14 +0100274 $cache{$w.$cutoff.$no_nbs.$sort.$dedupe} = $res;
Marc Kupietza5b90152016-03-15 17:39:19 +0100275 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100276 push(@lists, $res->{paradigmatic});
Marc Kupietz15987412017-11-07 15:56:58 +0100277 }
278 }
Marc Kupietz000ad862016-02-26 14:59:12 +0100279 $word =~ s/ *\| */ | /g;
Marc Kupietzb613b052016-04-28 14:11:59 +0200280 if($json) {
281 return $c->render(json => {word => $word, list => \@lists, collocators=>$res->{syntagmatic}});
Marc Kupietzc469f3b2017-11-13 14:07:36 +0100282 } elsif($csv) {
283 my $csv_data="";
284 for (my $i=0; $i <= $no_nbs; $i++) {
285 $csv_data .= $res->{paradigmatic}->[$i]->{word} . ", ";
286 }
287 for (my $i=0; $i < $no_nbs; $i++) {
288 $csv_data .= $res->{syntagmatic}->[$i]->{word} . ", ";
289 }
290 chop $csv_data;
291 chop $csv_data;
292 $csv_data .= "\n";
293 return $c->render(text=>$csv_data);
Marc Kupietzb613b052016-04-28 14:11:59 +0200294 } else {
Marc Kupietzd7760b42019-02-21 09:01:44 +0100295 my $distantWords="";
296 if(!defined($word) || $word !~ /^\s*$/) {
297 $distantWords = getBiggestMergedDifferences();
298 }
299 $c->render(template=>"index", title=>$title, word=>$word, distantWords=>$distantWords, cutoff=>$cutoff, 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, haveSProfiles=> $have_sprofiles, dedupe=> $dedupe, marked=>\%marked, lists=> \@lists, collocators=> $res->{syntagmatic});
Marc Kupietzb613b052016-04-28 14:11:59 +0200300 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200301};
302
Marc Kupietz30ca4342017-11-22 21:21:20 +0100303helper(bitvec2window => sub {
304 my ($self, $n) = @_;
305 my $str = unpack("B32", pack("N", $n));
306 $str =~ s/^\d{22}//;
307 $str =~ s/^(\d{5})/$1x/;
308 $str =~ s/0/·/g;
309 $str =~ s/1/+/g;
310 return $str;
311 });
312
Marc Kupietza5b90152016-03-15 17:39:19 +0100313$daemon->run; # app->start;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200314
315exit;
316
317__END__
318
319__C__
320#include <stdio.h>
321#include <string.h>
322#include <math.h>
323#include <malloc.h>
324#include <stdlib.h> //strlen
Marc Kupietzf0809762016-02-26 10:13:47 +0100325#include <sys/mman.h>
Marc Kupietz000ad862016-02-26 14:59:12 +0100326#include <pthread.h>
Marc Kupietze243efd2018-01-11 22:19:24 +0100327#include <collocatordb.h>
Marc Kupietzdc22b982015-10-09 09:19:34 +0200328
329#define max_size 2000
330#define max_w 50
Marc Kupietz7bc85fd2016-02-24 11:42:41 +0100331#define MAX_NEIGHBOURS 1000
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100332#define MAX_WORDS -1
Marc Kupietz000ad862016-02-26 14:59:12 +0100333#define MAX_THREADS 100
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100334#define MAX_CC 50
335#define EXP_TABLE_SIZE 1000
336#define MAX_EXP 6
Marc Kupietz271e2a42016-03-22 11:37:43 +0100337#define MIN_RESP 0.50
Marc Kupietzdc22b982015-10-09 09:19:34 +0200338
339//the thread function
340void *connection_handler(void *);
Marc Kupietz000ad862016-02-26 14:59:12 +0100341
342typedef struct {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100343 long long wordi;
344 long position;
345 float activation;
Marc Kupietz4116b432017-12-06 14:15:32 +0100346 float average;
Marc Kupietza77acce2017-11-30 16:59:07 +0100347 float cprobability; // column wise probability
Marc Kupietz4116b432017-12-06 14:15:32 +0100348 float cprobability_sum;
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100349 float probability;
Marc Kupietzd64f3f22017-11-30 12:07:42 +0100350 float activation_sum;
Marc Kupietzd64f3f22017-11-30 12:07:42 +0100351 float max_activation;
Marc Kupietz4116b432017-12-06 14:15:32 +0100352 float heat[16];
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100353} collocator;
354
355typedef struct {
356 collocator *best;
Marc Kupietz80abb442016-03-23 21:04:08 +0100357 int length;
Marc Kupietz000ad862016-02-26 14:59:12 +0100358} knn;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100359
Marc Kupietz000ad862016-02-26 14:59:12 +0100360typedef struct {
Marc Kupietz48c29682016-03-19 11:30:43 +0100361 long long wordi[MAX_NEIGHBOURS];
362 char sep[MAX_NEIGHBOURS];
363 int length;
364} wordlist;
365
366typedef struct {
Marc Kupietz2c79c5e2017-11-09 16:18:40 +0100367 long cutoff;
Marc Kupietz48c29682016-03-19 11:30:43 +0100368 wordlist *wl;
Marc Kupietz000ad862016-02-26 14:59:12 +0100369 char *token;
370 int N;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100371 long from;
Marc Kupietz000ad862016-02-26 14:59:12 +0100372 unsigned long upto;
Marc Kupietzc55c8872017-12-01 23:27:10 +0100373 collocator *best;
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100374 float *target_sums;
Marc Kupietzbd41da32017-11-24 10:26:43 +0100375 float *window_sums;
Marc Kupietz3c0fab12019-08-02 15:07:47 +0200376 float threshold;
Marc Kupietz000ad862016-02-26 14:59:12 +0100377} knnpars;
378
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100379typedef struct {
380 uint32_t index;
381 float value;
382} sparse_t;
383
384typedef struct {
385 uint32_t len;
386 sparse_t nbr[100];
387} profile_t;
388
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200389float *M, *M2=0L, *syn1neg_window, *expTable;
Marc Kupietzbd41da32017-11-24 10:26:43 +0100390float *window_sums;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200391char *vocab;
Marc Kupietz5c3887d2016-04-28 08:53:35 +0200392char *garbage = NULL;
Marc Kupietze243efd2018-01-11 22:19:24 +0100393COLLOCATORDB *cdb = NULL;
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100394profile_t *sprofiles = NULL;
395size_t sprofiles_qty = 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100396
Marc Kupietza2e64502016-04-27 09:53:51 +0200397long long words, size, merged_end;
Marc Kupietza5f60042017-05-04 10:38:12 +0200398long long merge_words = 0;
Marc Kupietz000ad862016-02-26 14:59:12 +0100399int num_threads=20;
Marc Kupietza5b90152016-03-15 17:39:19 +0100400int latin_enc=0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100401int window;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200402
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100403/* load collocation profiles if file exists */
404int load_sprofiles(char *vecsname) {
405 char *basename = strdup(vecsname);
406 char *pos = strstr(basename, ".vecs");
407 if(pos)
408 *pos=0;
409
410 char binsprofiles_fname[256];
411 strcpy(binsprofiles_fname, basename);
412 strcat(binsprofiles_fname, ".sprofiles.bin");
413 FILE *fp = fopen(binsprofiles_fname, "rb");
414 if (fp == NULL) {
415 printf("Collocation profiles %s not found. No problem.\n", binsprofiles_fname);
416 return 0;
417 }
418 fseek(fp, 0L, SEEK_END);
419 size_t sz = ftell(fp);
420 fclose(fp);
421
422 int fd = open(binsprofiles_fname, O_RDONLY);
423 sprofiles = mmap(0, sz, PROT_READ, MAP_SHARED, fd, 0);
424 if (sprofiles == MAP_FAILED) {
425 close(fd);
426 fprintf(stderr, "Cannot mmap %s\n", binsprofiles_fname);
427 sprofiles = NULL;
428 return 0;
429 } else {
430 sprofiles_qty = sz / sizeof(profile_t);
431 fprintf(stderr, "Successfully mmaped %s containing similar profiles for %ld word forms.\n", binsprofiles_fname, sprofiles_qty);
432 }
433 return 1;
434}
435
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100436int init_net(char *file_name, char *net_name, int latin) {
Marc Kupietz67c20282016-02-26 09:42:00 +0100437 FILE *f, *binvecs, *binwords;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100438 int binwords_fd, binvecs_fd, net_fd, i;
Marc Kupietz82b02672016-02-26 12:32:25 +0100439 long long a, b, c, d, cn;
440 float len;
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200441 double val;
Marc Kupietz82b02672016-02-26 12:32:25 +0100442
Marc Kupietz67c20282016-02-26 09:42:00 +0100443 char binvecs_fname[256], binwords_fname[256];
444 strcpy(binwords_fname, file_name);
445 strcat(binwords_fname, ".words");
446 strcpy(binvecs_fname, file_name);
447 strcat(binvecs_fname, ".vecs");
Marc Kupietzdc22b982015-10-09 09:19:34 +0200448
Marc Kupietza5b90152016-03-15 17:39:19 +0100449 latin_enc = latin;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200450 f = fopen(file_name, "rb");
451 if (f == NULL) {
452 printf("Input file %s not found\n", file_name);
453 return -1;
454 }
455 fscanf(f, "%lld", &words);
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100456 if(MAX_WORDS > 0 && words > MAX_WORDS) words = MAX_WORDS;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200457 fscanf(f, "%lld", &size);
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100458 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) < 0 || (binwords_fd = open(binwords_fname, O_RDONLY)) < 0) {
459 printf("Converting %s to memory mappable structures\n", file_name);
Marc Kupietzf0809762016-02-26 10:13:47 +0100460 vocab = (char *)malloc((long long)words * max_w * sizeof(char));
461 M = (float *)malloc((long long)words * (long long)size * sizeof(float));
462 if (M == NULL) {
463 printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size);
464 return -1;
465 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200466 if(strstr(file_name, ".txt")) {
467 for (b = 0; b < words; b++) {
468 a = 0;
469 while (1) {
470 vocab[b * max_w + a] = fgetc(f);
471 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
472 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
473 }
474 vocab[b * max_w + a] = 0;
475 len = 0;
476 for (a = 0; a < size; a++) {
477 fscanf(f, "%lf", &val);
478 M[a + b * size] = val;
479 len += val * val;
480 }
481 len = sqrt(len);
482 for (a = 0; a < size; a++) M[a + b * size] /= len;
483 }
484 } else {
485 for (b = 0; b < words; b++) {
486 a = 0;
487 while (1) {
488 vocab[b * max_w + a] = fgetc(f);
489 if (feof(f) || (vocab[b * max_w + a] == ' ')) break;
490 if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++;
491 }
492 vocab[b * max_w + a] = 0;
493 fread(&M[b * size], sizeof(float), size, f);
494 len = 0;
495 for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];
496 len = sqrt(len);
497 for (a = 0; a < size; a++) M[a + b * size] /= len;
498 }
499 }
Marc Kupietz67c20282016-02-26 09:42:00 +0100500 if( (binvecs = fopen(binvecs_fname, "wb")) != NULL && (binwords = fopen(binwords_fname, "wb")) != NULL) {
501 fwrite(M, sizeof(float), (long long)words * (long long)size, binvecs);
502 fclose(binvecs);
503 fwrite(vocab, sizeof(char), (long long)words * max_w, binwords);
504 fclose(binwords);
505 }
Marc Kupietz2cb667e2016-03-10 09:44:12 +0100506 }
507 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
508 M = mmap(0, sizeof(float) * (long long)words * (long long)size, PROT_READ, MAP_SHARED, binvecs_fd, 0);
509 vocab = mmap(0, sizeof(char) * (long long)words * max_w, PROT_READ, MAP_SHARED, binwords_fd, 0);
510 if (M == MAP_FAILED || vocab == MAP_FAILED) {
511 close(binvecs_fd);
512 close(binwords_fd);
513 fprintf(stderr, "Cannot mmap %s or %s\n", binwords_fname, binvecs_fname);
514 exit(-1);
515 }
516 } else {
517 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
518 exit(-1);
Marc Kupietz67c20282016-02-26 09:42:00 +0100519 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200520 fclose(f);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100521
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200522 if(net_name && strlen(net_name) > 0) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100523 if( (net_fd = open(net_name, O_RDONLY)) >= 0) {
524 window = (lseek(net_fd, 0, SEEK_END) - sizeof(float) * words * size) / words / size / sizeof(float) / 2;
525 // lseek(net_fd, sizeof(float) * words * size, SEEK_SET);
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100526 // munmap(M, sizeof(float) * words * size);
527 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 +0200528 if (M2 == MAP_FAILED) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100529 close(net_fd);
530 fprintf(stderr, "Cannot mmap %s\n", net_name);
531 exit(-1);
532 }
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100533 syn1neg_window = M2 + words * size;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100534 } else {
535 fprintf(stderr, "Cannot open %s\n", net_name);
536 exit(-1);
537 }
538 fprintf(stderr, "Successfully memmaped %s. Determined window size: %d\n", net_name, window);
Marc Kupietze243efd2018-01-11 22:19:24 +0100539
540 char collocatordb_name[2048];
541 strcpy(collocatordb_name, net_name);
542 char *ext = rindex(collocatordb_name, '.');
543 if(ext) {
544 strcpy(ext, ".rocksdb");
545 if(access(collocatordb_name, R_OK) == 0) {
546 *ext = 0;
547 fprintf(stderr, "Opening collocator DB %s\n", collocatordb_name);
548 cdb = open_collocatordb(collocatordb_name);
549 }
550 }
551 }
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100552
553 expTable = (float *) malloc((EXP_TABLE_SIZE + 1) * sizeof(float));
554 for (i = 0; i < EXP_TABLE_SIZE; i++) {
555 expTable[i] = exp((i / (float) EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
556 expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
557 }
Marc Kupietzbd41da32017-11-24 10:26:43 +0100558 window_sums = malloc(sizeof(float) * (window+1) * 2);
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100559
560 return 0;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200561}
562
Marc Kupietza2e64502016-04-27 09:53:51 +0200563long mergeVectors(char *file_name){
564 FILE *f, *binvecs, *binwords;
565 int binwords_fd, binvecs_fd, net_fd, i;
566 long long a, b, c, d, cn;
567 float len;
568 float *merge_vecs;
569 char *merge_vocab;
Marc Kupietza5f60042017-05-04 10:38:12 +0200570 /* long long merge_words, merge_size; */
571 long long merge_size;
Marc Kupietza2e64502016-04-27 09:53:51 +0200572
573 char binvecs_fname[256], binwords_fname[256];
574 strcpy(binwords_fname, file_name);
575 strcat(binwords_fname, ".words");
576 strcpy(binvecs_fname, file_name);
577 strcat(binvecs_fname, ".vecs");
578
579 f = fopen(file_name, "rb");
580 if (f == NULL) {
581 printf("Input file %s not found\n", file_name);
582 exit -1;
583 }
584 fscanf(f, "%lld", &merge_words);
585 fscanf(f, "%lld", &merge_size);
586 if(merge_size != size){
587 fprintf(stderr, "vectors must have the same length\n");
588 exit(-1);
589 }
590 if( (binvecs_fd = open(binvecs_fname, O_RDONLY)) >= 0 && (binwords_fd = open(binwords_fname, O_RDONLY)) >= 0) {
591 merge_vecs = malloc(sizeof(float) * (words + merge_words) * size);
592 merge_vocab = malloc(sizeof(char) * (words + merge_words) * max_w);
593 if (merge_vecs == NULL || merge_vocab == NULL) {
594 close(binvecs_fd);
595 close(binwords_fd);
596 fprintf(stderr, "Cannot reserve memory for %s or %s\n", binwords_fname, binvecs_fname);
597 exit(-1);
598 }
599 read(binvecs_fd, merge_vecs, merge_words * size * sizeof(float));
600 read(binwords_fd, merge_vocab, merge_words * max_w);
601 } else {
602 fprintf(stderr, "Cannot open %s or %s\n", binwords_fname, binvecs_fname);
603 exit(-1);
604 }
605 printf("Successfully reallocated memory\nMerging...\n");
606 fflush(stdout);
607 memcpy(merge_vecs + merge_words * size, M, words * size * sizeof(float));
608 memcpy(merge_vocab + merge_words * max_w, vocab, words * max_w);
609 munmap(M, words * size * sizeof(float));
610 munmap(vocab, words * max_w);
611 M = merge_vecs;
612 vocab = merge_vocab;
613 merged_end = merge_words;
614 words += merge_words;
615 fclose(f);
616 printf("merged_end: %lld, words: %lld\n", merged_end, words);
Marc Kupietzd7760b42019-02-21 09:01:44 +0100617 //printBiggestMergedDifferences();
Marc Kupietza2e64502016-04-27 09:53:51 +0200618 return((long) merged_end);
619}
620
Marc Kupietz5c3887d2016-04-28 08:53:35 +0200621void filter_garbage() {
622 long i;
Marc Kupietzab591a82016-04-28 14:08:49 +0200623 unsigned char *w, previous, c;
Marc Kupietz5c3887d2016-04-28 08:53:35 +0200624 garbage = malloc(words);
625 memset(garbage, 0, words);
626 for (i = 0; i < words; i++) {
627 w = vocab + i * max_w;
628 previous = 0;
Marc Kupietz969adfa2018-03-12 09:43:53 +0100629 if(strncmp("quot", w, 4) == 0) {
630 garbage[i]=1;
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100631// printf("Gargabe: %s\n", vocab + i * max_w);
Marc Kupietz969adfa2018-03-12 09:43:53 +0100632 } else {
633 while((c = *w++) && !garbage[i]) {
634 if( ((c <= 90 && c >= 65) && (previous >= 97 && previous <= 122)) ||
635 (previous == '-' && (c & 32)) ||
636 (previous == 0xc2 && (c == 0xa4 || c == 0xb6 )) ||
637 (previous == 'q' && c == 'u' && *(w) == 'o' && *(w+1) == 't') || /* quot */
638 c == '<'
639 ) {
640 garbage[i]=1;
641 continue;
642 }
643 previous = c;
Marc Kupietz5c3887d2016-04-28 08:53:35 +0200644 }
Marc Kupietz5c3887d2016-04-28 08:53:35 +0200645 }
646 }
647 return;
648}
649
Marc Kupietzac707b32018-12-20 11:36:38 +0100650
651knn *simpleGetCollocators(int word, int number, long cutoff, int *result) {
652 knnpars *pars = calloc(sizeof(knnpars), 1);
653 float *target_sums;
654 float *window_sums = malloc(sizeof(float) * (window+1) * 2);
655 pars->cutoff = (cutoff? cutoff : 300000);
656 long a = posix_memalign((void **) &target_sums, 128, pars->cutoff * sizeof(float));
657 for(a = 0; a < cutoff; a++)
658 target_sums[a] = 0;
659 pars->target_sums = target_sums;
660 pars->window_sums = window_sums;
661 pars->N = (number? number : 20);
662 pars->from = 0;
663 pars->upto = window * 2 -1;
Marc Kupietz7631e022019-01-25 12:04:42 +0100664 knn *syn_nbs = NULL; // = (knn*) getCollocators(pars);
Marc Kupietzac707b32018-12-20 11:36:38 +0100665 free(pars);
666 free(window_sums);
667 free(target_sums);
668 return syn_nbs;
669}
670
Marc Kupietz580ebdf2017-11-29 21:18:38 +0100671void *getCollocators(void *args) {
672 knnpars *pars = args;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100673 int N = pars->N;
Marc Kupietz52702832019-01-15 17:55:52 +0100674
Marc Kupietz271e2a42016-03-22 11:37:43 +0100675 int cc = pars->wl->wordi[0];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100676 knn *nbs = NULL;
677 long window_layer_size = size * window * 2;
678 long a, b, c, d, e, window_offset, target, max_target=0, maxmax_target;
679 float f, max_f, maxmax_f;
Marc Kupietz7631e022019-01-25 12:04:42 +0100680 float *target_sums=NULL, worstbest, wpos_sum;
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100681 collocator *best;
Marc Kupietzd5642582016-03-19 22:23:13 +0100682
Marc Kupietz43ee87e2016-04-25 10:50:08 +0200683 if(M2 == NULL || cc == -1)
Marc Kupietzd5642582016-03-19 22:23:13 +0100684 return NULL;
685
Marc Kupietz2c79c5e2017-11-09 16:18:40 +0100686 a = posix_memalign((void **) &target_sums, 128, pars->cutoff * sizeof(float));
Marc Kupietz7631e022019-01-25 12:04:42 +0100687 memset(target_sums, 0, pars->cutoff * sizeof(float));
688 best = malloc((N>200?N:200) * sizeof(collocator));
689 memset(best, 0, (N>200?N:200) * sizeof(collocator));
Marc Kupietz3c0fab12019-08-02 15:07:47 +0200690 worstbest = pars->threshold;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100691
Marc Kupietz2c79c5e2017-11-09 16:18:40 +0100692 for (b = 0; b < pars->cutoff; b++)
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100693 target_sums[b]=0;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100694 for (b = 0; b < N; b++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100695 best[b].wordi = -1;
696 best[b].probability = 1;
697 best[b].activation = worstbest;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100698 }
Marc Kupietz271e2a42016-03-22 11:37:43 +0100699
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100700 d = cc;
701 maxmax_f = -1;
702 maxmax_target = 0;
703
Marc Kupietz271e2a42016-03-22 11:37:43 +0100704 for (a = pars->from; a < pars->upto; a++) {
705 if(a >= window)
706 a++;
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100707 wpos_sum = 0;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100708 printf("window pos: %ld\n", a);
709 if (a != window) {
710 max_f = -1;
711 window_offset = a * size;
712 if (a > window)
713 window_offset -= size;
Marc Kupietz2c79c5e2017-11-09 16:18:40 +0100714 for(target = 0; target < pars->cutoff; target ++) {
715 if(garbage && garbage[target]) continue;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100716 if(target == d)
717 continue;
718 f = 0;
719 for (c = 0; c < size; c++)
Marc Kupietz10bec2b2016-03-23 09:41:31 +0100720 f += M2[d* size + c] * syn1neg_window[target * window_layer_size + window_offset + c];
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100721 if (f < -MAX_EXP)
722 continue;
723 else if (f > MAX_EXP)
724 continue;
725 else
726 f = expTable[(int) ((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
Marc Kupietzb864ccf2016-03-21 22:40:03 +0100727 wpos_sum += f;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100728
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100729 target_sums[target] += f;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100730 if(f > worstbest) {
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100731 for (b = 0; b < N; b++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100732 if (f > best[b].activation) {
733 memmove(best + b + 1, best + b, (N - b -1) * sizeof(collocator));
734 best[b].activation = f;
735 best[b].wordi = target;
736 best[b].position = window-a;
Marc Kupietz33679a32016-03-22 08:49:39 +0100737 break;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100738 }
739 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +0100740 if(b == N - 1)
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100741 worstbest = best[N-1].activation;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100742 }
743 }
744 printf("%d %.2f\n", max_target, max_f);
745 printf("%s (%.2f) ", &vocab[max_target * max_w], max_f);
746 if(max_f > maxmax_f) {
747 maxmax_f = max_f;
748 maxmax_target = max_target;
749 }
Marc Kupietz33679a32016-03-22 08:49:39 +0100750 for (b = 0; b < N; b++)
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100751 if(best[b].position == window-a)
Marc Kupietza77acce2017-11-30 16:59:07 +0100752 best[b].cprobability = best[b].activation / wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100753 } else {
754 printf("\x1b[1m%s\x1b[0m ", &vocab[d*max_w]);
755 }
Marc Kupietzbd41da32017-11-24 10:26:43 +0100756 pars->window_sums[a] = wpos_sum;
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100757 }
Marc Kupietz2c79c5e2017-11-09 16:18:40 +0100758 for (b = 0; b < pars->cutoff; b++)
Marc Kupietza77acce2017-11-30 16:59:07 +0100759 pars->target_sums[b] += target_sums[b]; //(target_sums[b] / wpos_sum ) / (window * 2);
Marc Kupietzd89431f2019-08-02 15:06:38 +0200760
Marc Kupietzce3d4c62016-03-23 16:11:25 +0100761 free(target_sums);
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100762 for(b=0; b<N && best[b].wordi >= 0; b++);; // THIS LOOP IS NEEDED (b...)
763// printf("%d: best syn: %s %.2f %.5f\n", b, &vocab[best[b].wordi*max_w], best[b].activation, best[b].probability);
Marc Kupietzbd41da32017-11-24 10:26:43 +0100764// printf("\n");
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100765 nbs = malloc(sizeof(knn));
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100766 nbs->best = best;
Marc Kupietz271e2a42016-03-22 11:37:43 +0100767 nbs->length = b-1;
768 pthread_exit(nbs);
Marc Kupietz6b2975c2016-03-18 21:59:33 +0100769}
770
Marc Kupietz30ca4342017-11-22 21:21:20 +0100771
Marc Kupietz66bfd952017-12-11 09:59:45 +0100772AV *getVecs(AV *array) {
773 int i, b;
774 AV *result = newAV();
775 for (i=0; i<=av_len(array); i++) {
776 SV** elem = av_fetch(array, i, 0);
777 if (elem != NULL) {
778 long j = (long) SvNV(*elem);
779 AV *vector = newAV();
780 for (b = 0; b < size; b++) {
781 av_push(vector, newSVnv(M[b + j * size]));
782 }
783 av_push(result, newRV_noinc(vector));
784 }
785 }
786 return result;
787}
788
Marc Kupietza51dcfa2018-03-19 16:22:05 +0100789char *getSimilarProfiles(long node) {
790 int i;
791 char buffer[120000];
792 char pair_buffer[2048];
793 buffer[0]='[';
794 buffer[1]=0;
795 if(node >= sprofiles_qty) {
796 printf("Not available in precomputed profile\n");
797 return(strdup("[{\"w\":\"not available\", \"v\":0}]\n"));
798 }
799
800 printf("******* %s ******\n", &vocab[max_w * node]);
801
802 for(i=0; i < 100 && i < sprofiles[node].len; i++) {
803 sprintf(pair_buffer, "{\"w\":\"%s\", \"v\":%f},", &vocab[max_w * (sprofiles[node].nbr[i].index)], sprofiles[node].nbr[i].value);
804 strcat(buffer, pair_buffer);
805 }
806 buffer[strlen(buffer)-1]=']';
807 strcat(buffer, "\n");
808 printf(buffer);
809 return(strdup(buffer));
810}
811
Marc Kupietze243efd2018-01-11 22:19:24 +0100812char *getClassicCollocators(long node) {
813 char *res = (cdb? strdup(get_collocators_as_json(cdb, node)) : "[]");
814 return res;
815}
816
Marc Kupietz0957d532019-01-03 17:54:00 +0100817wordlist *getTargetWords(char *st1, int search_backw) {
Marc Kupietz48c29682016-03-19 11:30:43 +0100818 wordlist *wl = malloc(sizeof(wordlist));
819 char st[100][max_size], sep[100];
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100820 long a, b=0, c=0, cn=0;
Marc Kupietza2e64502016-04-27 09:53:51 +0200821 int unmerged;
822
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100823 while (1) {
824 st[cn][b] = st1[c];
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100825 b++;
826 c++;
827 st[cn][b] = 0;
828 if (st1[c] == 0) break;
829 if (st1[c] == ' ' || st1[c] == '-') {
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100830 sep[cn++] = st1[c];
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100831 b = 0;
832 c++;
833 }
834 }
835 cn++;
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100836 for (a = 0; a < cn; a++) {
837 if (search_backw) {
Marc Kupietz3082fd02019-01-09 14:54:06 +0100838 for (b = words - 1; b >= (merge_words? merge_words : 0) && strcmp(&vocab[b * max_w], st[a]) !=0; b--);
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100839 } else {
Marc Kupietz3082fd02019-01-09 14:54:06 +0100840 for (b = 0; b < (merge_words? merge_words : words) && strcmp(&vocab[b * max_w], st[a]) != 0; b++);
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100841 }
842 if (b == words) b = -1;
843 wl->wordi[a] = b;
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100844 if (b == -1) {
845 fprintf(stderr, "Out of dictionary word!\n");
846 cn--;
Marc Kupietz3082fd02019-01-09 14:54:06 +0100847 } else {
848 fprintf(stderr, "Word: \"%s\" Position in vocabulary: %lld\n", &vocab[wl->wordi[a]*max_w], wl->wordi[a]);
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100849 }
850 }
Marc Kupietz48c29682016-03-19 11:30:43 +0100851 wl->length=cn;
852 return(wl);
853}
Marc Kupietz1f36dfa2019-01-03 16:18:12 +0100854
Marc Kupietz98ed1c02019-08-02 15:05:37 +0200855float get_distance(long b, long c) {
856 long a;
857 float dist = 0;
858 for (a = 0; a < size; a++) dist += M[a + c * size] * M[a + b * size];
859 return dist;
860}
861
Marc Kupietzd7760b42019-02-21 09:01:44 +0100862char *getBiggestMergedDifferences() {
863 static char *result = NULL;
Marc Kupietzebc131e2019-01-03 16:24:27 +0100864 float dist, len, vec[max_size];
865 long long a, b, c, d, cn, *bi;
866 char ch;
867 knn *nbs = NULL;
Marc Kupietzd7760b42019-02-21 09:01:44 +0100868 int N = 1000;
869
Marc Kupietzb6514dc2019-06-26 11:47:56 +0200870 if(merged_end == 0)
871 result = "[]";
872
Marc Kupietzd7760b42019-02-21 09:01:44 +0100873 if(result != NULL)
874 return result;
Marc Kupietzebc131e2019-01-03 16:24:27 +0100875
876 printf("Looking for biggest distances between main and merged vectors ...\n");
877 collocator *best;
878 best = malloc(N * sizeof(collocator));
879 memset(best, 0, N * sizeof(collocator));
880
881 float worstbest=1000000;
882
883 for (a = 0; a < N; a++) best[a].activation = worstbest;
884
Marc Kupietz2da2a812019-02-21 14:17:35 +0100885 for (c = 0; c < 500000; c++) {
Marc Kupietzebc131e2019-01-03 16:24:27 +0100886 if(garbage && garbage[c]) continue;
887 a = 0;
888 dist = 0;
889 for (a = 0; a < size; a++) dist += M[a + c * size] * M[a + (c+merged_end) * size];
890 if(dist < worstbest) {
891 for (a = 0; a < N; a++) {
892 if (dist < best[a].activation) {
893 memmove(best + a + 1, best + a, (N - a -1) * sizeof(collocator));
894 best[a].activation = dist;
895 best[a].wordi = c;
896 break;
897 }
898 }
899 worstbest = best[N-1].activation;
900 }
901 }
902
Marc Kupietzd7760b42019-02-21 09:01:44 +0100903 result = malloc(N*max_w);
904 char *p = result;
905 *p++ = '['; *p = 0;
Marc Kupietzebc131e2019-01-03 16:24:27 +0100906 for (a = 0; a < N; a++) {
Marc Kupietzd7760b42019-02-21 09:01:44 +0100907 p += sprintf(p, "{\"rank\":%d,\"word\":\"%s\",\"dist\":%.3f},", a, &vocab[best[a].wordi * max_w], 1-best[a].activation);
Marc Kupietzebc131e2019-01-03 16:24:27 +0100908 }
Marc Kupietzd7760b42019-02-21 09:01:44 +0100909 *--p = ']';
910 return(result);
Marc Kupietzebc131e2019-01-03 16:24:27 +0100911}
912
Marc Kupietz98ed1c02019-08-02 15:05:37 +0200913
914float cos_similarity(long b, long c) {
915 float dist=0;
916 long a;
917 for (a = 0; a < size; a++) dist += M[b * size + a] * M[c * size + a];
918 return dist;
919}
920
921char *cos_similarity_as_json(char *w1, char *w2) {
922 wordlist *a, *b;
923 float res;
924 a = getTargetWords(w1, 0);
925 b = getTargetWords(w2, 0);
926 if (a == NULL || b==NULL || a->length != 1 || b->length != 1)
927 res = -1;
928 else
929 res = cos_similarity(a->wordi[0], b->wordi[0]);
930 fprintf(stderr, "a: %lld b: %lld res:%f\n", a->wordi[0], b->wordi[0], res);
931 char *json = malloc(16);
932 sprintf(json, "%.5f", res);
933 return json;
934}
935
Marc Kupietz580ebdf2017-11-29 21:18:38 +0100936void *_get_neighbours(void *arg) {
937 knnpars *pars = arg;
Marc Kupietz48c29682016-03-19 11:30:43 +0100938 char *st1 = pars->token;
939 int N = pars->N;
940 long from = pars -> from;
941 unsigned long upto = pars -> upto;
942 char file_name[max_size], st[100][max_size], *sep;
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100943 float dist, len, vec[max_size];
944 long long a, b, c, d, cn, *bi;
Marc Kupietz48c29682016-03-19 11:30:43 +0100945 char ch;
946 knn *nbs = NULL;
947 wordlist *wl = pars->wl;
948
Marc Kupietzc55c8872017-12-01 23:27:10 +0100949 collocator *best = pars->best;
Marc Kupietz48c29682016-03-19 11:30:43 +0100950
951 float worstbest=-1;
952
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100953 for (a = 0; a < N; a++) best[a].activation = 0;
Marc Kupietz48c29682016-03-19 11:30:43 +0100954 a = 0;
955 bi = wl->wordi;
956 cn = wl->length;
957 sep = wl->sep;
958 b = bi[0];
959 c = 0;
Marc Kupietz000ad862016-02-26 14:59:12 +0100960 if (b == -1) {
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100961 N = 0;
962 goto end;
963 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200964 for (a = 0; a < size; a++) vec[a] = 0;
965 for (b = 0; b < cn; b++) {
966 if (bi[b] == -1) continue;
Marc Kupietz95aa1c02016-03-15 09:40:43 +0100967 if(b>0 && sep[b-1] == '-')
968 for (a = 0; a < size; a++) vec[a] -= M[a + bi[b] * size];
969 else
970 for (a = 0; a < size; a++) vec[a] += M[a + bi[b] * size];
Marc Kupietzdc22b982015-10-09 09:19:34 +0200971 }
972 len = 0;
973 for (a = 0; a < size; a++) len += vec[a] * vec[a];
974 len = sqrt(len);
975 for (a = 0; a < size; a++) vec[a] /= len;
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100976 for (a = 0; a < N; a++) best[a].activation = -1;
Marc Kupietz000ad862016-02-26 14:59:12 +0100977 for (c = from; c < upto; c++) {
Marc Kupietz5c3887d2016-04-28 08:53:35 +0200978 if(garbage && garbage[c]) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200979 a = 0;
Marc Kupietz34020dc2016-02-25 08:44:19 +0100980// do not skip taget word
Marc Kupietze8da3062016-02-25 08:37:53 +0100981// for (b = 0; b < cn; b++) if (bi[b] == c) a = 1;
982// if (a == 1) continue;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200983 dist = 0;
984 for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100985 if(dist > worstbest) {
986 for (a = 0; a < N; a++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100987 if (dist > best[a].activation) {
988 memmove(best + a + 1, best + a, (N - a -1) * sizeof(collocator));
989 best[a].activation = dist;
990 best[a].wordi = c;
Marc Kupietzbe1b9fc2016-02-26 10:34:30 +0100991 break;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200992 }
Marc Kupietzdc22b982015-10-09 09:19:34 +0200993 }
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +0100994 worstbest = best[N-1].activation;
Marc Kupietzdc22b982015-10-09 09:19:34 +0200995 }
996 }
Marc Kupietz34020dc2016-02-25 08:44:19 +0100997
Marc Kupietz44bee3c2016-02-25 16:26:29 +0100998end:
Marc Kupietz000ad862016-02-26 14:59:12 +0100999 pthread_exit(nbs);
Marc Kupietzdc22b982015-10-09 09:19:34 +02001000}
1001
Marc Kupietze0e42132017-11-24 16:44:34 +01001002int cmp_activation (const void * a, const void * b) {
1003 float fb = ((collocator *)a)->activation;
1004 float fa = ((collocator *)b)->activation;
1005 return (fa > fb) - (fa < fb);
1006}
1007
1008int cmp_probability (const void * a, const void * b) {
1009 float fb = ((collocator *)a)->probability;
1010 float fa = ((collocator *)b)->probability;
1011 return (fa > fb) - (fa < fb);
1012}
1013
Marc Kupietz6b2975c2016-03-18 21:59:33 +01001014
Marc Kupietzac707b32018-12-20 11:36:38 +01001015SV *get_neighbours(char *st1, int N, int sort_by, int search_backw, long cutoff, int dedupe, int no_similar_profiles) {
Marc Kupietz6b2975c2016-03-18 21:59:33 +01001016 HV *result = newHV();
Marc Kupietz7631e022019-01-25 12:04:42 +01001017 float *target_sums=NULL, vec[max_size];
Marc Kupietza5f60042017-05-04 10:38:12 +02001018 long long old_words;
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001019 long a, b, c, d, slice;
Marc Kupietz271e2a42016-03-22 11:37:43 +01001020 knn *para_nbs[MAX_THREADS];
1021 knn *syn_nbs[MAX_THREADS];
Marc Kupietz000ad862016-02-26 14:59:12 +01001022 knnpars pars[MAX_THREADS];
Marc Kupietz6b2975c2016-03-18 21:59:33 +01001023 pthread_t *pt = (pthread_t *)malloc((num_threads+1) * sizeof(pthread_t));
Marc Kupietz48c29682016-03-19 11:30:43 +01001024 wordlist *wl;
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001025 int syn_threads = (M2? window * 2 : 0);
Marc Kupietzac707b32018-12-20 11:36:38 +01001026 int para_threads = (no_similar_profiles? 0 : num_threads - syn_threads);
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001027
Marc Kupietz7631e022019-01-25 12:04:42 +01001028 collocator *best = NULL;
1029 posix_memalign((void **) &best, 128, 10 * (N>=200? N : 200) * sizeof(collocator));
1030 memset(best, 0, (N>=200? N : 200) * sizeof(collocator));
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001031
Marc Kupietz000ad862016-02-26 14:59:12 +01001032 if(N>MAX_NEIGHBOURS) N=MAX_NEIGHBOURS;
1033
Marc Kupietzd5d05732018-01-30 11:57:35 +01001034 if(cutoff < 1 || cutoff > words)
Marc Kupietz2c79c5e2017-11-09 16:18:40 +01001035 cutoff=words;
1036
Marc Kupietza2e64502016-04-27 09:53:51 +02001037 wl = getTargetWords(st1, search_backw);
Marc Kupietzf9ac54e2017-11-21 09:22:29 +01001038 if(wl == NULL || wl->length < 1)
Marc Kupietz271e2a42016-03-22 11:37:43 +01001039 goto end;
Marc Kupietz48c29682016-03-19 11:30:43 +01001040
Marc Kupietz2c79c5e2017-11-09 16:18:40 +01001041 old_words = cutoff;
Marc Kupietz3082fd02019-01-09 14:54:06 +01001042 slice = cutoff / para_threads;
Marc Kupietza5f60042017-05-04 10:38:12 +02001043
Marc Kupietz2c79c5e2017-11-09 16:18:40 +01001044 a = posix_memalign((void **) &target_sums, 128, cutoff * sizeof(float));
Marc Kupietz7631e022019-01-25 12:04:42 +01001045 memset(target_sums, 0, cutoff * sizeof(float));
Marc Kupietzce3d4c62016-03-23 16:11:25 +01001046
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001047 printf("Starting %d threads\n", para_threads);
1048 fflush(stdout);
Marc Kupietz271e2a42016-03-22 11:37:43 +01001049 for(a=0; a < para_threads; a++) {
Marc Kupietz2c79c5e2017-11-09 16:18:40 +01001050 pars[a].cutoff = cutoff;
Marc Kupietz000ad862016-02-26 14:59:12 +01001051 pars[a].token = st1;
Marc Kupietz48c29682016-03-19 11:30:43 +01001052 pars[a].wl = wl;
Marc Kupietz000ad862016-02-26 14:59:12 +01001053 pars[a].N = N;
Marc Kupietzc55c8872017-12-01 23:27:10 +01001054 pars[a].best = &best[N*a];
Marc Kupietz3082fd02019-01-09 14:54:06 +01001055 if(merge_words == 0 || search_backw == 0) {
Marc Kupietz1f0f7802019-01-03 16:23:29 +01001056 pars[a].from = a*slice;
1057 pars[a].upto = ((a+1)*slice > cutoff? cutoff : (a+1) * slice);
1058 } else {
Marc Kupietz3082fd02019-01-09 14:54:06 +01001059 pars[a].from = merge_words + a * slice;
1060 pars[a].upto = merge_words + ((a+1)*slice > cutoff? cutoff : (a+1) * slice);
Marc Kupietz1f0f7802019-01-03 16:23:29 +01001061 }
1062 printf("From: %ld, Upto: %ld\n", pars[a].from, pars[a].upto);
Marc Kupietz000ad862016-02-26 14:59:12 +01001063 pthread_create(&pt[a], NULL, _get_neighbours, (void *) &pars[a]);
1064 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001065 if(M2) {
1066 for(a=0; a < syn_threads; a++) {
Marc Kupietz2c79c5e2017-11-09 16:18:40 +01001067 pars[a + para_threads].cutoff = cutoff;
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001068 pars[a + para_threads].target_sums = target_sums;
Marc Kupietzbd41da32017-11-24 10:26:43 +01001069 pars[a + para_threads].window_sums = window_sums;
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001070 pars[a + para_threads].wl = wl;
1071 pars[a + para_threads].N = N;
Marc Kupietz3c0fab12019-08-02 15:07:47 +02001072 pars[a + para_threads].threshold = MIN_RESP;
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001073 pars[a + para_threads].from = a;
1074 pars[a + para_threads].upto = a+1;
1075 pthread_create(&pt[a + para_threads], NULL, getCollocators, (void *) &pars[a + para_threads]);
1076 }
Marc Kupietz271e2a42016-03-22 11:37:43 +01001077 }
1078 printf("Waiting for para threads to join\n");
1079 fflush(stdout);
Marc Kupietz580ebdf2017-11-29 21:18:38 +01001080 for (a = 0; a < para_threads; a++) pthread_join(pt[a], (void *) &para_nbs[a]);
Marc Kupietz271e2a42016-03-22 11:37:43 +01001081 printf("Para threads joint\n");
1082 fflush(stdout);
Marc Kupietz000ad862016-02-26 14:59:12 +01001083
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001084 /* if(!syn_nbs[0]) */
1085 /* goto end; */
Marc Kupietz000ad862016-02-26 14:59:12 +01001086
Marc Kupietzc55c8872017-12-01 23:27:10 +01001087 qsort(best, N*para_threads, sizeof(collocator), cmp_activation);
Marc Kupietz000ad862016-02-26 14:59:12 +01001088
Marc Kupietz000ad862016-02-26 14:59:12 +01001089
Marc Kupietzd0d3e912017-12-01 22:09:43 +01001090 long long chosen[MAX_NEIGHBOURS];
1091 printf("N: %ld\n", N);
1092
Marc Kupietz271e2a42016-03-22 11:37:43 +01001093 AV* array = newAV();
Marc Kupietzd91212f2017-11-13 10:05:09 +01001094 int i, j;
Marc Kupietza5f60042017-05-04 10:38:12 +02001095 int l1_words=0, l2_words=0;
Marc Kupietzd0d3e912017-12-01 22:09:43 +01001096
1097 for (a = 0, i = 0; i < N && a < N*para_threads; a++) {
Marc Kupietzd91212f2017-11-13 10:05:09 +01001098 int filtered=0;
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001099 long long c = best[a].wordi;
Marc Kupietze8b9dd22019-01-03 17:55:59 +01001100 if ((merge_words && dedupe && i > 1) || (!merge_words && dedupe && i > 0)) {
Marc Kupietzd0d3e912017-12-01 22:09:43 +01001101 for (j=0; j<i && !filtered; j++)
1102 if (strcasestr(&vocab[c * max_w], &vocab[chosen[j] * max_w]) ||
1103 strcasestr(&vocab[chosen[j] * max_w], &vocab[c * max_w])) {
1104 printf("filtering %s %s\n", &vocab[chosen[j] * max_w], &vocab[c * max_w]);
Marc Kupietzd91212f2017-11-13 10:05:09 +01001105 filtered = 1;
1106 }
1107 if(filtered)
1108 continue;
1109 }
Marc Kupietz3082fd02019-01-09 14:54:06 +01001110
1111
1112 if(0 && merge_words > 0) {
Marc Kupietza5f60042017-05-04 10:38:12 +02001113 if(c >= merge_words) {
1114 if(l1_words > N / 2)
1115 continue;
1116 else
1117 l1_words++;
1118 } else {
1119 if(l2_words > N / 2)
1120 continue;
1121 else
1122 l2_words++;
1123 }
1124 }
Marc Kupietz3082fd02019-01-09 14:54:06 +01001125
1126// printf("%s l1:%d l2:%d i:%d a:%ld\n", &vocab[c * max_w], l1_words, l2_words, i, a);
1127// fflush(stdout);
Marc Kupietz271e2a42016-03-22 11:37:43 +01001128 HV* hash = newHV();
Marc Kupietza5f60042017-05-04 10:38:12 +02001129 SV* word = newSVpvf(&vocab[c * max_w], 0);
Marc Kupietzd0d3e912017-12-01 22:09:43 +01001130 chosen[i] = c;
Marc Kupietz271e2a42016-03-22 11:37:43 +01001131 if(latin_enc == 0) SvUTF8_on(word);
Marc Kupietza5f60042017-05-04 10:38:12 +02001132 fflush(stdout);
Marc Kupietz271e2a42016-03-22 11:37:43 +01001133 hv_store(hash, "word", strlen("word"), word , 0);
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001134 hv_store(hash, "dist", strlen("dist"), newSVnv(best[a].activation), 0);
1135 hv_store(hash, "rank", strlen("rank"), newSVuv(best[a].wordi), 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +01001136 AV *vector = newAV();
1137 for (b = 0; b < size; b++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001138 av_push(vector, newSVnv(M[b + best[a].wordi * size]));
Marc Kupietz6b2975c2016-03-18 21:59:33 +01001139 }
Marc Kupietz271e2a42016-03-22 11:37:43 +01001140 hv_store(hash, "vector", strlen("vector"), newRV_noinc((SV*)vector), 0);
1141 av_push(array, newRV_noinc((SV*)hash));
Marc Kupietza5f60042017-05-04 10:38:12 +02001142 i++;
Marc Kupietz271e2a42016-03-22 11:37:43 +01001143 }
1144 hv_store(result, "paradigmatic", strlen("paradigmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz7631e022019-01-25 12:04:42 +01001145
Marc Kupietz50485ba2016-03-23 09:13:14 +01001146 for(b=0; b < MAX_NEIGHBOURS; b++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001147 best[b].wordi = -1L;
1148 best[b].activation = 0;
1149 best[b].probability = 0;
1150 best[b].position = 0;
1151 best[b].activation_sum = 0;
Marc Kupietz7631e022019-01-25 12:04:42 +01001152 memset(best[b].heat, 0, sizeof(float)*16);
Marc Kupietz50485ba2016-03-23 09:13:14 +01001153 }
1154
Marc Kupietza77acce2017-11-30 16:59:07 +01001155 float total_activation = 0;
1156
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001157 if (M2) {
1158 printf("Waiting for syn threads to join\n");
1159 fflush(stdout);
Marc Kupietz580ebdf2017-11-29 21:18:38 +01001160 for (a = 0; a < syn_threads; a++) pthread_join(pt[a+para_threads], (void *) &syn_nbs[a]);
Marc Kupietza77acce2017-11-30 16:59:07 +01001161 for (a = 0; a <= syn_threads; a++) {
Marc Kupietz63872182018-03-12 09:44:49 +01001162 if(a == window) continue;
Marc Kupietza77acce2017-11-30 16:59:07 +01001163 total_activation += window_sums[a];
1164 printf("window pos: %d, sum: %f\n", a, window_sums[a]);
1165 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001166 printf("syn threads joint\n");
1167 fflush(stdout);
Marc Kupietz50485ba2016-03-23 09:13:14 +01001168
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001169 for(b=0; b < syn_nbs[0]->length; b++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001170 memcpy(best + b, &syn_nbs[0]->best[b], sizeof(collocator));
1171 best[b].position = -1; // syn_nbs[0]->pos[b];
1172 best[b].activation_sum = target_sums[syn_nbs[0]->best[b].wordi];
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001173 best[b].max_activation = 0.0;
Marc Kupietz4116b432017-12-06 14:15:32 +01001174 best[b].average = 0.0;
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001175 best[b].probability = 0.0;
Marc Kupietza77acce2017-11-30 16:59:07 +01001176 best[b].cprobability = syn_nbs[0]->best[b].cprobability;
Marc Kupietz7631e022019-01-25 12:04:42 +01001177 memset(best[b].heat, 0, sizeof(float)*16);
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001178 }
Marc Kupietz30ca4342017-11-22 21:21:20 +01001179
1180 float best_window_sum[MAX_NEIGHBOURS];
1181 int found_index=0, i=0, j, w;
Marc Kupietz580ebdf2017-11-29 21:18:38 +01001182 for(a=0; a < syn_threads; a++) {
1183 for(b=0; b < syn_nbs[a]->length; b++) {
1184 for(i=0; i < found_index; i++)
1185 if(best[i].wordi == syn_nbs[a]->best[b].wordi)
1186 break;
1187 if(i >= found_index) {
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001188 best[found_index].max_activation = 0.0;
Marc Kupietz4116b432017-12-06 14:15:32 +01001189 best[found_index].average = 0.0;
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001190 best[found_index].probability = 0.0;
Marc Kupietz7631e022019-01-25 12:04:42 +01001191 memset(best[found_index].heat, 0, sizeof(float)*16);
Marc Kupietza77acce2017-11-30 16:59:07 +01001192 best[found_index].cprobability = syn_nbs[a]->best[b].cprobability;
1193 best[found_index].activation_sum = target_sums[syn_nbs[a]->best[b].wordi]; // syn_nbs[a]->best[b].activation_sum;
Marc Kupietz580ebdf2017-11-29 21:18:38 +01001194 best[found_index++].wordi = syn_nbs[a]->best[b].wordi;
1195 // printf("found: %s\n", &vocab[syn_nbs[a]->index[b] * max_w]);
Marc Kupietz30ca4342017-11-22 21:21:20 +01001196 }
1197 }
Marc Kupietz580ebdf2017-11-29 21:18:38 +01001198 }
Marc Kupietza77acce2017-11-30 16:59:07 +01001199 sort_by =0; // ALWAYS AUTO-FOCUS
Marc Kupietz580ebdf2017-11-29 21:18:38 +01001200 if(sort_by != 1 && sort_by != 2) { // sort by auto focus mean
Marc Kupietz30ca4342017-11-22 21:21:20 +01001201 printf("window: %d - syn_threads: %d, %d\n", window, syn_threads, (1 << syn_threads) -1);
Marc Kupietzbd41da32017-11-24 10:26:43 +01001202 int wpos;
Marc Kupietz4116b432017-12-06 14:15:32 +01001203 int bits_set = 0;
Marc Kupietz30ca4342017-11-22 21:21:20 +01001204 for(i=0; i < found_index; i++) {
Marc Kupietz4116b432017-12-06 14:15:32 +01001205 best[i].activation = best[i].probability = best[i].average = best[i].cprobability_sum = 0;
Marc Kupietz30ca4342017-11-22 21:21:20 +01001206 for(w=1; w < (1 << syn_threads); w++) { // loop through all possible windows
Marc Kupietz4116b432017-12-06 14:15:32 +01001207 float word_window_sum = 0, word_window_average=0, word_cprobability_sum=0, word_activation_sum = 0, total_window_sum = 0;
1208 bits_set = 0;
Marc Kupietzbd41da32017-11-24 10:26:43 +01001209 for(a=0; a < syn_threads; a++) {
Marc Kupietz30ca4342017-11-22 21:21:20 +01001210 if((1 << a) & w) {
Marc Kupietzbd41da32017-11-24 10:26:43 +01001211 wpos = (a >= window? a+1 : a);
1212 total_window_sum += window_sums[wpos];
Marc Kupietz30ca4342017-11-22 21:21:20 +01001213 }
1214 }
Marc Kupietzbd41da32017-11-24 10:26:43 +01001215// printf("%d window-sum %f\n", w, total_window_sum);
1216 for(a=0; a < syn_threads; a++) {
1217 if((1 << a) & w) {
1218 wpos = (a >= window? a+1 : a);
1219 bits_set++;
1220 for(b=0; b < syn_nbs[a]->length; b++)
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001221 if(best[i].wordi == syn_nbs[a]->best[b].wordi) {
Marc Kupietza77acce2017-11-30 16:59:07 +01001222// float acti = syn_nbs[a]->best[b].activation / total_window_sum;
Marc Kupietzbd41da32017-11-24 10:26:43 +01001223// word_window_sum += syn_nbs[a]->dist[b] * syn_nbs[a]->norm[b]; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
Marc Kupietzbd41da32017-11-24 10:26:43 +01001224// word_window_sum += syn_nbs[a]->norm[b]; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
1225// word_window_sum = (word_window_sum + syn_nbs[a]->norm[b]) - (word_window_sum * syn_nbs[a]->norm[b]); // syn_nbs[a]->norm[b];
Marc Kupietza77acce2017-11-30 16:59:07 +01001226
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001227 word_window_sum += syn_nbs[a]->best[b].activation; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
Marc Kupietza77acce2017-11-30 16:59:07 +01001228// word_window_sum += acti - (word_window_sum * acti); syn_nbs[a]->best[b].activation; // / window_sums[wpos]; // syn_nbs[a]->norm[b];
1229
Marc Kupietz4116b432017-12-06 14:15:32 +01001230 word_window_average += syn_nbs[a]->best[b].activation; // - word_window_average * syn_nbs[a]->best[b].activation; // conormalied activation sum
1231 word_cprobability_sum += syn_nbs[a]->best[b].cprobability - word_cprobability_sum * syn_nbs[a]->best[b].cprobability; // conormalied column probability sum
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001232 word_activation_sum += syn_nbs[a]->best[b].activation;
1233 if(syn_nbs[a]->best[b].activation > best[i].max_activation)
1234 best[i].max_activation = syn_nbs[a]->best[b].activation;
Marc Kupietzdb2dc7e2017-12-02 12:04:03 +01001235 if(syn_nbs[a]->best[b].activation > best[i].heat[wpos] )
Marc Kupietz728b8ed2017-12-02 11:13:49 +01001236 best[i].heat[wpos] = syn_nbs[a]->best[b].activation;
Marc Kupietzbd41da32017-11-24 10:26:43 +01001237 }
1238 }
1239 }
Marc Kupietz4116b432017-12-06 14:15:32 +01001240 if(bits_set) {
1241 word_window_average /= bits_set;
Marc Kupietzbd41da32017-11-24 10:26:43 +01001242// word_activation_sum /= bits_set;
1243// word_window_sum /= bits_set;
Marc Kupietz4116b432017-12-06 14:15:32 +01001244 }
Marc Kupietza77acce2017-11-30 16:59:07 +01001245
1246 word_window_sum /= total_window_sum;
Marc Kupietzbd41da32017-11-24 10:26:43 +01001247
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001248 if(word_window_sum > best[i].probability) {
Marc Kupietz4116b432017-12-06 14:15:32 +01001249// best[i].position = w;
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001250 best[i].probability = word_window_sum;
Marc Kupietz30ca4342017-11-22 21:21:20 +01001251 }
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001252
Marc Kupietz4116b432017-12-06 14:15:32 +01001253 if(word_cprobability_sum > best[i].cprobability_sum) {
1254 best[i].position = w;
1255 best[i].cprobability_sum = word_cprobability_sum;
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001256 }
Marc Kupietz4116b432017-12-06 14:15:32 +01001257
1258 best[i].average = word_window_average;
1259// best[i].activation = word_activation_sum;
1260 }
Marc Kupietz30ca4342017-11-22 21:21:20 +01001261 }
Marc Kupietze0e42132017-11-24 16:44:34 +01001262 qsort(best, found_index, sizeof(collocator), cmp_probability);
Marc Kupietz30ca4342017-11-22 21:21:20 +01001263// for(i=0; i < found_index; i++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001264// printf("found: %s - sum: %f - window: %d\n", &vocab[best[i].wordi * max_w], best[i].activation, best[i].position);
Marc Kupietz30ca4342017-11-22 21:21:20 +01001265// }
1266
Marc Kupietz580ebdf2017-11-29 21:18:38 +01001267 } else if(sort_by == 1) { // responsiveness any window position
1268 int wpos;
1269 for(i=0; i < found_index; i++) {
1270 float word_window_sum = 0, word_activation_sum = 0, total_window_sum = 0;
1271 for(a=0; a < syn_threads; a++) {
1272 wpos = (a >= window? a+1 : a);
1273 for(b=0; b < syn_nbs[a]->length; b++)
1274 if(best[i].wordi == syn_nbs[a]->best[b].wordi) {
1275 best[i].probability += syn_nbs[a]->best[b].probability;
1276 if(syn_nbs[a]->best[b].activation > 0.25)
1277 best[i].position |= 1 << wpos;
1278 if(syn_nbs[a]->best[b].activation > best[i].activation) {
1279 best[i].activation = syn_nbs[a]->best[b].activation;
1280 }
1281 }
1282 }
1283 }
1284 qsort(best, found_index, sizeof(collocator), cmp_activation);
1285 } else if(sort_by == 2) { // single window position
Marc Kupietz30ca4342017-11-22 21:21:20 +01001286 for(a=1; a < syn_threads; a++) {
1287 for(b=0; b < syn_nbs[a]->length; b++) {
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001288 for(c=0; c < MAX_NEIGHBOURS; c++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001289 if(syn_nbs[a]->best[b].activation > best[c].activation) {
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001290 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001291 memmove(best + d, best + d - 1, sizeof(collocator));
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001292 }
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001293 memcpy(best + c, &syn_nbs[a]->best[b], sizeof(collocator));
1294 best[c].position = 1 << (-syn_nbs[a]->best[b].position+window - (syn_nbs[a]->best[b].position < 0 ? 1:0));
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001295 break;
Marc Kupietz6d9a6782016-03-23 17:25:25 +01001296 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001297 }
1298 }
1299 }
1300 } else { // sort by mean p
1301 for(a=1; a < syn_threads; a++) {
1302 for(b=0; b < syn_nbs[a]->length; b++) {
1303 for(c=0; c < MAX_NEIGHBOURS; c++) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001304 if(target_sums[syn_nbs[a]->best[b].wordi] > best[c].activation_sum) {
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001305 for(d=MAX_NEIGHBOURS-1; d>c; d--) {
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001306 memmove(best + d, best + d - 1, sizeof(collocator));
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001307 }
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001308 memcpy(best + c, &syn_nbs[a]->best[b], sizeof(collocator));
1309 best[c].position = (1 << 2*window) - 1; // syn_nbs[a]->pos[b];
1310 best[c].activation_sum = target_sums[syn_nbs[a]->best[b].wordi];
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001311 break;
1312 }
Marc Kupietz271e2a42016-03-22 11:37:43 +01001313 }
Marc Kupietz6d9a6782016-03-23 17:25:25 +01001314 }
1315 }
1316 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001317 array = newAV();
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001318 for (a = 0, i=0; a < MAX_NEIGHBOURS && best[a].wordi >= 0; a++) {
1319 long long c = best[a].wordi;
Marc Kupietza77acce2017-11-30 16:59:07 +01001320/*
Marc Kupietzd91212f2017-11-13 10:05:09 +01001321 if (dedupe) {
1322 int filtered=0;
1323 for (j=0; j<i; j++)
1324 if (strcasestr(&vocab[c * max_w], chosen[j]) ||
1325 strcasestr(chosen[j], &vocab[c * max_w])) {
Marc Kupietza77acce2017-11-30 16:59:07 +01001326 printf("filtering %s %s\n", chosen[j], &vocab[c * max_w]);
1327 filtered = 1;
1328 }
Marc Kupietzd91212f2017-11-13 10:05:09 +01001329 if(filtered)
1330 continue;
1331 }
Marc Kupietza77acce2017-11-30 16:59:07 +01001332*/
Marc Kupietzb6c615d2017-12-02 10:38:20 +01001333 chosen[i++]=c;
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001334 HV* hash = newHV();
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001335 SV* word = newSVpvf(&vocab[best[a].wordi * max_w], 0);
Marc Kupietzb6c615d2017-12-02 10:38:20 +01001336 AV* heat = newAV();
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001337 if(latin_enc == 0) SvUTF8_on(word);
1338 hv_store(hash, "word", strlen("word"), word , 0);
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001339 hv_store(hash, "rank", strlen("rank"), newSVuv(best[a].wordi), 0);
Marc Kupietz4116b432017-12-06 14:15:32 +01001340 hv_store(hash, "average", strlen("average"), newSVnv(best[a].average), 0);
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001341 hv_store(hash, "prob", strlen("prob"), newSVnv(best[a].probability), 0);
Marc Kupietz4116b432017-12-06 14:15:32 +01001342 hv_store(hash, "cprob", strlen("cprob"), newSVnv(best[a].cprobability_sum), 0);
Marc Kupietzd64f3f22017-11-30 12:07:42 +01001343 hv_store(hash, "max", strlen("max"), newSVnv(best[a].max_activation), 0); // newSVnv(target_sums[best[a].wordi]), 0);
Marc Kupietza77acce2017-11-30 16:59:07 +01001344 hv_store(hash, "overall", strlen("overall"), newSVnv(best[a].activation_sum/total_activation), 0); // newSVnv(target_sums[best[a].wordi]), 0);
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001345 hv_store(hash, "pos", strlen("pos"), newSVnv(best[a].position), 0);
Marc Kupietzb6c615d2017-12-02 10:38:20 +01001346 best[a].heat[5]=0;
1347 for(i=10; i >= 0; i--) av_push(heat, newSVnv(best[a].heat[i]));
1348 hv_store(hash, "heat", strlen("heat"), newRV_noinc((SV*)heat), 0);
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001349 av_push(array, newRV_noinc((SV*)hash));
Marc Kupietz271e2a42016-03-22 11:37:43 +01001350 }
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001351 hv_store(result, "syntagmatic", strlen("syntagmatic"), newRV_noinc((SV*)array), 0);
Marc Kupietz271e2a42016-03-22 11:37:43 +01001352 }
Marc Kupietz000ad862016-02-26 14:59:12 +01001353end:
Marc Kupietz257a93d2019-01-03 17:55:22 +01001354 // words = old_words; // why was this here?
Marc Kupietzc8fdf3c2017-11-24 15:32:19 +01001355 free(best);
Marc Kupietz6b2975c2016-03-18 21:59:33 +01001356 return newRV_noinc((SV*)result);
Marc Kupietz000ad862016-02-26 14:59:12 +01001357}
Marc Kupietz7bc85fd2016-02-24 11:42:41 +01001358
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001359int dump_vecs(char *fname) {
1360 long i, j;
1361 FILE *f;
Marc Kupietz0a68a792018-12-20 11:41:45 +01001362 if(words>100000)
1363 words=100000;
Marc Kupietz6b2975c2016-03-18 21:59:33 +01001364
Marc Kupietz43ee87e2016-04-25 10:50:08 +02001365 if((f=fopen(fname, "w")) == NULL) {
1366 fprintf(stderr, "cannot open %s for writing\n", fname);
1367 return(-1);
1368 }
1369 fprintf(f, "%lld %lld\n", words, size);
1370 for (i=0; i < words; i++) {
1371 fprintf(f, "%s ", &vocab[i * max_w]);
1372 for(j=0; j < size - 1; j++)
1373 fprintf(f, "%f ", M[i*size + j]);
1374 fprintf(f, "%f\n", M[i*size + j]);
1375 }
1376 fclose(f);
1377 return(0);
1378}
Marc Kupietzdc22b982015-10-09 09:19:34 +02001379
Marc Kupietzfa194262018-06-05 09:39:32 +02001380int dump_for_numpy(char *fname) {
1381 long i, j;
1382 FILE *f;
Marc Kupietz1233eda2019-03-06 14:16:43 +01001383 int max;
1384 if(merged_end > 0)
1385 max = 150000;
1386 else
1387 max = 300000;
1388
1389 if(words>300000)
1390 words=300000;
Marc Kupietzfa194262018-06-05 09:39:32 +02001391
1392 if((f=fopen(fname, "w")) == NULL) {
1393 fprintf(stderr, "cannot open %s for writing\n", fname);
1394 return(-1);
1395 }
Marc Kupietz1233eda2019-03-06 14:16:43 +01001396 for (i=0; i < max; i++) {
Marc Kupietzfa194262018-06-05 09:39:32 +02001397 for(j=0; j < size - 1; j++)
1398 fprintf(f, "%f\t", M[i*size + j]);
1399 fprintf(f, "%f\n", M[i*size + j]);
Marc Kupietz1233eda2019-03-06 14:16:43 +01001400 printf("%s\n", &vocab[i * max_w]);
1401
1402 if(merged_end > 0) {
1403 for(j=0; j < size - 1; j++)
1404 fprintf(f, "%f\t", M[(merged_end + i)*size + j]);
1405 fprintf(f, "%f\n", M[(merged_end + i)*size + j]);
1406 printf("_%s\n", &vocab[i * max_w]);
1407 }
Marc Kupietzfa194262018-06-05 09:39:32 +02001408 }
1409 fclose(f);
Marc Kupietz7631e022019-01-25 12:04:42 +01001410 return(0);
Marc Kupietzfa194262018-06-05 09:39:32 +02001411}