graphnode.h 80.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
#ifndef _SPEL_BAYES_GRAPH_NODE_H_
#define _SPEL_BAYES_GRAPH_NODE_H_

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

13
14
15
/*#include "factor.h"*/
#include "../pedigree.h"

16
#include "../error.h"
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


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(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)));
        }

39
40
41
42
    friend
        std::ostream&
        operator << (std::ostream& os, const edge_type& e);
};
43

44
45
46
47
48
49


struct colour_proxy_impl;
typedef std::shared_ptr<colour_proxy_impl> colour_proxy;
struct colour_proxy_impl {
    colour_proxy proxy;
50
    colour_proxy cache;
51
52
53
54
55

    friend
        colour_proxy
        get_colour_impl(colour_proxy col)
        {
56
57
            while (col->cache->proxy) { col->cache = col->cache->proxy; }
            return col->cache;
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
        }

    friend
        colour_proxy
        assign_colour_impl(colour_proxy old_col, colour_proxy new_col)
        {
            get_colour_impl(old_col)->proxy = get_colour_impl(new_col);
            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
78
create_colour() { auto ret = std::make_shared<colour_proxy_impl>(); ret->cache = ret; return ret; }
79
80


81
template <typename V>
82
void
83
sort_and_unique(std::vector<V>& v)
84
85
86
87
88
89
{
    std::sort(v.begin(), v.end());
    v.erase(std::unique(v.begin(), v.end()), v.end());
}


90
enum node_type { Factor, Interface, Aggregate };
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

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
126
127
message_type
operator * (const message_type& accum, const message_type& msg)
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
{
    message_type tmp;

    std::map<variable_index_type, colour_proxy> colours;

    std::vector<var_vec> accum_varsets, msg_varsets;

    for (size_t ai = 0; ai < accum.size(); ++ai) {
        accum_varsets.push_back(get_parents(accum[ai]));
        for (variable_index_type v: accum_varsets.back()) {
            auto& ptr = colours[v];
            if (!ptr) {
                ptr = create_colour();
            }
        }
    }
    for (size_t mi = 0; mi < msg.size(); ++mi) {
        msg_varsets.push_back(get_parents(msg[mi]));
        for (variable_index_type v: msg_varsets.back()) {
            auto& ptr = colours[v];
            if (!ptr) {
                ptr = create_colour();
            }
        }
    }

    for (size_t i = 0; i < accum.size(); ++i) {
155
156
157
        if (accum_varsets[i].size() == 0) {
            continue;
        }
158
159
160
161
162
163
164
165
166
167
        auto mcol = colours[accum_varsets[i].front()];
        for (variable_index_type v: accum_varsets[i]) {
            auto& vcol = colours[v];
            if (vcol && !colour_equal(vcol, mcol)) {
                assign_colour_impl(vcol, mcol);
            }
        }
    }

    for (size_t i = 0; i < msg.size(); ++i) {
168
169
170
        if (msg_varsets[i].size() == 0) {
            continue;
        }
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        auto mcol = colours[msg_varsets[i].front()];
        for (variable_index_type v: msg_varsets[i]) {
            auto& vcol = colours[v];
            if (vcol && !colour_equal(vcol, mcol)) {
                assign_colour_impl(vcol, mcol);
            }
        }
    }

    std::vector<colour_proxy> uniq;
    for (const auto& kv: colours) {
        uniq.push_back(get_colour_impl(kv.second));
    }
    sort_and_unique(uniq);

    std::vector<size_t> accum_dest, msg_dest;
    for (size_t i = 0; i < accum.size(); ++i) {
188
189
190
191
        if (accum_varsets[i].size() == 0) {
            accum_dest.push_back(0);
            continue;
        }
192
193
194
        accum_dest.push_back(std::find(uniq.begin(), uniq.end(), get_colour_impl(colours[accum_varsets[i].front()])) - uniq.begin());
    }
    for (size_t i = 0; i < msg.size(); ++i) {
195
196
197
198
        if (msg_varsets[i].size() == 0) {
            msg_dest.push_back(0);
            continue;
        }
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        msg_dest.push_back(std::find(uniq.begin(), uniq.end(), get_colour_impl(colours[msg_varsets[i].front()])) - uniq.begin());
    }

    tmp.resize(uniq.size());

    for (size_t i = 0; i < accum.size(); ++i) {
        auto& table = tmp[accum_dest[i]];
        if (table.size()) {
            table = kronecker(table, accum[i]);
        } else {
            table = accum[i];
        }
    }
    for (size_t i = 0; i < msg.size(); ++i) {
        auto& table = tmp[msg_dest[i]];
        if (table.size()) {
            table = kronecker(table, msg[i]);
        } else {
            table = msg[i];
        }
    }

221
222
    return tmp;
}
223

224
225
226
227
228
229
inline
message_type&
operator *= (message_type& accum, const message_type& msg)
{
    auto tmp = accum * msg;
    accum.swap(tmp);
230
231
232
233
234
    return accum;
}

inline
std::shared_ptr<message_type>
235
operator *= (std::shared_ptr<message_type>& accum, const std::shared_ptr<message_type>& msg)
236
{
237
238
239
240
241
242
243
    if (accum) {
        if (msg) {
            *accum *= *msg;
        }
    } else {
        accum = msg;
    }
244
245
246
    return accum;
}

247
248
249
250
251
252
253
254
255
256
257
258
259
inline
std::shared_ptr<message_type>
operator * (std::shared_ptr<message_type> m1, std::shared_ptr<message_type> m2)
{
    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);
    }
}

