model.h 75.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Spell-QTL  Software suite for the QTL analysis of modern datasets.
 * Copyright (C) 2016,2017  Damien Leroux <damien.leroux@inra.fr>, Sylvain Jasson <sylvain.jasson@inra.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

18
19
20
#ifndef _SPEL_MODEL_MODEL_H_
#define _SPEL_MODEL_MODEL_H_

21
22
#include <stdexcept>

23
24
25
/*#include <Eigen/SVD>*/
/*#include <Eigen/QR>*/
#include "eigen.h"
Damien Leroux's avatar
Damien Leroux committed
26
#include "beta_gamma.h"
27

28
29
#include <cmath>

30

31
#include "labelled_matrix.h"
32
#include "settings.h"
33
#include "print.h"
34
#include "data/chromosome.h"
35
36
37

/*#define COMPONENT_EPSILON (1.e-10)*/
#define COMPONENT_EPSILON (active_settings->tolerance)
38
39
40

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

41
42
43
44
struct model_block_key_struc;
typedef std::shared_ptr<model_block_key_struc> model_block_key;


Damien Leroux's avatar
Damien Leroux committed
45
46
struct model;

47
48
49
static inline
void f_test(const model& model_current, const model& model_new, int col_num, MatrixXd* pvalue, MatrixXd* lod);

Damien Leroux's avatar
Damien Leroux committed
50
51
52
53
54
55
56
57
58
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();
    }
};

59
typedef enum { mbk_Covar, mbk_CI, mbk_POP, mbk_Dominance, mbk_Interaction } key_type;
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
inline
collection<model_block_type>
disassemble_block_multipop(const model_block_type& block, const collection<const qtl_pop_type*>& all_pops)
{
    VectorXi keep = VectorXi::Zero(block.cols());
    int r0 = 0;
    collection<model_block_type> ret;
    ret.reserve(all_pops.size());
    for (const auto& vpop: all_pops) {
        const qtl_pop_type* pop = *vpop;
        auto sub_block = block.data.middleRows(r0, pop->size());
        size_t ncols = 0;
        for (int col = 0; col < sub_block.cols(); ++col) {
            keep(col) = !sub_block.col(col).isZero(active_settings->tolerance);
            ncols += keep(col);
        }
        /*MSG_DEBUG("disasm block keep = " << keep.transpose());*/
        /*MSG_QUEUE_FLUSH();*/
        ret.emplace_back(model_block_type{});
        auto& pop_block = *ret.back();
        pop_block.column_labels.reserve(ncols);
        pop_block.data.resize(pop->size(), ncols);
        int pcol = 0;
        for (int col = 0; col < sub_block.cols(); ++col) {
            if (keep(col)) {
                pop_block.data.col(pcol++) = sub_block.col(col);
                pop_block.column_labels.push_back(block.column_labels[col]);
            }
        }
        r0 += pop->size();
    }
    return ret;
}

inline
value<model_block_type>
assemble_block_multipop(const collection<model_block_type>& pop_blocks)
{
    std::map<std::vector<char>, int> col_indices;
    for (const auto& pb: pop_blocks) {
        for (const auto& v: pb->column_labels) {
            col_indices[v] = 0;
        }
    }

    int index = 0;
    for (auto& kv: col_indices) {
        kv.second = index++;
    }

    int r0 = 0;

    for (const auto& vpb: pop_blocks) {
        r0 += vpb->rows();
    }

    value<model_block_type> ret = model_block_type{};
    ret->data = MatrixXd::Zero(r0, col_indices.size());
    ret->column_labels.reserve(col_indices.size());
    for (const auto& kv: col_indices) {
        ret->column_labels.push_back(kv.first);
    }

    r0 = 0;

    for (const auto& vpb: pop_blocks) {
        const auto& pb = *vpb;
        for (int i = 0; i < pb.cols(); ++i) {
            int col = col_indices[pb.column_labels[i]];
            ret->data.block(r0, col, pb.rows(), 1) = pb.data.col(i);
        }
        r0 += pb.rows();
    }

    return ret;
}


139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154

struct model_block_key_struc {
    key_type type;

    const chromosome* chr;
    locus_key loci;
    model_block_key left, right;

    model_block_key_struc(key_type kt, const chromosome* c, const locus_key& lk, const model_block_key& c1, const model_block_key& c2)
        : type(kt), chr(c), loci(lk), left(c1), right(c2)
    {}

    size_t
        order() const
        {
            switch (type) {
155
156
                case mbk_Covar:
                case mbk_CI:
157
158
159
160
161
162
163
164
                case mbk_POP: return 1; // loci->depth();
                case mbk_Dominance: return 2; // 2 * loci->depth();
                case mbk_Interaction: return left->order() + right->order();
            };
            return 0;
        }

    static
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    model_block_key
    cross_indicator()
    {
        model_block_key void_;
        locus_key void_lk;
        return std::make_shared<model_block_key_struc>(mbk_CI, (const chromosome*) NULL, void_lk, void_, void_);
    }

    static
    model_block_key
    covariables()
    {
        model_block_key void_;
        locus_key void_lk;
        return std::make_shared<model_block_key_struc>(mbk_Covar, (const chromosome*) NULL, void_lk, void_, void_);
    }
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

    static
        model_block_key
        pop(const chromosome* c, locus_key loci)
        {
            model_block_key void_;
            return std::make_shared<model_block_key_struc>(mbk_POP, c, loci, void_, void_);
        }

    static
        model_block_key
        dominance(const model_block_key& haplo)
        {
            model_block_key void_;
            locus_key void_lk;
            return std::make_shared<model_block_key_struc>(mbk_Dominance, (const chromosome*) NULL, void_lk, haplo, void_);
        }

