pedigree.h 56.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Spell-QTL  Software suite for the QTL analysis of modern datasets.
 * Copyright (C) 2016,2017  Damien Leroux <damien.leroux@inra.fr>, Sylvain Jasson <sylvain.jasson@inra.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

18
19
20
21
#ifndef _SPELL_BAYES_CSV_H_
#define _SPELL_BAYES_CSV_H_

#include <iostream>
22
#include "file.h"
23
24
25
26
27
#include <string>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <utility>
28
#include <unordered_set>
29
30


Damien Leroux's avatar
Damien Leroux committed
31
32
/*#include "permutation.h"*/
/*#include "symmetry.h"*/
33
34
#include "geno_matrix.h"
#include "linear_combination.h"
Damien Leroux's avatar
Damien Leroux committed
35
#include "pedigree_tree.h"
36
#include "bayes/output.h"
37
38


39
40
41
42
43
44
45
46
47
48
49
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)
    {}

50
51
52
    int compact() const { return *(int*) this; }
    int& compact() { return *(int*) this; }

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    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);
    }
75
76
77
78
79

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

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


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;

119
120
    pedigree_item() : gen_name(), id(0), p1(0), p2(0) {}

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


155
inline
156
157
158
159
160
161
162
163
164
165
166
167
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;
}


168
inline
169
170
171
172
173
174
175
176
177
178
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;
}


179
inline
180
181
182
183
184
185
186
187
188
189
190
191
192
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;
}


193
inline
194
195
196
197
198
199
200
201
202
203
204
205
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;
}


206
inline
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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;
}


222
inline
223
224
225
226
227
228
229
230
231
232
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;
}


233
inline
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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;
}


250
#if 0
251
252
253
254
255
256
257
258
259
260
261
262
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)};
        }
    }
263
264
265
    /*MSG_DEBUG("" << a << " * " << b << " = " << ret);*/
    return ret;
}
266
#endif
267
268
269
270


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

271
inline
272
273
274
275
276
277
278
279
280
281
282
283
284
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);*/
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    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;
    }
};


306
307
308
309
310
311
312
313
314
315
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 ();

316
    void operator () (ifile& ifs, bn_label_type& l) { l.compact() = read_int(ifs); }
317
    void operator () (ofile& ofs, bn_label_type& l) { write_int(ofs, l.compact()); }
318

319
    void operator () (ifile& fs, typename comb_type::key_type& key) { ref() (fs, key.parent); ref() (fs, key.state); }
320
    void operator () (ofile& fs, typename comb_type::key_type& key) { ref() (fs, key.parent); ref() (fs, key.state); }
321

322
    void operator () (ifile& fs, typename comb_type::key_list& keys) { ref() (fs, keys.keys); }
323
    void operator () (ofile& fs, typename comb_type::key_list& keys) { ref() (fs, keys.keys); }
324

325
    void operator () (ifile& fs, typename comb_type::element_type& elem) { ref() (fs, elem.keys); ref() (fs, elem.coef); }
326
    void operator () (ofile& fs, typename comb_type::element_type& elem) { ref() (fs, elem.keys); ref() (fs, elem.coef); }
327

328
    void operator () (ifile& fs, comb_type& comb)
329
330
331
332
333
    {
        if (fourcc(fs, "COMB")) { return; }
        ref() (fs, comb.m_combination);
    }

334
    void operator () (ofile& fs, comb_type& comb)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
    {
        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 ();

349
    void operator () (ifile& fs, pedigree_tree_type::node_type& node) { ref() (fs, node.p1); ref() (fs, node.p2); }
350
    void operator () (ofile& fs, pedigree_tree_type::node_type& node) { ref() (fs, node.p1); ref() (fs, node.p2); }
351

352
353
354
355
356
357
358
359
360
361
362
363
    template <typename STREAM_TYPE, typename TREE_TYPE>
        void tree_io_impl(STREAM_TYPE& fs, 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_ind_number_to_node_number);
            ref() (fs, tree.m_original_ordering);
        }

364
    void operator () (ifile& fs, pedigree_tree_type& tree)
365
    {
366
        tree_io_impl(fs, tree);
367
368
    }

369
    void operator () (ofile& fs, pedigree_tree_type& tree)
