symmetry.h 41.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Spell-QTL  Software suite for the QTL analysis of modern datasets.
 * Copyright (C) 2016,2017  Damien Leroux <damien.leroux@inra.fr>, Sylvain Jasson <sylvain.jasson@inra.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Damien Leroux's avatar
Damien Leroux committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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;


36
/*typedef std::pair<char, char> label_type;*/
Damien Leroux's avatar
Damien Leroux committed
37
38
39

#define GAMETE_L '<'
#define GAMETE_R '>'
40
#define GAMETE_EMPTY 0
Damien Leroux's avatar
Damien Leroux committed
41
42
43

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

44
45

#if 0
46
struct label_type {
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
    typedef int32_t letter_type;
    typedef uint64_t compact_type;
    union {
        struct {
            letter_type first;
            letter_type second;
        } p;
        compact_type compact;
    } data;

    label_type() : data({0, 0}) {}
    label_type(letter_type G) : data({G, 0}) {}
    label_type(letter_type l, letter_type r) : data({l, r}) {}

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

    letter_type& first() const { return data.p.first; }
    letter_type& second() const { return data.p.second; }
    compact_type compact() const { return data.compact; }

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



#else
struct label_type {
    typedef char letter_type;
97
98
99
100
101
102
103
104
105
106
    union {
        struct {
            char first;
            char second;
            char third;
            char count;
        } p;
        uint32_t compact;
    } data;

107
108
109
110
    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}}) {}
111
112
113
114
115
116
117
118
119

    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; }
120
    decltype(data.compact) compact() const { return data.compact; }
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

    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:
204
    label_type(char f, char s, char t, char c) : data({{f, s, t, c}}) {}
205
};
206
207
#endif

208
#if 0
209

Damien Leroux's avatar
Damien Leroux committed
210
struct letter_permutation_type {
211
212
    std::map<label_type::letter_type, label_type::letter_type> table;
    std::map<label_type::letter_type, label_type::letter_type> transposed;
Damien Leroux's avatar
Damien Leroux committed
213
214
215

    letter_permutation_type() : table() {}

216
    letter_permutation_type(const std::map<label_type::letter_type, label_type::letter_type>& init)
Damien Leroux's avatar
Damien Leroux committed
217
218
219
220
221
222
223
        : table(init), transposed()
    {
        for (const auto& kv: table) {
            transposed[kv.second] = kv.first;
        }
    }

224
    letter_permutation_type(std::initializer_list<std::pair<const label_type::letter_type, label_type::letter_type>> init)
Damien Leroux's avatar
Damien Leroux committed
225
226
227
228
229
230
231
232
233
234
235
        : 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;
236
        std::vector<label_type::letter_type> letters;
Damien Leroux's avatar
Damien Leroux committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        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) {
256
257
                ret.table[l.first()] = l.first();
                ret.table[l.second()] = l.second();
Damien Leroux's avatar
Damien Leroux committed
258
259
260
261
262
263
264
265
266
267
268
269
            }
            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());
270
        std::map<label_type::letter_type, int> indices;
Damien Leroux's avatar
Damien Leroux committed
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
        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;
        }
316
        ret.block(2, 2, table.size(), table.size()) = (' ' + ('@' - ' ') * matrix().cast<label_type::letter_type>().array()).matrix();
