pedigree.h 45 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
#ifndef _SPELL_BAYES_CSV_H_
#define _SPELL_BAYES_CSV_H_

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <utility>
11
#include <unordered_set>
12
13


Damien Leroux's avatar
Damien Leroux committed
14
15
/*#include "permutation.h"*/
/*#include "symmetry.h"*/
16
17
#include "geno_matrix.h"
#include "linear_combination.h"
Damien Leroux's avatar
Damien Leroux committed
18
#include "pedigree_tree.h"
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
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;
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
223
224
225
226


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)};
        }
    }
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    /*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);*/
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
    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;
            }
        };

};


418
419
420
421
422
423
424
/* TODO extraire l'arbre du pedigree
 * TODO opérations sur l'arbre :
 * TODO - insérer un nouveau noeud étant donné {P1, P2} (Pi étant soit néant soit un noeud existant)
 * TODO - extraire sous-arbre étant donné {RACINE, {FEUILLES}}
 * TODO - comparer deux arbres
 * TODO - pour deux arbres comparables, déterminer la rotation du second pour matcher le premier
 */
425
426
427
428
429
430
431
432

/*
 * pedigree_type: implements all facilities to compute proper geno_matrices for any pedigree, including reentrant individuals.
 */
struct pedigree_type : public archivable {
    /*
     * pedigree tree implementation
     */
Damien Leroux's avatar
Damien Leroux committed
433
    pedigree_tree_type tree;
434
435
436
437
438

    /*
     * pedigree tree metadata
     */
    typedef size_t geno_matrix_index_type;
Damien Leroux's avatar
Damien Leroux committed
439
    typedef int individual_index_type;
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    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::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<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;

460
461
462
463
464
465
466
467
468
469
470
    /*
     * overlump control
     */

    size_t max_states;

    /*
     * BN metadata
     */
    size_t n_alleles;

471
472
473
474
    /*
     * default ctor
     */
    pedigree_type()
Damien Leroux's avatar
Damien Leroux committed
475
476
477
        : tree(), node_generations(), ancestor_letters(), generation_names(),
          cache_gamete(), cache_geno(),
          max_states(NONE),
478
          n_alleles(1)
479
480
481
482
483
484
485
486
487
    {
        __init();
    }

