### Compile pkdgrav3 with Specific GCC and FFTW Source: https://github.com/dpotter/pkdgrav3/blob/master/README.md A detailed example of compiling pkdgrav3 with a specific GCC version (5.3) and FFTW3 installation path. This is useful for ensuring compatibility and reproducibility. ```bash mkdir build cd build CC=/scratch/isaacaa/opt/gcc53/bin/gcc CXX=/scratch/isaacaa/opt/gcc53/bin/g++ cmake -DFFTW_ROOT=/scratch/isaacaa/opt/fftw3 .. make ``` -------------------------------- ### Configure and install project files Source: https://github.com/dpotter/pkdgrav3/blob/master/mdl2/CMakeLists.txt Configures a header file (mdl_config.h) from a template and installs the main project target and header files. This includes the main executable/library, configuration headers, and MPI-related stub headers. ```cmake CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/mdl_config.h.in ${CMAKE_CURRENT_BINARY_DIR}/mdl_config.h) install(TARGETS ${PROJECT_NAME} DESTINATION "lib") install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mdl_config.h mpi/mdl.h mpi/mdlstubs.h mdlbase.h DESTINATION "include") ``` -------------------------------- ### Set Target Include Directories and Installation Source: https://github.com/dpotter/pkdgrav3/blob/master/CMakeLists.txt Configures include paths for the 'tostd' target and defines installation rules for the project binaries. ```cmake target_include_directories(tostd PUBLIC ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME} DESTINATION "bin") install(TARGETS ${PROJECT_NAME} tostd DESTINATION "bin") ``` -------------------------------- ### Install {fmt} via Conda Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Command to install the {fmt} library using the conda-forge channel. This is the recommended method for Linux, macOS, and Windows environments. ```bash conda install -c conda-forge fmt ``` -------------------------------- ### CMake: Configure Installation Targets Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/CMakeLists.txt Configures installation targets for the fmt library and its headers. It sets up installation directories for libraries, headers, and CMake configuration files, and generates necessary package configuration files. ```cmake if (FMT_INSTALL) include(GNUInstallDirs) include(CMakePackageConfigHelpers) set_verbose(FMT_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/fmt CACHE STRING "Installation directory for cmake files, a relative path " "that will be joined to ${CMAKE_INSTALL_PREFIX}, or an arbitrary absolute path.") set(version_config ${PROJECT_BINARY_DIR}/fmt-config-version.cmake) set(project_config ${PROJECT_BINARY_DIR}/fmt-config.cmake) set(pkgconfig ${PROJECT_BINARY_DIR}/fmt.pc) set(targets_export_name fmt-targets) set (INSTALL_TARGETS fmt) if (TARGET fmt-header-only) set(INSTALL_TARGETS ${INSTALL_TARGETS} fmt-header-only) endif () set_verbose(FMT_LIB_DIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING "Installation directory for libraries, a relative path " "that will be joined to ${CMAKE_INSTALL_PREFIX}, or an arbitrary absolute path.") set_verbose(FMT_INC_DIR ${CMAKE_INSTALL_INCLUDEDIR}/fmt CACHE STRING "Installation directory for include files, a relative path " "that will be joined to ${CMAKE_INSTALL_PREFIX}, or an arbitrary absolute path.") set_verbose(FMT_PKGCONFIG_DIR ${CMAKE_INSTALL_LIBDIR}/pkgconfig CACHE PATH "Installation directory for pkgconfig (.pc) files, a relative path " "that will be joined to ${CMAKE_INSTALL_PREFIX}, or an arbitrary absolute path.") # Generate the version, config and target files into the build directory. write_basic_package_version_file( ${version_config} VERSION ${FMT_VERSION} COMPATIBILITY AnyNewerVersion) join_paths(libdir_for_pc_file "\${exec_prefix}" "${CMAKE_INSTALL_LIBDIR}") join_paths(includedir_for_pc_file "\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}") configure_file( "${PROJECT_SOURCE_DIR}/support/cmake/fmt.pc.in" "${pkgconfig}" @ONLY) configure_package_config_file( ${PROJECT_SOURCE_DIR}/support/cmake/fmt-config.cmake.in ${project_config} INSTALL_DESTINATION ${FMT_CMAKE_DIR}) # Use a namespace because CMake provides better diagnostics for namespaced # imported targets. export(TARGETS ${INSTALL_TARGETS} NAMESPACE fmt:: FILE ${PROJECT_BINARY_DIR}/${targets_export_name}.cmake) # Install version, config and target files. install( FILES ${project_config} ${version_config} DESTINATION ${FMT_CMAKE_DIR}) install(EXPORT ${targets_export_name} DESTINATION ${FMT_CMAKE_DIR} NAMESPACE fmt::) # Install the library and headers. install(TARGETS ${INSTALL_TARGETS} EXPORT ${targets_export_name} LIBRARY DESTINATION ${FMT_LIB_DIR} ARCHIVE DESTINATION ${FMT_LIB_DIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) install(FILES $ DESTINATION ${FMT_LIB_DIR} OPTIONAL) install(FILES ${FMT_HEADERS} DESTINATION ${FMT_INC_DIR}) install(FILES "${pkgconfig}" DESTINATION "${FMT_PKGCONFIG_DIR}") endif () ``` -------------------------------- ### PKDGRAV3 Parameter Configuration Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/quickstart.md An example parameter file (cosmology.par) defining initial conditions, cosmological constants, simulation accuracy settings, and I/O preferences for a PKDGRAV3 run. ```default from accuracy import classic_theta_switch,classic_replicas_switch achOutName = "example" # Initial Condition dBoxSize = 2000 # Mpc/h nGrid = 128 # Simulation has nGrid^3 particles iLPT = 2 # LPT order for IC iSeed = 314159265 # Random seed dRedFrom = 49 # Starting redshift # Cosmology achTfFile = "euclid_z0_transfer_combined.dat" h = 0.67 dOmega0 = 0.32 dLambda = 0.68 dSigma8 = 0.83 dSpectral = 0.96 iStartStep = 0 nSteps = 100 dRedTo = 0.0 # Cosmological Simulation bComove = True # Use comoving coordinates bPeriodic = True # with a periodic box bEwald = True # enable Ewald periodic boundaries # Logging/Output iOutInterval = 10 #iCheckInterval = 10 bDoDensity = False bVDetails = True bOverwrite = True bParaRead = True # Read in parallel bParaWrite = False # Write in parallel (does not work on all file systems) #nParaRead = 8 # Limit number of simultaneous readers to this #nParaWrite = 8 # Limit number of simultaneous writers to this # Accuracy Parameters bEpsAccStep = True # Choose eps/a timestep criteria dTheta = classic_theta_switch() # 0.40, 0.55, 0.70 switch nReplicas = classic_replicas_switch() # 1 if theta > 0.52 otherwise 2 # Memory and performance bMemUnordered = True # iOrder replaced by potential and group id bNewKDK = True # No accelerations in the particle, dual tree possible ``` -------------------------------- ### Restarting Pkdgrav3 Simulation Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/changes.md Demonstrates how to restart a Pkdgrav3 simulation using the updated checkpoint file format. The example shows the command-line usage for specifying the checkpoint file and how to override restart parameters. ```bash srun pkdgrav3 checkpoint.00010.chk ``` -------------------------------- ### Run pkdgrav3 Simulation Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/install.md Commands to start the pkdgrav3 simulation using the provided environment view. Includes instructions for interactive use and SLURM queue submission. ```bash uenv start --view=pkdgrav3 pkdgrav3 pkdgrav3 cosmology.par ``` ```bash #SBATCH --uenv=pkdgrav3 --view=pkdgrav3 ``` -------------------------------- ### Install C++ Format via APT Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Installs the C++ Format library on Debian-based systems using the apt-get package manager. This command is useful for developers who need the library for system-wide use. ```bash $ sudo apt-get install libcppformat1-dev ``` -------------------------------- ### Configure GSL Path with CMake Source: https://github.com/dpotter/pkdgrav3/blob/master/README.md Example of how to specify the GSL installation directory to CMake if it's not found automatically. This is crucial for linking against the GNU Scientific Library. ```bash cmake -DGSL_ROOT_DIR=/opt/gsl/2.5 ``` -------------------------------- ### Spack External Package Configuration for macOS Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/install.md Example configuration for Spack's packages.yaml file to specify external installations of Python, FFTW, and Boost on macOS, disabling Spack's build process for these packages. ```yaml python: externals: - spec: python@3.12 prefix: /opt/homebrew/opt/python@3.12 buildable: false fftw: externals: - spec: fftw@3.3.10 prefix: /opt/homebrew/Cellar/fftw/3.3.10_2 buildable: false boost: externals: - spec: boost@1.88.0 prefix: /opt/homebrew/Cellar/boost/1.88.0 buildable: false ``` -------------------------------- ### Run pkdgrav3 Simulation Source: https://github.com/dpotter/pkdgrav3/blob/master/README.md Example of how to execute the pkdgrav3 simulation using MPI. The 'mpiexec' command is used to launch the executable with a simulation parameter file. ```bash mpiexec pkdgrav3 simfile.par ``` -------------------------------- ### Install macOS Dependencies with Homebrew Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/install.md Commands to install necessary development tools and libraries for pkdgrav3 on macOS using Homebrew, including cmake, boost, fftw, and python. ```bash brew install cmake boost fftw git gsl open-mpi hdf5-mpi python pyenv pyenv-virtualenv ``` -------------------------------- ### Verify macOS Homebrew Package Locations Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/install.md Command to verify the installation path and version of Python, FFTW, and Boost installed via Homebrew on macOS. ```bash brew --prefix python@3.12 fftw boost ``` -------------------------------- ### Joining Container Elements with fmt::join (C++) Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Illustrates the use of fmt::join to format elements of a range, separated by a specified string. This example uses fmt/format.h and demonstrates formatting a vector of doubles. ```c++ #include "fmt/format.h" std::vector v = {1.2, 3.4, 5.6}; // Prints "(+01.20, +03.40, +05.60)". fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", ")); ``` -------------------------------- ### SLURM Execution Scripts for PKDGRAV3 Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/quickstart.md Example bash scripts for submitting PKDGRAV3 jobs to a SLURM scheduler, demonstrating configurations for standard nodes and NUMA-aware node architectures. ```bash #!/bin/bash -l #SBATCH --nodes=10 #SBATCH --ntasks-per-node=1 --cpus-per-task=16 --ntasks-per-core=1 srun pkdgrav3 cosmology.par ``` ```bash #!/bin/bash -l #SBATCH --nodes=10 #SBATCH --ntasks-per-node=8 --cpus-per-task=16 --ntasks-per-core=1 srun pkdgrav3 cosmology.par ``` -------------------------------- ### Install C++ Format via Homebrew Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Installs the C++ Format library on OS X using the Homebrew package manager. This command is convenient for developers working on macOS. ```bash $ brew install cppformat ``` -------------------------------- ### Configure Blitz Library Build with CMake Source: https://github.com/dpotter/pkdgrav3/blob/master/blitz/CMakeLists.txt This CMake configuration initializes the project, defines the static library target, sets up include directories for both build and public interfaces, and handles header file installation. ```cmake cmake_minimum_required(VERSION 3.12) cmake_policy(VERSION 3.12...3.27) project(blitz) set(BLITZ_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) set(BLITZ_HEADERS ${BLITZ_INCLUDE_DIR}/blitz/array.h ) add_library(blitz STATIC globals.cpp) target_include_directories(blitz INTERFACE ${BLITZ_INCLUDE_DIR}) target_include_directories(blitz PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/bzconfig.h.in ${CMAKE_CURRENT_BINARY_DIR}/bzconfig.h) install(FILES ${BLITZ_HEADERS} DESTINATION "include/blitz") ``` -------------------------------- ### Configure Boost Path with CMake Source: https://github.com/dpotter/pkdgrav3/blob/master/README.md Demonstrates how to set the BOOST_ROOT environment variable for CMake to locate the Boost C++ libraries. This is often necessary for custom installations. ```bash cmake -DBOOST_ROOT=/path/to/boost ... ``` -------------------------------- ### C++ fmt::print with Core API Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Example of using the lightweight fmt::print function from the core API for simple console output. This API is designed to improve compile times and reduce code bloat by minimizing dependencies on standard headers. ```c++ #include fmt::print("The answer is {}. ", 42); ``` -------------------------------- ### Basic Printing with {fmt} Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/README.rst Demonstrates basic printing to stdout using {fmt}'s print and printf functions. It supports Python-like format string syntax and traditional printf syntax. ```c++ fmt::print("Hello, {}!", "world"); // Python-like format string syntax fmt::printf("Hello, %s!", "world"); // printf format string syntax ``` -------------------------------- ### Basic String Formatting Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates how to format a string using fmt::format with a std::string_view. ```c++ auto message = fmt::format(std::string_view("The answer is {}."), 42); ``` -------------------------------- ### Install Ubuntu Test Suite Dependency Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/install.md Commands to install the python3-xmlrunner package for running the pkdgrav3 test suite on Ubuntu 22.04. For older versions, a pip installation within a virtual environment is suggested. ```bash sudo apt install -y python3-xmlrunner ``` ```bash pip3 install xmlrunner ``` -------------------------------- ### Initialize static strings with fmt Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates the use of fmt::format for global or static string initialization on compilers supporting constexpr. ```c++ // This works on compilers with constexpr support. static const std::string answer = fmt::format("{}", 42); ``` -------------------------------- ### Use experimental string_view with fmt Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates how to print an experimental string_view using the fmt library. ```c++ #include #include fmt::print("{}", std::experimental::string_view("foo")); ``` -------------------------------- ### Develop pkdgrav3 with User Environment Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/install.md Instructions for compiling a custom version of pkdgrav3 using a user environment and loading necessary modules like boost, cmake, and fftw. ```bash [daint]$ uenv start --view=modules pkdgrav3 [daint]$ module load boost cmake cray-mpich fftw gcc gsl hdf5 pkdgrav3-python ``` -------------------------------- ### Execute PKDGRAV3 via Command Line Source: https://context7.com/dpotter/pkdgrav3/llms.txt Demonstrates the command-line interface for executing the PKDGRAV3 binary with a specific FOF configuration. The command takes the filename, linking length, and minimum member count as arguments. ```bash ./build/pkdgrav3 fof.py example.00100 0.0015625 10 ``` -------------------------------- ### Install Ubuntu Dependencies for pkdgrav3 Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/install.md Commands to update package lists and install essential development packages for pkdgrav3 on Ubuntu 20.04 and 22.04. Includes packages for compilation, MPI, and Python. ```bash sudo apt update sudo apt install -y autoconf automake pkg-config cmake gcc g++ make gfortran git sudo apt install -y libfftw3-dev libfftw3-mpi-dev libgsl0-dev libboost-all-dev libhdf5-dev libmemkind-dev libhwloc-dev sudo apt install -y python3-dev cython3 python3-pip python3-numpy python3-ddt python3-nose python3-tomli ``` -------------------------------- ### Select and Analyze Particles Source: https://context7.com/dpotter/pkdgrav3/llms.txt Demonstrates loading a simulation snapshot and preparing the environment for particle selection and property retrieval. ```python import PKDGRAV as msr import numpy as np time = msr.load("example.00100") msr.domain_decompose() msr.build_tree() ``` -------------------------------- ### Run fmt Library Benchmarks Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/README.rst Commands to clone the benchmark repository, generate build files with CMake, and execute speed or bloat tests. ```bash git clone --recursive https://github.com/fmtlib/format-benchmark.git cd format-benchmark cmake . make speed-test make bloat-test ``` -------------------------------- ### C++ printf Enum Formatting Example Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates the corrected formatting of enums with numeric format specifiers in fmt::(s)printf. This example highlights a fix for a breaking change related to enum formatting. ```c++ enum { ANSWER = 42 }; fmt::printf("%d", ANSWER); ``` -------------------------------- ### Format Pointers with fmt Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Illustrates how to format C strings as pointers using the p specifier. ```c++ fmt::print("{:p}", "test"); // prints pointer value ``` -------------------------------- ### GET /config/blackholes Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/parameters.md Configures black hole physics, including accretion, mergers, and AGN feedback mechanisms. ```APIDOC ## GET /config/blackholes ### Description Configures the behavior of black hole particles within the simulation environment. ### Method GET ### Endpoint /config/blackholes ### Parameters #### Query Parameters - **bBlackholes** (boolean) - Optional - Enable black hole particles - **dBHAccretionAlpha** (float) - Optional - Accretion boost parameter - **dBHRadiativeEff** (float) - Optional - AGN radiative efficiency ### Response #### Success Response (200) - **config** (object) - Black hole physics parameters ``` -------------------------------- ### Check CMake Version Source: https://github.com/dpotter/pkdgrav3/blob/master/README.md Command to verify the installed version of CMake. pkdgrav3 requires version 3.14 or newer. ```bash pkdgrav3:~> cmake --version ``` -------------------------------- ### Project Initialization Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/CMakeLists.txt Initializes the project with the name 'FMT' and specifies CXX as the primary language. This command must appear after all CMake version and policy settings. ```cmake project(FMT CXX) ``` -------------------------------- ### GET /config/star-formation Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/parameters.md Manages parameters related to star formation, including density thresholds and Kennicutt-Schmidt law settings. ```APIDOC ## GET /config/star-formation ### Description Defines the conditions under which gas particles are converted into stellar particles. ### Method GET ### Endpoint /config/star-formation ### Parameters #### Query Parameters - **bStars** (boolean) - Optional - Enable stellar particles - **dSFThresholdDen** (float) - Optional - Minimum density for star formation - **dSFindexKS** (float) - Optional - Index of the Kennicutt-Schmidt law ### Response #### Success Response (200) - **settings** (object) - Star formation configuration ``` -------------------------------- ### GET /config/eos Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/parameters.md Retrieves or defines the effective equation of state (EOS) parameters for gas pressurization at high densities. ```APIDOC ## GET /config/eos ### Description Configures the polytropic effective EOS to handle gas pressure at high densities. ### Method GET ### Endpoint /config/eos ### Parameters #### Query Parameters - **bDoEOS** (boolean) - Optional - Enable polytropic effective EOS - **dEOSFloornH** (float) - Optional - Minimum density for energy floor (nH cm-3) - **dEOSPolyFloorIndex** (float) - Optional - Index of the polytropic effective EOS ### Response #### Success Response (200) - **status** (string) - Configuration status - **params** (object) - Current EOS settings ``` -------------------------------- ### Apply Runtime Width Specification Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Illustrates how to dynamically specify the width of a formatted output at runtime using the fmt library's formatting syntax. ```cpp fmt::format("{0:{1}}", 42, 5); // gives " 42" ``` -------------------------------- ### Configure PKDGRAV3 Simulation Parameters Source: https://context7.com/dpotter/pkdgrav3/llms.txt Sets up fundamental parameters for PKDGRAV3 simulations, including unit systems for mass and length, gas physics properties like initial temperature, star formation criteria, supernova feedback parameters, and memory allocation flags for hydrodynamics. These parameters control the simulation's physical behavior and computational resource usage. ```python # Unit system for galaxy simulations dMsolUnit = 1.0e10 # Mass unit: 10^10 solar masses dKpcUnit = 1.0 # Length unit: 1 kpc # Gas physics bDoGravity = True dInitialT = 10000.0 # Initial gas temperature (K) # Cooling (requires GRACKLE compilation flag) # bGrackle = True # achGrackleDataFile = "CloudyData_UVB=HM2012.h5" # Star formation parameters bStarForm = True dTempMax = 30000.0 # Temperature threshold for SF dOverDensity = 100.0 # Overdensity threshold dSFEfficiency = 0.01 # Star formation efficiency # Supernova feedback bFeedback = True dESN = 1.0e51 # Supernova energy (erg) dDeltaStarForm = 1.0e6 # Minimum time between SF events (years) # Memory flags for hydrodynamics bMemVelocity = True bMemAcceleration = True bMemMass = True bMemSoft = True ``` -------------------------------- ### Argument ID Validation Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Example of an invalid format string that triggers an error due to repeated leading zeros in an argument ID. ```c++ fmt::print("{000}", 42); // error ``` -------------------------------- ### Enable and Use RGB Color Output in fmt Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates how to enable experimental RGB color support using the FMT_EXTENDED_COLORS macro and print colored text to the console. ```c++ #define FMT_EXTENDED_COLORS #define FMT_HEADER_ONLY #include fmt::print(fmt::color::steel_blue, "Some beautiful text"); ``` -------------------------------- ### Setup Rockstar Symbolic Links Source: https://github.com/dpotter/pkdgrav3/blob/master/CMakeLists.txt Creates symbolic links for Rockstar header files to resolve naming conflicts and includes them in the project build process. ```cmake if(ROCKSTAR_PATH) set(HAVE_ROCKSTAR TRUE) file(REAL_PATH ${ROCKSTAR_PATH} rdir EXPAND_TILDE) foreach(file particle.h halo.h io/io_internal.h) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rockstar/${file} COMMAND ${CMAKE_COMMAND} -E create_symlink ${rdir}/${file} ${CMAKE_CURRENT_BINARY_DIR}/rockstar/${file} ) target_sources(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/rockstar/${file}) endforeach() endif() ``` -------------------------------- ### Chrono Duration Formatting Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Examples of formatting chrono durations, including precision control and extracting specific units or values using %Q and %q specifiers. ```c++ auto s = fmt::format("{:.1}", std::chrono::duration(1.234)); auto value = fmt::format("{:%Q}", 42s); auto unit = fmt::format("{:%q}", 42s); auto s2 = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); ``` -------------------------------- ### String Formatting with Positional Arguments in {fmt} Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/README.rst Shows how to format strings and utilize positional arguments for localization or reordering. This allows for flexible string construction. ```c++ std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); // s == "I'd rather be happy than right." ``` -------------------------------- ### Configure GoogleTest and Test Executables with CMake Source: https://github.com/dpotter/pkdgrav3/blob/master/tests/CMakeLists.txt This script sets up the GoogleTest framework using FetchContent and defines several test executables. It configures C++17 standards, links necessary libraries like mdl2, blitz, and fmt, and registers tests with the CTest framework. ```cmake cmake_minimum_required(VERSION 3.14) set(USE_GTEST "no" CACHE STRING "Should we provide the tests using gtest framework") if(USE_GTEST) FetchContent_MakeAvailable(googletest) enable_testing() add_executable(cache cache.cxx) set_target_properties(cache PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO) target_link_libraries(cache mdl2 gtest_main) add_test(NAME cache COMMAND $ WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) endif() ``` -------------------------------- ### Configure FFTW3 Path with CMake Source: https://github.com/dpotter/pkdgrav3/blob/master/README.md Shows how to inform CMake about the location of the FFTW3 library installation using the FFTW_ROOT variable. This is required if FFTW3 is not found in standard system paths. ```bash cmake -DFFTW_ROOT=/path/to/fftw ... ``` -------------------------------- ### Format date and time Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Shows how to use the fmt/time.h header to format current system time using strftime-like specifiers. ```c++ #include "fmt/time.h" std::time_t t = std::time(nullptr); fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t)); ``` -------------------------------- ### Gravity, Domains, and Trees Parameters Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/parameters.md Configuration options for gravitational softening, domain decomposition, and tree building in PKDGRAV3. ```APIDOC ## Gravity, Domains, Trees ### Description Parameters in this section control gravitational softening, tree memory layout, and the frequency of domain decomposition and tree building. ### Parameters - **dSoft** (float) - Default: 0.0 - Sets the global gravitational softening length in code units. - **dSoftMax** (float) - Default: 0.0 - Maximum comoving gravitational softening length (absolute value or multiplier). - **bPhysicalSoft** (boolean) - Default: False - Specifies if the gravitational softening length is physical. - **bSoftMaxMul** (boolean) - Default: True - Indicates if the maximum comoving gravitational softening length is used as a multiplier. - **bDoGravity** (boolean) - Default: True - If false, gravitational accelerations are not applied, useful for hydrodynamical simulations. - **nGridLin** (integer) - Default: 0 - Grid size for linear species; 0 disables this feature. - **bDoLinPkOutput** (boolean) - Default: False - Enables power spectrum output for linear species. - **dFracNoDomainDecomp** (float) - Default: 0.1 - Fraction of active particles below which domain decomposition is not performed. - **dFracNoDomainRootFind** (float) - Default: 0.1 - Fraction of active particles below which domain root finding is not performed. - **dFracNoDomainDimChoice** (float) - Default: 0.1 - Fraction of active particles below which domain dimension choice is not performed. - **iMaxRungDomainDecomp** (integer) - Default: 2147483648 - The maximum rung level above which domain decomposition is not performed. ``` -------------------------------- ### Enabling Grisu Floating-Point Formatting Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Shows how to enable the experimental Grisu algorithm for faster floating-point formatting by defining the FMT_USE_GRISU macro. ```c++ #define FMT_USE_GRISU 1 #include auto s = fmt::format("{}", 4.2); ``` -------------------------------- ### Run FOF Group Finder in Python Source: https://context7.com/dpotter/pkdgrav3/llms.txt This script demonstrates how to load a simulation snapshot, configure the FOF algorithm with a specific linking length, and export group statistics. It requires the PKDGRAV Python module and assumes standard simulation data inputs. ```python import PKDGRAV as msr from PKDGRAV import OUT_TYPE # Load with group finding enabled time = msr.load("example.00100", bFindGroups=True, bMemGlobalGid=True, nMemEphemeral=8) msr.domain_decompose() msr.build_tree() # Run FOF algorithm msr.fof(0.0015625, 10) msr.reorder() # Write group statistics msr.write_group_stats("example.00100.fofstats") ``` -------------------------------- ### Overriding Restart Parameters in Pkdgrav3 Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/changes.md Illustrates how to override specific parameters during a Pkdgrav3 simulation restart. This example shows how to enable parallel reading and set the number of parallel readers by modifying the `restore` call. ```python msr.restore(__file__) # Changed to: msr.restore(__file__,bParaRead=True,nParaRead=100) ``` -------------------------------- ### Project Options Definition Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/CMakeLists.txt Defines various boolean options for the project, such as enabling pedantic warnings, halting on warnings, generating documentation, installation targets, testing, fuzzing, CUDA testing, and OS-specific core features. ```cmake option(FMT_PEDANTIC "Enable extra warnings and expensive tests." OFF) option(FMT_WERROR "Halt the compilation with an error on compiler warnings." OFF) # Options that control generation of various targets. option(FMT_DOC "Generate the doc target." ${MASTER_PROJECT}) option(FMT_INSTALL "Generate the install target." ${MASTER_PROJECT}) option(FMT_TEST "Generate the test target." ${MASTER_PROJECT}) option(FMT_FUZZ "Generate the fuzz target." OFF) option(FMT_CUDA_TEST "Generate the cuda-test target." OFF) option(FMT_OS "Include core requiring OS (Windows/Posix) " ON) ``` -------------------------------- ### Include fmt library headers Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates the updated include path for the fmt library following its rename from cppformat. ```c++ #include "fmt/format.h" ``` -------------------------------- ### Safe Printf Implementation with Positional Arguments in C++ Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Provides an example of using fmt::printf, a safe implementation of printf that supports positional arguments. This allows for more flexible and robust string formatting, especially in internationalized applications. ```c++ fmt::printf("Elapsed time: %.2f seconds", 1.23); fmt::printf("%1$s, %3$d %2$s", weekday, month, day); ``` -------------------------------- ### Format Wide String with Date in C++ Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Example of formatting a wide string literal with a Date object using fmt::format. This showcases the library's ability to handle wide characters and custom types for output. ```c++ fmt::format(L"The date is {0}", Date(2012, 12, 9)); ``` -------------------------------- ### Apply Terminal Colors and Emphasis Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Shows how to use fmt/color.h to apply foreground colors, background colors, and text emphasis like bold or italic to console output. ```c++ #include int main() { print(fg(fmt::color::crimson) | fmt::emphasis::bold, "Hello, {}!\n", "world"); print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | fmt::emphasis::underline, "Hello, {}!\n", "мир"); print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "Hello, {}!\n", "世界"); } ``` -------------------------------- ### Configure Custom Unit Systems for Simulations Source: https://context7.com/dpotter/pkdgrav3/llms.txt Defines custom unit systems for non-cosmological simulations, such as planetary dynamics, by setting length and mass units. Provides examples for AU-based, Earth-radius-based, and Galactic-scale units, emphasizing the G=1 convention. ```Python # units_custom.par - Custom unit system for planetary simulations # Use dKpcUnit and dMsolUnit to define G=1 unit system # Astronomical Unit scale (AU, km/s, ~Jupiter masses) dKpcUnit = 4.848101587970315e-09 # Length unit in kpc (= 1 AU) dMsolUnit = 0.0011272388129170855 # Mass unit in solar masses # This gives: # Length: 1 AU # Velocity: 1 km/s # Mass: ~1130 Earth masses # Time: ~0.978 years (derived from G=1) # Earth radius scale (for collision simulations) # dKpcUnit = 2.064688206889847e-13 # 1 Earth radius # dMsolUnit = 4.8006351375833994e-08 # ~48 micro solar masses # Galactic scale (kpc, km/s) # dKpcUnit = 1.0 # 1 kpc # dMsolUnit = 232508.541103 # ~2.3e5 solar masses # Time unit: ~0.978 Gyr # Unit conversion formulas (with G=1): # Velocity^2 = G * Mass / Length # Time = Length / Velocity # Density = Mass / Length^3 # Use tools/calculate_units.py to compute dKpcUnit and dMsolUnit # from your desired length/mass/velocity/time combinations ``` -------------------------------- ### Implementing Variadic Formatting Functions in C++ Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates how to implement variadic formatting functions using C++11 variadic templates or lightweight wrapper functions with the FMT_VARIADIC macro. This approach improves performance by avoiding temporary formatter objects and argument lifetime management. ```c++ void report_error(const char *format, const fmt::ArgList &args) { fmt::print("Error: {}"); fmt::print(format, args); } FMT_VARIADIC(void, report_error, const char *) report_error("file not found: {}", path); ``` -------------------------------- ### Configure Dynamic Accuracy Parameters Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/extensions.md Demonstrates how to initialize dynamic accuracy switches for cosmological simulations. These switches automatically adjust theta and replica parameters based on simulation state. ```python from accuracy import classic_theta_switch,classic_replicas_switch dTheta = classic_theta_switch() nReplicas = classic_replicas_switch() ``` -------------------------------- ### Pkdgrav3 Synchronized Redshift Steps Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/changes.md Demonstrates the new method for specifying synchronized steps to reach specific redshifts in Pkdgrav3, replacing `nStepsSync` and `dRedSync`. This example shows how to define multiple redshift targets and the number of steps for each interval. ```python # Old way: dRedFrom = 49 dRedTo = 0 nSteps = 160 nStepsSync = 60 dRedSync = 10 # This would take 60 steps to redshift 10, then 100 steps to redshift 0. # New way: dRedFrom = 40 dRedTo = [10,0] nSteps = [60,100] ``` -------------------------------- ### Convert Integer to String using fmt::to_string (C++) Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Demonstrates how to convert an integer to a string using the fmt::to_string function from the fmt/string.h header. This provides an alternative to std::to_string. ```c++ #include "fmt/string.h" std::string answer = fmt::to_string(42); ``` -------------------------------- ### CMake Visual Studio MSBuild Setup Script Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/CMakeLists.txt Generates a `run-msbuild.bat` script for Visual Studio builds when using the MS SDK. It includes logic to set up the build environment using `SetEnv.cmd` and calls `msbuild`, overriding the .NET Framework path to avoid specific warnings. ```cmake if (MASTER_PROJECT AND CMAKE_GENERATOR MATCHES "Visual Studio") # If Microsoft SDK is installed create script run-msbuild.bat that # calls SetEnv.cmd to set up build environment and runs msbuild. # It is useful when building Visual Studio projects with the SDK # toolchain rather than Visual Studio. include(FindSetEnv) if (WINSDK_SETENV) set(MSBUILD_SETUP "call \"${WINSDK_SETENV}\"") endif () # Set FrameworkPathOverride to get rid of MSB3644 warnings. join(netfxpath "C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\ ".NETFramework\\v4.0") file(WRITE run-msbuild.bat " ${MSBUILD_SETUP} ${CMAKE_MAKE_PROGRAM} -p:FrameworkPathOverride=\"${netfxpath}\" %*") endif () ``` -------------------------------- ### PKDGRAV Initial Condition Generation Source: https://context7.com/dpotter/pkdgrav3/llms.txt Programmatically generates initial conditions for cosmological simulations using the PKDGRAV interface. Allows customization of cosmology, grid size, redshift, box size, and perturbation order (e.g., 2LPT). Includes options for saving to Tipsy format. ```python # generate_ic.py - Generate initial conditions import PKDGRAV as msr from cosmology import SimpleCosmology # Define cosmology cosmology = SimpleCosmology( omega_matter=0.32, omega_lambda=0.68, omega_baryon=0.05, sigma8=0.83, ns=0.96, h=0.67, transfer_file="euclid_z0_transfer_combined.dat" ) # Generate initial conditions time = msr.generate_ic( cosmology=cosmology, grid=256, # 256^3 particles seed=42, # Random seed z=49, # Starting redshift L=1000, # Box size in Mpc/h order=2, # 2LPT (1=Zeldovich, 2=2LPT, 3=3LPT) fixed_amplitude=False, # Use random amplitudes phase_pi=0 # Phase offset (0 or 1) ) print(f"Generated ICs at time={time}") # Save to file msr.save("ic_z49.tipsy", time=time) # Can also generate with gas particles # In parameter file: bICgas = True, dInitialT = 100.0 ``` -------------------------------- ### Capturing Formatting Arguments with `make_format_args` Source: https://github.com/dpotter/pkdgrav3/blob/master/fmt/ChangeLog.rst Explains how to use `fmt::make_format_args` to capture formatting arguments, often used in variadic functions. ```APIDOC ## Capturing Formatting Arguments with `make_format_args` ### Description The `make_format_args` function is used to create a `format_args` object from a variable number of arguments. This is particularly useful when implementing functions that accept arbitrary formatting arguments, such as logging or reporting functions. ### Method N/A (Library function usage) ### Endpoint N/A ### Parameters N/A ### Request Example ```cpp // Prints formatted error message. void vreport_error(const char *format, fmt::format_args args) { fmt::print("Error: "); fmt::vprint(format, args); } template void report_error(const char *format, const Args & ... args) { vreport_error(format, fmt::make_format_args(args...)); } ``` ### Response N/A (Internal function usage) ### Response Example N/A ``` -------------------------------- ### Configure Light Cone Output Source: https://github.com/dpotter/pkdgrav3/blob/master/docs/parameters.md These parameters control the generation and format of light cone outputs. They allow enabling/disabling the feature, setting the starting redshift, configuring HEALPix map output, controlling particle output, specifying octants to include, defining the sky coverage in square degrees, and setting the light cone direction vector. ```default bLightCone = False dRedshiftLCP = 0.0 nSideHealpix = 0 bLightConeParticles = False bBowtie = False lstLightConeOctants = all sqdegLCP = 50.0 hLCP = [0.749, 0.454, 1.0] ``` -------------------------------- ### Build and Execute Simulation on HPC Source: https://context7.com/dpotter/pkdgrav3/llms.txt Commands to compile the PKDGRAV3 source code using CMake and execute the simulation using SLURM job scheduling on a high-performance computing cluster. ```bash cd /path/to/pkdgrav3 cmake -S . -B build cmake --build build -j 16 #!/bin/bash -l #SBATCH --nodes=10 #SBATCH --ntasks-per-node=1 --cpus-per-task=16 --ntasks-per-core=1 srun ./build/pkdgrav3 cosmology.par ```