Damien Leroux's avatar
Damien Leroux committed
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
        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 {
411
412
    std::vector<std::pair<label_type::letter_type, label_type::letter_type>> switches;  /* over letters */
    std::map<int, int> table;                     /* over states */
Damien Leroux's avatar
Damien Leroux committed
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
    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();
446
447
448
449
450

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

Damien Leroux's avatar
Damien Leroux committed
451
452
453
454
455
456
457
458
            bool ok = true;

            auto new_labels = permut * labels;

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

459
            std::map<label_type::letter_type, label_type::letter_type> switches;
Damien Leroux's avatar
Damien Leroux committed
460
            for (; li != lj; ++li, ++ni) {
461
                label_type::letter_type c1, n1, c2, n2;
Damien Leroux's avatar
Damien Leroux committed
462
                if (latent) {
463
464
                    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
465
                } else {
466
467
                    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
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
                }
                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 << '}';
        }

516
    std::vector<std::pair<label_type::letter_type, label_type::letter_type>> switches_from_labels(const std::vector<label_type>& labels, bool latent=false) const
Damien Leroux's avatar
Damien Leroux committed
517
    {
518
        std::set<std::pair<label_type::letter_type, label_type::letter_type>> tmp;
Damien Leroux's avatar
Damien Leroux committed
519
        /*MSG_DEBUG_INDENT_EXPR("[switches_from_labels#" << latent << "] ");*/
520
        if (latent && labels.front().second() != GAMETE_EMPTY) {
Damien Leroux's avatar
Damien Leroux committed
521
522
            for (const auto& kv: table) {
                /*MSG_DEBUG(kv.first << ',' << kv.second << ' ' << labels[kv.first] << ',' << labels[kv.second]);*/
523
524
                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
525
526
527
528
            }
        } else {
            for (const auto& kv: table) {
                /*MSG_DEBUG(kv.first << ',' << kv.second << ' ' << labels[kv.first] << ',' << labels[kv.second]);*/
529
530
531
                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
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
                }
            }
        }
        /*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
562
        std::map<label_type::letter_type, int> letter_indices(const std::vector<label_type>& data)
Damien Leroux's avatar
Damien Leroux committed
563
        {
564
            std::map<label_type::letter_type, int> ret;
Damien Leroux's avatar
Damien Leroux committed
565
            for (const auto& s: data) {
566
567
                if (s.first() != GAMETE_EMPTY) {
                    ret[s.first()] = 0;
Damien Leroux's avatar
Damien Leroux committed
568
                }
569
570
                if (s.second() != GAMETE_EMPTY) {
                    ret[s.second()] = 0;
Damien Leroux's avatar
Damien Leroux committed
571
572
573
574
575
576
577
578
579
580
                }
            }
            int i = 0;
            for (auto& l: ret) {
                l.second = i++;
                /*MSG_DEBUG("assign " << l.second << " to letter " << l.first);*/
            }
            return ret;
        }

581
    std::map<label_type::letter_type, label_type::letter_type> switch_map(const std::vector<label_type>& labels, bool latent=false) const
Damien Leroux's avatar
Damien Leroux committed
582
583
    {
        auto switches = switches_from_labels(labels, latent);
584
        std::map<label_type::letter_type, label_type::letter_type> ret;
Damien Leroux's avatar
Damien Leroux committed
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
        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
610
        std::vector<std::pair<label_type::letter_type, label_type::letter_type>> switches_from_matrix(const std::vector<label_type>& labels, const MatrixXb& switch_mat)
Damien Leroux's avatar
Damien Leroux committed
611
612
        {
            auto l = letter_indices(labels);
613
            std::vector<std::pair<label_type::letter_type, label_type::letter_type>> ret;
Damien Leroux's avatar
Damien Leroux committed
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
            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());
791
        std::map<label_type::letter_type, label_type::letter_type> letters;
Damien Leroux's avatar
Damien Leroux committed
792
        for (const auto& l: labels) {
793
794
            letters[l.first()] = l.first();
            letters[l.second()] = l.second();
Damien Leroux's avatar
Damien Leroux committed
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
889
890
891
892
893
894
895
896
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
        }
        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
        {
962
963
964
            MSG_DEBUG_INDENT_EXPR("[group.permute] ");
            MSG_DEBUG((*this));
            MSG_DEBUG("" << permut);
Damien Leroux's avatar
Damien Leroux committed
965
966
967
968
            symmetry_group_type ret;
            for (const auto& sym: m_symmetries) {
                ret.insert({permut * sym.table, sym.letters});
            }
969
            MSG_DEBUG_DEDENT;
Damien Leroux's avatar
Damien Leroux committed
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
            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(), {});
1016
1017
            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)
Damien Leroux's avatar
Damien Leroux committed
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
            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;
        }
};


inline
permutation_type
combine_permutations(
        const std::pair<std::vector<size_t>, std::vector<size_t>>& LR,
        const std::vector<permutation_type>& permuts)
{
    symmetry_mask_type ret = symmetry_mask_type::build(LR.first[0], LR.second[0], permuts[0]);
    for (size_t i = 1; i < LR.first.size(); ++i) {
        ret = ret & symmetry_mask_type::build(LR.first[i], LR.second[i], permuts[i]);
        if (ret.is_invalid()) {
            MSG_DEBUG("<sym invalid after " << i << " steps>");
            return {};
        }
    }
    return ret.as_permutation();
}


