generalized_product.h 43.5 KB
Newer Older
1
2
3
4
5
6
#ifndef _SPELL_BAYES_GENERALIZED_PRODUCT_H_
#define _SPELL_BAYES_GENERALIZED_PRODUCT_H_

#include "pedigree.h"


7
#include <cstring>
8
9
10
11
#include <unordered_map>
#include <boost/dynamic_bitset.hpp>


12
13
14
15
16
/* La spec est dans le code. */



/* Gère un curseur incrémentable multi-dimensionnel et les différentes opérations nécessaires desuss. */
17
struct state_index_type {
18
    /* TODO make data an array in case we need more than 64 bits of indexing space. */
19
    typedef uint64_t block_type;
20
21
22
    static constexpr size_t n_blocks = 4;
    std::array<block_type, n_blocks> data;

23
24
25
26
27

    inline
    state_index_type&
        operator = (const state_index_type& other)
        {
28
29
30
            for (size_t i = 0; i < n_blocks; ++i) {
                data[i] = other.data[i];
            }
31
32
33
34
35
36
37
            return *this;
        }

    inline
    state_index_type&
        operator = (uint64_t value)
        {
38
39
40
41
            data[0] = value;
            for (size_t i = 1; i < n_blocks; ++i) {
                data[i] = 0;
            }
42
43
44
45
46
47
48
            return *this;
        }

    inline
    size_t
        hash() const
        {
49
50
51
52
53
            size_t ret = std::hash<block_type>()(data[0]);
            for (size_t i = 0; i < n_blocks; ++i) {
                ret = (ret * 0xd3adb3ef) ^ std::hash<block_type>()(data[i]);
            }
            return ret;
54
55
56
        }

    inline
57
    void reset() { *this = 0; }
58

59
60
61
62
    /* Aide à la compilation des données nécessaires à calculer un produit.
     * Donne le bitshift suivant en s'assurant qu'on ne franchit pas une barrière de 64 bits.
     * Si un indice devait être encodé à cheval sur deux mots, son extraction et son insertion seraient très coûteuses.
     */
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    inline
    static
        size_t
        next_shift(size_t current_shift, size_t next_bit_width)
        {
            size_t base_word_ofs = current_shift >> 6;
            size_t ofs_end = (current_shift + next_bit_width) >> 6;
            if (base_word_ofs != ofs_end) {
                /* crossing a 64-bit boundary */
                return ofs_end << 6;
            } else {
                return current_shift;
            }
        }

78
    /* Calcule le masque local (au mot concerné) pour un indice (bitshift, bitwidth) donné. */
79
80
81
82
83
84
85
86
87
    inline
    static
        block_type
        mask(size_t shift, size_t bit_width)
        {
            /* guaranteed to not cross a 64-bit boundary if shift is given by next_shift() */
            return ((1 << bit_width) - 1) << (shift & 0x3f);
        }

88
    /* Seuls domain_descr et table_descr ont le droit de manipuler les indices au-delà des opérations de base. */
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    friend struct domain_descr;
    friend struct table_descr;

    inline
    bool operator == (const state_index_type& other) const { return data == other.data; }
    inline
    bool operator != (const state_index_type& other) const { return data != other.data; }
    inline
    bool operator > (const state_index_type& other) const { return data > other.data; }
    inline
    bool operator < (const state_index_type& other) const { return data < other.data; }
    inline
    bool operator >= (const state_index_type& other) const { return data >= other.data; }
    inline
    bool operator <= (const state_index_type& other) const { return data <= other.data; }

    inline
106
    bool is_bad() const { return data[n_blocks - 1] == (uint64_t) -1; }
107
108
109
110
111

    static constexpr
        state_index_type
        bad()
        {
112
            return {{~0ULL, ~0ULL, ~0ULL, ~0ULL}};
113
114
115
116
117
118
119
        }

    friend
    inline
        std::ostream&
        operator << (std::ostream& os, const state_index_type& s)
        {
120
121
122
            for (int i = n_blocks - 1; i >= 0; ++i) {
                uint64_t mask = 1ULL << 63;
                while (mask && !(s.data[i] & mask)) { mask >>= 1; }
123
                while (mask) { os << ((s.data[i] & mask) == 0); mask >>= 1; }
124
            }
125
126
127
128
            return os;
        }

protected:
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    /* accède au bon indice pour un shift donné */
    inline
        block_type&
        select_data(size_t shift)
        {
            return data[shift >> 6];
        }

