diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f530765b1..6b59a68b5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -34,7 +34,10 @@ jobs: if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y build-essential libeigen3-dev libfftw3-dev libhdf5-dev libopenmpi-dev libomp-dev python3-numpy + sudo apt-get install -y build-essential libeigen3-dev libfftw3-dev libhdf5-dev libopenmpi-dev libomp-dev python3-numpy python3-h5py + + - name: Verify HDF5 test dependencies + run: /usr/bin/python3 -c "import h5py, numpy" - name: Setup submodule and build run: | @@ -52,6 +55,7 @@ jobs: -DENABLE_NBODY=YES -DENABLE_PYEXP=YES -DCMAKE_BUILD_TYPE=Release + -DPython3_EXECUTABLE=/usr/bin/python3 -DEigen3_DIR=/usr/include/eigen3/share/eigen3/cmake -DCMAKE_INSTALL_PREFIX=./install -DCMAKE_CXX_FLAGS=${{ matrix.cxxflags }} diff --git a/.gitignore b/.gitignore index 122f619cd..6bf6640e8 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,5 @@ src/user/EllipsoidForce.cc src/user/SLSphere.cc _codeql_build_dir _codeql_detected_source_root +__pycache__/ +Testing/ diff --git a/expui/BiorthBasis.H b/expui/BiorthBasis.H index 1c8d91930..06c00976e 100644 --- a/expui/BiorthBasis.H +++ b/expui/BiorthBasis.H @@ -1,6 +1,7 @@ #ifndef _BiorthBasis_H #define _BiorthBasis_H +#include #include #include #include @@ -985,6 +986,12 @@ namespace BasisClasses double rcylmin, rcylmax, acyl, hcyl, bias; bool expcond, logarithmic, density, EVEN_M, sech2 = true; + //! Basis-cache compression. Only set when given in the YAML + //! config; otherwise the EmpCylSL defaults (as used by EXP and + //! gendisk) are left untouched. + std::optional H5compress; + std::optional H5shuffle; + std::vector potd, dpot, dpt2, dend; std::vector legs, dlegs, d2legs; diff --git a/expui/BiorthBasis.cc b/expui/BiorthBasis.cc index d21465d59..32673cc09 100644 --- a/expui/BiorthBasis.cc +++ b/expui/BiorthBasis.cc @@ -1279,7 +1279,9 @@ namespace BasisClasses "pyproj", "nint", "totalCovar", - "fullCovar" + "fullCovar", + "H5compress", + "H5shuffle" }; Cylindrical::Cylindrical(const YAML::Node& CONF) : @@ -1529,10 +1531,20 @@ namespace BasisClasses if (conf["vflag" ]) vflag = conf["vflag" ].as(); if (conf["pyname" ]) pyname = conf["pyname" ].as(); if (conf["pyproj" ]) pyproj = conf["pyproj" ].as(); - if (conf["pcavar"] ) pcavar = conf["pcavar" ].as(); - if (conf["subsamp"] ) sampT = conf["subsamp" ].as(); + if (conf["pcavar" ]) pcavar = conf["pcavar" ].as(); + if (conf["subsamp" ]) sampT = conf["subsamp" ].as(); if (conf["samplesz" ]) sampT = conf["samplesz" ].as(); + if (conf["H5compress"]) H5compress = conf["H5compress"].as(); + if (conf["H5shuffle" ]) H5shuffle = conf["H5shuffle" ].as(); + + if (H5compress and (*H5compress < 0 or *H5compress > 9)) { + if (myid==0) + std::cerr << "---- Cylindrical: WARNING, H5compress must be between 0 and 9" + << " (got " << *H5compress << "); using the default" << std::endl; + H5compress.reset(); + } + // Sanity sampT = std::max(1, sampT); @@ -1604,6 +1616,10 @@ namespace BasisClasses EmpCylSL::CMAPZ = cmapZ; EmpCylSL::logarithmic = logarithmic; EmpCylSL::VFLAG = vflag; + // Only override the EmpCylSL cache-compression defaults when the + // YAML config sets them + if (H5compress) EmpCylSL::H5compress = *H5compress; + if (H5shuffle ) EmpCylSL::H5shuffle = *H5shuffle; // Convert dmodel string to lower case (deprojection model for EOF // basis construction) diff --git a/exputil/EmpCylSL.cc b/exputil/EmpCylSL.cc index 5030c42df..ee9d1a2cf 100644 --- a/exputil/EmpCylSL.cc +++ b/exputil/EmpCylSL.cc @@ -68,6 +68,8 @@ double EmpCylSL::RMAX = 20.0; double EmpCylSL::HFAC = 0.2; double EmpCylSL::PPOW = 4.0; bool EmpCylSL::NewCoefs = true; +int EmpCylSL::H5compress = 5; +bool EmpCylSL::H5shuffle = false; EmpCylSL::EmpModel EmpCylSL::mtype = EmpCylSL::EmpModel::Exponential; @@ -994,7 +996,9 @@ int EmpCylSL::cache_grid(int readwrite, std::string cachename) if (readwrite) { - // Check for new HDF5 file + // Check for new HDF5 file. The exists/rename/create sequence is + // not atomic: independent jobs writing the same cache file name + // concurrently are unsupported (see cache_grid in EmpCylSL.H). if (std::filesystem::exists(cachefile)) { if (myid==0) std::cout << "---- EmpCylSL::cache_grid: cache file <" @@ -2403,6 +2407,22 @@ void EmpCylSL::generate_eof(int numr, int nump, int numt, Timer timer; if (VFLAG & 16) timer.start(); + // Sanity check on quadrature parameters + // + numr = std::max(1, numr); + nump = std::max(1, nump); + numt = std::max(1, numt); + + if (myid==0 and numr < 10) { + std::cerr << "EmpCylSL: Warning, numr=" << numr + << " is very small for quadrature" << std::endl; + } + + if (myid==0 and numt < 10) { + std::cerr << "EmpCylSL: Warning, numt=" << numt + << " is very small for quadrature" << std::endl; + } + // Create spherical orthogonal basis if necessary // if (not ortho) { @@ -2667,7 +2687,7 @@ void EmpCylSL::generate_eof(int numr, int nump, int numt, } // *** r quadrature loop - if (VFLAG & 8) { + if (VFLAG & 16) { auto t = timer.stop(); if (myid==0) { std::cout << std::endl @@ -2700,7 +2720,7 @@ void EmpCylSL::generate_eof(int numr, int nump, int numt, // make_eof(); - if (VFLAG & 8) { + if (VFLAG & 16) { cout << "Process " << setw(4) << myid << ": completed basis in " << timer.stop() << " seconds" << endl; @@ -7463,6 +7483,39 @@ void EmpCylSL::WriteH5Cache() file.createAttribute ("eof_numt", HighFive::DataSpace::From(eof_vars.numt)).write(eof_vars.numt); + // To write an Eigen::MatrixXd with compression in HighFive, we we + // create the dataset with explicit chunk sizes and a deflation + // (gzip) filter before writing, because shortcut functions do not + // pass compression parameters. + + auto dcpl = HighFive::DataSetCreateProps{}; + + // Define dimensions + std::vector dims {static_cast(NUMX+1), + static_cast(NUMY+1)}; + + // Dataspace size definition + HighFive::DataSpace ds(dims); + + // Define chunk size (e.g., matching matrix size or split into blocks) + std::vector chunk_dims {static_cast(NUMX+1), + static_cast(NUMY+1)}; + + // Deflate only accepts levels 0-9; clamp rather than lose the + // cache to an HDF5 error + int level = H5compress; + if (level > 9) { + std::cerr << "---- EmpCylSL::WriteH5Cache: WARNING, H5compress=" + << H5compress << " is out of range [0, 9]; using 9" << std::endl; + level = 9; + } + + if (level>0) { + dcpl.add(HighFive::Chunking(chunk_dims)); + if (H5shuffle) dcpl.add(HighFive::Shuffle()); + dcpl.add(HighFive::Deflate(level)); + } + // Cosine functions auto cosine = file.createGroup("Cosine"); @@ -7480,10 +7533,10 @@ void EmpCylSL::WriteH5Cache() sout << n; auto order = harmonic.createGroup(sout.str()); - order.createDataSet("potC", potC [m][n]); - order.createDataSet("rforceC", rforceC[m][n]); - order.createDataSet("zforceC", zforceC[m][n]); - order.createDataSet("densC", densC [m][n]); + order.createDataSet("potC", ds, dcpl).write(potC [m][n]); + order.createDataSet("rforceC", ds, dcpl).write(rforceC[m][n]); + order.createDataSet("zforceC", ds, dcpl).write(zforceC[m][n]); + order.createDataSet("densC", ds, dcpl).write(densC [m][n]); } } @@ -7504,15 +7557,23 @@ void EmpCylSL::WriteH5Cache() sout << n; auto order = harmonic.createGroup(sout.str()); - order.createDataSet("potS", potS [m][n]); - order.createDataSet("rforceS", rforceS[m][n]); - order.createDataSet("zforceS", zforceS[m][n]); - order.createDataSet("densS", densS [m][n]); + order.createDataSet("potS", ds, dcpl).write(potS [m][n]); + order.createDataSet("rforceS", ds, dcpl).write(rforceS[m][n]); + order.createDataSet("zforceS", ds, dcpl).write(zforceS[m][n]); + order.createDataSet("densS", ds, dcpl).write(densS [m][n]); } } - } catch (HighFive::Exception& err) { - std::cerr << err.what() << std::endl; + } catch (const std::exception& err) { + std::cerr << std::endl + << "**** EmpCylSL::WriteH5Cache: WARNING, FAILED to write the basis cache <" + << cachefile << ">" << std::endl + << "**** HDF5 error: " << err.what() << std::endl + << "**** The basis in memory is fine, but the cache file is missing or" + << " incomplete and will" << std::endl + << "**** not be reusable; it will need to be regenerated next time." + << std::endl << std::endl; + return; } std::cout << "---- EmpCylSL::WriteH5Cache: " diff --git a/include/EmpCylSL.H b/include/EmpCylSL.H index 3b92175fc..dd6df6123 100644 --- a/include/EmpCylSL.H +++ b/include/EmpCylSL.H @@ -254,8 +254,17 @@ struct eof_variables { //! The cache file name std::string cachefile; - // 1=write, 0=read - // return: 0=failure + /** Read (0) or write (1) the basis cache; returns 0 on failure. + + Writing is done by the root process only and is safe within one + run. Writing renames an existing cache to .bak and then + creates . This sequence is not protected against other + processes, so independent jobs (separate EXP, gendisk or pyEXP + runs) that write the same cache file name at the same time are + NOT supported: they can lose or overwrite each other's cache or + backup. Give concurrent jobs distinct cache file names, or + generate the cache once and let the other jobs read it. + */ int cache_grid(int, std::string file); double integral(int, int, int, int); void get_pot(Eigen::MatrixXd&, Eigen::MatrixXd&, double, double); @@ -448,6 +457,14 @@ public: //! No extrapolating beyond grid (default: false) static bool enforce_limits; + //! H5compression level (default: 5; good compromise between speed + //! and compression factor) + static int H5compress; + + //! H5shuffle (default: false; tests suggests that shuffling makes + //! cache compression worse) + static bool H5shuffle; + /** @brief Density model type Available options: diff --git a/include/massmodel1d.H b/include/massmodel1d.H index 1d5f42982..e292317dd 100644 --- a/include/massmodel1d.H +++ b/include/massmodel1d.H @@ -1,8 +1,17 @@ #ifndef _massmodel1d_H #define _massmodel1d_H +#include +#include +#include +#include +#include +#include +#include #include +#include #include +#include #include "massmodel.H" #include "biorth1d.H" @@ -836,8 +845,9 @@ public: // Convert energy to potential, so that the distribution function // is nonzero only. That is, assume E = Omega*Ja, not zero at +/- // H. - double J = fabs(E + M_PI*H)/Omega; - return -0.5*Omega*norm / std::pow(Jmax - J + epsilon, 1.5); + double shifted = E + M_PI*H; + double J = fabs(shifted)/Omega; + return std::copysign(0.5*norm / (Omega * std::pow(Jmax - J + epsilon, 1.5)), shifted); } double dfdv(const double E, const double p=0.0) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 45225dc3e..7ac60fec0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -2,6 +2,24 @@ include(CTest) set(CTEST_OUTPUT_ON_FAILURE ON) +option(ENABLE_HDF5_IC_TESTS "Enable HDF5 initial-condition schema tests when h5py is available" ON) +set(EXP_HDF5_IC_TESTS_AVAILABLE OFF) +if(ENABLE_HDF5_IC_TESTS AND ENABLE_NBODY AND ENABLE_UTILS) + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_Interpreter_FOUND) + execute_process( + COMMAND "${Python3_EXECUTABLE}" -c "import h5py, numpy" + RESULT_VARIABLE EXP_H5PY_STATUS + OUTPUT_QUIET ERROR_QUIET) + if(EXP_H5PY_STATUS STREQUAL "0") + set(EXP_HDF5_IC_TESTS_AVAILABLE ON) + endif() + endif() + if(NOT EXP_HDF5_IC_TESTS_AVAILABLE) + message(STATUS "HDF5 IC schema tests disabled (Python with h5py and NumPy is required)") + endif() +endif() + # Is EXP configured for pyEXP? If yes, run pyEXP tests... # if(ENABLE_PYEXP) @@ -56,10 +74,10 @@ if(ENABLE_NBODY) add_test(NAME expExecuteTest COMMAND ${EXP_MPI_LAUNCH} ${CMAKE_BINARY_DIR}/src/exp -v) - if (ENABLE_UTILS) + if(ENABLE_UTILS) # Makes some spherical ICs using utils/ICs/gensph add_test(NAME makeICTest - COMMAND ${EXP_MPI_LAUNCH} ${CMAKE_BINARY_DIR}/utils/ICs/gensph -N 10000 -i SLGridSph.model + COMMAND ${EXP_MPI_LAUNCH} ${CMAKE_BINARY_DIR}/utils/ICs/gensph -N 10000 -i SLGridSph.model --NUMG 100 WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) # Runs those ICs using exp @@ -108,19 +126,19 @@ if(ENABLE_NBODY) # perhaps there is a better way? add_test(NAME removeTempFiles COMMAND ${CMAKE_COMMAND} -E remove - config.run0.yml current.processor.rates.run0 new.bods + config.run0.yml current.processor.rates.run0 new.bods.h5 OUTLOG.run0 run0.levels SLGridSph.cache.run0 test.grid outcoef.halo.run0 SLGridSph.cache.run0 coefcovar.halo.test_covar.h5 WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) # Remove the temporary files set_tests_properties(removeTempFiles PROPERTIES DEPENDS expNbodyCheck2TW - REQUIRED_FILES "config.run0.yml;current.processor.rates.run0;new.bods;run0.levels;SLGridSph.cache.run0;test.grid;" + REQUIRED_FILES "config.run0.yml;current.processor.rates.run0;new.bods.h5;run0.levels;SLGridSph.cache.run0;test.grid;" ) # Makes some cube ICs using utils/ICs/cubeics add_test(NAME makeCubeICTest - COMMAND ${EXP_MPI_LAUNCH} ${CMAKE_BINARY_DIR}/utils/ICs/cubeics -N 4000 -z -d 2,2,2 + COMMAND ${CMAKE_BINARY_DIR}/utils/ICs/cubeics -N 4000 -z -d 2,2,2 WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Cube) # Runs those ICs using exp @@ -142,13 +160,164 @@ if(ENABLE_NBODY) # A separate test to remove the generated files if they all exist add_test(NAME removeCubeFiles COMMAND ${CMAKE_COMMAND} -E remove - config.runS.yml current.processor.rates.runS cube.bods + config.runS.yml current.processor.rates.runS cube.bods.h5 OUTLOG.runS runS.levels WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Cube) # Remove the temporary files set_tests_properties(removeCubeFiles PROPERTIES DEPENDS expCubeCheckPos - REQUIRED_FILES "config.runS.yml;current.processor.rates.runS;cube.bods;OUTLOG.runS;runS.levels;") + REQUIRED_FILES "config.runS.yml;current.processor.rates.runS;cube.bods.h5;OUTLOG.runS;runS.levels;") + + # These are basic sanity checks for writing and reading EXP HDF5 IC files + if(EXP_HDF5_IC_TESTS_AVAILABLE) + + # Run the generator and evolved-halo round trips in a scratch directory. + string(REPLACE ";" " " hdf5_ic_mpi_launcher "${EXP_MPI_LAUNCH}") + add_test(NAME TestHDF5InitialConditionGeneration + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_LIST_DIR}/test_hdf5_ics.py" + "${CMAKE_BINARY_DIR}" "--mpi-launcher=${hdf5_ic_mpi_launcher}" --ranks 2) + set_tests_properties(TestHDF5InitialConditionGeneration + PROPERTIES LABELS "long" PROCESSORS 2) + + # Check spherical body file generation + add_test(NAME makeSphHDF5ICTest + COMMAND ${EXP_MPI_LAUNCH} ${CMAKE_BINARY_DIR}/utils/ICs/gensph + --hdf5 -N 16 -i SLGridSph.model --SEED 17 --zerovel -o hdf5-sph.bods + --NUMG 100 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + + add_test(NAME checkSphHDF5ICTest + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_LIST_DIR}/check_hdf5_particles.py + hdf5-sph.bods.h5 --count 16 --mass 1.008 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(checkSphHDF5ICTest PROPERTIES DEPENDS makeSphHDF5ICTest) + + add_test(NAME removeSphHDF5ICFiles + COMMAND ${CMAKE_COMMAND} -E remove hdf5-sph.bods.h5 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(removeSphHDF5ICFiles PROPERTIES DEPENDS checkSphHDF5ICTest + REQUIRED_FILES "hdf5-sph.bods.h5") + set_tests_properties(makeSphHDF5ICTest checkSphHDF5ICTest removeSphHDF5ICFiles + PROPERTIES LABELS "long") + + # Keep the generated files in a directory that exists in clean checkouts. + set(slab_ic_dir "${CMAKE_CURRENT_BINARY_DIR}/Slab") + file(MAKE_DIRECTORY "${slab_ic_dir}") + add_test(NAME makeSlabHDF5ICTest + COMMAND ${CMAKE_BINARY_DIR}/utils/ICs/slabics --hdf5 --number + 16 --seed 17 --outfile hdf5-slab.bods --model Sech2mu + WORKING_DIRECTORY "${slab_ic_dir}") + + add_test(NAME checkSlabHDF5ICTest + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_LIST_DIR}/check_hdf5_particles.py + hdf5-slab.bods.h5 --count 16 --slab-paired + WORKING_DIRECTORY "${slab_ic_dir}") + set_tests_properties(checkSlabHDF5ICTest PROPERTIES DEPENDS makeSlabHDF5ICTest) + + add_test(NAME removeSlabHDF5ICFiles + COMMAND ${CMAKE_COMMAND} -E remove hdf5-slab.bods.h5 + WORKING_DIRECTORY "${slab_ic_dir}") + set_tests_properties(removeSlabHDF5ICFiles PROPERTIES DEPENDS checkSlabHDF5ICTest + REQUIRED_FILES "hdf5-slab.bods.h5") + set_tests_properties(makeSlabHDF5ICTest checkSlabHDF5ICTest removeSlabHDF5ICFiles + PROPERTIES LABELS "quick") + + # Check cube body file generation + add_test(NAME makeCubeHDF5ICTest + COMMAND ${CMAKE_BINARY_DIR}/utils/ICs/cubeics --hdf5 --number 16 --seed 17 --zerovel --file hdf5-cube.bods + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Cube) + + add_test(NAME checkCubeHDF5ICTest + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_LIST_DIR}/check_hdf5_particles.py + hdf5-cube.bods.h5 --count 16 --cube + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Cube) + set_tests_properties(checkCubeHDF5ICTest PROPERTIES DEPENDS makeCubeHDF5ICTest) + + add_test(NAME removeCubeHDF5ICFiles + COMMAND ${CMAKE_COMMAND} -E remove hdf5-cube.bods.h5 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Cube) + set_tests_properties(removeCubeHDF5ICFiles PROPERTIES DEPENDS checkCubeHDF5ICTest + REQUIRED_FILES "hdf5-cube.bods.h5") + set_tests_properties(makeCubeHDF5ICTest checkCubeHDF5ICTest removeCubeHDF5ICFiles + PROPERTIES LABELS "quick") + + # Check gendisk body file generation with a pared-down + # low-resolution basis + add_test(NAME makeGendiskHDF5ICTest + COMMAND ${EXP_MPI_LAUNCH} ${CMAKE_BINARY_DIR}/utils/ICs/gendisk + --nhalo 10000 --ndisk 10000 + --hdf5 --SEED 17 --ignore --MMAX 2 --NUMX 128 --NUMY 64 + --LMAXFID 32 --NMAXFID 24 --PNUM 0 --TNUM 32 + --hbods hdf5-gendisk-halo.bods --dbods hdf5-gendisk-disk.bods + --cachefile hdf5-gendisk.cache --suffix hdf5-gendisk + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + + add_test(NAME checkGendiskDiskHDF5ICTest + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_LIST_DIR}/check_hdf5_particles.py + hdf5-gendisk-disk.bods.h5 --count 10000 --mass 0.05 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(checkGendiskDiskHDF5ICTest PROPERTIES DEPENDS makeGendiskHDF5ICTest) + + add_test(NAME checkGendiskHaloHDF5ICTest + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_LIST_DIR}/check_hdf5_particles.py + hdf5-gendisk-halo.bods.h5 --count 10000 --mass 1.0079 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(checkGendiskHaloHDF5ICTest PROPERTIES DEPENDS makeGendiskHDF5ICTest) + + add_test(NAME removeGendiskHDF5ICFiles + COMMAND ${CMAKE_COMMAND} -E remove + hdf5-gendisk-halo.bods.h5 hdf5-gendisk-disk.bods.h5 + hdf5-gendisk.cache hdf5-gendisk.ortho_check + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(removeGendiskHDF5ICFiles PROPERTIES DEPENDS + "checkGendiskDiskHDF5ICTest;checkGendiskHaloHDF5ICTest" + REQUIRED_FILES "hdf5-gendisk-halo.bods.h5;hdf5-gendisk-disk.bods.h5") + set_tests_properties(makeGendiskHDF5ICTest + checkGendiskDiskHDF5ICTest checkGendiskHaloHDF5ICTest + removeGendiskHDF5ICFiles + PROPERTIES LABELS "long") + + # Check gendisk2d body file generation with a pared-down + # low-resolution basis + add_test(NAME makeGendisk2dHDF5ICTest + COMMAND ${EXP_MPI_LAUNCH} ${CMAKE_BINARY_DIR}/utils/ICs/gendisk2d + --hdf5 --nhalo 10000 --ndisk 10000 --SEED 17 --NUMX 128 --NUMY 64 + --PNUM 0 --TNUM 40 --LMAX 4 --MMAX 2 --NMAXH 4 --NMAXD 4 + --RMIN 3.333e-05 + --hbods hdf5-gendisk2d-halo.bods --dbods hdf5-gendisk2d-disk.bods + --cachefile hdf5-gendisk2d.cache + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + + add_test(NAME checkGendisk2dHaloHDF5ICTest + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_LIST_DIR}/check_hdf5_particles.py + hdf5-gendisk2d-halo.bods.h5 --count 10000 --mass 1.0079 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(checkGendisk2dHaloHDF5ICTest PROPERTIES DEPENDS makeGendisk2dHDF5ICTest) + + add_test(NAME checkGendisk2dDiskHDF5ICTest + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_LIST_DIR}/check_hdf5_particles.py + hdf5-gendisk2d-disk.bods.h5 --count 10000 --mass 0.05 + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(checkGendisk2dDiskHDF5ICTest PROPERTIES DEPENDS makeGendisk2dHDF5ICTest) + + add_test(NAME removeGendisk2dHDF5ICFiles + COMMAND ${CMAKE_COMMAND} -E remove + hdf5-gendisk2d-halo.bods.h5 hdf5-gendisk2d-disk.bods.h5 + hdf5-gendisk2d.cache hdf5-gendisk2d.ortho_check + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/Halo) + set_tests_properties(removeGendisk2dHDF5ICFiles PROPERTIES DEPENDS + "checkGendisk2dHaloHDF5ICTest;checkGendisk2dDiskHDF5ICTest" + REQUIRED_FILES "hdf5-gendisk2d-halo.bods.h5;hdf5-gendisk2d-disk.bods.h5") + set_tests_properties(makeGendisk2dHDF5ICTest checkGendisk2dHaloHDF5ICTest + checkGendisk2dDiskHDF5ICTest removeGendisk2dHDF5ICFiles + PROPERTIES LABELS "long") + endif() # Set labels for pyEXP tests set_tests_properties(expExecuteTest PROPERTIES LABELS "quick") diff --git a/tests/Cube/config.yml b/tests/Cube/config.yml index 148e3a228..4872da17d 100644 --- a/tests/Cube/config.yml +++ b/tests/Cube/config.yml @@ -30,7 +30,7 @@ Global: Components: - name : cube parameters : {nlevel: 1, indexing: true} - bodyfile : cube.bods + bodyfile : cube.bods.h5 force : id : cube parameters : diff --git a/tests/Halo/config.yml b/tests/Halo/config.yml index 596d51f36..b236c74fc 100644 --- a/tests/Halo/config.yml +++ b/tests/Halo/config.yml @@ -28,7 +28,7 @@ Global: Components: - name : halo parameters : {nlevel: 1, indexing: true} - bodyfile : new.bods + bodyfile : new.bods.h5 force : id : sphereSL parameters : diff --git a/tests/check_hdf5_particles.py b/tests/check_hdf5_particles.py new file mode 100644 index 000000000..6e7924ce7 --- /dev/null +++ b/tests/check_hdf5_particles.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Check the portable EXP particle HDF5 schema produced by IC generators.""" + +import argparse +import sys + +import h5py +import numpy as np + + +def fail(message): + print(f"HDF5 particle check failed: {message}", file=sys.stderr) + raise SystemExit(1) + + +parser = argparse.ArgumentParser() +parser.add_argument("file") +parser.add_argument("--count", type=int, required=True) +parser.add_argument("--float-bytes", type=int, default=4) +parser.add_argument("--mass", type=float, default=1.0) +parser.add_argument("--aux-ints", type=int, default=0) +parser.add_argument("--aux-floats", type=int, default=0) +parser.add_argument("--cube", action="store_true", help="check that particles are in the unit cube") +parser.add_argument("--slab-paired", action="store_true", + help="check reflected pairs for a slab with unit horizontal periods") +args = parser.parse_args() + +with h5py.File(args.file, "r") as h5: + for name, expected in (("num_particles", args.count), ("num_aux_ints", args.aux_ints), + ("num_aux_floats", args.aux_floats)): + if name not in h5.attrs or h5.attrs[name] != expected: + fail(f"attribute {name!r} is not {expected}") + + if "particles" not in h5: + fail("missing /particles group") + particles = h5["particles"] + required = {"m", "x", "y", "z", "u", "v", "w"} + required.update({f"aux_int_{i}" for i in range(args.aux_ints)}) + required.update({f"aux_float_{i}" for i in range(args.aux_floats)}) + if set(particles) != required: + fail(f"unexpected datasets: {sorted(particles)}") + + for name in required: + data = particles[name] + if data.shape != (args.count,): + fail(f"/particles/{name} has shape {data.shape}, expected ({args.count},)") + if name.startswith("aux_int_"): + if data.dtype.kind != "i": + fail(f"/particles/{name} has dtype {data.dtype}, expected an integer type") + else: + if data.dtype.kind != "f" or data.dtype.itemsize != args.float_bytes: + fail(f"/particles/{name} has dtype {data.dtype}, expected float{8 * args.float_bytes}") + if not np.isfinite(data[:]).all(): + fail(f"/particles/{name} contains non-finite values") + + if not np.isclose(particles["m"][:].sum(), args.mass, rtol=2e-4, atol=2e-4): + fail(f"particle masses do not sum to {args.mass}") + if args.cube: + for name in ("x", "y", "z"): + if (particles[name][:] < 0.0).any() or (particles[name][:] > 1.0).any(): + fail(f"/particles/{name} is outside the unit cube") + + if args.slab_paired: + if args.count % 2: + fail("paired slab output has an odd particle count") + for name in ("x", "y", "z", "u", "v", "w"): + values = particles[name][:] + expected = 1.0 if name in ("x", "y") else 0.0 + if not np.allclose(values[::2] + values[1::2], expected, atol=1e-6): + fail(f"/particles/{name} does not contain reflected pairs") diff --git a/tests/test_hdf5_ics.py b/tests/test_hdf5_ics.py new file mode 100644 index 000000000..2e56402fa --- /dev/null +++ b/tests/test_hdf5_ics.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Exercise EXP's IC generators and evolved-halo readers in a scratch directory.""" + +import argparse +from pathlib import Path +import os +import re +import shlex +import shutil +import subprocess +import sys +import tempfile + +import h5py +import numpy as np + + +PHASE_SPACE = ("m", "x", "y", "z", "u", "v", "w") +TEST_ORIGIN = np.array([0.125, -0.25, 0.5, -0.375, 0.25, 0.125]) +ORIGIN_OPTIONS = tuple(option for axis, value in zip(PHASE_SPACE[1:], TEST_ORIGIN) + for option in (f"--{axis.upper()}0", str(value))) +CASES = ("slabics", "cubeics", "gensph", "zangics", "gendisk", "gendisk2d", "gendisk-gas") + + +# (compression, compression_opts, shuffle) as h5py reports them for each +# HDF5 filter ID written by EXP::ParticleHDF5 +FILTER_PROPS = {1: ("gzip", 5, True), 2: (None, None, True), 3: (None, None, False), + 4: ("szip", ("nn", 16), False)} + + +def expected_filter(log, requested=1, count=None): + """Filter properties for a file written by the run that produced log. + + A generator that cannot use the requested filter (e.g. no SZIP encoder) + warns "using filter N ... instead" and writes with filter N. SZIP is + skipped for datasets shorter than its 16-element block. + """ + match = re.search(r"using filter (\d+) ", log.read_text()) + used = int(match.group(1)) if match else requested + if used == 4 and count is not None and count < 16: + return (None, None, False) + return FILTER_PROPS[used] + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def read_hdf5(path, count, *, float_bytes=4, aux_ints=0, aux_floats=0, + mass=None, compression=("gzip", 5, True)): + with h5py.File(path, "r") as file: + for key, expected in (("num_particles", count), ("num_aux_ints", aux_ints), + ("num_aux_floats", aux_floats)): + require(file.attrs[key] == expected, f"{path}: incorrect {key}") + group = file["particles"] + ints = tuple(f"aux_int_{i}" for i in range(aux_ints)) + floats = tuple(f"aux_float_{i}" for i in range(aux_floats)) + fields = PHASE_SPACE + ints + floats + require(set(group) == set(fields), f"{path}: incorrect datasets") + for name in fields: + dataset = group[name] + require(dataset.shape == (count,), f"{path}: incorrect shape for {name}") + kind, size = ("i", 4) if name in ints else ("f", float_bytes) + require((dataset.dtype.kind, dataset.dtype.itemsize) == (kind, size), + f"{path}: incorrect type for {name}") + require(np.isfinite(dataset[:]).all(), f"{path}: non-finite values in {name}") + require((dataset.compression, dataset.compression_opts, dataset.shuffle) == compression, + f"{path}: incorrect compression properties for {name}") + for name in ints + floats: + require(np.count_nonzero(group[name][:]) == 0, f"{path}: {name} should be zero") + values = np.column_stack([group[name][:] for name in PHASE_SPACE]) + if mass is not None: + np.testing.assert_allclose(values[:, 0].sum(dtype=np.float64), mass, rtol=3e-4, + err_msg=f"{path}: incorrect total mass") + return values + + +def particle_center(values): + return np.average(values[:, 1:], weights=values[:, 0], axis=0) + + +def check_center(values, label): + np.testing.assert_allclose(particle_center(values), TEST_ORIGIN, rtol=0, atol=1e-11, + err_msg=f"{label}: incorrect position or velocity center") + + +def read_ascii(path, count): + with path.open() as file: + header = tuple(int(value) for value in file.readline().split()) + require(header == (count, 0, 0), f"{path}: incorrect ASCII header {header}") + particles = np.loadtxt(file, ndmin=2) + require(particles.shape == (count, 7), f"{path}: incorrect ASCII particle shape") + return particles + + +def paired_slab(run, path, _model): + common = ("--seed", "17", "--model", "Sech2mu", "--Lx", "2", "--Ly", "3") + log = run(*common, "--number", "15", "--outfile", "paired") + paired = read_hdf5(path / "paired.h5", 16, mass=1, compression=expected_filter(log)) + np.testing.assert_allclose(paired[::2, 1:] + paired[1::2, 1:], + np.tile([2, 3, 0, 0, 0, 0], (8, 1)), atol=1e-6) + run(*common, "--number", "15", "--ascii", "--outfile", "paired.txt") + np.testing.assert_allclose(read_ascii(path / "paired.txt", 16), paired, + rtol=2e-6, atol=1e-8) + log = run(*common, "--number", "15", "--no-paired", "--double", + "--nauxint", "1", "--nauxfloat", "2", "--filter", "2", "--outfile", "single") + single = read_hdf5(path / "single.h5", 15, float_bytes=8, aux_ints=1, aux_floats=2, + mass=1, compression=expected_filter(log, 2)) + require(not np.allclose(single[0, 1:] + single[1, 1:], [2, 3, 0, 0, 0, 0]), + "slabics --no-paired still generated reflected partners") + + +def cube(run, path, _model): + common = ("--number", "16", "--seed", "17", "--zerovel") + log = run(*common, "--file", "cube") + values = read_hdf5(path / "cube.h5", 16, mass=1, compression=expected_filter(log)) + require(((values[:, 1:4] >= 0) & (values[:, 1:4] <= 1)).all(), + "cubeics positions are outside the unit cube") + run(*common, "--ascii", "--file", "cube.txt") + np.testing.assert_allclose(read_ascii(path / "cube.txt", 16), values, rtol=2e-6, atol=1e-8) + # HDF5 registered filter IDs: 2 = SHUFFLE only, 3 = FLETCHER32, 4 = SZIP. + # SZIP encoding is missing from many HDF5 builds; cubeics then falls + # back to GZIP, and expected_filter() reads that from the run log. + for fid, count in ((2, 16), (3, 16), (4, 16), (4, 8)): + name = f"cube_f{fid}_n{count}" + log = run("--number", str(count), "--seed", "17", "--zerovel", + "--filter", str(fid), "--file", name) + expected = expected_filter(log, fid, count) + require(fid == 4 or "using filter" not in log.read_text(), + f"{name}: unexpected filter fallback") + result = read_hdf5(path / f"{name}.h5", count, mass=1, compression=expected) + with h5py.File(path / f"{name}.h5", "r") as file: + require(file["particles/x"].fletcher32 == (fid == 3), + f"{name}: incorrect fletcher32 setting") + if count == 16: + np.testing.assert_allclose(result, values) + +def sphere(run, path, model): + common = ("-N", "16", "-i", str(model), "--NUMG", "100", "--SEED", "17", + "--zeropos", "--zerovel", *ORIGIN_OPTIONS) + log = run(*common, "--double", "--NI", "1", "--ND", "2", "-o", "sphere") + values = read_hdf5(path / "sphere.h5", 16, float_bytes=8, aux_ints=1, aux_floats=2, + mass=1.008, compression=expected_filter(log)) + check_center(values, "gensph") + run(*common, "--ascii", "-o", "sphere.txt") + np.testing.assert_allclose(read_ascii(path / "sphere.txt", 16), values, + rtol=2e-6, atol=1e-8) + + +def zang(run, path, _model): + common = ("--number", "16", "--seed", "17") + log = run(*common, "--NI", "1", "--ND", "2", "--file", "zang") + values = read_hdf5(path / "zang.h5", 16, aux_ints=1, aux_floats=2, + compression=expected_filter(log)) + run(*common, "--ascii", "--file", "zang.txt") + np.testing.assert_allclose(read_ascii(path / "zang.txt", 16), values, + rtol=6e-6, atol=1e-8) + + +def disk(run, path, model, *, planar=False, gas=False): + count = 10_000 + common = ("--nhalo", str(count), "--ndisk", str(count), "--SEED", "17", + "--NUMX", "128", "--NUMY", "64", "--PNUM", "0", "--MMAX", "2", + "--cachefile", "basis.cache", "--halofile1", str(model), "--double", + "--LMAX", "4", "--NMAXH", "4", "--NMAXD", "4", "--NUMR", "1000") + if planar: + common += ("--TNUM", "40", "--RMIN", "3.333e-05") + else: + common += ("--ignore", "--TNUM", "32", "--LMAXFID", "8", "--NMAXFID", "12", + "--H5compress", "5", "--H5shuffle=true") + + if gas: + gas_options = ("--ngas", "16", "--ngparam", "2", "--gas_mass", "0.01") + log = run(*common, *gas_options, "--hbods", "halo", "--dbods", "disk", "--gbods", "gas") + base = read_hdf5(path / "gas.h5", 16, float_bytes=8, aux_floats=2, mass=0.01, + compression=expected_filter(log)) + log = run(*common, *gas_options, *ORIGIN_OPTIONS, + "--hbods", "shifted-halo", "--dbods", "shifted-disk", "--gbods", "shifted-gas") + shifted = read_hdf5(path / "shifted-gas.h5", 16, float_bytes=8, aux_floats=2, mass=0.01, + compression=expected_filter(log)) + np.testing.assert_allclose(shifted[:, 0], base[:, 0], rtol=0, atol=0) + np.testing.assert_allclose(shifted[:, 1:] - base[:, 1:], + np.broadcast_to(TEST_ORIGIN, shifted[:, 1:].shape), + rtol=0, atol=1e-11) + for triple in particle_center(base).reshape(2, 3): + require(not np.allclose(triple, 0, rtol=0, atol=1e-8), + "gendisk gas was forced to have a zero position or velocity center") + return + + log = run(*common, *ORIGIN_OPTIONS, "--hbods", "halo", "--dbods", "disk") + expected = expected_filter(log) + halo = read_hdf5(path / "halo.h5", count, float_bytes=8, mass=1.0079, compression=expected) + check_center(halo, "generated halo") + check_center(read_hdf5(path / "disk.h5", count, float_bytes=8, mass=0.05, + compression=expected), "generated disk") + # The basis cache asks for GZIP via --H5compress; skip the check in + # the unlikely case that this HDF5 has no GZIP (particles fell back + # to shuffle only) + if not planar and expected[0] == "gzip": + with h5py.File(path / "basis.cache", "r") as cache: + dataset = cache["Cosine/0/0/potC"] + require(dataset.compression == "gzip" and dataset.compression_opts == 5 + and dataset.shuffle, "gendisk basis cache ignored compression settings") + + # Evolved-halo input is in the model frame. Undo the output shift, + # then feed identical coordinates to both native readers. + halo[:, 1:] -= TEST_ORIGIN + local_halo = path / "local-halo.h5" + shutil.copyfile(path / "halo.h5", local_halo) + with h5py.File(local_halo, "r+") as file: + for i, name in enumerate(PHASE_SPACE[1:], 1): + file["particles"][name][:] = halo[:, i] + np.savetxt(path / "halo.txt", halo, fmt="%.17g", header=f"{count} 0 0", comments="") + + # A complete center file overrides conflicting command-line origins. + centerfile = path / "center.txt" + np.savetxt(centerfile, TEST_ORIGIN.reshape(2, 3), fmt="%.17g") + zero_options = tuple("0" if i % 2 else option for i, option in enumerate(ORIGIN_OPTIONS)) + log_hdf5 = run(*common, *zero_options, "--centerfile", str(centerfile), + "--evolved", "--hbods", "local-halo", "--dbods", "from-hdf5") + log_ascii = run(*common, *ORIGIN_OPTIONS, "--evolved", "--hbods", "halo.txt", + "--dbods", "from-ascii") + from_hdf5 = read_hdf5(path / "from-hdf5.h5", count, float_bytes=8, mass=0.05, + compression=expected_filter(log_hdf5)) + from_ascii = read_hdf5(path / "from-ascii.h5", count, float_bytes=8, mass=0.05, + compression=expected_filter(log_ascii)) + for values in (from_hdf5, from_ascii): + check_center(values, "evolved disk") + values[:, 1:] -= TEST_ORIGIN + if planar: + # The planar generator produced different particle draws across runs + # with the same seed. Compare the sampled distributions. + for values in (from_hdf5, from_ascii): + np.testing.assert_array_equal(values[:, [3, 6]], 0) + for columns in ((1, 2), (4, 5)): + quantiles = [np.quantile(np.linalg.norm(values[:, columns], axis=1), [0.1, 0.5, 0.9]) + for values in (from_hdf5, from_ascii)] + np.testing.assert_allclose(*quantiles, rtol=0.03) + else: + np.testing.assert_allclose(from_hdf5, from_ascii, rtol=1e-10, atol=1e-12) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("build_dir", type=Path, help="configured and built EXP directory") + parser.add_argument("--bin-dir", type=Path, help="override build_dir/utils/ICs") + parser.add_argument("--case", action="append", choices=CASES, help="run only this case; repeatable") + parser.add_argument("--mpi-launcher", default="mpirun", help="MPI launcher with optional arguments") + parser.add_argument("--ranks", type=int, default=2) + parser.add_argument("--timeout", type=int, default=300, help="seconds allowed per generator run") + parser.add_argument("--keep", action="store_true", help="keep scratch output after success") + args = parser.parse_args() + if args.ranks < 1 or args.timeout < 1: + parser.error("--ranks and --timeout must be positive") + bin_dir = (args.bin_dir or args.build_dir / "utils/ICs").resolve() + model = Path(__file__).resolve().parent / "Halo/SLGridSph.model" + launcher = shlex.split(args.mpi_launcher) + if not launcher: + parser.error("--mpi-launcher must contain a command") + scratch = Path(tempfile.mkdtemp(prefix="exp-hdf5-ics-")) + cases = {"slabics": paired_slab, "cubeics": cube, "gensph": sphere, "zangics": zang, + "gendisk": disk, "gendisk2d": lambda *params: disk(*params, planar=True), + "gendisk-gas": lambda *params: disk(*params, gas=True)} + + def run_case(name): + path = scratch / name + path.mkdir() + executable = bin_dir / ("gendisk" if name == "gendisk-gas" else name) + require(executable.is_file(), f"missing executable: {executable}") + command = [str(executable)] + if name in ("gensph", "gendisk", "gendisk2d", "gendisk-gas"): + command = [*launcher, "-n", str(args.ranks), *command] + invocation = 0 + + def run(*options): + nonlocal invocation + invocation += 1 + log = path / f"run-{invocation}.log" + with log.open("w") as output: + print(shlex.join(command + list(options)), file=output, flush=True) + subprocess.run([*command, *options], cwd=path, stdout=output, + stderr=subprocess.STDOUT, timeout=args.timeout, check=True, + env=dict(os.environ, OMP_NUM_THREADS="1")) + return log + + cases[name](run, path, model) + print(f"PASS {name}", flush=True) + + failed = False + for name in dict.fromkeys(args.case or CASES): + try: + run_case(name) + except (AssertionError, OSError, subprocess.SubprocessError, KeyError) as error: + failed = True + print(f"FAIL {name}: {error}", file=sys.stderr, flush=True) + if failed: + parser.exit(1, f"Test files and generator logs are in {scratch}\n") + if args.keep: + print(f"Test files and logs are in {scratch}") + else: + shutil.rmtree(scratch) + + +if __name__ == "__main__": + main() diff --git a/utils/ICs/ParticleHDF5.H b/utils/ICs/ParticleHDF5.H new file mode 100644 index 000000000..2cf588b62 --- /dev/null +++ b/utils/ICs/ParticleHDF5.H @@ -0,0 +1,502 @@ +#ifndef EXP_PARTICLE_HDF5_H +#define EXP_PARTICLE_HDF5_H + +// Help class for writing the EXP phase-space HDF5 schema from a +// phase-space array. The schema unchanged from the Component update +// and is the same one tested by the hdf5bods and slabics +// implementations. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +namespace EXP +{ + + namespace ParticleHDF5 + { + + //! Pack particle records with the requested output origin. + template + inline std::vector> + records(const Particles& particles, + const std::array& position_origin, + const std::array& velocity_origin) + { + std::vector> result; + result.reserve(particles.size()); + for (const auto& p : particles) + result.push_back({p.mass, + p.pos[0] + position_origin[0], p.pos[1] + position_origin[1], + p.pos[2] + position_origin[2], p.vel[0] + velocity_origin[0], + p.vel[1] + velocity_origin[1], p.vel[2] + velocity_origin[2]}); + return result; + } + + //! Human-readable name for a supported filter ID, or nullptr if + //! the ID is not supported by ParticleHDF5. The IDs are HDF5's + //! own registered filter IDs (H5Zpublic.h and the HDF Group + //! filter registry), so they are passed to HDF5 unchanged. + inline const char* filter_name(unsigned filter) + { + switch (filter) { + case H5Z_FILTER_DEFLATE: return "GZIP (DEFLATE)"; // 1 + case H5Z_FILTER_SHUFFLE: return "SHUFFLE only (no compression)"; // 2 + case H5Z_FILTER_FLETCHER32: return "FLETCHER32 (checksum, no compression)"; // 3 + case H5Z_FILTER_SZIP: return "SZIP"; // 4 + case 307: return "BZIP2"; + case 32001: return "BLOSC"; + case 32004: return "LZ4"; + default: return nullptr; + } + } + + //! Check a filter ID at option-parse time and return the filter + //! to use. An ID that ParticleHDF5 does not support, or a filter + //! that is not available for encoding in this HDF5 library or on + //! HDF5_PLUGIN_PATH, is replaced by GZIP (1), or by SHUFFLE only + //! (2) in the unlikely case that this HDF5 has no GZIP. A warning + //! is printed to std::cerr when warn is true (pass myid==0). + inline unsigned check_filter(unsigned filter, bool warn = true) + { + auto can_encode = [](unsigned id) + { + const auto fid = static_cast(id); + if (H5Zfilter_avail(fid) <= 0) return false; + unsigned int config = 0; + if (H5Zget_filter_info(fid, &config) < 0) return false; + return (config & H5Z_FILTER_CONFIG_ENCODE_ENABLED) != 0; + }; + + const unsigned fallback = + can_encode(H5Z_FILTER_DEFLATE) ? H5Z_FILTER_DEFLATE : H5Z_FILTER_SHUFFLE; + + const char* name = filter_name(filter); + if (name == nullptr) { + if (warn) + std::cerr << "**** WARNING: HDF5 filter ID " << filter << " is not supported." + << " Supported IDs are 1 (GZIP), 2 (SHUFFLE only)," + << " 3 (FLETCHER32), 4 (SZIP), 307 (BZIP2), 32001 (BLOSC)," + << " 32004 (LZ4)." << std::endl + << "**** WARNING: using filter " << fallback << " (" + << filter_name(fallback) << ") instead." << std::endl; + return fallback; + } + + if (can_encode(filter)) return filter; + + if (warn) + std::cerr << "**** WARNING: HDF5 filter " << filter << " (" << name << ")" + << " is not available for encoding in this HDF5 build or on" + << " HDF5_PLUGIN_PATH." << std::endl + << "**** WARNING: using filter " << fallback << " (" + << filter_name(fallback) << ") instead." << std::endl; + return fallback; + } + + //! Create a HighFive::DataSetCreateProps object with chunking and + //! optional filter. The filter ID is HDF5's registered ID; see + //! filter_name() for the supported list. + inline HighFive::DataSetCreateProps properties(hsize_t size, unsigned filter) + { + HighFive::DataSetCreateProps props; + + // An empty particle file has zero-length datasets, which cannot + // be chunked or filtered; store them contiguously + if (size == 0) return props; + + // Chunk length (in elements, not bytes) is min(size, 262144) + props.add(HighFive::Chunking({std::min(size, 262144)})); + + // Byte shuffle helps the general-purpose compressors. It is + // skipped for FLETCHER32 (checksum only, no compression), SZIP + // (which does its own preprocessing) and BLOSC (which shuffles + // internally). + if (filter != H5Z_FILTER_FLETCHER32 && filter != H5Z_FILTER_SZIP && + filter != 32001) + props.add(HighFive::Shuffle()); + + // We could use HighFive::Deflate(level) for GZIP, but we want + // to support other filters as well, so we use the HDF5 C API + // directly. Filter IDs are HDF5's registered IDs: + // + // 1: GZIP (DEFLATE) H5Z_FILTER_DEFLATE + // 2: SHUFFLE only H5Z_FILTER_SHUFFLE + // 3: FLETCHER32 checksum H5Z_FILTER_FLETCHER32 + // 4: SZIP H5Z_FILTER_SZIP + // 307: BZIP2 (plugin) + // 32001: BLOSC (plugin) + // 32004: LZ4 (plugin) + // + // See https://github.com/HDFGroup/hdf5_plugins/blob/master/docs/RegisteredFilterPlugins.md + // + hid_t plist = props.getId(); + auto check = [filter](herr_t status) + { + if (status < 0) + throw std::runtime_error("ParticleHDF5: could not add HDF5 filter " + + std::to_string(filter) + " to the dataset properties"); + }; + auto set_filter = [plist, filter, &check](size_t nelmts, const unsigned* values) + { + check(H5Pset_filter(plist, filter, H5Z_FLAG_OPTIONAL, nelmts, values)); + }; + switch (filter) { + case H5Z_FILTER_DEFLATE: + case 307: + { + const unsigned level = 5; + set_filter(1, &level); + break; + } + case H5Z_FILTER_SHUFFLE: + break; // shuffle (added above) only + case H5Z_FILTER_FLETCHER32: + check(H5Pset_fletcher32(plist)); + break; + case H5Z_FILTER_SZIP: + // SZIP needs at least pixels_per_block (16) elements per chunk; + // smaller datasets are stored uncompressed + if (size < 16) break; + // Nearest-neighbor coding, 16 pixels per block + check(H5Pset_szip(plist, H5_SZIP_NN_OPTION_MASK, 16)); + break; + case 32004: + { + const unsigned options[] = {0}; + set_filter(1, options); + break; + } + case 32001: + { + const unsigned options[] = {0, 0, 0, 0, 5, 1, 1}; + set_filter(7, options); + break; + } + default: + throw std::invalid_argument("ParticleHDF5: unsupported HDF5 filter ID"); + } + return props; + } + + //! Write a particle phase-space file with optional auxiliary integer and floating-point data. + template + inline void write(const std::string& filename, + const std::vector& m, const std::vector& x, + const std::vector& y, const std::vector& z, + const std::vector& u, const std::vector& v, + const std::vector& w, + const std::vector>& aux_ints, + const std::vector>& aux_floats, + const std::optional>& index, + unsigned filter) + { + const auto count = m.size(); // zero writes a valid, empty file + if (count > static_cast(std::numeric_limits::max())) + throw std::overflow_error("ParticleHDF5: particle count exceeds the file format limit"); + if (x.size() != count || y.size() != count || z.size() != count || + u.size() != count || v.size() != count || w.size() != count) + throw std::invalid_argument("ParticleHDF5: inconsistent phase-space vector sizes"); + + HighFive::File file(filename, HighFive::File::ReadWrite | HighFive::File::Create | HighFive::File::Truncate); + + const int n = static_cast(count); + file.createAttribute("num_particles", HighFive::DataSpace::From(n)).write(n); + + const int num_aux_ints = static_cast(aux_ints.size()); + const int num_aux_floats = static_cast(aux_floats.size()); + file.createAttribute("num_aux_ints", HighFive::DataSpace::From(num_aux_ints)).write(num_aux_ints); + file.createAttribute("num_aux_floats", HighFive::DataSpace::From(num_aux_floats)).write(num_aux_floats); + + auto group = file.createGroup("particles"); + auto props = properties(count, filter); + group.createDataSet("m", m, props); group.createDataSet("x", x, props); group.createDataSet("y", y, props); + group.createDataSet("z", z, props); group.createDataSet("u", u, props); group.createDataSet("v", v, props); + group.createDataSet("w", w, props); + if (index) group.createDataSet("index", *index, props); + for (size_t j = 0; j < aux_ints.size(); ++j) + group.createDataSet("aux_int_" + std::to_string(j), aux_ints[j], props); + for (size_t j = 0; j < aux_floats.size(); ++j) + group.createDataSet("aux_float_" + std::to_string(j), aux_floats[j], props); + } + + //! Write a particle phase-space file from a vector of 7-element arrays with optional auxiliary integer and floating-point data. + template + inline void write(const std::string& filename, + const std::vector>& particles, + int num_aux_ints, int num_aux_floats, unsigned filter) + { + std::vector m, x, y, z, u, v, w; + m.reserve(particles.size()); x.reserve(particles.size()); y.reserve(particles.size()); z.reserve(particles.size()); + u.reserve(particles.size()); v.reserve(particles.size()); w.reserve(particles.size()); + for (const auto& p : particles) { + m.push_back(p[0]); x.push_back(p[1]); y.push_back(p[2]); z.push_back(p[3]); + u.push_back(p[4]); v.push_back(p[5]); w.push_back(p[6]); + } + if (num_aux_ints < 0 || num_aux_floats < 0) + throw std::invalid_argument("ParticleHDF5: auxiliary field counts must be non-negative"); + std::vector> auxi(num_aux_ints, std::vector(particles.size(), 0)); + std::vector> auxf(num_aux_floats, std::vector(particles.size(), 0)); + write(filename, m, x, y, z, u, v, w, auxi, auxf, std::nullopt, filter); + } + + //! Read this rank's portion of an evolved halo body file, in HDF5 or ASCII. + template + inline int read_halo(const std::string& filename, std::vector& particles, + int rank, int ranks) + { + std::string path = filename; + std::ifstream input(path); + if (!input) { + path += ".h5"; + input.clear(); + input.open(path); + } + if (!input) + throw std::runtime_error("cannot open halo body file " + filename + " or " + filename + ".h5"); + + const htri_t hdf5 = H5Fis_hdf5(path.c_str()); + if (hdf5 < 0) + throw std::runtime_error("cannot identify halo body file format: " + path); + + // Rank zero gets the remainder, matching the legacy ASCII partition. + auto partition = [rank, ranks](int total) { + const int per_rank = total / ranks; + const int remainder = total % ranks; + return std::make_pair(rank == 0 ? 0 : rank*per_rank + remainder, + per_rank + (rank == 0 ? remainder : 0)); + }; + + int total = 0, ni = 0, nd = 0; + auto validate_header = [&] { + if (total < 0 || ni < 0 || nd < 0) + throw std::runtime_error("invalid halo body file header: " + path); + }; + + if (hdf5 > 0) { + input.close(); + HighFive::File file(path, HighFive::File::ReadOnly); + total = file.getAttribute("num_particles").read(); + ni = file.getAttribute("num_aux_ints").read(); + nd = file.getAttribute("num_aux_floats").read(); + validate_header(); + + const auto range = partition(total); + const int start = range.first, count = range.second; + particles.assign(count, Particle(ni, nd)); + auto group = file.getGroup("particles"); + + auto read_column = [&](const std::string& name, auto value, auto assign) { + using T = decltype(value); + auto dataset = group.getDataSet(name); + if (dataset.getDimensions() != std::vector{static_cast(total)}) + throw std::runtime_error("invalid length for /particles/" + name + " in " + path); + if (count == 0) return; + auto column = dataset.select({static_cast(start)}, {static_cast(count)}) + .template read>(); + for (int i=0; i positions = {"x", "y", "z"}; + const std::array velocities = {"u", "v", "w"}; + for (int k=0; k<3; ++k) { + read_column(positions[k], 0.0, [k](Particle& p, double value) { p.pos[k] = value; }); + read_column(velocities[k], 0.0, [k](Particle& p, double value) { p.vel[k] = value; }); + } + for (int k=0; k> total >> ni >> nd)) + throw std::runtime_error("invalid ASCII halo body file header: " + path); + validate_header(); + + const auto [start, count] = partition(total); + particles.clear(); + particles.reserve(count); + auto read_line = [&] { + if (!std::getline(input, line)) + throw std::runtime_error("truncated ASCII halo body file: " + path); + }; + for (int i=0; i> particle.mass; + for (auto& value : particle.pos) row >> value; + for (auto& value : particle.vel) row >> value; + for (auto& value : particle.iattrib) row >> value; + for (auto& value : particle.dattrib) row >> value; + if (!row) + throw std::runtime_error("invalid ASCII particle record in " + path); + } + return total; + } + + //! Collect rank-local phase space records and have rank zero write + //! one file. + //! + //! The records are gathered and written one phase-space column at a + //! time, so rank zero holds at most one column of the full particle + //! set (8 bytes per particle, plus 4 more for a float32 copy) rather + //! than all seven (56 bytes per particle). Ranks with no particles + //! are fine, and if no rank has any particles a valid, empty file + //! (num_particles = 0) is written. If rank zero cannot write the + //! file, it reports the error and the run is stopped with + //! MPI_Abort. MPI must be initialized: EXP IC generators that call + //! this are always MPI programs. + inline void gather_and_write(const std::string& filename, + const std::vector>& local, + int num_aux_ints, int num_aux_floats, + unsigned filter, bool double_precision, + MPI_Comm comm = MPI_COMM_WORLD) + { + // This is an MPI-only path + // + int is_init = 0; + MPI_Initialized(&is_init); + if (not is_init) + throw std::logic_error("ParticleHDF5::gather_and_write: MPI is not initialized"); + + if (num_aux_ints < 0 || num_aux_floats < 0) + throw std::invalid_argument("ParticleHDF5: auxiliary field counts must be non-negative"); + + int myid = 0, ranks = 1; + MPI_Comm_rank(comm, &myid); + MPI_Comm_size(comm, &ranks); + + // The file schema uses an int for the particle count, so the + // per-column Gatherv counts and offsets (in doubles) fit in an + // int as well. + constexpr unsigned long long max_particles = std::numeric_limits::max(); + const unsigned long long local_size = std::min(local.size(), max_particles + 1); + unsigned long long total = 0; + MPI_Allreduce(&local_size, &total, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, comm); + if (total > max_particles) + throw std::overflow_error("ParticleHDF5: particle count exceeds the file format limit"); + // total == 0 falls through and writes a valid, empty file + + const int local_count = static_cast(local_size); + const size_t count = static_cast(total); + std::vector counts(myid == 0 ? ranks : 0), offsets; + MPI_Gather(&local_count, 1, MPI_INT, counts.data(), 1, MPI_INT, 0, comm); + + if (myid == 0) { + offsets.resize(ranks); + int offset = 0; + for (int i=0; i file; + std::optional group; + std::optional props; + + auto attempt = [&](auto&& action) { + if (myid != 0 || !error.empty()) return; + try { action(); } + catch (const std::exception& e) { error = e.what(); } + }; + + attempt([&] { + file.emplace(filename, HighFive::File::ReadWrite | HighFive::File::Create | HighFive::File::Truncate); + const int n = static_cast(count); + file->createAttribute("num_particles", HighFive::DataSpace::From(n)).write(n); + file->createAttribute("num_aux_ints", HighFive::DataSpace::From(num_aux_ints)).write(num_aux_ints); + file->createAttribute("num_aux_floats", HighFive::DataSpace::From(num_aux_floats)).write(num_aux_floats); + group.emplace(file->createGroup("particles")); + props.emplace(properties(count, filter)); + }); + + static constexpr std::array names = {"m", "x", "y", "z", "u", "v", "w"}; + std::vector send(local_count), column(myid == 0 ? count : 0); + for (size_t col = 0; col < names.size(); ++col) { + for (int i = 0; i < local_count; ++i) send[i] = local[i][col]; + MPI_Gatherv(send.data(), local_count, MPI_DOUBLE, column.data(), + counts.data(), offsets.data(), MPI_DOUBLE, 0, comm); + + attempt([&] { + if (double_precision) + group->createDataSet(names[col], column, *props); + else + group->createDataSet(names[col], std::vector(column.begin(), column.end()), *props); + }); + } + + // Release the column buffers before writing the auxiliary fields + std::vector().swap(column); + std::vector().swap(send); + + attempt([&] { + if (num_aux_ints > 0) { + std::vector auxi(count, 0); + for (int j = 0; j < num_aux_ints; ++j) + group->createDataSet("aux_int_" + std::to_string(j), auxi, *props); + } + if (num_aux_floats > 0) { + if (double_precision) { + std::vector auxf(count, 0); + for (int j = 0; j < num_aux_floats; ++j) + group->createDataSet("aux_float_" + std::to_string(j), auxf, *props); + } else { + std::vector auxf(count, 0); + for (int j = 0; j < num_aux_floats; ++j) + group->createDataSet("aux_float_" + std::to_string(j), auxf, *props); + } + } + file->flush(); + }); + + // Close the file on root before reporting the outcome + group.reset(); + file.reset(); + + // Share root's outcome and stop the run if the write failed + int failed = error.empty() ? 0 : 1; + MPI_Bcast(&failed, 1, MPI_INT, 0, comm); + if (failed) { + if (myid == 0) + std::cerr << "**** ParticleHDF5: FAILED to write phase-space file <" + << filename << ">: " << error << std::endl + << "**** ParticleHDF5: stopping the run" << std::endl; + MPI_Abort(comm, 1); + } + } + + } // namespace ParticleHDF5 + +} // namespace EXP + +#endif diff --git a/utils/ICs/ZangICs.cc b/utils/ICs/ZangICs.cc index dcc286d0b..e70f09c82 100644 --- a/utils/ICs/ZangICs.cc +++ b/utils/ICs/ZangICs.cc @@ -18,6 +18,7 @@ #include "Progress.H" // Progress bar #include "cxxopts.H" // Option parsing +#include "ParticleHDF5.H" // Particle HDF5 output int main(int ac, char **av) @@ -28,12 +29,17 @@ main(int ac, char **av) int N; // Number of particles int Nrepl; // Number of particle replicates per orbit + int NI, ND; // Number of integer and double attributes double mu, nu, Ri, Ro; // Taper paramters double Rmin, Rmax; // Radial range double sigma; // Velocity dispersion std::string bodyfile; // Output file unsigned seed; // Will be inialized by /dev/random if // not set on the command line + unsigned hdf5_filter = 1; // HDF5 filter ID (1 = GZIP, 2 = SHUFFLE only, 3 = FLETCHER32, 4 = SZIP) + bool hdf5_output = true; // Write HDF5 output by default + bool hdf5_double = false; // Write HDF5 output in double precision + cxxopts::Options options(av[0], "Ideal tapered Mestel IC generator"); @@ -42,6 +48,11 @@ main(int ac, char **av) ("V,nozerovel", "Do not zero the mean velocity") ("P,nozeropos", "Do not zero the center of mass") ("d,debug", "Print debug grid") + ("5,hdf5", "Write HDF5 phase-space output (default)") + ("A,ascii", "Write old-style ASCII output (default is HDF5)") + ("8,double", "Use float64 HDF5 output (default is float32)") + ("Z,filter", "HDF5 filter ID: 1=GZIP (default), 2=SHUFFLE only, 3=FLETCHER32, 4=SZIP, 307=BZIP2, 32001=BLOSC, 32004=LZ4", + cxxopts::value(hdf5_filter)->default_value("1")) ("N,number", "Number of particles to generate", cxxopts::value(N)->default_value("100000")) ("n,nu", "Inner taper exponent (0 for no taper)", @@ -64,6 +75,10 @@ main(int ac, char **av) cxxopts::value(Nrepl)->default_value("1")) ("f,file", "Output body file", cxxopts::value(bodyfile)->default_value("zang.bods")) + ("NI", "Number of integer attributes for PSP file", + cxxopts::value(NI)->default_value("0")) + ("ND", "Number of double attributes for PSP file", + cxxopts::value(ND)->default_value("0")) ; cxxopts::ParseResult vm; @@ -82,6 +97,15 @@ main(int ac, char **av) return 1; } + if (vm.count("hdf5")) hdf5_output = true; + if (vm.count("ascii")) hdf5_output = false; + hdf5_double = vm.count("double") > 0; + + // Check the HDF5 filter now, before any expensive work. An + // unsupported or unavailable filter falls back to GZIP with a warning. + // + if (hdf5_output) hdf5_filter = EXP::ParticleHDF5::check_filter(hdf5_filter, true); + // Set from /dev/random if not specified if (vm.count("seed")==0) { seed = std::random_device{}(); @@ -99,11 +123,14 @@ main(int ac, char **av) // Open the output file // - std::ofstream out(bodyfile); - if (not out) { - std::string msg(av[0]); - msg += ": output file <" + bodyfile + "> can not be opened"; - throw std::runtime_error(msg); + std::ofstream out; + if (not hdf5_output) { + out.open(bodyfile); + if (not out) { + std::string msg(av[0]); + msg += ": output file <" + bodyfile + "> can not be opened"; + throw std::runtime_error(msg); + } } SphericalOrbit::ZFRAC=0.3; // TEST @@ -294,16 +321,27 @@ main(int ac, char **av) std::cout << "** " << over << " particles failed acceptance" << std::endl << "** Particle mass=" << mass << std::endl; - out << std::setw(8) << N << std::setw(8) << 0 << std::setw(8) << 0 - << std::endl; + if (not hdf5_output) { + out << std::setw(8) << N << std::setw(8) << 0 << std::setw(8) << 0 + << std::endl; + } double ektot = 0.0, clausius = 0.0; - for (int n=0; n> hdf5_particles; + for (int n=0; n(bodyfile + ".h5", hdf5_particles, NI, ND, hdf5_filter); + } + if (vm.count("debug")) { std::cout << std::endl << "Peak per energy" << std::endl; for (int i=0; i<=numE; i++) { diff --git a/utils/ICs/cubeICs.cc b/utils/ICs/cubeICs.cc index fff4586ed..ff853ace4 100644 --- a/utils/ICs/cubeICs.cc +++ b/utils/ICs/cubeICs.cc @@ -15,6 +15,7 @@ #include #include "cxxopts.H" +#include "ParticleHDF5.H" int main(int ac, char **av) @@ -28,6 +29,8 @@ main(int ac, char **av) std::string bodyfile; // Output file unsigned seed; // Will be inialized by /dev/random if // not set on the command line + unsigned hdf5_filter = 1; + bool hdf5_output = true, hdf5_double = false; // Default values for the velocity dispersion and bulk velocity // @@ -55,6 +58,11 @@ main(int ac, char **av) cxxopts::value(seed)) ("o,file", "Output body file", cxxopts::value(bodyfile)->default_value("cube.bods")) + ("5,hdf5", "Write HDF5 phase-space output (default)") + ("A,ascii", "Write old-style ASCII output (default is HDF5)") + ("8,double", "Use float64 HDF5 output (default is float32)") + ("f,filter", "HDF5 filter ID: 1=GZIP (default), 2=SHUFFLE only, 3=FLETCHER32, 4=SZIP, 307=BZIP2, 32001=BLOSC, 32004=LZ4", + cxxopts::value(hdf5_filter)->default_value("1")) ("w,wave", "Perturbation wave vector", cxxopts::value>(pert)) ("p,pamp", "Perturbation amplitude", @@ -76,6 +84,14 @@ main(int ac, char **av) std::cout << options.help() << std::endl << std::endl; return 1; } + if (vm.count("hdf5")) hdf5_output = true; + if (vm.count("ascii")) hdf5_output = false; + hdf5_double = vm.count("double") > 0; + + // Check the HDF5 filter now, before any expensive work. An + // unsupported or unavailable filter falls back to GZIP with a warning. + // + if (hdf5_output) hdf5_filter = EXP::ParticleHDF5::check_filter(hdf5_filter, true); // Set from /dev/random if not specified if (vm.count("seed")==0) { @@ -116,19 +132,22 @@ main(int ac, char **av) // Make sure N>0 if (N<=0) { - std::cerr << av[0] << ": you must requiest at least one body" + std::cerr << av[0] << ": you must request at least one body" << std::endl; + return 1; } // Open the output file // - std::ofstream out(bodyfile); + std::ofstream out; + if (!hdf5_output) out.open(bodyfile); - if (out) { + if (hdf5_output || out) { // Header // - out << std::setw(10) << N << std::setw(10) << 0 << std::setw(10) << 0 - << std::endl << std::setprecision(10); + if (!hdf5_output) + out << std::setw(10) << N << std::setw(10) << 0 << std::setw(10) << 0 + << std::endl << std::setprecision(10); std::mt19937 gen(seed); std::uniform_real_distribution<> uniform(0.0, 1.0); @@ -184,19 +203,31 @@ main(int ac, char **av) double mass = M/N; - for (int i=0; i> particles; + particles.reserve(N); + for (int i=0; i(bodyfile + ".h5", particles, 0, 0, hdf5_filter); + else + EXP::ParticleHDF5::write(bodyfile + ".h5", particles, 0, 0, hdf5_filter); + } else { + for (int i=0; i& chunk_dims, - unsigned int filter_id, - // Scale from 1 (fast) to 9 (max compression) - int compression_level = 5) -{ - HighFive::DataSetCreateProps props; - props.add(HighFive::Chunking(chunk_dims)); - - // For most compressors, applying shuffle improves compression for - // floating-point data. (Blosc can do its own shuffling internally; - // shuffle-only/checksum-only are handled below.) - if (filter_id != 3 && filter_id != 4 && filter_id != 32001) { - props.add(HighFive::Shuffle()); - } - hid_t plist_id = props.getId(); - std::vector cd_values; - - switch (filter_id) { - case 1: // Deflate / GZIP (Built-in) - // Expects 1 parameter: compression level (0-9) - cd_values = { static_cast(compression_level) }; - break; - - case 2: // SZIP (Built-in) - // SZIP is complex and highly variant; HighFive includes native - // wrappers. For raw testing, standard pixels-per-block option is - // typically 16. - cd_values = { 141, 16 }; - break; - - case 3: // Shuffle Filter alone (No trailing compression) - props.add(HighFive::Shuffle()); - return props; - - case 4: // Fletcher32 Checksum alone (Data validation, not compression) - // Fletcher32 uses built-in ID 4 and accepts 0 configuration - // arguments. Call the native HDF5 library directly using - // HighFive's internal handle. - H5Pset_filter(plist_id, 4, H5Z_FLAG_OPTIONAL, 0, NULL); - return props; - - case 307: // BZip2 - // Expects 1 parameter: Block size in 100KB steps (1-9) - cd_values = { static_cast(compression_level) }; - break; - - case 32004: // LZ4 - // Expects 1 parameter: internal chunk/block size. - // 0 falls back to the default (64KB), optimized for CPU caches. - cd_values = { 0 }; - break; - - case 32001: // Blosc (v1 Meta-Compressor) - // Expects 7 parameters. Slots 0-3 are reserved. - // [4]=level(1-9), [5]=shuffle type(1=byte, 2=bit), [6]=codec code - // Codecs: 0=blosclz, 1=lz4, 2=lz4hc, 3=snappy, 4=zlib, 5=zstd - cd_values = { 0, 0, 0, 0, - static_cast(compression_level), - 1, // 1 = Byte Shuffle (Highly recommended for float/double) - 1 }; // 1 = Redirect internal processing to LZ4 - break; - - default: - throw std::invalid_argument("Unknown or unsupported testing filter ID requested."); - } - - // Pass the custom properties down to the HDF5 backend pipeline - if (!cd_values.empty()) { - H5Pset_filter(plist_id, filter_id, H5Z_FLAG_OPTIONAL, cd_values.size(), cd_values.data()); - } - - return props; -} - -// Specify floating point precision -enum class FloatPrecision { FLOAT32, FLOAT64 }; +#include "ParticleHDF5.H" // Template to handle float and double precision for particle data template @@ -124,6 +36,7 @@ struct ParticleData size_t num_aux_floats = 0; }; + // Write particle data to HDF5 file with specified filter and precision template void write_hdf5_data(const std::string& outfile, @@ -131,65 +44,10 @@ void write_hdf5_data(const std::string& outfile, unsigned filter_id, bool verbose) { - // Create HDF5 file with compression enabled (SEQUENTIAL - thread-safe) - // - if (verbose) std::cout << "Writing HDF5 file..." << std::endl; - std::string hdf5_file = outfile + ".h5"; - File file(hdf5_file, File::ReadWrite | File::Create | File::Truncate); - - // Store header information and precision metadata - // - file.createAttribute("num_particles", DataSpace::From(data.num_particles)) - .write(data.num_particles); - file.createAttribute("num_aux_ints", DataSpace::From(data.num_aux_ints)) - .write(data.num_aux_ints); - file.createAttribute("num_aux_floats", DataSpace::From(data.num_aux_floats)) - .write(data.num_aux_floats); - - // Create a group for particle data - // - Group particles_group = file.createGroup("particles"); - - // Calculate optimized, capped chunk size - // - hsize_t chunk_size = 262144; // Cachesafe cap (~2MB for double) - if (data.num_particles < chunk_size) { - chunk_size = std::max(1024, data.num_particles); - } - if (chunk_size > data.num_particles) { - chunk_size = data.num_particles; // Absolute safety fallback - } - - // Define compression filter - // - auto props = createFilterProps({chunk_size}, filter_id, 5); - - // Write datasets sequentially (HDF5 is not fully thread-safe for writing) - particles_group.createDataSet("m", data.m, props); - particles_group.createDataSet("x", data.x, props); - particles_group.createDataSet("y", data.y, props); - particles_group.createDataSet("z", data.z, props); - particles_group.createDataSet("u", data.u, props); - particles_group.createDataSet("v", data.v, props); - particles_group.createDataSet("w", data.w, props); - - // Write optional index dataset if present - if (data.index.has_value()) { - particles_group.createDataSet("index", *data.index, props); - } - - // Write auxiliary integer fields - for (size_t j = 0; j < data.aux_ints.size(); ++j) { - std::string dset_name = "aux_int_" + std::to_string(j); - particles_group.createDataSet(dset_name, data.aux_ints[j], props); - } - - // Write auxiliary float fields - for (size_t j = 0; j < data.aux_floats.size(); ++j) { - std::string dset_name = "aux_float_" + std::to_string(j); - particles_group.createDataSet(dset_name, data.aux_floats[j], props); - } + EXP::ParticleHDF5::write(hdf5_file, data.m, data.x, data.y, data.z, + data.u, data.v, data.w, data.aux_ints, + data.aux_floats, data.index, filter_id); if (verbose) { std::string precision_str = "float32"; @@ -225,7 +83,7 @@ main(int argc, char **argv) ("P,no-paired","Do not use paired sampling") ("v,verbose", "Verbose output") ("8,double", "Use double precision for HDF5 output (default is float)") - ("f,filter", "HDF5 filter ID to use (default: 1 = GZIP)", cxxopts::value(filter_id)->default_value("1")) + ("f,filter", "HDF5 filter ID: 1=GZIP (default), 2=SHUFFLE only, 3=FLETCHER32, 4=SZIP, 307=BZIP2, 32001=BLOSC, 32004=LZ4", cxxopts::value(filter_id)->default_value("1")) ("N,number", "Number of bodies", cxxopts::value(Num_particles)->default_value("10000")) ("nauxint", "Number of auxiliary integer fields", @@ -287,10 +145,20 @@ main(int argc, char **argv) if (vm.count("hdf5")) HDF5 = true; if (vm.count("ascii")) HDF5 = false; + // Check the HDF5 filter now, before any expensive work. An + // unsupported or unavailable filter falls back to GZIP with a warning. + // + if (HDF5) filter_id = EXP::ParticleHDF5::check_filter(filter_id, true); + if (vm.count("paired")) paired = true; if (vm.count("no-paired")) paired = false; + if (Num_particles <= 0) + throw std::invalid_argument("number of particles must be positive"); + if (paired and Num_particles % 2 != 0) { + if (Num_particles == std::numeric_limits::max()) + throw std::invalid_argument("paired sampling requires a representable even particle count"); std::cerr << "Error: Paired sampling requires an even number of particles, incrementing by 1." << std::endl; Num_particles++; } @@ -370,6 +238,7 @@ main(int argc, char **argv) double KE = 0.0; double VC = 0.0; + double mass = mu/Num_particles; if (vm.count("verbose")) { @@ -402,7 +271,9 @@ main(int argc, char **argv) data.num_particles = Num_particles; data.num_aux_ints = Num_aux_ints; data.num_aux_floats = Num_aux_floats; - + + if (Num_aux_ints < 0 || Num_aux_floats < 0) + throw std::invalid_argument("auxiliary field counts must be non-negative"); data.aux_ints.resize(Num_aux_ints); for (auto& vec : data.aux_ints) { vec.resize(Num_particles); @@ -417,37 +288,30 @@ main(int argc, char **argv) // fields to zero } - // This is fast enough that multithreading is not strictly - // necessary, but we can use OpenMP to parallelize the particle - // generation loop. The reduction clause is used to accumulate - // KE and VC across threads. -#pragma omp parallel for schedule(dynamic, 256) reduction(+:KE, VC) num_threads(omp_get_max_threads()) + // Generate serially so the seeded RNG state is never shared. for (int n=0; nget_dpot(data.z[n]); - - if (paired) { - n++; - data.m[n] = mass; - data.x[n] = Lx - data.x[n-1]; - data.y[n] = Ly - data.y[n-1]; - data.z[n] = -data.z[n-1]; - data.u[n] = -data.u[n-1]; - data.v[n] = -data.v[n-1]; - data.w[n] = -data.w[n-1]; - - KE += data.w[n] * data.w[n]; - VC += data.z[n] * model->get_dpot(data.z[n]); - } + data.m[n] = mass; + data.x[n] = Lx*Unit(gen); + data.y[n] = Ly*Unit(gen); + data.z[n] = odd2(Unit(gen)*M.back(), M, Z); + data.u[n] = Vh(gen); + data.v[n] = Vh(gen); + data.w[n] = Vv(gen); + KE += data.w[n] * data.w[n]; + VC += data.z[n] * model->get_dpot(data.z[n]); + + if (paired) { + ++n; + data.m[n] = mass; + data.x[n] = Lx - data.x[n-1]; + data.y[n] = Ly - data.y[n-1]; + data.z[n] = -data.z[n-1]; + data.u[n] = -data.u[n-1]; + data.v[n] = -data.v[n-1]; + data.w[n] = -data.w[n-1]; + KE += data.w[n] * data.w[n]; + VC += data.z[n] * model->get_dpot(data.z[n]); + } } write_hdf5_data(outfile, data, filter_id, vm.count("verbose") > 0); @@ -490,7 +354,7 @@ main(int argc, char **argv) Eigen::MatrixXd posvel(Num_particles, 6); // Generate particles -#pragma omp parallel for schedule(dynamic, 256) reduction(+:KE, VC) num_threads(omp_get_max_threads()) + // Generate serially so the seeded RNG state is not shared across threads. for (int n=0; nget_dpot(posvel(n, 2)); + if (paired) { + ++n; + posvel.row(n) = -posvel.row(n-1); + posvel(n, 0) += Lx; + posvel(n, 1) += Ly; + KE += posvel(n, 5)*posvel(n, 5); + VC += posvel(n, 2)*model->get_dpot(posvel(n, 2)); + } } std::cout << "Done generating particles" << std::endl; @@ -517,4 +389,3 @@ main(int argc, char **argv) return 0; } - diff --git a/utils/ICs/gensph.cc b/utils/ICs/gensph.cc index 4d72a2e70..f75cfbe9e 100644 --- a/utils/ICs/gensph.cc +++ b/utils/ICs/gensph.cc @@ -49,6 +49,7 @@ #include "fpetrap.h" #include "cxxopts.H" #include "EXPini.H" +#include "ParticleHDF5.H" // Reference to n-body globals // @@ -76,6 +77,8 @@ main(int argc, char **argv) double Emin0, Emax0, Kmin0, Kmax0, RBAR, MBAR, BRATIO, CRATIO, SMOOTH; bool LOGR, ELIMIT, VERBOSE, GRIDPOT, MODELS, EBAR, zeropos, zerovel; bool VTEST; + bool hdf5_output = true, hdf5_double = false; + unsigned hdf5_filter = 1; std::string INFILE, MMFILE, OUTFILE, OUTPS, config; const double goldenRatio = 1.618033988749895; @@ -108,6 +111,11 @@ main(int argc, char **argv) cxxopts::value(MMFILE)) ("o,PSFILE", "Phase-space output file", cxxopts::value(OUTPS)->default_value("new.bods")) + ("5,hdf5", "Write HDF5 phase-space output (default)") + ("A,ascii", "Write old-style ASCII output (default is HDF5)") + ("8,double", "Use float64 HDF5 output (default is float32)") + ("f,filter", "HDF5 filter ID: 1=GZIP (default), 2=SHUFFLE only, 3=FLETCHER32, 4=SZIP, 307=BZIP2, 32001=BLOSC, 32004=LZ4", + cxxopts::value(hdf5_filter)->default_value("1")) ("p,prefix", "Diagnostic output file prefix", cxxopts::value(OUTFILE)->default_value("gensph")) ("zeropos", "Set the origin at the center of mass", @@ -259,6 +267,14 @@ main(int argc, char **argv) return 0; } } + if (vm.count("hdf5")) hdf5_output = true; + if (vm.count("ascii")) hdf5_output = false; + hdf5_double = vm.count("double") > 0; + + // Check the HDF5 filter now, before any expensive work. An + // unsupported or unavailable filter falls back to GZIP with a warning. + // + if (hdf5_output) hdf5_filter = EXP::ParticleHDF5::check_filter(hdf5_filter, myid==0); if (vm.count("verbose")) VERBOSE = true; else VERBOSE = false; @@ -272,9 +288,10 @@ main(int argc, char **argv) // std::ostringstream sout; sout << OUTPS << "." << myid; - std::ofstream out(sout.str()); + std::ofstream out; int bad = 0; - if (!out) { + if (!hdf5_output) out.open(sout.str()); + if (!hdf5_output && !out) { std::cerr << "[" << myid << "] Couldn't open <" << sout.str() << "> for output" << std::endl; bad = 1; @@ -285,8 +302,10 @@ main(int argc, char **argv) exit(-1); } - out.precision(11); - out.setf(ios::scientific, ios::floatfield); + if (!hdf5_output) { + out.precision(11); + out.setf(ios::scientific, ios::floatfield); + } // Begin integration // @@ -701,6 +720,7 @@ main(int argc, char **argv) int ierr; Eigen::VectorXd ps(7), ps0(7); + std::vector> hdf5_particles; ps0[0] = 0.0; ps0[1] = X0; @@ -710,7 +730,7 @@ main(int argc, char **argv) ps0[5] = V0; ps0[6] = W0; - if (myid==0) { + if (!hdf5_output && myid==0) { out << std::setw(12) << N << std::setw( 6) << NI << std::setw( 6) << ND << std::endl; } @@ -849,10 +869,13 @@ main(int argc, char **argv) ps[0] *= mass; PS.push_back(ps); zz[0] += ps[0]; - if (zeropos) for (int i=1; i<3; i++) zz[i] -= ps[0]*ps[i]; + if (zeropos) for (int i=1; i<4; i++) zz[i] -= ps[0]*ps[i]; if (zerovel) for (int i=4; i<7; i++) zz[i] -= ps[0]*ps[i]; } - else { + else if (hdf5_output) { + hdf5_particles.push_back({mass * ps[0], ps[1] + ps0[1], ps[2] + ps0[2], ps[3] + ps0[3], + ps[4] + ps0[4], ps[5] + ps0[5], ps[6] + ps0[6]}); + } else { out << std::setw(20) << mass * ps[0]; for (int i=1; i<=6; i++) out << std::setw(20) << ps[i]+ps0[i]; @@ -919,6 +942,11 @@ main(int argc, char **argv) } for (auto ps : PS) { + if (hdf5_output) { + hdf5_particles.push_back({ps[0], ps[1] + ps0[1], ps[2] + ps0[2], ps[3] + ps0[3], + ps[4] + ps0[4], ps[5] + ps0[5], ps[6] + ps0[6]}); + continue; + } out << std::setw(20) << ps[0]; for (int i=1; i<=6; i++) out << std::setw(20) << ps[i]+ps0[i]; @@ -966,14 +994,20 @@ main(int argc, char **argv) } out.close(); + if (hdf5_output) + EXP::ParticleHDF5::gather_and_write(OUTPS + ".h5", hdf5_particles, NI, ND, hdf5_filter, hdf5_double); MPI_Barrier(MPI_COMM_WORLD); // Make the final phase-space file and clean up // - if (myid==0) { + if (!hdf5_output && myid==0) { std::ostringstream sout; - sout << "cat " << OUTPS << ".* > " << OUTPS; - sout << "; rm " << OUTPS << ".*"; + sout << "cat"; + for (int rank=0; rank " << OUTPS << "; rm"; + for (int rank=0; rank #include +#include +#include +#include +#include + #include +#include "quickdigest5.hpp" #include "config_exp.h" #ifdef HAVE_OMP_H #include @@ -103,6 +109,7 @@ #include "libvars.H" // Library globals #include "cxxopts.H" // Command-line parsing #include "EXPini.H" // Ini-style config +#include "ParticleHDF5.H" #include "norminv.H" @@ -400,9 +407,11 @@ main(int ac, char **av) double disk_mass, gas_mass, gscal_length, ToomreQ, Temp, Tmin; bool const_height, images, multi, basis, zeropos, zerovel; bool report, ignore, evolved, diskmodel; - int nhalo, ndisk, ngas, ngparam; + int nhalo, ndisk, ngas, ngparam, H5compress; std::string hbods, dbods, gbods, outtag, runtag, centerfile, halofile1, halofile2; std::string cachefile, config, gentype, dtype, dmodel, mtype, ctype; + unsigned hdf5_filter = 1; + bool hdf5_output = true, hdf5_double = false, H5shuffle = false; const std::string mesg("Generates a Monte Carlo realization of a halo with an\n embedded disk using Jeans' equations\n"); @@ -427,6 +436,11 @@ main(int ac, char **av) cxxopts::value(gbods)->default_value("gas.bods")) ("dbods", "The output bodyfile for the stellar disc", cxxopts::value(dbods)->default_value("disk.bods")) + ("5,hdf5", "Write HDF5 phase-space output (default)") + ("A,ascii", "Write old-style ASCII output (default is HDF5)") + ("8,double", "Use float64 HDF5 output (default is float32)") + ("f,filter", "HDF5 filter ID: 1=GZIP (default), 2=SHUFFLE only, 3=FLETCHER32, 4=SZIP, 307=BZIP2, 32001=BLOSC, 32004=LZ4", + cxxopts::value(hdf5_filter)->default_value("1")) ("cachefile", "The cache file for the cylindrical basis", cxxopts::value(cachefile)->default_value(".eof.cache.file")) ("ctype", "DiskHalo radial coordinate scaling type (one of: Linear, Log,Rat)", @@ -539,6 +553,10 @@ main(int ac, char **av) cxxopts::value(gas_mass)->default_value("0.0")) ("scale_length", "Scale length for the realized disk", cxxopts::value(scale_length)->default_value("0.01")) + ("gscal_length", "Gas disk scale length (inherits scale_length when omitted)", + cxxopts::value(gscal_length)) + ("scale_lenfkN", "Gas sampling scale length (inherits scale_length when omitted)", + cxxopts::value(scale_lenfkN)) ("scale_height", "Scale height for the realized disk", cxxopts::value(scale_height)->default_value("0.001")) ("ToomreQ", "Toomre Q parameter for the disk", @@ -613,9 +631,15 @@ main(int ac, char **av) cxxopts::value(runtag)) ("threads", "Number of threads to run", cxxopts::value(nthrds)->default_value("1")) + ("H5compress", "HDF5 compression level (0-9)", + cxxopts::value(H5compress)->default_value("5")) + ("H5shuffle", "HDF5 shuffle filter (true/false)", + cxxopts::value(H5shuffle)->default_value("false")) ("allow", "Allow multimass algorithm to generature negative masses for testing") ("nomono", "Allow non-monotonic mass interpolation") ("diskmodel", "Table describing the model for the disk plane") + ("ortho", "Check the orthogonality of the basis functions") + ("spline", "Use spline interpolation for the spherical model table") ("pyname", "Name of module with the user-specified target disk density", cxxopts::value(pyname)) ; @@ -670,6 +694,26 @@ main(int ac, char **av) return 0; } } + if (!vm.count("gscal_length")) gscal_length = scale_length; + if (!vm.count("scale_lenfkN")) scale_lenfkN = scale_length; + + if (vm.count("hdf5")) hdf5_output = true; + if (vm.count("ascii")) hdf5_output = false; + hdf5_double = vm.count("double") > 0; + + // Check the HDF5 filter now, before any expensive work. An + // unsupported or unavailable filter falls back to GZIP with a warning. + // + if (hdf5_output) hdf5_filter = EXP::ParticleHDF5::check_filter(hdf5_filter, myid==0); + + // The basis-cache compression level is passed to H5Pset_deflate, + // which only accepts 0-9 + // + if (H5compress < 0 || H5compress > 9) { + if (myid==0) std::cerr << "**** WARNING: --H5compress must be between 0 and 9" + << " (got " << H5compress << "); using 5" << std::endl; + H5compress = 5; + } if (vm.count("spline")) { SphericalModelTable::linear = 0; @@ -908,6 +952,8 @@ main(int ac, char **av) EmpCylSL::CMAPZ = CMAPZ; EmpCylSL::VFLAG = VFLAG; EmpCylSL::logarithmic = LOGR; + EmpCylSL::H5compress = H5compress; + EmpCylSL::H5shuffle = H5shuffle; // Create expansion only if needed . . . std::shared_ptr expandd; @@ -918,19 +964,19 @@ main(int ac, char **av) expandd = std::make_shared(NMAXFID, LMAXFID, MMAX, NMAXD, ASCALE, HSCALE, NODD, cachefile); #ifdef DEBUG - std::cout << "Process " << myid << ": " - << " rmin=" << EmpCylSL::RMIN - << " rmax=" << EmpCylSL::RMAX - << " a=" << ASCALE - << " h=" << HSCALE - << " nmaxfid=" << NMAXFID - << " lmaxfid=" << LMAXFID - << " mmax=" << MMAX - << " nmax=" << NMAXD - << " nodd=" << NODD - << std::endl << std::flush; + std::cout << "Process " << myid << ": " + << " rmin=" << EmpCylSL::RMIN + << " rmax=" << EmpCylSL::RMAX + << " a=" << ASCALE + << " h=" << HSCALE + << " nmaxfid=" << NMAXFID + << " lmaxfid=" << LMAXFID + << " mmax=" << MMAX + << " nmax=" << NMAXD + << " nodd=" << NODD + << std::endl << std::flush; #endif - + // Try to read existing cache to get EOF // if (not ignore) { @@ -947,7 +993,7 @@ main(int ac, char **av) return 0; } } - + // Use these user models to deproject for the EOF spherical basis // if (vm.count("deproject")) { @@ -955,7 +1001,7 @@ main(int ac, char **av) // height relative to the length // double H = scale_height/scale_length; - + // The model instance (you can add others in DiskModels.H). // It's MN or Exponential if not MN. // @@ -983,6 +1029,67 @@ main(int ac, char **av) if (expcond and not save_eof) { expandd->generate_eof(RNUM, PNUM, TNUM, dcond); save_eof = true; + + if (myid==0) { + + // Orthogonalith check for the cylindrical basis functions + // + if (vm.count("ortho")) { + auto oc = expandd->orthoCheck(); + for (int M=0; M to cache file <" << cachefile << ">" << std::endl; + + // Write the md5sum for the Python module + if (DTYPE == DiskType::python) { + try { + std::vector pyinfo = + {pyname, QuickDigest5::fileToHash(pyname + ".py")}; + + file.createAttribute("pythonDiskType", pyinfo); + + std::cout << "---- Cylindrical: writing pythonDiskType <" << pyname + ".py" + << "> to cache file <" << cachefile << ">" << std::endl; + + + } catch (const std::runtime_error& e) { + if (myid==0) { + std::cerr << "BiorthBasis::Cylindrical error: " + << e.what() + << ", can not write the pyname and md5 hash to HDF5" + << std::endl; + } + } + } + } catch (const HighFive::Exception& err) { + if (myid==0) { + std::cerr << err.what() << std::endl; + std::cerr << "Error writing metadata to cache file <" << cachefile + << std::endl; + } + } + // Errors will prevent metadata from being written to the cache + } + // Only the root process should be updating the cache } // Basis orthgonality check @@ -1020,44 +1127,25 @@ main(int ac, char **av) if (myid==0) std::cout << "done" << std::endl; } + std::array position_origin = {X0, Y0, Z0}; + std::array velocity_origin = {U0, V0, W0}; std::ifstream center(centerfile); - if (center) { - - bool ok = true; - - center >> X0; - if (center.fail()) ok = false; - - center >> Y0; - if (center.fail()) ok = false; - - center >> Z0; - if (center.fail()) ok = false; - - if (ok) { - diskhalo->set_pos_origin(X0, Y0, Z0); - if (myid==0) std::cout << "Using position origin: " - << X0 << ", " << Y0 << ", " << Z0 << std::endl; - } - - center >> U0; - if (center.fail()) ok = false; - - center >> V0; - if (center.fail()) ok = false; - - center >> W0; - if (center.fail()) ok = false; + std::array origin; + if (center >> origin[0] >> origin[1] >> origin[2]) { + position_origin = origin; + if (center >> origin[0] >> origin[1] >> origin[2]) + velocity_origin = origin; + } - if (ok) { - diskhalo->set_vel_origin(U0, V0, W0); - if (myid==0) std::cout << "Using velocity origin: " - << U0 << ", " << V0 << ", " << W0 << std::endl; - } + diskhalo->set_pos_origin(position_origin[0], position_origin[1], position_origin[2]); + diskhalo->set_vel_origin(velocity_origin[0], velocity_origin[1], velocity_origin[2]); + if (myid == 0) { + std::cout << "Using position origin: " << position_origin[0] << ", " + << position_origin[1] << ", " << position_origin[2] << std::endl; + std::cout << "Using velocity origin: " << velocity_origin[0] << ", " + << velocity_origin[1] << ", " << velocity_origin[2] << std::endl; } - // Make zero center of mass and - // center of velocity diskhalo->zero_com(zeropos); diskhalo->zero_cov(zerovel); @@ -1067,7 +1155,7 @@ main(int ac, char **av) // before realizing a large phase space) std::ofstream out_halo, out_disk; if (myid==0) { - if (not evolved and n_particlesH) { + if (!hdf5_output && not evolved && n_particlesH) { out_halo.open(hbods); if (!out_halo) { cout << "Could not open <" << hbods << "> for output\n"; @@ -1076,7 +1164,7 @@ main(int ac, char **av) } } - if (ndisk) { + if (!hdf5_output && ndisk) { out_disk.open(dbods); if (!out_disk) { std::cout << "Could not open <" << dbods << "> for output" << std::endl; @@ -1088,55 +1176,13 @@ main(int ac, char **av) //=================Make the phase space coordinates========================== - if (evolved) { // --------------------------- - // Use existing halo body file - std::ifstream hin(hbods); // --------------------------- - - if (hin) { - std::string line; - std::getline(hin, line); - std::istringstream sin(line); - - int niatr, ndatr; - sin >> nhalo; - sin >> niatr; - sin >> ndatr; - - // Divvy up the particles by core. The root node gets any - // remainder. - // - n_particlesH = nhalo/numprocs; - - int ibeg = 0; - int iend = nhalo - n_particlesH*(numprocs-myid-1); - - if (myid>0) { - ibeg = nhalo - n_particlesH*(numprocs-myid); - for (int i=0; i> P.mass; - for (int k=0; k<3; k++) sin >> P.pos[k]; - for (int k=0; k<3; k++) sin >> P.vel[k]; - for (int k=0; k> P.iattrib[k]; - for (int k=0; k> P.dattrib[k]; - hparticles.push_back(P); - } - - } else { - // Error message - if (myid==0) - std::cout << "Could not read halo file <" << hbods - << "> . . . quitting" << std::endl; - - MPI_Barrier(MPI_COMM_WORLD); - MPI_Finalize(); - exit(-1); + if (evolved) { + try { + nhalo = EXP::ParticleHDF5::read_halo(hbods, hparticles, myid, numprocs); + } catch (const std::exception& error) { + std::cerr << "Process " << myid << ": " << error.what() << std::endl; + MPI_Abort(MPI_COMM_WORLD, 1); + return 1; } std::cout << "Process " << myid << " has " << hparticles.size() @@ -1477,13 +1523,19 @@ main(int ac, char **av) if (not evolved) { if (myid==0) std::cout << "Writing phase space file for halo . . . " << std::flush; - diskhalo->write_file(out_halo, hparticles); + if (hdf5_output) + EXP::ParticleHDF5::gather_and_write(hbods + ".h5", EXP::ParticleHDF5::records(hparticles, position_origin, velocity_origin), 0, 0, hdf5_filter, hdf5_double); + else + diskhalo->write_file(out_halo, hparticles); if (myid==0) std::cout << "done" << std::endl; out_halo.close(); } if (myid==0) std::cout << "Writing phase space file for disk . . . " << std::flush; - diskhalo->write_file(out_disk, dparticles); + if (hdf5_output) + EXP::ParticleHDF5::gather_and_write(dbods + ".h5", EXP::ParticleHDF5::records(dparticles, position_origin, velocity_origin), 0, 0, hdf5_filter, hdf5_double); + else + diskhalo->write_file(out_disk, dparticles); if (myid==0) std::cout << "done" << std::endl; out_disk.close(); // Diagnostic . . . @@ -1693,9 +1745,11 @@ main(int ac, char **av) // // Prepare output stream // - ofstream outps("gas.bods"); - if (!outps) { - cerr << "Couldn't open <" << "gas.bods" << "> for output\n"; + ofstream outps; + std::vector> gas_particles; + if (!hdf5_output) outps.open(gbods); + if (!hdf5_output && !outps) { + cerr << "Couldn't open <" << gbods << "> for output\n"; exit (-1); } @@ -1726,8 +1780,8 @@ main(int ac, char **av) gmass = gmass0; fr = fz = potr = 0.0; - outps << setw(8) << ngas - << setw(6) << 0 << setw(6) << ngparam << endl; + if (!hdf5_output) + outps << setw(8) << ngas << setw(6) << 0 << setw(6) << ngparam << endl; for (int n=0; n gas_record = { + gmass, x + position_origin[0], y + position_origin[1], z + position_origin[2], + u + velocity_origin[0], v + velocity_origin[1], w + velocity_origin[2] + }; + if (hdf5_output) { + gas_particles.push_back(gas_record); + } else { + for (double value : gas_record) outps << setw(18) << value; + for (int k=0; kaccumulated_eval(R, z, phi, p0, p, fr, fz, fp); @@ -1828,6 +1885,20 @@ main(int ac, char **av) std::cout << endl << "Done!" << std::endl; + if (hdf5_output) { + try { + if (hdf5_double) + EXP::ParticleHDF5::write(gbods + ".h5", gas_particles, 0, ngparam, hdf5_filter); + else + EXP::ParticleHDF5::write(gbods + ".h5", gas_particles, 0, ngparam, hdf5_filter); + } catch (const std::exception& e) { + std::cerr << "**** FAILED to write gas phase-space file <" << gbods + << ".h5>: " << e.what() << std::endl + << "**** stopping the run" << std::endl; + MPI_Abort(MPI_COMM_WORLD, 1); + } + } + std::cout << "****************************" << std::endl << " Gas disk" << std::endl << "----------------------------" << std::endl diff --git a/utils/ICs/initial2d.cc b/utils/ICs/initial2d.cc index 5acbda48b..432f8e9e7 100644 --- a/utils/ICs/initial2d.cc +++ b/utils/ICs/initial2d.cc @@ -50,6 +50,7 @@ #include "libvars.H" // Library globals #include "cxxopts.H" // Command-line parsing #include "EXPini.H" // Ini-style config +#include "ParticleHDF5.H" #include "norminv.H" @@ -209,6 +210,8 @@ main(int ac, char **av) std::string hbods, dbods, suffix, centerfile, halofile1, halofile2; std::string cachefile, config, gentype, dtype, dmodel, mtype, ctype; std::string diskconf; + unsigned hdf5_filter = 1; + bool hdf5_output = true, hdf5_double = false; const std::string mesg("Generates a Monte Carlo realization of a halo with an\n embedded disk using Jeans' equations\n"); @@ -223,6 +226,11 @@ main(int ac, char **av) cxxopts::value(hbods)->default_value("halo.bods")) ("dbods", "The output bodyfile for the stellar disc", cxxopts::value(dbods)->default_value("disk.bods")) + ("5,hdf5", "Write HDF5 phase-space output (default)") + ("A,ascii", "Write old-style ASCII output (default is HDF5)") + ("8,double", "Use float64 HDF5 output (default is float32)") + ("f,filter", "HDF5 filter ID: 1=GZIP (default), 2=SHUFFLE only, 3=FLETCHER32, 4=SZIP, 307=BZIP2, 32001=BLOSC, 32004=LZ4", + cxxopts::value(hdf5_filter)->default_value("1")) ("cachefile", "The cache file for the cylindrical basis", cxxopts::value(cachefile)->default_value(".eof_2d_cache")) ("ctype", "DiskHalo radial coordinate scaling type (one of: Linear, Log,Rat)", @@ -429,6 +437,14 @@ main(int ac, char **av) return 0; } } + if (vm.count("hdf5")) hdf5_output = true; + if (vm.count("ascii")) hdf5_output = false; + hdf5_double = vm.count("double") > 0; + + // Check the HDF5 filter now, before any expensive work. An + // unsupported or unavailable filter falls back to GZIP with a warning. + // + if (hdf5_output) hdf5_filter = EXP::ParticleHDF5::check_filter(hdf5_filter, myid==0); if (vm.count("spline")) { SphericalModelTable::linear = 0; @@ -641,44 +657,25 @@ main(int ac, char **av) if (myid==0) std::cout << "done" << std::endl; } + std::array position_origin = {X0, Y0, Z0}; + std::array velocity_origin = {U0, V0, W0}; std::ifstream center(centerfile); - if (center) { - - bool ok = true; - - center >> X0; - if (center.fail()) ok = false; - - center >> Y0; - if (center.fail()) ok = false; - - center >> Z0; - if (center.fail()) ok = false; - - if (ok) { - diskhalo->set_pos_origin(X0, Y0, Z0); - if (myid==0) std::cout << "Using position origin: " - << X0 << ", " << Y0 << ", " << Z0 << std::endl; - } - - center >> U0; - if (center.fail()) ok = false; - - center >> V0; - if (center.fail()) ok = false; - - center >> W0; - if (center.fail()) ok = false; + std::array origin; + if (center >> origin[0] >> origin[1] >> origin[2]) { + position_origin = origin; + if (center >> origin[0] >> origin[1] >> origin[2]) + velocity_origin = origin; + } - if (ok) { - diskhalo->set_vel_origin(U0, V0, W0); - if (myid==0) std::cout << "Using velocity origin: " - << U0 << ", " << V0 << ", " << W0 << std::endl; - } + diskhalo->set_pos_origin(position_origin[0], position_origin[1], position_origin[2]); + diskhalo->set_vel_origin(velocity_origin[0], velocity_origin[1], velocity_origin[2]); + if (myid == 0) { + std::cout << "Using position origin: " << position_origin[0] << ", " + << position_origin[1] << ", " << position_origin[2] << std::endl; + std::cout << "Using velocity origin: " << velocity_origin[0] << ", " + << velocity_origin[1] << ", " << velocity_origin[2] << std::endl; } - // Make zero center of mass and - // center of velocity diskhalo->zero_com(zeropos); diskhalo->zero_cov(zerovel); @@ -688,7 +685,7 @@ main(int ac, char **av) // before realizing a large phase space) std::ofstream out_halo, out_disk; if (myid==0) { - if (not evolved and n_particlesH) { + if (!hdf5_output && not evolved && n_particlesH) { out_halo.open(hbods); if (!out_halo) { cout << "Could not open <" << hbods << "> for output\n"; @@ -697,7 +694,7 @@ main(int ac, char **av) } } - if (ndisk) { + if (!hdf5_output && ndisk) { out_disk.open(dbods); if (!out_disk) { std::cout << "Could not open <" << dbods << "> for output" << std::endl; @@ -709,55 +706,13 @@ main(int ac, char **av) //=================Make the phase space coordinates========================== - if (evolved) { // --------------------------- - // Use existing halo body file - std::ifstream hin(hbods); // --------------------------- - - if (hin) { - std::string line; - std::getline(hin, line); - std::istringstream sin(line); - - int niatr, ndatr; - sin >> nhalo; - sin >> niatr; - sin >> ndatr; - - // Divvy up the particles by core. The root node gets any - // remainder. - // - n_particlesH = nhalo/numprocs; - - int ibeg = 0; - int iend = nhalo - n_particlesH*(numprocs-myid-1); - - if (myid>0) { - ibeg = nhalo - n_particlesH*(numprocs-myid); - for (int i=0; i> P.mass; - for (int k=0; k<3; k++) sin >> P.pos[k]; - for (int k=0; k<3; k++) sin >> P.vel[k]; - for (int k=0; k> P.iattrib[k]; - for (int k=0; k> P.dattrib[k]; - hparticles.push_back(P); - } - - } else { - // Error message - if (myid==0) - std::cout << "Could not read halo file <" << hbods - << "> . . . quitting" << std::endl; - - MPI_Barrier(MPI_COMM_WORLD); - MPI_Finalize(); - exit(-1); + if (evolved) { + try { + nhalo = EXP::ParticleHDF5::read_halo(hbods, hparticles, myid, numprocs); + } catch (const std::exception& error) { + std::cerr << "Process " << myid << ": " << error.what() << std::endl; + MPI_Abort(MPI_COMM_WORLD, 1); + return 1; } std::cout << "Process " << myid << " has " << hparticles.size() @@ -927,13 +882,19 @@ main(int ac, char **av) if (not evolved) { if (myid==0) std::cout << "Writing phase space file for halo . . . " << std::flush; - diskhalo->write_file(out_halo, hparticles); + if (hdf5_output) + EXP::ParticleHDF5::gather_and_write(hbods + ".h5", EXP::ParticleHDF5::records(hparticles, position_origin, velocity_origin), 0, 0, hdf5_filter, hdf5_double); + else + diskhalo->write_file(out_halo, hparticles); if (myid==0) std::cout << "done" << std::endl; out_halo.close(); } if (myid==0) std::cout << "Writing phase space file for disk . . . " << std::flush; - diskhalo->write_file(out_disk, dparticles); + if (hdf5_output) + EXP::ParticleHDF5::gather_and_write(dbods + ".h5", EXP::ParticleHDF5::records(dparticles, position_origin, velocity_origin), 0, 0, hdf5_filter, hdf5_double); + else + diskhalo->write_file(out_disk, dparticles); if (myid==0) std::cout << "done" << std::endl; out_disk.close(); // Diagnostic . . .