model.h 42.1 KB
Newer Older
1
2
3
#ifndef _SPEL_MODEL_MODEL_H_
#define _SPEL_MODEL_MODEL_H_

4
5
#include <stdexcept>

6
7
8
/*#include <Eigen/SVD>*/
/*#include <Eigen/QR>*/
#include "eigen.h"
Damien Leroux's avatar
Damien Leroux committed
9
#include "beta_gamma.h"
10

11
12
#include <cmath>

13

14
#include "labelled_matrix.h"
15
#include "settings.h"
16
#include "print.h"
17
18
19

/*#define COMPONENT_EPSILON (1.e-10)*/
#define COMPONENT_EPSILON (active_settings->tolerance)
20
21
22

typedef labelled_matrix<Eigen::Matrix<double, -1, -1>, int, std::vector<char>> model_block_type;

Damien Leroux's avatar
Damien Leroux committed
23
24
25
26
27
28
29
30
31
32
33
34
struct model_block_key;
struct model;

struct key_already_exists : public std::exception {
    std::string m_what;
    key_already_exists(const model&, const model_block_key&);
    const char* what() const throw()
    {
        return m_what.c_str();
    }
};

35

36
37
38
struct model_block_key {
    typedef std::map<const chromosome*, locus_key> selection_type;
    typedef selection_type::value_type selection_value_type;
39
    selection_type selection;
40
41
42
43
44
45

    model_block_key() : selection() {}
    model_block_key(std::initializer_list<selection_value_type> il)
        : selection(std::forward<std::initializer_list<selection_value_type>>(il))
    {}

Damien Leroux's avatar
Damien Leroux committed
46
47
48
49
50
51
52
    model_block_key&
        operator = (const model_block_key& mbk)
        {
            selection = mbk.selection;
            return *this;
        }

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    locus_key
        operator [] (const chromosome* chr) const
        {
            auto it = selection.find(chr);
            return it == selection.end() ? locus_key() : it->second;
        }

    bool empty() const
    {
        if (selection.size()) {
            for (const auto& kv: selection) {
                if (!kv.second->is_empty()) {
                    return false;
                }
            }
        }
        return true;
    }

    model_block_key
        only_chromosome(const chromosome* c) const
        {
            return {{{c, selection.find(c)->second}}};
        }

    model_block_key
        without_locus(const chromosome* c, double l) const
        {
            model_block_key mbk = *this;
            locus_key& lk = mbk.selection.find(c)->second;
            lk = lk - l;
            return mbk;
        }

    model_block_key
        with_locus(const chromosome* c, double l) const
        {
            model_block_key mbk = *this;
            locus_key& lk = mbk.selection.find(c)->second;
            lk = lk + l;
            return mbk;
        }

    model_block_key&
        operator += (std::pair<const chromosome*, double> loc)
        {
            /*locus_key& lk = selection.find(loc.first)->second;*/
            /*lk = lk + loc.second;*/
            selection[loc.first] = selection[loc.first] + loc.second;
            return *this;
        }

    model_block_key&
        operator += (const model_block_key& mbk)
        {
            for (const auto& c_lk: mbk.selection) {
                auto it = selection.find(c_lk.first);
                if (it == selection.end()) {
                    selection.insert(c_lk);
                } else {
                    it->second = it->second + c_lk.second;
                }
            }
            return *this;
        }

    model_block_key&
        operator -= (std::pair<const chromosome*, double> loc)
        {
            locus_key& lk = selection.find(loc.first)->second;
            lk = lk - loc.second;
            return *this;
        }

    model_block_key
        operator / (const chromosome* c) const
        {
            model_block_key mbk;
            for (const auto& kv: selection) {
                if (kv.first != c) {
                    mbk.selection.insert(kv);
                }
            }
            return mbk;
        }

    model_block_key
        operator % (const chromosome* c) const
        {
            return only_chromosome(c);
        }

    std::vector<model_block_key>
        split() const
        {
            std::vector<model_block_key> ret;
            for (const auto& x: selection) {
                ret.push_back({x});
            }
            return ret;
        }

    std::vector<model_block_key>
        split_loci() const
        {
            std::vector<model_block_key> ret;
            for (const auto& x: selection) {
                for (double l: *x.second) {
                    /*locus_key lk(new locus_key_struc(NULL, l));*/
                    model_block_key k;
                    k.selection[x.first] = k.selection[x.first] + l;
                    /*ret.emplace_back({{x.first, lk}});*/
                    ret.push_back(std::move(k));
                }
            }
            return ret;
        }

