graphnode2.h 66.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _SPEL_BAYES_GRAPH_NODE_H_
#define _SPEL_BAYES_GRAPH_NODE_H_

#include "graphnode_base.h"

#include "../pedigree.h"

struct graph_type : public graph_base_type {
    graph_type() : graph_base_type() {}

    void
        add_variable(const var_vec& rule, variable_index_type new_variable)
        {
14
            /*scoped_indent _(MESSAGE("[add_variable " << rule << ' ' << new_variable << "] "));*/
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
            if (rule.size() > 0) {
                node_vec parents;
                if (rule.size() == 2) {
                    parents = variables_to_nodes(rule);
                } else {
                    parents = {node_by_var(rule.front())};
                }
                node_index_type newfac = add_factor(rule, new_variable);
                path_type path;
                foreach_in(parents, [&, this] (node_index_type p) {
                        if (add_edge(p, newfac, path)) {
                            aggregate_path(path);
                        }
                        });
            } else {
                add_interface(new_variable);
                char letter = m_ancestor_letters.size() + 'a';
                m_ancestor_letters[new_variable] = letter;
            }
            /*MSG_DEBUG("===================================");*/
            /*dump();*/
            /*MSG_DEBUG("===================================");*/
        }

    char
        ancestor_letter(variable_index_type v) const
        {
            return m_ancestor_letters.find(v)->second;
        }

    void
        postprocess()
        override
        {
            graph_base_type::postprocess();
            /**/
        }

53
54
55
56
57
58
59
60
61
    template <typename Action>
        void
        foreach_ancestor(Action&& action)
        {
            for (const auto& kv: m_ancestor_letters) {
                action(kv.first, kv.second);
            }
        }

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
private:
    std::map<variable_index_type, char> m_ancestor_letters;

    struct parents_of_max_rank {
        std::list<node_index_type>::iterator p1, child, p2;
    };

    parents_of_max_rank
        find_parents_of_max_rank(std::list<node_index_type>& path)
        {
            auto child = std::max_element(path.begin(), path.end(), [this](node_index_type n1, node_index_type n2) { return rank(n1) < rank(n2); });
            auto p1 = child, p2 = child;
            if (child == path.begin()) {
                p1 = path.end();
            }
            --p1;
            ++p2;
            if (p2 == path.end()) {
                p2 = path.begin();
            }
            return {p1, child, p2};
        }

    void
        aggregate_path(std::list<node_index_type>& path)
        {
            parents_of_max_rank aggr_first;
            while (path.size() > 2 && ((aggr_first = find_parents_of_max_rank(path)), !aggregate_part(*aggr_first.p1, *aggr_first.p2, path, aggr_first.p1))) {
                path.erase(aggr_first.p1);
                path.erase(aggr_first.p2);
                path.erase(aggr_first.child);
            }
        }

    bool
        aggregate_part(node_index_type p1, node_index_type p2, path_type& path, path_type::iterator pos)
        {
            node_vec aggr = find_aggregate_chain(p1, p2);
            sort_and_unique(aggr);
            node_index_type ret = aggregate(aggr);
            path.insert(pos, ret);
            return aggr.size() > 2;
        }

    node_vec
        variables_to_nodes(const var_vec& rule)
        {
            auto sorted_rule = rule;
            std::sort(sorted_rule.begin(), sorted_rule.end());
            auto find_rule = [&,this](node_index_type n) { return variables_of(n) % sorted_rule == sorted_rule; };
            node_index_type common = find_in(nodes(), find_rule);
            if (common == (node_index_type) -1) {
114
                /*MSG_DEBUG("common not found.");*/
115
116
117
118
119
120
121
122
                node_vec ret;
                for (variable_index_type v: rule) {
                    node_index_type n = node_by_var(v);
                    if (n != (node_index_type) -1) {
                        ret.push_back(n);
                    }
                }
                sort_and_unique(ret);
123
                /*MSG_DEBUG("returning parents " << ret);*/
124
125
                return ret;
            } else {
126
                /*MSG_DEBUG("Initial common " << common);*/
127
128
129
                node_index_type parent = -1;
                while ((parent = find_in(nei_in(common), find_rule)) != (node_index_type) -1) {
                    common = parent;
130
                    /*MSG_DEBUG("New common " << common);*/
131
132
133
134
135
136
137
                }
                node_vec parents;
                foreach_in_if(nei_in(common),
                    [&,this] (node_index_type n) { return sorted_rule.size() && !!(variables_of(n) % sorted_rule).size(); },
                    [&,this] (node_index_type n) {
                        sorted_rule -= variables_of(n);
                        parents.push_back(n);
138
                        /*MSG_DEBUG("Found parent " << n << " now sorted_rule is " << sorted_rule);*/
139
                    });
140
                /*MSG_DEBUG("remaining sorted_rule " << sorted_rule);*/
141
                if (!sorted_rule.size()) {
142
                    /*MSG_DEBUG("=> parents " << parents);*/
143
144
                    return parents;
                } else {
145
                    /*MSG_DEBUG("=> common " << common);*/
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
                    return {common};
                }
            }
        }

