pedigree.h 56.7 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
#include "bayes/output.h"
20
21


22
23
24
25
26
27
28
29
30
31
32
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)
    {}

33
34
35
    int compact() const { return *(int*) this; }
    int& compact() { return *(int*) this; }

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    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);
    }
58
59
60
61
62

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

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


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;


136
inline
137
138
139
140
141
142
143
144
145
146
147
148
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;
}


149
inline
150
151
152
153
154
155
156
157
158
159
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;
}


160
inline
161
162
163
164
165
166
167
168
169
170
171
172
173
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;
}


174
inline
175
176
177
178
179
180
181
182
183
184
185
186
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;
}


187
inline
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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;
}


203
inline
204
205
206
207
208
209
210
211
212
213
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;
}


214
inline
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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;
}


231
#if 0
232
233
234
235
236
237
238
239
240
241
242
243
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)};
        }
    }
244
245
246
    /*MSG_DEBUG("" << a << " * " << b << " = " << ret);*/
    return ret;
}
247
#endif
248
249
250
251


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

252
inline
253
254
255
256
257
258
259
260
261
262
263
264
265
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);*/
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
    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;
    }
};


287
288
289
290
291
292
293
294
295
296
template <class DERIVED>
struct rw_any {
    bool fourcc(std::ifstream& ifs, const char* cc)
    {
        if (check_fourcc(ifs, cc)) {
            MSG_ERROR("File is not valid or has been corrupted", "");
            return true;
        }
        return false;
    }
297

298
299
300
301
302
    bool fourcc(std::ofstream& ofs, const char* cc)
    {
        write_fourcc(ofs, cc);
        return false;
    }
303

304
    virtual ~rw_any() {}
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
    DERIVED& ref() { return *dynamic_cast<DERIVED*>(this); }

    void operator () (std::ifstream& ifs, std::string& s) { s = read_str(ifs); }
    void operator () (std::ofstream& ofs, const std::string& s) { write_str(ofs, s); }

    void operator () (std::ifstream& ifs, char& i) { i = read_char(ifs); }
    void operator () (std::ofstream& ofs, char i) { write_char(ofs, i); }

    void operator () (std::ifstream& ifs, int& i) { i = read_int(ifs); }
    void operator () (std::ofstream& ofs, int i) { write_int(ofs, i); }

    void operator () (std::ifstream& ifs, bool& i) { i = !!read_char(ifs); }
    void operator () (std::ofstream& ofs, bool i) { write_char(ofs, i); }

    void operator () (std::ifstream& ifs, double& i) { i = read_double(ifs); }
    void operator () (std::ofstream& ofs, double i) { write_double(ofs, i); }

    void operator () (std::ifstream& ifs, size_t& i) { i = read_size(ifs); }
    void operator () (std::ofstream& ofs, size_t i) { write_size(ofs, i); }

    void operator () (std::ifstream& ifs, label_type& l) { l = {read_char(ifs), read_char(ifs)}; }
    void operator () (std::ofstream& ofs, const label_type& l) { write_char(ofs, l.first()); write_char(ofs, l.second()); }

    void operator () (std::ifstream& ifs, bn_label_type& l) { l.compact() = read_int(ifs); }
    void operator () (std::ofstream& ofs, const bn_label_type& l) { write_int(ofs, l.compact()); }

