frontends4.h 93.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
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
759
760
761
762
763
764
765
766
767
768
769
770
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef _SPEL_FRONTENDS_H_
#define _SPEL_FRONTENDS_H_

#include "cache2.h"
#include "basic_data.h"
#include "model.h"
/*#include "model/tests.h"*/

#include <boost/math/distributions/normal.hpp> // for normal_distribution
  using boost::math::normal; // typedef provides default type is double.
  using boost::math::cdf;
  using boost::math::mean;
  using boost::math::variance;
  using boost::math::quantile;
  using boost::math::complement;


typedef std::pair<const chromosome*, double> selected_locus;

inline bool operator < (const selected_locus& sl1, const selected_locus& sl2) { return sl1.first < sl2.first || (sl1.first == sl2.first && sl1.second < sl2.second); }

inline std::ostream& operator << (std::ostream& os, const selected_locus& sl) { return os << sl.first->name << ':' << sl.second; }


struct chromosome_search_domain {
    const chromosome* chrom;
    std::vector<double> loci;

    chromosome_search_domain(const chromosome* c, const std::vector<double>& l) : chrom(c), loci(l) {}

    struct const_iterator {
        const chromosome_search_domain* this_csd;
        std::vector<double>::const_iterator i;
        const_iterator() : this_csd(NULL), i(__()) {}
        const_iterator(const chromosome_search_domain* t, const std::vector<double>::const_iterator& i_) : this_csd(t), i(i_) {}
        bool operator == (const const_iterator& other) const { return i == other.i; }
        bool operator != (const const_iterator& other) const { return i != other.i; }
        /*bool operator < (const const_iterator& other) const { return i < other.i; }*/
        /*size_t operator - (const const_iterator& other) const { return i - other.i; }*/
        std::pair<const chromosome*, double> operator * () const { return {this_csd->chrom, *i}; }
        const_iterator& operator ++ () { ++i; return *this; }
        const_iterator& operator -- () { --i; return *this; }
        static std::vector<double>::const_iterator __() { static std::vector<double> _; return _.end(); }
    };

    const_iterator begin() const { return {this, loci.begin()}; }
    const_iterator end() const { return {this, loci.end()}; }
    const_iterator cbegin() const { return {this, loci.begin()}; }
    const_iterator cend() const { return {this, loci.end()}; }
};


typedef std::vector<chromosome_search_domain> genome_search_domain;

struct gsd_iterator {
    std::vector<chromosome_search_domain>::const_iterator csd_i, csd_j;
    chromosome_search_domain::const_iterator i, j;

    bool operator == (const gsd_iterator& other) const { return csd_i == other.csd_i && i == other.i; }
    bool operator != (const gsd_iterator& other) const { return csd_i != other.csd_i || i != other.i; }

    gsd_iterator&
        operator ++ ()
        {
            ++i;
            if (i == j) {
                MSG_DEBUG("at end of chromosome!");
                ++csd_i;
                if (csd_i != csd_j) {
                    i = csd_i->begin();
                    j = csd_i->end();
                } else {
                    i = {};
                    j = {};
                }
            }
            return *this;
        }

    std::pair<const chromosome*, double> operator * () const { return *i; }
};

namespace std {
    inline gsd_iterator begin(const genome_search_domain& gsd) { return {gsd.begin(), gsd.end(), gsd.begin()->begin(), gsd.begin()->end()}; }
    inline gsd_iterator end(const genome_search_domain& gsd) { return {gsd.end(), gsd.end(), {}, {}}; }
}


typedef std::vector<selected_locus> locus_set;

typedef std::vector<locus_set> model_descriptor;

std::pair<bool, double>
detect_strongest_qtl(chromosome_value chr, const locus_key& lk,
                     const model& M0, const std::vector<double> pos);

MatrixXd
ftest_along_chromosome(chromosome_value chr, const locus_key& lk,
                       const model& M0, const std::vector<double> pos);


/* Definitions:
 * - cofactor: isolated POP (single chromosome, single locus)
 * - QTLs: joint POP (single chromosome, single or multiple loc(i)us)
 *
 *
 * Configurations:
 * - with/without Dominance                          D
 * - with/without Constraints (can/can't estimate)   WC
 * - Joint/Single POP computation mode               JS
 *
 *
 * Steps:                           D   JS  WC
 * - establish skeleton                      
 *   - manual (marker list)                  
 *   - by step                               
 * - discover cofactors                 S    
 *   - manual                           S    
 *   - forward                          S    
 *   - backward                         S    
 * - detect QTLs                    ?   J   Y
 *   - CIM-                         ?   J   Y
 *   - iQTLm                        ?   J   Y
 *   - iQTLm++                      ?   J   Y
 * - OPTIONALLY analyze epistasis   ?   J   Y
 * - estimate parameters            
 *
 *
 * Operations:
 * - select chromosome
 * - cofactors to QTLs for the current chromosome
 * - QTLs to cofactors for the current chromosome
 * - test along the chromosome
 * - test along all chromosomes
 * - add cofactor (if current chromosome in product probability mode)
 * - add QTL (if current chromosome in joint probability mode)
 * - remove cofactor/QTL
 */