    inline
        const block_type&
        select_data(size_t shift) const
        {
            return data[shift >> 6];
        }

144
    /* Donne la valeur max shiftée d'un indice, pour comparaison avec extract_unshifted() */
145
146
147
148
149
150
151
152
    static
    inline
        block_type
        max(size_t shift, size_t domain_size)
        {
            return (domain_size - 1) << (shift & 0x3f);
        }

153
    /* extrait un indice */
154
155
156
157
158
    inline
    uint64_t
        extract(size_t shift, block_type mask) const
        {
            /* data offset is shift >> 6 */
159
            return (select_data(shift) & mask) >> (shift & 0x3f);
160
161
162
163
164
165
        }

    inline
    void
        assign(size_t shift, block_type mask, uint64_t value)
        {
166
167
            select_data(shift) &= ~mask;
            select_data(shift) |= value << (shift & 0x3f);
168
169
        }

170
    /* Incrémente un indice et retourne carry */
171
172
173
174
    inline
    bool
        incr(size_t shift, block_type mask, block_type max)
        {
175
176
            auto& D = select_data(shift);
            block_type sub = (D & mask);
177
            if (sub == max) {
178
                D &= ~mask;
179
180
                return true;
            } else {
181
                D += 1 << (shift & 0x3f);
182
183
184
185
                return false;
            }
        }

186
    /* met un indice à zéro */
187
188
189
190
    inline
    void
        zero(size_t shift, block_type mask)
        {
191
            select_data(shift) &= ~mask;
192
193
        }

194
    /* fusionne deux curseurs étant donné un masque (utilise les dimensions de *this pour mask et d'other pour !mask) */
195
196
197
198
199
200
    inline
    state_index_type
        merge(const state_index_type& other, const state_index_type& mask) const
        {
            /* iterate over block index */
            state_index_type ret;
201
202
203
            for (size_t i = 0; i < n_blocks; ++i) {
                ret.data[i] = data[i] | (other.data[i] & ~mask.data[i]);
            }
204
205
206
            return ret;
        }

207
    /* extrait un indice mais économise le shift. à utiliser pour comparer avec max (voir incr()). */
208
209
210
211
    inline
    block_type
        extract_unshifted(size_t shift, block_type mask) const
        {
212
            return select_data(shift) & mask;
213
214
        }

215
    /* calcule le résultat de *this & m. Permet de passer d'un curseur global à un curseur local à une table. */
216
217
218
219
220
    inline
    state_index_type
        mask(const state_index_type& m) const
        {
            state_index_type ret;
221
222
223
            for (size_t i = 0; i < n_blocks; ++i) {
                ret.data[i] = data[i] & m.data[i];
            }
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
            return ret;
        }
};



namespace std {
    template <>
        struct hash<bn_label_type> {
            size_t operator () (const bn_label_type& l) const { return std::hash<int>()(l.compact()); }
        };

    template <>
        struct hash<genotype_comb_type::key_list> {
            size_t
                operator () (const genotype_comb_type::key_list& kl) const
                {
                    size_t accum = 0xdeadbe3f;
                    for (const auto& k: kl) {
                        accum *= std::hash<int>()(k.parent);
                        accum = (accum << 13) | (accum >> 19);
                        accum *= std::hash<bn_label_type>()(k.state);
                        accum = (accum << 19) | (accum >> 13);
                    }
                    return accum;
                }
        };

    template <>
        struct hash<state_index_type> {
            size_t operator () (const state_index_type& s) const { return s.hash(); }
        };
}



260
/* Permet d'itérer joliment sur la séquence inverse (rbegin->rend) avec la syntaxe for (v: container) {} */
261
262
263
264
265
266
267
template <typename CONTAINER> struct const_reversed_impl {
    const CONTAINER& ref;
    typedef typename std::decay<CONTAINER>::type::const_reverse_iterator iterator;
    iterator begin() { return ref.rbegin(); }
    iterator end() { return ref.rend(); }
};