370
    {
371
        tree_io_impl(fs, tree);
372
    }
373
374
375
376
377
378
379
380
381

    void operator () (ifile& fs, pedigree_item& pi)
    {
        (*this)(fs, pi.gen_name);
        (*this)(fs, pi.id);
        (*this)(fs, pi.p1);
        (*this)(fs, pi.p2);
    }

382
    void operator () (ofile& fs, pedigree_item& pi)
383
384
385
386
387
388
    {
        (*this)(fs, pi.gen_name);
        (*this)(fs, pi.id);
        (*this)(fs, pi.p1);
        (*this)(fs, pi.p2);
    }
389
390
391
};


392
393
394
395
396
397
398
/* 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
 */
399
400
401
402

/*
 * pedigree_type: implements all facilities to compute proper geno_matrices for any pedigree, including reentrant individuals.
 */
403
struct pedigree_type {
404
405
406
407
408
    /*
     * original data
     */
    std::vector<pedigree_item> items;

409
410
411
    /*
     * pedigree tree implementation
     */
Damien Leroux's avatar
Damien Leroux committed
412
    pedigree_tree_type tree;
413
414
415
416
417

    /*
     * pedigree tree metadata
     */
    typedef size_t geno_matrix_index_type;
Damien Leroux's avatar
Damien Leroux committed
418
    typedef int individual_index_type;
419
420
421
    std::vector<std::shared_ptr<geno_matrix>> generations;
    std::vector<geno_matrix_index_type> node_generations;
    std::map<individual_index_type, char> ancestor_letters;
422
    std::map<char, std::string> ancestor_names;
423
    std::map<geno_matrix_index_type, std::string> generation_names;
424
    std::map<int, int> m_id;
Damien Leroux's avatar
WIP.    
Damien Leroux committed
425
    bool with_LC;
426
    /*std::vector<VectorLC> LC;*/
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441

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

442
443
444
445
446
447
448
449
450
451
452
    /*
     * overlump control
     */

    size_t max_states;

    /*
     * BN metadata
     */
    size_t n_alleles;

453
454
455
456
457
458
459
460
461
462
463
464
465
    /*
     * 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 */

466
467
468
469
    /*
     * default ctor
     */
    pedigree_type()
470
        : tree(), node_generations(), ancestor_letters(), ancestor_names(), generation_names(), m_id(),
471
          with_LC(true),
Damien Leroux's avatar
Damien Leroux committed
472
473
          cache_gamete(), cache_geno(),
          max_states(NONE),
474
475
476
477
          n_alleles(1),
          filename("<none>"),
          LC(),
          factor_messages()
478
479
480
481
482
483
484
485
486
    {
        __init();
    }

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

Damien Leroux's avatar
Damien Leroux committed
487
#if 0
488
    /*
489
     * prealloc ctor
490
491
492
     */
    pedigree_type(size_t n_ind)
    {
493
        n_alleles = 1;
Damien Leroux's avatar
Damien Leroux committed
494
        max_states = NONE;
495
496
497
498
499
500
        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
501
502
    size_t last_node_index() const { return tree.size() - 1; }
#endif
503

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

515
    individual_index_type spawn(const std::string& generation_name, std::initializer_list<individual_index_type> parents)
516
    {
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
                    int n = tree.add_node();
                    MSG_DEBUG("node=" << n << " ind=" << ind);
525
                    compute_generation(generation_name, n);
526
                    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
                    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);
538
539
                    compute_generation(generation_name, n);
                    compute_LC(n);
Damien Leroux's avatar
Damien Leroux committed
540
                    /*compute_data_for_bn(n);*/
541
542
543
544
545
546
547
548
549
                    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
550
                    int n1 = tree.ind2node(p1);
551
                    individual_index_type p2 = *i;
Damien Leroux's avatar
Damien Leroux committed
552
                    int n2 = tree.ind2node(p2);
553
                    /*MSG_DEBUG("p1=" << p1 << " p2=" << p2 << " n1=" << n1 << " n2=" << n2);*/
Damien Leroux's avatar
Damien Leroux committed
554
555
556
557
                    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);
558
559
                    compute_generation(generation_name, n);
                    compute_LC(n);
Damien Leroux's avatar
Damien Leroux committed
560
                    /*compute_data_for_bn(n);*/
561
562
563
564
565
566
567
568
                    MSG_DEBUG_DEDENT;
                }
                break;
            default:;
        };
        return ind;
    }