struct signal_display {
#ifdef SIGNAL_DISPLAY_ONELINER
    static const char* tick(double x)
    {
        static const char* ticks[9] = { " ", "\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588" };
        return ticks[x < 0. ? 0
                            : x >= 1. ? 8
                                      : ((int) floor(x * 9))];
    }

    VectorXd values;
    int imax_;
    bool above_;

    signal_display(const VectorXd& v, int imax, bool above)
        : values(v.innerSize()), imax_(imax), above_(above)
    {
        values = v;
#if 0
        int sig_cols = msg_handler_t::termcols() - 3;
        MSG_DEBUG("values.innerSize = " << values.innerSize());
        MSG_QUEUE_FLUSH();
        while (values.innerSize() >= sig_cols) {
            if (values.innerSize() & 1) {
                int sz = values.innerSize();
                values.conservativeResize(sz + 1);
                values(sz) = values(sz - 1);
            }
            int i = values.innerSize() >> 1;
            values = values.transpose() * kroneckerProduct(MatrixXd::Identity(i, i), MatrixXd::Constant(1, 2, .5));
            MSG_DEBUG("values.innerSize = " << values.innerSize());
            MSG_QUEUE_FLUSH();
        }
#endif
        double vmin = values.minCoeff();
        double vmax = values.maxCoeff();
        if (vmin == vmax) {
            values = (values.array() - vmin).matrix();
        } else {
            values = ((values.array() - vmin) / (vmax - vmin)).matrix();
        }
    }

    friend std::ostream& operator << (std::ostream& os, const signal_display& sd)
    {
        os << _WHITE << '[';
        for (int i = 0; i < sd.values.innerSize(); ++i) {
            if (i == sd.imax_) {
                os << (sd.above_ ? _GREEN : _RED);
            }
            os << tick(sd.values(i));
            if (i == sd.imax_) {
                os << _WHITE;
            }
        }
        return os << ']' << _NORMAL;
    }
#else
    braille_grid grid;

    signal_display(const chromosome& chr, const std::vector<double>& X, const VectorXd& y, int imax, double threshold)
        : grid(build(chr, X, y, imax, threshold))
    {}

    braille_grid
        build(const chromosome& chr, const std::vector<double>& X, const VectorXd& y, int imax, double threshold)
        {
            std::vector<double> Y(y.data(), y.data() + y.size());
            int padding_left = 0;
            int W = (int) (msg_handler_t::termcols() * .8);
            if (W > 1000) {
                W = 80;
            }
            braille_grid chr_map = chr.pretty_print(W, {}, {}, padding_left, false);

            braille_plot plot(W - padding_left, 5, 0, X.back(), 0, std::max(threshold, y(imax)));
            plot.plot(X, Y);
            plot.hline(threshold, 1, 1, 0, 255, 0);
            bool above = y(imax) > threshold;
            plot.vline(X[imax], 1, 0, above ? 0 : 255, above ? 255 : 0, 0);
            return plot.compose_vert(true, chr_map, false);
        }

    friend
        std::ostream&
        operator << (std::ostream& os, const signal_display& sd)
        {
            return os << sd.grid;
        }
#endif
};


struct QTL {
    std::string chromosome;
    double locus;
    std::vector<double> LOD_loci;
    std::vector<double> LOD;

    QTL(const std::string& n, double l, const std::vector<double>& x, const MatrixXd& y)
        : chromosome(n), locus(l), LOD_loci(x), LOD(y.data(), y.data() + y.size())
    {
        /*MSG_DEBUG("QTL at " << chromosome << ':' << locus);*/
        /*MSG_DEBUG(y);*/
        /*MSG_DEBUG(MATRIX_SIZE(y));*/
        /*MSG_DEBUG("" << LOD);*/
    }

    static
        double
        interpolate(double x0, double y0, double x1, double y1, double yT)
        {
            double delta_x = x1 - x0;
            double delta_y = y1 - y0;
            return delta_x * (yT - y0) / delta_y + x0;
        }