    static
        model_block_key
        interaction(const model_block_key& l, const model_block_key& r)
        {
            locus_key void_lk;
            if (l < r) {
                return std::make_shared<model_block_key_struc>(mbk_Interaction, (const chromosome*) NULL, void_lk, l, r);
            } else {
                return std::make_shared<model_block_key_struc>(mbk_Interaction, (const chromosome*) NULL, void_lk, r, l);
            }
        }

211
212
213
214
215
216
217
218
219
220
221
222
223
    bool
    is_valid()
    {
        switch (type) {
            case mbk_Covar:
            case mbk_CI:          return true;
            case mbk_POP:         return !loci->is_empty();
            case mbk_Dominance:   return left->is_valid();
            case mbk_Interaction: return left->is_valid() && right->is_valid();
        };
        return false;  /* make compiler happy. */
    }

224
225
226
227
228
    friend
        std::ostream&
        operator << (std::ostream& os, const model_block_key_struc& mbk)
        {
            switch (mbk.type) {
229
230
231
                case mbk_Covar:
                    os << "Covar";
                    break;
232
233
234
235
236
237
238
239
240
241
                case mbk_CI:
                    os << "Cross";
                    break;
                case mbk_POP:
                    os << mbk.chr->name << ':' << mbk.loci;
                    break;
                case mbk_Dominance:
                    os << "Dom(" << mbk.left << ')';
                    break;
                case mbk_Interaction:
242
                    os << '(' << mbk.left << ":" << mbk.right << ')';
243
244
245
246
                    break;
            };
            return os;
        }
247

248
249
250
251
252
253
254
255
256
257
    friend
        std::ostream&
        operator << (std::ostream& os, const model_block_key& mbk)
        {
            return os << (*mbk);
        }

    bool
        can_interact_with(const model_block_key& mbk) const
        {
258
259
260
            if (type == mbk_CI || mbk->type == mbk_CI) {
                return active_settings->cross_indicator_can_interact;
            }
261
262
263
264
265
266
267
268
269
270
271
            auto v1 = flatten();
            auto v2 = mbk->flatten();
            decltype(v1) inter(std::min(v1.size(), v2.size()));
            auto e = std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), inter.begin());
            return e == inter.begin();
        }

    bool
        has_chromosome(const chromosome* c) const
        {
            switch (type) {
272
                case mbk_Covar:
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
                case mbk_CI:
                    return false;
                case mbk_POP:
                    return chr == c;
                case mbk_Dominance:
                    return left->has_chromosome(c);
                case mbk_Interaction:
                    return left->has_chromosome(c) || right->has_chromosome(c);
            };
            return false;
        }

    bool
        has_locus(const chromosome* c, double l) const
        {
            switch (type) {
289
                case mbk_Covar:
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
                case mbk_CI:
                    return false;
                case mbk_POP:
                    return chr == c && loci->has(l);
                case mbk_Dominance:
                    return left->has_locus(c, l);
                case mbk_Interaction:
                    return left->has_locus(c, l) || right->has_locus(c, l);
            };
            return false;
        }

    bool
        has(const model_block_key& mbk) const
        {
            return *this == *mbk
                || (left && left->has(mbk))
                || (right && right->has(mbk));
        }

    bool
        operator < (const model_block_key_struc& other) const
        {
            /* CI < POP < Dom < Inter
             * then sort on haplotypes
             * for interactions, sort on left&right children
             */
            switch (type) {
318
319
                case mbk_Covar:
                    return other.type != mbk_Covar;
320
                case mbk_CI:
321
                    return other.type != mbk_CI && other.type != mbk_Covar;
322
323
                case mbk_POP:
                    switch (other.type) {
324
                        case mbk_Covar:
325
326
327
328
329
330
331
332
333
                        case mbk_CI:
                            return false;
                        case mbk_POP:
                            return chr < other.chr || (chr == other.chr && loci < other.loci);
                        default:
                            return true;
                    };
                case mbk_Dominance:
                    switch (other.type) {
334
                        case mbk_Covar:
335
336
337
338
339
340
341
342
343
                        case mbk_CI:
                        case mbk_POP:
                            return false;
                        case mbk_Dominance:
                            return (*left) < (*other.left);
                        case mbk_Interaction:
                            return true;
                    };
                case mbk_Interaction:
344
345
346
347
348
349
350
351
352
353
                    {
                        auto o1 = order();
                        auto o2 = other.order();
                        if (o1 < o2) {
                            return true;
                        }
                        if (o1 > o2) {
                            return false;
                        }
                    }
354
355
356
357
358
359
360
361
362
363
                    switch (other.type) {
                        case mbk_Interaction:
                            return (*left) < (*other.left) || ((*left) == (*other.left) && (*right) < (*other.right));
                        default:
                            return false;
                    };
            };
            return false;
        }

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
    bool remove_position(const chromosome* chr, double locus)
    {
        switch (type) {
            case mbk_Covar:
            case mbk_CI:
                return true;
            case mbk_POP:
                if (has_locus(chr, locus)) {
                    loci = loci - locus;
                }
                return !loci->is_empty();
            case mbk_Dominance:
                return left->remove_position(chr, locus);
            case mbk_Interaction:
                bool a = left->remove_position(chr, locus);
                bool b = right->remove_position(chr, locus);
                return a && b;
        };
382
383
384
385
        if (!is_valid()) {
            MSG_ERROR("Created an invalid key!", "");
            throw 0;
        }
386
387
388
        return false;
    }

389
390
391
    friend
        inline
        bool
392
393
394
395
396
397
398
399
400
401
        operator < (const model_block_key& k1, const model_block_key& k2)
        {
            if (!k1) {
                return !!k2;
            }
            if (!k2) {
                return false;
            }
            return (*k1) < (*k2);
        }
