symmetry.h 38.1 KB
Newer Older
Damien Leroux's avatar
Damien Leroux committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef _SPEL_SYMMETRY_H_
#define _SPEL_SYMMETRY_H_

#include <vector>
#include <map>
#include <iostream>
#include "eigen.h"
#include "lumping2.h"
#include "permutation.h"
#include "error.h"

/*using namespace Eigen;*/

typedef Eigen::Matrix<char, Eigen::Dynamic, Eigen::Dynamic> MatrixXc;
typedef Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> MatrixXb;
typedef Eigen::Matrix<bool, Eigen::Dynamic, 1> VectorXb;


19
/*typedef std::pair<char, char> label_type;*/
Damien Leroux's avatar
Damien Leroux committed
20
21
22

#define GAMETE_L '<'
#define GAMETE_R '>'
23
#define GAMETE_EMPTY 0
Damien Leroux's avatar
Damien Leroux committed
24
25
26

#define NOT_GAMETE(_l) (_l != GAMETE_EMPTY)

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
struct label_type {
    union {
        struct {
            char first;
            char second;
            char third;
            char count;
        } p;
        uint32_t compact;
    } data;

    label_type() : data({0, 0, 0, 0}) {}
    label_type(char G) : data({G, 0, 0, 1}) {}
    label_type(char l, char r) : data({l, r, 0, 2}) {}
    label_type(char l, char r, char t) : data({l, r, t, 3}) {}

    label_type& operator = (const label_type& other) { data.compact = other.data.compact; return *this; }

    bool operator == (const label_type& other) const { return data.compact == other.data.compact; }
    bool operator != (const label_type& other) const { return data.compact != other.data.compact; }
    bool operator < (const label_type& other) const { return data.compact < other.data.compact; }

    const char& first() const { return data.p.first; }
    const char& second() const { return data.p.second; }

    label_type
        mult(const label_type& other, const std::vector<label_type>& history) const
        {
            if (other.first() == 0) {
                /* recall ! */
                /*MSG_DEBUG("recall! " << history[other.second() - 1]);*/
                return operator * (history[other.second() - 1]);
            }
            return operator * (other);
        }

    label_type
        operator * (const label_type& other) const
        {
            switch (data.p.count) {
                case 0:
                    /* ø * x = x */
                    return other;
                case 1:
                    /* H * P = HP */
                    /* genotype on the other side */
                    /* haplotype also? */
                    return {data.p.first, other.data.p.first, other.data.p.second, (char) (1 + other.data.p.count)};
                case 2:
                    /* P * G = H */
                    /* gamete on the other side */
                    return {other.data.p.first == GAMETE_L ? data.p.first : data.p.second, 0, 0, 1};
                case 3:
                    /* HP * G = HH = P */
                    /* gamete on the other side */
                    return {data.p.first, other.data.p.first == GAMETE_L ? data.p.second : data.p.third, 0, 2};
            };
            return {};  /* make the compiler happy, but this will never be reached. */
        }

    void
        apply_to(std::vector<char>& stack, const std::vector<label_type>& history) const
        {
            /*MSG_DEBUG("apply_to(" << stack << ", " << (*this) << ", " << history << ')');*/
            /*MSG_QUEUE_FLUSH();*/
            if (first() == 0) {
                history[second() - 1].apply_to(stack, history);
            } else {
                if (second() == 0) {
                    /* pop last two, push one back */
                    if (first() == GAMETE_L) {
                        stack.pop_back();
                    } else {
                        char tmp = stack.back();
                        stack.pop_back();
                        stack.back() = tmp;
                    }
                } else {
                    stack.push_back(first());
                    stack.push_back(second());
                }
            }
            /*MSG_DEBUG(" = " << stack);*/
            /*MSG_QUEUE_FLUSH();*/
        }

    friend
        std::ostream& operator << (std::ostream& os, const label_type& l)
        {
            if (l.data.p.first == 0) {
                os << '*';
                if (l.data.p.second != 0) {
                    os << ((int) l.data.p.second);
                }
            } else {
                os << l.data.p.first;
                if (l.data.p.second != 0) {
                    os << l.data.p.second;
                }
                if (l.data.p.third != 0) {
                    os << l.data.p.third;
                }
            }
            return os;
        }

protected:
    label_type(char f, char s, char t, char c) : data({f, s, t, c}) {}
};