    void __init()
    {
        generations.emplace_back();
    }

Damien Leroux's avatar
Damien Leroux committed
488
#if 0
489
    /*
490
     * prealloc ctor
491
492
493
     */
    pedigree_type(size_t n_ind)
    {
494
        n_alleles = 1;
Damien Leroux's avatar
Damien Leroux committed
495
        max_states = NONE;
496
497
498
499
500
501
        nodes.reserve(3 * n_ind);
        /*ind_generations.reserve(n_ind);*/
        ind_number_to_node_number.reserve(n_ind);
        __init();
    }

Damien Leroux's avatar
Damien Leroux committed
502
503
    size_t last_node_index() const { return tree.size() - 1; }
#endif
504

Damien Leroux's avatar
Damien Leroux committed
505
    individual_index_type spawn_gamete(const std::string& gamete_name, int parent_node)
506
    {
Damien Leroux's avatar
Damien Leroux committed
507
508
509
510
511
512
        int n = tree.add_node(parent_node);
        /*MSG_DEBUG_INDENT_EXPR("[compute " << gamete_name << " gamete] ");*/
        /*compute_generation(n);*/
        /*compute_LC(n);*/
        /*MSG_DEBUG_DEDENT;*/
        return n;
513
514
    }

515
516
    individual_index_type spawn(std::initializer_list<individual_index_type> parents)
    {
Damien Leroux's avatar
Damien Leroux committed
517
        individual_index_type ind = tree.next_ind_idx();
518
519
520
521
522
        switch (parents.size()) {
            case 0: /* ancestor */
                {
                    MSG_DEBUG_INDENT_EXPR("[compute gen #" << ind << "] ");
                    MSG_DEBUG("ANCESTOR");
Damien Leroux's avatar
Damien Leroux committed
523
524
525
526
                    int n = tree.add_node();
                    MSG_DEBUG("node=" << n << " ind=" << ind);
                    compute_generation(n);
                    compute_LC(n);
527
528
529
530
531
532
533
                    MSG_DEBUG_DEDENT;
                }
                break;
            case 1: /* doubling */
                {
                    MSG_DEBUG_INDENT_EXPR("[compute gen #" << ind << "] ");
                    MSG_DEBUG("DOUBLING");
Damien Leroux's avatar
Damien Leroux committed
534
535
536
537
538
539
                    individual_index_type p1 = *parents.begin();
                    int g1 = spawn_gamete("M", tree.ind2node(p1));
                    int n = tree.add_node(g1, g1);
                    MSG_DEBUG("node=" << n << " ind=" << ind);
                    compute_generation(n);
                    compute_LC(n);
540
541
542
543
544
545
546
547
548
                    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++;
Damien Leroux's avatar
Damien Leroux committed
549
                    int n1 = tree.ind2node(p1);
550
                    individual_index_type p2 = *i;
Damien Leroux's avatar
Damien Leroux committed
551
                    int n2 = tree.ind2node(p2);
552
                    /*MSG_DEBUG("p1=" << p1 << " p2=" << p2 << " n1=" << n1 << " n2=" << n2);*/
Damien Leroux's avatar
Damien Leroux committed
553
554
555
556
557
558
                    int g1 = spawn_gamete("M", n1);
                    int g2 = spawn_gamete("F", n2);
                    int n = tree.add_node(g1, g2);
                    MSG_DEBUG("node=" << n << " ind=" << ind);
                    compute_generation(n);
                    compute_LC(n);
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
                    MSG_DEBUG_DEDENT;
                }
                break;
            default:;
        };
        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({})); }

Damien Leroux's avatar
Damien Leroux committed
586
    void propagate_symmetries(int n, geno_matrix& gen)
587
    {
Damien Leroux's avatar
Damien Leroux committed
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
        std::vector<int> in, out;
        auto expr = tree.extract_expression(n, in, out);
        std::vector<pedigree_tree_type> input_trees;
        input_trees.reserve(in.size());
        for (int t: in) {
            input_trees.emplace_back(tree.extract_subtree(t));
        }
        symmetry_propagator sp(expr);
        gen.symmetries = sp.compute_propagated_symmetries(
                [&] (int i) -> const pedigree_tree_type& { MSG_DEBUG("request subtree for input #" << i); return input_trees[i]; },
                [&] (int node) -> const symmetry_group_type& { MSG_DEBUG("request symmetries for node #" << node); return get_node_gen(node)->symmetries; },
                [&] (int node) -> const symmetry_group_type& { MSG_DEBUG("request latent symmetries for node #" << node); return get_node_gen(node)->latent_symmetries; },
                gen.labels, gen.inf_mat,
                [this] (int node) -> MatrixXb { return get_node_gen(node)->collect.cast<bool>(); }
                );
        auto temp = sp.compute_propagated_latent_symmetries(
                [&] (int i) -> const pedigree_tree_type& { MSG_DEBUG("request subtree for input #" << i); return input_trees[i]; },
                [&] (int node) -> const symmetry_group_type& { MSG_DEBUG("request symmetries for node #" << node); return get_node_gen(node)->symmetries; },
                [&] (int node) -> const symmetry_group_type& { MSG_DEBUG("request latent symmetries for node #" << node); return get_node_gen(node)->latent_symmetries; },
                gen.labels, gen.inf_mat,
                [this] (int node) -> MatrixXb { return get_node_gen(node)->collect.cast<bool>(); }
                );
        MSG_DEBUG_INDENT_EXPR("[AFTER SYMMETRY PROPAGATION] ");
        MSG_DEBUG(temp);
        gen.latent_symmetries = temp - gen.symmetries;
        MSG_DEBUG(gen);
614
615
616
        MSG_DEBUG_DEDENT;
    }