402
403
404
405
406
407
408
409
410

    bool
        operator == (const model_block_key_struc& other) const
        {
            if (type != other.type) {
                return false;
            }
            switch (type) {
                case mbk_Interaction:
411
                    if (!((*right) == (*other.right))) {
412
413
414
                        return false;
                    }
                case mbk_Dominance:
415
                    if (!((*left) == (*other.left))) {
416
417
418
419
420
                        return false;
                    }
                    break;
                case mbk_POP:
                    return chr == other.chr && loci == other.loci;
421
                case mbk_Covar:
422
423
424
425
426
427
428
429
430
                case mbk_CI:
                    return true;
            };
            return false;
        }

    friend
        inline
        bool
431
432
433
434
        operator == (const model_block_key& k1, const model_block_key& k2)
        {
            return k1 && k2 && (*k1) == (*k2);
        }
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

    operator std::string () const { std::stringstream ret; ret << (*this); return ret.str(); }

private:
    typedef std::pair<const chromosome*, locus_key> item;

    std::vector<item>
        flatten() const
        {
            std::vector<item> ret;
            flatten(ret);
            std::sort(ret.begin(), ret.end(), [](const item& a, const item& b) { return a.first < b.first || (a.first == b.first && a.second < b.second); });
            return ret;
        }

    void
        flatten(std::vector<item>& ret) const
        {
            switch (type) {
                case mbk_Interaction:
                    right->flatten(ret);
                case mbk_Dominance:
                    left->flatten(ret);
                    break;
                case mbk_POP:
                    ret.emplace_back(chr, loci);
461
                case mbk_Covar:
462
463
464
465
466
467
468
469
                case mbk_CI:
                    ;
            };
        }

};


470
struct mbk_comp {
471
    bool
472
        operator () (const model_block_key& k1, const model_block_key& k2) const
473
        {
474
            return (*k1) < (*k2);
475
        }
476
477
};

478
479

typedef std::map<model_block_key, value<model_block_type>, mbk_comp> model_block_collection;
480
481
482
483
484
485

namespace std {
    template <>
        struct hash<model_block_key> {
            size_t operator () (const model_block_key& mbk) const
            {
486
487
488
489
                std::hash<const chromosome*> hc;
                std::hash<locus_key> hlk;
                size_t accum;
#if 0
490
491
492
493
494
495
496
                /* 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.
                 */
                for (const auto& kv: mbk.selection) {
                    accum = impl::ROTATE<7>(impl::ROTATE<7>(accum * hc(kv.first)) ^ hlk(kv.second));
                }
497
498
499
#endif
                accum = 0xbadc0def;
                switch (mbk->type) {
500
                    case mbk_Covar:
501
502
503
504
505
506
507
508
509
510
511
512
                    case mbk_CI:
                        return 0;
                    case mbk_POP:
                        accum = 0xdeadbe3f;
                        accum = impl::ROTATE<7>(impl::ROTATE<7>(accum * hc(mbk->chr)) ^ hlk(mbk->loci));
                        break;
                    case mbk_Dominance:
                        accum = impl::ROTATE<7>(accum * operator () (mbk->left));
                        break;
                    case mbk_Interaction:
                        accum = impl::ROTATE<7>(accum * operator () (mbk->left)) ^ impl::ROTATE<13>(accum * operator () (mbk->right));
                };
513
514
515
516
517
518
519
                return accum;
            }
        };
} // namespace std



520
static inline
521
bool
522
523
524
525
526
527
around_zero(double o)
{
    return o < COMPONENT_EPSILON && o > -COMPONENT_EPSILON;
}

static inline
528
bool
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
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;
    }
}

544
545
546

using namespace Eigen;

547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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;
}

567
static inline
568
MatrixXd concat_right(const collection<model_block_type>& mat_vec)
569
570
571
{
    size_t full_size = 0;
    MatrixXd ret;
572
573
    for (auto m: mat_vec) {
        full_size += m->outerSize();
574
        /*MSG_DEBUG("preparing concat_right with matrix(" << m->innerSize() << ',' << m->outerSize() << ')');*/
575
    }
576
    ret.resize(mat_vec.front()->innerSize(), full_size);
577
    full_size = 0;
578
    for (auto m: mat_vec) {
579
580
        /*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;*/
581
        ret.middleCols(full_size, m->outerSize()) = m->data;
582
        full_size += m->outerSize();
583
584
585
586
    }
    return ret;
}

587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
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;
}

625
static inline
626
MatrixXd concat_down(const std::vector<const MatrixXd*>& mat_vec)
627
628
629
{
    size_t full_size = 0;
    MatrixXd ret;
630
631
    for (auto m: mat_vec) {
        full_size += m->innerSize();
632
    }
633
    ret.resize(full_size, mat_vec.front()->outerSize());
634
    full_size = 0;
635
    for (auto m: mat_vec) {
636
637
        /*ret.block(full_size, 0, m->innerSize(), ret.outerSize()) = *m;*/
        ret.middleRows(full_size, m->innerSize()) = *m;
638
        full_size += m->innerSize();
639
640
641
642
643
644
645
646
647
    }
    return ret;
}


