disk_hashtable.h 19.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Spell-QTL  Software suite for the QTL analysis of modern datasets.
 * Copyright (C) 2016,2017  Damien Leroux <damien.leroux@inra.fr>, Sylvain Jasson <sylvain.jasson@inra.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

18
19
20
21
22
23
24
25
26
27
28
#ifndef _SPELL_DISK_HASHTABLE_H_
#define _SPELL_DISK_HASHTABLE_H_

#include <iostream>
#include "basic_file_checks.h"
#include "cache/file.h"
#include "error.h"
#include "settings.h"

#include <sys/types.h>
#include <dirent.h>
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#include <shared_mutex>


/*
 * http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#shared_mutex_imp
 */

#if 0

class shared_mutex
{
    std::mutex mut_;
    std::condition_variable gate1_;
    std::condition_variable gate2_;
    unsigned state_;

    static const unsigned write_entered_ = 1U << (sizeof(unsigned)*CHAR_BIT - 1);
    static const unsigned n_readers_ = ~write_entered_;

public:

    shared_mutex() : state_(0) {}

// Exclusive ownership

    inline void lock();
    inline bool try_lock();
//     bool timed_lock(nanoseconds rel_time);
    inline void unlock();

// Shared ownership

    inline void lock_shared();
    inline bool try_lock_shared();
//     bool timed_lock_shared(nanoseconds rel_time);
    inline void unlock_shared();
};

// Exclusive ownership

void
shared_mutex::lock()
{
//     std::this_thread::disable_interruption _;
    std::unique_lock<std::mutex> lk(mut_);
    while (state_ & write_entered_)
        gate1_.wait(lk);
    state_ |= write_entered_;
    while (state_ & n_readers_)
        gate2_.wait(lk);
}

bool
shared_mutex::try_lock()
{
    std::unique_lock<std::mutex> lk(mut_, std::try_to_lock);
    if (lk.owns_lock() && state_ == 0)
    {
        state_ = write_entered_;
        return true;
    }
    return false;
}

void
shared_mutex::unlock()
{
//     {
    std::unique_lock<std::mutex> _(mut_);
    state_ = 0;
//     }
    gate1_.notify_all();
}

// Shared ownership

void
shared_mutex::lock_shared()
{
//     std::this_thread::disable_interruption _;
    std::unique_lock<std::mutex> lk(mut_);
    while ((state_ & write_entered_) || (state_ & n_readers_) == n_readers_)
        gate1_.wait(lk);
    unsigned num_readers = (state_ & n_readers_) + 1;
    state_ &= ~n_readers_;
    state_ |= num_readers;
}

bool
shared_mutex::try_lock_shared()
{
    std::unique_lock<std::mutex> lk(mut_, std::try_to_lock);
    unsigned num_readers = state_ & n_readers_;
    if (lk.owns_lock() && !(state_ & write_entered_) && num_readers != n_readers_)
    {
        ++num_readers;
        state_ &= ~n_readers_;
        state_ |= num_readers;
        return true;
    }
    return false;
}

void
shared_mutex::unlock_shared()
{
    std::unique_lock<std::mutex> _(mut_);
    unsigned num_readers = (state_ & n_readers_) - 1;
    state_ &= ~n_readers_;
    state_ |= num_readers;
    if (state_ & write_entered_)
    {
        if (num_readers == 0)
            gate2_.notify_one();
    }
    else
    {
        if (num_readers == n_readers_ - 1)
            gate1_.notify_one();
    }
}



struct reader_lock {
    reader_lock(shared_mutex& _) : m(&_) { m->lock_shared(); }
    ~reader_lock() { m->unlock_shared(); }
private:
    shared_mutex* m;
};


struct writer_lock {
    writer_lock(shared_mutex& _) : m(&_) { m->lock(); }
    ~writer_lock() { m->unlock(); }
private:
    shared_mutex* m;
};

#endif


typedef std::shared_timed_mutex shared_mutex;
typedef std::shared_lock<shared_mutex> reader_lock;
typedef std::unique_lock<shared_mutex> writer_lock;










184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