Damien Leroux's avatar
Damien Leroux committed
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
struct letter_permutation_type {
    std::map<char, char> table;
    std::map<char, char> transposed;

    letter_permutation_type() : table() {}

    letter_permutation_type(const std::map<char, char>& init)
        : table(init), transposed()
    {
        for (const auto& kv: table) {
            transposed[kv.second] = kv.first;
        }
    }

    letter_permutation_type(std::initializer_list<std::pair<const char, char>> init)
        : table(init), transposed()
    {
        for (const auto& kv: table) {
            transposed[kv.second] = kv.first;
        }
    }

    letter_permutation_type(const letter_permutation_type& reference, const MatrixXb& new_permut)
        : table(), transposed()
    {
        int col = 0, row;
        std::vector<char> letters;
        letters.reserve(reference.table.size());
        for (const auto& kv: reference.table) {
            letters.push_back(kv.first);
        }
        for (const auto& kv: reference.table) {
            new_permut.col(col).maxCoeff(&row);
            table.emplace_hint(table.end(), kv.first, letters[row]);
            ++col;
        }
        for (const auto& kv: table) {
            transposed[kv.second] = kv.first;
        }
    }

    static
        letter_permutation_type identity(const std::vector<label_type>& labels)
        {
            letter_permutation_type ret;
            for (const auto& l: labels) {
183
184
                ret.table[l.first()] = l.first();
                ret.table[l.second()] = l.second();
Damien Leroux's avatar
Damien Leroux committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
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
            }
            ret.transposed = ret.table;
            return ret;
        }

    bool empty() const { return table.size() == 0; }

    letter_permutation_type transpose() const { letter_permutation_type ret; ret.table = transposed; ret.transposed = table; return ret; }

    MatrixXb matrix() const
    {
        MatrixXb ret = MatrixXb::Zero(table.size(), table.size());
        std::map<char, int> indices;
        for (const auto& kv: table) {
            int sz = indices.size();
            indices[kv.first] = sz;
        }
        for (const auto& kv: table) {
            /*MSG_DEBUG(kv.second << '[' << indices[kv.second] << "] " << kv.first << '[' << indices[kv.first] << ']');*/
            /*MSG_QUEUE_FLUSH();*/
            ret(indices[kv.second], indices[kv.first]) = 1;
        }
        return ret;
    }

    bool in_same_space(const letter_permutation_type& other) const
    {
        if (table.size() != other.table.size()) {
            return false;
        }
        auto i = table.begin();
        auto j = table.end();
        auto o = other.table.begin();
        for (; i != j; ++i, ++o) {
            if (i->first != o->first) {
                return false;
            }
        }
        return true;
    }

    MatrixXc pretty_print_matrix() const
    {
        MatrixXc ret = MatrixXc::Constant(table.size() + 3, table.size() + 3, ' ');
        int x = 0;
        for (int c = 0; c < ret.cols(); ++c) {
            ret(0, c) = '-';
            ret(ret.rows() - 1, c) = '-';
            ret(c, 0) = ':';
            ret(c, ret.cols() - 1) = ':';
        }
        ret(0, 0) = ret(0, ret.cols() - 1) = '.';
        ret(ret.rows() - 1) = ret(ret.rows() - 1, ret.cols() - 1) = '\'';
        for (const auto& kv: table) {
            ret(1, 2 + x) = kv.first;
            ret(2 + x, 1) = kv.first;
            ++x;
        }
        ret.block(2, 2, table.size(), table.size()) = (' ' + ('@' - ' ') * matrix().cast<char>().array()).matrix();
        return ret;
    }

    friend
        std::ostream& operator << (std::ostream& os, const letter_permutation_type& st)
        {
            auto i = st.table.begin();
            auto j = st.table.end();
            os << '{';
            if (i != j) {
                os << i->first << ':' << i->second;
                for (++i; i != j; ++i) {
                    os << ' ' << i->first << ':' << i->second;
                }
            }
            return os << '}';
        }

