genoprob_computer2.h 23.8 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
21
22
#ifndef _SPEL_GENOPROB_COMPUTER_H_
#define _SPEL_GENOPROB_COMPUTER_H_

#include "geno_matrix.h"
#include "labelled_matrix.h"
Damien Leroux's avatar
Damien Leroux committed
23
#include "data/qtl_chromosome.h"
24
25


26
27
struct out_of_segment_exception : public std::exception {};

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

struct geno_prob_computer {
    const std::vector<double>* locus;
    const MatrixXd* LV;
    const geno_matrix* this_gen;
    std::unordered_map<double, MatrixXd> tr_cache;

    std::vector<MatrixXd> TR;
    MatrixXd init_kernel;
    /*MatrixXd redux;*/
    std::map<int, MatrixXd> left, right;
    MatrixXd redux;
    VectorXd inv_stat_dist;
    std::vector<label_type> unique_labels;

    geno_prob_computer()
        : locus(0), LV(0), this_gen(0), TR(), init_kernel(), left(), right(), redux(), inv_stat_dist()
    {}

47
48
49
50
51
52
53
54
55
56
57
    geno_prob_computer(const geno_prob_computer& tmp)
        : locus(tmp.locus)
        , LV(tmp.LV)
        , this_gen(tmp.this_gen)
        , left(std::map<int, MatrixXd>(tmp.left))
        , right(std::map<int, MatrixXd>(tmp.right))
        , redux(tmp.redux)
        , inv_stat_dist(tmp.inv_stat_dist)
        , unique_labels(tmp.unique_labels)
    {}

58
59
60
61
62
63
64
65
    geno_prob_computer(geno_prob_computer&& tmp)
        : locus(tmp.locus)
        , LV(tmp.LV)
        , this_gen(tmp.this_gen)
        , left(std::forward<std::map<int, MatrixXd>>(tmp.left))
        , right(std::forward<std::map<int, MatrixXd>>(tmp.right))
        , redux(tmp.redux)
        , inv_stat_dist(tmp.inv_stat_dist)
66
        , unique_labels(std::forward<std::vector<label_type>>(tmp.unique_labels))
67
68
69
70
71
72
73
74
75
76
77
78
79
    {}

    geno_prob_computer&
        operator = (geno_prob_computer&& tmp)
        {
            locus = tmp.locus;
            LV = tmp.LV;
            this_gen = tmp.this_gen;
            TR.swap(tmp.TR);
            left.swap(tmp.left);
            right.swap(tmp.right);
            redux = tmp.redux;
            inv_stat_dist = tmp.inv_stat_dist;
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
            unique_labels.swap(tmp.unique_labels);
            return *this;
        }

    geno_prob_computer&
        operator = (const geno_prob_computer& tmp)
        {
            locus = tmp.locus;
            LV = tmp.LV;
            this_gen = tmp.this_gen;
            TR = tmp.TR;
            left = tmp.left;
            right = tmp.right;
            redux = tmp.redux;
            inv_stat_dist = tmp.inv_stat_dist;
            unique_labels = tmp.unique_labels;
96
97
98
99
100
101
102
            return *this;
        }

    MatrixXd& compute_tr(double dist)
    {
        auto it = tr_cache.find(dist);
        if (it == tr_cache.end()) {
Damien Leroux's avatar
Damien Leroux committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
             auto& TR = tr_cache[dist] = this_gen->exp(dist);
//              if ((TR.array() > 1.).any() || (TR.array() < -1.e-13).any()) {
//                  double max = TR.array().abs().maxCoeff();
//                  double min = TR.minCoeff();
//                  MSG_DEBUG("BAD TR @" << dist << "cM min=" << min << " max=" << max << std::endl << TR);
//                  abort();
//              }
            double min = TR.minCoeff();
            if (min < 0) {
                TR.array() += min;
//                 double max = TR.array().abs().maxCoeff();
//                 MSG_DEBUG("BAD TR @" << dist << "cM min=" << min << " max=" << max << std::endl << TR);
//                 abort();
            }
            normalize_by_col(TR);
            return tr_cache[dist];
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        }
        return it->second;
    }

