~esys-p-dev/esys-particle/trunk

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
/////////////////////////////////////////////////////////////
//                                                         //
// Copyright (c) 2003-2014 by The University of Queensland //
// Centre for Geoscience Computing                         //
// http://earth.uq.edu.au/centre-geoscience-computing      //
//                                                         //
// Primary Business: Brisbane, Queensland, Australia       //
// Licensed under the Open Software License version 3.0    //
// http://www.opensource.org/licenses/osl-3.0.php          //
//                                                         //
/////////////////////////////////////////////////////////////

#include "Parallel/LatticeMaster.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

//--- IO includes --
#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdexcept>

using std::ifstream;
using std::ofstream;
using std::fstream;
using std::ios;

// -- STL includes --
#include <map>
#include <algorithm>

using std::map;

// -- project includes --
#include "Model/TempPartStore.h"
#include "Parallel/mpi_tag_defs.h"
#include "Parallel/mpicmdbuf.h"
#include "Parallel/mpisgvbuf.h"
#include "Parallel/sublattice_cmd.h"
#include "Parallel/mpibarrier.h"
#include "Parallel/BroadCast_cmd.h"
#include "Parallel/BMesh2D_cmd.h"
#include "Model/Damping.h"
#include "Model/LocalDamping.h"
#include "Model/ElasticInteractionGroup.h"
#include "Model/Wall.h"
#include "Model/BWallInteractionGroup.h"
#include "Model/ViscWallIG.h"
#include "Model/SoftBWallInteractionGroup.h"
#include "Model/BodyForceGroup.h"
#include "Foundation/Timer.h"
#include "Foundation/PathSearcher.h"
#include "Foundation/StringUtil.h"
#include "Foundation/Functional.h"
#include "Fields/ParticleFieldMaster.h"
#include "Fields/ScalarParticleDistributionMaster.h"
#include "Fields/InteractionFieldMaster.h"
#include "Fields/VectorInteractionFieldMaster.h"
#include "Fields/VectorTriangleFieldMaster.h"
#include "Fields/ScalarTriangleFieldMaster.h"
#include "Fields/WallFieldMaster.h"
#include "Fields/TriggeredVectorParticleFieldMaster.h"
#include "Parallel/CheckPointInfo.h"
#include "Parallel/CheckPointLoader.h"
#include "Parallel/CheckPointController.h"
#include "Parallel/GeometryReader.h"
#include "Foundation/BoundingBox.h"
#include "Parallel/MeshReader.h"
#include "Parallel/Mesh2DReader.h"
#include "Model/MeshData2D.h"
#include "Parallel/MpiInfo.h"

#include "Parallel/MpiWrap.h"

#include <stdexcept>
#include <boost/shared_ptr.hpp>
#include <boost/filesystem/path.hpp>
#include <cstdlib>

using namespace esys::lsm;

//std::string CLatticeMaster::s_workerExeName="ESySParticleBEWorker";

CLatticeMaster::CLatticeMaster()
  : m_timingFileName(),
    m_pTimers(new MpiWTimers()),
    m_pCheckPointController(new CheckPointController()),
    m_pSnapShotController(new CheckPointController()),
    m_processDims(3, 0),
    m_save_fields(),
    m_bbx_has_been_set(false),
    m_geometry_is_initialized(false),
    m_global_rank(0),
    m_global_size(0),
    m_max_ts(0),
    m_center_id(0),
    m_total_time(0),
    m_t(0),
    m_dt(0),
    m_isInitialized(false),
    m_particle_type(),
    m_preRunnableVector(),
    m_postRunnableVector(),
    m_tml_global_comm(MPI_COMM_NULL),
    m_global_comm(MPI_COMM_NULL),
    m_dbl_NaN(std::numeric_limits<double>::quiet_NaN()),
    m_init_min_pt(m_dbl_NaN,m_dbl_NaN,m_dbl_NaN),
    m_init_max_pt(m_dbl_NaN,m_dbl_NaN,m_dbl_NaN),
    m_particle_dimensions(3)
{
  m_first_time=true;
}

CLatticeMaster::~CLatticeMaster()
{
  console.Debug() << "CLatticeMaster::~CLatticeMaster: enter\n";
  delete m_pTimers;
  delete m_pCheckPointController;
  delete m_pSnapShotController;
  for (vector<AFieldMaster*>::iterator it = m_save_fields.begin(); it != m_save_fields.end(); it++)
  {
    delete (*it);
  }
  m_save_fields.clear();

  // cleanup MPI groups and communicators
  // MPI_Group_free(&m_mpi_global_group);
  MPI_Group_free(&m_mpi_local_group);

  //MPI_Comm_free(&m_local_comm);

  console.Debug() << "CLatticeMaster::~CLatticeMaster: exit\n";
}

void CLatticeMaster::init()
{
  MPI_Comm_size(MPI_COMM_WORLD, &m_global_size);
  MPI_Comm_rank(MPI_COMM_WORLD, &m_global_rank);

  console.Debug() << "Master has rank " << m_global_rank << "\n" ;
  console.Debug() << "Global size is  " << m_global_size << "\n" ;
}

void CLatticeMaster::setupWorkers(int ns)
{
  // setup communicators and check size
  m_global_comm=MPI_COMM_WORLD;
  MPI_Comm_size(m_global_comm, &m_global_size);
  m_tml_global_comm.setComm(m_global_comm);

  // -- local communicator = global comm - proc(0)
  // get global MPI_Group
  MPI_Group mpi_global_group; 
  MPI_Comm_group(MPI_COMM_WORLD,&mpi_global_group);
  // subtract id 0 from global group
  int id0=0;
  MPI_Group_excl(mpi_global_group,1,&id0,&m_mpi_local_group);
  //  create communicator
  MPI_Comm_create(MPI_COMM_WORLD,m_mpi_local_group,&m_local_comm);

  // free global group
  MPI_Group_free(&mpi_global_group);

  m_tml_global_comm.barrier();
  	
  if(m_global_size!=ns+1){
    cerr << "wrong number of processes !! aborting" << endl << flush;
    exit(255);
    // should send abort command to workers
  } 
  initializeConsole("console.out",0); // 1st barrier -> sync time
}

int CLatticeMaster::getNumWorkerProcesses() const
{
  return m_global_size - 1;
}

void CLatticeMaster::setNumSteps(int s)
{
  m_max_ts=s;
  m_pCheckPointController->setNumTimeSteps(s);
  m_pSnapShotController->setNumTimeSteps(s);
}

void CLatticeMaster::saveTimingDataToFile(const std::string &fileNamePrefix)
{
  std::stringstream sStream;
  sStream << fileNamePrefix << m_global_rank << ".csv";
  setTimingFileName(sStream.str());

  CMPILCmdBuffer cmdBuffer(m_global_comm, MpiInfo(m_global_comm).rank());
  CMPIBarrier barrier(m_global_comm);
  cmdBuffer.broadcast(CMD_PERFORMTIMING);

  CVarMPIBuffer buffer(m_global_comm);
  // send timing filename prefix
  buffer.append(fileNamePrefix.c_str());
  buffer.broadcast(0);
  buffer.clear();
  m_tml_global_comm.barrier("performTiming");
}

void CLatticeMaster::setTimingFileName(const std::string &fileName)
{
  m_timingFileName = fileName;
}

const std::string &CLatticeMaster::getTimingFileName() const
{
  return m_timingFileName;
}

void CLatticeMaster::do2dCalculations(bool do2d)
{
  // Set the 2-D or 3-D dimension information for checkpoint files.
  m_pCheckPointController->set_is2d(do2d);
  m_pSnapShotController->set_is2d(do2d);

  CMPILCmdBuffer cmdBuffer(m_global_comm, MpiInfo(m_global_comm).rank());
  CMPIBarrier barrier(m_global_comm);
  cmdBuffer.broadcast(CMD_DO2DCALCULATIONS);

  CVarMPIBuffer buffer(m_global_comm);
  buffer.append(static_cast<int>(do2d));
  buffer.broadcast(0);

  m_tml_global_comm.barrier("do2dCalculations cmd");
}

/*!
  Make a lattice from particles of the given type. Does not set up neighbor tables.

  \param ptype the type of particle
  \param nrange search range
  \param alpha pair search cutoff
*/
void CLatticeMaster::makeLattice(const char* ptype, double nrange, double alpha)
{
  console.XDebug()
     << "CLatticeMaster::makeLattice( ptype=" << ptype
     << " , nrange=" << nrange << ", alpha=" << alpha << " )\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);

  m_particle_type = string(ptype);

  //send command to slave
  cmd_buffer.broadcast(CMD_MAKELATTICE);
  
  // send lattice parameters

  CLatticeParam clp(ptype, nrange, alpha, getProcessDims());
  clp.packInto(&buffer);
  buffer.broadcast(0);
  buffer.clear();

  m_tml_global_comm.barrier("CLatticeMaster::makeLattice");
  //m_tml_global_comm.barrier();

  console.XDebug() << "end CLatticeMaster::makeLattice\n";
}

/*!
  make lattice and set time step size

  \param ptype the type of particle
  \param nrange search range
  \param alpha pair search cutoff
  \param dt time step
*/
void CLatticeMaster::makeLattice(const char* ptype, double nrange, double alpha, double dt)
{
  makeLattice(ptype, nrange, alpha);
  setTimeStepSize(dt);
}

/*!
  set the time step size

  \param dt time step
*/
void CLatticeMaster::setTimeStepSize(double dt)
{
  m_pCheckPointController->setTimeStepSize(dt);
  m_pSnapShotController->setTimeStepSize(dt);
  m_dt = dt;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_SETTIMESTEPSIZE);
  cmd.append(m_dt);
  cmd.broadcast();
}

void CLatticeMaster::setProcessDims(const CLatticeParam::ProcessDims &dims)
{
  m_processDims = dims;
}

const CLatticeParam::ProcessDims &CLatticeMaster::getProcessDims() const
{
  return m_processDims;
}

/*!
 * Provides the initial minimum and maximum extents of all the particles read in from a geometry file.
 * 
 * \param initMinPt Minimum extent of particles inside domain.
 * \param initMaxPt Maximum extent of particles inside domain.
 */
void CLatticeMaster::getInitMinMaxPt(Vec3 &initMinPt, Vec3 &initMaxPt)
{
  initMinPt = m_init_min_pt;
  initMaxPt = m_init_max_pt;
}

/*!
   Define model bounding box and setup neighbor tables in Workers. Non-circular version.

   \param minBBoxPt minimum point of the bounding box
   \param maxBBoxPt maximum point of the bounding box
*/
void CLatticeMaster::setSpatialDomain(const Vec3 &minBBoxPt, const Vec3 &maxBBoxPt)
{
  console.Debug() << "CLatticeMaster::setSpatialDomain: enter\n";
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);

  // check if domain has already been set
  if(m_geometry_is_initialized){
	console.Warning() << "Spatial Domain has already been set and can not be changed - this call does nothing.\n"; 
  } else { 	
	// set geometry info according to parameters 
	// no need to set circular bc - defaults to (0,0,0) anyway  
	m_geo_info.setBBox(minBBoxPt,maxBBoxPt);
	m_bbx_has_been_set=true;
	// none of the boundaries circular -> simple initLattice
	cmd_buffer.broadcast(CMD_INITLATTICE);
	esys::lsm::Vec3Vector corners;
	corners.push_back(minBBoxPt);
	corners.push_back(maxBBoxPt);
	// send data to workers
	m_tml_global_comm.broadcast_cont_packed(corners);
	getSlaveSpatialDomains();
	m_tml_global_comm.barrier(std::string("cmd=") + StringUtil::toString(CMD_INITLATTICE));
	m_geometry_is_initialized=true;
  }
  console.Debug() << "CLatticeMaster::setSpatialDomain: exit\n";
}