    bool combine(const letter_permutation_type& other, letter_permutation_type& result) const
    {
        if (other.table.size() == 0) {
            result.table = table;
            return true;
        }
        if (table.size() == 0) {
            result.table = other.table;
            return true;
        }
        letter_permutation_type ret;
        auto ti = table.begin(), tj = table.end();
        auto oi = other.table.begin(), oj = other.table.end();

        for (; ti != tj && oi != oj;) {
            if (ti->first < oi->first) {
                result.table.insert(result.table.end(), *ti);
                ++ti;
            } else if (ti->first > oi->first) {
                result.table.insert(result.table.end(), *oi);
                ++oi;
            } else if (ti->second != oi->second) {
                result.table.clear();
                return false;
            } else {
                result.table.insert(result.table.end(), *ti);
                ++ti;
                ++oi;
            }
        }
        for (; ti != tj; ++ti) {
            result.table.insert(result.table.end(), *ti);
        }
        for (; oi != oj; ++oi) {
            result.table.insert(result.table.end(), *oi);
        }
        return true;
    }

    letter_permutation_type operator * (const letter_permutation_type& other) const
    {
        return compose(other);
    }

    letter_permutation_type compose(const letter_permutation_type& other) const
    {
        if (other.table.size() == 0) {
            return *this;
        }
        if (table.size() == 0) {
            return other;
        }
        MatrixXb m = matrix() * other.matrix();
        if (!(m.transpose() * m - MatrixXb::Identity(m.rows(), m.cols())).isZero()) {
            MSG_DEBUG("FOIRURE MATRICE DE PERMUTATION DE LETTRES COMBINEE");
            MSG_DEBUG(matrix());
            MSG_DEBUG("--");
            MSG_DEBUG(other.matrix());
            MSG_DEBUG("--");
            MSG_DEBUG(m);
            MSG_QUEUE_FLUSH();
            /*abort();*/
            return {};
        }
        letter_permutation_type ret{*this, m};
        MSG_DEBUG("[product A] " << (*this));
        MSG_DEBUG("[product B] " << other);
        MSG_DEBUG("[product R] " << ret);
        return ret;
    }

    bool operator < (const letter_permutation_type& other) const { return table < other.table; }
    bool operator == (const letter_permutation_type& other) const { return table == other.table; }
};

struct symmetry_table_type {
    //std::vector<std::pair<char, char>> switches;  /* over letters */
    //std::map<int, int> table;                     /* over states */
    permutation_type table;
    letter_permutation_type letters;

    symmetry_table_type(const std::map<int, int>& _t, const letter_permutation_type& _l)
        : table(_t), letters(_l)
    {}

    template <typename DERIVED>
        symmetry_table_type(const permutation_base<DERIVED>& state_matrix, const letter_permutation_type& l)
        : table(state_matrix), letters(l)
        {}

    symmetry_table_type() : table() {}

    symmetry_table_type(const symmetry_table_type& other) : table(other.table), letters(other.letters) {}

    symmetry_table_type& operator = (const symmetry_table_type& other) { table = other.table; letters = other.letters; return *this; }

    symmetry_table_type inverse() const { return {table.transpose(), letters.transpose()}; }