    template <typename V>
        void operator () (std::ifstream& ifs, std::set<V>& vec)
334
        {
335
336
337
338
339
340
341
342
            if (fourcc(ifs, "OSET")) { return; }
            size_t sz = read_size(ifs);
            vec.clear();
            for (size_t i = 0; i < sz; ++i) {
                V tmp;
                ref() (ifs, tmp);
                vec.emplace(tmp);
            }
343
344
        }

345
346
    template <typename V>
        void operator () (std::ofstream& ofs, const std::set<V>& vec)
347
        {
348
349
350
351
            if (fourcc(ofs, "OSET")) { return; }
            write_size(ofs, vec.size());
            for (const auto& e: vec) {
                ref() (ofs, e);
352
353
354
355
            }
        }


356
357
358
359
360
361
362
363
364
365
366
367
    template <typename V>
        void operator () (std::ifstream& ifs, std::unordered_set<V>& vec)
        {
            if (fourcc(ifs, "USET")) { return; }
            size_t sz = read_size(ifs);
            vec.clear();
            for (size_t i = 0; i < sz; ++i) {
                V tmp;
                ref() (ifs, tmp);
                vec.emplace(tmp);
            }
        }
368

369
370
371
372
373
374
375
376
377
    template <typename V>
        void operator () (std::ofstream& ofs, const std::unordered_set<V>& vec)
        {
            if (fourcc(ofs, "USET")) { return; }
            write_size(ofs, vec.size());
            for (const auto& e: vec) {
                ref() (ofs, e);
            }
        }
378

379
    void operator () (std::ifstream& ifs, std::vector<bool>::reference i) { i = !!read_char(ifs); }
380

381
382
383
384
385
386
387
388
389
390
    template <typename V, typename A>
        void operator () (std::ifstream& ifs, std::vector<V, A>& vec)
        {
            if (fourcc(ifs, "VECT")) { return; }
            size_t sz = read_size(ifs);
            vec.clear();
            vec.reserve(sz);
            for (size_t i = 0; i < sz; ++i) {
                vec.emplace_back();
                ref() (ifs, vec.back());
391
            }
392
        }
393

394
395
396
397
398
399
400
    template <typename V, typename A>
        void operator () (std::ofstream& ofs, const std::vector<V, A>& vec)
        {
            if (fourcc(ofs, "VECT")) { return; }
            write_size(ofs, vec.size());
            for (const auto& e: vec) {
                ref() (ofs, e);
401
            }
402
        }
403

404
405
406
407
408
409
410
411
412
413
414
415
    template <typename K, typename V, typename A, typename C>
        void operator () (std::ifstream& ifs, std::map<K, V, A, C>& map)
        {
            if (fourcc(ifs, "MAP ")) { return; }
            size_t count = read_size(ifs);
            map.clear();
            for (size_t i = 0; i < count; ++i) {
                K key;
                V value;
                ref() (ifs, key);
                ref() (ifs, value);
                map.emplace(std::move(key), std::move(value));
416
            }
417
        }
418

419
420
421
422
423
424
425
426
    template <typename K, typename V, typename A, typename C>
        void operator () (std::ofstream& ofs, const std::map<K, V, A, C>& map)
        {
            if (fourcc(ofs, "MAP ")) { return; }
            write_size(ofs, map.size());
            for (const auto& kv: map) {
                ref() (ofs, kv.first);
                ref() (ofs, kv.second);
427
            }
428
        }
429

430
431
    template <typename SCALAR, int ROW, int COL, int C, int D, int E>
        void operator () (std::ifstream& ifs, Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat) { read_matrix(ifs, mat); }
432

433
434
    template <typename SCALAR, int ROW, int COL, int C, int D, int E>
        void operator () (std::ofstream& ofs, const Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat) { write_matrix(ofs, mat); }
435

436
437
    void operator () (std::ifstream& ifs, geno_matrix& mat) { read_geno_matrix(ifs, mat); }
    void operator () (std::ofstream& ofs, geno_matrix& mat) { write_geno_matrix(ofs, mat); }
438

439
440
441
442
443
444
445
446
447
    void operator () (std::ifstream& ifs, std::shared_ptr<geno_matrix>& ptr)
    {
        ptr.reset();
        ptr = std::make_shared<geno_matrix>();
        ref() (ifs, *ptr);
        if (!ptr->size()) {
            ptr.reset();
        }
    }
448

449
450
451
452
453
454
455
456
457
458
    void operator () (std::ofstream& ofs, const std::shared_ptr<geno_matrix>& ptr)
    {
        if (ptr) {
            ref() (ofs, *ptr.get());
        } else {
            geno_matrix _;
            ref() (ofs, _);
        }
    }
};
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
struct rw_base : public rw_any<rw_base> {
    virtual ~rw_base() {}
    using rw_any<rw_base>::fourcc;
    using rw_any<rw_base>::ref;
    using rw_any<rw_base>::operator ();
};

