graphnode_base.h 32.3 KB
Newer Older
1
2
3
4
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
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
#ifndef _SPEL_BAYES_GRAPH_NODE_BASE_H_
#define _SPEL_BAYES_GRAPH_NODE_BASE_H_

#include <memory>
#include <vector>
#include <algorithm>
#include <iostream>
#include <deque>
#include <list>
#include <map>
#include <cstdio>

/*#include "factor.h"*/

#include "../error.h"

#include "generalized_product.h"

#define ENABLE_DEBUG
#ifndef ENABLE_DEBUG
#undef MSG_DEBUG
#undef MSG_QUEUE_FLUSH
#undef MSG_DEBUG_DEDENT
#undef MSG_DEBUG_INDENT
#undef MSG_DEBUG_INDENT_EXPR

#define MSG_DEBUG(_x_)
#define MSG_QUEUE_FLUSH()
#define MSG_DEBUG_DEDENT
#define MSG_DEBUG_INDENT
#define MSG_DEBUG_INDENT_EXPR(_x_)
#endif

template <typename V>
std::ostream&
operator << (std::ostream& os, const std::vector<std::vector<V>>& vv)
{
    auto i = vv.begin(), j = vv.end();
    if (i != j) {
        os << '{' << (*i) << '}';
        for (++i; i != j; ++i) {
            os << " {" << (*i) << '}';
        }
    }
    return os;
}

typedef int variable_index_type;
typedef size_t node_index_type;
typedef std::vector<node_index_type> node_vec;
typedef std::vector<variable_index_type> var_vec;
struct graph_type;
struct edge_type {
    const graph_type* graph;
    node_index_type first, second;

    edge_type() : graph(NULL), first(0), second(0) {}
    edge_type(const graph_type* g, node_index_type f, node_index_type s) : graph(g), first(f), second(s) {}

    bool
        operator < (const edge_type& other) const
        {
            return graph < other.graph
                || (graph == other.graph
                        && (first < other.first
                            || (first == other.first && second < other.second)));
        }

    void
        file_io(ifile& fs, const graph_type* g)
        {
            graph = g;
            rw_base rw;
            rw(fs, first);
            rw(fs, second);
        }

    void
        file_io(ofile& fs, const graph_type*)
        {
            rw_base rw;
            rw(fs, first);
            rw(fs, second);
        }

    friend
        std::ostream&
        operator << (std::ostream& os, const edge_type& e);
};



struct colour_proxy_impl;
typedef std::shared_ptr<colour_proxy_impl> colour_proxy;
struct colour_proxy_impl {
    colour_proxy proxy;
    std::weak_ptr<colour_proxy_impl> cache;

    friend
        colour_proxy
        get_colour_impl(colour_proxy col)
        {
            while (col->cache.lock()->proxy) { col->cache = col->cache.lock()->proxy; }
            return col->cache.lock();
        }

    friend
        colour_proxy
        assign_colour_impl(colour_proxy old_col, colour_proxy new_col)
        {
            auto oc = get_colour_impl(old_col);
            auto nc = get_colour_impl(new_col);
            if (oc != nc) {
                oc->proxy = nc;
            }
            return old_col;
        }

    friend
        bool
        colour_equal(colour_proxy c1, colour_proxy c2)
        {
            return get_colour_impl(c1) == get_colour_impl(c2);
        }
};

inline
colour_proxy
create_colour() { auto ret = std::make_shared<colour_proxy_impl>(); ret->cache = ret; return ret; }


template <typename V>
void
sort_and_unique(std::vector<V>& v)
{
    std::sort(v.begin(), v.end());
    v.erase(std::unique(v.begin(), v.end()), v.end());
}


template <typename V>
std::ostream&
operator << (std::ostream& os, const std::list<V>& v)
{
    auto i = v.begin(), j = v.end();
    if (i != j) {
        os << (*i);
        for (++i; i != j; ++i) {
            os << " -- " << (*i);
        }
    }
    return os;
}


