FML
Loading...
Searching...
No Matches
FML::FILEUTILS::GADGET::GadgetReader Class Reference

Class for reading Gadget files. Checks and corrects for different endian-ness. More...

#include <GadgetUtils.h>

Public Member Functions

 GadgetReader ()=default
 
 GadgetReader (int ndim)
 
template<class T , class Alloc = std::allocator<T>>
void read_gadget_single (std::string filename, std::vector< T, Alloc > &part, bool only_keep_part_in_domain, bool verbose)
 Read a single gadget file and store the data in part.
 
template<class T , class Alloc = std::allocator<T>>
void read_gadget (std::string filename, std::vector< T, Alloc > &part, double buffer_factor, bool only_keep_part_in_domain, bool verbose)
 Read all gadget files and store the data in part.
 
void read_section (std::ifstream &fp, std::vector< char > &buffer)
 Read a section (block) of a gadget file. The buffer is resized to the size of the block.
 
void read_header (std::ifstream &fp)
 Read the gadget header (detects the endianness and format 1 / format 2)
 
GadgetHeader get_header ()
 Get the header (assumes it has been read)
 
int get_num_files (std::string filename="")
 Get the number of gadget files.
 
void set_fields_in_file (std::vector< std::string > fields)
 If non-standard file, set the fields that are in the file (POS,VEL,ID,MASS implemented)
 

Detailed Description

Class for reading Gadget files. Checks and corrects for different endian-ness.

Definition at line 123 of file GadgetUtils.h.

Constructor & Destructor Documentation

◆ GadgetReader() [1/2]

FML::FILEUTILS::GADGET::GadgetReader::GadgetReader ( )
default

◆ GadgetReader() [2/2]

FML::FILEUTILS::GADGET::GadgetReader::GadgetReader ( int ndim)

Definition at line 60 of file GadgetUtils.cpp.

60: NDIM(ndim) {}

Member Function Documentation

◆ get_header()

GadgetHeader FML::FILEUTILS::GADGET::GadgetReader::get_header ( )

Get the header (assumes it has been read)

Definition at line 62 of file GadgetUtils.cpp.

62{ return header; }

◆ get_num_files()

int FML::FILEUTILS::GADGET::GadgetReader::get_num_files ( std::string filename = "")

Get the number of gadget files.

Definition at line 321 of file GadgetUtils.cpp.

321 {
322 // Read the header of filename if given (not one we read earlier, possibly of another snapshot)
323 if (not header_is_read or not filename.empty()) {
324 std::ifstream fp(filename.c_str(), std::ios::binary);
325 if (not fp.is_open()) {
326 std::string errormessage = "[GadgetReader::get_num_files] File " + filename + " is not open\n";
327 throw_error(errormessage);
328 }
329 read_header(fp);
330 }
331 return header.num_files;
332 }
const std::string filename
Definition Main.cpp:63
void read_header(std::ifstream &fp)
Read the gadget header (detects the endianness and format 1 / format 2)

◆ read_gadget()

template<class T , class Alloc >
void FML::FILEUTILS::GADGET::GadgetReader::read_gadget ( std::string filename,
std::vector< T, Alloc > & part,
double buffer_factor,
bool only_keep_part_in_domain,
bool verbose )

Read all gadget files and store the data in part.

If only_keep_part_in_domain then we only keep the partiles that fall within the local domain. If buffer_factor is > 1 then we allocate corresponding extra storage in part

Definition at line 334 of file GadgetUtils.h.