template <typename PARENT_TYPE, typename STATE_TYPE>
struct rw_comb : public rw_any<rw_comb<PARENT_TYPE, STATE_TYPE>> {
    typedef combination_type<PARENT_TYPE, STATE_TYPE> comb_type;

    virtual ~rw_comb() {}

    using rw_any<rw_comb<PARENT_TYPE, STATE_TYPE>>::fourcc;
    using rw_any<rw_comb<PARENT_TYPE, STATE_TYPE>>::ref;
    using rw_any<rw_comb<PARENT_TYPE, STATE_TYPE>>::operator ();

    void operator () (std::ifstream& fs, typename comb_type::key_type& key) { ref() (fs, key.parent); ref() (fs, key.state); }

    void operator () (std::ofstream& fs, const typename comb_type::key_type& key) { ref() (fs, key.parent); ref() (fs, key.state); }

    void operator () (std::ifstream& fs, typename comb_type::key_list& keys) { ref() (fs, keys.keys); }

    void operator () (std::ofstream& fs, const typename comb_type::key_list& keys) { ref() (fs, keys.keys); }

    void operator () (std::ifstream& fs, typename comb_type::element_type& elem) { ref() (fs, elem.keys); ref() (fs, elem.coef); }

    void operator () (std::ofstream& fs, const typename comb_type::element_type& elem) { ref() (fs, elem.keys); ref() (fs, elem.coef); }

    void operator () (std::ifstream& fs, comb_type& comb)
    {
        if (fourcc(fs, "COMB")) { return; }
        ref() (fs, comb.m_combination);
    }

    void operator () (std::ofstream& fs, const comb_type& comb)
    {
        if (fourcc(fs, "COMB")) { return; }
        ref() (fs, comb.m_combination);
    }
};


struct rw_tree : public rw_any<rw_tree> {
    virtual ~rw_tree() {}

    using rw_any<rw_tree>::fourcc;
    using rw_any<rw_tree>::ref;
    using rw_any<rw_tree>::operator ();

    void operator () (std::ifstream& fs, pedigree_tree_type::node_type& node) { ref() (fs, node.p1); ref() (fs, node.p2); }
    void operator () (std::ofstream& fs, const pedigree_tree_type::node_type& node) { ref() (fs, node.p1); ref() (fs, node.p2); }

    void operator () (std::ifstream& fs, pedigree_tree_type& tree)
    {
        ref() (fs, tree.m_leaves);
        ref() (fs, tree.m_roots);
        ref() (fs, tree.m_nodes);
        ref() (fs, tree.m_must_recompute);
        ref() (fs, tree.m_node_number_to_ind_number);
        ref() (fs, tree.m_original_ordering);
    }

    void operator () (std::ofstream& fs, const pedigree_tree_type& tree)
    {
        ref() (fs, tree.m_leaves);
        ref() (fs, tree.m_roots);
        ref() (fs, tree.m_nodes);
        ref() (fs, tree.m_must_recompute);
        ref() (fs, tree.m_node_number_to_ind_number);
        ref() (fs, tree.m_original_ordering);
    }
533
534
535
};


536
537
538
539
540
541
542
/* 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
 */
543
544
545
546

/*
 * pedigree_type: implements all facilities to compute proper geno_matrices for any pedigree, including reentrant individuals.
 */
547
struct pedigree_type {
548
549
550
    /*
     * pedigree tree implementation
     */
Damien Leroux's avatar
Damien Leroux committed
551
    pedigree_tree_type tree;
552
553
554
555
556

    /*
     * pedigree tree metadata
     */
    typedef size_t geno_matrix_index_type;
Damien Leroux's avatar
Damien Leroux committed
557
    typedef int individual_index_type;
558
559
560
561
    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;
562
    /*std::vector<VectorLC> LC;*/
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577