Damien Leroux's avatar
Damien Leroux committed
617
    void compute_generation(int n)
618
    {
Damien Leroux's avatar
Damien Leroux committed
619
        MSG_DEBUG("Computing generation for node " << tree.make_node_label(n));
620
621
        MSG_DEBUG(render_tree());

Damien Leroux's avatar
Damien Leroux committed
622
623
        int np1 = tree.get_p1(n);
        int np2 = tree.get_p2(n);
624
625
626
        node_generations.emplace_back(generations.size());
        geno_matrix new_gen;
        geno_matrix_index_type* cached_gen = NULL;
Damien Leroux's avatar
Damien Leroux committed
627
        if (np1 == NONE && np2 == NONE) {
628
629
630
631
            /* ancestor */
            char l = 'a' + ancestor_letters.size();
            ancestor_letters[n] = l;
            new_gen = ancestor_matrix(l);
Damien Leroux's avatar
Damien Leroux committed
632
        } else if (np2 == NONE) {
633
634
            /* gamete */
            auto gp = node_generations[np1];
Damien Leroux's avatar
Damien Leroux committed
635
            auto& cache = cache_gamete;
636
637
638
639
640
641
            cached_gen = &cache[gp];
            if (*cached_gen) {
                MSG_DEBUG("GENERATION HAS ALREADY BEEN COMPUTED");
                node_generations[n] = *cached_gen;
                return;
            }
Damien Leroux's avatar
Damien Leroux committed
642
            new_gen = kronecker(*generations[gp], gamete);
643
644
            /*MSG_DEBUG("TMP GAMETE GEN");*/
            /*MSG_DEBUG(new_gen);*/
645
646
647
        } else {
            auto ngp1 = node_generations[np1];
            auto ngp2 = node_generations[np2];
Damien Leroux's avatar
Damien Leroux committed
648
649
650
            /*auto gp1 = generations[ngp1];*/
            /*auto gp2 = generations[ngp2];*/
            MSG_DEBUG("Child of " << tree.node2ind(tree.get_p1(np1)) << " and " << tree.node2ind(tree.get_p1(np2)));
651
652
653
654
655
656
657
658

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

Damien Leroux's avatar
Damien Leroux committed
659
660
            const auto& recompute = tree.get_recompute_vec(n);

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
            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);
Damien Leroux's avatar
Damien Leroux committed
682
            new_gen.variant = (tree[n].is_genotype()
683
                               ? Geno
Damien Leroux's avatar
Damien Leroux committed
684
                               : Gamete);
685
686
687
688
689
690
691
692
            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();

Damien Leroux's avatar
Damien Leroux committed
693
            /*if (!(ind_number_to_node_number.size() == 9 && tree.size() == 23)) {*/
694
                MSG_DEBUG("PROPAGATING SYMMETRIES");
695
                /*propagate_symmetries(new_gen, recompute, n);*/
696
697
                /*study_expression_symmetries(new_gen);*/
                /*complete_symmetries(new_gen);*/
698
699
                MSG_DEBUG("COMPUTING LATENT SYMMETRY");
            /*}*/
700
701
702
        }
        node_generations[n] = generations.size();
        generations.emplace_back(new geno_matrix());
703
704
        MSG_DEBUG("BEFORE LUMPING");
        MSG_DEBUG(new_gen);
705
        *generations.back() = lump(new_gen, max_states);
Damien Leroux's avatar
Damien Leroux committed
706
707
708
709
710
        if (tree[n].is_crossing()) {
            propagate_symmetries(n, *generations.back());
        } else if (tree[n].is_ancestor()) {
            generations.back()->symmetries = symmetry_group_type(generations.back()->labels);
        }
