aboutsummaryrefslogtreecommitdiff
path: root/Carpet/CarpetLib/src/bboxset2.hh
blob: bb4893db9234d7c5a71ec0c15fb43f66e3c64d03 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
#ifndef BBOXSET2_HH
#define BBOXSET2_HH

#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <utility>
#include <vector>

#include <cctk.h>

#include "bbox.hh"
#include "defs.hh"
#include "vect.hh"

using namespace std;



/* A note on CARPET_AVOID_LAMBDA:
   
   When this macro is defined, then we cannot use C++11 lambdas.
   Instead, we use macros, both for the lambdas that we would
   otherwise create, and for the functions to which the lambdas would
   otherwise be passed. The functions taking lambdas as arguments
   could also be re-written as iterators, but we don't do this because
   this would be significantly more complex. Changing these functions
   and the lambdas to macros is a straightforward syntactical
   replacement.
   
   The macros can behave as expressions or as statements. Macros that
   behave like an expression can easily be created via the ({ ... })
   GNU extension, which is supported by almost all compilers.
   Unfortunately, e.g. the Blue Gene/Q IBM compiler does not seem to
   handle these correctly when they contain variable declarations
   requiring a non-trivial constructor. Therefore, we use macros that
   behave like statements.
   
   The functions that would otherwise take a lambda as argument are
   turned into a macro in the standard manner:
   - Name becomes all upper case
   - Name may have a suffix added since macros cannot be overloaded
   - Macro is wrapped in do { ... } while (0)
   - Macro arguments are safely accessed by defining local variables,
     and assigning the macro argument to them. Note that this is
     slightly non-trivial: the macro argument name must not be used
     elsewere (since it would otherwise be replaced as well), so we
     append an underscore to the original function argument name. If
     the macro argument that is passed has the name name as the local
     variable in which it is captured, then there is a conflict, so we
     choose a local variable name that has two underscores appended.
     Since this looks ugly, we then define a second local variable
     (without underscores) and assign in the double-underscore local
     variable.
   - Calling a lambda is also non-trivial, since the respective macro
     argument will be a sequence of statements, not a function-like
     object to which arguments can be passed. Instead, we store the
     arguments that the lambda would receive in local variables
     numbered _1, _2, ..., and define (if necessary) a local variable
     _0 that will hold the result. To keep our namespace clean, we put
     the "lambda call" into curly braces.
   
   The lambda definitions are then always located inside a macro call
   as just described. The actual lambda definition becomes a sequence
   of statements that is one argument to the macro call. (Note that
   one cannot have top-level commas in macro calls, since these would
   separate macro arguments. Luckily, top-level commas do not often
   appear in a sequence of statements.) Since the arguments will be
   passed in variables called _1, _2, ..., it is convenient to define
   local variables and assign these variables to them. Note also that
   the return value needs to be assigned to a variable called _0.
   
   Alternative approaches (that did not work) include:
   - Define local classes that can be called like a function. This
     does not work because these are local classes, and hence cannot
     be used as template argument.
   - Define local classes that can be called like a function, and make
     them a sub-class of an abstract base class. Instead of using
     templates, change the functions that accept lambda arguments from
     templates to using virtual function calls to evaluate the lambda.
     This does not work because ... (why did this not work?)
   - Use Boost lambdas. This does not work because these are intended
     for short expressions, and do not work for longer sections of
     code.
   
   Alternative approaches that could work:
   - Change the functions that accept lambda arguments into C++
     iterators. This would work, but will probably be d tedious.
   - Change the lambdas into function-like classes, but define these
     classes outside their containing function. This would work, but
     would be an invasive change to the code.
 */



#ifdef CARPET_ENABLE_BBOXSET2

namespace bboxset2 {



template<typename T, int D>
class bboxset {
  template<typename, int> friend class bboxset;
  typedef ::vect<T,D> vect;
  typedef ::bbox<T,D> bbox;
  typedef ::vect<T,D-1> vect1;
  typedef ::bbox<T,D-1> bbox1;
  typedef bboxset<T,D-1> bboxset1;
  
#if 0
  // We can't use auto_ptr or unique_ptr because we make read-only
  // copies of pointers. We could use weak_ptr for these copies, but
  // we don't do that yet.
  template<typename U>
  using smart_ptr = auto_ptr<U>;
#elif 0
  template<typename U>
  using smart_ptr = unique_ptr<U>;
#else
  // This "using" declaration is not accepted by older C++ compilers
  // template<typename U>
  // using smart_ptr = shared_ptr<U>;
#  define smart_ptr shared_ptr
#endif
  
  typedef map<T, smart_ptr<bboxset1>> subsets_t;
  subsets_t subsets;
  
  vect stride, offset;
  
  bool is_poison_;
  
  template<typename F>
  void traverse_subsets(const F& f) const
  // void traverse_subsets(function<void(int, const bboxset1&)>& f) const
  {
    bboxset1 decoded_subset;
    assert(decoded_subset.empty());
    forall (const auto& pos_subset, subsets) {
      const T& pos = pos_subset.first;
      const bboxset1* const subsetp = pos_subset.second.get();
      decoded_subset ^= *subsetp;
      f(pos, decoded_subset);
    }
    assert(decoded_subset.empty());
  }
#define TRAVERSE_SUBSETS1(f)                                    \
  do {                                                          \
    bboxset1 decoded_subset;                                    \
    assert(decoded_subset.empty());                             \
    forall (const auto& pos_subset, subsets) {                  \
      const T& pos = pos_subset.first;                          \
      const bboxset1* const subsetp = pos_subset.second.get();  \
      decoded_subset ^= *subsetp;                               \
      {                                                         \
        const auto& _1(pos);                                    \
        const auto& _2(decoded_subset);                         \
        f;                                                      \
      }                                                         \
    }                                                           \
    assert(decoded_subset.empty());                             \
  } while (0)
  
