model.h 44.7 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
    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;
        }

193
194
195
196
197
198
199
200
201
202
203
204
205
    bool
        contains(const model_block_key& sub) const
        {
            for (const auto& kv: sub.selection) {
                auto it = selection.find(kv.first);
                if (it == selection.end() || kv.second != (kv.second & it->second)) {
                    return false;
                }
                
            }
            return true;
        }

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
            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
241
242
                   || (ti->first == mi->first && (ti->second->depth() < mi->second->depth()
                                                  || (ti->second->depth() == mi->second->depth() && ti->second < mi->second)));
243
            }
Damien Leroux's avatar
Damien Leroux committed
244
245
246

            /*MSG_DEBUG((ret ? "YES" : "NO"));*/
            return ret;
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        }

    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) {
276
                return os << "Cross";
277
278
279
            }
            os << i->first->name << '{' << i->second << '}';
            for (++i; i != j; ++i) {
280
                os << ',' << i->first->name << '{' << i->second << '}';
281
282
283
            }
            return os;
        }
284
285

    operator std::string () const { std::stringstream ret; ret << (*this); return ret.str(); }
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
};

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



312
static inline
313
bool
314
315
316
317
318
319
around_zero(double o)
{
    return o < COMPONENT_EPSILON && o > -COMPONENT_EPSILON;
}

static inline
320
bool
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
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;
    }
}

336
337
338

using namespace Eigen;

339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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;
}

359
static inline
360
MatrixXd concat_right(const collection<model_block_type>& mat_vec)
361
362
363
{
    size_t full_size = 0;
    MatrixXd ret;
364
365
    for (auto m: mat_vec) {
        full_size += m->outerSize();
366
        /*MSG_DEBUG("preparing concat_right with matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
367
    }
368
    ret.resize(mat_vec.front()->innerSize(), full_size);
369
    full_size = 0;
370
    for (auto m: mat_vec) {
371
372
        /*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;*/
373
        ret.middleCols(full_size, m->outerSize()) = m->data;
374
        full_size += m->outerSize();
375
376
377
378
    }
    return ret;
}

379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399

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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
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;
}

417
static inline
418
MatrixXd concat_down(const std::vector<const MatrixXd*>& mat_vec)
419
420
421
{
    size_t full_size = 0;
    MatrixXd ret;
422
423
    for (auto m: mat_vec) {
        full_size += m->innerSize();
424
    }
425
    ret.resize(full_size, mat_vec.front()->outerSize());
426
    full_size = 0;
427
    for (auto m: mat_vec) {
428
429
        /*ret.block(full_size, 0, m->innerSize(), ret.outerSize()) = *m;*/
        ret.middleRows(full_size, m->innerSize()) = *m;
430
        full_size += m->innerSize();
431
432
433
434
435
436
437
438
439
    }
    return ret;
}


static inline
std::pair<int, MatrixXd>
rank_and_components(const MatrixXd& M)
{
440
    JacobiSVD<MatrixXd> svd(M, ComputeThinU);
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

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


461
enum class SolverType { QR };
462

Damien Leroux's avatar
Damien Leroux committed
463
464
465
466
typedef std::vector<std::map<model_block_key, MatrixXd>> constraint_list;


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

Damien Leroux's avatar
Damien Leroux committed
469

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516

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
517
/*#define ULTRA_MEGA_PARANOID*/
518
519
520
static inline
MatrixXd matrix_inverse(const MatrixXd& m)
{
Damien Leroux's avatar
Damien Leroux committed
521
522
    /*return m.fullPivHouseholderQr().inverse();*/
    /*return m.inverse();*/
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
    /* 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
}



552
553
struct model {
    model()
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
        : 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() << ')'); }*/
569
570
    {}

571
    model(const value<MatrixXd>& y, const collection<const qtl_pop_type*>& pops, SolverType st = SolverType::QR)
572
        : m_Y(y)
573
        , m_blocks(), m_X()
574
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
575
576
		, m_solver_type(st)
        , m_computed(false)
Damien Leroux's avatar
Damien Leroux committed
577
        , m_with_constraints(false)
578
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
579
        , m_all_pops(pops)
580
        , m_ancestor_names((*pops.front())->ancestor_names)
581
582
583
584
585
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
    {}

    model(const model& mo)
        : m_Y(mo.m_Y)
586
        , m_blocks(mo.m_blocks), m_X(mo.m_X)
587
		, m_rank(mo.m_rank), m_rss(mo.m_rss), m_coefficients(mo.m_coefficients)
588
        , m_residuals(mo.m_residuals)
589
590
		, m_solver_type(mo.m_solver_type)
        , m_computed(mo.m_computed)
591
592
        , m_with_constraints(mo.m_with_constraints)
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
593
        , m_all_pops(mo.m_all_pops)
594
        , m_ancestor_names(mo.m_ancestor_names)
595
596
597
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
    {}

598
599
600
601
602
603
604
605
606
607
    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)
608
        , m_ancestor_names(mo.m_ancestor_names)
609
610
611
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
    {}

612
# if 0
613
614
    model&
        operator = (const model& mo)
615
616
        = delete;
#else
617
618
619
620
621
622
623
624
625
626
627
628
629
630
    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;
631
            m_ancestor_names = mo.m_ancestor_names;
632
633
            return *this;
        }
634

635
636
637
638
639
640
641
642
643
644
645
646
647
648
    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;
649
            m_ancestor_names.swap(mo.m_ancestor_names);
650
651
            return *this;
        }
652
#endif
653