/*!
   Define model bounding box and setup neighbor tables in Workers. Circular boundary version.

   \param minBBoxPt minimum point of the bounding box
   \param maxBBoxPt maximum point of the bounding box
   \param circDimVector a vector of ints containing the circular boundary condition flags for all dimensions
*/
void CLatticeMaster::setSpatialDomain(
  const Vec3 &minBBoxPt,
  const Vec3 &maxBBoxPt,
  const esys::lsm::IntVector &circDimVector
)
{
  console.Debug() << "CLatticeMaster::setSpatialDomain circular: enter\n";
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  esys::lsm::BoolVector periodicDimensions;

  // check if domain has already been set
  if(m_geometry_is_initialized){
	console.Warning() << "Spatial Domain has already been set and can not be changed - this call does nothing.\n"; 
  } else {
	// check if we actually need the circular part or if the periodic dimensions are (false,false,false)
	if((circDimVector[0]!=0) || (circDimVector[1]!=0) || (circDimVector[2]!=0)) { // we have at least one periodic dimension
		// set geometry info according to parameters 
		m_geo_info.setBBox(minBBoxPt,maxBBoxPt);
		// need to set circular bc 
		for (int i = 0; i <= 2; i++) periodicDimensions.push_back(bool(circDimVector[i]));
		m_geo_info.setPeriodicDimensions(periodicDimensions);
		m_bbx_has_been_set=true;
			
		// at least one boundary circular -> initLatticeCirc
		console.XDebug()<< "Circular Lattice Init\n";
		cmd_buffer.broadcast(CMD_INITLATTICECIRC);

		esys::lsm::Vec3Vector corners;
		corners.push_back(minBBoxPt);	
		corners.push_back(maxBBoxPt);

		console.XDebug()<< "Broadcasting bounding-box corners\n";
		m_tml_global_comm.broadcast_cont_packed(corners);

		// send circ. markers
		m_tml_global_comm.broadcast_cont(circDimVector);

		getSlaveSpatialDomains();
		m_tml_global_comm.barrier("CMD_INITLATTICECIRC");
		console.Debug() << "CLatticeMaster::setSpatialDomain circular: exit\n";
		m_geometry_is_initialized=true;
		m_bbx_has_been_set=true;
	} else { // all dimensions non-periodic -> call non-circular version of setSpatialDomain
		setSpatialDomain(minBBoxPt,maxBBoxPt);
	}
   }
}



void CLatticeMaster::getSlaveSpatialDomains()
{
  console.XDebug()
    <<"CLatticeMaster::getSlaveSpatialDomains: enter\n";

  // get slave dimensions and coordinates 
  multimap<int,int> slavedims;
  multimap<int,int> slavecoords;
  console.XDebug()
    <<"CLatticeMaster::getSlaveSpatialDomains: gathering dims\n";

  m_tml_global_comm.gather(slavedims);

  console.XDebug()
    <<"CLatticeMaster::getSlaveSpatialDomains: gathering coords\n";
  m_tml_global_comm.gather(slavecoords);

  console.XDebug()
    <<"CLatticeMaster::getSlaveSpatialDomains: received dims & coords\n";

  // extract slave dimensions from received data 
  int dim_x,dim_y,dim_z; // dimensions in x,y,z direction
  multimap<int,int>::iterator iter=slavedims.find(1);
  dim_x=iter->second;
  iter++;
  dim_y=iter->second;
  iter++;
  dim_z=iter->second;
  // setup coord->rank mapping for slaves
  int nslaves=dim_x*dim_y*dim_z; // number of slaves
  for(int i=0;i<nslaves;i++){
    // extract slave coordinates from received data
    //int cx,cy,cz; // x-,y-,z- coord.
    
    multimap<int,int>::iterator coord_iter=slavecoords.find(i+1); // slaves are 1..n
    //cx=coord_iter->second;
    coord_iter++;
    //cy=coord_iter->second;
    coord_iter++;
    //cz=coord_iter->second;
  }
  console.XDebug()
    <<"CLatticeMaster::getSlaveSpatialDomains: exit\n";

}

/*!
  read geometry file
  calls appropriate reader function depending on particle type

  \param fileName the name of the geometry file
*/
void  CLatticeMaster::readGeometryFile(const string& fileName)
{
  console.Debug()<<"CLatticeMaster::readGeometryFile( " << fileName << ")\n";

  if (m_particle_type == "Basic"){
    readGeometry<CParticle>(fileName);
  } else if (m_particle_type == "Rot") {
    readGeometry<CRotParticle>(fileName);
  } else if (m_particle_type == "RotVi") {
    readGeometry<CRotParticleVi>(fileName);
  } else if (m_particle_type == "RotTherm") {
    readGeometry<CRotThermParticle>(fileName);
  } else {
    throw std::runtime_error(
      std::string("Unknown particle type: ")
      +
      m_particle_type
    );
  }
}

/*!
  Load data from a save checkpoint in order to restart the simulation. 
  Control flow:
  CLatticeMaster::loadCheckPointData() (i.e. here) 
  ->  CheckPointController::issueCheckPointLoadingCmd()
  ->  [on worker] CheckPointer::loadCheckPoint()
  ->  SubLattice::loadCheckPointData()

  \param checkPointFileName the name of the base file (*_0.txt) of the checkpoint 
*/
void CLatticeMaster::loadCheckPointData(const string &checkPointFileName)
{
  CheckPointInfo cpInfo;

  std::ifstream iStream(checkPointFileName.c_str());
  if (!iStream) {
    throw std::runtime_error(
      std::string("Could not open file ") + checkPointFileName
    );
  }

  // read geometry info from checkpoint file and initialise geometry
  cpInfo.read(iStream);
  GeometryInfo geoInfo = cpInfo.getGeometryInfo();
  
  // check if geometry info has been set previously
  if(m_bbx_has_been_set){ 
    // check if old & new geometry are identical (the "compatible" check of readGeometry is not sufficient)
    if(!m_geo_info.isIdenticalGeometry(geoInfo)){
	std::cerr << "Geometry info read from file is different from previously set geometry (bounding box, circular boundaries) - Model may not run properly!" << std::endl; 
    }
  } else {
    m_geo_info=geoInfo; // set geometry meta-info

    // set model spatial domain -> sets geometry info & initializes neighbor table in workers
    if(m_geo_info.hasAnyPeriodicDimensions()){
	setSpatialDomain(m_geo_info.getBBoxCorners()[0],m_geo_info.getBBoxCorners()[1],m_geo_info.getPeriodicDimensions());
    } else {
	setSpatialDomain(m_geo_info.getBBoxCorners()[0],m_geo_info.getBBoxCorners()[1]);
    }
    m_bbx_has_been_set=true; // flag that spatial domain has been set
  }
  
  m_t=cpInfo.getTimeStep();
  std::cout << "set time step to " << m_t << std::endl;
  
  // read data
  m_pCheckPointController->issueCheckPointLoadingCmd(checkPointFileName);
  searchNeighbors(true);
  updateInteractions();
}

/*!
  add a wall to the sublattice

  \param wname the name of the wall 
  \param ipos initial position of the wall
  \param inorm initial normal of the wall
*/
void CLatticeMaster::addWall(const string& wname, const Vec3& ipos,const Vec3& inorm)
{
  console.Debug() << "CLatticeMaster::addWall("<< wname << " , " << ipos << " , " << inorm << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDWALL);

  cmd.append(wname.c_str());
  cmd.append(ipos);
  cmd.append(inorm);
  //send command to slave
  cmd.broadcast();

  console.Debug() << "end CLatticeMaster::initWall() \n";
}



/*!
  add an elastic wall interaction to model

  \param param the interaction parameters (name of the wall, name of the interaction, spring constant)
*/
void CLatticeMaster::addWallIG(const CEWallIGP& param)
{
  console.Debug() << "CLatticeMaster::addWallIG( -elastic- " << param.getWallName() << " , " << param.getName() << " , " << param.getSpringConst() << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDEWALLIG);

  //send command to slave
  cmd.packInto(param);
  //send command to slave
  cmd.broadcast();
  
  console.Debug() << "end CLatticeMaster::addWallIG() \n";
}

/*!
  add a bonded wall interaction to model

  \param param the interaction parameters (name of the wall, name of the interaction, spring constant)
*/
void CLatticeMaster::addWallIG(const CBWallIGP& param)
{
  console.Debug() << "CLatticeMaster::addWallIG( -bonded- " 
		  << param.getWallName() << " , " 
		  << param.getName() << " , " 
		  << param.getSpringConst() << " , " 
		  << param.getTag() << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDBWALLIG);

  //send command to slave
  cmd.packInto(param);
  //send command to slave
  cmd.broadcast();
  
  console.Debug() << "end CLatticeMaster::addWallIG() \n";
}

/*!
  add a viscous wall interaction to model

  \param param the interaction parameters (name of the wall, name of the interaction, spring constant)
*/
void CLatticeMaster::addWallIG(const CVWallIGP& param)
{
  console.Debug() << "CLatticeMaster::addWallIG( -viscous- " 
		  << param.getWallName() << " , " 
		  << param.getName() << " , " 
		  << param.getSpringConst() << " , " 
		  << param.getNu() << " , "
		  << param.getTag() << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDBWALLIG);

  //send command to slave
  cmd.packInto(param);
  //send command to slave
  cmd.broadcast();
  
  console.Debug() << "end CLatticeMaster::addWallIG() \n";
}
/*!
  add a bonded wall interaction with direction-dependent spring constant to model

  \param param the interaction parameters (name of the wall, name of the interaction, spring constant)
*/
void CLatticeMaster::addWallIG(const CSoftBWallIGP& param)
{
  console.Debug() << "CLatticeMaster::addWallIG( -directional bonded- " 
		  << param.getWallName() << " , " 
		  << param.getName() << " , " 
		  << param.getNormalK() << " , " 
		  << param.getShearK() << " , " 
		  << param.getTag() << " , " 
		  << param.getScaling() << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDBBWALLIG);

  //send command to slave
  cmd.packInto(param);
  //send command to slave
  cmd.broadcast();
  
  console.Debug() << "end CLatticeMaster::addWallIG() \n";
}

/*!
  add a tagged elastic wall interaction to the model

  \param param the interaction parameters (name of the wall, name of the interaction, spring constant)
  \param tag the tag of the particles the wall is interacting with
  \param mask the mask determining which bits of the tag are significant
*/
void CLatticeMaster::addTaggedWallIG(const CEWallIGP& param,int tag,int mask)
{
  console.Debug() << "CLatticeMaster::addTaggedWallIG( -elastic- " << param.getWallName() << " , " << param.getName() << " , " << param.getSpringConst() << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDTAGGEDEWALLIG);

  //pack data into command buffer
  cmd.packInto(param);
  cmd.append(tag);
  cmd.append(mask);
  //send command to slave
  cmd.broadcast();
  
  console.Debug() << "end CLatticeMaster::addTaggedWallIG() \n";	
}

/*!
  Get position of a wall. Returns (0,0,0) for a non-existing wall.

  \param WallName the name of the wall
*/ 
Vec3 CLatticeMaster::getWallPosn(const std::string& WallName)
{
  console.Debug() << "CLatticeMaster::getWallPosn: enter\n";
  Vec3 wpos=Vec3(0.0,0.0,0.0);

  // setup command 
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_GETWALLPOS);

  // pack name into command buffer
  cmd.append(WallName.c_str());

  // broadcast command buffer
  cmd.broadcast();
  
  // collect data
  multimap<int,Vec3> posmap;
  m_tml_global_comm.gather(posmap);

  wpos=(posmap.find(1))->second;
  
  console.Debug() << "CLatticeMaster::getWallPosn: exit\n";
  return wpos;
}

/*!
  Get force acting on a wall. Returns (0,0,0) for a non-existing wall.

  \param WallName the name of the wall
*/
Vec3 CLatticeMaster::getWallForce(const std::string& WallName)
{
  console.Debug() << "CLatticeMaster::getWallForce: enter\n";
  Vec3 wforce=Vec3(0.0,0.0,0.0);

  // setup command 
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_GETWALLFORCE);

  // pack name into command buffer
  cmd.append(WallName.c_str());

  // broadcast command buffer
  cmd.broadcast();

  // collect data
  multimap<int,Vec3> forcemap;
  m_tml_global_comm.gather(forcemap);

  for(multimap<int,Vec3>::iterator iter=forcemap.begin();
      iter!=forcemap.end();
      iter++){
    wforce=wforce+iter->second;
  }

  console.Debug() << "CLatticeMaster::getWallForce: exit\n";
  return wforce;
}

/*!
  add a sphere body to the sublattice

  \param sname the name of the sphere 
  \param ipos initial position of the sphere
  \param radius radius of the sphere
*/
void CLatticeMaster::addSphereBody(const string& sname, const Vec3& ipos,const double& radius)
{
  console.Debug() << "CLatticeMaster::addSphereBody("<< sname << " , " << ipos << " , " << radius << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDSPHEREBODY);

  cmd.append(sname.c_str());
  cmd.append(ipos);
  cmd.append(radius);
  //send command to slave
  cmd.broadcast();

  console.Debug() << "end CLatticeMaster::addSphereBody() \n";
}