    template <typename DERIVED>
        static
        std::pair<bool, symmetry_table_type>
        build(const permutation_base<DERIVED>& permut, const std::vector<label_type>& labels, const MatrixXd& inf_mat, bool latent)
        {
            MSG_DEBUG("#@#@#@ TRYING TO BUILD SYMMETRY FROM");
            MSG_DEBUG("* labels " << labels);
            MSG_DEBUG("* inf_mat");
            MSG_DEBUG(inf_mat);
            MSG_DEBUG("* permutation");
            MSG_DEBUG(permut);
            MSG_QUEUE_FLUSH();
373
374
375
376
377

            if (permut.size() != labels.size()) {
                return {false, {}};
            }

Damien Leroux's avatar
Damien Leroux committed
378
379
380
381
382
383
384
385
386
387
388
389
            bool ok = true;

            auto new_labels = permut * labels;

            auto li = labels.begin();
            auto lj = labels.end();
            auto ni = new_labels.begin();

            std::map<char, char> switches;
            for (; li != lj; ++li, ++ni) {
                char c1, n1, c2, n2;
                if (latent) {
390
391
                    std::tie(c1, n2) = std::tie(li->first(), ni->first());
                    std::tie(c2, n1) = std::tie(li->second(), ni->second());
Damien Leroux's avatar
Damien Leroux committed
392
                } else {
393
394
                    std::tie(c1, n1) = std::tie(li->first(), ni->first());
                    std::tie(c2, n2) = std::tie(li->second(), ni->second());
Damien Leroux's avatar
Damien Leroux committed
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
                }
                auto i = switches.find(c1);
                if (i == switches.end()) {
                    switches[c1] = n1;
                } else if (i->second != n1) {
                    ok = false;
                    break;
                }
                i = switches.find(c2);
                if (i == switches.end()) {
                    switches[c2] = n2;
                } else if (i->second != n2) {
                    ok = false;
                    break;
                }
            }

            if (ok) {
                MatrixXd new_mat = permut % inf_mat;
                ok = (new_mat - inf_mat).isZero();
            } else {
                MSG_DEBUG("PERMUTATION CREATES INVALID LETTER MAPPING");
                MSG_DEBUG(permut);
            }

            if (ok) {
                return {true, {permut, switches}};
            }

            return {false, {}};
        }

    friend
        std::ostream& operator << (std::ostream& os, const symmetry_table_type& st)
        {
            os << st.letters << '-';
            auto i = st.table.begin();
            auto j = st.table.end();
            os << '{';
            if (i != j) {
                os << i->first << ':' << i->second;
                for (++i; i != j; ++i) {
                    os << ' ' << i->first << ':' << i->second;
                }
            }
            return os << '}';
        }

    std::vector<std::pair<char, char>> switches_from_labels(const std::vector<label_type>& labels, bool latent=false) const
    {
        std::set<std::pair<char, char>> tmp;
        /*MSG_DEBUG_INDENT_EXPR("[switches_from_labels#" << latent << "] ");*/
447
        if (latent && labels.front().second() != GAMETE_EMPTY) {
Damien Leroux's avatar
Damien Leroux committed
448
449
            for (const auto& kv: table) {
                /*MSG_DEBUG(kv.first << ',' << kv.second << ' ' << labels[kv.first] << ',' << labels[kv.second]);*/
450
451
                tmp.emplace(labels[kv.first].first(), labels[kv.second].second());
                tmp.emplace(labels[kv.first].second(), labels[kv.second].first());
Damien Leroux's avatar
Damien Leroux committed
452
453
454
455
            }
        } else {
            for (const auto& kv: table) {
                /*MSG_DEBUG(kv.first << ',' << kv.second << ' ' << labels[kv.first] << ',' << labels[kv.second]);*/
456
457
458
                tmp.emplace(labels[kv.first].first(), labels[kv.second].first());
                if (labels[kv.first].second() != GAMETE_EMPTY) {
                    tmp.emplace(labels[kv.first].second(), labels[kv.second].second());
Damien Leroux's avatar
Damien Leroux committed
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
                }
            }
        }
        /*MSG_DEBUG_DEDENT;*/
        return {tmp.begin(), tmp.end()};
    }

    bool is_consistent(const std::vector<label_type>& labels, bool latent=false) const
    {
        auto switches = switches_from_labels(labels, latent);
        auto smap = switch_map(labels, latent);
        letter_permutation_type tmp(smap);
        MSG_DEBUG_INDENT_EXPR("[is_consistent] ");
        MSG_DEBUG("smap");
        MSG_DEBUG(tmp);
        MSG_DEBUG("letters");
        MSG_DEBUG(letters);
        MSG_DEBUG_DEDENT;
        for (const auto& s: smap) {
            if (s.second == '!') {
                return false;
            }
        }
        return smap == letters.table;
        /*MSG_DEBUG("switches.size() = " << switches.size());*/
        /*MSG_DEBUG("switch_map().size() = " << smap.size());*/
        /*return switches.size() == smap.size();*/
    }