    MatrixXd normalize_by_col(const MatrixXd& m)
    {
        MatrixXd ret = MatrixXd::Zero(m.innerSize(), m.outerSize());
        VectorXd sums = m.colwise().sum();
        for (int i = 0; i < m.outerSize(); ++i) {
            if (sums(i) != 0) {
                ret.col(i) = m.col(i) / sums(i);
            }
        }
        return ret;
    }

    MatrixXd lv(int i)
    {
        return LV->col(i).asDiagonal();
    }

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#ifndef WITH_OVERLUMPING
        static
    MatrixXd
        make_collect(const std::set<subset>& lumping_partition, int n_cols)
        {
            /* Creation of L1 */
            MatrixXd C = MatrixXd::Zero(lumping_partition.size(), n_cols);
            int i = 0;
            for (const auto& part: lumping_partition) {
                for (int s: part) {
                    C(i, s) = 1.;
                }
                ++i;
            }
            return C;
        }
#endif

    
159
160
161
162
163
    void init(const geno_matrix* gen)
    {
        /*tr_cache.clear();*/
        this_gen = gen;
        /*redux = make_redux(matrix_labels_to_cliques(break_matrix.column_labels));*/
164
#ifdef WITH_OVERLUMPING
165
166
        experimental_lumper el(*this_gen);
        redux = el.make_collect(el.partition_on_labels(), this_gen->inf_mat.cols());
167
168
169
170
171
#else
        lumper<MatrixXd, label_type> el(this_gen->inf_mat, this_gen->labels);
        auto pol = el.partition_on_labels();
        redux = make_collect({pol.begin(), pol.end()}, this_gen->inf_mat.cols());
#endif
172
173
174
175
        inv_stat_dist = this_gen->stat_dist;
        for (int i = 0; i < inv_stat_dist.size(); ++i) {
            inv_stat_dist(i) = 1. / inv_stat_dist(i);
        }
176
177
178
179
180
181
182
183
184
185
186
187
        unique_labels = this_gen->get_unique_labels();
#if 0
        unique_labels.reserve(this_gen->labels.size());
        std::set<label_type> latemp;  //(this_gen->labels.begin(), this_gen->labels.end());
        for (const auto& l: this_gen->labels) {
            if (latemp.find(l) == latemp.end()) {
                latemp.insert(l);
                unique_labels.push_back(l);
            }
        }
        /*unique_labels.assign(latemp.begin(), latemp.end());*/
#endif
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210

        TR.clear();
        for (size_t i = 1; i < locus->size(); ++i) {
            TR.emplace_back(compute_tr((*locus)[i] - (*locus)[i - 1]));
        }
    }