    bool
        find_ascending_path(node_index_type p1, node_index_type p2, node_vec& path, std::vector<bool>& visited)
        {
            /*MSG_DEBUG("path from " << p1 << " to " << p2);*/
            if (p1 == p2) {
                return true;
            }
            for (node_index_type i: nei_in(p1)) {
                if (visited[i]) {
                    return false;
                }
                visited[i] = true;
                if (find_ascending_path(i, p2, path, visited)) {
                    path.push_back(i);
                    return true;
                }
            }
            return false;
        }

    node_vec
        find_aggregate_chain(node_index_type p1, node_index_type p2)
        {
            node_vec path;
            std::vector<bool> vis1(size(), false), vis2(size(), false);

            if (rank(p1) > rank(p2) && find_ascending_path(p1, p2, path, vis1)) {
                /*MSG_DEBUG("found ascending path from " << p1 << " to " << p2);*/
                path.push_back(p1);
            } else if (rank(p2) > rank(p1) && find_ascending_path(p2, p1, path, vis2)) {
                /*MSG_DEBUG("found ascending path from " << p2 << " to " << p1);*/
                path.push_back(p2);
            } else {
                /*MSG_DEBUG("no ascending path between parents");*/
                path = {p1, p2};
            }
            return path;
        }

};


template <typename Derived>
struct recursive_graph_type : public graph_type {
195
    recursive_graph_type() : graph_type(), m_subgraphs(), m_parent(nullptr), m_index_in_parent(-1) {}
196
197
198
199
200
201
202
203

    void
        dump()
        {
            foreach_in(nodes(), [this] (node_index_type n) {
                dump_node(n);
                if (node_is_subgraph(n)) {
                    MSG_DEBUG_INDENT_EXPR("      ");
204
                    subgraph(n)->dump();
205
206
207
208
209
210
211
212
                    MSG_DEBUG_DEDENT;
                }
            });
        }

    void
        build_subgraphs()
        {
213
214
            m_subgraphs.clear();
            m_subgraphs.resize(size());
215
216
217
            foreach_in_if(nodes(),
                    [this] (node_index_type n) { return node_is_subgraph(n); },
                    [this] (node_index_type n) {
218
219
                        m_subgraphs[n] = make_subgraph(n);
                        m_subgraphs[n]->build_subgraphs();
220
221
222
223
224
225
226
227
228
229
                    });
        }

    void
        postprocess()
        override
        {
            graph_type::postprocess();
            add_missing_interfaces();
            join_trees();
230
231
232
            foreach_in_if(nodes(),
                    [this] (node_index_type n) { return node_is_subgraph(n); },
                    [this] (node_index_type n) { m_subgraphs[n]->postprocess(); });
233
234
        }

235
236
237
238
239
240
241
242
243
    node_index_type
        index_in_parent() const { return m_index_in_parent; }

    const Derived*
        parent() const { return m_parent; }

    std::shared_ptr<Derived>
        subgraph(node_index_type n) const { return m_subgraphs[n]; }

244
245
246
247
248
249
250
251
252
253
254
255
protected:
    node_index_type
        create_interface(const var_vec& vv)
        {
            if (vv.size() == 1) {
                return add_interface(vv.front());
            } else {
                return add_interface(vv);
            }
        }

private:
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    void
        set_parent(const Derived* p, node_index_type i)
        {
            m_parent = p;
            m_index_in_parent = i;
        }

    std::shared_ptr<Derived>
        make_subgraph(node_index_type n)
        {
            /*scoped_indent _(MESSAGE("[subgraph " << n << "] "));*/
            /*MSG_DEBUG("Creating subgraph...");*/
            std::shared_ptr<Derived> ret = dynamic_cast<Derived*>(this)->create_subgraph(n);
            foreach_in_if(inner_nodes(n),
                    [&,this] (node_index_type i) { return node_is_factor(i); },
                    [&,this] (node_index_type i) {
                        dynamic_cast<Derived*>(this)->add_node_to_subgraph(ret, i);
                    });
            ret->set_parent(dynamic_cast<const Derived*>(this), n);
            return ret;
        }

278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    void
        add_interface_from(node_index_type from, const var_vec& vv)
        {
            path_type dont_care;
            add_edge(from, create_interface(vv), dont_care);
        }