    static
        model_block_key
        join(const std::vector<model_block_key>& list)
        {
            model_block_key ret;
            for (const auto& k: list) {
                ret += k;
            }
            return ret;
        }

    static
        model_block_key
        join(const std::map<model_block_key, value<model_block_type>>& coll)
        {
            model_block_key ret;
            for (const auto& kv: coll) {
                ret += kv.first;
            }
            return ret;
        }

    bool
        operator == (const model_block_key& mbk) const
        {
            return selection == mbk.selection;
        }

    bool
        operator != (const model_block_key& mbk) const
        {
            return selection != mbk.selection;
        }

    bool
        operator < (const model_block_key& mbk) const
        {
            /*MSG_DEBUG((*this) << " < " << mbk << "?");*/
Damien Leroux's avatar
Damien Leroux committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
            auto ti = selection.begin();
            auto tj = selection.end();
            auto mi = mbk.selection.begin();
            auto mj = mbk.selection.end();
            while (ti != tj
                    && mi != mj
                    && ti->first == mi->first
                    && ti->second == mi->second) {
                ++ti;
                ++mi;
            }

            bool ret;
            if (ti == tj) {
                ret = mi != mj;
            } else if (mi == mj) {
                ret = false;
            } else {
                ret = ti->first < mi->first
228
229
                   || (ti->first == mi->first && (ti->second->depth() < mi->second->depth()
                                                  || (ti->second->depth() == mi->second->depth() && ti->second < mi->second)));
230
            }
Damien Leroux's avatar
Damien Leroux committed
231
232
233

            /*MSG_DEBUG((ret ? "YES" : "NO"));*/
            return ret;
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
        }

    friend
        model_block_key
        operator + (const model_block_key& k, std::pair<const chromosome*, double> loc)
        {
            model_block_key ret = k;
            locus_key& lk = ret.selection.find(loc.first)->second;
            lk = lk + loc.second;
            return ret;
        }

    friend
        model_block_key
        operator - (const model_block_key& k, std::pair<const chromosome*, double> loc)
        {
            model_block_key ret = k;
            locus_key& lk = ret.selection.find(loc.first)->second;
            lk = lk - loc.second;
            return ret;
        }

    friend
        std::ostream&
        operator << (std::ostream& os, const model_block_key& mbk)
        {
            auto i = mbk.selection.begin();
            auto j = mbk.selection.end();
            if (i == j) {
                return os << "I";
            }
            os << i->first->name << '{' << i->second << '}';
            for (++i; i != j; ++i) {
                os << ',' << i->first << '{' << i->second << '}';
            }
            return os;
        }
};

typedef std::map<model_block_key, value<model_block_type>> model_block_collection;

namespace std {
    template <>
        struct hash<model_block_key> {
            size_t operator () (const model_block_key& mbk) const
            {
                /* WARNING FIXME this MUST NOT be used to hash a function parameter
                 * in a disk-cached task, because a POINTER is HASHED and the order
                 * is not guaranteed to be the same in every run.
                 */
                std::hash<const chromosome*> hc;
                std::hash<locus_key> hlk;
                size_t accum = 0xdeadbe3f;
                for (const auto& kv: mbk.selection) {
                    accum = impl::ROTATE<7>(impl::ROTATE<7>(accum * hc(kv.first)) ^ hlk(kv.second));
                }
                return accum;
            }
        };
} // namespace std



297
static inline
298
bool
299
300
301
302
303
304
around_zero(double o)
{
    return o < COMPONENT_EPSILON && o > -COMPONENT_EPSILON;
}

static inline
305
bool
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
much_smaller_than(double a, double b)
{
    return a < (COMPONENT_EPSILON * b);
}

static inline
void
set_if_much_smaller_than(double& a, double b)
{
    double tmp = COMPONENT_EPSILON * b;
    if (a < tmp) {
        a = tmp;
    }
}

321
322
323