  template<typename F>
  void traverse_subsets(const F& f, const bboxset& other) const
  {
    bboxset1 decoded_subset0;
    bboxset1 decoded_subset1;
    assert(decoded_subset0.empty());
    assert(decoded_subset1.empty());
    
    typedef typename subsets_t::const_iterator subsets_iter_t;
    subsets_iter_t iter0 = subsets.begin();
    subsets_iter_t iter1 = other.subsets.begin();
    subsets_iter_t const end0 = subsets.end();
    subsets_iter_t const end1 = other.subsets.end();
    while (iter0!=end0 or iter1!=end1) {
      const T next_pos0 = iter0!=end0 ? iter0->first : numeric_limits<T>::max();
      const T next_pos1 = iter1!=end1 ? iter1->first : numeric_limits<T>::max();
      const T pos = min(next_pos0, next_pos1);
      const bool active0 = next_pos0==pos;
      const bool active1 = next_pos1==pos;
      const bboxset1* const subset0p = active0 ? iter0->second.get() : 0;
      const bboxset1* const subset1p = active1 ? iter1->second.get() : 0;
      if (active0) decoded_subset0 ^= *subset0p;
      if (active1) decoded_subset1 ^= *subset1p;
      
      f(pos, decoded_subset0, decoded_subset1);
      
      if (active0) ++iter0;
      if (active1) ++iter1;
    }
    assert(decoded_subset0.empty());
    assert(decoded_subset1.empty());
  }
#define TRAVERSE_SUBSETS2(f, other_)                                    \
  do {                                                                  \
    const auto& other__(other_);                                        \
    const bboxset& other(other__);                                      \
                                                                        \
    bboxset1 decoded_subset0;                                           \
    bboxset1 decoded_subset1;                                           \
    assert(decoded_subset0.empty());                                    \
    assert(decoded_subset1.empty());                                    \
                                                                        \
    typedef typename subsets_t::const_iterator subsets_iter_t;          \
    subsets_iter_t iter0 = subsets.begin();                             \
    subsets_iter_t iter1 = other.subsets.begin();                       \
    subsets_iter_t const end0 = subsets.end();                          \
    subsets_iter_t const end1 = other.subsets.end();                    \
    while (iter0!=end0 or iter1!=end1) {                                \
      const T next_pos0 =                                               \
        iter0!=end0 ? iter0->first : numeric_limits<T>::max();          \
      const T next_pos1 =                                               \
        iter1!=end1 ? iter1->first : numeric_limits<T>::max();          \
      const T pos = min(next_pos0, next_pos1);                          \
      const bool active0 = next_pos0==pos;                              \
      const bool active1 = next_pos1==pos;                              \
      const bboxset1* const subset0p = active0 ? iter0->second.get() : 0; \
      const bboxset1* const subset1p = active1 ? iter1->second.get() : 0; \
      if (active0) decoded_subset0 ^= *subset0p;                        \
      if (active1) decoded_subset1 ^= *subset1p;                        \
                                                                        \
      {                                                                 \
        const auto& _1(pos);                                            \
        const auto& _2(decoded_subset0);                                \
        const auto& _3(decoded_subset1);                                \
        f;                                                              \
      }                                                                 \
                                                                        \
      if (active0) ++iter0;                                             \
      if (active1) ++iter1;                                             \
    }                                                                   \
    assert(decoded_subset0.empty());                                    \
    assert(decoded_subset1.empty());                                    \
  } while (0)
  
  template<typename F>
  bboxset binary_operator(const F& op, const bboxset& other) const
  {
    assert(not is_poison() and not other.is_poison());
    
#if 0
    // TODO: This assumes that the empty set is a neutral element for
    // the operator
    if (other.empty()) return *this;
    if (empty()) return other;
    assert(all(other.stride == stride));
    assert(all(offset == other.offset));
#endif
    
    if (not empty() and not other.empty()) {
      assert(all(stride == other.stride));
      assert(all(offset == other.offset));
    }
    
    bboxset res;
    if (empty()) {
      res.stride = other.stride;
      res.offset = other.offset;
    } else {
      res.stride = stride;
      res.offset = offset;
    }
    
    bboxset1 old_decoded_subsetr;
#ifndef CARPET_AVOID_LAMBDA
    traverse_subsets
      ([&](const T& pos,
           const bboxset1& decoded_subset0,
           const bboxset1& decoded_subset1)
       {
         bboxset1 decoded_subsetr = op(decoded_subset0, decoded_subset1);
         const auto subsetrp =
           make_shared<bboxset1>(decoded_subsetr ^ old_decoded_subsetr);
         if (not subsetrp->empty()) {
           res.subsets.insert(res.subsets.end(), make_pair(pos, subsetrp));
         }
         swap(old_decoded_subsetr, decoded_subsetr);
       },
       other);
#else
    CCTK_BUILTIN_UNREACHABLE();
#endif
    assert(old_decoded_subsetr.empty());
    
    return res;
  }
#define BINARY_OPERATOR(op, other_)                                     \
  do {                                                                  \
    const auto& other__(other_);                                        \
    const bboxset& other(other__);                                      \
                                                                        \
    assert(not is_poison() and not other.is_poison());                  \
                                                                        \
    if (not empty() and not other.empty()) {                            \
      assert(all(stride == other.stride));                              \
      assert(all(offset == other.offset));                              \
    }                                                                   \
                                                                        \
    bboxset res;                                                        \
    if (empty()) {                                                      \
      res.stride = other.stride;                                        \
      res.offset = other.offset;                                        \
    } else {                                                            \
      res.stride = stride;                                              \
      res.offset = offset;                                              \
    }                                                                   \
                                                                        \
    bboxset1 old_decoded_subsetr;                                       \
    TRAVERSE_SUBSETS2                                                   \
      (const T& pos(_1);                                                \
       const bboxset1& decoded_subset0(_2);                             \
       const bboxset1& decoded_subset1(_3);                             \
       {                                                                \
         bboxset1 decoded_subsetr;                                      \
         {                                                              \
           auto& _0(decoded_subsetr);                                   \
           const auto& _1(decoded_subset0);                             \
           const auto& _2(decoded_subset1);                             \
           op;                                                          \
         }                                                              \
         const auto subsetrp =                                          \
           make_shared<bboxset1>(decoded_subsetr ^ old_decoded_subsetr); \
         if (not subsetrp->empty()) {                                   \
           res.subsets.insert(res.subsets.end(), make_pair(pos, subsetrp)); \
         }                                                              \
         swap(old_decoded_subsetr, decoded_subsetr);                    \
       },                                                               \
       other);                                                          \
    assert(old_decoded_subsetr.empty());                                \
                                                                        \
    _0 = res;                                                           \
  } while (0)
  
public:
  
