From a10c206df5fb3188e7c28acb402db097381ea78e Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Tue, 1 Dec 2026 13:10:06 -0500 Subject: [PATCH 01/13] New option for Slab - freeze0: none (default; false also works), n0 (or true) or all. The k=0 field is captured at the first complete coefficient evaluation, after the MPI reduce and after multistep assembly. That's the same point the existing self_consistent: false freeze uses. - n0 sets value0 to the measured k=0, n=0 coefficient and turns on fixed0, so after capture it is your existing fixed0 path. all keeps every measured k=0 coefficient fixed. - Measured coefficients are unchanged, so outcoef still records the particles' live k=0 field as a diagnostic. - State file: SlabSL.freeze0...yml in outdir; you can override the name with freeze0file. Root writes it at capture. On a restart, root reads and checks it, then broadcasts it over MPI. If the file is missing, or its mode or nmaxz differ from the config, the run warns and re-measures. - Logging: stdout logs every decision: pending, captured (with T, value0 and all k=0 coefficients), restored, overridden (when fixed0/value0 are also given) and ignored (self_consistent: false). - GPU: no kernel change. For n0, initialize_constants() already copies slabFixed0 and slabValue0 to the device on every force call. For all, HtoD_coefs() swaps in the frozen k=0 entries before the copy. - Tests on 2 MPI ranks using a 20k-particle slab - GPU test TBD --- src/SlabSL.H | 38 ++++++++++ src/SlabSL.cc | 180 +++++++++++++++++++++++++++++++++++++++++++++- src/cudaSlabSL.cu | 11 +++ 3 files changed, 228 insertions(+), 1 deletion(-) diff --git a/src/SlabSL.H b/src/SlabSL.H index 490233965..3de07b7b6 100644 --- a/src/SlabSL.H +++ b/src/SlabSL.H @@ -79,6 +79,25 @@ @param value0 is the coefficient of the k=0, n=0 background for fixed0=true. + @param freeze0 freezes the k=0 (kx=ky=0) field at its first + evaluation from the particles, while the k!=0 terms stay self + consistent. Values: + - none (default, or false): no freezing + - n0 (or true): set value0 to the measured (k=0, n=0) + coefficient and turn on fixed0; the other k=0 terms are zero, + exactly as for fixed0 with that value0 + - all: keep every measured k=0 coefficient (all n) fixed at its + first value, e.g. when the basis and the model used for the + initial conditions do not match exactly + The frozen values are written by the root process to the YAML file + freeze0file and read back (and broadcast) on a restart, so that a + restarted run uses the same frozen field. freeze0 overrides fixed0 + and value0, and is ignored if self_consistent=false. The measured + coefficients (and so the coefficient output) are not altered. + + @param freeze0file is the name of that file (default: + SlabSL.freeze0...yml). + @param cachename is the name of the basis cache file. This is a required parameter. */ @@ -122,6 +141,25 @@ private: bool no_even = false, no_odd = false, zero_coefs = true, fixed0 = false; //@} + //@{ + //! Freeze the k=0 field at its first evaluation (see freeze0 above) + enum class Freeze0 { none, n0, all }; + Freeze0 freeze0 = Freeze0::none; + bool freeze0_pending = false; // true until captured or restored + std::vector> coefs0; // frozen k=0 coefficients, n=0..nmaxz-1 + std::string freeze0file; + static std::string freeze0Name(Freeze0 m); + //! Capture the k=0 coefficients from expccof[0] (all ranks) + void freeze0Capture(); + //! Read the state file on a restart (root reads, then broadcast) + bool freeze0Restore(); + //! Write the state file (root only) + void freeze0Write(); + //! True if the all-n frozen k=0 coefficients are in effect + bool frozenAll() const + { return freeze0 == Freeze0::all and not freeze0_pending; } + //@} + int imx, imy, imz, jmax, nnmax; double dfac, last=-std::numeric_limits::max(); std::complex kfacX, kfacY; diff --git a/src/SlabSL.cc b/src/SlabSL.cc index 62c436d77..8840e5f54 100644 --- a/src/SlabSL.cc +++ b/src/SlabSL.cc @@ -1,5 +1,8 @@ #include #include +#include +#include +#include #include "expand.H" @@ -24,6 +27,8 @@ SlabSL::valid_keys = { "nint", "value0", "fixed0", + "freeze0", + "freeze0file", "no_even", "no_odd", "samplesz", @@ -169,7 +174,158 @@ SlabSL::SlabSL(Component* c0, const YAML::Node& conf) : Basis(c0, conf) expccofN[i] -> setZero(); expccofL[i] -> setZero(); } - + + // Freeze the k=0 field at its first evaluation (or restore it on a + // restart) + // + if (freeze0 != Freeze0::none) { + if (not self_consistent) { + if (myid==0) + std::cout << "---- SlabSL: freeze0=" << freeze0Name(freeze0) + << " is ignored because self_consistent=false" << std::endl; + freeze0 = Freeze0::none; + } else { + if (freeze0file.size()==0) + freeze0file = outdir + "SlabSL.freeze0." + component->name + "." + runtag + ".yml"; + if (fixed0 and myid==0) + std::cout << "---- SlabSL: freeze0=" << freeze0Name(freeze0) + << " overrides fixed0/value0 (value0=" << value0 << " ignored)" << std::endl; + fixed0 = false; // live k=0 until the first evaluation + freeze0_pending = true; + coefs0.assign(nmaxz, 0.0); + if (restart) { + if (freeze0Restore()) freeze0_pending = false; + } + if (freeze0_pending and myid==0) + std::cout << "---- SlabSL: freeze0=" << freeze0Name(freeze0) + << ": the k=0 field will be frozen at the first coefficient evaluation" + << " and saved to <" << freeze0file << ">" << std::endl; + } + } +} + +std::string SlabSL::freeze0Name(Freeze0 m) +{ + switch (m) { + case Freeze0::n0: return "n0"; + case Freeze0::all: return "all"; + default: return "none"; + } +} + +void SlabSL::freeze0Capture() +{ + // expccof[0] holds the complete, MPI-reduced coefficients here, so it + // is identical on all ranks and no broadcast is needed + // + for (int iz=0; iz0 terms zero)"; + else + std::cout << ", all " << nmaxz << " k=0 coefficients"; + std::cout << std::endl << "---- SlabSL: k=0 coefficients [n: real imag]:"; + for (int iz=0; iz 1.0e-8*std::abs(coefs0[0].real())) + std::cout << "---- SlabSL: WARNING: Im c(0,0,0) is not negligible" << std::endl; + freeze0Write(); + } +} + +void SlabSL::freeze0Write() +{ + std::ofstream out(freeze0file); + if (not out) { + std::cout << "---- SlabSL: WARNING: could not write <" << freeze0file + << ">; a restart will re-measure the frozen k=0 field" << std::endl; + return; + } + out << std::setprecision(17) + << "# SlabSL freeze0 state: written by EXP when the k=0 field was\n" + << "# frozen and read back on a restart. Do not edit.\n" + << "runtag: " << runtag << "\n" + << "component: " << component->name << "\n" + << "mode: " << freeze0Name(freeze0) << "\n" + << "time: " << tnow << "\n" + << "nmaxz: " << nmaxz << "\n" + << "value0: " << coefs0[0].real() << "\n" + << "coefs0_real: ["; + for (int iz=0; iz buf(2*nmaxz + 1, 0.0); + + if (myid==0) { + std::string why; + if (not std::filesystem::exists(freeze0file)) { + why = "file not found"; + } else { + try { + YAML::Node node = YAML::LoadFile(freeze0file); + std::string mode = node["mode"].as(); + int nz = node["nmaxz"].as(); + auto re = node["coefs0_real"].as>(); + auto im = node["coefs0_imag"].as>(); + if (mode != freeze0Name(freeze0)) + why = "mode " + mode + " in the file differs from freeze0=" + freeze0Name(freeze0); + else if (nz != nmaxz or int(re.size()) != nmaxz or int(im.size()) != nmaxz) + why = "nmaxz in the file differs from this run"; + else { + for (int iz=0; iz(); + ok = 1; + } + } + catch (const std::exception& e) { + why = std::string("parse error: ") + e.what(); + } + } + if (not ok) + std::cout << "---- SlabSL: WARNING: restart with freeze0=" << freeze0Name(freeze0) + << " but <" << freeze0file << "> is not usable (" << why + << "); the k=0 field will be re-measured at the first evaluation" << std::endl; + } + + MPI_Bcast(&ok, 1, MPI_INT, 0, MPI_COMM_WORLD); + if (not ok) return false; + MPI_Bcast(buf.data(), buf.size(), MPI_DOUBLE, 0, MPI_COMM_WORLD); + + for (int iz=0; iz (frozen at T=" + << buf[2*nmaxz] << ")"; + if (freeze0 == Freeze0::n0) + std::cout << ", value0=" << std::setprecision(12) << value0 << " (fixed0 on)"; + std::cout << std::endl; + } + return true; } SlabSL::~SlabSL() @@ -202,6 +358,17 @@ void SlabSL::initialize() if (conf["type" ]) type = conf["type" ].as(); if (conf["value0"]) value0 = conf["value0"].as(); if (conf["fixed0"]) fixed0 = conf["fixed0"].as(); + if (conf["freeze0file"]) freeze0file = conf["freeze0file"].as(); + if (conf["freeze0"]) { + std::string v = conf["freeze0"].as(); + std::transform(v.begin(), v.end(), v.begin(), + [](unsigned char c){ return std::tolower(c); }); + if (v=="none" or v=="false" or v=="no" or v=="off") freeze0 = Freeze0::none; + else if (v=="n0" or v=="true" or v=="yes" or v=="on") freeze0 = Freeze0::n0; + else if (v=="all") freeze0 = Freeze0::all; + else + throw std::runtime_error("SlabSL: freeze0 must be one of none, n0 (true), all; got '" + v + "'"); + } if (conf["no_even"]) no_even = conf["no_even"].as(); if (conf["no_odd"]) no_odd = conf["no_odd"].as(); if (conf["orthochk"]) orthochk = conf["orthochk"].as(); @@ -476,6 +643,12 @@ void SlabSL::determine_coefficients(void) compute_multistep_coefficients(); } + // Freeze the k=0 field at the first complete evaluation (freeze0) + // + if (freeze0_pending and (multistep==0 or mlevel==multistep)) { + freeze0Capture(); + } + // Only used if self_consistent is false to ensure that coefficients // are only computed once (at the first time step) // @@ -753,6 +926,11 @@ void * SlabSL::determine_acceleration_and_potential_thread(void * arg) facf = 0.0; } } + // Frozen k=0 coefficients, all n (freeze0=all) + else if (ii==0 and jj==0 and frozenAll()) { + fac = facx*facy*zpot[id][iz]*coefs0[iz] * normXY; + facf = facx*facy*zfrc[id][iz]*coefs0[iz] * normXY; + } // Self consistent else if (self_consistent) { fac = facx*facy*zpot[id][iz]*expccof[0](ix, iy, iz) * normXY; diff --git a/src/cudaSlabSL.cu b/src/cudaSlabSL.cu index f9bbbc105..591aad4a6 100644 --- a/src/cudaSlabSL.cu +++ b/src/cudaSlabSL.cu @@ -1307,6 +1307,17 @@ void SlabSL::HtoD_coefs() else host_coefs[i] = expcofF.data()[i]; } + // freeze0=all: the k=0 terms use the frozen coefficients (the + // freeze0=n0 case goes through fixed0/value0, which + // initialize_constants() copies to the device on every force call) + // + if (self_consistent and frozenAll()) { + for (int iz=0; iz Date: Tue, 1 Dec 2026 16:51:30 -0500 Subject: [PATCH 02/13] New EXP hook - ExternalForce gains two methods: wantStepEnd(t), which by default never asks, and stepEnd(), which by default does nothing. The header comment spells out what a module may and may not do there. - ExternalCollection::stepEnd() calls the hook for each force that asks. For a force that isn't CUDA-aware, it first copies particles to the host. - The hook runs at every synchronized point: - once in begin.cc, at the initial state; - after the closing kick of every full step in step.cc, in both the multistep and non-multistep branches, just before output. --- src/ExternalCollection.H | 4 ++++ src/ExternalCollection.cc | 13 +++++++++++++ src/ExternalForce.H | 26 ++++++++++++++++++++++++++ src/begin.cc | 5 +++++ src/step.cc | 7 +++++++ 5 files changed, 55 insertions(+) diff --git a/src/ExternalCollection.H b/src/ExternalCollection.H index 1ce9b6ae2..d77a93810 100644 --- a/src/ExternalCollection.H +++ b/src/ExternalCollection.H @@ -52,6 +52,10 @@ public: //! Call the finish member for all external forces void finish(); + + //! Call the step-end hook of the external forces that request it at + //! this time (see ExternalForce::wantStepEnd) + void stepEnd(); }; #endif diff --git a/src/ExternalCollection.cc b/src/ExternalCollection.cc index 959057ec6..914529502 100644 --- a/src/ExternalCollection.cc +++ b/src/ExternalCollection.cc @@ -280,3 +280,16 @@ void ExternalCollection::finish() for (auto p : force_list) p->finish(); } +void ExternalCollection::stepEnd() +{ + for (auto ext : force_list) { + if (not ext->wantStepEnd(tnow)) continue; +#if HAVE_LIBCUDA==1 + // Non-cuda-aware forces read the host copy of the particles + if (use_cuda and not ext->cudaAware()) { + for (auto c : comp->components) c->CudaToParticles(); + } +#endif + ext->stepEnd(); + } +} diff --git a/src/ExternalForce.H b/src/ExternalForce.H index 2c8744853..bdc157976 100644 --- a/src/ExternalForce.H +++ b/src/ExternalForce.H @@ -56,6 +56,32 @@ public: //! Finish and clean-up (caching data necessary for restart) virtual void finish() {} + //@{ + /** Optional step-end hook. + + The force evaluation (determine_acceleration_and_potential) runs + between the drift and the closing velocity kick, where the + positions are at the new time but the velocities are still half a + step behind. A force that needs a synchronized phase space (for + example, to measure actions or energies) can instead use this + hook: EXP calls stepEnd() at every synchronized point, that is, + once after initialization and once at the end of every full step + (after the closing kick, before the output routines run), but + only if wantStepEnd(tnow) returns true. The default is never, so + existing forces are not affected. + + wantStepEnd() must return the same value on all MPI ranks (e.g. + decide from tnow only). stepEnd() is called on all ranks and must + not change the particles. For a force that is not cuda aware, EXP + copies the particles from the device before calling stepEnd(); a + cuda-aware force must fetch what it reads itself (e.g. with + Component::CudaToParticles()), which lets it skip the copy on + steps where it has nothing to do. + */ + virtual bool wantStepEnd(double time) { return false; } + virtual void stepEnd() {} + //@} + // #if HAVE_LIBCUDA==1 #if HAVE_LIBCUDA==1 //! Copy particles from device for non-cuda forces diff --git a/src/begin.cc b/src/begin.cc index 25304d78d..77855990d 100644 --- a/src/begin.cc +++ b/src/begin.cc @@ -133,6 +133,11 @@ void begin_run(void) //=================================== output->initialize(); + + // Step-end hook for external forces at the initial (synchronized) + // phase space + external->stepEnd(); + output->Run(0); //====================== diff --git a/src/step.cc b/src/step.cc index 9c2a73dde..8c5fe1a67 100644 --- a/src/step.cc +++ b/src/step.cc @@ -14,6 +14,7 @@ #include "expand.H" #include "OutputContainer.H" +#include "ExternalCollection.H" // Substep timing // @@ -230,6 +231,9 @@ void do_step(int n) } // END: mstep loop + // Step-end hook for external forces (phase space synchronized) + external->stepEnd(); + // Write output if (step_timing) timer_out.start(); if (cuda_prof) tPtr = std::make_shared("Data output"); @@ -312,6 +316,9 @@ void do_step(int n) incr_com_velocity(0.5*dtime); if (step_timing) timer_vel.stop(); + // Step-end hook for external forces + // (phase space synchronized) + external->stepEnd(); // Write output if (step_timing) timer_out.start(); nvTracerPtr tPtr; From ad4c774ecc695eb660fc98f835cf177b7435e44d Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Tue, 1 Dec 2026 19:27:50 -0500 Subject: [PATCH 03/13] =?UTF-8?q?Add=20build-time=20version=20generation?= =?UTF-8?q?=20-=20the=20actual=20commit=20on=20every=20build=20is=20record?= =?UTF-8?q?ed,=20with=20no=20cmake=20re-run=20=20=20needed;=20-=20for=20un?= =?UTF-8?q?committed=20changes,=20-dirty-<8=20hex>,=20a=20fingerprin?= =?UTF-8?q?t=20of=20git=20=20=20diff=20HEAD,=20so=20each=20distinct=20unco?= =?UTF-8?q?mmitted=20state=20is=20identifiable.=20-=20Untracked=20files=20?= =?UTF-8?q?and=20changes=20inside=20submodules=20don't=20count=20as=20=20?= =?UTF-8?q?=20changes.=20Run199k's=20header=20would=20have=20read=208c7478?= =?UTF-8?q?7bf=E2=80=A6-dirty-=E2=80=A6=20under=20=20=20this=20scheme.=20-?= =?UTF-8?q?=20Rebuild=20cost:=20the=20generated=20file=20is=20rewritten=20?= =?UTF-8?q?only=20when=20the=20git=20state=20changes=20-=20An=20unchanged?= =?UTF-8?q?=20rebuild=20compiles=20nothing.=20A=20change=20recompiles=20on?= =?UTF-8?q?ly=20=20=20parse.cc=20and=20OutHDF5.cc,=20plus=20ModulesVersion?= =?UTF-8?q?.cc=20-=20COMPILE=5FTIME=20("Built:"=20in=20the=20config=20head?= =?UTF-8?q?er)=20now=20means=20the=20time=20of=20=20=20the=20first=20build?= =?UTF-8?q?=20of=20that=20exact=20source=20state,=20not=20the=20time=20of?= =?UTF-8?q?=20the=20last=20=20=20cmake=20run.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CMakeLists.txt | 20 +++++++++++ cmake/GitVersion.cmake | 74 +++++++++++++++++++++++++++++++++++++++ config_cmake.h_in | 10 ++---- exp_git_version.h_in | 14 ++++++++ pyEXP/CMakeLists.txt | 1 + pyEXP/PyWrappers.cc | 1 + pyEXP/UtilWrappers.cc | 1 + src/CMakeLists.txt | 1 + src/ExternalCollection.cc | 23 +++++++----- src/ExternalForce.H | 10 +++--- src/OutHDF5.cc | 1 + src/parse.cc | 1 + 12 files changed, 136 insertions(+), 21 deletions(-) create mode 100644 cmake/GitVersion.cmake create mode 100644 exp_git_version.h_in diff --git a/CMakeLists.txt b/CMakeLists.txt index 0bcc50a97..27627d682 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -274,6 +274,26 @@ include_directories(${PROJECT_SOURCE_DIR}/extern/QuickDigest5/include) # Report to the user message("Configuring build for ${GIT_BRANCH}/${GIT_COMMIT} at ${COMPILE_TIME}") +# Git provenance (GIT_BRANCH, GIT_COMMIT, COMPILE_TIME) for the code is +# generated at BUILD time into exp_git_version.h, so that it always +# describes the tree actually compiled, including uncommitted changes +# (-dirty-), without having to re-run cmake. +# The header is rewritten only when the git state changes. The values +# above are for this configure message only. +set(EXP_GIT_VERSION_ARGS + -DGIT_EXECUTABLE=${GIT_EXECUTABLE} + -DSRC_DIR=${CMAKE_SOURCE_DIR} + -DTEMPLATE=${CMAKE_SOURCE_DIR}/exp_git_version.h_in + -DOUT=${CMAKE_BINARY_DIR}/exp_git_version.h) +execute_process(COMMAND ${CMAKE_COMMAND} ${EXP_GIT_VERSION_ARGS} + -P ${CMAKE_SOURCE_DIR}/cmake/GitVersion.cmake) +add_custom_target(exp_git_version ALL + COMMAND ${CMAKE_COMMAND} ${EXP_GIT_VERSION_ARGS} + -P ${CMAKE_SOURCE_DIR}/cmake/GitVersion.cmake + BYPRODUCTS ${CMAKE_BINARY_DIR}/exp_git_version.h + COMMENT "Checking git provenance" + VERBATIM) + add_subdirectory(extern/yaml-cpp) if (NOT DISABLE_PYTHON) add_subdirectory(extern/pybind11) diff --git a/cmake/GitVersion.cmake b/cmake/GitVersion.cmake new file mode 100644 index 000000000..0fef41063 --- /dev/null +++ b/cmake/GitVersion.cmake @@ -0,0 +1,74 @@ +# GitVersion.cmake -- write git provenance into a generated source file. +# +# Run in script mode at BUILD time (from a custom target), so that the +# recorded state is always that of the tree actually being compiled, +# not that of the last `cmake` run: +# +# cmake -DGIT_EXECUTABLE=... -DSRC_DIR= -DTEMPLATE= +# -DOUT= -P GitVersion.cmake +# +# Variables available to the @VAR@ template: +# GIT_BRANCH current branch +# GIT_COMMIT full hash of HEAD; if tracked files have uncommitted +# changes: -dirty-<8 hex digits of MD5(git diff HEAD)>, +# so that every distinct uncommitted state is identifiable +# GIT_HASH same as GIT_COMMIT +# GIT_DIRTY 0 or 1 +# GIT_DATE date of the HEAD commit +# GIT_COMMIT_MSG subject line of the HEAD commit (C-string escaped) +# COMPILE_TIME time of the first build of this exact source state +# +# OUT is rewritten only when the git state changes, so an unchanged tree +# triggers no recompilation. Untracked files and changes inside +# submodules are not counted as "dirty". + +if(NOT GIT_EXECUTABLE) + set(GIT_EXECUTABLE git) +endif() + +macro(_git var) + execute_process(COMMAND "${GIT_EXECUTABLE}" ${ARGN} + WORKING_DIRECTORY "${SRC_DIR}" + OUTPUT_VARIABLE ${var} RESULT_VARIABLE _rc + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if(NOT _rc EQUAL 0) + set(${var} "unknown") + endif() +endmacro() + +_git(GIT_BRANCH rev-parse --abbrev-ref HEAD) +_git(GIT_COMMIT rev-parse HEAD) +_git(GIT_DATE log -1 --format=%ad --date=local) +_git(GIT_COMMIT_MSG log -1 --format=%s) +_git(_status status --porcelain --untracked-files=no --ignore-submodules=dirty) + +set(GIT_DIRTY 0) +if(_status AND NOT _status STREQUAL "unknown") + set(GIT_DIRTY 1) + _git(_diff diff HEAD --ignore-submodules=dirty) + string(MD5 _md5 "${_diff}") + string(SUBSTRING "${_md5}" 0 8 _md5) + set(GIT_COMMIT "${GIT_COMMIT}-dirty-${_md5}") +endif() +set(GIT_HASH "${GIT_COMMIT}") + +# Escape for use inside a C string literal +foreach(v GIT_BRANCH GIT_DATE GIT_COMMIT_MSG) + string(REPLACE "\\" "\\\\" ${v} "${${v}}") + string(REPLACE "\"" "\\\"" ${v} "${${v}}") +endforeach() + +# Regenerate only if the state changed (the key excludes the time) +set(_key "${GIT_BRANCH}|${GIT_COMMIT}|${GIT_DATE}|${GIT_COMMIT_MSG}|${TEMPLATE}") +set(_keyfile "${OUT}.gitkey") +set(_old "") +if(EXISTS "${_keyfile}" AND EXISTS "${OUT}") + file(READ "${_keyfile}" _old) +endif() + +if(NOT _old STREQUAL _key) + string(TIMESTAMP COMPILE_TIME "%Y-%m-%d %H:%M:%S %Z") + configure_file("${TEMPLATE}" "${OUT}" @ONLY) + file(WRITE "${_keyfile}" "${_key}") + message(STATUS "Git provenance for ${SRC_DIR}: ${GIT_BRANCH}/${GIT_COMMIT}") +endif() diff --git a/config_cmake.h_in b/config_cmake.h_in index 6f45119a0..39ee9bf25 100644 --- a/config_cmake.h_in +++ b/config_cmake.h_in @@ -52,11 +52,5 @@ /* Version number of package */ #define VERSION "@PROJECT_VERSION@" -/* Git commit at configure */ -#define GIT_COMMIT "@GIT_COMMIT@" - -/* Git branch at configure */ -#define GIT_BRANCH "@GIT_BRANCH@" - -/* Date/time at configure */ -#define COMPILE_TIME "@COMPILE_TIME@" +/* GIT_COMMIT, GIT_BRANCH and COMPILE_TIME are generated at build time + in exp_git_version.h (see cmake/GitVersion.cmake) */ diff --git a/exp_git_version.h_in b/exp_git_version.h_in new file mode 100644 index 000000000..dc274e858 --- /dev/null +++ b/exp_git_version.h_in @@ -0,0 +1,14 @@ +// Generated at build time by cmake/GitVersion.cmake -- do not edit. +// +// Kept separate from config_exp.h so that a change of the git state +// recompiles only the few files that report it. +#pragma once + +//! Current git branch +#define GIT_BRANCH "@GIT_BRANCH@" + +//! Git commit hash; -dirty- for uncommitted changes +#define GIT_COMMIT "@GIT_COMMIT@" + +//! Time of the first build of this source state +#define COMPILE_TIME "@COMPILE_TIME@" diff --git a/pyEXP/CMakeLists.txt b/pyEXP/CMakeLists.txt index 8d8f24d1f..fb16fe162 100644 --- a/pyEXP/CMakeLists.txt +++ b/pyEXP/CMakeLists.txt @@ -39,6 +39,7 @@ pybind11_add_module(pyEXP PyWrappers.cc CoefWrappers.cc UtilWrappers.cc BasisWrappers.cc FieldWrappers.cc ParticleReaderWrappers.cc MSSAWrappers.cc EDMDWrappers.cc) target_link_libraries(pyEXP PUBLIC expui exputil ${common_LINKLIB}) +add_dependencies(pyEXP exp_git_version) # exp_git_version.h target_include_directories(pyEXP PUBLIC ${common_INCLUDE}) # TODO: Should find a proper solution for this, but for now, don't add OpenMP compile # options if compiling on macOS with Clang diff --git a/pyEXP/PyWrappers.cc b/pyEXP/PyWrappers.cc index b918e0fd6..10a47ea80 100644 --- a/pyEXP/PyWrappers.cc +++ b/pyEXP/PyWrappers.cc @@ -3,6 +3,7 @@ #include #include "config_exp.h" +#include "exp_git_version.h" // GIT_BRANCH, GIT_COMMIT, COMPILE_TIME namespace py = pybind11; diff --git a/pyEXP/UtilWrappers.cc b/pyEXP/UtilWrappers.cc index 7970fa95f..ebf6cad8d 100644 --- a/pyEXP/UtilWrappers.cc +++ b/pyEXP/UtilWrappers.cc @@ -8,6 +8,7 @@ namespace py = pybind11; #include "Centering.H" #include "KDdensity.H" #include "ParticleIterator.H" +#include "exp_git_version.h" // GIT_BRANCH, GIT_COMMIT, COMPILE_TIME void UtilityClasses(py::module &m) { diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 87df43c8f..a56f94e53 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -56,6 +56,7 @@ if(ENABLE_XDR AND TIRPC_FOUND) endif() add_library(EXPlib ${exp_SOURCES}) +add_dependencies(EXPlib exp_git_version) # exp_git_version.h (parse.cc, OutHDF5.cc) set_target_properties(EXPlib PROPERTIES OUTPUT_NAME EXPlib) target_include_directories(EXPlib PUBLIC ${common_INCLUDE_DIRS}) target_link_libraries(EXPlib PUBLIC ${common_LINKLIB}) diff --git a/src/ExternalCollection.cc b/src/ExternalCollection.cc index 914529502..f95a36172 100644 --- a/src/ExternalCollection.cc +++ b/src/ExternalCollection.cc @@ -282,14 +282,21 @@ void ExternalCollection::finish() void ExternalCollection::stepEnd() { - for (auto ext : force_list) { - if (not ext->wantStepEnd(tnow)) continue; + // Which forces want the hook at this time? + std::vector want; + for (auto ext : force_list) + if (ext->wantStepEnd(tnow)) want.push_back(ext); + + if (want.empty()) return; + #if HAVE_LIBCUDA==1 - // Non-cuda-aware forces read the host copy of the particles - if (use_cuda and not ext->cudaAware()) { - for (auto c : comp->components) c->CudaToParticles(); - } -#endif - ext->stepEnd(); + // The hook reads the host copy of the particles: fetch it from the + // device once, only at the times when some force wants the hook. + // (Done here, in EXP proper, so that user modules need no CUDA code.) + if (use_cuda) { + for (auto c : comp->components) c->CudaToParticles(); } +#endif + + for (auto ext : want) ext->stepEnd(); } diff --git a/src/ExternalForce.H b/src/ExternalForce.H index bdc157976..7437708c1 100644 --- a/src/ExternalForce.H +++ b/src/ExternalForce.H @@ -72,11 +72,11 @@ public: wantStepEnd() must return the same value on all MPI ranks (e.g. decide from tnow only). stepEnd() is called on all ranks and must - not change the particles. For a force that is not cuda aware, EXP - copies the particles from the device before calling stepEnd(); a - cuda-aware force must fetch what it reads itself (e.g. with - Component::CudaToParticles()), which lets it skip the copy on - steps where it has nothing to do. + not change the particles. On a GPU run, EXP copies the particles + from the device to the host before calling stepEnd(), but only at + the times when some force asks for the hook, so a force using it + needs no CUDA code of its own (and can declare itself cuda aware + to avoid the per-step copies of the force evaluation). */ virtual bool wantStepEnd(double time) { return false; } virtual void stepEnd() {} diff --git a/src/OutHDF5.cc b/src/OutHDF5.cc index 9c28459ed..df9b457b3 100644 --- a/src/OutHDF5.cc +++ b/src/OutHDF5.cc @@ -20,6 +20,7 @@ #include "global.H" #include "OutHDF5.H" +#include "exp_git_version.h" // GIT_BRANCH, GIT_COMMIT, COMPILE_TIME const std::set OutHDF5::valid_keys = { diff --git a/src/parse.cc b/src/parse.cc index 4c1948d0e..c21ae5603 100644 --- a/src/parse.cc +++ b/src/parse.cc @@ -19,6 +19,7 @@ #include #include "global_key_set.H" +#include "exp_git_version.h" // GIT_BRANCH, GIT_COMMIT, COMPILE_TIME void exp_version() { From 7fdb632a6a8a0c8bd48d8ecad717c3cc1972ecd2 Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Wed, 2 Dec 2026 12:03:08 -0500 Subject: [PATCH 04/13] Implemented 'gpu_assignment' in the EXP 'Global' configuration. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mode and behavior are as follows: - Mode 'auto' selects ordinal 0 when one GPU is visible. Otherwise uses the existing node-local rank and ngpus mapping. - Mode 'task' uses the rank’s visible GPU list. gpu_ordinal defaults to 0. Ranks sharing a GPU UUID on the same node trigger a warning. - Mode 'node' requires ranks on a node to see the same ordered GPU list and assigns by node-local rank. - Set gpu_allow_sharing: true to allow round-robin sharing. Existing configurations default to 'auto' and keep the current device-selection behavior. The changed sources compiled, and eight four-rank MPI checks passed with simulated CUDA devices, including duplicate UUID warnings and rejection of mismatched node lists. --- src/begin.cc | 173 +++++++++++++++++++++++++++++++------------ src/global.H | 3 + src/global.cc | 3 + src/global_key_set.H | 3 + src/parse.cc | 12 +++ 5 files changed, 147 insertions(+), 47 deletions(-) diff --git a/src/begin.cc b/src/begin.cc index 77855990d..c4a90e874 100644 --- a/src/begin.cc +++ b/src/begin.cc @@ -7,6 +7,9 @@ 4) write parameter file */ +#include +#include // For getenv +#include #include #include // For getpid @@ -149,6 +152,33 @@ void begin_run(void) } +#if HAVE_LIBCUDA==1 +namespace { +constexpr int gpuUuidLength = 36; + +std::string gpuUuid(int ordinal, const std::string& diagnostic) +{ + cudaDeviceProp properties{}; + const auto status = cudaGetDeviceProperties(&properties, ordinal); + if (status != cudaSuccess) + throw GenericError("Could not query CUDA ordinal " + std::to_string(ordinal) + + " on " + diagnostic + ": " + cudaGetErrorString(status), + __FILE__, __LINE__, 1000, true); + + constexpr char hex[] = "0123456789abcdef"; + std::string uuid; + uuid.reserve(gpuUuidLength); + for (int i = 0; i < sizeof(properties.uuid.bytes); ++i) { + if (i == 4 || i == 6 || i == 8 || i == 10) uuid += '-'; + const auto byte = static_cast(properties.uuid.bytes[i]); + uuid += hex[byte >> 4]; + uuid += hex[byte & 0xf]; + } + return uuid; +} +} +#endif + void initialize_cuda() { #if HAVE_LIBCUDA==1 @@ -160,57 +190,106 @@ void initialize_cuda() pid_t pid = getpid(); - // Get device count; exit on failure - // - cuda_safe_call_mpi(cudaGetDeviceCount(&deviceCount), __FILE__, __LINE__, - myid, "cudaGetDevicecCount failure"); - - // Query and assign my CUDA device - // - if (deviceCount>0) { - - int totalCount = std::max(deviceCount, ngpus); - - // Get my local rank in sibling processes - // - int myCount = 0, curCount = 0; - for (auto v : siblingList) { - if (myid==v) myCount = curCount; - curCount++; - } - - // Allow GPU to be used by multiple MPI processes - // - if (myCount < totalCount) cudaGlobalDevice = myCount % deviceCount; - - // Set device; exit on failure - // - if (cudaGlobalDevice>=0) { - - cuda_safe_call_mpi(cudaSetDevice(cudaGlobalDevice), __FILE__, __LINE__, - myid, "cudaSetDevice failure"); - - std::cout << "---- Process <" << pid << ">: " - << "setting CUDA device on Rank [" << myid - << "] on [" << processor_name << "] to [" - << cudaGlobalDevice << "/" << deviceCount << "]" - << std::endl; - - } else { - - std::cout << "---- Component <" << pid << ">: " - << "could not set CUDA device on Rank [" << myid - << "] on [" << processor_name << "] . . . " - << "this will cause a failure" << std::endl; - + const auto countStatus = cudaGetDeviceCount(&deviceCount); + + const auto rank = std::find(siblingList.begin(), siblingList.end(), myid); + const auto localRank = rank - siblingList.begin(); + const int totalCount = std::max(deviceCount, ngpus); + const char* visibleDevices = std::getenv("CUDA_VISIBLE_DEVICES"); + + std::ostringstream diagnostic; + diagnostic << "Rank [" << myid << "] on [" << processor_name << "]" + << ", node-local rank=" << localRank << "/" << siblingList.size() + << ", visible CUDA devices=" << deviceCount + << ", gpu_assignment=" << gpu_assignment + << ", ngpus=" << ngpus << ", CUDA_VISIBLE_DEVICES="; + if (visibleDevices) diagnostic << '"' << visibleDevices << '"'; + else diagnostic << ""; + + const std::string context = diagnostic.str(); + if (countStatus != cudaSuccess) + throw GenericError("cudaGetDeviceCount failed on " + context + ": " + + cudaGetErrorString(countStatus), __FILE__, __LINE__, 1000, true); + if (deviceCount == 0 || rank == siblingList.end()) + throw GenericError("Could not assign a CUDA device on " + context, + __FILE__, __LINE__, 1000, true); + + std::string selectedUuid; + MPI_Comm nodeComm = MPI_COMM_NULL; + if (gpu_assignment != "auto") + MPI_Comm_split(MPI_COMM_WORLD, siblingList.front(), myid, &nodeComm); + + if (gpu_assignment == "task") { + if (gpu_ordinal >= deviceCount) + throw GenericError("gpu_ordinal " + std::to_string(gpu_ordinal) + + " is outside the visible device list on " + context, + __FILE__, __LINE__, 1000, true); + cudaGlobalDevice = gpu_ordinal; + selectedUuid = gpuUuid(cudaGlobalDevice, context); + std::string selectedByRank(gpuUuidLength * siblingList.size(), '\0'); + MPI_Allgather(selectedUuid.data(), gpuUuidLength, MPI_CHAR, + selectedByRank.data(), gpuUuidLength, MPI_CHAR, nodeComm); + if (localRank == 0) { + std::map> ranksByUuid; + for (std::size_t i = 0; i < siblingList.size(); ++i) + ranksByUuid[selectedByRank.substr(i * gpuUuidLength, gpuUuidLength)] + .push_back(siblingList[i]); + for (const auto& [uuid, ranks] : ranksByUuid) { + if (ranks.size() < 2) continue; + std::ostringstream warning; + warning << "---- CUDA task assignment on [" << processor_name + << "]: GPU UUID " << uuid << " is shared by ranks"; + for (int sharedRank : ranks) warning << ' ' << sharedRank; + std::cerr << warning.str() << std::endl; + } } + } else if (gpu_assignment == "node") { + std::string visibleUuids; + for (int ordinal = 0; ordinal < deviceCount; ++ordinal) + visibleUuids += gpuUuid(ordinal, context); + int rootListLength = visibleUuids.size(); + MPI_Bcast(&rootListLength, 1, MPI_INT, 0, nodeComm); + std::string rootUuids = visibleUuids; + rootUuids.resize(rootListLength); + MPI_Bcast(rootUuids.data(), rootListLength, MPI_CHAR, 0, nodeComm); + if (visibleUuids != rootUuids) + throw GenericError("Node assignment requires identical ordered GPU UUID lists. " + + context + " differs from rank " + std::to_string(siblingList.front()) + + ". Use gpu_assignment: task for per-task GPU binding", + __FILE__, __LINE__, 1000, true); + if (!gpu_allow_sharing && siblingList.size() > static_cast(deviceCount)) + throw GenericError("More ranks than visible GPUs on " + context + + ". Set gpu_allow_sharing: true to allow round-robin GPU sharing", + __FILE__, __LINE__, 1000, true); + cudaGlobalDevice = localRank % deviceCount; + selectedUuid = visibleUuids.substr(cudaGlobalDevice * gpuUuidLength, gpuUuidLength); + } else if (deviceCount == 1) { + // A task with one visible GPU always addresses it as device 0. + cudaGlobalDevice = 0; + } else if (localRank < totalCount) { + cudaGlobalDevice = localRank % deviceCount; + } - } else { - std::ostringstream sout; - sout << "[#" << myid << "] CUDA detected but deviceCount<=0!"; - throw GenericError(sout.str(), __FILE__, __LINE__, 1000, true); + if (nodeComm != MPI_COMM_NULL) MPI_Comm_free(&nodeComm); + if (cudaGlobalDevice < 0) { + // Other ranks may already be entering the collective CUDA error check. + throw GenericError("Could not assign a CUDA device on " + diagnostic.str(), + __FILE__, __LINE__, 1000, true); } + if (selectedUuid.empty()) selectedUuid = gpuUuid(cudaGlobalDevice, context); + std::cout << "---- Process <" << pid << ">: CUDA assignment on " + << context << ", selected ordinal=" << cudaGlobalDevice + << ", GPU UUID=" << selectedUuid + << std::endl; + cuda_safe_call_mpi(cudaSetDevice(cudaGlobalDevice), __FILE__, __LINE__, + myid, "cudaSetDevice failure"); + + std::cout << "---- Process <" << pid << ">: " + << "setting CUDA device on Rank [" << myid + << "] on [" << processor_name << "] to [" + << cudaGlobalDevice << "/" << deviceCount << "]" + << std::endl; } #endif } diff --git a/src/global.H b/src/global.H index 20b8ad6b2..058dc00e1 100644 --- a/src/global.H +++ b/src/global.H @@ -51,6 +51,9 @@ extern int nsteps; //! Number of gpu devices per node extern int ngpus; +extern std::string gpu_assignment; +extern int gpu_ordinal; +extern bool gpu_allow_sharing; //! Number of steps between particle number reports (use 0 for none) extern int nreport; diff --git a/src/global.cc b/src/global.cc index 1a22c21b9..d135dbbab 100644 --- a/src/global.cc +++ b/src/global.cc @@ -14,6 +14,9 @@ int nsteps = 500; // Number of steps to execute int nscale = 20; // Number of steps between rescaling int ngpus = 0; // Number of GPUs per node (0 means use all available) +std::string gpu_assignment = "auto"; +int gpu_ordinal = 0; +bool gpu_allow_sharing = false; int nbalance = 0; // Steps between load balancing int nreport = 0; // Steps between particle reporting double dbthresh = 0.05; // Load balancing threshold (5% by default) diff --git a/src/global_key_set.H b/src/global_key_set.H index c31745af5..53dc1db1e 100644 --- a/src/global_key_set.H +++ b/src/global_key_set.H @@ -3,6 +3,9 @@ global_valid_keys = { "nsteps", "nthrds", "ngpus", + "gpu_assignment", + "gpu_ordinal", + "gpu_allow_sharing", "nreport", "nbalance", "dbthresh", diff --git a/src/parse.cc b/src/parse.cc index c21ae5603..c462ce997 100644 --- a/src/parse.cc +++ b/src/parse.cc @@ -90,6 +90,15 @@ void initialize(void) if (_G["nsteps"]) nsteps = _G["nsteps"].as(); if (_G["nthrds"]) nthrds = std::max(1, _G["nthrds"].as()); if (_G["ngpus"]) ngpus = _G["ngpus"].as(); + if (_G["gpu_assignment"]) gpu_assignment = _G["gpu_assignment"].as(); + if (_G["gpu_ordinal"]) gpu_ordinal = _G["gpu_ordinal"].as(); + if (_G["gpu_allow_sharing"]) gpu_allow_sharing = _G["gpu_allow_sharing"].as(); + if (gpu_assignment != "auto" && gpu_assignment != "task" && gpu_assignment != "node") + throw EXPException("Configuration error", "gpu_assignment must be auto, task, or node", + __FILE__, __LINE__); + if (gpu_ordinal < 0) + throw EXPException("Configuration error", "gpu_ordinal must be nonnegative", + __FILE__, __LINE__); if (_G["nreport"]) nreport = _G["nreport"].as(); if (_G["nbalance"]) nbalance = _G["nbalance"].as(); if (_G["dbthresh"]) dbthresh = _G["dbthresh"].as(); @@ -342,6 +351,9 @@ void update_parm() if (not conf["nsteps"]) conf["nsteps"] = nsteps; if (not conf["nthrds"]) conf["nthrds"] = nthrds; if (not conf["ngpus"]) conf["ngpus"] = ngpus; + if (not conf["gpu_assignment"]) conf["gpu_assignment"] = gpu_assignment; + if (not conf["gpu_ordinal"]) conf["gpu_ordinal"] = gpu_ordinal; + if (not conf["gpu_allow_sharing"]) conf["gpu_allow_sharing"] = gpu_allow_sharing; if (not conf["nreport"]) conf["nreport"] = nreport; if (not conf["nbalance"]) conf["nbalance"] = nbalance; if (not conf["dbthresh"]) conf["dbthresh"] = dbthresh; From 27a58cd77f8b883af1ab5564e1ce9c5d4f1b1234 Mon Sep 17 00:00:00 2001 From: Martin Weinberg Date: Wed, 2 Dec 2026 12:25:11 -0500 Subject: [PATCH 05/13] Improve file existence check with error code Updated file existence check to include error handling. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/SlabSL.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/SlabSL.cc b/src/SlabSL.cc index 8840e5f54..e9fc1dfc7 100644 --- a/src/SlabSL.cc +++ b/src/SlabSL.cc @@ -278,8 +278,9 @@ bool SlabSL::freeze0Restore() if (myid==0) { std::string why; - if (not std::filesystem::exists(freeze0file)) { - why = "file not found"; + std::error_code ec; + if (not std::filesystem::exists(freeze0file, ec)) { + why = ec ? ec.message() : "file not found"; } else { try { YAML::Node node = YAML::LoadFile(freeze0file); From dfbac275b9644ce6aeb16f6203be4abf85791015 Mon Sep 17 00:00:00 2001 From: The9Cat <25960766+The9Cat@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:27:18 +0000 Subject: [PATCH 06/13] SlabSL: use frozen k=0 coefficients in point-field potential and gradient Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/SlabSL.cc | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/SlabSL.cc b/src/SlabSL.cc index e9fc1dfc7..abe091fe6 100644 --- a/src/SlabSL.cc +++ b/src/SlabSL.cc @@ -1256,15 +1256,30 @@ void SlabSL::determine_fields_at_point if (no_odd and iz%2==1) continue; } - // Live for frozen potential - if (self_consistent) { - fac = facx*facy*zpot[0][iz]*expccof[0](ix, iy, iz) * normXY; - facf = facx*facy*zfrc[0][iz]*expccof[0](ix, iy, iz) * normXY; - facd = facx*facy*zden[0][iz]*expccof[0](ix, iy, iz) * normXY; - } else { - fac = facx*facy*zpot[0][iz]*expcofF(ix, iy, iz) * normXY; - facf = facx*facy*zfrc[0][iz]*expcofF(ix, iy, iz) * normXY; - facd = facx*facy*zden[0][iz]*expcofF(ix, iy, iz) * normXY; + // Density is always live; potential and gradient follow the + // same frozen/fixed selection as the particle force evaluation + std::complex cf; + if (self_consistent) cf = expccof[0](ix, iy, iz); + else cf = expcofF(ix, iy, iz); + + facd = facx*facy*zden[0][iz]*cf * normXY; + + if (fixed0 and ii==0 and jj==0) { + if (iz==0) { + fac = facx*facy*zpot[0][iz]*value0 * normXY; + facf = facx*facy*zfrc[0][iz]*value0 * normXY; + } else { + fac = 0.0; + facf = 0.0; + } + } + else if (ii==0 and jj==0 and frozenAll()) { + fac = facx*facy*zpot[0][iz]*coefs0[iz] * normXY; + facf = facx*facy*zfrc[0][iz]*coefs0[iz] * normXY; + } + else { + fac = facx*facy*zpot[0][iz]*cf * normXY; + facf = facx*facy*zfrc[0][iz]*cf * normXY; } // Limit to minimum wave number From 8ab290736150f4dd241b2c3e98944d87f027c6c5 Mon Sep 17 00:00:00 2001 From: The9Cat <25960766+The9Cat@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:28:20 +0000 Subject: [PATCH 07/13] step: run closing COM velocity kick before step-end hook and output Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/step.cc | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/step.cc b/src/step.cc index 8c5fe1a67..e5d9e55e2 100644 --- a/src/step.cc +++ b/src/step.cc @@ -231,6 +231,12 @@ void do_step(int n) } // END: mstep loop + // COM update: closing velocity half-kick (before hooks and output) + // + if (step_timing) timer_vel.start(); + incr_com_velocity(0.5*dtime); + if (step_timing) timer_vel.stop(); + // Step-end hook for external forces (phase space synchronized) external->stepEnd(); @@ -244,12 +250,6 @@ void do_step(int n) tPtr = std::make_shared("Adjust multistep"); } - // COM update: second velocity half-kick - // - if (step_timing) timer_vel.start(); - incr_com_velocity(0.5*dtime); - if (step_timing) timer_vel.stop(); - #ifdef CHK_STEP // Check steps if (myid==0) { // From e25ef12221fc0aa11ff2e8f30825b3393549a712 Mon Sep 17 00:00:00 2001 From: The9Cat <25960766+The9Cat@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:58:00 +0000 Subject: [PATCH 08/13] Synchronize output writers before CUDA hooks Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/ExternalCollection.cc | 2 ++ src/OutputContainer.H | 4 +++- src/OutputContainer.cc | 14 ++++++++------ 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/ExternalCollection.cc b/src/ExternalCollection.cc index f95a36172..417392007 100644 --- a/src/ExternalCollection.cc +++ b/src/ExternalCollection.cc @@ -13,6 +13,7 @@ #include #include "ExternalCollection.H" +#include "OutputContainer.H" #include "tidalField.H" #include "externalShock.H" @@ -294,6 +295,7 @@ void ExternalCollection::stepEnd() // device once, only at the times when some force wants the hook. // (Done here, in EXP proper, so that user modules need no CUDA code.) if (use_cuda) { + output->synchronize(); for (auto c : comp->components) c->CudaToParticles(); } #endif diff --git a/src/OutputContainer.H b/src/OutputContainer.H index cc5d406c5..625dc0fd1 100644 --- a/src/OutputContainer.H +++ b/src/OutputContainer.H @@ -31,9 +31,11 @@ public: //! Will read configuration stanza and initialize requested output methods void initialize(); + //! Wait for and release pending output threads + void synchronize(); + //! Execute the all methods in the container void Run(int nstep, int mstep=std::numeric_limits::max(), bool final=false); }; #endif - diff --git a/src/OutputContainer.cc b/src/OutputContainer.cc index 64673ea3c..b29c41703 100644 --- a/src/OutputContainer.cc +++ b/src/OutputContainer.cc @@ -148,6 +148,12 @@ OutputContainer::~OutputContainer() for (auto it : out) delete it; } +void OutputContainer::synchronize() +{ + for (auto v : cproc) v->join(); + cproc.clear(); +} + void OutputContainer::Run(int nstep, int mstep, bool final) { // Don't rerun a step unless EXP is quitting . . . but allow for @@ -161,14 +167,10 @@ void OutputContainer::Run(int nstep, int mstep, bool final) if (use_cuda) { for (auto c : comp->components) comp->fetched[c] = false; - // Wait check that all previous threads are finished - // - for (auto v : cproc) v->join(); + synchronize(); } #endif - cproc.clear(); // Delete the threads - // Loop through all instances // for (auto it : out) it->Run(nstep, mstep, final); @@ -194,7 +196,7 @@ void OutputContainer::Run(int nstep, int mstep, bool final) // Wait check that all previous threads are finished // if (not use_cuda) { - for (auto v : cproc) v->join(); + synchronize(); } } From 5cdeaa9546c70ff86db5d707dd418e8e78aa5fb6 Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Wed, 2 Dec 2026 22:12:14 -0500 Subject: [PATCH 09/13] Version bump --- CMakeLists.txt | 2 +- doc/exp.cfg | 2 +- doc/exp.cfg.breathe | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 27627d682..2051c702f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.25) # Needed for CUDA, MPI, and CTest features project( EXP - VERSION "7.11.3" + VERSION "7.11.4" HOMEPAGE_URL https://github.com/EXP-code/EXP LANGUAGES C CXX Fortran) diff --git a/doc/exp.cfg b/doc/exp.cfg index add4206b2..9438b85d6 100644 --- a/doc/exp.cfg +++ b/doc/exp.cfg @@ -48,7 +48,7 @@ PROJECT_NAME = EXP # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 7.11.3 +PROJECT_NUMBER = 7.11.4 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/doc/exp.cfg.breathe b/doc/exp.cfg.breathe index a2b0e4674..cc13a136f 100644 --- a/doc/exp.cfg.breathe +++ b/doc/exp.cfg.breathe @@ -48,7 +48,7 @@ PROJECT_NAME = EXP # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 7.11.3 +PROJECT_NUMBER = 7.11.4 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a From 78621374b6cdb63f3e425d1f5a6298cc5d8af081 Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Thu, 3 Dec 2026 12:57:11 -0500 Subject: [PATCH 10/13] Logic fix --- src/OrbTrace.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/OrbTrace.cc b/src/OrbTrace.cc index 96a8b9de6..289ead81f 100644 --- a/src/OrbTrace.cc +++ b/src/OrbTrace.cc @@ -254,8 +254,12 @@ void OrbTrace::initialize() void OrbTrace::Run(int n, int mstep, bool last) { - if (n % nint && !last && !tcomp && norb) return; - if (mstep % nintsub !=0 && !tcomp && norb) return; + if (!tcomp || norb == 0) return; // Nothing to trace + + if (!last) { + if (n % nint) return; // Output cadence in major steps + if (multistep>1 && mstep % nintsub !=0) return; + } if (tnow <= prev) return; prev = tnow; // Record current time From cd66836f90649cc630e5e62c2ed8178a395f4343 Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Fri, 4 Dec 2026 11:52:36 -0500 Subject: [PATCH 11/13] Put module registration in anonymous namespaces for isolation --- src/user/UserBar.cc | 4 ++++ src/user/UserDisk.cc | 4 ++++ src/user/UserHalo.cc | 4 ++++ src/user/UserLogPot.cc | 4 ++++ src/user/UserMNdisk.cc | 4 ++++ src/user/UserMW.cc | 4 ++++ src/user/UserTest.cc | 4 ++++ src/user/UserTestCuda.cc | 4 ++++ 8 files changed, 32 insertions(+) diff --git a/src/user/UserBar.cc b/src/user/UserBar.cc index 46d049464..2e65fc38d 100644 --- a/src/user/UserBar.cc +++ b/src/user/UserBar.cc @@ -511,6 +511,8 @@ extern "C" { } } +namespace { + class proxybar { public: proxybar() @@ -520,3 +522,5 @@ class proxybar { }; static proxybar p; + +} // namespace diff --git a/src/user/UserDisk.cc b/src/user/UserDisk.cc index 3aaf19906..3a177bd60 100644 --- a/src/user/UserDisk.cc +++ b/src/user/UserDisk.cc @@ -415,6 +415,8 @@ extern "C" { } } +namespace { + class proxydisk { public: proxydisk() @@ -424,3 +426,5 @@ class proxydisk { }; static proxydisk p; + +} // namespace diff --git a/src/user/UserHalo.cc b/src/user/UserHalo.cc index d0cdbc8e8..5019794ec 100644 --- a/src/user/UserHalo.cc +++ b/src/user/UserHalo.cc @@ -236,6 +236,8 @@ extern "C" { } } +namespace { + class proxyhalo { public: proxyhalo() @@ -245,3 +247,5 @@ class proxyhalo { }; static proxyhalo p; + +} // namespace diff --git a/src/user/UserLogPot.cc b/src/user/UserLogPot.cc index 19248fb24..c1141433f 100644 --- a/src/user/UserLogPot.cc +++ b/src/user/UserLogPot.cc @@ -125,6 +125,8 @@ extern "C" { } } +namespace { + class proxylogpot { public: proxylogpot() @@ -134,3 +136,5 @@ class proxylogpot { }; static proxylogpot p; + +} // namespace diff --git a/src/user/UserMNdisk.cc b/src/user/UserMNdisk.cc index 20c215003..1bd70ab56 100644 --- a/src/user/UserMNdisk.cc +++ b/src/user/UserMNdisk.cc @@ -194,6 +194,8 @@ extern "C" { } } +namespace { + class proxymndisk { public: proxymndisk() @@ -203,3 +205,5 @@ class proxymndisk { }; static proxymndisk p; + +} // namespace diff --git a/src/user/UserMW.cc b/src/user/UserMW.cc index 73dd9b7fd..46c0fecb1 100644 --- a/src/user/UserMW.cc +++ b/src/user/UserMW.cc @@ -227,6 +227,8 @@ extern "C" { } } +namespace { + class proxymw { public: proxymw() @@ -236,3 +238,5 @@ class proxymw { }; static proxymw p; + +} // namespace diff --git a/src/user/UserTest.cc b/src/user/UserTest.cc index f7ed5493f..f7936cfe4 100644 --- a/src/user/UserTest.cc +++ b/src/user/UserTest.cc @@ -55,6 +55,8 @@ extern "C" { } } +namespace { + class proxytest { public: proxytest() @@ -64,3 +66,5 @@ class proxytest { }; static proxytest p; + +} // namespace diff --git a/src/user/UserTestCuda.cc b/src/user/UserTestCuda.cc index 0faecc4ee..7666b96a0 100644 --- a/src/user/UserTestCuda.cc +++ b/src/user/UserTestCuda.cc @@ -99,6 +99,8 @@ extern "C" { } } +namespace { + class proxytestcuda { public: proxytestcuda() @@ -108,3 +110,5 @@ class proxytestcuda { }; static proxytestcuda p; + +} // namespace From c1bd90ffa331dedd6b9d7015577061819fe2b186 Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Fri, 4 Dec 2026 12:14:14 -0500 Subject: [PATCH 12/13] - Enable a configurable module directory - Add a manifest list to make sure that crufty module libraries are removed --- CMakeLists.txt | 20 ++++++++++++++++++++ src/user/CMakeLists.txt | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2051c702f..3517d61b2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -61,6 +61,11 @@ option(ENABLE_XDR "Enable RPC/XDR support for Tipsy standard" FALSE) option(ENABLE_VTK "Configure VTK if available" FALSE) option(ENABLE_CUDA_SINGLE "Use real*4 instead of real*8 for CUDA" FALSE) option(ENABLE_USER "Enable compilation of user modules" ON) +set(EXP_USER_MODULE_DIR "user" CACHE STRING "User module directory name under the install prefix's lib directory") +if(NOT EXP_USER_MODULE_DIR MATCHES "^[A-Za-z0-9_][A-Za-z0-9_.+-]*$") + message(FATAL_ERROR "EXP_USER_MODULE_DIR must be a directory name under lib") +endif() +set(EXP_USER_MODULE_DESTINATION "lib/${EXP_USER_MODULE_DIR}") option(ENABLE_SLCHECK "Enable *careful* Sturm-Liouville solutions" TRUE) option(ENABLE_TESTS "Enable build tests for EXP, pyEXP and helpers" ON) option(ENABLE_MINIMAL "Compile EXP support libraries only" OFF) @@ -308,6 +313,17 @@ set(H5_USE_EIGEN TRUE CACHE BOOL "Eigen3 support in HighFive") add_subdirectory(extern/HighFive EXCLUDE_FROM_ALL) +if(ENABLE_USER) + configure_file(cmake/UserModuleInstall.in.cmake UserModuleInstall.cmake @ONLY) + # Hold the lock across installation and pruning, including installs + # of the Unspecified component that contains the module targets. + install(CODE " + set(exp_module_install_begin TRUE) + include(\"${CMAKE_CURRENT_BINARY_DIR}/UserModuleInstall.cmake\") + unset(exp_module_install_begin) + ") +endif() + # Configure the remaining native subdirectories add_subdirectory(exputil) add_subdirectory(expui) @@ -439,3 +455,7 @@ set(CMAKE_CXX_FLAGS_UBSAN # from the same source. configure_file(${CMAKE_SOURCE_DIR}/config_cmake.h_in ${CMAKE_BINARY_DIR}/config_exp.h) include_directories(${PROJECT_BINARY_DIR}) + +if(ENABLE_USER) + install(SCRIPT "${CMAKE_CURRENT_BINARY_DIR}/UserModuleInstall.cmake") +endif() diff --git a/src/user/CMakeLists.txt b/src/user/CMakeLists.txt index a419b9c64..58691d3ac 100644 --- a/src/user/CMakeLists.txt +++ b/src/user/CMakeLists.txt @@ -39,6 +39,6 @@ foreach(mlib ${USER_MODULES}) set_target_properties(${mlib} PROPERTIES OUTPUT_NAME ${mlib}) target_include_directories(${mlib} PUBLIC ${common_INCLUDE_DIRS}) target_link_libraries(${mlib} PUBLIC ${common_LINKLIB}) - install(TARGETS ${mlib} DESTINATION lib/user) + install(TARGETS ${mlib} DESTINATION "${EXP_USER_MODULE_DESTINATION}") endforeach() From 35078baf4325028e1cd16459c2d5698be433139b Mon Sep 17 00:00:00 2001 From: "Martin D. Weinberg" Date: Fri, 4 Dec 2026 12:35:58 -0500 Subject: [PATCH 13/13] Missing configure rules for user modules --- cmake/UserModuleInstall.in.cmake | 64 ++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 cmake/UserModuleInstall.in.cmake diff --git a/cmake/UserModuleInstall.in.cmake b/cmake/UserModuleInstall.in.cmake new file mode 100644 index 000000000..189a97ac8 --- /dev/null +++ b/cmake/UserModuleInstall.in.cmake @@ -0,0 +1,64 @@ +# CMake's install manifest paths omit DESTDIR, while filesystem operations +# must use the staged path when DESTDIR is set. +if(CMAKE_INSTALL_LOCAL_ONLY) + return() +endif() +set(exp_module_destination "${CMAKE_INSTALL_PREFIX}/@EXP_USER_MODULE_DESTINATION@") +set(exp_module_directory "$ENV{DESTDIR}${exp_module_destination}") +set(exp_module_manifest "${exp_module_directory}/.exp-user-modules") + +if(exp_module_install_begin) + file(MAKE_DIRECTORY "${exp_module_directory}") + file(LOCK "${exp_module_manifest}.lock" GUARD PROCESS TIMEOUT 60) + return() +endif() + +# A component install cannot determine which modules have been retired. +if(NOT "${CMAKE_INSTALL_COMPONENT}" STREQUAL "") + return() +endif() + +set(exp_module_filename_pattern "^lib[A-Za-z0-9_.+-]+\\.(so(\\.[0-9]+)*|dylib|a)$") +set(exp_module_files) +foreach(exp_installed_file IN LISTS CMAKE_INSTALL_MANIFEST_FILES) + get_filename_component(exp_installed_dir "${exp_installed_file}" DIRECTORY) + if(exp_installed_dir STREQUAL exp_module_destination) + get_filename_component(exp_installed_name "${exp_installed_file}" NAME) + if(exp_installed_name MATCHES "${exp_module_filename_pattern}") + list(APPEND exp_module_files "${exp_installed_name}") + endif() + endif() +endforeach() +list(REMOVE_DUPLICATES exp_module_files) +list(SORT exp_module_files) + +if(IS_SYMLINK "${exp_module_manifest}" OR IS_DIRECTORY "${exp_module_manifest}") + message(FATAL_ERROR "Invalid EXP user module manifest: ${exp_module_manifest}") +endif() +if(EXISTS "${exp_module_manifest}") + file(STRINGS "${exp_module_manifest}" exp_previous_modules) + foreach(exp_previous_module IN LISTS exp_previous_modules) + # Accept library basenames only. Never remove a path outside this directory. + if(NOT exp_previous_module MATCHES "${exp_module_filename_pattern}") + message(FATAL_ERROR "Invalid entry in ${exp_module_manifest}: ${exp_previous_module}") + endif() + endforeach() + foreach(exp_previous_module IN LISTS exp_previous_modules) + if(NOT exp_previous_module IN_LIST exp_module_files) + set(exp_obsolete_module "${exp_module_directory}/${exp_previous_module}") + if(IS_DIRECTORY "${exp_obsolete_module}") + message(WARNING "Keeping directory at obsolete EXP module path: ${exp_obsolete_module}") + elseif(EXISTS "${exp_obsolete_module}" OR IS_SYMLINK "${exp_obsolete_module}") + message(STATUS "Removing obsolete EXP user module: ${exp_obsolete_module}") + file(REMOVE "${exp_obsolete_module}") + if(EXISTS "${exp_obsolete_module}" OR IS_SYMLINK "${exp_obsolete_module}") + message(FATAL_ERROR "Could not remove obsolete EXP user module: ${exp_obsolete_module}") + endif() + endif() + endif() + endforeach() +endif() + +list(JOIN exp_module_files "\n" exp_module_contents) +file(CONFIGURE OUTPUT "${exp_module_manifest}.tmp" CONTENT "${exp_module_contents}\n" @ONLY) +file(RENAME "${exp_module_manifest}.tmp" "${exp_module_manifest}")