using namespace Eigen;

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
static inline
MatrixXd concat_right(const std::vector<MatrixXd>& mat_vec)
{
    size_t full_size = 0;
    MatrixXd ret;
    for (auto& m: mat_vec) {
        full_size += m.outerSize();
        /*MSG_DEBUG("preparing concat_right with matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
    }
    ret.resize(mat_vec.front().innerSize(), full_size);
    full_size = 0;
    for (auto& m: mat_vec) {
        /*MSG_DEBUG("concat_right in M(" << ret.innerSize() << ',' << ret.outerSize() << ") at col " << full_size << "matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
        /*ret.block(0, full_size, ret.innerSize(), m->outerSize()) = *m;*/
        ret.middleCols(full_size, m.outerSize()) = m;
        full_size += m.outerSize();
    }
    return ret;
}

344
static inline
345
MatrixXd concat_right(const collection<model_block_type>& mat_vec)
346
347
348
{
    size_t full_size = 0;
    MatrixXd ret;
349
350
    for (auto m: mat_vec) {
        full_size += m->outerSize();
351
        /*MSG_DEBUG("preparing concat_right with matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
352
    }
353
    ret.resize(mat_vec.front()->innerSize(), full_size);
354
    full_size = 0;
355
    for (auto m: mat_vec) {
356
357
        /*MSG_DEBUG("concat_right in M(" << ret.innerSize() << ',' << ret.outerSize() << ") at col " << full_size << "matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
        /*ret.block(0, full_size, ret.innerSize(), m->outerSize()) = *m;*/
358
        ret.middleCols(full_size, m->outerSize()) = m->data;
359
        full_size += m->outerSize();
360
361
362
363
    }
    return ret;
}

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

static inline
MatrixXd concat_right(const model_block_collection& mat_map)
{
    size_t full_size = 0;
    MatrixXd ret;
    for (auto m: mat_map) {
        full_size += m.second->outerSize();
        /*MSG_DEBUG("preparing concat_right with matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
    }
    ret.resize(mat_map.begin()->second->innerSize(), full_size);
    full_size = 0;
    for (auto m: mat_map) {
        /*MSG_DEBUG("concat_right in M(" << ret.innerSize() << ',' << ret.outerSize() << ") at col " << full_size << "matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
        /*ret.block(0, full_size, ret.innerSize(), m->outerSize()) = *m;*/
        ret.middleCols(full_size, m.second->outerSize()) = m.second->data;
        full_size += m.second->outerSize();
    }
    return ret;
}

Damien Leroux's avatar
Damien Leroux committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
static inline
MatrixXd concat_down(const std::vector<MatrixXd>& mat_vec)
{
    size_t full_size = 0;
    MatrixXd ret;
    for (auto& m: mat_vec) {
        full_size += m.innerSize();
    }
    ret.resize(full_size, mat_vec.front().outerSize());
    full_size = 0;
    for (auto& m: mat_vec) {
        ret.middleRows(full_size, m.innerSize()) = m;
        full_size += m.innerSize();
    }
    return ret;
}

402
static inline
403
MatrixXd concat_down(const std::vector<const MatrixXd*>& mat_vec)
404
405
406
{
    size_t full_size = 0;
    MatrixXd ret;
407
408
    for (auto m: mat_vec) {
        full_size += m->innerSize();
409
    }
410
    ret.resize(full_size, mat_vec.front()->outerSize());
411
    full_size = 0;
412
    for (auto m: mat_vec) {
413
414
        /*ret.block(full_size, 0, m->innerSize(), ret.outerSize()) = *m;*/
        ret.middleRows(full_size, m->innerSize()) = *m;
415
        full_size += m->innerSize();
416
417
418
419
420
421
422
423
424
    }
    return ret;
}


static inline
std::pair<int, MatrixXd>
rank_and_components(const MatrixXd& M)
{
425
    JacobiSVD<MatrixXd> svd(M, ComputeThinU);
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445

    std::cout << "Singular values " << svd.singularValues().transpose() << std::endl;
    int nzsv = svd.nonzeroSingularValues();

    return {nzsv, svd.matrixU().leftCols(nzsv)};
}


static inline
MatrixXd components(const MatrixXd& M, const MatrixXd& P)
{
    MatrixXd pnorm(P.innerSize(), P.outerSize());
    for (int i = 0; i < P.outerSize(); ++i) {
        pnorm.col(i) = P.col(i).normalized();
    }
    MatrixXd orth = M - pnorm * pnorm.transpose() * M; /* feu ! */
    return rank_and_components(orth).second;
}


446
enum class SolverType { QR };
447

