model.h 24.5 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"
9

10
11
#include <cmath>
#include <boost/math/special_functions/beta.hpp>
12
#include <boost/math/special_functions/gamma.hpp>
13

14

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

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

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


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
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))
    {}

    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 << "?");*/
            if (selection.size() == mbk.selection.size()) {
                auto i = selection.begin();
                auto j = selection.end();
                auto mi = mbk.selection.begin();
                while (i != j) {
                    if (i->first < mi->first) {
                        /*MSG_DEBUG("YES");*/
                        return true;
                    } else if (i->first == mi->first) {
                        if (i->second < mi->second) {
                            /*MSG_DEBUG("YES");*/
                            return true;
                        } else if (i->second > mi->second) {
                            /*MSG_DEBUG("NO");*/
                            return false;
                        }
                    } else {
                        /*MSG_DEBUG("NO");*/
                        return false;
                    }
                    ++i; ++mi;
                }
                /*MSG_DEBUG("NO");*/
                return false;
            }
            /*MSG_DEBUG((selection.size() < mbk.selection.size() ? "YES" : "NO"));*/
            return selection.size() < mbk.selection.size();
        }

    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



281
static inline
282
bool
283
284
285
286
287
288
around_zero(double o)
{
    return o < COMPONENT_EPSILON && o > -COMPONENT_EPSILON;
}

static inline
289
bool
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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;
    }
}

305
306
307

using namespace Eigen;

308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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;
}

328
static inline
329
MatrixXd concat_right(const collection<model_block_type>& mat_vec)
330
331
332
{
    size_t full_size = 0;
    MatrixXd ret;
333
334
    for (auto m: mat_vec) {
        full_size += m->outerSize();
335
        /*MSG_DEBUG("preparing concat_right with matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
336
    }
337
    ret.resize(mat_vec.front()->innerSize(), full_size);
338
    full_size = 0;
339
    for (auto m: mat_vec) {
340
341
        /*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;*/
342
        ret.middleCols(full_size, m->outerSize()) = m->data;
343
        full_size += m->outerSize();
344
345
346
347
    }
    return ret;
}

348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
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;
}

386
static inline
387
MatrixXd concat_down(const std::vector<const MatrixXd*>& mat_vec)
388
389
390
{
    size_t full_size = 0;
    MatrixXd ret;
391
392
    for (auto m: mat_vec) {
        full_size += m->innerSize();
393
    }
394
    ret.resize(full_size, mat_vec.front()->outerSize());
395
    full_size = 0;
396
    for (auto m: mat_vec) {
397
398
        /*ret.block(full_size, 0, m->innerSize(), ret.outerSize()) = *m;*/
        ret.middleRows(full_size, m->innerSize()) = *m;
399
        full_size += m->innerSize();
400
401
402
403
404
405
406
407
408
    }
    return ret;
}


