Skip to content

Commit 74c868d

Browse files
Create hdf5_save.cpp
1 parent fe36df8 commit 74c868d

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

src/io/hdf5_save.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#include "hdf5_save.h"
2+
#include <hdf5.h>
3+
#include <vector>
4+
#include <string>
5+
6+
void SaveHDF5(const std::vector<Particle>& p, const std::string& filename)
7+
{
8+
hid_t file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
9+
10+
// Group: PartType1 (DM)
11+
hid_t group = H5Gcreate(file, "PartType1", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
12+
13+
size_t N = p.size();
14+
15+
// Prepare arrays
16+
std::vector<float> coords(N * 3);
17+
std::vector<float> vels(N * 3);
18+
std::vector<float> masses(N);
19+
std::vector<int> ids(N);
20+
21+
for (size_t i = 0; i < N; i++) {
22+
coords[3*i+0] = p[i].x;
23+
coords[3*i+1] = p[i].y;
24+
coords[3*i+2] = p[i].z;
25+
26+
vels[3*i+0] = p[i].vx;
27+
vels[3*i+1] = p[i].vy;
28+
vels[3*i+2] = p[i].vz;
29+
30+
masses[i] = p[i].m;
31+
ids[i] = i + 1; // Gadget requires IDs
32+
}
33+
34+
// Dataspace for Nx3
35+
hsize_t dims3[2] = { N, 3 };
36+
hid_t space3 = H5Screate_simple(2, dims3, NULL);
37+
38+
// Dataspace for N
39+
hsize_t dims1[1] = { N };
40+
hid_t space1 = H5Screate_simple(1, dims1, NULL);
41+
42+
// Write datasets
43+
H5Dcreate(group, "Coordinates", H5T_NATIVE_FLOAT, space3, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
44+
H5Dwrite(H5Dopen(group, "Coordinates", H5P_DEFAULT), H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, coords.data());
45+
46+
H5Dcreate(group, "Velocities", H5T_NATIVE_FLOAT, space3, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
47+
H5Dwrite(H5Dopen(group, "Velocities", H5P_DEFAULT), H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, vels.data());
48+
49+
H5Dcreate(group, "Masses", H5T_NATIVE_FLOAT, space1, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
50+
H5Dwrite(H5Dopen(group, "Masses", H5P_DEFAULT), H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, masses.data());
51+
52+
H5Dcreate(group, "ParticleIDs", H5T_NATIVE_INT, space1, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
53+
H5Dwrite(H5Dopen(group, "ParticleIDs", H5P_DEFAULT), H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, ids.data());
54+
55+
// Cleanup
56+
H5Sclose(space3);
57+
H5Sclose(space1);
58+
H5Gclose(group);
59+
H5Fclose(file);
60+
}

0 commit comments

Comments
 (0)