Damien Leroux's avatar
Damien Leroux committed
448
449
450
451
typedef std::vector<std::map<model_block_key, MatrixXd>> constraint_list;


MatrixXd
452
contrast_groups(const collection<const qtl_pop_type*>& all_pops, const locus_key& lk);
Damien Leroux's avatar
Damien Leroux committed
453

Damien Leroux's avatar
Damien Leroux committed
454

455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501

struct filename_stream {
    struct filtering_streambuf : public std::streambuf {
        std::streambuf* original;
        filtering_streambuf(std::streambuf* _) : original(_) {}
    protected:
        int overflow(int ch) override
        {
            switch (ch) {
                case ',':
                case '}':
                    return ch;
                case '{':
                    ch = '-';
                    break;
                case ' ':
                    ch = '_';
                default:;
            };
            return original->sputc(ch);
        }
    };

    std::ostringstream sstream;
    filtering_streambuf rdbuf;
    std::ostream ostream;

    filename_stream()
        : sstream(), rdbuf(sstream.rdbuf()), ostream(&rdbuf)
    {}

    template <typename T>
        friend
        filename_stream& operator << (filename_stream& fs, T x)
        {
            fs.ostream << x;
            return fs;
        }

    operator
        std::string () const
        {
            return sstream.str();
        }
};


Damien Leroux's avatar
Damien Leroux committed
502
/*#define ULTRA_MEGA_PARANOID*/
503
504
505
static inline
MatrixXd matrix_inverse(const MatrixXd& m)
{
Damien Leroux's avatar
Damien Leroux committed
506
507
    /*return m.fullPivHouseholderQr().inverse();*/
    /*return m.inverse();*/
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
    /* FIXME Should NOT use SVD (see note in compute() */
    JacobiSVD<MatrixXd> inverter(m, ComputeFullV);
    auto& V = inverter.matrixV();
    VectorXd inv_sv(inverter.singularValues());
    for (int i = 0; i < inv_sv.innerSize(); ++i) {
        if (!around_zero(inv_sv(i))) {
            inv_sv(i) = 1. / inv_sv(i);
        } else {
            inv_sv(i) = 0.;
        }
    }
#ifdef ULTRA_MEGA_PARANOID
    /* CHECK THAT THIS IS STABLE BY THE BEN ISRAEL SEQUENCE */
    MatrixXd svd_ret = V * inv_sv.asDiagonal() * V.transpose();
    MatrixXd ret = svd_ret;
    MatrixXd test = 2 * ret - ret * m * ret;
    if (!test.isApprox(ret, .00001)) {
        MSG_DEBUG("ret" << std::endl << ret << std::endl << "test" << std::endl << test);
    } else {
        MSG_DEBUG("m^-1 IS GOOD! Yeah man.");
    }
    return ret;
#else
    return V * inv_sv.asDiagonal() * V.transpose();
#endif
}



537
538
struct model {
    model()
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
        : m_Y(), m_blocks(), m_X(), m_rank(), m_rss(), m_coefficients(), m_solver_type(), m_computed(false), m_with_constraints(false), m_ghost_constraint(), m_all_pops(), m_ancestor_names()

    {}

    model(const value<MatrixXd>& y, const collection<const qtl_pop_type*>& pops, const std::map<char, std::string>& anam, SolverType st = SolverType::QR)
        : m_Y(y)
        , m_blocks(), m_X()
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
		, m_solver_type(st)
        , m_computed(false)
        , m_with_constraints(false)
        , m_ghost_constraint()
        , m_all_pops(pops)
        , m_ancestor_names(anam)
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
554
555
    {}

556
    model(const value<MatrixXd>& y, const collection<const qtl_pop_type*>& pops, SolverType st = SolverType::QR)
557
        : m_Y(y)
558
        , m_blocks(), m_X()
559
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
560
561
		, m_solver_type(st)
        , m_computed(false)
Damien Leroux's avatar
Damien Leroux committed
562
        , m_with_constraints(false)
563
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
564
        , m_all_pops(pops)
565
        , m_ancestor_names((*pops.front())->ancestor_names)
566
567
568
569
570
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
    {}

