blob: bb505dd9f38ba5a7333ef400744c67b6b26294ac [file] [log] [blame]
Marc Kupietz28cc53e2017-12-23 17:24:55 +01001#include <typeinfo>
Marc Kupietz4b799e92018-01-02 11:04:56 +01002#define EXPORT __attribute__((visibility("visible")))
3#define IMPORT
Marc Kupietz28cc53e2017-12-23 17:24:55 +01004#include <assert.h>
Marc Kupietz37359b12018-01-09 21:11:37 +01005#include <inttypes.h>
Marc Kupietz28cc53e2017-12-23 17:24:55 +01006#include <memory>
7#include <iostream>
Marc Kupietzc8ddf452018-01-07 21:33:12 +01008#include <algorithm>
9#include <vector>
Marc Kupietz28cc53e2017-12-23 17:24:55 +010010#include <stdint.h>
Marc Kupietzc8ddf452018-01-07 21:33:12 +010011#include <string>
12#include <sstream> // for ostringstream
13#include <math.h>
Marc Kupietzd31254c2018-01-20 21:29:30 +010014#include <rocksdb/cache.h>
Marc Kupietz28cc53e2017-12-23 17:24:55 +010015#include "rocksdb/comparator.h"
16#include "rocksdb/db.h"
17#include "rocksdb/env.h"
Marc Kupietzc8ddf452018-01-07 21:33:12 +010018#include "rocksdb/table.h"
Marc Kupietz28cc53e2017-12-23 17:24:55 +010019#include <rocksdb/merge_operator.h>
Marc Kupietzc8ddf452018-01-07 21:33:12 +010020#include <rocksdb/slice_transform.h>
Marc Kupietz28cc53e2017-12-23 17:24:55 +010021#include "rocksdb/utilities/db_ttl.h"
Marc Kupietzc8ddf452018-01-07 21:33:12 +010022#include "rocksdb/filter_policy.h"
Marc Kupietz28cc53e2017-12-23 17:24:55 +010023#include "merge_operators.h"
24
Marc Kupietz75af60f2019-01-22 22:34:29 +010025#define WINDOW_SIZE 5
Marc Kupietz98cbcdc2019-01-21 17:11:27 +010026#define FREQUENCY_THRESHOLD 5
Marc Kupietz28cc53e2017-12-23 17:24:55 +010027#define IS_BIG_ENDIAN (*(uint16_t *)"\0\xff" < 0x100)
28#define encodeCollocation(w1, w2, dist) (((uint64_t)dist << 56) | ((uint64_t)w2 << 24) | w1)
Marc Kupietz18375e12017-12-24 10:11:18 +010029#define W1(key) (uint64_t)(key & 0xffffff)
30#define W2(key) (uint64_t)((key >> 24) & 0xffffff)
31#define DIST(key) (int8_t)((uint64_t)((key >> 56) & 0xff))
Marc Kupietzc8ddf452018-01-07 21:33:12 +010032
33typedef struct {
34 uint64_t freq;
35 char *word;
36} vocab_entry;
37
38// typedef struct Collocator {
39// uint64_t w2;
40// uint64_t sum;
41// };
42
Marc Kupietz28cc53e2017-12-23 17:24:55 +010043using namespace rocksdb;
Marc Kupietzc8ddf452018-01-07 21:33:12 +010044using namespace std;
Marc Kupietz28cc53e2017-12-23 17:24:55 +010045
Marc Kupietz4b799e92018-01-02 11:04:56 +010046namespace rocksdb {
Marc Kupietz4a5e08a2018-06-05 11:07:11 +020047 class Collocator {
48 public:
Marc Kupietzc8ddf452018-01-07 21:33:12 +010049 uint64_t w2;
Marc Kupietz51f93792018-01-25 08:51:01 +010050 uint64_t raw;
Marc Kupietzc8ddf452018-01-07 21:33:12 +010051 double pmi;
52 double npmi;
53 double llr;
Marc Kupietzc8ddf452018-01-07 21:33:12 +010054 double lfmd;
Marc Kupietz41880452019-01-22 15:29:06 +010055 double md;
Marc Kupietz8e0ebea2018-01-24 09:53:26 +010056 double left_lfmd;
57 double right_lfmd;
58 double left_npmi;
59 double right_npmi;
Marc Kupietz41880452019-01-22 15:29:06 +010060 double dice;
61 double logdice;
Marc Kupietz75af60f2019-01-22 22:34:29 +010062 double af;
63 int window;
Marc Kupietzc8ddf452018-01-07 21:33:12 +010064 };
65
Marc Kupietz28cc53e2017-12-23 17:24:55 +010066 size_t num_merge_operator_calls;
67 void resetNumMergeOperatorCalls() { num_merge_operator_calls = 0; }
Marc Kupietzc8ddf452018-01-07 21:33:12 +010068
Marc Kupietz28cc53e2017-12-23 17:24:55 +010069 size_t num_partial_merge_calls;
70 void resetNumPartialMergeCalls() { num_partial_merge_calls = 0; }
Marc Kupietz28cc53e2017-12-23 17:24:55 +010071
72
Marc Kupietz4b799e92018-01-02 11:04:56 +010073 inline void EncodeFixed64(char* buf, uint64_t value) {
74 if (! IS_BIG_ENDIAN) {
75 memcpy(buf, &value, sizeof(value));
76 } else {
77 buf[0] = value & 0xff;
78 buf[1] = (value >> 8) & 0xff;
79 buf[2] = (value >> 16) & 0xff;
80 buf[3] = (value >> 24) & 0xff;
81 buf[4] = (value >> 32) & 0xff;
82 buf[5] = (value >> 40) & 0xff;
83 buf[6] = (value >> 48) & 0xff;
84 buf[7] = (value >> 56) & 0xff;
85 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +010086 }
87
Marc Kupietz4b799e92018-01-02 11:04:56 +010088 inline uint32_t DecodeFixed32(const char* ptr) {
89 if (! IS_BIG_ENDIAN) {
90 // Load the raw bytes
91 uint32_t result;
92 memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
93 return result;
94 } else {
95 return ((static_cast<uint32_t>(static_cast<unsigned char>(ptr[0])))
96 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[1])) << 8)
97 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[2])) << 16)
98 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[3])) << 24));
99 }
100 }
101
102 inline uint64_t DecodeFixed64(const char* ptr) {
103 if (! IS_BIG_ENDIAN) {
104 // Load the raw bytes
105 uint64_t result;
106 memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
107 return result;
108 } else {
109 uint64_t lo = DecodeFixed32(ptr);
110 uint64_t hi = DecodeFixed32(ptr + 4);
111 return (hi << 32) | lo;
112 }
113 }
114
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100115 static inline double ca_pmi(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
Marc Kupietz1335dd72019-01-22 15:35:21 +0100116 double
117 r1 = f1 * window_size,
118 c1 = f2,
119 e = r1 * c1 / total,
120 o = f12;
121 return log2(o/e);
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100122 }
123
Marc Kupietzce0b8b02018-06-05 11:06:39 +0200124 // Bouma, Gerlof (2009): <a href="https://svn.spraakdata.gu.se/repos/gerlof/pub/www/Docs/npmi-pfd.pdf">
125 // Normalized (pointwise) mutual information in collocation extraction</a>. In Proceedings of GSCL.
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100126 static inline double ca_npmi(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
Marc Kupietz1335dd72019-01-22 15:35:21 +0100127 double
128 r1 = f1 * window_size,
129 c1 = f2,
130 e = r1 * c1 / total,
131 o = f12;
132 if(f12 < FREQUENCY_THRESHOLD)
Marc Kupietz8caf9912018-06-05 10:51:18 +0200133 return -1.0;
134 else
Marc Kupietz1335dd72019-01-22 15:35:21 +0100135 return log2(o/e) / (-log2(o/total/window_size));
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100136 }
137
138 // Thanopoulos, A., Fakotakis, N., Kokkinakis, G.: Comparative evaluation of collocation extraction metrics.
139 // In: International Conference on Language Resources and Evaluation (LREC-2002). (2002) 620–625
140 // double md = log2(pow((double)max * window_size / total, 2) / (window_size * ((double)_vocab[w1].freq/total) * ((double)_vocab[last_w2].freq/total)));
141 static inline double ca_md(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
Marc Kupietz1335dd72019-01-22 15:35:21 +0100142 double
143 r1 = f1 * window_size,
144 c1 = f2,
145 e = r1 * c1 / total,
146 o = f12;
147 return log2(o*o/e);
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100148 }
149
150 static inline double ca_lfmd(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
Marc Kupietz1335dd72019-01-22 15:35:21 +0100151 double
152 r1 = f1 * window_size,
153 c1 = f2,
154 e = r1 * c1 / total,
155 o = f12;
Marc Kupietz8caf9912018-06-05 10:51:18 +0200156 if(f12 == 0)
157 return 0;
158 else
Marc Kupietz1335dd72019-01-22 15:35:21 +0100159 return log2(o*o*o/e);
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100160 }
161
Marc Kupietzbbd236e2019-01-21 16:50:19 +0100162 // Evert, Stefan (2004): The Statistics of Word Cooccurrences: Word Pairs and Collocations. PhD dissertation, IMS, University of Stuttgart. Published in 2005, URN urn:nbn:de:bsz:93-opus-23714.
163 // Free PDF available from http://purl.org/stefan.evert/PUB/Evert2004phd.pdf
164 static inline double ca_ll(uint64_t w1, uint64_t w2, uint64_t w12, uint64_t n, uint64_t window_size) {
165 double
166 r1 = (double) w1 * window_size,
167 r2 = (double) n - r1,
168 c1 = w2,
169 c2 = n - c1,
170 o11 = w12, o12 = r1 - o11,
171 o21 = c1 - w12, o22 = r2 - o21,
172 e11 = r1 * c1 / n, e12 = r1 * c2 / n,
173 e21 = r2 * c1 / n, e22 = r2 * c2 / n;
174 return (2 * ( (o11>0? o11 * log(o11/e11):0) + (o12>0? o12 * log(o12/e12):0) + (o21>0? o21 * log(o21/e21):0) + (o22>0? o22 * log(o22/e22):0)));
175 }
Marc Kupietz4b799e92018-01-02 11:04:56 +0100176
Marc Kupietz41880452019-01-22 15:29:06 +0100177
178 static inline double ca_dice(uint64_t w1, uint64_t w2, uint64_t w12, uint64_t n, uint64_t window_size) {
179 double
180 r1 = (double) w1 * window_size,
181 c1 = w2;
182 return 2 * w12 / (c1+r1);
183 }
184
185 // Rychlý, Pavel (2008): <a href="http://www.fi.muni.cz/usr/sojka/download/raslan2008/13.pdf">A lexicographer-friendly association score.</a> In Proceedings of Recent Advances in Slavonic Natural Language Processing, RASLAN, 6–9.
186 static inline double ca_logdice(uint64_t w1, uint64_t w2, uint64_t w12, uint64_t n, uint64_t window_size) {
187 double
188 e = 0.5,
189 r1 = (double) w1 * window_size,
190 c1 = w2;
191 return 14 + log2(2 * (w12+e) / (c1+e+r1+e));
192 }
193
Marc Kupietz4b799e92018-01-02 11:04:56 +0100194 class CountMergeOperator : public AssociativeMergeOperator {
195 public:
196 CountMergeOperator() {
197 mergeOperator_ = MergeOperators::CreateUInt64AddOperator();
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100198 }
199
Marc Kupietz4b799e92018-01-02 11:04:56 +0100200 virtual bool Merge(const Slice& key,
201 const Slice* existing_value,
202 const Slice& value,
203 std::string* new_value,
204 Logger* logger) const override {
205 assert(new_value->empty());
206 ++num_merge_operator_calls;
207 if (existing_value == nullptr) {
208 new_value->assign(value.data(), value.size());
209 return true;
210 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100211
Marc Kupietz4b799e92018-01-02 11:04:56 +0100212 return mergeOperator_->PartialMerge(
213 key,
214 *existing_value,
215 value,
216 new_value,
217 logger);
218 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100219
Marc Kupietz4b799e92018-01-02 11:04:56 +0100220 virtual const char* Name() const override {
221 return "UInt64AddOperator";
222 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100223
Marc Kupietz4b799e92018-01-02 11:04:56 +0100224 private:
225 std::shared_ptr<MergeOperator> mergeOperator_;
226 };
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100227
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100228
Marc Kupietz4b799e92018-01-02 11:04:56 +0100229 class CollocatorIterator : public Iterator {
230 private:
231 char prefixc[sizeof(uint64_t)];
232 Iterator *base_iterator_;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100233
234
Marc Kupietz4b799e92018-01-02 11:04:56 +0100235 public:
236 CollocatorIterator(Iterator* base_iterator)
237 : base_iterator_(base_iterator)
238 {}
239
Marc Kupietz4b799e92018-01-02 11:04:56 +0100240 void setPrefix(char *prefix) {
241 memcpy(prefixc, prefix, sizeof(uint64_t));
242 }
243
244 virtual void SeekToFirst() { base_iterator_->SeekToFirst(); }
245 virtual void SeekToLast() { base_iterator_->SeekToLast(); }
246 virtual void Seek(const rocksdb::Slice& s) { base_iterator_->Seek(s); }
247 virtual void Prev() { base_iterator_->Prev(); }
248 virtual void Next() { base_iterator_->Next(); }
249 virtual Slice key() const;
250 virtual Slice value() const;
251 virtual Status status() const;
252 virtual bool Valid() const;
253 bool isValid();
254 uint64_t intValue();
255 uint64_t intKey();
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100256
Marc Kupietz4b799e92018-01-02 11:04:56 +0100257 };
Marc Kupietz18375e12017-12-24 10:11:18 +0100258
Marc Kupietz4b799e92018-01-02 11:04:56 +0100259 // rocksdb::CollocatorIterator::CollocatorIterator(Iterator* base_iterator) {}
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100260
Marc Kupietz4b799e92018-01-02 11:04:56 +0100261 bool rocksdb::CollocatorIterator::Valid() const {
Marc Kupietz18375e12017-12-24 10:11:18 +0100262 return base_iterator_->Valid() && key().starts_with(std::string(prefixc,3));
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100263 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100264
Marc Kupietz4b799e92018-01-02 11:04:56 +0100265 bool rocksdb::CollocatorIterator::isValid() {
266 return base_iterator_->Valid() && key().starts_with(std::string(prefixc,3));
Marc Kupietzd31254c2018-01-20 21:29:30 +0100267 // return key().starts_with(std::string(prefixc,3));
Marc Kupietz4b799e92018-01-02 11:04:56 +0100268 }
Marc Kupietz18375e12017-12-24 10:11:18 +0100269
Marc Kupietz4b799e92018-01-02 11:04:56 +0100270 uint64_t rocksdb::CollocatorIterator::intKey() {
271 return DecodeFixed64(base_iterator_->key().data());
272 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100273
Marc Kupietz4b799e92018-01-02 11:04:56 +0100274 uint64_t rocksdb::CollocatorIterator::intValue() {
275 return DecodeFixed64(base_iterator_->value().data());
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100276 }
277
Marc Kupietz37359b12018-01-09 21:11:37 +0100278 class VocabEntry {
279 public:
280 string word;
281 uint64_t freq;
282 };
283
Marc Kupietz6aec7682018-01-10 09:47:48 +0100284 class CollocatorDB {
Marc Kupietz4b799e92018-01-02 11:04:56 +0100285 private:
286 WriteOptions merge_option_; // for merge
287 char _one[sizeof(uint64_t)];
288 Slice _one_slice;
Marc Kupietz37359b12018-01-09 21:11:37 +0100289 vector<VocabEntry> _vocab;
Marc Kupietz4ec51c12019-01-21 11:06:39 +0100290 uint64_t total = 0;
291 uint64_t sentences = 0;
Marc Kupietz8cf7e912019-01-21 17:05:23 +0100292 float avg_window_size = 8.0;
Marc Kupietz37359b12018-01-09 21:11:37 +0100293
Marc Kupietz4b799e92018-01-02 11:04:56 +0100294 protected:
295 std::shared_ptr<DB> db_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100296
Marc Kupietz4b799e92018-01-02 11:04:56 +0100297 WriteOptions put_option_;
298 ReadOptions get_option_;
299 WriteOptions delete_option_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100300
Marc Kupietz4b799e92018-01-02 11:04:56 +0100301 uint64_t default_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100302
Marc Kupietz4b799e92018-01-02 11:04:56 +0100303 std::shared_ptr<DB> OpenDb(const char *dbname);
Marc Kupietz6bb27762018-01-09 17:53:01 +0100304 std::shared_ptr<DB> OpenDbForRead(const char *dbname);
Marc Kupietz37359b12018-01-09 21:11:37 +0100305 void read_vocab(string fname);
306
Marc Kupietz4b799e92018-01-02 11:04:56 +0100307 public:
Marc Kupietz4a5e08a2018-06-05 11:07:11 +0200308 string getWord(uint32_t w1);
Marc Kupietz6aec7682018-01-10 09:47:48 +0100309 CollocatorDB(const char *db_name, bool read_only);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100310
Marc Kupietz6aec7682018-01-10 09:47:48 +0100311 // public interface of CollocatorDB.
Marc Kupietz4b799e92018-01-02 11:04:56 +0100312 // All four functions return false
313 // if the underlying level db operation failed.
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100314
Marc Kupietz4b799e92018-01-02 11:04:56 +0100315 // mapped to a levedb Put
316 bool set(const std::string& key, uint64_t value) {
317 // just treat the internal rep of int64 as the string
318 char buf[sizeof(value)];
319 EncodeFixed64(buf, value);
320 Slice slice(buf, sizeof(value));
321 auto s = db_->Put(put_option_, key, slice);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100322
Marc Kupietz4b799e92018-01-02 11:04:56 +0100323 if (s.ok()) {
324 return true;
325 } else {
326 std::cerr << s.ToString() << std::endl;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100327 return false;
328 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100329 }
Marc Kupietz4b799e92018-01-02 11:04:56 +0100330
331 DB *getDb() {
332 return db_.get();
333 }
334
335 // mapped to a rocksdb Delete
336 bool remove(const std::string& key) {
337 auto s = db_->Delete(delete_option_, key);
338
339 if (s.ok()) {
340 return true;
341 } else {
342 std::cerr << s.ToString() << std::endl;
343 return false;
344 }
345 }
346
347 // mapped to a rocksdb Get
348 bool get(const std::string& key, uint64_t* value) {
349 std::string str;
350 auto s = db_->Get(get_option_, key, &str);
351
352 if (s.IsNotFound()) {
353 // return default value if not found;
354 *value = default_;
355 return true;
356 } else if (s.ok()) {
357 // deserialization
358 if (str.size() != sizeof(uint64_t)) {
359 std::cerr << "value corruption\n";
360 return false;
361 }
362 *value = DecodeFixed64(&str[0]);
363 return true;
364 } else {
365 std::cerr << s.ToString() << std::endl;
366 return false;
367 }
368 }
369
370
371 uint64_t get(const uint32_t w1, const uint32_t w2, const int8_t dist) {
372 char encoded_key[sizeof(uint64_t)];
373 EncodeFixed64(encoded_key, encodeCollocation(w1,w2,dist));
374 uint64_t value = default_;
375 get(std::string(encoded_key, 8), &value);
376 return value;
377 }
378
379 virtual void inc(const std::string& key) {
380 db_->Merge(merge_option_, key, _one_slice);
381 }
382
383 void inc(const uint64_t key) {
384 char encoded_key[sizeof(uint64_t)];
385 EncodeFixed64(encoded_key, key);
386 db_->Merge(merge_option_, std::string(encoded_key, 8), _one_slice);
387 }
388
389 virtual void inc(const uint32_t w1, const uint32_t w2, const uint8_t dist);
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100390 void dump(uint32_t w1, uint32_t w2, int8_t dist);
Marc Kupietz37359b12018-01-09 21:11:37 +0100391 vector<Collocator> get_collocators(uint32_t w1);
Marc Kupietzbd966192018-10-13 14:14:37 +0200392 vector<Collocator> get_collocators(uint32_t w1, uint32_t max_w2);
Marc Kupietz3400aa52018-06-05 10:28:55 +0200393 void dumpSparseLlr(uint32_t w1, uint32_t min_cooccur);
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100394 string collocators2json(vector<Collocator> collocators);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100395
Marc Kupietz4b799e92018-01-02 11:04:56 +0100396 // mapped to a rocksdb Merge operation
397 virtual bool add(const std::string& key, uint64_t value) {
398 char encoded[sizeof(uint64_t)];
399 EncodeFixed64(encoded, value);
400 Slice slice(encoded, sizeof(uint64_t));
401 auto s = db_->Merge(merge_option_, key, slice);
402
403 if (s.ok()) {
404 return true;
405 } else {
406 std::cerr << s.ToString() << std::endl;
407 return false;
408 }
409 }
410
411 CollocatorIterator* SeekIterator(uint64_t w1, uint64_t w2, int8_t dist);
412 };
413
Marc Kupietz6aec7682018-01-10 09:47:48 +0100414 rocksdb::CollocatorDB::CollocatorDB(const char *db_name, bool read_only = false) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100415 // merge_option_.sync = true;
Marc Kupietz6bb27762018-01-09 17:53:01 +0100416 if(read_only)
417 db_ = OpenDbForRead(db_name);
418 else
419 db_ = OpenDb(db_name);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100420 assert(db_);
421 uint64_t one = 1;
422 EncodeFixed64(_one, one);
423 _one_slice = Slice(_one, sizeof(uint64_t));
424 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100425
Marc Kupietz6aec7682018-01-10 09:47:48 +0100426 void rocksdb::CollocatorDB::inc(const uint32_t w1, const uint32_t w2, const uint8_t dist) {
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100427 inc(encodeCollocation(w1, w2, dist));
428 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100429
Marc Kupietz6aec7682018-01-10 09:47:48 +0100430 void rocksdb::CollocatorDB::read_vocab(string fname) {
Marc Kupietz37359b12018-01-09 21:11:37 +0100431 char strbuf[2048];
432 uint64_t freq;
433 FILE *fin = fopen(fname.c_str(), "rb");
434 if (fin == NULL) {
435 cout << "Vocabulary file " << fname <<" not found\n";
436 exit(1);
437 }
438 uint64_t i = 0;
439 while(!feof(fin)) {
Marc Kupietzd31254c2018-01-20 21:29:30 +0100440 fscanf(fin, "%s %lu", strbuf, &freq);
Marc Kupietz37359b12018-01-09 21:11:37 +0100441 _vocab.push_back({strbuf, freq});
442 total += freq;
443 i++;
444 }
445 fclose(fin);
Marc Kupietz4ec51c12019-01-21 11:06:39 +0100446
447 char size_fname[256];
448 strcpy(size_fname, fname.c_str());
449 char *pos = strstr(size_fname, ".vocab");
450 if(pos) {
451 *pos=0;
452 strcat(size_fname, ".size");
453 FILE *fp = fopen(size_fname, "r");
454 if (fp != NULL) {
455 fscanf(fp, "%lu", &sentences);
456 fscanf(fp, "%lu", &total);
457 float sl = (float)total/(float)sentences;
458 float w = WINDOW_SIZE;
459 avg_window_size = ((sl > 2*w? (sl-2*w)*2*w: 0) + (double) w * (3*w -1)) / sl;
460 fprintf(stdout, "Size corrections found: corpus size: %lu tokens in %lu sentences, avg. sentence size: %f, avg. window size: %f\n", total, sentences, sl, avg_window_size);
461 fclose(fp);
462 } else {
463 std::cout << "size file " << size_fname << " not found\n";
464 }
465 } else {
466 std::cout << "cannot determine size file " << size_fname << "\n";
467 }
Marc Kupietz37359b12018-01-09 21:11:37 +0100468 }
469
Marc Kupietz6aec7682018-01-10 09:47:48 +0100470 std::shared_ptr<DB> rocksdb::CollocatorDB::OpenDbForRead(const char *name) {
Marc Kupietz6bb27762018-01-09 17:53:01 +0100471 DB* db;
472 Options options;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100473 options.env->SetBackgroundThreads(4);
474 options.create_if_missing = true;
475 options.merge_operator = std::make_shared<CountMergeOperator>();
476 options.max_successive_merges = 0;
477 // options.prefix_extractor.reset(NewFixedPrefixTransform(8));
478 options.IncreaseParallelism();
479 options.OptimizeLevelStyleCompaction();
480 options.prefix_extractor.reset(NewFixedPrefixTransform(3));
Marc Kupietz37359b12018-01-09 21:11:37 +0100481 ostringstream dbname, vocabname;
Marc Kupietz6bb27762018-01-09 17:53:01 +0100482 dbname << name << ".rocksdb";
483 auto s = DB::OpenForReadOnly(options, dbname.str(), &db);
484 if (!s.ok()) {
485 std::cerr << s.ToString() << std::endl;
486 assert(false);
487 }
Marc Kupietz37359b12018-01-09 21:11:37 +0100488 vocabname << name << ".vocab";
489 read_vocab(vocabname.str());
Marc Kupietz6bb27762018-01-09 17:53:01 +0100490 return std::shared_ptr<DB>(db);
491 }
492
Marc Kupietz6aec7682018-01-10 09:47:48 +0100493 std::shared_ptr<DB> rocksdb::CollocatorDB::OpenDb(const char *dbname) {
Marc Kupietz4b799e92018-01-02 11:04:56 +0100494 DB* db;
495 Options options;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100496
497
498 options.env->SetBackgroundThreads(4);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100499 options.create_if_missing = true;
500 options.merge_operator = std::make_shared<CountMergeOperator>();
501 options.max_successive_merges = 0;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100502 // options.prefix_extractor.reset(NewFixedPrefixTransform(8));
503 options.IncreaseParallelism();
504 options.OptimizeLevelStyleCompaction();
505 // options.max_write_buffer_number = 48;
506 // options.max_background_jobs = 48;
507 // options.allow_concurrent_memtable_write=true;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100508 // options.memtable_factory.reset(rocksdb::NewHashLinkListRepFactory(200000));
509 // options.enable_write_thread_adaptive_yield = 1;
510 // options.allow_concurrent_memtable_write = 1;
511 // options.memtable_factory.reset(new rocksdb::SkipListFactory);
512 // options.write_buffer_size = 1 << 22;
513 // options.allow_mmap_reads = true;
514 // options.allow_mmap_writes = true;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100515 // options.max_background_compactions = 40;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100516 // BlockBasedTableOptions table_options;
517 // table_options.filter_policy.reset(NewBloomFilterPolicy(24, false));
518 // options.bloom_locality = 1;
519 // std::shared_ptr<Cache> cache = NewLRUCache(512 * 1024 * 1024);
520 // table_options.block_cache = cache;
521 // options.table_factory.reset(NewBlockBasedTableFactory(table_options));
Marc Kupietz4b799e92018-01-02 11:04:56 +0100522 Status s;
523 // DestroyDB(dbname, Options());
524 s = DB::Open(options, dbname, &db);
525 if (!s.ok()) {
526 std::cerr << s.ToString() << std::endl;
527 assert(false);
528 }
529 return std::shared_ptr<DB>(db);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100530 }
531
Marc Kupietz6aec7682018-01-10 09:47:48 +0100532 CollocatorIterator* rocksdb::CollocatorDB::SeekIterator(uint64_t w1, uint64_t w2, int8_t dist) {
Marc Kupietz18375e12017-12-24 10:11:18 +0100533 ReadOptions options;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100534 options.prefix_same_as_start = true;
Marc Kupietz18375e12017-12-24 10:11:18 +0100535 char prefixc[sizeof(uint64_t)];
536 EncodeFixed64(prefixc, encodeCollocation(w1, w2, dist));
537 Iterator *it = db_->NewIterator(options);
538 CollocatorIterator *cit = new CollocatorIterator(it);
539 cit->Seek(std::string(prefixc,3));// it->Valid() && it->key().starts_with(std::string(prefixc,3)); it->Next()) {
540 cit->setPrefix(prefixc);
541 return cit;
542 }
543
Marc Kupietz6aec7682018-01-10 09:47:48 +0100544 void rocksdb::CollocatorDB::dump(uint32_t w1, uint32_t w2, int8_t dist) {
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100545 auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, w2, dist));
546 for (; it->isValid(); it->Next()) {
547 uint64_t value = it->intValue();
548 uint64_t key = it->intKey();
549 std::cout << "w1:" << W1(key) << ", w2:" << W2(key) << ", dist:" << (int32_t) DIST(key) << " - count:" << value << std::endl;
550 }
551 std::cout << "ready dumping\n";
552 }
553
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100554 bool sortByNpmi(const Collocator &lhs, const Collocator &rhs) { return lhs.npmi > rhs.npmi; }
555 bool sortByLfmd(const Collocator &lhs, const Collocator &rhs) { return lhs.lfmd > rhs.lfmd; }
Marc Kupietzd31254c2018-01-20 21:29:30 +0100556 bool sortByLlr(const Collocator &lhs, const Collocator &rhs) { return lhs.llr > rhs.llr; }
Marc Kupietz7e3dfde2019-01-22 16:27:33 +0100557 bool sortByLogDice(const Collocator &lhs, const Collocator &rhs) { return lhs.logdice > rhs.logdice; }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100558
Marc Kupietz75af60f2019-01-22 22:34:29 +0100559 std::vector<Collocator> rocksdb::CollocatorDB::get_collocators(uint32_t w1, uint32_t max_w2) {
560 std::vector<Collocator> collocators;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100561 uint64_t w2, last_w2 = 0xffffffffffffffff;
Marc Kupietz98cbcdc2019-01-21 17:11:27 +0100562 uint64_t maxv = 0, sum = 0, left = 0, right = 0;
Marc Kupietz75af60f2019-01-22 22:34:29 +0100563 uint64_t sumWindow[2*WINDOW_SIZE+1] = {};
Marc Kupietz98cbcdc2019-01-21 17:11:27 +0100564
Marc Kupietzd31254c2018-01-20 21:29:30 +0100565 for ( auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, 0, 0)); it->isValid(); it->Next()) {
566 uint64_t value = it->intValue(),
567 key = it->intKey();
Marc Kupietzbd966192018-10-13 14:14:37 +0200568 if((w2 = W2(key)) > max_w2)
569 continue;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100570 if(last_w2 == 0xffffffffffffffff) last_w2 = w2;
571 if (w2 != last_w2) {
Marc Kupietz75af60f2019-01-22 22:34:29 +0100572 if (sum >= FREQUENCY_THRESHOLD) {
573 uint64_t f1 = _vocab[w1].freq, f2 = _vocab[last_w2].freq;
Marc Kupietz98cbcdc2019-01-21 17:11:27 +0100574 double o = sum,
575 r1 = (double)_vocab[w1].freq * avg_window_size,
576 c1 = (double)_vocab[last_w2].freq,
577 e = r1 * c1 / total,
578 pmi = log2(o/e),
579 md = log2(o*o/e),
580 lfmd = log2(o*o*o/e),
Marc Kupietz75af60f2019-01-22 22:34:29 +0100581 llr = ca_ll(f1, f2, sum, total, avg_window_size);
582 double left_lfmd = ca_lfmd(f1, f2, left, total, 1);
583 double right_lfmd = ca_lfmd(f1, f2, right, total, 1);
584 double left_npmi = ca_npmi(f1, f2, left, total, 1);
585 double right_npmi = ca_npmi(f1, f2, right, total, 1);
586
587 int bestWindow = (1 << (2*WINDOW_SIZE)) - 1;
588 double bestAF = ca_logdice(f1, f2, sum, total, 2*WINDOW_SIZE);
589 double currentAF;
590 for (int bitmask=1; bitmask < (1 << (2*WINDOW_SIZE)); bitmask++) {
591 uint64_t currentWindowSum=0;
592 for (int pos=0; pos < 2*WINDOW_SIZE; pos++) {
593 if (((1<<pos) & bitmask) != 0)
594 currentWindowSum+=sumWindow[pos];
595 }
596 currentAF = ca_logdice(f1, f2, currentWindowSum, total, __builtin_popcount(bitmask));
597 if(currentAF > bestAF) {
598 bestAF = currentAF;
599 bestWindow = bitmask;
600 }
601 }
Marc Kupietz41880452019-01-22 15:29:06 +0100602 collocators.push_back ( {last_w2, sum, pmi, pmi / (-log2(o/total/avg_window_size)), /* normalize to [-1,1] */
Marc Kupietz98cbcdc2019-01-21 17:11:27 +0100603 llr, lfmd, md,
604 left_lfmd,
605 right_lfmd,
606 left_npmi,
Marc Kupietz41880452019-01-22 15:29:06 +0100607 right_npmi,
Marc Kupietz75af60f2019-01-22 22:34:29 +0100608 ca_dice(f1, f2, sum, total, avg_window_size),
609 ca_logdice(f1, f2, sum, total, avg_window_size),
610 bestAF,
611 bestWindow
Marc Kupietz41880452019-01-22 15:29:06 +0100612 }
Marc Kupietz98cbcdc2019-01-21 17:11:27 +0100613 );
614 }
Marc Kupietz75af60f2019-01-22 22:34:29 +0100615 memset(sumWindow, 0, 2*WINDOW_SIZE * sizeof(uint64_t));
616 sumWindow[-DIST(key)+WINDOW_SIZE-(DIST(key)<0?1:0)] = value;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100617 last_w2 = w2;
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100618 maxv = value;
Marc Kupietz98cbcdc2019-01-21 17:11:27 +0100619 sum = value;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100620 } else {
Marc Kupietz98cbcdc2019-01-21 17:11:27 +0100621 sum += value;
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100622 if(value > maxv)
623 maxv = value;
Marc Kupietz75af60f2019-01-22 22:34:29 +0100624 sumWindow[-DIST(key)+WINDOW_SIZE-(DIST(key)<0?1:0)] = value;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100625 }
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100626 if(DIST(key) == -1)
627 left = value;
628 else if(DIST(key) == 1)
629 right = value;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100630 }
631
Marc Kupietzd91e1d42019-01-22 16:18:32 +0100632 sort(collocators.begin(), collocators.end(), sortByLogDice);
Marc Kupietzd31254c2018-01-20 21:29:30 +0100633
Marc Kupietz0779a202018-06-05 11:13:35 +0200634 /*
Marc Kupietzd31254c2018-01-20 21:29:30 +0100635 int i=0;
636 for (Collocator c : collocators) {
637 if(i++>10) break;
638 std::cout << "w1:" << _vocab[w1].word << ", w2:" << _vocab[c.w2].word
639 << "\t f(w1):" << _vocab[w1].freq
640 << "\t f(w2):" << _vocab[c.w2].freq
641 << "\t f(w1, x):" << total_w1
Marc Kupietz51f93792018-01-25 08:51:01 +0100642 << "\t f(w1, w2):" << c.raw
Marc Kupietzd31254c2018-01-20 21:29:30 +0100643 << "\t pmi:" << c.pmi
644 << "\t npmi:" << c.npmi
645 << "\t llr:" << c.llr
Marc Kupietzd31254c2018-01-20 21:29:30 +0100646 << "\t lfmd:" << c.lfmd
647 << "\t fpmi:" << c.fpmi
648 << "\t total:" << total
649 << std::endl;
650 }
Marc Kupietz0779a202018-06-05 11:13:35 +0200651 */
Marc Kupietzd31254c2018-01-20 21:29:30 +0100652 return collocators;
653 }
654
Marc Kupietzbd966192018-10-13 14:14:37 +0200655 std::vector<Collocator> rocksdb::CollocatorDB::get_collocators(uint32_t w1) {
656 return get_collocators(w1, UINT32_MAX);
657 }
658
Marc Kupietz3400aa52018-06-05 10:28:55 +0200659 void rocksdb::CollocatorDB::dumpSparseLlr(uint32_t w1, uint32_t min_cooccur) {
660 std::vector<Collocator> collocators;
661 std::stringstream stream;
662 uint64_t w2, last_w2 = 0xffffffffffffffff;
663 uint64_t maxv = 0, total_w1 = 0;
664 bool first = true;
665 for ( auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, 0, 0)); it->isValid(); it->Next()) {
666 uint64_t value = it->intValue(),
667 key = it->intKey();
668 w2 = W2(key);
669 total_w1 += value;
670 if(last_w2 == 0xffffffffffffffff) last_w2 = w2;
671 if (w2 != last_w2) {
672 if(maxv >= min_cooccur) {
Marc Kupietzbbd236e2019-01-21 16:50:19 +0100673 double llr = ca_ll(_vocab[w1].freq, _vocab[last_w2].freq, maxv, total, 1);
Marc Kupietz3400aa52018-06-05 10:28:55 +0200674 if(first)
675 first = false;
676 else
677 stream << " ";
678 stream << w2 << " " << llr;
679 }
680 last_w2 = w2;
681 maxv = value;
682 } else {
683 if(value > maxv)
684 maxv = value;
685 }
686 }
687 if(first)
688 stream << "1 0.0";
689 stream << "\n";
690 std::cout << stream.str();
691 }
692
Marc Kupietz4b799e92018-01-02 11:04:56 +0100693 rocksdb::Slice rocksdb::CollocatorIterator::key() const { return base_iterator_->key(); }
694 rocksdb::Slice rocksdb::CollocatorIterator::value() const { return base_iterator_->value(); }
695 rocksdb::Status rocksdb::CollocatorIterator::status() const { return base_iterator_->status(); }
696
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100697};
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100698
Marc Kupietz4a5e08a2018-06-05 11:07:11 +0200699string rocksdb::CollocatorDB::getWord(uint32_t w1) {
700 return _vocab[w1].word;
701}
702
Marc Kupietz6aec7682018-01-10 09:47:48 +0100703string rocksdb::CollocatorDB::collocators2json(vector<Collocator> collocators) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100704 ostringstream s;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100705 int i = 0;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100706 s << "[";
707 bool first = true;
708 for (Collocator c : collocators) {
Marc Kupietzb999ec52018-06-05 11:20:46 +0200709 if(strncmp(_vocab[c.w2].word.c_str(), "quot", 4) == 0) continue;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100710 if (i++ > 200)
711 break;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100712 if(!first)
713 s << ",\n";
714 else
715 first = false;
716 s << "{"
Marc Kupietz7d9558f2019-01-22 16:26:50 +0100717 "\"word\":\"" << (string(_vocab[c.w2].word).compare("<num>") == 0? string("###") : string(_vocab[c.w2].word)) << "\"," <<
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100718 "\"rank\":" << c.w2 << "," <<
Marc Kupietz51f93792018-01-25 08:51:01 +0100719 "\"f\":" << c.raw << "," <<
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100720 "\"npmi\":" << c.npmi << "," <<
Marc Kupietz41880452019-01-22 15:29:06 +0100721 "\"pmi\":" << c.pmi << "," <<
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100722 "\"llr\":" << c.llr << "," <<
723 "\"lfmd\":" << c.lfmd << "," <<
Marc Kupietz41880452019-01-22 15:29:06 +0100724 "\"md\":" << c.md << "," <<
725 "\"dice\":" << c.dice << "," <<
726 "\"ld\":" << c.logdice << "," <<
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100727 "\"llfmd\":" << c.left_lfmd << "," <<
728 "\"rlfmd\":" << c.right_lfmd << "," <<
729 "\"lnpmi\":" << c.left_npmi << "," <<
Marc Kupietz75af60f2019-01-22 22:34:29 +0100730 "\"rnpmi\":" << c.right_npmi << "," <<
731 "\"af\":" << c.af << "," <<
732 "\"win\":" << c.window <<
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100733 "}";
734 }
735 s << "]\n";
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100736 // cout << s.str();
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100737 return s.str();
738}
739
Marc Kupietz6aec7682018-01-10 09:47:48 +0100740typedef rocksdb::CollocatorDB COLLOCATORS;
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100741
742extern "C" {
Marc Kupietz6aec7682018-01-10 09:47:48 +0100743 COLLOCATORS *open_collocatordb_for_write(char *dbname) {
744 return new rocksdb::CollocatorDB(dbname, false);
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100745 }
746
Marc Kupietz6aec7682018-01-10 09:47:48 +0100747 COLLOCATORS *open_collocatordb(char *dbname) {
748 return new rocksdb::CollocatorDB(dbname, true);
Marc Kupietz6bb27762018-01-09 17:53:01 +0100749 }
750
Marc Kupietz6aec7682018-01-10 09:47:48 +0100751 void inc_collocator(COLLOCATORS *db, uint32_t w1, uint32_t w2, int8_t dist) {
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100752 db->inc(w1, w2, dist);
753 }
754
755 void dump_collocators(COLLOCATORS *db, uint32_t w1, uint32_t w2, int8_t dist) {
756 db->dump(w1, w2, dist);
757 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100758
Marc Kupietz37359b12018-01-09 21:11:37 +0100759 void get_collocators(COLLOCATORS *db, uint32_t w1) {
760 db->get_collocators(w1);
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100761 }
762
Marc Kupietzca3a52e2018-06-05 14:16:23 +0200763 const char *get_word(COLLOCATORS *db, uint32_t w) {
764 return db->getWord(w).c_str();
765 }
766
Marc Kupietz37359b12018-01-09 21:11:37 +0100767 const char *get_collocators_as_json(COLLOCATORS *db, uint32_t w1) {
768 return strdup(db->collocators2json(db->get_collocators(w1)).c_str());
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100769 }
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100770}