    void
        add_interface_to(const var_vec& vv, node_index_type to)
        {
            path_type dont_care;
            add_edge(create_interface(vv), to, dont_care);
        }

    void
        create_interfaces_between_factors()
        {
            auto not_interface = [this] (node_index_type n) { return !node_is_interface(n); };
            /* create interfaces between factors/subgraphs */
            foreach_in_if(nodes(), not_interface,
                [&,this] (node_index_type from) {
                    auto nout = nei_out(from);
                    foreach_in_if(nout, not_interface,
                        [&,this] (node_index_type to) {
                            insert_interface_between(from, to);
                        });
                });
        }

    void
        export_ancestral_interfaces()
        {
            /* export ancestral interfaces from subgraphs if missing */
            foreach_in_if(nodes(),
                [this] (node_index_type n) { return node_is_subgraph(n); },
                [this] (node_index_type to) {
                    auto in_var = variables_of(nei_in(to));
315
316
                    subgraph(to)->foreach_in_if(subgraph(to)->nodes(),
                        [&,this] (node_index_type in) { return subgraph(to)->nei_in(in).size() == 0; },
317
                        [&,this] (node_index_type in) {
318
                            auto vv = subgraph(to)->variables_of(in) - in_var;
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
                            if (vv.size() > 0) {
                                for (variable_index_type v: vv) {
                                    add_interface_to({v}, to);
                                }
                            }
                        });
                });
        }

    void
        create_output_interfaces()
        {
            /* create output interfaces from factors */
            foreach_in_if(nodes(),
                [this] (node_index_type n) { return node_is_factor(n); },
                [this] (node_index_type from) {
                    var_vec out = var_vec{own_variable_of(from)} - variables_of(nei_out(from));
                    if (out.size()) {
                        add_interface_from(from, out);
                    }
                });
        }

    void
        add_missing_interfaces()
        {
            create_interfaces_between_factors();
            export_ancestral_interfaces();
            create_output_interfaces();
        }

    void
        join_trees()
        {
            std::map<colour_proxy, node_vec> tree_roots;
            foreach_in_if(nodes(),
                    [this] (node_index_type n) { return node_is_interface(n) && nei_out(n).size() == 0; },
                    [&,this] (node_index_type n) { tree_roots[colour_of(n)].push_back(n); });
357
            /*MSG_DEBUG("tree roots " << tree_roots);*/
358
359
360
361
362
363
364
            if (tree_roots.size() > 1) {
                node_vec nn;
                /*for (const auto& kv: tree_roots) { nn.insert(nn.end(), kv.second.begin(), kv.second.end()); }*/
                for (const auto& kv: tree_roots) { nn.push_back(kv.second.front()); }
                aggregate(nn);
            }
        }
365
366
367
368

    std::vector<std::shared_ptr<Derived>> m_subgraphs;
    const Derived* m_parent;
    node_index_type m_index_in_parent;
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

inline
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;
}





405
406
407
struct factor_graph_type : public recursive_graph_type<factor_graph_type> {
    std::map<variable_index_type, VariableIO> io;
    std::map<var_vec, genotype_comb_type> domains;
408
409
    /*const factor_graph_type* parent;*/
    /*node_index_type index_in_parent;*/
410
411
412
413
414
415
416
417
418
419
420
    size_t n_alleles;
    std::map<node_index_type, pedigree_item> pedigree_items;
    std::map<variable_index_type, bool> is_dh;
    std::vector<message_type> node_domains;
    std::map<node_index_type, node_index_type> anchor_points;
    std::vector<bool> node_domain_computed;

    graph_type& operator = (graph_type&& other) = delete;
    factor_graph_type(const graph_type& other) = delete;

    factor_graph_type(size_t n_al=1)
421
        : io(), domains(), /*parent(nullptr), index_in_parent(0),*/ n_alleles(n_al), is_dh(), node_domains(), anchor_points(), node_domain_computed()
422
423
424
425
426
427
428
429
430
431
    {}

