pedigree_tree.h 61.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
#ifndef _SPELL_PEDIGREE_TREE_H_
#define _SPELL_PEDIGREE_TREE_H_
#include <map>
#include <vector>
#include <set>
#include <unordered_set>
#include "permutation.h"


typedef std::map<int, int> ancestor_node_list_type;


ancestor_node_list_type reentrants(const ancestor_node_list_type& a)
{
    ancestor_node_list_type ret;
    for (const auto& kv: a) {
        if (kv.second > 1) {
            ret.emplace(kv);
        }
    }
    return ret;
}


ancestor_node_list_type operator + (const ancestor_node_list_type& a1, const ancestor_node_list_type& a2)
{
    ancestor_node_list_type ret(a1);
    for (const auto& kv: a2) {
        ret[kv.first] += kv.second;
    }
    return ret;
}


ancestor_node_list_type operator / (const ancestor_node_list_type& a, const ancestor_node_list_type& restr)
{
    ancestor_node_list_type ret;
    for (const auto& kv: a) {
        auto i = restr.find(kv.first);
        if (i != restr.end()) {
            ret.emplace(kv.first, std::min(kv.second, i->second));
        }
    }
    return ret;
}


ancestor_node_list_type operator % (const ancestor_node_list_type& a, const ancestor_node_list_type& restr)
{
    ancestor_node_list_type ret;
    for (const auto& kv: a) {
        if (restr.find(kv.first) != restr.end()) {
            ret.emplace(kv);
        }
    }
    return ret;
}


ancestor_node_list_type operator - (const ancestor_node_list_type& a, const ancestor_node_list_type& restr)
{
    ancestor_node_list_type ret;
    for (const auto& kv: a) {
        auto it = restr.find(kv.first);
        if (it == restr.end()) {
            ret.emplace(kv);
        } else if (kv.second > it->second) {
            ret.emplace(kv.first, kv.second - it->second);
        }
    }
    return ret;
}


ancestor_node_list_type operator * (const ancestor_node_list_type& a, int weight)
{
    ancestor_node_list_type ret;
    for (const auto& kv: a) {
        ret.emplace(kv.first, kv.second * weight);
    }
    return ret;
}


std::ostream& operator << (std::ostream& os, const ancestor_node_list_type& a)
{
    auto i = a.begin();
    auto j = a.end();
    if (i != j) {
        os << i->first << ':' << i->second;
        for (++i; i != j; ++i) {
            os << ' ' << i->first << ':' << i->second;
        }
    } else {
        os << "empty";
    }
    return os;
}



struct pedigree_tree_type {
#define NONE ((int) -1)
    typedef size_t individual_index_type;

    struct node_type {
        int p1, p2;
        node_type() : p1(NONE), p2(NONE) {}
        node_type(int p) : p1(p), p2(NONE) {}
        node_type(int a, int b) : p1(a), p2(b) {}
        node_type(const node_type& other) : p1(other.p1), p2(other.p2) {}
        bool operator == (const node_type& other) const { return p1 == other.p1 && p2 == other.p2; }
        bool operator < (const node_type& other) const { return p1 < other.p1 || (p1 == other.p1 && p2 < other.p2); }
        node_type& operator = (const node_type& other) { p1 = other.p1; p2 = other.p2; return *this; }
        bool is_ancestor() const { return p1 == NONE && p2 == NONE; }
        bool is_gamete() const { return p1 != NONE && p2 == NONE; }
Damien Leroux's avatar
Damien Leroux committed
117
118
        bool is_crossing() const { return p1 != NONE && p2 != NONE; }
        bool is_genotype() const { return p2 != NONE || p1 == NONE; }
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
        bool has_p1() const { return p1 != NONE; }
        bool has_p2() const { return p2 != NONE; }
    };

    std::vector<int> m_leaves;
    std::unordered_set<int> m_roots;

    std::vector<node_type> m_nodes;
    std::vector<std::vector<bool>> m_must_recompute;

    std::map<int, individual_index_type> m_node_number_to_ind_number;
    std::vector<int> m_ind_number_to_node_number;
    std::vector<int> m_original_ordering;

