output.h 66.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
21
22
#ifndef _SPELL_BAYES_OUTPUT_H_
#define _SPELL_BAYES_OUTPUT_H_

#include <map>
#include <vector>
Damien Leroux's avatar
Damien Leroux committed
23
24
25
#include <map>
#include <set>
#include <unordered_set>
26
#include <unordered_map>
27
28
#include <string>
#include <iostream>
29
#include "file.h"
30
31
32
33
#include <cstring>

#include "eigen.h"
#include "error.h"
34
#include "data/chromosome.h"
35
/*#include "generation_rs_fwd.h"*/
36
#include "input/read_trait.h"
37
#include "tensor.h"
38
#include "linear_combination.h"
39
40
41
42

/** FOURCC **/

inline
43
bool check_fourcc(ifile& ifs, const char* fourcc)
44
45
46
47
48
49
50
{
    char buf[4] = {0, 0, 0, 0};
    ifs.read(buf, 4);
    return strncmp(fourcc, buf, 4);
}

inline
51
void write_fourcc(ofile& ofs, const char* fourcc)
52
53
54
55
56
57
58
{
    ofs.write(fourcc, 4);
}

/** SIZE_T **/

inline
59
void write_size(ofile& ofs, size_t sz)
60
61
62
63
64
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
65
size_t read_size(ifile& ifs)
66
67
68
69
70
71
{
    size_t ret;
    ifs.read((char*) &ret, sizeof ret);
    return ret;
}

72
73
74
/** PTRDIFF_T **/

inline
75
void write_ptrdiff(ofile& ofs, ptrdiff_t sz)
76
77
78
79
80
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
81
ptrdiff_t read_ptrdiff(ifile& ifs)
82
83
84
85
86
87
{
    ptrdiff_t ret;
    ifs.read((char*) &ret, sizeof ret);
    return ret;
}

88
89
90
/** STRING **/

inline
91
std::string read_str(ifile& ifs)
92
93
94
95
96
97
98
99
{
    size_t sz = read_size(ifs);
    std::vector<char> tmp(sz);
    ifs.read(&tmp[0], sz);
    return {tmp.begin(), tmp.end()};
}

inline
100
void write_str(ofile& ofs, const std::string& s)
101
102
103
104
105
106
107
108
{
    write_size(ofs, s.size());
    ofs.write(s.c_str(), s.size());
}

/** DOUBLE **/

inline
109
void write_double(ofile& ofs, double sz)
110
111
112
113
114
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
115
double read_double(ifile& ifs)
116
117
118
119
120
121
122
123
124
{
    double ret;
    ifs.read((char*) &ret, sizeof ret);
    return ret;
}

/** INT **/

inline
125
void write_int(ofile& ofs, int sz)
126
127
128
129
130
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
131
int read_int(ifile& ifs)
132
133
134
135
136
137
{
    int ret;
    ifs.read((char*) &ret, sizeof ret);
    return ret;
}

138
139
140
/** CHAR **/

inline
141
void write_char(ofile& ofs, char sz)
142
143
144
145
146
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
147
char read_char(ifile& ifs)
148
149
150
151
152
153
154
{
    char ret;
    ifs.read(&ret, sizeof ret);
    return ret;
}

#if 0
155
156
157
/** FAST_POLYNOM **/

inline
158
void write_fast_polynom(ofile& ofs, const fast_polynom& fp)
159
160
161
162
163
164
165
166
167
168
169
170
{
    impl::f_polynom f = fp;
    write_int(ofs, fp.value);
    write_int(ofs, f.r_exp);
    write_int(ofs, f.s_exp);
    write_size(ofs, f.P.size());
    for (double c: f.P) {
        write_double(ofs, c);
    }
}

inline
171
fast_polynom read_fast_polynom(ifile& ifs, int& original_key)
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
{
    original_key = read_int(ifs);
    impl::f_polynom ret = fast_polynom::zero;
    ret.r_exp = read_int(ifs);
    ret.s_exp = read_int(ifs);
    size_t sz = read_size(ifs);
    ret.P.resize(sz);
    for (size_t i = 0; i < sz; ++i) {
        ret.P[i] = read_double(ifs);
    }
    return ret;
}

/** ALGREBRAIC GENOTYPE **/

187
inline void write_algebraic_genotype(ofile& ofs, const algebraic_genotype& ag)
188
189
190
191
192
193
{
    ofs.write((const char*) &ag.genotype, sizeof ag.genotype);
    ofs.write((const char*) &ag.type, sizeof ag.type);
    write_int(ofs, ag.poly.value);
}

194
inline algebraic_genotype read_algebraic_genotype(ifile& ifs, const std::map<int, fast_polynom>& pt)
195
196
197
198
199
200
201
202
203
204
{
    algebraic_genotype ag;
    ifs.read((char*) &ag.genotype, sizeof ag.genotype);
    ifs.read((char*) &ag.type, sizeof ag.type);
    ag.poly = pt.find(read_int(ifs))->second;
    return ag;
}

/** GENOMATRIX **/

205
inline void write_genomatrix(ofile& ofs, const GenoMatrix& mat)
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
{
    write_fourcc(ofs, "SGEM");
    /*std::map<decltype(fast_polynom::value), impl::f_polynom>*/
    std::set<fast_polynom> poly_table;
    for (int j = 0; j < mat.cols(); ++j) {
        for (int i = 0; i < mat.rows(); ++i) {
            poly_table.insert(mat(i, j).poly);
        }
    }
    write_size(ofs, poly_table.size());
    for (const auto& fp: poly_table) {
        write_fast_polynom(ofs, fp);
    }
    write_int(ofs, mat.cols());
    write_int(ofs, mat.rows());
    /*MSG_DEBUG("[write_genomatrix] cols=" << mat.cols() << " rows=" << mat.rows());*/
    for (int j = 0; j < mat.cols(); ++j) {
        for (int i = 0; i < mat.rows(); ++i) {
            /*write_int(ofs, mat(i, j).value);*/
            write_algebraic_genotype(ofs, mat(i, j));
        }
    }
}

inline
231
void read_genomatrix(ifile& ifs, GenoMatrix& mat)
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
{
    if (check_fourcc(ifs, "SGEM")) {
        MSG_ERROR("File is not valid or has been corrupted", "");
        return;
    }
    std::map<int, fast_polynom> poly_map;

    size_t table_size = read_size(ifs);
    int key;

    for (size_t i = 0; i < table_size; ++i) {
        auto f = read_fast_polynom(ifs, key);
        poly_map[key] = f;
    }

    int cols = read_int(ifs);
    int rows = read_int(ifs);
    /*MSG_DEBUG("[read_genomatrix] cols=" << cols << " rows=" << rows);*/
    mat.resize(rows, cols);
    for (int j = 0; j < mat.cols(); ++j) {
        for (int i = 0; i < mat.rows(); ++i) {
            mat(i, j) = read_algebraic_genotype(ifs, poly_map);
        }
    }
}

/** GENERATION_RS **/

260
inline void write_geno_matrix(ofile& ofs, const geno_matrix* gen)
261
262
263
264
265
266
267
268
269
270
271
{
    write_fourcc(ofs, "SGRS");
    write_str(ofs, gen->name);
    write_size(ofs, gen->P.size());
    for (const auto& p: gen->P) {
        write_double(ofs, p.weight);
        write_genomatrix(ofs, p.G.data);
    }
}

inline
272
geno_matrix* read_geno_matrix(ifile& ifs)
273
274
275
276
277
278
279
{
    if (check_fourcc(ifs, "SGRS")) {
        MSG_ERROR("File is not valid or has been corrupted", "");
    }
    /*MSG_DEBUG("pouet 1"); MSG_QUEUE_FLUSH();*/
    std::string name = read_str(ifs);
    /*MSG_DEBUG("pouet 2"); MSG_QUEUE_FLUSH();*/
280
    geno_matrix* ret = geno_matrix::blank(name);
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    /*MSG_DEBUG("pouet 3"); MSG_QUEUE_FLUSH();*/
    size_t n_p = read_size(ifs);
    /*MSG_DEBUG("Have " << n_p << " processes"); MSG_QUEUE_FLUSH();*/
    ret->P.resize(n_p);
    for (size_t i = 0; i < n_p; ++i) {
        ret->P[i].weight = read_double(ifs);
        GenoMatrix tmp;
        read_genomatrix(ifs, tmp);
        ret->P[i].G = convert(tmp);
        /*MSG_DEBUG("Read process");*/
        /*MSG_DEBUG(ret->P[i]);*/
    }
    ret->precompute();
    return ret;
}
296
297
#endif

298
299
300
301
302
303
304
305
306

/** MATRIX<SCALAR, R, C> **/

template <typename MATRIX_TYPE>
struct resize_matrix_impl;

template <> struct resize_matrix_impl<VectorXd> { void operator () (VectorXd& v, size_t rows, size_t) { v.resize(rows); } };
template <> struct resize_matrix_impl<MatrixXd> { void operator () (MatrixXd& m, size_t rows, size_t cols) { m.resize(rows, cols); } };

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
template <typename SCALAR, int ROW, int COL, int C, int D, int E>
struct resize_matrix_impl<Eigen::Matrix<SCALAR, ROW, COL, C, D, E>> {
    void operator () (Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& m, size_t r, size_t c) { m.resize(r, c); }
};

template <typename SCALAR, int ROW, int C, int D, int E>
struct resize_matrix_impl<Eigen::Matrix<SCALAR, ROW, 1, C, D, E>> {
    void operator () (Eigen::Matrix<SCALAR, ROW, 1, C, D, E>& v, size_t r, size_t) { v.resize(r); }
};

template <typename SCALAR, int COL, int C, int D, int E>
struct resize_matrix_impl<Eigen::Matrix<SCALAR, 1, COL, C, D, E>> {
    void operator () (Eigen::Matrix<SCALAR, 1, COL, C, D, E>& v, size_t, size_t c) { v.resize(c); }
};

322
323
324
325
template <typename MATRIX_TYPE>
void resize_matrix(MATRIX_TYPE& m, size_t r, size_t c) { resize_matrix_impl<MATRIX_TYPE>()(m, r, c); }

template <typename SCALAR, int ROW, int COL, int C, int D, int E>
326
void read_matrix(ifile& ifs, Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat)
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
{
    size_t scalar_sz = read_size(ifs);
    if (scalar_sz != sizeof(SCALAR)) {
        MSG_ERROR("WRONG SIZE OF SCALAR, CAN'T READ FILE", "Make sure spell-marker and spell-qtl are always executed on machines with same word size.");
    }
    size_t n_row = read_size(ifs);
    size_t n_col = read_size(ifs);
    if (ROW != Eigen::Dynamic && ((int) n_row) != ROW) {
        MSG_ERROR("WRONG ROW COUNT. FILE IS NOT A LOCUS VECTOR FILE OR IS CORRUPTED", "You may want to run spell-marker again");
    }
    if (COL != Eigen::Dynamic && ((int) n_col) != COL) {
        MSG_ERROR("WRONG COLUMN COUNT. FILE IS NOT A LOCUS VECTOR FILE OR IS CORRUPTED", "You may want to run spell-marker again");
    }
    resize_matrix(mat, n_row, n_col);
    ifs.read((char*) mat.data(), n_row * n_col * sizeof(SCALAR));
}

template <typename SCALAR, int ROW, int COL, int C, int D, int E>
345
void write_matrix(ofile& ofs, const Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat)
346
347
348
349
350
351
352
353
{
    write_size(ofs, sizeof(SCALAR));
    write_size(ofs, mat.rows());
    write_size(ofs, mat.cols());
    ofs.write((const char*) mat.data(), mat.size() * sizeof(SCALAR));
}


354
template <typename V, typename READ_ELEM_FUNC>
355
void read_vector(ifile& ifs, std::vector<V>& vec, READ_ELEM_FUNC read_elem)
356
357
358
359
360
361
362
363
364
365
366
{
    size_t sz = read_size(ifs);
    vec.clear();
    vec.reserve(sz);
    for (size_t i = 0; i < sz; ++i) {
        vec.emplace_back(read_elem(ifs));
    }
}


template <typename V, typename WRITE_ELEM_FUNC>
367
void write_vector(ofile& ofs, const std::vector<V>& vec, WRITE_ELEM_FUNC write_elem)
368
369
370
371
372
373
374
375
376
377
{
    write_size(ofs, vec.size());
    for (const auto& e: vec) {
        write_elem(ofs, e);
    }
}


/** LABEL_TYPE **/

378
inline
379
label_type read_label(ifile& ifs)
380
{
Damien Leroux's avatar
Damien Leroux committed
381
    char f = 0, s = 0;
382
    ifs >> f >> s;
Damien Leroux's avatar
Damien Leroux committed
383
    MSG_DEBUG("[read_label] " << int(f) << ':' << int(s));
384
385
386
    return {f, s};
}

387
inline
388
void write_label(ofile& ofs, const label_type& l)
389
390
391
392
393
394
395
{
    ofs << l.first() << l.second();
}


/** GENO_MATRIX **/

396
inline
397
void write_geno_matrix(ofile& ofs, const geno_matrix& mat)
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
{
    write_fourcc(ofs, "SGEM");
    write_str(ofs, mat.name);
    /* skip variant, it's deprecated. Or should be. */
    write_vector(ofs, mat.labels, write_label);
    write_matrix(ofs, mat.inf_mat);
    write_matrix(ofs, mat.p);
    write_matrix(ofs, mat.p_inv);
    write_matrix(ofs, mat.diag);
    write_matrix(ofs, mat.stat_dist);
    write_matrix(ofs, mat.collect);
    write_matrix(ofs, mat.dispatch);
    /* also skip symmetries for now. */
}

inline
414
void read_geno_matrix(ifile& ifs, geno_matrix& mat)
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
{
    if (check_fourcc(ifs, "SGEM")) {
        MSG_ERROR("File is not valid or has been corrupted", "");
        return;
    }
    mat.name = read_str(ifs);
    /* skip variant. */
    read_vector(ifs, mat.labels, read_label);
    read_matrix(ifs, mat.inf_mat);
    read_matrix(ifs, mat.p);
    read_matrix(ifs, mat.p_inv);
    read_matrix(ifs, mat.diag);
    read_matrix(ifs, mat.stat_dist);
    read_matrix(ifs, mat.collect);
    read_matrix(ifs, mat.dispatch);
    /* also skip symmetries for now. */
Damien Leroux's avatar
Damien Leroux committed
431
    MSG_DEBUG("read geno_matrix " << MATRIX_SIZE(mat.inf_mat) << " labels " << mat.labels);
432
433
434
}


435
inline
436
void write_geno_matrix(ofile& ofs, const geno_matrix* ptr)
437
438
439
440
{
    write_geno_matrix(ofs, *ptr);
}

441
inline
442
geno_matrix* read_geno_matrix(ifile& ifs)
443
444
445
446
447
448
449
{
    geno_matrix* ret = new geno_matrix();
    read_geno_matrix(ifs, *ret);
    return ret;
}


450
451
452

template <class DERIVED>
struct rw_any {
453
    bool fourcc(ifile& ifs, const char* cc)
454
455
456
457
458
459
460
461
    {
        if (check_fourcc(ifs, cc)) {
            MSG_ERROR("File is not valid or has been corrupted (expected " << cc << ')', "");
            return true;
        }
        return false;
    }

462
    bool fourcc(ofile& ofs, const char* cc)
463
464
465
466
467
468
469
470
471
    {
        write_fourcc(ofs, cc);
        return false;
    }

    virtual ~rw_any() {}

    DERIVED& ref() { return *dynamic_cast<DERIVED*>(this); }

472
473
    void operator () (ifile& ifs, std::string& s) { s = read_str(ifs); }
    void operator () (ofile& ofs, const std::string& s) { write_str(ofs, s); }
474

475
476
    void operator () (ifile& ifs, char& i) { i = read_char(ifs); }
    void operator () (ofile& ofs, char i) { write_char(ofs, i); }
477

478
479
    void operator () (ifile& ifs, int& i) { i = read_int(ifs); }
    void operator () (ofile& ofs, int i) { write_int(ofs, i); }
480

481
482
    void operator () (ifile& ifs, bool& i) { i = !!read_char(ifs); }
    void operator () (ofile& ofs, bool i) { write_char(ofs, i); }
483

484
485
    void operator () (ifile& ifs, double& i) { i = read_double(ifs); }
    void operator () (ofile& ofs, double i) { write_double(ofs, i); }
486

487
488
    void operator () (ifile& ifs, size_t& i) { i = read_size(ifs); }
    void operator () (ofile& ofs, size_t i) { write_size(ofs, i); }
489

490
491
    void operator () (ifile& ifs, ptrdiff_t& i) { i = read_ptrdiff(ifs); }
    void operator () (ofile& ofs, ptrdiff_t i) { write_ptrdiff(ofs, i); }
492

493
    void operator () (ifile& ifs, label_type& l) { l = {read_char(ifs), read_char(ifs)}; }
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    void operator () (ofile& ofs, label_type& l) { write_char(ofs, l.first()); write_char(ofs, l.second()); }

    template <typename K>
        auto operator () (ifile& fs, K& has_file_io)
        -> decltype(has_file_io.file_io(fs), void())
        {
            has_file_io.file_io(fs);
        }

    template <typename K>
        auto operator () (ofile& fs, K& has_file_io)
        -> decltype(has_file_io.file_io(fs), void())
        {
            has_file_io.file_io(fs);
        }
509
510

    template <typename V>
511
        void operator () (ifile& ifs, std::set<V>& vec)
512
513
514
515
516
517
518
519
520
521
522
523
        {
            if (fourcc(ifs, "OSET")) { return; }
            size_t sz = read_size(ifs);
            vec.clear();
            for (size_t i = 0; i < sz; ++i) {
                V tmp;
                ref() (ifs, tmp);
                vec.emplace(tmp);
            }
        }

    template <typename V>
524
        void operator () (ofile& ofs, std::set<V>& vec)
525
526
527
        {
            if (fourcc(ofs, "OSET")) { return; }
            write_size(ofs, vec.size());
528
            for (auto& e: vec) {
529
530
531
532
533
534
                ref() (ofs, e);
            }
        }


    template <typename V>
535
        void operator () (ifile& ifs, std::unordered_set<V>& vec)
536
537
538
539
540
541
542
543
544
545
546
547
        {
            if (fourcc(ifs, "USET")) { return; }
            size_t sz = read_size(ifs);
            vec.clear();
            for (size_t i = 0; i < sz; ++i) {
                V tmp;
                ref() (ifs, tmp);
                vec.emplace(tmp);
            }
        }

    template <typename V>
548
        void operator () (ofile& ofs, std::unordered_set<V>& vec)
549
550
551
        {
            if (fourcc(ofs, "USET")) { return; }
            write_size(ofs, vec.size());
552
            for (auto& e: vec) {
553
554
555
556
                ref() (ofs, e);
            }
        }

557
    void operator () (ifile& ifs, std::vector<bool>::reference i) { i = !!read_char(ifs); }
558
559

    template <typename V, typename A>
560
        void operator () (ifile& ifs, std::vector<V, A>& vec)
561
562
563
564
565
566
567
568
569
570
571
572
        {
            if (fourcc(ifs, "VECT")) { return; }
            size_t sz = read_size(ifs);
            vec.clear();
            vec.reserve(sz);
            for (size_t i = 0; i < sz; ++i) {
                vec.emplace_back();
                ref() (ifs, vec.back());
            }
        }

    template <typename V, typename A>
573
574
575
576
577
578
579
580
581
582
        void operator () (ofile& ofs, std::vector<V, A>& vec)
        {
            if (fourcc(ofs, "VECT")) { return; }
            write_size(ofs, vec.size());
            for (auto& e: vec) {
                ref() (ofs, e);
            }
        }

        void operator () (ofile& ofs, std::vector<bool>& vec)
583
584
585
586
587
588
589
590
591
        {
            if (fourcc(ofs, "VECT")) { return; }
            write_size(ofs, vec.size());
            for (const auto& e: vec) {
                ref() (ofs, e);
            }
        }

    template <typename V, typename A, typename RWElem>
592
        void operator () (ifile& ifs, std::vector<V, A>& vec, RWElem rw_elem)
593
594
595
596
597
598
599
600
601
602
603
604
        {
            if (fourcc(ifs, "VECT")) { return; }
            size_t sz = read_size(ifs);
            vec.clear();
            vec.reserve(sz);
            for (size_t i = 0; i < sz; ++i) {
                vec.emplace_back();
                rw_elem(ifs, vec.back());
            }
        }

    template <typename V, typename A, typename RWElem>
605
        void operator () (ofile& ofs, std::vector<V, A>& vec, RWElem rw_elem)
606
607
608
609
610
611
612
613
614
        {
            if (fourcc(ofs, "VECT")) { return; }
            write_size(ofs, vec.size());
            for (auto& e: vec) {
                rw_elem(ofs, e);
            }
        }

    template <typename K, typename V, typename A, typename C>
615
        void operator () (ifile& ifs, std::map<K, V, A, C>& map)
616
617
618
619
620
621
622
623
624
625
626
627
628
629
        {
            if (fourcc(ifs, "MAP ")) { return; }
            size_t count = read_size(ifs);
            map.clear();
            for (size_t i = 0; i < count; ++i) {
                K key;
                V value;
                ref() (ifs, key);
                ref() (ifs, value);
                map.emplace(std::move(key), std::move(value));
            }
        }

    template <typename K, typename V, typename A, typename C>
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
        void operator () (ifile& ifs, std::unordered_map<K, V, A, C>& map)
        {
            if (fourcc(ifs, "MAP ")) { return; }
            size_t count = read_size(ifs);
            map.clear();
            for (size_t i = 0; i < count; ++i) {
                K key;
                V value;
                ref() (ifs, key);
                ref() (ifs, value);
                map.emplace(std::move(key), std::move(value));
            }
        }

    template <typename K, typename V, typename A, typename C>
        void operator () (ofile& ofs, std::map<K, V, A, C>& map)
646
647
648
        {
            if (fourcc(ofs, "MAP ")) { return; }
            write_size(ofs, map.size());
649
650
651
652
653
654
655
656
657
658
659
660
            for (auto& kv: map) {
                ref() (ofs, const_cast<K&>(kv.first));
                ref() (ofs, kv.second);
            }
        }

    template <typename K, typename V, typename A, typename C>
        void operator () (ofile& ofs, std::unordered_map<K, V, A, C>& map)
        {
            if (fourcc(ofs, "MAP ")) { return; }
            write_size(ofs, map.size());
            for (auto& kv: map) {
661
662
663
664
665
                ref() (ofs, kv.first);
                ref() (ofs, kv.second);
            }
        }

666
667
668
669
670
671
672
    template <typename IO, typename A, typename B>
        void operator () (IO& fs, std::pair<A, B>& p)
        {
            ref() (fs, p.first);
            ref() (fs, p.second);
        }

673
    template <typename SCALAR, int ROW, int COL, int C, int D, int E>
674
        void operator () (ifile& ifs, Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat) { read_matrix(ifs, mat); }
675
676

    template <typename SCALAR, int ROW, int COL, int C, int D, int E>
677
        void operator () (ofile& ofs, Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat) { write_matrix(ofs, mat); }
678

679
680
    void operator () (ifile& ifs, geno_matrix& mat) { read_geno_matrix(ifs, mat); }
    void operator () (ofile& ofs, geno_matrix& mat) { write_geno_matrix(ofs, mat); }
681

682
    void operator () (ifile& ifs, std::shared_ptr<geno_matrix>& ptr)
683
684
685
686
687
688
689
690
691
    {
        ptr.reset();
        ptr = std::make_shared<geno_matrix>();
        ref() (ifs, *ptr);
        if (!ptr->size()) {
            ptr.reset();
        }
    }

692
    void operator () (ofile& ofs, std::shared_ptr<geno_matrix>& ptr)
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
    {
        if (ptr) {
            ref() (ofs, *ptr.get());
        } else {
            geno_matrix _;
            ref() (ofs, _);
        }
    }
};


struct rw_base : public rw_any<rw_base> {
    virtual ~rw_base() {}
    using rw_any<rw_base>::fourcc;
    using rw_any<rw_base>::ref;
    using rw_any<rw_base>::operator ();
};



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

typedef union _gamete_lv_value_type {
    Eigen::Vector4d binary;
    Eigen::Vector2d unary;
    
    static _gamete_lv_value_type unknown_binary() { static _gamete_lv_value_type ret = {(Eigen::Vector4d() << .25, .25, .25, .25).finished()}; return ret; }
    static _gamete_lv_value_type unknown_unary() { static _gamete_lv_value_type ret = {(Eigen::Vector4d() << .5, .5, 0, 0).finished()}; return ret; }
    
    _gamete_lv_value_type&
    operator = (const _gamete_lv_value_type& other)
    {
        binary = other.binary;
        return *this;
    }
    
    template <typename STREAM_TYPE>
    void
    file_io(STREAM_TYPE& fs)
    {
        rw_base rw;
        rw(fs, binary);
    }
    
    _gamete_lv_value_type() : binary() {}
    _gamete_lv_value_type(const _gamete_lv_value_type& other) : binary(other.binary) {}
    _gamete_lv_value_type(const Eigen::Vector2d& v) { unary = v; }
    _gamete_lv_value_type(const Eigen::Vector4d& v) { binary = v; }
    friend std::ostream& operator << (std::ostream& os, const _gamete_lv_value_type& glv) { return os << glv.binary.transpose(); }
} gamete_lv_value_type;


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
struct gamete_LV_type {
    bool is_single;
    std::map<std::string, gamete_lv_value_type> lv;

    friend std::ostream& operator << (std::ostream& os, const gamete_LV_type& glv) { return os << (glv.is_single ? "Unary{" : "Binary{") << glv.lv << '}'; }
    
    void get(const std::string& key, Eigen::Vector2d& value) const
    {
        auto it = lv.find(key);
        if (it == lv.end()) {
            value = Eigen::Vector2d::Zero();
        } else {
            value = it->second.unary;
        }
    }

    void get(const std::string& key, Eigen::Vector4d& value) const
    {
        auto it = lv.find(key);
        if (it == lv.end()) {
            value = Eigen::Vector4d::Zero();
        } else {
            value = it->second.binary;
        }
    }
    
    void add_normalized(const std::string& key, const Eigen::VectorXd& value) { if (value.size() == 2) { lv[key].unary = value; } else { lv[key].binary = value; } }

    template <typename T>
    void add(const std::string& key, const T& value) { add_normalized(key, value); }

    template <typename STREAM_TYPE>
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
    void
    file_io(STREAM_TYPE& fs)
    {
        rw_base rw;
        if (rw.fourcc(fs, "GLVT")) { return; }
        rw(fs, is_single);
        rw(fs, lv);
    }
};


#if 0
struct em_dist_opt : public Eigen::Functor<double> {
    em_dist_opt() : Eigen::Functor<double>(1, 5) {}
    int
    operator() (const VectorXd& b, VectorXd& fvec) const
    {
        double r = b(0);
        double r2 = r * r;
        fvec <<
            (r2 - r - r + 1),
            (r2 - r),
            (r2),
            (r),
            (1 - r);
        return 0;
    }
    
    int
    df(const VectorXd& b, VectorXd& fjac) const
    {
        double r = b(0);
        double _2r = r + r;
        fjac <<
            (_2r - 2),
            (_2r - 1),
            (_2r),
            (1),
            (-1);
        return 0;
    }
};
#endif


struct EM_helpers {
#   define sqrt5 2.236067977499789696

    struct max_return_type {
        double a, b, fa, fb;
    };
    
    template <typename F>
    max_return_type
    find_max(F&& f, double a0, double b0)
    {
#       define interval_too_small(_x, _y) ((_y - _x) < tolerance)
        static const double lambda = 0.5 * (sqrt5 - 1.0);
        static const double mu = 0.5 * (3.0 - sqrt5);         // = 1 - lambda
        static const double tolerance = 3.e-8;
        double x1;
        double x2;
        double fx1;
        double fx2;
        max_return_type ret = {a0, b0, f(a0), f(b0)};
        

                        // Find first two internal points and evaluate 
                        // the function at the two internal points.

        x1 = ret.b - lambda * (ret.b - ret.a);                            
        x2 = ret.a + lambda * (ret.b - ret.a);                         
        fx1 = f(x1);
        fx2 = f(x2);

                    // Verify that the tolerance is an acceptable number

//         if (tolerance <= 0.0) tolerance = sqrt(DBL_EPSILON) * (ret.b - ret.a);

                // Loop by exluding segments from current endpoints a, b
                // to current internal points x1, x2 and then calculating
                // a new internal point until the length of the interval
                // is less than or equal to the tolerance.

        while (!interval_too_small(ret.a, ret.b)) {
            if (fx1 < fx2) {
                ret.a = x1;
                ret.fa = fx1;
                if (interval_too_small(ret.a, ret.b)) break;
                x1 = x2;
                fx1 = fx2;
                x2 = ret.b - mu * (ret.b - ret.a);
                fx2 = f(x2);
            } else {
                ret.b = x2;
                ret.fb = fx2;
                if (interval_too_small(ret.a, ret.b)) break;
                x2 = x1;
                fx2 = fx1;
                x1 = ret.a + mu * (ret.b - ret.a);
                fx1 = f(x1);
            }
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
        return ret;
    }
    
    static
    const Eigen::Matrix2d&
    S_kernel(const Eigen::Vector2d&)
    {
        static Eigen::Matrix2d kernel = (Eigen::Matrix2d() << 1, 0, 0, 1).finished();
        return kernel;
    }

    static
    const Eigen::Matrix4d&
    S_kernel(const Eigen::Vector4d&)
    {
        static Eigen::Matrix4d kernel = (Eigen::Matrix4d() << 2, 1, 1, 0,
                                                              1, 2, 0, 1,
                                                              1, 0, 2, 1,
                                                              0, 1, 1, 2).finished();
        return kernel;
    }
    
    template <typename VTYPE>
    static
    double
    compute_S(VTYPE&& a, VTYPE&& b)
    {
        const auto& kernel = S_kernel(a);
        double ret = a.transpose() * kernel * b;
        scoped_indent _("[compute_S] ");
        MSG_DEBUG("a = " << a.transpose());
        MSG_DEBUG("b = " << b.transpose());
        MSG_DEBUG("kernel" << std::endl << kernel);
        MSG_DEBUG("ret = " << ret);
        return ret;
    }

    /*
    static
    double
    compute_S(const std::vector<gamete_LV_type>& v1, const std::vector<gamete_LV_type>& v2)
    {
        size_t n_mei = 0;
        auto i1 = v1.begin(), i2 = v2.begin(), j = v1.end();
        double s = 0;
        // should assert that v1.size() == v2.size()
        for (; i1 != j; ++i1, ++i2) {
            n_mei += 2 - i1->is_single;
            s += compute_S(*i1, *i2);
        }
        return s / n_mei;
    }
    //*/
    
    static
    double
    S_to_dist(double s)
    {
        scoped_indent _("[S_to_dist] ");
#define EM_S_MIN .499999
#define EM_S_MAX .999999
        MSG_DEBUG("s = " << s);
        if (s > EM_S_MAX) {
            s = EM_S_MAX;
        } else if (s < EM_S_MIN) {
            s = EM_S_MIN;
        }
            
        MSG_DEBUG("s = " << s);
        
        return -.5 * log(s + s - 1);
    }
953
954
};

955
956
957


struct gamete_LV_database : public EM_helpers {
Damien Leroux's avatar
WIP.    
Damien Leroux committed
958
    /* IND.ped / MARK => 1 or 2 gametes (.second will be empty when cross type is DH) */
959
960
961
962
963
    std::map<int, gamete_LV_type> data;
    std::map<double, Eigen::Matrix2d> cache2;
    std::map<double, Eigen::Matrix4d> cache4;
    std::vector<Eigen::Matrix2d> tr2;
    std::vector<Eigen::Matrix4d> tr4;
Damien Leroux's avatar
WIP.    
Damien Leroux committed
964
    
965
    gamete_LV_database() : data(), cache2(), cache4() {}
Damien Leroux's avatar
WIP.    
Damien Leroux committed
966
967

    Eigen::Matrix2d
968
    get_TR_unary(double dist_or_r, bool use_r=false)
Damien Leroux's avatar
WIP.    
Damien Leroux committed
969
    {
970
971
972
973
974
975
976
977
978
        double r, s;
        if (use_r) {
            r = dist_or_r;
            s = 1. - r;
        } else {
            s = .5 + exp(-2. * dist_or_r) * .5;
            r = 1. - s;
        }
        auto it = cache2.find(r);
979
        if (it == cache2.end()) {
Damien Leroux's avatar
WIP.    
Damien Leroux committed
980
981
            Eigen::Matrix2d ret;
            ret << s, r, r, s;
982
            cache2[r] = ret;
983
984
985
986
987
988
            return ret;
        }
        return it->second;
    }
    
    Eigen::Matrix4d
989
    get_TR_binary(double dist_or_r, bool use_r=false)
990
    {
991
992
993
994
995
996
997
998
999
        double r, s;
        if (use_r) {
            r = dist_or_r;
            s = 1. - r;
        } else {
            s = .5 + exp(-2. * dist_or_r) * .5;
            r = 1. - s;
        }
        auto it = cache4.find(r);
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
        if (it == cache4.end()) {
            double rs = r * s;
            double r2 = r * r;
            double s2 = s * s;
            Eigen::Matrix4d ret;
            ret <<
                s2, rs, rs, r2,
                rs, s2, r2, rs,
                rs, r2, s2, rs,
                r2, rs, rs, s2;
1010
            cache4[r] = ret;
Damien Leroux's avatar
WIP.    
Damien Leroux committed
1011
1012
1013
1014
1015
            return ret;
        }
        return it->second;
    }
    
1016
1017
1018
    void get_TR(double dist, Eigen::Matrix2d& result) { result = get_TR_unary(dist); }
    void get_TR(double dist, Eigen::Matrix4d& result) { result = get_TR_binary(dist); }

Damien Leroux's avatar
WIP.    
Damien Leroux committed
1019
1020
1021
    void
    add_gametes(const std::string& mark, int ind, const VectorXd& lv, bool dh)
    {
1022
1023
1024
1025
1026
1027
1028
1029
        auto it = data.find(ind);
        if (it == data.end()) {
            data[ind].is_single = dh;
        } else {
            if (dh != it->second.is_single) {
                MSG_ERROR("Individual #" << ind << " was first declared as " << (it->second.is_single ? "intercross" : "doubled haploid") << " and is now requested to be the other kind.", "");
            }
        }
1030
1031
//         data[ind].add(mark, (lv.array() > 0).select(VectorXd::Ones(lv.size()), VectorXd::Zero(lv.size())).matrix());
        data[ind].add(mark, lv);
Damien Leroux's avatar
WIP.    
Damien Leroux committed
1032
1033
    }

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
    void init_tr(bool is_single, const std::vector<double>& distances)
    {
        if (is_single) {
            if (tr2.size()) {
                return;
            }
            tr2.reserve(distances.size());
            for (double d: distances) {
                tr2.emplace_back();
                get_TR(d, tr2.back());
            }
        } else {
            if (tr4.size()) {
                return;
            }
            tr4.reserve(distances.size());
            for (double d: distances) {
                tr4.emplace_back();
                get_TR(d, tr4.back());
            }
        }
    }
1056

1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
    template <typename V, typename M>
    double gamete_likelihood_impl(std::vector<M>& TR, V& accum, const std::vector<std::string>& marker_names, const gamete_LV_type& gam)
    {
        auto name_i = marker_names.begin();
        V tmp;
        gam.get(*name_i++, tmp);
//         accum = tmp / tmp.sum();
// //         accum = tmp / (tmp.array() > 0).template cast<double>().sum();
        accum = tmp * .25;
        for (const auto& t: TR) {
            gam.get(*name_i++, tmp);
            MSG_DEBUG("accum = " << accum.transpose() << " LV = " << tmp.transpose());
            accum = accum.transpose() * t * tmp.asDiagonal();
        }
        MSG_DEBUG("final accum = " << accum.transpose());
        return accum.sum();
    }
1074

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
    double gamete_likelihood(int ind, const gamete_LV_type& gam, const std::vector<std::string>& marker_names, const std::vector<double>& distances)
    {
        init_tr(gam.is_single, distances);
        if (gam.is_single) {
            Eigen::Vector2d accum;
            return gamete_likelihood_impl(tr2, accum, marker_names, gam);
        } else {
            Eigen::Vector4d accum;
            return gamete_likelihood_impl(tr4, accum, marker_names, gam);
        }
    }
    
Damien Leroux's avatar
WIP.    
Damien Leroux committed
1087
1088
1089
1090
1091
1092
1093
    double
    map_likelihood(const std::vector<std::string>& marker_names, const std::vector<double>& distances)
    {
        if (marker_names.size() != distances.size() + 1) {
            MSG_ERROR("Need to have exactly one more marker name than the number of inter-marker distances", "");
            return NAN;
        }
1094
1095
1096
1097
1098
        double ret = 0;
        for (const auto& kv: data) {
            ret += log(gamete_likelihood(kv.first, kv.second, marker_names, distances));
        }
        return ret;
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
    }
    
    std::vector<double> em_distances;
    std::vector<double> em_old_distances;
    std::vector<Eigen::Matrix2d> em_TR2;
    std::vector<Eigen::Matrix4d> em_TR4;
    bool em_have_single = false;
    bool em_have_double = false;
    std::vector<std::vector<gamete_lv_value_type>> em_state_per_mark_per_ind;
    std::vector<std::vector<gamete_lv_value_type>> em_forward, em_backward, em_obs;
    double em_likelihood;
    std::vector<bool> em_chain_is_single;
    
    void
    EM_init(const std::vector<std::string>& marker_names)
    {
        em_distances.clear();
        em_distances.resize(marker_names.size() - 1, .5);
        em_old_distances.clear();
        em_old_distances.resize(marker_names.size() - 1, 0);
        
        em_chain_is_single.clear();
        em_chain_is_single.reserve(data.size());
        em_state_per_mark_per_ind.resize(marker_names.size());
        auto spmpi = em_state_per_mark_per_ind.begin();
        em_forward.clear();
        em_forward.resize(marker_names.size());
        em_backward.clear();
        em_backward.resize(marker_names.size());
        auto forwardi = em_forward.begin();
        auto backwardi = em_backward.begin();
        MSG_DEBUG("forward " << em_forward);
        MSG_DEBUG("backward " << em_backward);
//         size_t i = 0;
        for (const auto& m: marker_names) {
            (spmpi++)->resize(data.size());
            (forwardi++)->resize(data.size(), gamete_lv_value_type::unknown_binary());
            (backwardi++)->resize(data.size(), gamete_lv_value_type::unknown_binary());
Damien Leroux's avatar
WIP.    
Damien Leroux committed
1137
        }
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
        MSG_DEBUG("data");
        MSG_DEBUG(data);
        for (const auto& kv: data) {  // all markers for one individual
            em_chain_is_single.push_back(kv.second.is_single);
            em_have_single |= kv.second.is_single;
            em_have_double |= !kv.second.is_single;
//             auto mi = marker_names.begin();
//             MSG_DEBUG("marker_names " << marker_names);
//             if (em_chain_is_single.back()) {
//                 for (auto& vec: *spmpi) {
//                     vec.unary = kv.second.lv.find(*mi++)->second.unary;
1149
//                 }
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
//             } else {
//                 for (auto& vec: *spmpi) {
//                     vec.binary = kv.second.lv.find(*mi++)->second.binary;
//                 }
//             }
//             ++i;
        }
        
        auto di = data.begin();
        for (size_t i = 0; i < data.size(); ++i, ++di) {
            size_t mi = 0;
            for (const auto& m: marker_names) {
                em_state_per_mark_per_ind[mi][i].binary = di->second.lv.find(m)->second.binary;
                ++mi;
            }
        }
        
        if (em_have_double) {
            em_TR4.resize(em_distances.size());
        }
        if (em_have_single) {
            em_TR2.resize(em_distances.size());
        }

        em_obs = em_state_per_mark_per_ind;

        MSG_DEBUG("data");
        MSG_DEBUG(data);
        
        MSG_DEBUG("em_state_per_mark_per_ind");
        MSG_DEBUG(em_state_per_mark_per_ind);
        MSG_DEBUG("Have single? " << std::boolalpha << em_have_single);
        MSG_DEBUG("Have double? " << std::boolalpha << em_have_double);
        
        /*EM_update_distances();*/
    }
    
    void
    EM_init_TR()
    {
        if (em_have_double) {
            for (size_t i = 0; i < em_distances.size(); ++i) {
                em_TR4[i] = get_TR_binary(em_distances[i], true);
            }
        }
        if (em_have_single) {
            for (size_t i = 0; i < em_distances.size(); ++i) {
                em_TR2[i] = get_TR_unary(em_distances[i], true);
Damien Leroux's avatar
WIP.    
Damien Leroux committed
1198
1199
            }
        }
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
    }

    template <typename TYPE>
    double
    norm(TYPE&& m_or_v, double& sum)
    {
        sum = m_or_v.sum();
        if (sum > 0) {
            sum = 1. / sum;
            m_or_v *= sum;
            return sum;
        }
        return std::numeric_limits<double>::signaling_NaN();
    }

    template <typename TYPE>
    double
    norm(TYPE&& m_or_v)
    {
        double sum;
        return norm(m_or_v, sum);
    }

    template <typename VTYPE>
    typename std::decay<VTYPE>::type
    mult_and_norm(VTYPE&& a, VTYPE&& b)
    {
        typename std::decay<VTYPE>::type ret = (a.array() * b.array()).matrix();
        norm(ret);
Damien Leroux's avatar
WIP.    
Damien Leroux committed
1229
1230
1231
        return ret;
    }

1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
    template <typename VTYPE>
    typename std::decay<VTYPE>::type
    mult_and_norm(VTYPE&& a, VTYPE&& b, VTYPE&& c)
    {
        typename std::decay<VTYPE>::type ret = (a.array() * b.array() * c.array()).matrix();
        norm(ret);
        return ret;
    }

    void
    EM_update_gamete_prob()
    {
        scoped_indent _("[EM update state] ");
        EM_init_TR();

        Eigen::Vector4d v4;
        Eigen::Vector2d v2;

        for (size_t i = 0; i < em_chain_is_single.size(); ++i) {
            if (em_chain_is_single[i]) {
                size_t m = 0;
                em_forward[m][i].unary = Eigen::Vector2d::Constant(.5);
                // forward.
                for (; m < em_distances.size(); ++m) {
                    double norm_accum;
                    em_forward[m + 1][i].unary = em_TR2[m] * mult_and_norm(em_forward[m][i].unary, em_obs[m][i].unary);
                    norm(em_forward[m + 1][i].unary, norm_accum);
                }
                // backward.
                em_backward[m][i].unary = Eigen::Vector2d::Constant(.5);
                for (; m > 0; --m) {
                    em_backward[m - 1][i].unary = em_TR2[m - 1] * mult_and_norm(em_backward[m][i].unary, em_obs[m][i].unary);
                    norm(em_backward[m - 1][i].unary);
                }
                // forward * backward * obs then normalize.
                for (; m < em_state_per_mark_per_ind.size(); ++m) {
                    em_state_per_mark_per_ind[m][i].unary = mult_and_norm(em_forward[m][i].unary, em_backward[m][i].unary, em_obs[m][i].unary);
                }
            } else {
                size_t m = 0;
                em_forward[m][i].binary = Eigen::Vector4d::Constant(.25);
                // forward.
                for (; m < em_distances.size(); ++m) {
                    em_forward[m + 1][i].binary = em_TR4[m] * mult_and_norm(em_forward[m][i].binary, em_obs[m][i].binary);
                    norm(em_forward[m + 1][i].binary);
                }
                // backward.
                em_backward[m][i].binary = Eigen::Vector4d::Constant(.25);
                for (; m > 0; --m) {
                    em_backward[m - 1][i].binary = em_TR4[m - 1] * mult_and_norm(em_backward[m][i].binary, em_obs[m][i].binary);
                    norm(em_backward[m - 1][i].binary);
                }
                // forward * backward * obs then normalize.
                for (; m < em_state_per_mark_per_ind.size(); ++m) {
                    em_state_per_mark_per_ind[m][i].binary = mult_and_norm(em_forward[m][i].binary, em_backward[m][i].binary, em_obs[m][i].binary);
                }
            }
        }
        
        MSG_DEBUG("em_forward");
        MSG_DEBUG(em_forward);
        MSG_DEBUG("em_backward");
        MSG_DEBUG(em_backward);
        MSG_DEBUG("em_obs");
        MSG_DEBUG(em_obs);
        MSG_DEBUG("em_state_per_mark_per_ind");
        MSG_DEBUG(em_state_per_mark_per_ind);
    }

    double
    twoMarkerLikelihood(size_t i, double r)
    {
        auto m1 = em_forward[i].begin();
        auto o1 = em_obs[i].begin();
        auto m2 = em_backward[i + 1].begin();
        auto o2 = em_obs[i + 1].begin();
        auto sing = em_chain_is_single.begin(), done = em_chain_is_single.end();
        double accum = 0;
        for (; sing != done; ++sing, ++m1, ++m2, ++o1, ++o2) {
            if (*sing) {
                accum += log(mult_and_norm(m1->unary, o1->unary).transpose() * get_TR_unary(r, true) * mult_and_norm(m2->unary, o2->unary));
            } else {
                Eigen::Vector4d mm1 = mult_and_norm(m1->binary, o1->binary);
                Eigen::Vector4d mm2 = mult_and_norm(m2->binary, o2->binary);
                /*MSG_DEBUG("mm1 " << mm1.transpose());*/
                /*MSG_DEBUG("mm2 " << mm2.transpose());*/
                accum += log(mm1.transpose() * get_TR_binary(r, true) * mm2);
            }
        }
        return accum;
    }

    double
    compute_2pt_dist(size_t i)
    {
        for (double r = 0; r < .5; r += .05) {
            MSG_DEBUG("i=" << i << " r=" << r << " log(L)=" << twoMarkerLikelihood(i, r ? r : 0.0001));
        }
        auto opt = find_max([&] (double r) { return twoMarkerLikelihood(i, r); }, .5 - EM_S_MIN, EM_S_MIN);
        return (opt.a + opt.b) * .5;
        /*double s = 1. - (opt.a + opt.b) * .5;*/
        /*return 100. * S_to_dist(s);*/
        /*
        const auto& m1 = em_state_per_mark_per_ind[i1];
        const auto& m2 = em_state_per_mark_per_ind[i2];
        auto m1i = m1.begin(), m1j = m1.end(), m2i = m2.begin();
        auto single_i = em_chain_is_single.begin();
        double S_accum = 0;
        size_t n_mei = em_chain_is_single.size() + std::count(em_chain_is_single.begin(), em_chain_is_single.end(), false);
        MSG_DEBUG("em_chain_is_single.size " << em_chain_is_single.size());
        for (; m1i != m1j; ++m1i, ++m2i, ++single_i) {
//             ++n_mei;
            if (*single_i) {
                S_accum += compute_S(m1i->unary, m2i->unary);
            } else {
                S_accum += compute_S(m1i->binary, m2i->binary);
            }
            MSG_DEBUG("S_accum " << S_accum << " n_mei " << n_mei);
        }
        double ret = S_to_dist(S_accum / n_mei);
        MSG_DEBUG("computed 2pt dist = " << ret);
        return ret;
        //*/        
    }
    
    void
    EM_update_distances()
    {
        em_old_distances = em_distances;
        MSG_DEBUG("[update dist] old distances " << em_old_distances);
        for (size_t i = 0; i < em_distances.size(); ++i) {
            em_distances[i] = compute_2pt_dist(i);
        }
        MSG_DEBUG("[update dist] new distances " << em_distances);
    }
    
    double
    EM_delta()
    {
        double accum = 0;
        auto i = em_distances.begin(), j = em_distances.end(), k = em_old_distances.begin();
        for (; i != j; ++i, ++k) {
            accum += fabs(*i - *k);
        }
        MSG_DEBUG("distances old " << em_old_distances << " new " << em_distances << " => " << accum);
        return accum;
    }
    
    
    struct EM_map {
        std::vector<std::string> marker_names;
        std::vector<double> distances;
        double likelihood;
        int n_iterations;
    };
    
    EM_map
    EM(const std::vector<std::string>& marker_names, double convergence_threshold = 1.e-12, int max_iterations = 100)
    {
        double delta;
        EM_map ret;
        ret.n_iterations = 0;
        ret.marker_names = marker_names;
        EM_init(marker_names);
        EM_update_gamete_prob(); // E
        do {
            MSG_DEBUG("*** ITERATION ***");
            EM_update_gamete_prob(); // E
            EM_update_distances(); // M
            delta = EM_delta();
            ++ret.n_iterations;
        } while (delta > convergence_threshold && ret.n_iterations < max_iterations);
        ret.distances = em_distances;
        for (double& d: ret.distances) {
            d = -50. * log(1 - 2. * d);
        }
        ret.likelihood = /* ? */ -1;
        if (ret.n_iterations == max_iterations && delta > convergence_threshold) {
            ret.n_iterations = -1;
        }
        return ret;
    }
    

Damien Leroux's avatar
WIP.    
Damien Leroux committed
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
    template <typename STREAM_TYPE>
        void
        file_io(STREAM_TYPE& fs)
        {
            rw_base rw;
            if (rw.fourcc(fs, "GMLV")) { return; }
            rw(fs, data);
        }

    static
        gamete_LV_database
        load_from(const std::string& filename)
        {
            ifile ifs(filename);
            gamete_LV_database ret;
            ret.file_io(ifs);
            return ret;
        }

    void
        save_to(const std::string& filename)
        {
            ofile ofs(filename);
            file_io(ofs);
        }
};

1443
1444

struct LV_database {
1445
1446
1447
    /* GEN / MARK / IND => LV_vec */
    std::map<std::string, std::map<std::string, std::vector<VectorXd>>> data_by_marker;
    /* CHROM / GEN / IND => LV_mat */
1448
1449
    std::map<std::string, std::map<std::string, std::vector<MatrixXd>>> data;

1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
    LV_database() : data_by_marker(), data() {}

    void assemble_using_map(const std::vector<chromosome>& map)
    {
        data.clear();
        for (const auto& chr: map) {
            for (const auto& gen_dat: data_by_marker) {
                const auto& gen = gen_dat.first;
                const auto& mark_ind_lv = gen_dat.second;
                size_t n_states = mark_ind_lv.begin()->second.front().size();
                size_t n_mark = chr.raw.marker_name.size();
1461
                size_t n_condensed_mark = chr.condensed.marker_name.size();
1462
1463
1464
                size_t n_ind = mark_ind_lv.begin()->second.size();
                auto& ind_LVmat = data[chr.name][gen];
                ind_LVmat.resize(n_ind, {n_states, n_mark});
1465
1466
                /*MSG_DEBUG("[assemble.using.map] #haplo_size=" << chr.haplo_sizes.size());*/
                /*MSG_QUEUE_FLUSH();*/
Damien Leroux's avatar
Damien Leroux committed
1467
1468
                for (size_t ind = 0; ind < n_ind; ++ind) {
                    auto& mat = ind_LVmat[ind];
1469
                    mat = MatrixXd::Ones(n_states, n_condensed_mark);
Damien Leroux's avatar
Damien Leroux committed
1470
                    size_t m = 0;
1471
1472
                    int haplo_counter = 0;
                    auto haplo_size_i = chr.haplo_sizes.begin();
Damien Leroux's avatar
Damien Leroux committed
1473
1474
                    for (const auto& mark: chr.raw.marker_name) {
                        const auto& svec = mark_ind_lv.find(mark)->second;
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
                        /*MSG_DEBUG("[assemble.using.map] haplo_size=" << (*haplo_size_i) << " column=" << m);*/
                        /*MSG_QUEUE_FLUSH();*/
                        mat.col(m).array() *= svec[ind].array();
                        ++haplo_counter;
                        if (haplo_counter == *haplo_size_i) {
                            ++m;
                            ++haplo_size_i;
                            haplo_counter = 0;
                        }
                    }
                    auto hi = chr.begin();
                    for (int c = 0; c < mat.cols(); ++c, ++hi) {
                        double sum = mat.col(c).sum();
                        if (sum == 0) {
1489
1490
1491
1492
1493
1494
1495
                            /*std::stringstream ss;*/
                            /*ss << "Detected inconsistent observations! Generation is " << gen << ", chromosome " << chr.name << ", individual #" << (ind + 1) << ", involving markers";*/
                            /*auto haplo = *hi;*/
                            /*for (size_t i = haplo.first; i < haplo.second; ++i) {*/
                                /*ss << ' ' << chr.raw.marker_name[i];*/
                            /*}*/
                            /*MSG_WARNING(ss.str());*/
1496
1497
1498
                        } else {
                            mat.col(c) /= sum;
                        }
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
                    }
                }
            }
        }
    }