template <typename K, typename V>
std::ostream&
operator << (std::ostream& os, const std::map<K, V>& m)
{
    os << "{ ";
    for (const auto& kv: m) {
        os << kv.first << ": " << kv.second << ", ";
    }
    return os << '}';
}




typedef std::vector<genotype_comb_type> message_type;


inline
std::ostream&
operator << (std::ostream& os, const message_type& msg)
{
    auto i = msg.begin(), j = msg.end();
    if (i != j) {
        os << (*i);
        for (++i; i != j; ++i) {
            os << " | " << (*i);
        }
    }
    return os;
}


struct multiple_product_type {
    std::unordered_map<variable_index_type, colour_proxy> colours;
    std::vector<std::vector<var_vec>> vec_varsets;
    std::unordered_map<colour_proxy, std::vector<const genotype_comb_type*>> bins;
    std::unordered_map<colour_proxy, var_vec> varset_bins;
    std::vector<const message_type*> messages;

    void
        add(const message_type& msg)
        {
            size_t S = msg.size();
            vec_varsets.emplace_back();
            auto& varsets = vec_varsets.back();

            for (size_t i = 0; i < S; ++i) {
                varsets.emplace_back(get_parents(msg[i]));
                auto& varset = varsets.back();
                for (variable_index_type v: varset) {
                    auto& ptr = colours[v];
                    if (!ptr) {
                        ptr = create_colour();
                    }
                }
            }

            for (size_t i = 0; i < S; ++i) {
                if (varsets[i].size() == 0) { continue; }
                auto mcol = colours[varsets[i].front()];
                for (variable_index_type v: varsets[i]) {
                    auto& vcol = colours[v];
                    if (vcol && !colour_equal(vcol, mcol)) {
                        assign_colour_impl(vcol, mcol);
                    }
                }
            }
            messages.push_back(&msg);
        }

    void add(std::shared_ptr<message_type> ptr) { add(*ptr); }

    message_type
        compute(const var_vec& output, const std::map<var_vec, genotype_comb_type>& domains)
        {
            auto msg = messages.begin();
            for (const auto& varsets: vec_varsets) {
                for (size_t i = 0; i < varsets.size(); ++i) {
                    if (varsets[i].size() == 0) { continue; }
                    bins[get_colour_impl(colours[varsets[i].front()])].push_back(&(**msg)[i]);
                }
                for (const auto& kv: colours) {
                    varset_bins[get_colour_impl(kv.second)].push_back(kv.first);
                }
                ++msg;
            }

            for (auto& kv: varset_bins) {
                sort_and_unique(kv.second);
                /*MSG_DEBUG("varset " << kv.second << " assembles " << bins[kv.first].size() << " tables ");*/
                /*for (auto p: bins[kv.first]) { MSG_DEBUG(" * " << (*p)); }*/
            }

            message_type tmp;
            tmp.reserve(bins.size());
            for (const auto& kv: bins) {
                if ((output % varset_bins[kv.first]).size()) {
                    if (kv.second.size()) {
254
//                        MSG_QUEUE_FLUSH();
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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
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
405
406
407
408
409
410
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
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
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
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
556
557
558
559
                        /*if (kv.second.size() > 1) {*/
                            tmp.emplace_back(compute_product(kv.second.begin(), kv.second.end(), output, domains));
                        /*} else {*/
                            /*tmp.emplace_back(*kv.second.front() % output);*/
                        /*}*/
                    }
                }
            }
            /*MSG_DEBUG("result: " << tmp);*/
            return tmp;
        }
};


inline
message_type
product(const message_type& accum, const message_type& msg, const std::map<var_vec, genotype_comb_type>& domains)
{
    /*scoped_indent _(MESSAGE("[product] "));*/
    /*MSG_DEBUG("" << accum);*/
    /*MSG_DEBUG("" << msg);*/
    multiple_product_type mp;
    mp.add(accum);
    mp.add(msg);
    var_vec all;
    for (const auto& t: accum) { auto p = get_parents(t); all.insert(all.end(), p.begin(), p.end()); }
    for (const auto& t: msg) { auto p = get_parents(t); all.insert(all.end(), p.begin(), p.end()); }
    sort_and_unique(all);
    return mp.compute(all, domains);
}