711
712
713
714
715
        /**node_generations[n] = lump(new_gen);*/
        if (cached_gen) {
            *cached_gen = node_generations[n];
        }
        MSG_DEBUG("DONE COMPUTING GENERATION FOR NODE #" << n);
Damien Leroux's avatar
Damien Leroux committed
716
        MSG_DEBUG_INDENT_EXPR("[RESULT " << tree.make_node_label(n) << "] ");
717
718
        MSG_DEBUG((*generations.back()));
        MSG_DEBUG_DEDENT;
719
        /*MSG_DEBUG((*generations[node_generations[n]]));*/
720
721
722
        MSG_DEBUG("=========================================================================");
    }

Damien Leroux's avatar
Damien Leroux committed
723
    void compute_LC(int n)
724
    {
Damien Leroux's avatar
Damien Leroux committed
725
        int p1 = tree.get_p1(n);
726
        std::vector<gencomb_type> lc;
Damien Leroux's avatar
Damien Leroux committed
727
728
        const geno_matrix& m = *generations[node_generations[n]];
        if (p1 == NONE) {
729
730
            lc.emplace_back(1.);
        } else {
Damien Leroux's avatar
Damien Leroux committed
731
            lc = eval_vector(tree.size() - 1, tree.get_recompute_vec(n), &pedigree_type::get_LC, reentrant_LC);
732
733
734
735
736
        }
        VectorLC tmp(lc.size()), lumped;
        for (size_t i = 0; i < lc.size(); ++i) {
            tmp(i) = lc[i];
        }
737
        lumped = m.collect.cast<gencomb_type>() * tmp;
738
739
740
        LC.emplace_back(lumped);
        MSG_DEBUG("Computed new LC:");
        MSG_DEBUG(LC.back());
741

Damien Leroux's avatar
Damien Leroux committed
742
        if (p1 == NONE) {
743
744
745
            return;
        }

Damien Leroux's avatar
Damien Leroux committed
746
747
        std::vector<genotype_comb_type> glc = eval_vector(tree.size() - 1, tree.get_recompute_vec(n), &pedigree_type::get_GLC, reentrant_GLC);
        std::vector<bn_label_type> bn_labels = eval_vector(tree.size() - 1, tree.get_recompute_vec(n), &pedigree_type::get_bn_labels, reentrant_bn_label);
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
        MSG_DEBUG("glc.size = " << glc.size());
        MSG_DEBUG("bn_labels.size = " << bn_labels.size());

        std::map<bn_label_type, genotype_comb_type> glc_map;
        for (size_t i = 0; i < bn_labels.size(); ++i) {
            glc_map[bn_labels[i]] += glc[i];
        }

        MSG_DEBUG("Corresponding GLC:");
        std::vector<genotype_comb_type> expanded_glc;
        for (const auto& kv: glc_map) {
            MSG_DEBUG("" << kv.first << " = " << kv.second);
            for (const auto& elem: kv.second.m_combination) {
                expanded_glc.emplace_back();
                expanded_glc.back().m_combination.emplace_back(elem);
                auto& keys = expanded_glc.back().m_combination.back().keys.keys;
Damien Leroux's avatar
Damien Leroux committed
764
                keys.emplace_back(tree.size() - 1, kv.first);
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
                std::sort(keys.begin(), keys.end());
            }
        }

        MSG_DEBUG("Sparse GLC coefs:");
        for (const auto& g: expanded_glc) {
            MSG_DEBUG("" << g);
        }

        std::map<size_t, std::map<bn_label_type, genotype_comb_type>> messages;
        size_t n_nodes = expanded_glc.front().m_combination.front().keys.keys.size();
        for (const auto& lc: expanded_glc) {
            const auto& elems = lc.m_combination.front();
            const auto& keys = elems.keys.keys;
            for (size_t ni = 0; ni < n_nodes; ++ni) {
                genotype_comb_type tmp;
                tmp.m_combination.emplace_back(elems.coef);
                auto& msg_keys = tmp.m_combination.back().keys.keys;
                size_t i;
                for (i = 0; i < ni; ++i) {
                    msg_keys.emplace_back(keys[i]);
786
                }
787
788
789
790
791
792
793
794
795
796
797
                for (++i; i < n_nodes; ++i) {
                    msg_keys.emplace_back(keys[i]);
                }
                messages[keys[ni].parent][keys[ni].state] += tmp;
            }
        }

        for (const auto& kv1: messages) {
            MSG_DEBUG("MESSAGE TOWARDS #" << kv1.first);
            for (const auto& kv2: kv1.second) {
                MSG_DEBUG("" << kv2.first << " = " << kv2.second);
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
            }
        }
    }


    static MatrixXd kron(const MatrixXd& m1, const MatrixXd& m2)
    {
        return kroneckerProduct(m1, m2);
    }

    static MatrixXd kron_d(const MatrixXd& m1, const MatrixXd& m2)
    {
        return kroneckerProduct(m1, MatrixXd::Identity(m2.rows(), m2.cols()))
             + kroneckerProduct(MatrixXd::Identity(m1.rows(), m1.cols()), m2);
    }

    char ancestor_letter(size_t a) const
    {
Damien Leroux's avatar
Damien Leroux committed
816
        auto i = ancestor_letters.find(tree.ind2node(a));
817
818
819
        return i == ancestor_letters.end() ? 0 : i->second;
    }