    std::pair<double, double>
        confidence_interval(const std::string& trait, const std::vector<QTL>& selection);
#if 0
        {
            /*MSG_DEBUG_INDENT_EXPR("[Confidence interval] ");*/
            /*MSG_DEBUG("LOD: " << LOD);*/
            double maxLOD = *std::max_element(LOD.begin(), LOD.end());
            double lod_cap = maxLOD - 1.5;
            /*MSG_DEBUG("max=" << maxLOD << " threshold=" << lod_cap);*/
            int i;
            for (i = 0; i < (int) LOD_loci.size() && LOD_loci[i] < locus && LOD[i] < lod_cap; ++i);
            /*MSG_DEBUG("LEFT i=" << i);*/
            double left;
            if (i > 0) {
                left = interpolate(LOD_loci[i - 1], LOD[i - 1], LOD_loci[i], LOD[i], lod_cap);
            } else {
                left = LOD_loci[i];
            }
            for (i = LOD_loci.size() - 1; i >= 0 && LOD_loci[i] > locus && LOD[i] < lod_cap; --i);
            /*MSG_DEBUG("RIGHT i=" << i);*/
            double right;
            if (i < (int) (LOD_loci.size() - 1)) {
                right = interpolate(LOD_loci[i], LOD[i], LOD_loci[i + 1], LOD[i + 1], lod_cap);
            } else {
                right = LOD_loci[i];
            }
            /*MSG_INFO("Confidence interval for " << chromosome << ':' << locus << " {" << left << ':' << right << '}');*/
            /*MSG_DEBUG_DEDENT;*/
            return {left, right};
        }
#endif
};


struct model_manager;

enum class AR { RSS=1, Rank=2, Test=4, Model=8, All=0xFF };

constexpr bool operator & (AR a, AR b) { return !!(((int) a) & ((int) b)); }


enum probability_mode { Joint, Single };


struct analysis_report {

    bool output_rss;
    bool output_rank;
    bool output_test;
    bool output_model;

    std::string report_path;

    std::string trait_name;

    std::string full_path;

    file report_file;

    std::map<std::string, std::map<double, std::string>> poi;
    std::map<std::string, std::map<double, std::pair<double, double>>> roi;

    analysis_report(const std::string& path, AR what)
        : output_rss(what & AR::RSS), output_rank(what & AR::Rank), output_test(what & AR::Test), output_model(what & AR::Model)
        , report_path(path)
        , trait_name()
        , full_path()
        , report_file()
        , poi(), roi()
    {
        ensure_directories_exist(report_path);
    }

    ~analysis_report()
    {
        report_file.close();
        report_file.open(MESSAGE(report_path << "/full_map.txt"), std::fstream::out);
        for (const auto& chr: active_settings->map) {
            report_file << chr.pretty_print(200, poi[chr.name], roi[chr.name]) << std::endl;
        }
    }

    void attach_model_manager(model_manager& mm);
    void detach_model_manager(model_manager& mm);

    void report_trait(const std::string& /*name*/, const MatrixXd& values)
    {
        static Eigen::IOFormat trait_format(Eigen::FullPrecision, Eigen::DontAlignCols, "\t", "\n", "", "", "", "");
        std::string filename = MESSAGE(full_path << '/' << "trait_values.txt");
        ofile of(filename);
        of << values.format(trait_format);
        of.close();
    }

    void report_lod(const QTL& qtl)
    {
        std::string filename = MESSAGE(full_path << '/' << qtl.chromosome << ':' << qtl.locus << "_LOD.txt");
        ofile of(filename);
        for (size_t i = 0; i < qtl.LOD.size(); ++i) {
            of << qtl.LOD_loci[i] << '\t' << qtl.LOD[i] << std::endl;
        }
        of.close();
    }

    void report_model(const model& Mcurrent)
    {
        if (output_model) {
            Mcurrent.output_X_to_file(full_path);
            Mcurrent.output_XtX_inv_to_file(full_path);
        }
    }

    /*enum ComputationType { NoTest=0, FTest=1, FTestLOD=2, R2=4, Chi2=8, Mahalanobis=16 };*/
    std::string
        computation_type_to_string(ComputationType ct)
        {
            std::stringstream ret;
            if (ct & FTest) { ret << "_FTest"; }
            if (ct & FTestLOD) { ret << "_FTestLOD"; }
            if (ct & R2) { ret << "_R2"; }
            if (ct & Chi2) { ret << "_Chi2"; }
            if (ct & Mahalanobis) { ret << "_Mahalanobis"; }
            return ret.str();
        }