static inline
std::pair<int, MatrixXd>
rank_and_components(const MatrixXd& M)
{
648
    JacobiSVD<MatrixXd> svd(M, ComputeThinU);
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668

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


669
enum class SolverType { QR };
670

Damien Leroux's avatar
Damien Leroux committed
671
672
typedef std::vector<std::map<model_block_key, MatrixXd>> constraint_list;

673
674
675
676
677
678
679
680
681
682
683
684
inline
std::ostream& operator << (std::ostream& os, const constraint_list& cl)
{
    for (const auto& map: cl) {
        for (const auto& kv: map) {
            os << kv.first << std::endl << kv.second << std::endl;
        }
        os << "---" << std::endl;
    }
    return os;
}

Damien Leroux's avatar
Damien Leroux committed
685
686

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

Damien Leroux's avatar
Damien Leroux committed
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

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

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

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

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

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


Damien Leroux's avatar
Damien Leroux committed
737
/*#define ULTRA_MEGA_PARANOID*/
738
739
740
static inline
MatrixXd matrix_inverse(const MatrixXd& m)
{
Damien Leroux's avatar
Damien Leroux committed
741
742
    /*return m.fullPivHouseholderQr().inverse();*/
    /*return m.inverse();*/
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    /* 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
}


771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
struct gauss_elimination {
    MatrixXd block;
    std::vector<int> leading;

    gauss_elimination(const MatrixXd& mat)
        : block(mat)
        , leading(mat.rows())
    {
        for (int i = 0; i < block.rows(); ++i) {
            find_leading_coef(i);
        }

        sort_rows(0);
        for (int ref = 0; ref < block.rows(); ++ref) {
            if (is_null(ref)) {
                break;
            }
            anihilate_coef(ref, leading[ref]);
            sort_rows(ref);
        }
    }

    bool is_null(int row) const { return leading[row] == block.cols(); }
    int not_null(int row) const { return (int) (leading[row] != block.cols()); }

    int
        rank() const
        {
            /*MSG_DEBUG("echelon form" << std::endl << block);*/
            int count = 0;
            for (int i = 0; i < block.rows(); ++i) {
                count += not_null(i);
            }
            return count;
        }

    void
        sort_rows(int start)
        {
            std::vector<int> indices(block.rows() - start);
            int i = start;
            std::generate(indices.begin(), indices.end(), [&] () { return i++; });
            std::sort(indices.begin(), indices.end(), [&](int a, int b) { return leading[a] < leading[b]; });
            int sz = (int) indices.size();
            for (i = 0; i < sz; ++i) {
                if (i > indices[i]) {
                    swap_rows(i, indices[i]);
                }
            }
        }

    void
        swap_rows(int r1, int r2)
        {
            VectorXd tmp = block.row(r1);
            block.row(r1) = block.row(r2);
            block.row(r2) = tmp;
            std::swap(leading[r1], leading[r2]);
        }

    void
        anihilate_coef(int ref, int j)
        {
            for (int i = ref + 1; i < block.rows(); ++i) {
                if (leading[i] == j) {
                    anihilate_coef_in_row(ref, i, j);
                }
            }
        }

    void
        anihilate_coef_in_row(int ref, int r, int j)
        {
            block.row(r) *= 1. / block(r, j);
            block.row(r) -= block.row(ref);
            block(r, j) = 0;
            find_leading_coef(r);
            if (not_null(r)) {
                block.row(r) *= 1. / block(r, leading[r]);
            }
        }

    void
        find_leading_coef(int r)
        {
            int j;
            for (j = 0; j < block.cols() && block(r, j) == 0; ++j);
            leading[r] = j;
        }
};

862

863
864
struct model {
    model()
865
        : m_Y(), m_blocks(), m_X(), m_rank(), m_rss(), m_coefficients(), m_solver_type(), m_computed(false), m_with_constraints(false), m_ghost_constraint(), m_all_pops(), m_ancestor_names(), m_max_order(1), m_threshold(0), m_rank_fixer()
866
867
868

    {}

869
    model(const value<MatrixXd>& y, double threshold, const collection<const qtl_pop_type*>& pops, const std::map<char, std::string>& anam, size_t mo=1, SolverType st=SolverType::QR)
870
871
872
873
874
875
876
877
878
        : m_Y(y)
        , m_blocks(), m_X()
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
		, m_solver_type(st)
        , m_computed(false)
        , m_with_constraints(false)
        , m_ghost_constraint()
        , m_all_pops(pops)
        , m_ancestor_names(anam)
879
        , m_max_order(mo)
880
        , m_threshold(threshold)
881
        , m_rank_fixer()
882
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
883
884
    {}

885
    model(const value<MatrixXd>& y, double threshold, const collection<const qtl_pop_type*>& pops, size_t mo=1, SolverType st=SolverType::QR)
886
        : m_Y(y)
887
        , m_blocks(), m_X()
888
		, m_rank(), m_rss(), m_coefficients(), m_residuals()
889
890
		, m_solver_type(st)
        , m_computed(false)
Damien Leroux's avatar
Damien Leroux committed
891
        , m_with_constraints(false)
892
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
893
        , m_all_pops(pops)
894
        , m_ancestor_names((*pops.front())->ancestor_names)
895
        , m_max_order(mo)
896
        , m_threshold(threshold)
897
        , m_rank_fixer()
898
899
900
901
902
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << y.innerSize() << ',' << y.outerSize() << ')'); }*/
    {}

    model(const model& mo)
        : m_Y(mo.m_Y)
903
        , m_blocks(), m_X(mo.m_X)
904
		, m_rank(mo.m_rank), m_rss(mo.m_rss), m_coefficients(mo.m_coefficients)
905
        , m_residuals(mo.m_residuals)
906
907
		, m_solver_type(mo.m_solver_type)
        , m_computed(mo.m_computed)
908
909
        , m_with_constraints(mo.m_with_constraints)
        , m_ghost_constraint()
Damien Leroux's avatar
Damien Leroux committed
910
        , m_all_pops(mo.m_all_pops)
911
        , m_ancestor_names(mo.m_ancestor_names)
912
        , m_max_order(mo.m_max_order)
913
        , m_threshold(mo.m_threshold)
914
        , m_rank_fixer()
915
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
916
917
918
919
920
921
    {
        for (const auto& kv: mo.m_blocks) {
            model_block_key mbk = std::make_shared<model_block_key_struc>(*kv.first);
            m_blocks.emplace(mbk, kv.second);
        }
    }