    bool compute_partial_kernels()
    {
        std::map<int, std::string> lstring, rstring;
        left.clear();
        right.clear();

        int l = 0, r = LV->outerSize() - 1;

        MatrixXd kernel;

        left[0] = kernel = (this_gen->stat_dist.array() * LV->col(0).array()).matrix();

        lstring[0] = "LV0.";
        /*MSG_DEBUG("0 " << lstring[0]);*/
        /*MSG_DEBUG(left[0]);*/
        for(++l; l <= r; ++l) {
Damien Leroux's avatar
Damien Leroux committed
211
            MatrixXd old_kernel = kernel;
212
213
214
215
216
            kernel = LV->col(l).asDiagonal() * TR[l - 1] * kernel;
            double s = kernel.sum();
            if (s == 0) {
                return false;
            }
Damien Leroux's avatar
Damien Leroux committed
217
218
219
220
221
222
223
            if (s != s) {
                MSG_ERROR("#" << l << " LEFT KERNEL IS NaN", "");
                MSG_DEBUG("LV->col(" << l << ") =" << std::endl << LV->col(l).transpose());
                MSG_DEBUG("TR[" << (l - 1) << "] =" << std::endl << TR[l - 1]);
                MSG_DEBUG("old kernel =" << std::endl << old_kernel);
                abort();
            }
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
            kernel /= s;
            left[l] = kernel;
            std::stringstream ss;
            ss << "LV" << l << ".TR" << (l-1) << '.' << lstring[l-1];
            lstring[l] = ss.str();
            /*MSG_DEBUG(l << " " << lstring[l]);*/
            /*MSG_DEBUG(left[l]);*/
        }

        right[r+1] = VectorXd::Ones(this_gen->rows()) / this_gen->rows();
        /*right[r+1] = this_gen->stat_dist;*/
        rstring[r+1] = "";
        right[r-1] = right[r] = kernel = (this_gen->stat_dist.array() * LV->col(r).array()).matrix(); //LV->col(r) / LV->col(r).sum();
        { std::stringstream s; s << ".LV" << r; rstring[r-1] = rstring[r] = s.str(); }
        for (--r; r > 0; --r) {
Damien Leroux's avatar
Damien Leroux committed
239
            MatrixXd old_kernel = kernel;
240
241
242
243
244
            kernel = LV->col(r).asDiagonal() * TR[r] * kernel;
            double s = kernel.sum();
            if (s == 0) {
                return false;
            }
Damien Leroux's avatar
Damien Leroux committed
245
246
247
248
249
250
251
            if (s != s) {
                MSG_ERROR("#" << r << " RIGHT KERNEL IS NaN", "");
                MSG_DEBUG("LV->col(" << l << ") =" << std::endl << LV->col(l).transpose());
                MSG_DEBUG("TR[" << (l - 1) << "] =" << std::endl << TR[l - 1]);
                MSG_DEBUG("old kernel =" << std::endl << old_kernel);
                abort();
            }
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
            kernel /= s;
            right[r-1] = kernel;
            std::stringstream ss;
            ss << rstring[r] << ".TR" << r << ".LV" << r;
            rstring[r-1] = ss.str();
        }

        r = LV->outerSize() - 1;
        kernel = init_kernel;
        return true;
    }

    std::pair<size_t, size_t> find_lr(double loc)
    {
        size_t l = 0, r = LV->outerSize() - 1;
        if (loc < locus->front() || loc > locus->back()) {
            throw out_of_segment_exception();
        }

        for (; (l + 1) < r && (*locus)[l + 1] <= loc; ++l);
        for (; r > 0 && (*locus)[r - 1] > loc; --r);

        return {l, r};
    }

