From 16515dd79e06f5d4e123a66ac85fa4718a7d2f14 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 5 Nov 2025 10:58:50 +0100 Subject: [PATCH 01/18] add the core of J. Kempf's focing module to the main Idefix trunk --- src/forcing/CMakeLists.txt | 6 + src/forcing/OrnsteinUhlenbeckProcess.cpp | 203 +++++ src/forcing/OrnsteinUhlenbeckProcess.hpp | 68 ++ src/forcing/forcing.cpp | 1040 ++++++++++++++++++++++ src/forcing/forcing.hpp | 120 +++ 5 files changed, 1437 insertions(+) create mode 100644 src/forcing/CMakeLists.txt create mode 100644 src/forcing/OrnsteinUhlenbeckProcess.cpp create mode 100644 src/forcing/OrnsteinUhlenbeckProcess.hpp create mode 100644 src/forcing/forcing.cpp create mode 100644 src/forcing/forcing.hpp diff --git a/src/forcing/CMakeLists.txt b/src/forcing/CMakeLists.txt new file mode 100644 index 000000000..03d259cb2 --- /dev/null +++ b/src/forcing/CMakeLists.txt @@ -0,0 +1,6 @@ +target_sources(idefix + PUBLIC ${CMAKE_CURRENT_LIST_DIR}/forcing.hpp + PUBLIC ${CMAKE_CURRENT_LIST_DIR}/forcing.cpp + PUBLIC ${CMAKE_CURRENT_LIST_DIR}/OrnsteinUhlenbeckProcess.hpp + PUBLIC ${CMAKE_CURRENT_LIST_DIR}/OrnsteinUhlenbeckProcess.cpp + ) diff --git a/src/forcing/OrnsteinUhlenbeckProcess.cpp b/src/forcing/OrnsteinUhlenbeckProcess.cpp new file mode 100644 index 000000000..92d073aa7 --- /dev/null +++ b/src/forcing/OrnsteinUhlenbeckProcess.cpp @@ -0,0 +1,203 @@ +// *********************************************************************************** +// Idefix MHD astrophysical code +// Copyright(C) 2020-2022 Geoffroy R. J. Lesur +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +// *********************************************************************************** +// Idefix MHD astrophysical code +// Copyright(C) 2020-2021 Geoffroy R. J. Lesur +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#include "OrnsteinUhlenbeckProcess.hpp" + +OrnsteinUhlenbeckProcesses::OrnsteinUhlenbeckProcesses() +{ // Default (empty) constructor +} + +void OrnsteinUhlenbeckProcesses::InitProcesses(std::string folder, int seed, int nSeries, std::vector> modeNames) { + this->names = modeNames; + this->nSeries = nSeries; + this->ouValues = IdefixArray2D> ("ouValues", nSeries, COMPONENTS); + this->normalValuesReal = IdefixArray2D ("normalValuesReal", nSeries, COMPONENTS); + this->normalValuesImag = IdefixArray2D ("normalValuesImag", nSeries, COMPONENTS); + this->random_pool = Kokkos::Random_XorShift64_Pool<> (/*seed=*/seed); + + this->ouFilename = folder + "/ou_prank" + std::to_string(idfx::prank) + "_seed" + std::to_string(seed) + ".dat"; + this->normalFilename = folder + "/normal_prank" + std::to_string(idfx::prank) + "_seed" + std::to_string(seed) + ".dat"; + this->timestepFilename = folder + "/timestep.dat"; + this->precision = 10; + this->ouValuesHost = IdefixHostArray2D> ("ouValuesHost", nSeries, COMPONENTS); + this->normalValuesRealHost = IdefixHostArray2D ("normalValuesRealHost", nSeries, COMPONENTS); + this->normalValuesImagHost = IdefixHostArray2D ("normalValuesImagHost", nSeries, COMPONENTS); +} + +void OrnsteinUhlenbeckProcesses::SetProcesses(IdefixArray2D mean, IdefixArray2D tcorr, IdefixArray2D epsilon) { + this->epsilons = IdefixArray2D ("ouEpsilons", nSeries, COMPONENTS); + this->tcorrs = IdefixArray2D ("ouTcorrs", nSeries, COMPONENTS); + this->means = IdefixArray2D ("ouMeans", nSeries, COMPONENTS); + IdefixArray2D means = this->means; + IdefixArray2D tcorrs = this->tcorrs; + IdefixArray2D epsilons = this->epsilons; + IdefixArray2D> ouValues = this->ouValues; + int nSeries = this->nSeries; + idefix_for("SetProcesses", 0, nSeries, 0, COMPONENTS, + KOKKOS_LAMBDA (int l, int dir) { + means(l, dir) = mean(l, dir); + tcorrs(l, dir) = tcorr(l, dir); + epsilons(l, dir) = epsilon(l, dir)/nSeries; //so that the total amplitude is independent of the number of modes used to force + ouValues(l, dir) = mean(l, dir); + }); +} + +//void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt, IdefixArray1D epsilons) { +void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt) { + IdefixArray2D means = this->means; + IdefixArray2D tcorrs = this->tcorrs; + IdefixArray2D epsilons = this->epsilons; + IdefixArray2D> ouValues = this->ouValues; + IdefixArray2D normalValuesReal = this->normalValuesReal; + IdefixArray2D normalValuesImag = this->normalValuesImag; + Kokkos::Random_XorShift64_Pool<> random_pool = this->random_pool; + idefix_for("UpdateProcesses", 0, nSeries, 0, COMPONENTS, + KOKKOS_LAMBDA (int l, int dir) { + auto generator = random_pool.get_state(); + real normalReal = generator.normal(0., 1.); + real normalImag = generator.normal(0., 1.); + random_pool.free_state(generator); + normalValuesReal(l, dir) = normalReal; + normalValuesImag(l, dir) = normalImag; + real expTerm = std::exp(-dt/tcorrs(l, dir)); + real dou = std::sqrt(epsilons(l, dir)/sqrt(2.)/tcorrs(l, dir)*(1. - expTerm*expTerm)); + real realPart = ouValues(l, dir).real(); + real normalisedMean = means(l, dir)/sqrt(2.); + real newRealPart = normalisedMean + (realPart-normalisedMean)*expTerm + dou*normalReal; + + real imagPart = ouValues(l, dir).imag(); + real newImagPart = normalisedMean + (imagPart-normalisedMean)*expTerm + dou*normalImag; + Kokkos::complex newCompValue(newRealPart, newImagPart); + ouValues(l, dir) = newCompValue; + }); +} + +//void OrnsteinUhlenbeckProcesses::AdvanceProcessesValues(std::vector tabDt) { +//std::cout << tabDt.empty() << std::endl; +// while (not tabDt.empty()) { +// real dt = tabDt[0]; +// tabDt.erase(tabDt.begin()); +// UpdateProcessesValues(dt); +////std::cout << dt << std::endl; +// } +//} + +void OrnsteinUhlenbeckProcesses::AdvanceProcessesValues() { + + std::ifstream file(timestepFilename); + std::string line; + + if (file.is_open()) { + while (getline(file, line)) { + std::string::size_type sz; + real dt = std::stof(line, &sz); + real t = std::stof(line.substr(sz)); + UpdateProcessesValues(dt); + } + file.close(); + } + else { + IDEFIX_ERROR("UNABLE TO READ THE TIMESTEP FILE TO ADVANCE OU PROCESSES"); + } +} + +void OrnsteinUhlenbeckProcesses::ResetProcessesValues() { + if(idfx::prank==0) { + file.open(ouFilename, std::ios::trunc); + int col_width = 3*precision + 10; + file << "t"; + for (int l=0; lfile << std::scientific << time; + Kokkos::deep_copy(ouValuesHost, ouValues); + for (int l=0; lfile << std::scientific << std::setw(col_width) << time; + Kokkos::deep_copy(normalValuesRealHost, normalValuesReal); + Kokkos::deep_copy(normalValuesImagHost, normalValuesImag); + for (int l=0; lfile << std::scientific << std::setw(col_width) << dt; + this->file << std::scientific << std::setw(col_width) << time; + file << std::endl; + file.close(); + } +} + diff --git a/src/forcing/OrnsteinUhlenbeckProcess.hpp b/src/forcing/OrnsteinUhlenbeckProcess.hpp new file mode 100644 index 000000000..678caae11 --- /dev/null +++ b/src/forcing/OrnsteinUhlenbeckProcess.hpp @@ -0,0 +1,68 @@ +// *********************************************************************************** +// Idefix MHD astrophysical code +// Copyright(C) 2020-2022 Geoffroy R. J. Lesur +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +// *********************************************************************************** +// Idefix MHD astrophysical code +// Copyright(C) 2020-2021 Geoffroy R. J. Lesur +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#ifndef ORNSTEIN_UHLENBECK_PROCESS_HPP +#define ORNSTEIN_UHLENBECK_PROCESS_HPP + +//#include +//#include +#include +#include "idefix.hpp" +#include +#include +#include +//#include + + +class OrnsteinUhlenbeckProcesses { +private: + std::vector> names; + int nSeries; + + IdefixArray2D means; + IdefixArray2D tcorrs; + IdefixArray2D epsilons; + + Kokkos::Random_XorShift64_Pool<> random_pool; + +public: + IdefixArray2D> ouValues; + IdefixHostArray2D> ouValuesHost; + IdefixArray2D normalValuesReal; + IdefixArray2D normalValuesImag; + IdefixHostArray2D normalValuesRealHost; + IdefixHostArray2D normalValuesImagHost; + + OrnsteinUhlenbeckProcesses(); // Default (empty) constructor + void InitProcesses(std::string, int, int, std::vector>); + void SetProcesses(IdefixArray2D, IdefixArray2D, IdefixArray2D); + void UpdateProcessesValues(real); +// void AdvanceProcessesValues(std::vector); + void AdvanceProcessesValues(); + + std::string ouFilename; + std::string normalFilename; + std::string timestepFilename; + void ResetProcessesValues(); + void WriteProcessesValues(real); + void ResetNormalValues(); + void WriteNormalValues(real); + void ResetTimestep(); + void WriteTimestep(real, real); + int precision; + + std::ofstream file; +}; + +#endif // ORNSTEIN_UHLENBECK_PROCESS_HPP diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp new file mode 100644 index 000000000..032b1e995 --- /dev/null +++ b/src/forcing/forcing.cpp @@ -0,0 +1,1040 @@ +// *********************************************************************************** +// Idefix MHD astrophysical code +// Copyright(C) Geoffroy R. J. Lesur +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#include + +#include "forcing.hpp" +#include "dataBlock.hpp" +#include "dataBlockHost.hpp" +#include "input.hpp" + +KOKKOS_INLINE_FUNCTION real K_aff_11(real x, real x0, real x1) { + return 2./(x1-x0)*x - (x1+x0)/(x1-x0); +} + +KOKKOS_INLINE_FUNCTION real K_aff_02pi(real x, real x0, real x1) { + return 2.*M_PI*(x - x0)/(x1 - x0); +} + +KOKKOS_INLINE_FUNCTION real K_cheby_fst(int n, real x) { + if (x >= -1. and x <= 1.) { + return cos(n*acos(x)); + } else { + return ZERO_F; + } +} + +KOKKOS_INLINE_FUNCTION real K_cheby_fst_both_hom_dir(int n, real x) { + if (x >= -1. and x <= 1.) { + return cos(n*acos(x)) - 1.*((n+1)%2) - x*(n%2); + } else { + return ZERO_F; + } +} + +KOKKOS_INLINE_FUNCTION real K_cheby_fst_both_hom_neu(int n, real x) { + if (x >= -1. and x <= 1.) { + return cos(n*acos(x)) - pow(n/(n+2),2.)*cos((n+2)*acos(x)); +// return cos(n*acos(x)) - pow(n/(n+2),2.)*cos((n+2)*acos(x))*((n+1)%2) - pow(n/(n+2),2.)*cos((n+2)*acos(x))*(n%2); + } else { + return ZERO_F; + } +} + +KOKKOS_INLINE_FUNCTION real K_fourier(int n, real x) { + if (x >= 0. and x <= 2.*M_PI) { + return cos(n*x) + sin(n*x); + } else { + return ZERO_F; + } +} + +KOKKOS_INLINE_FUNCTION real K_sin(int n, real x) { + if (x >= 0. and x <= 2.*M_PI) { + return sin(n*x); + } else { + return ZERO_F; + } +} + +KOKKOS_INLINE_FUNCTION real K_cos(int n, real x) { + if (x >= 0. and x <= 2.*M_PI) { + return cos(n*x); + } else { + return ZERO_F; + } +} + +Forcing::Forcing(Input &input, DataBlock *datain) { + idfx::pushRegion("Forcing::Forcing"); + this->data = datain; + this->seed = input.GetOrSet("Forcing","seed",0,0); + + this->write = input.GetOrSet("Forcing","write",0, 0); +// std::string folder = input.GetOrSet("Forcing","filename",0,"testOU"); + this->folder = input.GetOrSet("Output","folder",0,"output"); + + this->stillHaveForcing = true; + this->stopTime = input.GetOrSet("Forcing","stoptime",0,std::numeric_limits::infinity()); + + this->nForcingModes = 0; + + this->kmin = -1.; + this->kmax = -1.; + this->ellmin = -1; + this->ellmax = -1; + this->mmin = -1; + this->mmax = -1; + this->haveSolenoidalForcing = false; + + this->xbeg = data->mygrid->xbeg[IDIR]; + this->xend = data->mygrid->xend[IDIR]; + this->ybeg = data->mygrid->xbeg[JDIR]; + this->yend = data->mygrid->xend[JDIR]; + this->zbeg = data->mygrid->xbeg[KDIR]; + this->zend = data->mygrid->xend[KDIR]; + + this->kx0 = 2.*M_PI/(xend - xbeg); + this->ky0 = 2.*M_PI/(yend - ybeg); + this->kz0 = 2.*M_PI/(zend - zbeg); + + if (input.CheckEntry("Forcing", "iso3D")>=0) { + this->forcingType = iso3D; + #if GEOMETRY != CARTESIAN + IDEFIX_ERROR("You cannot have 3D isotropic forcing in another geometry than Cartesian"); + #endif //GEOMETRY != CARTESIAN + #if COMPONENTS < 3 or DIMENSIONS < 3 +std::cout << COMPONENTS << DIMENSIONS << std::endl; + IDEFIX_ERROR("You cannot have 3D isotropic forcing with less than 3 components and dimensions."); + #endif //COMPONENTS < 3 or DIMENSIONS < 3 +// if () IDEFIX_ERROR("You should not have 3D isotropic forcing with other boundary conditions than fully periodic."); + #if GEOMETRY == SPHERICAL + IDEFIX_ERROR("Comparing radial with angular wavenumbers is somewhat shady."); + #endif //GEOMETRY == SPHERICAL + this->kmin = input.Get("Forcing","iso3D", 0); + this->kmax = input.Get("Forcing","iso3D", 1); + + std::vector> k3Disovec; + + int nxmax = kmax/kx0 + 1; + int nymax = kmax/ky0 + 1; + int nzmax = kmax/kz0 + 1; + for (int nx=1; nx= kmin*kmin and k_2 <= kmax*kmax) { + nForcingModes ++; + k3Disovec.push_back({kx, ky, kz}); + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz)}); + nForcingModes ++; + k3Disovec.push_back({kx, -ky, kz}); + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(-ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(-ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(-ny) + std::to_string(nz)}); + nForcingModes ++; + k3Disovec.push_back({kx, ky, -kz}); + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(-nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(-nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(-nz)}); + nForcingModes ++; + k3Disovec.push_back({kx, -ky, -kz}); + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(-ny) + std::to_string(-nz), "J" + std::to_string(nx) + std::to_string(-ny) + std::to_string(-nz), "K" + std::to_string(nx) + std::to_string(-ny) + std::to_string(-nz)}); + } + } + } + } + k3DisoHost = IdefixHostArray2D("k3DisoHost", nForcingModes, 3); + k3Diso = IdefixArray2D("k3Diso", nForcingModes, 3); + for (int l=0; lforcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) + } + + else if (input.CheckEntry("Forcing", "iso2D")>=0) { + this->forcingType = iso2D; + this->normal2DisoStr = input.Get("Forcing","iso2D", 0); + if (this->normal2DisoStr == "IDIR") this->normal2Diso = IDIR; + else if (this->normal2DisoStr == "JDIR") this->normal2Diso = JDIR; + else if (this->normal2DisoStr == "KDIR") this->normal2Diso = KDIR; + else IDEFIX_ERROR("The normal component for 2D isotropic forcing cannot not be something else than IDIR, JDIR or KDIR"); + #if COMPONENTS < 2 or DIMENSIONS < 2 + IDEFIX_ERROR("You cannot have 2D isotropic forcing with less than 2 components and dimensions."); + #endif //COMPONENTS < 2 or DIMENSIONS < 2 + #if GEOMETRY == SPHERICAL + if (this->normal2DisoStr == "JDIR" or this->normal2DisoStr == "KDIR") IDEFIX_ERROR("Comparing radial with angular wavenumbers is somewhat shady."); + #endif //GEOMETRY == SPHERICAL + + this->kmin = input.Get("Forcing","iso2D", 1); + this->kmax = input.Get("Forcing","iso2D", 2); + + std::vector> k2Disovec; + + kx0 = (this->normal2Diso==IDIR) ? ZERO_F : kx0; + ky0 = (this->normal2Diso==JDIR) ? ZERO_F : ky0; + kz0 = (this->normal2Diso==KDIR) ? ZERO_F : kz0; + int nxmax = (this->normal2Diso==IDIR) ? 1 : kmax/kx0 + 1; + int nymax = (this->normal2Diso==JDIR) ? 1 : kmax/ky0 + 1; + int nzmax = (this->normal2Diso==KDIR) ? 1 : kmax/kz0 + 1; + int xsign, ysign, zsign; + if (this->normal2Diso==IDIR) { + xsign = 0; + ysign = 1; + zsign = -1; + } else if (this->normal2Diso==JDIR) { + xsign = 1; + ysign = 0; + zsign = -1; + } else { + xsign = 1; + ysign = -1; + zsign = 0; + } + for (int nx=0; nx= kmin*kmin and k_2 <= kmax*kmax) { + nForcingModes ++; + k2Disovec.push_back({kx, ky, kz}); + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz)}); + nForcingModes ++; + k2Disovec.push_back({xsign*kx, ysign*ky, zsign*kz}); + modeNames.push_back({"I" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "J" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "K" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz)}); + } + } + } + } + k2DisoHost = IdefixHostArray2D("k2DisoHost", nForcingModes, 3); + k2Diso = IdefixArray2D("k2Diso", nForcingModes, 3); + for (int l=0; lforcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) + } + + else if (input.CheckEntry("Forcing", "ani3D")>=0) { + #if COMPONENTS < 3 or DIMENSIONS < 3 + IDEFIX_ERROR("You cannot have 3D anisotropic forcing with less than 3 components and dimensions."); + #endif //COMPONENTS < 3 or DIMENSIONS < 3 + this->forcingType = ani3D; + this->normal3DaniStr = input.Get("Forcing","ani3D", 0); + if (this->normal3DaniStr == "IDIR") this->normal3Dani = IDIR; + else if (this->normal3DaniStr == "JDIR") this->normal3Dani = JDIR; + else if (this->normal3DaniStr == "KDIR") this->normal3Dani = KDIR; + else IDEFIX_ERROR("The normal component for 3D anisotropic forcing cannot not be something else than IDIR, JDIR or KDIR"); +// this->normal3DaniBoundStr = input.Get("Forcing","ani3D", 1); +// if (this->normal3DaniBoundStr == "bothfree") this->normal3DaniBound = bothFree; +// else if (this->normal3DaniBoundStr == "righthomdir") this->normal3DaniBound = rightHomDir; +// else if (this->normal3DaniBoundStr == "bothhomdir") this->normal3DaniBound = bothHomDir; +// else if (this->normal3DaniBoundStr == "bothhomneu") this->normal3DaniBound = bothHomNeu; +// else IDEFIX_ERROR("The boundaries for the normal component of the forcing can only be bothfree, righthomdir, bothhomdir or bothhomneu for now."); +// this->normal3DaniBasisStr = input.Get("Forcing","ani3D", 2); +// if (this->normal3DaniBasisStr == "chebyshev") this->normal3DaniBasis = chebyshev; +//// else if (this->normal3DaniBasisStr == "legendre") this->normal3DaniBasis = legendre; +// else if (this->normal3DaniBasisStr == "fourier") this->normal3DaniBasis = fourier; +// else IDEFIX_ERROR("The basis for the normal component of the forcing can only be chebyshev and fourier for now (legendre coming soon)."); +//// if (this->normal3DaniBasis = chebyshev and this->normal3DaniBound = bothHomNeu) IDEFIX_ERROR("Cannot have a chebyshev basis which has both homogeneous Neumann boundaries."); +//// else if (normal3DaniBasis = fourier and normal3DaniBound = rightHomDir) IDEFIX_ERROR("Cannot have a fourier basis which has only right homogeneous Dirichlet boundary."); + + this->normal3DaniBasisStr = input.Get("Forcing","ani3D", 1); + if (this->normal3DaniBasisStr == "chebyshev") this->normal3DaniBasis = chebyshev; +// else if (this->normal3DaniBasisStr == "legendre") this->normal3DaniBasis = legendre; + else if (this->normal3DaniBasisStr == "fourier") this->normal3DaniBasis = fourier; + else IDEFIX_ERROR("The basis for the normal component of the forcing can only be chebyshev and fourier for now (legendre coming soon)."); + + std::vector vecNormal3DaniBound; + std::string dirbegStr = "X" + std::to_string(this->normal3Dani + 1) + "-beg"; + std::string direndStr = "X" + std::to_string(this->normal3Dani + 1) + "-end"; + if (input.Get("Boundary",dirbegStr, 0) != input.Get("Boundary",direndStr, 0)) { + IDEFIX_ERROR("Chebyshev basis with different BCs at the two sides are not yet implemented"); + } else if (input.Get("Boundary",dirbegStr, 0) == "reflective") { + (this->normal3Dani == IDIR) ? vecNormal3DaniBound.push_back(bothHomDir) : vecNormal3DaniBound.push_back(bothHomNeu); + (this->normal3Dani == JDIR) ? vecNormal3DaniBound.push_back(bothHomDir) : vecNormal3DaniBound.push_back(bothHomNeu); + (this->normal3Dani == KDIR) ? vecNormal3DaniBound.push_back(bothHomDir) : vecNormal3DaniBound.push_back(bothHomNeu); + } else if (input.Get("Boundary",dirbegStr, 0) == "outflow") { + vecNormal3DaniBound.push_back(bothHomNeu); + vecNormal3DaniBound.push_back(bothHomNeu); + vecNormal3DaniBound.push_back(bothHomNeu); + } else if (input.Get("Boundary",dirbegStr, 0) == "userdef") { + for (int dir = IDIR; dir("Boundary",userdefDirbegStr, 0) != input.Get("Boundary",userdefDirendStr, 0)) { + IDEFIX_ERROR("Chebyshev basis with different BCs at the two sides are not yet implemented"); + } else if (input.Get("Boundary",userdefDirbegStr, 0) == "dirichletZero") { + vecNormal3DaniBound.push_back(bothHomDir); + } else if (input.Get("Boundary",userdefDirbegStr, 0) == "neumann") { + vecNormal3DaniBound.push_back(bothHomNeu); + } else { + IDEFIX_ERROR("userdef BCs not recognised, they are needed choose the suitable forcing basis."); + } + } + } else if (input.Get("Boundary",dirbegStr, 0) == "periodic") { + IDEFIX_ERROR("periodic BCs recognised, you should use 3D isotropic forcing in this direction."); + } else { + IDEFIX_ERROR("BCs not recognised, they are needed choose the suitable forcing basis."); + } + normal3DaniBoundHost = IdefixHostArray1D("normal3DaniBoundHost", COMPONENTS); + normal3DaniBound = IdefixArray1D("normal3DaniBound", COMPONENTS); + for (int l=IDIR; lkmin = input.Get("Forcing","ani3D", 2); + this->kmax = input.Get("Forcing","ani3D", 3); + + if (input.GetOrSet("Forcing","ani3D", 4, "n") == "write") WriteNormalBasis(folder); + + std::vector> k3Danivec; + + int nxmax = kmax/kx0 + 1; + int nymax = kmax/ky0 + 1; + int nzmax = kmax/kz0 + 1; + int xsign, ysign, zsign; + if (this->normal3Dani==IDIR) { + xsign = 1; + ysign = 1; + zsign = -1; + } else if (this->normal3Dani==JDIR) { + xsign = 1; + ysign = 1; + zsign = -1; + } else if (this->normal3Dani==KDIR) { + xsign = 1; + ysign = -1; + zsign = 1; + } else { + IDEFIX_ERROR("Forcing: normal direction not known"); + } + for (int nx=1; nx= kmin*kmin and k_2 <= kmax*kmax) { + nForcingModes ++; + k3Danivec.push_back({kx, ky, kz}); + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz)}); + nForcingModes ++; + k3Danivec.push_back({xsign*kx, ysign*ky, zsign*kz}); + modeNames.push_back({"I" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "J" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "K" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz)}); + } + } + } + } + k3DaniHost = IdefixHostArray2D("k3DaniHost", nForcingModes, 3); + k3Dani = IdefixArray2D("k3Dani", nForcingModes, 3); + for (int l=0; lforcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) + } + + else if (input.CheckEntry("Forcing", "vsh")>=0) { + this->forcingType = vsh; + #if GEOMETRY != SPHERICAL + IDEFIX_ERROR("You cannot have vsh forcing in another geometry than spherical."); + #endif //GEOMETRY != SPHERICAL + #if VSH == NO + IDEFIX_ERROR("You cannot have vsh forcing without the VSH module."); + #endif //VSH == NO +// if () IDEFIX_ERROR("You cannot have vsh forcing without the full sphere."); + this->ellmin = input.Get("Forcing","vsh", 0); + this->ellmax = input.Get("Forcing","vsh", 1); + this->mmin = input.GetOrSet("Forcing","vsh", 2, 0); + this->mmax = input.GetOrSet("Forcing","vsh", 3, this->ellmax); + + std::vector> ellmVshvec; + for (int ell=ellmin; ellnForcingModes++; + ellmVshvec.push_back({ell,m}); + modeNames.push_back({"Y" + std::to_string(ell) + std::to_string(m), "S" + std::to_string(ell) + std::to_string(m), "T" + std::to_string(ell) + std::to_string(m)}); + } + } + ellmVshHost = IdefixHostArray2D("ellmVshHost", nForcingModes, 2); + ellmVsh = IdefixArray2D("ellmVsh", nForcingModes, 2); + for (int l=0; lforcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + // WARNING, vsh case needs a special treatment since the forcing modes between + // the theta and phi directions are coupled to each other... + this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", 2*nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", 2*nForcingModes, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) + } + +// else { this->haveUserDef = true;} + else { this->forcingType = userDef;} // TO BE CODED THOUGH + + if (input.CheckEntry("Forcing", "solenoidal")>=0) { + #if GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL + IDEFIX_ERROR("Cannot have solenoidal forcing in polar in cylindrical geometry."); + #endif //GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL + if (this->forcingType == vsh) IDEFIX_ERROR("Cannot have solenoidal forcing with vsh forcing. Select yourself the toroidal vector spherical harmonics in this case."); + else if (this->forcingType == userDef) IDEFIX_ERROR("Cannot have solenoidal forcing with userdef forcing."); + else this->haveSolenoidalForcing = true; + } + + // Allocate required arrays + this->forcingTerm = IdefixArray4D("forcingTerm", COMPONENTS, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); + this->pristineForcingTerm = IdefixArray4D("pristineForcingTerm", COMPONENTS, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); + this->solenoidalForcingTerm = IdefixArray4D("solenoidalForcingTerm", COMPONENTS, + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); +// this->compressiveForcingTerm = IdefixArray4D("compressiveForcingTerm", COMPONENTS, +// data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); + + this->means = IdefixArray2D("means", nForcingModes, COMPONENTS); + this->tcorrs = IdefixArray2D("tcorrs", nForcingModes, COMPONENTS); + this->epsilons = IdefixArray2D("epsilons", nForcingModes, COMPONENTS); + +// WARNING DO SOMETHING WITH MEANS TCORRS AND EPSILONS + this->hostMeans = IdefixHostArray2D("hostMeans", nForcingModes, COMPONENTS); + this->hostTcorrs = IdefixHostArray2D("hostTcorrs", nForcingModes, COMPONENTS); + this->hostEpsilons = IdefixHostArray2D("hostEpsilons", nForcingModes, COMPONENTS); + this->machNumber = input.GetOrSet("Forcing", "mach", 0, -1.); + if (this->machNumber >= 0) { // in this case they will be reset later + tcorr = 1.; + epsilon = -1.; + } else{ + tcorr = input.Get("Forcing", "t_corr", 0); + epsilon = input.Get("Forcing", "epsilon", 0); + } + #ifdef ISOTHERMAL + this->cs = input.Get("Hydro", "csiso", 1); //WARNING DOESN'T WORK FOR USERDEF csiso + #endif + + this->oUprocesses.InitProcesses(this->folder, this->seed, this->nForcingModes, this->modeNames); + idfx::popRegion(); +} + +void Forcing::ShowConfig() { + idfx::cout << "Forcing: ENABLED with seed " << seed << "." << std::endl; + if (stopTime < std::numeric_limits::infinity()) { + idfx::cout << "Forcing: will be stopped at t=" << stopTime << " ." << std::endl; + } + switch(forcingType) { + case ForcingType::iso3D: + idfx::cout << "Forcing: 3D isotropic." << std::endl; + idfx::cout << "Forcing: kmin=" << kmin << " and kmax=" << kmax << " ." << std::endl; + idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; + if (haveSolenoidalForcing) idfx::cout << "Forcing: solenoidal." << std::endl; + break; + case ForcingType::iso2D: + idfx::cout << "Forcing: 2D isotropic with normal " << normal2DisoStr << "." << std::endl; + idfx::cout << "Forcing: kmin=" << kmin << " and kmax=" << kmax << " ." << std::endl; + idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; + if (haveSolenoidalForcing) idfx::cout << "Forcing: solenoidal." << std::endl; + break; + case ForcingType::ani3D: + idfx::cout << "Forcing: 3D anisotropic with normal " << normal3DaniStr << " and " << normal3DaniBasisStr << " basis." << std::endl; + idfx::cout << "Forcing: kmin=" << kmin << " and kmax=" << kmax << " ." << std::endl; + idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; + if (haveSolenoidalForcing) idfx::cout << "Forcing: solenoidal." << std::endl; + break; + case ForcingType::vsh: + idfx::cout << "Forcing: vector spherical harmonics." << std::endl; + idfx::cout << "Forcing: ellmin=" << ellmin << " and ellmax=" << ellmax << " ." << std::endl; + idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; + break; + case ForcingType::userDef: + idfx::cout << "Forcing: userdef." << std::endl; + break; + } + + if (machNumber >= ZERO_F) { + idfx::cout << "Forcing: Mach number=" << machNumber << " ." << std::endl; + } else { + idfx::cout << "Forcing: epsilon=" << epsilon << " and tcorr=" << tcorr << " ." << std::endl; + } + +// if(skipGravity>1) { +// idfx::cout << "Gravity: gravity field will be updated every " << skipGravity +// << " cycles." << std::endl; +// } +} + +void Forcing::InitForcingParameters() { + idfx::pushRegion("Forcing::InitForcingParameters"); + + if (this->machNumber >= 0) { + real kf = HALF_F*(kmin+kmax); + #if HAVE_ENERGY + ComputeAverageSoundSpeed(); + #endif //ISOTHERMAL + this->epsilon = pow(this->machNumber*cs,3.)*kf/(2.*M_PI); + this->tcorr = 2.*M_PI/(this->machNumber*cs*kf); + } + for (int l=0; lhostMeans(l,dir) = ZERO_F; + this->hostTcorrs(l,dir) = tcorr; + this->hostEpsilons(l,dir) = epsilon; + } + } + Kokkos::deep_copy(this->means, this->hostMeans); + Kokkos::deep_copy(this->tcorrs, this->hostTcorrs); + Kokkos::deep_copy(this->epsilons, this->hostEpsilons); + this->oUprocesses.SetProcesses(this->means, this->tcorrs, this->epsilons); + + idfx::popRegion(); +} + +void Forcing::InitForcingModes() { + idfx::pushRegion("Forcing::InitForcingModes"); + + int normal3Dani = this->normal3Dani; +// IDEFIX_ERROR("DSTOP"); + IdefixArray1D normal3DaniBound = this->normal3DaniBound; + int normal3DaniBasis = this->normal3DaniBasis; + real kx0 = this->kx0; + real ky0 = this->ky0; + real kz0 = this->kz0; + real xbeg = this->xbeg; + real ybeg = this->ybeg; + real zbeg = this->zbeg; + real xend = this->xend; + real yend = this->yend; + real zend = this->zend; + EXPAND( + IdefixArray4D> forcingModesIdir = this->forcingModesIdir; , + IdefixArray4D> forcingModesJdir = this->forcingModesJdir; , + IdefixArray4D> forcingModesKdir = this->forcingModesKdir; ) + IdefixArray1D x1 = data->x[IDIR]; + IdefixArray1D x2 = data->x[JDIR]; + IdefixArray1D x3 = data->x[KDIR]; + IdefixArray2D k3Diso = this->k3Diso; + IdefixArray2D k2Diso = this->k2Diso; + IdefixArray2D k3Dani = this->k3Dani; + IdefixArray2D ellmVsh = this->ellmVsh; + Kokkos::complex unit_j(0.,1.); + int nForcingModes = this->nForcingModes; + ForcingType forcingType = this->forcingType; + idefix_for("Forcing::InitForcingModes", + 0, nForcingModes, + 0, data->np_tot[KDIR], + 0, data->np_tot[JDIR], + 0, data->np_tot[IDIR], + KOKKOS_LAMBDA(int l, int k, int j, int i) { + EXPAND( + forcingModesIdir(l,k,j,i) = ZERO_F; , + forcingModesJdir(l,k,j,i) = ZERO_F; , + forcingModesKdir(l,k,j,i) = ZERO_F; ) + if (forcingType == vsh) { + EXPAND( , + forcingModesJdir(l+nForcingModes,k,j,i) = ZERO_F; , + forcingModesKdir(l+nForcingModes,k,j,i) = ZERO_F; ) + } + }); + switch(forcingType) { + case ForcingType::iso3D: + idefix_for("iso3D", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int l, int k, int j, int i) { + real kx = k3Diso(l, IDIR); + real ky = k3Diso(l, JDIR); + real kz = k3Diso(l, KDIR); + real kdotx = kx*x1(i) + ky*x2(j) + kz*x3(k); + EXPAND( + forcingModesIdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesJdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesKdir(l,k,j,i) = exp(unit_j * kdotx); ) + }); + break; + case ForcingType::iso2D: + idefix_for("iso2D", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int l, int k, int j, int i) { + real kx = k2Diso(l, IDIR); + real ky = k2Diso(l, JDIR); + real kz = k2Diso(l, KDIR); + real kdotx = kx*x1(i) + ky*x2(j) + kz*x3(k); + EXPAND( + forcingModesIdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesJdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesKdir(l,k,j,i) = exp(unit_j * kdotx); ) + }); + break; + case ForcingType::ani3D: + idefix_for("ani3D", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int l, int k, int j, int i) { + real kx = k3Dani(l, IDIR); + real ky = k3Dani(l, JDIR); + real kz = k3Dani(l, KDIR); + int offx = (normal3Dani==IDIR) ? 0 : 1; + int offy = (normal3Dani==JDIR) ? 0 : 1; + int offz = (normal3Dani==KDIR) ? 0 : 1; + real kdotx = offx*kx*x1(i) + offy*ky*x2(j) + offz*kz*x3(k); + int oppx = (normal3Dani==IDIR) ? 1 : 0; + int oppy = (normal3Dani==JDIR) ? 1 : 0; + int oppz = (normal3Dani==KDIR) ? 1 : 0; + int order = 0; + order = (normal3Dani==IDIR) ? kx/kx0 : order; + order = (normal3Dani==JDIR) ? ky/ky0 : kz/kz0; + real rightx = oppx*x1(i) + oppy*x2(j) + oppz*x3(k); + real rightx0 = oppx*xbeg + oppy*ybeg + oppz*zbeg; + real rightx1 = oppx*xend + oppy*yend + oppz*zend; + switch(normal3DaniBasis) { + case NormalBasis::chebyshev: + for (int dir=IDIR; dir> Ylm_r = this->data->Ylm_r; + IdefixArray4D> Slm_th = this->data->Slm_th; + IdefixArray4D> Slm_phi = this->data->Slm_phi; + IdefixArray4D> Tlm_th = this->data->Tlm_th; + IdefixArray4D> Tlm_phi = this->data->Tlm_phi; + int nForcingModes = this->nForcingModes; + idefix_for("vsh", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int l, int k, int j, int i) { + int ell = ellmVsh(l, 0); + int m = ellmVsh(l, 1); + forcingModesIdir(l,k,j,i) = Ylm_r(ell,m,k,j); + forcingModesJdir(l,k,j,i) = Slm_th(ell,m,k,j); + forcingModesJdir(l+nForcingModes,k,j,i) = Tlm_th(ell,m,k,j); + forcingModesKdir(l,k,j,i) = Slm_phi(ell,m,k,j); + forcingModesKdir(l+nForcingModes,k,j,i) = Tlm_phi(ell,m,k,j); + }); + break; + #endif //VSH == YES +// case ForcingType::userDef: +// break; + } + idfx::popRegion(); +} + +// This function writes the normal basis in a txt file to later plot them with matplotlib +// Working in mono-domain and in the X1 direction only so far +void Forcing::WriteNormalBasis(std::string folder) { + IdefixArray1D x1 = data->x[IDIR]; + int order_max = kmax/kx0 + 1; + int order_min = kmin/kx0 - 1; + order_min = std::max(1, order_min); + real xbeg = this->xbeg; + real xend = this->xend; + IdefixArray1D normal3DaniBound = this->normal3DaniBound; + int normal3DaniBasis = this->normal3DaniBasis; + IdefixHostArray3D normalBasisHost("normalBasisHost", order_max, COMPONENTS, data->np_tot[IDIR]); + IdefixArray3D normalBasis("normalBasis", order_max, COMPONENTS, data->np_tot[IDIR]); + idefix_for("write", 0, order_max, 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int order, int i) { + switch(normal3DaniBasis) { + case NormalBasis::chebyshev: + for (int dir = IDIR; dir < COMPONENTS; dir++) { + int bound = normal3DaniBound(dir); + switch(bound) { + case NormalBoundType::bothHomDir: + normalBasis(order,dir,i) = K_cheby_fst_both_hom_dir(order, K_aff_11(x1(i), xbeg, xend)); + break; + case NormalBoundType::bothHomNeu: + normalBasis(order,dir,i) = K_cheby_fst_both_hom_neu(order, K_aff_11(x1(i), xbeg, xend)); + break; + } + } + break; + case NormalBasis::fourier: + for (int dir = IDIR; dir < COMPONENTS; dir++) { + int bound = normal3DaniBound(dir); + switch(bound) { + case NormalBoundType::bothHomDir: + normalBasis(order,dir,i) = K_sin(order, K_aff_02pi(x1(i), xbeg, xend)); + break; + case NormalBoundType::bothHomNeu: + normalBasis(order,dir,i) = K_cos(order, K_aff_02pi(x1(i), xbeg, xend)); + break; + } + } + break; + } + }); + IdefixHostArray1D x1host("x1host", data->np_tot[IDIR]); + Kokkos::deep_copy(normalBasisHost, normalBasis); + Kokkos::deep_copy(x1host, x1); + if(idfx::prank==0) { + int precision = 10; + int col_width = precision + 10; + std::string filename = folder + "/normalBasis.dat"; + std::ofstream file; + file.open(filename, std::ios::trunc); + file << std::setw(col_width) << "x"; + for (int dir=IDIR; dirnp_tot[IDIR]; i++) { + file << std::setw(col_width) << x1host(i); + for (int dir=IDIR; dir> forcingModesIdir = this->forcingModesIdir; , + IdefixArray4D> forcingModesJdir = this->forcingModesJdir; , + IdefixArray4D> forcingModesKdir = this->forcingModesKdir; ) + IdefixArray4D pristineForcingTerm = this->pristineForcingTerm; + IdefixArray2D> ouValues = this->oUprocesses.ouValues; + int nForcingModes = this->nForcingModes; + idefix_for("ComputePristineForcing", 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int k, int j, int i) { + Kokkos::complex forcingX1=0.; + Kokkos::complex forcingX2=0.; + Kokkos::complex forcingX3=0.; + for (int l=0; l= 2 + forcingX2 += ouValues(l,JDIR)*forcingModesJdir(l,k,j,i); + #if VSH == YES + //in this case (l,JDIR) -> (l,Slm) and (l,KDIR) -> (l,Tlm) + forcingX2 += ouValues(l,KDIR)*forcingModesJdir(l+nForcingModes,k,j,i); + #endif //VSH == YES + #if COMPONENTS == 3 + #if VSH == YES + //don't forget (l,JDIR) -> (l,Slm) and (l,KDIR) -> (l,Tlm) + forcingX3 += ouValues(l,JDIR)*forcingModesKdir(l,k,j,i); + forcingX3 += ouValues(l,KDIR)*forcingModesJdir(l+nForcingModes,k,j,i); + #else + forcingX3 += ouValues(l,KDIR)*forcingModesKdir(l,k,j,i); + #endif //VSH == YES + #endif //COMPONENTS == 3 + #endif //COMPONENTS >= 2 + } + pristineForcingTerm(IDIR,k,j,i) += forcingX1.real(); + pristineForcingTerm(JDIR,k,j,i) += forcingX2.real(); + pristineForcingTerm(KDIR,k,j,i) += forcingX3.real(); + }); + + idfx::popRegion(); +} + +// This function compute the solenoidal part of the forcing field +void Forcing::ComputeSolenoidalForcing(real dt) { + idfx::pushRegion("Forcing::ComputeSolenoidalForcing"); + + IdefixArray2D kiso = (this->forcingType == iso3D) ? this->k3Diso : this->k2Diso; + EXPAND( + IdefixArray4D> forcingModesIdir = this->forcingModesIdir; , + IdefixArray4D> forcingModesJdir = this->forcingModesJdir; , + IdefixArray4D> forcingModesKdir = this->forcingModesKdir; ) + IdefixArray4D pristineForcingTerm = this->pristineForcingTerm; + IdefixArray4D solenoidalForcingTerm = this->solenoidalForcingTerm; + + IdefixArray1D dx1 = data->dx[IDIR]; + IdefixArray1D dx2 = data->dx[JDIR]; + IdefixArray1D dx3 = data->dx[KDIR]; + + IdefixArray1D x1m = data->xl[IDIR]; + IdefixArray1D x2m = data->xl[JDIR]; + IdefixArray1D x1 = data->x[IDIR]; + IdefixArray1D x2 = data->x[JDIR]; + + IdefixArray1D sinx2 = data->sinx2; + + real kmean = HALF_F*(kmax + kmin); + idefix_for("ComputeSolenoidalForcing", 1, data->np_tot[KDIR] - 1, 1, data->np_tot[JDIR] - 1, 1, data->np_tot[IDIR] - 1, + KOKKOS_LAMBDA (int k, int j, int i) { + #if GEOMETRY == CARTESIAN + solenoidalForcingTerm(IDIR,k,j,i) = D_EXPAND( ZERO_F , + + 1/dx2(j) * (pristineForcingTerm(KDIR,k,j+1,i) - pristineForcingTerm(KDIR,k,j-1,i) ) , + - 1/dx3(k) * (pristineForcingTerm(JDIR,k+1,j,i) - pristineForcingTerm(JDIR,k-1,j,i) ) ); + #if DIMENSIONS >= 2 + solenoidalForcingTerm(JDIR,k,j,i) = D_EXPAND( - 1/dx1(i) * (pristineForcingTerm(KDIR,k,j,i+1) - pristineForcingTerm(KDIR,k,j,i-1) ) , + , + + 1/dx3(k) * (pristineForcingTerm(IDIR,k+1,j,i) - pristineForcingTerm(IDIR,k-1,j,i) ) ); + #endif + #if DIMENSIONS == 3 + solenoidalForcingTerm(KDIR,k,j,i) = 1/dx1(i) * (pristineForcingTerm(JDIR,k,j,i+1) - pristineForcingTerm(JDIR,k,j,i-1) ) + - 1/dx2(j) * (pristineForcingTerm(IDIR,k,j+1,i) - pristineForcingTerm(IDIR,k,j-1,i) ); + #endif + #endif + #if GEOMETRY == CYLINDRICAL + IDEFIX_ERROR("Not yet defined"); + #endif + #if GEOMETRY == POLAR + solenoidalForcingTerm(IDIR,k,j,i) = D_EXPAND( ZERO_F , + + 1/(x1(i)*dx2(j)) * (pristineForcingTerm(KDIR,k,j+1,i) - pristineForcingTerm(KDIR,k,j-1,i) ) , + - 1/dx3(k) * (pristineForcingTerm(JDIR,k+1,j,i) - pristineForcingTerm(JDIR,k-1,j,i) ) ); + + solenoidalForcingTerm(JDIR,k,j,i) = D_EXPAND( - 1/dx1(i) * (pristineForcingTerm(KDIR,k,j,i+1) - pristineForcingTerm(KDIR,k,j,i-1) ) , + , + + 1/dx3(k) * (pristineForcingTerm(IDIR,k+1,j,i) - pristineForcingTerm(IDIR,k-1,j,i) ) ); + + #if DIMENSIONS == 3 + solenoidalForcingTerm(KDIR,k,j,i) = 1/(x1(i)*dx1(i)) * (x1(i+1)*pristineForcingTerm(JDIR,k,j,i+1) - x1(i-1)*pristineForcingTerm(JDIR,k,j,i-1) ) + - 1/(x1(i)*dx2(j)) * (pristineForcingTerm(IDIR,k,j+1,i) - pristineForcingTerm(IDIR,k,j-1,i) ); + #endif + #endif + #if GEOMETRY == SPHERICAL + real Ax2 = fabs(sinx2(j)); +// // Regularisation along the axis +// if(FABS(Ax2)<1e-12) Ax2 = ONE_F; + solenoidalForcingTerm(IDIR,k,j,i) = D_EXPAND( ZERO_F , + + 1/(x1m(i)*Ax2) * (sinx2(j+1)*pristineForcingTerm(KDIR,k,j+1,i) + - sinx2(j-1)*pristineForcingTerm(KDIR,k,j-1,i) ) , + - 1/(x1(i)*Ax2*dx3(k)) * (pristineForcingTerm(JDIR,k+1,j,i) + - pristineForcingTerm(JDIR,k-1,j,i) ) ); + + solenoidalForcingTerm(JDIR,k,j,i) = D_EXPAND( - 1/(x1(i)*dx1(i)) * (x1(i+1)*pristineForcingTerm(KDIR,k,j,i+1) + - x1(i-1)*pristineForcingTerm(KDIR,k,j,i-1) ) , + , + + 1/(x1(i)*Ax2*dx3(k)) * (pristineForcingTerm(IDIR,k+1,j,i) + - pristineForcingTerm(IDIR,k-1,j,i) ) ); + + #if DIMENSIONS == 3 + solenoidalForcingTerm(KDIR,k,j,i) = 1/(x1(i)*dx1(i)) * (x1(i+1)*pristineForcingTerm(JDIR,k,j,i+1) - x1(i-1)*pristineForcingTerm(JDIR,k,j,i-1) ) + - 1/(x1(i)*dx2(j)) * (pristineForcingTerm(IDIR,k,j+1,i) - pristineForcingTerm(IDIR,k,j-1,i) ); + #endif + #endif + + solenoidalForcingTerm(IDIR,k,j,i) /= 2.*kmean; + solenoidalForcingTerm(JDIR,k,j,i) /= 2.*kmean; + solenoidalForcingTerm(KDIR,k,j,i) /= 2.*kmean; + }); + + idfx::popRegion(); +} + +//// This function compute the compressive part of the forcing field +//void Forcing::ComputeCompressiveForcing(real dt) { +// idfx::pushRegion("Forcing::ComputeCompressiveForcing"); +// +// ResetForcingTerms(); +// +// IdefixArray2D kiso = (this->forcingType == iso3D) ? this->k3Diso : this->k2Diso; +// IdefixArray4D> forcingModesIdir = this->forcingModesIdir; +// IdefixArray4D> forcingModesJdir = this->forcingModesJdir; +// IdefixArray4D> forcingModesKdir = this->forcingModesKdir; +// IdefixArray4D compressiveForcingTerm = this->compressiveForcingTerm; +// IdefixArray2D> ouValues = this->oUprocesses.ouValues; +// int nForcingModes = this->nForcingModes; +// Kokkos::complex unit_j(0.,1.); +// idefix_for("ComputeCompressiveForcing", 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], +// KOKKOS_LAMBDA (int k, int j, int i) { +// Kokkos::complex forcingX1 = 0.; +// Kokkos::complex forcingX2 = 0.; +// Kokkos::complex forcingX3 = 0.; +// real kx1, kx2, kx3; +// for (int l=0; l= 2 +// forcingX2 += unit_j*(ouValues(l,KDIR)*kx1 - ouValues(l,IDIR)*kx3)*forcingModesJdir(l,k,j,i); +// #if COMPONENTS == 3 +// forcingX3 += unit_j*(ouValues(l,IDIR)*kx2 - ouValues(l,JDIR)*kx1)*forcingModesKdir(l,k,j,i); +// #endif //COMPONENTS == 3 +// #endif //COMPONENTS >= 2 +// } +// compressiveForcingTerm(IDIR,k,j,i) += forcingX1.real(); +// compressiveForcingTerm(JDIR,k,j,i) += forcingX2.real(); +// compressiveForcingTerm(KDIR,k,j,i) += forcingX3.real(); +// }); +// +// idfx::popRegion(); +//} + +// Fill the forcing term with zeros +void Forcing::ResetForcingTerms() { + idfx::pushRegion("Forcing::ResetForcingTerms"); + IdefixArray4D forcingTerm = this->forcingTerm; + IdefixArray4D pristineForcingTerm = this->pristineForcingTerm; + IdefixArray4D solenoidalForcingTerm = this->solenoidalForcingTerm; +// IdefixArray4D compressiveForcingTerm = this->compressiveForcingTerm; + idefix_for("Forcing::ResetForcingTerms", + 0, data->np_tot[KDIR], + 0, data->np_tot[JDIR], + 0, data->np_tot[IDIR], + KOKKOS_LAMBDA(int k, int j, int i) { + forcingTerm(IDIR,k,j,i) = ZERO_F; + forcingTerm(JDIR,k,j,i) = ZERO_F; + forcingTerm(KDIR,k,j,i) = ZERO_F; + pristineForcingTerm(IDIR,k,j,i) = ZERO_F; + pristineForcingTerm(JDIR,k,j,i) = ZERO_F; + pristineForcingTerm(KDIR,k,j,i) = ZERO_F; + solenoidalForcingTerm(IDIR,k,j,i) = ZERO_F; + solenoidalForcingTerm(JDIR,k,j,i) = ZERO_F; + solenoidalForcingTerm(KDIR,k,j,i) = ZERO_F; +// compressiveForcingTerm(IDIR,k,j,i) = ZERO_F; +// compressiveForcingTerm(JDIR,k,j,i) = ZERO_F; +// compressiveForcingTerm(KDIR,k,j,i) = ZERO_F; + }); + idfx::popRegion(); +} + +void Forcing::ComputeAverageSoundSpeed() { + idfx::pushRegion("Forcing::ComputeAverageSoundSpeed"); + this->cs = 1.; + + DataBlockHost d(*this->data); + d.SyncFromDevice(); + IdefixHostArray1D x1=d.x[IDIR]; + IdefixHostArray1D x2=d.x[JDIR]; + IdefixHostArray1D x3=d.x[KDIR]; + IdefixHostArray4D Vc=d.Vc; + + #if GEOMETRY == CARTESIAN || GEOMETRY == SPHERICAL + real currentCs = ZERO_F; + real currentVol = ZERO_F; + #if GEOMETRY == CARTESIAN + for(int i = d.beg[IDIR]; i < d.end[IDIR] ; i++) { + for(int j = d.beg[JDIR]; j < d.end[JDIR] ; j++) { + for(int k = d.beg[KDIR]; k < d.end[KDIR] ; k++) { + currentCs += sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); + currentVol += d.dV(k,j,i); + } + } + } + #endif //GEOMETRY == CARTESIAN + #if GEOMETRY == SPHERICAL +// real r2, sint; + for(int i = d.beg[IDIR]; i < d.end[IDIR] ; i++) { +// r2 = x1(i)*x1(i); + for(int j = d.beg[JDIR]; j < d.end[JDIR] ; j++) { +// sint = SIN(d.x[JDIR](j)); + for(int k = d.beg[KDIR]; k < d.end[KDIR] ; k++) { +// currentCs += r2*sint*sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); + currentCs += d.dV(k,j,i)*sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); + currentVol += d.dV(k,j,i); + } + } + } + #endif //GEOMETRY == SPHERICAL + #ifdef WITH_MPI + MPI_Allreduce(MPI_IN_PLACE, ¤tCs, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + MPI_Allreduce(MPI_IN_PLACE, ¤tVol, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + #endif + this->cs = currentCs/currentVol; + #endif //GEOMETRY == CARTESIAN || GEOMETRY == SPHERICAL + idfx::popRegion(); +} + diff --git a/src/forcing/forcing.hpp b/src/forcing/forcing.hpp new file mode 100644 index 000000000..5b7059883 --- /dev/null +++ b/src/forcing/forcing.hpp @@ -0,0 +1,120 @@ +// *********************************************************************************** +// Idefix MHD astrophysical code +// Copyright(C) Geoffroy R. J. Lesur +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#ifndef FORCING_FORCING_HPP_ +#define FORCING_FORCING_HPP_ + +#include "idefix.hpp" +#include "input.hpp" +#include "OrnsteinUhlenbeckProcess.hpp" + +enum ForcingType {iso3D, iso2D, ani3D, vsh, userDef}; +enum NormalBoundType {bothFree, rightHomDir, bothHomDir, bothHomNeu}; +enum NormalBasis {chebyshev, legendre, fourier}; + +class DataBlock; + +class Forcing { + public: + Forcing(Input&, DataBlock*); + + bool stillHaveForcing; + real stopTime; + + void InitForcingParameters(); ///< init forcing parameters + + void InitForcingModes(); ///< init forcing modes given its type + + void ComputeForcing(real); ///< compute the required forcing field at current time t + + void ComputePristineForcing(real);///< compute the pristine forcing field at current time t + + void ComputeSolenoidalForcing(real); ///< compute the solenoidal part of the forcing field at current time t + +// void ComputeCompressiveForcing(real); ///< compute the compressive part of the forcing field at current time t + + void ResetForcingTerms(); ///< fill the forcing field with zeros. + + void ComputeAverageSoundSpeed(); ///< compute the initial average sound speed within the solution domain + + void ShowConfig(); ///< Show the forcing configuration + + // Forcing modes +// IdefixArray4D> forcingModes; + EXPAND( + IdefixArray4D> forcingModesIdir; , + IdefixArray4D> forcingModesJdir; , + IdefixArray4D> forcingModesKdir; ) +// IdefixHostArray2D modeNamesHost; + std::vector> modeNames; + // Forcing terms + IdefixArray4D forcingTerm; + IdefixArray4D pristineForcingTerm; + IdefixArray4D solenoidalForcingTerm; +// IdefixArray4D compressiveForcingTerm; + OrnsteinUhlenbeckProcesses oUprocesses; + + void WriteNormalBasis(std::string); ///< Write the functions of the normal basis in txt files + + int write; + private: + + DataBlock *data; + int seed; + std::string folder; + + int nForcingModes; + real machNumber; + real cs; + real tcorr; + real epsilon; + IdefixArray2D tcorrs; + IdefixArray2D means; + IdefixArray2D epsilons; + IdefixHostArray2D hostTcorrs; + IdefixHostArray2D hostMeans; + IdefixHostArray2D hostEpsilons; + + ForcingType forcingType; + int normal2Diso; + std::string normal2DisoStr; + int normal3Dani; + std::string normal3DaniStr; + IdefixHostArray1D normal3DaniBoundHost; + IdefixArray1D normal3DaniBound; + std::string normal3DaniBoundStr; + NormalBasis normal3DaniBasis; + std::string normal3DaniBasisStr; + int haveSolenoidalForcing; + + IdefixArray2D k3Diso; + IdefixHostArray2D k3DisoHost; + IdefixArray2D k2Diso; + IdefixHostArray2D k2DisoHost; + IdefixArray2D k3Dani; + IdefixHostArray2D k3DaniHost; + IdefixArray2D ellmVsh; + IdefixHostArray2D ellmVshHost; + real kmin; + real kmax; + real kx0; + real ky0; + real kz0; + real xbeg; + real ybeg; + real zbeg; + real xend; + real yend; + real zend; + int ellmin; + int ellmax; + int mmin; + int mmax; +// #endif //GEOMETRY == SPHERICAL +}; + +#endif // FORCING_FORCING_HPP_ From db91b070e94a6864338b801c1d1fdbbfa39ae36d Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Thu, 27 Nov 2025 10:42:17 +0100 Subject: [PATCH 02/18] clean up forcing (to be tested) --- src/forcing/forcing.cpp | 548 ++-------------------------------------- src/forcing/forcing.hpp | 8 +- 2 files changed, 20 insertions(+), 536 deletions(-) diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp index 032b1e995..c3effd04d 100644 --- a/src/forcing/forcing.cpp +++ b/src/forcing/forcing.cpp @@ -79,7 +79,7 @@ Forcing::Forcing(Input &input, DataBlock *datain) { this->folder = input.GetOrSet("Output","folder",0,"output"); this->stillHaveForcing = true; - this->stopTime = input.GetOrSet("Forcing","stoptime",0,std::numeric_limits::infinity()); + this->stopTime = input.GetOrSet("Forcing","stoptime",0,std::numeric_limits::infinity()); this->nForcingModes = 0; @@ -108,17 +108,14 @@ Forcing::Forcing(Input &input, DataBlock *datain) { IDEFIX_ERROR("You cannot have 3D isotropic forcing in another geometry than Cartesian"); #endif //GEOMETRY != CARTESIAN #if COMPONENTS < 3 or DIMENSIONS < 3 -std::cout << COMPONENTS << DIMENSIONS << std::endl; IDEFIX_ERROR("You cannot have 3D isotropic forcing with less than 3 components and dimensions."); #endif //COMPONENTS < 3 or DIMENSIONS < 3 // if () IDEFIX_ERROR("You should not have 3D isotropic forcing with other boundary conditions than fully periodic."); - #if GEOMETRY == SPHERICAL - IDEFIX_ERROR("Comparing radial with angular wavenumbers is somewhat shady."); - #endif //GEOMETRY == SPHERICAL + this->kmin = input.Get("Forcing","iso3D", 0); this->kmax = input.Get("Forcing","iso3D", 1); - std::vector> k3Disovec; + std::vector> k3Disovec; int nxmax = kmax/kx0 + 1; int nymax = kmax/ky0 + 1; @@ -181,7 +178,7 @@ std::cout << COMPONENTS << DIMENSIONS << std::endl; this->kmin = input.Get("Forcing","iso2D", 1); this->kmax = input.Get("Forcing","iso2D", 2); - std::vector> k2Disovec; + std::vector> k2Disovec; kx0 = (this->normal2Diso==IDIR) ? ZERO_F : kx0; ky0 = (this->normal2Diso==JDIR) ? ZERO_F : ky0; @@ -238,194 +235,11 @@ std::cout << COMPONENTS << DIMENSIONS << std::endl; data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) } - else if (input.CheckEntry("Forcing", "ani3D")>=0) { - #if COMPONENTS < 3 or DIMENSIONS < 3 - IDEFIX_ERROR("You cannot have 3D anisotropic forcing with less than 3 components and dimensions."); - #endif //COMPONENTS < 3 or DIMENSIONS < 3 - this->forcingType = ani3D; - this->normal3DaniStr = input.Get("Forcing","ani3D", 0); - if (this->normal3DaniStr == "IDIR") this->normal3Dani = IDIR; - else if (this->normal3DaniStr == "JDIR") this->normal3Dani = JDIR; - else if (this->normal3DaniStr == "KDIR") this->normal3Dani = KDIR; - else IDEFIX_ERROR("The normal component for 3D anisotropic forcing cannot not be something else than IDIR, JDIR or KDIR"); -// this->normal3DaniBoundStr = input.Get("Forcing","ani3D", 1); -// if (this->normal3DaniBoundStr == "bothfree") this->normal3DaniBound = bothFree; -// else if (this->normal3DaniBoundStr == "righthomdir") this->normal3DaniBound = rightHomDir; -// else if (this->normal3DaniBoundStr == "bothhomdir") this->normal3DaniBound = bothHomDir; -// else if (this->normal3DaniBoundStr == "bothhomneu") this->normal3DaniBound = bothHomNeu; -// else IDEFIX_ERROR("The boundaries for the normal component of the forcing can only be bothfree, righthomdir, bothhomdir or bothhomneu for now."); -// this->normal3DaniBasisStr = input.Get("Forcing","ani3D", 2); -// if (this->normal3DaniBasisStr == "chebyshev") this->normal3DaniBasis = chebyshev; -//// else if (this->normal3DaniBasisStr == "legendre") this->normal3DaniBasis = legendre; -// else if (this->normal3DaniBasisStr == "fourier") this->normal3DaniBasis = fourier; -// else IDEFIX_ERROR("The basis for the normal component of the forcing can only be chebyshev and fourier for now (legendre coming soon)."); -//// if (this->normal3DaniBasis = chebyshev and this->normal3DaniBound = bothHomNeu) IDEFIX_ERROR("Cannot have a chebyshev basis which has both homogeneous Neumann boundaries."); -//// else if (normal3DaniBasis = fourier and normal3DaniBound = rightHomDir) IDEFIX_ERROR("Cannot have a fourier basis which has only right homogeneous Dirichlet boundary."); - - this->normal3DaniBasisStr = input.Get("Forcing","ani3D", 1); - if (this->normal3DaniBasisStr == "chebyshev") this->normal3DaniBasis = chebyshev; -// else if (this->normal3DaniBasisStr == "legendre") this->normal3DaniBasis = legendre; - else if (this->normal3DaniBasisStr == "fourier") this->normal3DaniBasis = fourier; - else IDEFIX_ERROR("The basis for the normal component of the forcing can only be chebyshev and fourier for now (legendre coming soon)."); - - std::vector vecNormal3DaniBound; - std::string dirbegStr = "X" + std::to_string(this->normal3Dani + 1) + "-beg"; - std::string direndStr = "X" + std::to_string(this->normal3Dani + 1) + "-end"; - if (input.Get("Boundary",dirbegStr, 0) != input.Get("Boundary",direndStr, 0)) { - IDEFIX_ERROR("Chebyshev basis with different BCs at the two sides are not yet implemented"); - } else if (input.Get("Boundary",dirbegStr, 0) == "reflective") { - (this->normal3Dani == IDIR) ? vecNormal3DaniBound.push_back(bothHomDir) : vecNormal3DaniBound.push_back(bothHomNeu); - (this->normal3Dani == JDIR) ? vecNormal3DaniBound.push_back(bothHomDir) : vecNormal3DaniBound.push_back(bothHomNeu); - (this->normal3Dani == KDIR) ? vecNormal3DaniBound.push_back(bothHomDir) : vecNormal3DaniBound.push_back(bothHomNeu); - } else if (input.Get("Boundary",dirbegStr, 0) == "outflow") { - vecNormal3DaniBound.push_back(bothHomNeu); - vecNormal3DaniBound.push_back(bothHomNeu); - vecNormal3DaniBound.push_back(bothHomNeu); - } else if (input.Get("Boundary",dirbegStr, 0) == "userdef") { - for (int dir = IDIR; dir("Boundary",userdefDirbegStr, 0) != input.Get("Boundary",userdefDirendStr, 0)) { - IDEFIX_ERROR("Chebyshev basis with different BCs at the two sides are not yet implemented"); - } else if (input.Get("Boundary",userdefDirbegStr, 0) == "dirichletZero") { - vecNormal3DaniBound.push_back(bothHomDir); - } else if (input.Get("Boundary",userdefDirbegStr, 0) == "neumann") { - vecNormal3DaniBound.push_back(bothHomNeu); - } else { - IDEFIX_ERROR("userdef BCs not recognised, they are needed choose the suitable forcing basis."); - } - } - } else if (input.Get("Boundary",dirbegStr, 0) == "periodic") { - IDEFIX_ERROR("periodic BCs recognised, you should use 3D isotropic forcing in this direction."); - } else { - IDEFIX_ERROR("BCs not recognised, they are needed choose the suitable forcing basis."); - } - normal3DaniBoundHost = IdefixHostArray1D("normal3DaniBoundHost", COMPONENTS); - normal3DaniBound = IdefixArray1D("normal3DaniBound", COMPONENTS); - for (int l=IDIR; lkmin = input.Get("Forcing","ani3D", 2); - this->kmax = input.Get("Forcing","ani3D", 3); - - if (input.GetOrSet("Forcing","ani3D", 4, "n") == "write") WriteNormalBasis(folder); - - std::vector> k3Danivec; - - int nxmax = kmax/kx0 + 1; - int nymax = kmax/ky0 + 1; - int nzmax = kmax/kz0 + 1; - int xsign, ysign, zsign; - if (this->normal3Dani==IDIR) { - xsign = 1; - ysign = 1; - zsign = -1; - } else if (this->normal3Dani==JDIR) { - xsign = 1; - ysign = 1; - zsign = -1; - } else if (this->normal3Dani==KDIR) { - xsign = 1; - ysign = -1; - zsign = 1; - } else { - IDEFIX_ERROR("Forcing: normal direction not known"); - } - for (int nx=1; nx= kmin*kmin and k_2 <= kmax*kmax) { - nForcingModes ++; - k3Danivec.push_back({kx, ky, kz}); - modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz)}); - nForcingModes ++; - k3Danivec.push_back({xsign*kx, ysign*ky, zsign*kz}); - modeNames.push_back({"I" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "J" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "K" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz)}); - } - } - } - } - k3DaniHost = IdefixHostArray2D("k3DaniHost", nForcingModes, 3); - k3Dani = IdefixArray2D("k3Dani", nForcingModes, 3); - for (int l=0; lforcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , - this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , - this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) - } - - else if (input.CheckEntry("Forcing", "vsh")>=0) { - this->forcingType = vsh; - #if GEOMETRY != SPHERICAL - IDEFIX_ERROR("You cannot have vsh forcing in another geometry than spherical."); - #endif //GEOMETRY != SPHERICAL - #if VSH == NO - IDEFIX_ERROR("You cannot have vsh forcing without the VSH module."); - #endif //VSH == NO -// if () IDEFIX_ERROR("You cannot have vsh forcing without the full sphere."); - this->ellmin = input.Get("Forcing","vsh", 0); - this->ellmax = input.Get("Forcing","vsh", 1); - this->mmin = input.GetOrSet("Forcing","vsh", 2, 0); - this->mmax = input.GetOrSet("Forcing","vsh", 3, this->ellmax); - - std::vector> ellmVshvec; - for (int ell=ellmin; ellnForcingModes++; - ellmVshvec.push_back({ell,m}); - modeNames.push_back({"Y" + std::to_string(ell) + std::to_string(m), "S" + std::to_string(ell) + std::to_string(m), "T" + std::to_string(ell) + std::to_string(m)}); - } - } - ellmVshHost = IdefixHostArray2D("ellmVshHost", nForcingModes, 2); - ellmVsh = IdefixArray2D("ellmVsh", nForcingModes, 2); - for (int l=0; lforcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , - // WARNING, vsh case needs a special treatment since the forcing modes between - // the theta and phi directions are coupled to each other... - this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", 2*nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , - this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", 2*nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) - } - -// else { this->haveUserDef = true;} - else { this->forcingType = userDef;} // TO BE CODED THOUGH if (input.CheckEntry("Forcing", "solenoidal")>=0) { #if GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL IDEFIX_ERROR("Cannot have solenoidal forcing in polar in cylindrical geometry."); #endif //GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL - if (this->forcingType == vsh) IDEFIX_ERROR("Cannot have solenoidal forcing with vsh forcing. Select yourself the toroidal vector spherical harmonics in this case."); - else if (this->forcingType == userDef) IDEFIX_ERROR("Cannot have solenoidal forcing with userdef forcing."); else this->haveSolenoidalForcing = true; } @@ -481,20 +295,6 @@ void Forcing::ShowConfig() { idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; if (haveSolenoidalForcing) idfx::cout << "Forcing: solenoidal." << std::endl; break; - case ForcingType::ani3D: - idfx::cout << "Forcing: 3D anisotropic with normal " << normal3DaniStr << " and " << normal3DaniBasisStr << " basis." << std::endl; - idfx::cout << "Forcing: kmin=" << kmin << " and kmax=" << kmax << " ." << std::endl; - idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; - if (haveSolenoidalForcing) idfx::cout << "Forcing: solenoidal." << std::endl; - break; - case ForcingType::vsh: - idfx::cout << "Forcing: vector spherical harmonics." << std::endl; - idfx::cout << "Forcing: ellmin=" << ellmin << " and ellmax=" << ellmax << " ." << std::endl; - idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; - break; - case ForcingType::userDef: - idfx::cout << "Forcing: userdef." << std::endl; - break; } if (machNumber >= ZERO_F) { @@ -503,10 +303,7 @@ void Forcing::ShowConfig() { idfx::cout << "Forcing: epsilon=" << epsilon << " and tcorr=" << tcorr << " ." << std::endl; } -// if(skipGravity>1) { -// idfx::cout << "Gravity: gravity field will be updated every " << skipGravity -// << " cycles." << std::endl; -// } + } void Forcing::InitForcingParameters() { @@ -514,7 +311,7 @@ void Forcing::InitForcingParameters() { if (this->machNumber >= 0) { real kf = HALF_F*(kmin+kmax); - #if HAVE_ENERGY + #if HAVE_ENERGY ComputeAverageSoundSpeed(); #endif //ISOTHERMAL this->epsilon = pow(this->machNumber*cs,3.)*kf/(2.*M_PI); @@ -560,8 +357,6 @@ void Forcing::InitForcingModes() { IdefixArray1D x3 = data->x[KDIR]; IdefixArray2D k3Diso = this->k3Diso; IdefixArray2D k2Diso = this->k2Diso; - IdefixArray2D k3Dani = this->k3Dani; - IdefixArray2D ellmVsh = this->ellmVsh; Kokkos::complex unit_j(0.,1.); int nForcingModes = this->nForcingModes; ForcingType forcingType = this->forcingType; @@ -575,11 +370,6 @@ void Forcing::InitForcingModes() { forcingModesIdir(l,k,j,i) = ZERO_F; , forcingModesJdir(l,k,j,i) = ZERO_F; , forcingModesKdir(l,k,j,i) = ZERO_F; ) - if (forcingType == vsh) { - EXPAND( , - forcingModesJdir(l+nForcingModes,k,j,i) = ZERO_F; , - forcingModesKdir(l+nForcingModes,k,j,i) = ZERO_F; ) - } }); switch(forcingType) { case ForcingType::iso3D: @@ -608,172 +398,19 @@ void Forcing::InitForcingModes() { forcingModesKdir(l,k,j,i) = exp(unit_j * kdotx); ) }); break; - case ForcingType::ani3D: - idefix_for("ani3D", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], - KOKKOS_LAMBDA (int l, int k, int j, int i) { - real kx = k3Dani(l, IDIR); - real ky = k3Dani(l, JDIR); - real kz = k3Dani(l, KDIR); - int offx = (normal3Dani==IDIR) ? 0 : 1; - int offy = (normal3Dani==JDIR) ? 0 : 1; - int offz = (normal3Dani==KDIR) ? 0 : 1; - real kdotx = offx*kx*x1(i) + offy*ky*x2(j) + offz*kz*x3(k); - int oppx = (normal3Dani==IDIR) ? 1 : 0; - int oppy = (normal3Dani==JDIR) ? 1 : 0; - int oppz = (normal3Dani==KDIR) ? 1 : 0; - int order = 0; - order = (normal3Dani==IDIR) ? kx/kx0 : order; - order = (normal3Dani==JDIR) ? ky/ky0 : kz/kz0; - real rightx = oppx*x1(i) + oppy*x2(j) + oppz*x3(k); - real rightx0 = oppx*xbeg + oppy*ybeg + oppz*zbeg; - real rightx1 = oppx*xend + oppy*yend + oppz*zend; - switch(normal3DaniBasis) { - case NormalBasis::chebyshev: - for (int dir=IDIR; dir> Ylm_r = this->data->Ylm_r; - IdefixArray4D> Slm_th = this->data->Slm_th; - IdefixArray4D> Slm_phi = this->data->Slm_phi; - IdefixArray4D> Tlm_th = this->data->Tlm_th; - IdefixArray4D> Tlm_phi = this->data->Tlm_phi; - int nForcingModes = this->nForcingModes; - idefix_for("vsh", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], - KOKKOS_LAMBDA (int l, int k, int j, int i) { - int ell = ellmVsh(l, 0); - int m = ellmVsh(l, 1); - forcingModesIdir(l,k,j,i) = Ylm_r(ell,m,k,j); - forcingModesJdir(l,k,j,i) = Slm_th(ell,m,k,j); - forcingModesJdir(l+nForcingModes,k,j,i) = Tlm_th(ell,m,k,j); - forcingModesKdir(l,k,j,i) = Slm_phi(ell,m,k,j); - forcingModesKdir(l+nForcingModes,k,j,i) = Tlm_phi(ell,m,k,j); - }); - break; - #endif //VSH == YES + // case ForcingType::userDef: // break; } idfx::popRegion(); } -// This function writes the normal basis in a txt file to later plot them with matplotlib -// Working in mono-domain and in the X1 direction only so far -void Forcing::WriteNormalBasis(std::string folder) { - IdefixArray1D x1 = data->x[IDIR]; - int order_max = kmax/kx0 + 1; - int order_min = kmin/kx0 - 1; - order_min = std::max(1, order_min); - real xbeg = this->xbeg; - real xend = this->xend; - IdefixArray1D normal3DaniBound = this->normal3DaniBound; - int normal3DaniBasis = this->normal3DaniBasis; - IdefixHostArray3D normalBasisHost("normalBasisHost", order_max, COMPONENTS, data->np_tot[IDIR]); - IdefixArray3D normalBasis("normalBasis", order_max, COMPONENTS, data->np_tot[IDIR]); - idefix_for("write", 0, order_max, 0, data->np_tot[IDIR], - KOKKOS_LAMBDA (int order, int i) { - switch(normal3DaniBasis) { - case NormalBasis::chebyshev: - for (int dir = IDIR; dir < COMPONENTS; dir++) { - int bound = normal3DaniBound(dir); - switch(bound) { - case NormalBoundType::bothHomDir: - normalBasis(order,dir,i) = K_cheby_fst_both_hom_dir(order, K_aff_11(x1(i), xbeg, xend)); - break; - case NormalBoundType::bothHomNeu: - normalBasis(order,dir,i) = K_cheby_fst_both_hom_neu(order, K_aff_11(x1(i), xbeg, xend)); - break; - } - } - break; - case NormalBasis::fourier: - for (int dir = IDIR; dir < COMPONENTS; dir++) { - int bound = normal3DaniBound(dir); - switch(bound) { - case NormalBoundType::bothHomDir: - normalBasis(order,dir,i) = K_sin(order, K_aff_02pi(x1(i), xbeg, xend)); - break; - case NormalBoundType::bothHomNeu: - normalBasis(order,dir,i) = K_cos(order, K_aff_02pi(x1(i), xbeg, xend)); - break; - } - } - break; - } - }); - IdefixHostArray1D x1host("x1host", data->np_tot[IDIR]); - Kokkos::deep_copy(normalBasisHost, normalBasis); - Kokkos::deep_copy(x1host, x1); - if(idfx::prank==0) { - int precision = 10; - int col_width = precision + 10; - std::string filename = folder + "/normalBasis.dat"; - std::ofstream file; - file.open(filename, std::ios::trunc); - file << std::setw(col_width) << "x"; - for (int dir=IDIR; dirnp_tot[IDIR]; i++) { - file << std::setw(col_width) << x1host(i); - for (int dir=IDIR; dir> forcingModesIdir = this->forcingModesIdir; , IdefixArray4D> forcingModesJdir = this->forcingModesJdir; , @@ -804,23 +441,9 @@ void Forcing::ComputePristineForcing(real dt) { Kokkos::complex forcingX2=0.; Kokkos::complex forcingX3=0.; for (int l=0; l= 2 - forcingX2 += ouValues(l,JDIR)*forcingModesJdir(l,k,j,i); - #if VSH == YES - //in this case (l,JDIR) -> (l,Slm) and (l,KDIR) -> (l,Tlm) - forcingX2 += ouValues(l,KDIR)*forcingModesJdir(l+nForcingModes,k,j,i); - #endif //VSH == YES - #if COMPONENTS == 3 - #if VSH == YES - //don't forget (l,JDIR) -> (l,Slm) and (l,KDIR) -> (l,Tlm) - forcingX3 += ouValues(l,JDIR)*forcingModesKdir(l,k,j,i); - forcingX3 += ouValues(l,KDIR)*forcingModesJdir(l+nForcingModes,k,j,i); - #else - forcingX3 += ouValues(l,KDIR)*forcingModesKdir(l,k,j,i); - #endif //VSH == YES - #endif //COMPONENTS == 3 - #endif //COMPONENTS >= 2 + EXPAND( forcingX1 += ouValues(l,IDIR)*forcingModesIdir(l,k,j,i); , + forcingX2 += ouValues(l,JDIR)*forcingModesJdir(l,k,j,i); , + forcingX3 += ouValues(l,KDIR)*forcingModesKdir(l,k,j,i); ) } pristineForcingTerm(IDIR,k,j,i) += forcingX1.real(); pristineForcingTerm(JDIR,k,j,i) += forcingX2.real(); @@ -833,12 +456,12 @@ void Forcing::ComputePristineForcing(real dt) { // This function compute the solenoidal part of the forcing field void Forcing::ComputeSolenoidalForcing(real dt) { idfx::pushRegion("Forcing::ComputeSolenoidalForcing"); - + IdefixArray2D kiso = (this->forcingType == iso3D) ? this->k3Diso : this->k2Diso; - EXPAND( - IdefixArray4D> forcingModesIdir = this->forcingModesIdir; , - IdefixArray4D> forcingModesJdir = this->forcingModesJdir; , - IdefixArray4D> forcingModesKdir = this->forcingModesKdir; ) + EXPAND( IdefixArray4D> forcingModesIdir = this->forcingModesIdir; , + IdefixArray4D> forcingModesJdir = this->forcingModesJdir; , + IdefixArray4D> forcingModesKdir = this->forcingModesKdir; ) + IdefixArray4D pristineForcingTerm = this->pristineForcingTerm; IdefixArray4D solenoidalForcingTerm = this->solenoidalForcingTerm; @@ -870,44 +493,6 @@ void Forcing::ComputeSolenoidalForcing(real dt) { - 1/dx2(j) * (pristineForcingTerm(IDIR,k,j+1,i) - pristineForcingTerm(IDIR,k,j-1,i) ); #endif #endif - #if GEOMETRY == CYLINDRICAL - IDEFIX_ERROR("Not yet defined"); - #endif - #if GEOMETRY == POLAR - solenoidalForcingTerm(IDIR,k,j,i) = D_EXPAND( ZERO_F , - + 1/(x1(i)*dx2(j)) * (pristineForcingTerm(KDIR,k,j+1,i) - pristineForcingTerm(KDIR,k,j-1,i) ) , - - 1/dx3(k) * (pristineForcingTerm(JDIR,k+1,j,i) - pristineForcingTerm(JDIR,k-1,j,i) ) ); - - solenoidalForcingTerm(JDIR,k,j,i) = D_EXPAND( - 1/dx1(i) * (pristineForcingTerm(KDIR,k,j,i+1) - pristineForcingTerm(KDIR,k,j,i-1) ) , - , - + 1/dx3(k) * (pristineForcingTerm(IDIR,k+1,j,i) - pristineForcingTerm(IDIR,k-1,j,i) ) ); - - #if DIMENSIONS == 3 - solenoidalForcingTerm(KDIR,k,j,i) = 1/(x1(i)*dx1(i)) * (x1(i+1)*pristineForcingTerm(JDIR,k,j,i+1) - x1(i-1)*pristineForcingTerm(JDIR,k,j,i-1) ) - - 1/(x1(i)*dx2(j)) * (pristineForcingTerm(IDIR,k,j+1,i) - pristineForcingTerm(IDIR,k,j-1,i) ); - #endif - #endif - #if GEOMETRY == SPHERICAL - real Ax2 = fabs(sinx2(j)); -// // Regularisation along the axis -// if(FABS(Ax2)<1e-12) Ax2 = ONE_F; - solenoidalForcingTerm(IDIR,k,j,i) = D_EXPAND( ZERO_F , - + 1/(x1m(i)*Ax2) * (sinx2(j+1)*pristineForcingTerm(KDIR,k,j+1,i) - - sinx2(j-1)*pristineForcingTerm(KDIR,k,j-1,i) ) , - - 1/(x1(i)*Ax2*dx3(k)) * (pristineForcingTerm(JDIR,k+1,j,i) - - pristineForcingTerm(JDIR,k-1,j,i) ) ); - - solenoidalForcingTerm(JDIR,k,j,i) = D_EXPAND( - 1/(x1(i)*dx1(i)) * (x1(i+1)*pristineForcingTerm(KDIR,k,j,i+1) - - x1(i-1)*pristineForcingTerm(KDIR,k,j,i-1) ) , - , - + 1/(x1(i)*Ax2*dx3(k)) * (pristineForcingTerm(IDIR,k+1,j,i) - - pristineForcingTerm(IDIR,k-1,j,i) ) ); - - #if DIMENSIONS == 3 - solenoidalForcingTerm(KDIR,k,j,i) = 1/(x1(i)*dx1(i)) * (x1(i+1)*pristineForcingTerm(JDIR,k,j,i+1) - x1(i-1)*pristineForcingTerm(JDIR,k,j,i-1) ) - - 1/(x1(i)*dx2(j)) * (pristineForcingTerm(IDIR,k,j+1,i) - pristineForcingTerm(IDIR,k,j-1,i) ); - #endif - #endif solenoidalForcingTerm(IDIR,k,j,i) /= 2.*kmean; solenoidalForcingTerm(JDIR,k,j,i) /= 2.*kmean; @@ -917,52 +502,6 @@ void Forcing::ComputeSolenoidalForcing(real dt) { idfx::popRegion(); } -//// This function compute the compressive part of the forcing field -//void Forcing::ComputeCompressiveForcing(real dt) { -// idfx::pushRegion("Forcing::ComputeCompressiveForcing"); -// -// ResetForcingTerms(); -// -// IdefixArray2D kiso = (this->forcingType == iso3D) ? this->k3Diso : this->k2Diso; -// IdefixArray4D> forcingModesIdir = this->forcingModesIdir; -// IdefixArray4D> forcingModesJdir = this->forcingModesJdir; -// IdefixArray4D> forcingModesKdir = this->forcingModesKdir; -// IdefixArray4D compressiveForcingTerm = this->compressiveForcingTerm; -// IdefixArray2D> ouValues = this->oUprocesses.ouValues; -// int nForcingModes = this->nForcingModes; -// Kokkos::complex unit_j(0.,1.); -// idefix_for("ComputeCompressiveForcing", 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], -// KOKKOS_LAMBDA (int k, int j, int i) { -// Kokkos::complex forcingX1 = 0.; -// Kokkos::complex forcingX2 = 0.; -// Kokkos::complex forcingX3 = 0.; -// real kx1, kx2, kx3; -// for (int l=0; l= 2 -// forcingX2 += unit_j*(ouValues(l,KDIR)*kx1 - ouValues(l,IDIR)*kx3)*forcingModesJdir(l,k,j,i); -// #if COMPONENTS == 3 -// forcingX3 += unit_j*(ouValues(l,IDIR)*kx2 - ouValues(l,JDIR)*kx1)*forcingModesKdir(l,k,j,i); -// #endif //COMPONENTS == 3 -// #endif //COMPONENTS >= 2 -// } -// compressiveForcingTerm(IDIR,k,j,i) += forcingX1.real(); -// compressiveForcingTerm(JDIR,k,j,i) += forcingX2.real(); -// compressiveForcingTerm(KDIR,k,j,i) += forcingX3.real(); -// }); -// -// idfx::popRegion(); -//} - // Fill the forcing term with zeros void Forcing::ResetForcingTerms() { idfx::pushRegion("Forcing::ResetForcingTerms"); @@ -984,57 +523,6 @@ void Forcing::ResetForcingTerms() { solenoidalForcingTerm(IDIR,k,j,i) = ZERO_F; solenoidalForcingTerm(JDIR,k,j,i) = ZERO_F; solenoidalForcingTerm(KDIR,k,j,i) = ZERO_F; -// compressiveForcingTerm(IDIR,k,j,i) = ZERO_F; -// compressiveForcingTerm(JDIR,k,j,i) = ZERO_F; -// compressiveForcingTerm(KDIR,k,j,i) = ZERO_F; }); idfx::popRegion(); } - -void Forcing::ComputeAverageSoundSpeed() { - idfx::pushRegion("Forcing::ComputeAverageSoundSpeed"); - this->cs = 1.; - - DataBlockHost d(*this->data); - d.SyncFromDevice(); - IdefixHostArray1D x1=d.x[IDIR]; - IdefixHostArray1D x2=d.x[JDIR]; - IdefixHostArray1D x3=d.x[KDIR]; - IdefixHostArray4D Vc=d.Vc; - - #if GEOMETRY == CARTESIAN || GEOMETRY == SPHERICAL - real currentCs = ZERO_F; - real currentVol = ZERO_F; - #if GEOMETRY == CARTESIAN - for(int i = d.beg[IDIR]; i < d.end[IDIR] ; i++) { - for(int j = d.beg[JDIR]; j < d.end[JDIR] ; j++) { - for(int k = d.beg[KDIR]; k < d.end[KDIR] ; k++) { - currentCs += sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); - currentVol += d.dV(k,j,i); - } - } - } - #endif //GEOMETRY == CARTESIAN - #if GEOMETRY == SPHERICAL -// real r2, sint; - for(int i = d.beg[IDIR]; i < d.end[IDIR] ; i++) { -// r2 = x1(i)*x1(i); - for(int j = d.beg[JDIR]; j < d.end[JDIR] ; j++) { -// sint = SIN(d.x[JDIR](j)); - for(int k = d.beg[KDIR]; k < d.end[KDIR] ; k++) { -// currentCs += r2*sint*sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); - currentCs += d.dV(k,j,i)*sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); - currentVol += d.dV(k,j,i); - } - } - } - #endif //GEOMETRY == SPHERICAL - #ifdef WITH_MPI - MPI_Allreduce(MPI_IN_PLACE, ¤tCs, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); - MPI_Allreduce(MPI_IN_PLACE, ¤tVol, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); - #endif - this->cs = currentCs/currentVol; - #endif //GEOMETRY == CARTESIAN || GEOMETRY == SPHERICAL - idfx::popRegion(); -} - diff --git a/src/forcing/forcing.hpp b/src/forcing/forcing.hpp index 5b7059883..8015ab3a9 100644 --- a/src/forcing/forcing.hpp +++ b/src/forcing/forcing.hpp @@ -12,9 +12,7 @@ #include "input.hpp" #include "OrnsteinUhlenbeckProcess.hpp" -enum ForcingType {iso3D, iso2D, ani3D, vsh, userDef}; -enum NormalBoundType {bothFree, rightHomDir, bothHomDir, bothHomNeu}; -enum NormalBasis {chebyshev, legendre, fourier}; +enum ForcingType {iso3D, iso2D}; class DataBlock; @@ -30,7 +28,7 @@ class Forcing { void InitForcingModes(); ///< init forcing modes given its type void ComputeForcing(real); ///< compute the required forcing field at current time t - + void ComputePristineForcing(real);///< compute the pristine forcing field at current time t void ComputeSolenoidalForcing(real); ///< compute the solenoidal part of the forcing field at current time t @@ -39,8 +37,6 @@ class Forcing { void ResetForcingTerms(); ///< fill the forcing field with zeros. - void ComputeAverageSoundSpeed(); ///< compute the initial average sound speed within the solution domain - void ShowConfig(); ///< Show the forcing configuration // Forcing modes From a831fc10da5e8b6f0bef74af93dbf487f9d9b6cd Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 14 Jan 2026 06:32:09 +0100 Subject: [PATCH 03/18] simplify reset code --- src/forcing/forcing.cpp | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp index c3effd04d..38e689f70 100644 --- a/src/forcing/forcing.cpp +++ b/src/forcing/forcing.cpp @@ -505,24 +505,10 @@ void Forcing::ComputeSolenoidalForcing(real dt) { // Fill the forcing term with zeros void Forcing::ResetForcingTerms() { idfx::pushRegion("Forcing::ResetForcingTerms"); - IdefixArray4D forcingTerm = this->forcingTerm; - IdefixArray4D pristineForcingTerm = this->pristineForcingTerm; - IdefixArray4D solenoidalForcingTerm = this->solenoidalForcingTerm; -// IdefixArray4D compressiveForcingTerm = this->compressiveForcingTerm; - idefix_for("Forcing::ResetForcingTerms", - 0, data->np_tot[KDIR], - 0, data->np_tot[JDIR], - 0, data->np_tot[IDIR], - KOKKOS_LAMBDA(int k, int j, int i) { - forcingTerm(IDIR,k,j,i) = ZERO_F; - forcingTerm(JDIR,k,j,i) = ZERO_F; - forcingTerm(KDIR,k,j,i) = ZERO_F; - pristineForcingTerm(IDIR,k,j,i) = ZERO_F; - pristineForcingTerm(JDIR,k,j,i) = ZERO_F; - pristineForcingTerm(KDIR,k,j,i) = ZERO_F; - solenoidalForcingTerm(IDIR,k,j,i) = ZERO_F; - solenoidalForcingTerm(JDIR,k,j,i) = ZERO_F; - solenoidalForcingTerm(KDIR,k,j,i) = ZERO_F; - }); + + Kokkos::deep_copy(this->forcingTerm,0); + Kokkos::deep_copy(this->pristineForcingTerm,0); + Kokkos::deep_copy(this->solenoidalForcingTerm,0); + idfx::popRegion(); } From a1efe4cfc8ea8cd5fba52b32f19397c573dd006a Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 14 Jan 2026 08:37:27 +0100 Subject: [PATCH 04/18] include forcing in time integration using J. Kempf's implementation --- src/dataBlock/dataBlock.cpp | 8 ++ src/dataBlock/dataBlock.hpp | 6 ++ src/dataBlock/evolveStage.cpp | 9 ++ src/fluid/evolveStage.hpp | 157 ++++++++++++++++++++++++++++++++++ src/main.cpp | 2 + src/timeIntegrator.cpp | 24 ++++++ 6 files changed, 206 insertions(+) diff --git a/src/dataBlock/dataBlock.cpp b/src/dataBlock/dataBlock.cpp index 2877a8346..9df9cf127 100644 --- a/src/dataBlock/dataBlock.cpp +++ b/src/dataBlock/dataBlock.cpp @@ -12,6 +12,7 @@ #include "dataBlock.hpp" #include "fluid.hpp" #include "gravity.hpp" +#include "forcing.hpp" #include "planetarySystem.hpp" #include "vtk.hpp" #include "dump.hpp" @@ -144,6 +145,12 @@ DataBlock::DataBlock(Grid &grid, Input &input) { this->haveGravity = true; } + // Initialise forcing if needed + if(input.CheckBlock("Forcing")) { + this->forcing = std::make_unique(input, this); + this->haveForcing = true; + } + // Initialise dust grains if needed if(input.CheckBlock("Dust")) { haveDust = true; @@ -318,6 +325,7 @@ void DataBlock::ShowConfig() { << std::endl; if(haveUserStepLast) idfx::cout << "DataBlock: User's last step has been enrolled." << std::endl; + if(haveForcing) forcing->ShowConfig(); if(haveDust) { idfx::cout << "DataBlock: evolving " << dust.size() << " dust species." << std::endl; // Only show the config the first dust specie diff --git a/src/dataBlock/dataBlock.hpp b/src/dataBlock/dataBlock.hpp index 89b745fa5..d06948c17 100644 --- a/src/dataBlock/dataBlock.hpp +++ b/src/dataBlock/dataBlock.hpp @@ -19,6 +19,7 @@ #include "gridHost.hpp" #include "planetarySystem.hpp" #include "gravity.hpp" +#include "forcing.hpp" #include "stateContainer.hpp" ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -141,6 +142,7 @@ class DataBlock { void EvolveStage(); ///< Evolve this DataBlock by dt void EvolveRKLStage(); ///< Evolve this DataBlock by dt for terms impacted by RKL + void EvolveForcing(real, real); ///< Evolve this DataBlock by dt for the forcing term void SetBoundaries(); ///< Enforce boundary conditions to this datablock void ConsToPrim(); ///< Convert conservative to primitive variables void PrimToCons(); ///< Convert primitive to conservative variables @@ -163,6 +165,10 @@ class DataBlock { bool haveGravity{false}; std::unique_ptr gravity; + // Do we have Forcing ? + bool haveForcing{false}; + std::unique_ptr forcing; + // User step functions (before or after the main integrator step) void LaunchUserStepFirst(); ///< perform user-defined step before main integration step void LaunchUserStepLast(); ///< Perform user-defined step after main integration step diff --git a/src/dataBlock/evolveStage.cpp b/src/dataBlock/evolveStage.cpp index c97c9f713..c22807820 100644 --- a/src/dataBlock/evolveStage.cpp +++ b/src/dataBlock/evolveStage.cpp @@ -41,3 +41,12 @@ void DataBlock::EvolveRKLStage() { } idfx::popRegion(); } + + +void DataBlock::EvolveForcing(real t, real dt) { + idfx::pushRegion("DataBlock::EvolveForcing"); +// if(haveForcing) { + hydro->EvolveForcing(t, dt); +// } + idfx::popRegion(); +} diff --git a/src/fluid/evolveStage.hpp b/src/fluid/evolveStage.hpp index 31dae5b7d..ab251d0ab 100644 --- a/src/fluid/evolveStage.hpp +++ b/src/fluid/evolveStage.hpp @@ -10,6 +10,8 @@ #include "fluid.hpp" #include "riemannSolver.hpp" +#include "forcing.hpp" + template template void Fluid::LoopDir(const real t, const real dt) { @@ -88,4 +90,159 @@ void Fluid::EvolveStage(const real t, const real dt) { idfx::popRegion(); } + + +// Evolve one step forward in time of forcing +template +void Fluid::EvolveForcing(const real t, const real dt) { + idfx::pushRegion("Fluid::EvolveForcing"); + + data->forcing->ComputeForcing(dt); + data->forcing->oUprocesses.WriteTimestep(t, dt); + if (data->forcing->write) { + data->forcing->oUprocesses.WriteProcessesValues(t); + data->forcing->oUprocesses.WriteNormalValues(t); + } + + if (data->forcing->stillHaveForcing and t > data->forcing->stopTime) data->forcing->stillHaveForcing = false; + + // Loop on all of the directions + LoopForcingDir(t,dt); + + idfx::popRegion(); +} + +template +template +void Fluid::LoopForcingDir(const real t, const real dt) { + + CalcForcingRHS(t,dt); + + // Recursive: do next dimension + if constexpr (dir+1 < DIMENSIONS) LoopForcingDir(t, dt); +} + +template +struct Fluid_CalcForcingFunctor { + //***************************************************************** + // Functor constructor + //***************************************************************** + explicit Fluid_CalcForcingFunctor (Fluid *hydro, real dt) { + Uc = hydro->Uc; + Vc = hydro->Vc; + Flux = hydro->FluxRiemann; + dV = hydro->data->dV; + forcingTerm = hydro->data->forcing->forcingTerm; + + rt = hydro->data->rt; + dmu = hydro->data->dmu; + dx = hydro->data->dx[dir]; + dx2 = hydro->data->dx[JDIR]; +// invDt = hydro->InvDt; +// cMax = hydro->cMax; +// dMax = hydro->dMax; + this->dt = dt; + } + //***************************************************************** + // Functor Variables + //***************************************************************** + IdefixArray4D Uc; + IdefixArray4D Vc; + IdefixArray3D dV; + IdefixArray4D Flux; + IdefixArray4D forcingTerm; + + IdefixArray1D rt; + IdefixArray1D dmu; + IdefixArray1D dx; + IdefixArray1D dx2; + real dt; + + //***************************************************************** + // Functor Operator + //***************************************************************** + KOKKOS_INLINE_FUNCTION void operator() (const int k, const int j, const int i) const { + const int ioffset = (dir==IDIR) ? 1 : 0; + const int joffset = (dir==JDIR) ? 1 : 0; + const int koffset = (dir==KDIR) ? 1 : 0; + + real dtdV=dt / dV(k,j,i); + real rhs[Phys::nvar]; + + #pragma unroll + for(int nv = 0 ; nv < Phys::nvar ; nv++) { + rhs[nv] = ZERO_F; + } + + + // elmentary length for gradient computations + const int ig = ioffset*i + joffset*j + koffset*k; + real dl = dx(ig); + #if GEOMETRY == POLAR + if constexpr (dir==JDIR) + dl = dl*x1(i); + + #elif GEOMETRY == SPHERICAL + if constexpr(dir==JDIR) + dl = dl*rt(i); + else if constexpr(dir==KDIR) + dl = dl*rt(i)*dmu(j)/dx2(j); + #endif + + + rhs[MX1+dir] = dt * Vc(RHO,k,j,i) * forcingTerm(dir,k,j,i); + if constexpr(Phys::pressure) { + // rho * v . f + rhs[ENG] += dt * Vc(RHO,k,j,i) * Vc(VX1+dir,k,j,i) * forcingTerm(dir,k,j,i); + } // Pressure + + // Particular cases if we do not sweep all of the components + #if DIMENSIONS == 1 && COMPONENTS > 1 + EXPAND( , + rhs[MX2] += dt * Vc(RHO,k,j,i) * forcingTerm(JDIR,k,j,i); , + rhs[MX3] += dt * Vc(RHO,k,j,i) * forcingTerm(KDIR,k,j,i); ) + if constexpr(Phys::pressure) { + rhs[ENG] += dt * (EXPAND( ZERO_F , + + Vc(RHO,k,j,i) * Vc(VX2,k,j,i) * forcingTerm(JDIR,k,j,i) , + + Vc(HO,k,j,i) * Vc(VX3,k,j,i) * forcingTerm(KDIR,k,j,i) )); + } + #endif + #if DIMENSIONS == 2 && COMPONENTS == 3 + // Only add this term once! + if constexpr (dir==JDIR) { + rhs[MX3] += dt * Vc(RHO,k,j,i) * forcingTerm(KDIR,k,j,i); + if constexpr(Phys::pressure) { + rhs[ENG] += dt * Vc(RHO,k,j,i) * Vc(VX3,k,j,i) * forcingTerm(KDIR,k,j,i); + } + } + #endif + + #pragma unroll + for(int nv = 0 ; nv < Phys::nvar ; nv++) { + Uc(nv,k,j,i) = Uc(nv,k,j,i) + rhs[nv]; + } + + // WARNING DO SOMETHING FOR THE TIMESTEP DT? + + } +}; + +template +template +void Fluid::CalcForcingRHS(const real t, const real dt) { + idfx::pushRegion("Fluid::CalcForcing"); + + auto calcForcing = Fluid_CalcForcingFunctor(this,dt); + ///////////////////////////////////////////////////////////////////////////// + // Final conserved quantity budget from fluxes divergence + ///////////////////////////////////////////////////////////////////////////// + idefix_for("CalcForcing", + data->beg[KDIR],data->end[KDIR], + data->beg[JDIR],data->end[JDIR], + data->beg[IDIR],data->end[IDIR], + calcForcing); + + idfx::popRegion(); +} + #endif //FLUID_EVOLVESTAGE_HPP_ diff --git a/src/main.cpp b/src/main.cpp index 7b2c00c85..768f8eb27 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -146,6 +146,7 @@ int main( int argc, char* argv[] ) { data.DeriveVectorPotential(); idfx::popRegion(); #endif + if(data.haveForcing) data.forcing->InitForcingParameters(); } idfx::cout << "Main: Restarting from dump file." << std::endl; bool restartSuccess = output.RestartFromDump(data,input.restartFileNumber); @@ -175,6 +176,7 @@ int main( int argc, char* argv[] ) { data.SetBoundaries(); data.Validate(); output.CheckForWrites(data); + if(data.haveForcing) data.forcing->InitForcingParameters(); } /////////////////////////////// diff --git a/src/timeIntegrator.cpp b/src/timeIntegrator.cpp index 6ffb6acfb..548ae5947 100644 --- a/src/timeIntegrator.cpp +++ b/src/timeIntegrator.cpp @@ -81,6 +81,21 @@ TimeIntegrator::TimeIntegrator(Input & input, DataBlock & data) { data.states["begin"].AllocateAs(data.states["current"]); } + if(data.haveForcing) { + DataBlockHost d(data); + d.SyncToDevice(); + data.forcing->InitForcingModes(); + if (!input.restartRequested) { + data.forcing->oUprocesses.ResetProcessesValues(); // so that we get the excited modes even if we don't write + data.forcing->oUprocesses.ResetTimestep(); + if(data.forcing->write) { + data.forcing->oUprocesses.ResetNormalValues(); + } + } + if (input.restartRequested) data.forcing->oUprocesses.AdvanceProcessesValues(); +// if (input.restartRequested) data.forcing->oUprocesses.AdvanceProcessesValues(data.tabDt); + } + idfx::popRegion(); } @@ -359,6 +374,15 @@ void TimeIntegrator::Cycle(DataBlock &data) { } #endif + if(data.haveForcing) { + if(data.forcing->stillHaveForcing) { + data.EvolveForcing(data.t, data.dt); + + // Back to using Vc + data.ConsToPrim(); + } + } + if(haveRKL && (ncycles%2)==0) { // Runge-Kutta-Legendre cycle data.EvolveRKLStage(); } From be954909b1e104587a593ee8c86385cc51dd292e Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 14 Jan 2026 08:47:21 +0100 Subject: [PATCH 05/18] cmake update --- CMakeLists.txt | 1 + src/CMakeLists.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index a7c856ddd..10e414bfa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -226,6 +226,7 @@ target_include_directories(idefix PUBLIC src/fluid/RiemannSolver/MHDsolvers src/fluid/RiemannSolver/Dustsolvers src/fluid/tracer + src/forcing src/output src/rkl src/gravity diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 08dd93c61..fe97b81ac 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,6 +1,7 @@ add_subdirectory(fluid) add_subdirectory(dataBlock) +add_subdirectory(forcing) add_subdirectory(output) add_subdirectory(rkl) add_subdirectory(gravity) From 792120a5f64868c9df9ddc912851dc3d4a85d20d Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 14 Jan 2026 09:01:30 +0100 Subject: [PATCH 06/18] compiles --- src/fluid/fluid.hpp | 10 ++++++++++ src/forcing/forcing.cpp | 24 ++++++++---------------- src/forcing/forcing.hpp | 7 ------- 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/src/fluid/fluid.hpp b/src/fluid/fluid.hpp index 44cace6bf..8cabb7082 100644 --- a/src/fluid/fluid.hpp +++ b/src/fluid/fluid.hpp @@ -18,6 +18,7 @@ #include "eos.hpp" #include "thermalDiffusion.hpp" #include "bragThermalDiffusion.hpp" +#include "forcing.hpp" #include "selfGravity.hpp" #include "vtk.hpp" #include "dump.hpp" @@ -59,6 +60,7 @@ class Fluid { template void CalcParabolicFlux(const real); template void AddNonIdealMHDFlux(const real); template void CalcRightHandSide(real, real ); + template void CalcForcingRHS(real, real ); void CalcCurrent(); void AddSourceTerms(real, real ); void CoarsenFlow(IdefixArray4D&); @@ -66,6 +68,7 @@ class Fluid { real CheckDivB(); void EvolveStage(const real, const real); void ResetStage(); + void EvolveForcing(const real, const real); void ShowConfig(); IdefixArray4D GetFlux() {return this->FluxRiemann;} int CheckNan(); @@ -215,6 +218,9 @@ class Fluid { template friend struct Fluid_CalcRHSFunctor; + template + friend struct Fluid_CalcForcingFunctor; + template friend struct ShockFlattening_FindShockFunctor; @@ -244,6 +250,10 @@ class Fluid { // Loop on dimensions template void LoopDir(const real, const real); + + // Loop on dimensions for forcing + template + void LoopForcingDir(const real, const real); }; #include "physics.hpp" diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp index 38e689f70..b69eb9a7b 100644 --- a/src/forcing/forcing.cpp +++ b/src/forcing/forcing.cpp @@ -240,7 +240,7 @@ Forcing::Forcing(Input &input, DataBlock *datain) { #if GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL IDEFIX_ERROR("Cannot have solenoidal forcing in polar in cylindrical geometry."); #endif //GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL - else this->haveSolenoidalForcing = true; + this->haveSolenoidalForcing = true; } // Allocate required arrays @@ -335,10 +335,6 @@ void Forcing::InitForcingParameters() { void Forcing::InitForcingModes() { idfx::pushRegion("Forcing::InitForcingModes"); - int normal3Dani = this->normal3Dani; -// IDEFIX_ERROR("DSTOP"); - IdefixArray1D normal3DaniBound = this->normal3DaniBound; - int normal3DaniBasis = this->normal3DaniBasis; real kx0 = this->kx0; real ky0 = this->ky0; real kz0 = this->kz0; @@ -360,17 +356,13 @@ void Forcing::InitForcingModes() { Kokkos::complex unit_j(0.,1.); int nForcingModes = this->nForcingModes; ForcingType forcingType = this->forcingType; - idefix_for("Forcing::InitForcingModes", - 0, nForcingModes, - 0, data->np_tot[KDIR], - 0, data->np_tot[JDIR], - 0, data->np_tot[IDIR], - KOKKOS_LAMBDA(int l, int k, int j, int i) { - EXPAND( - forcingModesIdir(l,k,j,i) = ZERO_F; , - forcingModesJdir(l,k,j,i) = ZERO_F; , - forcingModesKdir(l,k,j,i) = ZERO_F; ) - }); + + // todo(GL): not sure this is needed + Kokkos::deep_copy(forcingModesIdir,0); + Kokkos::deep_copy(forcingModesJdir,0); + Kokkos::deep_copy(forcingModesKdir,0); + + switch(forcingType) { case ForcingType::iso3D: idefix_for("iso3D", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], diff --git a/src/forcing/forcing.hpp b/src/forcing/forcing.hpp index 8015ab3a9..0da45272d 100644 --- a/src/forcing/forcing.hpp +++ b/src/forcing/forcing.hpp @@ -78,13 +78,6 @@ class Forcing { ForcingType forcingType; int normal2Diso; std::string normal2DisoStr; - int normal3Dani; - std::string normal3DaniStr; - IdefixHostArray1D normal3DaniBoundHost; - IdefixArray1D normal3DaniBound; - std::string normal3DaniBoundStr; - NormalBasis normal3DaniBasis; - std::string normal3DaniBasisStr; int haveSolenoidalForcing; IdefixArray2D k3Diso; From 90b99a7aa4e86e8c4769e63eaf10374e078384e7 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 14 Jan 2026 19:01:38 +0100 Subject: [PATCH 07/18] add test for forcing --- reference | 2 +- test/HD/forcing/definitions.hpp | 4 +++ test/HD/forcing/idefix.ini | 35 +++++++++++++++++++++++++++ test/HD/forcing/setup.cpp | 40 ++++++++++++++++++++++++++++++ test/HD/forcing/testme.py | 43 +++++++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 1 deletion(-) create mode 100644 test/HD/forcing/definitions.hpp create mode 100644 test/HD/forcing/idefix.ini create mode 100644 test/HD/forcing/setup.cpp create mode 100755 test/HD/forcing/testme.py diff --git a/reference b/reference index 1028989b3..8d47f1a77 160000 --- a/reference +++ b/reference @@ -1 +1 @@ -Subproject commit 1028989b3847200da9b54ed74df0d5c0b0d13045 +Subproject commit 8d47f1a77cc66e7dddc95ea213e930cac8c1064b diff --git a/test/HD/forcing/definitions.hpp b/test/HD/forcing/definitions.hpp new file mode 100644 index 000000000..486a4ea34 --- /dev/null +++ b/test/HD/forcing/definitions.hpp @@ -0,0 +1,4 @@ +#define COMPONENTS 3 +#define DIMENSIONS 3 +#define ISOTHERMAL +#define GEOMETRY CARTESIAN diff --git a/test/HD/forcing/idefix.ini b/test/HD/forcing/idefix.ini new file mode 100644 index 000000000..e8520553c --- /dev/null +++ b/test/HD/forcing/idefix.ini @@ -0,0 +1,35 @@ +[Grid] +X1-grid 1 -0.5 32 u 0.5 +X2-grid 1 -0.5 32 u 0.5 +X3-grid 1 -0.5 32 u 0.5 + +[TimeIntegrator] +CFL 0.9 +tstop 1.0 +first_dt 1.e-4 +nstages 2 + +[Hydro] +solver hllc +csiso constant 1.0 + +[Forcing] +iso3D 1.0 20.0 # kmin, kmax, +mach 3 # presumably mach number? +t_corr 1.0 # used when Mach not set +epsilon 0.1 # idem + +[Setup] +Nothing nothing + +[Boundary] +X1-beg periodic +X1-end periodic +X2-beg periodic +X2-end periodic +X3-beg periodic +X3-end periodic + +[Output] +vtk 1.0 +dmp 1.0 diff --git a/test/HD/forcing/setup.cpp b/test/HD/forcing/setup.cpp new file mode 100644 index 000000000..7fa1ed717 --- /dev/null +++ b/test/HD/forcing/setup.cpp @@ -0,0 +1,40 @@ +#include "idefix.hpp" +#include "setup.hpp" + + +// Initialisation routine. Can be used to allocate +// Arrays or variables which are used later on +Setup::Setup(Input &input, Grid &grid, DataBlock &data, Output &output) { +} + +// This routine initialize the flow +// Note that data is on the device. +// One can therefore define locally +// a datahost and sync it, if needed +void Setup::InitFlow(DataBlock &data) { + // Create a host copy + DataBlockHost d(data); + + for(int k = 0; k < d.np_tot[KDIR] ; k++) { + for(int j = 0; j < d.np_tot[JDIR] ; j++) { + for(int i = 0; i < d.np_tot[IDIR] ; i++) { + real x = d.x[IDIR](i); + real y = d.x[JDIR](j); + real z = d.x[KDIR](k); + + // Uniform density, no velocity + d.Vc(RHO,k,j,i) = 1.0; + d.Vc(VX1,k,j,i) = 0.0; + d.Vc(VX2,k,j,i) = 0.0; + d.Vc(VX3,k,j,i) = 0.0; + + #ifndef ISOTHERMAL + d.Vc(PRS,k,j,i) = 1.0; + #endif + } + } + } + // Send it all, if needed + d.SyncToDevice(); +} + diff --git a/test/HD/forcing/testme.py b/test/HD/forcing/testme.py new file mode 100755 index 000000000..39df4395e --- /dev/null +++ b/test/HD/forcing/testme.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 + +""" + +@author: glesur +""" +import os +import sys +sys.path.append(os.getenv("IDEFIX_DIR")) + +import pytools.idfx_test as tst + +def testMe(test): + test.configure() + test.compile() + inifiles=["idefix.ini"] + + for ini in inifiles: + test.run(inputFile=ini) + if test.init and not test.mpi: + test.makeReference(filename="dump.0001.dmp") + test.standardTest() + test.nonRegressionTest(filename="dump.0001.dmp") + + +test=tst.idfxTest() +if not test.dec: + test.dec=['2','2','2'] + +if not test.all: + if(test.check): + test.checkOnly(filename="dump.0001.dmp") + else: + testMe(test) +else: + test.noplot = True + test.single=False + test.reconstruction=2 + test.mpi=False + testMe(test) + + test.mpi=True + testMe(test) From a675551616fbabe30ec1ef56c27858073997051d Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 14 Jan 2026 19:41:43 +0100 Subject: [PATCH 08/18] reorganise EvolveForcing routines --- src/dataBlock/evolveStage.cpp | 9 ++ src/fluid/evolveStage.hpp | 157 ++++------------------------------ src/fluid/fluid.hpp | 8 -- 3 files changed, 26 insertions(+), 148 deletions(-) diff --git a/src/dataBlock/evolveStage.cpp b/src/dataBlock/evolveStage.cpp index c22807820..a82f4fda5 100644 --- a/src/dataBlock/evolveStage.cpp +++ b/src/dataBlock/evolveStage.cpp @@ -45,6 +45,15 @@ void DataBlock::EvolveRKLStage() { void DataBlock::EvolveForcing(real t, real dt) { idfx::pushRegion("DataBlock::EvolveForcing"); + forcing->ComputeForcing(dt); + forcing->oUprocesses.WriteTimestep(t, dt); + if (forcing->write) { + forcing->oUprocesses.WriteProcessesValues(t); + forcing->oUprocesses.WriteNormalValues(t); + } + + if (forcing->stillHaveForcing and t > forcing->stopTime) forcing->stillHaveForcing = false; + // if(haveForcing) { hydro->EvolveForcing(t, dt); // } diff --git a/src/fluid/evolveStage.hpp b/src/fluid/evolveStage.hpp index ab251d0ab..8a043b1ea 100644 --- a/src/fluid/evolveStage.hpp +++ b/src/fluid/evolveStage.hpp @@ -97,150 +97,27 @@ template void Fluid::EvolveForcing(const real t, const real dt) { idfx::pushRegion("Fluid::EvolveForcing"); - data->forcing->ComputeForcing(dt); - data->forcing->oUprocesses.WriteTimestep(t, dt); - if (data->forcing->write) { - data->forcing->oUprocesses.WriteProcessesValues(t); - data->forcing->oUprocesses.WriteNormalValues(t); - } - - if (data->forcing->stillHaveForcing and t > data->forcing->stopTime) data->forcing->stillHaveForcing = false; - - // Loop on all of the directions - LoopForcingDir(t,dt); - - idfx::popRegion(); -} - -template -template -void Fluid::LoopForcingDir(const real t, const real dt) { - - CalcForcingRHS(t,dt); - - // Recursive: do next dimension - if constexpr (dir+1 < DIMENSIONS) LoopForcingDir(t, dt); -} - -template -struct Fluid_CalcForcingFunctor { - //***************************************************************** - // Functor constructor - //***************************************************************** - explicit Fluid_CalcForcingFunctor (Fluid *hydro, real dt) { - Uc = hydro->Uc; - Vc = hydro->Vc; - Flux = hydro->FluxRiemann; - dV = hydro->data->dV; - forcingTerm = hydro->data->forcing->forcingTerm; - - rt = hydro->data->rt; - dmu = hydro->data->dmu; - dx = hydro->data->dx[dir]; - dx2 = hydro->data->dx[JDIR]; -// invDt = hydro->InvDt; -// cMax = hydro->cMax; -// dMax = hydro->dMax; - this->dt = dt; - } - //***************************************************************** - // Functor Variables - //***************************************************************** - IdefixArray4D Uc; - IdefixArray4D Vc; - IdefixArray3D dV; - IdefixArray4D Flux; - IdefixArray4D forcingTerm; - - IdefixArray1D rt; - IdefixArray1D dmu; - IdefixArray1D dx; - IdefixArray1D dx2; - real dt; - - //***************************************************************** - // Functor Operator - //***************************************************************** - KOKKOS_INLINE_FUNCTION void operator() (const int k, const int j, const int i) const { - const int ioffset = (dir==IDIR) ? 1 : 0; - const int joffset = (dir==JDIR) ? 1 : 0; - const int koffset = (dir==KDIR) ? 1 : 0; - - real dtdV=dt / dV(k,j,i); - real rhs[Phys::nvar]; - - #pragma unroll - for(int nv = 0 ; nv < Phys::nvar ; nv++) { - rhs[nv] = ZERO_F; - } + auto Uc = this->Uc; + auto Vc = this->Vc; + auto forcingTerm = this->data->forcing->forcingTerm; - - // elmentary length for gradient computations - const int ig = ioffset*i + joffset*j + koffset*k; - real dl = dx(ig); - #if GEOMETRY == POLAR - if constexpr (dir==JDIR) - dl = dl*x1(i); - - #elif GEOMETRY == SPHERICAL - if constexpr(dir==JDIR) - dl = dl*rt(i); - else if constexpr(dir==KDIR) - dl = dl*rt(i)*dmu(j)/dx2(j); - #endif - - - rhs[MX1+dir] = dt * Vc(RHO,k,j,i) * forcingTerm(dir,k,j,i); - if constexpr(Phys::pressure) { - // rho * v . f - rhs[ENG] += dt * Vc(RHO,k,j,i) * Vc(VX1+dir,k,j,i) * forcingTerm(dir,k,j,i); - } // Pressure - - // Particular cases if we do not sweep all of the components - #if DIMENSIONS == 1 && COMPONENTS > 1 - EXPAND( , - rhs[MX2] += dt * Vc(RHO,k,j,i) * forcingTerm(JDIR,k,j,i); , - rhs[MX3] += dt * Vc(RHO,k,j,i) * forcingTerm(KDIR,k,j,i); ) - if constexpr(Phys::pressure) { - rhs[ENG] += dt * (EXPAND( ZERO_F , - + Vc(RHO,k,j,i) * Vc(VX2,k,j,i) * forcingTerm(JDIR,k,j,i) , - + Vc(HO,k,j,i) * Vc(VX3,k,j,i) * forcingTerm(KDIR,k,j,i) )); - } - #endif - #if DIMENSIONS == 2 && COMPONENTS == 3 - // Only add this term once! - if constexpr (dir==JDIR) { - rhs[MX3] += dt * Vc(RHO,k,j,i) * forcingTerm(KDIR,k,j,i); - if constexpr(Phys::pressure) { - rhs[ENG] += dt * Vc(RHO,k,j,i) * Vc(VX3,k,j,i) * forcingTerm(KDIR,k,j,i); - } - } - #endif - - #pragma unroll - for(int nv = 0 ; nv < Phys::nvar ; nv++) { - Uc(nv,k,j,i) = Uc(nv,k,j,i) + rhs[nv]; - } - - // WARNING DO SOMETHING FOR THE TIMESTEP DT? - - } -}; - -template -template -void Fluid::CalcForcingRHS(const real t, const real dt) { - idfx::pushRegion("Fluid::CalcForcing"); - - auto calcForcing = Fluid_CalcForcingFunctor(this,dt); - ///////////////////////////////////////////////////////////////////////////// - // Final conserved quantity budget from fluxes divergence - ///////////////////////////////////////////////////////////////////////////// - idefix_for("CalcForcing", + idefix_for("EvolveForcing", data->beg[KDIR],data->end[KDIR], data->beg[JDIR],data->end[JDIR], data->beg[IDIR],data->end[IDIR], - calcForcing); + KOKKOS_LAMBDA (int k, int j, int i) { + + for(int component = 0 ; component < COMPONENTS ; component++) { + Uc(MX1+component,k,j,i) += dt * Vc(RHO,k,j,i) * forcingTerm(component,k,j,i); + if constexpr(Phys::pressure) { + // rho * v . f + Uc(ENG,k,j,i) += dt * Vc(RHO,k,j,i) + * Vc(VX1+component,k,j,i) + * forcingTerm(component,k,j,i); + } // pressure + } + }); + idfx::popRegion(); } diff --git a/src/fluid/fluid.hpp b/src/fluid/fluid.hpp index 8cabb7082..bab9202be 100644 --- a/src/fluid/fluid.hpp +++ b/src/fluid/fluid.hpp @@ -60,7 +60,6 @@ class Fluid { template void CalcParabolicFlux(const real); template void AddNonIdealMHDFlux(const real); template void CalcRightHandSide(real, real ); - template void CalcForcingRHS(real, real ); void CalcCurrent(); void AddSourceTerms(real, real ); void CoarsenFlow(IdefixArray4D&); @@ -218,9 +217,6 @@ class Fluid { template friend struct Fluid_CalcRHSFunctor; - template - friend struct Fluid_CalcForcingFunctor; - template friend struct ShockFlattening_FindShockFunctor; @@ -250,10 +246,6 @@ class Fluid { // Loop on dimensions template void LoopDir(const real, const real); - - // Loop on dimensions for forcing - template - void LoopForcingDir(const real, const real); }; #include "physics.hpp" From 4fc472d261df0615607028aa7f5138ff38d71ce9 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 14 Jan 2026 21:23:03 +0100 Subject: [PATCH 09/18] more clean up. TimeIntegrator changes modifies the output of the forcing routine, but it more correct as it doesn't use the updated Vc to update Uc --- src/dataBlock/dataBlock.hpp | 2 +- src/dataBlock/evolveStage.cpp | 6 +++--- src/timeIntegrator.cpp | 12 ++++++++---- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/dataBlock/dataBlock.hpp b/src/dataBlock/dataBlock.hpp index d06948c17..c4cf142c2 100644 --- a/src/dataBlock/dataBlock.hpp +++ b/src/dataBlock/dataBlock.hpp @@ -142,7 +142,7 @@ class DataBlock { void EvolveStage(); ///< Evolve this DataBlock by dt void EvolveRKLStage(); ///< Evolve this DataBlock by dt for terms impacted by RKL - void EvolveForcing(real, real); ///< Evolve this DataBlock by dt for the forcing term + void EvolveForcing(); ///< Evolve this DataBlock by dt for the forcing term void SetBoundaries(); ///< Enforce boundary conditions to this datablock void ConsToPrim(); ///< Convert conservative to primitive variables void PrimToCons(); ///< Convert primitive to conservative variables diff --git a/src/dataBlock/evolveStage.cpp b/src/dataBlock/evolveStage.cpp index a82f4fda5..a339d9908 100644 --- a/src/dataBlock/evolveStage.cpp +++ b/src/dataBlock/evolveStage.cpp @@ -43,7 +43,7 @@ void DataBlock::EvolveRKLStage() { } -void DataBlock::EvolveForcing(real t, real dt) { +void DataBlock::EvolveForcing() { idfx::pushRegion("DataBlock::EvolveForcing"); forcing->ComputeForcing(dt); forcing->oUprocesses.WriteTimestep(t, dt); @@ -54,8 +54,8 @@ void DataBlock::EvolveForcing(real t, real dt) { if (forcing->stillHaveForcing and t > forcing->stopTime) forcing->stillHaveForcing = false; -// if(haveForcing) { + if(forcing->stillHaveForcing) { hydro->EvolveForcing(t, dt); -// } + } idfx::popRegion(); } diff --git a/src/timeIntegrator.cpp b/src/timeIntegrator.cpp index 548ae5947..95f67b086 100644 --- a/src/timeIntegrator.cpp +++ b/src/timeIntegrator.cpp @@ -352,6 +352,10 @@ void TimeIntegrator::Cycle(DataBlock &data) { data.fargo->ShiftSolution(t0,data.dt); } + if(data.haveForcing && stage == nstages-1) { + data.EvolveForcing(); + } + // Coarsen conservative variables once they have been evolved if(data.haveGridCoarsening) { data.Coarsen(); @@ -373,15 +377,15 @@ void TimeIntegrator::Cycle(DataBlock &data) { MPI_SAFE_CALL(MPI_Wait(&dtReduce, MPI_STATUS_IGNORE)); } #endif - - if(data.haveForcing) { +/* +if(data.haveForcing) { if(data.forcing->stillHaveForcing) { - data.EvolveForcing(data.t, data.dt); + data.EvolveForcing(); // Back to using Vc data.ConsToPrim(); } - } + }*/ if(haveRKL && (ncycles%2)==0) { // Runge-Kutta-Legendre cycle data.EvolveRKLStage(); From 1a5400095a495805ad68765bf16662b273a226f0 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Thu, 15 Jan 2026 14:34:15 +0100 Subject: [PATCH 10/18] ensure that we can restart safely --- src/fluid/addForcingSourceTerms.hpp | 0 src/forcing/OrnsteinUhlenbeckProcess.cpp | 2 +- src/main.cpp | 1 + 3 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 src/fluid/addForcingSourceTerms.hpp diff --git a/src/fluid/addForcingSourceTerms.hpp b/src/fluid/addForcingSourceTerms.hpp new file mode 100644 index 000000000..e69de29bb diff --git a/src/forcing/OrnsteinUhlenbeckProcess.cpp b/src/forcing/OrnsteinUhlenbeckProcess.cpp index 92d073aa7..f7fa98f33 100644 --- a/src/forcing/OrnsteinUhlenbeckProcess.cpp +++ b/src/forcing/OrnsteinUhlenbeckProcess.cpp @@ -108,7 +108,7 @@ void OrnsteinUhlenbeckProcesses::AdvanceProcessesValues() { file.close(); } else { - IDEFIX_ERROR("UNABLE TO READ THE TIMESTEP FILE TO ADVANCE OU PROCESSES"); + IDEFIX_WARNING("UNABLE TO READ THE TIMESTEP FILE TO ADVANCE OU PROCESSES"); } } diff --git a/src/main.cpp b/src/main.cpp index 768f8eb27..b4ab79b6d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -155,6 +155,7 @@ int main( int argc, char* argv[] ) { input.restartRequested = false; } else { data.SetBoundaries(); + if(data.haveForcing) data.forcing->InitForcingParameters(); } } if(!input.restartRequested) { From a8fab761e80fc72145c7baca206de60ada70eda5 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Sun, 15 Nov 2026 12:59:32 +0100 Subject: [PATCH 11/18] bring back compute average sound speed fix linting errors --- src/dataBlock/dataBlock.hpp | 2 +- src/dataBlock/evolveStage.cpp | 2 +- src/fluid/addForcingSourceTerms.hpp | 11 + src/fluid/evolveStage.hpp | 7 +- src/forcing/OrnsteinUhlenbeckProcess.cpp | 93 +++-- src/forcing/OrnsteinUhlenbeckProcess.hpp | 100 +++--- src/forcing/forcing.cpp | 414 ++++++++++++----------- src/forcing/forcing.hpp | 25 +- src/timeIntegrator.cpp | 5 +- test/HD/forcing/idefix.ini | 14 +- test/HD/forcing/setup.cpp | 1 - 11 files changed, 336 insertions(+), 338 deletions(-) diff --git a/src/dataBlock/dataBlock.hpp b/src/dataBlock/dataBlock.hpp index c4cf142c2..2afd82181 100644 --- a/src/dataBlock/dataBlock.hpp +++ b/src/dataBlock/dataBlock.hpp @@ -168,7 +168,7 @@ class DataBlock { // Do we have Forcing ? bool haveForcing{false}; std::unique_ptr forcing; - + // User step functions (before or after the main integrator step) void LaunchUserStepFirst(); ///< perform user-defined step before main integration step void LaunchUserStepLast(); ///< Perform user-defined step after main integration step diff --git a/src/dataBlock/evolveStage.cpp b/src/dataBlock/evolveStage.cpp index a339d9908..cf3cad535 100644 --- a/src/dataBlock/evolveStage.cpp +++ b/src/dataBlock/evolveStage.cpp @@ -52,7 +52,7 @@ void DataBlock::EvolveForcing() { forcing->oUprocesses.WriteNormalValues(t); } - if (forcing->stillHaveForcing and t > forcing->stopTime) forcing->stillHaveForcing = false; + if (forcing->stillHaveForcing && t > forcing->stopTime) forcing->stillHaveForcing = false; if(forcing->stillHaveForcing) { hydro->EvolveForcing(t, dt); diff --git a/src/fluid/addForcingSourceTerms.hpp b/src/fluid/addForcingSourceTerms.hpp index e69de29bb..049de70f6 100644 --- a/src/fluid/addForcingSourceTerms.hpp +++ b/src/fluid/addForcingSourceTerms.hpp @@ -0,0 +1,11 @@ +// *********************************************************************************** +// Idefix MHD astrophysical code +// Copyright(C) Geoffroy R. J. Lesur +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#ifndef FLUID_ADDFORCINGSOURCETERMS_HPP_ +#define FLUID_ADDFORCINGSOURCETERMS_HPP_ + +#endif // FLUID_ADDFORCINGSOURCETERMS_HPP_ diff --git a/src/fluid/evolveStage.hpp b/src/fluid/evolveStage.hpp index 8a043b1ea..d99f42418 100644 --- a/src/fluid/evolveStage.hpp +++ b/src/fluid/evolveStage.hpp @@ -106,15 +106,14 @@ void Fluid::EvolveForcing(const real t, const real dt) { data->beg[JDIR],data->end[JDIR], data->beg[IDIR],data->end[IDIR], KOKKOS_LAMBDA (int k, int j, int i) { - for(int component = 0 ; component < COMPONENTS ; component++) { Uc(MX1+component,k,j,i) += dt * Vc(RHO,k,j,i) * forcingTerm(component,k,j,i); if constexpr(Phys::pressure) { // rho * v . f - Uc(ENG,k,j,i) += dt * Vc(RHO,k,j,i) - * Vc(VX1+component,k,j,i) + Uc(ENG,k,j,i) += dt * Vc(RHO,k,j,i) + * Vc(VX1+component,k,j,i) * forcingTerm(component,k,j,i); - } // pressure + } // pressure } }); diff --git a/src/forcing/OrnsteinUhlenbeckProcess.cpp b/src/forcing/OrnsteinUhlenbeckProcess.cpp index f7fa98f33..f3db65848 100644 --- a/src/forcing/OrnsteinUhlenbeckProcess.cpp +++ b/src/forcing/OrnsteinUhlenbeckProcess.cpp @@ -1,44 +1,47 @@ // *********************************************************************************** // Idefix MHD astrophysical code -// Copyright(C) 2020-2022 Geoffroy R. J. Lesur +// Copyright(C) Geoffroy R. J. Lesur // and other code contributors // Licensed under CeCILL 2.1 License, see COPYING for more information // *********************************************************************************** -// *********************************************************************************** -// Idefix MHD astrophysical code -// Copyright(C) 2020-2021 Geoffroy R. J. Lesur -// and other code contributors -// Licensed under CeCILL 2.1 License, see COPYING for more information -// *********************************************************************************** +#include +#include #include "OrnsteinUhlenbeckProcess.hpp" -OrnsteinUhlenbeckProcesses::OrnsteinUhlenbeckProcesses() -{ // Default (empty) constructor +OrnsteinUhlenbeckProcesses::OrnsteinUhlenbeckProcesses() { // Default (empty) constructor } -void OrnsteinUhlenbeckProcesses::InitProcesses(std::string folder, int seed, int nSeries, std::vector> modeNames) { +void OrnsteinUhlenbeckProcesses::InitProcesses(std::string folder, int seed, int nSeries, + std::vector> modeNames) { this->names = modeNames; this->nSeries = nSeries; - this->ouValues = IdefixArray2D> ("ouValues", nSeries, COMPONENTS); - this->normalValuesReal = IdefixArray2D ("normalValuesReal", nSeries, COMPONENTS); - this->normalValuesImag = IdefixArray2D ("normalValuesImag", nSeries, COMPONENTS); - this->random_pool = Kokkos::Random_XorShift64_Pool<> (/*seed=*/seed); - - this->ouFilename = folder + "/ou_prank" + std::to_string(idfx::prank) + "_seed" + std::to_string(seed) + ".dat"; - this->normalFilename = folder + "/normal_prank" + std::to_string(idfx::prank) + "_seed" + std::to_string(seed) + ".dat"; + this->ouValues = IdefixArray2D>("ouValues", nSeries, COMPONENTS); + this->normalValuesReal = IdefixArray2D("normalValuesReal", nSeries, COMPONENTS); + this->normalValuesImag = IdefixArray2D("normalValuesImag", nSeries, COMPONENTS); + this->random_pool = Kokkos::Random_XorShift64_Pool<>(/*seed=*/seed); + + this->ouFilename = folder + "/ou_prank" + std::to_string(idfx::prank) + + "_seed" + std::to_string(seed) + ".dat"; + this->normalFilename = folder + "/normal_prank" + std::to_string(idfx::prank) + + "_seed" + std::to_string(seed) + ".dat"; this->timestepFilename = folder + "/timestep.dat"; this->precision = 10; - this->ouValuesHost = IdefixHostArray2D> ("ouValuesHost", nSeries, COMPONENTS); - this->normalValuesRealHost = IdefixHostArray2D ("normalValuesRealHost", nSeries, COMPONENTS); - this->normalValuesImagHost = IdefixHostArray2D ("normalValuesImagHost", nSeries, COMPONENTS); + this->ouValuesHost = + IdefixHostArray2D>("ouValuesHost", nSeries, COMPONENTS); + this->normalValuesRealHost = + IdefixHostArray2D("normalValuesRealHost", nSeries, COMPONENTS); + this->normalValuesImagHost = + IdefixHostArray2D("normalValuesImagHost", nSeries, COMPONENTS); } -void OrnsteinUhlenbeckProcesses::SetProcesses(IdefixArray2D mean, IdefixArray2D tcorr, IdefixArray2D epsilon) { - this->epsilons = IdefixArray2D ("ouEpsilons", nSeries, COMPONENTS); - this->tcorrs = IdefixArray2D ("ouTcorrs", nSeries, COMPONENTS); - this->means = IdefixArray2D ("ouMeans", nSeries, COMPONENTS); +void OrnsteinUhlenbeckProcesses::SetProcesses(IdefixArray2D mean, + IdefixArray2D tcorr, + IdefixArray2D epsilon) { + this->epsilons = IdefixArray2D("ouEpsilons", nSeries, COMPONENTS); + this->tcorrs = IdefixArray2D("ouTcorrs", nSeries, COMPONENTS); + this->means = IdefixArray2D("ouMeans", nSeries, COMPONENTS); IdefixArray2D means = this->means; IdefixArray2D tcorrs = this->tcorrs; IdefixArray2D epsilons = this->epsilons; @@ -48,12 +51,12 @@ void OrnsteinUhlenbeckProcesses::SetProcesses(IdefixArray2D mean, IdefixAr KOKKOS_LAMBDA (int l, int dir) { means(l, dir) = mean(l, dir); tcorrs(l, dir) = tcorr(l, dir); - epsilons(l, dir) = epsilon(l, dir)/nSeries; //so that the total amplitude is independent of the number of modes used to force + // so that the total amplitude is independent of the number of modes used to force + epsilons(l, dir) = epsilon(l, dir)/nSeries; ouValues(l, dir) = mean(l, dir); }); } -//void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt, IdefixArray1D epsilons) { void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt) { IdefixArray2D means = this->means; IdefixArray2D tcorrs = this->tcorrs; @@ -83,18 +86,7 @@ void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt) { }); } -//void OrnsteinUhlenbeckProcesses::AdvanceProcessesValues(std::vector tabDt) { -//std::cout << tabDt.empty() << std::endl; -// while (not tabDt.empty()) { -// real dt = tabDt[0]; -// tabDt.erase(tabDt.begin()); -// UpdateProcessesValues(dt); -////std::cout << dt << std::endl; -// } -//} - void OrnsteinUhlenbeckProcesses::AdvanceProcessesValues() { - std::ifstream file(timestepFilename); std::string line; @@ -106,14 +98,13 @@ void OrnsteinUhlenbeckProcesses::AdvanceProcessesValues() { UpdateProcessesValues(dt); } file.close(); - } - else { - IDEFIX_WARNING("UNABLE TO READ THE TIMESTEP FILE TO ADVANCE OU PROCESSES"); + } else { + IDEFIX_WARNING("UNABLE TO READ THE TIMESTEP FILE TO ADVANCE OU PROCESSES"); } } void OrnsteinUhlenbeckProcesses::ResetProcessesValues() { - if(idfx::prank==0) { + if (idfx::prank==0) { file.open(ouFilename, std::ios::trunc); int col_width = 3*precision + 10; file << "t"; @@ -129,7 +120,7 @@ void OrnsteinUhlenbeckProcesses::ResetProcessesValues() { } void OrnsteinUhlenbeckProcesses::WriteProcessesValues(real time) { - if(idfx::prank==0) { + if (idfx::prank==0) { int col_width = 3*precision + 10; file.open(ouFilename, std::ios::app); file.precision(precision); @@ -137,8 +128,8 @@ void OrnsteinUhlenbeckProcesses::WriteProcessesValues(real time) { Kokkos::deep_copy(ouValuesHost, ouValues); for (int l=0; l +// Copyright(C) Geoffroy R. J. Lesur // and other code contributors // Licensed under CeCILL 2.1 License, see COPYING for more information // *********************************************************************************** -// *********************************************************************************** -// Idefix MHD astrophysical code -// Copyright(C) 2020-2021 Geoffroy R. J. Lesur -// and other code contributors -// Licensed under CeCILL 2.1 License, see COPYING for more information -// *********************************************************************************** +#ifndef FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ +#define FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ -#ifndef ORNSTEIN_UHLENBECK_PROCESS_HPP -#define ORNSTEIN_UHLENBECK_PROCESS_HPP - -//#include -//#include -#include -#include "idefix.hpp" -#include #include #include -//#include - - -class OrnsteinUhlenbeckProcesses { -private: - std::vector> names; - int nSeries; - - IdefixArray2D means; - IdefixArray2D tcorrs; - IdefixArray2D epsilons; - - Kokkos::Random_XorShift64_Pool<> random_pool; - -public: - IdefixArray2D> ouValues; - IdefixHostArray2D> ouValuesHost; - IdefixArray2D normalValuesReal; - IdefixArray2D normalValuesImag; - IdefixHostArray2D normalValuesRealHost; - IdefixHostArray2D normalValuesImagHost; +#include +#include +#include - OrnsteinUhlenbeckProcesses(); // Default (empty) constructor - void InitProcesses(std::string, int, int, std::vector>); - void SetProcesses(IdefixArray2D, IdefixArray2D, IdefixArray2D); - void UpdateProcessesValues(real); -// void AdvanceProcessesValues(std::vector); - void AdvanceProcessesValues(); +#include - std::string ouFilename; - std::string normalFilename; - std::string timestepFilename; - void ResetProcessesValues(); - void WriteProcessesValues(real); - void ResetNormalValues(); - void WriteNormalValues(real); - void ResetTimestep(); - void WriteTimestep(real, real); - int precision; +#include "idefix.hpp" - std::ofstream file; +class OrnsteinUhlenbeckProcesses { + private: + std::vector> names; + int nSeries; + + IdefixArray2D means; + IdefixArray2D tcorrs; + IdefixArray2D epsilons; + + Kokkos::Random_XorShift64_Pool<> random_pool; + + public: + IdefixArray2D> ouValues; + IdefixHostArray2D> ouValuesHost; + IdefixArray2D normalValuesReal; + IdefixArray2D normalValuesImag; + IdefixHostArray2D normalValuesRealHost; + IdefixHostArray2D normalValuesImagHost; + + OrnsteinUhlenbeckProcesses(); // Default (empty) constructor + void InitProcesses(std::string, int, int, std::vector>); + void SetProcesses(IdefixArray2D, IdefixArray2D, IdefixArray2D); + void UpdateProcessesValues(real); + void AdvanceProcessesValues(); + + std::string ouFilename; + std::string normalFilename; + std::string timestepFilename; + void ResetProcessesValues(); + void WriteProcessesValues(real); + void ResetNormalValues(); + void WriteNormalValues(real); + void ResetTimestep(); + void WriteTimestep(real, real); + int precision; + + std::ofstream file; }; -#endif // ORNSTEIN_UHLENBECK_PROCESS_HPP +#endif // FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp index b69eb9a7b..577335393 100644 --- a/src/forcing/forcing.cpp +++ b/src/forcing/forcing.cpp @@ -5,81 +5,27 @@ // Licensed under CeCILL 2.1 License, see COPYING for more information // *********************************************************************************** +#include +#include #include +#include #include "forcing.hpp" #include "dataBlock.hpp" #include "dataBlockHost.hpp" #include "input.hpp" -KOKKOS_INLINE_FUNCTION real K_aff_11(real x, real x0, real x1) { - return 2./(x1-x0)*x - (x1+x0)/(x1-x0); -} - -KOKKOS_INLINE_FUNCTION real K_aff_02pi(real x, real x0, real x1) { - return 2.*M_PI*(x - x0)/(x1 - x0); -} - -KOKKOS_INLINE_FUNCTION real K_cheby_fst(int n, real x) { - if (x >= -1. and x <= 1.) { - return cos(n*acos(x)); - } else { - return ZERO_F; - } -} - -KOKKOS_INLINE_FUNCTION real K_cheby_fst_both_hom_dir(int n, real x) { - if (x >= -1. and x <= 1.) { - return cos(n*acos(x)) - 1.*((n+1)%2) - x*(n%2); - } else { - return ZERO_F; - } -} - -KOKKOS_INLINE_FUNCTION real K_cheby_fst_both_hom_neu(int n, real x) { - if (x >= -1. and x <= 1.) { - return cos(n*acos(x)) - pow(n/(n+2),2.)*cos((n+2)*acos(x)); -// return cos(n*acos(x)) - pow(n/(n+2),2.)*cos((n+2)*acos(x))*((n+1)%2) - pow(n/(n+2),2.)*cos((n+2)*acos(x))*(n%2); - } else { - return ZERO_F; - } -} - -KOKKOS_INLINE_FUNCTION real K_fourier(int n, real x) { - if (x >= 0. and x <= 2.*M_PI) { - return cos(n*x) + sin(n*x); - } else { - return ZERO_F; - } -} - -KOKKOS_INLINE_FUNCTION real K_sin(int n, real x) { - if (x >= 0. and x <= 2.*M_PI) { - return sin(n*x); - } else { - return ZERO_F; - } -} - -KOKKOS_INLINE_FUNCTION real K_cos(int n, real x) { - if (x >= 0. and x <= 2.*M_PI) { - return cos(n*x); - } else { - return ZERO_F; - } -} - Forcing::Forcing(Input &input, DataBlock *datain) { idfx::pushRegion("Forcing::Forcing"); this->data = datain; - this->seed = input.GetOrSet("Forcing","seed",0,0); + this->seed = input.GetOrSet("Forcing", "seed", 0, 0); - this->write = input.GetOrSet("Forcing","write",0, 0); -// std::string folder = input.GetOrSet("Forcing","filename",0,"testOU"); - this->folder = input.GetOrSet("Output","folder",0,"output"); + this->write = input.GetOrSet("Forcing", "write", 0, 0); + this->folder = input.GetOrSet("Output", "folder", 0, "output"); this->stillHaveForcing = true; - this->stopTime = input.GetOrSet("Forcing","stoptime",0,std::numeric_limits::infinity()); + this->stopTime = input.GetOrSet("Forcing", "stoptime", 0, + std::numeric_limits::infinity()); this->nForcingModes = 0; @@ -106,14 +52,14 @@ Forcing::Forcing(Input &input, DataBlock *datain) { this->forcingType = iso3D; #if GEOMETRY != CARTESIAN IDEFIX_ERROR("You cannot have 3D isotropic forcing in another geometry than Cartesian"); - #endif //GEOMETRY != CARTESIAN - #if COMPONENTS < 3 or DIMENSIONS < 3 - IDEFIX_ERROR("You cannot have 3D isotropic forcing with less than 3 components and dimensions."); - #endif //COMPONENTS < 3 or DIMENSIONS < 3 -// if () IDEFIX_ERROR("You should not have 3D isotropic forcing with other boundary conditions than fully periodic."); + #endif // GEOMETRY != CARTESIAN + #if COMPONENTS < 3 || DIMENSIONS < 3 + IDEFIX_ERROR("You cannot have 3D isotropic forcing with less than 3 components " + "and dimensions."); + #endif // COMPONENTS < 3 || DIMENSIONS < 3 - this->kmin = input.Get("Forcing","iso3D", 0); - this->kmax = input.Get("Forcing","iso3D", 1); + this->kmin = input.Get("Forcing", "iso3D", 0); + this->kmax = input.Get("Forcing", "iso3D", 1); std::vector> k3Disovec; @@ -127,19 +73,39 @@ Forcing::Forcing(Input &input, DataBlock *datain) { real ky = ky0*ny; real kz = kz0*nz; real k_2 = kx*kx + ky*ky + kz*kz; - if (k_2 >= kmin*kmin and k_2 <= kmax*kmax) { - nForcingModes ++; + if (k_2 >= kmin*kmin && k_2 <= kmax*kmax) { + nForcingModes++; k3Disovec.push_back({kx, ky, kz}); - modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz)}); - nForcingModes ++; + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + + std::to_string(nz), + "J" + std::to_string(nx) + std::to_string(ny) + + std::to_string(nz), + "K" + std::to_string(nx) + std::to_string(ny) + + std::to_string(nz)}); + nForcingModes++; k3Disovec.push_back({kx, -ky, kz}); - modeNames.push_back({"I" + std::to_string(nx) + std::to_string(-ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(-ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(-ny) + std::to_string(nz)}); - nForcingModes ++; + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(-ny) + + std::to_string(nz), + "J" + std::to_string(nx) + std::to_string(-ny) + + std::to_string(nz), + "K" + std::to_string(nx) + std::to_string(-ny) + + std::to_string(nz)}); + nForcingModes++; k3Disovec.push_back({kx, ky, -kz}); - modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(-nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(-nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(-nz)}); - nForcingModes ++; + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + + std::to_string(-nz), + "J" + std::to_string(nx) + std::to_string(ny) + + std::to_string(-nz), + "K" + std::to_string(nx) + std::to_string(ny) + + std::to_string(-nz)}); + nForcingModes++; k3Disovec.push_back({kx, -ky, -kz}); - modeNames.push_back({"I" + std::to_string(nx) + std::to_string(-ny) + std::to_string(-nz), "J" + std::to_string(nx) + std::to_string(-ny) + std::to_string(-nz), "K" + std::to_string(nx) + std::to_string(-ny) + std::to_string(-nz)}); + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(-ny) + + std::to_string(-nz), + "J" + std::to_string(nx) + std::to_string(-ny) + + std::to_string(-nz), + "K" + std::to_string(nx) + std::to_string(-ny) + + std::to_string(-nz)}); } } } @@ -154,29 +120,36 @@ Forcing::Forcing(Input &input, DataBlock *datain) { Kokkos::deep_copy(k3Diso, k3DisoHost); EXPAND( this->forcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) - } - - else if (input.CheckEntry("Forcing", "iso2D")>=0) { + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) + } else if (input.CheckEntry("Forcing", "iso2D")>=0) { this->forcingType = iso2D; - this->normal2DisoStr = input.Get("Forcing","iso2D", 0); - if (this->normal2DisoStr == "IDIR") this->normal2Diso = IDIR; - else if (this->normal2DisoStr == "JDIR") this->normal2Diso = JDIR; - else if (this->normal2DisoStr == "KDIR") this->normal2Diso = KDIR; - else IDEFIX_ERROR("The normal component for 2D isotropic forcing cannot not be something else than IDIR, JDIR or KDIR"); - #if COMPONENTS < 2 or DIMENSIONS < 2 - IDEFIX_ERROR("You cannot have 2D isotropic forcing with less than 2 components and dimensions."); - #endif //COMPONENTS < 2 or DIMENSIONS < 2 + this->normal2DisoStr = input.Get("Forcing", "iso2D", 0); + if (this->normal2DisoStr == "IDIR") { + this->normal2Diso = IDIR; + } else if (this->normal2DisoStr == "JDIR") { + this->normal2Diso = JDIR; + } else if (this->normal2DisoStr == "KDIR") { + this->normal2Diso = KDIR; + } else { + IDEFIX_ERROR("The normal component for 2D isotropic forcing cannot not be " + "something else than IDIR, JDIR or KDIR"); + } + #if COMPONENTS < 2 || DIMENSIONS < 2 + IDEFIX_ERROR("You cannot have 2D isotropic forcing with less than 2 components " + "and dimensions."); + #endif // COMPONENTS < 2 || DIMENSIONS < 2 #if GEOMETRY == SPHERICAL - if (this->normal2DisoStr == "JDIR" or this->normal2DisoStr == "KDIR") IDEFIX_ERROR("Comparing radial with angular wavenumbers is somewhat shady."); - #endif //GEOMETRY == SPHERICAL + if (this->normal2DisoStr == "JDIR" || this->normal2DisoStr == "KDIR") { + IDEFIX_ERROR("Comparing radial with angular wavenumbers is somewhat shady."); + } + #endif // GEOMETRY == SPHERICAL - this->kmin = input.Get("Forcing","iso2D", 1); - this->kmax = input.Get("Forcing","iso2D", 2); + this->kmin = input.Get("Forcing", "iso2D", 1); + this->kmax = input.Get("Forcing", "iso2D", 2); std::vector> k2Disovec; @@ -207,13 +180,23 @@ Forcing::Forcing(Input &input, DataBlock *datain) { real ky = ky0*ny; real kz = kz0*nz; real k_2 = kx*kx + ky*ky + kz*kz; - if (k_2 >= kmin*kmin and k_2 <= kmax*kmax) { - nForcingModes ++; + if (k_2 >= kmin*kmin && k_2 <= kmax*kmax) { + nForcingModes++; k2Disovec.push_back({kx, ky, kz}); - modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "J" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz), "K" + std::to_string(nx) + std::to_string(ny) + std::to_string(nz)}); - nForcingModes ++; + modeNames.push_back({"I" + std::to_string(nx) + std::to_string(ny) + + std::to_string(nz), + "J" + std::to_string(nx) + std::to_string(ny) + + std::to_string(nz), + "K" + std::to_string(nx) + std::to_string(ny) + + std::to_string(nz)}); + nForcingModes++; k2Disovec.push_back({xsign*kx, ysign*ky, zsign*kz}); - modeNames.push_back({"I" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "J" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz), "K" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + std::to_string(zsign*nz)}); + modeNames.push_back({"I" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + + std::to_string(zsign*nz), + "J" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + + std::to_string(zsign*nz), + "K" + std::to_string(xsign*nx) + std::to_string(ysign*ny) + + std::to_string(zsign*nz)}); } } } @@ -228,18 +211,17 @@ Forcing::Forcing(Input &input, DataBlock *datain) { Kokkos::deep_copy(k2Diso, k2DisoHost); EXPAND( this->forcingModesIdir = IdefixArray4D>("forcingModesIdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , this->forcingModesJdir = IdefixArray4D>("forcingModesJdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); , this->forcingModesKdir = IdefixArray4D>("forcingModesKdir", nForcingModes, - data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) + data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); ) } - if (input.CheckEntry("Forcing", "solenoidal")>=0) { - #if GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL + #if GEOMETRY == POLAR || GEOMETRY == CYLINDRICAL IDEFIX_ERROR("Cannot have solenoidal forcing in polar in cylindrical geometry."); - #endif //GEOMETRY == POLAR or GEOMETRY == CYLINDRICAL + #endif // GEOMETRY == POLAR || GEOMETRY == CYLINDRICAL this->haveSolenoidalForcing = true; } @@ -250,27 +232,24 @@ Forcing::Forcing(Input &input, DataBlock *datain) { data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); this->solenoidalForcingTerm = IdefixArray4D("solenoidalForcingTerm", COMPONENTS, data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); -// this->compressiveForcingTerm = IdefixArray4D("compressiveForcingTerm", COMPONENTS, -// data->np_tot[KDIR], data->np_tot[JDIR], data->np_tot[IDIR]); this->means = IdefixArray2D("means", nForcingModes, COMPONENTS); this->tcorrs = IdefixArray2D("tcorrs", nForcingModes, COMPONENTS); this->epsilons = IdefixArray2D("epsilons", nForcingModes, COMPONENTS); -// WARNING DO SOMETHING WITH MEANS TCORRS AND EPSILONS this->hostMeans = IdefixHostArray2D("hostMeans", nForcingModes, COMPONENTS); this->hostTcorrs = IdefixHostArray2D("hostTcorrs", nForcingModes, COMPONENTS); this->hostEpsilons = IdefixHostArray2D("hostEpsilons", nForcingModes, COMPONENTS); this->machNumber = input.GetOrSet("Forcing", "mach", 0, -1.); - if (this->machNumber >= 0) { // in this case they will be reset later + if (this->machNumber >= 0) { // in this case they will be reset later tcorr = 1.; epsilon = -1.; - } else{ + } else { tcorr = input.Get("Forcing", "t_corr", 0); epsilon = input.Get("Forcing", "epsilon", 0); } #ifdef ISOTHERMAL - this->cs = input.Get("Hydro", "csiso", 1); //WARNING DOESN'T WORK FOR USERDEF csiso + this->cs = input.Get("Hydro", "csiso", 1); #endif this->oUprocesses.InitProcesses(this->folder, this->seed, this->nForcingModes, this->modeNames); @@ -282,17 +261,19 @@ void Forcing::ShowConfig() { if (stopTime < std::numeric_limits::infinity()) { idfx::cout << "Forcing: will be stopped at t=" << stopTime << " ." << std::endl; } - switch(forcingType) { + switch (forcingType) { case ForcingType::iso3D: idfx::cout << "Forcing: 3D isotropic." << std::endl; idfx::cout << "Forcing: kmin=" << kmin << " and kmax=" << kmax << " ." << std::endl; - idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; + idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." + << std::endl; if (haveSolenoidalForcing) idfx::cout << "Forcing: solenoidal." << std::endl; break; case ForcingType::iso2D: idfx::cout << "Forcing: 2D isotropic with normal " << normal2DisoStr << "." << std::endl; idfx::cout << "Forcing: kmin=" << kmin << " and kmax=" << kmax << " ." << std::endl; - idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." << std::endl; + idfx::cout << "Forcing: There are " << nForcingModes << " different forcing modes." + << std::endl; if (haveSolenoidalForcing) idfx::cout << "Forcing: solenoidal." << std::endl; break; } @@ -302,8 +283,6 @@ void Forcing::ShowConfig() { } else { idfx::cout << "Forcing: epsilon=" << epsilon << " and tcorr=" << tcorr << " ." << std::endl; } - - } void Forcing::InitForcingParameters() { @@ -313,8 +292,8 @@ void Forcing::InitForcingParameters() { real kf = HALF_F*(kmin+kmax); #if HAVE_ENERGY ComputeAverageSoundSpeed(); - #endif //ISOTHERMAL - this->epsilon = pow(this->machNumber*cs,3.)*kf/(2.*M_PI); + #endif // HAVE_ENERGY + this->epsilon = pow(this->machNumber*cs, 3.)*kf/(2.*M_PI); this->tcorr = 2.*M_PI/(this->machNumber*cs*kf); } for (int l=0; lkx0; real ky0 = this->ky0; real kz0 = this->kz0; - real xbeg = this->xbeg; - real ybeg = this->ybeg; - real zbeg = this->zbeg; - real xend = this->xend; - real yend = this->yend; - real zend = this->zend; EXPAND( IdefixArray4D> forcingModesIdir = this->forcingModesIdir; , IdefixArray4D> forcingModesJdir = this->forcingModesJdir; , @@ -353,52 +326,47 @@ void Forcing::InitForcingModes() { IdefixArray1D x3 = data->x[KDIR]; IdefixArray2D k3Diso = this->k3Diso; IdefixArray2D k2Diso = this->k2Diso; - Kokkos::complex unit_j(0.,1.); + Kokkos::complex unit_j(0., 1.); int nForcingModes = this->nForcingModes; ForcingType forcingType = this->forcingType; - // todo(GL): not sure this is needed - Kokkos::deep_copy(forcingModesIdir,0); - Kokkos::deep_copy(forcingModesJdir,0); - Kokkos::deep_copy(forcingModesKdir,0); + Kokkos::deep_copy(forcingModesIdir, 0); + Kokkos::deep_copy(forcingModesJdir, 0); + Kokkos::deep_copy(forcingModesKdir, 0); - - switch(forcingType) { + switch (forcingType) { case ForcingType::iso3D: - idefix_for("iso3D", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], - KOKKOS_LAMBDA (int l, int k, int j, int i) { - real kx = k3Diso(l, IDIR); - real ky = k3Diso(l, JDIR); - real kz = k3Diso(l, KDIR); - real kdotx = kx*x1(i) + ky*x2(j) + kz*x3(k); - EXPAND( - forcingModesIdir(l,k,j,i) = exp(unit_j * kdotx); , - forcingModesJdir(l,k,j,i) = exp(unit_j * kdotx); , - forcingModesKdir(l,k,j,i) = exp(unit_j * kdotx); ) + idefix_for("iso3D", 0, nForcingModes, 0, data->np_tot[KDIR], + 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int l, int k, int j, int i) { + real kx = k3Diso(l, IDIR); + real ky = k3Diso(l, JDIR); + real kz = k3Diso(l, KDIR); + real kdotx = kx*x1(i) + ky*x2(j) + kz*x3(k); + EXPAND( + forcingModesIdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesJdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesKdir(l,k,j,i) = exp(unit_j * kdotx); ) }); break; case ForcingType::iso2D: - idefix_for("iso2D", 0, nForcingModes, 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], - KOKKOS_LAMBDA (int l, int k, int j, int i) { - real kx = k2Diso(l, IDIR); - real ky = k2Diso(l, JDIR); - real kz = k2Diso(l, KDIR); - real kdotx = kx*x1(i) + ky*x2(j) + kz*x3(k); - EXPAND( - forcingModesIdir(l,k,j,i) = exp(unit_j * kdotx); , - forcingModesJdir(l,k,j,i) = exp(unit_j * kdotx); , - forcingModesKdir(l,k,j,i) = exp(unit_j * kdotx); ) + idefix_for("iso2D", 0, nForcingModes, 0, data->np_tot[KDIR], + 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int l, int k, int j, int i) { + real kx = k2Diso(l, IDIR); + real ky = k2Diso(l, JDIR); + real kz = k2Diso(l, KDIR); + real kdotx = kx*x1(i) + ky*x2(j) + kz*x3(k); + EXPAND( + forcingModesIdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesJdir(l,k,j,i) = exp(unit_j * kdotx); , + forcingModesKdir(l,k,j,i) = exp(unit_j * kdotx); ) }); break; - -// case ForcingType::userDef: -// break; } idfx::popRegion(); } - - // This function compute the required forcing field void Forcing::ComputeForcing(real dt) { idfx::pushRegion("Forcing::ComputeForcing"); @@ -427,19 +395,20 @@ void Forcing::ComputePristineForcing(real dt) { IdefixArray4D pristineForcingTerm = this->pristineForcingTerm; IdefixArray2D> ouValues = this->oUprocesses.ouValues; int nForcingModes = this->nForcingModes; - idefix_for("ComputePristineForcing", 0, data->np_tot[KDIR], 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], - KOKKOS_LAMBDA (int k, int j, int i) { - Kokkos::complex forcingX1=0.; - Kokkos::complex forcingX2=0.; - Kokkos::complex forcingX3=0.; - for (int l=0; lnp_tot[KDIR], + 0, data->np_tot[JDIR], 0, data->np_tot[IDIR], + KOKKOS_LAMBDA (int k, int j, int i) { + Kokkos::complex forcingX1 = 0.; + Kokkos::complex forcingX2 = 0.; + Kokkos::complex forcingX3 = 0.; + for (int l=0; l dx2 = data->dx[JDIR]; IdefixArray1D dx3 = data->dx[KDIR]; - IdefixArray1D x1m = data->xl[IDIR]; - IdefixArray1D x2m = data->xl[JDIR]; - IdefixArray1D x1 = data->x[IDIR]; - IdefixArray1D x2 = data->x[JDIR]; - - IdefixArray1D sinx2 = data->sinx2; - real kmean = HALF_F*(kmax + kmin); - idefix_for("ComputeSolenoidalForcing", 1, data->np_tot[KDIR] - 1, 1, data->np_tot[JDIR] - 1, 1, data->np_tot[IDIR] - 1, - KOKKOS_LAMBDA (int k, int j, int i) { - #if GEOMETRY == CARTESIAN - solenoidalForcingTerm(IDIR,k,j,i) = D_EXPAND( ZERO_F , - + 1/dx2(j) * (pristineForcingTerm(KDIR,k,j+1,i) - pristineForcingTerm(KDIR,k,j-1,i) ) , - - 1/dx3(k) * (pristineForcingTerm(JDIR,k+1,j,i) - pristineForcingTerm(JDIR,k-1,j,i) ) ); - #if DIMENSIONS >= 2 - solenoidalForcingTerm(JDIR,k,j,i) = D_EXPAND( - 1/dx1(i) * (pristineForcingTerm(KDIR,k,j,i+1) - pristineForcingTerm(KDIR,k,j,i-1) ) , - , - + 1/dx3(k) * (pristineForcingTerm(IDIR,k+1,j,i) - pristineForcingTerm(IDIR,k-1,j,i) ) ); - #endif - #if DIMENSIONS == 3 - solenoidalForcingTerm(KDIR,k,j,i) = 1/dx1(i) * (pristineForcingTerm(JDIR,k,j,i+1) - pristineForcingTerm(JDIR,k,j,i-1) ) - - 1/dx2(j) * (pristineForcingTerm(IDIR,k,j+1,i) - pristineForcingTerm(IDIR,k,j-1,i) ); - #endif - #endif - - solenoidalForcingTerm(IDIR,k,j,i) /= 2.*kmean; - solenoidalForcingTerm(JDIR,k,j,i) /= 2.*kmean; - solenoidalForcingTerm(KDIR,k,j,i) /= 2.*kmean; + idefix_for("ComputeSolenoidalForcing", 1, data->np_tot[KDIR] - 1, + 1, data->np_tot[JDIR] - 1, 1, data->np_tot[IDIR] - 1, + KOKKOS_LAMBDA (int k, int j, int i) { + #if GEOMETRY == CARTESIAN + solenoidalForcingTerm(IDIR,k,j,i) = + D_EXPAND( ZERO_F, + + 1/dx2(j) * (pristineForcingTerm(KDIR,k,j+1,i) + - pristineForcingTerm(KDIR,k,j-1,i)), + - 1/dx3(k) * (pristineForcingTerm(JDIR,k+1,j,i) + - pristineForcingTerm(JDIR,k-1,j,i)) ); + #if DIMENSIONS >= 2 + solenoidalForcingTerm(JDIR,k,j,i) = + D_EXPAND( - 1/dx1(i) * (pristineForcingTerm(KDIR,k,j,i+1) + - pristineForcingTerm(KDIR,k,j,i-1)), + , + + 1/dx3(k) * (pristineForcingTerm(IDIR,k+1,j,i) + - pristineForcingTerm(IDIR,k-1,j,i)) ); + #endif + #if DIMENSIONS == 3 + solenoidalForcingTerm(KDIR,k,j,i) = + 1/dx1(i) * (pristineForcingTerm(JDIR,k,j,i+1) + - pristineForcingTerm(JDIR,k,j,i-1)) + - 1/dx2(j) * (pristineForcingTerm(IDIR,k,j+1,i) + - pristineForcingTerm(IDIR,k,j-1,i)); + #endif + #endif + + solenoidalForcingTerm(IDIR,k,j,i) /= 2.*kmean; + solenoidalForcingTerm(JDIR,k,j,i) /= 2.*kmean; + solenoidalForcingTerm(KDIR,k,j,i) /= 2.*kmean; }); idfx::popRegion(); } +void Forcing::ComputeAverageSoundSpeed() { + idfx::pushRegion("Forcing::ComputeAverageSoundSpeed"); + this->cs = 1.; + + DataBlockHost d(*this->data); + d.SyncFromDevice(); + IdefixHostArray4D Vc = d.Vc; + + #if GEOMETRY == CARTESIAN || GEOMETRY == SPHERICAL + real currentCs = ZERO_F; + real currentVol = ZERO_F; + #if GEOMETRY == CARTESIAN + for (int i = d.beg[IDIR]; i < d.end[IDIR]; i++) { + for (int j = d.beg[JDIR]; j < d.end[JDIR]; j++) { + for (int k = d.beg[KDIR]; k < d.end[KDIR]; k++) { + currentCs += sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); + currentVol += d.dV(k,j,i); + } + } + } + #endif // GEOMETRY == CARTESIAN + #if GEOMETRY == SPHERICAL + for (int i = d.beg[IDIR]; i < d.end[IDIR]; i++) { + for (int j = d.beg[JDIR]; j < d.end[JDIR]; j++) { + for (int k = d.beg[KDIR]; k < d.end[KDIR]; k++) { + currentCs += d.dV(k,j,i)*sqrt(d.Vc(PRS,k,j,i)/d.Vc(RHO,k,j,i)); + currentVol += d.dV(k,j,i); + } + } + } + #endif // GEOMETRY == SPHERICAL + #ifdef WITH_MPI + MPI_Allreduce(MPI_IN_PLACE, ¤tCs, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + MPI_Allreduce(MPI_IN_PLACE, ¤tVol, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + #endif + this->cs = currentCs/currentVol; + #endif // GEOMETRY == CARTESIAN || GEOMETRY == SPHERICAL + idfx::popRegion(); +} + // Fill the forcing term with zeros void Forcing::ResetForcingTerms() { idfx::pushRegion("Forcing::ResetForcingTerms"); - Kokkos::deep_copy(this->forcingTerm,0); - Kokkos::deep_copy(this->pristineForcingTerm,0); - Kokkos::deep_copy(this->solenoidalForcingTerm,0); + Kokkos::deep_copy(this->forcingTerm, 0); + Kokkos::deep_copy(this->pristineForcingTerm, 0); + Kokkos::deep_copy(this->solenoidalForcingTerm, 0); idfx::popRegion(); } diff --git a/src/forcing/forcing.hpp b/src/forcing/forcing.hpp index 0da45272d..2b8847d06 100644 --- a/src/forcing/forcing.hpp +++ b/src/forcing/forcing.hpp @@ -8,6 +8,9 @@ #ifndef FORCING_FORCING_HPP_ #define FORCING_FORCING_HPP_ +#include +#include + #include "idefix.hpp" #include "input.hpp" #include "OrnsteinUhlenbeckProcess.hpp" @@ -25,40 +28,33 @@ class Forcing { void InitForcingParameters(); ///< init forcing parameters - void InitForcingModes(); ///< init forcing modes given its type - - void ComputeForcing(real); ///< compute the required forcing field at current time t + void InitForcingModes(); ///< init forcing modes given its type - void ComputePristineForcing(real);///< compute the pristine forcing field at current time t + void ComputeForcing(real); ///< compute the required forcing field at current time t - void ComputeSolenoidalForcing(real); ///< compute the solenoidal part of the forcing field at current time t + void ComputePristineForcing(real); ///< compute the pristine forcing field at current time t -// void ComputeCompressiveForcing(real); ///< compute the compressive part of the forcing field at current time t + void ComputeSolenoidalForcing(real); ///< compute the solenoidal part of the forcing field - void ResetForcingTerms(); ///< fill the forcing field with zeros. + void ResetForcingTerms(); ///< fill the forcing field with zeros. - void ShowConfig(); ///< Show the forcing configuration + void ShowConfig(); ///< Show the forcing configuration // Forcing modes -// IdefixArray4D> forcingModes; EXPAND( IdefixArray4D> forcingModesIdir; , IdefixArray4D> forcingModesJdir; , IdefixArray4D> forcingModesKdir; ) -// IdefixHostArray2D modeNamesHost; std::vector> modeNames; // Forcing terms IdefixArray4D forcingTerm; IdefixArray4D pristineForcingTerm; IdefixArray4D solenoidalForcingTerm; -// IdefixArray4D compressiveForcingTerm; OrnsteinUhlenbeckProcesses oUprocesses; - void WriteNormalBasis(std::string); ///< Write the functions of the normal basis in txt files - int write; - private: + private: DataBlock *data; int seed; std::string folder; @@ -103,7 +99,6 @@ class Forcing { int ellmax; int mmin; int mmax; -// #endif //GEOMETRY == SPHERICAL }; #endif // FORCING_FORCING_HPP_ diff --git a/src/timeIntegrator.cpp b/src/timeIntegrator.cpp index 95f67b086..b03f665ac 100644 --- a/src/timeIntegrator.cpp +++ b/src/timeIntegrator.cpp @@ -86,7 +86,8 @@ TimeIntegrator::TimeIntegrator(Input & input, DataBlock & data) { d.SyncToDevice(); data.forcing->InitForcingModes(); if (!input.restartRequested) { - data.forcing->oUprocesses.ResetProcessesValues(); // so that we get the excited modes even if we don't write + // so that we get the excited modes even if we don't write + data.forcing->oUprocesses.ResetProcessesValues(); data.forcing->oUprocesses.ResetTimestep(); if(data.forcing->write) { data.forcing->oUprocesses.ResetNormalValues(); @@ -386,7 +387,7 @@ if(data.haveForcing) { data.ConsToPrim(); } }*/ - + if(haveRKL && (ncycles%2)==0) { // Runge-Kutta-Legendre cycle data.EvolveRKLStage(); } diff --git a/test/HD/forcing/idefix.ini b/test/HD/forcing/idefix.ini index e8520553c..72a7a6c5e 100644 --- a/test/HD/forcing/idefix.ini +++ b/test/HD/forcing/idefix.ini @@ -14,13 +14,13 @@ solver hllc csiso constant 1.0 [Forcing] -iso3D 1.0 20.0 # kmin, kmax, -mach 3 # presumably mach number? -t_corr 1.0 # used when Mach not set -epsilon 0.1 # idem +iso3D 1.0 20.0 # kmin, kmax, +mach 3 # presumably mach number? +t_corr 1.0 # used when Mach not set +epsilon 0.1 # idem [Setup] -Nothing nothing +Nothing nothing [Boundary] X1-beg periodic @@ -31,5 +31,5 @@ X3-beg periodic X3-end periodic [Output] -vtk 1.0 -dmp 1.0 +vtk 1.0 +dmp 1.0 diff --git a/test/HD/forcing/setup.cpp b/test/HD/forcing/setup.cpp index 7fa1ed717..b00894cab 100644 --- a/test/HD/forcing/setup.cpp +++ b/test/HD/forcing/setup.cpp @@ -37,4 +37,3 @@ void Setup::InitFlow(DataBlock &data) { // Send it all, if needed d.SyncToDevice(); } - From 9ae777c9232fdb78406d64240438b36015bbe8cd Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 25 Nov 2026 12:22:40 +0100 Subject: [PATCH 12/18] use dump to save forcing state --- pytools/dump_io.py | 5 +++++ src/dataBlock/evolveStage.cpp | 1 - src/forcing/forcing.cpp | 24 +++++++++++++++++++++--- src/forcing/forcing.hpp | 2 ++ src/main.cpp | 1 - src/timeIntegrator.cpp | 25 ++++++++++++------------- 6 files changed, 40 insertions(+), 18 deletions(-) diff --git a/pytools/dump_io.py b/pytools/dump_io.py index 3edd93ab5..3964eae91 100644 --- a/pytools/dump_io.py +++ b/pytools/dump_io.py @@ -39,6 +39,7 @@ FLOAT_SIZE = 4 INT_SIZE = 4 INT64_SIZE = 8 +UINT64_SIZE = 8 BOOL_SIZE = 1 HEADER_SIZE = 128 @@ -83,6 +84,10 @@ def __init__(self, fh, byteorder="little"): mysize = INT64_SIZE stringchar = "q" dtype = "int64" + elif self.type == 7: + mysize = UINT64_SIZE + stringchar = "Q" + dtype = "uint64" else: raise RuntimeError( "Found unknown data type %d for field %s" % (self.type, self.name) diff --git a/src/dataBlock/evolveStage.cpp b/src/dataBlock/evolveStage.cpp index d3457f35e..d8f8a4bf2 100644 --- a/src/dataBlock/evolveStage.cpp +++ b/src/dataBlock/evolveStage.cpp @@ -55,7 +55,6 @@ void DataBlock::EvolveRKLStage() { void DataBlock::EvolveForcing() { idfx::pushRegion("DataBlock::EvolveForcing"); forcing->ComputeForcing(dt); - forcing->oUprocesses.WriteTimestep(t, dt); if (forcing->write) { forcing->oUprocesses.WriteProcessesValues(t); forcing->oUprocesses.WriteNormalValues(t); diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp index 577335393..b7f86fe58 100644 --- a/src/forcing/forcing.cpp +++ b/src/forcing/forcing.cpp @@ -13,6 +13,7 @@ #include "forcing.hpp" #include "dataBlock.hpp" #include "dataBlockHost.hpp" +#include "dump.hpp" #include "input.hpp" Forcing::Forcing(Input &input, DataBlock *datain) { @@ -253,6 +254,22 @@ Forcing::Forcing(Input &input, DataBlock *datain) { #endif this->oUprocesses.InitProcesses(this->folder, this->seed, this->nForcingModes, this->modeNames); + + // The complete forcing state is stored in the restart dump as replicated + // 2D fields (identical on every rank), so that a restart is bit-exact + // (see agent/adr/0002). Registration happens here, in the constructor, which + // runs before the dump is read on restart: a restored state is therefore + // never overwritten by re-initialisation. + data->dump->RegisterVariable(this->oUprocesses.ouValues, "ouValues"); + data->dump->RegisterVariable(this->oUprocesses.rngState, "ouRngState"); + data->dump->RegisterVariable(this->oUprocesses.means, "ouMeans"); + data->dump->RegisterVariable(this->oUprocesses.tcorrs, "ouTcorrs"); + data->dump->RegisterVariable(this->oUprocesses.epsilons, "ouEpsilons"); + + // Initialise the forcing modes from the constructor for the same reason. + // InitForcingModes() is called as a separate member function because kernels + // cannot be launched from a constructor body under nvcc. + InitForcingModes(); idfx::popRegion(); } @@ -330,9 +347,10 @@ void Forcing::InitForcingModes() { int nForcingModes = this->nForcingModes; ForcingType forcingType = this->forcingType; - Kokkos::deep_copy(forcingModesIdir, 0); - Kokkos::deep_copy(forcingModesJdir, 0); - Kokkos::deep_copy(forcingModesKdir, 0); + EXPAND( + Kokkos::deep_copy(forcingModesIdir, 0); , + Kokkos::deep_copy(forcingModesJdir, 0); , + Kokkos::deep_copy(forcingModesKdir, 0); ) switch (forcingType) { case ForcingType::iso3D: diff --git a/src/forcing/forcing.hpp b/src/forcing/forcing.hpp index 2b8847d06..58288cd76 100644 --- a/src/forcing/forcing.hpp +++ b/src/forcing/forcing.hpp @@ -55,6 +55,8 @@ class Forcing { int write; private: + void ComputeAverageSoundSpeed(); ///< average sound speed of the current state + DataBlock *data; int seed; std::string folder; diff --git a/src/main.cpp b/src/main.cpp index 2520418b1..ac3ba50c0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -165,7 +165,6 @@ int main( int argc, char* argv[] ) { input.restartRequested = false; } else { data.SetBoundaries(); - if(data.haveForcing) data.forcing->InitForcingParameters(); } } if(!input.restartRequested) { diff --git a/src/timeIntegrator.cpp b/src/timeIntegrator.cpp index 4a61dde83..867539e16 100644 --- a/src/timeIntegrator.cpp +++ b/src/timeIntegrator.cpp @@ -93,20 +93,19 @@ TimeIntegrator::TimeIntegrator(Input & input, DataBlock & data) { data.states["begin"].AllocateAs(data.states["current"]); } - if(data.haveForcing) { - DataBlockHost d(data); - d.SyncToDevice(); - data.forcing->InitForcingModes(); - if (!input.restartRequested) { - // so that we get the excited modes even if we don't write - data.forcing->oUprocesses.ResetProcessesValues(); - data.forcing->oUprocesses.ResetTimestep(); - if(data.forcing->write) { - data.forcing->oUprocesses.ResetNormalValues(); - } + if(data.haveForcing && !input.restartRequested) { + // Forcing modes are initialised in the Forcing constructor; on restart, + // the complete forcing state (ouValues, rngState, ouMeans, ouTcorrs, + // ouEpsilons) comes from the dump (see agent/adr/0002). + // so that we get the excited modes even if we don't write + // todo: check if this is still needed with the new Forcing constructor as we + // might just overwrite the state with the dump values. + // If so, we can remove this call to ResetProcessesValues() and ResetNormalValues() + // Which should be called straight from oUprocesses constructor. + data.forcing->oUprocesses.ResetProcessesValues(); + if(data.forcing->write) { + data.forcing->oUprocesses.ResetNormalValues(); } - if (input.restartRequested) data.forcing->oUprocesses.AdvanceProcessesValues(); -// if (input.restartRequested) data.forcing->oUprocesses.AdvanceProcessesValues(data.tabDt); } idfx::popRegion(); From 0fabf1a77adb9a54f9fd3e5d817f1a7acefe8968 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 25 Nov 2026 12:23:29 +0100 Subject: [PATCH 13/18] implement a custom random number generator --- src/forcing/OrnsteinUhlenbeckProcess.cpp | 99 ++++++++++++------------ src/forcing/OrnsteinUhlenbeckProcess.hpp | 49 +++++++++--- 2 files changed, 90 insertions(+), 58 deletions(-) diff --git a/src/forcing/OrnsteinUhlenbeckProcess.cpp b/src/forcing/OrnsteinUhlenbeckProcess.cpp index f3db65848..06c4a7c8c 100644 --- a/src/forcing/OrnsteinUhlenbeckProcess.cpp +++ b/src/forcing/OrnsteinUhlenbeckProcess.cpp @@ -5,6 +5,7 @@ // Licensed under CeCILL 2.1 License, see COPYING for more information // *********************************************************************************** +#include #include #include @@ -14,19 +15,55 @@ OrnsteinUhlenbeckProcesses::OrnsteinUhlenbeckProcesses() { // Default (empty) c } void OrnsteinUhlenbeckProcesses::InitProcesses(std::string folder, int seed, int nSeries, - std::vector> modeNames) { + std::vector> modeNames) { this->names = modeNames; this->nSeries = nSeries; this->ouValues = IdefixArray2D>("ouValues", nSeries, COMPONENTS); this->normalValuesReal = IdefixArray2D("normalValuesReal", nSeries, COMPONENTS); this->normalValuesImag = IdefixArray2D("normalValuesImag", nSeries, COMPONENTS); - this->random_pool = Kokkos::Random_XorShift64_Pool<>(/*seed=*/seed); + this->rngState = IdefixArray2D("ouRngState", nSeries, COMPONENTS); + this->means = IdefixArray2D("ouMeans", nSeries, COMPONENTS); + this->tcorrs = IdefixArray2D("ouTcorrs", nSeries, COMPONENTS); + this->epsilons = IdefixArray2D("ouEpsilons", nSeries, COMPONENTS); + + // The OU amplitudes start at the (zero) mean. On a fresh start, + // SetProcesses() resets them to the actual mean; on a restart, the dump + // overwrites them with the exact values at the time of the dump. + Kokkos::deep_copy(this->ouValues, 0); + + // Deterministic initialisation of one xorshift64 state per (mode, component) + // from the configured seed (see agent/adr/0002). This mirrors the warm-up and + // the 16-bit packing used by Kokkos::Random_XorShift64_Pool::init, with a + // single host-side generator, so the initial states are identical on every + // rank. A zero state would be stuck at zero, so it is replaced as in the + // Kokkos generator constructor. + uint64_t genState = (seed == 0) ? static_cast(1318319) + : static_cast(seed); + auto hostRand = [&genState]() { // Kokkos::Random_XorShift64::rand() == urand()/2 + genState ^= genState >> 12; + genState ^= genState << 25; + genState ^= genState >> 27; + uint64_t tmp = (genState * 2685821657736338717ULL) >> 16; + return static_cast((tmp & 0xFFFFFFFFULL) / 2); + }; + for (int i = 0; i < 17; i++) hostRand(); // warm-up, as in the Kokkos pool + IdefixHostArray2D rngStateHost("ouRngStateHost", nSeries, COMPONENTS); + for (int l = 0; l < nSeries; l++) { + for (int dir = 0; dir < COMPONENTS; dir++) { + uint64_t state = 0; + state |= (static_cast(hostRand()) & 0xFFFF) << 0; + state |= (static_cast(hostRand()) & 0xFFFF) << 16; + state |= (static_cast(hostRand()) & 0xFFFF) << 32; + state |= (static_cast(hostRand()) & 0xFFFF) << 48; + rngStateHost(l, dir) = (state == 0) ? static_cast(1318319) : state; + } + } + Kokkos::deep_copy(this->rngState, rngStateHost); this->ouFilename = folder + "/ou_prank" + std::to_string(idfx::prank) + "_seed" + std::to_string(seed) + ".dat"; this->normalFilename = folder + "/normal_prank" + std::to_string(idfx::prank) + "_seed" + std::to_string(seed) + ".dat"; - this->timestepFilename = folder + "/timestep.dat"; this->precision = 10; this->ouValuesHost = IdefixHostArray2D>("ouValuesHost", nSeries, COMPONENTS); @@ -37,11 +74,8 @@ void OrnsteinUhlenbeckProcesses::InitProcesses(std::string folder, int seed, int } void OrnsteinUhlenbeckProcesses::SetProcesses(IdefixArray2D mean, - IdefixArray2D tcorr, - IdefixArray2D epsilon) { - this->epsilons = IdefixArray2D("ouEpsilons", nSeries, COMPONENTS); - this->tcorrs = IdefixArray2D("ouTcorrs", nSeries, COMPONENTS); - this->means = IdefixArray2D("ouMeans", nSeries, COMPONENTS); + IdefixArray2D tcorr, + IdefixArray2D epsilon) { IdefixArray2D means = this->means; IdefixArray2D tcorrs = this->tcorrs; IdefixArray2D epsilons = this->epsilons; @@ -62,15 +96,18 @@ void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt) { IdefixArray2D tcorrs = this->tcorrs; IdefixArray2D epsilons = this->epsilons; IdefixArray2D> ouValues = this->ouValues; + IdefixArray2D rngState = this->rngState; IdefixArray2D normalValuesReal = this->normalValuesReal; IdefixArray2D normalValuesImag = this->normalValuesImag; - Kokkos::Random_XorShift64_Pool<> random_pool = this->random_pool; idefix_for("UpdateProcesses", 0, nSeries, 0, COMPONENTS, KOKKOS_LAMBDA (int l, int dir) { - auto generator = random_pool.get_state(); - real normalReal = generator.normal(0., 1.); - real normalImag = generator.normal(0., 1.); - random_pool.free_state(generator); + // Each (mode, component) draws from its own xorshift64 state: the + // sequence is deterministic on every backend and identical on all + // ranks, and it is part of the restart dump (see agent/adr/0002). + uint64_t state = rngState(l, dir); + real normalReal = static_cast(XorShift64Normal(state)); + real normalImag = static_cast(XorShift64Normal(state)); + rngState(l, dir) = state; normalValuesReal(l, dir) = normalReal; normalValuesImag(l, dir) = normalImag; real expTerm = std::exp(-dt/tcorrs(l, dir)); @@ -86,23 +123,6 @@ void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt) { }); } -void OrnsteinUhlenbeckProcesses::AdvanceProcessesValues() { - std::ifstream file(timestepFilename); - std::string line; - - if (file.is_open()) { - while (getline(file, line)) { - std::string::size_type sz; - real dt = std::stof(line, &sz); - real t = std::stof(line.substr(sz)); - UpdateProcessesValues(dt); - } - file.close(); - } else { - IDEFIX_WARNING("UNABLE TO READ THE TIMESTEP FILE TO ADVANCE OU PROCESSES"); - } -} - void OrnsteinUhlenbeckProcesses::ResetProcessesValues() { if (idfx::prank==0) { file.open(ouFilename, std::ios::trunc); @@ -171,22 +191,3 @@ void OrnsteinUhlenbeckProcesses::WriteNormalValues(real time) { file.close(); } } - -void OrnsteinUhlenbeckProcesses::ResetTimestep() { - if (idfx::prank==0) { - file.open(timestepFilename, std::ios::trunc); - file.close(); - } -} - -void OrnsteinUhlenbeckProcesses::WriteTimestep(real time, real dt) { - if (idfx::prank==0) { - int col_width = precision + 10; - file.open(timestepFilename, std::ios::app); - file.precision(precision); - this->file << std::scientific << std::setw(col_width) << dt; - this->file << std::scientific << std::setw(col_width) << time; - file << std::endl; - file.close(); - } -} diff --git a/src/forcing/OrnsteinUhlenbeckProcess.hpp b/src/forcing/OrnsteinUhlenbeckProcess.hpp index 311978b17..ceab73256 100644 --- a/src/forcing/OrnsteinUhlenbeckProcess.hpp +++ b/src/forcing/OrnsteinUhlenbeckProcess.hpp @@ -8,29 +8,64 @@ #ifndef FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ #define FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ +#include #include #include #include +#include #include #include -#include - #include "idefix.hpp" +// Self-managed xorshift64 random draws (see agent/adr/0002). +// One 64-bit state per (mode, component) is stored in rngState and advanced +// with the exact same step as Kokkos::Random_XorShift64::urand64(), and the +// normal draws use the same Box–Muller transform as +// Kokkos::Random_XorShift64::normal(). The distribution is therefore unchanged, +// while the sequence becomes deterministic on every backend and thread count +// and identical on all MPI ranks (unlike Kokkos::Random_XorShift64_Pool, whose +// no-argument get_state() selects a state through a race on GPU). + +/// Advance `state` with the xorshift64 step and return a double in [0,1), +/// exactly like Kokkos::Random_XorShift64::drand() (urand64()/MAX_URAND64) +KOKKOS_INLINE_FUNCTION +double XorShift64Drand(uint64_t &state) { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + return static_cast((state * 2685821657736338717ULL) - 1) + / static_cast(std::numeric_limits::max()); +} + +/// Standard normal draw through the Box–Muller transform, exactly like +/// Kokkos::Random_XorShift64::normal() +KOKKOS_INLINE_FUNCTION +double XorShift64Normal(uint64_t &state) { + constexpr double two_pi = 2.0 * Kokkos::numbers::pi_v; + const double u = XorShift64Drand(state); + const double v = XorShift64Drand(state); + const double r = Kokkos::sqrt(-2.0 * Kokkos::log(u)); + const double theta = v * two_pi; + return r * Kokkos::cos(theta); +} + class OrnsteinUhlenbeckProcesses { private: std::vector> names; int nSeries; + public: + // OU parameters per (mode, component). They are replicated on every rank + // and stored in the restart dump (see agent/adr/0002). IdefixArray2D means; IdefixArray2D tcorrs; IdefixArray2D epsilons; - Kokkos::Random_XorShift64_Pool<> random_pool; - - public: + // Complete OU state, replicated on every rank and stored in the restart + // dump as "ouValues" (complex) and "ouRngState" (uint64_t). IdefixArray2D> ouValues; + IdefixArray2D rngState; IdefixHostArray2D> ouValuesHost; IdefixArray2D normalValuesReal; IdefixArray2D normalValuesImag; @@ -41,17 +76,13 @@ class OrnsteinUhlenbeckProcesses { void InitProcesses(std::string, int, int, std::vector>); void SetProcesses(IdefixArray2D, IdefixArray2D, IdefixArray2D); void UpdateProcessesValues(real); - void AdvanceProcessesValues(); std::string ouFilename; std::string normalFilename; - std::string timestepFilename; void ResetProcessesValues(); void WriteProcessesValues(real); void ResetNormalValues(); void WriteNormalValues(real); - void ResetTimestep(); - void WriteTimestep(real, real); int precision; std::ofstream file; From d90060b45f837f3f622f45b42c97625b363b26a9 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 25 Nov 2026 12:23:49 +0100 Subject: [PATCH 14/18] add unit64_t to restart dumps --- src/output/dump.hpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/output/dump.hpp b/src/output/dump.hpp index 2b8185ba2..3d136de9c 100644 --- a/src/output/dump.hpp +++ b/src/output/dump.hpp @@ -70,6 +70,7 @@ enum class DataType : int { ComplexFloat = 4, /// > (interleaved re,im floats) ComplexDouble = 5, /// > (interleaved re,im doubles) Int64 = 6, /// + UInt64 = 7, /// Unknown = -1 /// }; static_assert(static_cast(DataType::Double) == 0, "DataType value is on-disk format"); @@ -82,6 +83,8 @@ static_assert(static_cast(DataType::ComplexDouble) == 5, "DataType value is on-disk format"); static_assert(static_cast(DataType::Int64) == 6, "DataType value is on-disk format"); +static_assert(static_cast(DataType::UInt64) == 7, + "DataType value is on-disk format"); // Map C++ types to DataType template struct type_to_data_type { @@ -102,6 +105,9 @@ template<> struct type_to_data_type { template<> struct type_to_data_type { static constexpr DataType value = DataType::Int64; }; +template<> struct type_to_data_type { + static constexpr DataType value = DataType::UInt64; +}; // Kokkos::complex is layout-compatible with std::complex (two contiguous reals) template<> struct type_to_data_type> { static constexpr DataType value = DataType::ComplexFloat; @@ -143,6 +149,7 @@ constexpr int size_of(DataType type) { case DataType::ComplexFloat: return 2 * sizeof(float); case DataType::ComplexDouble: return 2 * sizeof(double); case DataType::Int64: return sizeof(int64_t); + case DataType::UInt64: return sizeof(uint64_t); default: return 0; } } @@ -158,6 +165,7 @@ inline MPI_Datatype to_mpi_type(DataType type) { case DataType::ComplexFloat: return MPI_CXX_FLOAT_COMPLEX; case DataType::ComplexDouble: return MPI_CXX_DOUBLE_COMPLEX; case DataType::Int64: return MPI_LONG_LONG; + case DataType::UInt64: return MPI_UNSIGNED_LONG_LONG; default: return MPI_DATATYPE_NULL; } } From 0bc8febfae710491845694c2929f26502a946e09 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 25 Nov 2026 12:24:07 +0100 Subject: [PATCH 15/18] linter for forcing test --- test/HD/forcing/testme.py | 49 +++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/test/HD/forcing/testme.py b/test/HD/forcing/testme.py index 39df4395e..16c022066 100755 --- a/test/HD/forcing/testme.py +++ b/test/HD/forcing/testme.py @@ -4,40 +4,43 @@ @author: glesur """ + import os import sys + sys.path.append(os.getenv("IDEFIX_DIR")) import pytools.idfx_test as tst + def testMe(test): - test.configure() - test.compile() - inifiles=["idefix.ini"] + test.configure() + test.compile() + inifiles = ["idefix.ini"] - for ini in inifiles: - test.run(inputFile=ini) - if test.init and not test.mpi: - test.makeReference(filename="dump.0001.dmp") - test.standardTest() - test.nonRegressionTest(filename="dump.0001.dmp") + for ini in inifiles: + test.run(inputFile=ini) + if test.init and not test.mpi: + test.makeReference(filename="dump.0001.dmp") + test.standardTest() + test.nonRegressionTest(filename="dump.0001.dmp") -test=tst.idfxTest() +test = tst.idfxTest() if not test.dec: - test.dec=['2','2','2'] + test.dec = ["2", "2", "2"] if not test.all: - if(test.check): - test.checkOnly(filename="dump.0001.dmp") - else: - testMe(test) + if test.check: + test.checkOnly(filename="dump.0001.dmp") + else: + testMe(test) else: - test.noplot = True - test.single=False - test.reconstruction=2 - test.mpi=False - testMe(test) - - test.mpi=True - testMe(test) + test.noplot = True + test.single = False + test.reconstruction = 2 + test.mpi = False + testMe(test) + + test.mpi = True + testMe(test) From 2933a72c370f82d7eeb6c6287650d21e0c1cb5a3 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 25 Nov 2026 13:53:00 +0100 Subject: [PATCH 16/18] separate the number random generation from the ou process --- src/forcing/OrnsteinUhlenbeckProcess.cpp | 44 +++------ src/forcing/OrnsteinUhlenbeckProcess.hpp | 37 +------ src/forcing/forcing.cpp | 2 +- src/utils/CMakeLists.txt | 2 + src/utils/random.cpp | 49 +++++++++ src/utils/random.hpp | 120 +++++++++++++++++++++++ 6 files changed, 186 insertions(+), 68 deletions(-) create mode 100644 src/utils/random.cpp create mode 100644 src/utils/random.hpp diff --git a/src/forcing/OrnsteinUhlenbeckProcess.cpp b/src/forcing/OrnsteinUhlenbeckProcess.cpp index 06c4a7c8c..bf7bc7345 100644 --- a/src/forcing/OrnsteinUhlenbeckProcess.cpp +++ b/src/forcing/OrnsteinUhlenbeckProcess.cpp @@ -21,7 +21,6 @@ void OrnsteinUhlenbeckProcesses::InitProcesses(std::string folder, int seed, int this->ouValues = IdefixArray2D>("ouValues", nSeries, COMPONENTS); this->normalValuesReal = IdefixArray2D("normalValuesReal", nSeries, COMPONENTS); this->normalValuesImag = IdefixArray2D("normalValuesImag", nSeries, COMPONENTS); - this->rngState = IdefixArray2D("ouRngState", nSeries, COMPONENTS); this->means = IdefixArray2D("ouMeans", nSeries, COMPONENTS); this->tcorrs = IdefixArray2D("ouTcorrs", nSeries, COMPONENTS); this->epsilons = IdefixArray2D("ouEpsilons", nSeries, COMPONENTS); @@ -32,33 +31,11 @@ void OrnsteinUhlenbeckProcesses::InitProcesses(std::string folder, int seed, int Kokkos::deep_copy(this->ouValues, 0); // Deterministic initialisation of one xorshift64 state per (mode, component) - // from the configured seed (see agent/adr/0002). This mirrors the warm-up and - // the 16-bit packing used by Kokkos::Random_XorShift64_Pool::init, with a - // single host-side generator, so the initial states are identical on every - // rank. A zero state would be stuck at zero, so it is replaced as in the - // Kokkos generator constructor. - uint64_t genState = (seed == 0) ? static_cast(1318319) - : static_cast(seed); - auto hostRand = [&genState]() { // Kokkos::Random_XorShift64::rand() == urand()/2 - genState ^= genState >> 12; - genState ^= genState << 25; - genState ^= genState >> 27; - uint64_t tmp = (genState * 2685821657736338717ULL) >> 16; - return static_cast((tmp & 0xFFFFFFFFULL) / 2); - }; - for (int i = 0; i < 17; i++) hostRand(); // warm-up, as in the Kokkos pool - IdefixHostArray2D rngStateHost("ouRngStateHost", nSeries, COMPONENTS); - for (int l = 0; l < nSeries; l++) { - for (int dir = 0; dir < COMPONENTS; dir++) { - uint64_t state = 0; - state |= (static_cast(hostRand()) & 0xFFFF) << 0; - state |= (static_cast(hostRand()) & 0xFFFF) << 16; - state |= (static_cast(hostRand()) & 0xFFFF) << 32; - state |= (static_cast(hostRand()) & 0xFFFF) << 48; - rngStateHost(l, dir) = (state == 0) ? static_cast(1318319) : state; - } - } - Kokkos::deep_copy(this->rngState, rngStateHost); + // from the configured seed (see agent/adr/0002 and idfx::RandomXorShift64). + // The generator stores a flat 1D state; the (l, dir) pair is mapped to the + // effective index l*COMPONENTS+dir (the LayoutRight offset of (l, dir)). + this->rng = idfx::RandomXorShift64(nSeries*COMPONENTS); + this->rng.InitFromSeed(seed); this->ouFilename = folder + "/ou_prank" + std::to_string(idfx::prank) + "_seed" + std::to_string(seed) + ".dat"; @@ -96,7 +73,7 @@ void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt) { IdefixArray2D tcorrs = this->tcorrs; IdefixArray2D epsilons = this->epsilons; IdefixArray2D> ouValues = this->ouValues; - IdefixArray2D rngState = this->rngState; + idfx::RandomXorShift64 rng = this->rng; IdefixArray2D normalValuesReal = this->normalValuesReal; IdefixArray2D normalValuesImag = this->normalValuesImag; idefix_for("UpdateProcesses", 0, nSeries, 0, COMPONENTS, @@ -104,10 +81,11 @@ void OrnsteinUhlenbeckProcesses::UpdateProcessesValues(real dt) { // Each (mode, component) draws from its own xorshift64 state: the // sequence is deterministic on every backend and identical on all // ranks, and it is part of the restart dump (see agent/adr/0002). - uint64_t state = rngState(l, dir); - real normalReal = static_cast(XorShift64Normal(state)); - real normalImag = static_cast(XorShift64Normal(state)); - rngState(l, dir) = state; + // The by-value copy of rng shares the same underlying state array. + // Effective 1D index of the (l, dir) stream in the flat state array. + const int idx = l*COMPONENTS + dir; + real normalReal = static_cast(rng.Normal(idx)); + real normalImag = static_cast(rng.Normal(idx)); normalValuesReal(l, dir) = normalReal; normalValuesImag(l, dir) = normalImag; real expTerm = std::exp(-dt/tcorrs(l, dir)); diff --git a/src/forcing/OrnsteinUhlenbeckProcess.hpp b/src/forcing/OrnsteinUhlenbeckProcess.hpp index ceab73256..ce70bcf23 100644 --- a/src/forcing/OrnsteinUhlenbeckProcess.hpp +++ b/src/forcing/OrnsteinUhlenbeckProcess.hpp @@ -17,38 +17,7 @@ #include #include "idefix.hpp" - -// Self-managed xorshift64 random draws (see agent/adr/0002). -// One 64-bit state per (mode, component) is stored in rngState and advanced -// with the exact same step as Kokkos::Random_XorShift64::urand64(), and the -// normal draws use the same Box–Muller transform as -// Kokkos::Random_XorShift64::normal(). The distribution is therefore unchanged, -// while the sequence becomes deterministic on every backend and thread count -// and identical on all MPI ranks (unlike Kokkos::Random_XorShift64_Pool, whose -// no-argument get_state() selects a state through a race on GPU). - -/// Advance `state` with the xorshift64 step and return a double in [0,1), -/// exactly like Kokkos::Random_XorShift64::drand() (urand64()/MAX_URAND64) -KOKKOS_INLINE_FUNCTION -double XorShift64Drand(uint64_t &state) { - state ^= state >> 12; - state ^= state << 25; - state ^= state >> 27; - return static_cast((state * 2685821657736338717ULL) - 1) - / static_cast(std::numeric_limits::max()); -} - -/// Standard normal draw through the Box–Muller transform, exactly like -/// Kokkos::Random_XorShift64::normal() -KOKKOS_INLINE_FUNCTION -double XorShift64Normal(uint64_t &state) { - constexpr double two_pi = 2.0 * Kokkos::numbers::pi_v; - const double u = XorShift64Drand(state); - const double v = XorShift64Drand(state); - const double r = Kokkos::sqrt(-2.0 * Kokkos::log(u)); - const double theta = v * two_pi; - return r * Kokkos::cos(theta); -} +#include "random.hpp" class OrnsteinUhlenbeckProcesses { private: @@ -63,9 +32,9 @@ class OrnsteinUhlenbeckProcesses { IdefixArray2D epsilons; // Complete OU state, replicated on every rank and stored in the restart - // dump as "ouValues" (complex) and "ouRngState" (uint64_t). + // dump as "ouValues" (complex) and "ouRngState" (uint64_t, via rng.state()). IdefixArray2D> ouValues; - IdefixArray2D rngState; + idfx::RandomXorShift64 rng; IdefixHostArray2D> ouValuesHost; IdefixArray2D normalValuesReal; IdefixArray2D normalValuesImag; diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp index b7f86fe58..ffd2a7499 100644 --- a/src/forcing/forcing.cpp +++ b/src/forcing/forcing.cpp @@ -261,7 +261,7 @@ Forcing::Forcing(Input &input, DataBlock *datain) { // runs before the dump is read on restart: a restored state is therefore // never overwritten by re-initialisation. data->dump->RegisterVariable(this->oUprocesses.ouValues, "ouValues"); - data->dump->RegisterVariable(this->oUprocesses.rngState, "ouRngState"); + data->dump->RegisterVariable(this->oUprocesses.rng.state(), "ouRngState"); data->dump->RegisterVariable(this->oUprocesses.means, "ouMeans"); data->dump->RegisterVariable(this->oUprocesses.tcorrs, "ouTcorrs"); data->dump->RegisterVariable(this->oUprocesses.epsilons, "ouEpsilons"); diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index f5276557d..f97ddf528 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -21,6 +21,8 @@ target_sources(idefix-core PRIVATE ${CMAKE_CURRENT_LIST_DIR}/lookupTable.hpp PRIVATE ${CMAKE_CURRENT_LIST_DIR}/column.cpp PRIVATE ${CMAKE_CURRENT_LIST_DIR}/column.hpp + PRIVATE ${CMAKE_CURRENT_LIST_DIR}/random.hpp + PRIVATE ${CMAKE_CURRENT_LIST_DIR}/random.cpp ) if (Idefix_GTEST) diff --git a/src/utils/random.cpp b/src/utils/random.cpp new file mode 100644 index 000000000..5a5297c36 --- /dev/null +++ b/src/utils/random.cpp @@ -0,0 +1,49 @@ +// *********************************************************************************** +// Idefix MHD astrophysical code +// +// Source file src/utils/random.cpp +// +// Last modified : 11/2026 +// +// Copyright(C) by : +// - Geoffroy Lesur (IPAG/UGA/CNRS - 2020 - 2026) +// and other code contributors +// +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#include "random.hpp" + +namespace idfx { + +void RandomXorShift64::InitFromSeed(int seed) { + // Deterministic initialisation of one xorshift64 state per entry from the + // configured seed (see agent/adr/0002). This mirrors the warm-up and the + // 16-bit packing used by Kokkos::Random_XorShift64_Pool::init, with a + // single host-side generator, so the initial states are identical on every + // rank. A zero state would be stuck at zero, so it is replaced as in the + // Kokkos generator constructor. + uint64_t genState = (seed == 0) ? static_cast(1318319) + : static_cast(seed); + auto hostRand = [&genState]() { // Kokkos::Random_XorShift64::rand() == urand()/2 + genState ^= genState >> 12; + genState ^= genState << 25; + genState ^= genState >> 27; + uint64_t tmp = (genState * 2685821657736338717ULL) >> 16; + return static_cast((tmp & 0xFFFFFFFFULL) / 2); + }; + for (int i = 0; i < 17; i++) hostRand(); // warm-up, as in the Kokkos pool + auto stateHost = Kokkos::create_mirror_view(state_); + const int n = static_cast(state_.extent(0)); + for (int i = 0; i < n; i++) { + uint64_t state = 0; + state |= (static_cast(hostRand()) & 0xFFFF) << 0; + state |= (static_cast(hostRand()) & 0xFFFF) << 16; + state |= (static_cast(hostRand()) & 0xFFFF) << 32; + state |= (static_cast(hostRand()) & 0xFFFF) << 48; + stateHost(i) = (state == 0) ? static_cast(1318319) : state; + } + Kokkos::deep_copy(state_, stateHost); +} + +} // namespace idfx diff --git a/src/utils/random.hpp b/src/utils/random.hpp new file mode 100644 index 000000000..8921eb431 --- /dev/null +++ b/src/utils/random.hpp @@ -0,0 +1,120 @@ +// *********************************************************************************** +// Idefix MHD astrophysical code +// +// Source file src/utils/random.hpp +// +// Last modified : 11/2026 +// +// Copyright(C) by : +// - Geoffroy Lesur (IPAG/UGA/CNRS - 2020 - 2026) +// and other code contributors +// +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#ifndef UTILS_RANDOM_HPP_ +#define UTILS_RANDOM_HPP_ + +#include +#include + +#include "idefix.hpp" +#include "arrays.hpp" + +namespace idfx { + +/// Self-managed xorshift64 random number generator (see agent/adr/0002). +/// +/// One 64-bit state per entry is stored in a flat device array and advanced +/// with the exact same step as Kokkos::Random_XorShift64::urand64(), and the +/// normal draws use the same Box–Muller transform as +/// Kokkos::Random_XorShift64::normal(). The distribution is therefore +/// unchanged, while the sequence becomes deterministic on every backend and +/// thread count and identical on all MPI ranks (unlike +/// Kokkos::Random_XorShift64_Pool, whose no-argument get_state() selects a +/// state through a race on GPU). +/// +/// The state is a flat 1D array so that the class stays agnostic of how the +/// caller maps logical indices to streams: a caller with 2D (l, dir) indices +/// simply passes the effective index l*n1+dir (the LayoutRight offset of +/// (l, dir) in a 2D array). +/// +/// Because the state lives in a plain Kokkos::View, the class is safe to +/// capture by value in a KOKKOS_LAMBDA: the copy shares the same underlying +/// state, so draws made inside a kernel advance the generator. +/// +/// The external draw API is indexed (Drand(i) / Normal(i) on stream i); the +/// raw single-state-word step and Box–Muller transform are private Impl +/// helpers, so the two cannot be confused. +class RandomXorShift64 { + public: + RandomXorShift64() = default; + /// Allocate the state array with n streams. Seeding is done separately + /// with InitFromSeed(). + explicit RandomXorShift64(int n) : state_("RandomXorShift64State", n) {} + + // The class only holds a View (a reference-counted handle), so the + // defaulted copy semantics are exactly what device lambdas need. + RandomXorShift64(const RandomXorShift64&) = default; + RandomXorShift64& operator=(const RandomXorShift64&) = default; + + /// Deterministically fill the state array from a seed, mirroring the + /// warm-up and 16-bit packing used by Kokkos::Random_XorShift64_Pool::init + /// with a single host-side generator, so the initial states are identical + /// on every rank (host only, defined in random.cpp). + void InitFromSeed(int seed); + + /// External API: advance state_[i] with the xorshift64 step and return a + /// double in [0,1), exactly like Kokkos::Random_XorShift64::drand(). + /// Const like Kokkos::View::operator(): the View handle is const but the + /// underlying state word is advanced in place (this is what makes draws + /// work inside a by-value KOKKOS_LAMBDA capture). + KOKKOS_INLINE_FUNCTION + double Drand(int i) const { + return DrandImpl(state_(i)); + } + + /// External API: standard normal draw from state_[i] through the + /// Box–Muller transform, exactly like Kokkos::Random_XorShift64::normal(). + KOKKOS_INLINE_FUNCTION + double Normal(int i) const { + return NormalImpl(state_(i)); + } + + /// Raw access to the state array, e.g. to register it in a restart dump. + IdefixArray1D& state() { return state_; } + const IdefixArray1D& state() const { return state_; } + + private: + // Internal helpers, operating on a raw 64-bit state word (advanced in + // place). They are private and carry an Impl suffix so that they cannot be + // confused with the external (indexed) draw API above. + /// xorshift64 step, exactly like + /// Kokkos::Random_XorShift64::urand64()/MAX_URAND64. + KOKKOS_INLINE_FUNCTION + static double DrandImpl(uint64_t &state) { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + return static_cast((state * 2685821657736338717ULL) - 1) + / static_cast(std::numeric_limits::max()); + } + + /// Box–Muller standard normal draw, exactly like + /// Kokkos::Random_XorShift64::normal(). + KOKKOS_INLINE_FUNCTION + static double NormalImpl(uint64_t &state) { + constexpr double two_pi = 2.0 * Kokkos::numbers::pi_v; + const double u = DrandImpl(state); + const double v = DrandImpl(state); + const double r = Kokkos::sqrt(-2.0 * Kokkos::log(u)); + const double theta = v * two_pi; + return r * Kokkos::cos(theta); + } + + IdefixArray1D state_; +}; + +} // namespace idfx + +#endif // UTILS_RANDOM_HPP_ From 85f96cf6ece01e662a5cda9efd7ba91c7c635480 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 25 Nov 2026 14:01:07 +0100 Subject: [PATCH 17/18] remove std::numerics dependence --- src/utils/random.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/random.hpp b/src/utils/random.hpp index 8921eb431..71c7871bd 100644 --- a/src/utils/random.hpp +++ b/src/utils/random.hpp @@ -97,7 +97,7 @@ class RandomXorShift64 { state ^= state << 25; state ^= state >> 27; return static_cast((state * 2685821657736338717ULL) - 1) - / static_cast(std::numeric_limits::max()); + / static_cast(Kokkos::Experimental::finite_max_v); } /// Box–Muller standard normal draw, exactly like From ad239286ad5532595e55f2eb38fbf39d20fbe8c0 Mon Sep 17 00:00:00 2001 From: Geoffroy Lesur Date: Wed, 25 Nov 2026 22:17:48 +0100 Subject: [PATCH 18/18] doc creation/update --- doc/source/modules.rst | 4 ++ doc/source/modules/forcing.rst | 88 +++++++++++++++++++++++++++++ doc/source/reference/idefix.ini.rst | 37 ++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 doc/source/modules/forcing.rst diff --git a/doc/source/modules.rst b/doc/source/modules.rst index 2f1f3787a..6fa137eb0 100644 --- a/doc/source/modules.rst +++ b/doc/source/modules.rst @@ -31,6 +31,9 @@ In this section, you will find a more detailed documentation about each module t :ref:`pydefixModule` The Python interaction module, that allows Idefix to interact directly with a python interpreter. +:ref:`forcingModule` + The stochastic forcing module, driving turbulence with Ornstein–Uhlenbeck Fourier modes. + .. toctree:: :maxdepth: 2 @@ -44,3 +47,4 @@ In this section, you will find a more detailed documentation about each module t modules/braginskii.rst modules/gridCoarsening.rst modules/pydefix.rst + modules/forcing.rst diff --git a/doc/source/modules/forcing.rst b/doc/source/modules/forcing.rst new file mode 100644 index 000000000..4e515e4fc --- /dev/null +++ b/doc/source/modules/forcing.rst @@ -0,0 +1,88 @@ +.. _forcingModule: + +Stochastic forcing module +========================= + +The forcing module drives turbulence by adding a stochastic external force to the fluid equations. +The force is a superposition of Fourier modes :math:`e^{i\,\mathbf{k}\cdot\mathbf{x}}` whose complex +amplitudes follow independent Ornstein–Uhlenbeck (OU) processes, one per mode and per vector component. +It is typically used to sustain turbulence in decaying-turbulence setups (see e.g. ``test/HD/forcing``). + +This approach is identical to the one described in `St-Onge, D. A., M. W. Kunz, J. Squire, et +A. A. Schekochihin, *Journal of Plasma +Physics* 86 (octobre 2020), 905860503 `_. + +The forcing term is added to the right-hand side of the momentum equation +(:math:`\partial_t(\rho \mathbf{v}) \mathrel{+}= \rho\,\mathbf{f}`), and to the energy equation +(:math:`\rho\,\mathbf{v}\cdot\mathbf{f}`) when the pressure equation is enabled. + +Input parameters +---------------- + +All parameters are set in the ``[Forcing]`` section of the input file (see :ref:`forcingSection` for +the full list): + +``iso3D kmin kmax`` + 3D isotropic forcing: all wavevectors with :math:`k_\mathrm{min} \le |\mathbf{k}| \le + k_\mathrm{max}` are driven. Cartesian geometry with 3 dimensions and 3 components only. + +``iso2D normal kmin kmax`` + 2D isotropic forcing in the plane perpendicular to ``normal`` (``IDIR``, ``JDIR`` or ``KDIR``), + with :math:`k_\mathrm{min} \le |\mathbf{k}| \le k_\mathrm{max}`. + +``solenoidal`` + When present, the forcing is projected onto its solenoidal (divergence-free) part, computed as + the curl of the pristine forcing normalised by the mean wavenumber. Not available in polar and + cylindrical geometries. + +``mach M`` + Alternative to ``t_corr``/``epsilon``: the amplitude is set from a target Mach number ``M``, + using the volume-averaged sound speed :math:`c_s` at :math:`t=0` (``csiso`` in isothermal runs): + + .. math:: + \epsilon = \frac{(M c_s)^3 k_f}{2\pi}, \qquad + t_\mathrm{corr} = \frac{2\pi}{M c_s k_f}, \qquad + k_f = \frac{k_\mathrm{min}+k_\mathrm{max}}{2}. + +``t_corr`` and ``epsilon`` + OU correlation time and amplitude, used when ``mach`` is not set. ``epsilon`` is internally + divided by the number of forcing modes, so the total injected amplitude does not depend on how + many modes are used. + +``seed`` + Seed of the random number generator (default: 0). + +``stoptime`` + Time after which the forcing is switched off (default: never). + +``write`` + If set to 1, the time series of the OU amplitudes and of the normal draws are written to + ``ou_prank0_seed.dat`` and ``normal_prank0_seed.dat`` in the output folder. + +How the OU processes are updated +-------------------------------- + +At each timestep, the complex amplitude :math:`A` of each (mode, component) pair is updated as + +.. math:: + A_{n+1} = \frac{\bar{A}}{\sqrt{2}} + + \left(A_n - \frac{\bar{A}}{\sqrt{2}}\right) e^{-\Delta t / t_\mathrm{corr}} + + \sqrt{\frac{\epsilon}{\sqrt{2}\,t_\mathrm{corr}} + \left(1 - e^{-2\Delta t / t_\mathrm{corr}}\right)}\, \mathcal{N}, + +where :math:`\bar{A}` is the (zero) mean and :math:`\mathcal{N}` a standard normal draw. The +resulting forcing field at a cell is :math:`\mathbf{f}(\mathbf{x}) = +\sum_l \mathrm{Re}\left[A_l\, e^{i\,\mathbf{k}_l\cdot\mathbf{x}}\right]`. + +Random numbers and reproducibility +---------------------------------- + +Random draws are produced by ``idfx::RandomXorShift64`` (``src/utils/random.hpp``): one +self-managed xorshift64 stream per (mode, component), with standard normal draws obtained through +the Box–Muller transform. Unlike a Kokkos random pool, the sequence is deterministic on every +backend, thread count and MPI rank, and identical on all ranks, and we can restore easily +its state from a restart dump. + +The complete forcing state (OU amplitudes ``ouValues``, random state ``ouRngState``, and the OU +parameters ``ouMeans``, ``ouTcorrs``, ``ouEpsilons``) is stored in the restart dumps, so a restart +is bit-exact: the forcing applied after a restart is identical to that of an uninterrupted run. diff --git a/doc/source/reference/idefix.ini.rst b/doc/source/reference/idefix.ini.rst index a6bc52bdb..95fc700f2 100644 --- a/doc/source/reference/idefix.ini.rst +++ b/doc/source/reference/idefix.ini.rst @@ -234,6 +234,43 @@ This section enables the orbital advection algorithm provided in *Idefix*. More | | | | Default: 10 | +----------------+-------------------------+---------------------------------------------------------------------------------------------+ +.. _forcingSection: + +``Forcing`` section +------------------- + +This section enables the stochastic forcing module provided in *Idefix*, which drives turbulence with +Ornstein-Uhlenbeck Fourier modes. More information may be found in :ref:`forcingModule` + ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| Entry name | Parameter type | | Comment | ++================+=========================+=============================================================================================+ +| iso3D | real, real | | 3D isotropic forcing: all wavevectors with ``kmin <= |k| <= kmax`` are driven. Cartesian | +| | | | geometry with 3 dimensions and 3 components only. | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| iso2D | string, real, real | | 2D isotropic forcing in the plane perpendicular to ``normal`` (``IDIR``, ``JDIR`` or | +| | | | ``KDIR``), with ``kmin <= |k| <= kmax``. | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| solenoidal | (flag) | | Projects the forcing onto its solenoidal (divergence-free) part. Not available in polar | +| | | | and cylindrical geometries. | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| mach | real | | Alternative to ``t_corr``/``epsilon``: sets the amplitude from a target Mach number | +| | | | ``M``, using the volume-averaged sound speed at t=0 (``csiso`` in isothermal runs). | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| t_corr | real | | Ornstein-Uhlenbeck correlation time. Used when ``mach`` is not set. | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| epsilon | real | | Ornstein-Uhlenbeck amplitude. Used when ``mach`` is not set. Internally divided by the | +| | | | number of forcing modes. | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| seed | integer | | Seed of the random number generator. Default is 0. | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| stoptime | real | | Time after which the forcing is switched off. Default is infinity (never). | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ +| write | integer | | If set to 1, writes the time series of the OU amplitudes and normal draws to the output | +| | | | folder (``ou_prank0_seed.dat`` and ``normal_prank0_seed.dat``). Default is 0. | ++----------------+-------------------------+---------------------------------------------------------------------------------------------+ + + .. _gravitySection: ``Gravity`` section