pedigree.h 115 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef _SPELL_BAYES_CSV_H_
#define _SPELL_BAYES_CSV_H_

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <utility>


#include "geno_matrix.h"
#include "linear_combination.h"


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
struct bn_label_type {
    char first;
    char second;
    char first_allele;
    char second_allele;
    bn_label_type() : first(0), second(0), first_allele(0), second_allele(0) {}
    bn_label_type(int) : first(0), second(0), first_allele(0), second_allele(0) {}
    bn_label_type(char f, char s, char fa, char sa)
        : first(f), second(s), first_allele(fa), second_allele(sa)
    {}

    friend std::ostream& operator << (std::ostream& os, const bn_label_type& bl)
    {
        if (bl.second != GAMETE_EMPTY) {
            return os << bl.first << ((int) bl.first_allele) << bl.second << ((int) bl.second_allele);
        } else {
            return os << bl.first << ((int) bl.first_allele);
        }
    }

    bool operator < (const bn_label_type& other) const
    {
        /*return first < other.first || (first == other.first*/
            /*&& (second < other.second || (second == other.second*/
            /*&& (first_allele < other.first_allele || (first_allele == other.first_allele*/
            /*&& second_allele < other.second_allele)))));*/
        return (*(int*)this) < (*(int*) &other);
    }

    bool operator == (const bn_label_type& other) const
    {
        return (*(int*)this) == (*(int*) &other);
    }
};

typedef combination_type<size_t, bn_label_type> genotype_comb_type;
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
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


template <typename Arg>
int read_field(std::stringstream& s, char sep, Arg& arg)
{
    std::string field;
    std::getline(s, field, sep);
    /*MSG_DEBUG("CSV FIELD |" << field << "|");*/
    std::stringstream ss(field);
    ss >> arg;
    return 0;
}


#define do_with_arg_pack(_expr) do { using _ = int[]; (void)_{0, ((_expr), void(), 0)...}; } while(0)

template <typename... Args>
void read_csv_line(std::istream& is, char sep, Args&... args)
{
    std::string line;
    std::getline(is, line);
    /*MSG_DEBUG("CSV LINE |" << line << "|");*/
    std::stringstream ss(line);
    do_with_arg_pack(read_field(ss, sep, args));
}





struct pedigree_item {
    std::string gen_name;
    int id;
    int p1;
    int p2;

    pedigree_item(const char* gn, int i, int a, int b)
        : gen_name(gn), id(i), p1(a), p2(b)
    {}

    pedigree_item(std::istream& is, char field_sep=';')
        : gen_name()
    {
        id = p1 = p2 = 0;
        read_csv_line(is, field_sep, gen_name, id, p1, p2);
        if (id == p1 && id == p2 && id == 0) {
            return;
        }
        if (id <= p1 || id <= p2) {
            throw std::runtime_error("Bad ID! ID must be greater than p1 AND p2");
            /*MSG_DEBUG("BAD ID!! " << id << " must be greater than " << p1 << " AND " << p2);*/
        }
    }

    bool is_ancestor() const { return p1 == 0 && p2 == 0; }
    bool is_self() const { return p1 > 0 && p1 == p2; }
    bool is_cross() const { return p1 > 0 && p2 > 0 && p1 != p2; }
    bool is_dh() const { return p1 != p2 && p1 >= 0 && p2 >= 0 && (p1 * p2) == 0; }
    bool is_bullshit() const { return !(is_ancestor() || is_self() || is_cross() || is_dh()); }
};


std::vector<pedigree_item>
read_csv(const std::string& pedigree_file, char field_sep=';');



typedef std::map<size_t, size_t> ancestor_list_type;


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


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