inline
message_type&
accumulate(message_type& accum, const message_type& msg, const std::map<var_vec, genotype_comb_type>& domains)
{
    /*auto tmp = accum * msg;*/
    auto tmp = product(accum, msg, domains);
    accum.swap(tmp);
    return accum;
}

inline
std::shared_ptr<message_type>
accumulate(std::shared_ptr<message_type>& accum, const std::shared_ptr<message_type>& msg, const std::map<var_vec, genotype_comb_type>& domains)
{
    if (accum && accum->size()) {
        if (msg && msg->size()) {
            /**accum *= *msg;*/
            accumulate(*accum, *msg, domains);
        }
    } else {
        accum = msg;
    }
    return accum;
}

inline
std::shared_ptr<message_type>
product(std::shared_ptr<message_type> m1, std::shared_ptr<message_type> m2, const std::map<var_vec, genotype_comb_type>& domains)
{
    if (!m1) {
        return m2 ? std::make_shared<message_type>(*m2) : std::make_shared<message_type>();
    } else if (!m2) {
        return std::make_shared<message_type>(*m1);
    } else {
        /*return std::make_shared<message_type>(*m1 * *m2);*/
        return std::make_shared<message_type>(product(*m1, *m2, domains));
    }
}


inline
message_type
operator % (const message_type& msg, const var_vec& variables)
{
    message_type tmp;
    tmp.reserve(msg.size());
    for (const auto& table: msg) {
        auto varset = get_parents(table);
        if (varset == variables) {
            tmp.push_back(table);
        } else {
            auto proj = varset % variables;
            if (proj.size()) {
                /*var_vec norm = varset - proj;*/
                var_vec norm;
                tmp.push_back(project(table, proj, norm));
            }
        }
    }
    return tmp;
}


inline
std::shared_ptr<message_type>
operator % (std::shared_ptr<message_type> msg, const var_vec& variables)
{
    if (msg) {
        return std::make_shared<message_type>(*msg % variables);
    } else {
        return msg;
    }
}


inline
message_type&
operator %= (message_type& msg, const var_vec& variables)
{
    auto tmp = msg % variables;
    msg.swap(tmp);
    return msg;
}


inline
std::shared_ptr<message_type>
operator %= (std::shared_ptr<message_type> msg, const var_vec& variables)
{
    auto tmp = (*msg) % variables;
    msg->swap(tmp);
    return msg;
}


template <typename V, typename A1, typename A2>
std::vector<V, A1>&
operator += (std::vector<V, A1>& a, const std::vector<V, A2>& b)
{
    auto tmp = a + b;
    a.swap(tmp);
    return a;
}

template <typename V, typename A1, typename A2>
std::vector<V, A1>&
operator -= (std::vector<V, A1>& a, const std::vector<V, A2>& b)
{
    auto tmp = a - b;
    a.swap(tmp);
    return a;
}


inline
genotype_comb_type&
accumulate(genotype_comb_type& table, const message_type& msg, const std::map<var_vec, genotype_comb_type>& domains)
{
    joint_variable_product_type jvp;
    jvp.add_table(table);
    for (const auto& mt: msg) {
        jvp.add_table(mt);
    }
    jvp.set_output(jvp.all_variable_names);
    jvp.compile(domains);
    table = jvp.compute();
    /*if (table.size()) {*/
        /*for (const auto& mt: msg) {*/
            /*table = kronecker(table, mt);*/
        /*}*/
    /*} else {*/
        /*auto i = msg.begin(), j = msg.end();*/
        /*if (i != j) {*/
            /*table = *i++;*/
        /*}*/
        /*for (; i != j; ++i) {*/
            /*table = kronecker(table, *i);*/
        /*}*/
    /*}*/
    return table;
}




inline
std::ostream&
operator << (std::ostream& os, std::shared_ptr<message_type> msg)
{
    if (msg) {
        return os << (*msg);
    } else {
        return os << "unif";
    }
}