569
570
571
572
    /*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, {}); }*/
573
574
575

    individual_index_type fill_db(const std::string& name, individual_index_type ind)
    {
576
        geno_matrix_by_generation_name[name].insert(get_gen_index(ind));
577
578
579
580
581
582
        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;
    }

583
584
585
586
    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, {})); }
587

588
#if 0
Damien Leroux's avatar
Damien Leroux committed
589
    void propagate_symmetries(int n, geno_matrix& gen)
590
    {
591
        MSG_DEBUG_INDENT_EXPR("[propagate symmetries #" << n << "] ");
Damien Leroux's avatar
Damien Leroux committed
592
593
594
595
596
597
598
        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));
        }
599
600
601
602
603
604
605
606
607
608
609
        /*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
610
        symmetry_propagator sp(expr);
611
        MSG_DEBUG_INDENT_EXPR("[SYMMETRIES] ");
Damien Leroux's avatar
Damien Leroux committed
612
613
614
615
616
        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,
617
                get_lumper
Damien Leroux's avatar
Damien Leroux committed
618
                );
619
620
        MSG_DEBUG_DEDENT;
        MSG_DEBUG_INDENT_EXPR("[LATENT SYMMETRIES] ");
Damien Leroux's avatar
Damien Leroux committed
621
622
623
624
625
        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,
626
                get_lumper
Damien Leroux's avatar
Damien Leroux committed
627
                );
628
        MSG_DEBUG_DEDENT;
Damien Leroux's avatar
Damien Leroux committed
629
630
        MSG_DEBUG(temp);
        gen.latent_symmetries = temp - gen.symmetries;
631
        MSG_DEBUG_INDENT_EXPR("[AFTER SYMMETRY PROPAGATION] ");
Damien Leroux's avatar
Damien Leroux committed
632
        MSG_DEBUG(gen);
633
        MSG_DEBUG_DEDENT;
634
        MSG_DEBUG_DEDENT;
635
    }
636
#endif
637

638
    void compute_generation(const std::string& generation_name, int n)
639
    {
Damien Leroux's avatar
Damien Leroux committed
640
        MSG_DEBUG("Computing generation for node " << tree.make_node_label(n));
641
        /*MSG_DEBUG(render_tree());*/
642

Damien Leroux's avatar
Damien Leroux committed
643
644
        int np1 = tree.get_p1(n);
        int np2 = tree.get_p2(n);
645
646
647
        node_generations.emplace_back(generations.size());
        geno_matrix new_gen;
        geno_matrix_index_type* cached_gen = NULL;
Damien Leroux's avatar
Damien Leroux committed
648
        if (np1 == NONE && np2 == NONE) {
649
650
651
            /* ancestor */
            char l = 'a' + ancestor_letters.size();
            ancestor_letters[n] = l;
652
            ancestor_names[l] = generation_name;
653
            new_gen = ancestor_matrix(generation_name, l);
Damien Leroux's avatar
Damien Leroux committed
654
        } else if (np2 == NONE) {
655
656
            /* gamete */
            auto gp = node_generations[np1];
Damien Leroux's avatar
Damien Leroux committed
657
            auto& cache = cache_gamete;
658
659
660
661
662
663
            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
664
            new_gen = kronecker(*generations[gp], gamete);
665
            new_gen.name = generation_name;
666
667
            /*MSG_DEBUG("TMP GAMETE GEN");*/
            /*MSG_DEBUG(new_gen);*/
668
        } else {
669
670
            /*auto ngp1 = node_generations[np1];*/
            /*auto ngp2 = node_generations[np2];*/
Damien Leroux's avatar
Damien Leroux committed
671
672
673
            /*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)));
674

675
676
677
678
            /* 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}];
679
680
681
682
683
684
            if (*cached_gen) {
                MSG_DEBUG("GENERATION HAS ALREADY BEEN COMPUTED");
                node_generations[n] = *cached_gen;
                return;
            }

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

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

690
691
            new_gen.name = generation_name;

692
693
694
695
696
697
            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");
698
            new_gen.diag = eval(n, &geno_matrix::diag, &pedigree_type::kron_d_diag, recompute, visited);
699
700
701
702
703
704
705
706
707
708
709
            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
710
            new_gen.variant = (tree[n].is_genotype()
711
                               ? Geno
Damien Leroux's avatar
Damien Leroux committed
712
                               : Gamete);
713
714
715
716
717
718
719
720
            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
721
            /*if (!(ind_number_to_node_number.size() == 9 && tree.size() == 23)) {*/
722
                /*MSG_DEBUG("PROPAGATING SYMMETRIES");*/
723
                /*propagate_symmetries(new_gen, recompute, n);*/
724
725
                /*study_expression_symmetries(new_gen);*/
                /*complete_symmetries(new_gen);*/
726
                /*MSG_DEBUG("COMPUTING LATENT SYMMETRY");*/
727
            /*}*/
728
729
730
        }
        node_generations[n] = generations.size();
        generations.emplace_back(new geno_matrix());