    model(const model& mo)
        : m_Y(mo.m_Y)
571
        , m_blocks(mo.m_blocks), m_X(mo.m_X)
572
		, m_rank(mo.m_rank), m_rss(mo.m_rss), m_coefficients(mo.m_coefficients)
573
        , m_residuals(mo.m_residuals)
574
575
		, m_solver_type(mo.m_solver_type)
        , m_computed(mo.m_computed)
576
577
        , m_with_constraints(mo.m_with_constraints)
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
578
        , m_all_pops(mo.m_all_pops)
579
        , m_ancestor_names(mo.m_ancestor_names)
580
581
582
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
    {}

583
584
585
586
587
588
589
590
591
592
    model(const value<MatrixXd>& y, const model& mo)
        : m_Y(y)
        , m_blocks(mo.m_blocks), m_X(mo.m_X)
		, m_rank(), m_rss(), m_coefficients()
        , m_residuals()
		, m_solver_type(mo.m_solver_type)
        , m_computed(false)
        , m_with_constraints(mo.m_with_constraints)
        , m_ghost_constraint()
        , m_all_pops(mo.m_all_pops)
593
        , m_ancestor_names(mo.m_ancestor_names)
594
595
596
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
    {}

597
# if 0
598
599
    model&
        operator = (const model& mo)
600
601
        = delete;
#else
602
603
604
605
606
607
608
609
610
611
612
613
614
615
    model&
        operator = (const model& mo)
        {
            m_Y = mo.m_Y;
            m_blocks = mo.m_blocks;
            m_computed = mo.m_computed;
            m_with_constraints = mo.m_with_constraints;
            m_ghost_constraint = mo.m_ghost_constraint;
            m_X = mo.m_X;
            m_rss = mo.m_rss;
            m_coefficients = mo.m_coefficients;
            m_residuals = mo.m_residuals;
            m_rank = mo.m_rank;
            m_all_pops = mo.m_all_pops;
616
            m_ancestor_names = mo.m_ancestor_names;
617
618
            return *this;
        }
619

620
621
622
623
624
625
626
627
628
629
630
631
632
633
    model&
        operator = (model&& mo)
        {
            m_Y = mo.m_Y;
            m_blocks.clear();
            m_blocks.swap(mo.m_blocks);
            m_computed = mo.m_computed;
            m_with_constraints = mo.m_with_constraints;
            m_ghost_constraint = mo.m_ghost_constraint;
            m_X = mo.m_X;
            m_rss = mo.m_rss;
            m_coefficients = mo.m_coefficients;
            m_residuals = mo.m_residuals;
            m_rank = mo.m_rank;
634
            m_ancestor_names.swap(mo.m_ancestor_names);
635
636
            return *this;
        }
637
#endif
638

Damien Leroux's avatar
Damien Leroux committed
639
    constraint_list
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
        compute_constraint(const model_block_key& mbk, const model_block_type& mb)
        {
            constraint_list ret;
            size_t n_qtl = mb.column_labels.front().size();
            if (mbk.empty()) {
                return ret;
            /*} else if (mbk.selection.size() == 1) {*/
            } else if (n_qtl == 1) {
                /* only one chromosome: do the contrast groups trick */
                ret = {{{mbk, contrast_groups(m_all_pops, mbk.selection.begin()->second)}}};
            } else {
                std::vector<std::set<char>> uniq_letters_per_qtl(mb.column_labels.front().size());
                /* need the epistasis magic here */
                for (const auto& vec: mb.column_labels) {
                    auto i = uniq_letters_per_qtl.begin();
                    for (char c: vec) { i->insert(c); ++i; }
                }
                std::vector<size_t> letter_counts(uniq_letters_per_qtl.size());
                for (size_t i = 0; i < letter_counts.size(); ++i) { letter_counts[i] = uniq_letters_per_qtl[i].size(); }
                size_t start = 1;
                size_t finish = (1 << letter_counts.size()) - 1;
                for (size_t variant = start; variant < finish; ++variant) {
                    MatrixXd constraint = MatrixXd::Identity(1, 1);
                    for (size_t i = 0; i < letter_counts.size(); ++i) {
                        bool flat = (variant >> i) & 1;
                        MatrixXd tmp;
                        if (flat) {
                            tmp = kroneckerProduct(constraint, MatrixXd::Ones(1, letter_counts[i]));
                        } else {
                            tmp = kroneckerProduct(constraint, MatrixXd::Identity(letter_counts[i], letter_counts[i]));
                        }
                        constraint = tmp;
                    }
                    ret.emplace_back();
                    MSG_DEBUG("Created constraint");
                    MSG_DEBUG("" << constraint);
                    ret.back().insert({{mbk, constraint}});
                }
            }
            if (mbk == m_ghost_constraint.first) {
                int n_par = m_blocks[mbk]->outerSize();
                ret.emplace_back();
                ret.back().insert({{m_ghost_constraint.first, MatrixXd::Identity(n_par, n_par)},
                        {m_ghost_constraint.second, -1. * MatrixXd::Identity(n_par, n_par)}});
            }
685
            return ret;
Damien Leroux's avatar
Damien Leroux committed
686
        }
687

Damien Leroux's avatar
Damien Leroux committed
688
689
690
691
692
693