922

923
924
    model(const value<MatrixXd>& y, const model& mo)
        : m_Y(y)
925
        , m_blocks(), m_X(mo.m_X)
926
927
928
929
930
931
932
		, m_rank(), m_rss(), m_coefficients()
        , m_residuals()
		, m_solver_type(mo.m_solver_type)
        , m_computed(false)
        , m_with_constraints(mo.m_with_constraints)
        , m_ghost_constraint()
        , m_all_pops(mo.m_all_pops)
933
        , m_ancestor_names(mo.m_ancestor_names)
934
        , m_max_order(mo.m_max_order)
935
        , m_threshold(mo.m_threshold)
936
        , m_rank_fixer()
937
    /*{ MSG_DEBUG("new model " << __LINE__ << " with Y(" << m_Y->innerSize() << ',' << m_Y->outerSize() << ')'); }*/
938
939
940
941
942
943
    {
        for (const auto& kv: mo.m_blocks) {
            model_block_key mbk = std::make_shared<model_block_key_struc>(*kv.first);
            m_blocks.emplace(mbk, kv.second);
        }
    }
944

945
# if 0
946
947
    model&
        operator = (const model& mo)
948
949
        = delete;
#else
950
951
952
953
954
955
956
957
958
959
960
961
962
963
    model&
        operator = (const model& mo)
        {
            m_Y = mo.m_Y;
            m_blocks = mo.m_blocks;
            m_computed = mo.m_computed;
            m_with_constraints = mo.m_with_constraints;
            m_ghost_constraint = mo.m_ghost_constraint;
            m_X = mo.m_X;
            m_rss = mo.m_rss;
            m_coefficients = mo.m_coefficients;
            m_residuals = mo.m_residuals;
            m_rank = mo.m_rank;
            m_all_pops = mo.m_all_pops;
964
            m_ancestor_names = mo.m_ancestor_names;
965
            m_max_order = mo.m_max_order;
966
            m_threshold = mo.m_threshold;
967
968
            return *this;
        }
969

970
971
972
973
974
975
976
977
978
979
980
981
982
983
    model&
        operator = (model&& mo)
        {
            m_Y = mo.m_Y;
            m_blocks.clear();
            m_blocks.swap(mo.m_blocks);
            m_computed = mo.m_computed;
            m_with_constraints = mo.m_with_constraints;
            m_ghost_constraint = mo.m_ghost_constraint;
            m_X = mo.m_X;
            m_rss = mo.m_rss;
            m_coefficients = mo.m_coefficients;
            m_residuals = mo.m_residuals;
            m_rank = mo.m_rank;
984
            m_ancestor_names.swap(mo.m_ancestor_names);
985
            m_max_order = mo.m_max_order;
986
            m_threshold = mo.m_threshold;
987
988
            return *this;
        }
989
#endif
990

991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
    struct rank_fixer_type {
        bool m_enabled = false;
        model* m_model = NULL;
        typedef std::map<model_block_key, std::vector<int>> col_order_map_type;
        col_order_map_type m_col_order, m_ctf;
        col_order_map_type::reverse_iterator m_current_block;
        std::vector<int>::iterator m_current_col;
        
        rank_fixer_type() : m_enabled(false), m_model(NULL), m_col_order(), m_ctf() {}
        
        std::vector<int> cols_to_fix(const model_block_key& mbk) { return m_ctf[mbk]; }
        bool enabled() const { return m_enabled; }
        void disable() { m_enabled = false; }
        void enable(model& this_model)
        {
            m_enabled = true;
            m_model = &this_model;
            m_ctf.clear();
            for (const auto& kv: m_model->m_blocks) {
                auto& mb = kv.second;
                auto mass = mb->data.colwise().sum();
                std::vector<int> col_order(mb->cols());
                std::iota(col_order.begin(), col_order.end(), 0);
                std::sort(col_order.begin(), col_order.end(), [&] (int a, int b) { return mass(a) < mass(b); });
                std::swap(m_col_order[kv.first], col_order);
            }
            MSG_DEBUG("Have col_order: " << m_col_order);
            m_current_block = m_col_order.rbegin();
            m_current_col = m_current_block->second.begin();
            if (m_current_block != m_col_order.rend()) {
                m_ctf[m_current_block->first].push_back(*m_current_col);
            }
        }
        
        bool next(bool validate_previous_column)
        {
            MSG_DEBUG("[rank_fixer] next (did" << (validate_previous_column ? "" : "n't") << " keep previously constrained column)");
            if (!validate_previous_column) {
                m_ctf[m_current_block->first].pop_back();
            }
            if (m_current_block == m_col_order.rend()) {
                MSG_DEBUG("[rank_fixer] at end.");
                return false;
            }
            if (m_current_col == m_current_block->second.end()) {
                MSG_DEBUG("[rank_fixer] next block.");
                ++m_current_block;
                if (m_current_block != m_col_order.rend()) {
                    m_current_col = m_current_block->second.begin();
                }
            } else {
                MSG_DEBUG("[rank_fixer] next column.");
                ++m_current_col;
                if (m_current_col == m_current_block->second.end()) {
                    MSG_DEBUG("[rank_fixer] next block.");
                    ++m_current_block;
                    if (m_current_block != m_col_order.rend()) {
                        m_current_col = m_current_block->second.begin();
                    }
                }
            }
            if (m_current_block != m_col_order.rend()) {
                MSG_DEBUG("[rank_fixer] adding " << m_current_block->first << '#' << (*m_current_col));
                m_ctf[m_current_block->first].push_back(*m_current_col);
                return true;
            }
            return false;
        }
    };

