generalized_product.cc 28.1 KB
Newer Older
1
#define SPELL_UNSAFE_OUTPUT
2
#include "bayes/generalized_product.h"
3
4
/*#include "graphnode.h"*/
#include "graphnode2.h"
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

#include <algorithm>
#include <random>

struct random_test {
    size_t max_alleles;
    size_t min_alleles;
    size_t n_variables;
    size_t n_tables;
    size_t min_variables;
    size_t max_variables;
    size_t min_output;
    size_t max_output;

    double prob_skip_state;

    std::random_device rd;
    std::mt19937_64 gen;
    std::uniform_int_distribution<unsigned long> N_AL;
    std::uniform_int_distribution<unsigned long> N_VAR;
    std::uniform_int_distribution<std::vector<int>::iterator::difference_type> SHUFFLE;
    std::uniform_real_distribution<double> R;
    std::uniform_real_distribution<double> COEF;

    std::vector<bn_label_type> alleles;
    std::vector<int> variables;
    std::map<std::vector<int>, genotype_comb_type> domains;

    std::vector<genotype_comb_type> tables;
    std::vector<int> all_used_vars;

    random_test()
        : max_alleles(2)
        , min_alleles(2)
        , n_variables(4)
        , n_tables(3)
        , min_variables(2)
        , max_variables(3)
        , min_output(1)
        , max_output(4)
        , prob_skip_state(.5)
        , rd()
        , gen(rd())
        , N_AL(min_alleles, max_alleles)
        , N_VAR(min_variables, max_variables)
        , SHUFFLE()
        , R(0, 1)
        , COEF(1, 1)
        , alleles()
        , variables()
        , domains()
        , tables(n_tables)
        , all_used_vars()
    {}

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
    random_test&
        set_allele_range(size_t min, size_t max)
        {
            min_alleles = min;
            max_alleles = max;
            N_AL = decltype(N_AL)(min, max);
            return *this;
        }

    random_test&
        set_n_var_range(size_t min, size_t max)
        {
            min_variables = min;
            max_variables = max;
            N_VAR = decltype(N_VAR)(min, max);
            return *this;
        }

    random_test&
        set_coef_range(double min, double max)
        {
            COEF = decltype(COEF)(min, max);
            return *this;
        }

    random_test&
        set_output_range(size_t min, size_t max)
        {
            min_output = min;
            max_output = max;
            return *this;
        }