inline
std::pair<bool, symmetry_table_type>
combine_symmetries(
        std::pair<std::vector<size_t>, std::vector<size_t>> LR, 
        std::function<symmetry_table_type(size_t)> get_sym,
        const std::vector<label_type>& labels, const MatrixXd& inf_mat)
{
    symmetry_mask_type ret = symmetry_mask_type::build(LR.first[0], LR.second[0], get_sym(0).table);
    for (size_t i = 1; i < LR.first.size(); ++i) {
        ret = ret & symmetry_mask_type::build(LR.first[i], LR.second[i], get_sym(i).table);
        if (ret.is_invalid()) {
            MSG_DEBUG("<sym invalid after " << i << " steps>");
            return {false, {}};
        }
    }
    return symmetry_table_type::build(ret.as_permutation(), labels, inf_mat, false);
}


inline
symmetry_group_type
combine_groups(
        std::pair<std::vector<size_t>, std::vector<size_t>> LR, 
        std::function<const symmetry_group_type&(size_t)> get_group,
        const std::vector<label_type>& labels, const MatrixXd& inf_mat)
{
    std::vector<symmetry_group_type::const_iterator> begins, ends, iterators;
    begins.resize(LR.first.size());
    iterators.resize(LR.first.size());
    ends.resize(LR.first.size());
    for (size_t i = 0; i < LR.first.size(); ++i) {
        MSG_DEBUG("group #" << i);
        MSG_DEBUG(get_group(i));
        iterators[i] = begins[i] = get_group(i).begin();
        ends[i] = get_group(i).end();
    }

    auto
        next = [&] ()
        {
            auto i = iterators.rbegin();
            auto j = iterators.rend();
            auto e = ends.rbegin();
            auto b = begins.rbegin();
            while (true) {
                if (i == j) {
                    return false;
                }
                ++*i;
                if (*i == *e) {
                    *i = *b;
                    ++i;
                    ++b;
                    ++e;
                } else {
                    return true;
                }
            }
        };

    std::function<const symmetry_table_type&(size_t)>
        get_sym = [&] (size_t i)
        {
            return *iterators[i];
        };

    symmetry_group_type ret(labels);

    do {
        auto result = combine_symmetries(LR, get_sym, labels, inf_mat);
        if (result.first) {
            ret.insert(result.second);
        }
    } while (next());

    return ret;
}


inline
symmetry_group_type
combine_groups(
        std::pair<std::vector<size_t>, std::vector<size_t>> LR, 
        const std::vector<symmetry_group_type>& groups,
        const std::vector<label_type>& labels, const MatrixXd& inf_mat)
{
    std::vector<symmetry_group_type::const_iterator> begins, ends, iterators;
    begins.resize(LR.first.size());
    iterators.resize(LR.first.size());
    ends.resize(LR.first.size());
    for (size_t i = 0; i < LR.first.size(); ++i) {
        MSG_DEBUG("group #" << i);
        MSG_DEBUG(groups[i]);
        MSG_QUEUE_FLUSH();
        iterators[i] = begins[i] = groups[i].begin();
        ends[i] = groups[i].end();
    }

    auto
        next = [&] ()
        {
            auto i = iterators.rbegin();
            auto j = iterators.rend();
            auto e = ends.rbegin();
            auto b = begins.rbegin();
            while (true) {
                if (i == j) {
                    return false;
                }
                ++*i;
                if (*i == *e) {
                    *i = *b;
                    ++i;
                    ++b;
                    ++e;
                } else {
                    return true;
                }
            }
        };

    std::function<symmetry_table_type(size_t)>
        get_sym = [&] (size_t i)
        {
            return *iterators[i];
        };

    symmetry_group_type ret(labels);

    do {
        auto result = combine_symmetries(LR, get_sym, labels, inf_mat);
        if (result.first) {
            ret.insert(result.second);
        } else {
            MSG_DEBUG("<couldn't build sym>");
        }
    } while (next());

    return ret;
}

1237
1238
#endif  /* 0 */

Damien Leroux's avatar
Damien Leroux committed
1239
1240
1241
1242


#endif