268
269
270
271
272
273
274
275
template <typename CONTAINER> struct reversed_impl {
    const CONTAINER& ref;
    typedef typename std::decay<CONTAINER>::type::reverse_iterator iterator;
    iterator begin() { return ref.rbegin(); }
    iterator end() { return ref.rend(); }
};

template <typename CONTAINER> reversed_impl<CONTAINER> reversed(CONTAINER&& x) { return {x}; }
276
template <typename CONTAINER> const_reversed_impl<CONTAINER> reversed(const CONTAINER& x) { return {x}; }
277
278


279
/* Descripteur du domaine d'une variable participant au produit */
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
struct domain_descr {
    int variable_name;
    size_t size;
    size_t bit_width;
    size_t shift;
    state_index_type::block_type max;
    state_index_type::block_type mask;
    std::unordered_map<bn_label_type, size_t> label_to_index;
    std::vector<bn_label_type> index_to_label;

    inline
    uint64_t
        extract(const state_index_type& s) const
        {
            return s.extract(shift, mask);
        }

    inline
    void
        init_indexer(size_t last_shift)
        {
            shift = state_index_type::next_shift(last_shift, bit_width);
            max = state_index_type::max(shift, size);
            mask = state_index_type::mask(shift, bit_width);
            /*MSG_DEBUG("last_shift=" << last_shift << " last_bit_width=" << last_bit_width << " shift=" << shift << " max=" << max << " mask=" << mask);*/
        }

    inline
    void
        assign(state_index_type& cursor, uint64_t value) const
        {
            cursor.assign(shift, mask, value);
        }

    inline
    void
        assign_mask(state_index_type& cursor) const
        {
            cursor.assign(shift, mask, (1 << bit_width) - 1);
        }

    inline
    bool
        incr(state_index_type& cursor) const
        {
            return cursor.incr(shift, mask, max);
        }

    inline
    void
        zero(state_index_type& cursor) const
        {
            cursor.zero(shift, mask);
        }

    inline
    uint64_t
        extract_unshifted(const state_index_type& cursor) const
        {
            return cursor.extract_unshifted(shift, mask);
        }
};


344
/* Descripteur d'une table participant au produit */
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
struct table_descr {
    const genotype_comb_type* data;
    std::vector<int> variable_names;
    std::vector<bool> variables_in_use;
    std::vector<bool> variables_left;
    std::vector<size_t> variable_indices;
    std::unordered_map<state_index_type, size_t> domain_to_offset;
    std::vector<state_index_type> offset_to_cursor;
    uint64_t offset;
    state_index_type mask;

    inline
    const genotype_comb_type::element_type&
        current_element() const
        {
            return data->m_combination[offset];
        }

    inline
    state_index_type
        local(const state_index_type& global) const
        {
            return global.mask(mask);
        }

    inline
    state_index_type
        merge(const state_index_type& local, const state_index_type& global) const
        {
            return local.merge(global, mask);
        }
};

378
379

/* L'algorithme à proprement parler. */
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
struct joint_variable_product_type {
    std::vector<domain_descr> domains;
    std::vector<table_descr> tables;
    std::vector<int> all_variable_names;
    std::vector<int> output_variable_names;
    std::vector<bool> output_variables_in_use;
    std::vector<std::pair<size_t, size_t>> key_extractors;

    state_index_type max_cursor;

    size_t total_bits;

    size_t last_variable_index;

    bool invalid_product = false;

396
397
    const std::map<std::vector<int>, genotype_comb_type>* all_domains = nullptr;

398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    inline
    void
        set_output(const std::vector<int>& variables)
        {
            output_variable_names = variables;
        }

    inline
    std::pair<size_t, size_t>
        find_offsets_around_cursor(const table_descr& t, state_index_type local_cursor)
        {
            auto it = t.domain_to_offset.find(local_cursor);
            if (it != t.domain_to_offset.end()) {
                return {it->second, it->second};
            }
            if (local_cursor > t.offset_to_cursor.back()) {
                return {t.offset_to_cursor.size() - 1, 0};
            } else if (local_cursor < t.offset_to_cursor.front()) {
                return {0, t.offset_to_cursor.size() - 1};
            }
#if 0
            std::vector<state_index_type>::const_iterator min, max, cur;
            min = t.offset_to_cursor.begin();
            max = t.offset_to_cursor.end();
            while ((max - min) > 1) {
                cur = min + ((max - min) >> 1);
                if (*cur > local_cursor) {
                    max = cur;
                } else {
                    min = cur;
                }
            }
            return {min - t.offset_to_cursor.begin(), max - t.offset_to_cursor.begin()};
#else
            size_t min = 0, max = t.offset_to_cursor.size(), cur;
            while ((max - min) > 1) {
                cur = min + ((max - min) >> 1);
                if (t.offset_to_cursor[cur] > local_cursor) {
                    max = cur;
                } else {
                    min = cur;
                }
            }
            return {min, max};
#endif
        }