260
261
262
263
264
265
266
267
268
269
270
271
272
273

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()) {
274
275
                /*var_vec norm = varset - proj;*/
                var_vec norm;
276
277
278
279
280
281
282
283
284
285
286
287
                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)
{
288
289
290
291
292
    if (msg) {
        return std::make_shared<message_type>(*msg % variables);
    } else {
        return msg;
    }
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
}


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


inline
genotype_comb_type&
operator *= (genotype_comb_type& table, const message_type& msg)
{
    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;
}




329
330
331
332
333
334
335
336
337
338
inline
std::ostream&
operator << (std::ostream& os, std::shared_ptr<message_type> msg)
{
    if (msg) {
        return os << (*msg);
    } else {
        return os << "unif";
    }
}
339
340
341
342




343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
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); }
362
363
364
365




366
struct graph_type {
367
368

    struct query_op_atom_type {
369
        const graph_type* g;
370
371
372
373
        var_vec variables;
        node_index_type node;
        size_t n_operands;

374
        query_op_atom_type(const graph_type* _g, const var_vec& vv, node_index_type n, size_t no)
375
376
377
378
379
380
381
            : g(_g), variables(vv), node(n), n_operands(no)
        {}

        friend
            std::ostream&
            operator << (std::ostream& os, const query_op_atom_type& qoa)
            {
382
                return os << "<op out=" << qoa.variables << " inner=" << (qoa.g->is_interface(qoa.node) ? 'I' : 'F') << qoa.g->variables_of(qoa.node) << " n_opd=" << qoa.n_operands << '>';
383
384
385
386
387
            }

        void
            operator () (std::vector<std::shared_ptr<message_type>>& stack, std::vector<const var_vec*>& var_stack) const
            {
388
389
390
391
392
393
394
395
396
397
398
                /*bool itf = g->is_interface(node);*/
                std::shared_ptr<message_type> ret;
                /*if (!itf) {*/
                    ret = std::make_shared<message_type>(g->state[node]);
                /*} else {*/
                /*}*/
                for (size_t i = 0; i < n_operands; ++i) {
                    auto op = stack.back();
                    stack.pop_back();
                    var_stack.pop_back();
                    ret *= op;
399
                }
400
401
402
403
                /*if (!itf) {*/
                    ret %= variables;
                /*}*/
                stack.emplace_back(ret);
404
405
406
407
408
409
410
                var_stack.push_back(&variables);
            }
    };