731
732
        /*MSG_DEBUG("BEFORE LUMPING");*/
        /*MSG_DEBUG(new_gen);*/
733
        *generations.back() = lump(new_gen, max_states);
734
735
736
        /*if (tree[n].is_crossing()) {*/
            /*propagate_symmetries(n, *generations.back());*/
        /*} else if (tree[n].is_ancestor()) {*/
737
//             generations.back()->symmetries = symmetry_group_type(generations.back()->labels);
738
        /*}*/
739
740
741
742
743
        /**node_generations[n] = lump(new_gen);*/
        if (cached_gen) {
            *cached_gen = node_generations[n];
        }
        MSG_DEBUG("DONE COMPUTING GENERATION FOR NODE #" << n);
744
        MSG_DEBUG_INDENT_EXPR("[RESULT " << tree.make_node_label(n) << " gen#" << node_generations[n] << "] ");
745
746
        MSG_DEBUG((*generations.back()));
        MSG_DEBUG_DEDENT;
747
        /*MSG_DEBUG((*generations[node_generations[n]]));*/
748
749
750
        MSG_DEBUG("=========================================================================");
    }

751
    std::map<genotype_comb_type::key_list, double> GLC_norm_factors(const std::vector<genotype_comb_type>& expanded)
752
    {
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
        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));
771
        }
772
773
774
775
776
777
778
779
780
781
782
783
784
        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));
            }
785
        }
786
787
        MSG_DEBUG("INDIVIDUALS IN FACTOR: " << iif);
    }
788

789
790
791
    void
        compute_LC(int n)
        {
Damien Leroux's avatar
WIP.    
Damien Leroux committed
792
793
794
            if (!with_LC) {
                return;
            }
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
            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());
812
813
        }

814
815
816
817
818
    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;
819

820
821
822
            if (tree.get_p1(n) == NONE) {
                return {};
            }
823

824
825
826
827
828
829
830
831
832
833
            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);
834
835
            }

836
837
838
839
840
841
842
            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];
            }
843

844
845
846
847
848
849
850
851
852
853
            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());
854
                }
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
            }

            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;
                last = n_nodes - 2;
            } else {
                first = 0;
                last = n_nodes - 1;
            }
            for (const auto& lc: expanded_glc) {
                const auto& elems = lc.m_combination.front();
                const auto& keys = elems.keys.keys;
                for (size_t ni = first; ni <= last; ++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]);
                    }
                    for (++i; i < n_nodes; ++i) {
                        msg_keys.emplace_back(keys[i]);
                    }
                    tmp.m_combination.front().coef /= glc_norm_factors[tmp.m_combination.back().keys];
                    messages[keys[ni].parent][keys[ni].state] += tmp;
893
894
895
                }
            }

896
897
898
899
900
            for (const auto& kv1: messages) {
                MSG_DEBUG("MESSAGE TOWARDS #" << kv1.first);
                for (const auto& kv2: kv1.second) {
                    MSG_DEBUG("" << kv2.first << " = " << kv2.second);
                }
901
            }
902
903

            return messages;
904
905
906
907
908
909
910
911
912
913
914
915
916
917
        }


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