    static
489
        std::map<char, int> letter_indices(const std::vector<label_type>& data)
Damien Leroux's avatar
Damien Leroux committed
490
491
492
        {
            std::map<char, int> ret;
            for (const auto& s: data) {
493
494
                if (s.first() != GAMETE_EMPTY) {
                    ret[s.first()] = 0;
Damien Leroux's avatar
Damien Leroux committed
495
                }
496
497
                if (s.second() != GAMETE_EMPTY) {
                    ret[s.second()] = 0;
Damien Leroux's avatar
Damien Leroux committed
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
                }
            }
            int i = 0;
            for (auto& l: ret) {
                l.second = i++;
                /*MSG_DEBUG("assign " << l.second << " to letter " << l.first);*/
            }
            return ret;
        }

    std::map<char, char> switch_map(const std::vector<label_type>& labels, bool latent=false) const
    {
        auto switches = switches_from_labels(labels, latent);
        std::map<char, char> ret;
        for (const auto& s: switches) {
            auto it = ret.find(s.first);
            if (it != ret.end() && it->second != s.second) {
                it->second = '!';
            } else {
                ret[s.first] = s.second;
            }
        }
        return ret;
    }

    MatrixXb switch_matrix(const std::vector<label_type>& labels, bool latent) const
    {
        auto l = letter_indices(labels);
        auto switches = switches_from_labels(labels, latent);
        MatrixXb ret = MatrixXb::Zero(l.size(), l.size());
        for (const auto& s: switches) {
            /*MSG_DEBUG("switch " << s.first << " -> " << s.second);*/
            ret(l[s.second], l[s.first]) = 1;
        }
        /* TODO: parano */
        return ret;
    }

    static
        std::vector<std::pair<char, char>> switches_from_matrix(const std::vector<label_type>& labels, const MatrixXb& switch_mat)
        {
            auto l = letter_indices(labels);
            std::vector<std::pair<char, char>> ret;
            ret.reserve(switch_mat.cols());
            for (const auto& kv1: l) {
                for (const auto& kv2: l) {
                    if (switch_mat(kv2.second, kv1.second)) {
                        ret.emplace_back(kv1.first, kv2.first);
                    }
                }
            }
            return ret;
        }

    MatrixXb matrix() const
    {
        MatrixXb ret = MatrixXb::Zero(table.size(), table.size());
        for (const auto& kv: table) {
            /*MSG_DEBUG("kv={" << kv.first << ',' << kv.second << '}');*/
            ret(kv.second, kv.first) = 1;
        }
        /* TODO: parano */
        /*MSG_DEBUG_INDENT_EXPR("[symmetry matrix] ");*/
        /*MSG_DEBUG(ret);*/
        /*MSG_DEBUG_DEDENT;*/
        return ret;
    }

    bool operator < (const symmetry_table_type& other) const { return letters < other.letters; }
    bool operator == (const symmetry_table_type& other) const { return letters == other.letters; }
    bool operator == (const letter_permutation_type& lp) const { return letters == lp; }

    friend
        symmetry_table_type kronecker(const symmetry_table_type& s1, const symmetry_table_type& s2)
        {
            MatrixXb mat = kroneckerProduct(s1.matrix(), s2.matrix());
            /*return {labels, mat};*/
            letter_permutation_type comb;
            s1.letters.combine(s2.letters, comb);
            return {permutation_type{mat}, comb};
        }

    struct dumpable {
        const symmetry_table_type* ptr;
        dumpable(const symmetry_table_type* p) : ptr(p) {}
        friend std::ostream& operator << (std::ostream& os, const dumpable& d)
        {
            os << d.ptr->letters << std::endl << d.ptr->table;
            return os;
        }
    };

    /*dumpable dump(const std::vector<label_type>&, bool latent=false) const { return {this}; }*/
    dumpable dump(const std::vector<label_type>&, bool) const { return {this}; }
    dumpable dump(const std::vector<label_type>&) const { return {this}; }