Damien Leroux's avatar
Damien Leroux committed
1061
    constraint_list
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
    compute_constraint(const model_block_key& mbk, const model_block_type& mb)
    {
        auto ret = compute_constraint_for_block_type(mbk, mb);
//         MSG_DEBUG("compute_constraint");
        if (m_rank_fixer.enabled()) {
//             MSG_DEBUG("constraint count before column zeroing: " << ret.size());
            std::vector<int> cols_to_fix = m_rank_fixer.cols_to_fix(mbk);
            for (int c: cols_to_fix) {
                MatrixXd colzero = MatrixXd::Zero(1, mb.cols());
                colzero(0, c) = 1;
                ret.emplace_back(std::map<model_block_key, MatrixXd>{{mbk, colzero}});
            }
//             MSG_DEBUG("constraint count after column zeroing: " << ret.size());
        }
        return ret;
    }

    constraint_list
        compute_constraint_for_block_type(const model_block_key& mbk, const model_block_type& mb)
1081
1082
        {
            constraint_list ret;
1083
            if (mbk->type == mbk_CI) {
1084
1085
                return ret;
            /*} else if (mbk.selection.size() == 1) {*/
1086
            } else if (mbk->type == mbk_POP) {
1087
//                size_t n_qtl = mb.column_labels.front().size();
1088
1089
//                if (n_qtl == 1) {
                if (1) {
1090
1091
                    /* only one chromosome: do the contrast groups trick */
                    ret = {{{mbk, contrast_groups(m_all_pops, mbk->loci)}}};
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//                } else {
//                    MSG_DEBUG("Creating constraints for " << mbk);
//                    std::vector<std::set<char>> uniq_letters_per_qtl(mb.column_labels.front().size());
//                    /* need the epistasis magic here */
//                    for (const auto& vec: mb.column_labels) {
//                        auto i = uniq_letters_per_qtl.begin();
//                        for (char c: vec) { i->insert(c); ++i; }
//                    }
//                    std::vector<size_t> letter_counts(uniq_letters_per_qtl.size());
//                    for (size_t i = 0; i < letter_counts.size(); ++i) { letter_counts[i] = uniq_letters_per_qtl[i].size(); }
//                    size_t start = 1;
//                    size_t finish = (1 << letter_counts.size()) - 1;
//                    for (size_t variant = start; variant < finish; ++variant) {
//                        MatrixXd constraint = MatrixXd::Identity(1, 1);
//                        for (size_t i = 0; i < letter_counts.size(); ++i) {
//                            bool flat = (variant >> i) & 1;
//                            MatrixXd tmp;
//                            if (flat) {
//                                tmp = kroneckerProduct(constraint, MatrixXd::Ones(1, letter_counts[i]));
//                            } else {
//                                tmp = kroneckerProduct(constraint, MatrixXd::Identity(letter_counts[i], letter_counts[i]));
//                            }
//                            constraint = tmp;
//                        }
//                        ret.emplace_back();
//                        MSG_DEBUG("Created constraint for " << mbk);
//                        MSG_DEBUG(constraint);
//                        ret.back().insert({{mbk, constraint}});
//                    }
1121
1122
                }
            } else if (mbk->type == mbk_Interaction) {
1123
1124
                /*MSG_DEBUG("Computing constraint for interaction " << mbk);*/
                /*MSG_QUEUE_FLUSH();*/
1125
1126
1127
1128
1129
1130
1131
                auto b1 = m_blocks[mbk->left];
                auto b2 = m_blocks[mbk->right];
                int cols1 = b1->data.cols();
                int cols2 = b2->data.cols();
                constraint_list
                    C1 = compute_constraint(mbk->left, *b1),
                    C2 = compute_constraint(mbk->right, *b2);
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
                if (C1.size() == 0) {
                    C1 = {{{{mbk->left, MatrixXd::Ones(1, b1->cols())}}}};
                }
                if (C2.size() == 0) {
                    C2 = {{{{mbk->left, MatrixXd::Ones(1, b2->cols())}}}};
                }
                /*MSG_DEBUG("Computing interaction constraints from" << std::endl*/
                        /*<< "C1" << std::endl << C1*/
                        /*<< "C2" << std::endl << C2*/
                        /*);*/
1142
                MatrixXd constraint;
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
                MatrixXd ghost_columns;
                if (mb.cols() < b1->cols() * b2->cols()) {
                    ghost_columns = MatrixXd::Zero(b1->cols() * b2->cols(), mb.cols());
                    int i = 0;
                    int j = 0;
                    /*MSG_DEBUG("Computing ghost columns");*/
                    /*MSG_DEBUG("L1 " << b1->column_labels);*/
                    /*MSG_DEBUG("L2 " << b2->column_labels);*/
                    for (const auto& l1: b1->column_labels) {
                        for (const auto& l2: b2->column_labels) {
                            auto il = make_interaction_label(l1, l2);
                            /*MSG_DEBUG("-- compare " << il << " and " << mb.column_labels[j]);*/
                            if (il == mb.column_labels[j]) {
                                ghost_columns(i, j++) = 1;
                            }
                            i++;
                        }
                    }
                    /*MSG_DEBUG("ghost_columns redux" << std::endl << ghost_columns);*/
                }
1163
1164
1165
                for (const auto& map1: C1) {
                    for (const auto& c1: map1) {
                        constraint = kroneckerProduct(c1.second, MatrixXd::Identity(cols2, cols2));
1166
1167
1168
1169
                        if (ghost_columns.size()) {
                            constraint = constraint * ghost_columns;
                        }
                        ret.emplace_back();
1170
1171
1172
1173
1174
                        ret.back().insert({{mbk, constraint}});
                    }
                }
                for (const auto& map2: C2) {
                    for (const auto& c2: map2) {
1175
1176
1177
1178
1179
                        constraint = kroneckerProduct(MatrixXd::Identity(cols1, cols1), c2.second);
                        if (ghost_columns.size()) {
                            constraint = constraint * ghost_columns;
                        }
                        ret.emplace_back();
1180
                        ret.back().insert({{mbk, constraint}});
1181
1182
1183
1184
1185
1186
1187
1188
1189
                    }
                }
            }
            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)}});
            }