    std::shared_ptr<factor_graph_type>
        create_subgraph(node_index_type n)
        {
            auto ret = std::make_shared<factor_graph_type>(n_alleles);
            ret->io = io;
            for (variable_index_type v: variables_of(nei_out(n))) {
                ret->io[v] |= Output;
            }
432
433
434
435
436
437
438
439
440
441
442
443
            foreach_in(nei_in(n),
                    [&,this] (node_index_type i) {
                        var_vec V = variables_of(i) % variables_of(n);
                        for (variable_index_type v: V) {
                            ret->io[v] |= Input;
                        }
                        ret->create_interface(V);
                    });
            /*for (variable_index_type v: variables_of(nei_in(n)) % variables_of(n)) {*/
                /*ret->io[v] |= Input;*/
                /*ret->add_interface(v);*/
            /*}*/
444
445
446
447
448
449
            return ret;
        }

    void
        add_node_to_subgraph(std::shared_ptr<factor_graph_type> sub, node_index_type n)
        {
450
            /*scoped_indent _(MESSAGE("[add_node_to_subgraph " << n << "] "));*/
451
452
453
454
455
456
457
            variable_index_type v = own_variable_of(n);
            sub->add_variable(rule(n), v);
            sub->is_dh[v] = is_dh[v];
        }

    static
        std::unique_ptr<factor_graph_type>
458
        from_pedigree(const std::vector<pedigree_item>& ped, size_t n_al, const std::vector<std::string>& input_gen, const std::vector<std::string>& output_gen/*, const std::string& debug_prefix = ""*/)
459
460
461
        {
            std::unique_ptr<factor_graph_type> g(new factor_graph_type(n_al));
            /*system("rm -vf test_*.png");*/
462
            for (const auto& p: filter_pedigree(ped, input_gen, output_gen)) {
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
                /*MSG_DEBUG("-------------------------------------------------------------------------------");*/
                /*MSG_DEBUG("-------------------------------------------------------------------------------");*/
                /*MSG_DEBUG("-------------------------------------------------------------------------------");*/
                VariableIO io = None;
                if (std::find(input_gen.begin(), input_gen.end(), p.gen_name) != input_gen.end()) {
                    io |= Input;
                }
                if (std::find(output_gen.begin(), output_gen.end(), p.gen_name) != output_gen.end()) {
                    io |= Output;
                }
                g->io[p.id] = io;
                g->is_dh[p.id] = p.is_dh();
                if (p.is_ancestor()) {
                    g->add_variable(var_vec{}, p.id);
                } else if (p.is_cross()) {
                    g->add_variable({p.p1, p.p2}, p.id);
                } else if (p.is_dh()) {
                    g->add_variable({p.p1}, p.id);
                } else if (p.is_self()) {
                    g->add_variable({p.p1}, p.id);
                }
                /*if (io) {*/
                    /*MSG_DEBUG("IO for var #" << p.id << ": " << io);*/
                /*}*/
            }
            /*g->finalize();*/
            /*g->compute_domains_and_factors();*/
            g->postprocess();
491
            g->finalize();
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
            return g;
        }

    VariableIO
        node_io(node_index_type n) const
        {
            VariableIO ret = None;
            if (node_is_factor(n)) {
                return io.find(own_variable_of(n))->second;
            }
            for (variable_index_type v: variables_of(n)) {
                ret |= io.find(v)->second;
            }
            return ret;
        }

    std::string
        to_image(const std::string& prefix, const std::string& format) const
        {
            auto A = nodes();
            std::string dotfilename = MESSAGE("/tmp/prout" << prefix); //std::tempnam(nullptr);
            std::vector<std::string> sub_filenames;
            {
                std::ofstream dotfile(dotfilename);
                dotfile << "digraph spell {rankdir=LR;" << std::endl;
517
                if (parent() != NULL) {
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
                    dotfile << "bgcolor=transparent;" << std::endl;
                }
                for (node_index_type n: A) {
                    std::string col;
                    auto io_val = node_io(n);
                    if (io_val == (Input | Output)) {
                        col = ", style=filled, fillcolor=mistyrose2";
                    } else if (io_val == Input) {
                        col = ", style=filled, fillcolor=lightsteelblue1";
                    } else if (io_val == Output) {
                        col = ", style=filled, fillcolor=darkseagreen1";
                    } else {
                        col = ", style=filled, fillcolor=white";
                    }
                    dotfile << n << "[";
                    if (node_is_interface(n)) {
                        dotfile << "shape=diamond, label=\"" << n  << " [" << inner_nodes(n) << "]   " << variables_of(n) << "\"";
                    } else if (node_is_subgraph(n)) {
536
                        std::string filename = subgraph(n)->to_image(MESSAGE("_sub_" << prefix << '_' << n), format);
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
                        dotfile << "shape=box,labeljust=\"l\", labelloc=\"t\", label=\"" << n << " [" << inner_nodes(n) << "]\",image=\"" << filename << "\"";
                        sub_filenames.push_back(filename);
                    } else {
                        dotfile << "shape=box,label=\"" << n << "   " << variables_of(n) << "\"";
                    }
                    dotfile << col << "];" << std::endl;
                }
                for (node_index_type h: A) {
                    for (node_index_type t: nei_out(h)) {
                        dotfile << h << " -> " << t << std::endl;
                    }
                }
                dotfile << '}' << std::endl;
            }
            std::string ret = MESSAGE(prefix << '.' << format);
            std::string cmd = MESSAGE("dot -T" << format << ' ' << dotfilename << " -o " << ret);
            if (system(cmd.c_str())) {
                MSG_ERROR("Dot failed " << strerror(errno), "");
            }
            for (const auto& s: sub_filenames) { unlink(s.c_str()); }
            return ret;
        }

560
561
562
563
564
565
566
567
568
    void
        dump_node(node_index_type n)
        override
        {
            graph_base_type::dump_node(n);
            if (node_domains.size()) {
                MSG_DEBUG("      Domain " << node_domains[n]);
            }
        }
569
570
571
572
573