820
    geno_matrix_index_type get_gen_index(size_t ind) const
821
    {
Damien Leroux's avatar
Damien Leroux committed
822
        return node_generations[tree.ind2node(ind)];
823
824
825
826
827
828
829
830
    }

    const std::shared_ptr<geno_matrix> get_gen(size_t ind) const
    {
        return generations[get_gen_index(ind)];
    }

    const geno_matrix&
Damien Leroux's avatar
Damien Leroux committed
831
        get_geno_matrix_by_individual(size_t ind) const { return *generations[node_generations[tree.ind2node(ind)]]; }
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
    const std::set<geno_matrix_index_type>&
        get_geno_matrices_by_name(const std::string& name) const { return geno_matrix_by_generation_name.find(name)->second; }
    const std::string&
        get_generation_name_by_individual(size_t ind) const { return *generation_name_by_individual.find(ind)->second; }

    const std::shared_ptr<geno_matrix> get_node_gen(size_t node) const
    {
        return generations[node_generations[node]];
    }

    typedef MatrixXd (* KronFunc) (const MatrixXd&, const MatrixXd&);

    template <typename FIELD_TYPE>
    FIELD_TYPE eval(size_t node, FIELD_TYPE geno_matrix::* field, KronFunc func, const std::vector<bool>& recompute, std::vector<bool>& visited) const
    {
        /*scoped_indent _;*/
848
        /*MSG_DEBUG("eval node " << node);*/
849
        if (visited[node]) {
850
            /*MSG_DEBUG("already visited => 1");*/
851
852
853
            return make_one<FIELD_TYPE>::_(func == kron_d);
        }
        visited[node] = true;
Damien Leroux's avatar
Damien Leroux committed
854
        if (recompute[node] || tree[node].is_gamete()) {
855
            FIELD_TYPE ret, m1, m2;
Damien Leroux's avatar
Damien Leroux committed
856
857
858
859
860
861
862
863
            if (tree[node].is_genotype()) {
                m1 = eval(tree.get_p1(node), field, func, recompute, visited);
                m2 = eval(tree.get_p2(node), field, func, recompute, visited);
                ret = func(m1, m2);
            } else {
                m1 = eval(tree.get_p1(node), field, func, recompute, visited);
                ret = func(m1, gamete.*field);
            }
864
865
            return ret;
        } else {
866
867
            /*MSG_DEBUG("using actual matrix");*/
            /*MSG_DEBUG((*generations[node_generations[node]]).*field);*/
868
869
870
871
872
873
874
875
876
877
878
879
            return (*generations[node_generations[node]]).*field;
        }
        return {};
    }

    template <typename VALUE_TYPE>
    struct vector_iterator {
        typedef std::vector<VALUE_TYPE> vector_type;
        vector_type data;
        typename vector_type::const_iterator begin, end, cur;
        vector_iterator() : data(), begin(data.begin()), end(data.end()), cur(data.begin()) {}
        vector_iterator(const vector_type& l) : data(l), begin(data.begin()), end(data.end()), cur(data.begin()) {}
880
        void reset() { cur = begin = data.begin(); end = data.end(); }
881
882
883
884
885
        void start() { cur = begin; }
        bool next() { if (at_end()) return true; return ++cur == end; }
        bool at_end() const { return cur == end; }
        size_t size() const { return end - begin; }
        const VALUE_TYPE& operator * () const { return *cur; }
886
        const VALUE_TYPE* operator -> () const { return &*cur; }
887
888
889
890
891
892
893
894
895
896
897
    };

    typedef vector_iterator<label_type> label_iterator;
    typedef vector_iterator<symmetry_table_type> symmetry_iterator;

    template <typename VALUE_TYPE>
        VALUE_TYPE eval_one(size_t node, const std::vector<bool>& recompute, const std::vector<vector_iterator<VALUE_TYPE>>& iterators,
                            const std::vector<size_t>& node_to_iterator, std::vector<bool>& visited,
                            VALUE_TYPE (&eval_reent)(size_t, const VALUE_TYPE&),
                            std::vector<VALUE_TYPE>& reent) const
        {
898
            /*scoped_indent _(MESSAGE("[eval #" << node << "] "));*/
899
900
901
            if (visited[node]) {
                auto ret = eval_reent(node, reent[node]);
                /*ret = eval_reent(node, iterators[node_to_iterator[node]]);*/
902
                /*MSG_DEBUG("reentrant; " << ret);*/
903
904
905
                return ret;
            } else {
                visited[node] = true;
Damien Leroux's avatar
Damien Leroux committed
906
907
908
909
910
911
912
913
914
915
916
917
918
                if (recompute[node] || tree[node].is_gamete()) {
                    if (tree[node].is_genotype()) {
                        /*MSG_DEBUG("eval p1");*/
                        auto p1 = eval_one(tree.get_p1(node), recompute, iterators, node_to_iterator, visited, eval_reent, reent);
                        /*MSG_DEBUG("p1 = " << p1);*/
                        /*MSG_DEBUG("eval p2");*/
                        auto p2 = eval_one(tree.get_p2(node), recompute, iterators, node_to_iterator, visited, eval_reent, reent);
                        /*MSG_DEBUG("p2 = " << p2);*/
                        reent[node] = p1 * p2;
                    } else {
                        reent[node] = eval_one(tree.get_p1(node), recompute, iterators, node_to_iterator, visited, eval_reent, reent)
                                    * *iterators[node_to_iterator[node]];
                    }
919
920
921
922
                } else {
                    reent[node] = *iterators[node_to_iterator[node]];
                }
            }
923
924
            /*MSG_DEBUG("ret = " << reent[node]);*/
            /*MSG_QUEUE_FLUSH();*/
925
926
927
928
929
930
931
932
933
934
935
936
            return reent[node];
        }

    struct skip_eval_exception {};

    template <typename VALUE_TYPE>
        VALUE_TYPE eval_one(size_t node, const std::vector<bool>& recompute, const std::vector<vector_iterator<VALUE_TYPE>>& iterators,
                            const std::vector<size_t>& node_to_iterator, std::vector<bool>& visited,
                            VALUE_TYPE (&eval_reent)(size_t, const VALUE_TYPE&),
                            std::vector<VALUE_TYPE>& reent,
                            bool (&skip_predicate)(const VALUE_TYPE&)) const
        {
937
            /*scoped_indent _(MESSAGE("[eval #" << node << "] "));*/
938
939
940
            if (visited[node]) {
                auto ret = eval_reent(node, reent[node]);
                /*ret = eval_reent(node, iterators[node_to_iterator[node]]);*/
941
                /*MSG_DEBUG("reentrant; " << ret);*/
942
943
944
                return ret;
            } else {
                visited[node] = true;
Damien Leroux's avatar
Damien Leroux committed
945
946
947
948
949
950
951
952
953
954
955
956
957
                if (recompute[node] || tree[node].is_gamete()) {
                    if (tree[node].is_genotype()) {
                        /*MSG_DEBUG("eval p1");*/
                        auto p1 = eval_one(tree.get_p1(node), recompute, iterators, node_to_iterator, visited, eval_reent, reent);
                        /*MSG_DEBUG("p1 = " << p1);*/
                        /*MSG_DEBUG("eval p2");*/
                        auto p2 = eval_one(tree.get_p2(node), recompute, iterators, node_to_iterator, visited, eval_reent, reent);
                        /*MSG_DEBUG("p2 = " << p2);*/
                        reent[node] = p1 * p2;
                    } else {
                        reent[node] = eval_one(tree.get_p1(node), recompute, iterators, node_to_iterator, visited, eval_reent, reent)
                                    * *iterators[node_to_iterator[node]];
                    }
958
959
960
961
                } else {
                    reent[node] = *iterators[node_to_iterator[node]];
                }
            }
962
            /*MSG_DEBUG("ret = " << reent[node]);*/
963
964
965
966
967
968
            /*if (skip_predicate(reent[node])) {*/
                /*throw skip_eval_exception();*/
            /*}*/
            return reent[node];
        }