    /*state_index_type*/
        /*find_smallest_next_state(const table_descr& t, state_index_type global_cursor)*/
        /*{*/
            /*auto offsets = find_offsets_around_cursor(t, global_cursor & t.mask);*/
        /*}*/

    inline
    void
        get_coords_at(const table_descr& t, uint64_t offset, std::vector<size_t>& coords)
        {
            auto i = coords.begin();
            auto vi = t.variable_indices.begin();
            for (const auto& k: t.data->m_combination[offset].keys) {
                /**i++ = k.state;*/
459
460
461
462
                /**i++ = domains[*vi++].label_to_index.find(k.state)->second;*/
                *i = domains[*vi].label_to_index.find(k.state)->second;
                ++i;
                ++vi;
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
            }
        }

    inline
    std::string
        dump(state_index_type cursor)
        {
            if (cursor.is_bad()) {
                return "<BAD INDEX>";
            }
            static std::vector<size_t> ret;
            ret.resize(domains.size());
            compute_coordinates(cursor, ret);
            return MESSAGE(WHITE << ret << NORMAL);
        }

    inline
    std::string
        dump(state_index_type cursor, const table_descr& t)
        {
            if (cursor.is_bad()) {
                return "<BAD INDEX>";
            }
            std::stringstream ss;
            auto di = domains.begin();
            bool first = true;
            for (bool in_use: t.variables_in_use) {
                auto index = di->extract(cursor);
                if (!first) {
                    ss << ' ';
                } else {
                    first = false;
                }
                if (in_use) {
                    ss << GREEN << index << NORMAL;
                } else {
                    ss << index;
                }
                ++di;
            }
            return ss.str();
        }

    inline
    bool
        move_cursor_if_state_is_valid(table_descr& t, state_index_type cursor)
        {
            /*MSG_DEBUG("table @" << t.data << " cursor=" << dump(cursor));*/
            auto it = t.domain_to_offset.find(t.local(cursor));
            if (it == t.domain_to_offset.end()) {
                /*MSG_DEBUG("not found");*/
                return false;
            }
            /*MSG_DEBUG("found");*/
            t.offset = it->second;
            return true;
        }

    inline
    void
        add_table(const genotype_comb_type& t)
        {
            if (t.size() == 0) {
                invalid_product = true;
                return;
            }
            std::vector<int> vars;
            vars.reserve(t.m_combination[0].keys.size());
            for (auto k: t.m_combination[0].keys) {
                vars.push_back(k.parent);
            }
            all_variable_names = all_variable_names + vars;
            tables.emplace_back();
            tables.back().data = &t;
            tables.back().variable_names.swap(vars);
538
            /*MSG_DEBUG("[joint_product] Added table " << (&t) << " " << t);*/
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
        }

    inline
    void
        compile(const std::map<std::vector<int>, genotype_comb_type>& all_variable_domains)
        {
            compile_domains(all_variable_domains);
            compile_tables();
            compile_output();
        }

