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

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


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

Damien Leroux's avatar
Damien Leroux committed
453

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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532

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


static inline
MatrixXd matrix_inverse(const MatrixXd& m)
{
    /* 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
}



533
534
struct model {
    model()
535
        : 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()
536
537
    {}

538
    model(const value<MatrixXd>& y, const collection<const qtl_pop_type*>& pops, SolverType st = SolverType::QR)
539
        : m_Y(y)
540
        , m_blocks(), m_X()
541
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
542
543
		, m_solver_type(st)
        , m_computed(false)
Damien Leroux's avatar
Damien Leroux committed
544
        , m_with_constraints(false)
545
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
546
        , m_all_pops(pops)
547
548
549
550
551
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
    {}

    model(const model& mo)
        : m_Y(mo.m_Y)
552
        , m_blocks(mo.m_blocks), m_X(mo.m_X)
553
		, m_rank(mo.m_rank), m_rss(mo.m_rss), m_coefficients(mo.m_coefficients)
554
        , m_residuals(mo.m_residuals)
555
556
		, m_solver_type(mo.m_solver_type)
        , m_computed(mo.m_computed)
557
558
        , m_with_constraints(mo.m_with_constraints)
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
559
        , m_all_pops(mo.m_all_pops)
560
561
562
563
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
    {}

    model& operator = (const model& mo)
564
565
566
# if 0
        = delete;
#else
567
568
    {
        m_Y = mo.m_Y;
569
        m_blocks = mo.m_blocks;
570
		m_computed = mo.m_computed;
Damien Leroux's avatar
Damien Leroux committed
571
		m_with_constraints = mo.m_with_constraints;
572
		m_ghost_constraint = mo.m_ghost_constraint;
573
574
575
		m_X = mo.m_X;
		m_rss = mo.m_rss;
		m_coefficients = mo.m_coefficients;
576
577
		m_residuals = mo.m_residuals;
        m_rank = mo.m_rank;
Damien Leroux's avatar
Damien Leroux committed
578
        m_all_pops = mo.m_all_pops;
579
580
581
582
583
584
        return *this;
    }

    model& operator = (model&& mo)
    {
        m_Y = mo.m_Y;
585
586
        m_blocks.clear();
        m_blocks.swap(mo.m_blocks);
587
		m_computed = mo.m_computed;
Damien Leroux's avatar
Damien Leroux committed
588
		m_with_constraints = mo.m_with_constraints;
589
		m_ghost_constraint = mo.m_ghost_constraint;
590
591
592
593
594
		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;
595
596
        return *this;
    }
597
#endif
598

Damien Leroux's avatar
Damien Leroux committed
599
600
    constraint_list
    compute_constraint(const model_block_key& mbk)
601
    {
602
        constraint_list ret;
Damien Leroux's avatar
Damien Leroux committed
603
        if (mbk.empty()) {
604
            return ret;
Damien Leroux's avatar
Damien Leroux committed
605
606
        } else if (mbk.selection.size() == 1) {
            /* only one chromosome: do the contrast groups trick */
607
            ret = {{{mbk, contrast_groups(m_all_pops, mbk.selection.begin()->second)}}};
Damien Leroux's avatar
Damien Leroux committed
608
609
610
        } else {
            /* need the epistasis magic here */
        }
611
612
613
614
615
616
617
        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)}});
        }
        return ret;
618
619
    }

Damien Leroux's avatar
Damien Leroux committed
620
621
622
623
624
625

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

626
    void add_block(const model_block_key& key, const value<model_block_type>& x)
627
    {
628
        /*MSG_DEBUG("add_block(" << key << ", <some block>)");*/
Damien Leroux's avatar
Damien Leroux committed
629
        if (m_blocks.find(key) != m_blocks.end()) {
630
631
            return;
            /*throw key_already_exists(*this, key);*/
Damien Leroux's avatar
Damien Leroux committed
632
633
        }
		m_computed = false;
634
        m_blocks[key] = x;
Damien Leroux's avatar
Damien Leroux committed
635
        /*MSG_DEBUG("selection now: " << keys());*/
636
637
        /*m_blocks.push_back(x);*/
        /*m_keys.push_back(key);*/
638
639
    }

Damien Leroux's avatar
Damien Leroux committed
640
641
642
643
644
645
    void add_blocks(const model_block_collection& mbc)
    {
		m_computed = false;
        m_blocks.insert(mbc.begin(), mbc.end());
    }

646
    void remove_block(const value<model_block_type>& x)
647
648
    {
		m_computed = false;
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        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()));*/
665
666
    }

Damien Leroux's avatar
Damien Leroux committed
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
    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;
        }
    }

683
684
685
686
687
688
689
690
691
    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;
    }