    void report_computation(const model& Mcurrent, const chromosome* chrom_under_study, const computation_along_chromosome& cac, ComputationType ct, ComputationResults /*cr*/, const std::vector<double>& testpos, probability_mode pmode=Single)
    {
        if (output_test | output_rss | output_rank) {
            /*MSG_DEBUG(MATRIX_SIZE(cac.ftest_pvalue));*/
            /*MSG_DEBUG(MATRIX_SIZE(cac.rss));*/
            std::string path = MESSAGE(full_path << '/' << chrom_under_study->name);
            ensure_directories_exist(path);
            std::string filename
                = MESSAGE(path << '/' << Mcurrent.keys()
                        << (output_test ? computation_type_to_string(ct) : "")
                        << (output_rss ? "_RSS" : "")
                        << (output_rank ? "_Rank" : "")
                        << (pmode == Joint ? "_Joint" : "")
                        << ".txt"
                        );
            ofile f(filename);
            if (output_test) { f << '\t' << "Test"; }
            if (output_rss) { for (int i = 0; i < cac.rss.innerSize(); ++i) { f << '\t' << "RSS"; } }
            if (output_rank) { f << '\t' << "Rank"; }
            f << std::endl;
            for (size_t i = 0; i < testpos.size(); ++i) {
                f << testpos[i];
                if (output_test) {
                    switch(ct) {
                        case ComputationType::FTest:
                            f << '\t' << cac.ftest_pvalue(0, i);
                            break;
                        case ComputationType::FTestLOD:
                            f << '\t' << cac.ftest_lod(0, i);
                            break;
                        case ComputationType::Chi2:
                            f << '\t' << cac.chi2(0, i);
                            break;
                        default:
                            /*last_computation = NULL;*/
                            ;
                    };
                }
                if (output_rss) {
                    for (int j = 0; j < cac.rss.innerSize(); ++j) {
                        f << '\t' << cac.rss(j, i);
                    }
                }
                if (output_rank) {
                    f << '\t' << cac.rank(i);
                }
                f << std::endl;
            }
            f.close();
        }
    }

    void report_final_model(model_manager& mm);

    void report_qtls(std::vector<QTL>& qtls);
};


typedef std::pair<double, double> forbidden_interval_type;
typedef std::vector<forbidden_interval_type> forbidden_interval_vector_type;
typedef std::map<chromosome_value, forbidden_interval_vector_type> forbidden_interval_map_type;

inline bool operator < (const forbidden_interval_type& fi1, const forbidden_interval_type& fi2) { return fi1.first < fi2.first; }

struct search_interval_type;

struct test_result {
    search_interval_type* this_interval;
    const chromosome* chrom;
    double locus;
    double test_value;
    int index;
    bool over_threshold;
    model_block_key block_key;
    value<model_block_type> block;

    test_result()
        : chrom(NULL), locus(0), test_value(0), index(0), over_threshold(false), block_key(), block()
    {}

    test_result(search_interval_type* ti, const chromosome* c, double l, double tv, int i, bool ot, const model_block_key& mbk, const value<model_block_type>& mb)
        : this_interval(ti), chrom(c), locus(l), test_value(tv), index(i), over_threshold(ot), block_key(mbk), block(mb)
    {}

    test_result(const test_result& tr)
        : this_interval(tr.this_interval),
        chrom(tr.chrom), locus(tr.locus), test_value(tr.test_value),
        index(tr.index), over_threshold(tr.over_threshold),
        block_key(tr.block_key), block(tr.block)
    {}

    test_result&
        operator = (const test_result& tr)
        {
            this_interval = tr.this_interval;
            chrom = tr.chrom;
            locus = tr.locus;
            test_value = tr.test_value;
            index = tr.index;
            over_threshold = tr.over_threshold;
            block_key = tr.block_key;
            block = tr.block;
            return *this;
        }

    void reset()
    {
        chrom = NULL;
        locus = 0;
        test_value = 0;
        index = 0;
        over_threshold = false;
        block_key.selection.clear();
        block = value<model_block_type>();
    }

    friend
        std::ostream& operator << (std::ostream& os, const test_result& tr)
        {
            os << "<result chrom=" << (tr.chrom ? tr.chrom->name : "nil")
                << " locus=" << tr.locus
                << " test=" << tr.test_value
                << " at=" << tr.index
                << " over?=" << tr.over_threshold
                << " block_key=" << tr.block_key
                << '>';
            return os;
        }

    void
        select(model_manager1& mm)
        {
            this_interval->select(*this, mm.Mcurrent);
            /* TODO apply on model_manager */
        }
};