    /*
     * 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;

578
579
580
581
582
583
584
585
586
587
588
    /*
     * overlump control
     */

    size_t max_states;

    /*
     * BN metadata
     */
    size_t n_alleles;

589
590
591
592
593
594
595
596
597
598
599
600
601
    /*
     * Metadata for XML output and recreating command line
     */
    std::string filename;

    /*
     * Actual output: LC and factors for bayesian network
     */
    std::vector<std::vector<gencomb_type>> LC;
    std::vector<std::vector<std::map<bn_label_type, genotype_comb_type>>> factor_messages;
    std::vector<std::vector<size_t>> individuals_in_factors;
    /* i-th element means the i-th variable receives a message through this factor from variables in genotype_comb_type:keys */

602
603
604
605
    /*
     * default ctor
     */
    pedigree_type()
Damien Leroux's avatar
Damien Leroux committed
606
607
608
        : tree(), node_generations(), ancestor_letters(), generation_names(),
          cache_gamete(), cache_geno(),
          max_states(NONE),
609
610
611
612
          n_alleles(1),
          filename("<none>"),
          LC(),
          factor_messages()
613
614
615
616
617
618
619
620
621
    {
        __init();
    }

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

Damien Leroux's avatar
Damien Leroux committed
622
#if 0
623
    /*
624
     * prealloc ctor
625
626
627
     */
    pedigree_type(size_t n_ind)
    {
628
        n_alleles = 1;
Damien Leroux's avatar
Damien Leroux committed
629
        max_states = NONE;
630
631
632
633
634
635
        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
636
637
    size_t last_node_index() const { return tree.size() - 1; }
#endif
638

639
    individual_index_type spawn_gamete(const std::string&, int parent_node)
640
    {
Damien Leroux's avatar
Damien Leroux committed
641
        int n = tree.add_node(parent_node);
642
        node_generations.emplace_back(node_generations[parent_node]);
Damien Leroux's avatar
Damien Leroux committed
643
644
645
646
647
        /*MSG_DEBUG_INDENT_EXPR("[compute " << gamete_name << " gamete] ");*/
        /*compute_generation(n);*/
        /*compute_LC(n);*/
        /*MSG_DEBUG_DEDENT;*/
        return n;
648
649
    }

650
    individual_index_type spawn(const std::string& generation_name, std::initializer_list<individual_index_type> parents)
651
    {
Damien Leroux's avatar
Damien Leroux committed
652
        individual_index_type ind = tree.next_ind_idx();
653
654
655
656
657
        switch (parents.size()) {
            case 0: /* ancestor */
                {
                    MSG_DEBUG_INDENT_EXPR("[compute gen #" << ind << "] ");
                    MSG_DEBUG("ANCESTOR");
Damien Leroux's avatar
Damien Leroux committed
658
659
                    int n = tree.add_node();
                    MSG_DEBUG("node=" << n << " ind=" << ind);
660
                    compute_generation(generation_name, n);
661
                    compute_LC(n);
662
663
664
665
666
667
668
                    MSG_DEBUG_DEDENT;
                }
                break;
            case 1: /* doubling */
                {
                    MSG_DEBUG_INDENT_EXPR("[compute gen #" << ind << "] ");
                    MSG_DEBUG("DOUBLING");
Damien Leroux's avatar
Damien Leroux committed
669
670
671
672
                    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);
673
674
                    compute_generation(generation_name, n);
                    compute_LC(n);
Damien Leroux's avatar
Damien Leroux committed
675
                    /*compute_data_for_bn(n);*/
676
677
678
679
680
681
682
683
684
                    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
685
                    int n1 = tree.ind2node(p1);
686
                    individual_index_type p2 = *i;
Damien Leroux's avatar
Damien Leroux committed
687
                    int n2 = tree.ind2node(p2);
688
                    /*MSG_DEBUG("p1=" << p1 << " p2=" << p2 << " n1=" << n1 << " n2=" << n2);*/
Damien Leroux's avatar
Damien Leroux committed
689
690
691
692
                    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);
693
694
                    compute_generation(generation_name, n);
                    compute_LC(n);
Damien Leroux's avatar
Damien Leroux committed
695
                    /*compute_data_for_bn(n);*/
696
697
698
699
700
701
702
703
                    MSG_DEBUG_DEDENT;
                }
                break;
            default:;
        };
        return ind;
    }