inline
void
normalize(genotype_comb_type& table)
{
    double accum = 0;
    for (const auto& e: table) {
        accum += e.coef;
    }
    if (accum != 0) {
        accum = 1. / accum;
        for (auto& e: table) {
            e.coef *= accum;
        }
    }
}


inline void normalize(message_type& msg) { for (auto& table: msg) { normalize(table); } }
inline void normalize(std::shared_ptr<message_type> msg) { normalize(*msg); }


enum node_type { Deleted=1, InAggregate=2, Factor=4, Interface=8, Aggregate=16 };
inline constexpr node_type operator | (node_type t1, node_type t2) { return (node_type) (((int) t1) | ((int) t2)); }
inline node_type& operator |= (node_type& t1, node_type t2) { t1 = (node_type) (((int) t1) | ((int) t2)); return t1; }
inline node_type operator & (node_type t1, node_type t2) { return (node_type) (((int) t1) & ((int) t2)); }
inline constexpr node_type operator ~ (node_type t) { return (node_type) ~((int) t); }

inline
std::string
to_string(node_type t)
{
    const std::vector<std::pair<node_type, std::string>> names = {
        {Deleted, "Deleted"},
        {InAggregate, "InAggregate"},
        {Factor, "Factor"},
        {Interface, "Interface"},
        {Aggregate, "Aggregate"}
    };
    bool sep = false;
    std::stringstream ret;
    for (const auto& p: names) {
        if (t & p.first) {
            if (sep) { ret << NORMAL << '|'; }
            ret << GREEN << p.second;
            sep = true;
        }
    }
    ret << NORMAL;
    return ret.str();
}

enum VariableIO { None=0, Input=1, Output=2 };
inline constexpr VariableIO operator | (VariableIO v1, VariableIO v2) { return (VariableIO) (((int) v1) | ((int) v2)); }
inline VariableIO& operator |= (VariableIO& v1, VariableIO v2) { v1 = (VariableIO) (((int) v1) | ((int) v2)); return v1; }
inline bool operator & (VariableIO v1, VariableIO v2) { return !!(((int) v1) & ((int) v2)); }



struct node_struc {
    node_index_type index;
    node_type type;
    size_t rank;
    node_index_type represented_by;
    colour_proxy colour;
    var_vec rule;
    node_vec neighbours_in, neighbours_out, inner_nodes;
    var_vec all_variables;
    variable_index_type variable;

    friend
        std::ostream&
        operator << (std::ostream& os, const node_struc& node)
        {
#define F(_l, _p, _s, _x) WHITE << ' ' << _l << NORMAL << '=' << GREEN << _p << node._x << _s << NORMAL
#define N(_l, _x) F(_l, '[', ']', _x)
#define V(_l, _x) F(_l, "", "", _x)

            return os << "<node " << WHITE << "type" << NORMAL << "=" << GREEN << to_string(node.type) << NORMAL
                      << N("in", neighbours_in)
                      << N("out", neighbours_out)
                      << N("inner", inner_nodes)
                      << V("rule", rule)
                      << V("variable", variable)
                      << V("all_variables", all_variables)
                      << WHITE << "colour" << NORMAL << '=' << GREEN << get_colour_impl(node.colour) << NORMAL
                      << '>';
#undef F
#undef N
#undef V
        }
};


/* TODO Tests
 * node.type & InAggregate => all_nei(node) == {}
 * node.type & InAggregate => node.represesented_by != node
 * !(node.type & InAggregate) => node.represesented_by == node
 * !(node.type & InAggregate) => node.inner_nodes == {node}
 * recopricity of neighbours
 * neighbours have same colour
 * rank(nei_out) > rank(nei_in)
 * nei is not Deleted or InAggregate
 * ...
 */

struct graph_base_type {
    typedef std::list<node_index_type> path_type;

    typedef graph_base_type G;

    node_struc&
        operator [] (node_index_type n) { return m_nodes[n]; }

