-
Notifications
You must be signed in to change notification settings - Fork 2
/
dsl.cpp
2665 lines (2243 loc) · 98.7 KB
/
dsl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
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
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
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
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
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
#include <array>
#include <algorithm>
#include <atomic>
#include <bitset>
#include <climits>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <functional>
#include <limits>
#include <numeric>
#include <unordered_map>
#include <unordered_set>
#include <vector>
const int NUM_COLORS = 10;
const int MAX_DIMS = 30;
#include "json11.hpp"
#include "helpers.h"
#if !ENABLE_MAIN
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
#endif // ENABLE_MAIN
#include "static_array.h"
#include "algorithms.h"
#include "dsl.h"
#include "json11.cpp"
struct Point {
uint x, y;
Point() : x{}, y{} {}
Point(uint a, uint b) : x{a}, y{b} {}
bool operator <(const Point &another) const {
return (x != another.x) ? x < another.x : y < another.y;
}
};
using Island = std::vector<Point>;
const int MAX_AREA = MAX_DIMS * MAX_DIMS;
enum RuleType {
COPY_COLOR_BY_DIRECTION,
CORNER_CHECK,
NBH_CHECK,
DIRECT_CHECK,
INDIRECT_CHECK,
COLOR_DISTRIBUTION,
FLIP,
ROTATE,
DISTRIBUTE_FROM_BORDER,
COLOR_FOR_INNERS,
DRAW_LINES,
DRAW_LINE_TO,
DISTRIBUTE_COLORS,
UNITY,
SPLIT_BY_H,
SPLIT_BY_W,
MAP_COLOR,
CROP_EMPTY,
CROP_FIGURE,
MAKE_HOLES,
GRAVITY,
CELLS,
FIGURES,
NOTHING,
COLOR_FIGURES,
CELLWISE_OR,
OUTPUT_FIRST,
OUTPUT_LAST,
ALIGN_PATTERN,
REDUCE,
MACRO_MULTIPLY,
};
enum Direction {
// Next 8 values must occupy places from 0 to 7
TOP,
BOTTOM,
LEFT,
RIGHT,
TOP_LEFT,
BOTTOM_LEFT,
TOP_RIGHT,
BOTTOM_RIGHT,
EVERYWHERE,
HORIZONTAL,
VERTICAL,
HORVER,
DIAGONAL,
NONE,
BORDER,
COLOR,
BIGGEST,
SMALLEST,
ALL,
INDEX,
LAST,
VER,
HOR,
};
enum MergeRule {
OR,
AND,
EQUAL,
XOR,
};
enum MacroType {
GLOBAL_RULE,
GLOBAL_INTERACTION_RULE,
CA_RULE,
};
#include "dsl_tables.h"
struct Rule {
MacroType macro_type;
std::bitset<NUM_COLORS> ignore_colors;
RuleType type;
Direction direction;
std::bitset<NUM_COLORS> copy_color;
data_type look_back_color;
std::bitset<NUM_COLORS> nbh_check_colors;
data_type nbh_check_out;
uint nbh_check_sum;
int check_in_empty;
data_type color_in;
data_type color_out;
std::bitset<NUM_COLORS> colors;
data_type start_by_color;
data_type not_stop_by_color;
data_type with_color;
Direction mode;
int horizontally;
int vertically;
data_type intersect;
RuleType gravity_type;
bool look_at_what_to_move;
data_type color_what;
Direction direction_type;
Direction direction_border;
data_type direction_color;
int steps_limit;
MergeRule merge_rule;
Direction sort;
data_type allow_color;
Direction apply_to;
data_type apply_to_index;
Direction how;
data_type rotations_count;
data_type dif_c_edge;
data_type k;
data_type k1;
data_type k2;
data_type skip_color;
data_type not_stop_by_color_and_skip;
data_type fill_with_color;
};
using Rules = std::vector<Rule>;
struct AutomatonParams {
Rules global_rules;
Rules ca_rules;
Rule split_rule;
Rule merge_rule;
};
enum NeisMode {
NeisAll,
NeisDirect,
NeisIndirect,
NeisUpLeft,
NeisUpRight,
NeisBottomLeft,
NeisBottomRight,
};
using NeisArray = static_array<data_type, 8>; // there could be 8 neighbours at most
std::vector<Island> get_connectivity_info(const AutomatonState &input, bool ignore_black,
bool edge_for_difcolors = false);
AutomatonState apply_rule(const AutomatonState &input, const Rule &rule);
AutomatonState compute_parametrized_automata(const AutomatonState &input, const Rules &rules);
const std::array<std::array<int, 2>, 8> all_neis = {{
{-1, 0}, {-1, -1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}}};
const std::array<std::array<int, 2>, 4> direct_neis = {{
{-1, 0}, {0, -1}, {1, 0}, {0, 1}}};
const std::array<std::array<int, 2>, 4> indirect_neis = {{
{-1, -1}, {1, -1}, {1, 1}, {-1, 1}}};
const std::array<std::array<int, 2>, 3> up_left_neis = {{
{-1, -1}, {-1, 0}, {0, -1}}};
const std::array<std::array<int, 2>, 3> up_right_neis = {{
{-1, 1}, {-1, 0}, {0, 1}}};
const std::array<std::array<int, 2>, 3> btm_left_neis = {{
{1, -1}, {1, 0}, {0, -1}}};
const std::array<std::array<int, 2>, 3> btm_right_neis = {{
{1, 1}, {1, 0}, {0, 1}}};
NeisArray get_neighbours(const AutomatonState &state, int i, int j, NeisMode mode) {
NeisArray res;
const std::array<int, 2> *neis = nullptr;
uint neis_count = 0;
switch (mode) {
case NeisAll:
neis = all_neis.data(), neis_count = all_neis.size();
break;
case NeisDirect:
neis = direct_neis.data(), neis_count = direct_neis.size();
break;
case NeisIndirect:
neis = indirect_neis.data(), neis_count = indirect_neis.size();
break;
case NeisUpLeft:
neis = up_left_neis.data(), neis_count = up_left_neis.size();
break;
case NeisUpRight:
neis = up_right_neis.data(), neis_count = up_right_neis.size();
break;
case NeisBottomLeft:
neis = btm_left_neis.data(), neis_count = btm_left_neis.size();
break;
case NeisBottomRight:
neis = btm_right_neis.data(), neis_count = btm_right_neis.size();
break;
default:
assert(false);
}
for (uint k = 0; k < neis_count; k++) {
uint a = i + neis[k][0], b = j + neis[k][1];
if (a < state.shape[0] && b < state.shape[1]) {
res.push_back(state(a, b));
}
}
return res;
}
// def apply_split_rule(input, hidden, split_rule):
std::vector<AutomatonState> apply_split_rule(const AutomatonState &input, const Rule &split_rule) {
// if split_rule['type'] == 'nothing':
// return [(input, hidden)]
if (split_rule.type == NOTHING) {
return {input};
}
// if split_rule['type'] == 'macro_multiply':
// ks = split_rule['k1'] * split_rule['k2']
// grids = [(np.copy(input), np.copy(hidden)) for _ in range(ks)]
// return grids
if (split_rule.type == MACRO_MULTIPLY) {
std::vector<AutomatonState> res;
uint ks = split_rule.k1 * split_rule.k2;
res.reserve(ks);
for (uint i = 0; i < ks; i++) {
res.push_back(input);
}
return res;
}
// split_rule['type'] = 'figures'
// dif_c_edge = split_rule['type'] == 'figures'
// communities = get_connectivity_info(input, ignore_black=True, edge_for_difcolors=dif_c_edge)
// communities = sorted(communities, key = len)
// if split_rule['sort'] == 'biggest':
// communities = communities[::-1]
bool dif_c_edge = split_rule.type == FIGURES;
std::vector<Island> communities = get_connectivity_info(input, true, dif_c_edge);
if (split_rule.sort == BIGGEST) {
std::reverse(communities.begin(), communities.end());
}
// grids = [(np.zeros_like(input), np.zeros_like(hidden)) for _ in range(len(communities))]
std::vector<AutomatonState> grids;
grids.reserve(communities.size());
// for i in range(len(communities)):
// for point in communities[i]:
// grids[i][0][point] = input[point]
for (uint i = 0; i < communities.size(); i++) {
grids.emplace_back(input.shape);
AutomatonState &last = grids.back();
for (const Point &p : communities[i]) {
last(p.x, p.y) = input(p.x, p.y);
}
}
if (grids.empty()) {
grids.push_back(input);
}
return grids;
}
// def apply_merge_rule(grids, merge_rule):
AutomatonState apply_merge_rule(std::vector<AutomatonState> grids, const Rule &merge_rule,
const Rule &split_rule) {
// if split_rule['type'] == 'macro_multiply':
// shape_base = grids[0][0].shape
// shapes = [arr[0].shape for arr in grids]
// if not np.array([shape_base == sh for sh in shapes]).all():
// return np.zeros((1))
//
// ks_1 = split_rule['k1']
// ks_2 = split_rule['k2']
// output = np.zeros((shape_base[0] * ks_1, shape_base[1] * ks_2))
// for k1 in range(ks_1):
// for k2 in range(ks_2):
// output[(k1*shape_base[0]):((k1+1) * shape_base[0]),
// (k2*shape_base[1]):((k2+1) * shape_base[1])] = grids[k1*ks_2 + k2][0]
//
// return output
if (split_rule.type == MACRO_MULTIPLY) {
const auto &shape_base = grids[0].shape;
for (uint i = 1; i < grids.size(); i++) {
if (grids[i].shape != shape_base) {
return AutomatonState{1, 1};
}
}
uint ks_1 = split_rule.k1, ks_2 = split_rule.k2;
AutomatonState output{shape_base[0] * ks_1, shape_base[1] * ks_2};
for (uint k1 = 0; k1 < ks_1; k1++) {
for (uint k2 = 0; k2 < ks_2; k2++) {
const AutomatonState &grid = grids[(k1 * ks_2 + k2) % grids.size()];
for (uint i = 0; i < shape_base[0]; i++) {
for (uint j = 0; j < shape_base[1]; j++) {
output(k1 * shape_base[0] + i, k2 * shape_base[1] + j) = grid(i, j);
}
}
}
}
return output;
}
// if merge_rule['type'] == 'cellwise_or':
// output = np.zeros_like(grids[0][0])
// for i in np.arange(len(grids))[::-1]:
// if grids[i][0].shape == output.shape:
// output[grids[i][0]>0] = grids[i][0][grids[i][0]>0]
// return output
// elif merge_rule['type'] == 'output_first':
// output = grids[0][0]
// elif merge_rule['type'] == 'output_last':
// output = grids[-1][0]
// return output
if (merge_rule.type == CELLWISE_OR) {
AutomatonState output{grids[0].shape};
for (uint grid_idx = grids.size() - 1; grid_idx != UINT_MAX; grid_idx--) {
if (grids[grid_idx].shape == output.shape) {
for (uint i = 0; i < grids[grid_idx].shape[0]; i++) {
for (uint j = 0; j < grids[grid_idx].shape[1]; j++) {
data_type col = grids[grid_idx](i, j);
if (col > 0) {
output(i, j) = col;
}
}
}
}
}
return output;
} else if (merge_rule.type == OUTPUT_FIRST) {
return grids.front();
} else if (merge_rule.type == OUTPUT_LAST) {
return grids.back();
} else {
assert(false);
return grids.front();
}
}
// def apply_interaction_rule(grids, rule):
void apply_interaction_rule(std::vector<AutomatonState> &grids, const Rule &rule) {
// if rule['type'] == 'align_pattern':
assert(rule.type == ALIGN_PATTERN);
// allow_rotation = rule['allow_rotation']
// if len(grids) > 5:
// return grids
const int MAX_GRIDS_FOR_APPLY_RULE = 5;
if (grids.size() > MAX_GRIDS_FOR_APPLY_RULE) {
return;
}
// for index_from in range(len(grids)):
// for index_to in range(index_from+1, len(grids)):
for (uint index_from = 0; index_from < grids.size(); index_from++) {
for (uint index_to = index_from + 1; index_to < grids.size(); index_to++) {
// input_i = grids[index_from][0]
// input_j = grids[index_to][0]
AutomatonState &input_i = grids[index_from];
AutomatonState &input_j = grids[index_to];
// i_nonzero_rows = np.arange(input_i.shape[0])[np.max(input_i>0, axis=1)]
// i_nonzero_columns = np.arange(input_i.shape[1])[np.max(input_i>0, axis=0)]
// j_nonzero_rows = np.arange(input_j.shape[0])[np.max(input_j>0, axis=1)]
// j_nonzero_columns = np.arange(input_j.shape[1])[np.max(input_j>0, axis=0)]
//
// if i_nonzero_rows.shape[0] == 0 or i_nonzero_columns.shape[0] == 0 or
// j_nonzero_rows.shape[0] == 0 or j_nonzero_columns.shape[0] == 0:
// continue
//
// i_minrow = np.min(i_nonzero_rows)
// i_mincol = np.min(i_nonzero_columns)
// i_maxrow = np.max(i_nonzero_rows) + 1
// i_maxcol = np.max(i_nonzero_columns) + 1
// j_minrow = np.min(j_nonzero_rows)
// j_mincol = np.min(j_nonzero_columns)
// j_maxrow = np.max(j_nonzero_rows) + 1
// j_maxcol = np.max(j_nonzero_columns) + 1
// This is not optimal:
//
// static_array<uint, MAX_DIMS> i_nonzero_rows = get_nonzero_rows(input_i);
// static_array<uint, MAX_DIMS> i_nonzero_columns = get_nonzero_cols(input_i);
// static_array<uint, MAX_DIMS> j_nonzero_rows = get_nonzero_rows(input_j);
// static_array<uint, MAX_DIMS> j_nonzero_columns = get_nonzero_cols(input_j);
//
// if (i_nonzero_rows.empty() or i_nonzero_columns.empty() or
// j_nonzero_rows.empty() or j_nonzero_columns.empty()) {
// continue;
// }
uint i_minrow, i_mincol, i_maxrow, i_maxcol;
get_bounding_box(i_minrow, i_mincol, i_maxrow, i_maxcol, input_i);
if (i_minrow >= i_maxrow or i_mincol >= i_maxcol) {
continue;
}
uint j_minrow, j_mincol, j_maxrow, j_maxcol;
get_bounding_box(j_minrow, j_mincol, j_maxrow, j_maxcol, input_j);
if (j_minrow >= j_maxrow or j_mincol >= j_maxcol) {
continue;
}
// figure_to_align = input_i[i_minrow:i_maxrow, i_mincol:i_maxcol]
// figure_target = input_j[j_minrow:j_maxrow, j_mincol:j_maxcol]
std::array<uint, 2> figure_to_align_shape = {i_maxrow - i_minrow, i_maxcol - i_mincol};
std::array<uint, 2> figure_target_shape = {j_maxrow - j_minrow, j_maxcol - j_mincol};
// best_fit = 0
// best_i_fit, best_j_fit = -1, -1
uint best_fit = 0, best_i_fit = 0, best_j_fit = 0;
// if figure_to_align.shape[0] < figure_target.shape[0] or figure_to_align.shape[1] < figure_target.shape[1]:
// continue
if (figure_to_align_shape[0] < figure_target_shape[0] or figure_to_align_shape[1] < figure_target_shape[1]) {
continue;
// else:
} else {
// for i_start in range((figure_to_align.shape[0] - figure_target.shape[0])+1):
// for j_start in range((figure_to_align.shape[1] - figure_target.shape[1])+1):
// fig_1 = figure_to_align[i_start:(i_start + figure_target.shape[0]), j_start:(j_start + figure_target.shape[1])]
// if np.logical_and(
// np.logical_and(figure_target > 0, figure_target!=rule['allow_color']),
// figure_target != fig_1).any():
// continue
// fit = np.sum(figure_target==fig_1)
// if fit > best_fit:
// best_i_fit, best_j_fit = i_start, j_start
// best_fit = fit
for (uint i_start = 0; i_start < figure_to_align_shape[0] - figure_target_shape[0] + 1; i_start++) {
for (uint j_start = 0; j_start < figure_to_align_shape[1] - figure_target_shape[1] + 1; j_start++) {
uint fit = 0;
for (uint a = 0; a < figure_target_shape[0]; a++) {
for (uint b = 0; b < figure_target_shape[1]; b++) {
data_type target_col = input_j(j_minrow + a, j_mincol + b);
data_type source_col = input_i(i_minrow + i_start + a,
i_mincol + j_start + b);
if (target_col > 0 and target_col != rule.allow_color and target_col != source_col) {
goto reject;
}
fit += source_col == target_col;
}
}
if (fit > best_fit) {
best_fit = fit, best_i_fit = i_start, best_j_fit = j_start;
}
reject: ;
}
}
// if best_fit == 0:
// continue
if (best_fit == 0) {
continue;
}
// imin = j_minrow - best_i_fit
// imax = j_minrow - best_i_fit + figure_to_align.shape[0]
// jmin = j_mincol - best_j_fit
// jmax = j_mincol - best_j_fit + figure_to_align.shape[1]
int imin = j_minrow - best_i_fit;
int imax = j_minrow - best_i_fit + figure_to_align_shape[0];
int jmin = j_mincol - best_j_fit;
int jmax = j_mincol - best_j_fit + figure_to_align_shape[1];
// begin_i = max(imin, 0)
// begin_j = max(jmin, 0)
// end_i = min(imax, input_j.shape[0])
// end_j = min(jmax, input_j.shape[1])
int begin_i = std::max(imin, 0);
int begin_j = std::max(jmin, 0);
uint end_i = std::min(uint(imax), input_j.shape[0]);
uint end_j = std::min(uint(jmax), input_j.shape[1]);
// i_fig_begin = (begin_i-imin)
// i_fig_end = figure_to_align.shape[0]-(imax-end_i)
// j_fig_begin = (begin_j-jmin)
// j_fig_end = figure_to_align.shape[1]-(jmax-end_j)
uint i_fig_begin = (begin_i-imin);
uint i_fig_end = figure_to_align_shape[0]-(imax-end_i);
uint j_fig_begin = (begin_j-jmin);
uint j_fig_end = figure_to_align_shape[1]-(jmax-end_j);
// if rule['fill_with_color'] == 0:
// input_j[begin_i:end_i, begin_j:end_j] = figure_to_align[i_fig_begin:i_fig_end, j_fig_begin:j_fig_end]
// else:
// for i, j in product(range(end_i-begin_i + 1), range(end_j-begin_j + 1)):
// if input_j[begin_i + i, begin_j + j] == 0:
// input_j[begin_i + i, begin_j + j] = rule['fill_with_color'] * (figure_to_align[i_fig_begin + i, j_fig_begin + j])
if (rule.fill_with_color == 0) {
for (uint a = i_fig_begin; a < i_fig_end; a++) {
for (uint b = j_fig_begin; b < j_fig_end; b++) {
input_j(begin_i - i_fig_begin + a, begin_j - j_fig_begin + b) = \
input_i(i_minrow + a, i_mincol + b);
}
}
} else {
for (uint a = i_fig_begin; a < i_fig_end; a++) {
for (uint b = j_fig_begin; b < j_fig_end; b++) {
data_type &dst = input_j(begin_i - i_fig_begin + a,
begin_j - j_fig_begin + b);
if (dst == 0) {
dst = rule.fill_with_color * input_i(i_minrow + a, i_mincol + b);
}
}
}
}
}
}
}
}
AutomatonState trace_param_automata(const AutomatonState &input, const AutomatonParams ¶ms,
int n_iter = 25) {
// Execute an automata and return all the intermediate states.
//
// arguments:
// input: initial automaton state
// params: automaton rules: global and CA
// returns:
// final automaton state
//
std::vector<AutomatonState> grids = apply_split_rule(input, params.split_rule);
for (const Rule &rule : params.global_rules) {
for (uint i = 0; i < grids.size(); i++) {
if (rule.macro_type == GLOBAL_RULE and (rule.apply_to == ALL or
rule.apply_to == INDEX and i == rule.apply_to_index % grids.size() or
rule.apply_to == LAST and i == grids.size() - 1)) {
grids[i] = apply_rule(grids[i], rule);
} else if (rule.macro_type == GLOBAL_INTERACTION_RULE) {
apply_interaction_rule(grids, rule);
}
}
}
for (uint i = 0; i < grids.size(); i++) {
AutomatonState &input = grids[i];
for (int it = 0; it < n_iter; it++) {
AutomatonState output = compute_parametrized_automata(input, params.ca_rules);
if (input == output) {
break;
}
input = output;
}
}
return apply_merge_rule(grids, params.merge_rule, params.split_rule);
}
// def compute_parametrized_automata(input, hidden_i, rules):
AutomatonState compute_parametrized_automata(const AutomatonState &input, const Rules &rules) {
// output = np.zeros_like(input, dtype=int)
AutomatonState output{input.shape};
// for i, j in product(range(input.shape[0]), range(input.shape[1])):
for (uint i = 0; i < input.shape[0]; i++) {
for (uint j = 0; j < input.shape[1]; j++) {
// i_c = input[i, j]
int i_c = input(i, j);
// cells which are adjacent to the current one
// i_nbh = get_neighbours(input, i, j)
// i_direct_nbh = {k: v for k, v in i_nbh.items() if k in {(1, 0), (-1, 0), (0, 1), (0, -1)}}
// i_indirect_nbh = {k: v for k, v in i_nbh.items() if k in {(1, 1), (-1, -1), (-1, 1), (1, -1)}}
NeisArray i_nbh = get_neighbours(input, i, j, NeisAll);
NeisArray i_direct_nbh = get_neighbours(input, i, j, NeisDirect);
NeisArray i_indirect_nbh = get_neighbours(input, i, j, NeisIndirect);
// is_top_b, is_bottom_b = i == 0, i == input.shape[0] - 1
// is_left_b, is_right_b = j == 0, j == input.shape[1] - 1
// is_b = is_top_b or is_bottom_b or is_left_b or is_right_b
bool is_top_b = i == 0, is_bottom_b = i == input.shape[0] - 1;
bool is_left_b = j == 0, is_right_b = j == input.shape[1] - 1;
// bool is_b = is_top_b or is_bottom_b or is_left_b or is_right_b;
// if i_c > 0:
if (i_c > 0) {
// output[i, j] = i_c
output(i, j) = i_c;
}
// for rule in rules:
for (const Rule &rule : rules) {
// if i_c in rule["ignore_color"]:
if (rule.ignore_colors.test(i_c)) {
continue;
}
switch (rule.type) {
// if rule["type"] == "copy_color_by_direction":
case COPY_COLOR_BY_DIRECTION: {
// if rule['direction'] == 'bottom' or rule['direction'] == 'everywhere':
// if not is_top_b and input[i - 1, j] in rule['copy_color'] and
// (i == 1 or input[i - 2, j] == rule['look_back_color']):
// output[i, j] = input[i - 1, j]
// break
if (rule.direction == BOTTOM or rule.direction == EVERYWHERE) {
if (!is_top_b && rule.copy_color.test(input(i - 1, j)) and
(i == 1 or input(i - 2, j) == rule.look_back_color)) {
output(i, j) = input(i - 1, j);
goto done;
}
}
// if rule["direction"] == "top" or rule["direction"] == "everywhere":
// if not is_bottom_b and input[i + 1, j] in rule["copy_color"] and
// (i == input.shape[0] - 2 or input[i + 2, j] == rule["look_back_color"]):
// output[i, j] = input[i + 1, j]
// break
if (rule.direction == TOP or rule.direction == EVERYWHERE) {
if (!is_bottom_b and rule.copy_color.test(input(i + 1, j)) and
(i == input.shape[0] - 2 or input(i + 2, j) == rule.look_back_color)) {
output(i, j) = input(i + 1, j);
goto done;
}
}
// if rule["direction"] == "right" or rule["direction"] == "everywhere":
// if not is_left_b and input[i, j - 1] in rule["copy_color"] and
// (j == 1 or input[i, j - 2] == rule["look_back_color"]):
// (j == 1 or input[i, j - 2] == rule["look_back_color"]):
// output[i, j] = input[i, j - 1]
// break
if (rule.direction == RIGHT or rule.direction == EVERYWHERE) {
if (!is_left_b and rule.copy_color.test(input(i, j -1)) and
(j == 1 or input(i, j -2) == rule.look_back_color)) {
output(i, j) = input(i, j - 1);
goto done;
}
}
// if rule["direction"] == "left" or rule["direction"] == "everywhere":
// if not is_right_b and input[i, j + 1] in rule["copy_color"] and
// (j == input.shape[1] - 2 or input[i, j + 2] == rule["look_back_color"]):
// output[i, j] = input[i, j + 1]
// break
if (rule.direction == LEFT or rule.direction == EVERYWHERE) {
if (!is_right_b and rule.copy_color.test(input(i, j + 1)) and
(j == input.shape[1] - 2 or input(i, j + 2) == rule.look_back_color)) {
output(i, j) = input(i, j + 1);
goto done;
}
}
}
break;
// elif rule["type"] == "corner_check":
case CORNER_CHECK: {
// color_nbh = rule["nbh_check_colors"]
// sum_nbh = 3
// out_nbh = rule["nbh_check_out"]
const std::bitset<NUM_COLORS> &color_nbh = rule.nbh_check_colors;
uint sum_nbh = 3;
data_type out_nbh = rule.nbh_check_out;
// if sum(1 for v in i_nbh.values() if v in color_nbh) < 3:
if (intersection_size(i_nbh, color_nbh) < 3) {
continue;
}
// i_uplecorner_nbh = {k: v for k, v in i_nbh.items() if k in {(-1, -1), (-1, 0), (0, -1)}}
// i_upricorner_nbh = {k: v for k, v in i_nbh.items() if k in {(-1, 1), (-1, 0), (0, 1)}}
// i_dolecorner_nbh = {k: v for k, v in i_nbh.items() if k in {(1, -1), (1, 0), (0, -1)}}
// i_doricorner_nbh = {k: v for k, v in i_nbh.items() if k in {(1, 1), (1, 0), (0, 1)}}
//
// did_something = False
// for corner_idx in [i_uplecorner_nbh, i_upricorner_nbh, i_dolecorner_nbh, i_doricorner_nbh]:
// for color in color_nbh:
// if sum(1 for v in corner_idx.values() if v == color) == sum_nbh:
// output[i, j] = out_nbh
// did_something = True
// break
// if did_something:
// break
// if did_something:
// break
// for (data_type color: color_nbh) {
for (data_type color = 0; color < NUM_COLORS; color++) {
if (color_nbh.test(color) and (
get_neighbours(input, i, j, NeisUpLeft).count(color) == sum_nbh or
get_neighbours(input, i, j, NeisUpRight).count(color) == sum_nbh or
get_neighbours(input, i, j, NeisBottomLeft).count(color) == sum_nbh or
get_neighbours(input, i, j, NeisBottomRight).count(color) == sum_nbh)) {
output(i, j) = out_nbh;
goto done;
}
}
}
break;
// elif rule["type"] == "nbh_check":
case NBH_CHECK: {
// color_nbh = rule["nbh_check_colors"]
// sum_nbh = rule["nbh_check_sum"]
// out_nbh = rule["nbh_check_out"]
//
// proper_nbhs = i_nbh.values()
// if sum(1 for v in proper_nbhs if v in color_nbh) > sum_nbh:
// output[i, j] = out_nbh
// break
const std::bitset<NUM_COLORS> &color_nbh = rule.nbh_check_colors;
uint sum_nbh = rule.nbh_check_sum;
data_type out_nbh = rule.nbh_check_out;
if (i_nbh.count([&](data_type v) { return color_nbh.test(v); }) > sum_nbh) {
output(i, j) = out_nbh;
goto done;
}
}
break;
// elif rule["type"] == "direct_check":
case DIRECT_CHECK: {
// color_nbh = rule["nbh_check_colors"]
// sum_nbh = rule["nbh_check_sum"]
// out_nbh = rule["nbh_check_out"]
//
// proper_nbhs = i_direct_nbh.values()
// if sum(1 for v in proper_nbhs if v in color_nbh) > sum_nbh:
// output[i, j] = out_nbh
// break
const std::bitset<NUM_COLORS> &color_nbh = rule.nbh_check_colors;
uint sum_nbh = rule.nbh_check_sum;
data_type out_nbh = rule.nbh_check_out;
if (i_direct_nbh.count([&](data_type v) { return color_nbh.test(v); }) > sum_nbh) {
output(i, j) = out_nbh;
goto done;
}
}
break;
// elif rule["type"] == "indirect_check":
case INDIRECT_CHECK: {
// color_nbh = rule["nbh_check_colors"]
// sum_nbh = rule["nbh_check_sum"]
// out_nbh = rule["nbh_check_out"]
//
// proper_nbhs = i_indirect_nbh.values()
// if sum(1 for v in proper_nbhs if v in color_nbh) > sum_nbh:
// output[i, j] = out_nbh
// break
const std::bitset<NUM_COLORS> &color_nbh = rule.nbh_check_colors;
uint sum_nbh = rule.nbh_check_sum;
data_type out_nbh = rule.nbh_check_out;
if (i_indirect_nbh.count([&](data_type v) { return color_nbh.test(v); }) > sum_nbh) {
output(i, j) = out_nbh;
goto done;
}
}
break;
// elif rule["type"] == "color_distribution":
case COLOR_DISTRIBUTION: {
// directions = ["top", "bottom", "left", "right", "topleft", "bottomleft", "topright", "bottomright"]
// not_border_conditions =
// [
// not is_top_b, not is_bottom_b, not is_left_b, not is_right_b,
// not is_top_b and not is_left_b,
// not is_bottom_b and not is_left_b,
// not is_top_b and not is_right_b,
// not is_bottom_b and not is_right_b
// ]
// index_from =
// [ (i-1, j), (i+1, j), (i, j-1), (i, j+1),
// (i-1, j-1), (i+1, j-1), (i-1, j+1), (i+1, j+1) ]
//
// for i_dir, direction in enumerate(directions):
// if rule["direction"] == direction:
// if not_border_conditions[i_dir]:
// if (rule["check_in_empty"] == 1 and input[index_from[i_dir]] > 0) or
// (rule["check_in_empty"] == 0 and input[index_from[i_dir]] == rule["color_in"]):
// output[i, j] = rule["color_out"]
std::array<bool, 8> border_conditions = {
not is_top_b, not is_bottom_b, not is_left_b, not is_right_b,
not is_top_b and not is_left_b,
not is_bottom_b and not is_left_b,
not is_top_b and not is_right_b,
not is_bottom_b and not is_right_b
};
static const std::array<std::array<int, 2>, 8> index_from = {{
{-1, 0}, {+1, 0}, {0, -1}, {0, +1},
{-1, -1}, {+1, -1}, {-1, +1}, {+1, +1}}};
assert(rule.direction < border_conditions.size());
if (border_conditions[rule.direction]) {
const std::array<int, 2> &offsets = index_from[rule.direction];
data_type col = input(offsets[0] + i, offsets[1] + j);
if (rule.check_in_empty and col > 0 or
!rule.check_in_empty and col == rule.color_in) {
output(i, j) = rule.color_out;
goto done;
}
}
}
break;
default:
assert(false);
}
}
done:;
}
}
return output;
}
struct UnionFind {
static_array<uint, MAX_AREA> area, parent;
UnionFind(uint sz) : area(sz, 1), parent(sz) {
for (uint i = 0; i < sz; i++) {
parent[i] = i;
}
}
uint find(uint x) {
uint root = x;
while (parent[root] != root) {
root = parent[root];
}
while (parent[x] != root) {
uint next_parent = parent[x];
parent[x] = root;
x = next_parent;
}
return parent[x];
}
void unite(uint u, uint v) {
int root_u = find(u), root_v = find(v);
if (root_u != root_v) {
int area_u = area[u], area_v = area[v];
if (area_u < area_v) {
std::swap(root_u, root_v);
}
parent[root_v] = root_u;
area[root_u] = area_u + area_v;
}
}
};
std::vector<Island> get_connectivity_info(const AutomatonState &input, bool ignore_black,
bool edge_for_difcolors) {
uint size = input.color.size();
UnionFind union_find(size);
// combine same colors
for (uint i = 0; i < input.shape[0]; i++) {
for (uint j = 0; j < input.shape[1]; j++) {
data_type col = input(i, j);
for (uint k = 0; k < all_neis.size(); k++) {
uint u = i + all_neis[k][0], v = j + all_neis[k][1];
// if u >= 0 and u < nrows and v >= 0 and v < ncols and
// (color[u, v] == color[i, j] or
// (edge_for_difcolors and (color[u, v]>0) == (color[i, j]>0))):
if (u < input.shape[0] and v < input.shape[1] and (input(u, v) == col or
edge_for_difcolors and (input(u, v) > 0) == (col > 0))) {
union_find.unite(u * input.shape[1] + v, i * input.shape[1] + j);
}
}
}
}