struct search_interval_type {
    probability_mode mode;
    /* all positions in this interval */
    std::vector<double> all_positions;
    /* all USED positions in this interval */
    std::vector<double> positions;
    /* positions actually used in the segment test (all_positions \ selection \ forbidden_intervals) */
    std::vector<double> effective_positions;
    /* current selection (subset of base model's selection for this search interval) */
    locus_key selection;
    /* the model blocks along the chromosome currently under study */
    collection<model_block_type> locus_blocks;
    /* dominance matrices per locus per population */
    std::vector<collection<parental_origin_per_locus_type>> dominance_blocks;
    test_result local_max;

    void
        test(int i0, computation_along_chromosome& cac, value<ComputationType> vct, value<ComputationResults> vcr, value<model>& Mbase,
             chromosome_value chr, const locus_key& lk, const std::vector<double>& steps, double threshold)
        {
            _recompute(lk, chr, steps, effective_positions);
            compute_along_interval<>(i0, cac, vct, vcr, Mcurrent, Mbase, model_block_key{{{chr, lk}}}, chr, effective_positions, locus_blocks);
            local_max = find_max(i0, vct, cac, chr, threshold);
        }


    void _recompute(const locus_key& lk, chromosome_value chrom_under_study, const std::vector<double>& loci, std::vector<double>& effective_pos)
    {
        std::vector<double>::const_iterator i = loci.begin(), j = loci.end();
        effective_pos.clear();
        effective_pos.reserve(loci.size());
        if (lk) {
            for (; i != j; ++i) {
                if (!lk->has(*i)) {
                    effective_pos.push_back(*i);
                }
            }
        } else {
            effective_pos.assign(i, j);
        }
        locus_blocks
            = compute_parental_origins_multipop(
                    all_pops,
                    as_value(chrom_under_study),
                    as_value(lk),
                    loci,
                    effective_pos);
    }

    test_result
        find_max(int i0, value<ComputationType> vct, computation_along_chromosome& cac, chromosome_value chrom_under_study, double threshold)
        {
            MatrixXd::ColsBlockXpr last_computation;
            switch(ct) {
                case ComputationType::FTest:
                    last_computation = cac.ftest_pvalue.middleCols(i0, effective_positions.size());
                    break;
                case ComputationType::FTestLOD:
                    last_computation = cac.ftest_lod.middleCols(i0, effective_positions.size());
                    break;
                case ComputationType::Chi2:
                    last_computation = cac.chi2.middleCols(i0, effective_positions.size());
                    break;
                default:
                    ;
            };
            if (effective_positions.size() != (size_t)(last_computation.outerSize())) {
                MSG_ERROR("LOCI INCONSISTENT WITH COMPUTATION RESULT (" << loci->size() << " vs " << last_computation.outerSize() << ")", "");
            }
            int i_max = -1;
            double max = -1;
            for (int i = 0; i < last_computation.outerSize(); ++i) {
                if (last_computation(0, i) >= max) {
                    max = last_computation(0, i);
                    i_max = i;
                }
            }
            if (i_max == -1) {
                return {};
            }
            /*model_block_key k = locus_base_key;*/
            model_block_key mbk = locus_base_key;
            mbk += std::make_pair(chrom_under_study, (*loci)[i_max]);
            /*MSG_DEBUG("locus_base_key " << locus_base_key << " mbk " << mbk);*/
            /*MSG_DEBUG("last_computation@" << last_computation);*/
            /*MSG_QUEUE_FLUSH();*/
            /*MSG_DEBUG((*last_computation));*/
            /*MSG_QUEUE_FLUSH();*/

#ifdef SIGNAL_DISPLAY_ONELINER
            /*signal_display sd(last_computation.transpose(), i_max, max > threshold);*/
            /*MSG_DEBUG("[COMPUTATION] " << loci->front() << sd << loci->back() << " max=" << max << " at " << (*loci)[i_max]);*/
#else
            /*signal_display sd(*chrom_under_study, effective_positions, last_computation.transpose(), i_max, threshold);*/
            /*MSG_DEBUG("[COMPUTATION] " << loci->front() << " ... " << loci->back() << " max=" << max << " at " << (*loci)[i_max] << std::endl << sd);*/
#endif

            return {chrom_under_study,
                effective_positions[i_max], max, i_max, max > threshold,
                mbk,
                locus_blocks[i_max]};
        }

    void select(const test_result& tr, value<model> M)
    {
        if (mode == Joint) {
            model_block_key mbk {{{tr.chrom, selection}}};
            M->remove_block(mbk);
        }
        M->add_block(tr.block_key, tr.block);
    }