    void
        postprocess()
        override
        {
574
575
            scoped_indent _("[postprocess] ");
            MSG_DEBUG("BUILD SUBGRAPHS");
576
            build_subgraphs();
577
            MSG_DEBUG("RECURSE THE POSTPROCESSING");
578
            recursive_graph_type<factor_graph_type>::postprocess();
579
            MSG_DEBUG("CREATE ANCESTOR DOMAINS");
580
            create_ancestor_domains();
581
582
583
584
585
586
587
588
589
            MSG_DEBUG("DONE.");
        }

    void
        finalize()
        {
            scoped_indent _(MESSAGE("[finalize] "));
            to_image("pre-optim", "png");
            MSG_DEBUG("DOMAINS");
590
            compute_domains_and_factors();
591
            MSG_DEBUG("OPTIMIZE");
592
            optimize();
593
594
595
            MSG_DEBUG("RUNNING INTERSECTIONS");
            running_intersections();
            MSG_DEBUG("DONE.");
596
597
        }

598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    void
        running_intersections()
        {
            if (parent()) {
                std::vector<var_vec> all_nei_vars;
                node_vec nei_nodes;
                nei_nodes = parent()->nei_in(index_in_parent()) + parent()->nei_out(index_in_parent());
                all_nei_vars.reserve(nei_nodes.size());
                /*MSG_DEBUG("NEI NODES " << nei_nodes);*/
                for (node_index_type n: nei_nodes) {
                    all_nei_vars.push_back(parent()->variables_of(n) % parent()->variables_of(index_in_parent()));
                }
                /*MSG_DEBUG("ALL NEI VARS " << all_nei_vars);*/
                /*reset_annotations();*/
                for (const auto& ia: anchor_incoming(all_nei_vars)) {
                    anchor_points[nei_nodes[ia.first]] = ia.second;
                }
            }
            foreach_in_if(nodes(),
                    [this] (node_index_type n) { return node_is_subgraph(n); },
                    [this] (node_index_type n) { subgraph(n)->running_intersections(); });
        }
620
621
622


    bool
623
        var_is_output(variable_index_type var) const
624
        {
625
626
            auto mode = io.find(var)->second;
            return mode & Output;
627
628
        }

629
630
    std::vector<bn_label_type>
        get_domain(variable_index_type var)
631
        {
632
633
634
635
636
            std::vector<bn_label_type> ret;
            const auto& dom = domains[{var}];
            ret.reserve(dom.size());
            for (const auto& e: dom) {
                ret.push_back(e.keys.keys.front().state);
637
            }
638
639
            return ret;
        }
640

641
642
643
644
645
646
647
    bool
        variables_are_independent(variable_index_type v1, variable_index_type v2, const std::list<node_index_type>& path) const
        {
            var_vec V = v1 < v2 ? var_vec{v1, v2} : var_vec{v2, v1};
            for (node_index_type n: path) {
                if (!(variables_of(n) % V).size()) {
                    return true;
648
649
                }
            }
650
            return false;
651
652
        }

653
654
    std::map<variable_index_type, node_index_type>
        get_output_interfaces(const var_vec& V) const
655
        {
656
657
658
659
660
661
662
663
664
665
666
            std::map<variable_index_type, node_index_type> ret;
            std::map<variable_index_type, node_vec> candidates;
            std::map<node_index_type, size_t> candidate_scores;
            foreach_in_if(nodes(),
                [this] (node_index_type n) { return !node_is_interface(n); },
                [&,this] (node_index_type n) {
                    auto vn = variables_of(n) % V;
                    if (vn.size()) {
                        candidate_scores[n] += vn.size();
                        for (auto v: vn) {
                            candidates[v].push_back(n);
667
668
                        }
                    }
669
                });
670

671
672
673
674
            for (auto& vn: candidates) {
                std::sort(vn.second.begin(), vn.second.end(), [&](node_index_type n1, node_index_type n2) { return candidate_scores[n1] > candidate_scores[n2]; });
                ret[vn.first] = vn.second.front();
            }
675

676
677
            return ret;
        }
678

679
680
681
682
    node_index_type
        find_anchor(const var_vec& V)
        {
            std::map<node_index_type, size_t> candidate_scores;
683
684
            foreach_in_if(nodes(),
                [this] (node_index_type n) { return node_is_interface(n); },
685
686
687
688
                [&,this] (node_index_type n) {
                    auto vn = variables_of(n) % V;
                    if (vn.size()) {
                        candidate_scores[n] = vn.size();
689
                    }
690
691
692
693
694
695
696
                });
            size_t max = 0;
            node_index_type best = (node_index_type) -1;
            for (const auto& kv: candidate_scores) {
                if (kv.second > max) {
                    max = kv.second;
                    best = kv.first;
697
698
                }
            }
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
            return best;
        }

