-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreduce_snapshots.cpp
More file actions
2268 lines (2144 loc) · 93.4 KB
/
reduce_snapshots.cpp
File metadata and controls
2268 lines (2144 loc) · 93.4 KB
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
/**
* @file reduce_snapshots.cpp
*
* @brief Program that takes a SOAP halo catalogue and a SWIFT snapshot and
* creates a new (SWIFT compatible) snapshot that only contains the particles
* that are part of spherical overdensities (SOs) of the flagged halos.
*
* Compilation requires MPI (any version) and HDF5 (>1.10.0).
* Example compilation commands:
* - on Ubuntu 18.04):
* mpic++ -Wall -Werror -fopenmp -O3 -I/usr/include/hdf5/serial \
* -o reduce_snapshots reduce_snapshots.cpp \
* -L/usr/lib/x86_64-linux-gnu/hdf5/serial -lhdf5
* - on cosma:
* module load intel_comp/2020-update2 \
* intel_mpi/2020-update2 \
* parallel_hdf5/1.10.6 gsl/2.5
* mpiicpc -O3 -qopenmp -qoverride-limits \
* -I/cosma/local/parallel-hdf5//intel_2020-update2_intel_mpi_2020-update2/1.10.6/include
* \
* -o reduce_snapshots reduce_snapshots.cpp \
* -L/cosma/local/parallel-hdf5//intel_2020-update2_intel_mpi_2020-update2/1.10.6/lib
* \
* -Wl,-rpath=/cosma/local/parallel-hdf5//intel_2020-update2_intel_mpi_2020-update2/1.10.6/lib
* \ -lhdf5
*
* Example run command:
* mpirun -np 16 ./reduce_snapshots halos_0008 flamingo_0008/flamingo_0008 \
* test_0008 SO/50_crit/SORadius 512
* Where all arguments are positional and:
* - halos_0008 is the prefix for the halo catalogue files
* (we require halos_0008.siminfo, halos_0008.properties[.*],
* halos_0008.catalog_SOlist[.*])
* - flamingo_0008/flamingo_0008 is the prefix for a (distributed) SWIFT
* snapshot file (we require at least flamingo_0008/flamingo_0008.hdf5)
* - test_0008 is the prefix for the output snapshot files
* (we will create the same number of files as the input files, using the
* same indices if it is a distributed snapshot file)
* - SO_R_100_rhocrit is the radius used to determine if a particle belongs to
* an SO.
* - 512 is the number of SWIFT top-level cells that are processed in one go.
* This should be a proper divisor of the total number of top-level cells
* (an error is thrown if this is not the case). A larger number leads to
* more memory usage and more complex table lookup operations. A lower
* number leads to more frequent disk reads and less continguous OpenMP
* parallel regions. If you can afford it memory-wise, a larger number will
* lead to better performance.
*
* Additional optional arguments:
* - HDF5 BLOCK SIZE: Maximum size (in bytes) that can be read while copying
* datasets from the original snapshot to the new file. A larger number
* uses more memory. The default is to read entire datasets. Note that
* applying a low limit here can lead to significant changes in dataset
* values if lossy compression is used, since the compression is applied
* on the individual chunks.
*
* @author Bert Vandenbroucke (vandenbroucke@strw.leidenuniv.nl)
* @author Rob McGibbon (mcgibbon@strw.leidenuniv.nl)
*/
// local includes:
// - custom error messages and assertions
#include "Error.hpp"
// - custom HDF5 library wrappers
#include "HDF5.hpp"
// standard includes
#include <algorithm>
#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <experimental/filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <mpi.h>
#include <numeric>
#include <sstream>
#include <string>
#include <sys/time.h>
#include <tuple>
#include <vector>
// we expose all HDF5 functions
using namespace HDF5;
namespace fs = std::experimental::filesystem;
// Available log levels:
// - output log messages from innermost loops
#define LOGLEVEL_FILELOOPS 2
// - output log messages from first level loops
#define LOGLEVEL_CHUNKLOOPS 1
// - only output general progress messages
#define LOGLEVEL_GENERAL 0
// set the log level for output
// a higher value means more output
#define LOG_LEVEL 1
// uncomment this to output detailed memory logs
//#define OUTPUT_MEMORY_LOG
/**
* @brief Simple execution timer used to display program progress.
*/
class Timer {
private:
/*! @brief Start time of the timer. */
timeval _start;
public:
/**
* @brief Start the timer.
*/
inline void start() { gettimeofday(&_start, nullptr); }
/**
* @brief Constructor.
*
* Starts the timer.
*/
inline Timer() { start(); }
/**
* @brief Get the current running time of the timer.
*
* @return Time since the timer was (last) started (in s).
*/
inline double current_time() {
timeval stop;
gettimeofday(&stop, nullptr);
timeval result;
timersub(&stop, &_start, &result);
return result.tv_sec + 1.e-6 * result.tv_usec;
}
};
// global timer (made global so that we can display progress messages from
// anywhere within the program)
Timer global_timer;
// global MPI control variables (global so that they can be displayed from
// anywhere within the program)
int MPI_rank, MPI_size;
/**
* @brief Write a progress message to the stderr.
*
* The message will include the current program run time (in seconds), the rank
* of the MPI process that writes and the location of the line that called the
* macro.
*
* @param s Message string (can contain format characters, like printf()).
* @param ... Additional arguments passed on to printf() (should match the
* format specifiers).
*/
#define timelog(level, s, ...) \
{ \
if (level <= LOG_LEVEL) { \
FILE *handle = (LOG_LEVEL == 0) ? stdout : stderr; \
fprintf(handle, "[%9.4f] [%3i]", global_timer.current_time(), MPI_rank); \
fprintf(handle, "%s:%s():%i: ", __FILE__, __FUNCTION__, __LINE__); \
fprintf(handle, s "\n", ##__VA_ARGS__); \
} \
}
/**
* @brief Find a file composed of a prefix, a name and a suffix and containing
* an optional index number.
*
* With prefix = "A", name = "B", suffix = ".C" and index = 1, the function
* will look for the following files:
* - regular file: AB.C
* - indexed file: AB.1.C
* (note that the index is always preceded by a '.').
* If none of these files are found, an error is thrown. In other cases, the
* behaviour depends on the values of the arguments only_one and use_index:
* - only_one = true, use_index = true (default): if both files exist, an
* error is thrown. If only one of them exists, then the name of the
* existing file is returned.
* - only_one = false, use_index = true: the name of the distributed file is
* returned if it exists, otherwise the name of the regular file is
* returned.
* - use_index = false: the name of the regular file is returned if it exists,
* an error is thrown if it does not. The distributed file is ignored.
*
* Note that the prefix and name are always combined in the same way. The only
* reason they are provided as separate arguments is to make it easier to
* compose filenames where the prefix and name are constructed in different
* ways.
*
* @param prefix File prefix.
* @param name File name.
* @param suffix File suffix (default: "").
* @param index File index (default: 0).
* @param only_one Require only one of the possible file matches to be present
* (default: yes - see above).
* @param use_index False if the index can be ignored; we only care about one
* of the possible file matches (default: true - see above).
* @return File name. The file will have been successfully opened, meaning it
* should exist.
*/
inline std::string find_file(const std::string prefix, const std::string name,
const std::string suffix = "",
const int_fast32_t index = 0,
const bool only_one = true,
const bool use_index = true) {
std::stringstream filename;
filename << prefix << name << suffix;
std::ifstream file(filename.str().c_str());
std::string non_distributed;
if (file.good()) {
non_distributed = filename.str();
file.close();
}
if (!use_index) {
// we explicitly ask for the non-distributed file (might be a virtual file)
if (non_distributed.size() == 0) {
my_error("Unable to find \"%s%s%s\"!", prefix.c_str(), name.c_str(),
suffix.c_str());
}
return non_distributed;
}
std::string distributed;
filename.str("");
filename << prefix << name << "." << index << suffix;
file.open(filename.str().c_str());
if (file.good()) {
distributed = filename.str();
file.close();
}
if (distributed.size() == 0 && non_distributed.size() == 0) {
my_error("Unable to find \"%s%s%s\" or \"%s%s.%" PRIiFAST32 "%s\"!",
prefix.c_str(), name.c_str(), suffix.c_str(), prefix.c_str(),
name.c_str(), index, suffix.c_str());
} else {
if (only_one && distributed.size() > 0 && non_distributed.size() > 0) {
my_error("Found both \"%s%s%s\" and \"%s%s.%" PRIiFAST32 "%s\"!",
prefix.c_str(), name.c_str(), suffix.c_str(), prefix.c_str(),
name.c_str(), index, suffix.c_str());
}
}
// if both files exist, we favour the distributed one (unless only_one is set,
// in which case we already threw an error)
return (distributed.size() > 0) ? distributed : non_distributed;
}
/**
* @brief Expand a dataset path into a list of groups and the dataset name.
*
* E.g. "path/to/dataset" --> (["path, "to"], "dataset")
* "dataset" --> ([], "dataset")
*
* @param path Full path to the dataset.
* @return std::pair containing a std::vector with all groups in the path,
* and the name of the dataset.
*/
inline std::pair<std::vector<std::string>, std::string>
decompose_dataset_path(const std::string path) {
size_t prevpos = 0;
size_t pos = path.find("/");
std::vector<std::string> full_path;
while (pos != std::string::npos) {
const std::string path_part = path.substr(prevpos, pos - prevpos);
full_path.push_back(path_part);
prevpos = pos + 1;
pos = path.find("/", prevpos);
}
const std::string dset_name = path.substr(prevpos, pos);
return std::make_pair(full_path, dset_name);
}
/**
* @brief Compose a file name using the given prefix and suffix and an optional
* additional index.
*
* If prefix = "A", suffix = ".B" and index = 1, this function returns
* - "A.B" if use_index is false (default)
* - "A.1.B" if use_index is true
* (note that the index is always preceded by a '.').
*
* If use_index is false, an index value other than 0 will lead to an error.
*
* @param prefix File name prefix.
* @param suffix File name suffix.
* @param index Optional index (default: 0).
* @param use_index Whether or not to use the index (default: no).
* @return Full composed file name.
*/
inline std::string compose_filename(const std::string prefix,
const std::string suffix,
const int_fast32_t index = 0,
const bool use_index = false) {
std::stringstream filename;
// sanity check: if we set the index to something other than 0, we probably
// intend to use it
if (!use_index && index > 0) {
my_error("Cannot create a file with index %" PRIiFAST32
" when use_index is disabled!",
index);
}
if (use_index) {
filename << prefix << "." << index << suffix;
} else {
filename << prefix << suffix;
}
return filename.str();
}
/**
* @brief Convert a size in bytes to something a human understands.
*
* This function is limited to a size of 16 EB, since that is the largest value
* that fits in a size_t.
*
* @param size Size in bytes.
* @return String representation of the size with two digit precision and the
* closest smaller human-readable unit.
*/
inline std::string human_readable_bytes(size_t size) {
const std::string units[7] = {"bytes", "KB", "MB", "GB", "TB", "PB", "EB"};
double floatsize = size;
int_fast8_t iu = 0;
// we don't go beyond EB, since 16 EB is the maximum size_t
while (iu < 7 && size > 0) {
floatsize /= 1024.;
size >>= 10;
++iu;
}
// correct for the overshoot
--iu;
floatsize *= 1024.;
char sizestr[100];
sprintf(sizestr, "%.2f %s", floatsize, units[iu].c_str());
return std::string(sizestr);
}
/**
* @brief Utility class used to keep track of memory usage.
*
* The memory log file is a hierarchical structure consisting of at least a root
* level group. Each group in this hierarchy can contain multiple other groups
* and individual memory allocation entries. These are all written to a text
* file. Groups can have two types: a normal group simply accumulates memory
* allocations for its elements. A "loop scope" group instead assumes only one
* of its elements is contained in memory at the same time and reports the
* maximum along its elements as memory usage.
*
* Internally, groups are represented by a MemoryLogBlock. No MemoryLogBlocks
* are actually stored within the MemoryLog. Upon creation, the MemoryLog will
* store an entry marking the MemoryLogBlock, while the MemoryLogBlock stores
* the information required to link its elements in the log file. All access
* to the MemoryLog should happen through the MemoryLogBlocks.
*
* As an example, the following code:
* int main(){
* MemoryLog mlog(100);
* auto mroot = mlog.get_root();
*
* std::vector<double> a(400);
* mroot.add_entry("a", a);
* mroot.add_entry("random size", 100);
*
* auto mloop = mroot.add_loop_scope("loop");
* for(int i = 0; i < 4; ++i){
* std::vector<double> b(100);
* auto mloopit = mloop.add_block("iteration");
* mloopit.add_entry("b", b);
* };
*
* mlog.dump("test.txt");
*
* return 0;
* }
* will produce the following memory log (test.txt):
* # type name size (bytes) parent
* g Root 0 0
* e a 3200 0
* e random size 100 0
* l loop 0 0
* g iteration 0 3
* e b 400 4
* g iteration 0 3
* e b 400 6
* g iteration 0 3
* e b 400 8
* g iteration 0 3
* e b 400 10
* Which corresponds to the following hierarchy:
* - Root:
* - a: 3200
* - random size: 100
* - loop:
* - iteration:
* - b: 400
* - iteration:
* - b: 400
* - iteration:
* - b: 400
* - iteration:
* - b: 400
* When analysed with the appropriate Python script, the total memory size will
* be found to be 3200 + 100 + 400.
*/
class MemoryLog {
public:
// forward declaration of the member class
class MemoryLogBlock;
private:
/*! @brief Lines in the log. Each line consists of a type char, a name string
* a size entry and a parent reference. The parent reference should refer
* to another line in the log. */
std::vector<std::tuple<char, std::string, size_t, size_t>> _log;
/*! @brief Next available entry in the log. The log is preallocated to
* minimise reallocations, so that we have to store the current index
* separately. */
size_t _next_entry;
/**
* @brief Add an entry to the log.
*
* @param type Type of the entry (currently accepted: 'e', 'g', 'l').
* @param name Name used to identify the entry. Spaces in the name will be
* replaced by '_'.
* @param size Size (in bytes) that should be logged.
* @param parent Line on which the entry for the parent group was made.
*/
inline size_t add_entry(const char type, const std::string name,
const size_t size, const size_t parent) {
// check if we need to grow the log
if (_next_entry == _log.size()) {
_log.resize(2 * _log.size());
}
std::string name_nospace(name);
// replace whitespaces in the name with '_' (to help numpy.loadtxt)
std::transform(name_nospace.begin(), name_nospace.end(),
name_nospace.begin(),
[](char c) { return (c == ' ') ? '_' : c; });
// create the entry
std::get<0>(_log[_next_entry]) = type;
std::get<1>(_log[_next_entry]) = name_nospace;
std::get<2>(_log[_next_entry]) = size;
std::get<3>(_log[_next_entry]) = parent;
// update the current index
++_next_entry;
// return the line on which this entry was made (used for group references)
return _next_entry - 1;
}
public:
/**
* @brief Constructor.
*
* @param initial_size Initial size of the log. Should be sensible to avoid
* having to grow the log all the time.
*/
MemoryLog(const size_t initial_size)
: _log(initial_size > 0 ? initial_size : 1), _next_entry(0) {
add_entry('g', "Root", 0, 0);
}
/**
* @brief Dump the log to a file with the given name.
*
* @param filename Output file name.
*/
inline void dump(const std::string filename) {
std::ofstream ofile(filename.c_str());
ofile << "# type\tname\tsize (bytes)\tparent\n";
for (size_t i = 0; i < _next_entry; ++i) {
char type;
std::string name;
size_t size, parent;
std::tie(type, name, size, parent) = _log[i];
ofile << type << "\t" << name << "\t" << size << "\t" << parent << "\n";
}
}
/**
* @brief Block (group) in the memory log.
*
* A block acts as an external gateway into the log. Upon creation, it adds
* an appropriate entry in the log. Whenever an entry is made in the block,
* the block appropriately links that entry to its own entry by setting the
* correct parent index. New levels in the hierarchy can be created by
* adding child blocks to the block.
*/
class MemoryLogBlock {
private:
/*! @brief Reference to the MemoryLog. */
MemoryLog &_log;
/*! @brief Line on which the block entry was made in the log. This number
* is used as parent index for all child entries. */
const size_t _line;
public:
/**
* @brief Constructor.
*
* @param log Reference to the MemoryLog.
* @param line Line on which the block entry was made in the log.
*/
inline MemoryLogBlock(MemoryLog &log, const size_t line)
: _log(log), _line(line) {}
/**
* @brief Add a child block to this block.
*
* @param name Name of the block in the log file.
* @return New MemoryLogBlock representing the new block.
*/
inline MemoryLogBlock add_block(const std::string name) {
const size_t line = _log.add_entry('g', name, 0, _line);
return MemoryLogBlock(_log, line);
}
/**
* @brief Add a child "loop scope" block to this block.
*
* @param name Name of the block in the log file.
* @return New MemoryLogBlock representing the new block.
*/
inline MemoryLogBlock add_loop_scope(const std::string name) {
const size_t line = _log.add_entry('l', name, 0, _line);
return MemoryLogBlock(_log, line);
}
/**
* @brief Log the memory used by a vector.
*
* @tparam _type_ Variable type stored in the vector.
* @param name Name of the entry in the log file.
* @param v Reference to the vector.
*/
template <typename _type_>
inline void add_entry(const std::string name,
const std::vector<_type_> &v) {
const size_t size = sizeof(_type_) * v.size();
_log.add_entry('e', name, size, _line);
}
/**
* @brief Log the memory used by a multimap.
*
* @tparam _type_A_ Type of the keys in the multimap.
* @tparam _type_B_ Type of the values in the multimap.
* @param name Name of the entry in the log file.
* @param mm Reference to the multimap.
*/
template <typename _type_A_, typename _type_B_>
inline void add_entry(const std::string name,
const std::multimap<_type_A_, _type_B_> &mm) {
const size_t size = (sizeof(_type_A_) + sizeof(_type_B_)) * mm.size();
_log.add_entry('e', name, size, _line);
}
/**
* @brief Log a custom memory size in the log.
*
* @param name Name of the entry in the log file.
* @param size Size (in bytes) that needs to be logged.
*/
inline void add_entry(const std::string name, const size_t size) {
_log.add_entry('e', name, size, _line);
}
};
/**
* @brief Get the MemoryLogBlock that represents the root of the log.
*
* Since MemoryLogBlocks are not actually stored in the MemoryLog, every
* call to this function will return a different object. All objects will
* however behave exactly the same as far as the log file hierarchy is
* concerned.
*
* @return Root of the log.
*/
inline MemoryLogBlock get_root() { return MemoryLogBlock(*this, 0); }
};
/**
* @brief Internal representation of the SOs contained in a SOAP halo catalogue.
*
* Upon creation, the SOTable object will read the relevant SOAP catalogue files
* and store all the information that is required for later access. To minimise
* memory usage, only SOs that are filtered out are kept in memory.
*
*/
class SOTable {
private:
/*! @brief SO coordinates: x. */
std::vector<double> _XSO;
/*! @brief SO coordinates: y. */
std::vector<double> _YSO;
/*! @brief SO coordinates: z. */
std::vector<double> _ZSO;
/*! @brief SO radii. */
std::vector<double> _RSO;
/*! @brief IDs of the halos. */
std::vector<uint64_t> _haloIDs;
/*! @brief Offsets of the distributed files in the total SO property
* arrays. */
std::vector<size_t> _file_boundaries;
/// Catalogue stats
/*! @brief Number of halos which are kept. */
size_t _Nkeep;
/*! @brief Number of halos in the catalogue (_Nkeep <= _Nhalo). */
size_t _Nhalo;
/*! @brief Prefix of the catalogue file names. */
const std::string _prefix;
public:
/**
* @brief Constructor.
*
* Does the full parsing of the SOAP catalogue and can therefore require quite
* some time and memory.
*
* @param prefix Prefix of the catalogue file names. We require the following
* files to be present: prefix.properties[.*], prefix.siminfo,
* prefix.catalog_SOlist[.*].
* @param radius_selection_name Name of the array in the .properties file that
* will be used for spatial particle filtering. Ideally, this name would
* match SO_R_XXX_rhocrit, where XXX is the value of the VR configuration
* variable Overdensity_output_maximum_radius_in_critical_density. But again,
* any possible valid array would work (including those that do not represent
* any radius at all, so be careful - again!).
* @param keep_selection_name Name of the array in the .properties file that
* will be used to determine which halos to keep
* @param memory MemoryLogBlock used to log memory usage.
*/
SOTable(const std::string prefix, const std::string radius_selection_name,
const std::string keep_selection_name,
MemoryLog::MemoryLogBlock &memory)
: _prefix(prefix) {
timelog(LOGLEVEL_GENERAL, "Reading SOAP catalog...");
const std::string first_catalog_file = find_file(prefix, "");
// find out number of files
HDF5FileOrGroup file = OpenFile(first_catalog_file, HDF5FileModeRead);
const int32_t num_of_files = 1;
HDF5FileOrGroup halogroup = OpenGroup(file, "InputHalos");
const uint64_t refTotNhalo = GetDatasetSize(halogroup, "HaloCatalogueIndex");
CloseGroup(halogroup);
HDF5FileOrGroup cosmogroup = OpenGroup(file, "Cosmology");
double raw_scale_factor[1];
ReadArrayAttribute(cosmogroup, "Scale-factor", raw_scale_factor);
const double scale_factor = raw_scale_factor[0];
CloseGroup(cosmogroup);
CloseFile(file);
if (MPI_rank == 0) {
timelog(LOGLEVEL_GENERAL,
"Found %zu halos in %i file(s). Scale factor is %g.", refTotNhalo,
num_of_files, scale_factor);
}
// read all the SO files and collect general catalogue statistics
_Nhalo = 0;
_Nkeep = 0;
// file offsets used for various purposes
// the bookkeeping in the loop is quite tedious!
size_t keep_file_offset = 0;
// register a loop scope in the memory log
auto memory_ifile_loop = memory.add_loop_scope("File loop");
for (int32_t ifile = 0; ifile < num_of_files; ++ifile) {
// find the appropriate part of the catalogue
const std::string catalog_file = find_file(prefix, "", "", ifile);
HDF5FileOrGroup file = OpenFile(catalog_file, HDF5FileModeRead);
// create a memory group for this iteration in the log
std::stringstream ifilename;
ifilename << "File" << ifile;
auto memory_ifile = memory_ifile_loop.add_block(ifilename.str());
// find out how many halos we are dealing with in this file
const uint64_t num_of_groups = refTotNhalo;
_Nhalo += num_of_groups;
// now read all the relevant halo properties
// we first read the entire file and then copy the appropriate bits
// into the class arrays
std::vector<int32_t> is_central(num_of_groups);
std::vector<double> XSO(num_of_groups);
std::vector<double> YSO(num_of_groups);
std::vector<double> ZSO(num_of_groups);
std::vector<double> CofP(3 * num_of_groups);
std::vector<double> RSO(num_of_groups);
std::vector<uint64_t> haloIDs(num_of_groups);
std::vector<int> keep(num_of_groups, false);
double unit_length_in_cgs;
{
HDF5FileOrGroup units = OpenGroup(file, "Units");
double temp[1];
ReadArrayAttribute(units, "Unit length in cgs (U_L)", temp);
unit_length_in_cgs = temp[0];
CloseGroup(units);
}
halogroup = OpenGroup(file, "InputHalos");
ReadEntireDataset(halogroup, "IsCentral", is_central);
ReadEntireDataset(halogroup, "HaloCatalogueIndex", haloIDs);
ReadEntireDataset(halogroup, "HaloCentre", CofP);
{
// A conversion factor is needed because SOAP can be set to output in physical units
double cgs_factor[1];
HDF5FileOrGroup dset = OpenDataset(halogroup, "HaloCentre");
ReadArrayAttribute(
dset,
"Conversion factor to physical CGS (including cosmological corrections)",
cgs_factor);
CloseDataset(dset);
const double conversion_factor = cgs_factor[0] / unit_length_in_cgs;
for (size_t ihalo = 0; ihalo < num_of_groups; ++ihalo) {
CofP[3 * ihalo] *= conversion_factor;
CofP[3 * ihalo + 1] *= conversion_factor;
CofP[3 * ihalo + 2] *= conversion_factor;
}
}
CloseGroup(halogroup);
for (size_t ihalo = 0; ihalo < num_of_groups; ++ihalo) {
XSO[ihalo] = CofP[3 * ihalo];
YSO[ihalo] = CofP[3 * ihalo + 1];
ZSO[ihalo] = CofP[3 * ihalo + 2];
}
CofP.clear();
if (keep_selection_name == "SOAP/IncludedInReducedSnapshot") {
HDF5FileOrGroup SOAPgroup = OpenGroup(file, "SOAP");
ReadEntireDataset(SOAPgroup, "IncludedInReducedSnapshot", keep);
} else if (keep_selection_name == "InputHalos/IsCentral") {
HDF5FileOrGroup SOAPgroup = OpenGroup(file, "InputHalos");
ReadEntireDataset(SOAPgroup, "IsCentral", keep);
} else {
my_error("Invalid keep_selection_name");
}
{
const auto radius_path = decompose_dataset_path(radius_selection_name);
const auto group_names = radius_path.first;
const auto radius_name = radius_path.second;
HDF5FileOrGroup parent_group = file;
std::vector<HDF5FileOrGroup> groups(group_names.size());
for (uint_fast32_t igroup = 0; igroup < group_names.size(); ++igroup) {
groups[igroup] = OpenGroup(parent_group, group_names[igroup]);
parent_group = groups[igroup];
}
ReadEntireDataset(parent_group, radius_name, RSO);
// A conversion factor is needed because SOAP can be set to output in physical units
double cgs_factor[1];
HDF5FileOrGroup dset = OpenDataset(parent_group, radius_name);
ReadArrayAttribute(
dset,
"Conversion factor to physical CGS (including cosmological corrections)",
cgs_factor);
CloseDataset(dset);
for (uint_fast32_t igroup = 0; igroup < group_names.size(); ++igroup) {
CloseGroup(groups[igroup]);
}
const double conversion_factor = cgs_factor[0] / unit_length_in_cgs;
for (size_t ihalo = 0; ihalo < num_of_groups; ++ihalo) {
RSO[ihalo] *= conversion_factor;
}
}
// we are done with the file, close it
CloseFile(file);
// report on memory usage
memory_ifile.add_entry("is_central", is_central);
memory_ifile.add_entry("XSO", XSO);
memory_ifile.add_entry("YSO", YSO);
memory_ifile.add_entry("ZSO", ZSO);
memory_ifile.add_entry("RSO", RSO);
memory_ifile.add_entry("haloIDs", haloIDs);
memory_ifile.add_entry("keep", keep);
// Count how many halos we are keeping
uint64_t this_Nkeep = 0;
for (size_t ih = 0; ih < num_of_groups; ++ih) {
if (keep[ih] == 1) {
if (RSO[ih] > 0) {
++this_Nkeep;
} else {
if (MPI_rank == 0) {
timelog(LOGLEVEL_GENERAL,
"Wrong RSO (%g) for halo %zu (halo catalogue index %zu)!",
RSO[ih], ih, haloIDs[ih]);
}
}
}
}
// update the catalogue stats
_Nkeep += this_Nkeep;
// now that we know the size of this file, we can reallocate the class
// arrays
_XSO.resize(keep_file_offset + this_Nkeep, 0.);
_YSO.resize(keep_file_offset + this_Nkeep, 0.);
_ZSO.resize(keep_file_offset + this_Nkeep, 0.);
_RSO.resize(keep_file_offset + this_Nkeep, 0.);
_haloIDs.resize(keep_file_offset + this_Nkeep, 0);
// copy the relevant SO properties
size_t ikeep = 0;
for (size_t ih = 0; ih < num_of_groups; ++ih) {
if (keep[ih] == 1 && RSO[ih] > 0.) {
// convert distances from physical to co-moving
// we need to do this because SWIFT outputs co-moving quantities
_XSO[keep_file_offset + ikeep] = XSO[ih] / scale_factor;
_YSO[keep_file_offset + ikeep] = YSO[ih] / scale_factor;
_ZSO[keep_file_offset + ikeep] = ZSO[ih] / scale_factor;
_RSO[keep_file_offset + ikeep] = RSO[ih] / scale_factor;
_haloIDs[keep_file_offset + ikeep] = haloIDs[ih];
++ikeep;
}
}
keep_file_offset += ikeep;
}
if (MPI_rank == 0) {
timelog(LOGLEVEL_GENERAL, "Stats: totNhalo: %zu, totNkeep: %zu", _Nhalo, _Nkeep);
}
timelog(LOGLEVEL_GENERAL, "Done reading SOAP catalog.");
my_assert(_Nkeep == _XSO.size(), "Size mismatch!");
my_assert(_Nkeep == _YSO.size(), "Size mismatch!");
my_assert(_Nkeep == _ZSO.size(), "Size mismatch!");
my_assert(_Nkeep == _RSO.size(), "Size mismatch!");
my_assert(_Nkeep == _haloIDs.size(), "Size mismatch!");
// log the class arrays in the memory log, now that their sizes are final
memory.add_entry("SO x position", _XSO);
memory.add_entry("SO y position", _YSO);
memory.add_entry("SO z position", _ZSO);
memory.add_entry("SO radii", _RSO);
memory.add_entry("SO halo IDs", _haloIDs);
}
/**
* @brief Get the total number of halos in the catalogue.
*
* @return Total number of halos, including subhalos.
*/
inline size_t number_of_halos() const { return _Nhalo; }
/**
* @brief Get the total number of halos that are retained
*
* Properties for retained SOs can be queried using the approperiate functions
* and an index in the range [0, number_to_keep()].
*
* @return Number of SOs actually stored in the SOTable.
*/
inline size_t number_to_keep() const { return _Nkeep; }
/**
* @brief Get the x position of an SO.
*
* @param index SO index in the range [0, number_to_keep()].
* @return X position of that SO, in co-moving VR distance units (Mpc).
*/
inline double XSO(const size_t index) const { return _XSO[index]; }
/**
* @brief Get the y position of an SO.
*
* @param index SO index in the range [0, number_to_keep()].
* @return Y position of that SO, in co-moving VR distance units (Mpc).
*/
inline double YSO(const size_t index) const { return _YSO[index]; }
/**
* @brief Get the z position of an SO.
*
* @param index SO index in the range [0, number_to_keep()].
* @return Z position of that SO, in co-moving VR distance units (Mpc).
*/
inline double ZSO(const size_t index) const { return _ZSO[index]; }
/**
* @brief Get the radius of an SO.
*
* What "radius" means is determined by the constructor argument
* "radius_selection_name"; see constructor documentation.
*
* @param index SO index in the range [0, number_to_keep()].
* @return Radius of that SO, in co-moving VR distance units (Mpc).
*/
inline double RSO(const size_t index) const { return _RSO[index]; }
/**
* @brief Get the halo ID for an SO.
*
* The halo ID is the unique ID assigned to the SO halo by VR, is independent
* of the SO index, and is consistent with the VR catalogue.
*
* @param index SO index in the range [0, number_to_keep()].
* @return Halo ID for the SO.
*/
inline size_t haloID(const size_t index) const { return _haloIDs[index]; }
};
/**
* @brief Auxiliary struct to keep track of orphan particles.
*
* Orphan particles are particles that have drifted beyond their top-level cell
* and therefore cannot be correctly linked to an SO based on cell masking
* alone.
*
* To not miss these particles in the reduced snapshot, we store all orphans
* (there usually are few) and do a brute-force search through the SOs to find
* SOs they belong to.
*/
struct Orphan {
/*! @brief Particle type of the orphan. */
int32_t type;
/*! @brief Index of the particle within the file. If we read any of the
* arrays in the PartTypeX (with X = type) group, the properties of the
* orphan particle will be stored on that location. */
int64_t index;
/*! @brief Top-level cell the particle was (incorrectly) assigned to. We do
* not correct SWIFT's mistakes and keep treating the particle as if it
* belongs to that cell. */
size_t cell;
/*! @brief Position of the orphan particle. Really our only way to figure out
* where the orphan is located. */
double position[3];
};
/**
* @brief Main program entry point.
*
* The program proceeds in three phases:
* 1. Halo catalogue parsing: all relevant properties from the halo catalogue
* are read in and stored in memory.
* 2. SWIFT snapshot file parsing: the SWIFT snapshot file(s) is (are) read
* in chuncks of top-level cells. For each chunk, a particle ID - halo ID
* dictionary is constructed from the catalogue and used to assign
* halo IDs to all particles. Particles that do not appear in the catalogue
* get assigned a halo index -1.
* 3. Output snapshot writing: a copy of the SWIFT snapshot(s) is made that
* contains exactly the same contents as the original snapshot, but with
* all particles with a halo index -1 filtered out.
*
* If the SWIFT snapshot is distributed among multiple files, then steps 2 and
* 3 are performed separately for each file, and an additional step 3 is
* performed in the end to also copy the virtual meta-file. In this case,
* the program can be run over MPI, using at most the same number of ranks as
* there are files (attempting to use more ranks will result in an error).
* Each rank will still independently parse the halo catalogue (step 1).
* Since the time needed to parse a single file is roughly constant, it is
* strongly recommended to use a number of ranks that is a sensible divisor
* of the number of files, to prevent ranks from idling.
* Note that each rank will still try to use as many OpenMP threads as allowed
* by OPENMP_NUM_THREADS. Allowing ranks to compete for threads is not
* necessarily bad for performance, although pushing this too far does lead
* to load imbalances between ranks that again cause ranks to be idle. So we
* can only advise to choose the number of threads in a sensible way.
*
* @param argc Number of command line arguments.
* @param argv Command line arguments. These are parsed positionally, nothing
* fancy.
*/
int main(int argc, char **argv) {
// first things first: initialise MPI
MPI_Init(&argc, &argv);
// and set our global variables (yuk!)
MPI_Comm_rank(MPI_COMM_WORLD, &MPI_rank);
MPI_Comm_size(MPI_COMM_WORLD, &MPI_size);
// start the global (yuk yuk!) timer
global_timer.start();
/// command line parsing
if (argc < 8) {
if (MPI_rank == 0) {
std::cerr << "Usage: ./reduce_snapshots SOAP_OUTPUT_PREFIX "
"SNAPSHOT_FILE_PREFIX MEMBERSHIP__FILE_PREFIX "
"OUTPUT_FILE_PREFIX "
"RADIUS_SELECTION_NAME "
"KEEP_SELECTION_NAME [CELLBUFSIZE] "
"[HDF5BUFSIZE]"
<< std::endl;
}
my_error("Wrong command line arguments!");
}
const std::string SOAP_output_prefix(argv[1]);
const std::string snapshot_file_prefix(argv[2]);
const std::string membership_file_prefix(argv[3]);
const std::string output_file_prefix(argv[4]);
std::string radius_selection_name(argv[5]);