model.h 31.6 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
39
40
41
42
43
44
45
struct model_block_key {
    typedef std::map<const chromosome*, locus_key> selection_type;
    typedef selection_type::value_type selection_value_type;
    std::map<const chromosome*, locus_key> selection;

    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
228
            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
                   || (ti->first == mi->first && ti->second < mi->second);
229
            }
Damien Leroux's avatar
Damien Leroux committed
230
231
232

            /*MSG_DEBUG((ret ? "YES" : "NO"));*/
            return ret;
233
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
        }

    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



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

static inline
304
bool
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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;
    }
}

320
321
322

using namespace Eigen;

323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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;
}

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

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

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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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;
}

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


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

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


445
enum class SolverType { QR, SVD };
446

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


MatrixXd
contrast_groups(const collection<const population*>& all_pops, const locus_key& lk);

Damien Leroux's avatar
Damien Leroux committed
453

454
455
struct model {
    model()
Damien Leroux's avatar
Damien Leroux committed
456
        : m_Y(), m_blocks(), m_X(), m_rank(), m_rss(), m_coefficients(), m_solver_type(), m_computed(false), m_with_constraints(false), m_all_pops()
457
458
    {}

Damien Leroux's avatar
Damien Leroux committed
459
    model(const value<MatrixXd>& y, const collection<const population*>& pops, SolverType st = SolverType::QR)
460
        : m_Y(y)
461
        , m_blocks(), m_X()
462
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
463
464
		, m_solver_type(st)
        , m_computed(false)
Damien Leroux's avatar
Damien Leroux committed
465
466
        , m_with_constraints(false)
        , m_all_pops(pops)
467
468
469
470
471
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
    {}

    model(const model& mo)
        : m_Y(mo.m_Y)
472
        , m_blocks(mo.m_blocks), m_X(mo.m_X)
473
		, m_rank(mo.m_rank), m_rss(mo.m_rss), m_coefficients(mo.m_coefficients)
474
        , m_residuals(mo.m_residuals)
475
476
		, m_solver_type(mo.m_solver_type)
        , m_computed(mo.m_computed)
Damien Leroux's avatar
Damien Leroux committed
477
478
        , m_with_constraints(false)
        , m_all_pops(mo.m_all_pops)
479
480
481
482
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
    {}

    model& operator = (const model& mo)
483
484
485
# if 0
        = delete;
#else
486
487
    {
        m_Y = mo.m_Y;
488
        m_blocks = mo.m_blocks;
489
		m_computed = mo.m_computed;
Damien Leroux's avatar
Damien Leroux committed
490
		m_with_constraints = mo.m_with_constraints;
491
492
493
		m_X = mo.m_X;
		m_rss = mo.m_rss;
		m_coefficients = mo.m_coefficients;
494
495
		m_residuals = mo.m_residuals;
        m_rank = mo.m_rank;
Damien Leroux's avatar
Damien Leroux committed
496
        m_all_pops = mo.m_all_pops;
497
498
499
500
501
502
        return *this;
    }

    model& operator = (model&& mo)
    {
        m_Y = mo.m_Y;
503
504
        m_blocks.clear();
        m_blocks.swap(mo.m_blocks);
505
		m_computed = mo.m_computed;
Damien Leroux's avatar
Damien Leroux committed
506
		m_with_constraints = mo.m_with_constraints;
507
508
509
510
511
		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;
512
513
        return *this;
    }
514
#endif
515

Damien Leroux's avatar
Damien Leroux committed
516
517
    constraint_list
    compute_constraint(const model_block_key& mbk)
518
    {
Damien Leroux's avatar
Damien Leroux committed
519
520
521
522
523
524
525
526
527
528
        if (mbk.empty()) {
            return {};
        } else if (mbk.selection.size() == 1) {
            /* only one chromosome: do the contrast groups trick */
            return {{{mbk, contrast_groups(m_all_pops, mbk.selection.begin()->second)}}};
        } else {
            /* need the epistasis magic here */
            return {};
        }
        return {};
529
530
    }

Damien Leroux's avatar
Damien Leroux committed
531
532
533
534
535
536

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

537
    void add_block(const model_block_key& key, const value<model_block_type>& x)
538
    {
539
        /*MSG_DEBUG("add_block(" << key << ", <some block>)");*/
Damien Leroux's avatar
Damien Leroux committed
540
        if (m_blocks.find(key) != m_blocks.end()) {
541
542
            return;
            /*throw key_already_exists(*this, key);*/
Damien Leroux's avatar
Damien Leroux committed
543
544
        }
		m_computed = false;
545
        m_blocks[key] = x;
Damien Leroux's avatar
Damien Leroux committed
546
        /*MSG_DEBUG("selection now: " << keys());*/
547
548
        /*m_blocks.push_back(x);*/
        /*m_keys.push_back(key);*/
549
550
    }

Damien Leroux's avatar
Damien Leroux committed
551
552
553
554
555
556
    void add_blocks(const model_block_collection& mbc)
    {
		m_computed = false;
        m_blocks.insert(mbc.begin(), mbc.end());
    }

557
    void remove_block(const value<model_block_type>& x)
558
559
    {
		m_computed = false;
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        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()));*/
    }

    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()));*/