704
705
706
707
    /*individual_index_type crossing(std::string& generation_name, individual_index_type p1, individual_index_type p2) { return spawn(generation_name, {p1, p2}); }*/
    /*individual_index_type selfing(std::string& generation_name, individual_index_type p1) { return spawn(generation_name, {p1, p1}); }*/
    /*individual_index_type dh(std::string& generation_name, individual_index_type p1) { return spawn(generation_name, {p1}); }*/
    /*individual_index_type ancestor(std::string& generation_name) { return spawn(generation_name, {}); }*/
708
709
710
711
712
713
714
715
716
717

    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;
    }

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

Damien Leroux's avatar
Damien Leroux committed
723
    void propagate_symmetries(int n, geno_matrix& gen)
724
    {
725
        MSG_DEBUG_INDENT_EXPR("[propagate symmetries #" << n << "] ");
Damien Leroux's avatar
Damien Leroux committed
726
727
728
729
730
731
732
        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));
        }
733
734
735
736
737
738
739
740
741
742
743
        /*auto recompute = tree.get_deep_recompute_vec(n);*/
        /*MSG_DEBUG("RECOMPUTE: " << recompute);*/
        auto get_lumper
            = [&, this] (int node) -> MatrixXb
            {
                /*if (tree[node].is_gamete() || recompute[node]) {*/
                    /*MSG_DEBUG("NIL lumper for node #" << node << " because" << (recompute[node] && tree[node].is_gamete() ? " recompute flag is set and it is a gamete" : tree[node].is_gamete() ? " it is a gamete" : " recompute flag is set"));*/
                    /*return {};*/
                /*}*/
                return get_node_gen(node)->collect.cast<bool>();
            };
Damien Leroux's avatar
Damien Leroux committed
744
        symmetry_propagator sp(expr);
745
        MSG_DEBUG_INDENT_EXPR("[SYMMETRIES] ");
Damien Leroux's avatar
Damien Leroux committed
746
747
748
749
750
        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,
751
                get_lumper
Damien Leroux's avatar
Damien Leroux committed
752
                );
753
754
        MSG_DEBUG_DEDENT;
        MSG_DEBUG_INDENT_EXPR("[LATENT SYMMETRIES] ");
Damien Leroux's avatar
Damien Leroux committed
755
756
757
758
759
        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,
760
                get_lumper
Damien Leroux's avatar
Damien Leroux committed
761
                );
762
        MSG_DEBUG_DEDENT;
Damien Leroux's avatar
Damien Leroux committed
763
764
        MSG_DEBUG(temp);
        gen.latent_symmetries = temp - gen.symmetries;
765
        MSG_DEBUG_INDENT_EXPR("[AFTER SYMMETRY PROPAGATION] ");
Damien Leroux's avatar
Damien Leroux committed
766
        MSG_DEBUG(gen);
767
        MSG_DEBUG_DEDENT;
768
        MSG_DEBUG_DEDENT;
769
770
    }

771
    void compute_generation(const std::string& generation_name, int n)