    inline
    void
        compile_domains(const std::map<std::vector<int>, genotype_comb_type>& all_variable_domains)
        {
554
            all_domains = &all_variable_domains;
555
556
557
558
559
560
561
            total_bits = 0;
            for (int v: all_variable_names) {
                const auto& domain = all_variable_domains.find(std::vector<int>{v})->second;
                domains.emplace_back();
                auto& d = domains.back();
                d.variable_name = v;
                d.size = domain.size();
562
                d.bit_width = 1;
563
564
                while ((1ULL << d.bit_width) < d.size) { ++d.bit_width; }
                total_bits += d.bit_width;
565
566
                /*MSG_DEBUG("Have domain for variable #" << d.variable_name << " size " << d.size << " bit_width " << d.bit_width);*/
                /*MSG_QUEUE_FLUSH();*/
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
                d.index_to_label.reserve(domain.size());
                for (size_t i = 0; i < domain.size(); ++i) {
                    const auto& label = domain.m_combination[i].keys.keys.front().state;
                    d.label_to_index[label] = i;
                    d.index_to_label.push_back(label);
                }
            }
            size_t shift = 0;
            max_cursor.reset();
            for (auto& d: reversed(domains)) {
                d.init_indexer(shift);
                /*d.max = (d.size - 1) << shift;*/
                /*d.mask = ((1 << d.bit_width) - 1) << shift;*/
                /*d.shift = shift;*/
                shift += d.bit_width;
                d.assign(max_cursor, d.max);
583
584
585
                /*MSG_QUEUE_FLUSH();*/
                /*MSG_DEBUG("Have domain for variable #" << d.variable_name << " size " << d.size << " bit_width " << d.bit_width << " mask " << boost::dynamic_bitset<uint64_t>(total_bits, d.mask) << " max " <<  boost::dynamic_bitset<uint64_t>(total_bits, d.max));*/
                /*MSG_QUEUE_FLUSH();*/
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
                if (0) {
                    std::stringstream ss;
                    for (const auto& kv: d.label_to_index) {
                        ss << ' ' << kv.first << ':' << kv.second;
                    }
                    MSG_DEBUG(ss.str());
                }
            }
            last_variable_index = all_variable_names.size() - 1;
        }

    inline
    void
        compile_tables()
        {
            std::vector<size_t> coordinates;
            coordinates.reserve(all_variable_names.size());
            for (auto& tab: tables) {
                tab.variable_indices.reserve(tab.variable_names.size());
                tab.variables_in_use.resize(all_variable_names.size(), false);
                tab.mask.reset();
                for (size_t v: tab.variable_names) {
                    tab.variable_indices.push_back(std::find(all_variable_names.begin(), all_variable_names.end(), v) - all_variable_names.begin());
                    tab.variables_in_use[tab.variable_indices.back()] = true;
                    /*tab.mask |= domains[tab.variable_indices.back()].mask;*/
                    domains[tab.variable_indices.back()].assign_mask(tab.mask);
                }
                tab.variables_left.resize(all_variable_names.size(), false);
                for (size_t v = 0; v < tab.variable_indices[0]; ++v) {
                    tab.variables_left[v] = true;
                }
617
618
619
620
621
                /*MSG_QUEUE_FLUSH();*/
                /*MSG_DEBUG("Table " << tab.data);*/
                /*MSG_QUEUE_FLUSH();*/
                /*MSG_DEBUG("Table variables " << tab.variable_names << " mask " << tab.mask);*/
                /*MSG_QUEUE_FLUSH();*/
622
623
624
625
626
627
628
629
630
                tab.offset = 0;
                coordinates.resize(tab.variable_names.size());
                tab.offset_to_cursor.reserve(tab.data->size());
                for (uint64_t i = 0; i < tab.data->size(); ++i) {
                    get_coords_at(tab, i, coordinates);
                    state_index_type cursor = compute_local_index(coordinates, tab);
                    tab.offset_to_cursor.push_back(cursor);
                    tab.domain_to_offset[cursor] = i;
                }
631
                if (0) {
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
                    std::stringstream ss;
                    ss << "Table";
                    for (const auto& x: tab.domain_to_offset) {
                        ss << ' ' << x.first << ':' << x.second;
                    }
                    ss << ',';
                    for (const auto& x: tab.offset_to_cursor) {
                        ss << ' ' << x;
                    }
                    MSG_DEBUG(ss.str());
                }
            }
            /*std::sort(tables.begin(), tables.end(), [](const table_descr& t1, const table_descr& t2) { return t1.data->size() > t2.data->size(); });*/
        }

