blob: 9ecbf63271e04221b17caabe9172a1c24d5b486b [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 Kupietz28cc53e2017-12-23 17:24:55 +010014#include "rocksdb/cache.h"
15#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;
50 uint64_t sum;
51 double pmi;
52 double npmi;
53 double llr;
54 double md;
55 double lfmd;
56 double fpmi;
57 };
58
Marc Kupietz28cc53e2017-12-23 17:24:55 +010059 size_t num_merge_operator_calls;
60 void resetNumMergeOperatorCalls() { num_merge_operator_calls = 0; }
Marc Kupietzc8ddf452018-01-07 21:33:12 +010061
Marc Kupietz28cc53e2017-12-23 17:24:55 +010062 size_t num_partial_merge_calls;
63 void resetNumPartialMergeCalls() { num_partial_merge_calls = 0; }
Marc Kupietz28cc53e2017-12-23 17:24:55 +010064
65
Marc Kupietz4b799e92018-01-02 11:04:56 +010066 inline void EncodeFixed64(char* buf, uint64_t value) {
67 if (! IS_BIG_ENDIAN) {
68 memcpy(buf, &value, sizeof(value));
69 } else {
70 buf[0] = value & 0xff;
71 buf[1] = (value >> 8) & 0xff;
72 buf[2] = (value >> 16) & 0xff;
73 buf[3] = (value >> 24) & 0xff;
74 buf[4] = (value >> 32) & 0xff;
75 buf[5] = (value >> 40) & 0xff;
76 buf[6] = (value >> 48) & 0xff;
77 buf[7] = (value >> 56) & 0xff;
78 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +010079 }
80
Marc Kupietz4b799e92018-01-02 11:04:56 +010081 inline uint32_t DecodeFixed32(const char* ptr) {
82 if (! IS_BIG_ENDIAN) {
83 // Load the raw bytes
84 uint32_t result;
85 memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
86 return result;
87 } else {
88 return ((static_cast<uint32_t>(static_cast<unsigned char>(ptr[0])))
89 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[1])) << 8)
90 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[2])) << 16)
91 | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[3])) << 24));
92 }
93 }
94
95 inline uint64_t DecodeFixed64(const char* ptr) {
96 if (! IS_BIG_ENDIAN) {
97 // Load the raw bytes
98 uint64_t result;
99 memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
100 return result;
101 } else {
102 uint64_t lo = DecodeFixed32(ptr);
103 uint64_t hi = DecodeFixed32(ptr + 4);
104 return (hi << 32) | lo;
105 }
106 }
107
108
109 class CountMergeOperator : public AssociativeMergeOperator {
110 public:
111 CountMergeOperator() {
112 mergeOperator_ = MergeOperators::CreateUInt64AddOperator();
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100113 }
114
Marc Kupietz4b799e92018-01-02 11:04:56 +0100115 virtual bool Merge(const Slice& key,
116 const Slice* existing_value,
117 const Slice& value,
118 std::string* new_value,
119 Logger* logger) const override {
120 assert(new_value->empty());
121 ++num_merge_operator_calls;
122 if (existing_value == nullptr) {
123 new_value->assign(value.data(), value.size());
124 return true;
125 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100126
Marc Kupietz4b799e92018-01-02 11:04:56 +0100127 return mergeOperator_->PartialMerge(
128 key,
129 *existing_value,
130 value,
131 new_value,
132 logger);
133 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100134
Marc Kupietz4b799e92018-01-02 11:04:56 +0100135 virtual const char* Name() const override {
136 return "UInt64AddOperator";
137 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100138
Marc Kupietz4b799e92018-01-02 11:04:56 +0100139 private:
140 std::shared_ptr<MergeOperator> mergeOperator_;
141 };
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100142
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100143
Marc Kupietz4b799e92018-01-02 11:04:56 +0100144 class CollocatorIterator : public Iterator {
145 private:
146 char prefixc[sizeof(uint64_t)];
147 Iterator *base_iterator_;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100148
149
Marc Kupietz4b799e92018-01-02 11:04:56 +0100150 public:
151 CollocatorIterator(Iterator* base_iterator)
152 : base_iterator_(base_iterator)
153 {}
154
Marc Kupietz4b799e92018-01-02 11:04:56 +0100155 void setPrefix(char *prefix) {
156 memcpy(prefixc, prefix, sizeof(uint64_t));
157 }
158
159 virtual void SeekToFirst() { base_iterator_->SeekToFirst(); }
160 virtual void SeekToLast() { base_iterator_->SeekToLast(); }
161 virtual void Seek(const rocksdb::Slice& s) { base_iterator_->Seek(s); }
162 virtual void Prev() { base_iterator_->Prev(); }
163 virtual void Next() { base_iterator_->Next(); }
164 virtual Slice key() const;
165 virtual Slice value() const;
166 virtual Status status() const;
167 virtual bool Valid() const;
168 bool isValid();
169 uint64_t intValue();
170 uint64_t intKey();
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100171
Marc Kupietz4b799e92018-01-02 11:04:56 +0100172 };
Marc Kupietz18375e12017-12-24 10:11:18 +0100173
Marc Kupietz4b799e92018-01-02 11:04:56 +0100174 // rocksdb::CollocatorIterator::CollocatorIterator(Iterator* base_iterator) {}
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100175
Marc Kupietz4b799e92018-01-02 11:04:56 +0100176 bool rocksdb::CollocatorIterator::Valid() const {
Marc Kupietz18375e12017-12-24 10:11:18 +0100177 return base_iterator_->Valid() && key().starts_with(std::string(prefixc,3));
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100178 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100179
Marc Kupietz4b799e92018-01-02 11:04:56 +0100180 bool rocksdb::CollocatorIterator::isValid() {
181 return base_iterator_->Valid() && key().starts_with(std::string(prefixc,3));
182 }
Marc Kupietz18375e12017-12-24 10:11:18 +0100183
Marc Kupietz4b799e92018-01-02 11:04:56 +0100184 uint64_t rocksdb::CollocatorIterator::intKey() {
185 return DecodeFixed64(base_iterator_->key().data());
186 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100187
Marc Kupietz4b799e92018-01-02 11:04:56 +0100188 uint64_t rocksdb::CollocatorIterator::intValue() {
189 return DecodeFixed64(base_iterator_->value().data());
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100190 }
191
Marc Kupietz37359b12018-01-09 21:11:37 +0100192 class VocabEntry {
193 public:
194 string word;
195 uint64_t freq;
196 };
197
Marc Kupietz6aec7682018-01-10 09:47:48 +0100198 class CollocatorDB {
Marc Kupietz4b799e92018-01-02 11:04:56 +0100199 private:
200 WriteOptions merge_option_; // for merge
201 char _one[sizeof(uint64_t)];
202 Slice _one_slice;
Marc Kupietz37359b12018-01-09 21:11:37 +0100203 vector<VocabEntry> _vocab;
204 uint64_t total;
205
Marc Kupietz4b799e92018-01-02 11:04:56 +0100206 protected:
207 std::shared_ptr<DB> db_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100208
Marc Kupietz4b799e92018-01-02 11:04:56 +0100209 WriteOptions put_option_;
210 ReadOptions get_option_;
211 WriteOptions delete_option_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100212
Marc Kupietz4b799e92018-01-02 11:04:56 +0100213 uint64_t default_;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100214
Marc Kupietz4b799e92018-01-02 11:04:56 +0100215 std::shared_ptr<DB> OpenDb(const char *dbname);
Marc Kupietz6bb27762018-01-09 17:53:01 +0100216 std::shared_ptr<DB> OpenDbForRead(const char *dbname);
Marc Kupietz37359b12018-01-09 21:11:37 +0100217 void read_vocab(string fname);
218
Marc Kupietz4b799e92018-01-02 11:04:56 +0100219 public:
Marc Kupietz6aec7682018-01-10 09:47:48 +0100220 CollocatorDB(const char *db_name, bool read_only);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100221
Marc Kupietz6aec7682018-01-10 09:47:48 +0100222 // public interface of CollocatorDB.
Marc Kupietz4b799e92018-01-02 11:04:56 +0100223 // All four functions return false
224 // if the underlying level db operation failed.
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100225
Marc Kupietz4b799e92018-01-02 11:04:56 +0100226 // mapped to a levedb Put
227 bool set(const std::string& key, uint64_t value) {
228 // just treat the internal rep of int64 as the string
229 char buf[sizeof(value)];
230 EncodeFixed64(buf, value);
231 Slice slice(buf, sizeof(value));
232 auto s = db_->Put(put_option_, key, slice);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100233
Marc Kupietz4b799e92018-01-02 11:04:56 +0100234 if (s.ok()) {
235 return true;
236 } else {
237 std::cerr << s.ToString() << std::endl;
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100238 return false;
239 }
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100240 }
Marc Kupietz4b799e92018-01-02 11:04:56 +0100241
242 DB *getDb() {
243 return db_.get();
244 }
245
246 // mapped to a rocksdb Delete
247 bool remove(const std::string& key) {
248 auto s = db_->Delete(delete_option_, key);
249
250 if (s.ok()) {
251 return true;
252 } else {
253 std::cerr << s.ToString() << std::endl;
254 return false;
255 }
256 }
257
258 // mapped to a rocksdb Get
259 bool get(const std::string& key, uint64_t* value) {
260 std::string str;
261 auto s = db_->Get(get_option_, key, &str);
262
263 if (s.IsNotFound()) {
264 // return default value if not found;
265 *value = default_;
266 return true;
267 } else if (s.ok()) {
268 // deserialization
269 if (str.size() != sizeof(uint64_t)) {
270 std::cerr << "value corruption\n";
271 return false;
272 }
273 *value = DecodeFixed64(&str[0]);
274 return true;
275 } else {
276 std::cerr << s.ToString() << std::endl;
277 return false;
278 }
279 }
280
281
282 uint64_t get(const uint32_t w1, const uint32_t w2, const int8_t dist) {
283 char encoded_key[sizeof(uint64_t)];
284 EncodeFixed64(encoded_key, encodeCollocation(w1,w2,dist));
285 uint64_t value = default_;
286 get(std::string(encoded_key, 8), &value);
287 return value;
288 }
289
290 virtual void inc(const std::string& key) {
291 db_->Merge(merge_option_, key, _one_slice);
292 }
293
294 void inc(const uint64_t key) {
295 char encoded_key[sizeof(uint64_t)];
296 EncodeFixed64(encoded_key, key);
297 db_->Merge(merge_option_, std::string(encoded_key, 8), _one_slice);
298 }
299
300 virtual void inc(const uint32_t w1, const uint32_t w2, const uint8_t dist);
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100301 void dump(uint32_t w1, uint32_t w2, int8_t dist);
Marc Kupietz37359b12018-01-09 21:11:37 +0100302 vector<Collocator> get_collocators(uint32_t w1);
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100303 string collocators2json(vector<Collocator> collocators);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100304
Marc Kupietz4b799e92018-01-02 11:04:56 +0100305 // mapped to a rocksdb Merge operation
306 virtual bool add(const std::string& key, uint64_t value) {
307 char encoded[sizeof(uint64_t)];
308 EncodeFixed64(encoded, value);
309 Slice slice(encoded, sizeof(uint64_t));
310 auto s = db_->Merge(merge_option_, key, slice);
311
312 if (s.ok()) {
313 return true;
314 } else {
315 std::cerr << s.ToString() << std::endl;
316 return false;
317 }
318 }
319
320 CollocatorIterator* SeekIterator(uint64_t w1, uint64_t w2, int8_t dist);
321 };
322
Marc Kupietz6aec7682018-01-10 09:47:48 +0100323 rocksdb::CollocatorDB::CollocatorDB(const char *db_name, bool read_only = false) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100324 // merge_option_.sync = true;
Marc Kupietz6bb27762018-01-09 17:53:01 +0100325 if(read_only)
326 db_ = OpenDbForRead(db_name);
327 else
328 db_ = OpenDb(db_name);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100329 assert(db_);
330 uint64_t one = 1;
331 EncodeFixed64(_one, one);
332 _one_slice = Slice(_one, sizeof(uint64_t));
333 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100334
Marc Kupietz6aec7682018-01-10 09:47:48 +0100335 void rocksdb::CollocatorDB::inc(const uint32_t w1, const uint32_t w2, const uint8_t dist) {
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100336 inc(encodeCollocation(w1, w2, dist));
337 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100338
Marc Kupietz6aec7682018-01-10 09:47:48 +0100339 void rocksdb::CollocatorDB::read_vocab(string fname) {
Marc Kupietz37359b12018-01-09 21:11:37 +0100340 char strbuf[2048];
341 uint64_t freq;
342 FILE *fin = fopen(fname.c_str(), "rb");
343 if (fin == NULL) {
344 cout << "Vocabulary file " << fname <<" not found\n";
345 exit(1);
346 }
347 uint64_t i = 0;
348 while(!feof(fin)) {
349 fscanf(fin, "%s %" PRIu64, strbuf, &freq);
350 _vocab.push_back({strbuf, freq});
351 total += freq;
352 i++;
353 }
354 fclose(fin);
355 }
356
Marc Kupietz6aec7682018-01-10 09:47:48 +0100357 std::shared_ptr<DB> rocksdb::CollocatorDB::OpenDbForRead(const char *name) {
Marc Kupietz6bb27762018-01-09 17:53:01 +0100358 DB* db;
359 Options options;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100360 options.env->SetBackgroundThreads(4);
361 options.create_if_missing = true;
362 options.merge_operator = std::make_shared<CountMergeOperator>();
363 options.max_successive_merges = 0;
364 // options.prefix_extractor.reset(NewFixedPrefixTransform(8));
365 options.IncreaseParallelism();
366 options.OptimizeLevelStyleCompaction();
367 options.prefix_extractor.reset(NewFixedPrefixTransform(3));
Marc Kupietz37359b12018-01-09 21:11:37 +0100368 ostringstream dbname, vocabname;
Marc Kupietz6bb27762018-01-09 17:53:01 +0100369 dbname << name << ".rocksdb";
370 auto s = DB::OpenForReadOnly(options, dbname.str(), &db);
371 if (!s.ok()) {
372 std::cerr << s.ToString() << std::endl;
373 assert(false);
374 }
Marc Kupietz37359b12018-01-09 21:11:37 +0100375 vocabname << name << ".vocab";
376 read_vocab(vocabname.str());
Marc Kupietz6bb27762018-01-09 17:53:01 +0100377 return std::shared_ptr<DB>(db);
378 }
379
Marc Kupietz6aec7682018-01-10 09:47:48 +0100380 std::shared_ptr<DB> rocksdb::CollocatorDB::OpenDb(const char *dbname) {
Marc Kupietz4b799e92018-01-02 11:04:56 +0100381 DB* db;
382 Options options;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100383
384
385 options.env->SetBackgroundThreads(4);
Marc Kupietz4b799e92018-01-02 11:04:56 +0100386 options.create_if_missing = true;
387 options.merge_operator = std::make_shared<CountMergeOperator>();
388 options.max_successive_merges = 0;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100389 // options.prefix_extractor.reset(NewFixedPrefixTransform(8));
390 options.IncreaseParallelism();
391 options.OptimizeLevelStyleCompaction();
392 // options.max_write_buffer_number = 48;
393 // options.max_background_jobs = 48;
394 // options.allow_concurrent_memtable_write=true;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100395 // options.memtable_factory.reset(rocksdb::NewHashLinkListRepFactory(200000));
396 // options.enable_write_thread_adaptive_yield = 1;
397 // options.allow_concurrent_memtable_write = 1;
398 // options.memtable_factory.reset(new rocksdb::SkipListFactory);
399 // options.write_buffer_size = 1 << 22;
400 // options.allow_mmap_reads = true;
401 // options.allow_mmap_writes = true;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100402 // options.max_background_compactions = 40;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100403 // BlockBasedTableOptions table_options;
404 // table_options.filter_policy.reset(NewBloomFilterPolicy(24, false));
405 // options.bloom_locality = 1;
406 // std::shared_ptr<Cache> cache = NewLRUCache(512 * 1024 * 1024);
407 // table_options.block_cache = cache;
408 // options.table_factory.reset(NewBlockBasedTableFactory(table_options));
Marc Kupietz4b799e92018-01-02 11:04:56 +0100409 Status s;
410 // DestroyDB(dbname, Options());
411 s = DB::Open(options, dbname, &db);
412 if (!s.ok()) {
413 std::cerr << s.ToString() << std::endl;
414 assert(false);
415 }
416 return std::shared_ptr<DB>(db);
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100417 }
418
Marc Kupietz6aec7682018-01-10 09:47:48 +0100419 CollocatorIterator* rocksdb::CollocatorDB::SeekIterator(uint64_t w1, uint64_t w2, int8_t dist) {
Marc Kupietz18375e12017-12-24 10:11:18 +0100420 ReadOptions options;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100421 options.prefix_same_as_start = true;
Marc Kupietz18375e12017-12-24 10:11:18 +0100422 char prefixc[sizeof(uint64_t)];
423 EncodeFixed64(prefixc, encodeCollocation(w1, w2, dist));
424 Iterator *it = db_->NewIterator(options);
425 CollocatorIterator *cit = new CollocatorIterator(it);
426 cit->Seek(std::string(prefixc,3));// it->Valid() && it->key().starts_with(std::string(prefixc,3)); it->Next()) {
427 cit->setPrefix(prefixc);
428 return cit;
429 }
430
Marc Kupietz6aec7682018-01-10 09:47:48 +0100431 void rocksdb::CollocatorDB::dump(uint32_t w1, uint32_t w2, int8_t dist) {
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100432 auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, w2, dist));
433 for (; it->isValid(); it->Next()) {
434 uint64_t value = it->intValue();
435 uint64_t key = it->intKey();
436 std::cout << "w1:" << W1(key) << ", w2:" << W2(key) << ", dist:" << (int32_t) DIST(key) << " - count:" << value << std::endl;
437 }
438 std::cout << "ready dumping\n";
439 }
440
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100441 double calculateLLR(uint64_t f_X_, uint64_t uintN, uint64_t f_X_Y_, uint64_t f_Y_) {
442 double f_e_, f_o_;
443 double A=0.0, B=0.0, C=0.0, D=0.0, N=0.0;
444 double LLR=0.0, statVal=0.0, minusDiffCoeff=0.0;
445 double BlogB=0.0, ClogC=0.0;
446
447 N = (double)uintN;
448 A = (double)f_X_Y_;
449 B = (double)f_X_ -A;
450 C = (double)f_Y_ -A;
451 D = (double)N -A-B-C;;
452
453 if (B > 0.) BlogB = B*log(B);
454 if (C > 0.) ClogC = C*log(C);
455
456 if ((A>0.) && (D>0.) && (N>0.)) {
457 f_e_ = (double)f_X_ /(double)N;
458 f_o_ = (double)f_X_Y_/(double)f_Y_;
459
460 minusDiffCoeff =
461 ( f_X_==0 ? (double)((-1)*f_X_Y_) :
462 ( f_X_Y_==0 ? (double)((+1)*f_X_) :
463 (f_e_-f_o_)/(f_e_+f_o_)
464 )
465 );
466
467 /* log likelihood ratio */
468 LLR = 2*( A*log(A)
469 +BlogB
470 +ClogC
471 +D*log(D)
472 -(A+B)*log(A+B)
473 -(A+C)*log(A+C)
474 -(B+D)*log(B+D)
475 -(C+D)*log(C+D)
476 +N*log(N)
477 );
478 }
479 return(minusDiffCoeff > 0 ? 0 : (statVal=LLR));
480 }
481
482
483 bool sortByNpmi(const Collocator &lhs, const Collocator &rhs) { return lhs.npmi > rhs.npmi; }
484 bool sortByLfmd(const Collocator &lhs, const Collocator &rhs) { return lhs.lfmd > rhs.lfmd; }
485
Marc Kupietz6aec7682018-01-10 09:47:48 +0100486 std::vector<Collocator> rocksdb::CollocatorDB::get_collocators(uint32_t w1) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100487 std::vector<Collocator> collocators;
488 uint64_t w2, last_w2 = 0xffffffffffffffff;
489 uint64_t sum = 0, total_w1 = 0;
490 for ( auto it = std::unique_ptr<CollocatorIterator>(SeekIterator(w1, 0, 0)); it->isValid(); it->Next()) {
491 uint64_t value = it->intValue(),
492 key = it->intKey();
493 w2 = W2(key);
494 total_w1 += value;
495 if(last_w2 == 0xffffffffffffffff) last_w2 = w2;
496 if (w2 != last_w2) {
497 double pmi = log2( total * ((double) sum) /
Marc Kupietz37359b12018-01-09 21:11:37 +0100498 (AVG_WINDOW_SIZE * ((double)_vocab[w1].freq) * ((double)_vocab[last_w2].freq) ));
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100499 // 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 +0100500 // 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)));
501 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 +0100502 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 +0100503 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 +0100504 last_w2 = w2;
505 sum = value;
506 } else {
507 sum += value;
508 }
509 }
510
511 sort(collocators.begin(), collocators.end(), sortByLfmd);
512
513 int i=0;
514 for (Collocator c : collocators) {
515 if(i++>10) break;
Marc Kupietz37359b12018-01-09 21:11:37 +0100516 std::cout << "w1:" << _vocab[w1].word << ", w2:" << _vocab[c.w2].word
517 << "\t f(w1):" << _vocab[w1].freq
518 << "\t f(w2):" << _vocab[c.w2].freq
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100519 << "\t f(w1, x):" << total_w1
520 << "\t f(w1, w2):" << c.sum
521 << "\t pmi:" << c.pmi
522 << "\t npmi:" << c.npmi
523 << "\t llr:" << c.llr
524 << "\t md:" << c.md
525 << "\t lfmd:" << c.lfmd
526 << "\t fpmi:" << c.fpmi
527 << "\t total:" << total
528 << std::endl;
529 }
530 return collocators;
531 }
532
Marc Kupietz4b799e92018-01-02 11:04:56 +0100533 rocksdb::Slice rocksdb::CollocatorIterator::key() const { return base_iterator_->key(); }
534 rocksdb::Slice rocksdb::CollocatorIterator::value() const { return base_iterator_->value(); }
535 rocksdb::Status rocksdb::CollocatorIterator::status() const { return base_iterator_->status(); }
536
Marc Kupietz28cc53e2017-12-23 17:24:55 +0100537};
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100538
Marc Kupietz6aec7682018-01-10 09:47:48 +0100539string rocksdb::CollocatorDB::collocators2json(vector<Collocator> collocators) {
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100540 ostringstream s;
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100541 int i = 0;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100542 s << "[";
543 bool first = true;
544 for (Collocator c : collocators) {
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100545 if (i++ > 200)
546 break;
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100547 if(!first)
548 s << ",\n";
549 else
550 first = false;
551 s << "{"
552 "\"word\":\"" << string(_vocab[c.w2].word) << "\"," <<
553 "\"rank\":" << c.w2 << "," <<
554 "\"npmi\":" << c.npmi << "," <<
555 "\"llr\":" << c.llr << "," <<
556 "\"lfmd\":" << c.lfmd << "," <<
Marc Kupietz0dd86ef2018-01-11 22:23:17 +0100557 "\"fpmi\":" << c.fpmi <<
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100558 "}";
559 }
560 s << "]\n";
561 return s.str();
562}
563
Marc Kupietz6aec7682018-01-10 09:47:48 +0100564typedef rocksdb::CollocatorDB COLLOCATORS;
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100565
566extern "C" {
Marc Kupietz6aec7682018-01-10 09:47:48 +0100567 COLLOCATORS *open_collocatordb_for_write(char *dbname) {
568 return new rocksdb::CollocatorDB(dbname, false);
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100569 }
570
Marc Kupietz6aec7682018-01-10 09:47:48 +0100571 COLLOCATORS *open_collocatordb(char *dbname) {
572 return new rocksdb::CollocatorDB(dbname, true);
Marc Kupietz6bb27762018-01-09 17:53:01 +0100573 }
574
Marc Kupietz6aec7682018-01-10 09:47:48 +0100575 void inc_collocator(COLLOCATORS *db, uint32_t w1, uint32_t w2, int8_t dist) {
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100576 db->inc(w1, w2, dist);
577 }
578
579 void dump_collocators(COLLOCATORS *db, uint32_t w1, uint32_t w2, int8_t dist) {
580 db->dump(w1, w2, dist);
581 }
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100582
Marc Kupietz37359b12018-01-09 21:11:37 +0100583 void get_collocators(COLLOCATORS *db, uint32_t w1) {
584 db->get_collocators(w1);
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100585 }
586
Marc Kupietz37359b12018-01-09 21:11:37 +0100587 const char *get_collocators_as_json(COLLOCATORS *db, uint32_t w1) {
588 return strdup(db->collocators2json(db->get_collocators(w1)).c_str());
Marc Kupietzc8ddf452018-01-07 21:33:12 +0100589 }
Marc Kupietz06c9a9f2018-01-02 16:56:43 +0100590}