template <typename Type> struct dht_argmatch;
template <typename Type> struct dht_argput;

template <typename IntegralType>
bool
match_integral(std::istream& is, IntegralType i)
{
    IntegralType tmp;
    is.read((char*) &tmp, sizeof(IntegralType));
    return tmp == i;
}


inline bool arg_match(std::istream& is, Eigen::Index i) { return match_integral(is, i); }
inline bool arg_match(std::istream& is, int i) { return match_integral(is, i); }
inline bool arg_match(std::istream& is, size_t i) { return match_integral(is, i); }
inline bool arg_match(std::istream& is, double i) { return match_integral(is, i); }

inline bool arg_match(std::istream& is, const label_type& l) { return match_integral(is, l.compact()); }

inline bool
    arg_match(std::istream& is, const std::string& s)
    {
        if (!arg_match(is, s.size())) {
            return false;
        }
        std::vector<char> buffer(s.size());
        is.read(buffer.data(), s.size());
        return std::string(buffer.begin(), buffer.end()) == s;
    }

template <typename X>
inline bool
    arg_match(std::istream& is, const std::vector<X>& vec)
    {
        if (!arg_match(is, vec.size())) {
            return false;
        }
        for (X i: vec) {
            if (!arg_match(is, i)) {
                return false;
            }
        }
        return true;
    }

template <typename Scalar, int... Opts>
bool
    arg_match(std::istream& is, const Eigen::Matrix<Scalar, Opts...>& mat)
    {
        if (!(arg_match(is, mat.rows()) && arg_match(is, mat.cols()))) {
            return false;
        }
        for (int i = 0; i < mat.rows(); ++i) {
            for (int j = 0; j < mat.cols(); ++j) {
                if (!arg_match(is, mat(i, j))) {
                    return false;
                }
            }
        }
        return true;
    }

248
249
250
251
252
253
254
template <typename C, typename R, typename M>
bool
    arg_match(std::istream& is, const labelled_matrix<C, R, M>& lm)
    {
        return arg_match(is, lm.column_labels) && arg_match(is, lm.row_labels) && arg_match(is, lm.data);
    }

255
256
257
258
259
260
261
262
inline bool
    arg_match(std::istream& is, const geno_matrix* mat)
    {
        return arg_match(is, mat->name)
            && arg_match(is, mat->labels)
            && arg_match(is, mat->diag);
    }

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
inline bool
    arg_match(std::istream& is, const std::vector<double>& vec)
    {
        if (!arg_match(is, vec.size())) {
            return false;
        }
        for (double d: vec) {
            if (!arg_match(is, d)) {
                return false;
            }
        }
        return true;
    }

inline bool
    arg_match(std::istream& is, const qtl_chromosome* qc)
    {
        if (qc == NULL) {
            return arg_match(is, (size_t)0);
        }
        return arg_match(is, qc->chr->name) && arg_match(is, qc->qtl);
    }

286
287
288
289
inline bool
    arg_match(std::istream& is, const context_key& ck)
    {
        static std::string null("null");
290
        return ((ck->pop ? arg_match(is, ck->pop->name) && arg_match(is, ck->pop->qtl_generation_name) && arg_match(is, ck->pop->indices)
291
                         : arg_match(is, null))
292
293
294
295
296
297
298
299
            && (ck->gen ? arg_match(is, ck->gen) : arg_match(is, null))
            && (ck->chr ? arg_match(is, ck->chr->name) : arg_match(is, null))
            && arg_match(is, ck->loci));
    }

inline bool
    arg_match(std::istream& is, const locus_key& lk)
    {
300
301
302
303
304
305
306
307
308
309
310
        static std::string end("LKend");
        if (lk) {
            auto vec = lk->to_vec();
            /*MSG_DEBUG("arg_match lk->to_vec " << vec);*/
            if (!arg_match(is, vec)) {
                return false;
            }
        }
        return arg_match(is, end);
#if 0
        static std::string end("LKend");
311
312
313
314
315
316
317
        locus_key tmp = lk;
        while (tmp) {
            if (!arg_match(is, tmp->locus)) {
                return false;
            }
            tmp = tmp->parent;
        }
318
        return arg_match(is, end);
319
        return true;
320
#endif
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    }