static inline
std::pair<int, MatrixXd>
rank_and_components(const MatrixXd& M)
{
409
    JacobiSVD<MatrixXd> svd(M, ComputeThinU);
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429

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


430
enum class SolverType { QR, SVD };
431

Damien Leroux's avatar
Damien Leroux committed
432

433
434
struct model {
    model()
435
        : m_Y(), m_blocks(), m_X(), m_rank(), m_rss(), m_coefficients(), m_solver_type(), m_computed(false)
436
437
438
439
    {}

    model(const value<MatrixXd>& y, SolverType st = SolverType::QR)
        : m_Y(y)
440
        , m_blocks(), m_X()
441
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
442
443
444
445
446
447
448
		, m_solver_type(st)
        , m_computed(false)
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
    {}

    model(const model& mo)
        : m_Y(mo.m_Y)
449
        , m_blocks(mo.m_blocks), m_X(mo.m_X)
450
		, m_rank(mo.m_rank), m_rss(mo.m_rss), m_coefficients(mo.m_coefficients)
451
        , m_residuals(mo.m_residuals)
452
453
454
455
456
457
		, m_solver_type(mo.m_solver_type)
        , m_computed(mo.m_computed)
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
    {}

    model& operator = (const model& mo)
458
459
460
# if 0
        = delete;
#else
461
462
    {
        m_Y = mo.m_Y;
463
        m_blocks = mo.m_blocks;
464
465
466
467
		m_computed = mo.m_computed;
		m_X = mo.m_X;
		m_rss = mo.m_rss;
		m_coefficients = mo.m_coefficients;
468
469
470
471
472
473
474
475
		m_residuals = mo.m_residuals;
        m_rank = mo.m_rank;
        return *this;
    }

    model& operator = (model&& mo)
    {
        m_Y = mo.m_Y;
476
477
        m_blocks.clear();
        m_blocks.swap(mo.m_blocks);
478
479
480
481
482
483
		m_computed = mo.m_computed;
		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;
484
485
        return *this;
    }
486
#endif
487
488
489

    bool operator == (const model& m) const
    {
490
        return m_Y == m.m_Y && m_blocks == m.m_blocks && m_rss == m.m_rss;
491
492
    }

493
    void add_block(const model_block_key& key, const value<model_block_type>& x)
494
495
    {
		m_computed = false;
496
497
498
499
        /*MSG_DEBUG("add_block(" << key << ", <some block>)");*/
        m_blocks[key] = x;
        /*m_blocks.push_back(x);*/
        /*m_keys.push_back(key);*/
500
501
    }

502
    void remove_block(const value<model_block_type>& x)
503
504
    {
		m_computed = false;
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
        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()));*/
521
522
523
524
    }

    void use_SVD()
    {
525
526
527
528
        if (m_solver_type != SolverType::SVD) {
    		m_computed = false;
            m_solver_type = SolverType::SVD;
        }
529
530
531
532
    }

    void use_QR()
    {
533
534
535
536
        if (m_solver_type != SolverType::QR) {
    		m_computed = false;
            m_solver_type = SolverType::QR;
        }
537
538
539
540
541
542
543
544
545
546
547
548
    }

    SolverType solver_type() const
    {
        return m_solver_type;
    }

	void compute()
	{
		m_computed = true;
		m_X = new immediate_value<MatrixXd>(MatrixXd());
		m_coefficients = new immediate_value<MatrixXd>(MatrixXd());
549
		m_residuals = new immediate_value<MatrixXd>(MatrixXd());
550
		m_rss = new immediate_value<VectorXd>(VectorXd());
551
552
        if (m_blocks.size() == 2) {
            MatrixXd tmp = concat_right(m_blocks);
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
    		m_X->resize(tmp.innerSize() + 1, tmp.outerSize());
            m_X->topRows(tmp.innerSize()) = tmp;
            (*m_X)(tmp.innerSize(), 0) = 0;
            (*m_X)(tmp.innerSize(), 1) = 1;
            (*m_X)(tmp.innerSize(), 2) = 1;
            if (m_Y->innerSize() != m_X->innerSize()) {
                /*MSG_DEBUG("X" << std::endl << m_X->transpose());*/
                /*MSG_DEBUG("X(" << m_X->innerSize() << ',' << m_X->outerSize() << ')');*/
                /*MSG_DEBUG("Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')');*/
                tmp = *m_Y;
                DUMP_FILE_LINE();
                m_Y = new immediate_value<MatrixXd>(tmp.innerSize() + 1, tmp.outerSize());
                /*MSG_DEBUG("Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')');*/
                DUMP_FILE_LINE();
                /*m_Y->resize(tmp.innerSize() + 1, tmp.outerSize());*/
                m_Y->topRows(tmp.innerSize()) = tmp;
                DUMP_FILE_LINE();
                m_Y->bottomRows(1) = MatrixXd::Zero(1, tmp.outerSize());
                DUMP_FILE_LINE();
            }
        } else {
574
            *m_X = concat_right(m_blocks);
575
        }
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
		if (m_solver_type == SolverType::QR) {
			int m_columns = m_X->outerSize();
			/*MSG_DEBUG("X(" << X().innerSize() << ',' << X().outerSize() << ')');*/
			/*MSG_DEBUG("Y(" << Y().innerSize() << ',' << Y().outerSize() << ')');*/
			FullPivHouseholderQR<MatrixXd> solver(*m_X);
			solver.setThreshold(COMPONENT_EPSILON);
			m_rank = solver.rank();
			m_coefficients->resize(m_columns, Y().outerSize());
			for (int i = 0; i < Y().outerSize(); ++i) {
				m_coefficients->col(i) = solver.solve(Y().col(i));
			}
		} else {
			JacobiSVD<MatrixXd> solver(*m_X);
            m_rank = 0;
            int nzsv = solver.nonzeroSingularValues();

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

			*m_coefficients = solver.solve(Y());
		}
598
599
		*m_residuals = Y() - X() * (*m_coefficients);
		*m_rss = m_residuals->array().square().colwise().sum();
600
601
602
603
604
605
606
607
	}

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