969
970
971
972
973
    static label_type reentrant_label(size_t, const label_type& l) { return l; }
    static bn_label_type reentrant_bn_label(size_t, const bn_label_type& l) { return l; }
    static gencomb_type reentrant_LC(size_t, const gencomb_type& lc) { return lc; }
    static genotype_comb_type reentrant_GLC(size_t, const genotype_comb_type& lc) { return lc; }
    static symmetry_table_type reentrant_sym(size_t, const symmetry_table_type& S) { return {permutation_type::identity(1), S.letters}; }
974
975
976
977
978
979
980
981
982
983

    template <typename VALUE_TYPE>
        void init_iterators_rec(size_t node, const std::vector<bool>& recompute, std::vector<bool>& visited,
                                std::vector<vector_iterator<VALUE_TYPE>>& iterators, std::vector<size_t>& node_to_iterator,
                                std::vector<VALUE_TYPE> (pedigree_type:: *accessor)(bool, size_t, const geno_matrix&) const) const
        {
            if (visited[node]) {
                return;
            }
            visited[node] = true;
Damien Leroux's avatar
Damien Leroux committed
984
985
986
987
988
989
990
991
992
993
994
            if (recompute[node] || tree[node].is_gamete()) {
                init_iterators_rec(tree.get_p1(node), recompute, visited, iterators, node_to_iterator, accessor);
                if (tree[node].is_genotype()) {
                    init_iterators_rec(tree.get_p2(node), recompute, visited, iterators, node_to_iterator, accessor);
                } else {
                    node_to_iterator[node] = iterators.size();
                    iterators.emplace_back((this->*accessor)(true, node, gamete));
                    MSG_DEBUG("GAMETE");
                    MSG_DEBUG("" << (this->*accessor)(true, node, gamete));
                }
#if 0
995
996
997
998
999
1000
                switch (nodes[node].type) {
                    case NTGenotype:
                        break;
                    case NTGamete:
                        break;
                    case NTDoubling:
For faster browsing, not all history is shown. View entire blame