1190
1191
            /*MSG_DEBUG("Constraints for block " << mbk);*/
            /*MSG_DEBUG("" << ret);*/
1192
            return ret;
Damien Leroux's avatar
Damien Leroux committed
1193
        }
1194

Damien Leroux's avatar
Damien Leroux committed
1195
1196
1197
1198
1199
1200

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

1201
1202
1203
    void
        add_block(const model_block_key& key, const value<model_block_type>& x)
        {
1204
            /*MSG_DEBUG("add_block(" << key << ", <some block>)");*/
1205
1206
1207
1208
1209
1210
1211
1212
            if (!x) {
                MSG_ERROR("Attempting to insert a null block in the model.", "");
                abort();
            }
            if (!key->is_valid()) {
                MSG_ERROR("Attempting to insert an invalid block key in the model.", "");
                abort();
            }
1213
            if (m_blocks.find(key) != m_blocks.end()) {
1214
                /*MSG_DEBUG("Key already exists");*/
1215
1216
1217
                return;
                /*throw key_already_exists(*this, key);*/
            }
1218
1219
1220
1221
            if (!x) {
                MSG_ERROR("Attempting to insert a null block in the model.", "");
                abort();
            }
1222
            m_computed = false;
1223
            m_blocks.insert({key, x});
1224
1225
1226
            /*MSG_DEBUG("selection now: " << keys());*/
            /*m_blocks.push_back(x);*/
            /*m_keys.push_back(key);*/
Damien Leroux's avatar
Damien Leroux committed
1227
        }
1228

1229
1230
1231
    bool
        add_block_if_test_is_good(const model_block_key& key, const value<model_block_type>& x, const model& ref)
        {
1232
            MatrixXd pvalue(m_Y->cols(), 1);
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
            model tmp(*this);
            tmp.add_block(key, x);
            tmp.compute();
            f_test(ref, tmp, 0, &pvalue, NULL);
            if (pvalue(0, 0) < m_threshold) {
                return false;
            }
            add_block(key, x);
            MSG_DEBUG("New block " << key << " has an f-test pvalue of " << pvalue(0, 0) << " >= " << m_threshold);
            return true;
        }

1245
1246
1247
1248
    void
        add_blocks(const model_block_collection& mbc)
        {
            m_computed = false;
1249
1250
1251
1252
1253
            for (auto kv: mbc) {
                if (!kv.second) {
                    MSG_ERROR("Attempting to insert a null block in the model.", "");
                    abort();
                }
1254
1255
1256
1257
                if (!kv.first->is_valid()) {
                    MSG_ERROR("Attempting to insert an invalid block key in the model.", "");
                    abort();
                }
1258
            }
1259
1260
            m_blocks.insert(mbc.begin(), mbc.end());
        }
Damien Leroux's avatar
Damien Leroux committed
1261

1262
1263
1264
1265
1266
1267
1268
    void
        remove_block(const value<model_block_type>& x)
        {
            auto i = m_blocks.begin();
            auto j = m_blocks.end();
            while (i != j && i->second != x) ++i;
            if (i != j) {
1269
                m_computed = false;
1270
1271
1272
1273
1274
1275
                std::vector<model_block_collection::iterator> to_remove;
                /*auto mbk = i->first;*/
                /*remove_dependencies(mbk);*/
                for (auto b: reverse_dependencies(to_remove, i->first)) {
                    m_blocks.erase(b);
                }
1276
1277
1278
            }
            /*auto it = m_blocks.erase(std::find(m_blocks.begin(), m_blocks.end(), x));*/
            /*m_keys.erase(m_keys.begin() + (it - m_blocks.begin()));*/
1279
1280
        }

1281
    /* FIXME need dependency graph for block keys */
1282
1283
1284
    void
        remove_block(const model_block_key& x)
        {
1285
            std::vector<model_block_collection::iterator> to_remove;
1286
            m_computed = false;
1287
            /*remove_dependencies(x);*/
1288
1289
1290
            for (auto b: reverse_dependencies(to_remove, x)) {
                m_blocks.erase(b);
            }
1291
1292
1293
1294
1295
            /*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()));*/
        }

1296
1297
    const std::vector<model_block_collection::iterator>&
        reverse_dependencies(std::vector<model_block_collection::iterator>& to_remove, const model_block_key& x)
1298
        {
1299
1300
1301
1302
            /*std::vector<model_block_key> to_remove;*/
            for (auto i = m_blocks.begin(), j = m_blocks.end(); i != j; ++i) {
                if (/*(i->first->type == mbk_Dominance || i->first->type == mbk_Interaction) &&*/ i->first->has(x)) {
                    to_remove.push_back(i);
1303
1304
                }
            }
1305
1306
1307
1308
            /*for (const auto& mbk: to_remove) {*/
                /*remove_block(mbk);*/
            /*}*/
            return to_remove;
1309
1310
        }