  /** Invariant */
  bool invariant() const
  {
    if (is_poison() and not empty()) return false;
    if (any(stride <= vect(0))) return false;
    if (any(offset < vect(0) or offset >= stride)) return false;
    forall (const auto& pos_subset, subsets) {
      if (pos_subset.second.get()->empty()) return false;
      if (any(pos_subset.second.get()->stride != init(stride))) return false;
      if (any(pos_subset.second.get()->offset != init(offset))) return false;
    }
    if (chi_size() % 2 != 0) return false;
    return true;
  }
  
  
  
  /** Create empty set */
  bboxset(): stride(vect(1)), offset(vect(0)), is_poison_(false)
  {
  }
  
  /** Return a is_poisoned set */
  static bboxset poison()
  {
    bboxset bs;
    bs.is_poison_ = true;
    return bs;
  }
  
  /** Copy constructor */
  bboxset(const bboxset& other);
  
  /** Copy constructor */
  // bboxset(bboxset&& other);
  
  /** Assignment */
  bboxset& operator=(const bboxset& other);
  
  /** Assignment */
  // bboxset& operator=(bboxset&& other);
  
  /** Create set from bbox */
  bboxset(const bbox& b);
  
  /** Create set from container of bboxes, bboxsets, or container
      thereof */
  template<typename C>
  bboxset(const C& elts);
  
  /** Create set from container of structs containing a bbox, bboxset,
      or container thereof */
  template<typename C, typename S, typename B>
  bboxset(const C& elts, const B S::* const mptr);
  
  
  
  /** Test for is_poison */
  bool is_poison() const
  {
    return is_poison_;
  }
  
  /** Test for emptiness */
  bool empty() const
  {
    assert(not is_poison());
    return subsets.empty();
  }
  
  /** Find a point contained in this set */
  vect front() const;
  
  /** Number of characteristic points */
  T chi_size() const;
  
  /** Number of elements */
  T size() const;
  
  /** Container (min and max) */
  bbox container() const;
  
  
  
  /** Test for equality */
  bool operator==(const bboxset& other) const;
  
  /** Test for is-subset-of */
  bool operator<=(const bboxset& other) const;
  
  /** Test for is-strict-subset-of */
  bool operator<(const bboxset& other) const;
  
  bool operator!=(const bboxset& other) const
  {
    return not (*this == other);
  }
  
  bool operator>=(const bboxset& other) const
  {
    return other <= *this;
  }
  
  bool operator>(const bboxset& other) const
  {
    return other < *this;
  }
  
  bool contains(const vect& v) const
  {
    return bbox(v, v, stride) <= *this;
  }
  
  bool intersects(const bbox& b) const
  {
    return not (b & *this).empty();
  }
  
  
  
  /** Symmetric set difference */
  bboxset operator^(const bboxset& other) const;
  
  /** Symmetric set difference */
  bboxset& operator^=(const bboxset& other);
  
  /** Set intersection */
  bboxset operator&(const bboxset& other) const;
  
  /** Set intersection */
  bboxset& operator&=(const bboxset& other);
  
  /** Set Union */
  bboxset operator|(const bboxset& other) const;
  
  /** Set union */
  bboxset& operator|=(const bboxset& other);
  
  /** Symmetric set union */
  bboxset operator+(const bboxset& other) const;
  
  /** Symmetric set union */
  bboxset& operator+=(const bboxset& other);
  
  /** Set difference */
  bboxset operator-(const bboxset& other) const;
  
  /** Set difference */
  bboxset& operator-=(const bboxset& other);
  
  
  
  /** Operators taking bboxes as arguments */
  bboxset& operator&=(const bbox& b)
  {
    return *this &= bboxset(b);
  }
  bboxset& operator^=(const bbox& b)
  {
    return *this ^= bboxset(b);
  }
  bboxset& operator|=(const bbox& b)
  {
    return *this |= bboxset(b);
  }
  bboxset& operator+=(const bbox& b)
  {
    return *this += bboxset(b);
  }
  bboxset& operator-=(const bbox& b)
  {
    return *this -= bboxset(b);
  }
  
  
  
  /** Shift all points */
  bboxset shift(const vect& dist, const vect& dist_denom = vect(1)) const;
  
  /** Expand the set (convolute with a bbox) */
  bboxset expand(const vect& lo, const vect& hi) const;
  
  /** Expand the set (convolute with a bbox) */
  bboxset expand(const ::vect<vect,2>& lohi) const
  {
    return expand(lohi[0], lohi[1]);
  }
  
  
  
private:
  static bool strides_are_compatible(const vect& str1, const vect& str2);
public:
  
  /** Expande the set (changing the stride): find the smallest
      b-compatible bboxset around this bboxset */
  // Possible implementation:
  // - convert bboxset into set of bboxes
  // - expand each bbox
  // - create new bboxset as union of these bboxes
  // Alternative, possibly more efficient implementation:
  // - for each dimension:
  //   - BS1 := shifted left to align with bbox
  //   - BS2 := shifted right to align with bbox
  //   - create union of BS1 and BS2
  bboxset expanded_for(const bbox& target) const;
  
  /** Shrink the set (changing the stride): find the largest
      b-compatible bboxset inside this bboxset */
  bboxset contracted_for(const bbox& target) const;
  
  /** Expande the set (changing the stride): find the smallest open
      b-compatible bboxset around this bboxset */
  bboxset anti_contracted_for(const bbox& target) const;
  
  
  
  /** Serialise the set */
  template<typename C>
  void serialise(C& out) const;
  
  /** Iterate over a serialised set */
private:
  typedef vector<bbox> iter_memo_t;
public:
  typedef typename iter_memo_t::const_iterator const_iterator;
private:
  mutable iter_memo_t iter_memo;
public:
  int setsize() const
  {
    iter_memo_t im;
    serialise(im);
    return im.size();
  }
  const_iterator begin() const
  {
    iter_memo.clear();
    serialise(iter_memo);
    return iter_memo.begin();
  }
  const_iterator end() const
  {
    return iter_memo.end();
  }
  
  
  /** Memory usage */
  size_t memory() const;
  
