blob: 752096847913d6426ffd28339a6e50aa9ec88564 [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 Kupietzc8ddf452018-01-07 21:33:12 +010025#define AVG_WINDOW_SIZE 7
Marc Kupietz06c9a9f2018-01-02 16:56:43 +010026
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 Kupietzc8ddf452018-01-07 21:33:12 +010047 class Collocator {
48 public:
49 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;
55 double fpmi;
Marc Kupietz8e0ebea2018-01-24 09:53:26 +010056 double left_lfmd;
57 double right_lfmd;
58 double left_npmi;
59 double right_npmi;
Marc Kupietzc8ddf452018-01-07 21:33:12 +010060 };
61
Marc Kupietz28cc53e2017-12-23 17:24:55 +010062 size_t num_merge_operator_calls;
63 void resetNumMergeOperatorCalls() { num_merge_operator_calls = 0; }
Marc Kupietzc8ddf452018-01-07 21:33:12 +010064
Marc Kupietz28cc53e2017-12-23 17:24:55 +010065 size_t num_partial_merge_calls;
66 void resetNumPartialMergeCalls() { num_partial_merge_calls = 0; }
Marc Kupietz28cc53e2017-12-23 17:24:55 +010067
68
Marc Kupietz4b799e92018-01-02 11:04:56 +010069 inline void EncodeFixed64(char* buf, uint64_t value) {
70 if (! IS_BIG_ENDIAN) {
71 memcpy(buf, &value, sizeof(value));
72 } else {
73 buf[0] = value & 0xff;
74 buf[1] = (value >> 8) & 0xff;
75 buf[2] = (value >> 16) & 0xff;
76 buf[3] = (value >> 24) & 0xff;
77 buf[4] = (value >> 32) & 0xff;
78 buf[5] = (value >> 40) & 0xff;
79 buf[6] = (value >> 48) & 0xff;
80 buf[7] = (value >> 56) & 0xff;
81 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +010082 }
83
Marc Kupietz4b799e92018-01-02 11:04:56 +010084 inline uint32_t DecodeFixed32(const char* ptr) {
85 if (! IS_BIG_ENDIAN) {
86 // Load the raw bytes
87 uint32_t result;
88 memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
89 return result;
90 } else {
91 return ((static_cast<uint32_t>(static_cast<unsigned char>(ptr[0])))
92 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[1])) << 8)
93 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[2])) << 16)
94 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[3])) << 24));
95 }
96 }
97
98 inline uint64_t DecodeFixed64(const char* ptr) {
99 if (! IS_BIG_ENDIAN) {
100 // Load the raw bytes
101 uint64_t result;
102 memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
103 return result;
104 } else {
105 uint64_t lo = DecodeFixed32(ptr);
106 uint64_t hi = DecodeFixed32(ptr + 4);
107 return (hi << 32) | lo;
108 }
109 }
110
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100111 static inline double ca_pmi(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
112 return log2( total * ((double) f12) / (window_size * ((double) f1) * ((double)f2) ));
113 }
114
115 static inline double ca_npmi(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
Marc Kupietz8caf9912018-06-05 10:51:18 +0200116 if(f12 == 0)
117 return -1.0;
118 else
119 return log2( total * ((double) f12) / (window_size * ((double) f1) * ((double)f2) )) / (-log2(((double) f12 / window_size / total)));
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100120 }
121
122 // Thanopoulos, A., Fakotakis, N., Kokkinakis, G.: Comparative evaluation of collocation extraction metrics.
123 // In: International Conference on Language Resources and Evaluation (LREC-2002). (2002) 620–625
124 // double md = log2(pow((double)max * window_size / total, 2) / (window_size * ((double)_vocab[w1].freq/total) * ((double)_vocab[last_w2].freq/total)));
125 static inline double ca_md(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
126 return log2((double)f12 * f12 / ((double) total * window_size * window_size * f1 * f2));
127 }
128
129 static inline double ca_lfmd(uint64_t f1, uint64_t f2, uint64_t f12, uint64_t total, double window_size) {
Marc Kupietz8caf9912018-06-05 10:51:18 +0200130 if(f12 == 0)
131 return 0;
132 else
133 return log2((double)f12 * f12 / ((double) total * window_size * window_size * f1 * f2)) + log2((double) f12 / window_size / total);
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100134 }
135
Marc Kupietz4b799e92018-01-02 11:04:56 +0100136
137 class CountMergeOperator : public AssociativeMergeOperator {
138 public:
139 CountMergeOperator() {
140 mergeOperator_ = MergeOperators::CreateUInt64AddOperator();
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100141 }
142
Marc Kupietz4b799e92018-01-02 11:04:56 +0100143 virtual bool Merge(const Slice& key,
144 const Slice* existing_value,
145 const Slice& value,
146 std::string* new_value,
147 Logger* logger) const override {
148 assert(new_value->empty());
149 ++num_merge_operator_calls;
150 if (existing_value == nullptr) {
151 new_value->assign(value.data(), value.size());
152 return true;
153 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100154
Marc Kupietz4b799e92018-01-02 11:04:56 +0100155 return mergeOperator_->PartialMerge(
156 key,
157 *existing_value,
158 value,
159 new_value,
160 logger);
161 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100162
Marc Kupietz4b799e92018-01-02 11:04:56 +0100163 virtual const char* Name() const override {
164 return "UInt64AddOperator";
165 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100166
Marc Kupietz4b799e92018-01-02 11:04:56 +0100167 private:
168 std::shared_ptr<MergeOperator> mergeOperator_;
169 };
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100170
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100171
Marc Kupietz4b799e92018-01-02 11:04:56 +0100172 class CollocatorIterator : public Iterator {
173 private:
174 char prefixc[sizeof(uint64_t)];
175 Iterator *base_iterator_;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100176
177
Marc Kupietz4b799e92018-01-02 11:04:56 +0100178 public:
179 CollocatorIterator(Iterator* base_iterator)
180 : base_iterator_(base_iterator)
181 {}
182
Marc Kupietz4b799e92018-01-02 11:04:56 +0100183 void setPrefix(char *prefix) {
184 memcpy(prefixc, prefix, sizeof(uint64_t));
185 }
186
187 virtual void SeekToFirst() { base_iterator_->SeekToFirst(); }
188 virtual void SeekToLast() { base_iterator_->SeekToLast(); }
189 virtual void Seek(const rocksdb::Slice& s) { base_iterator_->Seek(s); }
190 virtual void Prev() { base_iterator_->Prev(); }
191 virtual void Next() { base_iterator_->Next(); }
192 virtual Slice key() const;
193 virtual Slice value() const;
194 virtual Status status() const;
195 virtual bool Valid() const;
196 bool isValid();
197 uint64_t intValue();
198 uint64_t intKey();
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100199
Marc Kupietz4b799e92018-01-02 11:04:56 +0100200 };
Marc Kupietz18375e12017-12-24 10:11:18 +0100201
Marc Kupietz4b799e92018-01-02 11:04:56 +0100202 // rocksdb::CollocatorIterator::CollocatorIterator(Iterator* base_iterator) {}
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100203
Marc Kupietz4b799e92018-01-02 11:04:56 +0100204 bool rocksdb::CollocatorIterator::Valid() const {
Marc Kupietz18375e12017-12-24 10:11:18 +0100205 return base_iterator_->Valid() && key().starts_with(std::string(prefixc,3));
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100206 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100207
Marc Kupietz4b799e92018-01-02 11:04:56 +0100208 bool rocksdb::CollocatorIterator::isValid() {
209 return base_iterator_->Valid() && key().starts_with(std::string(prefixc,3));
Marc Kupietzd31254c2018-01-20 21:29:30 +0100210 // return key().starts_with(std::string(prefixc,3));
Marc Kupietz4b799e92018-01-02 11:04:56 +0100211 }
Marc Kupietz18375e12017-12-24 10:11:18 +0100212
Marc Kupietz4b799e92018-01-02 11:04:56 +0100213 uint64_t rocksdb::CollocatorIterator::intKey() {
214 return DecodeFixed64(base_iterator_->key().data());
215 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100216
Marc Kupietz4b799e92018-01-02 11:04:56 +0100217 uint64_t rocksdb::CollocatorIterator::intValue() {
218 return DecodeFixed64(base_iterator_->value().data());
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100219 }
220
Marc Kupietz37359b12018-01-09 21:11:37 +0100221 class VocabEntry {
222 public:
223 string word;
224 uint64_t freq;
225 };
226
Marc Kupietz6aec7682018-01-10 09:47:48 +0100227 class CollocatorDB {
Marc Kupietz4b799e92018-01-02 11:04:56 +0100228 private:
229 WriteOptions merge_option_; // for merge
230 char _one[sizeof(uint64_t)];
231 Slice _one_slice;
Marc Kupietz37359b12018-01-09 21:11:37 +0100232 vector<VocabEntry> _vocab;
233 uint64_t total;
234
Marc Kupietz4b799e92018-01-02 11:04:56 +0100235 protected:
236 std::shared_ptr<DB> db_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100237
Marc Kupietz4b799e92018-01-02 11:04:56 +0100238 WriteOptions put_option_;
239 ReadOptions get_option_;
240 WriteOptions delete_option_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100241
Marc Kupietz4b799e92018-01-02 11:04:56 +0100242 uint64_t default_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100243
Marc Kupietz4b799e92018-01-02 11:04:56 +0100244 std::shared_ptr<DB> OpenDb(const char *dbname);
Marc Kupietz6bb27762018-01-09 17:53:01 +0100245 std::shared_ptr<DB> OpenDbForRead(const char *dbname);
Marc Kupietz37359b12018-01-09 21:11:37 +0100246 void read_vocab(string fname);
247
Marc Kupietz4b799e92018-01-02 11:04:56 +0100248 public:
Marc Kupietz6aec7682018-01-10 09:47:48 +0100249 CollocatorDB(const char *db_name, bool read_only);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100250
Marc Kupietz6aec7682018-01-10 09:47:48 +0100251 // public interface of CollocatorDB.
Marc Kupietz4b799e92018-01-02 11:04:56 +0100252 // All four functions return false
253 // if the underlying level db operation failed.
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100254
Marc Kupietz4b799e92018-01-02 11:04:56 +0100255 // mapped to a levedb Put
256 bool set(const std::string& key, uint64_t value) {
257 // just treat the internal rep of int64 as the string
258 char buf[sizeof(value)];
259 EncodeFixed64(buf, value);
260 Slice slice(buf, sizeof(value));
261 auto s = db_->Put(put_option_, key, slice);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100262
Marc Kupietz4b799e92018-01-02 11:04:56 +0100263 if (s.ok()) {
264 return true;
265 } else {
266 std::cerr << s.ToString() << std::endl;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100267 return false;
268 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100269 }
Marc Kupietz4b799e92018-01-02 11:04:56 +0100270
271 DB *getDb() {
272 return db_.get();
273 }
274
275 // mapped to a rocksdb Delete
276 bool remove(const std::string& key) {
277 auto s = db_->Delete(delete_option_, key);
278
279 if (s.ok()) {
280 return true;
281 } else {
282 std::cerr << s.ToString() << std::endl;
283 return false;
284 }
285 }
286
287 // mapped to a rocksdb Get
288 bool get(const std::string& key, uint64_t* value) {
289 std::string str;
290 auto s = db_->Get(get_option_, key, &str);
291
292 if (s.IsNotFound()) {
293 // return default value if not found;
294 *value = default_;
295 return true;
296 } else if (s.ok()) {
297 // deserialization
298 if (str.size() != sizeof(uint64_t)) {
299 std::cerr << "value corruption\n";
300 return false;
301 }
302 *value = DecodeFixed64(&str[0]);
303 return true;
304 } else {
305 std::cerr << s.ToString() << std::endl;
306 return false;
307 }
308 }
309
310
311 uint64_t get(const uint32_t w1, const uint32_t w2, const int8_t dist) {
312 char encoded_key[sizeof(uint64_t)];
313 EncodeFixed64(encoded_key, encodeCollocation(w1,w2,dist));
314 uint64_t value = default_;
315 get(std::string(encoded_key, 8), &value);
316 return value;
317 }
318
319 virtual void inc(const std::string& key) {
320 db_->Merge(merge_option_, key, _one_slice);
321 }
322
323 void inc(const uint64_t key) {
324 char encoded_key[sizeof(uint64_t)];
325 EncodeFixed64(encoded_key, key);
326 db_->Merge(merge_option_, std::string(encoded_key, 8), _one_slice);
327 }
328
329 virtual void inc(const uint32_t w1, const uint32_t w2, const uint8_t dist);
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100330 void dump(uint32_t w1, uint32_t w2, int8_t dist);
Marc Kupietz37359b12018-01-09 21:11:37 +0100331 vector<Collocator> get_collocators(uint32_t w1);
Marc Kupietz3400aa52018-06-05 10:28:55 +0200332 void dumpSparseLlr(uint32_t w1, uint32_t min_cooccur);
Marc Kupietzd31254c2018-01-20 21:29:30 +0100333 vector<Collocator> get_collocators_avg(uint32_t w1);
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100334 string collocators2json(vector<Collocator> collocators);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100335
Marc Kupietz4b799e92018-01-02 11:04:56 +0100336 // mapped to a rocksdb Merge operation
337 virtual bool add(const std::string& key, uint64_t value) {
338 char encoded[sizeof(uint64_t)];
339 EncodeFixed64(encoded, value);
340 Slice slice(encoded, sizeof(uint64_t));
341 auto s = db_->Merge(merge_option_, key, slice);
342
343 if (s.ok()) {
344 return true;
345 } else {
346 std::cerr << s.ToString() << std::endl;
347 return false;
348 }
349 }
350
351 CollocatorIterator* SeekIterator(uint64_t w1, uint64_t w2, int8_t dist);
352 };
353
Marc Kupietz6aec7682018-01-10 09:47:48 +0100354 rocksdb::CollocatorDB::CollocatorDB(const char *db_name, bool read_only = false) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100355 // merge_option_.sync = true;
Marc Kupietz6bb27762018-01-09 17:53:01 +0100356 if(read_only)
357 db_ = OpenDbForRead(db_name);
358 else
359 db_ = OpenDb(db_name);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100360 assert(db_);
361 uint64_t one = 1;
362 EncodeFixed64(_one, one);
363 _one_slice = Slice(_one, sizeof(uint64_t));
364 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100365
Marc Kupietz6aec7682018-01-10 09:47:48 +0100366 void rocksdb::CollocatorDB::inc(const uint32_t w1, const uint32_t w2, const uint8_t dist) {
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100367 inc(encodeCollocation(w1, w2, dist));
368 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100369
Marc Kupietz6aec7682018-01-10 09:47:48 +0100370 void rocksdb::CollocatorDB::read_vocab(string fname) {
Marc Kupietz37359b12018-01-09 21:11:37 +0100371 char strbuf[2048];
372 uint64_t freq;
373 FILE *fin = fopen(fname.c_str(), "rb");
374 if (fin == NULL) {
375 cout << "Vocabulary file " << fname <<" not found\n";
376 exit(1);
377 }
378 uint64_t i = 0;
379 while(!feof(fin)) {
Marc Kupietzd31254c2018-01-20 21:29:30 +0100380 fscanf(fin, "%s %lu", strbuf, &freq);
Marc Kupietz37359b12018-01-09 21:11:37 +0100381 _vocab.push_back({strbuf, freq});
382 total += freq;
383 i++;
384 }
385 fclose(fin);
386 }
387
Marc Kupietz6aec7682018-01-10 09:47:48 +0100388 std::shared_ptr<DB> rocksdb::CollocatorDB::OpenDbForRead(const char *name) {
Marc Kupietz6bb27762018-01-09 17:53:01 +0100389 DB* db;
390 Options options;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100391 options.env->SetBackgroundThreads(4);
392 options.create_if_missing = true;
393 options.merge_operator = std::make_shared<CountMergeOperator>();
394 options.max_successive_merges = 0;
395 // options.prefix_extractor.reset(NewFixedPrefixTransform(8));
396 options.IncreaseParallelism();
397 options.OptimizeLevelStyleCompaction();
398 options.prefix_extractor.reset(NewFixedPrefixTransform(3));
Marc Kupietz37359b12018-01-09 21:11:37 +0100399 ostringstream dbname, vocabname;
Marc Kupietz6bb27762018-01-09 17:53:01 +0100400 dbname << name << ".rocksdb";
401 auto s = DB::OpenForReadOnly(options, dbname.str(), &db);
402 if (!s.ok()) {
403 std::cerr << s.ToString() << std::endl;
404 assert(false);
405 }
Marc Kupietz37359b12018-01-09 21:11:37 +0100406 vocabname << name << ".vocab";
407 read_vocab(vocabname.str());
Marc Kupietz6bb27762018-01-09 17:53:01 +0100408 return std::shared_ptr<DB>(db);
409 }
410
Marc Kupietz6aec7682018-01-10 09:47:48 +0100411 std::shared_ptr<DB> rocksdb::CollocatorDB::OpenDb(const char *dbname) {
Marc Kupietz4b799e92018-01-02 11:04:56 +0100412 DB* db;
413 Options options;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100414
415
416 options.env->SetBackgroundThreads(4);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100417 options.create_if_missing = true;
418 options.merge_operator = std::make_shared<CountMergeOperator>();
419 options.max_successive_merges = 0;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100420 // options.prefix_extractor.reset(NewFixedPrefixTransform(8));
421 options.IncreaseParallelism();
422 options.OptimizeLevelStyleCompaction();
423 // options.max_write_buffer_number = 48;
424 // options.max_background_jobs = 48;
425 // options.allow_concurrent_memtable_write=true;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100426 // options.memtable_factory.reset(rocksdb::NewHashLinkListRepFactory(200000));
427 // options.enable_write_thread_adaptive_yield = 1;
428 // options.allow_concurrent_memtable_write = 1;
429 // options.memtable_factory.reset(new rocksdb::SkipListFactory);
430 // options.write_buffer_size = 1 << 22;
431 // options.allow_mmap_reads = true;
432 // options.allow_mmap_writes = true;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100433 // options.max_background_compactions = 40;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100434 // BlockBasedTableOptions table_options;
435 // table_options.filter_policy.reset(NewBloomFilterPolicy(24, false));
436 // options.bloom_locality = 1;
437 // std::shared_ptr<Cache> cache = NewLRUCache(512 * 1024 * 1024);
438 // table_options.block_cache = cache;
439 // options.table_factory.reset(NewBlockBasedTableFactory(table_options));
Marc Kupietz4b799e92018-01-02 11:04:56 +0100440 Status s;
441 // DestroyDB(dbname, Options());
442 s = DB::Open(options, dbname, &db);
443 if (!s.ok()) {
444 std::cerr << s.ToString() << std::endl;
445 assert(false);
446 }
447 return std::shared_ptr<DB>(db);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100448 }
449
Marc Kupietz6aec7682018-01-10 09:47:48 +0100450 CollocatorIterator* rocksdb::CollocatorDB::SeekIterator(uint64_t w1, uint64_t w2, int8_t dist) {
Marc Kupietz18375e12017-12-24 10:11:18 +0100451 ReadOptions options;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100452 options.prefix_same_as_start = true;
Marc Kupietz18375e12017-12-24 10:11:18 +0100453 char prefixc[sizeof(uint64_t)];
454 EncodeFixed64(prefixc, encodeCollocation(w1, w2, dist));
455 Iterator *it = db_->NewIterator(options);
456 CollocatorIterator *cit = new CollocatorIterator(it);
457 cit->Seek(std::string(prefixc,3));// it->Valid() && it->key().starts_with(std::string(prefixc,3)); it->Next()) {
458 cit->setPrefix(prefixc);
459 return cit;
460 }
461
Marc Kupietz6aec7682018-01-10 09:47:48 +0100462 void rocksdb::CollocatorDB::dump(uint32_t w1, uint32_t w2, int8_t dist) {
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100463 auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, w2, dist));
464 for (; it->isValid(); it->Next()) {
465 uint64_t value = it->intValue();
466 uint64_t key = it->intKey();
467 std::cout << "w1:" << W1(key) << ", w2:" << W2(key) << ", dist:" << (int32_t) DIST(key) << " - count:" << value << std::endl;
468 }
469 std::cout << "ready dumping\n";
470 }
471
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100472 double calculateLLR(uint64_t f_X_, uint64_t uintN, uint64_t f_X_Y_, uint64_t f_Y_) {
473 double f_e_, f_o_;
474 double A=0.0, B=0.0, C=0.0, D=0.0, N=0.0;
475 double LLR=0.0, statVal=0.0, minusDiffCoeff=0.0;
476 double BlogB=0.0, ClogC=0.0;
477
478 N = (double)uintN;
479 A = (double)f_X_Y_;
480 B = (double)f_X_ -A;
481 C = (double)f_Y_ -A;
482 D = (double)N -A-B-C;;
483
484 if (B > 0.) BlogB = B*log(B);
485 if (C > 0.) ClogC = C*log(C);
486
487 if ((A>0.) && (D>0.) && (N>0.)) {
488 f_e_ = (double)f_X_ /(double)N;
489 f_o_ = (double)f_X_Y_/(double)f_Y_;
490
491 minusDiffCoeff =
492 ( f_X_==0 ? (double)((-1)*f_X_Y_) :
493 ( f_X_Y_==0 ? (double)((+1)*f_X_) :
494 (f_e_-f_o_)/(f_e_+f_o_)
495 )
496 );
497
498 /* log likelihood ratio */
499 LLR = 2*( A*log(A)
500 +BlogB
501 +ClogC
502 +D*log(D)
503 -(A+B)*log(A+B)
504 -(A+C)*log(A+C)
505 -(B+D)*log(B+D)
506 -(C+D)*log(C+D)
507 +N*log(N)
508 );
509 }
510 return(minusDiffCoeff > 0 ? 0 : (statVal=LLR));
511 }
512
513
514 bool sortByNpmi(const Collocator &lhs, const Collocator &rhs) { return lhs.npmi > rhs.npmi; }
515 bool sortByLfmd(const Collocator &lhs, const Collocator &rhs) { return lhs.lfmd > rhs.lfmd; }
Marc Kupietzd31254c2018-01-20 21:29:30 +0100516 bool sortByLlr(const Collocator &lhs, const Collocator &rhs) { return lhs.llr > rhs.llr; }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100517
Marc Kupietzd31254c2018-01-20 21:29:30 +0100518 std::vector<Collocator> rocksdb::CollocatorDB::get_collocators_avg(uint32_t w1) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100519 std::vector<Collocator> collocators;
520 uint64_t w2, last_w2 = 0xffffffffffffffff;
521 uint64_t sum = 0, total_w1 = 0;
522 for ( auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, 0, 0)); it->isValid(); it->Next()) {
523 uint64_t value = it->intValue(),
524 key = it->intKey();
525 w2 = W2(key);
526 total_w1 += value;
527 if(last_w2 == 0xffffffffffffffff) last_w2 = w2;
528 if (w2 != last_w2) {
529 double pmi = log2( total * ((double) sum) /
Marc Kupietz37359b12018-01-09 21:11:37 +0100530 (AVG_WINDOW_SIZE * ((double)_vocab[w1].freq) * ((double)_vocab[last_w2].freq) ));
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100531 // Thanopoulos, A., Fakotakis, N., Kokkinakis, G.: Comparative evaluation of collocation extraction metrics. In: International Conference on Language Resources and Evaluation (LREC-2002). (2002) 620–625
Marc Kupietz37359b12018-01-09 21:11:37 +0100532 // double md = log2(pow((double)sum * AVG_WINDOW_SIZE / total, 2) / (AVG_WINDOW_SIZE * ((double)_vocab[w1].freq/total) * ((double)_vocab[last_w2].freq/total)));
533 double md = log2((double)sum * sum / ((double) total * AVG_WINDOW_SIZE * AVG_WINDOW_SIZE * _vocab[w1].freq * _vocab[last_w2].freq));
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100534 collocators.push_back ( {last_w2, sum, pmi, pmi / (-log2(((double) sum / AVG_WINDOW_SIZE / total))), /* normalize to [-1,1] */
Marc Kupietz37359b12018-01-09 21:11:37 +0100535 calculateLLR(_vocab[w1].freq, total, sum, _vocab[last_w2].freq), md, md + log2((double)sum / AVG_WINDOW_SIZE / total), pmi*sum/total/AVG_WINDOW_SIZE} );
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100536 last_w2 = w2;
537 sum = value;
538 } else {
539 sum += value;
540 }
541 }
542
543 sort(collocators.begin(), collocators.end(), sortByLfmd);
544
545 int i=0;
546 for (Collocator c : collocators) {
547 if(i++>10) break;
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100548 std::cout << "dont call me w1:" << _vocab[w1].word << ", w2:" << _vocab[c.w2].word
Marc Kupietz37359b12018-01-09 21:11:37 +0100549 << "\t f(w1):" << _vocab[w1].freq
550 << "\t f(w2):" << _vocab[c.w2].freq
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100551 << "\t f(w1, x):" << total_w1
Marc Kupietz51f93792018-01-25 08:51:01 +0100552 << "\t f(w1, w2):" << c.raw
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100553 << "\t pmi:" << c.pmi
554 << "\t npmi:" << c.npmi
555 << "\t llr:" << c.llr
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100556 << "\t lfmd:" << c.lfmd
557 << "\t fpmi:" << c.fpmi
558 << "\t total:" << total
559 << std::endl;
560 }
561 return collocators;
562 }
563
Marc Kupietzd31254c2018-01-20 21:29:30 +0100564 std::vector<Collocator> rocksdb::CollocatorDB::get_collocators(uint32_t w1) {
565 std::vector<Collocator> collocators;
566 uint64_t w2, last_w2 = 0xffffffffffffffff;
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100567 uint64_t maxv = 0, left = 0, right = 0, total_w1 = 0;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100568 const double window_size = 1;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100569 for ( auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, 0, 0)); it->isValid(); it->Next()) {
570 uint64_t value = it->intValue(),
571 key = it->intKey();
572 w2 = W2(key);
573 total_w1 += value;
574 if(last_w2 == 0xffffffffffffffff) last_w2 = w2;
575 if (w2 != last_w2) {
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100576 double pmi = ca_pmi(_vocab[w1].freq, _vocab[last_w2].freq, maxv, total, window_size);
577 double lfmd = ca_lfmd(_vocab[w1].freq, _vocab[last_w2].freq, maxv, total, window_size);
578 double left_lfmd = ca_lfmd(_vocab[w1].freq, _vocab[last_w2].freq, left, total, 1);
579 double right_lfmd = ca_lfmd(_vocab[w1].freq, _vocab[last_w2].freq, right, total, 1);
580 double left_npmi = ca_npmi(_vocab[w1].freq, _vocab[last_w2].freq, left, total, 1);
581 double right_npmi = ca_npmi(_vocab[w1].freq, _vocab[last_w2].freq, right, total, 1);
582 collocators.push_back ( {last_w2, maxv, pmi, pmi / (-log2(((double) maxv / window_size / total))), /* normalize to [-1,1] */
583 calculateLLR(_vocab[w1].freq, total, maxv, _vocab[last_w2].freq), lfmd, pmi*maxv/total/window_size,
584 left_lfmd,
585 right_lfmd,
586 left_npmi,
587 right_npmi}
588 );
Marc Kupietzd31254c2018-01-20 21:29:30 +0100589 last_w2 = w2;
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100590 maxv = value;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100591 } else {
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100592 if(value > maxv)
593 maxv = value;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100594 }
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100595 if(DIST(key) == -1)
596 left = value;
597 else if(DIST(key) == 1)
598 right = value;
Marc Kupietzd31254c2018-01-20 21:29:30 +0100599 }
600
601 sort(collocators.begin(), collocators.end(), sortByLfmd);
602
603 int i=0;
604 for (Collocator c : collocators) {
605 if(i++>10) break;
606 std::cout << "w1:" << _vocab[w1].word << ", w2:" << _vocab[c.w2].word
607 << "\t f(w1):" << _vocab[w1].freq
608 << "\t f(w2):" << _vocab[c.w2].freq
609 << "\t f(w1, x):" << total_w1
Marc Kupietz51f93792018-01-25 08:51:01 +0100610 << "\t f(w1, w2):" << c.raw
Marc Kupietzd31254c2018-01-20 21:29:30 +0100611 << "\t pmi:" << c.pmi
612 << "\t npmi:" << c.npmi
613 << "\t llr:" << c.llr
Marc Kupietzd31254c2018-01-20 21:29:30 +0100614 << "\t lfmd:" << c.lfmd
615 << "\t fpmi:" << c.fpmi
616 << "\t total:" << total
617 << std::endl;
618 }
619 return collocators;
620 }
621
Marc Kupietz3400aa52018-06-05 10:28:55 +0200622 void rocksdb::CollocatorDB::dumpSparseLlr(uint32_t w1, uint32_t min_cooccur) {
623 std::vector<Collocator> collocators;
624 std::stringstream stream;
625 uint64_t w2, last_w2 = 0xffffffffffffffff;
626 uint64_t maxv = 0, total_w1 = 0;
627 bool first = true;
628 for ( auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, 0, 0)); it->isValid(); it->Next()) {
629 uint64_t value = it->intValue(),
630 key = it->intKey();
631 w2 = W2(key);
632 total_w1 += value;
633 if(last_w2 == 0xffffffffffffffff) last_w2 = w2;
634 if (w2 != last_w2) {
635 if(maxv >= min_cooccur) {
636 double llr = calculateLLR(_vocab[w1].freq, total, maxv, _vocab[last_w2].freq);
637 if(first)
638 first = false;
639 else
640 stream << " ";
641 stream << w2 << " " << llr;
642 }
643 last_w2 = w2;
644 maxv = value;
645 } else {
646 if(value > maxv)
647 maxv = value;
648 }
649 }
650 if(first)
651 stream << "1 0.0";
652 stream << "\n";
653 std::cout << stream.str();
654 }
655
Marc Kupietz4b799e92018-01-02 11:04:56 +0100656 rocksdb::Slice rocksdb::CollocatorIterator::key() const { return base_iterator_->key(); }
657 rocksdb::Slice rocksdb::CollocatorIterator::value() const { return base_iterator_->value(); }
658 rocksdb::Status rocksdb::CollocatorIterator::status() const { return base_iterator_->status(); }
659
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100660};
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100661
Marc Kupietz6aec7682018-01-10 09:47:48 +0100662string rocksdb::CollocatorDB::collocators2json(vector<Collocator> collocators) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100663 ostringstream s;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100664 int i = 0;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100665 s << "[";
666 bool first = true;
667 for (Collocator c : collocators) {
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100668 if (i++ > 200)
669 break;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100670 if(!first)
671 s << ",\n";
672 else
673 first = false;
674 s << "{"
675 "\"word\":\"" << string(_vocab[c.w2].word) << "\"," <<
676 "\"rank\":" << c.w2 << "," <<
Marc Kupietz51f93792018-01-25 08:51:01 +0100677 "\"f\":" << c.raw << "," <<
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100678 "\"npmi\":" << c.npmi << "," <<
679 "\"llr\":" << c.llr << "," <<
680 "\"lfmd\":" << c.lfmd << "," <<
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100681 "\"fpmi\":" << c.fpmi << "," <<
682 "\"llfmd\":" << c.left_lfmd << "," <<
683 "\"rlfmd\":" << c.right_lfmd << "," <<
684 "\"lnpmi\":" << c.left_npmi << "," <<
685 "\"rnpmi\":" << c.right_npmi <<
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100686 "}";
687 }
688 s << "]\n";
Marc Kupietz8e0ebea2018-01-24 09:53:26 +0100689 // cout << s.str();
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100690 return s.str();
691}
692
Marc Kupietz6aec7682018-01-10 09:47:48 +0100693typedef rocksdb::CollocatorDB COLLOCATORS;
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100694
695extern "C" {
Marc Kupietz6aec7682018-01-10 09:47:48 +0100696 COLLOCATORS *open_collocatordb_for_write(char *dbname) {
697 return new rocksdb::CollocatorDB(dbname, false);
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100698 }
699
Marc Kupietz6aec7682018-01-10 09:47:48 +0100700 COLLOCATORS *open_collocatordb(char *dbname) {
701 return new rocksdb::CollocatorDB(dbname, true);
Marc Kupietz6bb27762018-01-09 17:53:01 +0100702 }
703
Marc Kupietz6aec7682018-01-10 09:47:48 +0100704 void inc_collocator(COLLOCATORS *db, uint32_t w1, uint32_t w2, int8_t dist) {
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100705 db->inc(w1, w2, dist);
706 }
707
708 void dump_collocators(COLLOCATORS *db, uint32_t w1, uint32_t w2, int8_t dist) {
709 db->dump(w1, w2, dist);
710 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100711
Marc Kupietz37359b12018-01-09 21:11:37 +0100712 void get_collocators(COLLOCATORS *db, uint32_t w1) {
713 db->get_collocators(w1);
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100714 }
715
Marc Kupietz37359b12018-01-09 21:11:37 +0100716 const char *get_collocators_as_json(COLLOCATORS *db, uint32_t w1) {
717 return strdup(db->collocators2json(db->get_collocators(w1)).c_str());
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100718 }
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100719}