    inline
    void
        compile_output()
        {
651
            /*MSG_DEBUG("all output variables " << output_variable_names);*/
652
            output_variable_names = output_variable_names % all_variable_names;
653
            /*MSG_DEBUG("all_variable_names " << all_variable_names << " output_variable_names " << output_variable_names);*/
654
655
656
657
658
659
660
            output_variables_in_use.resize(all_variable_names.size(), false);
            for (int v: output_variable_names) {
                size_t index = std::find(all_variable_names.begin(), all_variable_names.end(), v) - all_variable_names.begin();
                output_variables_in_use[index] = true;
                for (size_t t = 0; t < tables.size(); ++t) {
                    auto iter = std::find(tables[t].variable_names.begin(), tables[t].variable_names.end(), v);
                    if (iter != tables[t].variable_names.end()) {
661
                        /*MSG_DEBUG("variable " << v << " found in table " << t << " at index " << (iter - tables[t].variable_names.begin()));*/
662
663
                        key_extractors.emplace_back(t, iter - tables[t].variable_names.begin());
                        break;
664
665
                    /*} else {*/
                        /*MSG_DEBUG("variable " << v << " not found in table " << t);*/
666
667
668
                    }
                }
            }
669
            if (0) {
670
671
672
673
674
675
                std::stringstream ss;
                ss << "key extractors";
                for (const auto& t_ki: key_extractors) {
                    ss << ' ' << t_ki.first << ':' << t_ki.second;
                }
                MSG_DEBUG(ss.str());
676
                MSG_QUEUE_FLUSH();
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
            }
        }

    inline
    state_index_type
        compute_local_index(const std::vector<size_t>& coordinates, const table_descr& t)
        {
            state_index_type accum;
            accum.reset();
            auto coordi = coordinates.begin();
            for (int v: t.variable_indices) {
                const auto& dom = domains[v];
                /*accum |= *coordi++ << dom.shift;*/
                dom.assign(accum, *coordi++);
            }
            return accum;
        }

    inline
    bool
        increment_index(state_index_type& index)
        {
            for (const auto& d: reversed(domains)) {
                if (!d.incr(index)) {
                    return false;
                }
            }
            return true;
                /*auto m = d.mask;*/
                /*if ((index & m) == d.max) {*/
                    /*index &= ~m;*/
                /*} else {*/
                    /*index += 1 << d.shift;*/
                    /*return false;*/
                /*}*/
            /*}*/
            /*return true;*/
        }

    inline
    void
        zero_right(state_index_type& index, size_t digit, const std::vector<bool>& variables_in_use)
        {
            auto di = domains.rbegin();
            auto in_use = variables_in_use.rbegin();
            auto dd = di + digit;
            /*state_index_type mask = 0;*/
            for (; di != dd; ++di) {
                if (!*in_use++) {
                    di->zero(index);
                    /*mask |= di->mask;*/
                }
            }
            /*index &= ~mask;*/
        }

    inline
    bool
        increment_left_and_zero_right(state_index_type& index, size_t digit)
        {
            auto di = domains.rbegin();
            auto dd = di + digit;
            auto dj = domains.rend();
            for (; di != dd; ++di) {
                di->zero(index);
            }
            di->zero(index);
            for (++di; di != dj; ++di) {
                if (!di->incr(index)) {
                    return false;
                }
            }
            return true;
        }

    inline
    state_index_type
        merge_cursors(const table_descr& t, state_index_type global, state_index_type local)
        {
            /* merge cursors, and increment if smaller than global cursor. otherwise, zero to the right of the leftmost modified digit. */
            /*scoped_indent _(MESSAGE("[merge_cursors " << dump(global) << " / " << dump(local, t) << "] "));*/
            state_index_type merged = t.merge(local, global);
            /*MSG_DEBUG("merged " << dump(merged, t));*/
            /*MSG_DEBUG("versus " << dump(global));*/
            size_t leftmost_modified_digit = 0;
            bool overflow = false;
            for (size_t v: t.variable_indices) {
                const auto& d = domains[v];
                state_index_type::block_type
                    m = d.extract_unshifted(merged),
                    g = d.extract_unshifted(global);
                /*MSG_DEBUG("m " << m << " g " << g);*/
                if (m != g) {
                    leftmost_modified_digit = last_variable_index - v;
                    overflow = m < g;
                    /*break;*/
                    /*MSG_DEBUG("leftmost_modified_digit " << leftmost_modified_digit << " overflow " << overflow);*/
                    if (overflow) {
                        /*MSG_DEBUG("increment_left_and_zero_right");*/
                        if (increment_left_and_zero_right(merged, leftmost_modified_digit)) {
                            /*MSG_DEBUG("general overflow !");*/
                            return state_index_type::bad();
                        }
                        return merged;
                    } else {
                        /*MSG_DEBUG("zero_right");*/
                        zero_right(merged, leftmost_modified_digit, t.variables_in_use);
                    }
                    /*MSG_DEBUG("return " << dump(merged));*/
                    return merged;
                }
            }
            return merged;
        }