338 {
339
340 verbose = verbose and FML::ThisTask == 0;
341
342 // Read the number of particles and the number of files
343 std::string filename = fileprefix + ".0";
344 std::ifstream fp(filename.c_str(), std::ios::binary);
345 if (not fp.is_open()) {
346 std::string errormessage = "[GadgetReader::read_gadget_all] File " + filename + " is not open\n";
347 throw_error(errormessage);
348 }
349 read_header(fp);
350 fp.close();
351
352 // Number of files
353 const int nfiles = header.num_files;
354
355 // Allocate memory for particle vector and reset it
356 // If we only keep in domain we reserve for buffer_factor more particles
357 // (but will resize if that is too little)
358#ifdef GADGET_ONLY_DM
359 size_t npartTotal = (size_t(header.npartTotalHighWord[1]) << 32) + size_t(header.npartTotal[1]);
360#else
361 size_t npartTotal = 0;
362 for (int i = 0; i < 6; i++)
363 npartTotal += (size_t(header.npartTotalHighWord[i]) << 32) + size_t(header.npartTotal[i]);
364#endif
365
366 size_t nalloc = npartTotal;
367 if (only_keep_part_in_domain)
368 nalloc = size_t(double(npartTotal) * buffer_factor) / FML::NTasks;
369 part.clear();
370 part.reserve(nalloc);
371
372 // Read all the files
373 for (int i = 0; i < nfiles; i++) {
374 filename = fileprefix + "." + std::to_string(i);
375 if (verbose)
376 std::cout << "Reading file " << filename << "\n";
377 read_gadget_single(filename, part, only_keep_part_in_domain, verbose);
378 }
379 }
const double buffer_factor
Definition Main.cpp:51
void read_gadget_single(std::string filename, std::vector< T, Alloc > &part, bool only_keep_part_in_domain, bool verbose)
Read a single gadget file and store the data in part.
int ThisTask
The MPI task number.
Definition Global.cpp:39
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40

◆ read_gadget_single()

template<class T , class Alloc >
void FML::FILEUTILS::GADGET::GadgetReader::read_gadget_single ( std::string filename,
std::vector< T, Alloc > & part,
bool only_keep_part_in_domain,
bool verbose )

Read a single gadget file and store the data in part.

If only_keep_part_in_domain then we only keep the partiles that fall within the local domain

Definition at line 382 of file GadgetUtils.h.