    typedef std::vector<query_op_atom_type> query_operation_type;

411
412
    enum ComputeStateOperation { PushState, PushMessage, Accumulate, Project, Store };
#define CSO_TYPE_STR(_c) (_c == PushState ? "PushState" : _c == PushMessage ? "PushMessage" : _c == Accumulate ? "Accumulate" : _c == Project ? "Project" : "Store")
413
    struct compute_state_operation_type {
414
        const graph_type* g;
415
416
417
418
        ComputeStateOperation op_type;
        size_t n;
        edge_type e;
        var_vec v;
419
420
        std::vector<query_operation_type> op;
        size_t n_nei_sub;
421

422
423
        compute_state_operation_type(const graph_type* _g, ComputeStateOperation ot, size_t _n, const edge_type& _e, var_vec&& _v)
            : g(_g), op_type(ot), n(_n), e(_e), v(std::move(_v)), op()
424
425
426
427
428
        {}

        void
            operator () (std::map<edge_type, std::shared_ptr<message_type>>& messages, std::vector<std::shared_ptr<message_type>>& stack) const
            {
429
                MSG_DEBUG(std::endl << (*this) << std::endl);
430
                switch (op_type) {
431
432
433
434
435
436
437
438
439
440
441
442
443
444
                    case PushState:
                        if (g->is_aggregate(n) && !g->is_compound_interface(n)) {
                            std::map<edge_type, std::shared_ptr<message_type>> messages;
                            g->subgraphs[n]->compute_messages(stack.end() - n_nei_sub, stack.end(), messages);
                            MSG_QUEUE_FLUSH();
                            stack.resize(stack.size() - n_nei_sub);
                            MSG_QUEUE_FLUSH();
                            g->subgraphs[n]->compute_state(op, messages);
                            stack.emplace_back(std::make_shared<message_type>());
                            for (const auto& msg: g->subgraphs[n]->extract(op)) {
                                stack.back() *= msg;
                            }
                            MSG_QUEUE_FLUSH();
                            /*stack.push_back(g->subgraphs[n]->extract(op));*/
445
                        } else {
446
                            stack.push_back(std::make_shared<message_type>(message_type{g->state[n]}));
447
448
449
450
451
452
453
454
455
                        }
                        break;
                    case PushMessage:
                        stack.push_back(messages[e]);
                        break;
                    case Accumulate:
                        for (size_t i = 0; i < n; ++i) {
                            auto m2 = stack.back();
                            stack.pop_back();
456
                            stack.back() = stack.back() * m2;
457
458
459
460
                        }
                        break;
                    case Project:
                        stack.back() %= v;
461
                        normalize(stack.back());
462
463
                        break;
                    case Store:
464
465
466
467
468
                        if (stack.back()) {
                            messages[e] = std::make_shared<message_type>(*stack.back());
                        } else {
                            messages[e] = std::make_shared<message_type>();
                        }
469
470
471
472
                        stack.pop_back();
                        break;
                    default:;
                };
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
                MSG_DEBUG("STACK");
                for (const auto& s: stack) { MSG_DEBUG("  " << s); }
                MSG_DEBUG("MESSAGES");
                for (const auto& kv: messages) {
                    MSG_DEBUG(std::setw(20) << std::left << kv.first << " [" << kv.second << ']');
                }
            }

        friend
            std::ostream&
            operator << (std::ostream& os, const compute_state_operation_type& cso)
            {
                os << '<';
                switch (cso.op_type) {
                    case PushState:
                        os << "PushState " << (cso.g->is_interface(cso.n) ? 'I' : cso.g->is_aggregate(cso.n) ? 'A' : 'F') << cso.g->variables_of(cso.n);
                        if (cso.g->is_aggregate(cso.n)) {
                            os << " query=" << cso.op;
                        }
                        break;
                    case PushMessage:
                        os << "PushMessage " << cso.e;
                        break;
                    case Accumulate:
                        os << "Accumulate " << cso.n;
                        break;
                    case Project:
                        os << "Project " << cso.v;
                        break;
                    case Store:
                        os << "Store " << cso.e;
                        break;
                };
                return os << '>';
507
508
509
            }
    };

510
511
512
513
514
515
516
517
518
519

    node_vec rank;
    node_vec represented_by;
    std::vector<node_type> type;
    std::vector<colour_proxy> colour;
    std::vector<node_vec> neighbours_in;
    std::vector<node_vec> neighbours_out;
    std::vector<node_vec> inner_nodes;
    std::vector<var_vec> rules;
    var_vec variables;
520

521
522
    std::map<variable_index_type, node_index_type> interface_to_node;
    std::map<node_index_type, variable_index_type> node_to_interface;
523

524
525
526
527
    std::vector<std::shared_ptr<graph_type>> subgraphs;