ancestor_list_type operator / (const ancestor_list_type& a, const ancestor_list_type& restr)
{
    ancestor_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_list_type operator % (const ancestor_list_type& a, const ancestor_list_type& restr)
{
    ancestor_list_type ret;
    for (const auto& kv: a) {
        if (restr.find(kv.first) != restr.end()) {
            ret.emplace(kv);
        }
    }
    return ret;
}


ancestor_list_type operator - (const ancestor_list_type& a, const ancestor_list_type& restr)
{
    ancestor_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_list_type operator * (const ancestor_list_type& a, size_t weight)
{
    ancestor_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_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;
}


label_type operator * (label_type a, label_type b)
{
    label_type ret;
    if (a.second == GAMETE_EMPTY) {
        ret = {a.first, b.first};
    } else {
        if (b.second == GAMETE_EMPTY) {
            ret = {SELECT(a, b.first), GAMETE_EMPTY};
        } else {
            ret = {SELECT(a, b.first), SELECT(a, b.second)};
        }
    }
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
    /*MSG_DEBUG("" << a << " * " << b << " = " << ret);*/
    return ret;
}


#define SELECT_A(__p, __b) ((__b) == GAMETE_R ? (__p).second_allele : (__p).first_allele)

bn_label_type operator * (bn_label_type a, bn_label_type b)
{
    bn_label_type ret;
    if (a.second == GAMETE_EMPTY) {
        ret = {a.first, b.first, a.first_allele, b.first_allele};
    } else {
        if (b.second == GAMETE_EMPTY) {
            ret = {SELECT(a, b.first), GAMETE_EMPTY, SELECT_A(a, b.first), 0};
        } else {
            ret = {SELECT(a, b.first), SELECT(a, b.second), SELECT_A(a, b.first), SELECT_A(a, b.second)};
        }
    }
    /*MSG_DEBUG("" << a << " * " << b << " = " << ret);*/
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
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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
    return ret;
}


template <typename F> struct make_one;
template <> struct make_one<MatrixXd> {
    static MatrixXd& _(bool der) {
        static MatrixXd one = MatrixXd::Ones(1, 1);
        static MatrixXd zero = MatrixXd::Zero(1, 1);
        return der ? zero : one;
    }
};
template <> struct make_one<VectorXd> {
    static VectorXd& _(bool der) {
        static VectorXd one = VectorXd::Ones(1);
        static VectorXd zero = VectorXd::Zero(1);
        return der ? zero : one;
    }
};





struct archivable {
    template <typename COMP>
        std::ostream& save_component(std::ostream& os, COMP&& component) const
        {
            long start_offset = os.tellp();
            os.write((const char*) &start_offset, sizeof(long));
            save(os, component);
            long end_offset = os.tellp();
            os.seekp(start_offset);
            os.write((const char*) &end_offset, sizeof(long));
            os.seekp(end_offset);
            return os;
        }

    template <typename COMP>
        std::istream& load_component(std::istream& is, COMP&& component, bool skip) const
        {
            long skip_offset;
            is.read((char*) &skip_offset, sizeof(long));
            if (skip) {
                is.seekg(skip_offset);
            } else {
                load(is, component);
            }
            return is;
        }

    template <typename COMP, bool IS_INTEGRAL>
        struct impl__;

    template <typename COMP>
        struct impl : public impl__<COMP, std::is_integral<COMP>::value> {};

    template <typename INTEGRAL>
        struct impl__<INTEGRAL, true> {
            static void load(std::istream& is, INTEGRAL& i) { is.read((char*) &i, sizeof(INTEGRAL)); }
            static void save(std::ostream& os, INTEGRAL i) { os.write((const char*) &i, sizeof(INTEGRAL)); }
        };

    template <typename CONTAINER_OR_OBJECT>
        struct impl__<CONTAINER_OR_OBJECT, false> {

        template <typename value_type>
            static void load(std::istream& is, std::vector<value_type>& ctr)
            {
                size_t n;
                is.read((char*) &n, sizeof(size_t));
                for (; n > 0; --n) {
                    ctr.emplace_back();
                    impl<value_type>::load(is, ctr.back());
                }
            }

        template <typename K, typename V>
            static void load(std::istream& is, std::map<K, V>& ctr)
            {
                size_t n;
                is.read((char*) &n, sizeof(size_t));
                for (; n > 0; --n) {
                    K key; V value;
                    impl<K>::load(is, key);
                    impl<V>::load(is, value);
                    ctr.emplace(key, value);
                }
            }

        template <typename value_type>
            static void load(std::istream& is, std::set<value_type>& ctr)
            {
                size_t n;
                is.read((char*) &n, sizeof(size_t));
                for (; n > 0; --n) {
                    value_type value;
                    impl<value_type>::load(is, value);
                    ctr.emplace(value);
                }
            }

        template <typename value_type>
            static void save(std::ostream& os, std::vector<value_type>& ctr)
            {
                size_t n = ctr.size();
                os.write((const char*) &n, sizeof(size_t));
                auto i = ctr.begin();
                auto j = ctr.end();
                for (; i != j; ++i) {
                    impl<value_type>::save(os, *i);
                }
            }

        template <typename value_type>
            static void save(std::ostream& os, std::set<value_type>& ctr)
            {
                size_t n = ctr.size();
                os.write((const char*) &n, sizeof(size_t));
                auto i = ctr.begin();
                auto j = ctr.end();
                for (; i != j; ++i) {
                    impl<value_type>::save(os, *i);
                }
            }

        template <typename K, typename V>
            static void save(std::ostream& os, std::map<K, V>& ctr)
            {
                typedef typename std::map<K, V>::value_type value_type;
                size_t n = ctr.size();
                os.write((const char*) &n, sizeof(size_t));
                auto i = ctr.begin();
                auto j = ctr.end();
                for (; i != j; ++i) {
                    impl<value_type>::save(os, *i);
                }
            }

        template <typename A, typename B>
            static void load(std::istream& is, std::pair<A, B>& pair)
            {
                impl<A>::load(is, pair.first);
                impl<B>::load(is, pair.second);
            }

        template <typename A, typename B>
            static void save(std::ostream& os, const std::pair<A, B>& pair)
            {
                impl<A>::save(os, pair.first);
                impl<B>::save(os, pair.second);
            }

        template <typename COMP>
            std::istream& load(std::istream& is, COMP&& component) const
            {
                component.load(is);
                return is;
            }

        template <typename COMP>
            std::ostream& save(std::ostream& os, COMP&& component) const
            {
                component.save(os);
                return os;
            }
        };

};



/*
 * pedigree_type: implements all facilities to compute proper geno_matrices for any pedigree, including reentrant individuals.
 */
struct pedigree_type : public archivable {
    /*
     * pedigree tree implementation
     */
    enum node_type {NTGenotype, NTGamete, NTDoubling};

    struct pedigree_node {
        node_type type;
        size_t p1, p2;
        pedigree_node(node_type t, size_t a, size_t b) : type(t), p1(a), p2(b) {}
        pedigree_node(std::istream& is) : type(), p1(), p2() { load(is); }

        std::ostream& save(std::ostream& os) const
        {
            os.write((const char*) &type, sizeof(node_type));
            os.write((const char*) &p1, sizeof(size_t));
            os.write((const char*) &p2, sizeof(size_t));
            return os;
        }

        std::istream& load(std::istream& is) const
        {
            is.read((char*) &type, sizeof(node_type));
            is.read((char*) &p1, sizeof(size_t));
            is.read((char*) &p2, sizeof(size_t));
            return is;
        }
    };

    std::vector<pedigree_node> nodes;

    /*
     * pedigree tree metadata
     */
    typedef size_t geno_matrix_index_type;
    typedef size_t individual_index_type;
    std::vector<std::shared_ptr<geno_matrix>> generations;
    std::vector<geno_matrix_index_type> node_generations;
    std::map<individual_index_type, char> ancestor_letters;
    std::map<geno_matrix_index_type, std::string> generation_names;

    std::map<size_t, individual_index_type> node_number_to_ind_number;
    std::vector<size_t> ind_number_to_node_number;

    std::vector<std::vector<bool>> must_recompute;
    std::vector<VectorLC> LC;

    /*
     * geno_matrix cache to avoid recomputing identical generations
     */
    std::map<geno_matrix_index_type, geno_matrix_index_type> cache_gamete;
    std::map<geno_matrix_index_type, geno_matrix_index_type> cache_doubling;
    std::map<std::pair<geno_matrix_index_type, geno_matrix_index_type>, geno_matrix_index_type> cache_geno;

    /*
     * geno_matrix database
     */

    std::map<std::string, std::set<geno_matrix_index_type>> geno_matrix_by_generation_name;
    std::map<std::string, std::vector<individual_index_type>> individuals_by_generation_name;
    std::map<individual_index_type, const std::string*> generation_name_by_individual;

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
    /*
     * overlump control
     */

    size_t max_states;

    /*
     * experimental feature
     */

    bool avoid_recursion;

    /*
     * BN metadata
     */
    size_t n_alleles;

497
498
499
500
501
502
    /*
     * default ctor
     */
    pedigree_type()
        : nodes(), node_generations(), ancestor_letters(), generation_names(),
          node_number_to_ind_number(), ind_number_to_node_number(),
503
504
505
506
          cache_gamete(), cache_doubling(), cache_geno(),
          max_states((size_t) -1),
          avoid_recursion(false),
          n_alleles(1)
507
508
509
510
511
512
513
514
515
516
517
518
    {
        __init();
    }

    void __init()
    {
        ind_number_to_node_number.push_back((size_t) -1);
        generations.emplace_back();
        /*ind_generations.emplace_back();*/
    }

    /*
519
     * prealloc ctor
520
521
522
     */
    pedigree_type(size_t n_ind)
    {
523
524
525
        n_alleles = 1;
        max_states = (size_t) -1;
        avoid_recursion = false;
526
527
528
529
530
531
532
533
        nodes.reserve(3 * n_ind);
        /*ind_generations.reserve(n_ind);*/
        ind_number_to_node_number.reserve(n_ind);
        __init();
    }

    size_t last_node_index() const { return nodes.size() - 1; }

534
535
536
537
538
539
540
541
542
543
544
545
546
547
    individual_index_type spawn_gamete(node_type nt, const std::string& gamete_name, size_t parent_node)
    {
        nodes.emplace_back(nt, parent_node, (size_t) -1);
        if (gamete_name == "doubling") {
            MSG_DEBUG_INDENT_EXPR("[compute doubling gamete] ");
        } else {
            MSG_DEBUG_INDENT_EXPR("[compute gamete " << gamete_name << "] ");
        }
        compute_generation();
        compute_LC();
        MSG_DEBUG_DEDENT;
        return last_node_index();
    }

548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    individual_index_type spawn(std::initializer_list<individual_index_type> parents)
    {
        individual_index_type ind = ind_number_to_node_number.size();
        switch (parents.size()) {
            case 0: /* ancestor */
                {
                    MSG_DEBUG_INDENT_EXPR("[compute gen #" << ind << "] ");
                    MSG_DEBUG("ANCESTOR");
                    nodes.emplace_back(NTGenotype, (size_t) -1, (size_t) -1);
                    node_number_to_ind_number[nodes.size() - 1] = ind;
                    MSG_DEBUG("node=" << (nodes.size() - 1) << " ind=" << ind);
                    compute_generation();
                    compute_LC();
                    MSG_DEBUG_DEDENT;
                }
                break;
            case 1: /* doubling */
                {
                    MSG_DEBUG_INDENT_EXPR("[compute gen #" << ind << "] ");
                    MSG_DEBUG("DOUBLING");
                    individual_index_type p1 = *parents.begin();
                    size_t np1 = ind_number_to_node_number[p1];
570
                    /*
571
572
573
574
575
                    nodes.emplace_back(NTDoubling, np1, (size_t) -1);
                    MSG_DEBUG_INDENT_EXPR("[compute doubling gamete] ");
                    compute_generation();
                    MSG_DEBUG_DEDENT;
                    size_t g1 = last_node_index();
576
577
                    */
                    size_t g1 = spawn_gamete(NTDoubling, "doubling", np1);
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
                    nodes.emplace_back(NTGenotype, g1, (size_t) -1);
                    node_number_to_ind_number[nodes.size() - 1] = ind;
                    MSG_DEBUG("node=" << (nodes.size() - 1) << " ind=" << ind);
                    compute_generation();
                    compute_LC();
                    MSG_DEBUG_DEDENT;
                }
                break;
            case 2: /* crossing & selfing */
                {
                    MSG_DEBUG_INDENT_EXPR("[compute gen #" << ind << "] ");
                    MSG_DEBUG("CROSSING/SELFING");
                    auto i = parents.begin();
                    individual_index_type p1 = *i++;
                    size_t n1 = ind_number_to_node_number[p1];
593
                    individual_index_type p2 = *i;
594
                    size_t n2 = ind_number_to_node_number[p2];
595
596
597
                    /*MSG_DEBUG("p1=" << p1 << " p2=" << p2 << " n1=" << n1 << " n2=" << n2);*/
                    size_t g1 = spawn_gamete(NTGamete, "M", n1);
                    size_t g2 = spawn_gamete(NTGamete, "F", n2);
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
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
                    nodes.emplace_back(NTGenotype, g1, g2);
                    node_number_to_ind_number[nodes.size() - 1] = ind;
                    MSG_DEBUG("node=" << (nodes.size() - 1) << " ind=" << ind);
                    compute_generation();
                    compute_LC();
                    MSG_DEBUG_DEDENT;
                }
                break;
            default:;
        };
        size_t ret = nodes.size() - 1;
        /*size_t ind = node_number_to_ind_number.size() + 1;*/
        /*node_number_to_ind_number.emplace(ret, ind);*/
        /*node_number_to_ind_number[ret] = ind;*/
        ind_number_to_node_number.push_back(ret);
        MSG_DEBUG("i2n " << ind_number_to_node_number);
        MSG_DEBUG("n2i " << node_number_to_ind_number);
        MSG_DEBUG("n2i(" << ret << ")=" << node_number_to_ind_number[ret]);
        MSG_DEBUG("i2n(" << ind << ")=" << ind_number_to_node_number[ind]);
        /*MSG_QUEUE_FLUSH();*/
        return ind;
    }

    individual_index_type crossing(individual_index_type p1, individual_index_type p2) { return spawn({p1, p2}); }
    individual_index_type selfing(individual_index_type p1) { return spawn({p1, p1}); }
    individual_index_type dh(individual_index_type p1) { return spawn({p1}); }
    individual_index_type ancestor() { return spawn({}); }

    individual_index_type fill_db(const std::string& name, individual_index_type ind)
    {
        geno_matrix_by_generation_name[name].insert(get_gen_index(ind)).first;
        individuals_by_generation_name[name].push_back(ind);
        auto it = individuals_by_generation_name.find(name);
        generation_name_by_individual[ind] = &it->first;
        return ind;
    }

    individual_index_type crossing(const std::string& name, individual_index_type p1, individual_index_type p2) { return fill_db(name, spawn({p1, p2})); }
    individual_index_type selfing(const std::string& name, individual_index_type p1) { return fill_db(name, spawn({p1, p1})); }
    individual_index_type dh(const std::string& name, individual_index_type p1) { return fill_db(name, spawn({p1})); }
    individual_index_type ancestor(const std::string& name) { return fill_db(name, spawn({})); }

    std::map<size_t, size_t>
        count_ancestors(size_t node)
        {
            std::map<size_t, size_t> ret;
            if (node == (size_t) -1) {
                return ret;
            }
            std::vector<size_t> stack;
            stack.reserve(nodes.size());
            if (nodes[node].p1 != (size_t) -1) {
                stack.push_back(nodes[node].p1);
            }
            if (nodes[node].p2 != (size_t) -1) {
                stack.push_back(nodes[node].p2);
            }
            while (stack.size()) {
                size_t n = stack.back();
                stack.pop_back();
                if (nodes[n].p1 != (size_t) -1) {
                    stack.push_back(nodes[n].p1);
                }
                if (nodes[n].p2 != (size_t) -1) {
                    stack.push_back(nodes[n].p2);
                }
                ++ret[n];
            }
            return ret;
        }

    std::map<size_t, size_t>
        rank_ancestors(size_t node)
        {
            std::vector<bool> visited(nodes.size(), false);
            std::map<size_t, size_t> ret;
            rank_ancestors_rec(node, visited, ret);
            return ret;
        }

    void rank_ancestors_rec(size_t node, std::vector<bool>& visited, std::map<size_t, size_t>& ranks)
    {
        size_t p1 = nodes[node].p1;
        size_t p2 = nodes[node].p2;

        size_t r1 = 0;
        size_t r2 = 0;

        if (visited[node]) {
            return;
        }

        if (p1 != (size_t) -1) {
            rank_ancestors_rec(p1, visited, ranks);
            r1 = ranks[p1];
        }

        if (p2 != (size_t) -1) {
            rank_ancestors_rec(p2, visited, ranks);
            r2 = ranks[p2];
        }

        ranks[node] = std::max(r1, r2) + 1;
        visited[node] = true;
    }

    std::vector<size_t> ordered_ancestors(size_t node, const ancestor_list_type& anc)
    {
        auto ranks = rank_ancestors(node);
        std::vector<size_t> order;
        order.reserve(anc.size());
        for (const auto& kv: anc) { order.push_back(kv.first); }
        std::sort(order.begin(), order.end(), [&] (size_t a, size_t b) { return ranks[a] > ranks[b]; });
        return order;
    }

    ancestor_list_type cleanup_reentrants(size_t node)
    {
        auto A = count_ancestors(node);
        auto Ap1 = count_ancestors(nodes[node].p1);
        auto Ap2 = count_ancestors(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_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);
        }
        MSG_DEBUG_DEDENT;

        return ret;
    }

    static std::set<letter_permutation_type>& uniq_permutations() { static std::set<letter_permutation_type> _; return _; }

    static bool skip_sym(const symmetry_table_type& S) { return !uniq_permutations().insert(S.letters).second; }

    void propagate_symmetries(geno_matrix& new_gen, const std::vector<bool>& recompute, size_t n) const
    {
        uniq_permutations().clear();
        auto all_sym = eval_vector(n, recompute, &pedigree_type::get_symmetries, reentrant_sym, skip_sym);
        auto all_sym2 = eval_vector(n, recompute, &pedigree_type::get_latent_symmetries, reentrant_sym, skip_sym);
        all_sym.insert(all_sym.end(), all_sym2.begin(), all_sym2.end());
        std::set<letter_permutation_type> uniq_sym;
        std::vector<symmetry_table_type> group;
        group.reserve(all_sym.size());
        for (const auto& sym: all_sym) {
            MSG_DEBUG_INDENT_EXPR("[testing symmetry] ");
764
765
            MSG_DEBUG("" << sym.letters);
            /*MSG_DEBUG(sym.dump(new_gen.labels, false));*/
766
767
768
769
770
771
            MSG_DEBUG_DEDENT;
            /*if (uniq_sym.find(sym.letters) != uniq_sym.end()) {*/
                /*MSG_DEBUG("skip!");*/
                /*continue;*/
            /*}*/
            MatrixXd tmp = sym.matrix().cast<double>();
772
773
774
            /*MSG_DEBUG(MATRIX_SIZE(tmp));*/
            /*MSG_DEBUG(MATRIX_SIZE(new_gen.collect));*/
            /*MSG_DEBUG(MATRIX_SIZE(new_gen.inf_mat));*/
775
            MSG_DEBUG("consistent? " << sym.is_consistent(new_gen.labels));
776
            /*MSG_DEBUG((tmp.transpose() * new_gen.inf_mat * tmp - new_gen.inf_mat));*/
777
778
            if (sym.is_consistent(new_gen.labels) && (tmp.transpose() * new_gen.inf_mat * tmp - new_gen.inf_mat).isZero(FLOAT_TOL)) {
                MSG_DEBUG("Found a consistent symmetry");
779
                /*MSG_DEBUG("" << sym.dump(new_gen.labels, false));*/
780
781
782
783
                uniq_sym.insert(sym.letters);
                group.emplace_back(sym);
            }
        }
784
        /*MSG_DEBUG("Have " << group.size() << " symmetries.");*/
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
811
812
813
814
815
816
        for (size_t i = 0; i < group.size(); ++i) {
            for (size_t j = i; j < group.size(); ++j) {
                /*auto S = group[i] * group[j];*/
                symmetry_table_type S(group[i].matrix() * group[j].matrix(), group[i].letters.compose(group[j].letters));
                if (uniq_sym.find(S.letters) == uniq_sym.end()) {
                    uniq_sym.emplace(S.letters);
                    group.push_back(S);
                }
            }
        }
        MSG_DEBUG("Have grown to " << group.size() << " symmetries.");
        new_gen.symmetries.assign(group.begin(), group.end());
    }


    void compute_generation()
    {
        size_t n = nodes.size() - 1;

        MSG_DEBUG("Computing generation for node " << make_node_label(n));
        MSG_DEBUG(render_tree());

        size_t np1 = nodes[n].p1;
        size_t np2 = nodes[n].p2;
        node_generations.emplace_back(generations.size());
        geno_matrix new_gen;
        geno_matrix_index_type* cached_gen = NULL;
        if (np1 == ((size_t) -1) && np2 == ((size_t) -1)) {
            /* ancestor */
            char l = 'a' + ancestor_letters.size();
            ancestor_letters[n] = l;
            new_gen = ancestor_matrix(l);
817
818
819
            /*MSG_DEBUG("# # # #");*/
            /*MSG_DEBUG("" << new_gen.symmetries);*/
            /*MSG_DEBUG("# # # #");*/
820
821
822
823
            /*MSG_QUEUE_FLUSH();*/
            must_recompute.emplace_back();
        } else if (np2 == (size_t) -1) {
            static MatrixXb gsm = MatrixXb::Ones(2, 2) - MatrixXb::Identity(2, 2);
824
            /*size_t p1 = node_number_to_ind_number[np1];*/
825
826
827
828
829
830
831
832
833
834
835
            /* gamete */
            auto gp = node_generations[np1];
            auto& cache = nodes[n].type == NTGamete ? cache_gamete : cache_doubling;
            must_recompute.emplace_back(nodes.size(), false);
            must_recompute.back().back() = true;
            cached_gen = &cache[gp];
            if (*cached_gen) {
                MSG_DEBUG("GENERATION HAS ALREADY BEEN COMPUTED");
                node_generations[n] = *cached_gen;
                return;
            }
836
837
            /*MSG_DEBUG("Gametization of");*/
            /*MSG_DEBUG((*generations[gp]));*/
838
839
840
841
842
843
844
            new_gen = kronecker(*generations[gp], nodes[n].type == NTGamete ? gamete : doubling_gamete);
            propagate_symmetries(new_gen, must_recompute.back(), n);
            if (generations[gp]->latent_symmetries.size()) {
                for (const auto& ls: generations[gp]->latent_symmetries) {
                    new_gen.symmetries.emplace_back(kroneckerProduct(ls.matrix(), gsm), ls.letters);
                }
            }
845
846
            /*MSG_DEBUG("TMP GAMETE GEN");*/
            /*MSG_DEBUG(new_gen);*/
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
        } else {
            auto ngp1 = node_generations[np1];
            auto ngp2 = node_generations[np2];
            auto gp1 = generations[ngp1];
            auto gp2 = generations[ngp2];
            size_t p1 = node_number_to_ind_number[nodes[np1].p1];
            size_t p2 = node_number_to_ind_number[nodes[np2].p1];
            MSG_DEBUG("Child of " << p1 << " and " << p2);

            auto all_ancestors = count_ancestors(n);
            auto rall = reentrants(all_ancestors);

            auto tmp_ancestors = all_ancestors;

            must_recompute.emplace_back(nodes.size(), false);
            std::vector<bool>& recompute = must_recompute.back();

            auto tmp_reent = cleanup_reentrants(n);
            MSG_DEBUG("cleaned reentrants: " << tmp_reent);

            for (size_t i = 0; i < nodes.size(); ++i) {
                recompute[i] = (tmp_reent % count_ancestors(i)).size() > 0;
                MSG_DEBUG("must_recompute " << make_node_label(i) << " = " << recompute[i]);
            }
            recompute.back() = true;

            auto all_descr_entries = all_ancestors;
            all_descr_entries[n] = 1;
            auto descr = compute_descr(all_descr_entries);
876
877
878
879
880
            /*for (size_t i = 0; i < recompute.size(); ++i) {*/
                /*if (recompute[i]) {*/
                    /*MSG_DEBUG("descr(#" << i << ") = " << (*descr[i]));*/
                /*}*/
            /*}*/
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
922

            cached_gen = &cache_geno[{ngp1, ngp2}];
            if (*cached_gen) {
                MSG_DEBUG("GENERATION HAS ALREADY BEEN COMPUTED");
                node_generations[n] = *cached_gen;
                return;
            }

            std::vector<bool> visited_clear(recompute.size(), false);
            std::vector<bool> visited;

            visited = visited_clear;
            MSG_DEBUG("COMPUTING INF_MAT");
            new_gen.inf_mat = eval(n, &geno_matrix::inf_mat, &pedigree_type::kron_d, recompute, visited);
            MSG_DEBUG(MATRIX_SIZE(new_gen.inf_mat));
            visited = visited_clear;
            MSG_DEBUG("COMPUTING DIAG");
            new_gen.diag = eval(n, &geno_matrix::diag, &pedigree_type::kron_d, recompute, visited);
            visited = visited_clear;
            MSG_DEBUG("COMPUTING STAT_DIST");
            new_gen.stat_dist = eval(n, &geno_matrix::stat_dist, &pedigree_type::kron, recompute, visited);
            visited = visited_clear;
            MSG_DEBUG("COMPUTING P");
            new_gen.p = eval(n, &geno_matrix::p, &pedigree_type::kron, recompute, visited);
            visited = visited_clear;
            MSG_DEBUG("COMPUTING P_INV");
            new_gen.p_inv = eval(n, &geno_matrix::p_inv, &pedigree_type::kron_d, recompute, visited);
            /*new_gen.labels = eval_labels(n, recompute, visited_clear);*/
            new_gen.labels = eval_vector(n, recompute, &pedigree_type::get_labels, reentrant_label);
            new_gen.variant = (nodes[n].type == NTGenotype
                               ? Geno
                               : nodes[n].type == NTGamete
                                 ? Gamete
                                 : DoublingGamete);
            new_gen.dispatch = new_gen.collect = MatrixXd::Identity(new_gen.diag.size(), new_gen.diag.size());
            MSG_DEBUG(MATRIX_SIZE(new_gen.inf_mat));
            MSG_DEBUG(MATRIX_SIZE(new_gen.p));
            MSG_DEBUG(MATRIX_SIZE(new_gen.p_inv));
            MSG_DEBUG(MATRIX_SIZE(new_gen.diag));
            MSG_DEBUG("new_gen.labels.size()=" << new_gen.labels.size());
            MSG_QUEUE_FLUSH();

923
924
            /*if (!(ind_number_to_node_number.size() == 9 && nodes.size() == 23)) {*/
                MSG_DEBUG("PROPAGATING SYMMETRIES");
925
                /*propagate_symmetries(new_gen, recompute, n);*/
926
927
928
929
930
931
932
933
934
935
936
937
938
                study_expression_symmetries(new_gen);
                complete_symmetries(new_gen);
                MSG_DEBUG("COMPUTING LATENT SYMMETRY");
                if (descr[np1] == descr[np2]) {
                    tree_descr_bool_map_type cursL, cursR, visL, visR;
                    MSG_DEBUG("Potential latent symmetry");
                    descr[np1]->reset_visited(visL);
                    MSG_DEBUG("Left sub-tree has " << descr[np1]->count_permutations(visL) << " permutations");
                    descr[np2]->reset_visited(visR);
                    MSG_DEBUG("Right sub-tree has " << descr[np2]->count_permutations(visR) << " permutations");
                    MSG_DEBUG("Permutations of left sub-tree leaves:");
                    descr[np1]->reset_cursor(cursL);
                    /*bool found_bijection = false;*/
939
940
941
942
943
944
945
946
947
948
949
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
995
996
997
998
999
1000
                    /*bool ok = false;*/
                    if (0)
                    {
                        MSG_DEBUG("testing permutation_iterator");
                        auto sub_descr = truncate_descr(descr, recompute, n);
                        MSG_DEBUG("RECOMPUTE " << recompute);
                        MSG_DEBUG("sub_descr");
                        for (const auto& kv: sub_descr) {
                            MSG_DEBUG(std::left << std::setw(10) << make_node_label(kv.first) << "   " << kv.second << " [" << descr[kv.first] << ']');
                        }
                        subtree_permutation_iterator spi(this, n, sub_descr);
                        while (spi()) {
                            /*std::string asL = spi.asL();*/
                            /*std::string asR = spi.asR();*/
                            MSG_DEBUG('[' << spi.nsL << "] <-> [" << spi.nsR << ']');
                        }
                        MSG_DEBUG("done testing permutation_iterator");
                    }

                    subtree_permutation_iterator spi(this, n, descr);
                    while (spi()) {
                        std::string asL = spi.asL();
                        std::string asR = spi.asR();

                        letter_permutation_type lp;
                        for (size_t i = 0; i < asL.size(); ++i) {
                            lp.table[asL[i]] = asR[i];
                            lp.table[asR[i]] = asL[i];
                        }

                        if (std::find_if(new_gen.symmetries.begin(), new_gen.symmetries.end(),
                                    [&](const symmetry_table_type& s) {
                                    MSG_DEBUG("COMPARING");
                                    MSG_DEBUG("" << s.letters);
                                    MSG_DEBUG("VS");
                                    MSG_DEBUG("" << lp);
                                    return s.letters == lp; })
                                == new_gen.symmetries.end()) {
                            MSG_DEBUG("Found bijection: " << asL << " <-> " << asR);
                            MatrixXb permutL = spi.permutL();
                            MatrixXb permutR = spi.permutR();
                            MSG_DEBUG(__FILE__ << ':' << __LINE__);
                            MatrixXb permut = kroneckerProduct(permutL, permutR);

                            if (permut.cols() != new_gen.cols()) {
                                MSG_DEBUG("WRONG PERMUT SIZE!");
                                MSG_DEBUG(MATRIX_SIZE(permut));
                                MSG_DEBUG(MATRIX_SIZE(new_gen.inf_mat));
                                /*ok = false;*/
                                break;
                            }
                            MSG_DEBUG(__FILE__ << ':' << __LINE__);
                            MatrixXb latsym = generate_lozenge(permutR.cols(), permutL.cols(), permut);
                            MSG_DEBUG(__FILE__ << ':' << __LINE__);
                            symmetry_table_type temp(latsym, lp);
                            /*MSG_DEBUG("PUTATIVE LATENT SYMMETRY");*/
                            /*MSG_DEBUG("" << temp.dump(new_gen.labels, true));*/
                            if (permut != permut.transpose()) {
                                MSG_DEBUG("HAVE PERMUT != T(PERMUT)");
                            }
                            MSG_DEBUG(__FILE__ << ':' << __LINE__);
                            if (temp.is_consistent(new_gen.labels, true)) {
For faster browsing, not all history is shown. View entire blame