  /** Input */
  istream& input(istream& is);
  
  /** Output */
  ostream& debug_output(ostream& os) const;
  ostream& output(ostream& os) const;
};



template<typename T>
class bboxset<T,0> {
  template<typename, int> friend class bboxset;
  typedef ::vect<T,0> vect;
  typedef ::bbox<T,0> bbox;
  
  bool state;
  vect stride, offset;
  bool is_poison_;
public:
  bool invariant() const
  {
    if (is_poison() and state) return false;
    return true;
  }
  
  bboxset():
    state(false), is_poison_(false)
  {
  }
  static bboxset poison()
  {
    bboxset bs; bs.is_poison_ = true; return bs;
  }
  bboxset(const bbox& b):
    state(true), is_poison_(false)
  {
    assert(not b.is_poison());
  }
  bboxset(const bboxset& other):
    state(other.state), is_poison_(other.is_poison_)
  {
  }
  bboxset& operator=(const bboxset& other)
  {
    state = other.state;
    is_poison_ = other.is_poison_;
    return *this;
  }
  
  bool is_poison() const
  {
    return is_poison_;
  }
  bool empty() const
  {
    assert(not is_poison());
    return not state;
  }
  vect front() const
  {
    assert(not is_poison());
    assert(not empty());
    return vect();
  }
  T chi_size() const
  {
    assert(not is_poison());
    return 1;
  }
  T size() const
  {
    assert(not is_poison());
    return state;
  }
  bbox container() const
  {
    assert(not is_poison());
    return bbox();
  }
  
  bool operator==(const bboxset& other) const
  {
    assert(not is_poison() and not other.is_poison());
    return state == other.state;
  }
  bool operator<=(const bboxset& other) const
  {
    assert(not is_poison() and not other.is_poison());
    return state <= other.state;
  }
  bool operator!=(const bboxset& other) const
  {
    return not (*this == other);
  }
  bool operator>=(const bboxset& other) const
  {
    return other <= *this;
  }
  bool operator<(const bboxset& other) const
  {
    return not (*this >= other);
  }
  bool operator>(const bboxset& other) const
  {
    return not (*this <= other);
  }
  
  bboxset& operator&=(const bboxset& other)
  {
    assert(not is_poison() and not other.is_poison());
    state &= other.state;
    return *this;
  }
  bboxset operator&(const bboxset& other) const
  {
    bboxset res = *this;
    return res &= other;
  }
  bboxset& operator^=(const bboxset& other)
  {
    assert(not is_poison() and not other.is_poison());
    state ^= other.state;
    return *this;
  }
  bboxset operator^(const bboxset& other) const
  {
    bboxset res = *this;
    return res ^= other;
  }
  bboxset& operator|=(const bboxset& other)
  {
    assert(not is_poison() and not other.is_poison());
    state |= other.state;
    return *this;
  }
  bboxset operator|(const bboxset& other) const
  {
    bboxset res = *this;
    return res |= other;
  }
  bboxset& operator+=(const bboxset& other)
  {
    assert(not is_poison() and not other.is_poison());
    assert(not (state and other.state));
    return *this |= other;
  }
  bboxset operator+(const bboxset& other) const
  {
    bboxset res = *this;
    return res += other;
  }
  bboxset& operator-=(const bboxset& other)
  {
    assert(not is_poison() and not other.is_poison());
    state &= not other.state;
    return *this;
  }
  bboxset operator-(const bboxset& other) const
  {
    bboxset res = *this;
    return res -= other;
  }
  
  bboxset& operator&=(const bbox& b)
  {
    return *this &= bboxset(b);
  }
  bboxset& operator^=(const bbox& b)
  {
    return *this ^= bboxset(b);
  }
  bboxset& operator|=(const bbox& b)
  {
    return *this |= bboxset(b);
  }
  bboxset& operator+=(const bbox& b)
  {
    return *this += bboxset(b);
  }
  bboxset& operator-=(const bbox& b)
  {
    return *this -= bboxset(b);
  }
  
  bboxset shift(const vect& dist, const vect& dist_denom = vect(1)) const
  {
    assert(not is_poison());
    return *this;
  }
  bboxset expand(const vect& lo, const vect& hi) const
  {
    assert(not is_poison());
    return *this;
  }
  bboxset expand(const ::vect<vect,2>& lohi) const
  {
    return expand(lohi[0], lohi[1]);
  }
  
  template<typename C>
  void serialise(C& out) const
  {
    assert(not is_poison());
    if (state) out.insert(out.end(), bbox());
  }
  
  size_t memory() const
  {
    return sizeof *this;
  }
  
  istream& input(istream& is);
  
  ostream& debug_output(ostream& os) const;
  ostream& output(ostream& os) const;
};



/** Operators involving bboxes */
template<typename T, int D>
inline bboxset<T,D> operator&(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs & bboxset<T,D>(b);
}
template<typename T, int D>
inline bboxset<T,D> operator&(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) & bs;
}
// Note: bbox & bbox -> bbox

template<typename T, int D>
inline bboxset<T,D> operator^(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs ^ bboxset<T,D>(b);
}
template<typename T, int D>
inline bboxset<T,D> operator^(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) ^ bs;
}
template<typename T, int D>
inline bboxset<T,D> operator^(const bbox<T,D>& b1, const bbox<T,D>& b2)
{
  return bboxset<T,D>(b1) ^ bboxset<T,D>(b2);
}

template<typename T, int D>
inline bboxset<T,D> operator|(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs | bboxset<T,D>(b);
}
template<typename T, int D>
inline bboxset<T,D> operator|(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) | bs;
}
template<typename T, int D>
inline bboxset<T,D> operator|(const bbox<T,D>& b1, const bbox<T,D>& b2)
{
  return bboxset<T,D>(b1) | bboxset<T,D>(b2);
}