    bool
        recursive_find_path_to_var(node_index_type node, variable_index_type v, path_type& path, std::vector<bool>& visited) const
        {
            auto V = variables_of(node);
            if (std::find(V.begin(), V.end(), v) != V.end()) {
                /*path.push_back(node);*/
                return true;
            }
            visited[node] = true;
            for (node_index_type n: nei_in(node)) {
                if (!visited[n] && recursive_find_path_to_var(n, v, path, visited)) {
                    path.push_back(n);
                    return true;
715
716
                }
            }
717
718
719
720
            for (node_index_type n: nei_out(node)) {
                if (!visited[n] && recursive_find_path_to_var(n, v, path, visited)) {
                    path.push_back(n);
                    return true;
721
722
                }
            }
723
724
725
726
727
728
729
730
731
732
733
            return false;
        }

    std::list<node_index_type>
        find_path_to_var(node_index_type start, variable_index_type v)
        {
            std::vector<bool> visited(size(), false);
            visited[start] = true;
            std::list<node_index_type> path;
            recursive_find_path_to_var(start, v, path, visited);
            return path;
734
735
736
        }

    void
737
        annotate(node_index_type anchor, const var_vec& V)
738
        {
739
740
741
            for (variable_index_type v: V) {
                for (node_index_type n: find_path_to_var(anchor, v)) {
                    /*annotations[n].push_back(v);*/
742
                    add_variables_to_node(n, {v});
743
744
                }
            }
745
            add_variables_to_node(anchor, V);
746
747
        }

748
749
750
751
752
753
754
755
756
757
758
759
760
761
    std::map<size_t, node_index_type>
        anchor_incoming(const std::vector<var_vec>& incoming)
        {
            std::map<size_t, node_index_type> ret;
            std::vector<size_t> indices(incoming.size());
            size_t index = 0;
            std::generate(indices.begin(), indices.end(), [&] () { return index++; });
            std::sort(indices.begin(), indices.end(), [&] (size_t i, size_t j) { return incoming[i].size() > incoming[j].size(); });
            for (size_t i: indices) {
                node_index_type anchor = find_anchor(incoming[i]);
                annotate(anchor, incoming[i]);
                ret[i] = anchor;
            }
            /*sort_annotations();*/
762
            /*MSG_DEBUG("ANCHORS " << ret);*/
763
764
765
766
            return ret;
        }


767
768
769
770
771
772
773
774
775
776
777
778
    std::list<node_index_type>
        find_vpath(variable_index_type v1, variable_index_type v2) const
        {
            node_vec nv1, nv2;
            std::list<node_index_type> ret;
            if (v1 > v2) {
                v1 ^= v2;
                v2 ^= v1;
                v1 ^= v2;
            }
            var_vec V = {v1, v2};
            /*MSG_DEBUG("v1 " << v1 << " v2 " << v2);*/
779
            foreach_in_if(nodes(),
780
                [this] (node_index_type n) { return node_is_factor(n); },
781
                [&,this] (node_index_type n) {
782
783
784
                    for (variable_index_type v: V % variables_of(n)) {
                        (v == v1 ? nv1 : nv2).push_back(n);
                    }
785
                });
786
787
788
789
790
791
792
793
            /*MSG_DEBUG("nv1 " << nv1 << " nv2 " << nv2);*/
            auto joint_itf = nv1 % nv2;
            if (joint_itf.size()) {
                return {*std::min_element(joint_itf.begin(), joint_itf.end(), [this](node_index_type n1, node_index_type n2) { return variables_of(n1).size() < variables_of(n2).size(); })};
            }
            size_t path_size = (size_t) -1;
            for (auto n1: nv1) {
                for (auto n2: nv2) {
794
                    if (!colour_equal(colour_of(n1), colour_of(n2))) {
795
796
                        return {};
                    }
797
                    auto path = find_path(n1, n2);
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
                    /*MSG_DEBUG("n1 " << n1 << " n2 " << n2 << " path " << path);*/
                    size_t psz = path.size();
                    if (psz && psz < path_size) {
                        path_size = psz;
                        path.swap(ret);
                    }
                }
            }
            return ret;
        }