/*!
  add an elastic sphere body interaction to model

  \param param the interaction parameters (name of the sphere, name of the interaction, spring constant)
*/
void CLatticeMaster::addSphereBodyIG(const CESphereBodyIGP& param)
{
  console.Debug() << "CLatticeMaster::addSphereBodyIG( -elastic- " << param.getSphereBodyName() << " , " << param.getName() << " , " << param.getSpringConst() << ")\n" ;

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_ADDESPHEREBODYIG);

  //send command to slave
  cmd.packInto(param);
  //send command to slave
  cmd.broadcast();

  console.Debug() << "end CLatticeMaster::addSphereBodyIG() \n";
}

/*!
  Get position of a sphere body. Returns (0,0,0) for a non-existing sphere body.

  \param SphereName the name of the wall
*/
Vec3 CLatticeMaster::getSphereBodyPosn(const std::string& SphereName)
{
  console.Debug() << "CLatticeMaster::getSphereBodyPosn: enter\n";
  Vec3 wpos=Vec3(0.0,0.0,0.0);

  // setup command 
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_GETSPHEREBODYPOS);

  // pack name into command buffer
  cmd.append(SphereName.c_str());

  // broadcast command buffer
  cmd.broadcast();

  // collect data
  multimap<int,Vec3> posmap;
  m_tml_global_comm.gather(posmap);

  wpos=(posmap.find(1))->second;

  console.Debug() << "CLatticeMaster::getSphereBodyPosn: exit\n";
  return wpos;
}

/*!
  Get force acting on a sphere body. Returns (0,0,0) for a non-existing sphere body.

  \param SphereName the name of the sphere body
*/
Vec3 CLatticeMaster::getSphereBodyForce(const std::string& SphereName)
{
  console.Debug() << "CLatticeMaster::getSphereBodyForce: enter\n";
  Vec3 wforce=Vec3(0.0,0.0,0.0);

  // setup command 
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_GETSPHEREBODYFORCE);

  // pack name into command buffer
  cmd.append(SphereName.c_str());

  // broadcast command buffer
  cmd.broadcast();

  // collect data
  multimap<int,Vec3> forcemap;
  m_tml_global_comm.gather(forcemap);

  for(multimap<int,Vec3>::iterator iter=forcemap.begin();
      iter!=forcemap.end();
      iter++){
    wforce=wforce+iter->second;
  }

  console.Debug() << "CLatticeMaster::getSphereBodyForce: exit\n";
  return wforce;
}

/*!
  Move all particles with a given tag to a given displacement relative to their original position. 

  \param id the tag of the particles to be moved
  \param d the displacement
*/
void CLatticeMaster::moveParticleTo(int tag, const Vec3& d)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PMOVE);
  buffer.append(tag);
  buffer.append(d) ; 
  buffer.broadcast(m_global_rank);
  barrier.wait("moveParticleTo");
}

/*!
  Move all particles with a given tag by a given displacement relative
  to their current position.

  \param tag the tag of the particles to be moved
  \param d the displacement
*/
void CLatticeMaster::moveTaggedParticlesBy(int tag, const Vec3& d)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PMOVETAGGEDBY);
  buffer.append(tag);
  buffer.append(d) ; 
  buffer.broadcast(m_global_rank);
  barrier.wait("moveTaggedParticlesBy");
  // force ntable rebuild
  searchNeighbors(true);
}

void CLatticeMaster::moveSingleParticleTo(int particleId, const Vec3& posn)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_IDPARTICLEMOVE);
  buffer.append(particleId);
  buffer.append(posn) ;
  buffer.broadcast(m_global_rank);
  barrier.wait("moveSingleParticleTo");
}

/*!
  Move a node in a TriMeshIG by a given amount.

  \param tm_name the name of the TriMeshIG
  \param id the node id
  \param d the displacement
*/
void CLatticeMaster::moveSingleNodeBy(const string& name,int id,const Vec3& d)
{  
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_MOVENODE);
  buffer.append(name.c_str());
  buffer.append(id) ;
  buffer.append(d);
  buffer.broadcast(m_global_rank);
  barrier.wait("moveSingleNodeBy");
}

/*!
  Move all nodes with a given tag in a TriMeshIG by a given amount.

  \param tm_name the name of the TriMeshIG
  \param tag the tag
  \param d the displacement
*/
void CLatticeMaster::moveTaggedNodesBy(const string& name,int tag,const Vec3& d)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_MOVETAGGEDNODES);
  buffer.append(name.c_str());
  buffer.append(tag) ;
  buffer.append(d);
  buffer.broadcast(m_global_rank);
  barrier.wait("moveTaggedNodesBy");
}

/*!
  Move a whole mesh by a given amount.

  \param meshName the name of the mesh to be moved
  \param translation the vector by which the mesh is translated
*/
void CLatticeMaster::translateMeshBy(
  const string &meshName,
  const Vec3& translation
)
{
  console.Debug() << "CLatticeMaster::translateMeshBy(): enter \n";
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_TRANSLATEMESHBY);

  cmd.append(meshName.c_str());
  cmd.append(translation);
  //send command to slave
  cmd.broadcast();
  console.Debug() << "CLatticeMaster::translateMeshBy(): exit \n";
}

/*!
  Add a given tag to the particle closest to a given position. Only the bits
  set in the mask will be influenced, i.e. new_tag=(old_tag & !mask) | (tag & mask).

  \param tag the tag
  \param mask the mask
  \param pos the position
*/
void CLatticeMaster::tagParticleNearestTo(int tag,int mask,const Vec3& pos)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PTAG);
  buffer.append(tag);
  buffer.append(mask) ;
  buffer.append(pos);
  buffer.broadcast(m_global_rank);
  barrier.wait("tagParticleNearestTo");
}

/*!
  Add a given tag to the particle closest to a given position. Only the bits
  set in the mask will be influenced, i.e. new_tag=(old_tag & !mask) | (tag &
mask).

  \param tag the tag
  \param mask the mask
  \param pos the position
*/
int CLatticeMaster::findParticleNearestTo(const Vec3& pos)
{
  console.Debug() << "CLatticeMaster::findParticleNearestTo: enter\n";
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_FINDNEARESTPARTICLE);
  buffer.append(pos);
  buffer.broadcast(m_global_rank);

  typedef std::pair<double,int> DistIdPair;
  typedef multimap<int, DistIdPair> RankPairMMap;
  RankPairMMap rankPairMMap;
  m_tml_global_comm.gather(rankPairMMap);

  RankPairMMap::const_iterator it = rankPairMMap.begin();
  DistIdPair nearest = it->second;
  console.Debug()
    << "CLatticeMaster::findParticleNearestTo:"
    << " nearest=" << it->second.second
    << ", distance = " << it->second.first << "\n";

  for (
    it++;
    it != rankPairMMap.end();
    it++
  )
  {
    console.Debug()
      << "CLatticeMaster::findParticleNearestTo:"
      << " particle=" << it->second.second
      << ", distance = " << it->second.first << "\n";

    if (it->second.first < nearest.first)
    {
      console.Debug()
        << "CLatticeMaster::findParticleNearestTo:"
        << " nearest=" << it->second.second
        << ", distance = " << it->second.first << "\n";
      nearest = it->second;
    }
  }
  barrier.wait(
    (std::string("cmd=")+StringUtil::toString(CMD_FINDNEARESTPARTICLE)).c_str()
  );
  console.Debug() << "CLatticeMaster::findParticleNearestTo: exit\n";
  return nearest.second;
}

Vec3 CLatticeMaster::getParticlePosn(int particleId)
{
  console.Debug() << "CLatticeMaster::getParticlePosn: enter\n";
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_GETPARTICLEPOSN);
  buffer.append(particleId);
  buffer.broadcast(m_global_rank);

  typedef std::pair<int,Vec3> IdVec3Pair;
  typedef multimap<int, IdVec3Pair> RankPairMMap;
  RankPairMMap rankPairMMap;
  m_tml_global_comm.gather(rankPairMMap);

  IdVec3Pair idPosnPair(-1,Vec3());
  for (
    RankPairMMap::const_iterator it = rankPairMMap.begin();
    it != rankPairMMap.end();
    it++
  )
  {
    if ((it->second.first) > 0)
    {
      idPosnPair = it->second;
    }
  }
  barrier.wait(
    (std::string("cmd=") + StringUtil::toString(CMD_GETPARTICLEPOSN)).c_str()
  );
  console.Debug() << "CLatticeMaster::getParticlePosn: exit\n";
  return idPosnPair.second;
}

/*!
  Set all particles with a given tag to be non-dynamic, i.e. to have infinite mass

  \param tag the tag
*/
void CLatticeMaster::setParticleNonDynamic(int tag)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PSETND);
  buffer.append(tag);
  buffer.broadcast(m_global_rank);
  barrier.wait("setParticleNonDynamic");
}

/*!
  Set all particles with a given tag to be non-rotational, i.e. to have infinite rotational inertia

  \param tag the tag
*/
void CLatticeMaster::setParticleNonRot(int tag)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PSETNR);
  buffer.append(tag);
  buffer.broadcast(m_global_rank);
  barrier.wait("setParticleNonRot");
}

/*!
  Set all particles with a given tag to be linear non-dynamic, i.e. switch off velocity updates

  \param tag the tag
*/
void CLatticeMaster::setParticleNonTrans(int tag)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PSETNT);
  buffer.append(tag);
  buffer.broadcast(m_global_rank);
  barrier.wait("setParticleNonTrans");
}

/*! 
  set the velocity of a particle 

  \param id  the id of the particle to be moved
  \param V the velocity
*/
void CLatticeMaster::setParticleVel(int id,const Vec3& V)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PVEL);
  buffer.append(id);
  buffer.append(V) ; 
  buffer.broadcast(m_global_rank);
  barrier.wait("setParticleVel");
}

/*!
  set the velocity of all particles with a given tag
  	 
  \param tag the tag
  \param V the velocity
*/

void CLatticeMaster::setTaggedParticleVel(int tag,const Vec3& V)
{
   CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
   CVarMPIBuffer buffer(m_global_comm);
   CMPIBarrier barrier(m_global_comm);
	 
   cmd_buffer.broadcast(CMD_PTVEL);
   buffer.append(tag);
   buffer.append(V) ;
   buffer.broadcast(m_global_rank);
   barrier.wait("setTaggedParticleVel");
}

/*!
  set the density (i.e. adjust mass) of all particles with a given tag
  
  \param tag the tag
  \param mask the tag mask
  \param rho the density
*/  
void CLatticeMaster::setParticleDensity(int tag,int mask,double rho)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);
  
  cmd_buffer.broadcast(CMD_PDENS);
  buffer.append(tag);
  buffer.append(mask);
  buffer.append(rho) ; 
  buffer.broadcast(m_global_rank);
  barrier.wait("setParticleDensity");
}

/*! 
  Call the SubLattice function to set the angular velocity of a particle.
  If the SubLattice is not a RotSubLattice the called function is a NOP.

  \param id the id of the particle
  \param A the angular velocity
*/
void CLatticeMaster::setParticleAngVel(int id,const Vec3& A)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_PANGVEL);
  buffer.append(id);
  buffer.append(A) ; 
  buffer.broadcast(m_global_rank);
  barrier.wait("setParticleAngVel");
}

/*!
  move a wall by given vector

  \param name the name of the wall to be moved
  \param d the movement vector
*/
void CLatticeMaster::moveWallBy(const string& name,const Vec3& d)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_WMOVE);
  buffer.append(name.c_str());
  buffer.append(d); 
  buffer.broadcast(m_global_rank);
  barrier.wait("moveWallBy");
}

/*!
  move a sphere body by given vector

  \param name the name of the sphere body to be moved
  \param d the movement vector
*/
void CLatticeMaster::moveSphereBodyBy(const string& name,const Vec3& d)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_SPHEREBODYMOVE);
  buffer.append(name.c_str());
  buffer.append(d); 
  buffer.broadcast(m_global_rank);
  barrier.wait("moveSphereBodyBy");
}

/*!
  set a wall Normal by given vector

  \param id the nr of the wall normal to change
  \param d the normal
*/
void CLatticeMaster::setWallNormal(const string& name,const Vec3& d)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_WNORM);
  buffer.append(name.c_str());
  buffer.append(d);
  buffer.broadcast(m_global_rank);
  barrier.wait("setWallNormal");
}

/*!
  apply a given force to a wall

  \param id the nr of the wall 
  \param f the force
*/
void CLatticeMaster::applyForceToWall(const string& name,const Vec3& f)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_WFORCE);
  buffer.append(name.c_str());
  buffer.append(f); 
  buffer.broadcast(m_global_rank);
  barrier.wait("applyForceToWall");
}