    inline
    void
        compute_coordinates(state_index_type index, std::vector<size_t>& coordinates)
        {
            /*auto di = domains.rbegin();*/
            /*auto finished = domains.rend();*/
            auto coordi = coordinates.rbegin();
            /*size_t shift = 0;*/
            /*for (; di != finished; ++di) {*/
                /**coordi = (index & di->mask) >> shift;*/
                /*++coordi;*/
                /*shift += di->bit_width;*/
            /*}*/
            for (const domain_descr& d: reversed(domains)) {
                /**coordi++ = (index & d.mask) >> d.shift;*/
                *coordi++ = d.extract(index);
            }
        }

811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
    struct update_key {
        size_t
            key_size(const joint_variable_product_type& jvp) const { return jvp.output_variable_names.size(); }
        void
            operator () (const joint_variable_product_type& jvp, genotype_comb_type::key_list& key) const
            {
                auto ki = key.begin();
                for (const auto& t_ki: jvp.key_extractors) {
                    *ki++ = jvp.tables[t_ki.first].current_element().keys.keys[t_ki.second];
                }
            }
    };

    struct update_key_build_factor {
        size_t
            key_size(const joint_variable_product_type& jvp) const { return jvp.output_variable_names.size(); } /* parents + gameteS, where gameteS will be replaced by the output variable */
        void
            operator () (joint_variable_product_type& jvp, genotype_comb_type::key_list& key) const
            {
                auto ki = key.begin();
                auto ti = jvp.tables.begin();
                bn_label_type G = ti->current_element().keys.keys.front().state;
                /*MSG_DEBUG("Have gamete label " << G); MSG_QUEUE_FLUSH();*/
                for (const auto& t_ki: jvp.key_extractors) {
                    *ki++ = jvp.tables[t_ki.first].current_element().keys.keys[t_ki.second];
                    /**ki++ = ti->current_element().keys.keys.front();*/
                }
                /*MSG_DEBUG("Have temp key " << key); MSG_QUEUE_FLUSH();*/
                const auto& p1 = key.keys[G.first_allele];
                const auto& p2 = key.keys[G.second_allele];
                bool f1 = G.first == GAMETE_L;
                bool f2 = G.second == GAMETE_L;
                /*MSG_DEBUG("Have p1 " << p1 << " p2 " << p2 << " f1 " << f1 << " f2 " << f2); MSG_QUEUE_FLUSH();*/
                *ki = {
                    jvp.output_variable_names.back(), {f1 ? p1.state.first : p1.state.second,
                    f2 ? p2.state.first : p2.state.second,
                    f1 ? p1.state.first_allele : p1.state.second_allele,
                    f2 ? p2.state.first_allele : p2.state.second_allele}
                };
                /*MSG_DEBUG("Have complete key " << key); MSG_QUEUE_FLUSH();*/
            }
    };

#if 0
855
856
857
858
859
860
861
862
863
    inline
    void
        update_key(genotype_comb_type::key_list& key)
        {
            auto ki = key.begin();
            for (const auto& t_ki: key_extractors) {
                *ki++ = tables[t_ki.first].current_element().keys.keys[t_ki.second];
            }
        }
864
#endif
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921

    inline
    double
        compute_coef()
        {
            auto ti = tables.begin();
            auto tj = tables.end();
            double accum = ti->current_element().coef;
            for (++ti; ti != tj; ++ti) {
                accum *= ti->current_element().coef;
            }
            return accum;
        }