    /*bool operator == (const model& m) const*/
    /*{*/
        /*return m_Y == m.m_Y && m_blocks == m.m_blocks && m_rss == m.m_rss;*/
    /*}*/

694
695
696
    void
        add_block(const model_block_key& key, const value<model_block_type>& x)
        {
697
            /*MSG_DEBUG("add_block(" << key << ", <some block>)");*/
698
            if (m_blocks.find(key) != m_blocks.end()) {
699
                /*MSG_DEBUG("Key already exists");*/
700
701
702
703
704
705
706
707
                return;
                /*throw key_already_exists(*this, key);*/
            }
            m_computed = false;
            m_blocks[key] = x;
            /*MSG_DEBUG("selection now: " << keys());*/
            /*m_blocks.push_back(x);*/
            /*m_keys.push_back(key);*/
Damien Leroux's avatar
Damien Leroux committed
708
        }
709

710
711
712
713
714
715
    void
        add_blocks(const model_block_collection& mbc)
        {
            m_computed = false;
            m_blocks.insert(mbc.begin(), mbc.end());
        }
Damien Leroux's avatar
Damien Leroux committed
716

717
718
719
720
721
722
723
724
725
726
727
728
    void
        remove_block(const value<model_block_type>& x)
        {
            m_computed = false;
            auto i = m_blocks.begin();
            auto j = m_blocks.end();
            while (i != j && i->second != x) ++i;
            if (i != j) {
                m_blocks.erase(i);
            }
            /*auto it = m_blocks.erase(std::find(m_blocks.begin(), m_blocks.end(), x));*/
            /*m_keys.erase(m_keys.begin() + (it - m_blocks.begin()));*/
729
730
731
732
733
734
735
736
        }

    void remove_block(const model_block_key& x)
    {
		m_computed = false;
        m_blocks.erase(x);
        /*auto it = m_keys.erase(std::find(m_keys.begin(), m_keys.end(), x));*/
        /*m_blocks.erase(m_blocks.begin() + (it - m_keys.begin()));*/
737
738
    }

Damien Leroux's avatar
Damien Leroux committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
    void enable_constraints()
    {
        if (!m_with_constraints) {
            m_with_constraints = true;
            m_computed = false;
        }
    }

    void disable_constraints()
    {
        if (m_with_constraints) {
            m_with_constraints = false;
            m_computed = false;
        }
    }

755
756
757
758
759
760
761
762
763
    void ghost_constraint(const chromosome* chr, double l1, double l2)
    {
        model_block_key k1, k2;
        k1 += std::make_pair(chr, l1);
        k2 += std::make_pair(chr, l2);
        m_ghost_constraint.first = k1;
        m_ghost_constraint.second = k2;
    }

764
765
766
767
768
769
770
    SolverType solver_type() const
    {
        return m_solver_type;
    }