    VectorXd fast_compute_at(double loc, size_t l, size_t r)
    {
#if 0
        MSG_DEBUG("l=" << l);
        MSG_DEBUG("r=" << r);
        MSG_DEBUG("locus_l=" << (*locus)[l]);
        MSG_DEBUG("locus_r=" << (*locus)[r]);
        MSG_DEBUG("locus=" << loc);
#endif
        MatrixXd& TRL = compute_tr(loc - (*locus)[l]);
        MatrixXd& TRR = compute_tr((*locus)[r] - loc);
#if 0
        MSG_DEBUG(MATRIX_SIZE(TRL));
        MSG_DEBUG(TRL);
        MSG_DEBUG(MATRIX_SIZE(TRR));
        MSG_DEBUG(TRR);
        MSG_DEBUG(MATRIX_SIZE(left[l]));
        MSG_DEBUG(left[l]);
        MSG_DEBUG(MATRIX_SIZE(right[l]));
        MSG_DEBUG(right[l]);
#endif
        auto L = (TRL * left[l]).array();
        auto R = (TRR * right[l]).array();
#if 0
        /*std::cout << loc << std::endl << (L * R).matrix().transpose() << std::endl;*/
        MSG_DEBUG(MATRIX_SIZE(L));
        MSG_DEBUG(L);
        MSG_DEBUG(MATRIX_SIZE(R));
        MSG_DEBUG(R);
Damien Leroux's avatar
Damien Leroux committed
306
307
        MSG_DEBUG(MATRIX_SIZE(redux));
        MSG_DEBUG(redux);
308
309
310
#endif
        VectorXd vv = redux * (L * R * inv_stat_dist.array()).matrix();
        double s = vv.sum();
Damien Leroux's avatar
Damien Leroux committed
311
312
313
314
315
        if (s != s) {
            MSG_ERROR("geno_prob_computer spotted a nan!", "");
            MSG_DEBUG(vv);
            abort();
        }
316
317
318
319
320
321
        if (s == 0) {
            return vv;
        }
        return vv / s;
    }

322
323
    MatrixXd
        fast_compute_over_segment_raw(const std::vector<double>& steps)
324
        {
325
            MatrixXd ret(unique_labels.size(), steps.size());
Damien Leroux's avatar
Damien Leroux committed
326
            MSG_DEBUG(MATRIX_SIZE(ret));
327
328
329
330
            size_t l = 0, last = steps.size() - 1, r = !!(LV->outerSize() - 1);
            for (size_t i = 0; i < steps.size(); ++i) {
                /* FIXME: optimize the CORRECT initialization of l & r */
                std::tie(l, r) = find_lr(steps[i]);
331
332
333
334
                ret.col(i) = fast_compute_at(steps[i], l, r);
                for (int k = 0; k < ret.rows(); ++k) {
                    if (ret(k, i) < FLOAT_TOL && ret(k, i) > -FLOAT_TOL) {
                        ret(k, i) = 0;
Damien Leroux's avatar
Damien Leroux committed
335
336
                    }
                }
337
338
                if ((ret.col(i).array() < 0).any()) {
                    MSG_DEBUG("Bad value at column #" << i << std::endl << ret.col(i).transpose());
Damien Leroux's avatar
Damien Leroux committed
339
//                     MSG_DEBUG((*this_gen));
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
#if 0
                    MSG_DEBUG("steps: " << steps);
                    MSG_DEBUG("LV:" << std::endl << (*LV));
                    MSG_DEBUG(*this_gen);
                    for (const auto& m: TR) {
                        MSG_DEBUG(m);
                    }
                    for (const auto& kv: left) {
                        MSG_DEBUG("left " << kv.first);
                        MSG_DEBUG(kv.second);
                    }
                    for (const auto& kv: right) {
                        MSG_DEBUG("right " << kv.first);
                        MSG_DEBUG(kv.second);
                    }
#endif
                    /*throw 0;*/
                }
                while (steps[i] >= (*locus)[r]) {
                    ++l;
                    if (i < last) {
                        ++r;
                    } else {
                        break;
                    }
                    /*r += i < last;*/
                }
            }
Damien Leroux's avatar
Damien Leroux committed
368
//             MSG_DEBUG("STATE PROBABILITIES" << std::endl << ret);
369
370
            return ret;
        }
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386

    labelled_matrix<MatrixXd, label_type, double>
        fast_compute_over_segment(const std::vector<double>& steps)
        {
            if (!compute_partial_kernels()) {
                labelled_matrix<MatrixXd, label_type, double>
                    ret(unique_labels, steps);
                ret.data = MatrixXd::Zero(ret.row_labels.size(), ret.column_labels.size());
                return ret;
            }

            labelled_matrix<MatrixXd, label_type, double>
                ret(unique_labels, steps);
            ret.data = fast_compute_over_segment_raw(steps);
            return ret;
        }
387
388
};

Damien Leroux's avatar
Damien Leroux committed
389
390
391
392


struct segment_computer_t {
    const geno_matrix* g_this;
393
    qtl_chromosome chr;
Damien Leroux's avatar
Damien Leroux committed
394
    geno_prob_computer gpc_vec;
395
    /*std::vector<double> steps;*/
Damien Leroux's avatar
Damien Leroux committed
396
397
398
    std::vector<double> loci;
    double noise;

399
    segment_computer_t() : g_this(0), chr(), gpc_vec(), /*steps(),*/ noise(0) {}
Damien Leroux's avatar
Damien Leroux committed
400
401

    segment_computer_t(segment_computer_t&& sc)
402
        : g_this(sc.g_this), chr(sc.chr), gpc_vec(std::move(sc.gpc_vec)), /*steps(std::move(sc.steps)),*/ loci(std::move(sc.loci)), noise(sc.noise)
Damien Leroux's avatar
Damien Leroux committed
403
404
405
    {}


406
407
    segment_computer_t(const geno_matrix& g, const chromosome* pchr, const locus_key& lk, double /*step*/, double nz)
        : g_this(&g), chr(pchr, lk), gpc_vec(), noise(nz)
Damien Leroux's avatar
Damien Leroux committed
408
    {
409
410
        chr.copy_loci(loci);
        /*steps = compute_steps(loci, step);*/
Damien Leroux's avatar
Damien Leroux committed
411
412
413
        init();
    }

414
415
    segment_computer_t(const geno_matrix& g, const chromosome* pchr, const locus_key& lk, double nz/*, const std::vector<double>& loc_vec*/)
        : g_this(&g), chr(pchr, lk), gpc_vec(), noise(nz)
Damien Leroux's avatar
Damien Leroux committed
416
    {
417
418
        chr.copy_loci(loci);
        /*steps = loc_vec;*/
Damien Leroux's avatar
Damien Leroux committed
419
420
421
422
        init();
    }