    virtual ~graph_base_type() {}

560
561
562
    graph_base_type()
        : m_nodes(), variable_to_node() { create_node(Deleted); }

563
564
565
566
    node_index_type
        create_node(node_type t, variable_index_type v=-1)
        {
            node_index_type ret = m_nodes.size();
567
            /*MSG_DEBUG("creating node " << ret);*/
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
            m_nodes.emplace_back();
            m_nodes.back().colour = create_colour();
            m_nodes.back().type = t;
            m_nodes.back().rank = 0;
            m_nodes.back().variable = v;
            m_nodes.back().represented_by = ret;
            m_nodes.back().inner_nodes = {ret};
            if (v != -1 && variable_to_node.find(v) == variable_to_node.end()) {
                variable_to_node[v] = ret;
                /*node_to_variable.insert({ret, v});*/
            }
            return ret;
        }

    void
583
        add_variables_to_node(node_index_type n, const var_vec& new_var)
584
585
586
587
        {
            m_nodes[n].all_variables += new_var;
        }

588
589
590
591
592
593
    void
        set_variables_for_node(node_index_type n, const var_vec& new_var)
        {
            m_nodes[n].all_variables = new_var;
        }

594
595
596
    node_index_type
        add_interface(variable_index_type v)
        {
597
            /*scoped_indent _(MESSAGE("[+I " << v << "] "));*/
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
            node_index_type ret = create_node(Interface, v);
            m_nodes[ret].all_variables.push_back(v);
            /*MSG_DEBUG("new node " << m_nodes[ret]);*/
            return ret;
        }

    node_index_type
        add_interface(const var_vec& vv)
        {
            node_vec nn;
            for (variable_index_type v: vv) {
                nn.push_back(add_interface(v));
            }
            return aggregate(nn);
        }

    node_index_type
        add_factor(const var_vec& rule, variable_index_type v)
        {
617
            /*scoped_indent _(MESSAGE("[+F " << rule << ' ' << v << "] "));*/
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
            node_index_type ret = create_node(Factor, v);
            auto sorted_rule = rule;
            std::sort(sorted_rule.begin(), sorted_rule.end());
            m_nodes[ret].all_variables = rule;
            std::sort(m_nodes[ret].all_variables.begin(), m_nodes[ret].all_variables.end());
            m_nodes[ret].all_variables += var_vec{v};
            m_nodes[ret].rule = rule;
#if 0
            path_type dont_care;
            node_index_type i = add_interface(v);
            add_edge(ret, i, dont_care);
            variable_to_node[v] = i;
#endif
            /*MSG_DEBUG("new node " << m_nodes[ret]);*/
            return ret;
        }

    void
        move_node_to_aggregate(node_index_type inner, node_index_type aggr)
        {
638
            /*MSG_DEBUG("move node to aggregate " << aggr << ": " << inner);*/
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
            if (!(m_nodes[inner].type & Aggregate)) {
                m_nodes[aggr].type |= m_nodes[inner].type & ~InAggregate;
                m_nodes[aggr].inner_nodes.push_back(inner);
                m_nodes[aggr].all_variables += variables_of(inner);
                m_nodes[inner].type |= InAggregate;
                m_nodes[inner].represented_by = aggr;
            }
            path_type dont_care;
            foreach_in(nei_in(inner), [&,this] (node_index_type i) {
                add_edge(i, aggr, dont_care);
                remove_edge(i, inner);
            });
            foreach_in(nei_out(inner), [&,this] (node_index_type o) {
                add_edge(aggr, o, dont_care);
                remove_edge(inner, o);
            });
            if (m_nodes[inner].type & Aggregate) {
                foreach_in(inner_nodes(inner), [&,this] (node_index_type i) {
                    move_node_to_aggregate(i, aggr);
                });
                delete_node(inner);
            }
        }