    void deselect(double position, value<model> M)
    {
        if (mode == Joint) {
            model_block_key mbk {{{tr.chrom, selection}}};
            M->remove_block(mbk);
            /* Need to add the reduced block now */
        } else {
            locus_key lk;
            lk = lk + position;
            model_block_key mbk {{{tr.chrom, lk}}};
            M->remove_block(mbk);
        }
    }
};



struct model_manager1 {

    /* name of the studied trait */
    std::string trait_name;
    double threshold;
    /* populations used in this model */
    collection<population_value> all_pops;
    /* number of parents (for locus_key reduction of POP matrices) per population (same order) */
    std::vector<size_t> n_par;
    /* thy reference model */
    model Mcurrent;

    /* all steps, split by haplotypic intervals, inside which joint probabilities must be computed */
    std::map<chromosome_value, std::vector<std::pair<search_interval_type, locus_key>>> search_intervals;
    /* the current selection split by haplotypic interval */
    std::map<chromosome_value, std::vector<locus_key>> selection;
    forbidden_interval_map_type forbidden_intervals;

    /* structure to cache the results of the last computation along the chromosome */
    std::map<chromosome_value, computation_along_chromosome> cac;
    /* a direct access to the result of the last computation (&cac.TEST_TYPE) */
    std::map<MatrixXd*, chromosome_value> last_computation;

    std::map<std::vector<double>, chromosome_value> testpos;

    /* additiona, colpops.front()->ancestor_namesl data for output and postprocessing */
    std::map<std::string, std::map<double, std::pair<double, double>>> qtl_confidence_interval;

    analysis_report* reporter;

/* Construction
 */
    model_manager1(const std::string& trait, const collection<population_value>& colpops,
                   const value<MatrixXd>& y,
                   ComputationType ct = ComputationType::FTest,
                   SolverType st = SolverType::QR)
        : trait_name(trait)
        , all_pops(colpops)
        , pop_blocks()
        , n_par()
        , Mcurrent(y, colpops, (*colpops.front())->ancestor_names, st)
        , haplotypic_intervals()
        , locus_blocks()
        , cac()
        , last_computation(NULL)
        , pmode(Single)
        , testpos()
        , qtl_confidence_interval()
        , reporter(NULL)
    {
        Mcurrent.add_block({}, cross_indicator(trait));
        Mcurrent.compute();
        /*MSG_DEBUG("INITIAL MODEL SIZE: " << MATRIX_SIZE(Mcurrent.X()));*/
        /*MSG_QUEUE_FLUSH();*/
        /*for (const auto& kpop: active_settings->populations) {*/
        for (const auto& kpop: all_pops) {
            context_key ck(new context_key_struc(*kpop,
                                                 &active_settings->map[0],
                                                 std::vector<double>()));
            n_par.push_back(
                    make_value<Mem>(compute_state_to_parental_origin,
                                    as_value(ck),
                                    as_value(locus_key()))->innerSize());
        }
        pop_blocks.resize(active_settings->populations.size());
    }

    void
        cleanup_intervals(forbidden_interval_vector_type& intervals)
        {
            std::sort(intervals.begin(), intervals.end());
            forbidden_interval_vector_type output;
            output.reserve(intervals.size());
            output.push_back(intervals.front());
            for (size_t i = 1; i < intervals.size(); ++i) {
                if (output.back().second > intervals[i].first) {
                    output.back().second = std::max(output.back().second, intervals[i].second);
                } else {
                    output.push_back(intervals[i]);
                }
            }
            intervals.swap(output);
        }

    void
        add_forbidden_interval(chromosome_value chr, double start, double end)
        {
            auto& i = forbidden_intervals[chr];
            i.emplace_back(start, end);
            cleanup_intervals(i);
        }

    /* FIXME this can't remove a sub-interval or split intervals. need previous/next position info for each locus to do so. */
    void remove_forbidden_interval(chromosome_value chr, double start, double end)
        {
            auto& i = forbidden_intervals[chr];
            std::pair<double, double> p {start, end};
            auto it = std::find(i.begin(), i.end(), p);
            if (it != i.end()) {
                i.erase(it);
            }
        }

    void
        select(chromosome_value chr, double pos)
        {
            auto& hi_lk_vec = haplotypic_intervals.find(chr)->second;
            for (auto& hi_lk: hi_lk_vec) {
                if (pos >= hi_lk.first.front() && pos <= hi_lk.first.back()) {
                    hi_lk.second = hi_lk.second + pos;
                    /*add_forbidden_interval(chr, pos, pos);*/
                }
            }
        }