template <typename... Args> struct arg_matcher;
template <typename Arg> struct arg_matcher<Arg> {
    bool operator () (std::istream& is, Arg&& arg) const { return arg_match(is, arg); }
};
template <typename Arg, typename... Args> struct arg_matcher<Arg, Args...> {
    bool operator () (std::istream& is, Arg&& arg, Args... other) const
    {
        return arg_match(is, arg) && arg_matcher<Args...>()(is, std::forward<Args>(other)...);
    }
};



template <typename IntegralType>
    inline void write_integral(std::ostream& os, IntegralType i) { os.write((char*) &i, sizeof(IntegralType)); }

inline void arg_write(std::ostream& os, Eigen::Index i) { write_integral(os, i); }
inline void arg_write(std::ostream& os, int i) { write_integral(os, i); }
inline void arg_write(std::ostream& os, size_t i) { write_integral(os, i); }
inline void arg_write(std::ostream& os, double i) { write_integral(os, i); }

inline void arg_write(std::ostream& os, const label_type& l) { write_integral(os, l.compact()); }

inline void arg_write(std::ostream& os, const std::string& s) { arg_write(os, s.size()); os.write(s.data(), s.size()); }

template <typename X>
    inline void arg_write(std::ostream& os, const std::vector<X>& vec)
    {
        arg_write(os, vec.size());
        for (auto x: vec) { arg_write(os, x); }
    }

template <typename Scalar, int... Opts>
    inline void
    arg_write(std::ostream& os, const Eigen::Matrix<Scalar, Opts...>& mat)
    {
        arg_write(os, mat.rows());
        arg_write(os, mat.cols());
        for (int i = 0; i < mat.rows(); ++i) {
            for (int j = 0; j < mat.cols(); ++j) {
                arg_write(os, mat(i, j));
            }
        }
    }

368
369
370
371
372
373
374
375
376
template <typename R, typename C, typename M>
    inline void
    arg_write(std::ostream& os, const labelled_matrix<R, C, M>& lm)
    {
        arg_write(os, lm.column_labels);
        arg_write(os, lm.row_labels);
        arg_write(os, lm.data);
    }

377
378
379
380
381
382
383
384
inline void
    arg_write(std::ostream& os, const geno_matrix* mat)
    {
        arg_write(os, mat->name);
        arg_write(os, mat->labels);
        arg_write(os, mat->diag);
    }

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
inline void
    arg_write(std::ostream& os, const std::vector<double>& vec)
    {
        arg_write(os, vec.size());
        for (double d: vec) {
            arg_write(os, d);
        }
    }

inline void
    arg_write(std::ostream& os, const qtl_chromosome* qc)
    {
        if (qc == NULL) {
            arg_write(os, (size_t) 0);
        } else {
            arg_write(os, qc->chr->name);
            arg_write(os, qc->qtl);
        }
    }

405
406
407
408
inline void
    arg_write(std::ostream& os, const context_key& ck)
    {
        static std::string null("null");
409
410
411
        if (ck->pop) {
            arg_write(os, ck->pop->name);
            arg_write(os, ck->pop->qtl_generation_name);
412
            arg_write(os, ck->pop->indices);
413
414
415
        } else {
            arg_write(os, null);
        }
416
417
418
419
420
421
422
423
424
425
426
427
        if (ck->gen) {
            arg_write(os, ck->gen);
        } else {
            arg_write(os, null);
        }
        arg_write(os, ck->chr ? ck->chr->name : null);
        arg_write(os, ck->loci);
    }

inline void
    arg_write(std::ostream& os, const locus_key& lk)
    {
428
429
430
431
432
433
434
435
436
        static std::string end("LKend");
        if (lk) {
            auto vec = lk->to_vec();
            /*MSG_DEBUG("arg_write lk->to_vec " << vec);*/
            arg_write(os, vec);
        }
        arg_write(os, end);
#if 0
        static std::string end("LKend");
437
438
439
440
441
        locus_key tmp = lk;
        while (tmp) {
            arg_write(os, tmp->locus);
            tmp = tmp->parent;
        }
442
443
        arg_write(os, end);
#endif
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
    }