template<typename T, int D>
inline bboxset<T,D> operator+(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs + bboxset<T,D>(b);
}
template<typename T, int D>
inline bboxset<T,D> operator+(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) + bs;
}
template<typename T, int D>
inline bboxset<T,D> operator+(const bbox<T,D>& b1, const bbox<T,D>& b2)
{
  return bboxset<T,D>(b1) + bboxset<T,D>(b2);
}

template<typename T, int D>
inline bboxset<T,D> operator-(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs - bboxset<T,D>(b);
}
template<typename T, int D>
inline bboxset<T,D> operator-(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) - bs;
}
template<typename T, int D>
inline bboxset<T,D> operator-(const bbox<T,D>& b1, const bbox<T,D>& b2)
{
  return bboxset<T,D>(b1) - bboxset<T,D>(b2);
}

template<typename T, int D>
inline bool operator==(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) == bs;
}
template<typename T, int D>
inline bool operator==(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs == bboxset<T,D>(b);
}

template<typename T, int D>
inline bool operator!=(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) != bs;
}
template<typename T, int D>
inline bool operator!=(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs != bboxset<T,D>(b);
}

template<typename T, int D>
inline bool operator<=(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) <= bs;
}
template<typename T, int D>
inline bool operator<=(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs <= bboxset<T,D>(b);
}

template<typename T, int D>
inline bool operator<(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) < bs;
}
template<typename T, int D>
inline bool operator<(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs < bboxset<T,D>(b);
}

template<typename T, int D>
inline bool operator>=(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) >= bs;
}
template<typename T, int D>
inline bool operator>=(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs >= bboxset<T,D>(b);
}

template<typename T, int D>
inline bool operator>(const bbox<T,D>& b, const bboxset<T,D>& bs)
{
  return bboxset<T,D>(b) > bs;
}
template<typename T, int D>
inline bool operator>(const bboxset<T,D>& bs, const bbox<T,D>& b)
{
  return bs > bboxset<T,D>(b);
}



/** Memory usage */
template<typename T, int D>
inline size_t memoryof(bboxset<T,D> const& bs)
{
  return bs.memory();
}

/** Input */
template<typename T, int D>
inline istream& operator>>(istream& is, bboxset<T,D>& bs)
{
  return bs.input(is);
}