    void
        deselect(chromosome_value chr, double pos)
        {
            auto& hi_lk_vec = haplotypic_intervals.find(chr)->second;
            for (auto& hi_lk: hi_lk_vec) {
                if (pos >= hi_lk.first.front() && pos <= hi_lk.first.back()) {
                    hi_lk.second = hi_lk.second - pos;
                    /*remove_forbidden_interval(chr, pos, pos);*/
                }
            }
        }


    std::vector<std::pair<std::vector<double>, locus_key>>
        compute_intervals(const std::vector<std::pair<std::vector<double>, locus_key>>& haploz, const forbidden_interval_vector_type& forbidden_intervals)
        {
            std::vector<std::pair<std::vector<double>, locus_key>> ret;
            auto fi = forbidden_intervals.begin(), fj = forbidden_intervals.end();
            ret.reserve(haploz.size());
            for (const auto& steps_lk: haploz) {
                ret.emplace_back(std::vector<double>{}, steps_lk.second);
                ret.back().first.reserve(steps_lk.first.size());
                for (double d: steps_lk.first) {
                    for (; d < fi->first && fi != fj; ++fi);
                    if (fi != fj && d <= fi->second) {
                        continue;
                    }
                    ret.back().first.push_back(d);
                }
                if (ret.back().first.size() <= steps_lk.second->depth()) {  /* we need some effective loci outside the actual selection to test */
                    ret.pop_back();
                }
            }
            return ret;
        }

    /* TODO make use compute_along_interval, and make it possible to disable intervals */
    const std::map<chromosome_value, computation_along_chromosome>&
        custom_test(ComputationType ct, ComputationResults cr, value<model>& Mbase,
                    const forbidden_interval_map_type& forbidden, chromosome_value chr=NULL)
        {
            value<ComputationType> vct = ct;
            value<ComputationResults> vcr = cr;

            cac.clear();
            static forbidden_interval_vector_type no_intervals;
            for (auto& chr_intervals: haplotypic_intervals) {
                if (chr != NULL && chr != chr_intervals.first) {
                    continue;
                }
                chromosome_value chr = chr_intervals.first;
                auto forbint_i = forbidden.find(chr_intervals.first);
                const auto& forbidden_intervals = forbint_i == forbidden.end() ? no_intervals : forbint_i->second;
                auto intervals_lk = compute_intervals(chr_intervals.second, forbidden_intervals);

                std::vector<int> i0_vec = {0};
                for (const auto& vlk: intervals_lk) {
                    i0_vec.push_back(i0_vec.back() + vlk.first.size() - vlk.second->depth());
                }

                init_computation(cac[chr], ct, cr, i0_vec.back(), Mbase->Y().rows(), Mbase->Y().cols());

                auto i0i = i0_vec.begin();

                for (const auto& steps_lk: intervals_lk) {
                    test_one_interval(*i0i, vct, vcr, Mbase, chr, steps_lk.second, steps_lk.first);
                    ++i0i;
                }

                last_computation.clear();
                switch(ct) {
                    case ComputationType::FTest:
                        last_computation[chr] = &cac[chr].ftest_pvalue;
                        break;
                    case ComputationType::FTestLOD:
                        last_computation[chr] = &cac[chr].ftest_lod;
                        break;
                    case ComputationType::Chi2:
                        last_computation[chr] = &cac[chr].chi2;
                        break;
                    default:
                        last_computation[chr] = NULL;
                };

                if (reporter) { reporter->report_computation(Mcurrent, chr_intervals.first, cac[chr], ct, cr, testpos[chr]); }
            }
            return cac;
        }

    void
        test_one_interval(int i0, value<ComputationType> vct, value<ComputationResults> vcr, value<model>& Mbase,
                          chromosome_value chr, const locus_key& lk, const std::vector<double>& steps)
        {
            std::vector<double> effective_pos;
            _recompute(lk, chr, steps, effective_pos);
            compute_along_interval<>(i0, cac[chr], vct, vcr, Mcurrent, Mbase, model_block_key{{{chr, lk}}}, chr, effective_pos, locus_blocks);
            auto& tp = testpos[chr];
            tp.insert(tp.end(), effective_pos.begin(), effective_pos.end());
        }


    void _recompute(const locus_key& lk, chromosome_value chrom_under_study, const std::vector<double>& loci, std::vector<double>& effective_pos)
    {
        std::vector<double>::const_iterator i = loci.begin(), j = loci.end();
        effective_pos.clear();
        effective_pos.reserve(loci.size());
        if (lk) {
            for (; i != j; ++i) {
                if (!lk->has(*i)) {
                    effective_pos.push_back(*i);
                }
            }
        } else {
            effective_pos.assign(i, j);
        }
        locus_blocks
            = compute_parental_origins_multipop(
                    all_pops,
                    as_value(chrom_under_study),
                    as_value(lk),
                    loci,
                    effective_pos);
    }