576
577
578
579
    }

    void use_SVD()
    {
580
581
582
583
        if (m_solver_type != SolverType::SVD) {
    		m_computed = false;
            m_solver_type = SolverType::SVD;
        }
584
585
586
587
    }

    void use_QR()
    {
588
589
590
591
        if (m_solver_type != SolverType::QR) {
    		m_computed = false;
            m_solver_type = SolverType::QR;
        }
592
593
    }

Damien Leroux's avatar
Damien Leroux committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
    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;
        }
    }

610
611
612
613
614
615
616
    SolverType solver_type() const
    {
        return m_solver_type;
    }

	void compute()
	{
Damien Leroux's avatar
Damien Leroux committed
617
618
619
620
        /*MSG_DEBUG("Recomputing model with selection " << keys());*/
        if (m_computed) {
            return;
        }
621
622
623
		m_computed = true;
		m_X = new immediate_value<MatrixXd>(MatrixXd());
		m_coefficients = new immediate_value<MatrixXd>(MatrixXd());
624
		m_residuals = new immediate_value<MatrixXd>(MatrixXd());
625
		m_rss = new immediate_value<VectorXd>(VectorXd());
Damien Leroux's avatar
Damien Leroux committed
626
627
628
629
630
631
632
633
634
635
636
637

        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) {
                auto tmp = compute_constraint(b.first);
                constraints.insert(constraints.end(), tmp.begin(), tmp.end());
                n_cols += b.second->outerSize();
                n_pop_rows = b.second->innerSize();
638
            }
Damien Leroux's avatar
Damien Leroux committed
639
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
            /* 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);
684
        } else {
685
            *m_X = concat_right(m_blocks);
686
        }
Damien Leroux's avatar
Damien Leroux committed
687
688
689
690
        /*MSG_DEBUG("DEBUG X" << std::endl << (*m_X));*/
        /*MSG_DEBUG("DEBUG Y" << std::endl << (*m_Y));*/

        /*MSG_DEBUG("X:" << std::endl << (*m_X));*/
691
692
693
694
695
696
697
698
699
700
701
        /*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.
         */
702
		if (m_solver_type == SolverType::QR) {
Damien Leroux's avatar
Damien Leroux committed
703
            /*MSG_DEBUG((*m_X));*/
704
			int m_columns = m_X->outerSize();
705
			/*ColPivHouseholderQR<MatrixXd> solver(*m_X);*/
706
			FullPivHouseholderQR<MatrixXd> solver(*m_X);
707
708
709
            {
                MatrixXd Q = solver.matrixQ();
                MatrixXd QR = solver.matrixQR();
710
711
712
                /*MSG_DEBUG("Q" << std::endl << Q);*/
                /*MSG_DEBUG("Q.Qt" << std::endl << (Q * Q.transpose()));*/
                /*MSG_DEBUG("QR" << std::endl << QR);*/
713
            }
714
            /*MSG_DEBUG("Threshold: " << COMPONENT_EPSILON);*/
715
716
			solver.setThreshold(COMPONENT_EPSILON);
			m_rank = solver.rank();
717
            /*MSG_DEBUG("Rank: " << m_rank);*/
718
			m_coefficients->resize(m_columns, Y().outerSize());
719
            /*MSG_DEBUG(MATRIX_SIZE((*m_coefficients)));*/
720
			for (int i = 0; i < Y().outerSize(); ++i) {
721
                /*MSG_DEBUG(MATRIX_SIZE(Y().col(i)) << std::endl << Y().col(i));*/
722
                MatrixXd tmp = solver.solve(Y().col(i));
723
                /*MSG_DEBUG(MATRIX_SIZE(tmp) << std::endl << tmp);*/
724
				m_coefficients->col(i) = tmp;
725
726
			}
		} else {
727
728
            MatrixXd x = *m_X;
			JacobiSVD<MatrixXd> solver(x);
729
730
731
732
733
734
735
            m_rank = 0;
            int nzsv = solver.nonzeroSingularValues();

            for (int i = 0; i < nzsv; ++i) {
                m_rank += !around_zero(solver.singularValues()(i));
            }

736
737
738
739
            MatrixXd y = Y();

            /* FIXME: there's a segfault somewhere around HERE. */
			*m_coefficients = solver.solve(y);
740
		}