772
    {
Damien Leroux's avatar
Damien Leroux committed
773
        MSG_DEBUG("Computing generation for node " << tree.make_node_label(n));
774
        /*MSG_DEBUG(render_tree());*/
775

Damien Leroux's avatar
Damien Leroux committed
776
777
        int np1 = tree.get_p1(n);
        int np2 = tree.get_p2(n);
778
779
780
        node_generations.emplace_back(generations.size());
        geno_matrix new_gen;
        geno_matrix_index_type* cached_gen = NULL;
Damien Leroux's avatar
Damien Leroux committed
781
        if (np1 == NONE && np2 == NONE) {
782
783
784
            /* ancestor */
            char l = 'a' + ancestor_letters.size();
            ancestor_letters[n] = l;
785
            new_gen = ancestor_matrix(generation_name, l);
Damien Leroux's avatar
Damien Leroux committed
786
        } else if (np2 == NONE) {
787
788
            /* gamete */
            auto gp = node_generations[np1];
Damien Leroux's avatar
Damien Leroux committed
789
            auto& cache = cache_gamete;
790
791
792
793
794
795
            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
796
            new_gen = kronecker(*generations[gp], gamete);
797
            new_gen.name = generation_name;
798
799
            /*MSG_DEBUG("TMP GAMETE GEN");*/
            /*MSG_DEBUG(new_gen);*/
800
        } else {
801
802
            /*auto ngp1 = node_generations[np1];*/
            /*auto ngp2 = node_generations[np2];*/
Damien Leroux's avatar
Damien Leroux committed
803
804
805
            /*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)));
806

807
808
809
810
            /* use node's grandparents generations, not parents (no gamete generation) */
            size_t g1 = node_generations[tree.get_p1(np1)];
            size_t g2 = node_generations[tree.get_p1(np2)];
            cached_gen = &cache_geno[{g1, g2}];
811
812
813
814
815
816
            if (*cached_gen) {
                MSG_DEBUG("GENERATION HAS ALREADY BEEN COMPUTED");
                node_generations[n] = *cached_gen;
                return;
            }

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

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

822
823
            new_gen.name = generation_name;

824
825
826
827
828
829
            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");
830
            new_gen.diag = eval(n, &geno_matrix::diag, &pedigree_type::kron_d_diag, recompute, visited);
831
832
833
834
835
836
837
838
839
840
841
            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
842
            new_gen.variant = (tree[n].is_genotype()
843
                               ? Geno
Damien Leroux's avatar
Damien Leroux committed
844
                               : Gamete);
845
846
847
848
849
850
851
852
            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
853
            /*if (!(ind_number_to_node_number.size() == 9 && tree.size() == 23)) {*/
854
                /*MSG_DEBUG("PROPAGATING SYMMETRIES");*/
855
                /*propagate_symmetries(new_gen, recompute, n);*/
856
857
                /*study_expression_symmetries(new_gen);*/
                /*complete_symmetries(new_gen);*/
858
                /*MSG_DEBUG("COMPUTING LATENT SYMMETRY");*/
859
            /*}*/
860
861
862
        }
        node_generations[n] = generations.size();
        generations.emplace_back(new geno_matrix());
863
864
        /*MSG_DEBUG("BEFORE LUMPING");*/
        /*MSG_DEBUG(new_gen);*/
865
        *generations.back() = lump(new_gen, max_states);
866
867
868
        /*if (tree[n].is_crossing()) {*/
            /*propagate_symmetries(n, *generations.back());*/
        /*} else if (tree[n].is_ancestor()) {*/
Damien Leroux's avatar
Damien Leroux committed
869
            generations.back()->symmetries = symmetry_group_type(generations.back()->labels);
870
        /*}*/
871
872
873
874
875
        /**node_generations[n] = lump(new_gen);*/
        if (cached_gen) {
            *cached_gen = node_generations[n];
        }
        MSG_DEBUG("DONE COMPUTING GENERATION FOR NODE #" << n);
876
        MSG_DEBUG_INDENT_EXPR("[RESULT " << tree.make_node_label(n) << " gen#" << node_generations[n] << "] ");
877
878
        MSG_DEBUG((*generations.back()));
        MSG_DEBUG_DEDENT;
879
        /*MSG_DEBUG((*generations[node_generations[n]]));*/
880
881
882
        MSG_DEBUG("=========================================================================");
    }

883
    std::map<genotype_comb_type::key_list, double> GLC_norm_factors(const std::vector<genotype_comb_type>& expanded)