template <typename... Args> struct arg_writer;
template <typename Arg> struct arg_writer<Arg> {
    void operator () (std::ostream& os, Arg&& arg) const { arg_write(os, arg); }
};
template <typename Arg, typename... Args> struct arg_writer<Arg, Args...> {
    void operator () (std::ostream& os, Arg&& arg, Args... other) const
    {
        arg_write(os, arg);
        arg_writer<Args...>()(os, std::forward<Args>(other)...);
    }
};


namespace std {
template <typename V, typename A>
    struct hash<std::vector<V, A>> {
        size_t operator () (const std::vector<V, A>& vec) const
        {
            size_t accum = (1 + vec.size());
            for (const V& x: vec) {
                accum = (accum * 39916801) ^ hash<V>()(x);
            }
            return accum;
        }
    };

    template <typename X>
        struct hash<const X&> { size_t operator () (const X& x) const { return hash<X>()(x); } };
}


template <typename... Args> struct arg_hasher;
template <typename Arg> struct arg_hasher<Arg> {
    /*size_t operator () (Arg&& arg) const { return 0xdeadbeef ^ (39916801 * std::hash<Arg>()(arg)); }*/
    size_t operator () (Arg&& arg) const { return std::hash<Arg>()(std::forward<Arg>(arg)); }
};
template <typename Arg, typename... Args> struct arg_hasher<Arg, Args...> {
    size_t operator () (Arg&& arg, Args... other) const
    {
        return std::hash<Arg>()(std::forward<Arg>(arg)) ^ (arg_hasher<Args...>()(std::forward<Args>(other)...) * 39916801);
    }
};



template <typename Func> struct disk_hashtable;


template <typename ValueType, typename... AllArgs>
struct disk_hashtable<ValueType(AllArgs...)> {
    typedef ValueType value_type;
    typedef disk_hashtable<ValueType(AllArgs...)> this_type;

    disk_hashtable(const std::string& base_path)
501
502
        : m_base_path()
        , m_mutex()
503
        /*: m_base_path(SPELL_STRING(active_settings->work_directory << '/' << base_name))*/
504
    {
505
506
        writer_lock lock(m_mutex);
        m_base_path = base_path;
507
        ensure_directories_exist(m_base_path);
508
509
510
511
512
513
514
    }

    std::string
        hash(AllArgs&&... args) const
        {
            static char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            size_t h = arg_hasher<AllArgs...>()(std::forward<AllArgs>(args)...);
515
516
            std::string ret(11, '/');
            static size_t ret_ofs[8] = {0, 1, 3, 4, 6, 7, 9, 10};
517
            for (int i = 7; i >= 0; --i) {
518
                ret[ret_ofs[i]] = hex[h & 0xF];
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
                h >>= 4;
            }
            return ret;
        }

    /* 
     * List all existing entries
     */
    std::vector<std::string>
        get_entries(const std::string& path) const
        {
            std::vector<std::string> ret;
            DIR *dir;
            struct dirent *ent;
            if ((dir = opendir (path.c_str())) != NULL) {
                /* print all the files and directories within directory */
                while ((ent = readdir (dir)) != NULL) {
                    /*printf ("%s\n", ent->d_name);*/
537
                    /*ret.push_back(SPELL_STRING(path << '/' << ent->d_name));*/
538
                    if (check_file(SPELL_STRING(path << '/' << ent->d_name), false, true, false)) {
539
540
541
542
543
544
545
546
547
                        ret.push_back(ent->d_name);
                    }
                }
                closedir (dir);
            }
            return ret;
        }

    bool
548
        match_key(file& entry, AllArgs&&... args) const
549
550
551
552
553
        {
            return arg_matcher<AllArgs...>()(entry, std::forward<AllArgs>(args)...);
        }