    node_index_type
        aggregate(const node_vec& nodes)
        {
666
            /*scoped_indent _(MESSAGE("[+A " << nodes << "] "));*/
667
668
            node_index_type ret = create_node(Aggregate);
            m_nodes[ret].inner_nodes.clear();
669
            /*MSG_DEBUG("Creating aggregate " << ret);*/
670
            foreach_in(nodes, [&,this] (node_index_type n) { move_node_to_aggregate(n, ret); });
671
            /*MSG_DEBUG("updating ranks...");*/
672
//            MSG_QUEUE_FLUSH();
673
674
675
            update_ranks(ret);
            std::sort(m_nodes[ret].inner_nodes.begin(), m_nodes[ret].inner_nodes.end());
            remove_edge(ret, ret);
676
            /*MSG_DEBUG("new node " << m_nodes[ret]);*/
677
678
679
680
681
682
683
684
685
            for (variable_index_type v: variables_of(ret)) {
                variable_to_node[v] = ret;
            }
            return ret;
        }

    void
        rec_update_rank(node_index_type n, const std::vector<bool>& modified, std::vector<bool>& updated)
        {
686
            /*MSG_DEBUG("rec_update_rank on " << n);*/
687
//            MSG_QUEUE_FLUSH();
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
            size_t r = 0;
            for (node_index_type i: nei_in(n)) {
                if (modified[i] && !updated[i]) {
                    rec_update_rank(i, modified, updated);
                }
                r = std::max(r, rank(i));
            }
            m_nodes[n].rank = r + 1;
            updated[n] = true;
        }

    void
        update_ranks(node_index_type root)
        {
            std::vector<bool> modified(size(), false);
            node_vec stack;
            stack.reserve(size());
            stack = {root};
            node_vec endpoints;
            while (stack.size()) {
                node_index_type n = stack.back();
                stack.pop_back();
                if (modified[n]) {
                    continue;
                }
                modified[n] = true;
                auto nout = nei_out(n);
                stack.insert(stack.end(), nout.begin(), nout.end());
                if (nei_out(n).size() == 0) {
                    endpoints.push_back(n);
                }
            }

            node_vec order;
            std::vector<bool> updated(size(), false);
            updated[root] = true;

            for (node_index_type e: endpoints) {
                rec_update_rank(e, modified, updated);
            }
        }

    bool
        add_edge(node_index_type from, node_index_type to, path_type& path)
        {
733
            /*scoped_indent _(MESSAGE("[add edge " << from << "->" << to << "] "));*/
734
735
736
737
738
739
740
741
742
743
744
745
            bool have_cycle = colour_equal(m_nodes[from].colour, m_nodes[to].colour);
            if (have_cycle) {
                path = find_path(from, to);
            } else {
                path.clear();
                assign_colour_impl(m_nodes[to].colour, m_nodes[from].colour);
            }
            m_nodes[from].neighbours_out += node_vec{to};
            m_nodes[to].neighbours_in += node_vec{from};
            if (rank(to) <= rank(from)) {
                m_nodes[to].rank = rank(from) + 1;
            }
746
            /*MSG_DEBUG("cycle? " << have_cycle);*/
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
            return have_cycle;
        }

    void
        remove_edge(node_index_type from, node_index_type to)
        {
            m_nodes[from].neighbours_out -= node_vec{to};
            m_nodes[to].neighbours_in -= node_vec{from};
            if (all_nei(from).size() == 0) {
                m_nodes[from].colour = create_colour();
            }
            if (all_nei(to).size() == 0) {
                m_nodes[to].colour = create_colour();
            }
        }

    void
        delete_node(node_index_type d)
        {
            m_nodes[d].type |= Deleted;
            foreach_in(nei_in(d), [&, this] (node_index_type n) { remove_edge(n, d); });
            foreach_in(nei_out(d), [&, this] (node_index_type n) { remove_edge(d, n); });
        }

    node_vec
        nodes() const
        {
            node_vec ret;
            ret.reserve(m_nodes.size());
            for (node_index_type n = 0; n < m_nodes.size(); ++n) {
                if (!(m_nodes[n].type & (Deleted | InAggregate))) {
                    ret.push_back(n);
                }
            }
            return ret;
        }