884
    {
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
        std::map<genotype_comb_type::key_list, double> ret;
        for (const auto& e: expanded) {
            const auto& elem = e.m_combination.front();  /* all LC are singletons in the expanded vector */
            for (const auto& k: elem.keys) {
                auto sub_k = elem.keys - k;
                ret[sub_k] += elem.coef;
            }
        }
        return ret;
    }

    void compute_data_for_bn(int n)
    {
        compute_LC(n);

        factor_messages.resize(n + 1);
        for (auto& dest_f: compute_factors(n, true)) {
            factor_messages[dest_f.first].emplace_back(std::move(dest_f.second));
903
        }
904
905
906
907
908
909
910
911
912
913
914
915
916
        for (auto& dest_f: compute_factors(n, false)) {
            factor_messages[dest_f.first].emplace_back(std::move(dest_f.second));
        }
        individuals_in_factors.resize(n + 1);
        std::vector<size_t>& iif = individuals_in_factors.back();
        std::vector<int> in;
        std::vector<int> out;
        auto expr = tree.extract_expression(n, in, out);
        iif.reserve(expr.m_nodes.size());
        for (size_t i = 0; i < expr.m_nodes.size(); ++i) {
            if (expr.m_nodes[i].is_genotype()) {
                iif.push_back(expr.original_node_number(i));
            }
917
        }
918
919
        MSG_DEBUG("INDIVIDUALS IN FACTOR: " << iif);
    }
920

921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
    void
        compute_LC(int n)
        {
            int p1 = tree.get_p1(n);
            std::vector<gencomb_type> lc;
            const geno_matrix& m = *generations[node_generations[n]];
            if (p1 == NONE) {
                lc.emplace_back(1.);
            } else {
                lc = eval_vector(tree.size() - 1, tree.get_recompute_vec(n), &pedigree_type::get_LC, reentrant_LC);
            }
            VectorLC tmp(lc.size()), lumped;
            for (size_t i = 0; i < lc.size(); ++i) {
                tmp(i) = lc[i];
            }
            lumped = m.collect.cast<gencomb_type>() * tmp;
            LC.resize(n + 1);
            LC.back().assign(lumped.data(), lumped.data() + lumped.size());
            MSG_DEBUG("Computed new LC:");
            MSG_DEBUG("" << LC.back());
941
942
        }

943
944
945
946
947
    std::map<size_t, std::map<bn_label_type, genotype_comb_type>>
        compute_factors(int n, bool up)
        {
            std::vector<genotype_comb_type> glc;
            std::vector<bn_label_type> bn_labels;
948

949
950
951
            if (tree.get_p1(n) == NONE) {
                return {};
            }
952

953
954
955
956
957
958
959
960
961
962
            if (up) {
                std::vector<bool> recompute(n + 1, false);
                recompute[n] = true;
                recompute[tree.get_p1(n)] = true;
                recompute[tree.get_p2(n)] = true;
                glc = eval_vector(tree.size() - 1, recompute, &pedigree_type::get_GLC, reentrant_GLC);
                bn_labels = eval_vector(tree.size() - 1, recompute, &pedigree_type::get_bn_labels, reentrant_bn_label);
            } else {
                glc = eval_vector(tree.size() - 1, tree.get_recompute_vec(n), &pedigree_type::get_GLC, reentrant_GLC);
                bn_labels = eval_vector(tree.size() - 1, tree.get_recompute_vec(n), &pedigree_type::get_bn_labels, reentrant_bn_label);
963
964
            }

965
966
967
968
969
970
971
            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];
            }
972

973
974
975
976
977
978
979
980
981
982
            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;
                    keys.emplace_back(tree.size() - 1, kv.first);
                    std::sort(keys.begin(), keys.end());
983
                }
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
            }

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

            auto glc_norm_factors = GLC_norm_factors(expanded_glc);
            for (const auto& kn: glc_norm_factors) {
                MSG_DEBUG('|' << kn.first << "| = " << kn.second);
            }

            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();
            size_t first, last;
            if (up) {
                first = 0;
For faster browsing, not all history is shown. View entire blame