1311
1312
1313
    void
        remove_dependencies(const model_block_key& mbk)
        {
1314
#if 0
1315
1316
            auto i = m_blocks.begin(), j = m_blocks.end();
            for (; i != j;) {
1317
                if (i->first->contains(mbk)) {
1318
1319
1320
1321
1322
1323
1324
1325
                    auto tmp = i;
                    ++tmp;
                    m_blocks.erase(i);
                    i = tmp;
                } else {
                    ++i;
                }
            }
1326
1327
1328
1329
1330
1331
1332
#else
            switch (mbk->type) {
                case mbk_Interaction:
                    remove_dependencies(mbk->right);
                case mbk_Dominance:
                    remove_dependencies(mbk->left);
                case mbk_POP:
1333
                case mbk_Covar:
1334
1335
1336
1337
1338
1339
1340
1341
                case mbk_CI:
                    ;
            };
            auto it = m_blocks.find(mbk);
            if (it != m_blocks.end()) {
                m_blocks.erase(it);
            }
#endif
1342
        }
1343

Damien Leroux's avatar
Damien Leroux committed
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
    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;
        }
    }

1360
1361
    void ghost_constraint(const chromosome* chr, double l1, double l2)
    {
1362
1363
1364
1365
1366
1367
1368
1369
        /*model_block_key k1, k2;*/
        /*k1 += std::make_pair(chr, l1);*/
        /*k2 += std::make_pair(chr, l2);*/
        locus_key lk, k1, k2;
        k1 = lk + l1;
        k2 = lk + l2;
        m_ghost_constraint.first = model_block_key_struc::pop(chr, k1);
        m_ghost_constraint.second = model_block_key_struc::pop(chr, k2);
1370
1371
    }

1372
1373
1374
1375
1376
    SolverType solver_type() const
    {
        return m_solver_type;
    }

1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
    void compute()
    {
        compute_impl();
        if (m_with_constraints && rank() < m_X->cols()) {
            MSG_WARNING("Insufficient rank in model matrix. Attempting to fix this automatically.");
            m_rank_fixer.enable(*this);
            bool keep;
//             MSG_DEBUG(X());
//             MSG_DEBUG("rank: " << rank());
            do {
                auto old_rank = rank();
                m_computed = false;
                compute_impl();
//                 MSG_DEBUG(X());
//                 MSG_DEBUG("rank: " << rank());
                keep = old_rank < rank();
            } while (rank() < m_X->cols() && m_rank_fixer.next(keep));
            m_rank_fixer.disable();
        }
    }
    
	void compute_impl()
1399
	{
1400
//        MSG_DEBUG('[' << std::this_thread::get_id() << "] Recomputing model with selection " << keys());
Damien Leroux's avatar
Damien Leroux committed
1401
1402
1403
        if (m_computed) {
            return;
        }
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416

        {
            auto i = m_blocks.begin(), j = m_blocks.end();
            for (; i != j;) {
                if (i->first->type == mbk_POP && i->first->loci->depth() == 0) {
                    auto tmp = i;
                    ++i;
                    m_blocks.erase(tmp);
                } else {
                    ++i;
                }
            }
        }
1417
//        MSG_DEBUG('[' << std::this_thread::get_id() << "] Filtered selection " << keys());
1418

1419
1420
1421
		m_computed = true;
		m_X = new immediate_value<MatrixXd>(MatrixXd());
		m_coefficients = new immediate_value<MatrixXd>(MatrixXd());
1422
		m_residuals = new immediate_value<MatrixXd>(MatrixXd());
1423
		m_rss = new immediate_value<VectorXd>(VectorXd());
Damien Leroux's avatar
Damien Leroux committed
1424
1425
1426
1427
1428
1429
1430
1431

        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) {
1432
                auto tmp = compute_constraint(b.first, *b.second);
Damien Leroux's avatar
Damien Leroux committed
1433
1434
1435
                constraints.insert(constraints.end(), tmp.begin(), tmp.end());
                n_cols += b.second->outerSize();
                n_pop_rows = b.second->innerSize();
1436
            }
Damien Leroux's avatar
Damien Leroux committed
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
            /* 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);
            /* 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;
1456
1457
//                MSG_DEBUG("DEBUG X" << std::endl << (*m_X));
//                MSG_QUEUE_FLUSH();
Damien Leroux's avatar
Damien Leroux committed
1458
1459
1460
                n_cols += mb.outerSize();
            }
            n_rows = n_pop_rows;
1461
//            MSG_DEBUG("n_rows=" << n_rows << " n_cols=" << n_cols);
1462
//            MSG_DEBUG("DEBUG X" << std::endl << (*m_X));
1463
            if (0) {
1464
1465
1466
1467
1468
1469
1470
                /*os << "<model Y(" << m.m_Y->innerSize() << ',' << m.m_Y->outerSize() << "), " << m.m_blocks.size() << " blocks>";*/
                MatrixXd big = MatrixXd::Zero(1, X().cols());
                model_print::matrix_with_sections<std::string, void, std::string, std::vector<char>> mws(big);
                /*model_print::matrix_with_sections<std::string, void, model_block_key, void> mws(m.X());*/
                set_column_sections(mws);
                MSG_DEBUG("DEBUG X" << std::endl << mws);
            }
Damien Leroux's avatar
Damien Leroux committed
1471
1472
1473
            for (const auto& cmap: constraints) {
                n_cols = 0;
                size_t row_incr = 0;
1474
//                MSG_DEBUG("row=" << n_rows << " col=" << n_cols);
1475
//                MSG_QUEUE_FLUSH();
Damien Leroux's avatar
Damien Leroux committed
1476
1477
1478
1479
                for (const auto& b: m_blocks) {
                    auto it = cmap.find(b.first);
                    if (it != cmap.end()) {
                        const MatrixXd& constraint = it->second;
1480
1481
//                        MSG_DEBUG('[' << std::this_thread::get_id() << "] Adding (" << constraint.innerSize() << ',' << constraint.outerSize() << ") constraint at " << n_rows << "," << n_cols << " within (" << m_X->rows() << ',' << m_X->cols() << ')');
//                        MSG_DEBUG(constraint);
Damien Leroux's avatar
Damien Leroux committed
1482
1483
1484
1485
1486