diff --git a/CMakeLists.txt b/CMakeLists.txt index d5bb2526..f10ccb58 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -354,6 +354,7 @@ target_include_directories(idefix-core PUBLIC src/fluid/RiemannSolver/MHDsolvers src/fluid/RiemannSolver/Dustsolvers src/fluid/tracer + src/forcing src/output src/rkl src/gravity diff --git a/doc/source/modules.rst b/doc/source/modules.rst index 2f1f3787..6fa137eb 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 00000000..4e515e4f --- /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 a6bc52bd..95fc700f 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 diff --git a/pytools/dump_io.py b/pytools/dump_io.py index 3edd93ab..3964eae9 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/CMakeLists.txt b/src/CMakeLists.txt index c801a06c..cf771298 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -15,6 +15,7 @@ add_subdirectory(fluid) add_subdirectory(dataBlock) +add_subdirectory(forcing) add_subdirectory(output) add_subdirectory(rkl) add_subdirectory(gravity) diff --git a/src/dataBlock/dataBlock.cpp b/src/dataBlock/dataBlock.cpp index 3440faca..c2bf8b7c 100644 --- a/src/dataBlock/dataBlock.cpp +++ b/src/dataBlock/dataBlock.cpp @@ -22,6 +22,7 @@ #include "dataBlock.hpp" #include "fluid.hpp" #include "gravity.hpp" +#include "forcing.hpp" #include "planetarySystem.hpp" #include "vtk.hpp" #include "dump.hpp" @@ -154,6 +155,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; @@ -328,6 +335,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 6d322e7e..d804f80b 100644 --- a/src/dataBlock/dataBlock.hpp +++ b/src/dataBlock/dataBlock.hpp @@ -28,6 +28,7 @@ #include "gridHost.hpp" #include "planetarySystem.hpp" #include "gravity.hpp" +#include "forcing.hpp" #include "stateContainer.hpp" ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -150,6 +151,7 @@ class DataBlock { void EvolveStage(); ///< Evolve this DataBlock by dt void EvolveRKLStage(); ///< Evolve this DataBlock by dt for terms impacted by RKL + 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 @@ -172,6 +174,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 c00c44fe..d8f8a4bf 100644 --- a/src/dataBlock/evolveStage.cpp +++ b/src/dataBlock/evolveStage.cpp @@ -50,3 +50,20 @@ void DataBlock::EvolveRKLStage() { } idfx::popRegion(); } + + +void DataBlock::EvolveForcing() { + idfx::pushRegion("DataBlock::EvolveForcing"); + forcing->ComputeForcing(dt); + if (forcing->write) { + forcing->oUprocesses.WriteProcessesValues(t); + forcing->oUprocesses.WriteNormalValues(t); + } + + if (forcing->stillHaveForcing && t > forcing->stopTime) forcing->stillHaveForcing = false; + + if(forcing->stillHaveForcing) { + hydro->EvolveForcing(t, dt); + } + idfx::popRegion(); +} diff --git a/src/fluid/addForcingSourceTerms.hpp b/src/fluid/addForcingSourceTerms.hpp new file mode 100644 index 00000000..049de70f --- /dev/null +++ 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 44c61cf3..4ec914ce 100644 --- a/src/fluid/evolveStage.hpp +++ b/src/fluid/evolveStage.hpp @@ -17,6 +17,8 @@ #include "fluid.hpp" #include "riemannSolver.hpp" +#include "forcing.hpp" + template template void Fluid::LoopDir(const real t, const real dt) { @@ -95,4 +97,35 @@ 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"); + + auto Uc = this->Uc; + auto Vc = this->Vc; + auto forcingTerm = this->data->forcing->forcingTerm; + + idefix_for("EvolveForcing", + data->beg[KDIR],data->end[KDIR], + 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) + * forcingTerm(component,k,j,i); + } // pressure + } + }); + + + idfx::popRegion(); +} + #endif //FLUID_EVOLVESTAGE_HPP_ diff --git a/src/fluid/fluid.hpp b/src/fluid/fluid.hpp index d32b074f..9b4549ac 100644 --- a/src/fluid/fluid.hpp +++ b/src/fluid/fluid.hpp @@ -25,6 +25,7 @@ #include "eos.hpp" #include "thermalDiffusion.hpp" #include "bragThermalDiffusion.hpp" +#include "forcing.hpp" #include "selfGravity.hpp" #include "vtk.hpp" #include "dump.hpp" @@ -73,6 +74,7 @@ class Fluid { real CheckDivB(); void EvolveStage(const real, const real); void ResetStage(); + void EvolveForcing(const real, const real); void ShowConfig(); IdefixArray4D GetFlux(int dir) {return this->FluxRiemann.at(dir);} int CheckNan(); diff --git a/src/forcing/CMakeLists.txt b/src/forcing/CMakeLists.txt new file mode 100644 index 00000000..03d259cb --- /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 00000000..bf7bc734 --- /dev/null +++ b/src/forcing/OrnsteinUhlenbeckProcess.cpp @@ -0,0 +1,171 @@ +// *********************************************************************************** +// 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 +#include + +#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->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 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"; + this->normalFilename = folder + "/normal_prank" + std::to_string(idfx::prank) + + "_seed" + std::to_string(seed) + ".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) { + 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); + // 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) { + IdefixArray2D means = this->means; + IdefixArray2D tcorrs = this->tcorrs; + IdefixArray2D epsilons = this->epsilons; + IdefixArray2D> ouValues = this->ouValues; + idfx::RandomXorShift64 rng = this->rng; + IdefixArray2D normalValuesReal = this->normalValuesReal; + IdefixArray2D normalValuesImag = this->normalValuesImag; + idefix_for("UpdateProcesses", 0, nSeries, 0, COMPONENTS, + KOKKOS_LAMBDA (int l, int dir) { + // 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). + // 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)); + 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::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; l +// and other code contributors +// Licensed under CeCILL 2.1 License, see COPYING for more information +// *********************************************************************************** + +#ifndef FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ +#define FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +#include "idefix.hpp" +#include "random.hpp" + +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; + + // Complete OU state, replicated on every rank and stored in the restart + // dump as "ouValues" (complex) and "ouRngState" (uint64_t, via rng.state()). + IdefixArray2D> ouValues; + idfx::RandomXorShift64 rng; + 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); + + std::string ouFilename; + std::string normalFilename; + void ResetProcessesValues(); + void WriteProcessesValues(real); + void ResetNormalValues(); + void WriteNormalValues(real); + int precision; + + std::ofstream file; +}; + +#endif // FORCING_ORNSTEINUHLENBECKPROCESS_HPP_ diff --git a/src/forcing/forcing.cpp b/src/forcing/forcing.cpp new file mode 100644 index 00000000..ffd2a749 --- /dev/null +++ b/src/forcing/forcing.cpp @@ -0,0 +1,536 @@ +// *********************************************************************************** +// 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 +#include +#include + +#include "forcing.hpp" +#include "dataBlock.hpp" +#include "dataBlockHost.hpp" +#include "dump.hpp" +#include "input.hpp" + +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); + 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 || 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); + + 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 && 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 || 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" || 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 && 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]); ) + } + + if (input.CheckEntry("Forcing", "solenoidal")>=0) { + #if GEOMETRY == POLAR || GEOMETRY == CYLINDRICAL + IDEFIX_ERROR("Cannot have solenoidal forcing in polar in cylindrical geometry."); + #endif // GEOMETRY == POLAR || GEOMETRY == CYLINDRICAL + 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->means = IdefixArray2D("means", nForcingModes, COMPONENTS); + this->tcorrs = IdefixArray2D("tcorrs", nForcingModes, COMPONENTS); + this->epsilons = IdefixArray2D("epsilons", nForcingModes, COMPONENTS); + + 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); + #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.rng.state(), "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(); +} + +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; + } + + if (machNumber >= ZERO_F) { + idfx::cout << "Forcing: Mach number=" << machNumber << " ." << std::endl; + } else { + idfx::cout << "Forcing: epsilon=" << epsilon << " and tcorr=" << tcorr << " ." << std::endl; + } +} + +void Forcing::InitForcingParameters() { + idfx::pushRegion("Forcing::InitForcingParameters"); + + if (this->machNumber >= 0) { + real kf = HALF_F*(kmin+kmax); + #if HAVE_ENERGY + ComputeAverageSoundSpeed(); + #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; 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"); + + real kx0 = this->kx0; + real ky0 = this->ky0; + real kz0 = this->kz0; + 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; + Kokkos::complex unit_j(0., 1.); + int nForcingModes = this->nForcingModes; + ForcingType forcingType = this->forcingType; + + EXPAND( + 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], + 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; + } + idfx::popRegion(); +} + +// This function compute the required forcing field +void Forcing::ComputeForcing(real dt) { + idfx::pushRegion("Forcing::ComputeForcing"); + + ResetForcingTerms(); + if (haveSolenoidalForcing) { + ComputePristineForcing(dt); + ComputeSolenoidalForcing(dt); + forcingTerm = solenoidalForcingTerm; + } else { + ComputePristineForcing(dt); + forcingTerm = pristineForcingTerm; + } + oUprocesses.UpdateProcessesValues(dt); + idfx::popRegion(); +} + +// This function compute the pristine forcing field +void Forcing::ComputePristineForcing(real dt) { + idfx::pushRegion("Forcing::ComputePristineForcing"); + + EXPAND( + IdefixArray4D> 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 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]; + + 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; + }); + + 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); + + idfx::popRegion(); +} diff --git a/src/forcing/forcing.hpp b/src/forcing/forcing.hpp new file mode 100644 index 00000000..58288cd7 --- /dev/null +++ b/src/forcing/forcing.hpp @@ -0,0 +1,106 @@ +// *********************************************************************************** +// 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 +#include + +#include "idefix.hpp" +#include "input.hpp" +#include "OrnsteinUhlenbeckProcess.hpp" + +enum ForcingType {iso3D, iso2D}; + +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 + + void ResetForcingTerms(); ///< fill the forcing field with zeros. + + void ShowConfig(); ///< Show the forcing configuration + + // Forcing modes + EXPAND( + IdefixArray4D> forcingModesIdir; , + IdefixArray4D> forcingModesJdir; , + IdefixArray4D> forcingModesKdir; ) + std::vector> modeNames; + // Forcing terms + IdefixArray4D forcingTerm; + IdefixArray4D pristineForcingTerm; + IdefixArray4D solenoidalForcingTerm; + OrnsteinUhlenbeckProcesses oUprocesses; + + int write; + + private: + void ComputeAverageSoundSpeed(); ///< average sound speed of the current state + + 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 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 // FORCING_FORCING_HPP_ diff --git a/src/main.cpp b/src/main.cpp index b46c8a43..ac3ba50c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -156,6 +156,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); @@ -185,6 +186,7 @@ int main( int argc, char* argv[] ) { data.SetBoundaries(); data.Validate(); output.CheckForWrites(data); + if(data.haveForcing) data.forcing->InitForcingParameters(); } /////////////////////////////// diff --git a/src/output/dump.hpp b/src/output/dump.hpp index 2b8185ba..3d136de9 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; } } diff --git a/src/timeIntegrator.cpp b/src/timeIntegrator.cpp index e23808f0..867539e1 100644 --- a/src/timeIntegrator.cpp +++ b/src/timeIntegrator.cpp @@ -93,6 +93,21 @@ TimeIntegrator::TimeIntegrator(Input & input, DataBlock & data) { data.states["begin"].AllocateAs(data.states["current"]); } + 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(); + } + } + idfx::popRegion(); } @@ -346,6 +361,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(); @@ -368,6 +387,15 @@ void TimeIntegrator::Cycle(DataBlock &data) { MPI_SAFE_CALL(MPI_Wait(&dtReduce, MPI_STATUS_IGNORE)); } #endif +/* +if(data.haveForcing) { + if(data.forcing->stillHaveForcing) { + data.EvolveForcing(); + + // Back to using Vc + data.ConsToPrim(); + } + }*/ if(haveRKL && (ncycles%2)==0) { // Runge-Kutta-Legendre cycle data.EvolveRKLStage(); diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index f5276557..f97ddf52 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 00000000..5a5297c3 --- /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 00000000..71c7871b --- /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(Kokkos::Experimental::finite_max_v); + } + + /// 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_ diff --git a/test/HD/forcing/definitions.hpp b/test/HD/forcing/definitions.hpp new file mode 100644 index 00000000..486a4ea3 --- /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 00000000..72a7a6c5 --- /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 00000000..b00894ca --- /dev/null +++ b/test/HD/forcing/setup.cpp @@ -0,0 +1,39 @@ +#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 00000000..16c02206 --- /dev/null +++ b/test/HD/forcing/testme.py @@ -0,0 +1,46 @@ +#!/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)