/*!
  set velocity of a wall. Only affects ViscWall, i.e. wall position
  doesn't get updatet !!

  \param id the nr of the wall 
  \param v the velocity
*/
void CLatticeMaster::setVelocityOfWall(const string& name,const Vec3& v)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer buffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  cmd_buffer.broadcast(CMD_WVEL);
  buffer.append(name.c_str());
  buffer.append(v); 
  buffer.broadcast(m_global_rank);
  barrier.wait("setVelocityOfWall");
}

/*!
  perform a single time step
 */
void CLatticeMaster::oneStep()
{
  m_pTimers->start("OneStepForceAndExchange");
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  m_pTimers->start("ForceCalculation");
  cmd_buffer.broadcast(CMD_CALC); // local calculations
  barrier.wait("oneStep.1");
  m_pTimers->stop("ForceCalculation");

  m_pTimers->start("BoundaryDataExchange");
  cmd_buffer.broadcast(CMD_XCHANGE); // exchange boundary data
  barrier.wait("oneStep.2");
  m_pTimers->stop("BoundaryDataExchange");

  console.Debug() << "=== TIME STEP ===\n"; 
  //-- times --
  console.Info() << "Force calculation  " << m_pTimers->getTiming("ForceCalculation") << "\n";
  console.Info() << "Boundary exchange  " << m_pTimers->getTiming("BoundaryDataExchange") << "\n";
  m_pTimers->stop("OneStepForceAndExchange");
  console.Info() << "one step           " << m_pTimers->getTiming("OneStepForceAndExchange") << "\n";
  //---
}

/*!
  neighbor search. A check if the search is necessary is performed first

  \param force if true, force neighborsearch even if displacement is below threshold
*/
void CLatticeMaster::searchNeighbors(bool force)
{
  console.Debug() << "CLatticeMaster::searchNeighbors\n" ; 
  
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);
  
  bool need_search=true; 

  if(!force){
    need_search=checkNeighbors();
  }
  if(need_search){
    cmd_buffer.broadcast(CMD_NSEARCH);
    barrier.wait("searchNeighbors");
  }
  console.Debug() << "end CLatticeMaster::searchNeighbors\n" ; 
}

/*!
  Test if neighbor search is necessary.

*/
bool CLatticeMaster::checkNeighbors()
{
  console.Debug() << "CLatticeMaster::checkNeighbors()\n";
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);
  CMPISGBufferRoot buffer(m_global_comm,8);
  
  bool res=false;
  
  cmd_buffer.broadcast(CMD_CHECKNEIGHBORS);
  buffer.gather();
  int i=1;
  while((i<m_global_size)&&(!res)){
    int b=buffer.pop_int(i);
    res=(b==1); // replace with pop_bool -> to be implemented    
    i++;
  } 
  barrier.wait("checkNeighbors");
  console.Debug() << "end CLatticeMaster::checkNeighbors(), res= " << res << "\n";

  return res;
}

/*!
 */
void CLatticeMaster::updateInteractions()
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  console.XDebug() << "CLatticeMaster::updateInteractions()\n";
  // send the command
  cmd_buffer.broadcast(CMD_UPDATE);
 
  barrier.wait("updateInteractions");
  console.XDebug() << "end CLatticeMaster::updateInteractions()\n";
}

/*!
  add a scalar particle field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
*/
void CLatticeMaster::addScalarParticleSaveField(
  const string& filename,
  const string& fieldname,
  const string& savetype,
  int t_0,
  int t_end,
  int dt
)
{
  console.Debug()
    << "CLatticeMaster::addScalarParticleSaveField("
    << filename
    << ","
    << fieldname
    << ","
    << t_0
    << ","
    << t_end
    << ","
    << dt
    << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_SPF);

  AFieldMaster* new_fm = 
    new ScalarParticleFieldMaster(
      &m_tml_global_comm,
      fieldname,
      filename,
      savetype,
      t_0,
      t_end,
      dt
    );
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addScalarParticleSaveField");

  console.Debug() << "end CLatticeMaster::addScalarParticleSaveField()\n";
} 

/*!
  add a scalar particle field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param tag tag of the particles for which the field is saved
  \param mask the mask used in tag comparisons
*/
void CLatticeMaster::addTaggedScalarParticleSaveField(const string& filename, const string& fieldname,const string& savetype, int t_0,int t_end,int dt,int tag,int mask)
{
  console.Debug() << "CLatticeMaster::addTaggedScalarParticleSaveField(" << filename << ","<< fieldname << "," << t_0 << "," << t_end << "," << dt << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_SPF);

  AFieldMaster* new_fm=new ScalarParticleFieldMaster(&m_tml_global_comm,fieldname,filename,savetype,t_0,t_end,dt,tag,mask);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addTaggedScalarParticleSaveField");

  console.Debug() << "end CLatticeMaster::addTaggedScalarParticleSaveField()\n";
} 
 
/*!
  save the distribution/histogram of a scalar field on tagged particles

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param savetype output file format (WINDOW or GLOBAL)
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between adding samples into the distribution
  \param t_snap time between snapshot saves 
  \param tag tag of the particles for which the field is saved
  \param mask the mask used in tag comparisons
  \param x_0 minimum data size in distribution
  \param x_max maximum data size in distribution
  \param nx number of bins
*/
void CLatticeMaster::addTaggedScalarParticleDistributionSaver(const string& filename,const string& fieldname,const string& savetype,int t_0,int t_end,int dt,int t_snap,int tag,int mask,double x_0,double x_max,int nx)
{
  console.Debug() << "CLatticeMaster::addTaggedScalarParticleDistributionSaver(" << filename << ","<< fieldname << "," << t_0 << "," << t_end << "," << dt << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_SPF);

  AFieldMaster* new_fm=new ScalarParticleDistributionMaster(&m_tml_global_comm,fieldname,filename,savetype,t_0,t_end,dt,t_snap,x_0,x_max,nx,tag,mask);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addTaggedScalarParticleDistributionSaver");

  console.Debug() << "end CLatticeMaster::addTaggedScalarParticleSaveField()\n";
}

/*!
  add a vector particle field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
*/
void CLatticeMaster::addVectorParticleSaveField(const string& filename,const string& fieldname,const string& savetype,int t_0,int t_end,int dt)
{
  console.Debug() << "CLatticeMaster::addVectorParticleSaveField(" << filename << ","<< fieldname << "," << t_0 << "," << t_end << "," << dt << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_VPF);

  AFieldMaster* new_fm=new VectorParticleFieldMaster(&m_tml_global_comm,fieldname,filename,savetype,t_0,t_end,dt);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addVectorParticleSaveField");

  console.Debug() << "end CLatticeMaster::addVectorParticleSaveField()\n";
} 

/*!
  add a vector particle field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param tag tag of the particles for which the field is saved
  \param mask the mask used in tag comparisons
*/
void CLatticeMaster::addTaggedVectorParticleSaveField(const string& filename,const string& fieldname,const string& savetype,int t_0,int t_end,int dt,int tag, int mask)
{
  console.Debug() << "CLatticeMaster::addTaggedVectorParticleSaveField(" << filename << ","<< fieldname << "," << t_0 << "," << t_end << "," << dt << "," << tag << "," << mask << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_VPF);

  AFieldMaster* new_fm=new VectorParticleFieldMaster(&m_tml_global_comm,fieldname,filename,savetype,t_0,t_end,dt,tag,mask);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addTaggedVectorParticleSaveField");

  console.Debug() << "end CLatticeMaster::addTaggedVectorParticleSaveField()\n";
} 
/*!
  add a vector particle field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param tprms trigger parameters
*/
void CLatticeMaster::addVectorParticleSaveFieldWT(const string& filename,const string& fieldname,const string& savetype,int t_0,int t_end,int dt,const MaxTrigParams &tprms)
{
  console.Debug() << "CLatticeMaster::addVectorParticleSaveField(" << filename << ","<< fieldname << "," << t_0 << "," << t_end << "," << dt << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_VPF);

  AFieldMaster* new_fm=new TriggeredVectorParticleFieldMaster(&m_tml_global_comm,fieldname,filename,savetype,t_0,t_end,dt,tprms);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addVectorParticleSaveField");

  console.Debug() << "end CLatticeMaster::addVectorParticleSaveField()\n";
} 

/*!
  add a vector particle field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param tag tag of the particles for which the field is saved
  \param mask the mask used in tag comparisons
  \param tprms trigger parameters
*/
void CLatticeMaster::addTaggedVectorParticleSaveFieldWT(const string& filename,const string& fieldname,const string& savetype,int t_0,int t_end,int dt,int tag, int mask,const MaxTrigParams &tprms)
{
  console.Debug() << "CLatticeMaster::addTaggedVectorParticleSaveField(" << filename << ","<< fieldname << "," << t_0 << "," << t_end << "," << dt << "," << tag << "," << mask << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_VPF);

  AFieldMaster* new_fm=new TriggeredVectorParticleFieldMaster(&m_tml_global_comm,fieldname,filename,savetype,t_0,t_end,dt,tag,mask,tprms);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addTaggedVectorParticleSaveField");

  console.Debug() << "end CLatticeMaster::addTaggedVectorParticleSaveField()\n";
} 

/*!
  add a vector wall field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param walls names of the walls 
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
*/
void CLatticeMaster::addVectorWallField(const string& filename,
					const string& fieldname,
					vector<string> walls,
					const string& savetype,
					int t_0,
					int t_end,
					int dt)
{
  console.Debug() << "CLatticeMaster::addVectorWallField(" << filename << ","<< fieldname << "," << t_0 << "," << t_end << "," << dt << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);

  //send command to slaves
  cmd_buffer.broadcast(CMD_ADD_VWF);
  
  // create master
  VectorWallFieldMaster* new_fm=new VectorWallFieldMaster(&m_tml_global_comm,fieldname,filename,walls,savetype,t_0,t_end,dt);
  m_save_fields.push_back(new_fm);

  m_tml_global_comm.barrier();

  console.Debug() << "end CLatticeMaster::addVectorWallField()\n";
}

/*!
  Setup parameters for restart checkpoints

 \param fileNamePrefix Path prefix for checkpoint files. Multiple snapshot
  files may be generated for a single timestep snapshot.
  \param beginTime      Time to begin checkpointing. Time of first snapshot.
  \param endTime        End time for checkpointing. Time of last snapshot.
  \param timeInterval   Time interval between snapshot file generation.
  \param saveBinary     Saves the data in binary format if true, ascii if false 
*/
void CLatticeMaster::performCheckPoints(
  const string &fileNamePrefix,
  int beginTime,
  int endTime,
  int timeInterval,
  int precision
)
{
  m_pCheckPointController->setGeometryInfo(m_geo_info);
  m_pCheckPointController->setCheckPointParams(
    fileNamePrefix,
    beginTime,
    endTime,
    timeInterval,
    false,
    precision
  );
  m_pCheckPointController->setMpiComm(m_global_comm);
}

/*!
  Setup parameters for restart checkpoints written though the master process

 \param fileNamePrefix Path prefix for checkpoint files. Multiple snapshot
  files may be generated for a single timestep snapshot.
  \param beginTime      Time to begin checkpointing. Time of first snapshot.
  \param endTime        End time for checkpointing. Time of last snapshot.
  \param timeInterval   Time interval between snapshot file generation.
  \param saveBinary     Saves the data in binary format if true, ascii if false 
*/
void CLatticeMaster::performCheckPointsThroughMaster(
  const string &fileNamePrefix,
  int beginTime,
  int endTime,
  int timeInterval,
  int precision
)
{
  // check if spatial extent of the model has been set and warn if not
  if(!m_bbx_has_been_set){
	console.Warning() << "Setting up Checkpointer : Model Spatial Domain has not been set - checkpoint headers will contain invalid geometry info \n";
  }
  m_pSnapShotController->setGeometryInfo(m_geo_info);
  m_pCheckPointController->setCheckPointParams(
    fileNamePrefix,
    beginTime,
    endTime,
    timeInterval,
    true,
    precision
  );
  m_pCheckPointController->setMpiComm(m_global_comm);
}

/*!
  Initialises parameters for performing model snapshots.
  
  \param fileNamePrefix Path prefix for checkpoint files. Multiple snapshot
  files may be generated for a single timestep snapshot.
  \param beginTime      Time to begin checkpointing. Time of first snapshot.
  \param endTime        End time for checkpointing. Time of last snapshot.
  \param timeInterval   Time interval between snapshot file generation.
*/
void CLatticeMaster::initSnapShotController(
  const string &fileNamePrefix,
  int beginTime,
  int endTime,
  int timeInterval
)
{ 
  console.Debug() << "CLatticeMaster::initSnapShotController\n";
  // check if spatial extent of the model has been set and warn if not
  if(!m_bbx_has_been_set){
	console.Warning() << "Setting up Snapshot Controller : Model Spatial Domain has not been set - snapshot headers will contain invalid geometry info \n";
  }	  
  m_pSnapShotController->setGeometryInfo(m_geo_info);
  m_pSnapShotController->setCheckPointParams(
    fileNamePrefix,
    beginTime,
    endTime,
    timeInterval,
    false
  );
  m_pSnapShotController->setMpiComm(m_global_comm);
  console.Debug() << "end CLatticeMaster::initSnapShotController\n";
}