741
        /*MSG_DEBUG("Coefficients:" << std::endl << m_coefficients);*/
742
		*m_residuals = Y() - X() * (*m_coefficients);
743
        /*MSG_DEBUG("Residuals:" << std::endl << m_residuals);*/
744
		*m_rss = m_residuals->array().square().colwise().sum();
745
        /*MSG_DEBUG("RSS:" << std::endl << m_rss);*/
Damien Leroux's avatar
Damien Leroux committed
746
747
748
749
750
751
752
753
754
#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
755
756
757
758
759
760
761
762
	}

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

763
	const VectorXd& rss() const
764
765
766
767
768
	{
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
		return *m_rss;
	}

769
    const MatrixXd& coefficients() const
770
771
772
773
774
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
        return *m_coefficients;
    }

775
    const MatrixXd& residuals() const
776
777
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
778
        return *m_residuals;
779
780
    }

781
    int rank() const
782
    {
783
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
784
785
786
787
788
        return m_rank;
    }

    const MatrixXd& Y() const
    {
789
790
791
792
793
		if (!m_Y) {
			MSG_ERROR("NULL Y!", "Fix the code");
			throw 0;
		}
        return *m_Y;
794
795
    }

796
    model extend(const model_block_key& k, const value<model_block_type>& m) const
797
    {
798
        model ret(*this);
799
        /*MSG_DEBUG("extend model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')');*/
800
        /*model ret(m_Y, m_solver_type);*/
801
802
        /*ret.add_block(X());*/
        ret.add_block(k, m);
803
804
805
        return ret;
    }

Damien Leroux's avatar
Damien Leroux committed
806
807
808
809
810
811
812
813
814
815
816
817
818
    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;
    }

819
    MatrixXd XtX() const
820
    {
821
        return X().transpose() * X();
822
823
    }

824
    MatrixXd XtX_pseudo_inverse() const
825
    {
826
        JacobiSVD<MatrixXd> inverter(XtX(), ComputeFullV);
827
828
829
830
831
        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);
832
            } else {
833
                inv_sv(i) = 0.;
834
835
            }
        }
836
        return V * inv_sv.asDiagonal() * V.transpose();
837
838
    }

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
    model_block_collection
        blocks_with_chromosome(const chromosome* chr)
        {
            model_block_collection ret;
            for (const auto& bkv: m_blocks) {
                for (const auto c_lk: bkv.first.selection) {
                    if (c_lk.first == chr) {
                        ret.insert(bkv);
                        break;
                    }
                }
            }
            return ret;
        }

    model_block_collection
        extract_blocks_with_chromosome_and_locus(const chromosome* chr, double locus)
        {
Damien Leroux's avatar
Damien Leroux committed
857
            m_computed = false;
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
            auto bi = m_blocks.begin();
            auto bj = m_blocks.end();
            std::vector<decltype(bi)> sub;
            for (;bi != bj; ++bi) {
                for (const auto c_lk: bi->first.selection) {
                    if (c_lk.first == chr && c_lk.second->has(locus)) {
                        sub.push_back(bi);
                        break;
                    }
                }
            }
            model_block_collection ret;
            for (auto x: sub) {
                ret.insert(*x);
                m_blocks.erase(x);
            }
            return ret;
        }

    model_block_collection
        extract_blocks_with_chromosome(const chromosome* chr)
        {
Damien Leroux's avatar
Damien Leroux committed
880
            m_computed = false;
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
            auto bi = m_blocks.begin();
            auto bj = m_blocks.end();
            std::vector<decltype(bi)> sub;
            for (;bi != bj; ++bi) {
                for (const auto c_lk: bi->first.selection) {
                    if (c_lk.first == chr) {
                        sub.push_back(bi);
                        break;
                    }
                }
            }
            model_block_collection ret;
            for (auto x: sub) {
                ret.insert(*x);
                m_blocks.erase(x);
            }
            return ret;
        }

    void remove_blocks_with_chromosome(const chromosome* chr)
    {
Damien Leroux's avatar
Damien Leroux committed
902
        m_computed = false;
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
        auto bi = m_blocks.begin();
        auto bj = m_blocks.end();
        std::vector<decltype(bi)> sub;
        for (;bi != bj; ++bi) {
            for (const auto c_lk: bi->first.selection) {
                if (c_lk.first == chr) {
                    sub.push_back(bi);
                    break;
                }
            }
        }
        for (auto x: sub) {
            m_blocks.erase(x);
        }
    }

    std::vector<model_block_key>
        find_epistasis_dependencies(const model_block_key& mbk)
        {
            if (mbk.selection.size() == 1) {
                /* FIXME: all on the same chromosome, nothing to return? */
                return {mbk};
            }
            /* FIXME: how to handle epistasis with N QTLs on M chromosomes and N > M ? */
            return {};
        }