    pedigree_tree_type()
Damien Leroux's avatar
Damien Leroux committed
134
        : m_leaves(), m_roots(), m_nodes(), m_must_recompute(), m_node_number_to_ind_number(), m_ind_number_to_node_number(1, NONE)
135
136
    {}

Damien Leroux's avatar
Damien Leroux committed
137
138
139
140
141
142
143
144
145

    int get_p1(int n) const { return m_nodes[n].p1; }
    int get_p2(int n) const { return m_nodes[n].p2; }

    const node_type& operator [] (int n) const { return m_nodes[n]; }

    size_t size() const { return m_nodes.size(); }
    const std::vector<bool>& get_recompute_vec(int n) const { return m_must_recompute[n]; }

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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    /* building helpers */

    int ancestor() { return add_node(); }
    int gamete(int p) { return add_node(p); }
    int crossing(int p1, int p2) { return add_node(gamete(p1), gamete(p2)); }
    int dh(int p1) { int g = gamete(p1); return add_node(g, g); }
    int selfing(int p1) { return crossing(p1, p1); }

    /* expression helpers */

    pedigree_tree_type
        extract(const std::vector<bool>& include, std::vector<int>& inputs, std::vector<int>& outputs) const
        {
            pedigree_tree_type ret;
            if (include.size() != m_nodes.size()) {
                return {};
            }
            std::vector<int> translate(1 + m_nodes.size(), NONE);
            std::vector<int> inv_translate(1 + m_nodes.size(), NONE);
            const int sz = (int) m_nodes.size();
            for (int i = 0; i < sz; ++i) {
                if (include[i]) {
                    translate[1 + i] = ret.add_node(translate[1 + m_nodes[i].p1], translate[1 + m_nodes[i].p2]);
                    inv_translate[translate[1 + i]] = i;
                    ret.m_original_ordering.back() = m_original_ordering[i];
                }
            }
            inputs.clear();
            inputs.reserve(ret.m_leaves.size());
            for (size_t i = 0; i < ret.m_leaves.size(); ++i) {
                inputs.push_back(inv_translate[ret.m_leaves[i]]);
            }
            outputs.clear();
            outputs.reserve(ret.m_roots.size());
            for (int r: ret.m_roots) {
                outputs.push_back(inv_translate[r]);
            }
            return ret;
        }

    int original_node_number(int i) const { return m_original_ordering[i]; }

    pedigree_tree_type
        extract_expression(int n, std::vector<int>& inputs, std::vector<int>& outputs)
        {
            std::vector<bool> include(m_nodes.size(), false);
            std::vector<int> stack(1, n);
            const auto& recompute = m_must_recompute[n];
            /* what to include?
             * - any must_recompute node
             * - any parent of gamete (single-parent) node
             */
            while (stack.size() != 0) {
                n = stack.back();
                stack.pop_back();
                include[n] = true;
                if (recompute[n] || m_nodes[n].is_gamete()) {
                    if (!include[m_nodes[n].p1]) {
                        stack.push_back(m_nodes[n].p1);
                    }
                    if (m_nodes[n].has_p2() && !include[m_nodes[n].p2]) {
                        stack.push_back(m_nodes[n].p2);
                    }
                }
            }
            return extract(include, inputs, outputs);
        }

    std::vector<bool>
        get_deep_recompute_vec(int n) const
        {
            std::vector<bool> ret(m_must_recompute[n]);
            for (int i = n; i >= 0; --i) {
                if (!ret[i]) {
                    const auto& sub_recompute = m_must_recompute[i];
                    for (int sub = 0; sub < i; ++sub) {
                        ret[sub] = ret[sub] | sub_recompute[sub];
                    }
                }
            }
            ret[n] = false;
            return ret;
        }

    pedigree_tree_type
        extract_subtree(int n)
        {
            std::vector<bool> include(m_nodes.size(), false);
            std::vector<int> stack(1, n);

            while (stack.size() != 0) {
                n = stack.back();
                stack.pop_back();
                include[n] = true;
                if (m_nodes[n].has_p1() && !include[m_nodes[n].p1]) {
                    stack.push_back(m_nodes[n].p1);
                }
                if (m_nodes[n].has_p2() && !include[m_nodes[n].p2]) {
                    stack.push_back(m_nodes[n].p2);
                }
            }
            std::vector<int> discard_inputs, discard_outputs;
            return extract(include, discard_inputs, discard_outputs);
        }