/*!
  add a scalar interaction field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param igname the name of the interaction group from which the field is taken
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param checked choose between normal and checked field (defaults to false)
*/
void CLatticeMaster::addScalarInteractionSaveField(
  const string& filename,
  const string& fieldname,
  const string& igtype,
  const string& igname,
  const string& savetype,
  int t_0,
  int t_end,
  int dt,
  bool checked
)
{
  console.Debug()
     << "CLatticeMaster::addScalarInteractionSaveField("
     << filename
     << ","
     << fieldname
     << ","
     << igname
     << ","
     << t_0
     << ","
     << t_end
     << ","
     << dt
     << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_SIF);

  AFieldMaster* new_fm = 
    new ScalarInteractionFieldMaster(
      &m_tml_global_comm,
      fieldname,
      igtype,
      igname,
      filename,
      savetype,
      t_0,
      t_end,
      dt,
      checked
    );
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addScalarInteractionSaveField");

  console.Debug() << "end CLatticeMaster::addScalarInteractionSaveField()\n";
} 

/*!
  add a scalar interaction field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param igname the name of the interaction group from which the field is taken
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param checked choose between normal and checked field (defaults to false)
*/
void CLatticeMaster::addScalarHistoryInteractionSaveField(const string& filename,const string& fieldname,
	const string& igtype,const string& igname,const string& savetype,int t_0,int t_end,int dt)
{
  console.Debug() << "CLatticeMaster::addScalarHistoryInteractionSaveField(" << filename << "," << fieldname << "," << igname << ","
	<< t_0 << "," << t_end << "," << dt << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_HIF);

  //AFieldMaster* new_fm = new ScalarHistoryInteractionFieldMaster(&m_tml_global_comm,fieldname,igtype,igname,
  //    filename,savetype,t_0,t_end,dt,checked);
  //m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addScalarHistoryInteractionSaveField");

  console.Debug() << "end CLatticeMaster::addScalarHistoryInteractionSaveField()\n";
} 

/*!
  add a vector field on the triangles of a given trimesh to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param meshname the name of the mesh from which the field is taken
  \param savetype the format in which the data is to be saved
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
*/
void CLatticeMaster::addVectorTriangleSaveField(const string& filename,
						const string& fieldname,
						const string& meshname,
						const string& savetype,
						int t_0,int t_end,int dt)
{
  console.Debug() << "CLatticeMaster::addVectorTriangleSaveField\n";
  
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_VTF);

  AFieldMaster* new_fm = new VectorTriangleFieldMaster(&m_tml_global_comm,fieldname,meshname,filename,savetype,t_0,t_end,dt);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addVectorTriangleSaveField");

  console.Debug() << "end CLatticeMaster::addVectorTriangleSaveField\n";
}

/*!
  add a scalar field on the triangles of a given trimesh to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param meshname the name of the mesh from which the field is taken
  \param savetype the format in which the data is to be saved
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
*/
void CLatticeMaster::addScalarTriangleSaveField(const string& filename,
						const string& fieldname,
						const string& meshname,
						const string& savetype,
						int t_0,int t_end,int dt)
{
  console.Debug() << "CLatticeMaster::addScalarTriangleSaveField\n";
  
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_STF);

  AFieldMaster* new_fm = new ScalarTriangleFieldMaster(&m_tml_global_comm,fieldname,meshname,filename,savetype,t_0,t_end,dt);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addScalarTriangleSaveField");

  console.Debug() << "end CLatticeMaster::addScalarTriangleSaveField\n";
}

/*!
  add a vector interaction field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param igname the name of the interaction group from which the field is taken
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param checked choose between normal and checked field (defaults to false)
*/
void CLatticeMaster::addVectorInteractionSaveField(const string& filename,const string& fieldname,const string& igtype,
						   const string& igname,const string& savetype,int t_0,int t_end,int dt,bool checked)
{
  console.Debug() << "CLatticeMaster::addVectorInteractionSaveField()\n";
  
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_VIF);

  AFieldMaster* new_fm = new VectorInteractionFieldMaster(&m_tml_global_comm,fieldname,igtype,igname,filename,savetype,t_0,t_end,dt,checked);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addVectorInteractionSaveField");

  console.Debug() << "end CLatticeMaster::addVectorInteractionSaveField()\n";
} 


/*!
  add a scalar interaction field to the list of fields to be saved

  \param filename the name of the file the field is saved into 
  \param fieldname the name of the field
  \param igname the name of the interaction group from which the field is taken
  \param savetype output file format
  \param t_0 first timestep to be saved
  \param t_end last timestep to be saved
  \param dt timesteps between saves
  \param tag the particle tag
  \param mask the mask used for tag comparisons
	\param checked choice between "full" and "checked" fields
*/
void CLatticeMaster::addTaggedScalarInteractionSaveField(const string& filename, const string& fieldname,const string& igtype,const string& igname,const string& savetype, int t_0,int t_end,int dt,int tag,int mask, bool checked)
{
  console.Debug() << "CLatticeMaster::addTaggedScalarInteractionSaveField(" << filename << ","<< fieldname << "," << igname << "," << t_0 << "," << t_end << "," << dt << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  //send cmd to slave
  cmd_buffer.broadcast(CMD_ADD_SIF);

  AFieldMaster* new_fm=new ScalarInteractionFieldMaster(&m_tml_global_comm,fieldname,igtype,igname,filename,savetype,t_0,t_end,dt,tag,mask,checked);
  m_save_fields.push_back(new_fm);

  barrier.wait("CLatticeMaster::addTaggedScalarInteractionSaveField");

  console.Debug() << "end CLatticeMaster::addTaggedScalarInteractionSaveField()\n";
} 

/*!
  Initialisation to run the simulation
*/
void CLatticeMaster::runInit()
{
  if (!m_isInitialized)
  {
    m_pTimers->start("TotalRunTime");

    console.Debug() << "timer resolution : " << MPI_Wtick() << "\n" ;
    m_isInitialized = true ;
    //m_t=0 ; 
    m_pTimers->clear();
  }
}

/*!
  Finalize after running the simulation
*/
void CLatticeMaster::runEnd()
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  console.Debug() << "total time: " << m_pTimers->getTiming("TotalRunTime") << " seconds for " << m_max_ts-1 << " time steps\n" ;
  cmd_buffer.broadcast(CMD_FINISH);
  barrier.wait("runEnd");
  barrier.wait("runEnd2");
}

void CLatticeMaster::saveTimingData()
{
  if (!getTimingFileName().empty()) {

    m_pTimers->start("WorkerTimingDataSave");
    CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
    CMPIBarrier barrier(m_global_comm);
    cmd_buffer.broadcast(CMD_SAVETIMINGDATA);
    barrier.wait("saveTimingData");
    m_pTimers->stop("WorkerTimingDataSave");

    m_pTimers->appendData(getTimingFileName());    
  }
}

void CLatticeMaster::addPreTimeStepRunnable(Runnable &runnable)
{
  m_preRunnableVector.push_back(&runnable);
}

void CLatticeMaster::addPostTimeStepRunnable(Runnable &runnable)
{
  m_postRunnableVector.push_back(&runnable);
}

void CLatticeMaster::runRunnables(RunnableVector::iterator begin, RunnableVector::iterator end)
{
  for (RunnableVector::iterator it = begin; it != end; it++)
  {
    (*it)->run();
  }
}

void CLatticeMaster::runPreRunnables()
{
  runRunnables(
    m_preRunnableVector.begin(),
    m_preRunnableVector.end()
  );
}

void CLatticeMaster::runPostRunnables()
{
  runRunnables(
    m_postRunnableVector.begin(),
    m_postRunnableVector.end()
  );
}

/**
 *  Perform a single time step of the simulation.
 */
void CLatticeMaster::runOneStep()
{
  runInit();

  m_pTimers->start("RunOneStep");

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CMPIBarrier barrier(m_global_comm);

  // Field saving of initial state (if required)
  if(m_first_time){
    m_pTimers->start("FieldMasterCollect");
    m_pTimers->pause("FieldMasterCollect");
    m_pTimers->start("FieldMasterWrite");
    m_pTimers->pause("FieldMasterWrite");
    for(vector<AFieldMaster*>::iterator iter=m_save_fields.begin();
        iter!=m_save_fields.end();
        iter++){
      if((*iter)->needSave(0)){
        m_pTimers->resume("FieldMasterCollect");    
        cmd_buffer.broadcast(CMD_SEND_FIELDS);
        (*iter)->collect();
        barrier.wait("runOneStep.collect");
        m_pTimers->pause("FieldMasterCollect");      
        m_pTimers->resume("FieldMasterWrite");
        (*iter)->write();
        m_pTimers->pause("FieldMasterWrite");
      }
    }
    m_pTimers->stop("FieldMasterCollect");  
    m_pTimers->stop("FieldMasterWrite");
  }
  // Save a check-point of the initial state (if required)
  m_pTimers->start("NeighbourSearch");
  if(m_first_time){  
    searchNeighbors(true);
    m_pCheckPointController->performCheckPoint(0);
    m_pSnapShotController->performSnapShot(0);
    m_first_time=false;
  }
  m_pTimers->stop("NeighbourSearch");

  m_t++ ; 
  console.Info() << "Begining time step: " << m_t << "\n" ;
  m_pTimers->start("LoadingMechanism");
  runPreRunnables();
  m_pTimers->stop("LoadingMechanism");

  m_pTimers->start("NeighbourSearch");
  searchNeighbors(false);
  m_pTimers->stop("NeighbourSearch");

  //  barrier.wait("runOneStep.2");
  m_pTimers->start("UpdateInteractions");
  updateInteractions();
  m_pTimers->stop("UpdateInteractions");

  m_pTimers->start("CalcForcesAndExchange");
  oneStep();
  m_pTimers->stop("CalcForcesAndExchange");

  m_pTimers->start("SavingData");
  // saving fields
  /*
  bool app;
  if(m_t==1){ 
    app=false; // if 1st time step -> new file
  } else {
    app=true; // else append
  }
  */

  // new field saving
  m_pTimers->start("FieldMasterCollect");
  m_pTimers->pause("FieldMasterCollect");
  m_pTimers->start("FieldMasterWrite");
  m_pTimers->pause("FieldMasterWrite");
  for(vector<AFieldMaster*>::iterator iter=m_save_fields.begin();
      iter!=m_save_fields.end();
      iter++){
    if((*iter)->needSave(m_t)){
      m_pTimers->resume("FieldMasterCollect");    
      cmd_buffer.broadcast(CMD_SEND_FIELDS);
      (*iter)->collect();
      barrier.wait("runOneStep.collect");
      m_pTimers->pause("FieldMasterCollect");      
      m_pTimers->resume("FieldMasterWrite");
      (*iter)->write();
      m_pTimers->pause("FieldMasterWrite");
    }
  }
  m_pTimers->stop("FieldMasterCollect");  
  m_pTimers->stop("FieldMasterWrite");

  // Save a check-point (if required)
  m_pTimers->start("CheckPoint");
  // force ntable rebuild before checkpoint
  if(m_pCheckPointController->isCheckPoint(m_t)){
    searchNeighbors(true);
  }
  m_pCheckPointController->performCheckPoint(m_t);
  m_pTimers->stop("CheckPoint");

  // write a snapshot (if required)
  m_pTimers->start("SnapShot");
  m_pSnapShotController->performSnapShot(m_t);
  m_pTimers->stop("SnapShot");

  m_pTimers->stop("SavingData");

  runPostRunnables();

  m_pTimers->stop("RunOneStep");

  m_pTimers->stop("TotalRunTime", true);

  saveTimingData();

  console.Info() << "updateInteractions : " << m_pTimers->getTiming("UpdateInteractions") << " seconds\n" ;
  console.Info() << "searchNeighbors    : " <<  m_pTimers->getTiming("NeighbourSearch") << " seconds\n" ;
  console.Info() << "one step           : " <<  m_pTimers->getTiming("CalcForcesAndExchange") << " seconds\n" ;
  console.Info() << "saving data        : " <<  m_pTimers->getTiming("SavingData") << " seconds\n" ;

  console.Info() << "End of time step: " << m_t << "\n" ;
}