    std::vector<label_type> reorder_labels(const std::vector<label_type>& l, int method)
    {
        std::vector<label_type> ret(l.size());
        switch (method) {
            case 0:
                for (const auto& kv: table) {
                    ret[kv.first] = l[kv.second];
                }
                break;
            case 1:
                for (const auto& kv: table) {
                    ret[kv.second] = l[kv.first];
                }
                break;
            case 2:
                {
                    VectorXi idx(l.size());
                    for (int i = 0; i < idx.size(); ++i) { idx(i) = i; }
                    VectorXi n_idx = idx.transpose() * matrix().cast<int>();
                    for (int i = 0; i < idx.size(); ++i) {
                        ret[i] = l[n_idx[i]];
                    }
                }
                break;
            case 3:
                {
                    VectorXi idx(l.size());
                    for (int i = 0; i < idx.size(); ++i) { idx(i) = i; }
                    VectorXi n_idx = idx.transpose() * matrix().cast<int>();
                    for (int i = 0; i < idx.size(); ++i) {
                        ret[n_idx[i]] = l[i];
                    }
                }
                break;
            case 4:
                {
                    VectorXi idx(l.size());
                    for (int i = 0; i < idx.size(); ++i) { idx(i) = i; }
                    VectorXi n_idx = matrix().cast<int>() * idx;
                    for (int i = 0; i < idx.size(); ++i) {
                        ret[i] = l[n_idx[i]];
                    }
                }
                break;
            case 5:
                {
                    VectorXi idx(l.size());
                    for (int i = 0; i < idx.size(); ++i) { idx(i) = i; }
                    VectorXi n_idx = matrix().cast<int>() * idx;
                    for (int i = 0; i < idx.size(); ++i) {
                        ret[n_idx[i]] = l[i];
                    }
                }
                break;
        };
        return ret;
    }

    symmetry_table_type operator * (const symmetry_table_type& other) const
    {
        if (!letters.in_same_space(other.letters)) {
            return {};
        }
        return {table * other.table, letters * other.letters};
#if 0
        MSG_DEBUG("COMPOSING SYMMETRIES");
        MSG_DEBUG("" << (*this));
        MSG_DEBUG("AND");
        MSG_DEBUG("" << other);
        MSG_DEBUG("...");
        MatrixXb M1 = matrix();
        MatrixXb M2 = other.matrix();
        MatrixXb new_mat = kroneckerProduct(M1, M2);

        std::map<int, int> new_table;

        for (int j = 0; j < new_mat.cols(); ++j) {
            int i;
            new_mat.col(j).maxCoeff(&i);
            new_table.emplace(j, i);
        }

        letter_permutation_type new_letters;
        if (!letters.combine(other.letters, new_letters)) {
            MSG_DEBUG("foirure.");
        }

        symmetry_table_type ret(new_table, new_letters);
        MSG_DEBUG("RESULT:");
        MSG_DEBUG(ret);
        return ret;
#endif
    }

    symmetry_table_type
        lump(const std::set<subset>& P0) const
        {
            return {table.lump(P0), letters};
        }

    symmetry_table_type
        lump(const Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>& mat) const
        {
            return {table.lump(mat), letters};
        }
};


typedef std::vector<symmetry_table_type> symmetry_list_type;

struct symmetry_group_type {
    typedef symmetry_list_type::const_iterator const_iterator;
    typedef symmetry_list_type::iterator iterator;
    typedef symmetry_list_type::reverse_iterator reverse_iterator;

    std::map<letter_permutation_type, size_t> m_letter_permutations;
    symmetry_list_type m_symmetries;

    symmetry_group_type() : m_letter_permutations(), m_symmetries() {}
    symmetry_group_type(const std::vector<label_type>& labels)
        : m_letter_permutations(), m_symmetries()
    {
        MSG_DEBUG("NEW GROUP FROM " << labels.size() << " LABELS");
        permutation_type permut = permutation_type::identity(labels.size());
        std::map<char, char> letters;
        for (const auto& l: labels) {
720
721
            letters[l.first()] = l.first();
            letters[l.second()] = l.second();
Damien Leroux's avatar
Damien Leroux committed
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
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
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
886
887
888
        }
        insert(symmetry_table_type{permut, letters});
    }

    static const symmetry_group_type&
        gamete()
        {
            static symmetry_group_type _(2);
            return _;
        }