    random_test&
        set_n_tables(size_t n)
        {
            n_tables = n;
            return *this;
        }

100
101
102
    void
        init()
        {
103
104
105
106
107
108
            alleles.clear();
            tables.clear();
            variables.clear();
            domains.clear();
            all_used_vars.clear();

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
            auto coin = [&](double p) { return R(gen) < p; };

            MSG_DEBUG("GENERATING DATA...");

            for (size_t i = 0; i < max_alleles; ++i) {
                alleles.push_back({'a', 'a', (char) i, (char) i});
            }
            MSG_DEBUG("  alleles. " << alleles);

            for (size_t i = 0; i < n_variables; ++i) {
                variables.push_back(i + 1);
                auto& domain = domains[{variables.back()}];
                size_t n_al = N_AL(gen);
                MSG_DEBUG("   n_al = " << n_al);
                domain.m_combination.reserve(n_al);
                for (size_t a = 0; a < n_al; ++a) {
                    domain.m_combination.emplace_back(genotype_comb_type::key_list{{variables.back(), alleles[a]}}, 1.);
                }
            }
            MSG_DEBUG("  variables.");
            for (const auto& kv: domains) {
                MSG_DEBUG("    * " << kv.first[0] << ": " << kv.second);
            }

            std::function<void(std::vector<int>::const_iterator, std::vector<int>::const_iterator, double&, const genotype_comb_type::element_type&, genotype_comb_type&)>
                generate_states_rec
                = [&] (std::vector<int>::const_iterator i, std::vector<int>::const_iterator j, double& norm, const genotype_comb_type::element_type& accum, genotype_comb_type& result)
                {
                    if (i == j) {
                        if (!coin(prob_skip_state)) {
                            double coef = COEF(gen);
                            result.m_combination.push_back(accum * coef);
                            norm += coef;
                        }
                    } else {
                        for (const auto& e: domains[{*i}]) {
                            generate_states_rec(i + 1, j, norm, accum * e, result);
                        }
                    }
                };

            auto generate_states
                = [&] (const std::vector<int>& vars, genotype_comb_type& ret)
                {
                    double norm = 0;
                    genotype_comb_type::element_type e;
                    e.coef = 1.;
                    generate_states_rec(vars.begin(), vars.end(), norm, e, ret);
                    /*if (norm > 0) {*/
                        /*norm = 1. / norm;*/
                        /*for (auto& e: ret) {*/
                            /*e.coef *= norm;*/
                        /*}*/
                    /*}*/
                };

165
            tables.resize(n_tables);
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
            for (size_t t = 0; t < n_tables; ++t) {
                MSG_DEBUG("current variable list " << variables);
                std::shuffle(variables.begin(), variables.end(), gen);
                MSG_DEBUG("shuffled variable list " << variables);
                /* pick variables */
                size_t n_v = N_VAR(gen);
                MSG_DEBUG("n_v = " << n_v);
                std::vector<int> vars(variables.begin(), variables.begin() + n_v);
                std::sort(vars.begin(), vars.end());
                all_used_vars = all_used_vars + vars;
                /* generate states */
                MSG_DEBUG("  generating table for variables " << vars);
                generate_states(vars, tables[t]);
            }
            MSG_DEBUG("  tables.");

            MSG_DEBUG("TABLES:");
            for (const auto& t: tables) {
                MSG_DEBUG(" * " << t);
            }
        }

    std::vector<int>
        output_vars(size_t n)
        {
            std::vector<int> output = all_used_vars;
192
            std::shuffle(output.begin(), output.end(), gen);
193
194
            output.resize(std::min(output.size(), n));
            std::sort(output.begin(), output.end());
195
            /*MSG_DEBUG("OUTPUT: " << output);*/
196
197
198
199
200
201
            return output;
        }

    std::pair<double, double>
        new_product(const std::vector<int>& output, genotype_comb_type& result, size_t n_repeats = 1)
        {
202
            double inv_repeat_micro = 1.e-6 / n_repeats;
203
204
205
206
207
208
209
210
211
212
213
214
215
216
            auto t0 = std::chrono::high_resolution_clock::now();
            joint_variable_product_type jvp;
            for (const auto& t: tables) {
                jvp.add_table(t);
            }
            jvp.set_output(output);
            jvp.compile(domains);
            auto init = std::chrono::high_resolution_clock::now();
            for (; n_repeats > 1; --n_repeats) {
                jvp.compute();
            }
            result = jvp.compute();
            auto done = std::chrono::high_resolution_clock::now();

217
218
219
220
221
222
223
224
225
            /*if (n_repeats == 1) {*/
                /*auto i = jvp.tables.begin();*/
                /*auto j = jvp.tables.end();*/
                /*MSG_DEBUG((*i->data));*/
                /*for (++i; i != j; ++i) {*/
                    /*MSG_DEBUG(" *" << std::endl << (*i->data));*/
                /*}*/
            /*}*/
            /*MSG_DEBUG(" =" << std::endl << result);*/
226
227

            return {
228
                std::chrono::duration_cast<std::chrono::microseconds>(init - t0).count() * 1.e-6,
229
230
231
232
233
234
235
                std::chrono::duration_cast<std::chrono::microseconds>(done - init).count() * inv_repeat_micro,
            };
        }