/*!
  run the simulation
*/
void CLatticeMaster::run()
{
  while (m_t < m_max_ts) {
    runOneStep();
  }
  runEnd();
}
/*
CLatticeMaster::ParticleIdPairVector
CLatticeMaster::getBondGroupIdPairs(
  const std::string &groupName
)
{
  console.XDebug() << "CLatticeMaster::getBondGroupIdPairs(): enter\n";
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_GETBONDGROUPIDPAIRS);
  cmd.append(groupName.c_str());
  cmd.broadcastCommand();
  cmd.broadcastBuffer();
  typedef std::pair<double,int> DistIdPair;
  typedef multimap<int, ParticleIdPair> ParticleIdPairMMap;
  ParticleIdPairMMap idPairMMap;
  m_tml_global_comm.gather(idPairMMap);
  ParticleIdPairVector idPairVector;
  idPairVector.reserve(idPairMMap.size());
  std::transform(
    idPairMMap.begin(),
    idPairMMap.end(),
    std::back_insert_iterator<ParticleIdPairVector>(idPairVector),
    ext::select2nd<ParticleIdPairMMap::value_type>()
  );
  cmd.wait("CMD_GETBONDGROUPIDPAIRS");
  console.XDebug() << "CLatticeMaster::getBondGroupIdPairs(): exit\n";
  return idPairVector;
}
*/

/*!
  Create and add a new bonded IG

  \param name the name of the bonded IG
  \param k spring constant of the created bonds
  \param dist maximum distance between two particles to create bond
  \param break_dist (relative) breaking distance of bonds
  
*/
void CLatticeMaster::addBondedIG(const CBondedIGP &prms)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm,20);
  CMPIBarrier barrier(m_global_comm);

  console.XDebug() << "CLatticeMaster::addBondedIG()\n ";

  // send the command
  cmd_buffer.broadcast(CMD_ADDBONDEDIG);
  // send parameters
  pbuffer.append(prms.tag);
  pbuffer.append(prms.getName().c_str());
  pbuffer.append(prms.k);
  pbuffer.append(prms.rbreak);
  pbuffer.append(static_cast<int>(prms.m_scaling));

  pbuffer.broadcast(0);

  barrier.wait("addBondedIG()");
  console.XDebug() << "end CLatticeMaster::addBondedIG()" << "\n";
} 

/*!
  Create and add a new bonded IG with force limit

  \param name the name of the bonded IG
  \param k spring constant of the created bonds
  \param dist maximum distance between two particles to create bond
  \param break_dist (relative) breaking distance of bonds
  \param maxforce the maximum force
*/
void CLatticeMaster::addCappedBondedIG(int tag,const string& name,double k,double break_dist,double maxforce)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm,20);
  CMPIBarrier barrier(m_global_comm);

  console.XDebug() << "CLatticeMaster::addCappedBondedIG()\n ";

  // send the command
  cmd_buffer.broadcast(CMD_ADDCAPPEDBONDEDIG);
  // send parameters
  pbuffer.append(tag);
  pbuffer.append(name.c_str());
  pbuffer.append(k);
  pbuffer.append(break_dist);
  pbuffer.append(maxforce);
  pbuffer.broadcast(0);

  // broadcast connection data
  // m_tml_global_comm.broadcast_cont(m_temp_conn[tag]);

  barrier.wait("addCappedBondedIG()");
  console.XDebug() << "end CLatticeMaster::addCappedBondedIG()" << "\n";
} 

/*!
  Create and add a new short bonded IG

  \param name the name of the bonded IG
  \param k spring constant of the created bonds
  \param dist maximum distance between two particles to create bond
  \param break_dist (relative) breaking distance of bonds
  
*/
void CLatticeMaster::addShortBondedIG(int tag,const string& name,double k,double break_dist)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm,20);
  CMPIBarrier barrier(m_global_comm);

  console.XDebug() << "CLatticeMaster::addShortBondedIG()\n ";

  // send the command
  cmd_buffer.broadcast(CMD_ADDSHORTBONDEDIG);
  // send parameters
  pbuffer.append(tag);
  pbuffer.append(name.c_str());
  pbuffer.append(k);
  pbuffer.append(break_dist);

  pbuffer.broadcast(0);

  // broadcast connection data

  //console.XDebug() << "broadcast " << m_temp_conn[0].size() << " connection data" << "\n";
  //m_tml_global_comm.broadcast_cont(m_temp_conn[tag]);
  barrier.wait("addShortBondedIG()");
  console.XDebug() << "end CLatticeMaster::addShortBondedIG()" << "\n";
} 

void CLatticeMaster::addRotBondedIG(
  int    tag,
  const  string& name,
  double kr,
  double ks,
  double kt,
  double kb,
  double max_nForce,
  double max_shForce,
  double max_tMoment,
  double max_bMoment,
  bool   scaling,
  bool   meanR_scaling,
  double truncated
)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm, 256);  // 20 need change ?
  CMPIBarrier barrier(m_global_comm);

  console.XDebug() << "CLatticeMaster::addRotBondedIG()\n ";

  // send the command
  cmd_buffer.broadcast(CMD_ADDROTBONDEDIG);
  // send parameters
  pbuffer.append(tag);
  pbuffer.append(name.c_str());
  pbuffer.append(kr);
  pbuffer.append(ks);
  pbuffer.append(kt);
  pbuffer.append(kb);
  pbuffer.append(max_nForce);
  pbuffer.append(max_shForce);
  pbuffer.append(max_tMoment);
  pbuffer.append(max_bMoment);
  pbuffer.append(static_cast<int>(scaling));
  pbuffer.append(static_cast<int>(meanR_scaling));
  pbuffer.append(truncated);

  pbuffer.broadcast(0);

  // broadcast connection data
  //m_tml_global_comm.broadcast_cont(m_temp_conn[tag]);

  barrier.wait("addRotBondedIG()");
  console.XDebug() << "end CLatticeMaster::addRotBondedIG()" << "\n";
}

void CLatticeMaster::addRotThermBondedIG(
  const CRotThermBondedIGP &prms
)
{
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm, 256);  // 20 need change ?
  CMPIBarrier barrier(m_global_comm);

  console.XDebug() << "CLatticeMaster::addRotThermBondedIG()\n ";

  // send the command
  cmd_buffer.broadcast(CMD_ADDROTTHERMBONDEDIG);
  // send parameters
  pbuffer.append(prms.tag);
  pbuffer.append(prms.getName().c_str());
  pbuffer.append(prms.kr);
  pbuffer.append(prms.ks);
  pbuffer.append(prms.kt);
  pbuffer.append(prms.kb);
  pbuffer.append(prms.max_nForce);
  pbuffer.append(prms.max_shForce);
  pbuffer.append(prms.max_tMoment);
  pbuffer.append(prms.max_bMoment);
  pbuffer.append(prms.diffusivity);

  pbuffer.broadcast(0);

  // broadcast connection data
  //m_tml_global_comm.broadcast_cont(m_temp_conn[tag]);

  barrier.wait("addRotThermBondedIG()");
  console.XDebug() << "end CLatticeMaster::addRotThermBondedIG()" << "\n";
}

int CLatticeMaster::getNumParticles()
{
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_GETNUMPARTICLES);
  cmd.broadcastCommand();
  
  // get slave dimensions and coordinates 
  typedef multimap<int,int> RankNumParticlesMMap;
  RankNumParticlesMMap numParticlesMMap;
  m_tml_global_comm.gather(numParticlesMMap);

  int numParticles = 0;
  for (
    RankNumParticlesMMap::const_iterator it = numParticlesMMap.begin();
    it != numParticlesMMap.end();
    it++
  )
  {
    numParticles += it->second;
  }
  cmd.wait("CLatticeMaster::getNumParticles");
  return numParticles;
}

class IGPCommand : public BroadcastCommand
{
public:
  IGPCommand(const MpiRankAndComm &globalRankAndComm)
    : BroadcastCommand(globalRankAndComm, CMD_ADDPIG)
  {
  }

  IGPCommand(const MpiRankAndComm &globalRankAndComm, int commandId)
    : BroadcastCommand(globalRankAndComm, commandId)
  {
  }

  void appendIGP(const AIGParam &prms)
  {
    appendTypeAndName(prms);
  }

private:
};

void CLatticeMaster::addPairIG(const CElasticIGP &prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_k);
  igpCmd.append(static_cast<int>(prms.m_scaling));
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CFrictionIGP &prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.k);
  igpCmd.append(prms.mu);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.append(static_cast<int>(prms.m_scaling));
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const FractalFrictionIGP &prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.k);
  igpCmd.append(prms.mu_0);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.append(prms.x0);
  igpCmd.append(prms.y0);
  igpCmd.append(prms.dx);
  igpCmd.append(prms.dy);
  igpCmd.append(prms.nx);
  igpCmd.append(prms.ny);
  for (int i = 0; i < (prms.nx*prms.ny); i++) {
    igpCmd.append((prms.mu.get())[i]);
  }
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CAdhesiveFrictionIGP &prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.k);
  igpCmd.append(prms.mu);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.append(prms.r_cut);
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CLinearDashpotIGP & prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_damp);
  igpCmd.append(prms.m_cutoff);
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CHertzianElasticIGP &prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_E);
  igpCmd.append(prms.m_nu);
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CHertzianViscoElasticFrictionIGP &prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_A);
  igpCmd.append(prms.m_E);
  igpCmd.append(prms.m_nu);
  igpCmd.append(prms.mu);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CHertzianViscoElasticIGP &prms)
{
  IGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_A);
  igpCmd.append(prms.m_E);
  igpCmd.append(prms.m_nu);
  igpCmd.broadcast();
}


//---
// rotational interactions
//---

class RotIGPCommand : public IGPCommand
{
public:
  RotIGPCommand(const MpiRankAndComm &globalRankAndComm) : IGPCommand(globalRankAndComm, CMD_ADDPIG)
  {
  }
  
  void appendIGP(const AIGParam &prms)
  {
    appendTypeAndName(prms);
  }

private:
};

void CLatticeMaster::addPairIG(const CRotElasticIGP &prms)
{
  RotIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_kr);
  igpCmd.append(static_cast<int>(prms.m_scaling));
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CRotFrictionIGP &prms)
{
  RotIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.k);
  igpCmd.append(prms.mu_s);
  igpCmd.append(prms.mu_d);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.append(static_cast<int>(prms.scaling));
  igpCmd.append(static_cast<int>(prms.meanR_scaling));
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CRotThermElasticIGP &prms)
{
  RotIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_kr);
  igpCmd.append(prms.diffusivity);
  igpCmd.broadcast();
}

void CLatticeMaster::addPairIG(const CRotThermFrictionIGP &prms)
{
  RotIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.k);
  igpCmd.append(prms.mu_s);
  igpCmd.append(prms.mu_d);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.diffusivity);
  igpCmd.append(prms.dt);
  igpCmd.broadcast();
}

//---
// creation of tagged pair interaction groups
//---
 

// --- RotFriction ---
class TaggedIGPCommand : public IGPCommand
{
public:
  TaggedIGPCommand(const MpiRankAndComm &globalRankAndComm) : IGPCommand(globalRankAndComm, CMD_ADDTAGPIG)
  {
  }
  
  void appendIGP(const AIGParam &prms)
  {
    appendTypeAndName(prms);
  }

private:
};

void CLatticeMaster::addTaggedPairIG(
  const CRotFrictionIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.k);
  igpCmd.append(prms.mu_s);
  igpCmd.append(prms.mu_d);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.append(static_cast<int>(prms.scaling));
  igpCmd.append(static_cast<int>(prms.meanR_scaling));
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  
  igpCmd.broadcast();
}

// --- NRotFriction ---
void CLatticeMaster::addTaggedPairIG(
  const CFrictionIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.k);
  igpCmd.append(prms.mu);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.append(static_cast<int>(prms.m_scaling));
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  igpCmd.broadcast();
}

void CLatticeMaster::addTaggedPairIG(
  const CLinearDashpotIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_damp);
  igpCmd.append(prms.m_cutoff);
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  
  igpCmd.broadcast();
}


// --- Hertzian Elastic ---
void CLatticeMaster::addTaggedPairIG(
  const CHertzianElasticIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_E);
  igpCmd.append(prms.m_nu);
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  
  igpCmd.broadcast();
}

// --- Hertzian ViscoElasticFriction ---
void CLatticeMaster::addTaggedPairIG(
  const CHertzianViscoElasticFrictionIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_A);
  igpCmd.append(prms.m_E);
  igpCmd.append(prms.m_nu);
  igpCmd.append(prms.mu);
  igpCmd.append(prms.k_s);
  igpCmd.append(prms.dt);
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  
  igpCmd.broadcast();
}