/** Output */
template<typename T, int D>
inline ostream& operator<<(ostream& os, const bboxset<T,D>& bs)
{
  return bs.output(os);
}
  
  
  
  //////////////////////////////////////////////////////////////////////////////
  // bboxset<T,D>
  //////////////////////////////////////////////////////////////////////////////
  
  /** Copy constructor */
  template<typename T, int D>
  bboxset<T,D>::bboxset(const bboxset& other): 
    stride(other.stride), offset(other.offset), is_poison_(other.is_poison_)
  {
    forall (const auto& pos_subset, other.subsets) {
      const T& pos = pos_subset.first;
      const auto new_subsetp = make_shared<bboxset1>(*pos_subset.second.get());
      subsets.insert(subsets.end(), make_pair(pos, new_subsetp));
    }
  }
  
  /** Copy constructor */
  // bboxset(bboxset&& other): stride(other.stride), offset(other.offset)
  // {
  //   swap(subsets, other.subsets);
  // }
  
  /** Assignment */
  template<typename T, int D>
  bboxset<T,D>& bboxset<T,D>::operator=(const bboxset& other)
  {
    if (&other == this) return *this;
    subsets.clear();
    forall (const auto& pos_subset, other.subsets) {
      const T& pos = pos_subset.first;
      const auto new_subsetp = make_shared<bboxset1>(*pos_subset.second.get());
      subsets.insert(subsets.end(), make_pair(pos, new_subsetp));
    }
    stride = other.stride;
    offset = other.offset;
    is_poison_ = other.is_poison_;
    return *this;
  }
  
  /** Assignment */
  // bboxset& operator=(bboxset&& other)
  // {
  //   if (&other == this) return *this;
  //   swap(subsets, other.subsets);
  //   stride = other.stride;
  //   offset = other.offset;
  //   return *this;
  // }
  
  /** Create set from bbox */
  template<typename T, int D>
  bboxset<T,D>::bboxset(const bbox& b):
    stride(b.stride()), offset(imod(b.lower(), b.stride())), is_poison_(false)
  {
    assert(not b.is_poison());
    if (b.empty()) return;
    const T lo = last(b.lower());
    const T hi = last(b.upper()) + last(b.stride());
    const bbox1 b1(init(b.lower()), init(b.upper()), init(b.stride()));
    const auto lo_subsetp = make_shared<bboxset1>(b1);
    const auto hi_subsetp = make_shared<bboxset1>(b1);
    // subsets.emplace_hint(subsets.end(), lo, lo_subsetp);
    // subsets.emplace_hint(subsets.end(), hi, hi_subsetp);
    subsets.insert(subsets.end(), make_pair(lo, lo_subsetp));
    subsets.insert(subsets.end(), make_pair(hi, hi_subsetp));
  }
  
  /** Create set from container of bboxes, bboxsets, or container
      thereof */
  template<typename T, int D>
  template<typename C>
  bboxset<T,D>::bboxset(const C& elts)
  {
    *this = bboxset();
    forall (const auto& elt, elts) {
      *this += bboxset(elt);
    }
  }
  
  /** Create set from container of structs containing a bbox, bboxset,
      or container thereof */
  template<typename T, int D>
  template<typename C, typename S, typename B>
  bboxset<T,D>::bboxset(const C& elts, const B S::* const mptr)
  {
    *this = bboxset();
    forall (const auto& elt, elts) {
      *this += bboxset(elt.*mptr);
    }
  }
  
  
  
  /** Find a point contained in this set */
  template<typename T, int D>
  vect<T,D> bboxset<T,D>::front() const
  {
    assert(not is_poison());
    assert(not empty());
    const auto& pos_subset = *subsets.begin();
    const auto& pos = pos_subset.first;
    const auto& subset = *pos_subset.second.get();
    const vect1 f1 = subset.front();
    return vect(f1, pos);
  }
  
  /** Number of characteristic points */
  template<typename T, int D>
  T bboxset<T,D>::chi_size() const
  {
    assert(not is_poison());
    T sum = 0;
    forall (const auto& pos_subset, subsets) {
      sum += pos_subset.second->chi_size();
    }
    return sum;
  }
  
  /** Number of elements */
  template<typename T, int D>
  T bboxset<T,D>::size() const
  {
    assert(not is_poison());
    T total_size = 0;           // accumulated total number of points
    T old_pos = numeric_limits<T>::min(); // location of last subset
    T old_subset_size = 0;      // number of points in the last subset
#ifndef CARPET_AVOID_LAMBDA
    traverse_subsets
      ([&](const T& pos, const bboxset1& subset)
       {
         const T subset_size = subset.size();
         total_size += (pos - old_pos) * old_subset_size;
         old_pos = pos;
         old_subset_size = subset_size;
       });
#else
    TRAVERSE_SUBSETS1
      (const T& pos(_1);
       const bboxset1& subset(_2);
       {
         const T subset_size = subset.size();
         total_size += (pos - old_pos) * old_subset_size;
         old_pos = pos;
         old_subset_size = subset_size;
       });
#endif
    assert(old_subset_size == 0);
    return total_size;
  }
  
  /** Container (min and max) */
  template<typename T, int D>
  bbox<T,D> bboxset<T,D>::container() const
  {
    assert(not is_poison());
    if (empty()) return bbox();
    const T lo = subsets.begin()->first;
    const T hi = subsets.rbegin()->first;
    bbox1 container1;
#ifndef CARPET_AVOID_LAMBDA
    traverse_subsets
      ([&](const T& pos, const bboxset1& subset)
       {
         container1 = container1.expanded_containing(subset.container());
       });
#else
    TRAVERSE_SUBSETS1
      (const T& pos(_1);
       const bboxset1& subset(_2);
       {
         container1 = container1.expanded_containing(subset.container());
       });
#endif
    return bbox(vect(container1.lower(), lo),
                vect(container1.upper(), hi - last(stride)),
                vect(container1.stride(), last(stride)));
  }
  
  
  
  /** Test for equality */
  template<typename T, int D>
  bool bboxset<T,D>::operator==(const bboxset& other) const
  {
    return (*this ^ other).empty();
  }
  
  /** Test for is-subset-of */
  template<typename T, int D>
  bool bboxset<T,D>::operator<=(const bboxset& other) const
  {
    return (*this | other) == other;
  }
  
  /** Test for is-strict-subset-of */
  template<typename T, int D>
  bool bboxset<T,D>::operator<(const bboxset& other) const
  {
    return *this != other and *this <= other;
  }
  
  
  
  /** Symmetric set difference */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::operator^(const bboxset& other) const
  {
    // TODO: If other is much smaller than this, direct insertion may
    // be faster
#ifndef CARPET_AVOID_LAMBDA
    return binary_operator
      ([](const bboxset1& set0, const bboxset1& set1) { return set0 ^ set1; },
       other);
#else
    bboxset _0;
    BINARY_OPERATOR
      (const bboxset1& set0(_1);
       const bboxset1& set1(_2);
       { _0 = set0 ^ set1; },
       other);
    return _0;
#endif
  }
  
  /** Symmetric set difference */
  template<typename T, int D>
  bboxset<T,D>& bboxset<T,D>::operator^=(const bboxset& other)
  {
    bboxset res = *this;
    return *this = *this ^ other;
  }
  
  /** Set intersection */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::operator&(const bboxset& other) const
  {
#ifndef CARPET_AVOID_LAMBDA
    return binary_operator
      ([](const bboxset1& set0, const bboxset1& set1) { return set0 & set1; },
       other);
#else
    bboxset _0;
    BINARY_OPERATOR
      (const bboxset1& set0(_1);
       const bboxset1& set1(_2);
       { _0 = set0 & set1; },
       other);
    return _0;
#endif
  }
  
  /** Set intersection */
  template<typename T, int D>
  bboxset<T,D>& bboxset<T,D>::operator&=(const bboxset& other)
  {
    return *this = *this & other;
  }
  
  /** Set Union */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::operator|(const bboxset& other) const
  {
#ifndef CARPET_AVOID_LAMBDA
    return binary_operator
      ([](const bboxset1& set0, const bboxset1& set1) { return set0 | set1; },
       other);
#else
    bboxset _0;
    BINARY_OPERATOR
      (const bboxset1& set0(_1);
       const bboxset1& set1(_2);
       { _0 = set0 | set1; },
       other);
    return _0;
#endif
  }
  
  /** Set union */
  template<typename T, int D>
  bboxset<T,D>& bboxset<T,D>::operator|=(const bboxset& other)
  {
    return *this = *this | other;
  }
  
  /** Symmetric set union */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::operator+(const bboxset& other) const
  {
    // return binary_operator
    //   ([](const bboxset1& set0, const bboxset1& set1) { return set0 + set1; },
    //    other);
#ifdef CARPET_DEBUG
    assert((*this & other).empty());
#endif
    return *this ^ other;
  }
  
  /** Symmetric set union */
  template<typename T, int D>
  bboxset<T,D>& bboxset<T,D>::operator+=(const bboxset& other)
  {
    return *this = *this + other;
  }
  
  /** Set difference */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::operator-(const bboxset& other) const
  {
#ifndef CARPET_AVOID_LAMBDA
    return binary_operator
      ([](const bboxset1& set0, const bboxset1& set1) { return set0 - set1; },
       other);
#else
    bboxset _0;
    BINARY_OPERATOR
      (const bboxset1& set0(_1);
       const bboxset1& set1(_2);
       { _0 = set0 - set1; },
       other);
    return _0;
#endif
  }
  
  /** Set difference */
  template<typename T, int D>
  bboxset<T,D>& bboxset<T,D>::operator-=(const bboxset& other)
  {
    return *this = *this - other;
  }
  
  
  
  /** Shift all points */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::shift(const vect& dist, const vect& dist_denom)
    const
  {
    assert(not is_poison());
    assert(all(stride % dist_denom == 0));
    if (all(dist == 0)) return *this;
    bboxset res;
    res.stride = stride;
    res.offset = imod(offset + dist * stride / dist_denom, res.stride);
    forall (const auto& pos_subset, subsets) {
      const T& pos = pos_subset.first;
      const bboxset1& subset = *pos_subset.second.get();
      const T new_pos = pos + last(dist * stride / dist_denom);
      const auto new_subsetp =
        make_shared<bboxset1>(subset.shift(init(dist), init(dist_denom)));
      res.subsets.insert(res.subsets.end(), make_pair(new_pos, new_subsetp));
    }
    return res;
  }
  
  /** Expand the set (convolute with a bbox) */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>:: expand(const vect& lo, const vect& hi) const
  {
    assert(not is_poison());
    assert(all(lo >= 0 and hi >= 0));
    bboxset res = shift(-lo);
    for (int d=0; d<D; ++d) {
      T to_expand = (hi + lo)[d];
      T current_size = 1;
      while (to_expand > 0) {
        const T this_expand = min(to_expand, current_size);
        res |= res.shift(vect::dir(d) * this_expand);
        current_size += this_expand;
        to_expand -= this_expand;
      }
      assert(to_expand == 0);
    }
    return res;
  }
  
  
  
  template<typename T, int D>
  bool bboxset<T,D>::strides_are_compatible(const vect& str1, const vect& str2)
  {
    if (all(str1 >= str2)) {
      return all(imod(str1, str2) == 0);
    } else if (all(str1 <= str2)) {
      return all(imod(str2, str1) == 0);
    }
    return false;
  }
  
  /** Expande the set (changing the stride): find the smallest
      b-compatible bboxset around this bboxset */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::expanded_for(const bbox& target) const
  {
    // Check preconditions
    assert(not is_poison() and not target.is_poison());
    assert(not target.empty());
    assert(strides_are_compatible(stride, target.stride()));
    vector<bbox> bs;
    serialise(bs);
    bboxset res;
    forall (const auto& b, bs) {
      res |= b.expanded_for(target);
    }
    return res;
  }
  
  /** Shrink the set (changing the stride): find the largest
      b-compatible bboxset inside this bboxset */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::contracted_for(const bbox& target) const
  {
    // Check preconditions
    assert(not is_poison() and not target.is_poison());
    assert(not target.empty());
    assert(strides_are_compatible(stride, target.stride()));
    const bbox cont = container();
    const vect safety = 10;
    const bbox good_world = cont.anti_contracted_for(target).expand(safety);
    const bbox world1 = good_world.anti_contracted_for(cont).expand(safety);
    const bbox world2 = world1.anti_contracted_for(target).expand(safety);
    return (world2 ^ (world1 ^ *this).anti_contracted_for(target)) & good_world;
  }
  
  /** Expande the set (changing the stride): find the smallest open
      b-compatible bboxset around this bboxset */
  template<typename T, int D>
  bboxset<T,D> bboxset<T,D>::anti_contracted_for(const bbox& target) const
  {
    // Check preconditions
    assert(not is_poison() and not target.is_poison());
    assert(not target.empty());
    assert(strides_are_compatible(stride, target.stride()));
    vector<bbox> bs;
    serialise(bs);
    bboxset res;
    forall (const auto& b, bs) {
      res |= b.anti_contracted_for(target);
    }
    return res;
  }
  
  
  
  /** Serialise the set */
  template<typename T, int D>
  template<typename C>
  void bboxset<T,D>::serialise(C& out) const
  {
    assert(not is_poison());
    typedef map<bbox1,T> subboxes_t;
    typedef set<bbox1> subboxes1_t;
    // TODO: Instead of copying from old_subboxes to subboxes,
    // maintain subboxes via a non-const iterator
    subboxes_t old_subboxes;
#ifndef CARPET_AVOID_LAMBDA
    traverse_subsets
      ([&](const T& pos, const bboxset1& subset)
       {
         // Convert subset to bboxes
         subboxes1_t subboxes1;
         subset.serialise(subboxes1);
         
         const bbox1 dummy1;
         subboxes_t subboxes;
         // subboxes.reserve(old_subboxes.size() + subboxes1.size());
         typedef typename subboxes_t::const_iterator subboxes_iter_t;
         typedef typename subboxes1_t::const_iterator subboxes1_iter_t;
         subboxes_iter_t iter0 = old_subboxes.begin();
         subboxes1_iter_t iter1 = subboxes1.begin();
         subboxes_iter_t const end0 = old_subboxes.end();
         subboxes1_iter_t const end1 = subboxes1.end();
         while (iter0!=end0 or iter1!=end1) {
           bool active0 = iter0!=end0;
           bool active1 = iter1!=end1;
           const bbox1& subbox0 = active0 ? iter0->first : dummy1;
           const bbox1& subbox1 = active1 ? *iter1 : dummy1;
           // When both subboxes are active, keep only the first (as
           // determined by less<>)
           if (active0 and active1) {
             if (subbox0 != subbox1) {
               /*const*/ less<bbox1> bbox1_less;
               if (bbox1_less(subbox0, subbox1)) {
                 active1 = false;
               } else {
                 active0 = false;
               }
             }
           }
           const T old_pos = active0 ? iter0->second : T();
           
           if ((active0 and active1) and (subbox0 == subbox1)) {
             // The current bbox continues unchanged -- keep it
             subboxes.insert(subboxes.end(), *iter0);
           } else {
             if (active0) {
               // The current box changed; finalize it
               const bbox new_box(vect(subbox0.lower(), old_pos),
                                  vect(subbox0.upper(), pos - last(stride)),
                                  stride);
               out.insert(out.end(), new_box);
             }
             if (active1) {
               // There is a new box; add it
               subboxes.insert(subboxes.end(), make_pair(subbox1, pos));
             }
           }
           
           if (active0) ++iter0;
           if (active1) ++iter1;
         }
         swap(old_subboxes, subboxes);
       });
#else
    TRAVERSE_SUBSETS1
      (const T& pos(_1);
       const bboxset1& subset(_2);
       {
         // Convert subset to bboxes
         subboxes1_t subboxes1;
         subset.serialise(subboxes1);
         
         const bbox1 dummy1;
         subboxes_t subboxes;
         // subboxes.reserve(old_subboxes.size() + subboxes1.size());
         typedef typename subboxes_t::const_iterator subboxes_iter_t;
         typedef typename subboxes1_t::const_iterator subboxes1_iter_t;
         subboxes_iter_t iter0 = old_subboxes.begin();
         subboxes1_iter_t iter1 = subboxes1.begin();
         subboxes_iter_t const end0 = old_subboxes.end();
         subboxes1_iter_t const end1 = subboxes1.end();
         while (iter0!=end0 or iter1!=end1) {
           bool active0 = iter0!=end0;
           bool active1 = iter1!=end1;
           const bbox1& subbox0 = active0 ? iter0->first : dummy1;
           const bbox1& subbox1 = active1 ? *iter1 : dummy1;
           // When both subboxes are active, keep only the first (as
           // determined by less<>)
           if (active0 and active1) {
             if (subbox0 != subbox1) {
               /*const*/ less<bbox1> bbox1_less;
               if (bbox1_less(subbox0, subbox1)) {
                 active1 = false;
               } else {
                 active0 = false;
               }
             }
           }
           const T old_pos = active0 ? iter0->second : T();
           
           if ((active0 and active1) and (subbox0 == subbox1)) {
             // The current bbox continues unchanged -- keep it
             subboxes.insert(subboxes.end(), *iter0);
           } else {
             if (active0) {
               // The current box changed; finalize it
               const bbox new_box(vect(subbox0.lower(), old_pos),
                                  vect(subbox0.upper(), pos - last(stride)),
                                  stride);
               out.insert(out.end(), new_box);
             }
             if (active1) {
               // There is a new box; add it
               subboxes.insert(subboxes.end(), make_pair(subbox1, pos));
             }
           }
           
           if (active0) ++iter0;
           if (active1) ++iter1;
         }
         swap(old_subboxes, subboxes);
       });
#endif
    assert(old_subboxes.empty());
  }
  
  
  
  /** Memory usage */
  template<typename T, int D>
  size_t bboxset<T,D>::memory() const
  {
    size_t s = sizeof *this;
    forall (const auto& pos_subset, subsets) {
      s += sizeof pos_subset;
      const auto* const subsetp = pos_subset.second.get();
      s += memoryof(*subsetp);
    }
    return s;
  }
  
  /** Input */
  template<typename T, int D>
  istream& bboxset<T,D>::input(istream& is)
  {
    T Tdummy;
    try {
      skipws(is);
      consume(is, "bboxset<");
      consume(is, typestring(Tdummy));
      consume(is, ",");
      int D_;
      is >> D_;
      if (D_ != D) {
        ostringstream msg;
        msg << "Input error: Wrong bboxset dimension " << D_ << ", expected " << D;
        CCTK_WARN(CCTK_WARN_ALERT, msg.str().c_str());
        throw input_error();
      }
      consume(is, ">(");
      consume(is, "set<bbox>:");
      set<bbox> bs;
      is >> bs;
      *this = bboxset(bs);
      consume(is, ",");
      consume(is, "stride:");
      is >> stride;
      consume(is, ",");
      consume(is, "offset:");
      is >> offset;
      consume(is, ")");
    } catch (input_error& err) {
      ostringstream msg;
      msg << "Input error while reading a bboxset<" << typestring(Tdummy) << ",0>";
      CCTK_WARN(CCTK_WARN_ALERT, msg.str().c_str());
      throw err;
    }
    is_poison_ = false;
    return is;
  }
  
  /** Output */
  template<typename T, int D>
  ostream& bboxset<T,D>::debug_output(ostream& os) const
  {
    T Tdummy;
    os << "bboxset[debug]<" << typestring(Tdummy) << "," << D << ">("
       << "subsets:{";
    bool first=true;
    forall (const auto& pos_subset, subsets) {
      if (not first) os << ",";
      first=false;
      os << pos_subset.first << ":";
      pos_subset.second.get()->debug_output(os);
    }
    os << "},"
       << "stride:" << stride << ","
       << "offset:" << offset << ","
       << "is_poison_:" << is_poison_ << ")";
    return os;
  }
  
  template<typename T, int D>
  ostream& bboxset<T,D>::output(ostream& os) const
  {
    assert(not is_poison());
    T Tdummy;
    set<bbox> bs;
    serialise(bs);
    return os << "bboxset<" << typestring(Tdummy) << "," << D << ">("
              << "set<bbox>:" << bs << ","
              << "stride:" << stride << ","
              << "offset:" << offset << ")";
  }
  
  
  
  //////////////////////////////////////////////////////////////////////////////
  // bboxset<T,0>
  //////////////////////////////////////////////////////////////////////////////
  
  template<typename T>
  istream& bboxset<T,0>::input(istream& is)
  {
    T Tdummy;
    try {
      skipws(is);
      consume(is, "bboxset<");
      consume(is, typestring(Tdummy));
      consume(is, ",0>(");
      consume(is, "state:");
      is >> state;
      consume(is, ",");
      consume(is, "stride:");
      is >> stride;
      consume(is, ",");
      consume(is, "offset:");
      is >> offset;
      consume(is, ")");
    } catch (input_error& err) {
      ostringstream msg;
      msg << "Input error while reading a bboxset<" << typestring(Tdummy) << ",0>";
      CCTK_WARN(CCTK_WARN_ALERT, msg.str().c_str());
      throw err;
    }
    is_poison_ = false;
    return is;
  }



  template<typename T>
  ostream& bboxset<T,0>::debug_output(ostream& os) const
  {
    T Tdummy;
    return os << "bboxset[debug]<" << typestring(Tdummy) << ",0>("
              << "state:" << state << ","
              << "stride:" << stride << ","
              << "offset:" << offset << ","
              << "is_poison_:" << is_poison_ << ")";
  }
  
  template<typename T>
  ostream& bboxset<T,0>::output(ostream& os) const
  {
    assert(not is_poison());
    T Tdummy;
    return os << "bboxset<" << typestring(Tdummy) << ",0>("
              << "state:" << state << ","
              << "stride:" << stride << ","
              << "offset:" << offset << ")";
  }



} // namespace bboxset2

#endif  // #ifdef CARPET_ENABLE_BBOXSET2



#endif  // #ifndef BBOXSET2_HH