    node_index_type
        insert_interface_between(node_index_type from, node_index_type to)
        {
            var_vec vv = variables_of(from) % variables_of(to);
            path_type dont_care;
            node_index_type ret = (node_index_type) -1;
            foreach_in_if(nei_out(from),
                    [&,this] (node_index_type n) {
                        return (ret == (node_index_type) -1) && node_is_interface(n) && (variables_of(n) % vv) == vv;
                    },
                    [&,this] (node_index_type n) {
                        ret = n;
                    });
            if (ret == (node_index_type) -1) {
                if (vv.size() == 1) {
                    ret = add_interface(vv.front());
                } else {
                    node_vec nn;
                    nn.reserve(vv.size());
                    for (variable_index_type v: vv) {
                        nn.push_back(add_interface(v));
                    }
                    ret = aggregate(nn);
                }
                add_edge(from, ret, dont_care);
            }
            add_edge(ret, to, dont_care);
            remove_edge(from, to);
            return ret;
        }

    size_t size() const { return m_nodes.size(); }
    node_vec nei_in(node_index_type n) const { return m_nodes[n].neighbours_in; }
    node_vec nei_out(node_index_type n) const { return m_nodes[n].neighbours_out; }
    node_vec all_nei(node_index_type n) const { return nei_in(n) + nei_out(n); }
    node_vec nei_in(const node_vec& nn) const { node_vec ret; for (node_index_type n: nn) { ret += nei_in(n); } return ret; }
    node_vec nei_out(const node_vec& nn) const { node_vec ret; for (node_index_type n: nn) { ret += nei_out(n); } return ret; }
    node_vec all_nei(const node_vec& nn) const { return nei_in(nn) + nei_out(nn); }
    node_vec inner_nodes(node_index_type n) const { return m_nodes[n].inner_nodes; }
    const var_vec& rule(node_index_type n) const { return m_nodes[n].rule; }
    variable_index_type own_variable_of(node_index_type n) const { return m_nodes[n].variable; }
    const var_vec& variables_of(node_index_type n) const { return m_nodes[n].all_variables; }
    colour_proxy colour_of(node_index_type n) const { return get_colour_impl(m_nodes[n].colour); }
    const var_vec& rule_of(node_index_type n) const { return m_nodes[n].rule; }
    var_vec variables_of(node_vec nn) const { var_vec ret; for (node_index_type n: nn) { ret += variables_of(n); } return ret; }
    size_t rank(node_index_type n) const { return m_nodes[n].rank; }

831
832
833
834
835
836
    bool
        node_is_deleted(node_index_type n) const
        {
            return m_nodes[n].type & Deleted;
        }

837
838
839
    bool
        node_is_subgraph(node_index_type n) const
        {
840
            return !node_is_deleted(n) && (m_nodes[n].type & Aggregate) && (m_nodes[n].type & Factor);
841
842
843
844
845
        }

    bool
        node_is_interface(node_index_type n) const
        {
846
            return !node_is_deleted(n) && (m_nodes[n].type & Interface) && !(m_nodes[n].type & Factor);
847
848
849
850
851
        }

    bool
        node_is_factor(node_index_type n) const
        {
852
            return !node_is_deleted(n) && (m_nodes[n].type & Factor) && !(m_nodes[n].type & Aggregate);
853
854
855
856
857
858
859
860
861
862
863
864
865
866
        }

    node_index_type
        node_by_var(variable_index_type v)
        {
            auto it = variable_to_node.find(v);
            if (it == variable_to_node.end()) {
                return add_interface(v);
                /*return (node_index_type) -1;*/
            }
            return it->second;
        }

    path_type
867
        find_path(node_index_type a, node_index_type b) const
868
869
870
871
        {
            return find_shortest_path(node_vec{a, b});
        }

872
    virtual
873
874
875
876
877
878
879
880
881
882
883
884
885
886
    void
        dump_node(node_index_type n)
        {
            MSG_DEBUG(std::setw(5) << std::left << n << ' ' << m_nodes[n]);
        }