    bool
423
        operator == (const segment_computer_t& sc) const { return g_this == sc.g_this /*&& steps == sc.steps*/ && noise == sc.noise; }
Damien Leroux's avatar
Damien Leroux committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438

    void
        init()
        {
            /*MSG_DEBUG("init !");*/
            gpc_vec.locus = &loci;
            gpc_vec.init(g_this);
        }

    segment_computer_t&
        operator = (segment_computer_t&& sc)
        {
            /*MSG_DEBUG("OPERATOR = :" << __LINE__);*/
            g_this = sc.g_this;
            chr = sc.chr;
439
440
            chr.copy_loci(loci);
            /*steps.swap(sc.steps);*/
Damien Leroux's avatar
Damien Leroux committed
441
442
443
444
445
446
447
448
            /*gpc_vec.swap(sc.gpc_vec);*/
            gpc_vec = std::move(sc.gpc_vec);
            noise = sc.noise;
            init();
            return *this;
        }

    labelled_matrix<MatrixXd, label_type, double>
449
        compute(const MatrixXd& LV, const std::vector<double>& steps)
Damien Leroux's avatar
Damien Leroux committed
450
451
452
        {
            /*DUMP_FILE_LINE();*/
            auto unphased_LV = g_this->unphased_LV();
453
            auto joint_qtl_iterator = chr.qtl_state_iterator(unphased_LV);
Damien Leroux's avatar
Damien Leroux committed
454
455
456
457
458
459
460
            /*MatrixXd lv = g_this->noisy_LV(LV, noise);*/
            MatrixXd qtl_lv(LV.innerSize(), loci.size());
            /*MSG_DEBUG(MATRIX_SIZE(lv) << std::endl << lv.transpose());*/
            gpc_vec.LV = &qtl_lv;
            joint_qtl_iterator.init_expansion(LV, qtl_lv);
            /*MSG_DEBUG(MATRIX_SIZE(qtl_lv));*/
            /*MSG_DEBUG(qtl_lv.transpose());*/
461
            auto tmp = compute(steps);
Damien Leroux's avatar
Damien Leroux committed
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
            int n_states = tmp.innerSize();
            std::vector<label_type> row_labels;
            row_labels.reserve(n_states * joint_qtl_iterator.size());
            /*MSG_DEBUG("qtl_iterator.size = " << joint_qtl_iterator.size());*/
            for (int i = 0; i < joint_qtl_iterator.size(); ++i) {
                row_labels.insert(row_labels.end(), tmp.row_labels.begin(), tmp.row_labels.end());
            }
            labelled_matrix<MatrixXd, label_type, double> ret(row_labels, steps);
            /*MSG_DEBUG("ret.data$dim(" << ret.data.innerSize() << ',' << ret.data.outerSize() << ") tmp.data$dim(" << tmp.innerSize() << ',' << tmp.outerSize() << ") n_states=" << n_states);*/
            /*ret.data.topRows(n_states) = compute().data;*/
            ret.data.topRows(n_states) = tmp.data;
            /*ret.emplace_back(compute());*/
            int row_ofs = n_states;
            while (!joint_qtl_iterator.next()) {
                if (joint_qtl_iterator.update(LV, qtl_lv)) {
                    /*ret.emplace_back(compute());*/
                    /*MSG_DEBUG(MATRIX_SIZE(qtl_lv));*/
                    /*MSG_DEBUG(qtl_lv.transpose());*/
480
                    ret.data.middleRows(row_ofs, n_states) = compute(steps).data;
Damien Leroux's avatar
Damien Leroux committed
481
482
483
484
485
486
487
488
489
                } else {
                    ret.data.middleRows(row_ofs, n_states) = MatrixXd::Zero(n_states, ret.data.outerSize());
                }
                row_ofs += n_states;
            }
            return ret;
        }