    symmetry_group_type
        operator - (const symmetry_group_type& other) const
        {
            symmetry_group_type ret;
            for (const auto& kv: m_letter_permutations) {
                if (other.m_letter_permutations.find(kv.first) == other.m_letter_permutations.end()) {
                    /*ret.insert(m_symmetries[kv.second]);*/
                    ret.m_letter_permutations[kv.first] = ret.m_symmetries.size();
                    ret.m_symmetries.emplace_back(m_symmetries[kv.second]);
                }
            }
            return ret;
        }

    const_iterator cbegin() const { return m_symmetries.cbegin(); }
    const_iterator cend() const { return m_symmetries.cend(); }
    const_iterator begin() const { return m_symmetries.begin(); }
    const_iterator end() const { return m_symmetries.end(); }

    iterator begin() { return m_symmetries.begin(); }
    iterator end() { return m_symmetries.end(); }

    reverse_iterator rbegin() { return m_symmetries.rbegin(); }
    reverse_iterator rend() { return m_symmetries.rend(); }

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

    bool
        insert_impl(const symmetry_table_type& sym)
        {
            auto i = m_letter_permutations.find(sym.letters);
            if (i != m_letter_permutations.end()) {
                MSG_DEBUG("-- SKIP   " << sym.letters);
                return false;
            }
            if (m_letter_permutations.emplace(sym.letters, m_symmetries.size()).second) {
                MSG_DEBUG("## INSERT " << sym.letters);
                m_symmetries.push_back(sym);
            }
            return true;
        }

    bool
        insert(const symmetry_table_type& sym)
        {
            size_t result = insert_impl(sym) + insert_impl(sym.inverse());
            if (result > 0) {
                generate(result);
            }
            return !!result;
        }

    void
        generate(size_t n)
        {
            MSG_DEBUG_INDENT;
            for (size_t j = m_symmetries.size() - n; j < m_symmetries.size(); ++j) {
                for (size_t i = 1; i < j; ++i) { /* skip identity ! WARNING must be certain identity has been put there first */
                    insert_impl(m_symmetries[i] * m_symmetries[j]);
                    insert_impl(m_symmetries[j] * m_symmetries[i]);
                }
                insert_impl(m_symmetries[j] * m_symmetries[j]);
            }
            MSG_DEBUG_DEDENT;
        }

    bool
        operator == (const symmetry_group_type& other) const
        {
            if (m_letter_permutations.size() != other.m_letter_permutations.size()) {
                return false;
            }
            auto i = m_letter_permutations.begin();
            auto j = m_letter_permutations.end();
            auto oi = other.m_letter_permutations.begin();
            for (; i != j && oi->first == i->first; ++i, ++oi);
            return i == j;
        }

    bool
        operator < (const symmetry_group_type& other) const
        {
            if (m_letter_permutations.size() < other.m_letter_permutations.size()) {
                return true;
            }
            if (m_letter_permutations.size() > other.m_letter_permutations.size()) {
                return false;
            }
            auto i = m_letter_permutations.begin();
            auto j = m_letter_permutations.end();
            auto oi = other.m_letter_permutations.begin();
            for (; i != j; ++i, ++oi) {
                if (i->first < oi->first) {
                    return true;
                } else if (oi->first < i->first) {
                    return false;
                }
            }
            return false;
        }

    friend
        std::ostream&
        operator << (std::ostream& os, const symmetry_group_type& grp)
        {
            if (grp.size() == 0) {
                return os << "[empty]";
            }
            std::vector<std::string> bracket;
            std::vector<std::string> bracket_r;
            bracket.reserve(grp.size());
            if (grp.size() == 1) {
                bracket.push_back("[");
                bracket_r.push_back("]");
            } else {
                bracket.push_back("⎡");
                bracket_r.push_back("⎤");
                for (size_t i = 2; i < grp.size(); ++i) {
                    bracket.push_back("⎢");
                    bracket_r.push_back("⎥");
                }
                bracket.push_back("⎣");
                bracket_r.push_back("⎦");
            }
            auto bi = bracket.begin();
            auto bri = bracket_r.begin();
            for (const auto& s: grp) {
                os << (*bi++) << s << (*bri++) << std::endl;
            }
            return os;
        }

    symmetry_group_type
        lump(const std::set<subset>& P0) const
        {
            symmetry_group_type ret;
            for (const auto& sym: m_symmetries) {
                ret.insert(sym.lump(P0));
            }
            return ret;
        }