692
693
694
695
696
697
698
    SolverType solver_type() const
    {
        return m_solver_type;
    }

	void compute()
	{
Damien Leroux's avatar
Damien Leroux committed
699
700
701
702
        /*MSG_DEBUG("Recomputing model with selection " << keys());*/
        if (m_computed) {
            return;
        }
703
704
705
		m_computed = true;
		m_X = new immediate_value<MatrixXd>(MatrixXd());
		m_coefficients = new immediate_value<MatrixXd>(MatrixXd());
706
		m_residuals = new immediate_value<MatrixXd>(MatrixXd());
707
		m_rss = new immediate_value<VectorXd>(VectorXd());
Damien Leroux's avatar
Damien Leroux committed
708
709
710
711
712
713
714
715
716
717
718
719

        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();
720
            }
Damien Leroux's avatar
Damien Leroux committed
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
            /* 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);
766
        } else {
767
            *m_X = concat_right(m_blocks);
768
        }
Damien Leroux's avatar
Damien Leroux committed
769
770
771
772
        /*MSG_DEBUG("DEBUG X" << std::endl << (*m_X));*/
        /*MSG_DEBUG("DEBUG Y" << std::endl << (*m_Y));*/

        /*MSG_DEBUG("X:" << std::endl << (*m_X));*/
773
774
775
776
777
778
779
780
781
782
783
        /*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.
         */
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
        /*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);*/
        solver.setThreshold(COMPONENT_EPSILON);
        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;
        }
806
        /*MSG_DEBUG("Coefficients:" << std::endl << m_coefficients);*/
807
		*m_residuals = Y() - X() * (*m_coefficients);
808
        /*MSG_DEBUG("Residuals:" << std::endl << m_residuals);*/
809
		*m_rss = m_residuals->array().square().colwise().sum();
810
        /*MSG_DEBUG("RSS:" << std::endl << m_rss);*/
Damien Leroux's avatar
Damien Leroux committed
811
812
813
814
815
816
817
818
819
#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
820
821
822
823
824
825
826
827
	}

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

828
	const VectorXd& rss() const
829
830
831
832
833
	{
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
		return *m_rss;
	}

834
    const MatrixXd& coefficients() const
835
836
837
838
839
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
        return *m_coefficients;
    }

840
    const MatrixXd& residuals() const
841
842
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
843
        return *m_residuals;
844
845
    }

846
    int rank() const
847
    {
848
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
849
850
851
852
853
        return m_rank;
    }

    const MatrixXd& Y() const
    {
854
855
856
857
858
		if (!m_Y) {
			MSG_ERROR("NULL Y!", "Fix the code");
			throw 0;
		}
        return *m_Y;
859
860
    }

861
    model extend(const model_block_key& k, const value<model_block_type>& m) const
862
    {
863
        model ret(*this);
864
        /*MSG_DEBUG("extend model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')');*/
865
        /*model ret(m_Y, m_solver_type);*/
866
867
        /*ret.add_block(X());*/
        ret.add_block(k, m);
868
869
870
        return ret;
    }

Damien Leroux's avatar
Damien Leroux committed
871
872
873
874
875
876
877
878
879
880
881
882
883
    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;
    }

884
    MatrixXd XtX() const
885
    {
886
        return X().transpose() * X();
887
888
    }

889
    MatrixXd XtX_pseudo_inverse() const
890
    {
891
892
        return matrix_inverse(XtX());
#if 0
893
        /* FIXME Should NOT use SVD (see note in compute() */
894
        JacobiSVD<MatrixXd> inverter(XtX(), ComputeFullV);
895
896
897
898
899
        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);
900
            } else {
901
                inv_sv(i) = 0.;
902
903
            }
        }
904
905
906
907
908
909
910
911
912
913
914
915
#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 * XtX() * ret;
        if (!test.isApprox(ret, .00001)) {
            MSG_DEBUG("ret" << std::endl << ret << std::endl << "test" << std::endl << test);
        } else {
            MSG_DEBUG("XtX^-1 IS GOOD! Yeah man.");
        }
        return ret;
#else
916
        return V * inv_sv.asDiagonal() * V.transpose();
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
#endif
#endif
    }

    void output_X_to_file() const
    {
        static Eigen::IOFormat model_format(Eigen::FullPrecision, Eigen::DontAlignCols, "\t", "\n", "", "", "", "");
        filename_stream filename;
        filename << "Model_" << keys() << "_X.txt";
        std::ofstream(filename) << X().format(model_format);
    }

    void output_XtX_inv_to_file() const
    {
        static Eigen::IOFormat model_format(Eigen::FullPrecision, Eigen::DontAlignCols, "\t", "\n", "", "", "", "");
        filename_stream filename;
        filename << "Model_" << keys() << "_XtX_inv.txt";
        std::ofstream(filename) << XtX_pseudo_inverse().format(model_format);
935
936
    }

937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
    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
955
            m_computed = false;
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
            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
978
            m_computed = false;
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
            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
1000
        m_computed = false;