    labelled_matrix<MatrixXd, label_type, double>
490
        compute(const std::vector<double>& steps)
Damien Leroux's avatar
Damien Leroux committed
491
492
493
494
495
496
497
498
499
500
        {
            return gpc_vec.fast_compute_over_segment(steps);
        }

    friend
        inline
        std::ostream&
        operator << (std::ostream& os, const segment_computer_t& sc)
        {
            return os << '<' << sc.g_this->name
501
502
                /*<< " n_steps=" << sc.steps.size()*/
                << " chr=" << sc.chr.chr->name
Damien Leroux's avatar
Damien Leroux committed
503
504
505
506
507
508
                << " noise=" << sc.noise << '>';
        }

};


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
struct optim_segment_computer_t {
    const geno_matrix* g_this;
    qtl_chromosome chr;
    std::vector<geno_prob_computer> gpc_vec;
    std::vector<bool> gpc_not_zero;
    std::vector<double> loci;
    double noise;
    std::vector<label_type> row_labels;
    std::vector<MatrixXd> lv_vec;
    size_t n_states;

    optim_segment_computer_t()
        : g_this(0), chr(), gpc_vec(), gpc_not_zero(), loci(), noise(), row_labels(), lv_vec(), n_states(0) {}

    optim_segment_computer_t(optim_segment_computer_t&& other)
        : g_this(other.g_this)
        , chr(other.chr)
        , gpc_vec(std::move(other.gpc_vec))
        , gpc_not_zero(std::move(other.gpc_not_zero))
        , loci(std::move(other.loci))
        , noise(other.noise)
        , row_labels(std::move(other.row_labels))
        , lv_vec(std::move(other.lv_vec))
        , n_states(other.n_states)
    {
        for (size_t i = 0; i < gpc_vec.size(); ++i) {
            gpc_vec[i].locus = &loci;
            gpc_vec[i].LV = &lv_vec[i];
        }
    }

    optim_segment_computer_t(const optim_segment_computer_t& other)
        : g_this(other.g_this)
        , chr(other.chr)
        , gpc_vec(other.gpc_vec)
        , gpc_not_zero(other.gpc_not_zero)
        , loci(other.loci)
        , noise(other.noise)
        , row_labels(other.row_labels)
        , lv_vec(other.lv_vec)
        , n_states(other.n_states)
    {
        for (size_t i = 0; i < gpc_vec.size(); ++i) {
            gpc_vec[i].locus = &loci;
            gpc_vec[i].LV = &lv_vec[i];
        }
555
        /*MSG_DEBUG("optim_segment_computer_t copy " << gpc_vec.size() << " parts; labels " << row_labels);*/
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
    }

    optim_segment_computer_t&
        operator = (const optim_segment_computer_t& other)
        {
            g_this = other.g_this;
            chr = other.chr;
            gpc_vec = other.gpc_vec;
            gpc_not_zero = other.gpc_not_zero;
            loci = other.loci;
            noise = other.noise;
            row_labels = other.row_labels;
            lv_vec = other.lv_vec;
            n_states = other.n_states;
            for (size_t i = 0; i < gpc_vec.size(); ++i) {
                gpc_vec[i].locus = &loci;
                gpc_vec[i].LV = &lv_vec[i];
            }
574
            /*MSG_DEBUG("optim_segment_computer_t = " << gpc_vec.size() << " parts; labels " << row_labels);*/
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
            return *this;
        }