	void compute()
	{
Damien Leroux's avatar
Damien Leroux committed
771
772
773
774
        /*MSG_DEBUG("Recomputing model with selection " << keys());*/
        if (m_computed) {
            return;
        }
775
776
777
		m_computed = true;
		m_X = new immediate_value<MatrixXd>(MatrixXd());
		m_coefficients = new immediate_value<MatrixXd>(MatrixXd());
778
		m_residuals = new immediate_value<MatrixXd>(MatrixXd());
779
		m_rss = new immediate_value<VectorXd>(VectorXd());
Damien Leroux's avatar
Damien Leroux committed
780
781
782
783
784
785
786
787

        if (m_with_constraints) {
            constraint_list constraints;
            size_t n_rows;
            size_t n_pop_rows = 0;
            size_t n_cols = 0;
            /* establish constraints */
            for (const auto& b: m_blocks) {
788
                auto tmp = compute_constraint(b.first, *b.second);
Damien Leroux's avatar
Damien Leroux committed
789
790
791
                constraints.insert(constraints.end(), tmp.begin(), tmp.end());
                n_cols += b.second->outerSize();
                n_pop_rows = b.second->innerSize();
792
            }
Damien Leroux's avatar
Damien Leroux committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
            /* compute total size */
            n_rows = n_pop_rows;
            for (const auto& cmap: constraints) {
                int block_rows = 0;
                for (const auto& kv: cmap) {
                    if (kv.second.innerSize() > block_rows) {
                        block_rows = kv.second.innerSize();
                    }
                }
                n_rows += block_rows;
            }
            /**m_X = MatrixXd(n_rows, n_cols);*/
            *m_X = MatrixXd::Zero(n_rows, n_cols);
            /*MSG_DEBUG("DEBUG X" << std::endl << (*m_X));*/
            /* now fill the matrix */
            n_rows = 0;
            n_cols = 0;
            for (const auto& b: m_blocks) {
                const model_block_type& mb = *b.second;
                m_X->block(n_rows, n_cols, mb.innerSize(), mb.outerSize()) = mb.data;
                /*MSG_DEBUG("DEBUG X" << std::endl << (*m_X));*/
                n_cols += mb.outerSize();
            }
            n_rows = n_pop_rows;
            for (const auto& cmap: constraints) {
                n_cols = 0;
                size_t row_incr = 0;
                for (const auto& b: m_blocks) {
                    auto it = cmap.find(b.first);
                    if (it != cmap.end()) {
                        const MatrixXd& constraint = it->second;
                        if (constraint.size()) {
                            m_X->block(n_rows, n_cols, constraint.innerSize(), constraint.outerSize()) = constraint;
                            row_incr = constraint.innerSize();
                        }
                    }
                    n_cols += b.second->outerSize();
                }
                n_rows += row_incr;
                /*MSG_DEBUG("DEBUG X" << std::endl << (*m_X));*/
            }
            m_Y->conservativeResize(n_rows, Eigen::NoChange_t());
            int dr = n_rows - n_pop_rows;
            int c = m_Y->outerSize();
            m_Y->block(n_pop_rows, 0, dr, c) = MatrixXd::Zero(dr, c);
838
        } else {
839
            *m_X = concat_right(m_blocks);
840
        }
Damien Leroux's avatar
Damien Leroux committed
841
842
843
844
        /*MSG_DEBUG("DEBUG X" << std::endl << (*m_X));*/
        /*MSG_DEBUG("DEBUG Y" << std::endl << (*m_Y));*/

        /*MSG_DEBUG("X:" << std::endl << (*m_X));*/
845
846
847
848
849
850
851
852
853
854
855
        /*MSG_DEBUG(MATRIX_SIZE(X()) << ' ' << MATRIX_SIZE(Y()) << std::endl);*/
        /*MSG_DEBUG("XtX" << std::endl <<*/
                    /*(m_X->transpose() * (*m_X)));*/
        /*MSG_DEBUG("XtX^-1" << std::endl << XtX_pseudo_inverse());*/
        /*MSG_DEBUG("XtX^-1 * Xt * Y" << std::endl <<*/
                /*XtX_pseudo_inverse() * X().transpose() * Y());*/

        /*! IMPORTANT NOTE
         * Either ColPivHouseholderQR or SVD give BAD results with our typical matrices.
         * There is only FullPivHouseholderQR to give acceptable results.
         */
856
857
858
859
860
861
862
863
864
865
866
        /*MSG_DEBUG((*m_X));*/
        int m_columns = m_X->outerSize();
        FullPivHouseholderQR<MatrixXd> solver(*m_X);
        {
            MatrixXd Q = solver.matrixQ();
            MatrixXd QR = solver.matrixQR();
            /*MSG_DEBUG("Q" << std::endl << Q);*/
            /*MSG_DEBUG("Q.Qt" << std::endl << (Q * Q.transpose()));*/
            /*MSG_DEBUG("QR" << std::endl << QR);*/
        }
        /*MSG_DEBUG("Threshold: " << COMPONENT_EPSILON);*/
867
        solver.setThreshold(sqrt(COMPONENT_EPSILON));
868
869
870
871
872
873
874
875
876
877
        m_rank = solver.rank();
        /*MSG_DEBUG("Rank: " << m_rank);*/
        m_coefficients->resize(m_columns, Y().outerSize());
        /*MSG_DEBUG(MATRIX_SIZE((*m_coefficients)));*/
        for (int i = 0; i < Y().outerSize(); ++i) {
            /*MSG_DEBUG(MATRIX_SIZE(Y().col(i)) << std::endl << Y().col(i));*/
            MatrixXd tmp = solver.solve(Y().col(i));
            /*MSG_DEBUG(MATRIX_SIZE(tmp) << std::endl << tmp);*/
            m_coefficients->col(i) = tmp;
        }
878
        /*MSG_DEBUG("Coefficients:" << std::endl << m_coefficients);*/
879
		*m_residuals = Y() - X() * (*m_coefficients);
880
        /*MSG_DEBUG("Residuals:" << std::endl << m_residuals);*/
881
		*m_rss = m_residuals->array().square().colwise().sum();
882
        /*MSG_DEBUG("RSS:" << std::endl << m_rss);*/
Damien Leroux's avatar
Damien Leroux committed
883
884
885
886
887
888
889
890
891
#if 0
        if (m_X->outerSize() == 129 && m_rank == 2) {
            MSG_DEBUG("==============================================================" << std::endl
                      << m_X << std::endl
                      << "rank=" << m_rank
                      << "rss=" << m_rss->transpose()
                      << "==============================================================" << std::endl);
        }
#endif
892
893
894
895
896
897
898
899
	}