385 {
386
387 verbose = verbose and FML::ThisTask == 0;
388
389 // Open file and read the header
390 std::ifstream fp(filename.c_str(), std::ios::binary);
391 if (not fp.is_open()) {
392 std::string errormessage = "[GadgetReader::read_gadget_single] File " + filename + " is not open\n";
393 throw_error(errormessage);
394 }
395 read_header(fp);
396 if (verbose)
397 print_header_info(header);
398
399 // Positions normalized by the boxsize in the file
400 const double pos_norm = 1.0 / header.BoxSize;
401
402 // Velocities normalized to peculiar in km/s
403 const double vel_norm = sqrt(header.time);
404
405 // The particles of type t are [type_start[t], type_start[t+1]) in the file
406 size_t type_start[7];
407 type_start[0] = 0;
408 for (int t = 0; t < 6; t++)
409 type_start[t + 1] = type_start[t] + size_t(header.npart[t]);
410 const size_t NumPartFileTot = type_start[6];
411 auto type_of = [&](size_t i) {
412 int t = 0;
413 while (i >= type_start[t + 1])
414 t++;
415 return t;
416 };
417
418 // Nothing to read
419 if (NumPartFileTot == 0)
420 return;
421
422#ifndef GADGET_ONLY_DM
423 if constexpr (FML::PARTICLE::has_set_family<T>() == false) {
424 if (NumPartFileTot != size_t(header.npart[1])) {
425 std::string errormessage = "[GadgetReader::read_gadget_single] Particle type does not have "
426 "set_family, but Gadget file contains multiple species! Either use "
427 "define GADGET_ONLY_DM or add methods to particle\n";
428 throw_error(errormessage);
429 }
430 }
431#endif
432
433 // The number of particles in the MASS block (types with MassTable = 0)
434 size_t NumPartWithMass = 0;
435 for (int t = 0; t < 6; t++)
436 if (header.mass[t] == 0.0)
437 NumPartWithMass += header.npart[t];
438
439 // Reserve the whole file only for unfiltered reads. Filtered reads append
440 // only local particles, reusing existing capacity and growing as needed.
441 if (not only_keep_part_in_domain and part.capacity() < part.size() + NumPartFileTot)
442 part.reserve(part.size() + NumPartFileTot);
443
444 // Which particles in the file we keep (in the domain, and type 1 for GADGET_ONLY_DM)
445 std::vector<char> keep(NumPartFileTot, 1);
446 const size_t index_start = part.size();
447 bool pos_is_read = false;
448
449 // Size of the elements in a block (float or double, int or long long) with n * ncomp elements
450 auto element_size = [&](const std::string & field, size_t bytes, size_t n, size_t ncomp) {
451 for (size_t size : {size_t(4), size_t(8)})
452 if (bytes == size * n * ncomp)
453 return size;
454 throw_error("[GadgetReader::read_gadget_single] The " + field + " block in " + filename + " has " +
455 std::to_string(bytes) + " bytes, expected 4 or 8 bytes times " +
456 std::to_string(n * ncomp) + "\n");
457 return size_t(0);
458 };
459 // Element i of a block of floats/doubles (as double)
460 auto real_value = [&](const std::vector<char> & buffer, size_t size, size_t i) -> double {
461 if (size == 4)
462 return double(reinterpret_cast<const float *>(buffer.data())[i]);
463 return reinterpret_cast<const double *>(buffer.data())[i];
464 };
465 auto swap_block = [&](std::vector<char> & buffer, size_t size) {
466 if (not endian_swap)
467 return;
468 if (size == 4)
469 swap_endian_vector(reinterpret_cast<int32_t *>(buffer.data()), buffer.size() / 4);
470 else
471 swap_endian_vector(reinterpret_cast<int64_t *>(buffer.data()), buffer.size() / 8);
472 };
473 auto check_pos_is_read = [&](const std::string & field) {
474 if (not pos_is_read)
475 throw_error("[GadgetReader::read_gadget_single] The " + field + " block comes before POS in " +
476 filename + " (POS has to be read first)\n");
477 };
478
479 // Process a block
480 std::vector<char> buffer;
481 auto process_block = [&](const std::string & field) {
482 if (field == "POS") {
483 const size_t size = element_size(field, buffer.size(), NumPartFileTot, NDIM);
484 swap_block(buffer, size);
485 if (verbose)
486 std::cout << "Reading POS bytes = " << buffer.size() << "\n";
487 std::vector<double> x(NDIM);
488 for (size_t i = 0; i < NumPartFileTot; i++) {
489 for (int idim = 0; idim < NDIM; idim++) {
490 x[idim] = real_value(buffer, size, NDIM * i + idim) * pos_norm;
491 if (x[idim] >= 1.0)
492 x[idim] -= 1.0;
493 if (x[idim] < 0.0)
494 x[idim] += 1.0;
495 }
496 assert_mpi(x[0] >= 0.0 and x[0] < 1.0,
497 "[read_gadet_single] Particle has x position outside the boxsize even after "
498 "periodic wrap");
499 const int type = type_of(i);
500#ifdef GADGET_ONLY_DM
501 if (type != 1) {
502 keep[i] = 0;
503 continue;
504 }
505#endif
506 if (only_keep_part_in_domain and
507 not(x[0] >= FML::xmin_domain and x[0] < FML::xmax_domain)) {
508 keep[i] = 0;
509 continue;
510 }
511 part.push_back(T{});
512 auto & p = part.back();
513 if constexpr (FML::PARTICLE::has_get_pos<T>()) {
514 auto * pos = FML::PARTICLE::GetPos(p);
515 for (int idim = 0; idim < NDIM; idim++)
516 pos[idim] = x[idim];
517 }
518 if constexpr (FML::PARTICLE::has_set_family<T>())
520 }
521 pos_is_read = true;
522 } else if (field == "VEL") {
523 check_pos_is_read(field);
524 const size_t size = element_size(field, buffer.size(), NumPartFileTot, NDIM);
525 swap_block(buffer, size);
526 if constexpr (FML::PARTICLE::has_get_vel<T>()) {
527 size_t index = index_start;
528 for (size_t i = 0; i < NumPartFileTot; i++) {
529 if (not keep[i])
530 continue;
531 auto * vel = FML::PARTICLE::GetVel(part[index++]);
532 for (int idim = 0; idim < NDIM; idim++)
533 vel[idim] = real_value(buffer, size, NDIM * i + idim) * vel_norm;
534 }
535 }
536 } else if (field == "ID") {
537 check_pos_is_read(field);
538 const size_t size = element_size(field, buffer.size(), NumPartFileTot, 1);
539 swap_block(buffer, size);
540 if constexpr (FML::PARTICLE::has_set_id<T>()) {
541 size_t index = index_start;
542 for (size_t i = 0; i < NumPartFileTot; i++) {
543 if (not keep[i])
544 continue;
545 const long long int id =
546 size == 4 ? (long long int)(reinterpret_cast<int32_t *>(buffer.data())[i]) :
547 (long long int)(reinterpret_cast<int64_t *>(buffer.data())[i]);
548 FML::PARTICLE::SetID(part[index++], id);
549 }
550 }
551 } else if (field == "MASS") {
552 check_pos_is_read(field);
553 const size_t size = element_size(field, buffer.size(), NumPartWithMass, 1);
554 swap_block(buffer, size);
555 if constexpr (FML::PARTICLE::has_set_mass<T>()) {
556 size_t index = index_start;
557 size_t count = 0;
558 for (size_t i = 0; i < NumPartFileTot; i++) {
559 const bool has_mass = header.mass[type_of(i)] == 0.0;
560 const double mass = has_mass ? real_value(buffer, size, count++) : 0.0;
561 if (not keep[i])
562 continue;
563 if (has_mass)
564 FML::PARTICLE::SetMass(part[index], mass);
565 index++;
566 }
567 }
568 } else {
569 if (verbose)
570 std::cout << "Skipping block [" << field << "]\n";
571 }
572 };
573
574 if (format2) {
575 // The blocks are labeled: read all of them and use the ones we know
576 std::string label;
577 while (read_label(fp, label)) {
578 read_section(fp, buffer);
579 if (label == "MASS" and NumPartWithMass == 0)
580 continue;
581 process_block(label);
582 }
583 } else {
584 auto fields = fields_in_file;
585 if (NumPartWithMass > 0 and std::find(fields.begin(), fields.end(), "MASS") == fields.end())
586 fields.push_back("MASS");
587 for (auto & field : fields) {
588 if (field == "MASS") {
589 if (NumPartWithMass == 0)
590 continue;
591 // Files without the MASS block (all masses in the MassTable equal to 0)
592 if (fp.peek() == std::ifstream::traits_type::eof())
593 break;
594 }
595 read_section(fp, buffer);
596 process_block(field);
597 }
598 }
599 if (not pos_is_read)
600 throw_error("[GadgetReader::read_gadget_single] No POS block in " + filename + "\n");
601 }
const int NDIM
void read_section(std::ifstream &fp, std::vector< char > &buffer)
Read a section (block) of a gadget file. The buffer is resized to the size of the block.
void print_header_info(const GadgetHeader &header)
void swap_endian_vector(T *vec, size_t n)
get_vel constexpr double * GetPos(...)
constexpr void SetMass(...)
constexpr double * GetVel(...)
constexpr void SetFamily(...)
constexpr void SetID(...)
double xmax_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:50
double xmin_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:49