    test_result
        find_max()
        {
            if (last_computation == NULL) {
                return {};
            }
            if (testpos.size() != (size_t)(last_computation->outerSize())) {
                MSG_ERROR("LOCI INCONSISTENT WITH COMPUTATION RESULT (" << loci->size() << " vs " << last_computation->outerSize() << ")", "");
            }
            int i_max = -1;
            double max = -1;
            for (int i = 0; i < last_computation->outerSize(); ++i) {
                if ((*last_computation)(0, i) >= max) {
                    max = (*last_computation)(0, i);
                    i_max = i;
                }
            }
            if (i_max == -1) {
                return {};
            }
            /*model_block_key k = locus_base_key;*/
            model_block_key mbk = locus_base_key;
            mbk += std::make_pair(chrom_under_study, (*loci)[i_max]);
            /*MSG_DEBUG("locus_base_key " << locus_base_key << " mbk " << mbk);*/
            /*MSG_DEBUG("last_computation@" << last_computation);*/
            /*MSG_QUEUE_FLUSH();*/
            /*MSG_DEBUG((*last_computation));*/
            /*MSG_QUEUE_FLUSH();*/

#ifdef SIGNAL_DISPLAY_ONELINER
            /*signal_display sd(last_computation->transpose(), i_max, max > threshold);*/
            /*MSG_DEBUG("[COMPUTATION] " << loci->front() << sd << loci->back() << " max=" << max << " at " << (*loci)[i_max]);*/
#else
            /*signal_display sd(*chrom_under_study, testpos, last_computation->transpose(), i_max, threshold);*/
            /*MSG_DEBUG("[COMPUTATION] " << loci->front() << " ... " << loci->back() << " max=" << max << " at " << (*loci)[i_max] << std::endl << sd);*/
#endif

            return {chrom_under_study,
                testpos[i_max], max, i_max, max > threshold,
                mbk,
                locus_blocks[i_max]};
        }
};


struct model_manager {
    /* name of the studied trait */
    std::string trait_name;
    /* populations used in this model */
    collection<population_value> all_pops;
    /* POP matrices per locus per population (in the order of active_settings->populations) */
    std::vector<collection<parental_origin_per_locus_type>> pop_blocks;
    /* number of parents (for locus_key reduction of POP matrices) per population (same order) */
    std::vector<size_t> n_par;
    /* thy reference model */
    model Mcurrent;
    /* thy cofactor/qtl acceptance threshold */
    double threshold;
    /* the test to perform (FTest, Chi2...) */
    ComputationType test_type;
    /* the lists of loci behind the expression "compute X along the chromosome" per chromosome */
    std::map<const chromosome*, value<std::vector<double>>> all_loci;
    /* the chrrently selected chromosome */
    const chromosome* chrom_under_study;
    /* the list of loci for the chromosome currently under study */
    value<std::vector<double>> loci;
    /* the model blocks along the chromosome currently under study */
    collection<model_block_type> locus_blocks;
    /* the keys for each model block in locus_blocks */
    /*std::vector<model_block_key> locus_keys;*/
    model_block_key locus_base_key;
    /* structure to cache the results of the last computation along the chromosome */
    computation_along_chromosome cac;
    /* a direct access to the result of the last computation (&cac.TEST_TYPE) */
    MatrixXd* last_computation;
    /* the current probability mode */
    probability_mode pmode;

    /* slight hack. */
    std::vector<double> testpos;

    /* additiona, colpops.front()->ancestor_namesl data for output and postprocessing */
    std::map<std::string, std::map<double, std::pair<double, double>>> qtl_confidence_interval;

    analysis_report* reporter;

/* Construction
 */
    model_manager(const std::string& trait, const collection<population_value>& colpops,
                  const value<MatrixXd>& y, double th,
                  ComputationType ct = ComputationType::FTest,
                  SolverType st = SolverType::QR)
        : trait_name(trait)
        , all_pops(colpops)
        , pop_blocks()
        , n_par()
        , Mcurrent(y, colpops, (*colpops.front())->ancestor_names, st)
        , threshold(th)
        , test_type(ct)
        , all_loci()
        , chrom_under_study(NULL)
        , loci()
        , locus_blocks()
        , cac()
        , last_computation(NULL)
        , pmode(Single)
        , testpos()
        , qtl_confidence_interval()
        , reporter(NULL)
    {
        Mcurrent.add_block({}, cross_indicator(trait));
        Mcurrent.compute();