    const MatrixXd& X() const
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
        return *m_X;
    }

900
	const VectorXd& rss() const
901
902
903
904
905
	{
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
		return *m_rss;
	}

906
    const MatrixXd& coefficients() const
907
908
909
910
911
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
        return *m_coefficients;
    }

912
    const MatrixXd& residuals() const
913
914
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
915
        return *m_residuals;
916
917
    }

918
    int rank() const
919
    {
920
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
921
922
923
924
925
        return m_rank;
    }

    const MatrixXd& Y() const
    {
926
927
928
929
930
		if (!m_Y) {
			MSG_ERROR("NULL Y!", "Fix the code");
			throw 0;
		}
        return *m_Y;
931
932
    }

933
    model extend(const model_block_key& k, const value<model_block_type>& m) const
934
    {
935
        model ret(*this);
936
        /*MSG_DEBUG("extend model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')');*/
937
        /*model ret(m_Y, m_solver_type);*/
938
939
        /*ret.add_block(X());*/
        ret.add_block(k, m);
940
941
942
        return ret;
    }

Damien Leroux's avatar
Damien Leroux committed
943
944
945
946
947
948
949
950
951
952
953
954
955
    model reduce(const chromosome* chr) const
    {
        model ret(*this);
        ret.remove_blocks_with_chromosome(chr);
        return ret;
    }

    model clone() const
    {
        model ret(*this);
        return ret;
    }

956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
    std::vector<std::vector<char>>
        labels_to_ancestor_names(const model_block_type& block) const
        {
            return labels_to_ancestor_names(block.column_labels);
        }

    std::vector<std::vector<char>>
        labels_to_ancestor_names(const std::vector<std::vector<char>>& column_labels) const
        {
            std::vector<std::vector<char>> colnames;
            for (const auto& cvec: column_labels) {
                colnames.emplace_back();
                auto& cn = colnames.back();
                for (char c: cvec) {
                    auto it = m_ancestor_names.find(c);
                    if (it == m_ancestor_names.end()) {
                        /*MSG_ERROR("Ancestor letter '" << c << "' doesn't exist in " << m_ancestor_names, "");*/
                        /*MSG_QUEUE_FLUSH();*/
                        cn.push_back(c);
                    } else {
                        const auto& n = it->second;
                        /*MSG_DEBUG("Replacing '" << c << "' with '" << n << '\'');*/
                        if (cn.size()) {
                            cn.push_back(',');
                        }
                        cn.insert(cn.end(), n.begin(), n.end());
                    }
                }
            }
            return colnames;
        }

988
    MatrixXd XtX() const
989
    {
990
        return X().transpose() * X();
991
992
    }

993
994
995
996
997
998
999
1000
    int dof() const { return rank(); }
    int
        n_obs() const
        {
            int n_rows = 0;
            for (const auto& kp: m_all_pops) {
                n_rows += (*kp)->size();
            }