    void
        dump()
        {
            foreach_in(nodes(), [this] (node_index_type n) { dump_node(n); });
        }

    template <typename Predicate_type>
    node_index_type
887
        find_in(const node_vec& list, Predicate_type&& pred) const
888
889
890
891
892
        {
            for (node_index_type n: list) if (pred(n)) { return n; }
            return (node_index_type) -1;
        }

893
894
895
896
897
898
899
900
901
    template <typename Predicate_type>
    node_vec
        filter(const node_vec& list, Predicate_type&& pred) const
        {
            node_vec ret;
            for (node_index_type n: list) if (pred(n)) { ret.push_back(n); }
            return ret;
        }

902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
    template <typename Action_type>
    void
        foreach_in(const node_vec& list, Action_type&& action)
        {
            for (node_index_type n: list) { action(n); }
        }

    template <typename Action_type, typename Predicate_type>
    void
        foreach_in_if(const node_vec& list, Predicate_type&& pred, Action_type&& action)
        {
            for (node_index_type n: list) if (pred(n)) {
                action(n);
            }
        }

918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
    template <typename Action_type>
    void
        foreach_in(const node_vec& list, Action_type&& action) const
        {
            for (node_index_type n: list) { action(n); }
        }

    template <typename Action_type, typename Predicate_type>
    void
        foreach_in_if(const node_vec& list, Predicate_type&& pred, Action_type&& action) const
        {
            for (node_index_type n: list) if (pred(n)) {
                action(n);
            }
        }

934
    std::list<node_index_type>
935
        find_shortest_path(const node_vec& between) const
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        {
#define all_bits ((node_index_type) -1)
#define uninitialized (all_bits ^ (all_bits >> 1))
#define starting_point (uninitialized >> 1)
#define node_is_parent(_n) (from[_n] & starting_point)
#define node_is_initialized(_n) (!(from[_n] & uninitialized))
            /*scoped_indent _(MESSAGE("[breadth-first " << between << "] "));*/
            /*MSG_DEBUG("uninitialized " << uninitialized << " starting_point " << starting_point);*/
            node_vec from(m_nodes.size(), uninitialized);
            std::vector<bool> visited(m_nodes.size(), false);
            std::deque<node_index_type> stack;
            for (node_index_type n: between) {
                /*stack.insert(stack.end(), direction[n].begin(), direction[n].end());*/
                stack.push_back(n);
                from[n] = starting_point;
            }
            if (0) {
                std::stringstream ss;
                ss << "from";
                size_t i = 0;
                for (node_index_type f: from) {
                    ss << ' ' << i << ':';
                    if (node_is_parent(f)) {
                        ss << 'P';
                    } else if (node_is_initialized(i)) {
                        ss << f;
                    } else {
                        ss << '-';
                    }
                }
                MSG_DEBUG(ss.str());
            }
            while (stack.size()) {
                node_index_type this_node = stack.front();
                stack.pop_front();
                if (visited[this_node]) {
                    continue;
                }
                visited[this_node] = true;
                auto neighbours = all_nei(this_node);
                for (node_index_type n: neighbours) {
                    if (visited[n]) {
                        continue;
                    }
                    /*MSG_DEBUG("neighbour " << n);*/
                    if (node_is_parent(n)) {
                        std::list<node_index_type> ret;
                        ret.push_back(n);
                        node_index_type p = this_node;
                        while (!node_is_parent(p)) {
                            ret.push_back(p);
                            /*MSG_DEBUG("building path (1) " << ret);*/
                            p = from[p];
                        }
                        /*MSG_DEBUG("end branch");*/
                        ret.push_back(p);
                        /*MSG_DEBUG("complete path " << ret);*/
                        return ret;
                    } else if (node_is_initialized(n)) {
                        std::list<node_index_type> ret;
                        /* compute path and return */
                        node_index_type p = n;
                        while (!node_is_parent(p)) {
                            ret.push_back(p);
                            /*MSG_DEBUG("building path (1) " << ret);*/
For faster browsing, not all history is shown. View entire blame