    symmetry_group_type
        lump(const Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>& mat) const
        {
            symmetry_group_type ret;
            for (const auto& sym: m_symmetries) {
                ret.insert(sym.lump(mat));
            }
            return ret;
        }

    template <typename DERIVED>
        symmetry_group_type
        permute(const permutation_base<DERIVED>& permut) const
        {
889
890
891
            MSG_DEBUG_INDENT_EXPR("[group.permute] ");
            MSG_DEBUG((*this));
            MSG_DEBUG("" << permut);
Damien Leroux's avatar
Damien Leroux committed
892
893
894
895
            symmetry_group_type ret;
            for (const auto& sym: m_symmetries) {
                ret.insert({permut * sym.table, sym.letters});
            }
896
            MSG_DEBUG_DEDENT;
Damien Leroux's avatar
Damien Leroux committed
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
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
            return ret;
        }

    private:
    symmetry_group_type(int) /* gamete letter-agnostic group */
        : m_letter_permutations(), m_symmetries()
    {
        insert(symmetry_table_type{permutation_type{1, 0}, letter_permutation_type{}});
    }
};

struct symmetry_mask_type {
    std::vector<std::vector<int>> m_mask;

    bool is_invalid() const { for (const auto& v: m_mask) { if (!v.size()) { return true; } } return false; }
    bool is_singletons() const { for (const auto& v: m_mask) { if (v.size() != 1) { return false; } } return true; }

    permutation_type
        as_permutation() const
        {
            std::vector<int> ret;
            ret.reserve(m_mask.size());
            for (const auto& v: m_mask) {
                ret.push_back(v.front());
            }
            return permutation_type{ret};
        }

    MatrixXb
        as_matrix() const
        {
            MatrixXb ret = MatrixXb::Zero(m_mask.size(), m_mask.size());
            for (size_t j = 0; j < m_mask.size(); ++j) {
                for (int i: m_mask[j]) {
                    ret(i, j) = 1;
                }
            }
            return ret;
        }

    static
        symmetry_mask_type
        build(const size_t L, const size_t R, const permutation_type& permut)
        {
            symmetry_mask_type ret;
            ret.m_mask.resize(L * R * permut.size(), {});
            // L is the outer shape factor (number of repeats of the permutation pattern)
            // R is the inner shape factor (number of repeats of each permutted state)
            const size_t inner_size = R * permut.size();
            auto
                pos = [&] (size_t li, int state, size_t ri)
                {
                    return li * inner_size + state * R + ri;
                };

            for (auto p: permut) {
                for (size_t li = 0; li < L; ++li) {
                    for (size_t lj = 0; lj < L; ++lj) {
                        for (size_t ri = 0; ri < R; ++ri) {
                            size_t s1 = pos(li, p.first, ri);
                            for (size_t rj = 0; rj < R; ++rj) {
                                size_t s2 = pos(lj, p.second, rj);
                                ret.m_mask[s1].push_back(s2);
                            }
                        }
                    }
                }
            }
            return ret;
        }

    symmetry_mask_type
        operator & (const symmetry_mask_type& other) const
        {
            symmetry_mask_type ret;
            ret.m_mask.resize(m_mask.size());
            for (size_t i = 0; i < m_mask.size(); ++i) {
                ret.m_mask[i].resize(std::max(m_mask[i].size(), other.m_mask[i].size()));
                auto end = std::set_intersection(
                        m_mask[i].begin(), m_mask[i].end(),
                        other.m_mask[i].begin(), other.m_mask[i].end(),
                        ret.m_mask[i].begin());
                ret.m_mask[i].resize(end - ret.m_mask[i].begin());
            }
            return ret;
        }

    friend
        std::ostream&
        operator << (std::ostream& os, const symmetry_mask_type& sm)
        {
            size_t n = 0;
            for (const auto& v: sm.m_mask) {
                os << (n++) << ":";
                if (v.size() == 0) {
                    os << "(empty)" << std::endl;
                    continue;
                }
                for (int i: v) {
                    os << ' ' << i;
                }
                os << std::endl;
            }
            return os;