    bool
554
        find(std::function<void(file&)> process_result, AllArgs&&... args) const
555
556
        {
            std::string hashed_key = hash(std::forward<AllArgs>(args)...);
557
            std::string path = SPELL_STRING(m_base_path << '/' << hashed_key);
558
559
560
561
562
563
            std::vector<std::string> entries = get_entries(path);
            return find(path, entries, process_result, std::forward<AllArgs>(args)...);
        }

    bool
        find(const std::string& path, const std::vector<std::string>& entries,
564
                std::function<void(file&)> process_result, AllArgs&&... args) const
565
566
        {
            for (const auto& ent: entries) {
567
                file entf(SPELL_STRING(path << '/' << ent), std::fstream::in | std::fstream::binary);
568
569
                if (match_key(entf, std::forward<AllArgs>(args)...)) {
                    process_result(entf);
570
                    entf.close();
571
572
                    return true;
                }
573
                entf.close();
574
575
576
577
578
579
580
            }
            return false;
        }

    std::pair<bool, value_type>
        get(AllArgs&&... args) const
        {
581
            static std::string end("end");
582
            std::pair<bool, value_type> ret;
583
584
585
586
587
588
            try {
                ret.first = find([&] (file& ifs) { cache_input ci(ifs); ci & ret.second; if (!arg_match(ifs, end)) { throw file::error(""); } },
                                 std::forward<AllArgs>(args)...);
            } catch(file::error& fuuuuu) {
                ret.first = false;
            }
589
590
591
592
593
594
595
            return ret;
        }

    void
        put(value_type& value, AllArgs&&... args)
        {
            std::string hashed_key = hash(std::forward<AllArgs>(args)...);
596
            std::string path = SPELL_STRING(m_base_path << '/' << hashed_key);
597
            ensure_directories_exist(path);
598
599
600
601
602
603
604
605
            std::vector<std::string> entries = get_entries(path);
            put(path, entries, value, std::forward<AllArgs>(args)...);
        }

    void
        put(const std::string& path, const std::vector<std::string>& entries,
                value_type& value, AllArgs&&... args)
        {
606
            static std::string end("end");
607
            writer_lock lock(m_mutex);
608
            bool exists = find(path, entries, [&] (file& ofs) { cache_output co(ofs); co & value; arg_write(ofs, end); },
609
610
611
                               std::forward<AllArgs>(args)...);
            /*MSG_DEBUG("entries " << entries);*/
            if (!exists) {
612
                std::string new_entry = SPELL_STRING(path << '/' << entries.size());
613
                /*MSG_DEBUG("new_entry " << new_entry);*/
614
615
616
617
                file ofs(new_entry, std::fstream::out | std::fstream::binary);
                /*if (ofs.rdstate() & std::ios_base::failbit) {*/
                    /*MSG_DEBUG("open failed " << new_entry);*/
                /*}*/
618
619
620
                arg_writer<AllArgs...>()(ofs, std::forward<AllArgs>(args)...);
                cache_output co(ofs);
                co & value;
621
                arg_write(ofs, end);
622
                ofs.close();
623
624
625
626
627
628
629
            }
        }

    value_type
        get_or_compute(std::function<value_type(AllArgs...)> func, AllArgs&&... args)
        {
            std::string hashed_key = hash(std::forward<AllArgs>(args)...);
630
            std::string path;
631
            std::pair<bool, value_type> ret;
632
633
634
            std::vector<std::string> entries;
            {
                reader_lock lock(m_mutex);
635
                path = SPELL_STRING(m_base_path << '/' << hashed_key);
636
637
638
639
640
641
                ensure_directories_exist(path);
                entries = get_entries(path);
                ret.first = find([&] (file& ifs) { cache_input ci(ifs); ci & ret.second; },
//                                 args...);
                                std::forward<AllArgs>(args)...);
            }
642
643
644
            if (!ret.first) {
                ret.second = func(std::forward<AllArgs>(args)...);
                put(path, entries, ret.second, std::forward<AllArgs>(args)...);
645
646
//                ret.second = func(args...);
//                put(path, entries, ret.second, args...);
647
648
649
650
651
652
            }
            return ret.second;
        }

private:
    std::string m_base_path;
653
    mutable shared_mutex m_mutex;
654
655
656
657
658
659
};



#endif