// --- Hertzian ViscoElastic ---
void CLatticeMaster::addTaggedPairIG(
  const CHertzianViscoElasticIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_A);
  igpCmd.append(prms.m_E);
  igpCmd.append(prms.m_nu);
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  
  igpCmd.broadcast();
}

// --- tagged elastic ---
void CLatticeMaster::addTaggedPairIG(
  const CElasticIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_k);
  igpCmd.append(static_cast<int>(prms.m_scaling));
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  
  igpCmd.broadcast();
}

void CLatticeMaster::addTaggedPairIG(
  const CRotElasticIGP &prms,
  int tag1,
  int mask1,
  int tag2,
  int mask2
)
{
  TaggedIGPCommand igpCmd(getGlobalRankAndComm());
  igpCmd.appendIGP(prms);
  igpCmd.append(prms.m_kr);
  igpCmd.append(static_cast<int>(prms.m_scaling));
  igpCmd.append(tag1);
  igpCmd.append(mask1);
  igpCmd.append(tag2);
  igpCmd.append(mask2);
  
  igpCmd.broadcast();
}

/*!
  Remove interaction group. Send name of the interactiongroup to workers

  \param name the name of the interaction group which is to be removed
*/
void CLatticeMaster::removeIG(const std::string& name)
{
  BroadcastCommand cmd(getGlobalRankAndComm(),CMD_REMOVEIG);

  cmd.append(name.c_str());
  cmd.broadcast();
}

//---
// creation of interaction groups between particles and meshes
//---

/*!
 Broadcast command to add a (non-bonded) trimesh IG
*/
class TriMeshIGCommand : public BroadcastCommand
{
public:
  TriMeshIGCommand(const MpiRankAndComm &globalRankAndComm)
    : BroadcastCommand(globalRankAndComm, CMD_ADDTRIMESHIG)
  {
  }
};

/*!
  add(non-bonded) trimesh IG
*/
void CLatticeMaster::addTriMeshIG(const ETriMeshIP &prms)
{
  TriMeshIGCommand cmd(getGlobalRankAndComm());

  cmd.appendTypeAndName(prms);
  cmd.append(prms.getMeshName().c_str());
  cmd.append(prms.k);
  cmd.broadcast();
}

/*!
 Broadcast command to add a (non-bonded) interaction group between particles and 
 a 2D mesh
*/
class Mesh2DIGCommand : public BroadcastCommand
{
public:
  Mesh2DIGCommand(const MpiRankAndComm &globalRankAndComm)
    : BroadcastCommand(globalRankAndComm, CMD_ADDMESH2DIG)
  {
  }
};

/*!
  add(non-bonded) interaction group between particles and 
 a 2D mesh
*/
void CLatticeMaster::addMesh2DIG(const ETriMeshIP &prms)
{
  Mesh2DIGCommand cmd(getGlobalRankAndComm());

  cmd.appendTypeAndName(prms);
  cmd.append(prms.getMeshName().c_str());
  cmd.append(prms.k);
  cmd.broadcast();
}

class BondedTriMeshIGCommand : public BroadcastCommand
{
public:
  BondedTriMeshIGCommand(const MpiRankAndComm &globalRankAndComm)
    : BroadcastCommand(globalRankAndComm, CMD_ADDBONDEDTRIMESHIG)
  {
  }

  void appendTriMeshPrms(const BTriMeshIP &triMeshPrms)
  {
    append(triMeshPrms.getName().c_str());
    append(triMeshPrms.getMeshName().c_str());
    append(triMeshPrms.k);
    append(triMeshPrms.brk);
  }

  void appendTagBuildPrms(const MeshTagBuildPrms &buildPrms)
  {
    append(buildPrms.getTypeString().c_str());
    append(buildPrms.m_tag);
    append(buildPrms.m_mask);
  }

  void appendGapBuildPrms(const MeshGapBuildPrms &buildPrms)
  {
    append(buildPrms.getTypeString().c_str());
    append(buildPrms.m_maxGap);
  }
};

/*!
  add bonded trimesh IG by particle tag

  \param triMeshPrms the interaction parameters, i.e. k , r_break....
  \param buildPrms the build parameters, i.e. the tag & mask
*/
void CLatticeMaster::addBondedTriMeshIG(const BTriMeshIP &triMeshPrms, const MeshTagBuildPrms &buildPrms)
{
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG with tag build prms\n";
  BondedTriMeshIGCommand bndTriMeshCmd(getGlobalRankAndComm());
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG appending mesh prms to command...\n";
  bndTriMeshCmd.appendTriMeshPrms(triMeshPrms);
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG appending mesh build prms to command...\n";
  bndTriMeshCmd.appendTagBuildPrms(buildPrms);
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG broadcasting...\n";
  bndTriMeshCmd.broadcast();
  console.Debug() << "end CLatticeMaster::addBondedTriMeshIG\n";
  
}

/*!
  add bonded trimesh IG by distance between particle & mesh

  \param triMeshPrms the interaction parameters, i.e. k , r_break....
  \param buildPrms the build parameters, i.e. the max. dist
*/
void CLatticeMaster::addBondedTriMeshIG(const BTriMeshIP &triMeshPrms, const MeshGapBuildPrms &buildPrms)
{
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG with gap build prms\n";
  BondedTriMeshIGCommand bndTriMeshCmd(getGlobalRankAndComm());
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG appending mesh prms to command...\n";
  bndTriMeshCmd.appendTriMeshPrms(triMeshPrms);
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG appending mesh build prms to command...\n";
  bndTriMeshCmd.appendGapBuildPrms(buildPrms);
  console.Debug() << "CLatticeMaster::addBondedTriMeshIG broadcasting...\n";
  bndTriMeshCmd.broadcast();
  console.Debug() << "end CLatticeMaster::addBondedTriMeshIG\n";
}

/*!
  add bonded interactions with 2d mesh using a gap parameter 
*/
void CLatticeMaster::addBondedMesh2DIG(const BMesh2DIP &igp, const MeshGapBuildPrms &buildPrms)
{
  console.Debug() << "CLatticeMaster::addBondedMesh2DIG with Mesh2DGapBuildPrms\n";
  BondedMesh2DIGCommand cmd(getGlobalRankAndComm());
  console.Debug() << "made cmd\n";
  cmd.appendMesh2DParam(igp);
  console.Debug() << "appended IGP\n";
  cmd.appendGapBuildPrms(buildPrms);
  console.Debug() << "appended buildParams\n";
  cmd.broadcast();
  console.Debug() << "end CLatticeMaster::addBondedMesh2DIG\n";
}

/*!
  add bonded interactions with 2d mesh using tag/mask parameters 
*/
void CLatticeMaster::addBondedMesh2DIG(const BMesh2DIP &igp, const MeshTagBuildPrms &buildPrms)
{
  console.Debug() << "CLatticeMaster::addBondedMesh2DIG with Mesh2DGapBuildPrms\n";
  BondedMesh2DIGCommand cmd(getGlobalRankAndComm());
  console.Debug() << "made cmd\n";
  cmd.appendMesh2DParam(igp);
  console.Debug() << "appended IGP\n";
  cmd.appendTagBuildPrms(buildPrms);
  console.Debug() << "appended buildParams\n";
  cmd.broadcast();
  console.Debug() << "end CLatticeMaster::addBondedMesh2DIG\n";
}

#if 0
/*!
  add a group of bonded triangle mesh (surface) to particle interactions

    \param name the name of the itneraction group
    \param meshname the name of the mesh
    \param k spring constant
    \param r_break (relative) breaking distance
    \param buildtype the way to initially build the IG
    \param buildparam the parameters for building the IG
*/
void CLatticeMaster::addBondedTriMeshIG(const std::string& name,
					const std::string& meshname,
					double k,
					double r_break,
					const std::string& buildtype,
					std::list<OpValue> buildparams)
{
  console.XDebug() << "begin CLatticeMaster::addBondedTriMeshIG\n";
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm);
  CMPIBarrier barrier(m_global_comm);

  // send command 
  cmd_buffer.broadcast(CMD_ADDBONDEDTRIMESHIG);

  // send data
  pbuffer.append(name.c_str());
  pbuffer.append(meshname.c_str());
  pbuffer.append(k);
  pbuffer.append(r_break);
  pbuffer.append(buildtype.c_str());
  if(buildtype=="BuildByTag"){
    console.XDebug() << "BuildByTag\n";
    // extract build parameters
    list<OpValue>::iterator iter=buildparams.begin();
    pbuffer.append(int(iter->Content.l)); iter++; // tag
    pbuffer.append(int(iter->Content.l)); 
    // send params
    pbuffer.broadcast(0);
  } else if (buildtype=="BuildByGap"){
    list<OpValue>::iterator iter=buildparams.begin();
    pbuffer.append(iter->Content.d); // max. gap 
    // send params
    pbuffer.broadcast(0);
  } else {
    throw std::runtime_error(std::string("Unknown BTriMeshInteraction build type: ")+buildtype);
  }
  barrier.wait("readBondedTriMeshIG");
  
  console.XDebug() << "end CLatticeMaster::addBondedTriMeshIG\n";
}

#endif 

/*!
  add a triangle mesh

  \param name the name of the mesh
  \param filename the name of the mesh file
*/
void CLatticeMaster::addTriMesh(const string& meshName, const string& fileName)
{
  console.XDebug() << "begin CLatticeMaster::addTriMesh\n";
  
  readAndDistributeTriMesh(meshName, fileName);

  console.XDebug() << "end CLatticeMaster::addTriMesh\n";
}

/*!
  Read a triangle mesh from a file and distribute the data to the workers.
  The tags on the mesh data are ignored, i.e. the whole file is read as a single mesh.

  \param meshName the name of the mesh
  \param meshFileName the filename
*/
void CLatticeMaster::readAndDistributeTriMesh(const std::string& meshName, const std::string& meshFileName)
{
  TriMeshDataPair meshData = readTriMesh(meshFileName);
  createTriMesh(meshName, meshData.first, meshData.second);
}

/*!
  Read a triangle mesh from a file and distribute the data to the workers.

  \param meshName the name of the mesh
  \param meshFileName the filename
  \param tag the tag in the mesh data determining if a triangle belongs to this mesh or not
*/
void CLatticeMaster::readAndDistributeTriMesh(
     const std::string& meshName, 
     const std::string& meshFileName, 
     int tag)
{
  TriMeshDataPair meshData = readTriMesh(meshFileName,tag);
  createTriMesh(meshName, meshData.first, meshData.second);
}

/*!
  Read triangle mesh data from file and return data as <vector of nodes,vector of triangles> pair.
  Tags are ignored, i.e. the whole file is read as a single mesh.

  \param meshfilename the filename
*/
CLatticeMaster::TriMeshDataPair CLatticeMaster::readTriMesh(const std::string& meshfilename)
{
  console.XDebug() << "CLatticeMaster::readTriMesh(" << meshfilename << ")\n";
  // buffers
  MeshNodeDataVector node_send_buffer;
  MeshTriDataVector tri_send_buffer;

  // mesh reader
  MeshReader reader(meshfilename);

  // --- Nodes ---
  MeshReader::NodeIterator &niter=reader.getNodeIterator();
  // read nodes into vector
  while(niter.hasNext()){
    node_send_buffer.push_back(niter.next());
  }

  // --- Triangles ---
  MeshReader::TriIterator &titer=reader.getTriIterator();
  // read triangles into vector
  while(titer.hasNext()){
    tri_send_buffer.push_back(titer.next());
  }
  return TriMeshDataPair(node_send_buffer, tri_send_buffer);
}

/*!
  read a triangle mesh from a file and distribute the data to the workers

  \param meshfilename the filename
  \param tag the tag in the mesh data determining if a triangle belongs to this mesh or not
*/
CLatticeMaster::TriMeshDataPair CLatticeMaster::readTriMesh(const std::string& meshfilename,int tag)
{
  console.XDebug() << "CLatticeMaster::readTriMesh(" << meshfilename << ")\n";
  // buffers
  vector<MeshNodeData> node_buffer;
  vector<MeshTriData> tri_buffer;

  // mesh reader
  MeshReader reader(meshfilename);


  // --- Nodes ---
  MeshReader::NodeIterator &niter=reader.getNodeIterator();
  // read nodes into vector
  while(niter.hasNext()){
    node_buffer.push_back(niter.next());
  }
 
  // --- Triangles ---
  MeshReader::TriIterator &titer=reader.getTriIterator();
  // read triangles into vector
  while(titer.hasNext()){
    MeshTriData mtd=titer.next();
    if(mtd.tag==tag){
      tri_buffer.push_back(mtd);
    }
  }

  console.XDebug() << "end CLatticeMaster::readTriMesh\n";
  return TriMeshDataPair(node_buffer, tri_buffer);
}