Damien Leroux's avatar
Damien Leroux committed
654
    constraint_list
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
        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)}});
            }
700
            return ret;
Damien Leroux's avatar
Damien Leroux committed
701
        }
702

Damien Leroux's avatar
Damien Leroux committed
703
704
705
706
707
708

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

709
710
711
    void
        add_block(const model_block_key& key, const value<model_block_type>& x)
        {
712
            /*MSG_DEBUG("add_block(" << key << ", <some block>)");*/
713
            if (m_blocks.find(key) != m_blocks.end()) {
714
                /*MSG_DEBUG("Key already exists");*/
715
716
717
718
719
720
721
722
                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
723
        }
724

725
726
727
728
729
730
    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
731

732
733
734
735
736
737
738
    void
        remove_block(const value<model_block_type>& x)
        {
            auto i = m_blocks.begin();
            auto j = m_blocks.end();
            while (i != j && i->second != x) ++i;
            if (i != j) {
739
740
741
                m_computed = false;
                remove_dependencies(i->first);
                /*m_blocks.erase(i);*/
742
743
744
            }
            /*auto it = m_blocks.erase(std::find(m_blocks.begin(), m_blocks.end(), x));*/
            /*m_keys.erase(m_keys.begin() + (it - m_blocks.begin()));*/
745
746
        }

747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
    void
        remove_block(const model_block_key& x)
        {
            m_computed = false;
            remove_dependencies(x);
            /*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()));*/
        }

    void
        remove_dependencies(const model_block_key& mbk)
        {
            auto i = m_blocks.begin(), j = m_blocks.end();
            for (; i != j;) {
                if (i->first.contains(mbk)) {
                    auto tmp = i;
                    ++tmp;
                    m_blocks.erase(i);
                    i = tmp;
                } else {
                    ++i;
                }
            }
        }
772

Damien Leroux's avatar
Damien Leroux committed
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
    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;
        }
    }

789
790
791
792
793
794
795
796
797
    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;
    }

798
799
800
801
802
803
804
    SolverType solver_type() const
    {
        return m_solver_type;
    }

	void compute()
	{
Damien Leroux's avatar
Damien Leroux committed
805
806
807
808
        /*MSG_DEBUG("Recomputing model with selection " << keys());*/
        if (m_computed) {
            return;
        }
809
810
811
		m_computed = true;
		m_X = new immediate_value<MatrixXd>(MatrixXd());
		m_coefficients = new immediate_value<MatrixXd>(MatrixXd());
812
		m_residuals = new immediate_value<MatrixXd>(MatrixXd());
813
		m_rss = new immediate_value<VectorXd>(VectorXd());
Damien Leroux's avatar
Damien Leroux committed
814
815
816
817
818
819
820
821

        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) {
822
                auto tmp = compute_constraint(b.first, *b.second);
Damien Leroux's avatar
Damien Leroux committed
823
824
825
                constraints.insert(constraints.end(), tmp.begin(), tmp.end());
                n_cols += b.second->outerSize();
                n_pop_rows = b.second->innerSize();
826
            }
Damien Leroux's avatar
Damien Leroux committed
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
            /* 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);
872
        } else {
873
            *m_X = concat_right(m_blocks);
874
        }
Damien Leroux's avatar
Damien Leroux committed
875
876
877
878
        /*MSG_DEBUG("DEBUG X" << std::endl << (*m_X));*/
        /*MSG_DEBUG("DEBUG Y" << std::endl << (*m_Y));*/

        /*MSG_DEBUG("X:" << std::endl << (*m_X));*/
879
880
881
882
883
884
885
886
887
888
889
        /*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.
         */
890
891
892
893
894
895
896
897
898
899
900
        /*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);*/
901
        solver.setThreshold(sqrt(COMPONENT_EPSILON));
902
903
904
905
906
907
908
909
910
911
        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;
        }
912
        /*MSG_DEBUG("Coefficients:" << std::endl << m_coefficients);*/
913
		*m_residuals = Y() - X() * (*m_coefficients);
914
        /*MSG_DEBUG("Residuals:" << std::endl << m_residuals);*/
915
		*m_rss = m_residuals->array().square().colwise().sum();
916
        /*MSG_DEBUG("RSS:" << std::endl << m_rss);*/
Damien Leroux's avatar
Damien Leroux committed
917
918
919
920
921
922
923
924
925
#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
926
927
928
929
930
931
932
933
	}

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

934
	const VectorXd& rss() const
935
936
937
938
939
	{
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
		return *m_rss;
	}

940
    const MatrixXd& coefficients() const
941
942
943
944
945
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
        return *m_coefficients;
    }

946
    const MatrixXd& residuals() const
947
948
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
949
        return *m_residuals;
950
951
    }

952
    int rank() const
953
    {
954
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
955
956
957
958
959
        return m_rank;
    }

    const MatrixXd& Y() const
    {
960
961
962
963
964
		if (!m_Y) {
			MSG_ERROR("NULL Y!", "Fix the code");
			throw 0;
		}
        return *m_Y;
965
966
    }

967
    model extend(const model_block_key& k, const value<model_block_type>& m) const
968
    {
969
        model ret(*this);
970
        /*MSG_DEBUG("extend model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')');*/
971
        /*model ret(m_Y, m_solver_type);*/
972
973
        /*ret.add_block(X());*/
        ret.add_block(k, m);
974
975
976
        return ret;
    }

Damien Leroux's avatar
Damien Leroux committed
977
978
979
980
981
982
983
984
985
986
987
988
989
    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;
    }

990
991
992
993
994
995
996
997
998
999
1000
    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) {