    /*std::map<colour_proxy, std::vector<std::list<node_index_type>>>*/
    std::vector<std::vector<std::list<node_index_type>>>
        find_vpath(var_vec vv) const
        {
            /*std::map<colour_proxy, std::vector<std::list<node_index_type>>> ret;*/
            std::map<variable_index_type, std::vector<node_vec>> nv;
            std::map<colour_proxy, var_vec> by_colour;
            for (auto v: vv) {
817
                auto nn = filter(nodes(), [&] (node_index_type n) { auto vv = variables_of(n); return std::find(vv.begin(), vv.end(), v) != vv.end(); });
818
819
820
821
822
823
824
825
826
                /*MSG_DEBUG("variable " << v << " nodes " << nn);*/
                for (auto n: nn) {
                    /*MSG_DEBUG("  node colour " << colour_of(n));*/
                }
                if (nn.size()) {
                    auto col = colour_of(nn.front());
                    nv[v].push_back(nn);
                    by_colour[col].push_back(v);
                }
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
            }
            std::vector<var_vec> cliques;
            std::map<std::pair<variable_index_type, variable_index_type>, std::list<node_index_type>> paths;
            std::vector<std::vector<std::list<node_index_type>>> paths_by_clique;
            std::map<variable_index_type, size_t> var_clique;
            for (auto& kv: by_colour) {
                /*MSG_DEBUG("In component " << kv.second);*/
                if (kv.second.size() > 1) {
                    auto i = kv.second.begin(), j = kv.second.end();
                    for (; i != j; ++i) {
                        if (var_clique.find(*i) == var_clique.end()) {
                            var_clique[*i] = cliques.size();
                            cliques.emplace_back();
                            cliques.back().push_back(*i);
                            paths_by_clique.emplace_back();
                            /*MSG_DEBUG("Variable " << (*i) << " is in a new clique");*/
                        }
                        for (auto k = i + 1; k != j; ++k) {
                            /*MSG_DEBUG("Find path between " << (*i) << " and " << (*k));*/
                            auto path = find_vpath(*i, *k);
                            if (path.size()) {
                                paths[{*i, *k}] = path;
                                paths_by_clique[var_clique[*i]].emplace_back(path);
                                cliques[var_clique[*i]].push_back(*k);
                                var_clique[*k] = var_clique[*i];
                            }
                        }
                        if (paths_by_clique[var_clique[*i]].size() == 0) {
                            paths_by_clique[var_clique[*i]].emplace_back();
                            /*paths_by_clique[var_clique[*i]].back().emplace_back(*i);*/
                            paths_by_clique[var_clique[*i]].back().emplace_back(nv[*i].front().front());
                        }
                    }
                    /*MSG_DEBUG("var_clique " << var_clique);*/
                } else {
                    auto var = kv.second.front();
                    /*MSG_DEBUG("var is single " << var);*/
                    var_clique[var] = cliques.size();
                    cliques.emplace_back();
                    cliques.back().push_back(var);
                    paths_by_clique.emplace_back();
                    paths_by_clique.back().emplace_back();
                    /*paths_by_clique.back().emplace_back(var);*/
                    /*paths_by_clique.back().emplace_back(find_vpath(var, var));*/
                    paths_by_clique.back().back().emplace_back(nv[var].front().front());
                }
            }
            /*MSG_DEBUG("cliques " << cliques);*/
            /*MSG_DEBUG("paths " << paths);*/
            /*MSG_DEBUG("paths_by_clique " << paths_by_clique);*/

            return paths_by_clique;
        }