    std::pair<double, double>
        old_product(const std::vector<int>& output, genotype_comb_type& result, size_t n_repeats = 1)
        {
236
            double inv_repeat_micro = 1.e-6 / n_repeats;
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
            auto t0 = std::chrono::high_resolution_clock::now();
            for (; n_repeats > 0; --n_repeats) {
                result = tables[0];
                for (size_t ti = 1; ti < tables.size(); ++ti) {
                    result = kronecker(result, tables[ti]);
                }
                result = project(result, output, {});
            }
            auto done = std::chrono::high_resolution_clock::now();
            return {
                0.,
                std::chrono::duration_cast<std::chrono::microseconds>(done - t0).count() * inv_repeat_micro,
            };

        }

    bool
254
        test_equality(const std::vector<int>& output, double& old_time, double& new_time)
255
256
        {
            genotype_comb_type n, o;
257
258
259
260
261
            auto nt = new_product(output, n);
#if 1
            auto ot = old_product(output, o);
            old_time += ot.second;
            new_time += nt.first + nt.second;
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            auto ni = n.begin(), nj = n.end(), oi = o.begin(), oj = o.end();
            for (; ni != nj && oi != oj; ++ni, ++oi) {
                if (ni->keys != oi->keys) {
                    MSG_DEBUG("Keys differ " << (*ni) << " vs " << (*oi));
                    break;
                }
                if (fabs(ni->coef - oi->coef) > 1.e-6) {
                    MSG_DEBUG("Coefs differ " << (*ni) << " vs " << (*oi));
                    break;
                }
            }
            if (ni != nj) {
                MSG_DEBUG("Elements remained in result of new_product");
            }
            if (oi != oj) {
                MSG_DEBUG("Elements remained in result of old_product");
            }
            MSG_DEBUG("OLD " << o);
            MSG_DEBUG("NEW " << n);
            if (ni == nj && oi == oj) {
                MSG_DEBUG(std::endl << "GOOD.");
                return true;
            }
            return false;
286
287
288
#else
            return true;
#endif
289
290
291
292
293
294
295
296
297
298
299
300
        }

    void
        measure_speed(const std::vector<int>& output, size_t n_repeats)
        {
            std::pair<double, double> timers;
            genotype_comb_type result;
            timers = new_product(output, result, n_repeats);
            MSG_DEBUG("New product took " << timers.first << " microseconds to initialize, and performed " << n_repeats << " operations at an average speed of " << timers.second << " microseconds per operation");
            timers = old_product(output, result, n_repeats);
            MSG_DEBUG("Old product took " << timers.first << " microseconds to initialize, and performed " << n_repeats << " operations at an average speed of " << timers.second << " microseconds per operation");
        }
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

    void
        test_correctness(uint64_t seed, size_t& good, size_t& failed, double& old_time, double& new_time)
        {
            std::pair<double, double> times = {0, 0};
            gen.seed(seed);
            std::stringstream initss;
            MSG_QUEUE_FLUSH();
            msg_handler_t::redirect(initss);
            init();
            MSG_QUEUE_FLUSH();
            msg_handler_t::restore();
            size_t nout_max = std::min(max_output, all_used_vars.size());
            size_t nout_min = std::min(min_output, all_used_vars.size());
            for (size_t nout = nout_min; nout < nout_max; ++nout) {
                std::stringstream os;
                MSG_QUEUE_FLUSH();
                msg_handler_t::redirect(os);
                auto out = output_vars(nout);
                if (!test_equality(out, old_time, new_time)) {
                    std::stringstream filename;
                    filename << "FAILED_TEST_" << prob_skip_state << '_' << min_variables << '-' << max_variables << '_' << min_alleles << '-' << max_alleles << '_' << n_tables << '_' << nout << '_' << seed << ".log";
                    std::ofstream log(filename.str());
                    MSG_QUEUE_FLUSH();
                    log << initss.str() << std::endl << os.str();
                    ++failed;
                } else {
                    ++good;
                }
                MSG_QUEUE_FLUSH();
                msg_handler_t::restore();
                CREATE_MESSAGE(msg_channel::Out, MESSAGE(good << " good, " << failed << " bad, old took " << old_time << "s, new took " << new_time << "s, speedup is " << (old_time / new_time) << "x                                \r"));
            }
        }