    std::vector<std::shared_ptr<message_type>> tables;
    std::vector<message_type> state;
528
    std::map<var_vec, genotype_comb_type> domains;
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    std::map<variable_index_type, char> ancestor_letters;
    std::vector<compute_state_operation_type> compute_state_ops;

    const graph_type* parent;
    node_index_type index_in_parent;

    bool aggregate_cycles;
    bool generate_interfaces;

    size_t n_alleles = 1;

    graph_type()
        : rank(), represented_by(), type(), colour(), neighbours_in(), neighbours_out(), inner_nodes(), rules(), variables(), interface_to_node(), node_to_interface(), subgraphs(),  parent(nullptr), index_in_parent(0),aggregate_cycles(true), generate_interfaces(true), n_alleles(1)
    {}

    graph_type(size_t n_al)
        : rank(), represented_by(), type(), colour(), neighbours_in(), neighbours_out(), inner_nodes(), rules(), variables(), interface_to_node(), node_to_interface(), subgraphs(), parent(nullptr), index_in_parent(0), aggregate_cycles(true), generate_interfaces(true), n_alleles(n_al)
    {}

548

549
    bool is_aggregate(node_index_type node) const { return inner_nodes[node].size() > 1; }
550

551
552
553
554
555
556
557
558
559
560
561
562
563
    bool
        is_compound_interface(node_index_type node) const
        {
            if (is_aggregate(node)) {
                for (node_index_type n: inner_nodes[node]) {
                    if (type[n] != Interface) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
564

565
566
567
568
569
570
571
572
573
574
575
576
577
    bool
        is_interface(node_index_type node) const
        {
            if (is_aggregate(node)) {
                for (node_index_type n: inner_nodes[node]) {
                    if (type[n] != Interface) {
                        return false;
                    }
                }
                return true;
            }
            return type[node] == Interface;
        }
578

579
580
581
582
583
    bool
        is_computable(node_index_type node) const
        {
            return !is_interface(node);
        }
584
585
586

    size_t size() const { return rank.size(); }

587
    node_vec
588
589
        active_nodes() const
        {
590
            node_vec ret;
591
            ret.reserve(represented_by.size());
592
            for (node_index_type i = 0; i < represented_by.size(); ++i) {
593
594
595
596
597
598
599
                if (represented_by[i] == i) {
                    ret.push_back(i);
                }
            }
            return ret;
        }

600
601
    node_vec
        resolve_vector(const node_vec& vec) const
602
        {
603
            node_vec ret;
604
            ret.reserve(vec.size());
605
            for (node_index_type i: vec) {
606
607
608
609
610
611
                ret.push_back(resolve(i));
            }
            sort_and_unique(ret);
            return ret;
        }

612
613
    var_vec
        interface_nodes(var_vec inputs) const
614
        {
615
616
617
618
619
620
621
622
            var_vec ret;
            for (variable_index_type v: inputs) {
                ret.push_back(resolve(interface_to_node.find(v)->second));
            }
            sort_and_unique(ret);
            return ret;
        }

623
    std::vector<edge_type>
624
625
        active_edges() const
        {
626
            std::vector<edge_type> ret;
627
628
            for (node_index_type n: active_nodes()) {
                for (node_index_type o: resolve_vector(neighbours_out[n])) {
629
                    ret.emplace_back(this, n, o);
630
631
632
633
634
635
636
637
                }
            }
            return ret;
        }


    void
        dump_node(node_index_type n)
638
        {
639
640
            MSG_DEBUG(
                   '[' << rank[n] << "] " << (is_interface(n) ? "INTERFACE " : (n == inner_nodes[n][0] ? "FACTOR " : "AGGREGATE ")) << n << std::endl
641
642
643
644
645
646
                << "  creation rule " << rules[n] << std::endl
                << "  represented by " << represented_by[n] << " (" << resolve(n) << ')' << std::endl
                << "  colour " << get_colour_impl(colour[n]) << std::endl
                << "  inputs " << neighbours_in[n] << " (" << resolve_vector(neighbours_in[n]) << ')' << std::endl
                << "  outputs " << neighbours_out[n] << " (" << resolve_vector(neighbours_out[n]) << ')' << std::endl
                << "  inner nodes " << inner_nodes[n] << std::endl
647
                << "  variable(s) " << variables_of(n) << std::endl
648
                );
649
            if (inner_nodes[n].size() > 1) {
650
651
652
                for (node_index_type i: inner_nodes[n]) {
                    /*var_vec remaining, imported;*/
                    /*restrict_inputs(rules[i], inner_nodes[n], remaining, imported);*/
653
654
                    /*MSG_DEBUG("  * rule for " << i << ": " << remaining << " / " << imported);*/
                    MSG_DEBUG("  * rule for " << i << ": " << rules[i]);
655
656
                }
            }
657
            MSG_DEBUG("");
658
659
        }

660
661
662
663
664
#define DUMP_SZ(_x) << " * " #_x " " << _x.size() << std::endl

    void
        dump_sizes() const
        {
665
            MSG_DEBUG(""
666
667
668
669
670
671
672
673
674
                DUMP_SZ(rank)
                DUMP_SZ(type)
                DUMP_SZ(rules)
                DUMP_SZ(colour)
                DUMP_SZ(variables)
                DUMP_SZ(inner_nodes)
                DUMP_SZ(neighbours_in)
                DUMP_SZ(neighbours_out)
                DUMP_SZ(represented_by)
675
                );
676
677
        }

678
679
680
    void
        dump()
        {
681
            MSG_DEBUG("ALL NODES");
682
683
            dump_sizes();
            for (node_index_type i = 0; i < rank.size(); ++i) {
684
685
686
687
688
689
690
                dump_node(i);
            }
        }

    void
        dump_active()
        {
691
            MSG_DEBUG("ACTIVE NODES");
692
693
            dump_sizes();
            for (node_index_type i: active_nodes()) {
694
695
696
697
                dump_node(i);
            }
        }

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
    void
        compute_ranks()
        {
            std::vector<bool> visited(rank.size(), false);
            compute_ranks(active_nodes(), visited);
        }

    void
        compute_ranks(const node_vec& nodes, std::vector<bool>& visited)
        {
            for (node_index_type n: nodes) {
                if (visited[n]) { continue; }
                visited[n] = true;
                auto nin = resolve_vector(neighbours_in[n]);
                compute_ranks(nin, visited);
                rank[n] = 0;
                if (nin.size()) {
                    for (node_index_type i: nin) {
                        if (rank[n] < rank[i]) {
                            rank[n] = rank[n];
                        }
                    }
                    ++rank[n];
                }
            }
        }

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
    typedef std::pair<size_t, var_vec> emitter_and_interface_type;
    struct compare_eai {
        bool operator () (const emitter_and_interface_type& e1, const emitter_and_interface_type& e2) const { return e1.first < e2.first || (e1.first == e2.first && e1.second < e2.second); }
    };

    void
        rebuild_interface_between(node_index_type n1, node_index_type n2, std::map<emitter_and_interface_type, size_t, compare_eai>& interface_map)
        {
            auto varset = variables_of(n1) % variables_of(n2);
            /*MSG_DEBUG("edge between factor(graph)s " << n1 << " and " << n2 << " carries variables " << varset);*/
            node_index_type& i = interface_map[{n1, varset}];
            if (i == 0) {
                if (varset.size() == 1) {
                    i = add_interface(node_vec{n1}, varset.front());
                    colour[i] = get_colour_impl(colour[n1]);
                    neighbours_out[i].push_back(n2);
                } else {
                    node_vec iv;
                    iv.reserve(varset.size());
                    for (variable_index_type v: varset) {
                        iv.push_back(add_interface(node_vec{}, v));
                    }
                    i = add_node(node_vec{n1}, node_vec{n2}, var_vec{}, get_colour_impl(colour[n1]), Aggregate, iv, -1);
                    for (node_index_type ni: iv) {
                        represented_by[ni] = i;
                    }
                }
            } else {
                neighbours_out[i].push_back(n2);
            }
            filter_out_and_replace_by(neighbours_out[n1], node_vec{n2}, i);
            filter_out_and_replace_by(neighbours_in[n2], node_vec{n1}, i);
            /*dump_node(n1);*/
            /*dump_node(i);*/
            /*dump_node(n2);*/
        }

762
    void
763
        finalize(bool reconstruct_itf=true)
764
        {
765
            /*dump_active();*/
766
            auto edges = active_edges();
767
            std::map<emitter_and_interface_type, size_t, compare_eai> interface_map;
768
769
770
771
772
            if (reconstruct_itf) {
                for (const auto& e: edges) {
                    if (is_interface(e.first) ^ !is_interface(e.second)) {
                        /* By construction, it's a factor->factor edge, never an interface->interface edge */
                        rebuild_interface_between(e.first, e.second, interface_map);
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
                    }
                }
            }

            if (size()) {
                var_vec all_variables;
                std::vector<bool> var_represented(1 + *std::max_element(variables.begin(), variables.end()), false);
                node_vec A = active_nodes();
                for (node_index_type n: A) {
                    if (is_interface(n)) {
                        for (variable_index_type v: variables_of(n)) {
                            var_represented[v] = true;
                        }
                    }
                }

                for (node_index_type n: A) {
                    if (!is_interface(n)) {
                        for (variable_index_type v: variables_of(n)) {
                            if (var_represented[v]) { continue; }
                            node_index_type i = add_interface(node_vec{n}, v);
                            neighbours_out[n].push_back(i);
                        }
                    }
                }
798
799
800

                for (node_index_type n: A) {
                    if (is_aggregate(n) && !is_interface(n)) {
801
                        MSG_DEBUG("subgraphs.size() = " << subgraphs.size() << " n = " << n);
802
803
804
                        subgraphs[n] = subgraph(n);
                    }
                }
805
            }
806
807
808
809

            if (reconstruct_itf) {
                /*build_compute_graph();*/
            }
810
811
812
813
814
815
        }

    node_index_type
        add_node(const node_vec& in, const node_vec& out,
                 const var_vec& rule, colour_proxy col, node_type t,
                 const node_vec& inner, variable_index_type var)
816
        {
817
            node_index_type ret = rank.size();
818
            /*MSG_DEBUG("adding node " << ret);*/
819
820
821
822
823
824
825
826
827
828
829
830
831
            neighbours_out.emplace_back(out);
            neighbours_in.emplace_back(in);
            rules.emplace_back(rule);
            colour.emplace_back(col);
            if (in.size()) {
                size_t r = 0;
                for (node_index_type i: in) {
                    r = std::max(r, rank[i]);
                }
                rank.push_back(r + 1);
            } else {
                rank.push_back(0);
            }
832
            /*MSG_DEBUG("rank=" << rank.back());*/
833
834
            type.push_back(t);
            variables.push_back(var);
835
            represented_by.push_back(ret);
836
837
            subgraphs.emplace_back();
            tables.emplace_back();
838
            state.emplace_back();
839
840
841
842
843
844
845
846
847
848
849
850
851
852
            if (inner.size()) {
                inner_nodes.emplace_back(inner);
            } else {
                inner_nodes.emplace_back(node_vec{ret});
            }
            /*dump();*/
            return ret;
        }

    node_index_type
        resolve_interface(variable_index_type var)
        {
            auto it = interface_to_node.find(var);
            if (it == interface_to_node.end()) {
853
                /*MSG_DEBUG("resolve_interface(" << var << ") => new interface");*/
854
855
                return add_interface(node_vec{}, var);
            }
856
            /*MSG_DEBUG("resolve_interface(" << var << ") => resolve(" << it->second << ") = " << resolve(it->second));*/
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
            return resolve(it->second);
        }

    node_index_type
        add_interface(const node_vec& producer, variable_index_type var)
        {
            node_index_type ret = add_node(producer, node_vec{}, var_vec{}, create_colour(), Interface, node_vec{}, var);
            interface_to_node[var] = ret;
            node_to_interface[ret] = var;
            for (node_index_type p: producer) {
                neighbours_out[p].push_back(ret);
            }
            return ret;
        }

    node_index_type
        add_factor(const var_vec& rule, colour_proxy col,
                 variable_index_type var)
        {
            node_vec in, out;
            if (generate_interfaces) {
                for (variable_index_type v: rule) {
                    in.push_back(resolve_interface(v));
                }
            } else {
                for (variable_index_type v: rule) {
                    auto it = interface_to_node.find(v);
                    if (it != interface_to_node.end()) {
                        in.push_back(resolve(it->second));
                    }
                }
            }
            sort_and_unique(in);
            node_index_type ret = add_node(in, node_vec{}, rule, col, Factor, node_vec{}, var);
            for (node_index_type n: in) {
                neighbours_out[n].push_back(ret);
            }
            if (generate_interfaces) {
                node_index_type i = add_node(node_vec{ret}, node_vec{}, var_vec{}, colour[ret], Interface, node_vec{}, var);
                interface_to_node[var] = i;
                node_to_interface[i] = var;
                neighbours_out[ret].push_back(i);
            } else {
                interface_to_node[var] = ret;
                node_to_interface[ret] = var;
            }
            return ret;
        }

    node_index_type
        add_factor(variable_index_type var)
        {
909
            /*MSG_DEBUG("add_factor(" << var << ')');*/
910
911
            node_index_type ret = add_factor(var_vec{}, create_colour(), var);
            /*dump();*/
912
913
914
            return ret;
        }

915
916
    node_index_type
        resolve(node_index_type n) const
917
918
919
920
921
        {
            while (n != represented_by[n]) { n = represented_by[n]; }
            return n;
        }

922
923
    node_index_type
        add_factor(variable_index_type v1, variable_index_type var)
924
        {
925
            /*MSG_DEBUG("add_factor(" << v1 << ", " << var << ')');*/
926
927
928
929
930
931
932
933
934
935
936
937
            node_index_type p1r;
            if (!generate_interfaces) {
                auto it = interface_to_node.find(v1);
                if (it == interface_to_node.end()) {
                    auto ret = add_factor(var);
                    rules.back() = {v1};
                    return ret;
                } else {
                    p1r = resolve(it->second);
                }
            } else {
                p1r = resolve_interface(v1);
938
            }
939
940
941
            node_index_type ret = add_factor(var_vec{v1}, colour[p1r], var);
            /*compute_ranks();*/
            /*dump();*/
942
943
944
            return ret;
        }

945
946
    node_index_type
        add_factor(variable_index_type v1,variable_index_type v2, variable_index_type var)
947
        {
948
            /*MSG_DEBUG("add_factor(" << v1 << ", " << v2 << ", " << var << ')');*/
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
            node_index_type p1r, p2r;
            if (!generate_interfaces) {
                auto it = interface_to_node.find(v1);
                if (it == interface_to_node.end()) {
                    node_index_type ret = add_factor(v2, var);
                    rules.back() = {v1, v2};
                    return ret;
                } else {
                    p1r = resolve(it->second);
                }
                it = interface_to_node.find(v2);
                if (it == interface_to_node.end()) {
                    node_index_type ret = add_factor(v1, var);
                    rules.back() = {v1, v2};
                    return ret;
                } else {
                    p2r = resolve(it->second);
                }
            } else {
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
                /* first, search for a factor/aggregate containing both parents */
#if 0
                var_vec sorted_rule = v1 < v2 ? var_vec{v1, v2} : var_vec{v2, v1};
                bool found = false;
                node_index_type common = 0;
                for (auto n: active_nodes()) {
                    auto varset = variables_of(n);
                    auto result = sorted_rule % varset;
                    MSG_DEBUG("searching for rule " << sorted_rule << " in #" << n << ' ' << varset << " => " << result);
                    if (result == sorted_rule) {
                        found = true;
                        common = n;
                        break;
                    }
                }
                if (found) {
                    if (!is_interface(common)) {
                        node_vec in;
                        for (auto n: neighbours_out[common]) {
                            auto varset = variables_of(n);
                            auto result = sorted_rule % varset;
                            MSG_DEBUG("searching for rule (in outputs) " << sorted_rule << " in #" << n << ' ' << varset << " => " << result);
                            if (result == sorted_rule) {
                                common = n;
                                break;
                            }
                        }
                    }
                    if (!is_interface(common)) {
                        /*if (rule.size() == 1) {*/
                        node_index_type i1, i2;
                        if (v1 == variables[common]) {
                            i1 = resolve_interface(v1);
For faster browsing, not all history is shown. View entire blame