◆ read_header()

void FML::FILEUTILS::GADGET::GadgetReader::read_header ( std::ifstream & fp)

Read the gadget header (detects the endianness and format 1 / format 2)

Definition at line 109 of file GadgetUtils.cpp.

109 {
110 if (not fp.is_open()) {
111 std::string errormessage = "[GadgetReader::read_header] File is not open\n";
112 throw_error(errormessage);
113 }
114
115 // Detect the format and the endianness from the first block size: 256 (the header, format 1)
116 // or 8 (the label block, format 2)
117 endian_swap = false;
118 format2 = false;
119 int bytes_start, bytes_end;
120 fp.read((char *)&bytes_start, sizeof(bytes_start));
121 if (not fp)
122 throw_error("[GadgetReader::read_header] Could not read the header\n");
123 if (bytes_start == 8 or swap_endian(bytes_start) == 8) {
124 format2 = true;
125 endian_swap = bytes_start != 8;
126 fp.seekg(0, fp.beg);
127 std::string label;
128 read_label(fp, label);
129 if (label != "HEAD")
130 throw_error("[GadgetReader::read_header] Format 2 file without a HEAD block first\n");
131 fp.read((char *)&bytes_start, sizeof(bytes_start));
132 if (endian_swap)
133 bytes_start = swap_endian(bytes_start);
134 } else if (bytes_start != int(sizeof(header))) {
135 // Ok lets try to swap endian and see if that works better
136 endian_swap = true;
137 bytes_start = swap_endian(bytes_start);
138 }
139 if (bytes_start != int(sizeof(header))) {
140 std::string errormessage = "[GadgetReader::read_header] Error: not a GADGET file (the first block "
141 "is not a 256 byte header or a format 2 label in either endianness)\n";
142 throw_error(errormessage);
143 }
144 fp.read((char *)&header, bytes_start);
145 fp.read((char *)&bytes_end, sizeof(bytes_end));
146 if (not fp)
147 throw_error("[GadgetReader::read_header] The file ended inside the header\n");
148 if (endian_swap)
149 bytes_end = swap_endian(bytes_end);
150
151 if (bytes_start != bytes_end) {
152 std::string errormessage =
153 "[GadgetReader::read_header] Error: we find that BytesStart != ByteEnd!\n";
154 throw_error(errormessage);
155 }
156
157 // Check if endian of file needs to be changed
158 // Swap endian of header and set flag so that we
159 // swap the endian of the other fields also
160 if (endian_swap) {
161 swap_endian_vector(header.npart, 6);
162 swap_endian_vector(header.mass, 6);
163 swap_endian_vector(header.npartTotal, 6);
164 swap_endian_vector(header.npartTotalHighWord, 6);
165 header.time = swap_endian(header.time);
166 header.redshift = swap_endian(header.redshift);
167 header.flag_sfr = swap_endian(header.flag_sfr);
168 header.flag_feedback = swap_endian(header.flag_feedback);
169 header.flag_cooling = swap_endian(header.flag_cooling);
170 header.num_files = swap_endian(header.num_files);
171 header.BoxSize = swap_endian(header.BoxSize);
172 header.Omega0 = swap_endian(header.Omega0);
173 header.OmegaLambda = swap_endian(header.OmegaLambda);
174 header.HubbleParam = swap_endian(header.HubbleParam);
175 header.flag_stellarage = swap_endian(header.flag_stellarage);
176 header.flag_metals = swap_endian(header.flag_metals);
177 header.flag_entropy_instead_u = swap_endian(header.flag_entropy_instead_u);
178 }
179
180 header_is_read = true;
181 }