    void
        test_table_permutations(uint64_t seed, size_t& good, size_t& failed, double& old_time, double& new_time)
        {
            std::pair<double, double> times = {0, 0};
            gen.seed(seed);
            std::stringstream initss;
            MSG_QUEUE_FLUSH();
            msg_handler_t::redirect(initss);
            init();
            MSG_QUEUE_FLUSH();
            msg_handler_t::restore();
            size_t nout_max = std::min(max_output, all_used_vars.size());
            size_t nout_min = std::min(min_output, all_used_vars.size());
            for (size_t nout = nout_min; nout < nout_max; ++nout) {
                std::stringstream os;
                MSG_QUEUE_FLUSH();
                msg_handler_t::redirect(os);
                auto out = output_vars(nout);
                if (!test_equality(out, old_time, new_time)) {
                    std::stringstream filename;
                    filename << "FAILED_TEST_" << prob_skip_state << '_' << min_variables << '-' << max_variables << '_' << min_alleles << '-' << max_alleles << '_' << n_tables << '_' << nout << '_' << seed << ".log";
                    std::ofstream log(filename.str());
                    MSG_QUEUE_FLUSH();
                    log << initss.str() << std::endl << os.str();
                    ++failed;
                } else {
                    ++good;
                }
                MSG_QUEUE_FLUSH();
                msg_handler_t::restore();
                CREATE_MESSAGE(msg_channel::Out, MESSAGE(good << " good, " << failed << " bad, old took " << old_time << "s, new took " << new_time << "s                                \r"));
            }
        }
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
struct test_descr {
    double prob_skip_state;
    size_t n_variables;
    size_t n_tables;
    std::pair<size_t, size_t>
        seeds,
        alleles,
        variables,
        output;
    std::pair<double, double>
        coef;

    friend
        std::ostream&
        operator << (std::ostream& os, const test_descr& t)
        {
            return os << "prob_skip_state=" << t.prob_skip_state
                      << " n_variables=" << t.n_variables
                      << " n_tables=" << t.n_tables
                      << " seeds={" << t.seeds.first << ' ' << t.seeds.second
                      << "} alleles={" << t.alleles.first << ' ' << t.alleles.second
                      << "} variables={" << t.variables.first << ' ' << t.variables.second
                      << "} output={" << t.output.first << ' ' << t.output.second
                      << "} coef={" << t.coef.first << ' ' << t.coef.second
                      << '}';
        }
};

std::vector<test_descr> all_tests = {
    /*{0, 8, 16, {0, 1000}, {2, 2}, {2, 2}, {1, 8}, {1., 1.}},*/
    /*{0, 3, 2, {0, 10000}, {2, 4}, {2, 2}, {1, 3}, {1., 1.}},*/
403
404
405
406
407
408
409
410

    /*{0, 3, 2, {0, 1000}, {2, 2}, {2, 2}, {1, 3}, {1., 1.}},*/
    /*{.5, 3, 2, {0, 1000}, {2, 2}, {2, 2}, {1, 3}, {1., 1.}},*/
    /*{0, 5, 3, {0, 1000}, {2, 4}, {2, 3}, {1, 4}, {1., 1.}},*/
    /*{.25, 5, 3, {0, 1000}, {2, 4}, {2, 3}, {1, 4}, {1., 1.}},*/
    /*{.5, 6, 3, {0, 1000}, {2, 10}, {2, 3}, {1, 4}, {1., 1.}},*/

    {.95, 4, 3, {0, 1000}, {64, 64}, {3, 3}, {1, 4}, {1., 1.}},
411
412
};

413

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442

std::vector<pedigree_item>
filter_pedigree(const std::vector<pedigree_item>& full_pedigree, const std::vector<std::string>& inputs, const std::vector<std::string>& outputs)
{
    std::vector<pedigree_item> ret;
    std::map<int, pedigree_item> items;
    std::map<int, bool> protect;
    for (const auto& p: full_pedigree) {
        protect[p.id] = std::find(inputs.begin(), inputs.end(), p.gen_name) != inputs.end()
                     || std::find(outputs.begin(), outputs.end(), p.gen_name) != outputs.end();
    }
    auto pi = full_pedigree.rbegin(), pj = full_pedigree.rend();
    for (; pi != pj; ++pi) {
        if (protect[pi->id]) {
            if (pi->p1) { protect[pi->p1] = true; }
            if (pi->p2) { protect[pi->p2] = true; }
        }
    }
    ret.reserve(full_pedigree.size());
    for (const auto& p: full_pedigree) {
        if (protect[p.id]) {
            ret.emplace_back(p);
        }
    }
    return ret;
}



443
444
445
446
447
448
449
inline bool ends_with(std::string const & value, std::string const & ending)
{
    if (ending.size() > value.size()) return false;
    return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}


450

451
452
453
int
main(int argc, char** argv)
{
454
455
    msg_handler_t::set_color(true);

456
#if 0
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    std::map<std::vector<int>, genotype_comb_type> domains;
    std::map<int, genotype_comb_type> factors;
    auto anc
        = [&] (char a, char n)
        {
            int var = domains.size();
            auto& dom = domains[{var}];
            for (char i = 0; i < n; ++i) {
                dom.m_combination.emplace_back(
                    genotype_comb_type::key_list{{var, {a, a, i, i}}},
                    1.
                );
            }
            return var;
        };

    auto cross
        = [&] (int p1, int p2)
        {
            int var = domains.size();
            std::vector<genotype_comb_type> parent_tables;
            std::vector<int> parents;
            bool dh = false;
            if (p1 != p2) {
                dh = !p2;
                if (!dh) {
                    parent_tables = {domains[{p1}], domains[{p2}]};
                    parents = {p1, p2};
                } else {
                    parent_tables = {domains[{p1}]};
                    parents = {p1};
                }
            } else {
                parent_tables = {domains[{p1}]};
                parents = {p1};
            }
            MSG_DEBUG("PROUT 1");
            MSG_QUEUE_FLUSH();
            auto jp = compute_product(parent_tables.begin(), parent_tables.end(), parents, domains);
            MSG_DEBUG("PROUT 2");
            MSG_QUEUE_FLUSH();
            factors[var] = generate_factor(parents, dh, var, jp, domains);
            MSG_DEBUG("PROUT 3");
            MSG_QUEUE_FLUSH();
            extract_domain(factors[var], {var}, domains);
            MSG_DEBUG("PROUT 4");
            MSG_QUEUE_FLUSH();
            return var;
        };

    auto sparsity
        = [&] (int f)
        {
            size_t fs = factors[f].size();
            double ds = 1;
            for (const auto& k: factors[f].m_combination.front().keys) {
                ds *= domains[{k.parent}].size();
            }
            std::stringstream ss;
            ss << '#' << fs << " sparsity=" << (fs / ds);
            return ss.str();
        };

    domains[{-1}] = {};
521

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    int A = anc('a', 2);
    int B = anc('b', 2);
    int F1 = cross(A, B);
    int F2 = cross(F1, F1);
    int F3 = cross(F2, F2);
    int F4 = cross(F3, F3);
    int F5 = cross(F4, F4);
    int F6 = cross(F5, F5);
    int F3_2 = cross(F2, F2);
    int F3dh = cross(F3, 0);
    MSG_DEBUG("A " << domains[{A}]);
    MSG_DEBUG("B " << domains[{B}]);
    MSG_DEBUG("F1 " << sparsity(F1) << ' ' << factors[F1]);
    MSG_DEBUG("F2 " << sparsity(F2) << ' ' << factors[F2]);
    MSG_DEBUG("F3 " << sparsity(F3) << ' ' << factors[F3]);
    MSG_DEBUG("F3dh " << sparsity(F3dh) << ' ' << factors[F3dh]);

    std::vector<genotype_comb_type> tmp = {factors[F3], factors[F3dh]};

    factors[23] = compute_product(tmp.begin(), tmp.end(), {F2, F3, F3dh}, domains);
    tmp = {factors[F3], factors[F3_2]};
    factors[42] = compute_product(tmp.begin(), tmp.end(), {F2, F3, F3_2}, domains);
    MSG_DEBUG("F3 * F3dh " << sparsity(23) << ' ' << factors[23]);
    MSG_DEBUG("F3 * F3_2 " << sparsity(42) << ' ' << factors[42]);

    tmp = {factors[F4], factors[F5]};
    factors[100] = compute_product(tmp.begin(), tmp.end(), {F3, F5}, domains);
    tmp.push_back(factors[F6]);
    factors[101] = compute_product(tmp.begin(), tmp.end(), {F3, F6}, domains);
    MSG_DEBUG("F4 size " << factors[F4].size());
    MSG_DEBUG("F5 size " << factors[F5].size());
    MSG_DEBUG("F4 * F5 (squeeze F4) size " << factors[100].size());
    MSG_DEBUG("F4 * F5 * F6 (squeeze F4&F5) size " << factors[101].size());
#endif
556
    std::unique_ptr<factor_graph_type> g;
557
558

    if (argc == 1) {
559
        g = factor_graph_type::from_pedigree(read_csv("random.ped", ';'), 2, {}, {}/*, "boiboite"*/);
560
        g->to_image("boiboite", "png");
561
562
563
564
565
566
        /*g.dump_active();*/

        /*g = graph_type::from_pedigree(read_csv("random12.ped", ';'), 2, {}, {}, "boiboite12");*/
        /*g.to_image("boiboite12", "png");*/
        /*g.dump_active();*/

567
        g = factor_graph_type::from_pedigree(read_csv("/home/daleroux/devel/spel/sample-data/data_magic/pedigree_clean_DH.csv", ';'), 1, {"Cervil", "Levovil", "Criollo", "Stupicke", "Plovdiv", "LA1420", "Ferum", "LA0147", "ICS3"}, {"ICS3"});
568
        g->to_image("magic-dh", "png");
569
570
571
572
573
574

        /*g = graph_type::from_pedigree(read_csv("/home/daleroux/devel/spel/sample-data/data_magic/pedigree_clean-norepeat.csv", ';'), 1, {}, {});*/
        /*g.to_image("magic-dh", "png");*/
        /*g.dump_active();*/
    } else {
        std::string pedfile = argv[1];
575
576
577
578
        if (ends_with(pedfile, ".ped")) {
            std::string prefix = argv[2];
            std::vector<std::string> in, out;
            size_t pos;
579
            size_t n_al;
580
581
582
583
584
585
586
            {
                std::string s(argv[3]);
                while ((pos = s.find(",")) != std::string::npos) {
                    in.push_back(s.substr(0, pos));
                    s.erase(0, pos + 1);
                }
                in.push_back(s);
587
            }
588
589
590
591
592
593
594
595
            {
                std::string s(argv[4]);
                while ((pos = s.find(",")) != std::string::npos) {
                    out.push_back(s.substr(0, pos));
                    s.erase(0, pos + 1);
                }
                out.push_back(s);
            }
596
597
598
            {
                std::stringstream(argv[2]) >> n_al;
            }
599
600
601
602
603
604
605
606
            MSG_DEBUG("[args] Pedigree: " << pedfile);
            MSG_DEBUG("[args] Prefix: " << prefix);
            MSG_DEBUG("[args] In: " << in);
            MSG_DEBUG("[args] Out: " << out);
            /*g = graph_type::from_pedigree(read_csv(pedfile, ';'), 2, in, out);*/
            /*g.to_image(MESSAGE(prefix << "-pre-optim"), "png");*/
            /*g.optimize();*/
            /*g.to_image(prefix, "png");*/
607
            g = factor_graph_type::from_pedigree(filter_pedigree(read_csv(pedfile, ';'), in, out), n_al, in, out/*, MESSAGE("debug-" << prefix)*/);
608
609
610
            /*g->build_subgraphs();*/
            g->dump();
            /*g->to_image(MESSAGE(prefix << "-filtered-pre-optim"), "png");*/
611
            /*g->dump_active();*/
612
613
            /*g->optimize();*/
            /*MSG_DEBUG("Creating png...");*/
614
            g->to_image(MESSAGE(prefix << "-filtered"), "png");
615
616
617
618
619
620
            MSG_DEBUG("Creating instance...");
            auto I = instance(g);
            ofile of(MESSAGE(prefix << "-instance.data"));
            I->file_io(of);
            rw_comb<int, bn_label_type>()(of, g->domains);
#if 1
621
        } else {
622
            std::unique_ptr<instance_type> I(new instance_type());
623
624
625
626
627
628
629
630
631
632
633
634
635
            std::map<var_vec, genotype_comb_type> domains;
            ifile ifs(pedfile);
            I->file_io(ifs);
            rw_comb<int, bn_label_type>()(ifs, domains);
            MSG_DEBUG("Computing messages....");
            auto ret = I->compute(0, domains);
            MSG_DEBUG("MESSAGES");
            for (const auto& kv: I->message_index) {
                MSG_DEBUG(std::setw(4) << kv.first.first << " -> " << std::setw(4) << kv.first.second << "  ==  " << I->messages[kv.second]);
            }
            MSG_DEBUG("OUTPUT");
            for (const auto& t: ret) {
                MSG_DEBUG("" << t);
636
            }
637
#endif
638
639
        }
    }
640
641
642
643

    return 0;

#if 0
644
    msg_handler_t::set_color(true);
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
    random_test T;
    size_t good = 0, failed = 0;
    double old_time = 0, new_time = 0;
    for (const auto& t: all_tests) {
        MSG_DEBUG("Running test " << t);
        T.prob_skip_state = t.prob_skip_state;
        T.n_variables = t.n_variables;
        T.n_tables = t.n_tables;
        T.set_allele_range(t.alleles.first, t.alleles.second);
        T.set_n_var_range(t.variables.first, t.variables.second);
        T.set_coef_range(t.coef.first, t.coef.second);
        T.set_output_range(t.output.first, t.output.second);
        genotype_comb_type g;
        old_time = new_time = 0;
        for (uint64_t seed = t.seeds.first; seed < t.seeds.second; ++seed) {
            T.test_correctness(seed, good, failed, old_time, new_time);
            /*T.new_product(T.output_vars(1), g, 10);*/
        }
        MSG_DEBUG("");
    }
    /*T.prob_skip_state = .4;*/
    /*for (uint64_t seed = 0; seed < 1000; ++seed) {*/
        /*T.test_correctness(seed, good, failed);*/
    /*}*/
    MSG_DEBUG("");
    MSG_DEBUG("performed " << (good + failed) << " tests, " << good << " good, " << failed << " failed.");
    return failed == 0;
672
#endif
673
#if 0
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
    joint_variable_product_type jvp;
    bn_label_type
        s0 = {'a', 'a', 0, 0},
        s1 = {'a', 'a', 1, 1};
    genotype_comb_type::key_type
        a0 = {1, s0},
        a1 = {1, s1},
        b0 = {2, s0},
        b1 = {2, s1},
        c0 = {3, s0},
        c1 = {3, s1};
        /*d0 = {4, s0},*/
        /*d1 = {4, s1};*/
    genotype_comb_type A, B, C, D, T1, T2, T3, V1, V2, V3;
    A.m_combination = {
        {{a0, b0}, .25},
        {{a0, b1}, .25},
        /*{{a1, b0}, .25},*/
        {{a1, b1}, .25}
    };
    B.m_combination = {
        /*{{b0, c0}, .5},*/
        {{b0, c1}, .5},
        {{b1, c0}, .5},
    };
    C.m_combination = {
        {{a0, c0}, .25},
        /*{{a0, c1}, .25},*/
        {{a1, c0}, .25},
        {{a1, c1}, .25}
    };
    T1.m_combination = {
        {{a0}, .5},
        {{a1}, .5},
    };
    T2.m_combination = {
        {{b0}, .5},
        {{b1}, .5},
    };
    T3.m_combination = {
        {{c0}, .5},
        {{c1}, .5},
    };
    V1.m_combination = {{{a0}, 1}, {{a1}, 1}};
    V2.m_combination = {{{b0}, 1}, {{b1}, 1}};
    V3.m_combination = {{{c0}, 1}, {{c1}, 1}};
    jvp.add_table(A);
    /*jvp.add_table(B);*/
    /*jvp.add_table(C);*/
    /*jvp.add_table(T1);*/
    /*jvp.add_table(T2);*/
    jvp.add_table(T3);
    std::map<std::vector<int>, genotype_comb_type>
        domains = {
            {{1}, V1},
            {{2}, V2},
            {{3}, V3}
        };
    jvp.set_output({1, 2, 3});
    jvp.compile(domains);

    auto result = jvp.compute();

    {
        auto i = jvp.tables.begin();
        auto j = jvp.tables.end();
        MSG_DEBUG((*i->data));
        for (++i; i != j; ++i) {
            MSG_DEBUG(" *" << std::endl << (*i->data));
        }
    }
    MSG_DEBUG(" =" << std::endl << result);

    /*jvp.domains = {{5, 4, 3, 0x78}, {3, 2, 2, 0x6}, {2, 1, 1, 0x1}};*/
    /*jvp.domain_sizes = {5, 3, 2};*/
    /*jvp.domain_max = {4, 2, 1};*/
    /*jvp.domain_bit_widths = {3, 2, 1};*/
    /*jvp.domain_masks = {0x78, 0x6, 0x1};*/

    /*std::vector<bool> A = {1, 1, 0};*/
    /*std::vector<bool> B = {0, 1, 1};*/
    /*std::vector<bool> C = {1, 0, 1};*/

    /*std::vector<size_t> coords;*/
    /*coords.resize(3);*/
    /*uint64_t index = 0;*/

    /*jvp.compute_coordinates(index, coords);*/
    /*MSG_DEBUG(std::bitset<7>(index) << ' ' << coords[0] << ' ' << coords[1] << ' ' << coords[2]);*/
#if 0

    /*int counter = 0;*/
    state_index_type cursor = jvp.init_product(), last = cursor;
    for (;;)
    {
        /*if (++counter > 10) {*/
            /*break;*/
        /*}*/
        jvp.compute_coordinates(cursor, coords);
        MSG_DEBUG(std::bitset<7>(cursor) << ' ' << coords[0] << ' ' << coords[1] << ' ' << coords[2]);

        last = cursor;
        if (jvp.increment_index(cursor)) {
            break;
        }
        cursor = jvp.find_valid_state(cursor);
        if (cursor <= last) {
            break;
        }
    }

    /*std::vector<int> test = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};*/
    /*for (int i: reversed(test)) {*/
        /*std::cout << i << ' ';*/
    /*}*/
    /*std::cout << std::endl;*/
#endif

    random_test T;

    if (argc > 1) {
        std::stringstream ss(argv[1]);
        uint64_t seed;
        ss >> seed;
        T.gen.seed(seed);
    }

    T.prob_skip_state = .4;
    T.init();
    auto output = T.output_vars(3);
    T.test_equality(output);
    /*T.measure_speed(output, 1000);*/
806
#endif
807
808
809
810
    return 0;
    (void) argc; (void) argv;
}