918
919
920
921
922
923
    static MatrixXd kron_d_diag(const MatrixXd& m1, const MatrixXd& m2)
    {
        return kroneckerProduct(m1, MatrixXd::Ones(m2.rows(), m2.cols()))
             + kroneckerProduct(MatrixXd::Ones(m1.rows(), m1.cols()), m2);
    }

924
925
    char ancestor_letter(size_t a) const
    {
Damien Leroux's avatar
Damien Leroux committed
926
        auto i = ancestor_letters.find(tree.ind2node(a));
927
928
929
        return i == ancestor_letters.end() ? 0 : i->second;
    }

930
    geno_matrix_index_type get_gen_index(size_t ind) const
931
    {
Damien Leroux's avatar
Damien Leroux committed
932
        return node_generations[tree.ind2node(ind)];
933
934
935
936
937
938
939
    }

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

940
941
942
943
944
945
    int
        ind2id(int i) const
        {
            return items[i - 1].id;
        }

946
    const geno_matrix&
Damien Leroux's avatar
Damien Leroux committed
947
        get_geno_matrix_by_individual(size_t ind) const { return *generations[node_generations[tree.ind2node(ind)]]; }
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
    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
    {
963
        scoped_indent _;
964
        /*MSG_DEBUG("eval node " << node);*/
965
        if (visited[node]) {
966
            /*MSG_DEBUG("already visited => 1");*/
967
            return make_one<FIELD_TYPE>::_(func == kron_d || func == kron_d_diag);
968
969
        }
        visited[node] = true;
Damien Leroux's avatar
Damien Leroux committed
970
        if (recompute[node] || tree[node].is_gamete()) {
971
            FIELD_TYPE ret, m1, m2;
Damien Leroux's avatar
Damien Leroux committed
972
973
974
975
976
977
978
979
            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);
            }
980
981
            return ret;
        } else {
982
983
            /*MSG_DEBUG("using actual matrix");*/
            /*MSG_DEBUG((*generations[node_generations[node]]).*field);*/
984
985
986
987
988
989
990
991
992
993
994
995
            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()) {}
996
        void reset() { cur = begin = data.begin(); end = data.end(); }
997
998
999
1000
1001
        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; }
1002
        const VALUE_TYPE* operator -> () const { return &*cur; }
1003
1004
1005
    };

    typedef vector_iterator<label_type> label_iterator;
1006
//     typedef vector_iterator<symmetry_table_type> symmetry_iterator;
1007
1008
1009
1010
1011
1012
1013

    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
        {
1014
            /*scoped_indent _(SPELL_STRING("[eval #" << node << "] "));*/
1015
1016
1017
            if (visited[node]) {
                auto ret = eval_reent(node, reent[node]);
                /*ret = eval_reent(node, iterators[node_to_iterator[node]]);*/
1018
                /*MSG_DEBUG("reentrant; " << ret);*/
1019
1020
1021
                return ret;
            } else {
                visited[node] = true;
Damien Leroux's avatar
Damien Leroux committed
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
                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]];
                    }
1035
1036
1037
1038
                } else {
                    reent[node] = *iterators[node_to_iterator[node]];
                }
            }
1039
1040
            /*MSG_DEBUG("ret = " << reent[node]);*/
            /*MSG_QUEUE_FLUSH();*/
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
            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
        {
1053
            /*scoped_indent _(SPELL_STRING("[eval #" << node << "] "));*/
1054
1055
1056
            if (visited[node]) {
                auto ret = eval_reent(node, reent[node]);
                /*ret = eval_reent(node, iterators[node_to_iterator[node]]);*/
1057
                /*MSG_DEBUG("reentrant; " << ret);*/
1058
1059
1060
                return ret;
            } else {
                visited[node] = true;
Damien Leroux's avatar
Damien Leroux committed
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
                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]];
                    }
1074
1075
1076
1077
                } else {
                    reent[node] = *iterators[node_to_iterator[node]];
                }
            }
1078
            /*MSG_DEBUG("ret = " << reent[node]);*/
1079
1080
1081
1082
            /*if (skip_predicate(reent[node])) {*/
                /*throw skip_eval_exception();*/
            /*}*/
            return reent[node];
1083
            (void)skip_predicate;
1084
1085
        }

1086
1087
    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; }
1088
1089
    static gencomb_type reentrant_LC(size_t, const gencomb_type&) { return {1.}; }
    static genotype_comb_type reentrant_GLC(size_t, const genotype_comb_type&) { return {1.}; }
1090
//     static symmetry_table_type reentrant_sym(size_t, const symmetry_table_type& S) { return {permutation_type::identity(1), S.letters}; }
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100

    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
1101
1102
1103
1104
1105
1106
1107
            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));
1108
1109
                    /*MSG_DEBUG("GAMETE");*/
                    /*MSG_DEBUG("" << (this->*accessor)(true, node, gamete));*/
Damien Leroux's avatar
Damien Leroux committed
1110
1111
                }
#if 0
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
                switch (nodes[node].type) {
                    case NTGenotype:
                        break;
                    case NTGamete:
                        break;
                    case NTDoubling:
                        node_to_iterator[node] = iterators.size();
                        iterators.emplace_back((this->*accessor)(true, node, doubling_gamete));
                        MSG_DEBUG("DOUBLING GAMETE");
                        MSG_DEBUG("" << (this->*accessor)(true, node, doubling_gamete));
                };
Damien Leroux's avatar
Damien Leroux committed
1123
#endif
1124
1125
1126
            } else {
                node_to_iterator[node] = iterators.size();
                iterators.emplace_back((this->*accessor)(false, node, *generations[node_generations[node]]));
1127
1128
                /*MSG_DEBUG("GENERATION");*/
                /*MSG_DEBUG("" << (this->*accessor)(false, node, *generations[node_generations[node]]));*/
1129
1130
1131
1132
            }
        }

    std::vector<label_type> get_labels(bool, size_t, const geno_matrix& m) const { return m.labels; }
1133
1134
1135
1136
1137
1138
    std::vector<bn_label_type> get_bn_labels(bool, size_t, const geno_matrix& m) const
    {
        if (m.variant == Geno) {
            std::vector<bn_label_type> ret;
            ret.reserve(m.labels.size() * n_alleles * n_alleles);
            for (const auto& l: m.labels) {
1139
1140
                for (int a1 = 0; a1 < (int) n_alleles; ++a1) {
                    for (int a2 = 0; a2 < (int) n_alleles; ++a2) {
1141
                        ret.emplace_back(l.first(), l.second(), a1, a2);
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
                    }
                }
            }
            return ret;
        } else if (m.variant == Gamete) {
            return {{GAMETE_L, GAMETE_EMPTY, 0, 0}, {GAMETE_R, GAMETE_EMPTY, 0, 0}};
        } else if (m.variant == DoublingGamete) {
            return {{GAMETE_L, GAMETE_L, 0, 0}, {GAMETE_R, GAMETE_R, 0, 0}};
        } else {
            std::vector<bn_label_type> ret;
            ret.reserve(m.labels.size() * n_alleles);
            for (const auto& l: m.labels) {
1154
                for (int a1 = 0; a1 < (int) n_alleles; ++a1) {
1155
                    ret.emplace_back(l.first(), l.second(), a1, 0);
1156
1157
1158
1159
1160
                }
            }
            return ret;
        }
    }
1161
1162
1163
1164

    std::vector<gencomb_type> get_LC(bool recompute, size_t node, const geno_matrix& m) const
    {
        /*return {LC[node].data(), LC[node].data() + LC[node].size()};*/
Damien Leroux's avatar
Damien Leroux committed
1165
1166
        if (recompute && !tree[node].is_genotype()) {
            return {.5, .5};
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
        } else {
            std::vector<gencomb_type> ret(m.cols());
            for (size_t i = 0; i < ret.size(); ++i) {
                ret[i].m_combination.emplace_back(gencomb_type::key_type{node, i}, 1.);
            }
            return ret;
        }
        return {};
    }

1177
1178
1179
    std::vector<genotype_comb_type> get_GLC(bool recompute, size_t node, const geno_matrix& m) const
    {
        /*return {LC[node].data(), LC[node].data() + LC[node].size()};*/
Damien Leroux's avatar
Damien Leroux committed
1180
1181
        if (recompute && !tree[node].is_genotype()) {
            return {.5, .5};
1182
        } else {
Damien Leroux's avatar
Damien Leroux committed
1183
            if (tree[node].is_genotype()) {
1184
1185
                std::vector<genotype_comb_type> ret(m.cols() * n_alleles * n_alleles);
                size_t n = 0;
1186
                double norm = 1.; // / (n_alleles * n_alleles);
1187
                for (size_t i = 0; i < m.labels.size(); ++i) {
1188
1189
                    for (char a1 = 0; a1 < (char) n_alleles; ++a1) {
                        for (char a2 = 0; a2 < (char) n_alleles; ++a2) {
1190
                            ret[n++].m_combination.emplace_back(genotype_comb_type::key_type{(int) node, {m.labels[i].first(), m.labels[i].second(), a1, a2}}, norm);
1191
1192
1193
1194
1195
1196
1197
                        }
                    }
                }
                return ret;
            } else {
                std::vector<genotype_comb_type> ret(m.cols() * n_alleles);
                size_t n = 0;
1198
                double norm = 1.; // / n_alleles;
1199
                for (size_t i = 0; i < m.labels.size(); ++i) {
1200
                    for (char a1 = 0; a1 < (char) n_alleles; ++a1) {
1201
                        ret[n++].m_combination.emplace_back(genotype_comb_type::key_type{(int) node, {m.labels[i].first(), m.labels[i].second(), a1, 0}}, norm);
1202
1203
1204
1205
1206
1207
1208
1209
                    }
                }
                return ret;
            }
        }
        return {};
    }

1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
    template <typename VALUE_TYPE>
        bool next(std::vector<vector_iterator<VALUE_TYPE>>& iterators) const
        {
            auto i = iterators.rbegin(), j = iterators.rend();
            for (; i != j; ++i) {
                if (i->next()) {
                    i->start();
                } else {
                    break;
                }
            }
            return i != j;
        }

1224
1225
1226
1227
1228
1229
1230
1231
    template <typename VALUE_TYPE>
        void reset(std::vector<vector_iterator<VALUE_TYPE>>& iterators) const
        {
            for (auto& vi: iterators) {
                vi.reset();
            }
        }

1232
1233
1234
1235
1236
1237
    template <typename VALUE_TYPE>
        std::vector<VALUE_TYPE>
        eval_vector(size_t node, const std::vector<bool>& recompute,
                    std::vector<VALUE_TYPE> (pedigree_type:: *accessor)(bool, size_t, const geno_matrix&) const,
                    VALUE_TYPE (&eval_reent)(size_t, const VALUE_TYPE&)) const
        {
Damien Leroux's avatar
Damien Leroux committed
1238
            std::vector<VALUE_TYPE> reent(tree.size());
1239
            /*MSG_DEBUG_INDENT_EXPR("[eval_vector #" << node << "] ");*/
Damien Leroux's avatar
Damien Leroux committed
1240
            std::vector<bool> visited(tree.size(), false);
1241
1242
1243
1244
            std::vector<vector_iterator<VALUE_TYPE>> iterators;
            std::vector<size_t> node_to_iterator;
            std::vector<VALUE_TYPE> ret;

Damien Leroux's avatar
Damien Leroux committed
1245
1246
            iterators.reserve(tree.size());
            node_to_iterator.reserve(tree.size());
1247

1248
            /*MSG_DEBUG("init iterators");*/
1249
1250
1251
1252
1253
1254
1255
            init_iterators_rec(node, recompute, visited, iterators, node_to_iterator, accessor);

            size_t total_size = 1;

            for (const auto& i: iterators) {
                total_size *= i.size();
            }
1256
            /*MSG_DEBUG("total size = " << total_size);*/
1257
1258

            if (!total_size) {
1259
1260
                /*MSG_DEBUG("EMPTY!");*/
                /*MSG_DEBUG_DEDENT;*/
1261
1262
1263
1264
1265
                return {};
            }

            ret.reserve(total_size);

1266
            /*size_t i = 0;*/
1267
            do {
1268
                /*MSG_DEBUG((++i) << "/" << total_size);*/
Damien Leroux's avatar
Damien Leroux committed
1269
                visited.assign(tree.size(), false);
1270
1271
1272
                ret.push_back(eval_one(node, recompute, iterators, node_to_iterator, visited, eval_reent, reent));
            } while (next(iterators));

1273
1274
            /*MSG_DEBUG("DONE");*/
            /*MSG_DEBUG_DEDENT;*/