output.h 20 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _SPELL_BAYES_OUTPUT_H_
#define _SPELL_BAYES_OUTPUT_H_

#include <map>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <cstring>

#include "eigen.h"
#include "error.h"
#include "generation_rs_fwd.h"
14
#include "input/read_trait.h"
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

/** FOURCC **/

inline
bool check_fourcc(std::ifstream& ifs, const char* fourcc)
{
    char buf[4] = {0, 0, 0, 0};
    ifs.read(buf, 4);
    return strncmp(fourcc, buf, 4);
}

inline
void write_fourcc(std::ofstream& ofs, const char* fourcc)
{
    ofs.write(fourcc, 4);
}

/** SIZE_T **/

inline
void write_size(std::ofstream& ofs, size_t sz)
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
size_t read_size(std::ifstream& ifs)
{
    size_t ret;
    ifs.read((char*) &ret, sizeof ret);
    return ret;
}

/** STRING **/

inline
std::string read_str(std::ifstream& ifs)
{
    size_t sz = read_size(ifs);
    std::vector<char> tmp(sz);
    ifs.read(&tmp[0], sz);
    return {tmp.begin(), tmp.end()};
}

inline
void write_str(std::ofstream& ofs, const std::string& s)
{
    write_size(ofs, s.size());
    ofs.write(s.c_str(), s.size());
}

/** DOUBLE **/

inline
void write_double(std::ofstream& ofs, double sz)
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
double read_double(std::ifstream& ifs)
{
    double ret;
    ifs.read((char*) &ret, sizeof ret);
    return ret;
}

/** INT **/

inline
void write_int(std::ofstream& ofs, int sz)
{
    ofs.write((const char*) &sz, sizeof sz);
}

inline
int read_int(std::ifstream& ifs)
{
    int ret;
    ifs.read((char*) &ret, sizeof ret);
    return ret;
}

/** FAST_POLYNOM **/

inline
void write_fast_polynom(std::ofstream& ofs, const fast_polynom& fp)
{
    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
fast_polynom read_fast_polynom(std::ifstream& ifs, int& original_key)
{
    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 **/

inline void write_algebraic_genotype(std::ofstream& ofs, const algebraic_genotype& ag)
{
    ofs.write((const char*) &ag.genotype, sizeof ag.genotype);
    ofs.write((const char*) &ag.type, sizeof ag.type);
    write_int(ofs, ag.poly.value);
}

inline algebraic_genotype read_algebraic_genotype(std::ifstream& ifs, const std::map<int, fast_polynom>& pt)
{
    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 **/

inline void write_genomatrix(std::ofstream& ofs, const GenoMatrix& mat)
{
    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
void read_genomatrix(std::ifstream& ifs, GenoMatrix& mat)
{
    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 **/

inline void write_generation_rs(std::ofstream& ofs, const generation_rs* gen)
{
    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
generation_rs* read_generation_rs(std::ifstream& ifs)
{
    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();*/
    generation_rs* ret = generation_rs::blank(name);
    /*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;
}

/** 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); } };

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>
void read_matrix(std::ifstream& ifs, Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat)
{
    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>
void write_matrix(std::ofstream& ofs, const Eigen::Matrix<SCALAR, ROW, COL, C, D, E>& mat)
{
    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));
}


/** **/


struct LV_database {
    std::map<std::string, std::map<std::string, std::vector<MatrixXd>>> data;

    LV_database() : data() {}
    
    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];
    }

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    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;
                const auto& lv_vec = chr_gen_lv_vec.second.find(gen)->second;
                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;
        }

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
    static
        bool lv_check_fourcc(std::ifstream& ifs, const char* fourcc)
        {
            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)
        {
            std::ifstream ifs(filename);
            return load_from(ifs);
        }

    static
        LV_database load_from(std::ifstream& ifs)
        {
            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)
    {
        std::ofstream ofs(filename);
        save_to(ofs);
    }

    void save_to(std::ofstream& ofs)
    {
        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);
                }
            }
        }
    }

    friend
        std::ostream& operator << (std::ostream& os, const LV_database& LV)
        {
            for (const auto& chr_gen_vec_lv: LV.data) {
                MSG_DEBUG("CHROMOSOME " << chr_gen_vec_lv.first);
                for (const auto& gen_vec_lv: chr_gen_vec_lv.second) {
                    MSG_DEBUG("* generation " << gen_vec_lv.first);
                    size_t i = 0;
                    for (const auto& lv: gen_vec_lv.second) {
                        MSG_DEBUG("  #" << i);
                        ++i;
                        MSG_DEBUG(lv);
                    }
                }
            }
            return os;
        }
};


/** **/


405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
struct qtl_pop_type {
    std::string name;
    std::vector<size_t> indices;
    const generation_rs* gen;
    std::map<std::string, std::vector<MatrixXd>> LV;
    std::string observed_traits_filename;
    std::vector<trait> observed_traits;
    /*qtl_pop_type(const std::string& n, const std::vector<size_t>& ind, const generation_rs* g,*/
                 /*std::vector<MatrixXd>&& lv, const std::string& otf, std::vector<trait>&& ot)*/
        /*: name(n), indices(ind), gen(g), LV(std::move(lv)), observed_traits_filename(ofs), observed_traits(std::move(ot))*/
    /*{}*/

    size_t size() const
    {
        return observed_traits.front().values.size();
    }

    const MatrixXd& get_LV(const std::string& chr, size_t i) const { return LV.find(chr)->second[i]; }
};


/** **/


429
430
431
432
433
434
435
436
struct pop_data_type {
    std::string name;
    std::map<std::string, std::string> marker_observation_filenames;
    std::string genetic_map_filename;
    std::string pedigree_filename;
    std::string qtl_generation_name;
    std::map<std::string, generation_rs*> generations;
    LV_database LV;
437
438
    std::map<std::string, std::vector<int>> families;
    std::map<size_t, const generation_rs*> gen_by_id;
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

    std::string save()
    {
        static const char* forbidden = ":?*/\\";
        std::stringstream filename;
        for (char c: name) {
            if (strchr(forbidden, c)) {
                filename << '_';
            } else {
                filename << c;
            }
        }
        filename << ".popdata";
        save_to(filename.str());
        return filename.str();
    }

    void save_to(const std::string& filename)
    {
        std::ofstream ofs(filename);
        write_fourcc(ofs, "SPOP");
        write_str(ofs, name);
        write_size(ofs, marker_observation_filenames.size());
        for (const auto& kv: marker_observation_filenames) {
            write_str(ofs, kv.first);
            write_str(ofs, kv.second);
        }
        write_str(ofs, genetic_map_filename);
        write_str(ofs, pedigree_filename);
        write_str(ofs, qtl_generation_name);
        write_size(ofs, generations.size());
        for (const auto& kv: generations) {
            write_fourcc(ofs, "SGTE");
            write_str(ofs, kv.first);
            write_generation_rs(ofs, kv.second);
        }
        LV.save_to(ofs);
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
        write_fourcc(ofs, "SFAM");
        write_size(ofs, families.size());
        for (const auto& kv: families) {
            write_str(ofs, kv.first);
            write_size(ofs, kv.second.size());
            for (int i: kv.second) {
                write_int(ofs, i);
            }
        }
        write_fourcc(ofs, "SGBI");
        write_size(ofs, gen_by_id.size());
        for (const auto& kv: gen_by_id) {
            write_size(ofs, kv.first);
            write_str(ofs, kv.second->name);
        }
491
492
    }

493
494
495
496
497
498
499
500
501
502
    static
        bool pop_check_fourcc(std::ifstream& ifs, const char* fourcc)
        {
            if (check_fourcc(ifs, fourcc)) {
                MSG_ERROR("Could not read FOURCC \"" << fourcc << "\". This is not a valid population data file.", "");
                return true;
            }
            return false;
        }

503
504
505
    static
        pop_data_type load_from(const std::string& filename)
        {
506
#define CHECK_4CC(_fourcc_) if (pop_check_fourcc(ifs, _fourcc_)) { return ret; }
507
508
            std::ifstream ifs(filename);
            pop_data_type ret;
509
            CHECK_4CC("SPOP");
510
511
512
513
514
515
516
517
518
519
520
521
            ret.name = read_str(ifs);
            size_t n_mof = read_size(ifs);
            for (size_t i = 0; i < n_mof; ++i) {
                std::string k = read_str(ifs);
                std::string v = read_str(ifs);
                ret.marker_observation_filenames[k] = v;
            }
            ret.genetic_map_filename = read_str(ifs);
            ret.pedigree_filename = read_str(ifs);
            ret.qtl_generation_name = read_str(ifs);
            size_t n_gen = read_size(ifs);
            for (size_t i = 0; i < n_gen; ++i) {
522
                CHECK_4CC("SGTE");
523
524
525
526
                std::string k = read_str(ifs);
                ret.generations[k] = read_generation_rs(ifs);
            }
            ret.LV = LV_database::load_from(ifs);
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
            CHECK_4CC("SFAM");
            size_t n_fam = read_size(ifs);
            for (size_t f = 0; f < n_fam; ++f) {
                std::string k = read_str(ifs);
                size_t n_ind = read_size(ifs);
                auto& fam = ret.families[k];
                for (size_t i = 0; i < n_ind; ++i) {
                    ret.families[k].push_back(read_int(ifs));
                }
            }
            CHECK_4CC("SGBI");
            size_t n_gbi = read_size(ifs);
            for (size_t g = 0; g < n_gbi; ++g) {
                size_t k = read_size(ifs);
                std::string gen = read_str(ifs);
                ret.gen_by_id[k] = ret.generations[gen];
            }
544
545
546
            return ret;
        }

547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    size_t size() const { return families.find(qtl_generation_name)->second.size(); }

    const generation_rs* get_generation_rs(const std::string& family, size_t ind) const
    {
        return gen_by_id.find(families.find(family)->second[ind])->second;
    }

    std::map<const generation_rs*, std::vector<size_t>>
        all_qtl_generation_rs() const
        {
            std::map<const generation_rs*, std::vector<size_t>> ret;
            size_t i = 0;
            for (size_t ind: families.find(qtl_generation_name)->second) {
                ret[gen_by_id.find(ind)->second].push_back(i);
                ++i;
            }
            return ret;
        }

Damien Leroux's avatar
Damien Leroux committed
566
    std::string extract_subpops(std::multimap<std::string, qtl_pop_type>& pops, const std::string& traits_filename, const std::vector<trait>& traits, std::vector<std::vector<const qtl_pop_type*>>& linked_pops)
567
568
569
570
571
572
573
574
575
576
577
578
579
580
    {
        auto extract_traits
            = [&] (const std::vector<size_t>& ind_vec)
            {
                std::vector<trait> ret;
                ret.resize(traits.size());
                for (size_t ti = 0; ti < traits.size(); ++ti) {
                    ret[ti].name = traits[ti].name;
                    ret[ti].values.reserve(ind_vec.size());
                    for (size_t i: ind_vec) { ret[ti].values.push_back(traits[ti].values[i]); }
                }
                return ret;
            };
        auto aqg = all_qtl_generation_rs();
Damien Leroux's avatar
Damien Leroux committed
581
582
        linked_pops.emplace_back();
        linked_pops.back().reserve(aqg.size());
583
        for (const auto& kv: aqg) {
Damien Leroux's avatar
Damien Leroux committed
584
585
586
587
588
589
590
591
592
593
            auto it = 
                pops.insert({name, {
                    name,
                    kv.second,
                    kv.first,
                    LV.extract(qtl_generation_name, kv.second),
                    traits_filename,
                    extract_traits(kv.second)
                }});
            linked_pops.back().push_back(&it->second);
594
595
596
597
        }
        return name;
    }

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
    template <typename PRINTABLE>
    static
        void prepend(std::ostream& os, const std::string& pfx, PRINTABLE&& p)
        {
            std::stringstream ss;
            ss << p;
            while (!ss.eof()) {
                std::string line;
                std::getline(ss, line);
                os << pfx << line << std::endl;
            }
        }

    friend
        std::ostream& operator << (std::ostream& os, const pop_data_type& pop_data)
        {
            os << "POPULATION " << pop_data.name << std::endl
               << "| QTL generation: " << pop_data.qtl_generation_name << std::endl
               << "| Marker observations:" << std::endl;
            for (const auto& kv: pop_data.marker_observation_filenames) {
                os << "| - " << kv.first << ": " << kv.second << std::endl;
            }
            os << "| Generation matrices:" << std::endl;
            for (const auto& kv: pop_data.generations) {
                prepend(os, "|   ", (*kv.second));
            }
624
625
626
627
            os << "| Families" << std::endl;
            for (const auto& kv: pop_data.families) {
                os << "| * " << kv.first << ": " << kv.second << std::endl;
            }
628
            os << "| Computed locus vectors:" << std::endl;
629
630
631
632
633
            /*prepend(os, "| ", pop_data.LV);*/
            for (const auto& kv: pop_data.LV.data) {
                os << "| Chromosome " << kv.first << std::endl;
                for (const auto& gen_lv: kv.second) {
                    os << "|   Generation " << gen_lv.first << std::endl;
634
                    const auto& family = pop_data.families.find(gen_lv.first)->second;
635
                    for (size_t i = 0; i < gen_lv.second.size(); ++i) {
636
                        os << "|     #" << i << "  " << pop_data.get_generation_rs(gen_lv.first, i)->name << std::endl;
637
638
639
640
                        prepend(os, "|     ", gen_lv.second[i]);
                    }
                }
            }
641
642
643
644
645
646
647
648
649
650

            return os;
        }
};




#endif