    inline
    state_index_type
        next_state(state_index_type from)
        {
            uint64_t valid = 0, all = (1 << tables.size()) - 1;
            size_t ti = 0;
            while (valid != all && !from.is_bad()) {
                /*MSG_DEBUG("valid " << valid << " all " << all << " table " << (*tables[ti].data));*/
                if (!move_cursor_if_state_is_valid(tables[ti], from)) {
                    auto range = find_offsets_around_cursor(tables[ti], tables[ti].local(from));
                    /*MSG_DEBUG("offsets are " << range.first << " and " << range.second);*/
                    state_index_type
                        c1 = merge_cursors(tables[ti], from, tables[ti].offset_to_cursor[range.first]),
                        c2 = merge_cursors(tables[ti], from, tables[ti].offset_to_cursor[range.second]);
                    /*MSG_DEBUG("from = " << dump(from) << " c1 = " << dump(c1, tables[ti]) << " c2 = " << dump(c2, tables[ti]));*/
                    state_index_type tmp; // = std::min(c1, c2);
                    if (c1 > from) {
                        if (c2 > from) {
                            tmp = std::min(c1, c2);
                        } else {
                            tmp = c1;
                        }
                    } else if (c2 > from) {
                        tmp = c2;
                    } else {
                        return state_index_type::bad();
                    }
                    /*MSG_DEBUG("new lower bound is now " << dump(tmp));*/
                    if (tmp < from) {
                        return state_index_type::bad();
                    }
                    from = tmp;
                    valid = 0;
                    /*ti = !ti;*/
                } else {
                    valid |= 1 << ti;
                }
                ++ti;
                ti %= tables.size();
            }
            return from;
        }

922

923
    genotype_comb_type
924
        extract_domain()
925
        {
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
            genotype_comb_type ret;
            genotype_comb_type::key_list key;
            update_key uk;
            key.keys.resize(output_variable_names.size());
            std::unordered_map<genotype_comb_type::key_list, double> values;
            size_t& offset = tables.front().offset;
            size_t max = tables.front().data->size();
            for (offset = 0; offset < max; ++offset) {
                uk(*this, key);
                values[key] = 1;
            }
            for (const auto& kv: values) {
                /*ret.m_combination.emplace_back(kv.first, kv.second * norm);*/
                ret.m_combination.emplace_back(kv.first, kv.second);
            }
            std::sort(ret.m_combination.begin(), ret.m_combination.end());
            /*MSG_DEBUG("have domain " << ret);*/
            return ret;
        }

    template <typename key_computing_variant>
    genotype_comb_type
        compute_generic()
        {
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
            if (total_bits >= 32) {
                std::vector<size_t> output_variable_indices;
                for (size_t i = 0; i < output_variables_in_use.size(); ++i) {
                    output_variable_indices.push_back(i);
                }
                /* Build adjacency matrix */
                std::vector<std::vector<int>> weights(tables.size());
                for (size_t i = 0; i < tables.size(); ++i) { weights[i].resize(tables.size(), 0); }
                for (size_t i = 0; i < tables.size(); ++i) {
                    const auto& Vi = tables[i].variable_indices;
                    for (size_t j = i + 1; j < tables.size(); ++j) {
                        const auto& Vj = tables[j].variable_indices;
                        int w = 0;
                        for (size_t varidx: (Vi % Vj) - output_variable_indices) {
                            w += domains[varidx].bit_width;
                        }
                        weights[i][j] = w;
                        weights[j][i] = w;
                    }
                }
                /* Find minimum cut */
                std::pair<int, std::vector<int>> cut = get_min_cut(weights);
                std::vector<bool> first_part(tables.size(), false);
                for (int c: cut.second) {
                    first_part[c] = true;
                }
                joint_variable_product_type p1, p2;
                auto ti = tables.begin();
                for (auto b: first_part) {
                    (b ? p1 : p2).add_table(*ti->data);
                }
                auto common = p1.all_variable_names % p2.all_variable_names;
                p1.set_output(output_variable_names + common);
                p2.set_output(output_variable_names + common);
                p1.compile(*all_domains);
                p2.compile(*all_domains);
                genotype_comb_type t1 = p1.compute_generic<key_computing_variant>();
                genotype_comb_type t2 = p2.compute_generic<key_computing_variant>();
                joint_variable_product_type final;
                final.add_table(t1);
                final.add_table(t2);
                final.compile(*all_domains);
                return final.compute_generic<key_computing_variant>();
            }

995
            key_computing_variant key_update;
996
997
998
999
1000
            if (invalid_product) { return {}; }

            genotype_comb_type ret;
            size_t counter = 0;
            genotype_comb_type::key_list key;
For faster browsing, not all history is shown. View entire blame