◆ read_section()

void FML::FILEUTILS::GADGET::GadgetReader::read_section ( std::ifstream & fp,
std::vector< char > & buffer )

Read a section (block) of a gadget file. The buffer is resized to the size of the block.

Definition at line 64 of file GadgetUtils.cpp.

64 {
65 if (not fp.is_open()) {
66 std::string errormessage = "[GadgetReader::read_section] File is not open\n";
67 throw_error(errormessage);
68 }
69
70 int bytes_start, bytes_end;
71 fp.read((char *)&bytes_start, sizeof(bytes_start));
72 if (not fp)
73 throw_error("[GadgetReader::read_section] Could not read the block size (end of file?)\n");
74 if (endian_swap)
75 bytes_start = swap_endian(bytes_start);
76 if (bytes_start < 0)
77 throw_error("[GadgetReader::read_section] Negative block size in file\n");
78
79 // NB: we do not swap endian-ness here, the caller will have to do that
80 // depending on what type of data we are reading
81 buffer.resize(size_t(bytes_start));
82 fp.read(buffer.data(), bytes_start);
83
84 fp.read((char *)&bytes_end, sizeof(bytes_end));
85 if (not fp)
86 throw_error("[GadgetReader::read_section] The file ended inside a block\n");
87 if (endian_swap)
88 bytes_end = swap_endian(bytes_end);
89
90 if (bytes_start != bytes_end) {
91 std::string errormessage = "[GadgetReader::read_section] Error in file BytesStart != ByteEnd!\n";
92 throw_error(errormessage);
93 }
94 }

◆ set_fields_in_file()

void FML::FILEUTILS::GADGET::GadgetReader::set_fields_in_file ( std::vector< std::string > fields)

If non-standard file, set the fields that are in the file (POS,VEL,ID,MASS implemented)

Definition at line 58 of file GadgetUtils.cpp.

58{ fields_in_file = fields; }

The documentation for this class was generated from the following files: