TreElM / source / tem_tracking_module.f90

   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
! See copyright notice in the COPYRIGHT file.
!******************************************************************************!
!> A tracking output (e.g. for macroscopic values) for tracking certain flow
!! Quantities over a period of time at certain locations in the grid.
!!
!! \section tracking Tracking
!! 
!! During the runtime of simulations, the user needs to keep track of the 
!! simultation state without being obliged to write out the complete domain 
!! to disk.
!! This is achieved by tracking objects, at which the state is evaluated 
!! at certain defined intervals and then written to disk.
!! 
!! \subsection tracking_format Tracking format
!! 
!! We support three formats for tracking.
!! <em>Note: We strongly encourage you to use the Harvester format. </em>
!! Herefore you need to run Harvester on the simulation folder to create 
!! files for the Visualization tools.
!! - \ref tem_tracking_dumpasciitransient "ascii" - 
!! Transient data: simple gnuplot-style 
!! A simple ascii file which creates a small header and then writes at each 
!! defined time step a column wise representation of all variables and points. 
!! This is not efficient and should only be used for simple point-tracking 
!! objects.
!! Each process writes its own file.
!! - \ref tem_tracking_dumpasciispatial "asciiSpatial" - 
!! Spatial Data: This format stores solution data along with coordinates in 
!! single data file for every timestep. Therefore, there would be multiple 
!! files depending on the total number of time-steps. 
!! It is ideal for tracking *line* and *plane*.
!! 
!! - \ref tem_restart_module::restart_format "Harvester Format"
!! Writes all participating elements to a treelm mesh and creates for each 
!! required time step a restart file.
!! This is a scalable tracking object which works regardless of number of 
!! processes.
!! \verbatim format='harvester', folder = './tracking/'\endverbatim 
!! 
!! <em>Note: We will demonstrate each format in the examples of tracking point, 
!! line and plane in the following sections</em>
!! 
!! \subsection tracking_variabletypes Tracking variable types
!! 
!! - \ref tem_variable_module "variables": 
!!  all variables defined in the \ref tem_var_system_module "global variable 
!!                   system" can be tracked.
!!                   See \ref tem_variable_module::tem_variable_from 
!!                   "how to define variables"
!! - derived variables: all variables defined in the global variable system 
!!    can be tracked
!! - spacetime: as analytical result, can be defined in lua file
!! - \ref tem_reduction_module "reductions": 
!!     e.g. difference, sum or average of defined variables
!! 
!! \subsection tracking_shapes Tracking shapes
!! 
!! We show the tracking with simple shapes here. 
!! Get an overview over all existing shapes \ref tem_shape_module "here".
!! 
!! - zero-dimensional: point 
!! - one-dimensional: line 
!! - two-dimensional: plane
!! - three-dimensional: cubes, cylinders
!! 
!! So far point, line, plane are implemented in \ref tem_shape_module "shapes".
!! 
!! \subsection tracking_usage Usage
!! 
!! The user specifies the desired parameters in the configuration file 
!! (in the scheme table) as
!! \verbatim 
!! -- if you want to have a analytical solution as reference, you can add 
!! --  a spacetime variable first
!! -- define single new (spacetime) variable
!! add_variable = { name='spacetime', ncomponents=1, spacetime=luaFun }
!! -- define multiple new (spacetime) variables
!! add_variable = {                                                   
!! {name='spacetime', ncomponents=1, spacetime=luaFun },
!! {name='spacetime2', ncomponents=1, spacetime=luaFun }
!! }
!! 
!! -- Tracking
!! tracking = {
!! { label = 'probe_error',
!! variable = {
!!   { 'velocity' },
!!   { name='difference', 
!!     ncomponents=1, 
!!     dep={'density','spacetime'}},
!!   { name='difference', 
!!     ncomponents=1, 
!!     dep={'wss','spacetime2'}}},
!! folder = './tracking/',
!! format = 'ascii',
!! time = {interval = 1, min = 1000, max = 4000 },
!! reduction = {'l2norm'},  
!! shape = { kind = 'canoND', 
!!           object = { origin ={0.,0.,0.},
!!                      vec = {1.,0.,0.}, 
!!                      segments={100}} }
!! } 
!! \endverbatim 
!! Here, a point at the location {0.,0.,0.} is defined as a pressure probe. 
!! The interval is set to 1, meaning at each time step, the pressure has to 
!! be written.
!! The probing starts at iteration 1000 and lasts until 4000.
!! The tracking write both pressure and velocityX in a single file.
!! Use ref_value to normalize the output.
!! \verbatim 
!! # Name:       GaussPulse_TestSimulation     Date 2011-060-27  Time 11:43 CEST
!! # Probe type: Point at {0.0 0.0 0.0} 
!! # Quantities: pressure, velocityX
!! # tMin:       1000,     tMax:    4000,     Interval: 1
!! # ref_value: 1.0, 0.01
!! #   iTime     rTime      Pressure           velocityX
!! 1000          1000.0     1.0241818          0.00158287
!! 1001          1001.0     1.0251427          0.00152617
!! ...                                      
!! 4000          4000.0     1.7162511          0.01273673
!! \endverbatim 
!! 
!! The shape is defined as a canonical object. 
!! The different shapes are basically derivatives of a simple cube. 
!! A cube with no length in any direction is a point, a cube with length along 
!! only one axis is a line whereas a cube with length along two axes is simply 
!! treated as plane by the underlying code. 
!! One example each for Point, Line and Plane is shown below.
!! 
!! \subsection tracking_point Point Tracking
!! 
!! <em>Example: tracking a point in ASCII format</em>
!! 
!! \verbatim               
!! tracking = { label = 'Velocity', 
!! variable = {'velocity'},   -- options: density, velocity
!! 
!! --   Tracking over a point
!! shape={kind = 'canoND', origin = {0.5,0.5,0.5} },
!! 
!! time = {min = 0, max = -1, interval = 1},     -- max = -1 assigns max=tmax
!! format = 'ascii',
!! folder = 'tracking/'}
!! }
!! \endverbatim 
!! 
!! Once, the above section is executed within the musubi.lua file, an output in 
!! the asciiTransient format is generated in the output folder specified 
!! (tracking in this particular example). 
!! Now, we open the result file inside tracking folder, the structure of which 
!! looks like below:
!! 
!! \verbatim 
!! # Rank of the process:       0
!! #               time     velocity_01     velocity_02     velocity_03
!! 1.0000  0.000000000000  0.000000000000  0.000000000000
!! 2.0000  0.000000000000  0.000000000000  0.000000000000
!! 3.0000  0.000000000000  0.000000000000  0.000000000000
!! 4.0000  0.000000000000  0.000000000000  0.000000000000
!! ...
!! ...
!! 1997.0000 -0.006065558329  0.000443400622 -0.000003481789
!! 1998.0000 -0.006063901533  0.000443795703 -0.000003286949
!! 1999.0000 -0.006061596302  0.000443327890 -0.000003534752
!! 2000.0000 -0.006059665212  0.000443720604 -0.000003339771
!! \endverbatim 
!! Here, it can be noticed that 3 velocity components for all time steps at the 
!! point (0.5, 0.5, 0.5) are stored. The interval was chosen as 1, so they are 
!! tracked for each time step. If the interval was chosen as say 10, then the 
!! tracking would have been done after 10 timesteps.
!! 
!! 
!! \subsection tracking_line Line Tracking
!! 
!! We need to set the origin and the direction vector, 
!! as e.g. {origin={0.,0.,0.}, vec={1.0,1.0,1.0}}.
!! The line is represented as a list of points in the tracking facility. 
!! The number of subdivisions and its distribution of the points on the line 
!! needs to be set, as e.g. @segments=500, distribution='equal'@. 
!! Make sure to specify enough segments to take into account all the required 
!! elements on the line. 
!! Elements are added only once, so it might be beneficial to specify much more 
!! segments than actually needed to consider elements on the highest levels as 
!! well.
!! 
!! <em>Example: Tracking a line in ASCII Spatial format</em>
!! 
!! \verbatim tracking = { 
!!   label = 'line_probe',
!!   variable = {'state'}, -- state (=pdfs), pressure, density etc
!!   shape = { kind = 'canoND', 
!!             object={
!!               origin = {0.5,0.5,0.5}, 
!!               vec = { {0.0,0.2,0.0}},
!!               segments = {300},
!!               distribution='equal'} 
!!           },
!!   format='harvester', 
!!   folder='tracking/',
!!   time = {interval = 5, min = 0, max = 800 } }
!! }\endverbatim 
!! 
!! After, the above tracking is executed within musubi.lua file multiple res 
!! files are obtained inside the tracking folder each specific to particular 
!! time step. If you open any one of the @res@ files, there will be six data 
!! columns: three coordinate and three velocity components. 
!! An example is shown below: 
!! \verbatim 
!! # Rank of the process:       0
!! #         coordX          coordY          coordZ     velocity_01     velocity_02     velocity_03
!! 0.51562500      0.51562500      0.51562500 -0.000998448727 -0.000118182367  0.000007560959
!! 0.51562500      0.54687500      0.51562500 -0.000922746216  0.000011023243 -0.000000130462
!! 0.51562500      0.57812500      0.51562500 -0.001083956104  0.000038534363 -0.000003774649
!! ...
!! 0.51562500      0.64062500      0.51562500 -0.001343981219 -0.000131107478 -0.000004381864
!! 0.51562500      0.67187500      0.51562500 -0.001261956611  0.000081027056  0.000000215364
!! 0.51562500      0.70312500      0.51562500 -0.001733303068  0.000060154818  0.000005793207
!! \endverbatim 
!! 
!! Out of three coordinate components, only 'coordY' is varying and 'coordX', 
!! 'coordZ' remain constant. This is according to our tracking input with 
!! @origin = {0.5, 0.5, 0.5}, vec = {0.0, 0.2, 0.0}@.
!! You can now make a line plot with any one of velocity components with 
!! respect to @coordY@ in "gnuplot":http://www.gnuplot.info/.
!! 
!! \subsection tracking_plane Plane Tracking
!! 
!! We need to set the origin and the direction vectors, as e.g. 
!! object = {origin={0.,0.,0.}, vec={{1.0,1.0,1.0},{0.0,-1.0,1.0}}}.
!! The plane is, just as the line, represented as a list of points in the 
!! tracking facility. 
!! The number of subdivisions in each direction and its distribution of the 
!! points on the plane needs to be set, 
!! as e.g. @segments1=500, segments2=300, distribution='equal'@. 
!! Make sure to specify enough segments to take into account all the required 
!! elements on the line. 
!! Elements are added only once, so it might be beneficial to specify much more 
!! segments than actually needed to consider elements on the highest levels 
!! as well.
!! 
!! <em> Example: tracking a plane in harvester format</em>
!! 
!! \verbatim tracking = { 
!!   label = 'plane_probe',
!!   variable = {'state'}, -- state (=pdfs), pressure, density etc
!!   shape = { kind = 'canoND', 
!!             object={
!!               origin = {-75.,-15.,0.}, 
!!               vec = { {150.,0,0.}, {0.,30,0.}},
!!               segments = {300, 300},
!!               distribution='equal'} 
!!           },
!!   format='harvester', 
!!   folder='tracking/',
!!   time = {interval = 5, min = 0, max = 800 } }
!! }\endverbatim 
!! 
!! \subsection tracking_global_mesh Global mesh tracking
!! 
!! <em> Example: tracking the whole mesh</em>
!! 
!! \verbatim tracking = { 
!!   ...
!!   shape = { kind = 'global' },
!!   ...
!! }\endverbatim 
!! 
!! \subsection tracking_boundary Boundary elements tracking
!! 
!! <em> Example: tracking the boundary elements</em>
!! 
!! \verbatim tracking = { 
!!   ...
!!   shape = { kind = 'property', property = {'boundary'} },
!!   ...
!! }\endverbatim 
!! 
!! \subsection tracking_design Design and Implementation
!! 
!! The user-specified tracking shapes have to be translated to a set of elements, 
!! on which the defined quantities are calculated and written to disk in a suitable format.
!! 
!! All elements are converted to a set of points.
!! For each point, the correspoinding treeID is added to the element list of the tracker as 
!! \verbatim track%elems( iLevel )%elem(1:nElems)\endverbatim 
!! Each element will only be added once.
!! All these elements are then treated in the main loop within the @tracker@ routine.
!! \author Manuel Hasert
module tem_tracking_module
  use mpi
  use env_module, only: rk, long_k, newunit, globalMaxLevels, dbgUnit,         &
    &                   labelLen, pathLen, pathSep
  use treelmesh_module, only: treelmesh_type, dump_treelmesh
  use tem_aux_module, only: tem_abort, tem_unit_close
  use tem_comm_env_module, only: process, tem_comm_env_type
  use tem_dyn_array_module, only: dyn_longArray_type,                          &
    &                             init, append, expand, destroy
  use tem_geometry_module, only: tem_PosOfId, tem_BaryOfId
  use tem_restart_module, only: tem_restart_type, tem_init_restart,            &
    &                           tem_restart_finalize
  use tem_reduction_module, only: tem_reduction_type, tem_load_reduction,      &
    &                             tem_reduction_init, tem_reduction_toChunk
  use tem_transient_reduction_module, only: tem_transient_reduction_type,      &
    &                             tem_load_transient_reduction,                &
    &                             tem_transient_reduction_init
  use tem_shape_module,  only: tem_shape_type, tem_load_shape,                 &
    &                          tem_shape_out
  use tem_subTree_module, only: tem_create_subTree_of
  use tem_solveHead_module, only: tem_solveHead_type, tem_solverTag
  use tem_time_module, only: tem_generate_timeStamp, tem_time_type
  use tem_timeControl_module, only: tem_timeControl_type,                      &
    &                               tem_load_timeControl,                      &
    &                               tem_timeControl_out
  use tem_var_system_module, only: tem_var_system_type, tem_var_intersect,     &
    &                              tem_var_sys_load, tem_var_sys_dump,         &
    &                              tem_var_sys_out, tem_writeSolverSpec
  use tem_variable_module, only: tem_variable_type
  use tem_tools_module, only: tem_write, tem_horizontalSpacer
  use tem_topology_module, only: tem_levelOf
  use tem_condition_module, only: tem_convergence_type, tem_condition_type,           &
    &                             tem_load_cond_single, tem_load_convergence

  use flu_binding, only: flu_State
  use aot_table_module, only: aot_table_open, aot_table_close,                 &
    &                         aot_table_length, aot_get_val
  use aot_out_module, only: aot_out_type, aot_out_val,                         &
    &                       aot_out_open, aot_out_close,                       &
    &                       aot_out_open_table, aot_out_close_table
  use aot_path_module, only: aot_path_type, aot_path_addNode, assignment(=)

  implicit none

  private

  public :: tem_tracking_type
  public :: tem_trackingControl_type
  public :: tem_load_tracking
  public :: tem_init_tracker
  public :: tem_tracking_finalize
  public :: tem_tracking_header_Ascii
  public :: tem_tracking_close_AsciiTransient
  public :: tem_tracking_dumpAsciiTransient
  public :: tem_tracking_dumpAsciiSpatial
  public :: tem_transform_solSpecChar

  !> Parameter for harvester output
  integer, public, parameter :: tem_trackingHarvester      = 2
  !> Parameter for gnuplot ascii, writing a complete spatial
  !! representation at each time step into a new file
  integer, public, parameter :: tem_trackingAsciiSpatial   = 3
  !> parameter for ascii output, writing only one row consisting
  !! of all the elements with all variable values in that row
  !! into an initially opened file
  integer, public, parameter :: tem_trackingAsciiTransient = 4
  !> Parameter for convergence
  integer, public, parameter :: tem_trackingConvergence    = 5

  !> type for storing a list of elements to track and their values
  type tem_elemList_type
    !> Number of elements in the list
    integer :: nElems
    !> List of elements (actually the position of the
    !! element in glob%levelDesc( level )%total
    integer, allocatable :: elem(:)
  end type tem_elemList_type

  !> General information about the tracking entities
  type tem_trackingControl_type
   logical :: active   = .true.        !< output status, activated?
   integer :: nTrackings = 0           !< number of tracking entities
  end type tem_trackingControl_type

  !> Contains all header information about tracking
  type tem_trackingHeader_type
    !> if this tracking object acts on the complete tree
    logical :: useGlobalMesh
    !> log object labels
    character(len=labelLen)  :: label
    !> folder to store files to
    character(len=pathLen) :: prefix
    !> a unique tag for the solver including version
    character(len=LabelLen) :: solverTag
    !> from the user requested system of variables
    type(tem_var_system_type) :: requestedSys
    !> stores time control parameters
    type(tem_timeControl_type) :: timeControl
    !< simple gnuplot or partial tree mesh
    integer :: fileformat
    !> unit to write to the ascii file
    integer :: unit  = -1
    !> tracking shapes
    type(tem_shape_type), allocatable  :: geometry(:)
    type(tem_convergence_type) :: convergence
  end type tem_trackingHeader_type

  !> Tracking entity definition
  type tem_tracking_type
    !> tracking header for collecting the properties from the lua file
    type(tem_trackingHeader_type) :: header
    !> Variable system definition, i.e. list of variables to track
    type(tem_var_system_type)  :: varSys
    !> map the requested variables to the offered ones
    integer,allocatable :: varMap(:)
    !> Restart type for saving in harvester format
    type(tem_restart_type)  :: restart
    !> sub-tree resulting from the elements within the tracking shape
    !! The sub-tree also holds the sub-communicator
    type(treelmesh_type)    :: tree
    !> Store the barycenters for the linearized tree elements
    !! it has a size of ( nElems, 3 )
    real(kind=rk), allocatable :: bary(:,:)
    !> store where the treeIDs of the sub-mesh are located in the levelwise
    !! arrays of levelDesc( iLevel )%total
    integer, allocatable    :: levelPointer(:)
    !> does only the root process of this tracking object have to write to disk?
    !! this is the case for spatial reduction where a transient ascii file is
    !! written
    logical :: onlyRootDumps
    !> Is there any reduction active inside this tracker?
    logical :: reduceActive
    !> reduction type which saves results from reduction
    type(tem_reduction_type), allocatable  :: reduce(:)
    !> is there any transient reduction active?
    !! Then this tracking must be updated every timestep!
    logical :: transientReduceActive
    !> transient reductions which collect and reduce data over several timesteps
    type(tem_transient_reduction_type), allocatable :: transientReduce(:)
  end type tem_tracking_type

  contains

!******************************************************************************!
  !> Read the tracker configuration from the main lua file
  !!
  !! Setup the values for the tracking entities
  subroutine tem_load_tracking( tCtrl, me, conf, parent, path, prefix )
    !--------------------------------------------------------------------------
    !> list of the tracking entities to create
    type( tem_tracking_type ), allocatable :: me(:)
    type( tem_trackingControl_type ) :: tCtrl !< general control parameters
    type( flu_state ) :: conf !< handle of the lua config file
    !> if the tracking table is a child-table of some other table,
    !! use the parent as a reference
    integer, optional :: parent
    type( aot_path_type ),intent(in), optional :: path !< lua path
    !> prefix for tracking label to differiate tracking for different scheme
    !! with same tracking label
    character(len=*), intent(in), optional :: prefix
    !--------------------------------------------------------------------------
    integer :: tc_handle, sub_handle
    integer :: iTrack, nTracks
    integer :: verbose
    type( aot_path_type ) :: track_path, track_sub_path
    !--------------------------------------------------------------------------
    ! \todo link this verbose to the debug%verboseLevel
    verbose = 1

    ! Generally assume that tracking is not defined
    tCtrl%active = .false.

    ! Read the number of trackings in the lua file
    if( present( parent )) then
      call aot_table_open(L=conf, thandle=tc_handle, key='tracking', parent = parent)
    else
      call aot_table_open(L=conf, thandle=tc_handle, key='tracking')
    end if

    if (tc_handle .eq. 0) then
      call tem_write( 'No Tracking entities found!' )
      call aot_table_close(L=conf, thandle=tc_handle)
      call tem_horizontalSpacer()
      nTracks = 0
      tCtrl%nTrackings = nTracks
      allocate( me( nTracks ) )
      return
    else ! track entity exists.
      ! add this path to track path
      if( present( path ) ) then
        track_path = path
        call aot_path_addNode( me = track_path, NodeType = 'table', &
          &                    key = 'tracking' )
      end if
      tCtrl%active = .true.
    end if

    ! Check whether tracking had a subtable
    ! If no, then it is a single table, load single tracking entry
    ! else load multiple tables, open tracking subtable
    call aot_table_open(L=conf, parent=tc_handle, thandle=sub_handle, pos=1)

    ! Only single table
    if (sub_handle .eq. 0) then
      nTracks = 1
      tCtrl%nTrackings = nTracks
      call tem_write( 'Tracking is a single table' )
      allocate( me( nTracks ) )
      if( present( path ) ) then
        call tem_load_trackingHeader( conf=conf, sub_handle = tc_handle, &
          &                           me = me(1), prefix = prefix,       &
          &                           path = track_path, verbose = verbose )
      else
        call tem_load_trackingHeader( conf=conf, sub_handle = tc_handle, &
          &                           me = me(1), prefix = prefix, verbose = verbose)
      end if
      call aot_table_close(L=conf, thandle=sub_handle)
    else ! Multiple table
      call aot_table_close(L=conf, thandle=sub_handle)
      nTracks = aot_table_length(L=conf, thandle=tc_handle)
      tCtrl%nTrackings = nTracks
      ! Allocate the defined number of tracking entities
      allocate( me( nTracks ))
      call tem_write( 'Number of Tracking entities: ', nTracks )

      ! Loop over all the definitions and assign the variables from the lua file on the
      ! tem_tracking_type
      ! Inside this routine it will open tracking subtable. Each subtable contains one or more
      ! tracking variables
      ! the stuff is done in the routine tem_load_trackingHeader
      do iTrack = 1, nTracks
        call tem_write( 'Loading tracker ', iTrack )
        call aot_table_open(L=conf, parent=tc_handle, thandle=sub_handle, pos=iTrack)
        if( present( path )) then
          track_sub_path = track_path
          call aot_path_addNode( me = track_sub_path, NodeType = 'table',   &
            &                    pos = iTrack )
          call tem_load_trackingHeader( conf = conf, sub_handle  = sub_handle,  &
            &                           me = me(iTrack), path = track_sub_path, &
            &                           prefix = prefix,                        &
            &                           verbose = verbose )
        else
          call tem_load_trackingHeader( conf = conf, sub_handle  = sub_handle, &
            &                           me = me(iTrack), prefix = prefix,      &
            &                           verbose = verbose )
        end if
        call aot_table_close(L=conf, thandle=sub_handle)
        call tem_write( 'Done tracker ', iTrack )
      end do
    end if ! sub_handle

    call aot_table_close(L=conf, thandle=tc_handle) ! close tracking table
    call tem_horizontalSpacer()

  end subroutine tem_load_tracking
!******************************************************************************!


!******************************************************************************!
  !> Read the tracker variables from tracking subtables defined in
  !! configuration from the main lua file
  !!
  !! If tracking is just a single table with single tracking entry
  !! then load only one tracking log exists with
  !! one or more variables using tem_load_trackingHeader_single.
  !! Else if tracking is table of many log then allocate log and load each log type
  !! using tem_load_trackingHeader_single
  !! Setup the values for the tracking entities
  subroutine tem_load_trackingHeader( me, conf, sub_handle, path, prefix, verbose )
    !--------------------------------------------------------------------------
    type( tem_tracking_type ), intent(out) :: me !< list of the tracking entities to create
    type( flu_state ) :: conf !< handle of the lua config file
    integer, intent(in) :: sub_handle !< table sub-handle for the tracking table
    type( aot_path_type ),intent(in), optional :: path !< lua path
    !> prefix for tracking label to differiate tracking for different scheme
    !! with same tracking label
    character(len=*), intent(in), optional :: prefix
    integer, intent(in) :: verbose !< verbosity level
    !--------------------------------------------------------------------------
    integer :: iError               !< error flag handle
    integer :: iShape               !< error flag handle
    character(len=32) :: buffer     !< temporary variable for string treatment
    !--------------------------------------------------------------------------

    call aot_get_val(L=conf, thandle=sub_handle, &
      &                    val=me%header%label, ErrCode=iError, &
      &                    key='label', default='unnamed_track')
    if(present(prefix)) then
      if( trim(prefix) .ne. '' ) &
        &write(me%header%label, '(a)') trim(prefix)//'_'//trim(me%header%label)
    end if

    call tem_write('Tracking entity: '//trim( me%header%label ))

    ! Load single variable system
    ! \todo remove duplicate calls
    if( present( path )) then
      call tem_var_sys_load( conf = conf, sys = me%header%requestedSys, &
        &                    thandle = sub_handle, path = path,         &
        &                    verbose = .true., sysName = trim(me%header%label)//'_sys' )
    else
      call tem_var_sys_load( conf = conf, sys = me%header%requestedSys, &
        &                    thandle = sub_handle, verbose = .true.,    &
        &                    sysName = trim(me%header%label)//'_sys' )
    end if

    ! load time control to output tracking
    call tem_load_timeControl( conf = conf, parent = sub_handle, &
                               me = me%header%timeControl, verbose = .true.  )

    ! Where to store the tracking file?
    call aot_get_val(L=conf, thandle=sub_handle, &
      &                    val=me%header%prefix, ErrCode=iError, &
      &                    key='folder', default='.'//pathSep)


    ! load tracking object shapes like point, line, plane
    call tem_load_shape( conf = conf, parent = sub_handle, &
                         me = me%header%geometry, verbose = .true.  )

    if( size( me%header%geometry) .lt. 1) then
      call tem_write('The geometrical objects for the tracker are not defined correctly.')
      call tem_abort()
    end if

    ! Check if an option for the global mesh had been given.
    me%header%useGlobalMesh = .false.
    do iShape = 1, size( me%header%geometry)
      call tem_write( ' use Global mesh: ',me%header%geometry( iShape )%useGlobalMesh )
      if( me%header%geometry( iShape )%useGlobalMesh ) me%header%useGlobalMesh = .true.
    end do

    ! load reductions
    me%reduceActive = .false.
    call tem_load_reduction( conf = conf, parent = sub_handle, &
      &                  me = me%reduce, verbose = .true.  )
    if( size( me%reduce ) .gt. 0 ) me%reduceActive = .true.

    if( me%reduceActive ) then
      ! Check if the number of reductions correspond to the number of variables in the system
      if( size( me%reduce) .ne. me%header%requestedSys%nVars ) then
        call tem_write('The number of defined reductions does not correspond to the ')
        call tem_write('number of variables in the system. ')
        call tem_abort()
      end if
    end if

    ! load transient reductions
    me%transientReduceActive = .false.
    call tem_load_transient_reduction( conf = conf, parent = sub_handle, &
      &                                me = me%transientReduce, verbose = .true.  )
    if( size( me%transientReduce ) .gt. 0 ) me%transientReduceActive = .true.

    if( me%transientReduceActive ) then
      ! Check if the number of reductions correspond to the number of variables in the system
      if( size( me%transientReduce) .ne. me%header%requestedSys%nVars ) then
        call tem_write('The number of defined transient reductions does not correspond to the ')
        call tem_write('number of variables in the system. ')
        call tem_abort()
      end if
    end if


    ! get tracking format
    call aot_get_val(L=conf, thandle=sub_handle, &
      &                    val=buffer, ErrCode=iError, &
      &                    key='format', default='ascii')
    if( me%reduceActive ) then
      if( trim(buffer) .ne. 'ascii' .and. trim(buffer) .ne. 'convergence') then
        call tem_write('Warning: ')
        call tem_write('Reduction is defined in current tracking object')
        call tem_write('Activating asciiTransient, as it is the only format which')
        call tem_write('makes sense here.')
        buffer = 'ascii'
      end if
    end if

     ! Decide, which format is being written to disk
    select case( trim(buffer))
      case( 'ascii','Ascii','ASCII', 'asciiTransient')
        me%header%fileformat = tem_trackingAsciiTransient
      case( 'asciiSpatial')
        ! write an ascii file for each time step and write all three barycenters
        ! each line has corrdinates and variables of only ONE element
        ! #       coordX  coordY  coordZ    var1       var2        var3
        me%header%fileformat = tem_trackingAsciiSpatial
      case( 'harvester','Harvester','binary')
        ! ... in the harvester format, meaning
        ! there is a mesh in treelm format and corresponding to it
        ! there are restart files which hold the state information for the elements
        ! in the mesh for the requested time step
        me%header%fileformat = tem_trackingHarvester
      !\todo:KJ: Adding the convergence case, if convergence is defined we load 
      !! the condition table
      case( 'convergence' )
        me%header%fileFormat = tem_trackingConvergence
        call tem_load_convergence( me = me%header%convergence, conf = conf,    &
          &                        parent = sub_handle, verbose = verbose )
       
      case default
        call tem_write( '  Unknown Tracking Format specified! ' )
        call tem_write( '  Choose between ascii and harvester. Stopping!' )
        call tem_abort()
    end select

  end subroutine tem_load_trackingHeader
!******************************************************************************!



!******************************************************************************!
  !> Initialize the tracker entities
  !!
  !! Identify, how many and which elements exist on my local process and are
  !! requested from the trackers
  !! Empty tracking entities are removed, so the track(:) might be re-allocated
  !! \verbatim scheme = { ... tracking = { ... }} \endverbatim
  subroutine tem_init_tracker( me, tCtrl, levelPointer, &
                               tree, solver, label, varSys, nDofs )
    !---------------------------------------------------------------------------
    type(tem_tracking_type ),intent(inout),allocatable :: me(:) !< tracking entities
    type(tem_trackingControl_type ),intent(inout) :: tCtrl !< global tracking parameters
    !> Global mesh from which the elements are identified and then stored to
    !! sub-meshes inside the trackers
    type(treelmesh_type), intent(in) :: tree
    !> Pointer from the global treeID list to the level-wise positions of the
    !! elements, optional due to harvester usage without levelwise information
    integer, optional, intent(in) :: levelPointer(:)
    !> Global solver information
    type(tem_solveHead_type ),intent(in) :: solver
    !> label for the different parts of the simulation (flow, particle ...)
    character(len=*), optional, intent(in) :: label
    !> solver-provided variable systems
    type(tem_var_system_type ) :: varSys
    !> The number of dofs for each scalar variable of the equation system
    integer, intent(in), optional :: nDofs
    !---------------------------------------------------------------------------
    integer :: iLog, iElem, nElems, elemPos
    type( tem_tracking_type ),allocatable :: tempTrack(:) !< temporary tracker array
!    integer :: iCell( globalMaxLevels )
    integer :: nTracks
    integer :: tLevel
    integer :: iError
    logical :: writeTreeToDisk
    ! Define limit for max number of tracking entities in ascii file
    integer, parameter :: nElemLimit_ascii = 200
    integer(kind=long_k) :: tTreeID !< temporary treeID
    type(tem_var_system_type), allocatable :: tmpSys(:)
    integer :: currentNDofs
    ! store levelwise information
    logical :: levelwise
    !--------------------------------------------------------------------------

    if(present(nDofs)) then
      currentNDofs = nDofs
    else
      currentNDofs = 1
    end if

    ! fill levelwise information
    if( present( levelPointer ))then
      levelwise = .true.
    else
      levelwise = .false.
    end if

    call tem_horizontalSpacer
    call tem_write('Setting up the tracking infrastructure')
    call tem_horizontalSpacer
    nTracks = 0

    ! Allocate the temporary track
    allocate( tempTrack(size(me)) )
    allocate( tmpSys(1) )

    if( tCtrl%active ) then
      do iLog = 1, size(me)
        call tem_write( 'Initializing tracking object ', iLog )
        if (present(label)) then
          call tem_write( ' which has the label '//trim(label))
        end if
        ! map variables
        call tem_var_intersect( systemA = me( iLog )%header%requestedSys,   &
          &                     systemB = varSys,                           &
          &                     resSys = me( iLog )%varSys,                 &
          &                     iError = iError,                            &
          &                     verbose = .false. )
        if( iError .gt. 0 ) then
          call tem_write(' Intersection was not entirely completed. ')
          call tem_write(' Continuing with partial variables...     ')
        end if
        ! Store solver tag in trackingHeader
        me( iLog )%header%solverTag = tem_solverTag( solver )

        !\todo: SZ: check wether the st_fun is defined (maybe luaPath???) if yes use
        !           st_fun%tree else use global tree
        !           what about multiple variables in me(ilog)%varSys????
        !-----------------------------------------------------------------------
        ! identify tracker elements
        !-----------------------------------------------------------------------
        call tem_create_subTree_of( inTree = tree,                             &
          &                         outTree = me( iLog )%tree,                 &
          &                         inShape = me( iLog )%header%geometry,      &
          &                         prefix = trim(me(iLog)%header%prefix)//    &
          &                                  trim( me(iLog)%header%label )//'_')

        ! get rid of the empty track in order to avoid empty writes to disk
        if ( me( iLog )%tree%nElems .gt. 0 .and. .not. me( iLog )%header%useGlobalMesh )then
          nTracks = nTracks + 1 !< Increase number of log

          ! Copy all entries from the log derived type to the temporary one.
          ! this might not work on all compilers!!
          tempTrack( nTracks ) = me( iLog )
          if( levelwise )then
            allocate( tempTrack( nTracks )%levelPointer( me( iLog )%tree%nElems ))
          end if

          if( levelwise )then
            ! Find the corresponding elements
            do iElem =1, me( iLog )%tree%nElems
              ! Find the position in the treeID list
              elemPos  = tem_PosOfId( me( iLog )%tree%treeID( iElem ), tree%treeID )
              ! Determine the level of the treeID
              tLevel = tem_levelOf( tree%treeID( elemPos ))
              ! Store the element position in the level-wise total list
              elemPos = levelPointer( elemPos )
              ! Create a reference treeID-sorted to the position in levelDesc%total
              temptrack( nTracks )%levelPointer( iElem ) = elemPos
            end do
          end if
        else if( me( iLog )%header%useGlobalMesh )then
          nTracks = nTracks + 1
          tempTrack( nTracks ) = me( iLog )
        end if
      end do  ! nTracks

      deallocate( me )
      allocate( me( nTracks ))


      do iLog = 1, nTracks
        ! Copy the stuff from the temporary track
        me( iLog ) = temptrack( iLog )

        !----------------------------------------------------------------------
        ! Initialize restart header and communicator
        ! the tem_tracking_header_Ascii needs initialized restart type
        !----------------------------------------------------------------------
        me( iLog )%restart%controller%writePrefix =                      &
          &     trim( me( iLog )%header%prefix )//                       &
          &     trim( me(iLog)%header%label )   //'_'

        ! this restart object is not meant to read data!
        me( iLog )%restart%controller%readRestart = .false.

        ! init the restart typed file format
        ! should be called when the first time the mesh is dumped
        ! Also init the communicator (copy from
        tmpsys(1) = me( iLog )%varSys
        if ( me( iLog )%header%useGlobalMesh ) then
          call tem_init_restart( me = me( iLog )%restart,  &
            &                    nSys = 1,                 &
            &                    varSys = tmpsys,          &
            &                    solver = solver,          &
            &                    tree = tree,              &
            &                    nDofs = currentNDofs      )

          ! Assign barycenters
          nElems = tree%nElems
          allocate( me( iLog )%bary( nElems, 3 ) )
          do iElem = 1, nElems
            tTreeID = tree%treeID( iElem )
            me(iLog)%bary( iElem, : ) = tem_BaryOfId( tree, tTreeID )
          end do
        else ! not use global mesh
          call tem_init_restart( me = me( iLog )%restart,  &
            &                    nSys = 1,                 &
            &                    varSys = tmpsys,          &
            &                    solver = solver,          &
            &                    tree = me( iLog )%tree,   &
            &                    nDofs = currentNDofs      )

          ! Assign barycenters
          nElems = me( iLog )%tree%nElems
          allocate( me( iLog )%bary( nElems, 3 ) )
          do iElem = 1, nElems
            tTreeID = me( iLog )%tree%treeID( iElem )
            me(iLog)%bary( iElem, : ) = tem_BaryOfId( me(iLog)%tree, tTreeID )
          end do
        end if ! useGlobalMesh

        ! Initialize reduction
        call tem_reduction_init( me( iLog )%reduce, me(iLog)%varSys )

        ! initialize transient reductions
        call tem_transient_reduction_init( me( iLog )%transientReduce, &
          &                       nElems, me(iLog)%varSys,             &
          &                       me( iLog )%header%timeControl%tMin )

        ! Is it only the root process of the tracking object who has to
        ! write to disk? this is (so far) only the case for spatial
        ! reductions
        me( iLog )%onlyRootDumps = me( iLog )%reduceActive

        ! Depending on the selected format, intitialize the files and headers
        select case( me( iLog )%header%fileformat )
        case( tem_trackingAsciiTransient )
          writeTreeToDisk = .false.
          ! Check if there are too many entries for an ascii line
          if( me( iLog )%tree%nElems*me(iLog)%varSys%nVars .gt. nElemLimit_ascii  &
            .and. .not. me( iLog )%reduceActive) then
            call tem_write('Error in tracking object ', iLog)
            call tem_write('There are n entities to track:', me( iLog )%tree%nElems * me(iLog)%varSys%nVars)
            call tem_write('Limit:                        ', nElemLimit_ascii )
            call tem_write('Error: Too many entries for the tracking entity as it is in ascii format')
            call tem_write('       All this information must be packed into one line.               ')
            call tem_write('Solution1: Use the Harvester format. It is way more efficient.           ')
            call tem_write('Solution2: reduce number of variables, number of elements(segments)      ')
            call tem_abort
          end if
          if( (me( iLog )%onlyRootDumps .and. me( iLog )%tree%global%myPart .eq. 0 ) &
             .or. .not. me( iLog )%onlyRootDumps ) then
            ! open ascii file transient output and write first line to define datas in the column
            call tem_tracking_open_AsciiTransient( me( iLog ), commGlob = process )
            ! Write the file headers
            call tem_tracking_header_Ascii( me = me( iLog ), commGlob = process, &
              &                             solver = solver, ssUnit = varSys%solSpecUnit )
          end if

        case( tem_trackingAsciiSpatial )
          writeTreeToDisk = .false.
          ! Write the file headers
          call tem_tracking_header_Ascii( me = me( iLog ), commGlob = process, &
            &                             solver = solver, ssUnit = varSys%solSpecUnit )

        case( tem_trackingHarvester )
          ! This should only occur, if really elements are here, and so I must be
          ! part of the communicator
          writeTreeToDisk = .not. me(iLog)%header%useGlobalMesh
          ! Prepare the solver specific information for the restart header file
        case( tem_trackingConvergence )
          writeTreetoDisk = .false.
        case default
          writeTreeToDisk = .false.
        end select

        if (writeTreeToDisk) then
          call dump_treelmesh( me( iLog )%tree )
        end if
      end do
    end if ! if tracking active

    deallocate( temptrack )
    deallocate(tmpsys)

  end subroutine tem_init_tracker
!******************************************************************************!


!******************************************************************************!
  !> close the ascii transient output unit
  !!
  subroutine tem_tracking_close_AsciiTransient( me )
    !--------------------------------------------------------------------------
    type(tem_tracking_type ), intent(inout) :: me      !< tracker object
    !local variable
    logical :: nUnitOpened

    ! check if tracking unit is open
    inquire( unit = me%header%unit, opened =  nUnitOpened )
    if ( nUnitOpened ) close( me%header%unit )

  end subroutine tem_tracking_close_AsciiTransient
!******************************************************************************!



!******************************************************************************!
  !> open the ascii transient output unit
  !!
  subroutine tem_tracking_open_AsciiTransient( me, commGlob )
    !---------------------------------------------------------------------------
    type(tem_tracking_type ), intent(inout) :: me      !< tracker object
    !> Global communicator type for global rank information
    type(tem_comm_env_type ), intent(in) :: commGlob
    !---------------------------------------------------------------------------
    character(len=254) :: logName
    character(len=1024)  :: buffer
    !---------------------------------------------------------------------------


    if ( me%tree%global%myPart .eq. 0 ) then
      write(buffer,'(i5.5)') commGlob%rank
       ! Include the rank name in the file name to avoid overwriting of files
       ! by different processes
      write(logName,'(a)') trim(me%header%prefix) &
         &                         //trim( me%header%label ) &
         &                         //'_p'//trim(buffer)//'.res'

      me%header%unit = newunit()
      open( unit=me%header%unit, file=trim(logName), position='append', &
        &status = 'replace' )

      write ( me%header%unit , '(a,i7)' ) &
       '# Rank of the process: ', commGlob%rank
      write( buffer, '(a)' ) '#'
      write( buffer, '(a,a19)' ) trim(buffer),'time'
      call tem_tracking_getHeader( me, buffer )
      ! ... and write the header row to the file
      write ( me%header%unit , '(a)' ) trim(buffer)
    end if

  end subroutine tem_tracking_open_AsciiTransient
!******************************************************************************!


!******************************************************************************!
  !> Write the header of the ascii tracking files
  !!
  !! This writes a header with detailed information into the ascii file for the
  !! defined tracking object it writes into the unit, which was opened before in
  !! \ref tem_init_tracker
  subroutine tem_tracking_header_Ascii( me, commGlob, solver, ssUnit )
    !--------------------------------------------------------------------------
    type(tem_tracking_type ), intent(inout) :: me      !< tracker object
    !> Global communicator type for global rank information
    type(tem_comm_env_type ), intent(in) :: commGlob
    !> Global solver information
    type(tem_solveHead_type ),intent(in) :: solver
    !> The solver specific unit
    integer, intent(in)                  :: ssUnit
    !--------------------------------------------------------------------------
    character(len=1024) :: logName
    type(aot_out_type) :: conf !< aotus lua state to write output
    character(len=1024)  :: buffer
    !--------------------------------------------------------------------------

    write( buffer, '(a)' ) trim(me%header%prefix)//trim(me%header%label)
    write(logName,'(a)') trim(buffer)//'.lua'

    write( buffer, '(a)' ) trim(buffer)//'_p*'

    if ( me%tree%global%myPart .eq. 0 ) then
      !! Write the header only on the root process
      !open up the mesh header lua file to dump the stuff using aotus library
      call aot_out_open( conf, logName )
      select case( me%header%fileformat)
        case( tem_trackingAsciiTransient )
          call aot_out_val( put_conf = conf, vname = 'format', val = 'AsciiTransient' )
        case( tem_trackingAsciiSpatial )
          call aot_out_val( put_conf = conf, vname = 'format', val = 'AsciiSpatial' )
      end select
      call aot_out_val( put_conf = conf, vname = 'solver', val = trim(me%header%solverTag) )
      call aot_out_val( put_conf = conf, vname = 'simname', val = trim(solver%simname) )
      call aot_out_val( put_conf = conf, vname = 'label', val = trim(me%header%label) )
      call aot_out_val( put_conf = conf, vname = 'prefix', val = trim(me%header%prefix) )
      call aot_out_val( put_conf = conf, vname = 'rank', val = commGlob%rank )
      call aot_out_val( put_conf = conf, vname = 'nprocs', val = commGlob%comm_size )
      call aot_out_val( put_conf = conf, vname = 'resultfile', val = trim(buffer) )
      call aot_out_open_table( put_conf = conf, tname = 'nElems')
!      do iLevel = 1, globalMaxLevels
!        if ( me%elems( iLevel )%nElems .gt. 0) then
!          call aot_out_open_table( put_conf = conf, tname = 'nElems')
!          call aot_out_val( put_conf = conf, val = me%elems(iLevel)%nElems )
!          call aot_out_val( put_conf = conf, vname = 'level', val = iLevel )
!          call aot_out_close_table( put_conf = conf )
!        end if
!      end do
      call aot_out_close_table( put_conf = conf )
      ! write timeControl info
      call tem_timeControl_out( me%header%timeControl, conf )
      ! write shapes
      call tem_shape_out( me%header%geometry, conf )
      ! write variable systems
      if ( ssUnit .ge. 0 ) then
        call tem_var_sys_out( me%varSys, conf, ssUnit )
      else
        call tem_var_sys_out( me%varSys, conf )
      end if
!      ! write solve specific info is already in restart header
!      if ( ssUnit .ge. 0 ) &
!        & call tem_writeSolverSpec( outUnit = conf%outUnit, &
!        &                           ssUnit = ssUnit)
      ! close aotus file
      call aot_out_close( conf )
    end if

  end subroutine tem_tracking_header_Ascii
!******************************************************************************!


!******************************************************************************!
  !> Write single log for the right scheme into its ascii file.
  !!
  subroutine tem_tracking_dumpAsciiTransient( me, chunk, nChunkElems, timing)
    !--------------------------------------------------------------------------
    type(tem_tracking_type ) :: me  !< the tracking log to dump to disk
    real(kind=rk)  :: chunk(:)
    integer, intent(in)   :: nChunkElems !< how many elements are in the chunk
    type(tem_time_type )  :: timing !< the current global time
    !--------------------------------------------------------------------------
    integer :: iElem, iScalar, nScalars
    character(len=4000) :: log_output !< output buffer
    !--------------------------------------------------------------------------


    if ( me%tree%global%myPart .eq. 0 ) then
  !    if( size( me%reduce ) .gt. 0 ) then
  !      call tem_reduction_toChunk( me%reduce, chunk, nChunkElems )
  !    end if
      nScalars = me%varSys%nScalars

      ! First assemble the complete row consisting of the time ...
      write( log_output, '(e20.8)' ) timing%rTime
      ! and all the scalars entries of the variable systems for each elements
      do iElem = 1, nChunkElems
        do iScalar = 1, nScalars
          write( log_output, '(a,e20.10)' ) trim(log_output), &
                 chunk( (iElem-1)*nScalars + iScalar )
        end do
      end do
      ! ... then write into the open ascii file
      write ( me%header%unit , '(a)' ) trim(log_output)
    end if

  end subroutine tem_tracking_dumpAsciiTransient
!******************************************************************************!


!******************************************************************************!
  !> Write a spatial representation for elements into an ascii tracking file
  !!
  !! Each time this routine is called, a new file is written
  !! Filename: {tracking_folder}{tracking_label}_spatial_{proc}_{timestamp}.res
  !!     e.g.: tracking/lineProbe_spatial_00001_01_01378.1.res
  !! Each process writes its own files
  !!
  subroutine tem_tracking_dumpAsciiSpatial( me, commGlob, solver, chunk, nChunkElems, timing)
    !--------------------------------------------------------------------------
    type(tem_tracking_type ), intent(inout) :: me !< tracking lgo to write to disk
    type(tem_solveHead_type ), intent(in) :: solver !< solver information
    !> Global communicator type for global rank information
    type(tem_comm_env_type ), intent(in) :: commGlob
    real(kind=rk)  :: chunk(:)
    integer, intent(in)   :: nChunkElems !< how many elements are in the chunk
    type(tem_time_type ), intent(in)  :: timing !< the current global time
    !--------------------------------------------------------------------------
    integer :: iElem
    integer :: iScalar, nScalars
    character(len=pathLen)  :: logName  !< ascii file name
    character(len=1024)  :: buffer
    character(len=labelLen) :: timestamp
    !--------------------------------------------------------------------------
    nScalars = me%varSys%nScalars
    ! Write the rank into the string buffer
    write(buffer,'(i5.5)') commGlob%rank

    timestamp = tem_generate_timeStamp( timing )

    ! Generate ascii file name
    write(logName,'(a)') trim(me%header%prefix)//trim( me%header%label )//&
      &         '_p'//trim(buffer)//'_t'//trim(timestamp)//'.res'
    me%header%unit = newunit()
    open( unit=me%header%unit, file=trim(logName), recl=1024, &
      &status = 'replace' )

    ! First write the header
    write ( me%header%unit , '(a,i7)' ) &
     '# Rank of the process: ', commGlob%rank
    write ( buffer, '(a)' ) '#         coordX          coordY          coordZ'
    call tem_tracking_getHeader( me, buffer )
    ! ... and write the header row to the file
    write ( me%header%unit , '(a)' ) trim(buffer)

    ! Then gather contents into buffer, and write buffer to file
    do iElem = 1, nChunkElems
      write( buffer, '(3e16.8)' ) me%bary(iElem, 1:3)
      do iScalar = 1, nScalars
        write( buffer, '(a,e20.12)' ) trim(buffer), &
             chunk( (iElem-1)*nScalars + iScalar )
      end do
      write ( me%header%unit , '(a)' ) trim(buffer)
    end do

    close( unit=me%header%unit)

  end subroutine tem_tracking_dumpAsciiSpatial
!******************************************************************************!


!******************************************************************************!
  !> This routine write a variable labels into buffer
  !! and this buffer is written into ascii result header for for spatial and
  !! transient
  subroutine tem_tracking_getHeader( me, buffer )
    type(tem_tracking_type ), intent(inout) :: me !< tracking lgo to write to disk
    character(len=*), intent(inout)  :: buffer !< buffer contains first column of the header
    !local variable
    character(len=pathLen)  :: buffer2
    integer :: iVar, iComp
    character(len=4)  :: reduceChar

    if( size( me%reduce ) .gt. 0 ) then
      reduceChar = '_red'
    else
      reduceChar = ''
    end if
    do iVar = 1, me%varSys%nVars
      if ( me%varSys%Variable%val( iVar )%nComponents .gt. 1 ) then
        do iComp = 1, me%varSys%Variable%val( iVar )%nComponents
          write( buffer2, '(3a,i2.2)' ) trim(me%varSys%Variable%val( iVar )%label)&
              & ,trim(reduceChar)  &
              & ,'_',iComp
          write( buffer, '(a,a20)' ) trim(buffer), trim(buffer2)
        end do
      else
        write(buffer, '(a,a20,a,a4)') trim(buffer), &
          &                    trim(me%varSys%Variable%val( iVar )%label), &
          &                    trim(reduceChar)
      end if
    end do

  end subroutine tem_tracking_getHeader
!******************************************************************************!


!******************************************************************************!
  !> Close all the units of the tracking objects
  !!
  subroutine tem_tracking_finalize( me )
    !---------------------------------------------------------------------------
    type(tem_tracking_type ), intent(inout) :: me(:) !< tracker object to close
    !---------------------------------------------------------------------------
    integer :: iTrack
    !---------------------------------------------------------------------------

    do iTrack = 1, size(me)
      ! Close solver specific units
      call tem_unit_close( me( iTrack )%header%unit )
      ! finalize the restart for harvester output
      if( me( iTrack )%header%fileformat .eq. tem_trackingHarvester )then
        call tem_restart_finalize( me( iTrack )%restart )
      end if
    end do

  end subroutine tem_tracking_finalize
!******************************************************************************!


!******************************************************************************!
  !> Linearize the information from file into a single string.
  !!
  subroutine tem_transform_solSpecChar( spc_unit, string )
    !---------------------------------------------------------------------------
    integer, intent(in) :: spc_unit
    character(len=*) :: string
    !---------------------------------------------------------------------------
    integer :: old_pos, length
    integer :: io
    logical :: nUnitOpened
    character(len=PathLen) :: loc_string
    !---------------------------------------------------------------------------
    string = ' '
    inquire(unit= spc_unit, opened=nUnitOpened)
    if (nUnitOpened) then
      ! Go to the start of the scratch file.
      rewind(spc_unit)
      old_pos = 0
      do
        ! Read all contents of the scratch file until eof is encountered
        read(spc_unit, '(a)', iostat=io) loc_string

        if ( io .eq. 0 ) then
          length = LEN_TRIM(loc_string)
          string( old_pos+1 : old_pos+length) = trim(loc_string)
          old_pos = old_pos+length
        else
          ! Reached end of the file, exit the loop.
          exit
        end if
      end do
    else
      call tem_write(' WARNING: no solver specific unit was opened before!')
      call tem_write('          Restart header file might be incomplete   ')
    end if

  end subroutine tem_transform_solSpecChar
!******************************************************************************!


end module tem_tracking_module
!******************************************************************************!
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.