608
	const VectorXd& rss() const
609
610
611
612
613
	{
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
		return *m_rss;
	}

614
    const MatrixXd& coefficients() const
615
616
617
618
619
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
        return *m_coefficients;
    }

620
    const MatrixXd& residuals() const
621
622
    {
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
623
        return *m_residuals;
624
625
    }

626
    int rank() const
627
    {
628
		if (!m_computed) { throw std::runtime_error("Model not computed"); }
629
630
631
632
633
        return m_rank;
    }

    const MatrixXd& Y() const
    {
634
635
636
637
638
		if (!m_Y) {
			MSG_ERROR("NULL Y!", "Fix the code");
			throw 0;
		}
        return *m_Y;
639
640
    }

641
    model extend(const model_block_key& k, const value<model_block_type>& m) const
642
    {
643
        model ret(*this);
644
        /*MSG_DEBUG("extend model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')');*/
645
        /*model ret(m_Y, m_solver_type);*/
646
647
        /*ret.add_block(X());*/
        ret.add_block(k, m);
648
649
650
        return ret;
    }

651
    MatrixXd XtX() const
652
    {
653
        return X().transpose() * X();
654
655
    }

656
    MatrixXd XtX_pseudo_inverse() const
657
    {
658
        JacobiSVD<MatrixXd> inverter(XtX(), ComputeFullV);
659
660
661
662
663
        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);
664
            } else {
665
                inv_sv(i) = 0.;
666
667
            }
        }
668
        return V * inv_sv.asDiagonal() * V.transpose();
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
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
    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)
        {
            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)
        {
            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)
    {
        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 {};
        }

759
/*private:*/
760
    value<MatrixXd> m_Y;
761
762
763
    /*collection<model_block_type> m_blocks;*/
    /*std::vector<model_block_key> m_keys;*/
    model_block_collection m_blocks;
764
    value<MatrixXd> m_X;
765
    int m_rank;
766
767
768
    value<VectorXd> m_rss;
    value<MatrixXd> m_coefficients;
    value<MatrixXd> m_residuals;
769
    SolverType m_solver_type;
770
771
    /*decomposition_base* m_solver;*/
	bool m_computed;
772

Damien Leroux's avatar
Damien Leroux committed
773
774
775
776
777
public:
    friend
    inline
    md5_digest& operator << (md5_digest& md5, const model& m)
    {
778
        md5 << m.Y() << m.m_blocks;
Damien Leroux's avatar
Damien Leroux committed
779
        return md5;
780
781
    }

Damien Leroux's avatar
Damien Leroux committed
782
783
784
785
    friend
        inline
        std::ostream& operator << (std::ostream& os, const model& m)
        {
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
            /*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;
            pop_sections.reserve(active_settings->populations.size());
            int n_rows = 0;
            for (const auto& kp: active_settings->populations) {
                std::stringstream s;
                s << "POP " << kp.second.name;
                pop_sections.push_back(s.str());
                mws.add_row_section(pop_sections.back(), kp.second.size());
                n_rows += kp.second.size();
            }
            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;
809
810
        }

Damien Leroux's avatar
Damien Leroux committed
811
812
    size_t hash() const
    {
813
        std::hash<model_block_type> hm;
814
        std::hash<model_block_key> hk;
Damien Leroux's avatar
Damien Leroux committed
815
        size_t accum = 0;
816
817
818
        for (const auto& b: m_blocks) {
            accum ^= hk(b.first);
            accum ^= hm(*b.second);
819
        }
Damien Leroux's avatar
Damien Leroux committed
820
        return accum;
821
    }
Damien Leroux's avatar
Damien Leroux committed
822
};
823

Damien Leroux's avatar
Damien Leroux committed
824
825
826
827
828
829

namespace std {
template <>
struct hash<model> {
    size_t operator () (const model& m) { return m.hash(); }
};
830
831
832

}

833
834
#endif