/*!
  create a triangle mesh from a vector of nodes and a vector of triangles

  \param meshName the name assigned to the triangle mesh
  \param node_send_buffer the vector of nodes
  \param tri_send_buffer the vector of triangles
*/
void CLatticeMaster::createTriMesh(
  const std::string &meshName,
  const MeshNodeDataVector &node_send_buffer,
  const MeshTriDataVector &tri_send_buffer
)
{
  console.XDebug() << "CLatticeMaster::distributeTriMesh: enter\n";
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm);

  // send command 
  cmd_buffer.broadcast(CMD_ADDTRIMESH);

  pbuffer.append(meshName.c_str());
  pbuffer.broadcast(0);

  CMPIBarrier barrier(m_global_comm);
  // distribute the node vector
  m_tml_global_comm.broadcast_cont_packed(node_send_buffer);
  // distribute the triangle vector
  m_tml_global_comm.broadcast_cont_packed(tri_send_buffer);

  barrier.wait("distributeTriMesh");
  console.XDebug() << "CLatticeMaster::distributeTriMesh: exit\n";
}


/*!
  add a 2D mesh

  \param name the name of the mesh
  \param filename the name of the mesh file
  \param tag the tag of the edges that are included into the mesh 
*/
void CLatticeMaster::addMesh2D(const string& name, const string& filename, int tag)
{
  console.XDebug() << "CLatticeMaster::addMesh2D( " << name << " , " << filename << ")\n";

  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);
  CVarMPIBuffer pbuffer(m_global_comm);

  // send command 
  cmd_buffer.broadcast(CMD_ADDMESH2D);

  pbuffer.append(name.c_str());
  pbuffer.broadcast(0);
  readAndDistributeMesh2D(filename,tag);
  
  console.XDebug() << "end CLatticeMaster::addMesh2D\n";
}

/*!
  read a 2D mesh from a file and distribute the data to the workers

  \param meshfilename the filename
  \param tag the tag of the edges that are included into the mesh 
*/
void CLatticeMaster::readAndDistributeMesh2D(const std::string& meshfilename,int tag)
{
  console.XDebug() << "CLatticeMaster::readAndDistributeMesh2D(" << meshfilename << ")\n";
  CMPIBarrier barrier(m_global_comm);
  vector<MeshNodeData2D> node_send_buffer;
  vector<MeshEdgeData2D> edge_send_buffer;

  // mesh reader
  Mesh2DReader reader(meshfilename);

  // --- Nodes ---
  Mesh2DReader::NodeIterator &niter=reader.getNodeIterator();
  console.XDebug() << "Node reader initialized\n";
  // read nodes into vector
  while(niter.hasNext()){
    node_send_buffer.push_back(niter.next());
  }
 
  // --- Edges ---
  Mesh2DReader::EdgeIterator &eiter=reader.getEdgeIterator();
  console.XDebug() << "Edge reader initialized\n";
  // read triangles into vector
  while(eiter.hasNext()){
    MeshEdgeData2D med=eiter.next();
    if(med.tag==tag){
      edge_send_buffer.push_back(med);
    }
  }

  // distribute the node vector
  m_tml_global_comm.broadcast_cont_packed(node_send_buffer);
  // distribute the triangle vector
  m_tml_global_comm.broadcast_cont_packed(edge_send_buffer);

  barrier.wait("readAndDistributeMesh2D");
  console.XDebug() << "end CLatticeMaster::readAndDistributeMesh2D\n";
}

class SIGCommand : public BroadcastCommand
{
public:
  SIGCommand(const MpiRankAndComm &globalRankAndComm)
    : BroadcastCommand(globalRankAndComm, CMD_ADDSIG)
  {
  }
  
  void appendGravityIGP(const esys::lsm::GravityIGP &gravityIGP)
  {
    append(gravityIGP.getTypeString().c_str());
    packInto(gravityIGP);
  }

  void appendBuoyancyIGP(const esys::lsm::BuoyancyIGP &buoyancyIGP)
  {
    append(buoyancyIGP.getTypeString().c_str());
    packInto(buoyancyIGP);
  }
};

void CLatticeMaster::addSingleIG(const esys::lsm::GravityIGP &gravityIGP)
{
  SIGCommand sigCmd(getGlobalRankAndComm());
  sigCmd.appendGravityIGP(gravityIGP);
  sigCmd.broadcast();
}

void CLatticeMaster::addSingleIG(const esys::lsm::BuoyancyIGP &buoyancyIGP)
{
  SIGCommand sigCmd(getGlobalRankAndComm());
  sigCmd.appendBuoyancyIGP(buoyancyIGP);
  sigCmd.broadcast();
}

#if 0
/*!
  add body force

  \param type the type of force, i.e. Gravity,...
  \param prms the interaction parameters
*/
void CLatticeMaster::addBodyForce(const string& type, const esys::lsm::BodyForceIGP &prms)
{
  console.XDebug() << "begin CLatticeMaster::addBodyForce\n";  
  if (type == "Gravity") {
    console.XDebug()<<"Body force type is " << type << "\n";
     
    CVarMPIBuffer pbuffer(MPI_COMM_WORLD,20);
    CMPIBarrier barrier(MPI_COMM_WORLD);
    CMPILCmdBuffer cmd_buffer(MPI_COMM_WORLD,m_global_rank);
  
    //send the command
    cmd_buffer.broadcast(CMD_ADDSIG);
    // console.Debug()<<"adding Gravity IG\n";
    pbuffer.append(type.c_str());
    prms.packInto(&pbuffer);
    pbuffer.broadcast(0);

    barrier.wait("addBodyForce()");
  }
  else {
    throw std::runtime_error(
      std::string("Unknown body force type: ")
      +
      type
    );
  }
  console.XDebug() << "end CLatticeMaster::addBodyForce\n";  
}

void CLatticeMaster::addSingleIG(const string& type, const string& name, list<OpValue> params)
{
  console.XDebug()<<"CLatticeMaster::addSingleIG\n";

  if(type=="Gravity"){

    list<OpValue>::iterator iter=params.begin();
    double x = iter->Content.d;
    iter++;
    double y = iter->Content.d;
    iter++;
    double z = iter->Content.d;
    
    addBodyForce(type, esys::lsm::BodyForceIGP(name, Vec3(x, y, z)));
  }else{
    throw std::runtime_error(
      std::string("Unknown body force type: ")
      +
      type
    );
  }
  console.XDebug()<<"end CLatticeMaster::addSingleIG\n";
}
#endif

class DampingCommand : public BroadcastCommand
{
public:
  DampingCommand(const MpiRankAndComm &globalRankAndComm)
    : BroadcastCommand(globalRankAndComm, CMD_ADDDAMP)
  {
  }
};

void CLatticeMaster::addDamping(const CDampingIGP &dampingIGP)
{
  DampingCommand dampCmd(getGlobalRankAndComm());
  dampCmd.append(dampingIGP.getTypeString().c_str());
  dampCmd.packInto(dampingIGP);
  dampCmd.broadcast();
}

void CLatticeMaster::addDamping(const CLocalDampingIGP &dampingIGP)
{
  DampingCommand dampCmd(getGlobalRankAndComm());
  dampCmd.append(dampingIGP.getTypeString().c_str());
  dampCmd.packInto(dampingIGP);
  dampCmd.broadcast();
}

void CLatticeMaster::addDamping(const ABCDampingIGP &dampingIGP)
{
  DampingCommand dampCmd(getGlobalRankAndComm());
  dampCmd.append(dampingIGP.getTypeString().c_str());
  dampCmd.packInto(dampingIGP);
  dampCmd.broadcast();
}

#if 0
/*!
  Add damping to a lattice. Send parameters to slaves
*/
void CLatticeMaster::addDamping(const string& type,list<OpValue> params)
{
  console.XDebug()<<"CLatticeMaster::addDamping\n";
   
  CVarMPIBuffer pbuffer(m_global_comm,20);
  CMPIBarrier barrier(m_global_comm);
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);

  //send the command
  cmd_buffer.broadcast(CMD_ADDDAMP);
  if(type=="Damping"){
    // console.Debug()<<"adding Damping\n";
    pbuffer.append("Damping");
    CDampingIGP igp;
    list<OpValue>::iterator iter=params.begin();
    igp.setName("damp");
    igp.setVRef(Vec3(0.0,0.0,0.0));
    igp.setVisc(iter->Content.d);
    console.XDebug()<< "visc : " << iter->Content.d;
    iter++;
    igp.setTimeStep(iter->Content.d);
    console.XDebug()<< "dt : " << iter->Content.d;
    iter++;
    igp.setMaxIter(iter->Content.l);
    igp.packInto(&pbuffer);
    pbuffer.broadcast(0);
  }else{
    console.Error()<<"trying to add Damping of unknown type\n";
  }
  barrier.wait("addDamping()");
  console.XDebug()<<"end CLatticeMaster::addDamping\n";
}

#endif

/*!
  set IG s1 as excluding IG in s2, i.e. an two particles interacting in s1 
  can't interact in s2
*/
void CLatticeMaster::addExIG(const string& s1,const string& s2)
{
  console.XDebug()<<"CLatticeMaster::addExIG\n";
   
  CVarMPIBuffer pbuffer(m_global_comm,20);
  CMPIBarrier barrier(m_global_comm);
  CMPILCmdBuffer cmd_buffer(m_global_comm,m_global_rank);

  //send the command
  cmd_buffer.broadcast(CMD_EXIG);
  pbuffer.append(s1.c_str());
  pbuffer.append(s2.c_str());
  pbuffer.broadcast(0);
  barrier.wait("addExIG()");
  console.XDebug()<<"end CLatticeMaster::addExIG\n";
  // update interactions - relevant in case the exclusion is added _during_ a run
  updateInteractions();
}  

#if 0
/*!
  Get the list of face ids for a given mesh, i.e. edge ids in 2D, triangle ids in 3D

  \param meshname
*/
void CLatticeMaster::getMeshFaceReferences(const string& meshname)
{
  console.XDebug()<<"CLatticeMaster::getMeshFaceReferences( " << meshname << ")\n";
  GetFaceRefCommand cmd(getGlobalRankAndComm(),meshname);
  // broadcast command
  cmd.broadcast();
  
  // receive data (multimap)
  multimap<int,int> ref_mmap;
  m_tml_global_comm.gather(ref_mmap);
  // collate into set
  set<int> ref_set; //== this is the set of node ids == 
  for(multimap<int,int>::iterator iter=ref_mmap.begin();
      iter!=ref_mmap.end();
      iter++){
    ref_set.insert(iter->second);
  }  
  console.XDebug()<<"end CLatticeMaster::getMeshFaceReferences()\n";
}

/*!
  Get the list of stresses for a given mesh. 

  \param meshname
*/
void CLatticeMaster::getMesh2DEdgeStress(const string& meshname)
{
  console.XDebug()<<"CLatticeMaster::getMesh2DEdgeStress( " << meshname << ")\n";
  multimap<int,pair<int,Vec3> > temp_mm;
  map<int,Vec3> m_data; //=== map of id, value ===

  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_GETMESH2DSTRESS);
  cmd.append(meshname.c_str());
  cmd.broadcastCommand();
  

  // get data from slaves
  m_tml_global_comm.gather(temp_mm);
  
  // add data together
  for(multimap<int,pair<int,Vec3> >::iterator iter=temp_mm.begin();
      iter!=temp_mm.end();
      iter++){
    if(m_data.find((iter->second).first)==m_data.end()){ // id not in m_data -> insert
      m_data.insert(iter->second);
    } else { // id is in m_data -> add
      m_data[(iter->second).first]+=(iter->second).second;
    }
  }  

  console.XDebug()<<"end CLatticeMaster::getMesh2DEdgeStress()\n";  
}
#endif

/*!
  Set local console verbosity and send command to workers to set console verbosity there
*/
void CLatticeMaster::setVerbosity(int verbose)
{
  console.SetVerbose(verbose);
  
  // workers
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_SETVERBOSITY);
  cmd.append(verbose);
  cmd.broadcast();

}

/*!
  initialize local console and send command to workers initialize consoles there

  \param filename the base name of the output file
  \param bufflen the length of the internal buffer in the console 0-> no buffering 
*/
void CLatticeMaster::initializeConsole(const string& filename, int bufflen)
{
  // workers
  BroadcastCommand cmd(getGlobalRankAndComm(), CMD_INITCONSOLE);
  cmd.append(filename.c_str());
  cmd.append(bufflen);
  cmd.broadcast();

  //master
  console.Initialize(filename);
}