    optim_segment_computer_t(const geno_matrix& g, const chromosome* pchr, const locus_key& lk, double nz, const MatrixXd& LV)
        : g_this(&g), chr(pchr, lk), gpc_vec(), gpc_not_zero(), loci(), noise(nz), row_labels(), lv_vec(), n_states(0)
    {
        auto unphased_LV = g_this->unphased_LV();
        chr.copy_loci(loci);
        MatrixXd qtl_lv(LV.innerSize(), loci.size());
        auto joint_qtl_iterator = chr.qtl_state_iterator(unphased_LV);
        bool lv_ok = joint_qtl_iterator.init_expansion(LV, qtl_lv);
        gpc_vec.reserve(joint_qtl_iterator.size());
        lv_vec.reserve(joint_qtl_iterator.size());
        {
            geno_prob_computer tmp;
            tmp.locus = &loci;
            tmp.init(g_this);
            n_states = tmp.unique_labels.size();
            row_labels.reserve(n_states * joint_qtl_iterator.size());
            for (int i = 0; i < joint_qtl_iterator.size(); ++i) {
                row_labels.insert(row_labels.end(), tmp.unique_labels.begin(), tmp.unique_labels.end());
            }
        }

        auto
            add_gpc = [&] (bool lv_ok)
            {
                if (lv_ok) {
                    lv_vec.push_back(qtl_lv);
                    gpc_vec.emplace_back();
                    gpc_vec.back().locus = &loci;
                    gpc_vec.back().LV = &lv_vec.back();
                    gpc_vec.back().init(g_this);
                    if (gpc_vec.back().compute_partial_kernels()) {
                        gpc_not_zero.push_back(true);
610
                        /*MSG_DEBUG("GPC::LV" << std::endl << lv_vec.back());*/
611
612
613
614
615
                    } else {
                        gpc_not_zero.push_back(false);
                        gpc_vec.pop_back();
                        gpc_vec.emplace_back();
                        lv_vec.pop_back();
616
                        /*MSG_DEBUG("GPC::LV none. Update was OK but partial kernel computation failed.");*/
617
618
619
620
621
                    }
                } else {
                    gpc_not_zero.push_back(false);
                    gpc_vec.emplace_back();
                    lv_vec.emplace_back();
622
                    /*MSG_DEBUG("GPC::LV none. Update failed.");*/
623
624
625
626
627
628
629
630
631
                }
            };

        add_gpc(lv_ok);

        for (; !joint_qtl_iterator.next(); ) {
            add_gpc(joint_qtl_iterator.update(LV, qtl_lv));
        }

632
633
        /*MSG_DEBUG("optim_segment_computer_t NEW " << gpc_vec.size() << " parts; labels " << row_labels);*/

634
        /*MSG_DEBUG("NEW GPC row_labels " << row_labels);*/
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
#if 0
        for (; !joint_qtl_iterator.next();) {
            lv_vec.push_back(qtl_lv);
            gpc_vec.emplace_back();
            gpc_vec.back().locus = &loci;
            gpc_vec.back().LV = &lv_vec.back();
            gpc_vec.back().init(g_this);
            if (joint_qtl_iterator.update(LV, lv_vec.back()) && (lv_vec.push_back(qtl_lv), gpc_vec.back().compute_partial_kernels())) {
                gpc_not_zero.push_back(true);
            } else {
                gpc_not_zero.push_back(false);
                gpc_vec.pop_back();
                gpc_vec.emplace_back();
                lv_vec.pop_back();
                lv_vec.emplace_back();
            }
            MSG_DEBUG("GPC::LV" << std::endl << lv_vec.back());
        }
#endif
    }

    labelled_matrix<MatrixXd, label_type, double>
        compute(const std::vector<double>& steps)
        {
            labelled_matrix<MatrixXd, label_type, double> ret(row_labels, steps);
660
            /*MSG_DEBUG("segment_computer::compute => " << MATRIX_SIZE(ret.data));*/
661
662
663
664
665
666
667
668
669
670
671
672
673
674
            auto nzi = gpc_not_zero.begin(), nzj = gpc_not_zero.end();
            auto gpci = gpc_vec.begin();
            int row_ofs = 0;
            for (; nzi != nzj; ++nzi, ++gpci, row_ofs += n_states) {
                if (*nzi) {
                    ret.data.middleRows(row_ofs, n_states) = gpci->fast_compute_over_segment_raw(steps);
                } else {
                    ret.data.middleRows(row_ofs, n_states) = MatrixXd::Zero(n_states, steps.size());
                }
            }
            return ret;
        }
};

675
676
#endif