    message_type
        get_joint_domain(const var_vec& varset)
        {
886
887
888
            /*MSG_QUEUE_FLUSH();*/
            scoped_indent _(MESSAGE("[get_joint_domain " << varset << "] "));
            /*MSG_DEBUG("[get_joint_domain " << varset << "] ");*/
889
890
891
892
893
894
895
896
897
898
            auto path = find_vpath(varset);
            message_type ret;
            for (const auto& cliq: path) {
                ret.emplace_back();
                message_type accum;
                for (const auto& path: cliq) {
                    message_type tmp;
                    for (node_index_type n: path) {
                        accumulate(tmp, get_node_domain(n), domains);
                        tmp %= varset + variables_of(n);
899
                        MSG_DEBUG("tmp " << tmp);
900
901
902
903
904
905
906
907
908
909
910
911
                    }
                    accumulate(accum, tmp, domains);
                    accum %= varset;
                }
                accumulate(ret, accum, domains);
            }
            return ret;
        }

    message_type
        get_node_domain(node_index_type n)
        {
912
            if (node_is_subgraph(n)) {
913
                if (!node_domain_computed[n]) {
914
                    subgraph(n)->compute_domains_and_factors();
915
916
                    node_domain_computed[n] = true;
                }
917
                return subgraph(n)->get_joint_domain(variables_of(n));
918
919
920
921
922
923
924
925
926
927
928
            } else {
                if (!node_domain_computed[n]) {
                    compute_node_domain(n);
                }
                return node_domains[n];
            }
        }

    message_type
        get_node_domain(node_index_type n, const var_vec& vv)
        {
929
            /*MSG_DEBUG("get_node_domain(" << n << ", " << vv << ") " << variables_of(n));*/
930
            if (node_is_subgraph(n)) {
931
                if (!node_domain_computed[n]) {
932
                    subgraph(n)->compute_domains_and_factors();
933
934
                    node_domain_computed[n] = true;
                }
935
                return subgraph(n)->get_joint_domain(vv);
936
937
938
939
            } else {
                if (!node_domain_computed[n]) {
                    compute_node_domain(n);
                }
940
941
942
943
                var_vec vo = variables_of(n);
                if (vv % vo == vo) {
                    return node_domains[n];
                }
944
945
946
947
948
949
950
951
952
953
954
955
                return node_domains[n] % vv;
            }
        }

    void
        propagate_spawnling_domain_rec(const var_vec& V, const genotype_comb_type& dom, std::map<const graph_type*, bool>& visited)
        {
            /*if (visited[this]) {*/
                /*return;*/
            /*}*/
            visited[this] = true;
            domains[V] = dom;
956
957
958
            /*MSG_DEBUG("Domains " << (parent() ? MESSAGE(parent() << "->" << index_in_parent()) : std::string("top-level")) << ' ' << domains);*/
            if (parent() && !visited[parent()]) {
                const_cast<factor_graph_type*>(parent())->propagate_spawnling_domain(V, dom);
959
            }
960
961
962
963
964
            foreach_in_if(nodes(),
                    [&,this] (node_index_type n) { return node_is_subgraph(n) && !visited[subgraph(n).get()]; },
                    [&,this] (node_index_type n) {
                        subgraph(n)->propagate_spawnling_domain_rec(V, dom, visited);
                    });
965
966
967
968
969
970
971
972
973
        }

    void
        propagate_spawnling_domain(const var_vec& V, const genotype_comb_type& dom)
        {
            std::map<const graph_type*, bool> visited;
            propagate_spawnling_domain_rec(V, dom, visited);
        }

974
975
976
977
978
979
980
981
982
983
984
    void
        create_ancestor_domains()
        {
            foreach_ancestor([this] (variable_index_type id, char letter) {
                auto& domain = domains[{id}];
                for (char al = 0; al < (char) n_alleles; ++al) {
                    domain.m_combination.emplace_back(genotype_comb_type::element_type{{{id, {letter, letter, al, al}}}, 1.});
                }
            });
        }

985
986
987
988
989
990
    void
        compute_node_domain(node_index_type n)
        {
            scoped_indent _(MESSAGE("[compute_node_domain #" << n << "] "));
            auto inputs = nei_in(n);
            auto vv = variables_of(n);
991
            if (node_is_interface(n)) {
992
993
994
995
996
997
998
999
1000
                multiple_product_type mp;
                std::vector<message_type> stack;
                for (node_index_type i: inputs) {
                    stack.emplace_back(get_node_domain(i, vv));
                }
                for (const auto& m: stack) {
                    mp.add(m);
                }
                node_domains[n] = mp.compute(vv, domains);
For faster browsing, not all history is shown. View entire blame