summaryrefslogtreecommitdiff
path: root/lbm.org
blob: b21ca1d4cca80f8c9fd12a5c09940009857cbea1 (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
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
#+TITLE: A literate Lattice Boltzmann Code
#+SUBTITLE: [[https://kummerlaender.eu][Adrian Kummerländer]]
#+STARTUP: latexpreview
#+OPTIONS: toc:nil html-postamble:nil html5-fancy:t html-style:nil
#+PROPERTY: header-args :exports both :mkdirp yes :noweb no-export :eval no-export
#+PROPERTY: header-args:python+ :var lattice="D2Q9"
#+PROPERTY: header-args:cpp+ :main no :eval no
#+HTML_DOCTYPE: html5
#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="org.css"/>
#+HTML_MATHJAX: path:"https://static.kummerlaender.eu/mathjax/MathJax.js?config=TeX-AMS_HTML"

#+BEGIN_ABSTRACT
This file describes a full Lattice Boltzmann code featuring both 2D and 3D lattices, a workable selection of boundary conditions, Smagorinsky
turbulence modelling, expression-level code optimization and even a full ray marcher for just-in-time volumetric visualization in addition
to a set of interesting examples. All of this runs on GPUs using CUDA near the maximum possible performance on that platform.

*This document is a [[*Open tasks][work in progress]].*
#+BEGIN_EXPORT html
<video style="width:100%" src="https://literatelb.org/media/fire.webm" playsinline controls loop muted/>
#+END_EXPORT
#+END_ABSTRACT
#+TOC: headlines 2

* Preamble                                                                                :noexport:
#+BEGIN_SRC python :session :results none
from sympy import *
from sympy.codegen.ast import CodeBlock, Assignment
from mako.template import Template
import itertools

def printlatexpr(*exprs):
    print("$$\\begin{align*}")
    for expr in exprs:
        print(f"{latex(expr.lhs)} &:= {latex(expr.rhs)} \\\\")
    
    print("\\end{align*}$$")

def multirange(*ranges):
    return itertools.product(*[ range(r) for r in ranges ])

def multisum(f, *ranges):
    return sum([ f(*idx) for idx in multirange(*ranges) ])

descriptor = { }
#+END_SRC

#+NAME: eval-using-descriptor
#+BEGIN_SRC python :session :results output :var src=""
if lattice in descriptor:
    D = descriptor[lattice]
    print(Template(src).render(**locals()))
#+END_SRC

#+RESULTS: eval-using-descriptor

* Introduction
Approaches to modeling fluid dynamics can be coarsely grouped into three categories: Microscopic, Mesoscopic and Macroscopic models.
Microscopic models describe the behavior of the individual /particles/ of whose the macroscopic fluid movement is an emergent property.
On the other side of the spectrum, macroscopic models consider only the large scale properties of a fluid such as its velocity and density
fields. One could say that microscopic particle models are closest to what actually happens in nature and macroscopic models in the form
of the /Navier Stokes equations (NSE)/ represent an ideal vision of a fluid that only holds for /large enough/ space scales.
As is the case for most things, what we call a /fluid/ is by itself already an abstraction.

Mesoscopic models sit between these two extremes and consider neither individual particles nor purely macroscopic properties but rather
the probability of some amount of particles moving with some velocity into a certain direction at various points in time and space. The
mathematical field of /kinetic theory/ provides a foundation for linking all of these three models.

** Kinetic Theory
One can use kinetic theory to get from a microscropic or /molecular/ system governed by e.g. Newton's laws of motion to macroscopic
descriptions of certain properties of such a system. For example one can reach the diffusion equation for /billiard systems/ of particles
colliding with solid obstacles or to the Navier Stokes equations for systems of pairwise colliding particles.

In very rough terms one starts out by considering the microscopic system and taking its limit for infinitely many particles of
vanishingly small size. This yields a /kinetic equation/ that describes the behaviour of the particle distribution function
under some collision operator for any point in space and time. When we consider pairwise colliding particles the result
turns out to be the well known /Boltzmann transport equation/:

$$(\partial_t + v \cdot \nabla_x) f(t,x,v) = \Omega (f).$$

This PDE describes the behavior of the probability $f(t,x,v)$ that particles move into direction $v$ at location $x$ and time $t$ for
some collision operator $\Omega$. Discretizing this equation on a lattice for a finite set of discrete velocities is called the /Lattice Boltzmann Method (LBM)/.

The practical usefulness of LBM hinges on the ability of reaching the desired /target equations/
such as NSE or the heat equation as a limit of the kinetic equation.

** Lattice Boltzmann Method
We discretize the Boltzmann equation in spatial, velocity and temporal space on a cartesian lattice using discrete velocities
$\xi_i$ that point to the neighbors of each cell.

$$(\partial_t + v \cdot \nabla_x)f = \Omega(f) \approx f_i(x + \xi_i, t + 1) - f_i(x,t) = \Omega_i(x,t)$$

A common collision operator $\Omega$ for Navier-Stokes approximation is given by Bhatnagar, Gross and Kroog (BGK).

$$\Omega(f) := -\frac{f - f^\text{eq}}{\tau}$$

This BGK operator /relaxes/ the local population $f$ towards some equilibrium distribution $f^\text{eq}$ with rate $\tau$. Inserting this operator
into the discrete Boltzmann equation yields the discrete LBM BGK equation.

$$f_i(x + \xi_i, t + 1) = f_i(x,t) - \frac{1}{\tau} (f_i(x,t) - f_i^\text{eq}(x,t))$$

This explicit form exposes the separation of the LBM algorithm into a local collision step followed by a streaming step.
The collision step relaxes the population of each cell towards its local equilibrium and the streaming step propagates the resulting
updated population values to the respective neighboring cells.

Macroscopic moments such as density and velocity can be calculated directly from the distribution functions.

$$\rho := \sum_{i=0}^{q-1} f_i(x,t) \text{ and } u := \frac{1}{\rho} \sum_{i=0}^{q-1} \xi_i f_i(x,t)$$

The equilibrium distribution $f_i^\text{eq}$ for these macroscopic properties is given by

$$f_i^\text{eq}(x,t) := \omega_i \rho \left( 1 + \frac{u \cdot \xi_i}{c_s^2} + \frac{(u \cdot \xi_i)^2}{2c_s^4} - \frac{u \cdot u}{2c_s^2} \right)$$

using lattice-dependent weights $\omega_i$ and speed of sound $c_s$. Note that this is just one possible discretization of the Boltzmann
equation -- nothing stops us from using different sets of velocities, relaxation times, collision operators and so on.
Changing these things is how different physics are modeled in LBM. e.g. what we will do in the section on
[[*Smagorinsky BGK Collision][Smagorinsky turbulence modelling]] is to locally change the relaxation time.

To summarize what we are going to do for the simplest bulk fluid case: First calculate the current density and velocity
moments of a cell, then compute the matching equilibrium distributions and finally perform the local BGK collision to
update the cell populations.
The last step before we start again is to propagate the post-collision values to the corresponding neighbor cells. 

Special care has to be taken for the boundary conditions at the lattice frontier and around any obstacle geometries.
Such boundary conditions are one of the major topics of LBM research with a very rich toolbox of specialized collision
steps for modeling e.g. inflow, outflow, solid or moving walls of various kinds.

As a starting point for further reading on LBM I can recommend the de facto standard text
cite:krugerLatticeBoltzmannMethod2017  by Krüger et al.

** Literate Programming
The present website is the documentation /woven/ from the literate program file [[https://code.kummerlaender.eu/LiterateLB/tree/lbm.org][=lbm.org=]].
In the same fashion this program file may also be /tangled/ into compilable code.
Programs written using this paradigm are commonly referred to as /literate/ and promise
to decouple program exposition from the strict confines of machine-targeted languages.

LiterateLB utilizes the literate programming framework offered by [[https://emacs.org][Emacs's]] [[https://orgmode.org][Org Mode]].

The easiest way to tangle and compile the project is to use the [[https://nixos.org][Nix package manager]].
On CUDA-enabled NixOS hosts the following commands are all that is needed to tangle,
compile and run one of the simulation examples:

#+BEGIN_SRC sh :eval no
git clone https://code.kummerlaender.eu/LiterateLB
cd LiterateLB
nix build
./result/bin/nozzle
#+END_SRC

On other systems the dependencies
+ Emacs 28 (earlier possible for up-to-date orgmode)
+ CMake 3.10 or later
+ Nvidia CUDA 10.2 or later
+ SFML 2.5 or later and ImGui-SFML
+ Python with SymPy, NumPy, SciPy and Mako
will have to be provided manually. Note that the current tangle output is included so strictly
speaking compiling and testing the examples requires neither Emacs nor Python.

Note that I started developing this as a beginner in both Emacs and Org mode so some aspects of this document
may be more clunky than necessary. Most of the complexity stems from maintaining a Python session for the
generation of optimized GPU kernel functions using the SymPy CAS.
* Lattice
The cartesian grids used for the spatial discretization are commonly described as =DXQY= lattices where =X= is the number of spatial dimensions
and =Y= is the number of discrete velocities $\xi_i$. e.g. a  =D2Q9= lattice is two dimensional and stores nine population values per cell. Each population has
an associated weigth $\omega_i$ that in a sense controls its impact on the collision step. Additionally we also require the lattice speed of sound $c_s$ which is
the speed of information propagation within the lattice.

#+BEGIN_SRC python :session :results none
from fractions import Fraction

class Descriptor:
    def __init__(self, name, data):
        self.name = name
        self.c = [ Matrix(eval(row[0]))    for row in data ]
        self.w = [ Rational(f.numerator, f.denominator)
                   for f in [ Fraction(row[1]) for row in data ] ]
        self.d = self.c[0].shape[0]
        self.q = len(self.c)
        self.c_s = sqrt(Rational(1,3))
#+END_SRC

All of these constants have to be accessible for symbolic computations which is why we store them within a so called descriptor class.
For convenience we write out the directions and weights as plain tables that are then read into the Python structure.

#+NAME: load-descriptor
#+BEGIN_SRC python :session :results output :var data=D2Q9
descriptor[lattice] = Descriptor(lattice, data)
print(f"Loaded D{descriptor[lattice].d}Q{descriptor[lattice].q} lattice with a weight sum of {sum(descriptor[lattice].w)}.")
#+END_SRC

#+RESULTS: load-descriptor
: Loaded D2Q9 lattice with a weight sum of 1.

#+CALL: load-descriptor(lattice="D3Q19", data=D3Q19)

#+RESULTS:
: Loaded D3Q19 lattice with a weight sum of 1.

** D2Q9
#+NAME: D2Q9
| Direction | Weight |
|-----------+--------|
| (-1,-1)   | 1/36   |
| (-1, 0)   | 1/9    |
| (-1, 1)   | 1/36   |
| ( 0,-1)   | 1/9    |
| ( 0, 0)   | 4/9    |
| ( 0, 1)   | 1/9    |
| ( 1,-1)   | 1/36   |
| ( 1, 0)   | 1/9    |
| ( 1, 1)   | 1/36   |

** D3Q19
#+NAME: D3Q19
| Direction  | Weight |
|------------+--------|
| ( 0, 1, 1) | 1/36   |
| (-1, 0, 1) | 1/36   |
| ( 0, 0, 1) | 1/18   |
| ( 1, 0, 1) | 1/36   |
| ( 0,-1, 1) | 1/36   |
| (-1, 1, 0) | 1/36   |
| ( 0, 1, 0) | 1/18   |
| ( 1, 1, 0) | 1/36   |
| (-1, 0, 0) | 1/18   |
| ( 0, 0, 0) | 1/3    |
| ( 1, 0, 0) | 1/18   |
| (-1,-1, 0) | 1/36   |
| ( 0,-1, 0) | 1/18   |
| ( 1,-1, 0) | 1/36   |
| ( 0, 1,-1) | 1/36   |
| (-1, 0,-1) | 1/36   |
| ( 0, 0,-1) | 1/18   |
| ( 1, 0,-1) | 1/36   |
| ( 0,-1,-1) | 1/36   |

* Collision Steps
While the streaming step of the LBM algorithm only propagates the populations between cells in an unform fashion,
the collision step determines the actual values those populations take. This means that the physical behaviour
modelled by a given LBM algorithm is determined primarily by the collision step.

In this section we are going to generate the code for bulk collisions. i.e. the collisions that model fluid and other transport
phenomena apart from domain boundaries. Those will be handled at a later point by special purpose collision steps called
/boundary conditions/.

** Code printing
Before we can get started on constructing expression trees and generating code from them we need to
setup some basics so SymPy actually generates something we can compile in our environment.

In order to get more fine grained control we need to overload an approproate SymPy C code printer class.
This allows us to e.g. easily print indexed expressions that access the population array in the correct way
or to explicitly type float constants according to a compile-time template type.

#+BEGIN_SRC python :session :results none
from sympy.printing.ccode import C11CodePrinter

class CodeBlockPrinter(C11CodePrinter):
    def __init__(self, custom_assignment, custom_functions):
        super(CodeBlockPrinter, self).__init__()
        self._default_settings['contract'] = False
        self.custom_assignment = custom_assignment
        for f in custom_functions:
            self._kf[f] = f

    def _print_Indexed(self, expr):
        assert len(expr.indices) == 1
        if expr.base.name[0] == 'f':
            return f"{expr.base.name}[{expr.indices[0]}]"
        else:
            return f"{expr.base.name}_{expr.indices[0]}"

    def _print_Float(self, flt):
        return "T{%s}" % str(flt.evalf())

    def _print_Pow(self, expr):
        if expr.exp == -1:
            return "T{1} / (%s)" % self.doprint(expr.base)
        else:
            return super()._print_Pow(expr)

    def _print_Assignment(self, expr):
        if self.custom_assignment and expr.lhs.is_Indexed and expr.lhs.base.name[0] == 'f':
            return f"{self.doprint(expr.lhs)} = {self.doprint(expr.rhs.evalf())};"
        else:
            return f"T {self.doprint(expr.lhs)} = {self.doprint(expr.rhs.evalf())};"
#+END_SRC

For convenience the instantiation of this class is hidden in a =printcode= function that we can use everywhere.

#+BEGIN_SRC python :session :results none
def printcode(expr, custom_assignment=True, custom_functions=[]):
    print(CodeBlockPrinter(custom_assignment, custom_functions).doprint(expr))
#+END_SRC

The additional assignment parameter allow us to control whether the targets of assignment expressions should be
instantiated as a new scalar variable in addition while the functions parameter allows us to make custom runtime
functions known to SymPy. If we don't do this for a function =f= that our assignment expression contains a reference
to, the printer will generate unwanted comments to reflect this.

*** Custom expression transformations
We do not want to use the =pow= function for squares in the generated code. This can be achieved by providing
a custom =ReplaceOptim= structure during the CSE optimization step that conditionally resolves =Pow= expressions.

#+BEGIN_SRC python :session :results none
from sympy.codegen.rewriting import ReplaceOptim
from sympy.simplify import cse_main

expand_pos_square = ReplaceOptim(
    lambda e: e.is_Pow and e.exp.is_integer and e.exp == 2,
    lambda p: UnevaluatedExpr(Mul(p.base, p.base, evaluate = False))
)

custom_opti = cse_main.basic_optimizations + [
    (expand_pos_square, expand_pos_square)
]
#+END_SRC

#+BEGIN_SRC python :session :results none
def cse(block, symbol_prefix = 'x'):
    return block.cse(symbols = numbered_symbols(prefix=symbol_prefix), optimizations = custom_opti, order = 'none')
#+END_SRC

** Moments
#+BEGIN_SRC python :session :results none
i, j = symbols('i, j')
d, q = symbols('d, q')
xi = IndexedBase('xi')
#+END_SRC

To start we define placeholders for the spatial and discrete velocity dimensions as well as the velocity set $\xi$ of
some lattice. As the moments are constructed using the lattice populations $f$ we also require placeholders
for those in addition to the moments $\rho$ and $u$ themselves.

#+BEGIN_SRC python :session :results none
f = IndexedBase('f')
rho = Symbol('rho')
u = IndexedBase('u', d)
u_i = Symbol('u_i')
#+END_SRC

We are now ready to formulate the density moment which is simply the sum of a cell's populations.

#+BEGIN_SRC python :session :results output replace :wrap latex
def rho_from_f(f, q):
    return Assignment(rho, Sum(f[j], (j, 0, q-1)))

printlatexpr(rho_from_f(f, q))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
\rho &:= \sum_{j=0}^{q - 1} {f}_{j} \\
\end{align*}$$
#+end_latex

Next we build the velocity moment function. The i-th component of the velocty $u$ is the sum of all
relevant populations divided by the density. In this context /relevant/ populations are all values $f_j$ 
for which the i-th component of velocity $\xi_j$ is non-zero.

#+BEGIN_SRC python :session :results output replace :wrap latex
def u_i_from_f(f, q, xi):
    return Assignment(u_i, Sum(xi[j,i] * f[j], (j, 0, q-1)) / Sum(f[j], (j, 0, q-1)))

printlatexpr(u_i_from_f(f, q, xi))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
u_{i} &:= \frac{\sum_{j=0}^{q - 1} {f}_{j} {\xi}_{j,i}}{\sum_{j=0}^{q - 1} {f}_{j}} \\
\end{align*}$$
#+end_latex

Both to illustrate what we are actually going to compute for a given lattice cell and as the
next step towards code generation we now want to /realize/ our abstract moment expressions
for a concrete lattice.

#+BEGIN_SRC python :session :results output :wrap latex
def realize_rho(D):
    return rho_from_f(f, D.q).doit()

D = descriptor[lattice]
printlatexpr(realize_rho(D))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
\rho &:= {f}_{0} + {f}_{1} + {f}_{2} + {f}_{3} + {f}_{4} + {f}_{5} + {f}_{6} + {f}_{7} + {f}_{8} \\
\end{align*}$$
#+end_latex

#+BEGIN_SRC python :session :results none
def from_indices(elems, car, *cdr):
    return elems[car] if len(cdr) == 0 else from_indices(elems[car], *cdr)

def realize_indexed(expr, idx, values):
    return expr.replace(lambda expr: expr.is_Indexed and expr.base.name == idx.name,
                        lambda elem: from_indices(values, *elem.indices))
#+END_SRC

#+BEGIN_SRC python :session :results output :wrap latex
def realize_u_i(D, j):
    return realize_indexed(u_i_from_f(f, D.q, xi).doit().subs([(u_i, u[j]), (i, j)]), xi, D.c)

D = descriptor[lattice]
printlatexpr(realize_u_i(D, 0))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
{u}_{0} &:= \frac{- {f}_{0} - {f}_{1} - {f}_{2} + {f}_{6} + {f}_{7} + {f}_{8}}{{f}_{0} + {f}_{1} + {f}_{2} + {f}_{3} + {f}_{4} + {f}_{5} + {f}_{6} + {f}_{7} + {f}_{8}} \\
\end{align*}$$
#+end_latex

At this point we have everything needed to generate an optimized code snippet that
can be used to compute density and velocity values given a set of variables containing
a single cell's populations. As a convention we are going to prefix these /current/ population
variables with =f_curr=.

#+BEGIN_SRC python :session :results none
def moments_code_block(D, populations):
    f_rho = realize_indexed(realize_rho(D), f, populations)
    f_u = [ realize_indexed(realize_u_i(D, i), f, populations) for i in range(D.d) ]
    return CodeBlock(f_rho, *f_u).cse(symbols = numbered_symbols(prefix='m'), optimizations = custom_opti)
#+END_SRC

#+NAME: moments-from-f_curr
#+BEGIN_SRC python :session :results output :cache yes
printcode(moments_code_block(descriptor[lattice], IndexedBase('f_curr')))
#+END_SRC

#+RESULTS[11633b87f250d3c0a8e39c7091e10d2ef75b19dc]: moments-from-f_curr
: T m0 = f_curr[1] + f_curr[2];
: T m1 = f_curr[3] + f_curr[6];
: T m2 = m0 + m1 + f_curr[0] + f_curr[4] + f_curr[5] + f_curr[7] + f_curr[8];
: T m3 = f_curr[0] - f_curr[8];
: T m4 = T{1} / (m2);
: T rho = m2;
: T u_0 = -m4*(m0 + m3 - f_curr[6] - f_curr[7]);
: T u_1 = -m4*(m1 + m3 - f_curr[2] - f_curr[5]);

Both the fluid dynamics implemented by collision steps and boundary conditions as well as functions
for computing moments to e.g. visualize are implemented as GPU kernel functions. In CUDA this means
plain functions marked by the =__global__= specifier. As most kernel share common aspects in their call
requirements and parameter sets we wrap them in =__device__= functions of sensibly named structures.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collect_moments.h
#pragma once
#include <LLBM/call_tag.h>

struct CollectMomentsF {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], std::size_t gid, T* cell_rho, T* cell_u) {
  <<moments-from-f_curr(lattice="D2Q9")>>

  cell_rho[gid] = rho;
  cell_u[2*gid+0] = u_0;
  cell_u[2*gid+1] = u_1;
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], std::size_t gid, T* cell_rho, T* cell_u) {
  <<moments-from-f_curr(lattice="D3Q19")>>

  cell_rho[gid] = rho;
  cell_u[3*gid+0] = u_0;
  cell_u[3*gid+1] = u_1;
  cell_u[3*gid+2] = u_2;
}

};
#+END_SRC

** Equilibrium
#+BEGIN_SRC python :session :results none
f_eq = IndexedBase('f_eq', q)
#+END_SRC

$$f_i^\text{eq}(x,t) := \omega_i \rho \left( 1 + \frac{u \cdot \xi_i}{c_s^2} + \frac{(u \cdot \xi_i)^2}{2c_s^4} - \frac{u \cdot u}{2c_s^2} \right)$$

Calculating the equilibrium distribution of some population $f_i$ requires the evaluation of inner products
between vectors. As there doesn't seem to be a nice way of writing an abstract SymPy expression that both
generates nice LaTeX and can be realized on a concrete lattice we skip the fully abstract step and jump
right into the latter part.

#+BEGIN_SRC python :session :results output :wrap latex
def realize_f_eq_i(D, i):
    v = Matrix([ u[j] for j in range(D.d) ])
    return Assignment(f_eq[i], D.w[i] * rho * ( 1
                                              + D.c[i].dot(v)    /    D.c_s**2
                                              + D.c[i].dot(v)**2 / (2*D.c_s**4)
                                              - v.dot(v)         / (2*D.c_s**2) ))

D = descriptor[lattice]
printlatexpr(realize_f_eq_i(D, 0))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
{f_{eq}}_{0} &:= \frac{\rho \left(\frac{9 \left(- {u}_{0} - {u}_{1}\right)^{2}}{2} - \frac{3 {u}_{0}^{2}}{2} - 3 {u}_{0} - \frac{3 {u}_{1}^{2}}{2} - 3 {u}_{1} + 1\right)}{36} \\
\end{align*}$$
#+end_latex

#+BEGIN_SRC python :session :results none
def equilibrium_code_block(D):
    f_moment_eq = [ Assignment(f_next[i], realize_f_eq_i(D, i).rhs) for i in range(D.q) ]
    return cse(CodeBlock(*f_moment_eq), symbol_prefix = 'e')
#+END_SRC

#+NAME: equilibrium-from-moments
#+BEGIN_SRC python :session :results output :cache yes
printcode(equilibrium_code_block(descriptor[lattice]))
#+END_SRC

#+RESULTS[7843a5ae8cf9ac0b63787ab4080ba2488a6cc0a7]: equilibrium-from-moments
#+begin_example
T e0 = T{0.0277777777777778}*rho;
T e1 = T{3.00000000000000}*u_1;
T e2 = T{3.00000000000000}*u_0;
T e3 = u_0 + u_1;
T e4 = T{4.50000000000000}*(e3*e3);
T e5 = u_1*u_1;
T e6 = T{1.50000000000000}*e5;
T e7 = u_0*u_0;
T e8 = T{1.50000000000000}*e7;
T e9 = e8 + T{-1.00000000000000};
T e10 = e6 + e9;
T e11 = T{0.111111111111111}*rho;
T e12 = -e2;
T e13 = T{1.00000000000000} - e6;
T e14 = e13 + T{3.00000000000000}*e7;
T e15 = -e8;
T e16 = e1 + e15;
T e17 = u_0 - u_1;
T e18 = e13 + T{4.50000000000000}*(e17*e17);
T e19 = T{3.00000000000000}*e5;
f_next[0] = -e0*(e1 + e10 + e2 - e4);
f_next[1] = e11*(e12 + e14);
f_next[2] = e0*(e12 + e16 + e18);
f_next[3] = -e11*(e1 - e19 + e9);
f_next[4] = -T{0.444444444444444}*e10*rho;
f_next[5] = e11*(e16 + e19 + T{1.00000000000000});
f_next[6] = e0*(-e1 + e15 + e18 + e2);
f_next[7] = e11*(e14 + e2);
f_next[8] = e0*(e13 + e16 + e2 + e4);
#+end_example

** BGK Collision
The BGK collision operators takes a current population $f^{curr}_i$ and /relaxes/ it toward the equilibrium distribution
$f^{eq}_i$ with some rate $\tau$. The result of this process is the new population $f^{next}_i$.

#+BEGIN_SRC python :session :results none
tau = Symbol('tau')
f_curr = IndexedBase('f_curr', q)
f_next = IndexedBase('f_next', q)
f_curr_i, f_next_i, f_eq_i = symbols('f^curr_i, f^next_i, f^eq_i')
#+END_SRC

#+BEGIN_SRC python :session :results output :wrap latex
def bgk_collision(f_curr, f_next, f_eq, tau):
    return Assignment(f_next, f_curr + 1/tau * (f_eq - f_curr))

printlatexpr(bgk_collision(f_curr_i, f_next_i, f_eq_i, tau))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
f^{next}_{i} &:= f^{curr}_{i} + \frac{- f^{curr}_{i} + f^{eq}_{i}}{\tau} \\
\end{align*}$$
#+end_latex

As we might want to use different moment values than the ones constructed from the current population 
as the foundation for the equilibrium distribution the generated code will assume variables =rho= and =u_i=
to exist. Building the expression tree for code generation is now as simple as instantiating the BGK
operator for all $q$ directions and substituting the equilibrium distribution.

#+BEGIN_SRC python :session :results none
def bgk_collision_code_block(D):
    f_eq_def = [ realize_f_eq_i(D, i).rhs for i in range(D.q) ]
    f_post_collide = [ bgk_collision(f_curr[i], f_next[i], f_eq_def[i], tau) for i in range(D.q) ]
    return CodeBlock(*f_post_collide).cse(optimizations = custom_opti)
#+END_SRC

#+NAME: bgk-collide-to-f_next
#+BEGIN_SRC python :session :results output :cache yes
printcode(bgk_collision_code_block(descriptor[lattice]), custom_assignment=True)
#+END_SRC

#+RESULTS[b9035596468cbdcf22f3e63f7fa43d74a6261849]: bgk-collide-to-f_next
#+begin_example
T x0 = T{1} / (tau);
T x1 = T{0.0138888888888889}*x0;
T x2 = T{6.00000000000000}*u_1;
T x3 = T{6.00000000000000}*u_0;
T x4 = u_0 + u_1;
T x5 = T{9.00000000000000}*(x4*x4);
T x6 = u_1*u_1;
T x7 = T{3.00000000000000}*x6;
T x8 = u_0*u_0;
T x9 = T{3.00000000000000}*x8;
T x10 = x9 + T{-2.00000000000000};
T x11 = x10 + x7;
T x12 = T{0.0555555555555556}*x0;
T x13 = -x3;
T x14 = T{2.00000000000000} - x7;
T x15 = x14 + T{6.00000000000000}*x8;
T x16 = -x9;
T x17 = x16 + x2;
T x18 = u_0 - u_1;
T x19 = x14 + T{9.00000000000000}*(x18*x18);
T x20 = T{6.00000000000000}*x6;
f_next[0] = -x1*(rho*(x11 + x2 + x3 - x5) + T{72.0000000000000}*f_curr[0]) + f_curr[0];
f_next[1] = x12*(rho*(x13 + x15) - T{18.0000000000000}*f_curr[1]) + f_curr[1];
f_next[2] = x1*(rho*(x13 + x17 + x19) - T{72.0000000000000}*f_curr[2]) + f_curr[2];
f_next[3] = -x12*(rho*(x10 + x2 - x20) + T{18.0000000000000}*f_curr[3]) + f_curr[3];
f_next[4] = -T{0.111111111111111}*x0*(T{2.00000000000000}*rho*x11 + T{9.00000000000000}*f_curr[4]) + f_curr[4];
f_next[5] = x12*(rho*(x17 + x20 + T{2.00000000000000}) - T{18.0000000000000}*f_curr[5]) + f_curr[5];
f_next[6] = x1*(rho*(x16 + x19 - x2 + x3) - T{72.0000000000000}*f_curr[6]) + f_curr[6];
f_next[7] = x12*(rho*(x15 + x3) - T{18.0000000000000}*f_curr[7]) + f_curr[7];
f_next[8] = x1*(rho*(x14 + x17 + x3 + x5) - T{72.0000000000000}*f_curr[8]) + f_curr[8];
#+end_example

In order to call this collision kernel on the GPU we wrap it in =apply= functions of an appropriately
named operator structure.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collide.h
#pragma once
#include <LLBM/call_tag.h>

struct BgkCollideO {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, T tau) {
  <<moments-from-f_curr(lattice="D2Q9")>>
  <<bgk-collide-to-f_next(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, T tau) {
  <<moments-from-f_curr(lattice="D3Q19")>>
  <<bgk-collide-to-f_next(lattice="D3Q19")>>
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/bulk.h
#include "kernel/collide.h"
#+END_SRC

** Smagorinsky BGK Collision
Simulation of turbulent flow using plain BGK collisions is possible -- after all turbulence is captured by the Navier-Stokes
equations that in turn are the target equations of our BGK-LB method -- but requires very highly resolved grids. The reason
for this is that turbulence is characterized by the formation of eddies at both very big and very small scales. Most of the
energy is contained in the large scale features but dissipates into heat at the finest scales. To capture turbulent flow we either
have to resolve the grid all the way to these finest scales or implement some kind of model for the characteristics of these
scales in a coarser grid. Computation on such a coarser grid is then also called a large eddy simulation (LES).

One comparably simple model for respresenting the smaller eddies in such a LES is the Smagorinsky subgrid-scale model.
This model yields a expression for computing the /effective relaxation rate/ $\tau_\text{eff}$ on a per-cell basis given the global relaxation
time $\tau$ and a Smagorinsky constant. As the relaxation time in BGK LBM is a function of the viscosity this translates into
computing the effective viscosity using a local strain-rate tensor reconstruction based on the non-equilibrium part of each
cell's populations. This follows the approach laid out by  Yu et al. in cite:yuDNSDecayingIsotropic2005.

#+BEGIN_SRC python :session :results none
tau, smagorinsky = symbols('tau, smagorinsky')
#+END_SRC

The non-equilibrium part is simply the difference between the actual population stored in a cell and the respective
equilibrium population that we relax towards. Using these local non-equilibrium parts to reconstruct the strain-rate
tensor $\Pi_{i,j}^\text{neq}$ is quite convenient as we otherwise would have to employ e.g. a finite difference method just for this.

#+BEGIN_SRC python :session :results none
def pi_neq(D, f, f_eq):
    pi_neq = zeros(D.d, D.d)
    for i, j, k in multirange(D.d, D.d, D.q):
        pi_neq[i,j] += D.c[k][i] * D.c[k][j] * (f[k] - f_eq[k])
    
    return pi_neq
#+END_SRC

To compute the effective relaxation rate we need the norm of this strain-rate tensor.

#+BEGIN_SRC python :session :results none
def pi_neq_norm(D, f, f_eq):
    pi = pi_neq(D, f, f_eq)
    return sqrt(2*multisum(lambda i, j: pi[i,j]**2, D.d, D.d))
#+END_SRC

#+BEGIN_SRC python :session :results none
def effective_tau(D, f, f_eq, tau, smagorinsky):
    pi_norm = pi_neq_norm(D, f, f_eq)
    return tau + 0.5*(sqrt(tau**2 + 2*sqrt(2)*smagorinsky**2 * pi_norm / D.c_s**4) - tau)
#+END_SRC

Finally the resulting per-cell relaxation time is simply plugged into the existing BGK collision operator to yield the
complete Smagorinsky BGK collision step.

#+BEGIN_SRC python :session :results none
def smagorinsky_bgk_collision_code_block(D, tau, smagorinsky):
    f_rho = realize_indexed(realize_rho(D), f, f_curr)
    f_u = [ realize_indexed(realize_u_i(D, i), f, f_curr) for i in range(D.d) ]
    f_eq = [ realize_f_eq_i(D, i).rhs for i in range(D.q) ]
    eff_tau = effective_tau(D, f_curr, f_eq, tau, smagorinsky)
    f_post_collide = [ bgk_collision(f_curr[i], f_next[i], f_eq[i], eff_tau) for i in range(D.q) ]
    return CodeBlock(f_rho, *f_u, *f_post_collide).cse(optimizations = custom_opti)
#+END_SRC

This way the BGK collisions are numerically stabilized for low resolutions and high Reynolds numbers.

#+NAME: smagorinsky-bgk-collide-to-f_next
#+BEGIN_SRC python :session :results output :cache yes
D = descriptor[lattice]
printcode(smagorinsky_bgk_collision_code_block(D, tau, smagorinsky))
#+END_SRC

#+RESULTS[b6cd612f0c97e3da6908e302f304b8a50516eb05]: smagorinsky-bgk-collide-to-f_next
#+begin_example
T x0 = f_curr[1] + f_curr[2];
T x1 = f_curr[3] + f_curr[6];
T x2 = x0 + x1 + f_curr[0] + f_curr[4] + f_curr[5] + f_curr[7] + f_curr[8];
T x3 = f_curr[0] - f_curr[8];
T x4 = T{1} / (x2);
T x5 = T{72.0000000000000}*f_curr[2];
T x6 = T{72.0000000000000}*f_curr[6];
T rho = x2;
T x31 = T{4.00000000000000}*rho;
T x40 = T{2.00000000000000}*rho;
T u_0 = -x4*(x0 + x3 - f_curr[6] - f_curr[7]);
T x7 = T{6.00000000000000}*u_0;
T x8 = -x7;
T x15 = u_0*u_0;
T x16 = T{3.00000000000000}*x15;
T x17 = -x16;
T x27 = x16 + T{-2.00000000000000};
T u_1 = -x4*(x1 + x3 - f_curr[2] - f_curr[5]);
T x9 = u_0 - u_1;
T x10 = T{9.00000000000000}*(x9*x9);
T x11 = u_1*u_1;
T x12 = T{3.00000000000000}*x11;
T x13 = T{2.00000000000000} - x12;
T x14 = T{6.00000000000000}*u_1;
T x18 = x14 + x17;
T x19 = x13 + x18;
T x20 = x10 + x19 + x8;
T x21 = rho*x20;
T x22 = x10 + x13 - x14 + x17 + x7;
T x23 = rho*x22;
T x24 = u_0 + u_1;
T x25 = T{9.00000000000000}*(x24*x24);
T x26 = x19 + x25 + x7;
T x28 = x12 + x27;
T x29 = x14 - x25 + x28 + x7;
T x30 = rho*x26 - rho*x29 - T{72.0000000000000}*f_curr[0] - T{72.0000000000000}*f_curr[8];
T x32 = x13 + T{6.00000000000000}*x15;
T x33 = x32 + x8;
T x34 = x32 + x7;
T x35 = x21 + x23 + x30 - x5 - x6;
T x36 = T{6.00000000000000}*x11;
T x37 = x14 + x27 - x36;
T x38 = x18 + x36 + T{2.00000000000000};
T x39 = T{1} / (tau + sqrt(T{0.707106781186548}*(smagorinsky*smagorinsky)*sqrt((-x21 - x23 + x30 + x5 + x6)*(-x21 - x23 + x30 + x5 + x6) + T{0.500000000000000}*((x31*x33 + x31*x34 + x35 - 72*f_curr[1] - 72*f_curr[7])*(x31*x33 + x31*x34 + x35 - 72*f_curr[1] - 72*f_curr[7])) + T{0.500000000000000}*((-x31*x37 + x31*x38 + x35 - 72*f_curr[3] - 72*f_curr[5])*(-x31*x37 + x31*x38 + x35 - 72*f_curr[3] - 72*f_curr[5]))) + tau*tau));
f_next[0] = -T{0.0138888888888889}*x39*(x29*x40 + T{144.000000000000}*f_curr[0]) + f_curr[0];
f_next[1] = T{0.0555555555555556}*x39*(x33*x40 - T{36.0000000000000}*f_curr[1]) + f_curr[1];
f_next[2] = T{0.0138888888888889}*x39*(x20*x40 - T{144.000000000000}*f_curr[2]) + f_curr[2];
f_next[3] = -T{0.0555555555555556}*x39*(x37*x40 + T{36.0000000000000}*f_curr[3]) + f_curr[3];
f_next[4] = -T{0.111111111111111}*x39*(T{4.00000000000000}*rho*x28 + T{18.0000000000000}*f_curr[4]) + f_curr[4];
f_next[5] = T{0.0555555555555556}*x39*(x38*x40 - T{36.0000000000000}*f_curr[5]) + f_curr[5];
f_next[6] = T{0.0138888888888889}*x39*(x22*x40 - T{144.000000000000}*f_curr[6]) + f_curr[6];
f_next[7] = T{0.0555555555555556}*x39*(x34*x40 - T{36.0000000000000}*f_curr[7]) + f_curr[7];
f_next[8] = T{0.0138888888888889}*x39*(x26*x40 - T{144.000000000000}*f_curr[8]) + f_curr[8];
#+end_example


#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/smagorinsky_collide.h
#pragma once
#include <LLBM/call_tag.h>

struct SmagorinskyBgkCollideO {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, T tau, T smagorinsky) {
  <<smagorinsky-bgk-collide-to-f_next(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, T tau, T smagorinsky) {
  <<smagorinsky-bgk-collide-to-f_next(lattice="D3Q19")>>
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/bulk.h
#include "kernel/smagorinsky_collide.h"
#+END_SRC

* Boundary conditions
Real-world  simulations are limited by the available computational resources. This means that we can not allocate
an infinitely large lattice and consequently we at a minimum need to prescribe some conditions for the outer boundary
of our finite lattice -- even in cases where we only want to simulate a fluid without any obstacles.
In practice we commonly want to do both: Prescribe some inflow and outflow conditions as well as various boundaries
that represent some obstacle geometry. This way we could for example create a virtual wind tunnel where fluid enters
the domain on one side, is kept in line by smooth free slip walls, encounters some obstacle whose aerodynamic
properties we want to investigate and exits the simulation lattice on the other side.
** Bounce Back
To fit bounce back's reputation as the simplest LBM boundary condition we do not require any
fancy expression trickery to generate its code. This boundary condition simply reflects back
all populations the way they came from. As such it models a solid wall with no tangential velocity
at the boundary.

#+BEGIN_SRC python :session :results none
def bounce_back(D, populations):
    return [ Assignment(f_next[i], populations[D.c.index(-c_i)]) for i, c_i in enumerate(D.c) ]
#+END_SRC

#+NAME: bounce-back-full-way
#+BEGIN_SRC python :session :results output
D = descriptor[lattice]
printcode(CodeBlock(*bounce_back(D, IndexedBase('f_curr', D.q))))
#+END_SRC

#+RESULTS: bounce-back-full-way
: f_next[0] = f_curr[8];
: f_next[1] = f_curr[7];
: f_next[2] = f_curr[6];
: f_next[3] = f_curr[5];
: f_next[4] = f_curr[4];
: f_next[5] = f_curr[3];
: f_next[6] = f_curr[2];
: f_next[7] = f_curr[1];
: f_next[8] = f_curr[0];

If this is used to model the walls of a simple pipe setup we will observe the well known Poiseuille velocity profile.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/bounce_back.h
#pragma once
#include <LLBM/call_tag.h>

struct BounceBackO {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid) {
  <<bounce-back-full-way(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid) {
  <<bounce-back-full-way(lattice="D3Q19")>>
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/boundary.h
#include "kernel/bounce_back.h"
#+END_SRC

** Moving Wall Bounce Back
Modeling solid unmoving obstacles using e.g. bounce back is nice enough but in practice
we commonly want to induce some kind of movement in our fluids. While this can be done
by e.g. prescribing an inflow velocity using [[*Prescribed Equilibrium][prescribed equilibrium boundaries]], bounce
back can be modified to represent not just a solid wall but also some momentum exerted
on the fluid.

#+BEGIN_SRC python :session :results none
def moving_wall_correction(D, i):
    u_raw = symarray('u', D.d)
    return 2 * D.w[D.c.index(-D.c[i])] / D.c_s**2 * -D.c[i].dot(Matrix(u_raw))
#+END_SRC

The simplest way of incorporating such movement into bounce back is to add the velocity
components tangential to the respective population's direction.

#+BEGIN_SRC python :session :results none
def moving_wall_bounce_back(D, populations):
    return [ Assignment(expr.lhs, expr.rhs - moving_wall_correction(D, i))
             for i, expr
             in enumerate(bounce_back(D, populations)) ]
#+END_SRC

#+NAME: bounce-back-full-way-moving-wall
#+BEGIN_SRC python :session :results output
D = descriptor[lattice]
printcode(CodeBlock(*moving_wall_bounce_back(D, IndexedBase('f_curr', D.q))))
#+END_SRC

#+RESULTS: bounce-back-full-way-moving-wall
: f_next[0] = -T{0.166666666666667}*u_0 - T{0.166666666666667}*u_1 + f_curr[8];
: f_next[1] = -T{0.666666666666667}*u_0 + f_curr[7];
: f_next[2] = -T{0.166666666666667}*u_0 + T{0.166666666666667}*u_1 + f_curr[6];
: f_next[3] = -T{0.666666666666667}*u_1 + f_curr[5];
: f_next[4] = f_curr[4];
: f_next[5] = T{0.666666666666667}*u_1 + f_curr[3];
: f_next[6] = T{0.166666666666667}*u_0 - T{0.166666666666667}*u_1 + f_curr[2];
: f_next[7] = T{0.666666666666667}*u_0 + f_curr[1];
: f_next[8] = T{0.166666666666667}*u_0 + T{0.166666666666667}*u_1 + f_curr[0];

Strictly speaking this should only be used to model tangentially moving walls (such as in the 
[[*Lid-driven Cavity][lid-driven cavity]] example). More complex situations are possible but require boundary
conditions to e.g. track the position of obstacles during the simulation.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/bounce_back_moving_wall.h
#pragma once
#include <LLBM/call_tag.h>

struct BounceBackMovingWallO {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, T u_0, T u_1) {
  <<bounce-back-full-way-moving-wall(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, T u_0, T u_1, T u_2) {
  <<bounce-back-full-way-moving-wall(lattice="D3Q19")>>
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/boundary.h
#include "kernel/bounce_back_moving_wall.h"
#+END_SRC

** Free Slip Boundary
This is another special case of the bounce back boundaries where populations are reflected
specularly with respect to a given normal vector instead of simply bouncing them back
the way they came from.

#+BEGIN_SRC python :session :results none
def bounce_back_free_slip(D, populations, n):
    return [ Assignment(f_next[i], populations[D.c.index(2*n.dot(-c_i)*n+c_i)])
             for i, c_i in enumerate(D.c) ]
#+END_SRC

#+NAME: bounce-back-full-way-specular-reflection
#+BEGIN_SRC python :session :results output :var normal='(0 1)
D = descriptor[lattice]
printcode(CodeBlock(*bounce_back_free_slip(D, IndexedBase('f_curr', D.q), Matrix(normal))))
#+END_SRC

#+RESULTS: bounce-back-full-way-specular-reflection
: f_next[0] = f_curr[2];
: f_next[1] = f_curr[1];
: f_next[2] = f_curr[0];
: f_next[3] = f_curr[5];
: f_next[4] = f_curr[4];
: f_next[5] = f_curr[3];
: f_next[6] = f_curr[8];
: f_next[7] = f_curr[7];
: f_next[8] = f_curr[6];

Such a boundary condition is able to represent non-zero tangential /free slip/ velocities.
The mapping between pre- and post-collision velocities is of course specific to each
wall normal. We use tag dispatching for allowing the use to select which kind of wall
each boundary condition call represents.

#+BEGIN_SRC cpp :tangle tangle/LLBM/wall.h
#pragma once

template <int N_0, int N_1, int N_2=0>
struct WallNormal { };
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/free_slip.h
#pragma once
#include <LLBM/call_tag.h>
#include <LLBM/wall.h>
#include <LLBM/descriptor.h>

struct BounceBackFreeSlipO {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, WallNormal<1,0>) {
  <<bounce-back-full-way-specular-reflection(lattice="D2Q9", normal='(1 0))>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, WallNormal<0,1>) {
  <<bounce-back-full-way-specular-reflection(lattice="D2Q9", normal='(0 1))>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, WallNormal<0,1,0>) {
  <<bounce-back-full-way-specular-reflection(lattice="D3Q19", normal='(0 1 0))>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, WallNormal<0,0,1>) {
  <<bounce-back-full-way-specular-reflection(lattice="D3Q19", normal='(0 0 1))>>
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/boundary.h
#include "kernel/free_slip.h"
#+END_SRC

** Interpolated Bounce Back
#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/bouzidi.h
#pragma once
#include <LLBM/call_tag.h>
#include <LLBM/lattice.h>

<<bouzidi-config>>
#+END_SRC

Following the approach by Bouzidi et al. cite:bouzidiMomentumTransferBoltzmannlattice2001
an improved version of plain bounce back can be formulated using the distance between cell and wall.
This /interpolated/ bounce back condition reconstructs the missing populations using a basic linear
interpolation w.r.t. a precomputed wall distance factor $q$.

$$\begin{align*}
f_i(x_f,t+\delta t) &= 2q f_j(x_f,t) + (1-2q) f_j(x_{f} + \delta x \xi_i,t)  && q \leq \frac{1}{2} \\
f_i(x_f,t+\delta t) &= \frac{1}{2q}f_j(x_f,t) + \left(1 - \frac{1}{2q}\right) f_i(x_f,t) && q > \frac{1}{2}
\end{align*}$$

Note that the case distinction can be unified into a single case by precomputing
distance and wall velocity correction factors.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/bouzidi.h
struct BouzidiO {

using call_tag = tag::call_by_list_index;

template <typename T, typename S, typename DESCRIPTOR>
__device__ static void apply(
    LatticeView<DESCRIPTOR,S> lattice
  , std::size_t index
  , std::size_t count
  , BouzidiConfig<S> config
) {
  pop_index_t& iPop = config.missing[index];
  pop_index_t  jPop = descriptor::opposite<DESCRIPTOR>(iPop);
  pop_index_t  kPop = config.boundary[index] == config.fluid[index] ? iPop : jPop;

  S f_bound_j = *lattice.pop(jPop, config.boundary[index]);
  S f_fluid_j = *lattice.pop(kPop, config.fluid[index]);
  S* f_next_i =  lattice.pop(iPop, config.solid[index]);

  *f_next_i = config.distance[index] * f_bound_j
            + (1. - config.distance[index]) * f_fluid_j
            + config.correction[index];
}

};
#+END_SRC

The cells locations $x_f$, $x_f + \xi_i$  in addition to distance factors $q$, velocity corrections and the
missing population index to be reconstructed are stored in a =InterpolatedBounceBackConfig=
structure. This simplifies passing of all relevant data to the GPU kernel.

#+NAME: bouzidi-config
#+BEGIN_SRC cpp
template <typename S>
struct BouzidiConfig {
  std::size_t* boundary; // boundary cell to be interpolated
  std::size_t* solid;    // adjacent solid cell
  std::size_t* fluid;    // adjacent fluid cell
  S* distance;           // precomputed distance factor q
  S* correction;         // correction for moving walls
  pop_index_t* missing;  // population to be reconstructed
};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/boundary.h
#include "kernel/bouzidi.h"
#+END_SRC

** Prescribed Equilibrium
One way of modeling an open boundary of our simulation domain is to prescribe either the velocity or the density at the wall cell.
To realize this prescription we have to set the missing populations accordingly. The simplest way to that is to set all populations
of the wall cell to the equilibrium values given by velocity and density.
i.e. we have to recover the density if we are given the wall-normal velocity and vice versa.

To do this we will use SymPy for solving the missing moment for a set of unknown populations and the prescribed boundary
condition. As the =solve= function doesn't seem to work with the =Indexed= type we used to represent the population values we
need helper methods for converting between indexed symbols and an array of plain symbols.

#+BEGIN_SRC python :session :results none
def replace_symarray_with_indexed(expr, arr, idx):
    return expr.replace(lambda expr: expr.is_Symbol and expr in list(arr),
                        lambda i: idx[list(arr).index(i)])
#+END_SRC

The prescribed and recovered moments will get an underscore =w= to distinguish them from normal population moments.

#+BEGIN_SRC python :session :results none
rho_w, u_w = symbols('rho_w, u_w')
#+END_SRC

As we have four respectively six possible axis-orthogonal inflow walls we want to package the rho solution into a reusable
function that takes the wall normal as input.

*** Velocity boundary
#+BEGIN_SRC python :session :results none
def recover_rho_w(D, c_w):
    f_raw  = symarray('f', D.q)
    
    wall_normal_idx = next(i for i, c_w_i in enumerate(c_w) if c_w_i != 0)
    
    f_raw_rho = realize_indexed(realize_rho(D), f, f_raw)
    f_raw_u = [ realize_indexed(realize_u_i(D, i), f, f_raw) for i in range(D.d) ]
    
    rho_w_def = Eq(rho_w, f_raw_rho.rhs.doit())
    
    missing_c = filter(lambda c_i: c_i[wall_normal_idx] != 0 and c_i[wall_normal_idx] == c_w[wall_normal_idx], D.c)
    missing_pops = [ f_raw[i] for i in [ D.c.index(c_i) for c_i in missing_c ] ]
    
    missing_pops_given_by_rho_w = solve(rho_w_def, sum(missing_pops))
    missing_pops_given_by_rho_w = next(s for s in missing_pops_given_by_rho_w if s != 0)
    
    u_w_def = Eq(rho_w * u_w, rho_w_def.rhs * f_raw_u[wall_normal_idx].rhs)
    missing_pops_given_by_u_w = solve(u_w_def, sum(missing_pops))
    missing_pops_given_by_u_w = next(s for s in missing_pops_given_by_u_w if s != 0)
    
    missing_pops_solution = solve(Eq(missing_pops_given_by_rho_w, missing_pops_given_by_u_w), rho_w, minimal=True)
    missing_pops_solution = next(s for s in missing_pops_solution if s != 0)
    
    return Assignment(rho_w, replace_symarray_with_indexed(missing_pops_solution, f_raw, f))
#+END_SRC

This function simply constructs two definitions for the set of missing populations using either the wall velocity or the value of rho.
As these definitions must be equal in a valid system we can solve them for the desired reconstruction of rho.

#+BEGIN_SRC python :session :results output :wrap latex
D = descriptor[lattice]
printlatexpr(recover_rho_w(D, [0,1]))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
\rho_{w} &:= - \frac{2 {f}_{0} + {f}_{1} + 2 {f}_{3} + {f}_{4} + 2 {f}_{6} + {f}_{7}}{u_{w} - 1} \\
\end{align*}$$
#+end_latex

#+BEGIN_SRC python :session :results none
def recover_rho_code_block(D, populations, normal):
    rho_def = recover_rho_w(D, normal).subs(rho_w, rho)
    return CodeBlock(realize_indexed(rho_def, f, populations))
#+END_SRC

#+NAME: recover-rho-using-wall-velocity
#+BEGIN_SRC python :session :results output :var normal='(1 0)
D = descriptor[lattice]
printcode(recover_rho_code_block(D, IndexedBase('f_curr', q), normal))
#+END_SRC

#+RESULTS: recover-rho-using-wall-velocity
: T rho = -(T{2.00000000000000}*f_curr[0] + T{2.00000000000000}*f_curr[1] + T{2.00000000000000}*f_curr[2] + f_curr[3] + f_curr[4] + f_curr[5])/(u_w + T{-1.00000000000000});

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/equilibrium_velocity_wall.h
#pragma once
#include <LLBM/call_tag.h>
#include <LLBM/wall.h>
#include <LLBM/descriptor.h>

struct EquilibriumVelocityWallO {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, T u_w, WallNormal<1,0>) {
  <<recover-rho-using-wall-velocity(lattice="D2Q9", normal='(1 0))>>
  T u_0 = u_w;
  T u_1 = 0.;
  <<equilibrium-from-moments(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, T u_w, WallNormal<-1,0>) {
  <<recover-rho-using-wall-velocity(lattice="D2Q9",normal='(-1 0))>>
  T u_0 = u_w;
  T u_1 = 0;
  <<equilibrium-from-moments(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, T u_w, WallNormal<1,0,0>) {
  <<recover-rho-using-wall-velocity(lattice="D3Q19", normal='(1 0 0))>>
  T u_0 = u_w;
  T u_1 = 0;
  T u_2 = 0;
  <<equilibrium-from-moments(lattice="D3Q19")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, T u_w, WallNormal<-1,0,0>) {
  <<recover-rho-using-wall-velocity(lattice="D3Q19", normal='(-1 0 0))>>
  T u_0 = u_w;
  T u_1 = 0;
  T u_2 = 0;
  <<equilibrium-from-moments(lattice="D3Q19")>>
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/boundary.h
#include "kernel/equilibrium_velocity_wall.h"
#+END_SRC

*** Density boundary
#+BEGIN_SRC python :session :results none
def recover_u_w(D, c_w):
    f_raw  = symarray('f', D.q)
    
    wall_normal_idx = next(i for i, c_w_i in enumerate(c_w) if c_w_i != 0)
    
    f_raw_rho = realize_indexed(realize_rho(D), f, f_raw)
    f_raw_u = realize_indexed(realize_u_i(D, wall_normal_idx), f, f_raw)
    
    rho_w_def = Eq(rho_w, f_raw_rho.rhs.doit())
    
    missing_c = list(filter(lambda c_i: c_i[wall_normal_idx] != 0 and c_i[wall_normal_idx] == c_w[wall_normal_idx], D.c))
    missing_pops = [ f_raw[i] for i in [ D.c.index(c_i) for c_i in missing_c ] ]
    
    missing_pops_given_by_rho_w = solve(rho_w_def, sum(missing_pops))
    missing_pops_given_by_rho_w = next(s for s in missing_pops_given_by_rho_w if s != 0)
    
    u_w_def = Eq(rho_w * u_w, rho_w_def.rhs * f_raw_u.rhs)
    missing_pops_given_by_u_w = solve(u_w_def, sum(missing_pops))
    missing_pops_given_by_u_w = next(s for s in missing_pops_given_by_u_w if s != 0)
    
    missing_pops_solution = solve(Eq(missing_pops_given_by_rho_w, missing_pops_given_by_u_w), u_w, minimal=True)
    missing_pops_solution = next(s for s in missing_pops_solution if s != 0)
    
    return Assignment(u_w, replace_symarray_with_indexed(missing_pops_solution, f_raw, f))
#+END_SRC

The only difference between this function and the previous one is that we solve for the wall-normal velocity instead of for the wall density.

#+BEGIN_SRC python :session :results output :wrap latex
D = descriptor[lattice]
printlatexpr(recover_u_w(D, [1,0]))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
u_{w} &:= \frac{\rho_{w} - 2 {f}_{0} - 2 {f}_{1} - 2 {f}_{2} - {f}_{3} - {f}_{4} - {f}_{5}}{\rho_{w}} \\
\end{align*}$$
#+end_latex

#+BEGIN_SRC python :session :results none
def recover_u_code_block(D, populations, normal):
    u_def = recover_u_w(D, normal).subs(u_w, Symbol('u'))
    return CodeBlock(realize_indexed(u_def, f, populations))
#+END_SRC

#+NAME: recover-u-using-wall-density
#+BEGIN_SRC python :session :results output :var normal='(0 1)
D = descriptor[lattice]
printcode(recover_u_code_block(D, IndexedBase('f_curr', q), normal))
#+END_SRC

#+RESULTS: recover-u-using-wall-density
: T u = (rho_w - T{2.00000000000000}*f_curr[0] - f_curr[1] - T{2.00000000000000}*f_curr[3] - f_curr[4] - T{2.00000000000000}*f_curr[6] - f_curr[7])/rho_w;

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/equilibrium_density_wall.h
#pragma once
#include <LLBM/call_tag.h>
#include <LLBM/wall.h>
#include <LLBM/descriptor.h>

struct EquilibriumDensityWallO {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, T rho_w, WallNormal<1,0>) {
  <<recover-u-using-wall-density(lattice="D2Q9", normal='(1 0))>>
  T rho = rho_w;
  T u_0 = u;
  T u_1 = 0.;
  <<equilibrium-from-moments(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D2Q9, S f_curr[9], S f_next[9], std::size_t gid, T rho_w, WallNormal<-1,0>) {
  <<recover-u-using-wall-density(lattice="D2Q9",normal='(-1 0))>>
  T rho = rho_w;
  T u_0 = u;
  T u_1 = 0.;
  <<equilibrium-from-moments(lattice="D2Q9")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, T rho_w, WallNormal<1,0,0>) {
  <<recover-u-using-wall-density(lattice="D3Q19", normal='(1 0 0))>>
  T rho = rho_w;
  T u_0 = u;
  T u_1 = 0.;
  T u_2 = 0.;
  <<equilibrium-from-moments(lattice="D3Q19")>>
}

template <typename T, typename S>
__device__ static void apply(descriptor::D3Q19, S f_curr[19], S f_next[19], std::size_t gid, T rho_w, WallNormal<-1,0,0>) {
  <<recover-u-using-wall-density(lattice="D3Q19", normal='(-1 0 0))>>
  T rho = rho_w;
  T u_0 = u;
  T u_1 = 0.;
  T u_2 = 0.;
  <<equilibrium-from-moments(lattice="D3Q19")>>
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/boundary.h
#include "kernel/equilibrium_density_wall.h"
#+END_SRC

* Propagation Pattern
Up until now the symbolic expressions and the generated code did not explicitly implement the
second essential part of the LBM algorithm: propagation. Rather the propagation was modelled
abstractly by reading from some population =f_curr= and writing to another population =f_next=.
To remedy this we will now describe how =f_curr= and =f_next= are actually represented in memory.
This representation will then allow /implicit/ propagation by changing the pointers that are used
to access it.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
#pragma once

#include "memory.h"
#include "descriptor.h"
#include "kernel/propagate.h"

#include <cuda.h>
#include <cuda/runtime_api.hpp>
#+END_SRC

Our code employs the /Periodic Shift (PS)/ cite:kummerlanderImplicitPropagationDirectly2021 propagation
pattern to perform the streaming step of the LB algorithm. This pattern uses a /Structure of Arrays/ data layout for the
populations where each individual array is viewed as cyclic. The Sweep space filling curve is used as the bijection
between these one dimensional arrays and spatial cell locations. 
As the distance between any two cells along some fixed vector is invariant of the specific cell
locations propagation is equivalent to rotating the population arrays. Such rotation can be
implemented without data transfer by shifting the start pointers in a control structure.

The control structure describes the mapping between cells and memory locations for
a specific point in time. We group all neccessary data into a /LatticeView/ structure.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
template <typename DESCRIPTOR, typename S>
struct LatticeView {
  const descriptor::Cuboid<DESCRIPTOR> cuboid;
  S** population;

  __device__ __forceinline__
  S* pop(pop_index_t iPop, std::size_t gid) const;
};
#+END_SRC

This lightweight structure will be passed by-value to any kernel functions and is the only way for
collision operators, functors and boundary conditions to access lattice data.

** Memory
As the population memory layout and propagation algorithm are codependent we implement
them in a single /CyclicPopulationBuffer/ class. This class will manage the \(q\)  individual device-side
cyclic arrays together with their control structure.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
template <typename DESCRIPTOR, typename S>
class CyclicPopulationBuffer {
protected:
  const descriptor::Cuboid<DESCRIPTOR> _cuboid;

  const std::size_t _page_size;
  const std::size_t _volume;

  CUmemGenericAllocationHandle _handle[DESCRIPTOR::q];
  CUmemAllocationProp _prop{};
  CUmemAccessDesc _access{};
  CUdeviceptr _ptr;

  SharedVector<S*> _base;
  SharedVector<S*> _population;

  S* device() {
    return reinterpret_cast<S*>(_ptr);
  }

public:
  CyclicPopulationBuffer(descriptor::Cuboid<DESCRIPTOR> cuboid);
  ~CyclicPopulationBuffer();

  LatticeView<DESCRIPTOR,S> view() {
    return LatticeView<DESCRIPTOR,S>{ _cuboid, _population.device() };
  }

  void stream();

};
#+END_SRC

In order to enable rotation of cyclic arrays by shifting only the start pointer in /LatticeView/ we need
to perform the index wrapping at the end of the physical array as efficiently as possible. In turns
out that this can be done at virtually no cost by using the in-hardware virtual address translation
logic. Doing so requires the array sizes to be exact multiples of the device page size.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
std::size_t getDevicePageSize() {
  auto device = cuda::device::current::get();
  std::size_t granularity = 0;
  CUmemAllocationProp prop = {};
  prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
  prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
  prop.location.id = device.id();
  cuMemGetAllocationGranularity(&granularity, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM);
  return granularity;
}
#+END_SRC

The concrete page size value which is 2 MiB on current Nvidia GPUs can now be used to round the
in-memory size of each population array to the nearest page boundary.

** Initialization
#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
template <typename DESCRIPTOR, typename S>
CyclicPopulationBuffer<DESCRIPTOR,S>::CyclicPopulationBuffer(
  descriptor::Cuboid<DESCRIPTOR> cuboid):
  _cuboid(cuboid),
  _page_size{getDevicePageSize()},
  _volume{((cuboid.volume * sizeof(S) - 1) / _page_size + 1) * _page_size},
  _base(DESCRIPTOR::q),
  _population(DESCRIPTOR::q)
{
#+END_SRC

After calculating the page-aligned memory size and constructing two vectors of population
pointers for the control strucuture we are ready to place two consecutive views of the same
physical array in virtual memory.

To do this we first need to know which device is currently selected.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
  auto device = cuda::device::current::get();
#+END_SRC

Using this device ID, a device-pinned address area large enough to fit two full views of the
lattice can be reserved.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
  _prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
  _prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
  _prop.location.id = device.id();
  cuMemAddressReserve(&_ptr, 2 * _volume * DESCRIPTOR::q, 0, 0, 0);
#+END_SRC

The /structure of cyclic arrays/ required for our chosen propagation pattern is then
mapped into this address area.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
  for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
    // per-population handle until cuMemMap accepts non-zero offset
    cuMemCreate(&_handle[iPop], _volume, &_prop, 0);
    cuMemMap(_ptr + iPop * 2 * _volume,           _volume, 0, _handle[iPop], 0);
    cuMemMap(_ptr + iPop * 2 * _volume + _volume, _volume, 0, _handle[iPop], 0);
  }
#+END_SRC

Actually reading from and writing to locations within this memory depends on setting
the correct access flags

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
  _access.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
  _access.location.id = device.id();
  _access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
  cuMemSetAccess(_ptr, 2 * _volume * DESCRIPTOR::q, &_access, 1);
#+END_SRC

after which we are ready to initialize the buffer with lattice equilibrium values.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
  for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
    float eq = descriptor::weight<DESCRIPTOR>(iPop);
    cuMemsetD32(_ptr + iPop * 2 * _volume, *reinterpret_cast<int*>(&eq), 2 * (_volume / sizeof(S)));
  }
#+END_SRC

As the rotation of the cyclic arrays is to be realized by shifting the per-population start pointers
we also need to store those somewhere.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
  for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
    _base[iPop] = this->device() + iPop * 2 * (_volume / sizeof(S));
    _population[iPop] = _base[iPop] + iPop * ((_volume / sizeof(S)) / DESCRIPTOR::q);
  }

  _base.syncDeviceFromHost();
  _population.syncDeviceFromHost();
}
#+END_SRC

Finally, once the population buffer is no longer needed, we should also release the
mapped memory again.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
template <typename DESCRIPTOR, typename S>
CyclicPopulationBuffer<DESCRIPTOR,S>::~CyclicPopulationBuffer() {
  cuMemUnmap(_ptr, 2 * _volume * DESCRIPTOR::q);
  for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
    cuMemRelease(_handle[iPop]);
  }
  cuMemAddressFree(_ptr, 2 * _volume * DESCRIPTOR::q);
}
#+END_SRC

** Access
The common interface of most of out GPU kernels is to accept an array of current propulations and
write the new populations to another array. This way we can control where the populations are read
from and stored to at a central location.

#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h
template <typename DESCRIPTOR, typename S>
__device__ __forceinline__
S* LatticeView<DESCRIPTOR,S>::pop(pop_index_t iPop, std::size_t gid) const {
  return population[iPop] + gid;
}
#+END_SRC

In practice a slight performance improvement can be observed on some GPUs when only evaluating
this addition once per-kernel and caching the resulting locations.

#+NAME: read-f-curr
#+BEGIN_SRC cpp
S* preshifted_f[DESCRIPTOR::q];
for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
  preshifted_f[iPop] = lattice.pop(iPop, gid);
  f_curr[iPop] = *preshifted_f[iPop];
}
#+END_SRC

At this point the various kernel functions can execute a generic operator on a cell's
populations without knowing anything about where the cell data is stored.

The preshifted pointers are then reused to perform the store operations after
the generic operator implementation is done with its work.

#+NAME: write-f-next
#+BEGIN_SRC cpp
for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
  *preshifted_f[iPop] = f_next[iPop];
}
#+END_SRC

** Update
#+BEGIN_SRC cpp :tangle tangle/LLBM/propagate.h :noweb no
template <typename DESCRIPTOR, typename S>
void CyclicPopulationBuffer<DESCRIPTOR,S>::stream() {
  cuda::launch(propagate<DESCRIPTOR,S>,
               cuda::launch_configuration_t(1,1),
               view(), _base.device(), _volume / sizeof(S));
}
#+END_SRC

The =propagate= kernel shifts the start pointers of each population array by the respective
discrete velocity offset and performs wrapping if necessary. This ensures that the actual
population accesses are always presented a contiguous view of the full array.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/propagate.h
#pragma once

template <typename DESCRIPTOR, typename S>
class LatticeView;

template <typename DESCRIPTOR, typename S>
__global__ void propagate(LatticeView<DESCRIPTOR,S> lattice, S** base, std::size_t size) {
#+END_SRC

It is very important to use the correct types when doing pointer arithmetic.

Rotation is performed by shifting the start position of each population array by the invariant
neighborhood distance given by its discrete velocity vector. As this operation can cross the
array boundaries special care has to be taken in wrapping these invalid positions back into
the array.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/propagate.h
  for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
    std::ptrdiff_t shift = -descriptor::offset<DESCRIPTOR>(lattice.cuboid, iPop);

    lattice.population[iPop] += shift;

    if (lattice.population[iPop] < base[iPop]) {
      lattice.population[iPop] += size;
    } else if (lattice.population[iPop] + size > base[iPop] + 2*size) {
      lattice.population[iPop] -= size;
    }
  }
}
#+END_SRC

* Geometry Modeling
One straight forward way to define arbitrarily complex geometries that are amenable to both
boundary parametrization and usage in just-in-time visualization are /signed distance functions/.

$$d : \mathbb{R}^d \to \mathbb{R}$$

If such a function $d$ is constructed in a way to return the shortest distance to the obstacle surface
for every point in space then those distances are positive for any point outside of the obstacle and
negative for any point inside of it. This is where the /signed/ in SDF comes from.

Note that SDFs do not in general return the true shortest distance to the surface as measured by
e.g. the Euclidean norm but rather a bound of the distance. This is especially the case when one
combines multiple distance functions using boolean operators. Luckily we can still approximate
the true distance using iteration.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
#pragma once
#include <vector_types.h>
#include <cuda-samples/Common/helper_math.h>
#+END_SRC

** Sphere tracing
Sphere tracing provides an approximation of the true euclidean distance to the surface defined by a SDF in the direction
of some ray even when the provided distance is only a bound of the true distance. For a lower bound this is straight forward
to see as the convergence may take longer if shortest distance sphere is not as large as possible but it will still happen after
a sufficiently high number of iterations. An upper bound SDF can be compensated by restricting the maximum step distance.
This is also useful in the other cases as we may /overshoot/ the true intersection otherwise.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
template <typename SDF, typename V>
__device__ __host__
float approximateDistance(SDF sdf, V origin, V dir, float d0, float d1, float eps=1e-2, unsigned N=128) {
  float distance = d0;
  float delta = (d1-d0) / N;
  for (unsigned i=0; i < N; ++i) {
    float d = sdf(origin + distance*dir);
    if (d < eps) {
      return distance;
    }
    distance += d;
    if (distance > d1) {
      return d1;
    }
  }
  return d1;
}
#+END_SRC

** Constructive solid geometry
A convenient way for generating SDFs for arbitrary shapes is to construct them by combining
various primitives such as spheres and boxes using boolean operators such as addition and
substraction.

A comprensive listing of different such functions is available on [[https://iquilezles.org/www/articles/distfunctions/distfunctions.htm][iquilezles.org]].
The remainder of this section translates some of these shader functions into C++
functions executable both on the host and the device.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
namespace sdf {
#+END_SRC
*** Primitives
A sphere is arguably the simplest shape to model using signed distance functions as the euklidean norm of a vector
stays constant for spherical surfaces centered on the origin. This is also the definition that is often used when defining
spherical sets in mathematics.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
template <typename V>
__device__ __host__ float sphere(V p, float r) {
  return length(p) - r;
}
#+END_SRC

Note that a 2D sphere SDF can also be used to construct cylinders in 3D space.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float box(float3 p, float3 b) {
  float3 q = fabs(p) - b;
  return length(fmaxf(q,make_float3(0))) + fmin(fmax(q.x,fmax(q.y,q.z)),0);
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float cylinder(float3 p, float r, float h) {
	return fmax(length(make_float2(p.x,p.y)) - r, fabs(p.z) - 0.5*h);
}
#+END_SRC

*** Operators
It makes intuitive sense that the union of two SDFs can be taken by using the minimum of the respective distances.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float add(float a, float b) {
  return fmin(a, b);
}
#+END_SRC

The intersection of two SDFs, i.e. their shared parts, can be generated by using the maximum of the distances.
For the intersecting part both must be below zero but if any distance is positive the sample point can obviously
not be part of the intersection.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float intersect(float a, float b) {
  return fmax(a, b);
}
#+END_SRC

The result of substracting one SDF from the other is composed by inverting the SDF to be substracted and
taking the intersection of this inversion and the other SDF.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float sub(float a, float b) {
  return intersect(-a, b);
}
#+END_SRC

Smooth versions of these constructive operators exist.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float sadd(float a, float b, float k) {
  float h = clamp(0.5f + 0.5f*(b-a)/k, 0.0f, 1.0f);
  return lerp(b, a, h) - k*h*(1.f-h);
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float ssub(float a, float b, float k) {
  float h = clamp(0.5f - 0.5f*(b+a)/k, 0.f, 1.f);
  return lerp(b, -a, h) + k*h*(1.f-h);
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float sintersect(float a, float b, float k) {
  float h = clamp(0.5f - 0.5f*(b-a)/k, 0.f, 1.f);
  return lerp(b, a, h) + k*h*(1.f-h);
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
__device__ __host__ float3 twisted(float3 p, float k) {
  float c = cos(k*p.y);
  float s = sin(k*p.y);
  float3  q = make_float3(0,0,p.y);
  q.x = p.x*c + p.z*-s;
  q.y = p.x*s + p.z* c;
  return q;
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
}
#+END_SRC

** Boundary conditions
We can now use the distance finding algorithm to provide a convenient interface for generating [[*Interpolated Bounce Back][interpolated bounce back]]
boundary parameters to fit a given SDF. This way we ensure that any displayed geometry actually fits what we simulate.

The /bogus distance/ warnings are generated when the cell's position is exactly on top of the boundary 
or farther away then the next neighbor cell in the search direction. These cases should be handled by
other boundary conditions if we are interested in the best possible results.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf_boundary.h
#pragma once
#include <LLBM/memory.h>
#include <LLBM/materials.h>
#include <LLBM/kernel/bouzidi.h>
#include <iostream>

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
class SignedDistanceBoundary {
private:
const descriptor::Cuboid<DESCRIPTOR> _cuboid;
const std::size_t _count;

SharedVector<std::size_t> _boundary;
SharedVector<std::size_t> _fluid;
SharedVector<std::size_t> _solid;
SharedVector<S> _distance;
SharedVector<S> _correction;
SharedVector<S> _factor;
SharedVector<pop_index_t> _missing;

void set(std::size_t index, std::size_t iCell, pop_index_t iPop, S dist) {
  pop_index_t jPop = descriptor::opposite<DESCRIPTOR>(iPop);
  const std::size_t jPopCell = descriptor::neighbor<DESCRIPTOR>(_cuboid, iCell, jPop);
  const std::size_t iPopCell = descriptor::neighbor<DESCRIPTOR>(_cuboid, iCell, iPop);

  _boundary[index] = iCell;
  _solid[index] = jPopCell;
  _distance[index] = dist;
  _correction[index] = 0;
  _missing[index] = iPop;

  T q = dist / descriptor::velocity_length<DESCRIPTOR>(iPop);
  if (q > 0.5) {
    _fluid[index] = iCell;
    _factor[index] = 1 / (2*q);
  } else {
    _fluid[index] = iPopCell;
    _factor[index] = 2*q;
  }
}

void syncDeviceFromHost() {
  _boundary.syncDeviceFromHost();
  _fluid.syncDeviceFromHost();
  _solid.syncDeviceFromHost();
  _distance.syncDeviceFromHost();
  _correction.syncDeviceFromHost();
  _factor.syncDeviceFromHost();
  _missing.syncDeviceFromHost();
}

public:
SignedDistanceBoundary(Lattice<DESCRIPTOR,T,S>&, CellMaterials<DESCRIPTOR>& materials, SDF geometry, int bulk, int solid):
  _cuboid(materials.cuboid()),
  _count(materials.get_link_count(bulk, solid)),
  _boundary(_count),
  _fluid(_count),
  _solid(_count),
  _distance(_count),
  _correction(_count),
  _factor(_count),
  _missing(_count)
{
  std::size_t index = 0;
  materials.for_links(bulk, solid, [&](std::size_t iCell, pop_index_t iPop) {
    auto p         = gidInverseSmooth(_cuboid, iCell);
    auto direction = normalize(descriptor::velocity<DESCRIPTOR>(iPop));
    float length   = descriptor::velocity_length<DESCRIPTOR>(iPop);
    float distance = approximateDistance(geometry, p, direction, 0, length);
    if (distance == 0.f || distance > length) {
      std::cout << "Bogus distance d=" << distance << " at cell " << iCell
                << " in direction " << std::to_string(iPop) << std::endl;
    }
    set(index++, iCell, descriptor::opposite<DESCRIPTOR>(iPop), distance);
  });
  syncDeviceFromHost();
}

template <typename VELOCITY>
void setVelocity(VELOCITY field) {
  for (std::size_t index=0; index < _count; ++index) {
    pop_index_t jPop = descriptor::opposite<DESCRIPTOR>(_missing[index]);
    auto direction = normalize(descriptor::velocity<DESCRIPTOR>(jPop));
    float length = descriptor::velocity_length<DESCRIPTOR>(jPop);
    auto p = descriptor::gidInverseSmooth(_cuboid, _boundary[index]);
    auto u_w = field(p + _distance[index] * direction);
    _correction[index] = 2*3*descriptor::weight<DESCRIPTOR>(jPop)
                       * dot(u_w, descriptor::velocity<DESCRIPTOR>(jPop));
    if (_distance[index] / length > 0.5) {
      _correction[index] *= _factor[index];
    }
  }
  _correction.syncDeviceFromHost();
}

std::size_t getCount() const {
  return _count;
}

BouzidiConfig<S> getConfig() {
  return BouzidiConfig<S>{
    _boundary.device(),
    _solid.device(),
    _fluid.device(),
    _factor.device(),
    _correction.device(),
    _missing.device()
  };
}

};

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
SignedDistanceBoundary(Lattice<DESCRIPTOR,T,S>&, CellMaterials<DESCRIPTOR>&, SDF, int, int) -> SignedDistanceBoundary<DESCRIPTOR,T,S,SDF>;
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/boundary.h
#include "sdf_boundary.h"
#+END_SRC

* Runtime Context
** Memory
#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
#pragma once

#include <memory>
#include <vector>
#include <cstring>

#include <cuda/runtime_api.hpp>
#+END_SRC

Most memory of our simulation resides solely on the GPU. While we already defined a data structure for
the population data in the propagation section we also need buffers for additional data such as functor
results or material numbers.

#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
template <typename T>
class DeviceBuffer {
protected:
  const std::size_t _size;
  cuda::device_t _device;
  cuda::memory::device::unique_ptr<T[]> _data;
#+END_SRC

Note that the value of the =_data= pointer is going to be a address in GPU memory. We only expose access to it
via a =device()= member function and not e.g. via an implicit conversion operator as it is very important to
be clear whether one refers to device or host memory. GPU kernels can only access device memory but are
called from the host which is why the value of the =_data= member is not itself stored on the device but on the
host.

#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
public:
  DeviceBuffer(std::size_t size):
    _size(size),
    _device(cuda::device::current::get()),
    _data(cuda::memory::device::make_unique<T[]>(_device, size))
  { }
  <<device-buffer-load-from-plain-data>>
  <<device-buffer-load-from-std-vector>>

  T* device() {
    return _data.get();
  }

  std::size_t size() const {
    return _size;
  }
};
#+END_SRC

The most generic way of initializing this device data structure from the host side is to pass a plain memory reference consisting
of a pointer and the size.

#+NAME: device-buffer-load-from-plain-data
#+BEGIN_SRC cpp :eval no
DeviceBuffer(const T* data, std::size_t size):
  DeviceBuffer(size) {
  cuda::memory::copy(_data.get(), data, size*sizeof(T));
}
#+END_SRC

For convenience we also implement a constructor to initialize a =DeviceBuffer= using a =std::vector= stored on the host.
Note that for this to work the =std::vector= specialization has to guarantee contiguous storage. i.e. this will not work for
=std::vector<bool>= .

#+NAME: device-buffer-load-from-std-vector
#+BEGIN_SRC cpp :eval no
DeviceBuffer(const std::vector<T>& data):
  DeviceBuffer(data.data(), data.size()) { }
#+END_SRC

While this should be enough to contain data such as lists of cell IDs or simulation results, some of this data will have to be
communicated between device and host. For this purpose we implement a =SharedVector= that maintains equally sized
memory buffers on both the GPU and the host.

#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
template <typename T>
class SharedVector : public DeviceBuffer<T> {
private:
  std::unique_ptr<T[]> _host_data;

public:
  SharedVector(std::size_t size):
    DeviceBuffer<T>(size),
    _host_data(new T[size]{}) {
    syncDeviceFromHost();
  }

  T* host() {
    return _host_data.get();
  }

  T& operator[](unsigned i) {
    return host()[i];
  }

  void syncHostFromDevice() {
    cuda::memory::copy(_host_data.get(), this->_data.get(), this->_size*sizeof(T));
  }

  void syncDeviceFromHost() {
    cuda::memory::copy(this->_data.get(), _host_data.get(), this->_size*sizeof(T));
  }

};
#+END_SRC

When visualizing data using e.g. volumetric rendering it is very convenient to access this data as textures.
Amongst other things this provides very fast in-hardware interpolation between individual /pixels/.

#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
template <typename T>
class DeviceTexture {
protected:
  cudaExtent _extent;
  cudaArray_t _array;

  cudaChannelFormatDesc _channel_desc;
  cudaResourceDesc _res_desc;
  cudaTextureDesc  _tex_desc;

  cudaTextureObject_t _texture;
  cudaSurfaceObject_t _surface;
#+END_SRC

The setup of such textures is quite a bit more involved that for plain GPU memory. The reason for this is
that a texture is actually a /view/ for data that resides in a special area of GPU memory. So we need
to first allocate the data as a 3D array of some channel description that defines the scalar type stored
by the texture. This 3D array then has to be connected to a texture object by declaring appropriate
ressource and texture description structures. The latter of which defines how the texture is addressed
and interpolated.

#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
public:
  DeviceTexture(std::size_t nX, std::size_t nY, std::size_t nZ=0):
    _extent(make_cudaExtent(nX,nY,nZ)),
    _channel_desc(cudaCreateChannelDesc<float>()) {
    cudaMalloc3DArray(&_array, &_channel_desc, _extent);

    std::memset(&_res_desc, 0, sizeof(_res_desc));
    _res_desc.resType = cudaResourceTypeArray;
    _res_desc.res.array.array = _array;

    std::memset(&_tex_desc, 0, sizeof(_tex_desc));
    _res_desc.resType = cudaResourceTypeArray;
    _tex_desc.addressMode[0]   = cudaAddressModeClamp;
    _tex_desc.addressMode[1]   = cudaAddressModeClamp;
    _tex_desc.addressMode[2]   = cudaAddressModeClamp;
    _tex_desc.filterMode       = cudaFilterModeLinear;
    _tex_desc.normalizedCoords = 0;

    cudaCreateTextureObject(&_texture, &_res_desc, &_tex_desc, NULL);
    cudaCreateSurfaceObject(&_surface, &_res_desc);
  }

  DeviceTexture(descriptor::CuboidD<3> c):
    DeviceTexture(c.nX, c.nY, c.nZ) { }

  ~DeviceTexture() {
    cudaFreeArray(_array);
  }

  cudaTextureObject_t getTexture() const {
    return _texture;
  }

  cudaSurfaceObject_t getSurface() const {
    return _surface;
  }

};
#+END_SRC

We are going to use the SFML library for straight forward displaying of textures in OpenGL.

#+BEGIN_SRC cpp :tangle tangle/util/texture.h
#pragma once

#include <cstring>
#include <SFML/Graphics.hpp>
#include <cuda_gl_interop.h>
#include <LLBM/memory.h>

cudaSurfaceObject_t bindTextureToCuda(sf::Texture& texture) {
  GLuint gl_tex_handle = texture.getNativeHandle();
  cudaGraphicsResource* cuda_tex_handle;
  cudaArray* buffer;

  cudaGraphicsGLRegisterImage(&cuda_tex_handle, gl_tex_handle, GL_TEXTURE_2D, cudaGraphicsRegisterFlagsNone);
  cudaGraphicsMapResources(1, &cuda_tex_handle, 0);
  cudaGraphicsSubResourceGetMappedArray(&buffer, cuda_tex_handle, 0, 0);

  cudaResourceDesc resDesc;
  resDesc.resType = cudaResourceTypeArray;

  resDesc.res.array.array = buffer;
  cudaSurfaceObject_t cudaSurfaceObject = 0;
  cudaCreateSurfaceObject(&cudaSurfaceObject, &resDesc);

  return cudaSurfaceObject;
}
#+END_SRC

** Descriptor Structure
Not all parts of our simulation code can be statically resolved during the tangling of this file. e.g. we might want to iterate
over all population IDs or calculate opposite indices at runtime. For this purpose we gather some data from our Python
descriptor structure into a C++ header.

#+NAME: cpp-descriptor-template
#+BEGIN_EXAMPLE cpp
struct ${D.name} {
  static constexpr unsigned d = ${D.d};
  static constexpr unsigned q = ${D.q};
};
#+END_EXAMPLE

Each descriptor is identified by such an appropriately named struct in our C++ code. The struct stores the dimension and number of characteristic velocities and
its type is used as a template argument in any further descriptor-dependent code.

#+NAME: descriptor-opposite-indices
#+BEGIN_SRC python :session :results output
def opposites(c):
    return ', '.join(map(str, [ c.index(-c_i) for _, c_i in enumerate(c) ]))

print(opposites(descriptor[lattice].c))
#+END_SRC

#+RESULTS: descriptor-opposite-indices
: 8, 7, 6, 5, 4, 3, 2, 1, 0

#+NAME: descriptor-velocities
#+BEGIN_SRC python :session :results output
def velocities(c):
    return ', '.join([ f"{{{','.join(map(str, list(c_i)))}}}" for _, c_i in enumerate(descriptor[lattice].c) ])

print(velocities(descriptor[lattice].c))
#+END_SRC

#+RESULTS: descriptor-velocities
: {-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,0}, {0,1}, {1,-1}, {1,0}, {1,1}

#+NAME: descriptor-weights
#+BEGIN_SRC python :session :results output
def weights(D):
    return ', '.join(map(lambda w: str(w.evalf()), D.w))

print(weights(descriptor[lattice]))
#+END_SRC

#+RESULTS: descriptor-weights
: 0.0277777777777778, 0.111111111111111, 0.0277777777777778, 0.111111111111111, 0.444444444444444, 0.111111111111111, 0.0277777777777778, 0.111111111111111, 0.0277777777777778

#+NAME: descriptor-invCs2
#+BEGIN_SRC python :session :results output
print((1/descriptor[lattice].c_s**2).evalf())
#+END_SRC

#+RESULTS: descriptor-invCs2
: 3.00000000000000

#+NAME: descriptor-velocity-lengths
#+BEGIN_SRC python :session :results output
def velocityLengths(c):
    return ', '.join(map(str, [ sqrt(c_i.dot(c_i)).evalf() for _, c_i in enumerate(c) ]))

print(velocityLengths(descriptor[lattice].c))
#+END_SRC

#+RESULTS: descriptor-velocity-lengths
: 1.41421356237310, 1.00000000000000, 1.41421356237310, 1.00000000000000, 0, 1.00000000000000, 1.41421356237310, 1.00000000000000, 1.41421356237310


#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
#pragma once

#include <algorithm>
#include <cstdint>
#include <type_traits>
#include <cuda-samples/Common/helper_math.h>

<<cuda-data-fix>>

using pop_index_t = std::uint8_t;

namespace descriptor {

<<eval-using-descriptor(src=cpp-descriptor-template, lattice="D2Q9")>>

<<eval-using-descriptor(src=cpp-descriptor-template, lattice="D3Q19")>>

namespace device_data {
  template <typename DESCRIPTOR>
  __constant__ pop_index_t opposite[DESCRIPTOR::q] { };

  template <typename DESCRIPTOR>
  __constant__ int c[DESCRIPTOR::q][DESCRIPTOR::d] { };

  template <typename DESCRIPTOR>
  __constant__ float c_length[DESCRIPTOR::q] { };

  template <typename DESCRIPTOR>
  __constant__ float weight[DESCRIPTOR::q] { };

  <<eval-using-descriptor(src=cpp-device-data-template, lattice="D2Q9")>>

  <<eval-using-descriptor(src=cpp-device-data-template, lattice="D3Q19")>>
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
namespace host_data {
  template <typename DESCRIPTOR>
  constexpr pop_index_t opposite[DESCRIPTOR::q] { };

  template <typename DESCRIPTOR>
  constexpr int c[DESCRIPTOR::q][DESCRIPTOR::d] { };

  template <typename DESCRIPTOR>
  constexpr float c_length[DESCRIPTOR::q] { };

  template <typename DESCRIPTOR>
  constexpr float weight[DESCRIPTOR::q] { };

  <<eval-using-descriptor(src=cpp-host-data-template, lattice="D2Q9")>>

  <<eval-using-descriptor(src=cpp-host-data-template, lattice="D3Q19")>>
}

template <typename DESCRIPTOR>
__host__ __device__
pop_index_t opposite(pop_index_t iPop) {
  return DESCRIPTOR::q - 1 - iPop;
}

template <typename DESCRIPTOR>
__host__ __device__
int velocity(pop_index_t iPop, unsigned iDim) {
  return DATA::template c<DESCRIPTOR>[iPop][iDim];
}

template <typename DESCRIPTOR>
__host__ __device__
std::enable_if_t<DESCRIPTOR::d == 2, float2> velocity(pop_index_t iPop) {
  return make_float2(DATA::template c<DESCRIPTOR>[iPop][0],
                     DATA::template c<DESCRIPTOR>[iPop][1]);
}

template <typename DESCRIPTOR>
__host__ __device__
std::enable_if_t<DESCRIPTOR::d == 3, float3> velocity(pop_index_t iPop) {
  return make_float3(DATA::template c<DESCRIPTOR>[iPop][0],
                     DATA::template c<DESCRIPTOR>[iPop][1],
                     DATA::template c<DESCRIPTOR>[iPop][2]);
}

template <typename DESCRIPTOR>
__host__ __device__
float velocity_length(pop_index_t iPop) {
  return DATA::template c_length<DESCRIPTOR>[iPop];
}

template <typename DESCRIPTOR>
__host__ __device__
float weight(pop_index_t iPop) {
  return DATA::template weight<DESCRIPTOR>[iPop];
}
#+END_SRC

Above we see an outline of the descriptor header that will contain all data exported from the Python environment in addition to some handy functions
for working with this data both on the host side and from within the actual GPU kernel functions.

#+NAME: cpp-device-data-template
#+BEGIN_EXAMPLE cpp
template <>
__constant__ pop_index_t opposite<${D.name}>[${D.q}] = {
  ${opposites(D.c)}
};

template <>
__constant__ int c<${D.name}>[${D.q}][${D.d}] = {
  ${velocities(D.c)}
};

template <>
__constant__ float c_length<${D.name}>[${D.q}] = {
  ${velocityLengths(D.c)}
};

template <>
__constant__ float weight<${D.name}>[${D.q}] = {
  ${weights(D)}
};
#+END_EXAMPLE

#+NAME: cpp-host-data-template
#+BEGIN_EXAMPLE cpp
template <>
constexpr pop_index_t opposite<${D.name}>[${D.q}] = {
  ${opposites(D.c)}
};

template <>
constexpr int c<${D.name}>[${D.q}][${D.d}] = {
  ${velocities(D.c)}
};

template <>
constexpr float c_length<${D.name}>[${D.q}] = {
  ${velocityLengths(D.c)}
};

template <>
constexpr float weight<${D.name}>[${D.q}] = {
  ${weights(D)}
};
#+END_EXAMPLE

Note that we use some preprocessor trickery to get this descriptor structure working in the same way both on the host and on the GPU device.

#+NAME: cuda-data-fix
#+BEGIN_SRC cpp
#ifdef __CUDA_ARCH__
  #define DATA device_data
#else
  #define DATA host_data
#endif
#+END_SRC

For convenience we group all commonly required headers into a single include.

#+BEGIN_SRC cpp :tangle tangle/LLBM/base.h
#pragma once

#include "descriptor.h"
#include "memory.h"
#include "lattice.h"
#include "materials.h"
#+END_SRC

** Cuboid
Our LBM code assumes that all lattices are axis-aligned cuboids with a discrete extent of cells along
each spatial dimension. Such a structure describes the regular lattice on which the population
values will be defined. As these populations need to be stored in memory we need some mapping
between their spatial locations and a linear in-memory location.

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
template <unsigned D>
struct CuboidD;

template <>
struct CuboidD<2> {
  const std::size_t nX;
  const std::size_t nY;
  const std::size_t nZ;
  const std::size_t volume;

  CuboidD(std::size_t x, std::size_t y):
    nX(x), nY(y), nZ(1),
    volume(x*y) { };
};

template <>
struct CuboidD<3> {
  const std::size_t nX;
  const std::size_t nY;
  const std::size_t nZ;
  const std::size_t volume;
  const std::size_t plane;

  CuboidD(std::size_t x, std::size_t y, std::size_t z):
    nX(x), nY(y), nZ(z),
    volume(x*y*z),
    plane(x*y) { };
};

template <typename DESCRIPTOR>
using Cuboid = CuboidD<DESCRIPTOR::d>;
#+END_SRC

This linear location is given by a =gid= function that implements a sweep space filling curve.
The neighborhood properties of this curve are the foundation for being able to perform the
propagation step implicitly by only modifying a pointer structure.

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
__host__ __device__
std::size_t gid(const CuboidD<2>& c, int iX, int iY, int iZ=0) {
  return iY*c.nX + iX;
}

__host__ __device__
std::size_t gid(const CuboidD<3>& c, int iX, int iY, int iZ) {
  return iZ*c.plane + iY*c.nX + iX;
}
#+END_SRC

The =offset= function provides the distance from a cell to its neighbors
in the given direction. This value is the same for all cells where the
direction target is well defined.

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
__host__ __device__
int offset(const CuboidD<2>& c, int iX, int iY) {
  return iY*c.nX + iX;
}

template <typename DESCRIPTOR>
__host__ __device__
int offset(const CuboidD<2>& c, pop_index_t iPop) {
  static_assert(DESCRIPTOR::d == 2, "Dimensions must match");
  return offset(c,
    descriptor::velocity<DESCRIPTOR>(iPop, 0),
    descriptor::velocity<DESCRIPTOR>(iPop, 1)
  );
}

__host__ __device__
int offset(const CuboidD<3>& c, int iX, int iY, int iZ) {
  return iZ*c.plane + iY*c.nX + iX;
}

template <typename DESCRIPTOR>
__host__ __device__
int offset(const CuboidD<3>& c, pop_index_t iPop) {
  static_assert(DESCRIPTOR::d == 3, "Dimensions must match");
  return offset(c,
    descriptor::velocity<DESCRIPTOR>(iPop, 0),
    descriptor::velocity<DESCRIPTOR>(iPop, 1),
    descriptor::velocity<DESCRIPTOR>(iPop, 2)
  );
}
#+END_SRC

The =neighbor= function is a simple wrapper to directly compute the cell index of the target
for some discrete velocity and origin cell.

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
template <typename DESCRIPTOR>
__host__ __device__
std::size_t neighbor(const CuboidD<2>& c, std::size_t iCell, pop_index_t iPop) {
  return iCell + offset<DESCRIPTOR>(c, iPop);
}

template <typename DESCRIPTOR>
__host__ __device__
std::size_t neighbor(const CuboidD<3>& c, std::size_t iCell, pop_index_t iPop) {
  return iCell + offset<DESCRIPTOR>(c, iPop);
}
#+END_SRC

For some non-performance critical situations such as during geometry initialization
we provide an inverse function of the cell index projection that maps linear locations
back into the spatial domain.

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
__host__ __device__
uint2 gidInverse(const CuboidD<2>& c, std::size_t gid) {
  int iY = gid / c.nX;
  int iX = gid % c.nX;
  return make_uint2(iX, iY);
}

__host__ __device__
uint3 gidInverse(const CuboidD<3>& c, std::size_t gid) {
  int iZ = gid / c.plane;
  int iY = (gid % c.plane) / c.nX;
  int iX = (gid % c.plane) % c.nX;
  return make_uint3(iX,iY,iZ);
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
__host__ __device__
float2 gidInverseSmooth(const CuboidD<2>& c, std::size_t gid) {
  int iY = gid / c.nX;
  int iX = gid % c.nX;
  return make_float2(iX, iY);
}

__host__ __device__
float3 gidInverseSmooth(const CuboidD<3>& c, std::size_t gid) {
  int iZ = gid / c.plane;
  int iY = (gid % c.plane) / c.nX;
  int iX = (gid % c.plane) % c.nX;
  return make_float3(iX,iY,iZ);
}
#+END_SRC

Checking whether some cell index is inside a cuboid can be performed by
simply comparing it to the total number of cells within said cuboid.

#+BEGIN_SRC cpp :tangle tangle/LLBM/descriptor.h
bool isInside(const CuboidD<2>& c, std::size_t gid) {
  return gid < c.volume;
}

bool isInside(const CuboidD<3>& c, std::size_t gid) {
  return gid < c.volume;
}

}
#+END_SRC

** Lattice
The =Lattice= class bundles an on-device population buffer storing the actual data
with the =PropagationControl= for performing the LBM streaming step and provides
various methods for applying operators and functors.

#+BEGIN_SRC cpp :tangle tangle/LLBM/lattice.h
#pragma once

#include "memory.h"
#include "call_tag.h"
#include "operator.h"

#include "propagate.h"
#include "kernel/executor.h"

template <typename DESCRIPTOR, typename T, typename S=T>
class Lattice {
private:
const descriptor::Cuboid<DESCRIPTOR> _cuboid;

CyclicPopulationBuffer<DESCRIPTOR,S> _population;

public:
Lattice(descriptor::Cuboid<DESCRIPTOR> cuboid):
  _cuboid(cuboid),
  _population(cuboid) { }

descriptor::Cuboid<DESCRIPTOR> cuboid() const {
  return _cuboid;
}

void stream() {
  _population.stream();
}
#+END_SRC

** Operator Application
All of our kernel functions can be grouped into three categories: Kernels that are applied to cell IDs, kernels that are applied
to entries of a list and kernels that are applied to a mask in a spatial configuration. As we are going to employ C++ tag dispatching
for selecting the appropriate wrapper functions to call the kernel operators we define a set of structs to distinguish the overloads:

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/call_tag.h
#pragma once

namespace tag {

struct call_by_cell_id { };
struct call_by_list_index { };
struct call_by_spatial_cell_mask { };

struct post_process_by_list_index { };
struct post_process_by_spatial_cell_mask { };

}
#+END_SRC

Generally speaking we want to avoid control flow branching inside of GPU kernels. However, it can
make sense to group multiple masked operators into a single lattice pass of a single kernel using some
small number of branches instead of launching a separate branch-free kernel for each operator.

In fact, the most common type of operator call we will use for the collisions in our simulations is the
fused application of a set of masked operators /curried/ with their arguments.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename... OPERATOR>
void apply(OPERATOR... ops) {
  const auto block_size = 32;
  const auto block_count = (_cuboid.volume + block_size - 1) / block_size;
  cuda::launch(kernel::call_operators<DESCRIPTOR,T,S,OPERATOR...>,
               cuda::launch_configuration_t(block_count, block_size),
               _population.view(),
               ops...);
}
#+END_SRC

In order to generate a single kernel from multiple operators curried with their respective arguments
we implement a small =Operator= helper class.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/operator.h
#pragma once

#include <tuple>

template <typename OPERATOR, typename... ARGS>
struct Operator {
  bool* const mask;
  const std::tuple<ARGS...> config;

  Operator(OPERATOR, DeviceBuffer<bool>& m, ARGS... args):
    mask(m.device()),
    config(args...) { }
#+END_SRC

This =Operator= wrapper stores both the mask pointer and any arguments for a given =OPERATOR= type.
The arguments will be passed to the actual =OPERATOR::apply= by the following proxy method for
any masked cell index.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/operator.h
  template <typename DESCRIPTOR, typename T, typename S>
  __device__ bool apply(DESCRIPTOR d, S f_curr[DESCRIPTOR::q], S f_next[DESCRIPTOR::q], std::size_t gid) const {
    if (mask[gid]) {
      std::apply([](auto... args) { OPERATOR::template apply<T,S>(args...); },
                 std::tuple_cat(std::make_tuple(d, f_curr, f_next, gid), config));
      return true;
    } else {
      return false;
    }
  }
};
#+END_SRC

Finally a deduction guide can be used to remove some of the visual cruft of declaring =Operator= instances in
the application code.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/operator.h
template <typename OPERATOR, typename... ARGS>
Operator(OPERATOR, DeviceBuffer<bool>&, ARGS... args) -> Operator<OPERATOR,std::remove_reference_t<ARGS>...>;
#+END_SRC

For single operator application the =apply= dispatcher calls the appropriate overload by instantiating the type defined
by =OPERATOR::call_tag= and passing it on to =call_operator= alongside any other arguments. Note that the dispatching
function and the overloaded functions have to be of different names to prevent infinite recursion as the variadic parameter
pack could of course also capture tags.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename OPERATOR, typename... ARGS>
void apply(ARGS&&... args) {
  call_operator<OPERATOR>(typename OPERATOR::call_tag{}, std::forward<ARGS&&>(args)...);
}
#+END_SRC

One common case is to apply a =call_by_cell_id= operator on a list of such IDs.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename OPERATOR, typename... ARGS>
void call_operator(tag::call_by_cell_id, DeviceBuffer<std::size_t>& cells, ARGS... args) {
  const auto block_size = 32;
  const auto block_count = (cells.size() + block_size - 1) / block_size;
  cuda::launch(kernel::call_operator<OPERATOR,DESCRIPTOR,T,S,ARGS...>,
               cuda::launch_configuration_t(block_count, block_size),
               _population.view(),
               cells.device(), cells.size(),
               std::forward<ARGS>(args)...);
}
#+END_SRC

The more generic version of this caller is list-based application. These calls can be thought of as simply iterating
over =count= elements and passing the current index to the individual device operator. This is useful when calling
e.g. the interpolated bounce back kernel as there is no 1:1 mapping between threads and cells to be found there.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename OPERATOR, typename... ARGS>
void call_operator(tag::call_by_list_index, std::size_t count, ARGS... args) {
  const auto block_size = 32;
  const auto block_count = (count + block_size - 1) / block_size;
  cuda::launch(kernel::call_operator_using_list<OPERATOR,DESCRIPTOR,T,S,ARGS...>,
               cuda::launch_configuration_t(block_count, block_size),
               _population.view(),
               count,
               std::forward<ARGS>(args)...);
}
#+END_SRC

Next, we provide corresponding =inspect= callers for read-only functor kernels.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename FUNCTOR, typename... ARGS>
void inspect(ARGS&&... args) {
  call_functor<FUNCTOR>(typename FUNCTOR::call_tag{}, std::forward<ARGS&&>(args)...);
}
#+END_SRC

Different from cell-based operators, the common case for functors is to evaluate a =call_by_cell_id=
functor using a mask (specifically the bulk mask) instead of a list.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename FUNCTOR, typename... ARGS>
void call_functor(tag::call_by_cell_id, DeviceBuffer<bool>& mask, ARGS... args) {
  const auto block_size = 32;
  const auto block_count = (_cuboid.volume + block_size - 1) / block_size;
  cuda::launch(kernel::call_functor<FUNCTOR,DESCRIPTOR,T,S,ARGS...>,
               cuda::launch_configuration_t(block_count, block_size),
               _population.view(),
               mask.device(),
               std::forward<ARGS>(args)...);
}
#+END_SRC

When we evaluate functors on the full domain to e.g. extract velocity norms into a 3d texture for volumetric visualization,
access to the spatial location of each cell is required. We could implement this by inverting each cell ID but it is both
more efficient and more clear to use the possibility of calling CUDA kernels in a 3D grid for this kind of work.

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename FUNCTOR, typename... ARGS>
void call_functor(tag::call_by_spatial_cell_mask, DeviceBuffer<bool>& mask, ARGS... args) {
  const dim3 block(32,8,4);
  const dim3 grid((_cuboid.nX + block.x - 1) / block.x,
                  (_cuboid.nY + block.y - 1) / block.y,
                  (_cuboid.nZ + block.z - 1) / block.z);
  cuda::launch(kernel::call_spatial_functor<FUNCTOR,DESCRIPTOR,T,S,ARGS...>,
               cuda::launch_configuration_t(grid, block),
               _population.view(),
               mask.device(),
               std::forward<ARGS>(args)...);
}
#+END_SRC

Sometimes we only want to do post-processing on e.g. the velocity moments without recalculating anything from the
populations. Strictly speaking such a kernel should not be called from the control class but as it is quite convenient
in practice we do so anyway:

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename OPERATOR, typename... ARGS>
void helper(ARGS&&... args) {
  tagged_helper<OPERATOR>(typename OPERATOR::call_tag{}, std::forward<ARGS&&>(args)...);
}
#+END_SRC

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename OPERATOR, typename... ARGS>
void tagged_helper(tag::post_process_by_list_index, std::size_t count, ARGS... args) {
  const auto block_size = 32;
  const auto block_count = (count + block_size - 1) / block_size;
  cuda::launch(kernel::call_operator_using_list<OPERATOR,DESCRIPTOR,T,S,ARGS...>,
               cuda::launch_configuration_t(block_count, block_size),
               DESCRIPTOR(),
               count,
               std::forward<ARGS>(args)...);
}
#+END_SRC

#+BEGIN_SRC cpp :noweb no :tangle tangle/LLBM/lattice.h
template <typename OPERATOR, typename... ARGS>
void tagged_helper(tag::post_process_by_spatial_cell_mask, DeviceBuffer<bool>& mask, ARGS... args) {
  const dim3 block(32,8,4);
  const dim3 grid((_cuboid.nX + block.x - 1) / block.x,
                  (_cuboid.nY + block.y - 1) / block.y,
                  (_cuboid.nZ + block.z - 1) / block.z);
  cuda::launch(kernel::call_spatial_operator<OPERATOR,DESCRIPTOR,T,S,ARGS...>,
               cuda::launch_configuration_t(grid, block),
               _cuboid,
               mask.device(),
               std::forward<ARGS>(args)...);
}

};
#+END_SRC

** Kernel Execution
#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
#pragma once

#include <LLBM/operator.h>

namespace kernel {
#+END_SRC

In this section we are finally implementing the actual kernels to be called by CUDA. These
kernels are plain functions marked with the =__global__= declaration specifier and called
using a special syntax for declaring the desired thread layout. The actual operators and
functors are abstracted in separate named structures implementing as generic an interface
as possible. Due to this the main work here will be to handle some GPU kernel specifics and
to read and write the populations as required by the operator's call type.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
template <typename OPERATOR, typename DESCRIPTOR, typename T, typename S, typename... ARGS>
__global__ void call_operator(
    LatticeView<DESCRIPTOR,S> lattice
  , std::size_t* cells
  , std::size_t  cell_count
  , ARGS... args
) {
  const std::size_t index = blockIdx.x * blockDim.x + threadIdx.x;
  if (!(index < cell_count)) {
      return;
  }
  const std::size_t gid = cells[index];

  S f_curr[DESCRIPTOR::q];
  S f_next[DESCRIPTOR::q];
  <<read-f-curr>>
  OPERATOR::template apply<T,S>(DESCRIPTOR(), f_curr, f_next, gid, std::forward<ARGS>(args)...);
  <<write-f-next>>
}
#+END_SRC

Of course the same argument holds for read-only functors where we in most cases only want
to compute moments for the bulk cells.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
template <typename FUNCTOR, typename DESCRIPTOR, typename T, typename S, typename... ARGS>
__global__ void call_functor(
    LatticeView<DESCRIPTOR,S> lattice
  , bool* mask
  , ARGS... args
) {
  const std::size_t gid = blockIdx.x * blockDim.x + threadIdx.x;
  if (!(gid < lattice.cuboid.volume) || !mask[gid]) {
      return;
  }

  S f_curr[DESCRIPTOR::q];
  <<read-f-curr>>
  FUNCTOR::template apply<T,S>(DESCRIPTOR(), f_curr, gid, std::forward<ARGS>(args)...);
}
#+END_SRC

A list of curried =Operator= instances passed as a variadic argument pack can be processed
using C++17's fold expressions. Note that we use the return value of the operator proxy calls
to perform short circuting if the currently folded call applied. This makes sense as masks
should be disjunctive in all cases -- otherwise multiple collision steps or boundary conditions
would be applied to the same cell during the same timestep.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
template <typename DESCRIPTOR, typename T, typename S, typename... OPERATOR>
__global__ void call_operators(
    LatticeView<DESCRIPTOR,S> lattice
  , OPERATOR... ops
) {
  const std::size_t gid = blockIdx.x * blockDim.x + threadIdx.x;
  if (!(gid < lattice.cuboid.volume)) {
      return;
  }

  S f_curr[DESCRIPTOR::q];
  S f_next[DESCRIPTOR::q];
  <<read-f-curr>>
  (ops.template apply<DESCRIPTOR,T,S>(DESCRIPTOR(), f_curr, f_next, gid) || ... || false);
  <<write-f-next>>
}
#+END_SRC

Not all operators fit into the a /one-application-per-cell/ framework. e.g. interpolated bounce
back boundaries are more naturally expressed in a /one-application-per-missing-population/
approach.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
template <typename OPERATOR, typename DESCRIPTOR, typename T, typename S, typename... ARGS>
__global__ void call_operator_using_list(
    LatticeView<DESCRIPTOR,S> lattice
  , std::size_t count
  , ARGS... args
) {
  const std::size_t index = blockIdx.x * blockDim.x + threadIdx.x;
  if (!(index < count)) {
      return;
  }
  OPERATOR::template apply<T,S>(lattice, index, count, std::forward<ARGS>(args)...);
}
#+END_SRC

For some post-processing operators and functors it is convenient to apply them in
a spatial setting where the threads are mapped in a 3D grid by CUDA. e.g. this is
used when writing data into the 3D textures used by our ray marcher.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
template <typename FUNCTOR, typename DESCRIPTOR, typename T, typename S, typename... ARGS>
__global__ void call_spatial_functor(
    LatticeView<DESCRIPTOR,S> lattice
  , bool* mask
  , ARGS... args
) {
  const std::size_t iX = blockIdx.x * blockDim.x + threadIdx.x;
  const std::size_t iY = blockIdx.y * blockDim.y + threadIdx.y;
  const std::size_t iZ = blockIdx.z * blockDim.z + threadIdx.z;
  if (!(iX < lattice.cuboid.nX && iY < lattice.cuboid.nY && iZ < lattice.cuboid.nZ)) {
      return;
  }
  const std::size_t gid = descriptor::gid(lattice.cuboid,iX,iY,iZ);
  if (!mask[gid]) {
      return;
  }

  S f_curr[DESCRIPTOR::q];
  <<read-f-curr>>
  FUNCTOR::template apply<T,S>(DESCRIPTOR(), f_curr, lattice.cuboid, gid, iX, iY, iZ, std::forward<ARGS>(args)...);
}
#+END_SRC

Again, as some helper operators such as the one used for shear layer thresholding do not
need direct lattice access, an appropriate wrapper is provided.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
template <typename OPERATOR, typename DESCRIPTOR, typename T, typename S, typename... ARGS>
__global__ void call_spatial_operator(
    descriptor::Cuboid<DESCRIPTOR> cuboid
  , bool* mask
  , ARGS... args
) {
  const std::size_t iX = blockIdx.x * blockDim.x + threadIdx.x;
  const std::size_t iY = blockIdx.y * blockDim.y + threadIdx.y;
  const std::size_t iZ = blockIdx.z * blockDim.z + threadIdx.z;
  if (!(iX < cuboid.nX && iY < cuboid.nY && iZ < cuboid.nZ)) {
      return;
  }
  const std::size_t gid = descriptor::gid(cuboid,iX,iY,iZ);
  if (!mask[gid]) {
      return;
  }
  OPERATOR::template apply<T,S>(DESCRIPTOR(), gid, iX, iY, iZ, std::forward<ARGS>(args)...);
}
#+END_SRC

At this point we have defined all kernel functions necessary to call all functors and operators necessary
for both simulation and visualization on the GPU.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/executor.h
}
#+END_SRC

** Cell List Generation
Each call to e.g. our collision kernel operates on a subset of cells represented by their IDs.
To ensure that these subsets are disjoint and that we do not perform e.g. both a bulk
collision and some boundary handling on the same cell we maintain a map of material
numbers on the host.

#+NAME: cell-materials-class
#+BEGIN_SRC cpp :tangle tangle/LLBM/materials.h
#pragma once

#include "memory.h"
#include "sdf.h"

template <typename DESCRIPTOR>
class CellMaterials : public SharedVector<int> {
private:
  const descriptor::Cuboid<DESCRIPTOR> _cuboid;
  int* const _materials;

public:
  CellMaterials(descriptor::Cuboid<DESCRIPTOR> cuboid):
    SharedVector<int>(cuboid.volume),
    _cuboid(cuboid),
    _materials(this->host()) { }

  template <typename F>
  CellMaterials(descriptor::Cuboid<DESCRIPTOR> cuboid, F f):
    CellMaterials(cuboid) {
    set(f);
  }

  descriptor::Cuboid<DESCRIPTOR> cuboid() const {
    return _cuboid;
  };

  <<cell-materials-basic-access>>
  <<cell-materials-fancy-setters>>
  <<cell-materials-get-list>>
  <<cell-materials-get-mask>>
  <<cell-materials-missing-links>>
};
#+END_SRC

This map assigns exactly one material number to each individual cell and allows extracting
a sorted list of all IDs belonging to a specific material number as a device buffer.

#+NAME: cell-materials-get-list
#+BEGIN_SRC cpp :eval no
DeviceBuffer<std::size_t> list_of_material(int material) {
	std::vector<std::size_t> cells;
	for (std::size_t iCell=0; iCell < _cuboid.volume; ++iCell) {
		if (_materials[iCell] == material) {
			cells.emplace_back(iCell);
		}
	}
	return DeviceBuffer<std::size_t>(cells);
}
#+END_SRC

Of course we also need some basic way of manipulating the material number assignments:

#+NAME: cell-materials-basic-access
#+BEGIN_SRC cpp :eval no
int get(std::size_t iCell) const {
  return _materials[iCell];
}

void set(std::size_t iCell, int material) {
  _materials[iCell] = material;
}
#+END_SRC

In practice we do not want to set each number /by hand/ but want to set them in bulk, e.g. using
lambda expressions that are evaluated for each cell:

#+NAME: cell-materials-fancy-setters
#+BEGIN_SRC cpp :eval no
template <typename F>
void set(F f) {
  for (std::size_t iCell=0; iCell < _cuboid.volume; ++iCell) {
    set(iCell, f(gidInverse(_cuboid, iCell)));
  }
}

template <typename S>
void sdf(S distance, int material, float eps=1e-2) {
  for (std::size_t iCell=0; iCell < _cuboid.volume; ++iCell) {
    auto p = gidInverseSmooth(_cuboid, iCell);
    if (distance(p) < eps) {
      set(iCell, material);
    }
  }
}

void clean(int material) {
  for (std::size_t iCell=0; iCell < _cuboid.volume; ++iCell) {
    if (get(iCell) == material) {
      if (_cuboid.isInside(iCell)) {
        bool surrounded = true;
        for (unsigned iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
          int m = get(descriptor::neighbor<DESCRIPTOR>(_cuboid, iCell, iPop));
          surrounded &= m == material || m == 0;
        }
        if (surrounded) {
          set(iCell, 0);
        }
      }
    }
  }
}
#+END_SRC

In some cases, e.g. when operating on the bulk of cells during the collision step, it is
preferable to apply a kernel over the whole domain and select the desired subset using
a boolean mask. Such masks are easily generated from material numbers.

#+NAME: cell-materials-get-mask
#+BEGIN_SRC cpp :eval no
DeviceBuffer<bool> mask_of_material(int material) {
  std::unique_ptr<bool[]> mask(new bool[_cuboid.volume]{});
	for (std::size_t iCell=0; iCell < _cuboid.volume; ++iCell) {
    mask[iCell] = (_materials[iCell] == material);
	}
	return DeviceBuffer<bool>(mask.get(), _cuboid.volume);
}
#+END_SRC

For boundaries such as interpolated bounce back we need to identify the /missing links/
between two material numbers. i.e. the pairs of propagation-adjacent cells of given
type.

#+NAME: cell-materials-missing-links
#+BEGIN_SRC cpp :eval no
std::size_t get_link_count(int bulk, int solid) {
  std::size_t count = 0;
  for (pop_index_t iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
    for (std::size_t iCell=0; iCell < _cuboid.volume; ++iCell) {
      std::size_t jCell = descriptor::neighbor<DESCRIPTOR>(_cuboid, iCell, iPop);
      if (get(iCell) == bulk && get(jCell) == solid) {
        count++;
      }
    }
  }
  return count;
}

template <typename F>
void for_links(int bulk, int solid, F f) {
  for (pop_index_t iPop=0; iPop < DESCRIPTOR::q; ++iPop) {
    for (std::size_t iCell=0; iCell < _cuboid.volume; ++iCell) {
      std::size_t jCell = descriptor::neighbor<DESCRIPTOR>(_cuboid, iCell, iPop);
      if (get(iCell) == bulk && get(jCell) == solid) {
        f(iCell, iPop);
      }
    }
  }
}
#+END_SRC

* Visualization
** Color Palettes
Developing and selecting color plattes is a quite involved topic and a good color palette is essential for visually pleasing results.
Furthermore careful choice of colors can expose details in the fluid structure that are otherwise easy to overlook, e.g. an outlier palette
allows the visualization to focus on the variations in the upper end of the sampled values.

#+NAME: colors-by-sciviscolor
| Name        | Url                                                                                                                         |
|-------------+-----------------------------------------------------------------------------------------------------------------------------|
| 3wave_BGY   | https://sciviscolor.org/media/filer_public/e3/fb/e3fbab88-037e-45d1-a221-dd3b69c13217/4-3wbgy.xml                           |
| orange      | https://sciviscolor.org/media/filer_public/28/9e/289e38f7-dba3-4d6e-81c1-907a635991ab/3-yel15.xml                           |
| blue        | https://sciviscolor.org/media/filer_public/1c/a9/1ca9ea72-c5f7-4bf9-9629-a1b4197b882a/24-colormap64.xml                     |
| autumn      | https://sciviscolor.org/media/filer_public/98/67/98676eda-e050-4cf3-89d2-6df6018619cb/discrete-3-5-section-muted-autumn.xml |
| blue_orange | https://sciviscolor.org/media/filer_public/48/d2/48d285e6-43bb-498b-9e3d-14103140c1e7/div1-blue-orange-div.xml              |
| green_brown | https://sciviscolor.org/media/filer_public/c1/49/c14908e6-3882-40ba-82f3-888b17414c36/div3-green-brown-div.xml              |
| 4wave_equal | https://sciviscolor.org/media/filer_public/7d/ef/7def2949-20a1-48fc-8161-15bffa3fad1b/9-4wequal1.xml                        |
| 5wave_cool  | https://sciviscolor.org/media/filer_public/1c/2a/1c2a0049-ed94-40f6-bbe5-2774ab354861/18-5w_coolcrisp2.xml                  |

The colormaps are provided as ParaView-compatible XML files. For simplicity we want to render the palettes described in those files into
images that we can then sample as textures at runtime. i.e. we precompute the colors instead of interpolating them at runtime.

#+BEGIN_SRC python :session :results none
from xml.etree import ElementTree
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

def readColormap(src):
    colors=[]
    values=[]
    root = ElementTree.fromstring(src)
    for s in root.findall('.//Point'):
        values.append(float(s.attrib['x']))
        colors.append((float(s.attrib['r']), float(s.attrib['g']), float(s.attrib['b'])))
    colormap = [ ]
    if values[0] != 0:
        colormap.append((0, colors[0]))
    for pos, color in zip(values, colors):
        colormap.append((pos, color))
    if values[-1] != 1:
        colormap.append((1, colors[-1]))
    return colormap

def renderColormap(cmap, path, reversed = False):
    gradient = np.linspace(1, 0, 1000) if reversed else np.linspace(0, 1, 1000)
    gradient = np.vstack((gradient, gradient))
    fig = plt.figure(figsize=(10,1))
    plot = fig.add_subplot(111)
    plot.set_frame_on(False)
    plot.get_xaxis().set_visible(False)
    plot.get_yaxis().set_visible(False)
    fig.tight_layout(pad=0)
    plot.imshow(gradient, aspect='auto', cmap=plt.get_cmap(colormap))
    plt.savefig(str(path), dpi=100)
    plt.close(fig)
#+END_SRC

#+NAME: generate-colormap
#+BEGIN_SRC python :results output file :session :var name="4wave_ROTB" :var reversed=1 :var forceRegen=0 :var data=colors-by-sciviscolor
import urllib.request
from pathlib import Path

colormapPicture = Path(f"tangle/asset/palette/{name}.png")

if forceRegen or not colormapPicture.is_file():
    url = dict(data)[name]
    src = ''.join([ line.decode() for line in urllib.request.urlopen(url) ])
    raw = readColormap(src)
    colormap = LinearSegmentedColormap.from_list(name, raw, N=1000)
    renderColormap(colormap, colormapPicture, reversed)

print(colormapPicture)
#+END_SRC

#+RESULTS: generate-colormap
[[file:tangle/asset/palette/4wave_ROTB.png]]

#+CALL: generate-colormap("orange", 1)

#+RESULTS:
[[file:tangle/asset/palette/orange.png]]

#+CALL: generate-colormap("blue", 1)

#+RESULTS:
[[file:tangle/asset/palette/blue.png]]

#+CALL: generate-colormap("blue_orange", 0)

#+RESULTS:
[[file:tangle/asset/palette/blue_orange.png]]

#+CALL: generate-colormap("green_brown", 1)

#+RESULTS:
[[file:tangle/asset/palette/green_brown.png]]

#+CALL: generate-colormap("5wave_cool", 0)

#+RESULTS:
[[file:tangle/asset/palette/5wave_cool.png]]

#+CALL: generate-colormap("4wave_equal", 0)

#+RESULTS:
[[file:tangle/asset/palette/4wave_equal.png]]

#+CALL: generate-colormap("autumn", 1)

#+RESULTS:
[[file:tangle/asset/palette/autumn.png]]

#+BEGIN_SRC cpp :tangle tangle/util/colormap.h
#pragma once
#include "assets.h"
#include "texture.h"

#include <imgui.h>
#include <imgui-SFML.h>
#include <SFML/Graphics.hpp>
#+END_SRC

At runtime we map the $[0,1]$ interval to these color palette textures.

#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
__device__ float3 colorFromTexture(cudaSurfaceObject_t colormap, float value) {
  uchar4 color{};
  value = clamp(value, 0.f, 1.f);
  surf2Dread(&color, colormap, unsigned(value * 999)*sizeof(uchar4), 0);
  return make_float3(color.x / 255.f,
                     color.y / 255.f,
                     color.z / 255.f);
}
#+END_SRC

The currently selected colormap is tracked by a =ColorPalette= class…

#+BEGIN_SRC cpp :tangle tangle/util/colormap.h
struct ColorPalette {
  const assets::File* current;
  sf::Texture texture;

  ColorPalette(cudaSurfaceObject_t& palette) {
    current = &assets::palette::files[5];
    texture.loadFromMemory(current->data, current->size);
    palette = bindTextureToCuda(texture);
  }

  void interact();
};
#+END_SRC

…that also offers a convenient UI for changing between all available colormaps.
The =asset= namespace referenced here is automatically generated using CMake
instructions.

#+BEGIN_SRC cpp :tangle tangle/util/colormap.h
void ColorPalette::interact() {
  if (ImGui::BeginCombo("Color palette", current->name.c_str())) {
    for (unsigned i=0; i < assets::palette::file_count; ++i) {
      bool is_selected = (current == &assets::palette::files[i]);
      if (ImGui::Selectable(assets::palette::files[i].name.c_str(), is_selected)) {
        current = &assets::palette::files[i];
        texture.loadFromMemory(current->data, current->size);
        break;
      }
      if (is_selected) {
        ImGui::SetItemDefaultFocus();
      }
    }
    ImGui::EndCombo();
  }
  ImGui::Image(texture, sf::Vector2f(400.,40.));
}
#+END_SRC

** Velocity Norm
#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collect_velocity_norm.h
#pragma once
#include <LLBM/call_tag.h>

struct CollectVelocityNormF {

using call_tag = tag::post_process_by_spatial_cell_mask;

template <typename T, typename S>
__device__ static void apply(
    descriptor::D2Q9
  , std::size_t gid
  , std::size_t iX
  , std::size_t iY
  , std::size_t iZ
  , T* u
  , cudaSurfaceObject_t surface
) {
  float norm = length(make_float2(u[2*gid+0], u[2*gid+1]));
  surf2Dwrite(norm, surface, iX*sizeof(float), iY);
}

template <typename T, typename S>
__device__ static void apply(
    descriptor::D3Q19
  , std::size_t gid
  , std::size_t iX
  , std::size_t iY
  , std::size_t iZ
  , T* u
  , cudaSurfaceObject_t surface
  , T* u_norm = nullptr
) {
  float norm = length(make_float3(u[3*gid+0], u[3*gid+1], u[3*gid+2]));
  surf3Dwrite(norm, surface, iX*sizeof(float), iY, iZ);
  if (u_norm != nullptr) {
    u_norm[gid] = norm;
  }
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collect_velocity_norm.h
template <typename SLICE, typename SAMPLE, typename PALETTE>
__global__ void renderSliceViewToTexture(std::size_t width, std::size_t height, SLICE slice, SAMPLE sample, PALETTE palette, cudaSurfaceObject_t texture) {
  const int screenX = threadIdx.x + blockIdx.x * blockDim.x;
  const int screenY = threadIdx.y + blockIdx.y * blockDim.y;

  if (screenX > width-1 || screenY > height-1) {
    return;
  }
  
  const std::size_t gid = slice(screenX,screenY);
  float3 color = palette(sample(gid));

  uchar4 pixel {
    static_cast<unsigned char>(color.x * 255),
    static_cast<unsigned char>(color.y * 255),
    static_cast<unsigned char>(color.z * 255),
    255
  };
  surf2Dwrite(pixel, texture, screenX*sizeof(uchar4), screenY);
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/sampler/velocity_norm.h
#pragma once

#include "sampler.h"

#include <LLBM/kernel/collect_moments.h>
#include <LLBM/kernel/collect_velocity_norm.h>

#include <thrust/pair.h>
#include <thrust/device_vector.h>
#include <thrust/extrema.h>

#include <iostream>

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
class VelocityNormS : public Sampler {
private:
Lattice<DESCRIPTOR,T,S>& _lattice;
DeviceBuffer<bool>& _mask;
SDF _geometry;

DeviceBuffer<float> _moments_rho;
DeviceBuffer<float> _moments_u;
DeviceBuffer<float> _u_norm;

float _scale = 1;
float _lower = 0;
float _upper = 1;

public:
VelocityNormS(Lattice<DESCRIPTOR,T,S>& lattice, DeviceBuffer<bool>& mask, SDF geometry):
  Sampler("Velocity norm", lattice.cuboid()),
  _lattice(lattice),
  _mask(mask),
  _geometry(geometry),
  _moments_rho(lattice.cuboid().volume),
  _moments_u(DESCRIPTOR::d * lattice.cuboid().volume),
  _u_norm(lattice.cuboid().volume)
{ }

void sample() {
  _lattice.template inspect<CollectMomentsF>(_mask, _moments_rho.device(), _moments_u.device());
  _lattice.template helper<CollectVelocityNormF>(_mask, _moments_u.device(), _sample_surface, _u_norm.device());
}

void render(VolumetricRenderConfig& config) {
  raymarch<<<
    dim3(config.canvas_size.x / 32 + 1, config.canvas_size.y / 32 + 1),
    dim3(32, 32)
  >>>(config,
      _geometry,
      [samples=_sample_texture, scale=_scale, lower=_lower, upper=_upper]
      __device__ (float3 p) -> float {
        float sample = scale * tex3D<float>(samples, p.x, p.y, p.z);
        return sample >= lower && sample <= upper ? sample : 0;
      },
      [] __device__ (float x) -> float {
        return x;
      });
}

void scale() {
  auto max = thrust::max_element(thrust::device_pointer_cast(_u_norm.device()),
                                 thrust::device_pointer_cast(_u_norm.device() + _lattice.cuboid().volume));
  _scale = 1 / max[0];
}

void interact() {
  ImGui::SliderFloat("Scale", &_scale, 0.01f, 100.f);
  ImGui::SameLine();
  if (ImGui::Button("Auto")) {
    scale();
  }
  ImGui::DragFloatRange2("Bounds", &_lower, &_upper, 0.01f, 0.f, 1.f, "%.2f", "%.2f");
}

};

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
VelocityNormS(Lattice<DESCRIPTOR,T,S>&, DeviceBuffer<bool>&, SDF) -> VelocityNormS<DESCRIPTOR,T,S,SDF>;
#+END_SRC

** Curl
The curl of a velocity projects each point of the fluid to a vector that is perpendicular to the local axis of
rotation and the longer the higher the magnitude of said rotation. We are going to symbolically derive
finite difference approximations of arbitrary order for the first partial derivatives in order to compute the
curl of our velocity field.

#+BEGIN_SRC python :session :results none
def taylor_expansion(point, order):
    h, x = symbols('h, x')
    g = Function('g')
    return sum(point**i / factorial(i) * g(x).diff(x, i) for i in range(order+1))

def finite_difference(n_grid, order, i):
    h, x = symbols('h, x')
    g = Function('g')
    grid = np.arange(-(n_grid-1)/2, (n_grid-1)/2+1).astype(int)
    coefficients = ZeroMatrix(n_grid, n_grid).as_mutable()
    for p, h_coefficient in zip(range(n_grid), grid):
        expansion = taylor_expansion(h_coefficient * h, order)
        for d in range(order + 1):
            coefficients[d, p] = expansion.coeff(g(x).diff(x, d))
    
    derivative = ZeroMatrix(order + 1, 1).as_mutable()
    derivative[i,0] = 1
    return ((coefficients.inv() @ derivative).subs(h,1).T * Matrix([ g(x) for x in grid ]))[0]

#+END_SRC

#+NAME: finite-difference
#+BEGIN_SRC python :session :results output :var n_grid=3 :var order=2 :var component=1 :var f_name="g"
g = Function('g')
print(finite_difference(n_grid, order, component).replace(g, lambda arg: Function(f_name)(arg)))
#+END_SRC

#+RESULTS: finite-difference
: -g(-1)/2 + g(1)/2

#+BEGIN_SRC python :session :results output :wrap latex
def curl_approximation(order):
    def letter(i):
        return "xyz"[i]
    
    def resolve_arg(component, arg):
        return [ arg if j == component else 0 for j in range(3) ]
    
    curl_def = [ ]
    fd = finite_difference(order+1, order, 1)
    g = Function('g')
    
    def ui_dj(i,j):
        return fd.replace(g, lambda arg: Function(f"u_{letter(i)}")(*resolve_arg(j,arg)))
    
    curl_def.append(Assignment(Symbol("curl_0"), ui_dj(2,1) - ui_dj(1,2)))
    curl_def.append(Assignment(Symbol("curl_1"), ui_dj(0,2) - ui_dj(2,0)))
    curl_def.append(Assignment(Symbol("curl_2"), ui_dj(1,0) - ui_dj(0,1)))
    return curl_def

printlatexpr(*curl_approximation(4))
#+END_SRC

#+RESULTS:
#+begin_latex
$$\begin{align*}
curl_{0} &:= - \frac{\operatorname{u_{y}}{\left(0,0,-2 \right)}}{12} + \frac{2 \operatorname{u_{y}}{\left(0,0,-1 \right)}}{3} - \frac{2 \operatorname{u_{y}}{\left(0,0,1 \right)}}{3} + \frac{\operatorname{u_{y}}{\left(0,0,2 \right)}}{12} + \frac{\operatorname{u_{z}}{\left(0,-2,0 \right)}}{12} - \frac{2 \operatorname{u_{z}}{\left(0,-1,0 \right)}}{3} + \frac{2 \operatorname{u_{z}}{\left(0,1,0 \right)}}{3} - \frac{\operatorname{u_{z}}{\left(0,2,0 \right)}}{12} \\
curl_{1} &:= \frac{\operatorname{u_{x}}{\left(0,0,-2 \right)}}{12} - \frac{2 \operatorname{u_{x}}{\left(0,0,-1 \right)}}{3} + \frac{2 \operatorname{u_{x}}{\left(0,0,1 \right)}}{3} - \frac{\operatorname{u_{x}}{\left(0,0,2 \right)}}{12} - \frac{\operatorname{u_{z}}{\left(-2,0,0 \right)}}{12} + \frac{2 \operatorname{u_{z}}{\left(-1,0,0 \right)}}{3} - \frac{2 \operatorname{u_{z}}{\left(1,0,0 \right)}}{3} + \frac{\operatorname{u_{z}}{\left(2,0,0 \right)}}{12} \\
curl_{2} &:= - \frac{\operatorname{u_{x}}{\left(0,-2,0 \right)}}{12} + \frac{2 \operatorname{u_{x}}{\left(0,-1,0 \right)}}{3} - \frac{2 \operatorname{u_{x}}{\left(0,1,0 \right)}}{3} + \frac{\operatorname{u_{x}}{\left(0,2,0 \right)}}{12} + \frac{\operatorname{u_{y}}{\left(-2,0,0 \right)}}{12} - \frac{2 \operatorname{u_{y}}{\left(-1,0,0 \right)}}{3} + \frac{2 \operatorname{u_{y}}{\left(1,0,0 \right)}}{3} - \frac{\operatorname{u_{y}}{\left(2,0,0 \right)}}{12} \\
\end{align*}$$
#+end_latex

#+NAME: curl-3d-from-preshifted-u
#+BEGIN_SRC python :session :results output :cache yes
printcode(CodeBlock(*curl_approximation(2)), custom_functions=["u_x", "u_y", "u_z"])
#+END_SRC

#+RESULTS[9d36761e18f08f87b6f7da32166b132270c35c86]: curl-3d-from-preshifted-u
: T curl_0 = T{0.500000000000000}*u_y(0, 0, -1) - T{0.500000000000000}*u_y(0, 0, 1) - T{0.500000000000000}*u_z(0, -1, 0) + T{0.500000000000000}*u_z(0, 1, 0);
: T curl_1 = -T{0.500000000000000}*u_x(0, 0, -1) + T{0.500000000000000}*u_x(0, 0, 1) + T{0.500000000000000}*u_z(-1, 0, 0) - T{0.500000000000000}*u_z(1, 0, 0);
: T curl_2 = T{0.500000000000000}*u_x(0, -1, 0) - T{0.500000000000000}*u_x(0, 1, 0) - T{0.500000000000000}*u_y(-1, 0, 0) + T{0.500000000000000}*u_y(1, 0, 0);

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collect_curl.h
#pragma once
#include <LLBM/call_tag.h>

struct CollectCurlF {

using call_tag = tag::call_by_spatial_cell_mask;

template <typename T, typename S>
__device__ static void apply(
    descriptor::D3Q19
  , S f_curr[19]
  , descriptor::CuboidD<3> cuboid
  , std::size_t gid
  , std::size_t iX
  , std::size_t iY
  , std::size_t iZ
  , S* moments_u
  , cudaSurfaceObject_t surface
  , S* curl_norm = nullptr
) {
  auto u_x = [moments_u,cuboid,gid] __device__ (int x, int y, int z) -> T {
    return moments_u[3*(gid + descriptor::offset(cuboid,x,y,z)) + 0];
  };
  auto u_y = [moments_u,cuboid,gid] __device__ (int x, int y, int z) -> T {
    return moments_u[3*(gid + descriptor::offset(cuboid,x,y,z)) + 1];
  };
  auto u_z = [moments_u,cuboid,gid] __device__ (int x, int y, int z) -> T {
    return moments_u[3*(gid + descriptor::offset(cuboid,x,y,z)) + 2];
  };

  <<curl-3d-from-preshifted-u()>>
  float3 curl = make_float3(curl_0, curl_1, curl_2);
  float norm = length(curl);

  surf3Dwrite(norm, surface, iX*sizeof(float), iY, iZ);

  if (curl_norm != nullptr) {
    curl_norm[gid] = norm; 
  }
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/sampler/curl_norm.h
#pragma once

#include "sampler.h"

#include <LLBM/kernel/collect_moments.h>
#include <LLBM/kernel/collect_curl.h>

#include <thrust/pair.h>
#include <thrust/device_vector.h>
#include <thrust/extrema.h>

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
class CurlNormS : public Sampler {
private:
Lattice<DESCRIPTOR,T,S>& _lattice;
DeviceBuffer<bool>& _mask;
SDF _geometry;

DeviceBuffer<float> _moments_rho;
DeviceBuffer<float> _moments_u;
DeviceBuffer<float> _curl_norm;

float _scale = 1;
float _lower = 0;
float _upper = 1;

public:
CurlNormS(Lattice<DESCRIPTOR,T,S>& lattice, DeviceBuffer<bool>& mask, SDF geometry):
  Sampler("Curl norm", lattice.cuboid()),
  _lattice(lattice),
  _mask(mask),
  _geometry(geometry),
  _moments_rho(lattice.cuboid().volume),
  _moments_u(DESCRIPTOR::d * lattice.cuboid().volume),
  _curl_norm(lattice.cuboid().volume)
{ }

void sample() {
  _lattice.template inspect<CollectMomentsF>(_mask, _moments_rho.device(), _moments_u.device());
  _lattice.template inspect<CollectCurlF>(_mask, _moments_u.device(), _sample_surface, _curl_norm.device());
}

void render(VolumetricRenderConfig& config) {
  raymarch<<<
    dim3(config.canvas_size.x / 32 + 1, config.canvas_size.y / 32 + 1),
    dim3(32, 32)
  >>>(config,
      _geometry,
      [samples=_sample_texture, scale=_scale, lower=_lower, upper=_upper]
      __device__ (float3 p) -> float {
        float sample = scale * tex3D<float>(samples, p.x, p.y, p.z);
        return sample >= lower && sample <= upper ? sample : 0;
      },
      [] __device__ (float x) -> float {
        return x;
      });
}

void scale() {
  auto max = thrust::max_element(thrust::device_pointer_cast(_curl_norm.device()),
                                 thrust::device_pointer_cast(_curl_norm.device() + _lattice.cuboid().volume));
  _scale = 1 / max[0];
}

void interact() {
  ImGui::SliderFloat("Scale", &_scale, 0.01f, 100.f);
  ImGui::SameLine();
  if (ImGui::Button("Auto")) {
    scale();
  }
  ImGui::DragFloatRange2("Bounds", &_lower, &_upper, 0.01f, 0.f, 1.f, "%.2f", "%.2f");
}

};

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
CurlNormS(Lattice<DESCRIPTOR,T,S>&, DeviceBuffer<bool>&, SDF) -> CurlNormS<DESCRIPTOR,T,S,SDF>;
#+END_SRC

** Rheoscopic fluid
Rheoscopic fluids are a tool for experimental visualization of fluid flow based on small suspended particles that
tend to align themselves along the local velocity vector and shear layer. If one shines light on such a suspension
the reflected light offers a detailed view of the shear layer and velocity structure.
In this section we want to try to reproduce such a view by shading the sample values according to the local shear
layer normal vector.

*** Calculate shear layer normal
Translating the approach of Barth and Burns cite:barthVirtualRheoscopicFluids2007 into LBM
we can compute the shear layer normal from the strain rate tensor that in turn can be recovered from a
cells non-equilibrium population.

#+BEGIN_SRC python :session :results none
n = IndexedBase('n', d)

def shear_layer_normal_approx(D, f, f_eq, u):
    pi = pi_neq(D, f, f_eq)
    u_normed = u / sqrt(sum([ u[i]**2 for i in range(D.d) ]))
    return 2*pi*u_normed - 2*u.dot(pi*u_normed)*u_normed

def shear_layer_normal(D):
    v = Matrix([ u[j] for j in range(D.d) ])
    normal = shear_layer_normal_approx(D, f, f_eq, v)
    return normal

def shear_layer_normal_code_block(D):
    f_curr = IndexedBase('f_curr', q)
    rho = realize_indexed(realize_rho(D), f, f_curr)
    u = [ realize_indexed(realize_u_i(D, i), f, f_curr) for i in range(D.d) ]
    f_moment_eq = [ realize_f_eq_i(D, i).rhs for i in range(D.q) ]
    
    normal = realize_indexed(shear_layer_normal(D), f, f_curr)
    normal = realize_indexed(normal, f_eq, f_moment_eq)
    return CodeBlock(rho.doit(), *u, *[ Assignment(n[i], normal[i]) for i in range(D.d) ]).cse(optimizations = custom_opti)
#+END_SRC

#+NAME: shear-layer-normal-from-f-curr
#+BEGIN_SRC python :session :results output
printcode(shear_layer_normal_code_block(descriptor[lattice]))
#+END_SRC

#+RESULTS: shear-layer-normal-from-f-curr
#+begin_example
T x0 = f_curr[1] + f_curr[2];
T x1 = f_curr[3] + f_curr[6];
T x2 = x0 + x1 + f_curr[0] + f_curr[4] + f_curr[5] + f_curr[7] + f_curr[8];
T x3 = f_curr[0] - f_curr[8];
T x4 = T{1} / (x2);
T x9 = T{72.0000000000000}*f_curr[2];
T x10 = T{72.0000000000000}*f_curr[6];
T rho = x2;
T x29 = T{4.00000000000000}*rho;
T u_0 = -x4*(x0 + x3 - f_curr[6] - f_curr[7]);
T x5 = u_0*u_0;
T x12 = -T{3.00000000000000}*x5;
T x15 = T{6.00000000000000}*u_0;
T x16 = -x15;
T u_1 = -x4*(x1 + x3 - f_curr[2] - f_curr[5]);
T x6 = u_1*u_1;
T x7 = x5 + x6;
T x8 = pow(x7, T{-0.500000000000000});
T x11 = -u_0 + u_1;
T x13 = T{6.00000000000000}*u_1;
T x14 = x12 + x13;
T x17 = T{2.00000000000000} - T{3.00000000000000}*x6;
T x18 = x16 + x17;
T x19 = rho*(x14 + x18 + T{9.00000000000000}*(x11*x11));
T x20 = u_0 - u_1;
T x21 = x12 - x13;
T x22 = x15 + x17;
T x23 = rho*(x21 + x22 + T{9.00000000000000}*(x20*x20));
T x24 = u_0 + u_1;
T x25 = T{9.00000000000000}*(x24*x24);
T x26 = rho*(x14 + x22 + x25) + rho*(x18 + x21 + x25) - T{72.0000000000000}*f_curr[0] - T{72.0000000000000}*f_curr[8];
T x27 = x10 - x19 - x23 + x26 + x9;
T x28 = x27*x8;
T x30 = x17 + T{6.00000000000000}*x5;
T x31 = -x10 + x19 + x23 + x26 - x9;
T x32 = x29*(x15 + x30) + x29*(x16 + x30) + x31 - T{72.0000000000000}*f_curr[1] - T{72.0000000000000}*f_curr[7];
T x33 = T{6.00000000000000}*x6 + T{2.00000000000000};
T x34 = x29*(x14 + x33) + x29*(x21 + x33) + x31 - T{72.0000000000000}*f_curr[3] - T{72.0000000000000}*f_curr[5];
T x35 = ((x27*u_0 + x34*u_1)*u_1 + (x27*u_1 + x32*u_0)*u_0)/x7;
T n_0 = -T{0.0277777777777778}*x28*u_1 - T{0.0277777777777778}*x32*x8*u_0 + T{0.0277777777777778}*x35*u_0;
T n_1 = -T{0.0277777777777778}*x28*u_0 - T{0.0277777777777778}*x34*x8*u_1 + T{0.0277777777777778}*x35*u_1;
#+end_example

*** Determine shear layer visibility
#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collect_shear_layer_normal.h
#pragma once
#include <LLBM/call_tag.h>

struct CollectShearLayerNormalsF {

using call_tag = tag::call_by_cell_id;

template <typename T, typename S>
__device__ static void apply(
    descriptor::D3Q19
  , S f_curr[19]
  , std::size_t gid
  , T* cell_rho 
  , T* cell_u
  , T* cell_shear_normal
) {
  <<shear-layer-normal-from-f-curr(lattice="D3Q19")>>

  cell_rho[gid] = rho;

  cell_u[3*gid+0] = u_0;
  cell_u[3*gid+1] = u_1;
  cell_u[3*gid+2] = u_2;

  float3 n = normalize(make_float3(n_0, n_1, n_2));
  cell_shear_normal[3*gid+0] = n.x;
  cell_shear_normal[3*gid+1] = n.y;
  cell_shear_normal[3*gid+2] = n.z;
}

};
#+END_SRC

One possible use case for these shear layer normals is to extract those layers aligned with some vector.
The resulting visibility value can either be used to threshold rendering of some other value such as the
velocity norm or as a sample value by iself -- when combined with some additional coloring logic the
latter results in something that looks like a rheoscopic fluid.

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collect_shear_layer_normal.h
struct CollectShearLayerVisibilityF {

using call_tag = tag::post_process_by_spatial_cell_mask;

template <typename T, typename S>
__device__ static void apply(
    descriptor::D3Q19
  , std::size_t gid
  , std::size_t iX
  , std::size_t iY
  , std::size_t iZ
  , T* shear_normal
  , float3 view_direction
  , cudaSurfaceObject_t surface
) {
  float3 n = make_float3(shear_normal[3*gid+0], shear_normal[3*gid+1], shear_normal[3*gid+2]);
  float visibility = dot(n, view_direction);
  surf3Dwrite(visibility, surface, iX*sizeof(float), iY, iZ);
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/sampler/shear_layer.h
#pragma once

#include "sampler.h"

#include <LLBM/kernel/collect_moments.h>
#include <LLBM/kernel/collect_shear_layer_normal.h>

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
class ShearLayerVisibilityS : public Sampler {
private:
Lattice<DESCRIPTOR,T,S>& _lattice;
DeviceBuffer<bool>& _mask;
SDF _geometry;

DeviceBuffer<float> _moments_rho;
DeviceBuffer<float> _moments_u;
DeviceBuffer<float> _shear_normals;

float3 _shear_layer;
float _lower = 0;
float _upper = 1;
bool _center = true;

public:
ShearLayerVisibilityS(Lattice<DESCRIPTOR,T,S>& lattice, DeviceBuffer<bool>& mask, SDF geometry, float3 shear_layer):
  Sampler("Shear layer visibility", lattice.cuboid()),
  _lattice(lattice),
  _mask(mask),
  _geometry(geometry),
  _moments_rho(lattice.cuboid().volume),
  _moments_u(DESCRIPTOR::d * lattice.cuboid().volume),
  _shear_normals(DESCRIPTOR::d * lattice.cuboid().volume),
  _shear_layer(shear_layer)
{ }

void sample() {
  _lattice.template inspect<CollectShearLayerNormalsF>(_mask, _moments_rho.device(), _moments_u.device(), _shear_normals.device());
  _lattice.template helper<CollectShearLayerVisibilityF>(_mask, _shear_normals.device(), _shear_layer, _sample_surface);
}

void render(VolumetricRenderConfig& config) {
  raymarch<<<
    dim3(config.canvas_size.x / 32 + 1, config.canvas_size.y / 32 + 1),
    dim3(32, 32)
  >>>(config,
      _geometry,
      [samples=_sample_texture, lower=_lower, upper=_upper, center=_center]
      __device__ (float3 p) -> float {
        float sample = tex3D<float>(samples, p.x, p.y, p.z);
        float centered = center ? 0.5 + 0.5*sample : sample;
        return fabs(sample) >= lower && fabs(sample) <= upper ? fabs(centered) : 0;
      },
      [] __device__ (float x) -> float {
        return x;
      });
}

void interact() {
  ImGui::InputFloat3("Normal", reinterpret_cast<float*>(&_shear_layer));
  ImGui::Checkbox("Center", &_center);
  ImGui::DragFloatRange2("Bounds", &_lower, &_upper, 0.01f, 0.f, 1.f, "%.2f", "%.2f");
}

};

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
ShearLayerVisibilityS(Lattice<DESCRIPTOR,T,S>&, DeviceBuffer<bool>&, SDF) -> ShearLayerVisibilityS<DESCRIPTOR,T,S,SDF>;
#+END_SRC

** Q-Criterion
#+BEGIN_SRC python :session :results none
def strain_rate_norm_code_block(D):
    f_curr = IndexedBase('f_curr', q)
    f_moment_eq = [ realize_f_eq_i(D, i).rhs for i in range(D.q) ]
    strain = Assignment(Symbol('strain'), pi_neq_norm(D, f_curr, f_moment_eq))
    return CodeBlock(strain).cse(optimizations = custom_opti)
#+END_SRC

#+NAME: strain-rate-norm-from-f-curr
#+BEGIN_SRC python :session :results output
printcode(strain_rate_norm_code_block(descriptor[lattice]))
#+END_SRC

#+RESULTS: strain-rate-norm-from-f-curr
#+begin_example
T x0 = T{72.0000000000000}*f_curr[2];
T x1 = T{72.0000000000000}*f_curr[6];
T x2 = T{6.00000000000000}*u_0;
T x3 = -x2;
T x4 = u_0 - u_1;
T x5 = T{9.00000000000000}*(x4*x4);
T x6 = u_1*u_1;
T x7 = T{3.00000000000000}*x6;
T x8 = T{2.00000000000000} - x7;
T x9 = T{6.00000000000000}*u_1;
T x10 = u_0*u_0;
T x11 = T{3.00000000000000}*x10;
T x12 = -x11;
T x13 = x12 + x9;
T x14 = x13 + x8;
T x15 = rho*(x14 + x3 + x5);
T x16 = rho*(x12 + x2 + x5 + x8 - x9);
T x17 = u_0 + u_1;
T x18 = T{9.00000000000000}*(x17*x17);
T x19 = x11 + x9 + T{-2.00000000000000};
T x20 = rho*(x14 + x18 + x2) - rho*(-x18 + x19 + x2 + x7) - T{72.0000000000000}*f_curr[0] - T{72.0000000000000}*f_curr[8];
T x21 = x0 + x1 - x15 - x16 + x20;
T x22 = T{4.00000000000000}*rho;
T x23 = T{6.00000000000000}*x10 + x8;
T x24 = -x0 - x1 + x15 + x16 + x20;
T x25 = x22*(x2 + x23) + x22*(x23 + x3) + x24 - T{72.0000000000000}*f_curr[1] - T{72.0000000000000}*f_curr[7];
T x26 = T{6.00000000000000}*x6;
T x27 = -x22*(x19 - x26) + x22*(x13 + x26 + T{2.00000000000000}) + x24 - T{72.0000000000000}*f_curr[3] - T{72.0000000000000}*f_curr[5];
T strain = T{0.0277777777777778}*sqrt(x21*x21 + T{0.500000000000000}*(x25*x25) + T{0.500000000000000}*(x27*x27));
#+end_example

#+BEGIN_SRC cpp :tangle tangle/LLBM/kernel/collect_q_criterion.h
#pragma once
#include <LLBM/call_tag.h>

struct CollectQCriterionF {

using call_tag = tag::call_by_spatial_cell_mask;

template <typename T, typename S>
__device__ static void apply(
    descriptor::D3Q19
  , S f_curr[19]
  , descriptor::CuboidD<3> cuboid
  , std::size_t gid
  , std::size_t iX
  , std::size_t iY
  , std::size_t iZ
  , T* cell_rho
  , T* cell_u
  , T* cell_curl_norm
  , cudaSurfaceObject_t surface
  , T* cell_q = nullptr
) {
  const T rho = cell_rho[gid];
  const T u_0 = cell_u[3*gid + 0];
  const T u_1 = cell_u[3*gid + 1];
  const T u_2 = cell_u[3*gid + 2];

  <<strain-rate-norm-from-f-curr(lattice="D3Q19")>>

  float vorticity = cell_curl_norm[gid];
  float q = vorticity*vorticity - strain*strain;
  q = q > 0 ? q : 0;

  surf3Dwrite(q, surface, iX*sizeof(float), iY, iZ);

  if (cell_q != nullptr) {
    cell_q[gid] = q;
  }
}

};
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/sampler/q_criterion.h
#pragma once

#include "sampler.h"

#include <LLBM/kernel/collect_moments.h>
#include <LLBM/kernel/collect_curl.h>
#include <LLBM/kernel/collect_q_criterion.h>

#include <thrust/pair.h>
#include <thrust/device_vector.h>
#include <thrust/extrema.h>

#include <iostream>

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
class QCriterionS : public Sampler {
private:
Lattice<DESCRIPTOR,T,S>& _lattice;
DeviceBuffer<bool>& _mask;
SDF _geometry;

DeviceTexture<float> _curl_buffer;
cudaTextureObject_t _curl_texture;
cudaSurfaceObject_t _curl_surface;

DeviceBuffer<float> _moments_rho;
DeviceBuffer<float> _moments_u;
DeviceBuffer<float> _curl_norm;
DeviceBuffer<float> _q;

float _scale = 1;
float _lower = 0.01;
float _upper = 1;

public:
QCriterionS(Lattice<DESCRIPTOR,T,S>& lattice, DeviceBuffer<bool>& mask, SDF geometry):
  Sampler("Q criterion", lattice.cuboid()),
  _lattice(lattice),
  _mask(mask),
  _geometry(geometry),
  _curl_buffer(lattice.cuboid()),
  _curl_texture(_curl_buffer.getTexture()),
  _curl_surface(_curl_buffer.getSurface()),
  _moments_rho(lattice.cuboid().volume),
  _moments_u(DESCRIPTOR::d * lattice.cuboid().volume),
  _curl_norm(lattice.cuboid().volume),
  _q(lattice.cuboid().volume)
{ }

void sample() {
  _lattice.template inspect<CollectMomentsF>(_mask, _moments_rho.device(), _moments_u.device());
  _lattice.template inspect<CollectCurlF>(_mask, _moments_u.device(), _curl_surface, _curl_norm.device());
  _lattice.template inspect<CollectQCriterionF>(_mask, _moments_rho.device(), _moments_u.device(), _curl_norm.device(), _sample_surface, _q.device());
}

void render(VolumetricRenderConfig& config) {
  raymarch<<<
    dim3(config.canvas_size.x / 32 + 1, config.canvas_size.y / 32 + 1),
    dim3(32, 32)
  >>>(config,
      _geometry,
      [samples=_sample_texture, scale=_scale, lower=_lower, upper=_upper]
      __device__ (float3 p) -> float {
        float sample = scale * tex3D<float>(samples, p.x, p.y, p.z);
        return (sample >= lower) * (sample <= upper) * sample;
      },
      [] __device__ (float x) -> float {
        return (x > 0) * 1;
      });
}

void scale() {
  auto max = thrust::max_element(thrust::device_pointer_cast(_q.device()),
                                 thrust::device_pointer_cast(_q.device() + _lattice.cuboid().volume));
  _scale = 1 / max[0];
}

void interact() {
  ImGui::SliderFloat("Scale", &_scale, 0.01f, 10000.f);
  ImGui::SameLine();
  if (ImGui::Button("Auto")) {
    scale();
  }
  ImGui::DragFloatRange2("Bounds", &_lower, &_upper, 0.01f, 0.01f, 1.f, "%.2f", "%.2f");
}

};

template <typename DESCRIPTOR, typename T, typename S, typename SDF>
QCriterionS(Lattice<DESCRIPTOR,T,S>&, DeviceBuffer<bool>&, SDF) -> QCriterionS<DESCRIPTOR,T,S,SDF>;
#+END_SRC

** Volumetric Rendering
*** Intersection Primitives
In order to quickly check whether a given ray intersects our embedded simulation domain we implement a common
function for checking intersections with /axis-aligned bounding boxes/. Requiring the box to be axis-aligned greatly
simplifies and speeds up the problem.

#+NAME: box-intersection
#+BEGIN_SRC cpp
__device__ bool aabb(float3 origin, float3 dir, float3 min, float3 max, float& tmin, float& tmax) {
  float3 invD = make_float3(1./dir.x, 1./dir.y, 1./dir.z);
  float3 t0s = (min - origin) * invD;
  float3 t1s = (max - origin) * invD;
  float3 tsmaller = fminf(t0s, t1s);
  float3 tbigger  = fmaxf(t0s, t1s);
  tmin = fmaxf(tmin, fmaxf(tsmaller.x, fmaxf(tsmaller.y, tsmaller.z)));
  tmax = fminf(tmax, fminf(tbigger.x, fminf(tbigger.y, tbigger.z)));
  return (tmin < tmax);
}

__device__ bool aabb(float3 origin, float3 dir, descriptor::CuboidD<3>& cuboid, float& tmin, float& tmax) {
  return aabb(origin, dir, make_float3(0), make_float3(cuboid.nX,cuboid.nY,cuboid.nZ), tmin, tmax);
}
#+END_SRC

*** Pinhole Camera
#+NAME: raycast-pinhole-camera
#+BEGIN_SRC cpp
__device__ float2 getNormalizedScreenPos(float w, float h, float x, float y) {
	return make_float2(
		2.f * (.5f - x/w) * w/h,
		2.f * (.5f - y/h)
	);
}

__device__ float3 getEyeRayDir(float2 screen_pos, float3 forward, float3 right, float3 up) {
	return normalize(screen_pos.x*right + screen_pos.y*up + 4*forward);
}
#+END_SRC

*** Image Synthesis
Let $C$ be the color along a ray $r$ with length $L$ and given an absorption $\mu$. Then the volume rendering equation
to determine said color $C$ looks as follows:

$$C(r) = \int_0^L c(x) \mu(x) \exp\left(-\int_0^x \mu(t) dt\right) dx$$

i.e. we integrate over the color values $c(x)$ along the ray weighted by the current absorption $\mu$ and the accumulated
absorption up to the current point. This way samples that are closer to the view origin will be more prominent than samples
of the same magnitude that are farther away which of course is also a basic version of how a real volume looks, hence
the name.

We are now going to implement an optimized version of this volume rendering equation to determine
the color of a pixel in location =screen_pos= given a normalized ray direction =ray_dir= and an eye position
=camera_position= as the starting point.

#+NAME: volumetric-render-config
#+BEGIN_SRC cpp
struct VolumetricRenderConfig {
  descriptor::CuboidD<3> cuboid;

  cudaSurfaceObject_t palette;
  cudaSurfaceObject_t noise;

  float delta = 1;
  float transparency = 1;
  float brightness = 1;
  float3 background = make_float3(22.f / 255.f);

  float3 camera_position;
  float3 camera_forward;
  float3 camera_right;
  float3 camera_up;

  cudaSurfaceObject_t canvas;
  uint2 canvas_size;

  bool align_slices_to_view = true;
  bool apply_noise = true;
  bool apply_blur = true;

  VolumetricRenderConfig(descriptor::CuboidD<3> c):
    cuboid(c) { }
};
#+END_SRC

#+NAME: volumetric-renderer
#+BEGIN_SRC cpp
float3 r = make_float3(0);
float  a = 0;

float tmin = 0;
float tmax = 4000;

if (aabb(config.camera_position, ray_dir, config.cuboid, tmin, tmax)) {
  float volume_dist = tmax - tmin;
  float3 geometry_pos = config.camera_position + tmin*ray_dir;
  float geometry_dist = approximateDistance(geometry, geometry_pos, ray_dir, 0, volume_dist);
  geometry_pos += geometry_dist * ray_dir;

  float jitter = config.align_slices_to_view * (floor(fabs(dot(config.camera_forward, tmin*ray_dir)) / config.delta) * config.delta - tmin)
               + config.apply_noise          * config.delta * noiseFromTexture(config.noise, threadIdx.x, threadIdx.y);

  tmin          += jitter;
  volume_dist   -= jitter;
  geometry_dist -= jitter;

  if (volume_dist > config.delta) {
    float3 sample_pos = config.camera_position + tmin * ray_dir;
    unsigned n_samples = floor(geometry_dist / config.delta);
    for (unsigned i=0; i < n_samples; ++i) {
      <<volumetric-renderer-body>>
    }
  }

  if (geometry_dist < volume_dist) {
    float3 n = sdf_normal(geometry, geometry_pos);
    r = lerp((0.3f + fabs(dot(n, ray_dir))) * make_float3(0.3f), r, a);
  }
} else {
  a = 0;
}

if (a < 1) {
  r += (1 - a) * config.background;
}
#+END_SRC

This listing sets up the ray marching loop for any ray that intersects the simulation domain bounding box. It also handles
the incorporation of obstacle geometries as described by a signed distance function. We should use the exact same function
for this that we also use to set boundary material numbers or to configure interpolated bounce back distances.

The most relevant part of this is the content of the marching loop that traverses the domain and sums up the samples
along the way. We use a straight forward performance-friendfly simplification of the volume rendering equation for that.

$$C(r) = \sum_{i=0}^N C(i \Delta x) \alpha (i \Delta x) \prod_{j=0}^{i-1} \left(1 - \alpha(j\Delta x)\right)$$

#+NAME: volumetric-renderer-body
#+BEGIN_SRC cpp
sample_pos += config.delta * ray_dir;

float  sample_value = sampler(sample_pos);
float3 sample_color = config.brightness * colorFromTexture(config.palette, sample_value);

float sample_attenuation = attenuator(sample_value) * config.transparency;
float attenuation = 1 - a;

r += attenuation * sample_attenuation * sample_color;
a += attenuation * sample_attenuation;
#+END_SRC

To call this render function we now only need to wrap it in a CUDA kernel that we template for given
sampling and color palette functions.

#+BEGIN_SRC cpp :tangle tangle/LLBM/volumetric.h
#include <cuda-samples/Common/helper_math.h>

#include <LLBM/sdf.h>

<<raycast-pinhole-camera>>

<<box-intersection>>

<<volumetric-render-config>>

<<color-from-texture>>

template <typename SDF, typename SAMPLER, typename ATTENUATOR>
__global__ void raymarch(
  VolumetricRenderConfig config,
  SDF geometry,
  SAMPLER sampler,
  ATTENUATOR attenuator
) {
  unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;
  unsigned int y = blockIdx.y*blockDim.y + threadIdx.y;

  if (x > config.canvas_size.x - 1 || y > config.canvas_size.y - 1) {
    return;
  }

  const float2 screen_pos = getNormalizedScreenPos(config.canvas_size.x, config.canvas_size.y, x, y);
  const float3 ray_dir = getEyeRayDir(screen_pos, config.camera_forward, config.camera_right, config.camera_up);

  <<volumetric-renderer>>

  uchar4 pixel {
    static_cast<unsigned char>(clamp(r.x, 0.0f, 1.0f) * 255),
    static_cast<unsigned char>(clamp(r.y, 0.0f, 1.0f) * 255),
    static_cast<unsigned char>(clamp(r.z, 0.0f, 1.0f) * 255),
    255
  };
  surf2Dwrite(pixel, config.canvas, x*sizeof(uchar4), y);
}
#+END_SRC

*** Surface Shading
Basic shading of the SDF-described obstacles requires us to calculate surface normals for arbitrary interesection points.

Local normals are easily reconstructed from a signed distance function by sampling their neighborhood. We do not even
have to use the true distance in some direction for this as near some surface the shortest distance should be reasonably
close - at least close enough to produce correct looking visualizations.

#+BEGIN_SRC cpp :tangle tangle/LLBM/sdf.h
template <typename SDF>
__device__ float3 sdf_normal(SDF sdf, float3 v, float eps=1e-4) {
  return normalize(make_float3(
    sdf(make_float3(v.x + eps, v.y, v.z)) - sdf(make_float3(v.x - eps, v.y, v.z)),
    sdf(make_float3(v.x, v.y + eps, v.z)) - sdf(make_float3(v.x, v.y - eps, v.z)),
    sdf(make_float3(v.x, v.y, v.z + eps)) - sdf(make_float3(v.x, v.y, v.z - eps))
  ));
}
#+END_SRC

*** Noise
Volumetric renderings that are produced when using a plain ray marching algorithm may
contain undesired artifacts that distract from the actual visualization. Specifically the choice
of start offsets w.r.t. to the view origin can lead to slicing artifacts. While this tends to become
less noticable for smaller step widths these are not desirable from a performance perspective.

Our renderer employs view-aligned slicing and random jittering to remove visible slicing.
The choice of /randomness/ for jittering the ray origin is critical here as plain random numbers
produce a ugly static-like pattern. A common choice in practice is to use so called /blue noise/
instead. Noise is called /blue/ if it contains only higher frequency components which makes it
harder for the pattern recognizer that we call brain to find patterns where there should be none.

For performance it makes sense to precompute such blue noise into tileable textures 
than can then be easily used to fetch per-pixel-ray jitter offsets.

The void-and-cluster algorithm cite:ulichneyVoidandclusterMethodDither1993
provides a straight forward method for generating tileable blue noise textures.

#+BEGIN_SRC python :session :results none
import numpy as np
import matplotlib.pyplot as plt
from numpy.ma import masked_array
from scipy.ndimage import gaussian_filter
#+END_SRC

The first ingredient for this algorithm is a =filteredPattern= function that applies a
plain Gaussian filter with given $\sigma$ to a cyclic 2d array. Using cyclic wrapping here is
what makes the generated texture tileable.

#+BEGIN_SRC python :session :results none
def filteredPattern(pattern, sigma):
    return gaussian_filter(pattern.astype(float), sigma=sigma, mode='wrap', truncate=np.max(pattern.shape))
#+END_SRC

This function will be used to compute the locations of the largest void and tightest
cluster in a binary pattern (i.e. a 2D array of 0s and 1s). In this context a /void/ describes
an area with only zeros and a /cluster/ describes an area with only ones.

#+BEGIN_SRC python :session :results none
def largestVoidIndex(pattern, sigma):
    return np.argmin(masked_array(filteredPattern(pattern, sigma), mask=pattern))
#+END_SRC

These two functions work by considering the given binary pattern as a float array that is blurred by
the Gaussian filter. The blurred pattern gives an implicit ordering of the /voidness/ of each pixel, the
minimum of which we can determine by a simple search. It is important to exclude the initial binary
pattern here as void-and-cluster depends on finding the largest areas where no pixel is set.

#+BEGIN_SRC python :session :results none
def tightestClusterIndex(pattern, sigma):
    return np.argmax(masked_array(filteredPattern(pattern, sigma), mask=np.logical_not(pattern)))
#+END_SRC

Computing the tightest cluster works in the same way with the exception of searching the largest array
element and masking by the inverted pattern.

#+BEGIN_SRC python :session :results none
def initialPattern(shape, n_start, sigma):
    initial_pattern = np.zeros(shape, dtype=np.bool)
    initial_pattern.flat[0:n_start] = True
    initial_pattern.flat = np.random.permutation(initial_pattern.flat)
    
    cluster_idx, void_idx = -2, -1
    while cluster_idx != void_idx:
        cluster_idx = tightestClusterIndex(initial_pattern, sigma)
        initial_pattern.flat[cluster_idx] = False
        void_idx = largestVoidIndex(initial_pattern, sigma)
        initial_pattern.flat[void_idx] = True
    
    return initial_pattern
#+END_SRC

For the initial binary pattern we set =n_start= random locations to one and then repeatedly
break up the largest void by setting its center to one. This is also done for the tightest cluster
by setting its center to zero. We do this until the locations of the tightest cluster and largest
void overlap.

#+BEGIN_SRC python :session :results none
def blueNoise(shape, sigma):
    n = np.prod(shape)
    n_start = int(n / 10)
    
    initial_pattern = initialPattern(shape, n_start, sigma)
    noise = np.zeros(shape)
    
    pattern = np.copy(initial_pattern)
    for rank in range(n_start,-1,-1):
        cluster_idx = tightestClusterIndex(pattern, sigma)
        pattern.flat[cluster_idx] = False
        noise.flat[cluster_idx] = rank
    
    pattern = np.copy(initial_pattern)
    for rank in range(n_start,int((n+1)/2)):
        void_idx = largestVoidIndex(pattern, sigma)
        pattern.flat[void_idx] = True
        noise.flat[void_idx] = rank
    
    for rank in range(int((n+1)/2),n):
        cluster_idx = tightestClusterIndex(np.logical_not(pattern), sigma)
        pattern.flat[cluster_idx] = True
        noise.flat[cluster_idx] = rank
    
    return noise / (n-1)
#+END_SRC

The actual algorithm utilizes these three helper functions in  four steps:
1. Initial pattern generation
2. Eliminiation of =n_start= tightest clusters
3. Elimination of =n/2-n_start= largest voids
4. Elimination of =n-n/2= tightest clusters of inverse pattern
For each elimination the current =rank= is stored in the noise texture
producing a 2D arrangement of the integers from 0 to =n=. As the last
step the array is divided by =n-1= to yield a grayscale texture with values
in $[0,1]$.

#+BEGIN_SRC python :session :results file :cache yes
test_noise = blueNoise((101,101), 1.9)
test_noise_path = 'tangle/tmp/test_noise.png'

fig, axs = plt.subplots(1,2, figsize=(8,4), sharey=True)
axs[0].set_title('Raw blue noise texture')
axs[0].set_axis_off()
axs[0].imshow(np.dstack((test_noise,test_noise,test_noise)))
axs[1].set_title('Fourier transformation')
axs[1].set_axis_off()
axs[1].imshow(np.log(np.abs(np.fft.fftshift(np.fft.fft2(test_noise)))), cmap='binary')

fig.savefig(test_noise_path, bbox_inches='tight', pad_inches=0)
test_noise_path
#+END_SRC

#+RESULTS[d74551fb6d155b85b3fce050ac0b5561ee217040]:
[[file:tangle/tmp/test_noise.png]]

#+NAME: blue-noise-values
#+BEGIN_SRC python :session :results file :cache yes
fig, axs = plt.subplots(1,5, figsize=(8,2))

for i in range(5):
    noise = blueNoise((32,32), 1.9)
    noise_rgb = np.dstack((noise,noise,noise))
    plt.imsave(f"tangle/asset/noise/blue_{ i }.png", noise_rgb)
    axs[i].imshow(noise_rgb)
    axs[i].set_axis_off()

noise_overview_path = 'tangle/tmp/noise_overview.png'
fig.savefig(noise_overview_path, bbox_inches='tight', pad_inches=0)
noise_overview_path
#+END_SRC

#+RESULTS[124750b29bb542c10bf3a939d5226f502f0f98f9]: blue-noise-values
[[file:tangle/tmp/noise_overview.png]]

#+BEGIN_SRC cpp :tangle tangle/util/noise.h
#pragma once
#include "assets.h"
#include "texture.h"

#include <imgui.h>
#include <imgui-SFML.h>
#include <SFML/Graphics.hpp>
#+END_SRC

In order to manage the noise texture at runtime we implement a simple =NoiseSource=
similar to the =ColorPalette= class.

#+BEGIN_SRC cpp :tangle tangle/util/noise.h
struct NoiseSource {
  const assets::File* current;
  sf::Texture texture;

  NoiseSource(cudaSurfaceObject_t& noise) {
    current = &assets::noise::files[0];
    texture.loadFromMemory(current->data, current->size);
    noise = bindTextureToCuda(texture);
  }

  void interact();
};
#+END_SRC

The values of the selected noise texture are also accessed similarly.

#+BEGIN_SRC cpp :tangle tangle/LLBM/memory.h
__device__ float noiseFromTexture(cudaSurfaceObject_t noisemap, int x, int y) {
  uchar4 color{};
  surf2Dread(&color, noisemap, x*sizeof(uchar4), y);
  return color.x / 255.f;
}
#+END_SRC

The interaction UI only provides a image-displaying drop down box to choose
between the five different noise textures generated in this section.

#+BEGIN_SRC cpp :tangle tangle/util/noise.h
void NoiseSource::interact() {
  ImGui::Image(texture, sf::Vector2f(32,20));
  ImGui::SameLine();
  if (ImGui::BeginCombo("Noise", current->name.c_str())) {
    for (unsigned i=0; i < assets::noise::file_count; ++i) {
      bool is_selected = (current == &assets::noise::files[i]);
      if (ImGui::Selectable(assets::noise::files[i].name.c_str(), is_selected)) {
        current = &assets::noise::files[i];
        texture.loadFromMemory(current->data, current->size);
        break;
      }
      if (is_selected) {
        ImGui::SetItemDefaultFocus();
      }
    }
    ImGui::EndCombo();
  }
}
#+END_SRC

We can apply a basic Gauß blurring stencil as a GLSL fragment shader to smoothen out the remaining artifacts.
This common filter simply sums up the neighboring pixel colors weighted by a Gaussian normal distribution.

#+BEGIN_SRC glsl :eval no :tangle tangle/asset/shader/blur.frag
#version 330

uniform sampler2D texture;

layout(location = 0) out vec4 color;
layout(origin_upper_left, pixel_center_integer) in vec4 gl_FragCoord;

float kernel[7] = float[]( <<gauss-blur-filter()>> );

void main() {
  vec3 blurred = vec3(0.0);

  for (int i=-3; i <= 3; ++i) {
    for (int j=-3; j <= 3; ++j) {
      blurred += kernel[3+j] * kernel[3+i] * texelFetch(texture, ivec2(gl_FragCoord.xy) + ivec2(i,j), 0).xyz;
    }
  }

  color = vec4(blurred, 1.0);
}
#+END_SRC

As the weights used by the blur stencil stay the same for every pixel we can precompute them to speed up the shader.

#+NAME: gauss-blur-filter
#+BEGIN_SRC python :session :results output
def pdf(x):
    return 1/sqrt(2*pi) * exp(-1/2*x**2)

print(', '.join([ str(pdf(x).evalf()) for x in range(-3,4) ]))
#+END_SRC

#+RESULTS: gauss-blur-filter
: 0.00443184841193801, 0.0539909665131881, 0.241970724519143, 0.398942280401433, 0.241970724519143, 0.0539909665131881, 0.00443184841193801

*** Camera Controller
#+BEGIN_SRC cpp :tangle tangle/util/camera.h
#pragma once
#include <cuda-samples/Common/helper_math.h>
#include <glm/gtx/quaternion.hpp>
#include "SFML/Window/Event.hpp"
#+END_SRC

A convenient way of interactively controlling the view parameters of a pinhole camera is to implement
a orbiting camera. This type of camera can be rotated around a central target point using the mouse.

While translation is realized easily by adding the same shift vector to the current camera position and
target point, rotation is more complex. Quaternions are a common object for expressing rotations of 3D
space in a easily combinable manner.

Given 3D vectors $v$ are easily rotated by a quaternion $q$ using $v^\prime = q v \overline{q}$.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
glm::vec3 apply(glm::quat q, glm::vec3 v) {
  return glm::axis(q * glm::quat(0, v) * glm::conjugate(q));
}
#+END_SRC

Interactive manipulations of the rotation around a point require accumulation of individual
rotations over consecutive operations. Each single operation also results of the combination
of multiple basic rotations. Our =Camera= class is  going to accumulate all rotations in a single
quaternion variable =_rotation=.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
class Camera {
private:
glm::quat _rotation;
#+END_SRC

Using the rotation quaternion we can compute all pinhole camera parameters. As they only
change when a rotation is performed we store them in a set of variables.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
glm::vec3 _target;
glm::vec3 _position;
glm::vec3 _forward;
glm::vec3 _right;
glm::vec3 _up;
float _distance;
#+END_SRC

Handling user input events depends on tracking some additional state to compute the
delta between current and previous mouse location as well as the currently active
manipulation.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
float2 _mouse;

bool _rotating;
bool _moving;

bool _restricted_x;
bool _restricted_y;
#+END_SRC

The =update= function projects the screen space forward, right and up vectors into world space.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
void update() {
  _position = _target + apply(_rotation, glm::vec3(0, _distance, 0));
  _forward = glm::normalize(_target - _position);
  _right = apply(_rotation, glm::vec3(-1, 0, 0));
  _up = apply(_rotation, glm::cross(glm::vec3(0, 1, 0), glm::vec3(-1, 0, 0)));
}
#+END_SRC

The camera's initial view will be at a =distance= from a given =target= position.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
public:
Camera(float3 target, float distance):
  _distance(distance),
  _target(target.x, target.y, target.z),
  _rotating(false),
  _moving(false),
  _restricted_x(false),
  _restricted_y(false) {
  update();
}
#+END_SRC

The event handler accepts SFML-provided input events to control rotation restrictions
as well as the currently selected tool.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
void handle(sf::Event& event) {
  switch (event.type) {
  case sf::Event::KeyPressed:
    if (event.key.code == sf::Keyboard::LShift && !_restricted_x && !_restricted_y) {
      _restricted_x = true;
      _restricted_y = true;
    }
    break;
  case sf::Event::KeyReleased:
    if (event.key.code == sf::Keyboard::LShift) {
      _restricted_x = false;
      _restricted_y = false;
    }
    break;
  case sf::Event::MouseButtonPressed:
    if (event.mouseButton.button == sf::Mouse::Left) {
      _rotating = true;
    } else if (event.mouseButton.button == sf::Mouse::Right) {
      _moving = true;
    }
    _mouse = make_float2(event.mouseButton.x, event.mouseButton.y);
    break;
  case sf::Event::MouseButtonReleased: {
    bool restricted = _restricted_x + _restricted_y;
    _restricted_x = restricted;
    _restricted_y = restricted;
    _rotating = false;
    _moving = false;
    break;
  }
#+END_SRC

Next we change the translation and rotation vectors to zoom when the mouse wheel is turned…

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
  case sf::Event::MouseWheelMoved:
    _distance -= event.mouseWheel.delta * 10;
    break;
#+END_SRC

…rotate around the current screen-relative x- and z-axis…

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
  case sf::Event::MouseMoved:
    float2 mouse = make_float2(event.mouseMove.x, event.mouseMove.y);
    if (_rotating) {
      float2 delta = 0.005 * (mouse - _mouse);
      if (_restricted_x && _restricted_y) {
        if (std::abs(delta.x) > std::abs(delta.y)) {
          _restricted_y = false;
        } else {
          _restricted_x = false;
        }
      }
      if (_restricted_x) { delta.y = 0; }
      if (_restricted_y) { delta.x = 0; }
      glm::quat rotation_z = glm::vec3(0,0,delta.x);
      glm::quat rotation_x = glm::vec3(delta.y,0,0);
      _rotation *= glm::cross(rotation_x, rotation_z);
    }
#+END_SRC

…or move the target point while preserving rotation.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
    if (_moving) {
      float2 delta = 0.04 * (mouse - _mouse);
      _target += _right*delta.x + _up*delta.y;
    }
    _mouse = mouse;
    break;
  }
  update();
}
#+END_SRC

Finally we need to provide a set of method through which the
ray marching code can access the camera parametrization.

#+BEGIN_SRC cpp :tangle tangle/util/camera.h
float3 getPosition() const {
  return make_float3(_position.x, _position.y, _position.z);
}
float3 getForward() const {
  return make_float3(_forward.x, _forward.y, _forward.z);
}
float3 getRight() const {
  return make_float3(_right.x, _right.y, _right.z);
}
float3 getUp() const {
  return make_float3(_up.x, _up.y, _up.z);
}
};
#+END_SRC

*** Samplers
#+BEGIN_SRC cpp :tangle tangle/sampler/sampler.h
#pragma once
#include <LLBM/base.h>

class RenderWindow;
class VolumetricRenderConfig;
#+END_SRC

All methods for mapping interfacing lattice data and image synthesizer
share the common base class =Sampler=. This class provides a texture
buffer for storing the sampled information as well as the common
interface consisting of =sample=, =render= and =interact= methods to
be called by higher-level scaffolding.

#+BEGIN_SRC cpp :tangle tangle/sampler/sampler.h
class Sampler {
protected:
const std::string _name;

DeviceTexture<float> _sample_buffer;
cudaTextureObject_t _sample_texture;
cudaSurfaceObject_t _sample_surface;

public:
Sampler(std::string name, descriptor::CuboidD<3> cuboid):
  _name(name),
  _sample_buffer(cuboid),
  _sample_texture(_sample_buffer.getTexture()),
  _sample_surface(_sample_buffer.getSurface())
 { }

const std::string& getName() const {
  return _name;
}

virtual void sample() = 0;
virtual void render(VolumetricRenderConfig& config) = 0;
virtual void interact() = 0;

};
#+END_SRC

*** Scaffolding
<<sec:volumetric-scaffold>>
#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
#pragma once
#include <LLBM/volumetric.h>
#include "camera.h"
#include "texture.h"
#include "colormap.h"
#include "noise.h"
#include "render_window.h"
#include "../sampler/sampler.h"
#+END_SRC

Any =Sampler= implementations we want to provide in a given simulation are maintained in a central
=_sampler= vector. The currently selected sampling method is designated by a pointer through
which the relevant =Sampler::sample=, =Sampler::interact=  and =Sampler::render= methods are
going to be called.

#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
class VolumetricExample : public RenderWindow {
private:
std::vector<std::unique_ptr<Sampler>> _sampler;
Sampler* _current = nullptr;
#+END_SRC

We also maintain instances of the previously defined camera controller, render configuration,
color palette and a noise source for jittering the ray origins.

#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
Camera _camera;
VolumetricRenderConfig _config;
ColorPalette _palette;
NoiseSource _noise;

int _steps_per_second = 100;
int _samples_per_second = 30;
#+END_SRC

Example cases construct their samplers using the =add= method.

#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
public:
template <template<typename...> class SAMPLER, typename... ARGS>
void add(ARGS&&... args) {
  _sampler.emplace_back(new SAMPLER(std::forward<ARGS>(args)...));
  _current = _sampler.back().get();
}
#+END_SRC

At its core the =VolumetricExample= class offers a =run= method that calls
the example-specific simulation code via the =step= callable.

#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
template <typename TIMESTEP>
void run(TIMESTEP step) {
  sf::Clock last_sample;
  sf::Clock last_frame;
  std::size_t iStep = 0;
  volatile bool simulate = true;
#+END_SRC

Next, the method instantiates a separate thread for updating the simulation state independently
of visualization. This way we can e.g. vary the simulation speed or evaluate different visualization
setups for a paused state.

#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
  sf::Thread simulation([&]() {
    while (this->isOpen()) {
      if (last_sample.getElapsedTime().asSeconds() > 1.0 / _samples_per_second) {
        _current->sample();
        cudaStreamSynchronize(cudaStreamPerThread);
        last_sample.restart();
        if (simulate) {
          for (unsigned i=0; i < (1.0 / _samples_per_second) * _steps_per_second; ++i) {
            step(iStep++);
          }
        }
      }
    }
  });
  simulation.launch();
#+END_SRC

After the simulation thread has been started we enter the main visualization loop. This
loop will keep running as long as the window is opened, all the while calling the =draw=
method at the desired frame rate.

#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
  while (this->isOpen()) {
    this->draw(
      [&](){
        <<volumetric-example-simulation-control>>
        <<volumetric-example-render-control>>
      },
      [&](sf::Event& event) {
        <<volumetric-example-handle-events>>
      }
    );
    if (last_frame.getElapsedTime().asSeconds() > 1.0 / _samples_per_second) {
      _current->render(_config);
      cudaStreamSynchronize(cudaStreamPerThread);
      last_frame.restart();
    }
  }

  simulation.wait();
}
#+END_SRC

During event handling the sampler selection can be changed interactively.

#+NAME: volumetric-example-simulation-control
#+BEGIN_SRC cpp
ImGui::Begin("Simulation", 0, ImGuiWindowFlags_AlwaysAutoResize);
if (ImGui::BeginCombo("Source", _current->getName().c_str())) {
  for (auto& option : _sampler) {
    if (ImGui::Selectable(option->getName().c_str(), _current == option.get())) {
      _current = option.get();
    }
  }
  ImGui::EndCombo();
}
_current->interact();
ImGui::SliderInt("Timestep/s", &_steps_per_second, 1, 1500);
ImGui::SliderInt("Samples/s", &_samples_per_second, 1, 60);
if (simulate) {
  simulate = !ImGui::Button("Pause");
} else {
  simulate =  ImGui::Button("Continue");
}
ImGui::End();
#+END_SRC

The volumetric rendering parameters that are independent of specific sampling sources
are exposed in a separate window.

#+NAME: volumetric-example-render-control
#+BEGIN_SRC cpp
ImGui::Begin("Render", 0, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::SliderFloat("Brightness", &_config.brightness, 0.1f, 2.f);
ImGui::SliderFloat("Delta", &_config.delta, 0.05f, 2.f);
ImGui::SliderFloat("Transparency", &_config.transparency, 0.001f, 1.f);
_palette.interact();
if (ImGui::CollapsingHeader("Details")) {
  ImGui::Checkbox("Align slices to view", &_config.align_slices_to_view);
  ImGui::SameLine();
  ImGui::Checkbox("Jitter", &_config.apply_noise);
  ImGui::SameLine();
  ImGui::Checkbox("Blur", &_config.apply_blur);
  this->setBlur(_config.apply_blur);
  if (_config.apply_noise) {
    _noise.interact();
  }
}
ImGui::End();
#+END_SRC

Any input events that are not captured by the UI framework are passed to the camera controller.

#+NAME: volumetric-example-handle-events
#+BEGIN_SRC cpp
_camera.handle(event);
_config.camera_position = _camera.getPosition();
_config.camera_forward = _camera.getForward();
_config.camera_right = _camera.getRight();
_config.camera_up = _camera.getUp();
_config.canvas_size = make_uint2(this->getRenderView().width, this->getRenderView().height);
#+END_SRC

Finally a constructor is needed to instantiate the rendering environment.

#+BEGIN_SRC cpp :tangle tangle/util/volumetric_example.h
VolumetricExample(descriptor::CuboidD<3> cuboid):
  RenderWindow("LiterateLB"),
  _camera(make_float3(cuboid.nX/2,cuboid.nY/2,cuboid.nZ/2), cuboid.nX),
  _config(cuboid),
  _palette(_config.palette),
  _noise(_config.noise)
{
  _config.canvas = this->getRenderSurface();
  this->setBlur(_config.apply_blur);
}

};
#+END_SRC

** Window
While we did not need to directly use e.g. OpenGL instructions to produce and display visualizations,
we still need some way of interfacing with the system UI and to display the textures generated from
CUDA. For convenience this is done using the SFML library.

#+BEGIN_SRC cpp :tangle tangle/util/render_window.h
#pragma once

#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Image.hpp>

#include <imgui.h>
#include <imgui-SFML.h>

#include "texture.h"
#include "assets.h"
#+END_SRC

As all 2D and 3D example simulations render their visualizations to 2D textures and provide
any interactivity via the Dear ImGui library a =RenderWindow= wrapper class is used to collect the
common scaffolding.

#+BEGIN_SRC cpp :tangle tangle/util/render_window.h
class RenderWindow {
private:
sf::RenderWindow _window;

sf::Sprite          _render_sprite;
sf::Texture         _render_texture;
cudaSurfaceObject_t _render_surface;
sf::Rect<int>       _render_texture_view;

sf::Shader _blur_shader;
bool _blur = false;

sf::Clock _ui_delta_clock;

public:
RenderWindow(std::string name):
  _window(sf::VideoMode(800, 600), name) {
  _render_texture.create(sf::VideoMode::getDesktopMode().width, sf::VideoMode::getDesktopMode().height);
  _render_surface = bindTextureToCuda(_render_texture);
  _render_sprite.setTexture(_render_texture);
  _render_texture_view = sf::Rect<int>(0,0,_window.getSize().x,_window.getSize().y);
  _render_sprite.setTextureRect(_render_texture_view);
  _window.setView(sf::View(sf::Vector2f(_render_texture_view.width/2, _render_texture_view.height/2),
                           sf::Vector2f(_window.getSize().x, _window.getSize().y)));
  _window.setVerticalSyncEnabled(true);
  _blur_shader.loadFromMemory(std::string(reinterpret_cast<const char*>(assets::shader::file_blur_frag)), sf::Shader::Fragment);
  _blur_shader.setUniform("texture", sf::Shader::CurrentTexture);
  ImGui::SFML::Init(_window);
  ImGuiIO& io = ImGui::GetIO();
  io.MouseDrawCursor = true;
};

bool isOpen() const {
  return _window.isOpen();
}

void setBlur(bool state) {
  _blur = state;
}

template <typename UI, typename MOUSE>
void draw(UI ui, MOUSE mouse);

cudaSurfaceObject_t getRenderSurface() {
  return _render_surface;
}

sf::Rect<int> getRenderView() {
  return _render_texture_view;
}

};
#+END_SRC

The essential component of this class is the =draw= method to which we can pass
two functions for rendering to the window texture on one hand and for providing
any UI functionality on the other hand.

#+BEGIN_SRC cpp :tangle tangle/util/render_window.h
template <typename UI, typename MOUSE>
void RenderWindow::draw(UI ui, MOUSE mouse) {
  sf::Event event;
  while (_window.pollEvent(event)) {
    ImGui::SFML::ProcessEvent(event);
    if (event.type == sf::Event::Closed) {
      _window.close();
    }
    if (event.type == sf::Event::Resized) {
      _render_texture_view = sf::Rect<int>(0,0,event.size.width,event.size.height);
      _render_sprite.setTextureRect(_render_texture_view);
      sf::View view(sf::Vector2f(_render_texture_view.width/2, _render_texture_view.height/2),
                    sf::Vector2f(event.size.width, event.size.height));
      _window.setView(view);
    }
    if (!ImGui::GetIO().WantCaptureMouse) {
      mouse(event);
    }
  }

  ImGui::SFML::Update(_window, _ui_delta_clock.restart());
  ui();
  _window.clear();
  if (_blur) {
    _window.draw(_render_sprite, &_blur_shader);
  } else {
    _window.draw(_render_sprite);
  }
  ImGui::SFML::Render(_window);
  _window.display();
}
#+END_SRC

This functionality is sufficient for the 2D examples but as volumetric rendering both requires significantly more
scaffolding and builds on different /sampler/ classes section [[sec:volumetric-scaffold]] builds a =VolumetricExample=
class on top of the =RenderWindow=.

* Examples
#+NAME: example-headers
#+BEGIN_SRC cpp
#include <LLBM/base.h>
#include <LLBM/bulk.h>
#include <LLBM/boundary.h>

#include "util/render_window.h"
#include "util/texture.h"
#include "util/colormap.h"
#+END_SRC

** Lid-driven Cavity
The lid-driven cavity is a very common example in the LBM community due to its simple setup while
providing quite complex dynamics and extensive reference results in literature. Its geometry consists
of a plain square box with solid walls and a lid moving at a constant velocity. This lid movement then
induces a characteristic vortex structure inside the box.

#+BEGIN_SRC cpp :tangle tangle/ldc-2d.cu
<<example-headers>>

#include <LLBM/kernel/collect_moments.h>
#include <LLBM/kernel/collect_velocity_norm.h>

using T = float;
using DESCRIPTOR = descriptor::D2Q9;

int main() {
if (cuda::device::count() == 0) {
  std::cerr << "No CUDA devices on this system" << std::endl;
  return -1;
}
auto current = cuda::device::current::get();
#+END_SRC

After including the relevant headers and declaring which floating point precision and descriptor
type to use we are ready to set up the lattice of a \(500 \times 500\) grid.

#+BEGIN_SRC cpp :tangle tangle/ldc-2d.cu
const descriptor::Cuboid<DESCRIPTOR> cuboid(500, 500);
Lattice<DESCRIPTOR,T> lattice(cuboid);
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/ldc-2d.cu
CellMaterials<DESCRIPTOR> materials(cuboid, [&cuboid](uint2 p) -> int {
  if (p.x == 0 || p.y == 0 || p.x == cuboid.nX-1) {
    return 2; // boundary cell
  } else if (p.y == cuboid.nY-1) {
    return 3; // lid cell
  } else {
    return 1; // bulk
  }
});

auto bulk_mask = materials.mask_of_material(1);
auto wall_mask = materials.mask_of_material(2);
auto lid_mask  = materials.mask_of_material(3);
#+END_SRC

The bulk collisions are going to use a relaxation time of \(0.51\) and the lid enacts a velocity of \(0.05\) lattice units.
This maximum velocity can be used to scale the velocity norm for visualization.

#+BEGIN_SRC cpp :tangle tangle/ldc-2d.cu
const float tau = 0.51;
const float u_lid = 0.05;
#+END_SRC

#+NAME: ldc-simulation-step
#+BEGIN_SRC cpp
lattice.apply(Operator(BgkCollideO(), bulk_mask, tau),
              Operator(BounceBackO(), wall_mask),
              Operator(BounceBackMovingWallO(), lid_mask, std::min(iStep*1e-3, 1.0)*u_lid, 0.f));
lattice.stream();
#+END_SRC

Every couple of time steps we execute the =CollectMomentsF= functor to compute the velocity
moments that are then visualized using =renderSliceViewToTexture=.

#+NAME: ldc-visualization-step
#+BEGIN_SRC cpp :eval no :noweb no
lattice.inspect<CollectMomentsF>(bulk_mask, moments_rho.device(), moments_u.device());
renderSliceViewToTexture<<<
  dim3(cuboid.nX / 32 + 1, cuboid.nY / 32 + 1),
  dim3(32,32)
>>>(cuboid.nX, cuboid.nY,
    slice,
    [u,u_lid] __device__ (std::size_t gid) -> float {
      return length(make_float2(u[2*gid+0], u[2*gid+1])) / u_lid;
    },
    [colormap] __device__ (float x) -> float3 {
      return colorFromTexture(colormap, clamp(x, 0.f, 1.f));
    },
    window.getRenderSurface());
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/ldc-2d.cu
RenderWindow window("LDC");
cudaSurfaceObject_t colormap;
ColorPalette palette(colormap);
auto slice = [cuboid] __device__ (int iX, int iY) -> std::size_t {
               return descriptor::gid(cuboid,iX,cuboid.nY-1-iY);
             };
DeviceBuffer<T> moments_rho(cuboid.volume);
DeviceBuffer<T> moments_u(2*cuboid.volume);
T* u = moments_u.device();
std::size_t iStep = 0;

while (window.isOpen()) {
  <<ldc-simulation-step>>
  if (iStep % 100 == 0) {
    cuda::synchronize(current);
    <<ldc-visualization-step>>
    window.draw([&]() {
      ImGui::Begin("Render");
      palette.interact();
      ImGui::End();
    }, [](sf::Event&) { });
  }
  ++iStep;
}
}
#+END_SRC

The same example can also be built in 3D and visualized using volumetric rendering.

#+BEGIN_SRC cpp :tangle tangle/ldc-3d.cu
<<example-headers>>

#include "util/volumetric_example.h"
#include "sampler/velocity_norm.h"
#include "sampler/curl_norm.h"
#include "sampler/shear_layer.h"

using T = float;
using DESCRIPTOR = descriptor::D3Q19;

int main() {
if (cuda::device::count() == 0) {
  std::cerr << "No CUDA devices on this system" << std::endl;
  return -1;
}
auto current = cuda::device::current::get();
#+END_SRC

After including the relevant headers we construct the D3Q19 lattice.

#+BEGIN_SRC cpp :tangle tangle/ldc-3d.cu
const descriptor::Cuboid<DESCRIPTOR> cuboid(100, 100, 100);
Lattice<DESCRIPTOR,T> lattice(cuboid);
#+END_SRC

Before constructing the sphere we set up a basic square pipe with
separate walls, in- and outlets.

#+BEGIN_SRC cpp :tangle tangle/ldc-3d.cu
CellMaterials<DESCRIPTOR> materials(cuboid, [&cuboid](uint3 p) -> int {
  if (p.x == 0 || p.x == cuboid.nX-1 || p.y == 0 || p.y == cuboid.nY-1 || p.z == cuboid.nZ-1) {
    return 2; // boundary cell
  } else if (p.z == 0) {
    return 3; // lid cell
  } else {
    return 1; // bulk
  }
});
#+END_SRC

At this point we are ready to generate masks for operator application.

#+BEGIN_SRC cpp :tangle tangle/ldc-3d.cu
auto bulk_mask = materials.mask_of_material(1);
auto wall_mask = materials.mask_of_material(2);
auto lid_mask  = materials.mask_of_material(3);

cuda::synchronize(current);
#+END_SRC

In order to model the flow we employ standard BGK collisions in the bulk. The side and bottom
walls are modelled using bounce back while the lid uses moving wall bounce back.

#+NAME: ldc-3d-simulation-step
#+BEGIN_SRC cpp :eval no
const float tau = 0.56;
const float lid = 0.10;

lattice.apply(Operator(BgkCollideO(), bulk_mask, tau),
              Operator(BounceBackO(), wall_mask),
              Operator(BounceBackMovingWallO(), lid_mask, std::min(iStep*1e-3, 1.0)*lid, 0.f, 0.f));

lattice.stream();
#+END_SRC

Finally the volumetric renderer is used to control the simulation
loop and to provide velocity, curl and shear layer visualizations.

#+BEGIN_SRC cpp :tangle tangle/ldc-3d.cu
auto none = [] __device__ (float3) -> float { return 1; };
VolumetricExample renderer(cuboid);
renderer.add<CurlNormS>(lattice, bulk_mask, none);
renderer.add<ShearLayerVisibilityS>(lattice, bulk_mask, none, make_float3(0,1,0));
renderer.add<VelocityNormS>(lattice, bulk_mask, none);
renderer.run([&](std::size_t iStep) {
  <<ldc-3d-simulation-step>>
});
}
#+END_SRC

** Magnus
This example simulates the flow around two cylinders, one of which is spinning and thus invoking the Magnus effect.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
<<example-headers>>

#include <LLBM/kernel/collect_moments.h>
#include <LLBM/kernel/collect_velocity_norm.h>

using T = float;
using DESCRIPTOR = descriptor::D2Q9;

int main() {
if (cuda::device::count() == 0) {
  std::cerr << "No CUDA devices on this system" << std::endl;
  return -1;
}
auto current = cuda::device::current::get();
#+END_SRC

Adding another non-spinning cylinder allows for direct comparison and also produces a Kármán vortex street.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
const descriptor::Cuboid<DESCRIPTOR> cuboid(1200, 500);
Lattice<DESCRIPTOR,T> lattice(cuboid);
#+END_SRC

After setting up the lattice we define the relaxation time for the BGK collisions in the
bulk and the desired rotation and inflow velocities.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
const float tau = 0.52;
const float u_inflow = 0.02;
const float u_rotate = 0.08;
#+END_SRC

For the geometry we first distinguish between the bulk and walls ignoring the cylinders.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
CellMaterials<DESCRIPTOR> materials(cuboid, [&cuboid](uint2 p) -> int {
  if (p.x == 0) {
    return 3; // inflow
  } else if (p.x == cuboid.nX-1) {
    return 4; // outflow
  } else if (p.y == 0 || p.y == cuboid.nY-1) {
    return 2; // wall
  } else {
    return 1; // bulk
  }
});
#+END_SRC

Using free-slip conditions at the lower and upper walls requires special handling of the edge cells to prevent
artifacts from forming.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
materials.set(gid(cuboid, 0,0), 2);
materials.set(gid(cuboid, 0,cuboid.nY-1), 2);
materials.set(gid(cuboid, cuboid.nX-1,0), 5);
materials.set(gid(cuboid, cuboid.nX-1,cuboid.nY-1), 5);
#+END_SRC

Both cylinders are modelled using interpolated bounce back.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
auto cylinder = [cuboid] __host__ __device__ (float2 p) -> float {
                  float2 q = p - make_float2(cuboid.nX/6, 3*cuboid.nY/4);
                  float2 r = p - make_float2(cuboid.nX/6, 1*cuboid.nY/4);
                  return sdf::add(sdf::sphere(q, cuboid.nY/18),
                                  sdf::sphere(r, cuboid.nY/18));
                };

materials.sdf(cylinder, 0);
SignedDistanceBoundary bouzidi(lattice, materials, cylinder, 1, 0);
#+END_SRC

The distance from the rotating cylinder's center is used to decide where to set up the
moving wall boundary.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
bouzidi.setVelocity([cuboid,u_rotate](float2 p) -> float2 {
  float2 q = p - make_float2(cuboid.nX/6, 3*cuboid.nY/4);
  if (length(q) < 1.1*cuboid.nY/18) {
    return u_rotate * normalize(make_float2(-q.y, q.x));
  } else {
    return make_float2(0);
  }
});
#+END_SRC

The geometry setup is concluded by generating per-material masks to be used by the collision kernel.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
auto bulk_mask = materials.mask_of_material(1);
auto wall_mask = materials.mask_of_material(2);
auto inflow_mask  = materials.mask_of_material(3);
auto outflow_mask = materials.mask_of_material(4);
auto edge_mask = materials.mask_of_material(5);
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
cuda::synchronize(current);
#+END_SRC

During each timestep we apply all purely local collision operators in a single fused
sweep of the lattice. This is followed by calling =BouzidiO= on the SDF-generated
boundary configuration.

#+NAME: magnus-simulation-step
#+BEGIN_SRC cpp
lattice.apply(Operator(BgkCollideO(), bulk_mask, tau),
              Operator(BounceBackFreeSlipO(), wall_mask, WallNormal<0,1>()),
              Operator(EquilibriumVelocityWallO(), inflow_mask, std::min(iStep*1e-5, 1.)*u_inflow, WallNormal<1,0>()),
              Operator(EquilibriumDensityWallO(), outflow_mask, 1., WallNormal<-1,0>()),
              Operator(BounceBackO(), edge_mask));
lattice.apply<BouzidiO>(bouzidi.getCount(), bouzidi.getConfig());
lattice.stream();
#+END_SRC

Visualization is restricted to a plain velocity norm display in this case.
More involved options will be provided for later examples.

#+NAME: magnus-visualization-step
#+BEGIN_SRC cpp :eval no :noweb no
lattice.inspect<CollectMomentsF>(bulk_mask, moments_rho.device(), moments_u.device());
renderSliceViewToTexture<<<
  dim3(cuboid.nX / 32 + 1, cuboid.nY / 32 + 1),
  dim3(32,32)
>>>(cuboid.nX, cuboid.nY,
    [cuboid] __device__ (int iX, int iY) -> std::size_t {
      return descriptor::gid(cuboid,iX,cuboid.nY-1-iY);
    },
    [u,u_rotate] __device__ (std::size_t gid) -> float {
      return length(make_float2(u[2*gid+0], u[2*gid+1])) / u_rotate;
    },
    [colormap] __device__ (float x) -> float3 {
      return colorFromTexture(colormap, clamp(x, 0.f, 1.f));
    },
    window.getRenderSurface());
#+END_SRC

The render target is provided by our =RenderWindow= class. We also need
variables for storing the colormap and buffers for storing the computed
moments.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
RenderWindow window("Magnus");
cudaSurfaceObject_t colormap;
ColorPalette palette(colormap);
DeviceBuffer<T> moments_rho(cuboid.volume);
DeviceBuffer<T> moments_u(2*cuboid.volume);
T* u = moments_u.device();
#+END_SRC

Finally we run the simulation as long as the window is open
while periodically calling the visualization code.

#+BEGIN_SRC cpp :tangle tangle/magnus.cu
std::size_t iStep = 0;
while (window.isOpen()) {
  <<magnus-simulation-step>>
  if (iStep % 200 == 0) {
    cuda::synchronize(current);
    <<magnus-visualization-step>>
    window.draw([&]() {
      ImGui::Begin("Render");
      palette.interact();
      ImGui::End();
    }, [](sf::Event&) { });
  }
  ++iStep;
}
}
#+END_SRC

Contrasting the rotating and non-rotating cylinders we can observe both the
magnus effect and the formation of a Kármán vortex street.

#+BEGIN_EXPORT html
<video style="width:100%" src="https://literatelb.org/media/magnus.webm" playsinline muted controls loop/>
#+END_EXPORT

** Channel with obstacle
This example models a channel flow around a spherical obstacle.

#+BEGIN_SRC cpp :tangle tangle/channel.cu
<<example-headers>>

#include "util/volumetric_example.h"
#include "sampler/velocity_norm.h"
#include "sampler/curl_norm.h"
#include "sampler/q_criterion.h"

using T = float;
using DESCRIPTOR = descriptor::D3Q19;

int main() {
if (cuda::device::count() == 0) {
  std::cerr << "No CUDA devices on this system" << std::endl;
  return -1;
}
auto current = cuda::device::current::get();
#+END_SRC

After including the relevant headers we construct the D3Q19 lattice.

#+BEGIN_SRC cpp :tangle tangle/channel.cu
const descriptor::Cuboid<DESCRIPTOR> cuboid(500, 100, 100);
Lattice<DESCRIPTOR,T> lattice(cuboid);
#+END_SRC

Before constructing the sphere we set up a basic square channel with
free slip walls and separate in- and outlets.

#+BEGIN_SRC cpp :tangle tangle/channel.cu
CellMaterials<DESCRIPTOR> materials(cuboid, [&cuboid](uint3 p) -> int {
  if (p.z == 0 || p.z == cuboid.nZ-1) {
    return 2; // boundary cell
  } else if (p.y == 0 || p.y == cuboid.nY-1) {
    return 3; // boundary cell
  } else if (p.x == 0) {
    return 4; // inflow cell
  } else if (p.x == cuboid.nX-1) {
    return 5; // outflow cell
  } else {
    return 1; // bulk
  }
});
#+END_SRC

As the free slip bounce back condition is not well defined at the edges we use
plain bounce back instead.

#+BEGIN_SRC cpp :tangle tangle/channel.cu
for (std::size_t iX=0; iX < cuboid.nX; ++iX) {
  materials.set(gid(cuboid, iX, 0,           0), 6);
  materials.set(gid(cuboid, iX, cuboid.nY-1, 0), 6);
  materials.set(gid(cuboid, iX, 0,           cuboid.nZ-1), 6);
  materials.set(gid(cuboid, iX, cuboid.nY-1, cuboid.nZ-1), 6);
}
#+END_SRC

The obstacle is modelled using a signed distance function from which we
generate a configuraton of the interpolated bounce back condition.

#+BEGIN_SRC cpp :tangle tangle/channel.cu
auto obstacle = [cuboid] __host__ __device__ (float3 p) -> float {
  p -= make_float3(cuboid.nX/5, cuboid.nY/2, cuboid.nZ/2);
  float3 q = sdf::twisted(p, 0.01);
  return sdf::sphere(p, cuboid.nY/3.5) + sin(0.2*q.x)*sin(0.2*q.y)*sin(0.2*q.z);
};

materials.sdf(obstacle, 0);
SignedDistanceBoundary bouzidi(lattice, materials, obstacle, 1, 0);
#+END_SRC

At this point the masks for operator application can be generated.

#+BEGIN_SRC cpp :tangle tangle/channel.cu
auto bulk_mask    = materials.mask_of_material(1);
auto wall_mask_z  = materials.mask_of_material(2);
auto wall_mask_y  = materials.mask_of_material(3);
auto inflow_mask  = materials.mask_of_material(4);
auto outflow_mask = materials.mask_of_material(5);
auto edge_mask    = materials.mask_of_material(6);

cuda::synchronize(current);
#+END_SRC

In order to model the flow we employ Smagorinsky BGK collisions in the bulk. The
channel walls are modelled using (free slip) bounce back and the SDF-described
obstacle is represented with interpolated bounce back.

#+NAME: channel-simulation-step
#+BEGIN_SRC cpp :eval no
const float tau = 0.501;
const float smagorinsky = 0.1;
const float inflow = 0.04;

lattice.apply(Operator(SmagorinskyBgkCollideO(), bulk_mask, tau, smagorinsky),
              Operator(BounceBackFreeSlipO(), wall_mask_z, WallNormal<0,0,1>()),
              Operator(BounceBackFreeSlipO(), wall_mask_y, WallNormal<0,1,0>()),
              Operator(EquilibriumVelocityWallO(), inflow_mask, std::min(iStep*1e-4, 1.0)*inflow, WallNormal<1,0,0>()),
              Operator(EquilibriumDensityWallO(), outflow_mask, 1, WallNormal<-1,0,0>()),
              Operator(BounceBackO(), edge_mask));
lattice.apply<BouzidiO>(bouzidi.getCount(), bouzidi.getConfig());

lattice.stream();
#+END_SRC

Finally the volumetric renderer is used to control the simulation
loop and to provide velocity, curl and Q criterion visualizations.

#+BEGIN_SRC cpp :tangle tangle/channel.cu
VolumetricExample renderer(cuboid);
renderer.add<QCriterionS>(lattice, bulk_mask, obstacle);
renderer.add<CurlNormS>(lattice, bulk_mask, obstacle);
renderer.add<VelocityNormS>(lattice, bulk_mask, obstacle);
renderer.run([&](std::size_t iStep) {
  <<channel-simulation-step>>
});
}
#+END_SRC

** Taylor-Couette
A fluid confined in the gap between two rotating cylinders with sufficient angular velocity develops
interesting toroidial vortices. For this example we are going to use a special shear-layer thresholding
approach for highlighting those vortices.

#+BEGIN_SRC cpp :tangle tangle/taylor-couette.cu
<<example-headers>>

#include "util/volumetric_example.h"
#include "sampler/velocity_norm.h"
#include "sampler/curl_norm.h"
#include "sampler/shear_layer.h"

using T = float;
using DESCRIPTOR = descriptor::D3Q19;

int main() {
if (cuda::device::count() == 0) {
  std::cerr << "No CUDA devices on this system" << std::endl;
  return -1;
}
auto current = cuda::device::current::get();
#+END_SRC

After including the relevant headers we construct the D3Q19 lattice.

#+BEGIN_SRC cpp :tangle tangle/taylor-couette.cu
const descriptor::Cuboid<DESCRIPTOR> cuboid(500, 96, 96);
Lattice<DESCRIPTOR,T> lattice(cuboid);
#+END_SRC

The initial geometry consists only of a cube with separated left and right boundaries.

#+BEGIN_SRC cpp :tangle tangle/taylor-couette.cu
CellMaterials<DESCRIPTOR> materials(cuboid, [&cuboid](uint3 p) -> int {
  if (p.x == 0 || p.x == cuboid.nX-1) {
    return 2;
  } else {
    return 1;
  }
});
#+END_SRC

The two cylinders are modelled using a signed distance function from which
we generate a configuraton of the interpolated bounce back condition.

#+BEGIN_SRC cpp :tangle tangle/taylor-couette.cu
auto inner_cylinder = [cuboid] __host__ __device__ (float3 p) -> float {
                        float3 q = p - make_float3(0, cuboid.nY/2, cuboid.nZ/2);
                        return sdf::sphere(make_float2(q.y,q.z), cuboid.nY/T{4.5});
                      };
auto geometry = [cuboid,inner_cylinder] __host__ __device__ (float3 p) -> float {
                  float3 q = p - make_float3(0, cuboid.nY/2, cuboid.nZ/2);
                  return sdf::add(-sdf::sphere(make_float2(q.y,q.z), cuboid.nY/T{2.14}), inner_cylinder(p));
                };
materials.sdf(geometry, 0);
SignedDistanceBoundary bouzidi(lattice, materials, geometry, 1, 0);
#+END_SRC

The rotation of the inner cyclinder is modelled using a velocity field from which we
generate a velocity correction for the Bouzidi boundaries.

#+BEGIN_SRC cpp :tangle tangle/taylor-couette.cu
const float wall = 0.2;

bouzidi.setVelocity([cuboid,wall](float3 p) -> float3 {
  float3 q = p - make_float3(0, cuboid.nY/2, cuboid.nZ/2);
  if (length(make_float2(q.y,q.z)) < cuboid.nY/T{2.5}) {
    return wall * normalize(make_float3(0, -q.z, q.y));
  } else {
    return make_float3(0);
  }
});
#+END_SRC

At this point we are ready to generate masks for operator application and to
initialize all cells with their equilibrium.

#+BEGIN_SRC cpp :tangle tangle/taylor-couette.cu
auto bulk_mask = materials.mask_of_material(1);
auto bulk_list = materials.list_of_material(1);
auto wall_mask = materials.mask_of_material(2);
auto wall_list = materials.list_of_material(2);

cuda::synchronize(current);
#+END_SRC

Due to the large quantity of inactive cells in this example we call the collision
operators on lists of cells instead of masking a full sweep of the lattice.

#+NAME: taylor-couette-simulation-step
#+BEGIN_SRC cpp :eval no
const float tau = 0.55;

lattice.apply<BgkCollideO>(bulk_list, tau);
lattice.apply<BounceBackO>(wall_list);
lattice.apply<BouzidiO>(bouzidi.getCount(), bouzidi.getConfig());

lattice.stream();
#+END_SRC

Finally the volumetric example renderer is used to control the simulation
loop and to provide velocity, curl norm and shear layer visualizations.

#+BEGIN_SRC cpp :tangle tangle/taylor-couette.cu
VolumetricExample renderer(cuboid);
renderer.add<VelocityNormS>(lattice, bulk_mask, inner_cylinder);
renderer.add<ShearLayerVisibilityS>(lattice, bulk_mask, inner_cylinder, make_float3(1,0,0));
renderer.run([&](std::size_t iStep) {
  <<taylor-couette-simulation-step>>
});
}
#+END_SRC

After compiling the tangled program and playing around with the rendering
settings for the shear layer sampler, we end up with something similar to
this:

#+BEGIN_EXPORT html
<video style="width:100%" src="https://literatelb.org/media/taylor-couette.webm" playsinline muted controls/>
#+END_EXPORT

** Nozzle
This is the example that was used to provide the teaser video at the start of this
document. It simulates the turbulent flow that develops when a channel flow
is forced through a small nozzle.

#+BEGIN_SRC cpp :tangle tangle/nozzle.cu
<<example-headers>>

#include "util/volumetric_example.h"
#include "sampler/velocity_norm.h"
#include "sampler/curl_norm.h"
#include "sampler/q_criterion.h"

using T = float;
using DESCRIPTOR = descriptor::D3Q19;

int main() {
if (cuda::device::count() == 0) {
  std::cerr << "No CUDA devices on this system" << std::endl;
  return -1;
}
auto current = cuda::device::current::get();
#+END_SRC

After including the relevant headers we construct the D3Q19 lattice.

#+BEGIN_SRC cpp :tangle tangle/nozzle.cu
const descriptor::Cuboid<DESCRIPTOR> cuboid(500, 80, 80);
Lattice<DESCRIPTOR,T> lattice(cuboid);
#+END_SRC

Before constructing the nozzle geometry we set up a basic square pipe
with separate walls, in- and outlets.

#+BEGIN_SRC cpp :tangle tangle/nozzle.cu
CellMaterials<DESCRIPTOR> materials(cuboid, [&cuboid](uint3 p) -> int {
  if (p.y == 0 || p.y == cuboid.nY-1 || p.z == 0 || p.z == cuboid.nZ-1) {
    return 2; // boundary cell
  } else if (p.x == 0) {
    return 3; // inflow cell
  } else if (p.x == cuboid.nX-1) {
    return 4; // outflow cell
  } else {
    return 1; // bulk
  }
});
#+END_SRC

The smoothly curved nozzle is modelled using a signed distance function from
which we generate a configuraton of the interpolated bounce back condition.

#+BEGIN_SRC cpp :tangle tangle/nozzle.cu
auto obstacle = [cuboid] __host__ __device__ (float3 p) -> float {
                  float3 q = p - make_float3(cuboid.nX/24.2f, cuboid.nY/2, cuboid.nZ/2);
                  return sdf::ssub(sdf::sphere(make_float2(q.y,q.z), cuboid.nY/T{9}),
                                   sdf::box(q, make_float3(cuboid.nX/128,cuboid.nY/2,cuboid.nZ/2)),
                                   5);
                };
materials.sdf(obstacle, 0);
SignedDistanceBoundary bouzidi(lattice, materials, obstacle, 1, 0);
#+END_SRC

At this point we are ready to generate masks for operator application and to
initialize all cells with their equilibrium.

#+BEGIN_SRC cpp :tangle tangle/nozzle.cu
auto bulk_mask     = materials.mask_of_material(1);
auto boundary_mask = materials.mask_of_material(2);
auto inflow_mask   = materials.mask_of_material(3);
auto outflow_mask  = materials.mask_of_material(4);

cuda::synchronize(current);
#+END_SRC

In order to model the turbulence we employ Smagorinsky BGK collisions in the bulk.
The channel walls are modelled using bounce back and the SDF-described nozzle is
represented with interpolated bounce back.

#+NAME: nozzle-simulation-step
#+BEGIN_SRC cpp :eval no
const float tau = 0.501;
const float smagorinsky = 0.1;
const float inflow = 0.0075;

lattice.apply(Operator(SmagorinskyBgkCollideO(), bulk_mask, tau, smagorinsky),
              Operator(BounceBackO(), boundary_mask),
              Operator(EquilibriumVelocityWallO(), inflow_mask, std::min(iStep*1e-4, 1.0)*inflow, WallNormal<1,0,0>()),
              Operator(EquilibriumDensityWallO(), outflow_mask, 1, WallNormal<-1,0,0>()));
lattice.apply<BouzidiO>(bouzidi.getCount(), bouzidi.getConfig());

lattice.stream();
#+END_SRC

Finally the volumetric renderer is again used to control the
simulation loop and to provide various visualizations.

#+BEGIN_SRC cpp :tangle tangle/nozzle.cu
VolumetricExample renderer(cuboid);
renderer.add<CurlNormS>(lattice, bulk_mask, obstacle);
renderer.add<QCriterionS>(lattice, bulk_mask, obstacle);
renderer.add<VelocityNormS>(lattice, bulk_mask, obstacle);
renderer.run([&](std::size_t iStep) {
  <<nozzle-simulation-step>>
});
}
#+END_SRC

For example, this is how the velocity magnitude visualization evolves:

#+BEGIN_EXPORT html
<video style="width:100%" src="https://literatelb.org/media/nozzle.webm" playsinline muted controls/>
#+END_EXPORT

* Benchmark
** Performance Measurement
#+BEGIN_SRC cpp :tangle tangle/util/timer.h
#pragma once
#include <chrono>

namespace timer {
#+END_SRC

The notion of performance is directly tied to measuring timespans which is why
we start out by defining some helpers to store the current time and compute
how many seconds have passed between now and such a stored value.

#+BEGIN_SRC cpp :tangle tangle/util/timer.h
std::chrono::time_point<std::chrono::steady_clock> now() {
  return std::chrono::steady_clock::now();
}

double secondsSince(
  std::chrono::time_point<std::chrono::steady_clock>& pit) {
  return std::chrono::duration_cast<std::chrono::duration<double>>(now() - pit).count();
}
#+END_SRC

The total performance of LBM codes is commonly measured using how many
million lattice cells are updated per second, denoted as MLUPs for short.

#+BEGIN_SRC cpp :tangle tangle/util/timer.h
double mlups(std::size_t nCells, std::size_t nSteps, std::chrono::time_point<std::chrono::steady_clock>& start) {
  return nCells * nSteps / (secondsSince(start) * 1e6);
}
#+END_SRC

#+BEGIN_SRC cpp :tangle tangle/util/timer.h
}
#+END_SRC

** Lid-driven Cavity
#+BEGIN_SRC cpp :tangle tangle/benchmark-ldc.cu
#include <LLBM/base.h>

#include <LLBM/kernel/collide.h>
#include <LLBM/kernel/bounce_back.h>
#include <LLBM/kernel/bounce_back_moving_wall.h>

#include "util/timer.h"

#include <iostream>
#+END_SRC

In order to benchmark the performance limits of our LBM code this example implements
a lid driven cavity without any visual output.

#+BEGIN_SRC cpp :tangle tangle/benchmark-ldc.cu
using T = float;
using DESCRIPTOR = descriptor::D3Q19;
#+END_SRC

As 3D simulations are generally what is of relevance for practical applications, we are
using a =D3Q19= lattice of single precision values.

#+NAME: benchmark-ldc-setup-lattice
#+BEGIN_SRC cpp
Lattice<DESCRIPTOR,T> lattice(cuboid);

CellMaterials<DESCRIPTOR> materials(cuboid, [&cuboid](uint3 p) -> int {
  if (p.x == 0 || p.x == cuboid.nX-1 || p.y == 0 || p.y == cuboid.nY-1 || p.z == 0) {
    return 2; // boundary cell
  } else if (p.z == cuboid.nZ-1) {
    return 3; // lid cell
  } else {
    return 1; // bulk
  }
});

auto bulk_mask = materials.mask_of_material(1);
auto box_mask  = materials.mask_of_material(2);
auto lid_mask  = materials.mask_of_material(3);

cuda::synchronize(current);
#+END_SRC

The simulation step consists of BGK collisions in the bulk and bounce back boundaries at the sides.

#+NAME: benchmark-ldc-simulation-step
#+BEGIN_SRC cpp
lattice.apply(Operator(BgkCollideO(), bulk_mask, 0.56),
              Operator(BounceBackO(), box_mask),
              Operator(BounceBackMovingWallO(), lid_mask, 0.05f, 0.f, 0.f));
lattice.stream();
#+END_SRC

The =simulate= function accepts a the cuboid configuration together with a step count
and the floating point type to be used for lattice data and computations.

#+BEGIN_SRC cpp :tangle tangle/benchmark-ldc.cu
void simulate(descriptor::Cuboid<DESCRIPTOR> cuboid, std::size_t nStep) {
  auto current = cuda::device::current::get();

  <<benchmark-ldc-setup-lattice>>

  for (std::size_t iStep=0; iStep < 100; ++iStep) {
    <<benchmark-ldc-simulation-step>>
  }

  cuda::synchronize(current);

  auto start = timer::now();

  for (std::size_t iStep=0; iStep < nStep; ++iStep) {
    <<benchmark-ldc-simulation-step>>
  }

  cuda::synchronize(current);

  auto mlups = timer::mlups(cuboid.volume, nStep, start);

  std::cout << sizeof(T) << ", " << cuboid.nX << ", " << nStep << ", " << mlups << std::endl;
}
#+END_SRC

In order to easily perform many benchmarks for different configurations we implement
some very basic CLI parameter handling in the =main= function.

#+BEGIN_SRC cpp :tangle tangle/benchmark-ldc.cu
int main(int argc, char* argv[]) {
  if (cuda::device::count() == 0) {
    std::cerr << "No CUDA devices on this system" << std::endl;
    return -1;
  }
  if (argc != 3) {
    std::cerr << "Invalid parameter count" << std::endl;
    return -1;
  }

  const std::size_t n     = atoi(argv[1]);
  const std::size_t steps = atoi(argv[2]);

  simulate({ n, n, n}, steps);

  return 0;
}
#+END_SRC

So once this is tangled and compiled we are ready to perform some benchmarks:

#+BEGIN_SRC bash :eval query
nvidia-smi --query-gpu=name --format=csv,noheader
#+END_SRC

#+RESULTS:
: GeForce RTX 3070

#+NAME: benchmark-ldc
#+BEGIN_SRC bash :dir build :eval query :var min=64 :var max=256 :var step=16 :var nSteps=1000 :async t
for n in $(seq $min $step $max); do
    ./benchmark-ldc $n $nSteps
done
#+END_SRC

#+RESULTS: benchmark-ldc
| 4 |  64 | 1000 | 2416.56 |
| 4 |  80 | 1000 | 2471.92 |
| 4 |  96 | 1000 | 2534.33 |
| 4 | 112 | 1000 | 2512.18 |
| 4 | 128 | 1000 | 2569.58 |
| 4 | 144 | 1000 | 2541.29 |
| 4 | 160 | 1000 | 2599.92 |
| 4 | 176 | 1000 | 2499.82 |
| 4 | 192 | 1000 | 2513.63 |
| 4 | 208 | 1000 | 2492.54 |
| 4 | 224 | 1000 | 2533.04 |
| 4 | 240 | 1000 | 2561.12 |
| 4 | 256 | 1000 | 2511.97 |

* References
#+BIBLIOGRAPHY: sources acm option:-dl option:-nobibsource option:-u
* Open tasks
:properties:
:unnumbered: notoc
:end:
** TODO Add more detailed explanations
** TODO Expand example documentation
** TODO Add literature citations for method sections
** TODO Add physical dimensionalization
** TODO Improve camera controller
** TODO Re-add streamline visualization example