    MatrixXd operator () (
            std::vector<std::string>::const_iterator begin,
            std::vector<std::string>::const_iterator end,
            const std::string& gen, size_t ind) const
    {
        const auto& milv = data_by_marker.find(gen)->second;
        size_t n_states = milv.find(*begin)->second.front().size();
        MatrixXd LV(n_states, end - begin);
        for (size_t i = 0; i < n_states; ++i) {
            LV.col(i) = milv.find(*begin)->second[ind];
        }
        return LV;
    }

1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
    MatrixXd& operator () (const std::string& chr, const std::string& gen, size_t ind)
    {
        return data[chr][gen][ind];
    }

    const MatrixXd& operator () (const std::string& chr, const std::string& gen, size_t ind) const
    {
        return data.find(chr)->second.find(gen)->second[ind];
    }

1529
1530
1531
1532
1533
1534
    std::map<std::string, std::vector<MatrixXd>>
        extract(const std::string& gen, const std::vector<size_t> ind_vec) const
        {
            std::map<std::string, std::vector<MatrixXd>> ret;
            for (const auto& chr_gen_lv_vec: data) {
                const std::string& chr = chr_gen_lv_vec.first;
Damien Leroux's avatar
Damien Leroux committed
1535
1536
1537
1538
1539
1540
1541
                auto it = chr_gen_lv_vec.second.find(gen);
                if (it == chr_gen_lv_vec.second.end()) {
                    /* whine */
                    MSG_ERROR("Generation " << gen << " doesn't exist!", "Double-check the generation names given in commandline.");
                    continue;
                }
                const auto& lv_vec = it->second;
1542
1543
1544
1545
1546
1547
1548
1549
1550
                auto& ret_lv_vec = ret[chr];
                ret_lv_vec.reserve(ind_vec.size());
                for (size_t i: ind_vec) {
                    ret_lv_vec.push_back(lv_vec[i]);
                }
            }
            return ret;
        }

1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
    template <typename STREAM_TYPE>
        void
        file_io(STREAM_TYPE& fs)
        {
            rw_base rw;
            if (rw.fourcc(fs, "SMLV")) { return; }
            rw(fs, data_by_marker);
            rw(fs, data);
        }

    static
        LV_database
        load_from(const std::string& filename)
        {
1565
            ifile ifs(filename);
1566
1567
1568
1569
1570
1571
1572
1573
            LV_database ret;
            ret.file_io(ifs);
            return ret;
        }

    void
        save_to(const std::string& filename)
        {
1574
            ofile ofs(filename);
1575
1576
1577
1578
            file_io(ofs);
        }

    /*
1579
    static
1580
        bool lv_check_fourcc(ifile& ifs, const char* fourcc)
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
        {
            if (check_fourcc(ifs, fourcc)) {
                MSG_ERROR("FILE IS NOT A LOCUS VECTOR FILE OR IS CORRUPTED", "You may want to run spell-marker again.");
                return true;
            }
            return false;
        }

    static
        LV_database load_from(const std::string& filename)
        {
1592
            ifile ifs(filename);
1593
1594
1595
1596
            return load_from(ifs);
        }

    static
1597
        LV_database load_from(ifile& ifs)
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
        {
            LV_database LV;

            if (lv_check_fourcc(ifs, "SMLV")) { return {}; }
            size_t n_chrom = read_size(ifs);
            size_t n_gen = read_size(ifs);
            for (size_t c = 0; c < n_chrom; ++c) {
                if (lv_check_fourcc(ifs, "SCHR")) { return {}; }
                std::string chr_name = read_str(ifs);
                for (size_t g = 0; g < n_gen; ++g) {
                    if (lv_check_fourcc(ifs, "SGEN")) { return {}; }
                    std::string gen_name = read_str(ifs);
                    size_t n_ind = read_size(ifs);
                    LV.data[chr_name][gen_name].resize(n_ind);
                    for (size_t i = 0; i < n_ind; ++i) {
                        if (lv_check_fourcc(ifs, "SLV_")) { return {}; }
                        read_matrix(ifs, LV.data[chr_name][gen_name][i]);
                    }
                }
            }
            return LV;
        }

    void save_to(const std::string& filename)
    {
1623
        ofile ofs(filename);
1624
1625
1626
        save_to(ofs);
    }

1627
    void save_to(ofile& ofs)
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
    {
        write_fourcc(ofs, "SMLV");
        write_size(ofs, data.size());
        write_size(ofs, data.begin()->second.size());
        for (const auto& chr_gen_vec_lv: data) {
            write_fourcc(ofs, "SCHR");
            write_str(ofs, chr_gen_vec_lv.first);
            for (const auto& gen_vec_lv: chr_gen_vec_lv.second) {
                write_fourcc(ofs, "SGEN");
                write_str(ofs, gen_vec_lv.first);
                write_size(ofs, gen_vec_lv.second.size());
                for (const auto& lv: gen_vec_lv.second) {
                    write_fourcc(ofs, "SLV_");
                    write_matrix(ofs, lv);
                }
            }
        }
    }
1646
    */
1647
1648
1649
1650
1651

    friend
        std::ostream& operator << (std::ostream& os, const LV_database& LV)
        {
            for (const auto& chr_gen_vec_lv: LV.data) {
1652
                os << "CHROMOSOME " << chr_gen_vec_lv.first << std::endl;
1653
                for (const auto& gen_vec_lv: chr_gen_vec_lv.second) {
1654
                    os << "* generation " << gen_vec_lv.first << std::endl;
1655
1656
                    size_t i = 0;
                    for (const auto& lv: gen_vec_lv.second) {
1657
                        os << "  #" << i << std::endl;
1658
                        ++i;
1659
                        os << lv << std::endl;
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
                    }
                }
            }
            return os;
        }
};


/** **/


1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
template <typename V>
std::vector<V>
filter_vector(const std::vector<V>& vec, const std::vector<size_t>& list)
{
    std::vector<V> ret;
    ret.reserve(list.size());
    for (size_t i: list) {
        ret.push_back(vec[i]);
    }
    return ret;
}


1684
1685
struct qtl_pop_type {
    std::string name;
Damien Leroux's avatar
Damien Leroux committed
1686
    std::string qtl_generation_name;