    int
        add_node(int p1=NONE, int p2=NONE)
        {
            int ret = (int) m_nodes.size();
            m_nodes.emplace_back(p1, p2);
            m_roots.erase(p1);
            m_roots.erase(p2);
            m_roots.insert(ret);
            m_must_recompute.emplace_back(m_nodes.size(), false);
            std::vector<bool>& recompute = m_must_recompute.back();
            if (p2 != NONE || p1 == NONE) { /* descendant or ancestor, not gamete */
                m_node_number_to_ind_number[ret] = m_ind_number_to_node_number.size();
                m_ind_number_to_node_number.push_back(ret);
            }
            if (p1 != NONE && p2 != NONE) {
                auto tmp_reent = cleanup_reentrants(ret);
                for (size_t i = 0; i < m_nodes.size(); ++i) {
                    recompute[i] = (tmp_reent % count_ancestors(i)).size() > 0;
                    /*MSG_DEBUG("must_recompute " << make_node_label(i) << " = " << recompute[i]);*/
                }
            } else if (p1 == NONE && p2 == NONE) {
                m_leaves.push_back(ret);
            }
            recompute.back() = true;
            m_original_ordering.push_back(m_original_ordering.size());
            return ret;
        }

    ancestor_node_list_type
Damien Leroux's avatar
Damien Leroux committed
280
        cleanup_reentrants(int node) const
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
        {
            auto A = count_ancestors(node);
            auto Ap1 = count_ancestors(m_nodes[node].p1);
            auto Ap2 = count_ancestors(m_nodes[node].p2);

            auto R = reentrants(A);
            auto Rp1 = reentrants(Ap1);
            auto Rp2 = reentrants(Ap2);

            /*MSG_DEBUG_INDENT_EXPR("[cleanup_reentrants] ");*/
            /*MSG_DEBUG("A: " << A);*/
            /*MSG_DEBUG("Ap1: " << Ap1);*/
            /*MSG_DEBUG("Ap2: " << Ap2);*/
            /*MSG_DEBUG("R: " << R);*/
            /*MSG_DEBUG("Rp1: " << Rp1);*/
            /*MSG_DEBUG("Rp2: " << Rp2);*/

            R = R - Rp1 - Rp2;

            ancestor_node_list_type ret = R;
            auto i = R.rbegin();
            auto j = R.rend();
            for (; i != j; ++i) {
                /*MSG_DEBUG("cleaning from #" << i->first << " (x" << i->second << ')');*/
                auto sub_re = reentrants(count_ancestors(i->first) * i->second);
                /*MSG_DEBUG(" sub reentrants = " << sub_re);*/
                ret = ret - sub_re;
                /*MSG_DEBUG(" current list = " << ret);*/
            }
Damien Leroux's avatar
Damien Leroux committed
310
            /*MSG_DEBUG_DEDENT;*/
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
344
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

            return ret;
        }

    ancestor_node_list_type
        count_ancestors(int node) const
        {
            ancestor_node_list_type ret;
            if (node == NONE) {
                return ret;
            }
            std::vector<int> stack;
            stack.reserve(m_nodes.size());
            /*stack.push_back(node);*/
            if (m_nodes[node].has_p1()) {
                stack.push_back(m_nodes[node].p1);
            }
            if (m_nodes[node].has_p2()) {
                stack.push_back(m_nodes[node].p2);
            }
            while (stack.size()) {
                int n = stack.back();
                stack.pop_back();
                if (m_nodes[n].has_p1()) {
                    stack.push_back(m_nodes[n].p1);
                }
                if (m_nodes[n].has_p2()) {
                    stack.push_back(m_nodes[n].p2);
                }
                ++ret[n];
            }
            /*ret[node] = 1;*/
            return ret;
        }

    std::string
        make_node_label(int ni) const
        {
            const node_type& n = m_nodes[ni];
            std::string sub;
            std::string p1;
            std::stringstream l;
            l <<  '(' << ni << ") ";
            if (n.has_p2() || !n.has_p1()) {
                l << m_node_number_to_ind_number.find(ni)->second;
            } else {
                l << "G(" << m_node_number_to_ind_number.find(n.p1)->second << ')';
            }
            return l.str();
        }

    individual_index_type
        node2ind(int node) const
        {
            auto it = m_node_number_to_ind_number.find(node);
            if (it != m_node_number_to_ind_number.end()) { return it->second; }
            return NONE;
        }

    int
        ind2node(individual_index_type ind) const
        {
            return m_ind_number_to_node_number[ind];
        }

Damien Leroux's avatar
Damien Leroux committed
376
377
    int next_ind_idx() const { return m_ind_number_to_node_number.size(); }

378
379
    void
        render_tree_stream(std::string& path) const
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
        {
            std::ofstream tmp("/tmp/pedigree_tree");
            std::vector<std::string> labels;
            labels.reserve(m_nodes.size());
            for (size_t ni = 0; ni < m_nodes.size(); ++ni) {
                labels.emplace_back(make_node_label(ni));
            }
            size_t ni = 0;
            for (const auto& n: m_nodes) {
                if (n.has_p1()) {
                    tmp << '[' << labels[n.p1] << "]-->[" << labels[ni] << ']' << std::endl;
                }
                if (n.has_p2()) {
                    tmp << '[' << labels[n.p2] << "]-->[" << labels[ni] << ']' << std::endl;
                }
                ++ni;
            }
            tmp.close();
            { auto ret = system("graph-easy /tmp/pedigree_tree --as_boxart /tmp/pedigree_tree.txt"); (void) ret; }
399
400
401
402
403
404
405
406
407
            path = "/tmp/pedigree_tree.txt";
        }

    std::string
        render_tree() const
        {
            std::string path;
            render_tree_stream(path);
            std::ifstream out(path);
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
            char c;
            std::stringstream converter;
            while (!out.get(c).eof()) {
                converter << c;
            }
            return converter.str();
        }

    bool
        operator == (const pedigree_tree_type& other) const
        {
            return m_nodes == other.m_nodes;
        }

    bool
        operator < (const pedigree_tree_type& other) const
        {
            return m_nodes < other.m_nodes;
        }

    friend
        std::ostream&
        operator << (std::ostream& os, const pedigree_tree_type& tree)
        {
432
433
434
435
436
437
438
439
            std::string path;
            tree.render_tree_stream(path);
            std::ifstream out(path);
            char c;
            while (!out.get(c).eof()) {
                os << c;
            }
            return os;
440
441
442
443
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
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
        }

    struct tree_descr_struc;
    typedef std::shared_ptr<tree_descr_struc> tree_descr_type;

    /*struct tree_descr_comp {*/
        /*bool operator () (const tree_descr_struc* a, const tree_descr_struc* b) const { return *a < *b; }*/
    /*};*/

    /*typedef std::map<tree_descr_struc*, bool, tree_descr_comp> tree_descr_bool_map_type;*/
    typedef std::map<tree_descr_struc*, bool> tree_descr_bool_map_type;

    struct tree_descr_struc {
        size_t count;
        tree_descr_type sub1, sub2;
        bool LR;
        bool RL;

        tree_descr_struc(size_t c, tree_descr_type s1, tree_descr_type s2)
            : count(c), sub1(), sub2(), LR(false), RL(false)
        {
            if ((*s1) == (*s2)) {
                LR = RL = true;
                sub1 = s1;
                sub2 = s2;
            } else if ((*s1) < (*s2)) {
                LR = true;
                sub1 = s1;
                sub2 = s2;
            } else {
                RL = true;
                sub1 = s2;
                sub2 = s1;
            }
        }

        tree_descr_struc(size_t c, tree_descr_type s1)
            : count(c), sub1(s1), sub2(), LR(true), RL(false)
        {}

        tree_descr_struc(size_t c)
            : count(c), sub1(), sub2(), LR(true), RL(false)
        {}

        bool operator == (const tree_descr_struc& other) const
        {
            if (!this) {
                return !(&other);
            }
            if (!(&other)) {
                return !this;
            }
            return count == other.count
                && (sub1 == other.sub1 || *sub1 == *other.sub1)
                && (sub2 == other.sub2 || *sub2 == *other.sub2);
        }

        bool operator < (const tree_descr_struc& other) const
        {
            if (!this) {
                return !!(&other);
            }
            if (!(&other)) {
                return false;
            }
            return count < other.count
                || (count == other.count
                    && (*sub1 < *other.sub1
                        || (*sub1 == *other.sub1 && *sub2 < *other.sub2)));
        }

        void reset_cursor(tree_descr_bool_map_type& cursors)
        {
            cursors[this] = !LR;
            /*MSG_DEBUG_INDENT_EXPR("[RC " << LR << RL << "] ");*/
            /*MSG_DEBUG(cursors[this]);*/
            if (sub1) {
                sub1->reset_cursor(cursors);
            }
            if (sub2) {
                sub2->reset_cursor(cursors);
            }
            /*MSG_DEBUG_DEDENT;*/
        }

        void reset_visited(tree_descr_bool_map_type& visited)
        {
            visited[this] = false;
            if (sub1) { sub1->reset_visited(visited); }
            if (sub2) { sub2->reset_visited(visited); }
        }

        bool next(tree_descr_bool_map_type& cursors, tree_descr_bool_map_type& visited)
        {
            if (!this || visited[this]) {
                return true;
            }
            visited[this] = true;
            bool carry = true;
            if (LR && RL) {
                if (sub2->next(cursors, visited)) {
                    if (sub1->next(cursors, visited)) {
                        carry = cursors[this];
                        cursors[this] = !cursors[this];
                    } else {
                        carry = false;
                    }
                } else {
                    carry = false;
                }
            } else if (sub2) {
                carry = sub2->next(cursors, visited);
                carry &= sub1->next(cursors, visited);
            } else if (sub1) {
                carry = sub1->next(cursors, visited);
            }
            return carry;
        }

        size_t count_permutations(tree_descr_bool_map_type& visited)
        {
            if (visited[this]) {
                return 1;
            }
            visited[this] = true;
            if (sub1) {
                if (sub2) {
                    size_t count = LR + RL;
                    return count * sub1->count_permutations(visited) * sub2->count_permutations(visited);
                }
                return sub1->count_permutations(visited);
            }
            return 1;
        }

        template <typename FBefore, typename FAfter>
            void
            visit(int node, const pedigree_tree_type& tree,
                  const tree_descr_bool_map_type& cursors, tree_descr_bool_map_type& visited,
                  FBefore before, FAfter after)
            {
                /*MSG_DEBUG("visiting " << (*this) << " node " << node);*/
                /*MSG_QUEUE_FLUSH();*/
                bool has_p1 = tree.m_nodes[node].has_p1();
                bool has_p2 = tree.m_nodes[node].has_p2();
                bool v = visited[this];
                visited[this] = true;
                bool cursor = cursors.find(this)->second;
                if (!before(node, has_p1, has_p2, cursor, v)) {
                    return;
                }
                if (cursor) {
                    /*MSG_DEBUG("cursor TRUE");*/
                    /* R-to-L.
                     * p2 then p1
                     * if LR is set then: use sub2/p2, sub1/p1
                     * else: use sub1/p2, sub2/p1
                     */
                    if (LR) {
                        /*MSG_DEBUG("LR TRUE");*/
                        /*MSG_QUEUE_FLUSH();*/
                        sub2->visit(tree.m_nodes[node].p2, tree, cursors, visited, before, after);
                        sub1->visit(tree.m_nodes[node].p1, tree, cursors, visited, before, after);
                    } else {
                        /*MSG_DEBUG("LR FALSE");*/
                        /*MSG_QUEUE_FLUSH();*/
                        sub1->visit(tree.m_nodes[node].p2, tree, cursors, visited, before, after);
                        sub2->visit(tree.m_nodes[node].p1, tree, cursors, visited, before, after);
                    }
                } else {
                    /*MSG_DEBUG("cursor FALSE");*/
                    /*MSG_QUEUE_FLUSH();*/
                    /* L-to-R.
                     * p1 then p2, and sub1 is p1.
                     */
                    if (has_p1) {
                        /*MSG_DEBUG("HAS P1");*/
                        /*MSG_QUEUE_FLUSH();*/
                        sub1->visit(tree.m_nodes[node].p1, tree, cursors, visited, before, after);
                    }
                    if (has_p2) {
                        /*MSG_DEBUG("HAS P2");*/
                        /*MSG_QUEUE_FLUSH();*/
                        sub2->visit(tree.m_nodes[node].p2, tree, cursors, visited, before, after);
                    }
                }
                after(node, has_p1, has_p2, cursor);
            }

        friend
            std::ostream& operator << (std::ostream& os, const tree_descr_struc& td)
            {
                static int recurse = 0;
                if (!(&td)) {
                    return os;
                }
                os << td.count;
                if (td.sub1) {
                    ++recurse;
                    os << (*td.sub1);
                    --recurse;
                }
                if (td.sub2) {
                    ++recurse;
                    os << (*td.sub2);
                    --recurse;
                }
                os << '0';
                if (td.LR && !recurse) {
                    os << " [LR]";
                }
                if (td.RL && !recurse) {
                    os << " [RL]";
                }
                return os;
            }

        friend
            std::ostream& operator << (std::ostream& os, const tree_descr_type& td)
            {
                if (!td || td.get() == NULL) {
                    return os;
                }
                return os << (*td);
            }
    };

    typedef std::map<size_t, tree_descr_type> tree_descr_map_type;

    tree_descr_map_type
        compute_descr(int node) const
        {
            std::map<size_t, tree_descr_type> ret;
            auto all_counts = count_ancestors(node);
            for (const auto& kv: all_counts) {
                if (m_nodes[kv.first].has_p2()) {
                    ret[kv.first] = std::make_shared<tree_descr_struc>(kv.second, ret[m_nodes[kv.first].p1], ret[m_nodes[kv.first].p2]);
                } else if (m_nodes[kv.first].has_p1()) {
                    ret[kv.first] = std::make_shared<tree_descr_struc>(kv.second, ret[m_nodes[kv.first].p1]);
                } else {
                    ret[kv.first] = std::make_shared<tree_descr_struc>(kv.second);
                }
                /*MSG_DEBUG("computed descr for #" << kv.first << ": " << ret[kv.first]);*/
            }
            if (m_nodes[node].has_p2()) {
                ret[node] = std::make_shared<tree_descr_struc>(1, ret[m_nodes[node].p1], ret[m_nodes[node].p2]);
            } else if (m_nodes[node].has_p1()) {
                ret[node] = std::make_shared<tree_descr_struc>(1, ret[m_nodes[node].p1]);
            } else {
                ret[node] = std::make_shared<tree_descr_struc>(1);
            }
            return ret;
        }

694
    struct subtree_configuration_iterator {
695
696
697
698
699
        tree_descr_bool_map_type curs;
        const pedigree_tree_type* tree;
        tree_descr_type descr;
        int node;

700
        subtree_configuration_iterator()
701
702
703
            : curs(), tree(NULL), descr(), node(NONE)
        {}

704
705
        subtree_configuration_iterator&
            operator = (const subtree_configuration_iterator& other)
706
707
708
709
710
711
712
713
714
            {
                tree = other.tree;
                descr = other.descr;
                node = other.node;
                curs.clear();
                descr->reset_cursor(curs);
                return *this;
            }

715
        subtree_configuration_iterator(const pedigree_tree_type* t, int n, tree_descr_type d)
716
717
718
719
720
            : curs(), tree(t), descr(d), node(n)
        {
            descr->reset_cursor(curs);
        }

721
        subtree_configuration_iterator(const pedigree_tree_type* t, int n, tree_descr_type d, const tree_descr_bool_map_type& cursors_)
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
            : curs(cursors_), tree(t), descr(d), node(n)
        {}

        const std::vector<bool>
            cursors() const
            {
                std::vector<bool> ret(curs.size(), false);
                tree_descr_bool_map_type vis;
                descr->reset_visited(vis);
                descr->visit(tree->root(), *tree, curs, vis,
                        [] (int, bool, bool, bool, bool v) { return !v; },
                        [&] (int n, bool, bool, bool c) { ret[n] = c; }
                        );
                return ret;
            }

        std::vector<int>
            node_order(bool p_before=false, bool once=false) const
            {
                std::vector<int> ret;
                ret.reserve(tree->m_nodes.size());
                tree_descr_bool_map_type vis;
                descr->reset_visited(vis);
                if (p_before) {
                    descr->visit(node, *tree, curs, vis,
                                 [&] (int, bool, bool, bool, bool v) { return !(v && once); },
                                 [&](int node, bool, bool, bool) { ret.push_back(node); });
                } else {
                    descr->visit(node, *tree, curs, vis,
                                 [&] (int node, bool, bool, bool, bool v) { if (v && once) { return false; } ret.push_back(node); return true; },
                                 [&](int, bool, bool, bool) {});
                }
                return ret;
            }

        std::vector<int>
            leaf_order(bool once=false) const
            {
                std::vector<int> ret;
                ret.reserve(tree->m_nodes.size());
                tree_descr_bool_map_type vis;
                descr->reset_visited(vis);
                descr->visit(node, *tree, curs, vis,
                             [&] (int, bool, bool, bool, bool v) { return !(v && once); },
                             [&](int node, bool, bool, bool) { ret.push_back(node); });
                return ret;
            }

        bool
            next()
            {
                tree_descr_bool_map_type vis;
                descr->reset_visited(vis);
                return descr->next(curs, vis);
            }

        size_t
            size() const
            {
                tree_descr_bool_map_type vis;
                descr->reset_visited(vis);
                return descr->count_permutations(vis);
            }
    };

    int root() const { return *m_roots.begin(); }

789
790
    subtree_configuration_iterator
        configuration_iterator() const
791
792
793
794
795
        {
            int node = root();
            return {this, node, compute_descr(node)[node]};
        }

796
797
    subtree_configuration_iterator
        configuration_iterator(const std::vector<bool>& cursors) const;
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

    /* Only if there is exactly one root... */
    tree_descr_type root_descr() const
    {
        int r = root();
        return compute_descr(r)[r];
    }
};


inline
pedigree_tree_type::tree_descr_bool_map_type
make_cursors(const pedigree_tree_type::tree_descr_map_type& descr, const std::vector<bool>& cursors)
{
    pedigree_tree_type::tree_descr_bool_map_type ret;
    MSG_DEBUG("make_cursors... descr.size=" << descr.size() << " cursors.size=" << cursors.size());
    MSG_QUEUE_FLUSH();
    for (int i = 0; i < (int) descr.size(); ++i) {
        ret[descr.find(i)->second.get()] = cursors[i];
    }
    return ret;
}


inline
823
824
pedigree_tree_type::subtree_configuration_iterator
pedigree_tree_type::configuration_iterator(const std::vector<bool>& cursors) const
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
855
856
857
858
859
860
861
862
863
864
865
866
867
{
    int node = root();
    auto descr = compute_descr(node);
    tree_descr_bool_map_type curs = make_cursors(descr, cursors);
    return {this, node, descr[node], curs};
}


inline
std::map<int, int>
compute_tree_mapping(const std::vector<int>& o1, const std::vector<int>& o2)
{
    if (o1.size() != o2.size()) {
        MSG_DEBUG("NODE ORDER SIZES DON'T MATCH");
        return {};
    }
    std::map<int, int> ret;
    MSG_DEBUG("o1 " << o1);
    MSG_DEBUG("o2 " << o2);
    for (size_t i = 0; i < o1.size(); ++i) {
        auto it = ret.find(o1[i]);
        if (it == ret.end()) {
            ret[o1[i]] = o2[i];
        } else if (it->second != o2[i]) {
            MSG_DEBUG("MAPPING FAILED");
            return {};
        }
    }
    return ret;
}

struct expression_symmetries_type {
    std::vector<std::vector<bool>> symmetry_cursors;
    std::vector<std::vector<bool>> latent_symmetry_cursors;

    std::vector<std::vector<std::vector<int>>> input_cliques;
    std::vector<std::vector<std::vector<int>>> latent_input_cliques;

    const pedigree_tree_type* tree;

    expression_symmetries_type(const pedigree_tree_type& t)
        : symmetry_cursors(), latent_symmetry_cursors(), input_cliques(), latent_input_cliques(), tree(&t)
    {
868
        MSG_DEBUG_INDENT_EXPR("[EXP SYM TYPE] ");
869
        auto descr = tree->root_descr();
870
        auto spi = tree->configuration_iterator();
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
        auto ref = spi.node_order();
        std::map<int, size_t> leaf_idx;
        for (int i: tree->m_leaves) {
            size_t sz = leaf_idx.size();
            leaf_idx[i] = sz;
        }
        do {
            MSG_DEBUG("testing order");
            MSG_DEBUG("" << spi.node_order());
            MSG_DEBUG("" << ref);
            auto mapping = compute_tree_mapping(ref, spi.node_order());
            if (mapping.size()) {
                MSG_DEBUG("mapping: " << mapping);
                auto cursors = spi.cursors();

                /* determine cliques */
                std::vector<std::vector<int>> cliques;
                std::vector<bool> visited(tree->m_leaves.size(), false);
                for (int l: tree->m_leaves) {
                    if (visited[leaf_idx[l]]) { continue; }
                    cliques.emplace_back(1, l);
                    visited[leaf_idx[l]] = true;
                    while (!visited[leaf_idx[(l = mapping[l])]]) {
                        cliques.back().push_back(l);
                        visited[leaf_idx[l]] = true;
                    }
                }
                MSG_DEBUG("input cliques: ");
                for (const auto& c: cliques) {
                    MSG_DEBUG("  " << c);
                }

903
                if (cursors.back() && descr->LR) {
904
905
906
907
908
909
910
911
912
                    /* latent! */
                    latent_symmetry_cursors.push_back(cursors);
                    latent_input_cliques.push_back(cliques);
                } else {
                    symmetry_cursors.push_back(cursors);
                    input_cliques.push_back(cliques);
                }
            }
        } while (!spi.next());
913
        MSG_DEBUG_DEDENT;
914
915
916
917
918
919
920
921
922
923
924
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
950
951
952
953
954
955
956
    }

    std::vector<bool>
        test_input_permutability_in_symmetries(const std::vector<pedigree_tree_type::tree_descr_type>& input_descriptors)
        {
            return test_input_permutability_in_(input_cliques, input_descriptors);
        }

    std::vector<bool>
        test_input_permutability_in_latent_symmetries(const std::vector<pedigree_tree_type::tree_descr_type>& input_descriptors)
        {
            return test_input_permutability_in_(latent_input_cliques, input_descriptors);
        }

    std::vector<bool>
        test_input_permutability_in_(const std::vector<std::vector<std::vector<int>>>& all_cliques,
                                     const std::vector<pedigree_tree_type::tree_descr_type>& input_descriptors)
        {
            std::vector<bool> ret;

            for (const auto& cliques: all_cliques) {
                bool ok = true;
                for (const auto& clique: cliques) {
                    auto d1 = input_descriptors[clique[0]];
                    for (size_t i = 1; i < clique.size(); ++i) {
                        ok &= (*d1 == *input_descriptors[clique[i]]);
                    }
                }
                ret.push_back(ok);
            }

            return ret;
        }
};



struct expression_mapping_type {
    std::map<int, int> mapping;
    std::vector<bool> cursors;
private:
    const pedigree_tree_type* tree;
    const pedigree_tree_type* ref;
957
    pedigree_tree_type::subtree_configuration_iterator spi;
958
959
960
961
962
963
964
965

    expression_mapping_type()
        : mapping(), cursors(), tree(NULL), ref(NULL), spi()
    {}

    expression_mapping_type(const pedigree_tree_type* r, const pedigree_tree_type* t)
        : mapping(), cursors(), tree(t), ref(r), spi()
    {
966
967
        auto ref_order = ref->configuration_iterator().node_order();
        spi = tree->configuration_iterator();
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
995
996
997
998
999
1000
        do {
            mapping = compute_tree_mapping(ref_order, spi.node_order());
        } while (!mapping.size() && !spi.next());
        cursors = spi.cursors();
    }

public:

    friend
    expression_mapping_type
    create_mapping(const pedigree_tree_type& ref, const pedigree_tree_type& tree);
};

inline
expression_mapping_type
create_mapping(const pedigree_tree_type& ref, const pedigree_tree_type& tree)
{
    int rr = *ref.m_roots.begin();
    int tr = *tree.m_roots.begin();
    auto descr_ref = ref.compute_descr(rr)[rr];
    auto descr_tree = tree.compute_descr(tr)[tr];
    if (!(*descr_ref == *descr_tree)) {
        MSG_DEBUG("DESCRIPTORS DON'T MATCH");
        MSG_DEBUG("ref  " << descr_ref);
        MSG_DEBUG("tree " << descr_tree);
        return {};
    }
    return {&ref, &tree};
}


struct iterative_lumper {
    std::vector<int> bins;
For faster browsing, not all history is shown. View entire blame