Damien Leroux's avatar
Damien Leroux committed
930
931
932
933
934
935
936
937
938
939
940
    bool operator == (const model& m) const
    {
        /* only compare keys */
        if (m.m_blocks.size() != m_blocks.size()) {
            return false;
        }
        auto i = m_blocks.begin(), j = m_blocks.end(), mi = m.m_blocks.begin();
        while (i != j && mi->first == i->first) { ++i; ++mi; }
        return i == j;
    }

941
/*private:*/
942
    value<MatrixXd> m_Y;
943
944
945
    /*collection<model_block_type> m_blocks;*/
    /*std::vector<model_block_key> m_keys;*/
    model_block_collection m_blocks;
946
    value<MatrixXd> m_X;
947
    int m_rank;
948
949
950
    value<VectorXd> m_rss;
    value<MatrixXd> m_coefficients;
    value<MatrixXd> m_residuals;
951
    SolverType m_solver_type;
952
953
    /*decomposition_base* m_solver;*/
	bool m_computed;
Damien Leroux's avatar
Damien Leroux committed
954
955
	bool m_with_constraints;
    collection<const population*> m_all_pops;
956

Damien Leroux's avatar
Damien Leroux committed
957
958
959
960
961
public:
    friend
    inline
    md5_digest& operator << (md5_digest& md5, const model& m)
    {
962
        md5 << m.Y() << m.m_blocks;
Damien Leroux's avatar
Damien Leroux committed
963
        return md5;
964
965
    }

Damien Leroux's avatar
Damien Leroux committed
966
967
968
969
    friend
        inline
        std::ostream& operator << (std::ostream& os, const model& m)
        {
970
971
972
973
974
975
976
977
            /*os << "<model Y(" << m.m_Y->innerSize() << ',' << m.m_Y->outerSize() << "), " << m.m_blocks.size() << " blocks>";*/
            model_print::matrix_with_sections<std::string, void, model_block_key, std::vector<char>> mws(m.X());
            /*model_print::matrix_with_sections<std::string, void, model_block_key, void> mws(m.X());*/
            for (const auto& kv: m.m_blocks) {
                mws.add_column_section(kv.first, kv.second->column_labels);
                /*mws.add_column_section(kv.first, kv.second->outerSize());*/
            }
            std::vector<std::string> pop_sections;
Damien Leroux's avatar
Damien Leroux committed
978
            pop_sections.reserve(m.m_all_pops.size());
979
            int n_rows = 0;
Damien Leroux's avatar
Damien Leroux committed
980
            for (const auto& kp: m.m_all_pops) {
981
                std::stringstream s;
Damien Leroux's avatar
Damien Leroux committed
982
                s << "POP " << (*kp)->name;
983
                pop_sections.push_back(s.str());
Damien Leroux's avatar
Damien Leroux committed
984
985
                mws.add_row_section(pop_sections.back(), (*kp)->size());
                n_rows += (*kp)->size();
986
987
988
989
990
991
992
            }
            if (n_rows < m.X().innerSize()) {
                static std::string constraints("CONSTRAINTS");
                mws.add_row_section(constraints, m.X().innerSize() - n_rows);
            }
            os << "Model Y(" << m.m_Y->innerSize() << ',' << m.m_Y->outerSize() << "), " << m.m_blocks.size() << " blocks" << std::endl;
            return os << mws;
993
994
        }

Damien Leroux's avatar
Damien Leroux committed
995
996
997
998
999
1000
    struct xtx_printable {
        model_print::matrix_with_sections<model_block_key, std::vector<char>, model_block_key, std::vector<char>> mws;
        xtx_printable(const model& m, bool inv)
            : mws(inv ? m.XtX_pseudo_inverse() : m.XtX())
        {
            for (const auto& kv: m.m_blocks) {