diff --git a/entity.schema.json b/entity.schema.json index c91ccff73..d08641546 100644 --- a/entity.schema.json +++ b/entity.schema.json @@ -658,7 +658,7 @@ } }, "radiation": { - "description": "Radiative drag and photon emission parameters", + "description": "Radiative drag and emission parameters", "type": "object", "additionalProperties": false, "properties": { @@ -708,7 +708,7 @@ } }, "emission": { - "description": "Photon emission parameters", + "description": "Photon and pair emission parameters", "type": "object", "additionalProperties": false, "properties": { @@ -839,6 +839,180 @@ } } } + }, + "bethe_heitler": { + "description": "Bethe-Heitler pair production by protons on a prescribed isotropic photon field (the photons are not simulated); the emitting species is treated as protons (Z = 1) whatever its charge", + "type": "object", + "additionalProperties": false, + "required": [ + "electron_species", + "positron_species", + "optical_depth" + ], + "properties": { + "electron_species": { + "description": "Index of species for the created electron (mass 1, negative charge)", + "type": "integer", + "minimum": 1, + "x-entity": { + "type": "ushort [> 0]" + } + }, + "positron_species": { + "description": "Index of species for the created positron (mass 1, charge opposite to the electron species)", + "type": "integer", + "minimum": 1, + "x-entity": { + "type": "ushort [> 0]" + } + }, + "optical_depth": { + "description": "Nominal Bethe-Heitler optical depth over one code unit of length: `tau = n_ph * alpha * r_e^2 * L`, with `L` the physical length of one unit of the coordinates of `grid.extent` (n_ph = number density of the photons, alpha = fine-structure constant, r_e = classical electron radius)", + "type": "number", + "minimum": 0.0, + "x-entity": { + "type": "float [>= 0.0]", + "notes": [ + "Interaction rate of a particle per unit time is `tau * J(Gamma_p)` with the tabulated dimensionless rate `J`" + ] + } + }, + "mass_ratio": { + "description": "Physical proton-to-electron mass ratio: an emitting particle of kinetic energy `K` (units of `m_e c^2`) is treated as a proton of Lorentz factor `Gamma_p = 1 + K / mass_ratio`", + "type": "number", + "exclusiveMinimum": 0.0, + "default": 1836.15267343, + "x-entity": { + "type": "float [> 0.0]" + } + }, + "pair_weight": { + "description": "Weight of the created leptons relative to the emitting particle (each macro-pair stands for `pair_weight` interactions)", + "type": "number", + "exclusiveMinimum": 0.0, + "default": 1.0, + "x-entity": { + "type": "float [> 0.0]", + "notes": [ + "Values other than 1 require `particles.use_weights = true`" + ] + } + }, + "max_probability": { + "description": "Largest admissible interaction probability per particle per timestep (at most one interaction per step is drawn)", + "type": "number", + "exclusiveMinimum": 0.0, + "maximum": 1.0, + "default": 0.1, + "x-entity": { + "type": "float [0.0 -> 1.0]", + "notes": [ + "The run stops if `tau * J * dt / pair_weight` exceeds it anywhere on the tables" + ] + } + }, + "max_loss_fraction": { + "description": "Largest fraction of its kinetic energy a particle may lose in one interaction; outcomes above it are skipped and counted", + "type": "number", + "exclusiveMinimum": 0.0, + "exclusiveMaximum": 1.0, + "default": 0.04, + "x-entity": { + "type": "float [0.0 -> 1.0]" + } + }, + "gamma_max": { + "description": "Upper edge in `Gamma_p` of the rate tables; particles above it do not interact (and are counted)", + "type": "number", + "minimum": 0.0, + "default": 0.0, + "x-entity": { + "type": "float [>= 0.0]", + "notes": [ + "0 = largest value for which the rest-frame photon energy stays below min(0.05 * mass_ratio, 1000) `m_e c^2`" + ] + } + }, + "photon_spectrum": { + "description": "Spectrum of the photon field in the simulation frame", + "anyOf": [ + { + "enum": [ + "mono", + "powerlaw", + "blackbody" + ] + }, + { + "type": "string", + "pattern": "(?i)^(mono|powerlaw|blackbody)$" + } + ], + "default": "mono", + "x-entity": { + "type": "string", + "notes": [ + "Photon energies are in units of `m_e c^2` and must stay below 2" + ] + } + }, + "photon_energy": { + "description": "Photon energy for `photon_spectrum = \"mono\"`", + "type": "number", + "exclusiveMinimum": 0.0, + "exclusiveMaximum": 2.0, + "x-entity": { + "type": "float [0.0 -> 2.0]", + "notes": [ + "[required] for `photon_spectrum = \"mono\"`" + ] + } + }, + "photon_energy_min": { + "description": "Lower end of the spectrum for `photon_spectrum = \"powerlaw\"` or `\"blackbody\"`", + "type": "number", + "minimum": 0.0, + "x-entity": { + "type": "float [>= 0.0]", + "notes": [ + "[required] for `photon_spectrum = \"powerlaw\"`; defaults to 0 for `\"blackbody\"`" + ] + } + }, + "photon_energy_max": { + "description": "Upper end of the spectrum for `photon_spectrum = \"powerlaw\"` or `\"blackbody\"`", + "type": "number", + "exclusiveMinimum": 0.0, + "exclusiveMaximum": 2.0, + "x-entity": { + "type": "float [0.0 -> 2.0]", + "notes": [ + "[required] for `photon_spectrum = \"powerlaw\"` and `\"blackbody\"`" + ] + } + }, + "photon_index": { + "description": "Index `p` of the number spectrum `dn / d eps ~ eps^(-p)` for `photon_spectrum = \"powerlaw\"`", + "type": "number", + "x-entity": { + "type": "float", + "notes": [ + "[required] for `photon_spectrum = \"powerlaw\"`" + ] + } + }, + "photon_temperature": { + "description": "Temperature `k T / m_e c^2` for `photon_spectrum = \"blackbody\"`", + "type": "number", + "exclusiveMinimum": 0.0, + "x-entity": { + "type": "float [> 0.0]", + "notes": [ + "[required] for `photon_spectrum = \"blackbody\"`" + ] + } + } + } } } } @@ -1415,12 +1589,13 @@ "None", "Synchrotron", "Compton", + "Bethe_Heitler", "Custom" ] }, { "type": "string", - "pattern": "(?i)^(None|Synchrotron|Compton|Custom)$" + "pattern": "(?i)^(None|Synchrotron|Compton|Bethe_Heitler|Custom)$" } ], "default": "None", diff --git a/input.default.toml b/input.default.toml index f5ac994b7..ff6f87944 100644 --- a/input.default.toml +++ b/input.default.toml @@ -254,7 +254,7 @@ # @from: `scales.larmor0` # @value: `1 / larmor0` -# Radiative drag and photon emission parameters +# Radiative drag and emission parameters [radiation] # Radiation reaction (drag) parameters @@ -278,7 +278,7 @@ # "compton"` gamma_rad = 1.0 - # Photon emission parameters + # Photon and pair emission parameters [radiation.emission] # Synchrotron emission parameters @@ -354,6 +354,90 @@ # @from: `.gamma_qed` # @value: `(1 / gamma_qed)^2` + # Bethe-Heitler pair production by protons on a prescribed isotropic photon + # field (the photons are not simulated); the emitting species is treated as + # protons (Z = 1) whatever its charge + [radiation.emission.bethe_heitler] + # Index of species for the created electron (mass 1, negative charge) + # @required + # @type: ushort [> 0] + electron_species = 1 + # Index of species for the created positron (mass 1, charge opposite to + # the electron species) + # @required + # @type: ushort [> 0] + positron_species = 1 + # Nominal Bethe-Heitler optical depth over one code unit of length: `tau = + # n_ph * alpha * r_e^2 * L`, with `L` the physical length of one unit of + # the coordinates of `grid.extent` (n_ph = number density of the photons, + # alpha = fine-structure constant, r_e = classical electron radius) + # @required + # @type: float [>= 0.0] + # @note: Interaction rate of a particle per unit time is `tau * + # J(Gamma_p)` with the tabulated dimensionless rate `J` + optical_depth = 0.0 + # Physical proton-to-electron mass ratio: an emitting particle of kinetic + # energy `K` (units of `m_e c^2`) is treated as a proton of Lorentz factor + # `Gamma_p = 1 + K / mass_ratio` + # @type: float [> 0.0] + # @default: 1836.15267343 + mass_ratio = 1836.15267343 + # Weight of the created leptons relative to the emitting particle (each + # macro-pair stands for `pair_weight` interactions) + # @type: float [> 0.0] + # @default: 1.0 + # @note: Values other than 1 require `particles.use_weights = true` + pair_weight = 1.0 + # Largest admissible interaction probability per particle per timestep (at + # most one interaction per step is drawn) + # @type: float [0.0 -> 1.0] + # @default: 0.1 + # @note: The run stops if `tau * J * dt / pair_weight` exceeds it + # anywhere on the tables + max_probability = 0.1 + # Largest fraction of its kinetic energy a particle may lose in one + # interaction; outcomes above it are skipped and counted + # @type: float [0.0 -> 1.0] + # @default: 0.04 + max_loss_fraction = 0.04 + # Upper edge in `Gamma_p` of the rate tables; particles above it do not + # interact (and are counted) + # @type: float [>= 0.0] + # @default: 0.0 + # @note: 0 = largest value for which the rest-frame photon energy stays + # below min(0.05 * mass_ratio, 1000) `m_e c^2` + gamma_max = 0.0 + # Spectrum of the photon field in the simulation frame + # @type: string + # @default: "mono" + # @enum: "mono", "powerlaw", "blackbody" + # @note: Photon energies are in units of `m_e c^2` and must stay below 2 + photon_spectrum = "mono" + # Photon energy for `photon_spectrum = "mono"` + # @type: float [0.0 -> 2.0] + # @note: [required] for `photon_spectrum = "mono"` + photon_energy = 1.0 + # Lower end of the spectrum for `photon_spectrum = "powerlaw"` or + # `"blackbody"` + # @type: float [>= 0.0] + # @note: [required] for `photon_spectrum = "powerlaw"`; defaults to 0 + # for `"blackbody"` + photon_energy_min = 0.0 + # Upper end of the spectrum for `photon_spectrum = "powerlaw"` or + # `"blackbody"` + # @type: float [0.0 -> 2.0] + # @note: [required] for `photon_spectrum = "powerlaw"` and `"blackbody"` + photon_energy_max = 1.0 + # Index `p` of the number spectrum `dn / d eps ~ eps^(-p)` for + # `photon_spectrum = "powerlaw"` + # @type: float + # @note: [required] for `photon_spectrum = "powerlaw"` + photon_index = 0.0 + # Temperature `k T / m_e c^2` for `photon_spectrum = "blackbody"` + # @type: float [> 0.0] + # @note: [required] for `photon_spectrum = "blackbody"` + photon_temperature = 1.0 + # Parameters for two-body interactions [two_body] # Nominal Thomson optical depth: `tau = n0 * sigma_T * 1` over a distance of 1 @@ -612,7 +696,7 @@ # Particle emission policy for the species # @type: string # @default: "None" - # @enum: "None", "Synchrotron", "Compton", "Custom" + # @enum: "None", "Synchrotron", "Compton", "Bethe_Heitler", "Custom" # @note: Only one emission mechanism allowed # @note: Appropriate radiation drag flag will be applied automatically # (unless explicitly set to "None") diff --git a/src/archetypes/emission/bethe_heitler.h b/src/archetypes/emission/bethe_heitler.h new file mode 100644 index 000000000..559d6c835 --- /dev/null +++ b/src/archetypes/emission/bethe_heitler.h @@ -0,0 +1,858 @@ +/** + * @file archetypes/emission/bethe_heitler.h + * @brief Emission policy for Bethe-Heitler pair production by protons on a + * prescribed isotropic photon field + * @implements + * - arch::emission::bh::Counters + * - arch::emission::bh::Tables + * - arch::emission::bh::GetTables -> Tables& + * - arch::emission::bh::GetCounters -> Counters + * - arch::emission::BetheHeitler<> + * @namespaces: + * - arch::emission:: + * - arch::emission::bh:: + * + * @note + * The process is p + gamma -> p + e- + e+ on a static photon field that is + * not a species of the simulation. An emitting particle of mass `mu_d` (in + * units of the electron mass) and momentum `u` (in units of its own `m c`) + * has the kinetic energy `K = mu_d u^2 / (gamma + 1)` in units of `m_e c^2` + * and is treated as a proton of Lorentz factor `Gamma_p = 1 + K / mass_ratio`, + * so that a reduced mass ratio in the dynamics does not change the energy + * scale of the process. The cross sections are those of a proton (Z = 1): the + * charge of the emitting species does not enter. + * + * @note + * At each timestep, for each emitting particle: + * - the probability of one interaction is + * p = optical_depth * J(Gamma_p) * dt / pair_weight + * with J the tabulated interaction rate (units of alpha r_e^2 c per unit + * photon density) and `optical_depth = n_ph alpha r_e^2 L`, L being the + * physical length of one code unit of length (the unit of the extent of + * the grid); one uniform number decides (at most one interaction per + * particle per step, so `p` has to be small); + * - the outcome (photon energy and the two lepton momenta) is drawn from + * the Born cross sections in the rest frame of the proton and boosted to + * the simulation frame; + * - the particle loses `pair_weight * D` of kinetic energy along its + * momentum, D = E_- + E_+ - eps being the energy of the pair minus that + * of the absorbed photon; + * - one electron and one positron of weight `pair_weight * weight` are + * inserted at the position of the particle. + * + * @note + * The new leptons are charged. The policy writes their previous position + * equal to their position, so that the current deposit sees no displacement + * for a lepton that is not pushed in the step in which it is created (lepton + * species listed before the emitting species), and the pusher overwrites it + * otherwise. Charge is conserved in both cases. + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_H + +#include "enums.h" +#include "global.h" + +#include "arch/kokkos_aliases.h" +#include "traits/metric.h" +#include "utils/error.h" +#include "utils/formatting.h" +#include "utils/log.h" +#include "utils/numeric.h" +#include "utils/param_container.h" + +#include "archetypes/emission/bethe_heitler/bh_born_qk.h" +#include "archetypes/emission/bethe_heitler/bh_event_host.h" +#include "archetypes/emission/bethe_heitler/bh_interpolate.h" +#include "archetypes/emission/bethe_heitler/bh_physics.h" +#include "archetypes/emission/bethe_heitler/bh_sampler_device.h" +#include "archetypes/emission/bethe_heitler/bh_tables_device.h" +#include "framework/containers/particles.h" +#include "kernels/injectors.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace arch::emission { + using namespace ntt; + + namespace bh { + + /** + * @brief Event counters, accumulated on the device since the tables were built + * @note With MPI these are the numbers of the calling rank + */ + struct Counters { + // pairs created + unsigned long long pairs { 0 }; + // particle-steps above the upper edge of the tables (no interaction) + unsigned long long above_tables { 0 }; + // particle-steps with a probability above `max_probability` (an error) + unsigned long long probability_exceeded { 0 }; + // interactions skipped because the loss exceeded `max_loss_fraction` + unsigned long long loss_bound_skipped { 0 }; + // interactions skipped because a lepton species was full + unsigned long long capacity_dropped { 0 }; + // energy of the absorbed photons, sum of weight * eps [m_e c^2] + double absorbed_energy { 0.0 }; + }; + + enum CounterIndex : int { + cPairs = 0, + cAboveTables = 1, + cProbabilityExceeded = 2, + cLossBoundSkipped = 3, + cCapacityDropped = 4, + cTotal = 5 + }; + + /** + * @brief Tables of the process and its counters: built once per run on + * the first call of `GetTables`, kept on the device between + * steps, released when Kokkos finalizes + */ + struct Tables { + // interaction rate J(Gamma_p) on the device + ::arch::bh::HadronicTables rates; + // rest-frame sampler of the outcome on the device + ::arch::bh::SamplerTables sampler; + // nodes of the rate tables on the host + ::arch::bh::HadronicTablesHost host; + // largest photon energy of the spectrum [m_e c^2] + double photon_energy_max { 0.0 }; + + array_t counters; + array_t absorbed_energy; + + // parameters the tables were built with, and those last checked + std::string tables_key, checks_key; + + /** + * @brief Interaction rate J(Gamma_p) [alpha r_e^2 c per unit photon + * density]; zero below the lower edge of the tables + */ + auto rate(double gamma_p) const -> double { + return ::arch::bh::interpolate_rate_host(host, gamma_p); + } + + /** + * @brief Energy-loss rate I(Gamma_p) = J [m_e c^2 alpha r_e^2 c + * per unit photon density] + */ + auto loss_rate(double gamma_p) const -> double { + return ::arch::bh::interpolate_loss_host(host, gamma_p); + } + + /** + * @brief Mean loss per interaction (Gamma_p) [m_e c^2] + */ + auto mean_loss(double gamma_p) const -> double { + double mean_loss { 0.0 }, mean_photon_energy { 0.0 }; + ::arch::bh::interpolate_outcome_host(host, + gamma_p, + mean_loss, + mean_photon_energy); + return mean_loss; + } + }; + + namespace detail { + inline auto tables_ptr() -> std::unique_ptr& { + static std::unique_ptr tables; + return tables; + } + + template + auto get(const prm::Parameters& params, const std::string& name) -> T { + return params.template get("radiation.emission.bethe_heitler." + name); + } + + inline auto get_double(const prm::Parameters& params, + const std::string& name) -> double { + const auto value = static_cast(get(params, name)); + // comparisons with a NaN are false: it would pass the range checks + // and switch the process off without a word + raise::ErrorIf(not std::isfinite(value), + "Bethe-Heitler " + name + " must be finite", + HERE); + return value; + } + + inline auto make_bath(const prm::Parameters& params) + -> std::shared_ptr { + ::arch::bh::BathSpec spec; + spec.type = get(params, "photon_spectrum"); + spec.eps0 = get_double(params, "photon_energy"); + spec.eps_min = get_double(params, "photon_energy_min"); + spec.eps_max = get_double(params, "photon_energy_max"); + spec.index = get_double(params, "photon_index"); + spec.theta = get_double(params, "photon_temperature"); + raise::ErrorIf(spec.type != "mono" and spec.type != "powerlaw" and + spec.type != "blackbody", + "Bethe-Heitler photon_spectrum must be mono, powerlaw " + "or blackbody", + HERE); + return ::arch::bh::make_bath(spec); + } + + inline auto tables_key(const prm::Parameters& params) -> std::string { + return fmt::format("%s|%.17g|%.17g|%.17g|%.17g|%.17g|%.17g|%.17g", + get(params, "photon_spectrum").c_str(), + get_double(params, "photon_energy"), + get_double(params, "photon_energy_min"), + get_double(params, "photon_energy_max"), + get_double(params, "photon_index"), + get_double(params, "photon_temperature"), + get_double(params, "mass_ratio"), + get_double(params, "gamma_max")); + } + + inline auto checks_key(const prm::Parameters& params, real_t dt) + -> std::string { + return fmt::format( + "%.17g|%.17g|%.17g|%.17g|%.17g|%d", + get_double(params, "optical_depth"), + get_double(params, "pair_weight"), + get_double(params, "max_probability"), + get_double(params, "max_loss_fraction"), + static_cast(dt), + static_cast(params.template get("particles.use_weights"))); + } + + inline auto build(const prm::Parameters& params) -> std::unique_ptr { + auto T = std::make_unique(); + T->tables_key = tables_key(params); + // host threads of this build: the processors the calling thread may + // run on (see `thread_limit`), and with a threaded host execution + // space at most its threads + unsigned n_threads = ::arch::bh::rf::thread_limit(); +#if defined(KOKKOS_ENABLE_OPENMP) || defined(KOKKOS_ENABLE_THREADS) + n_threads = std::max( + 1u, + std::min(n_threads, + static_cast( + Kokkos::DefaultHostExecutionSpace().concurrency()))); +#endif + try { + // the table of the Born cross section is built at its first use: + // here, unless something has read it before + ::arch::bh::born::table(n_threads); + const auto bath = make_bath(params); + ::arch::bh::Quadrature quadrature; + const ::arch::bh::BetheHeitlerRates rates(bath, quadrature); + T->host = ::arch::bh::build_tables(rates, + get_double(params, "mass_ratio"), + get_double(params, "gamma_max")); + ::arch::bh::validate_tables(T->host); + T->rates = ::arch::bh::mirror_tables_to_device(T->host); + T->sampler = ::arch::bh::build_sampler_tables(*bath, T->host, n_threads); + T->photon_energy_max = bath->eps_cut(); + } catch (const std::exception& e) { + raise::Error(fmt::format("Bethe-Heitler tables: %s", e.what()), HERE); + } + T->counters = array_t { "bh_counters", cTotal }; + T->absorbed_energy = array_t { "bh_absorbed_energy", 1 }; + return T; + } + + /** + * @brief Startup checks of the parameters against the tables, and the + * report of the numbers they are made with + */ + inline void check(Tables& T, const prm::Parameters& params, real_t dt) { + const auto tau = get_double(params, "optical_depth"); + const auto pair_weight = get_double(params, "pair_weight"); + const auto p_max = get_double(params, "max_probability"); + const auto f_max = get_double(params, "max_loss_fraction"); + const auto mass_ratio = get_double(params, "mass_ratio"); + + raise::ErrorIf((pair_weight != 1.0) and + not params.template get("particles.use_weights"), + "Bethe-Heitler pair_weight != 1 requires " + "particles.use_weights = true", + HERE); + + // largest rate and smallest admissible pair weight over the tables + double rate_max { 0.0 }, gamma_at_rate_max { 0.0 }; + double pair_weight_max { 0.0 }; + for (std::size_t i = 0; i < T.host.size(); ++i) { + if (T.host.J[i] > rate_max) { + rate_max = T.host.J[i]; + gamma_at_rate_max = T.host.gamma[i]; + } + // no outcome may cost more than max_loss_fraction of the kinetic energy + const auto a_max = ::arch::bh::event::a_max(T.host.gamma[i], + T.photon_energy_max, + mass_ratio, + f_max); + if (i == 0 or a_max < pair_weight_max) { + pair_weight_max = a_max; + } + } + const auto probability_max = tau * rate_max * static_cast(dt) / + pair_weight; + info::Print( + fmt::format( + "Bethe-Heitler emission: tables on %.6g <= Gamma_p <= %.6g " + "(%d nodes); probability per step <= %.4g (at Gamma_p = %.6g; " + "max_probability = %.4g); pairs per emitter per unit time <= " + "%.6g; pair_weight = %.4g (no outcome is skipped for pair_weight " + "<= %.4g)", + T.host.gamma_min, + T.host.gamma_max, + static_cast(T.host.size()), + probability_max, + gamma_at_rate_max, + p_max, + tau * rate_max / pair_weight, + pair_weight, + pair_weight_max), + false); + raise::ErrorIf( + probability_max > p_max, + fmt::format("Bethe-Heitler emission probability per step reaches " + "%.4g > max_probability = %.4g: reduce the timestep or " + "the optical depth, or raise pair_weight", + probability_max, + p_max), + HERE); + T.checks_key = checks_key(params, dt); + } + } // namespace detail + + namespace detail { + /** + * @brief Warning in the log of this rank, the first time `condition` + * holds for the counter `index` + */ + inline void warn_once(int index, bool condition, const std::string& msg) { + static bool warned[cTotal] {}; + if (condition and not warned[index]) { + warned[index] = true; + raise::Warning(msg, HERE, false); + } + } + } // namespace detail + + /** + * @brief Tables of the run: built on the first call, rebuilt only if the + * photon spectrum, the mass ratio or the range have changed + * @note Raises if the timestep is not finite, or if the probability of + * an interaction per step exceeds `max_probability` somewhere on + * the tables + */ + inline auto GetTables(const prm::Parameters& params, real_t dt) -> Tables& { + // a NaN would pass the bound on the probability (comparisons with a NaN + // are false), and so would minus infinity + raise::ErrorIf(not std::isfinite(dt), + "Bethe-Heitler: the timestep must be finite", + HERE); + static bool hook_registered { false }; + if (not hook_registered) { + // the device views must be released before Kokkos finalizes + Kokkos::push_finalize_hook([]() { + detail::tables_ptr().reset(); + }); + hook_registered = true; + } + auto& tables = detail::tables_ptr(); + if (tables == nullptr or tables->tables_key != detail::tables_key(params)) { + tables = detail::build(params); + } + if (tables->checks_key != detail::checks_key(params, dt)) { + detail::check(*tables, params, dt); + } + return *tables; + } + + /** + * @brief Counters of the run so far (zero if the policy was never used) + */ + inline auto GetCounters() -> Counters { + Counters c; + const auto& tables = detail::tables_ptr(); + if (tables == nullptr) { + return c; + } + auto counters_h = Kokkos::create_mirror_view(tables->counters); + Kokkos::deep_copy(counters_h, tables->counters); + auto energy_h = Kokkos::create_mirror_view(tables->absorbed_energy); + Kokkos::deep_copy(energy_h, tables->absorbed_energy); + c.pairs = counters_h(cPairs); + c.above_tables = counters_h(cAboveTables); + c.probability_exceeded = counters_h(cProbabilityExceeded); + c.loss_bound_skipped = counters_h(cLossBoundSkipped); + c.capacity_dropped = counters_h(cCapacityDropped); + c.absorbed_energy = energy_h(0); + return c; + } + + } // namespace bh + + template + struct BetheHeitler { + struct Payload { + // slot of the new pair past the current end of the lepton species + npart_t ticket { 0u }; + // lepton momenta [m_e c] and absorbed photon energy [m_e c^2] + real_t u_electron[3] { ZERO, ZERO, ZERO }; + real_t u_positron[3] { ZERO, ZERO, ZERO }; + real_t photon_energy { ZERO }; + }; + + const spidx_t electron_index, positron_index; + + // mass of the emitting species in units of the electron mass + const double mu_d; + // physical proton-to-electron mass ratio + const double mass_ratio; + // optical_depth * dt / pair_weight + const double probability_norm; + const double pair_weight; + const double max_probability; + const double max_loss_fraction; + + ::arch::bh::HadronicTables rates; + ::arch::bh::SamplerTables sampler; + + array_t electron_i1, electron_i2, electron_i3; + array_t electron_dx1, electron_dx2, electron_dx3; + array_t electron_i1_prev, electron_i2_prev, electron_i3_prev; + array_t electron_dx1_prev, electron_dx2_prev, electron_dx3_prev; + array_t electron_ux1, electron_ux2, electron_ux3; + array_t electron_phi; + array_t electron_weight; + array_t electron_tag; + array_t electron_pld_i; + + array_t positron_i1, positron_i2, positron_i3; + array_t positron_dx1, positron_dx2, positron_dx3; + array_t positron_i1_prev, positron_i2_prev, positron_i3_prev; + array_t positron_dx1_prev, positron_dx2_prev, positron_dx3_prev; + array_t positron_ux1, positron_ux2, positron_ux3; + array_t positron_phi; + array_t positron_weight; + array_t positron_tag; + array_t positron_pld_i; + + // tickets taken in this step (may exceed the capacity) + array_t tickets { "bh_tickets" }; + const npart_t electron_offset, positron_offset; + const npart_t electron_cntr, positron_cntr; + // free slots common to the two lepton species + const npart_t capacity; + const npart_t domain_idx; + const bool electron_use_tracking, positron_use_tracking; + + array_t counters; + array_t absorbed_energy; + + random_number_pool_t random_pool; + + /** + * @note `sp_mass` and `dt` are taken as given: the timestep is checked in + * `bh::GetTables` and the mass of the emitting species by the + * factory of the policy (`kernel::sr::MakePusherPolicyEmission`) + */ + BetheHeitler(Particles& electron_species, + Particles& positron_species, + spidx_t electron_index, + spidx_t positron_index, + float sp_mass, + real_t dt, + npart_t domain_idx, + const prm::Parameters& params, + bh::Tables& tables, + random_number_pool_t& random_pool) + : electron_index { electron_index } + , positron_index { positron_index } + , mu_d { static_cast(sp_mass) } + , mass_ratio { bh::detail::get_double(params, "mass_ratio") } + , probability_norm { bh::detail::get_double(params, "optical_depth") * + static_cast(dt) / + bh::detail::get_double(params, "pair_weight") } + , pair_weight { bh::detail::get_double(params, "pair_weight") } + , max_probability { bh::detail::get_double(params, "max_probability") } + , max_loss_fraction { bh::detail::get_double(params, "max_loss_fraction") } + , rates { tables.rates } + , sampler { tables.sampler } + , electron_i1 { electron_species.i1 } + , electron_i2 { electron_species.i2 } + , electron_i3 { electron_species.i3 } + , electron_dx1 { electron_species.dx1 } + , electron_dx2 { electron_species.dx2 } + , electron_dx3 { electron_species.dx3 } + , electron_i1_prev { electron_species.i1_prev } + , electron_i2_prev { electron_species.i2_prev } + , electron_i3_prev { electron_species.i3_prev } + , electron_dx1_prev { electron_species.dx1_prev } + , electron_dx2_prev { electron_species.dx2_prev } + , electron_dx3_prev { electron_species.dx3_prev } + , electron_ux1 { electron_species.ux1 } + , electron_ux2 { electron_species.ux2 } + , electron_ux3 { electron_species.ux3 } + , electron_phi { electron_species.phi } + , electron_weight { electron_species.weight } + , electron_tag { electron_species.tag } + , electron_pld_i { electron_species.pld_i } + , positron_i1 { positron_species.i1 } + , positron_i2 { positron_species.i2 } + , positron_i3 { positron_species.i3 } + , positron_dx1 { positron_species.dx1 } + , positron_dx2 { positron_species.dx2 } + , positron_dx3 { positron_species.dx3 } + , positron_i1_prev { positron_species.i1_prev } + , positron_i2_prev { positron_species.i2_prev } + , positron_i3_prev { positron_species.i3_prev } + , positron_dx1_prev { positron_species.dx1_prev } + , positron_dx2_prev { positron_species.dx2_prev } + , positron_dx3_prev { positron_species.dx3_prev } + , positron_ux1 { positron_species.ux1 } + , positron_ux2 { positron_species.ux2 } + , positron_ux3 { positron_species.ux3 } + , positron_phi { positron_species.phi } + , positron_weight { positron_species.weight } + , positron_tag { positron_species.tag } + , positron_pld_i { positron_species.pld_i } + , electron_offset { electron_species.npart() } + , positron_offset { positron_species.npart() } + , electron_cntr { electron_species.counter() } + , positron_cntr { positron_species.counter() } + , capacity { std::min(electron_species.maxnpart() - electron_species.npart(), + positron_species.maxnpart() - positron_species.npart()) } + , domain_idx { domain_idx } + , electron_use_tracking { electron_species.use_tracking() } + , positron_use_tracking { positron_species.use_tracking() } + , counters { tables.counters } + , absorbed_energy { tables.absorbed_energy } + , random_pool { random_pool } {} + + auto emitted_species_indices() const -> std::vector { + return { electron_index, positron_index }; + } + + /** + * @brief Number of pairs inserted in this step (tickets beyond the + * capacity were refused in `shouldEmit`) + * @note Called on the host after the pusher kernel: it also raises the + * error for a probability above `max_probability`, and warns once + * when pairs start being skipped + */ + auto numbers_injected() const -> std::vector { + auto tickets_h = Kokkos::create_mirror_view(tickets); + Kokkos::deep_copy(tickets_h, tickets); + auto counters_h = Kokkos::create_mirror_view(counters); + Kokkos::deep_copy(counters_h, counters); + raise::ErrorIf( + counters_h(bh::cProbabilityExceeded) > 0u, + fmt::format("Bethe-Heitler emission probability per step exceeded " + "max_probability = %.4g for %llu particle-steps", + max_probability, + counters_h(bh::cProbabilityExceeded)), + HERE); + bh::detail::warn_once( + bh::cCapacityDropped, + counters_h(bh::cCapacityDropped) > 0u, + fmt::format("Bethe-Heitler pairs are dropped: lepton species %d or %d " + "is full (increase maxnpart)", + static_cast(electron_index), + static_cast(positron_index))); + bh::detail::warn_once( + bh::cAboveTables, + counters_h(bh::cAboveTables) > 0u, + "Bethe-Heitler: particles above the upper edge of the tables do not " + "interact (see gamma_max)"); + bh::detail::warn_once( + bh::cLossBoundSkipped, + counters_h(bh::cLossBoundSkipped) > 0u, + "Bethe-Heitler: interactions above max_loss_fraction are skipped " + "(reduce pair_weight)"); + const auto n_injected = std::min(tickets_h(), capacity); + return { n_injected, n_injected }; + } + + /** + * @brief Decide whether the particle interacts in this step, and if so + * draw the outcome and compute the recoil + * + * @param u_Ph Momentum of the particle in units of its own m c + * @param delta_u_Ph Output: the recoil (same units), along `u_Ph` + * @param payload Output: slot and momenta of the new leptons + * + * @returns (emit, recoil): both true for an interaction, both false otherwise + */ + Inline auto shouldEmit(const coord_t&, + const coord_t&, + const vec_t& u_Ph, + const vec_t&, + const vec_t&, + vec_t& delta_u_Ph, + Payload& payload) const -> Kokkos::pair { + const double ux = static_cast(u_Ph[0]); + const double uy = static_cast(u_Ph[1]); + const double uz = static_cast(u_Ph[2]); + const double u_sqr = ux * ux + uy * uy + uz * uz; + if (not(u_sqr > 0.0)) { + return Kokkos::make_pair(false, false); + } + const double u_mag = math::sqrt(u_sqr); + const double gamma = math::sqrt(1.0 + u_sqr); + // kinetic energy [m_e c^2] and Lorentz factor of the equivalent proton + const double K = mu_d * u_sqr / (gamma + 1.0); + const double Gamma_p = 1.0 + K / mass_ratio; + + if (Gamma_p < rates.gamma_min) { + return Kokkos::make_pair(false, false); + } + if (Gamma_p > rates.gamma_max) { + Kokkos::atomic_inc(&counters(bh::cAboveTables)); + return Kokkos::make_pair(false, false); + } + const double probability = probability_norm * rates.J(Gamma_p); + if (not(probability > 0.0)) { + return Kokkos::make_pair(false, false); + } + if (probability > max_probability) { + Kokkos::atomic_inc(&counters(bh::cProbabilityExceeded)); + return Kokkos::make_pair(false, false); + } + + auto rand_gen = random_pool.get_state(); + if (not(rand_gen.drand() < probability)) { + random_pool.free_state(rand_gen); + return Kokkos::make_pair(false, false); + } + // outcome in the frame with z along the momentum of the particle + ::arch::bh::SampledPair outcome; + sampler.draw(Gamma_p, rand_gen, outcome); + random_pool.free_state(rand_gen); + + if (pair_weight * outcome.D > max_loss_fraction * K) { + Kokkos::atomic_inc(&counters(bh::cLossBoundSkipped)); + return Kokkos::make_pair(false, false); + } + + const npart_t ticket = Kokkos::atomic_fetch_add(&tickets(), + static_cast(1)); + if (ticket >= capacity) { + Kokkos::atomic_inc(&counters(bh::cCapacityDropped)); + return Kokkos::make_pair(false, false); + } + + // recoil along the momentum + const double nx = ux / u_mag, ny = uy / u_mag, nz = uz / u_mag; + const double K_new = K - pair_weight * outcome.D; + const double u_new = math::sqrt(K_new * (K_new + 2.0 * mu_d)) / mu_d; + delta_u_Ph[0] = static_cast((u_new - u_mag) * nx); + delta_u_Ph[1] = static_cast((u_new - u_mag) * ny); + delta_u_Ph[2] = static_cast((u_new - u_mag) * nz); + + // rotate the lepton momenta to the simulation frame: (e1, e2, n) + double e1x, e1y, e1z; + if (math::abs(nx) < 0.9) { + e1x = 1.0 - nx * nx; + e1y = -nx * ny; + e1z = -nx * nz; + } else { + e1x = -ny * nx; + e1y = 1.0 - ny * ny; + e1z = -ny * nz; + } + const double e1_norm = math::sqrt(e1x * e1x + e1y * e1y + e1z * e1z); + e1x /= e1_norm; + e1y /= e1_norm; + e1z /= e1_norm; + const double e2x = ny * e1z - nz * e1y; + const double e2y = nz * e1x - nx * e1z; + const double e2z = nx * e1y - ny * e1x; + + payload.ticket = ticket; + payload.u_electron[0] = static_cast( + outcome.pm[0] * e1x + outcome.pm[1] * e2x + outcome.pm[2] * nx); + payload.u_electron[1] = static_cast( + outcome.pm[0] * e1y + outcome.pm[1] * e2y + outcome.pm[2] * ny); + payload.u_electron[2] = static_cast( + outcome.pm[0] * e1z + outcome.pm[1] * e2z + outcome.pm[2] * nz); + payload.u_positron[0] = static_cast( + outcome.pp[0] * e1x + outcome.pp[1] * e2x + outcome.pp[2] * nx); + payload.u_positron[1] = static_cast( + outcome.pp[0] * e1y + outcome.pp[1] * e2y + outcome.pp[2] * ny); + payload.u_positron[2] = static_cast( + outcome.pp[0] * e1z + outcome.pp[1] * e2z + outcome.pp[2] * nz); + payload.photon_energy = static_cast(outcome.eps); + + Kokkos::atomic_inc(&counters(bh::cPairs)); + return Kokkos::make_pair(true, true); + } + + /** + * @brief Insert the electron and the positron at the position of the + * emitting particle + * @note `direction` (minus the direction of the recoil) is not used: the + * lepton momenta come from the payload + */ + Inline void emit(const tuple_t& xi_Cd, + const tuple_t& dxi_Cd, + const vec_t&, + real_t weight, + real_t phi, + const Payload& payload) const { + const auto pair_weight_r = static_cast(pair_weight) * weight; + insert(electron_offset + payload.ticket, + electron_i1, + electron_i2, + electron_i3, + electron_dx1, + electron_dx2, + electron_dx3, + electron_i1_prev, + electron_i2_prev, + electron_i3_prev, + electron_dx1_prev, + electron_dx2_prev, + electron_dx3_prev, + electron_ux1, + electron_ux2, + electron_ux3, + electron_phi, + electron_weight, + electron_tag, + electron_pld_i, + xi_Cd, + dxi_Cd, + { payload.u_electron[0], payload.u_electron[1], payload.u_electron[2] }, + pair_weight_r, + phi, + electron_use_tracking, + electron_cntr + payload.ticket); + insert(positron_offset + payload.ticket, + positron_i1, + positron_i2, + positron_i3, + positron_dx1, + positron_dx2, + positron_dx3, + positron_i1_prev, + positron_i2_prev, + positron_i3_prev, + positron_dx1_prev, + positron_dx2_prev, + positron_dx3_prev, + positron_ux1, + positron_ux2, + positron_ux3, + positron_phi, + positron_weight, + positron_tag, + positron_pld_i, + xi_Cd, + dxi_Cd, + { payload.u_positron[0], payload.u_positron[1], payload.u_positron[2] }, + pair_weight_r, + phi, + positron_use_tracking, + positron_cntr + payload.ticket); + Kokkos::atomic_add(&absorbed_energy(0), + static_cast(pair_weight_r) * + static_cast(payload.photon_energy)); + } + + private: + Inline void insert(npart_t p, + const array_t& i1, + const array_t& i2, + const array_t& i3, + const array_t& dx1, + const array_t& dx2, + const array_t& dx3, + const array_t& i1_prev, + const array_t& i2_prev, + const array_t& i3_prev, + const array_t& dx1_prev, + const array_t& dx2_prev, + const array_t& dx3_prev, + const array_t& ux1, + const array_t& ux2, + const array_t& ux3, + const array_t& phi_arr, + const array_t& weight_arr, + const array_t& tag, + const array_t& pld_i, + const tuple_t& xi_Cd, + const tuple_t& dxi_Cd, + const vec_t& u, + real_t weight, + real_t phi, + bool use_tracking, + npart_t species_cntr) const { + if (not use_tracking) { + kernel::InjectParticle(p, + i1, + i2, + i3, + dx1, + dx2, + dx3, + ux1, + ux2, + ux3, + phi_arr, + weight_arr, + tag, + pld_i, + xi_Cd, + dxi_Cd, + u, + weight, + phi); + } else { + kernel::InjectParticle(p, + i1, + i2, + i3, + dx1, + dx2, + dx3, + ux1, + ux2, + ux3, + phi_arr, + weight_arr, + tag, + pld_i, + xi_Cd, + dxi_Cd, + u, + weight, + phi, + domain_idx, + species_cntr); + } + // previous position = position: no displacement for the current + // deposit until the particle is pushed for the first time + if constexpr (M::Dim == Dim::_1D or M::Dim == Dim::_2D or M::Dim == Dim::_3D) { + i1_prev(p) = xi_Cd[0]; + dx1_prev(p) = dxi_Cd[0]; + } + if constexpr (M::Dim == Dim::_2D or M::Dim == Dim::_3D) { + i2_prev(p) = xi_Cd[1]; + dx2_prev(p) = dxi_Cd[1]; + } + if constexpr (M::Dim == Dim::_3D) { + i3_prev(p) = xi_Cd[2]; + dx3_prev(p) = dxi_Cd[2]; + } + } + }; + +} // namespace arch::emission + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_H diff --git a/src/archetypes/emission/bethe_heitler/bh_born_qk.h b/src/archetypes/emission/bethe_heitler/bh_born_qk.h new file mode 100644 index 000000000..1ac093040 --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_born_qk.h @@ -0,0 +1,334 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_born_qk.h + * @brief Table of q_k(k), the mean momentum absorbed by the proton along the + * direction of the photon in its rest frame, from the Born cross + * section of Bethe-Heitler pair production + * @implements + * - arch::bh::born::direct_quadrature -> rf::RestFrameQuadrature + * - arch::bh::born::direct -> double + * - arch::bh::born::CubicSpline + * - arch::bh::born::Table + * - arch::bh::born::table -> const Table& + * - arch::bh::born::hook_q_k_delta -> double + * @namespaces: + * - arch::bh::born:: + * + * @note + * Host-only code that does not depend on Kokkos. Including this header + * registers `hook_q_k_delta` in the hook of bh_physics.h. + * + * @note + * With k the photon energy and E', p', theta' the energy, the momentum and + * the angle to the photon of one lepton, all in the rest frame of the proton, + * q_k(k) = k - 2 = 2 <(E' - p') + p' (1 - cos theta')>, + * the average being taken with the angular law (Motz, Olsen & Koch 1969, + * formula 3D-2000 = Blumenthal 1970, eq. 10; `rf::dsigma_dE_dcos_closed`) + * normalised by its own integral. The quadrature is that of `rf::moments`: + * panels in s for the energy, with E' = 1 + (k - 2) sin^2(pi s / 2), panels + * in t = ln(1 - cos theta' + w) for the angle, Gauss-Legendre on each panel. + * With the order of `direct_quadrature` the node values are accurate to + * 1e-8. + * + * @note + * The table: + * - nodes uniform in log10(k - 2), NODES_PER_DECADE per decade from + * k - 2 = DELTA_MIN to the upper end k_max of the range (the last node + * exactly at k_max), every node by direct quadrature, in parallel over + * the host threads; + * - between the nodes a not-a-knot cubic spline of ln q_k in + * t = ln(k - 2). The error of the spline is bounded by + * (5/384) h^4 max|f''''| with h = ln(10) / NODES_PER_DECADE and + * f = ln q_k(t), a smooth function with derivatives of order one. With + * 64 nodes per decade the interpolant agrees with the direct quadrature + * to 5.2e-10 (relative) at the midpoints between the nodes; + * - below DELTA_MIN the linear continuation q_k = 2 - s (k - 2) with the + * slope s from the first node (q_k(2) = 2 exactly). Its error is of + * second order in k - 2: below 1e-10 (relative) at DELTA_MIN; + * - above k_max the value at k_max. + * The table is built once per process, on first use, and the time this takes + * is recorded (`Table::build_seconds`). + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_BORN_QK_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_BORN_QK_H + +#include "archetypes/emission/bethe_heitler/bh_physics.h" +#include "archetypes/emission/bethe_heitler/bh_restframe.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace arch::bh::born { + + /// grid: nodes per decade of k - 2, and k - 2 at the first node + inline constexpr int NODES_PER_DECADE = 64; + inline constexpr double DELTA_MIN = 1.0e-5; + + /** + * @brief The quadrature of the direct evaluation of q_k: Gauss-Legendre of + * order 24 on 32 panels in lepton energy and on panels of width 0.25 + * in t for the angle, for an accuracy of 1e-8 + */ + inline rf::RestFrameQuadrature direct_quadrature() { + rf::RestFrameQuadrature q; + q.gl_order = 24; + q.energy_panels = 32; + q.h_t_angle = 0.25; + return q; + } + + /** + * @brief q_k(k) by direct quadrature of the angular law (no table) + */ + inline double direct(double k, + const rf::RestFrameQuadrature& q = direct_quadrature()) { + if (!(k > 2.0)) { + return 2.0; + } + return rf::moments(k, q).q_k; + } + + /** + * @brief Not-a-knot cubic spline on strictly increasing abscissae + */ + class CubicSpline { + public: + CubicSpline() = default; + + CubicSpline(std::vector x, std::vector y) + : m_x { std::move(x) } + , m_y { std::move(y) } { + const std::size_t n = m_x.size(); + if (n < 4 || m_y.size() != n) { + throw std::invalid_argument("CubicSpline: need at least four nodes"); + } + for (std::size_t i = 1; i < n; ++i) { + if (!(m_x[i] > m_x[i - 1])) { + throw std::invalid_argument("CubicSpline: abscissae must increase"); + } + } + // second derivatives M_i from the not-a-knot conditions (third derivative + // continuous at x_1 and x_{n-2}); tridiagonal system solved by elimination + std::vector h(n - 1); + for (std::size_t i = 0; i + 1 < n; ++i) { + h[i] = m_x[i + 1] - m_x[i]; + } + std::vector a(n, 0.0), b(n, 0.0), c(n, 0.0), d(n, 0.0); + // row 0: not-a-knot at x_1: h1 M0 - (h0 + h1) M1 + h0 M2 = 0 + // expressed through rows 0 and 1 to keep the system tridiagonal + for (std::size_t i = 1; i + 1 < n; ++i) { + a[i] = h[i - 1]; + b[i] = 2.0 * (h[i - 1] + h[i]); + c[i] = h[i]; + d[i] = 6.0 * + ((m_y[i + 1] - m_y[i]) / h[i] - (m_y[i] - m_y[i - 1]) / h[i - 1]); + } + // not-a-knot: M0 = ((h0 + h1) M1 - h0 M2) / h1 and + // M_{n-1} = ((h_{n-2} + h_{n-3}) M_{n-2} - h_{n-2} M_{n-3}) / h_{n-3}; + // substitute into rows 1 and n-2 + { + const double h0 = h[0], h1 = h[1]; + // row 1: a1 M0 + b1 M1 + c1 M2 = d1 with M0 = ((h0+h1) M1 - h0 M2)/h1 + b[1] += a[1] * (h0 + h1) / h1; + c[1] -= a[1] * h0 / h1; + a[1] = 0.0; + const double hm = h[n - 2], hp = h[n - 3]; + // row n-2: a M_{n-3} + b M_{n-2} + c M_{n-1} = d with + // M_{n-1} = ((hm+hp) M_{n-2} - hm M_{n-3})/hp + b[n - 2] += c[n - 2] * (hm + hp) / hp; + a[n - 2] -= c[n - 2] * hm / hp; + c[n - 2] = 0.0; + } + // Thomas algorithm on rows 1..n-2 + std::vector M(n, 0.0); + { + std::vector cp(n, 0.0), dp(n, 0.0); + cp[1] = c[1] / b[1]; + dp[1] = d[1] / b[1]; + for (std::size_t i = 2; i + 1 < n; ++i) { + const double den = b[i] - a[i] * cp[i - 1]; + cp[i] = c[i] / den; + dp[i] = (d[i] - a[i] * dp[i - 1]) / den; + } + M[n - 2] = dp[n - 2]; + for (std::size_t i = n - 3; i >= 1; --i) { + M[i] = dp[i] - cp[i] * M[i + 1]; + } + M[0] = ((h[0] + h[1]) * M[1] - h[0] * M[2]) / h[1]; + M[n - 1] = ((h[n - 2] + h[n - 3]) * M[n - 2] - h[n - 2] * M[n - 3]) / + h[n - 3]; + } + m_M = std::move(M); + } + + double operator()(double x) const { + const std::size_t n = m_x.size(); + if (x <= m_x.front()) { + return m_y.front(); + } + if (x >= m_x.back()) { + return m_y.back(); + } + std::size_t lo = 0, hi = n - 1; + while (hi - lo > 1) { + const std::size_t mid = (lo + hi) / 2; + if (m_x[mid] <= x) { + lo = mid; + } else { + hi = mid; + } + } + const double h = m_x[hi] - m_x[lo]; + const double A = (m_x[hi] - x) / h, B = (x - m_x[lo]) / h; + return A * m_y[lo] + B * m_y[hi] + + ((A * A * A - A) * m_M[lo] + (B * B * B - B) * m_M[hi]) * h * h / 6.0; + } + + const std::vector& x() const { + return m_x; + } + + private: + std::vector m_x, m_y, m_M; + }; + + /** + * @brief The node table and its interpolant + */ + class Table { + public: + Table() = default; + + /** + * @brief Build the table: nodes delta_j = 10^(log10(DELTA_MIN) + j / + * NODES_PER_DECADE) while 2 + delta_j < k_max, then k_max exactly; direct + * quadrature at every node in parallel + */ + explicit Table(double k_max, + const rf::RestFrameQuadrature& q = direct_quadrature(), + unsigned n_threads = 0) { + if (!(k_max > 2.0 + DELTA_MIN)) { + throw std::invalid_argument( + "born::Table: k_max must exceed 2 + DELTA_MIN"); + } + const auto t0 = std::chrono::steady_clock::now(); + const double l0 = std::log10(DELTA_MIN); + for (int j = 0;; ++j) { + const double delta = std::pow( + 10.0, + l0 + static_cast(j) / NODES_PER_DECADE); + if (2.0 + delta >= k_max * (1.0 - 1.0e-12)) { + break; + } + m_k.push_back(2.0 + delta); + } + m_k.push_back(k_max); + m_q.assign(m_k.size(), 0.0); + std::vector& qv = m_q; + const std::vector& kv = m_k; + rf::parallel_for_index( + m_k.size(), + [&qv, &kv, &q](std::size_t i) { + qv[i] = direct(kv[i], q); + }, + n_threads); + std::vector t(m_k.size()), lnq(m_k.size()); + for (std::size_t i = 0; i < m_k.size(); ++i) { + if (!(m_q[i] > 0.0) || !std::isfinite(m_q[i])) { + throw std::runtime_error( + "born::Table: q_k not positive and finite at k = " + + std::to_string(m_k[i])); + } + t[i] = std::log(m_k[i] - 2.0); + lnq[i] = std::log(m_q[i]); + } + m_spline = CubicSpline(t, lnq); + // continuation below the first node: q = 2 - s delta, s being the secant + // from the exact value at threshold, q_k(2) = 2 (the pair at rest in the + // frame of the proton), to the first node (delta = 1e-5): + // s = 1/4 + O(delta), the slope at threshold being exactly 1/4 + m_slope = (2.0 - m_q[0]) / (m_k[0] - 2.0); + m_k_max = k_max; + m_build_seconds = std::chrono::duration( + std::chrono::steady_clock::now() - t0) + .count(); + } + + /// q_k at k = 2 + delta + double q_k_delta(double delta) const { + if (!(delta > 0.0)) { + return 2.0; + } + if (delta < m_k[0] - 2.0) { + return 2.0 - m_slope * delta; + } + if (delta >= m_k_max - 2.0) { + return m_q.back(); + } + return std::exp(m_spline(std::log(delta))); + } + + double q_k(double k) const { + return q_k_delta(k - 2.0); + } + + const std::vector& nodes_k() const { + return m_k; + } + + const std::vector& nodes_q() const { + return m_q; + } + + double threshold_slope() const { + return m_slope; + } + + double build_seconds() const { + return m_build_seconds; + } + + std::size_t size() const { + return m_k.size(); + } + + private: + std::vector m_k, m_q; + CubicSpline m_spline; + double m_slope { 0.25 }; + double m_k_max { constants::K_MAX }; + double m_build_seconds { 0.0 }; + }; + + /** + * @brief The table of the process on [2, K_MAX], built on first use + * (thread-safe) and read by the cumulatives of bh_physics.h + * @param n_threads host threads of the build (0: `rf::thread_limit()`); + * it matters only in the call that builds the table + */ + inline const Table& table(unsigned n_threads = 0) { + static const Table T(constants::K_MAX, direct_quadrature(), n_threads); + return T; + } + +} // namespace arch::bh::born + +namespace arch::bh::born { + + /// the function registered in the hook of bh_physics.h + inline double hook_q_k_delta(double delta) { + return table().q_k_delta(delta); + } + + /// registration at static initialisation of every translation unit that + /// includes this header + inline const bool registered = (born_qk_hook() = &hook_q_k_delta, true); + +} // namespace arch::bh::born + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_BORN_QK_H diff --git a/src/archetypes/emission/bethe_heitler/bh_event_host.h b/src/archetypes/emission/bethe_heitler/bh_event_host.h new file mode 100644 index 000000000..ebbdae509 --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_event_host.h @@ -0,0 +1,108 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_event_host.h + * @brief Upper bound of the energy lost by the proton in one Bethe-Heitler + * interaction, and the largest weight of the pair that it allows + * @implements + * - arch::bh::event::gamma_beta -> double + * - arch::bh::event::dmax_at -> double + * - arch::bh::event::eps_prime_hi -> double + * - arch::bh::event::dmax_unweighted -> double + * - arch::bh::event::a_max -> double + * @namespaces: + * - arch::bh::event:: + * + * @note + * Host-only code that does not depend on Kokkos. Energies are in m_e c^2. + * + * @note + * D = E- + E+ - eps is the energy that the proton loses in an interaction: + * the energies of the two leptons minus that of the absorbed photon, in the + * simulation frame. In the rest frame of the proton, where the photon has + * the energy eps', the component of the total momentum of the pair along the + * velocity of the proton lies in [-sqrt(eps'^2 - 4), sqrt(eps'^2 - 4)], and + * eps' is at most eps'_hi = Gamma eps (1 + beta). Hence + * D <= D_max(eps, eps') = Gamma eps' - eps + Gamma beta sqrt(eps'^2 - 4), + * which increases with eps' and with eps. Over the whole spectrum the bound + * is reached at its largest photon energy eps_max and at + * eps' = eps'_hi(eps_max): + * D_max(Gamma) = Gamma eps'_hi - eps_max + Gamma beta sqrt(eps'_hi^2 - 4). + * + * @note + * A pair of weight a, in units of the weight of the proton, removes the + * energy a D from the kinetic energy K = mu_r (Gamma - 1) of the proton, mu_r + * being the proton-to-electron mass ratio. The largest weight for which no + * outcome removes more than the fraction f_max of K is + * a_max(Gamma) = f_max K / D_max(Gamma). + * For eps_max <= 1, a_max decreases monotonically with Gamma above the + * threshold (K grows as Gamma - 1, D_max as Gamma^2). For a harder spectrum + * it first rises: for eps_max = 1.9 (Gamma_th = 1.0013) from the threshold + * to a maximum near Gamma = 1.33, and decreases beyond. The smallest a_max + * over a range of Gamma is therefore to be found by scanning the range. + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_EVENT_HOST_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_EVENT_HOST_H + +#include +#include +#include +#include + +namespace arch::bh::event { + + /** + * @brief Gamma beta from Gamma (no cancellation for Gamma close to 1) + */ + inline auto gamma_beta(double Gamma) -> double { + return std::sqrt((Gamma - 1.0) * (Gamma + 1.0)); + } + + /** + * @brief D_max(eps, eps') at a given (eps, eps'); 0 below the threshold of + * pair production, eps' < 2 (no interaction) + */ + inline auto dmax_at(double Gamma, double eps, double eps_prime) -> double { + if (!(eps_prime >= 2.0)) { + return 0.0; + } + const double gb = gamma_beta(Gamma); + return Gamma * eps_prime - eps + + gb * std::sqrt((eps_prime - 2.0) * (eps_prime + 2.0)); + } + + /** + * @brief The largest energy eps'_hi = Gamma eps (1 + beta), in the rest + * frame of the proton, of a photon of energy eps in the simulation + * frame + */ + inline auto eps_prime_hi(double Gamma, double eps) -> double { + return Gamma * eps + gamma_beta(Gamma) * eps; + } + + /** + * @brief D_max(Gamma): the bound over every outcome for a bath whose + * spectrum ends at eps_max (eps0 for a monochromatic bath); 0 when + * eps'_hi(eps_max) < 2 (below the threshold of the hardest photon: + * no interaction) + */ + inline auto dmax_unweighted(double Gamma, double eps_max) -> double { + return dmax_at(Gamma, eps_max, eps_prime_hi(Gamma, eps_max)); + } + + /** + * @brief a_max(Gamma) = f_max K / D_max(Gamma) with K = mu_r (Gamma - 1); + * +inf when D_max = 0 (no interaction is possible: no bound can be + * exceeded) + */ + inline auto a_max(double Gamma, double eps_max, double mu_r, double f_max) + -> double { + const double D = dmax_unweighted(Gamma, eps_max); + if (!(D > 0.0)) { + return std::numeric_limits::infinity(); + } + return f_max * mu_r * (Gamma - 1.0) / D; + } + +} // namespace arch::bh::event + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_EVENT_HOST_H diff --git a/src/archetypes/emission/bethe_heitler/bh_interpolate.h b/src/archetypes/emission/bethe_heitler/bh_interpolate.h new file mode 100644 index 000000000..3d22e8410 --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_interpolate.h @@ -0,0 +1,146 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_interpolate.h + * @brief Interpolation of the rate tables on the host, with the same law as + * the lookup on the device (bh_tables_device.h) + * @implements + * - arch::bh::interpolate_loss_host -> double + * - arch::bh::interpolate_outcome_host -> void + * - arch::bh::interpolate_rate_host -> double + * @namespaces: + * - arch::bh:: + * + * @note + * Host-only code that does not depend on Kokkos. The rates are interpolated + * linearly in y = log10(Gamma - Gamma_th) of their logarithm; they are zero + * below the lower edge of the table and equal to the value at the last node + * above its upper edge. + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_INTERPOLATE_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_INTERPOLATE_H + +#include "archetypes/emission/bethe_heitler/bh_physics.h" + +#include +#include + +namespace arch::bh { + + /** + * @brief Energy-loss rate I(Gamma): linear in y of ln I between the nodes + * of the host table + */ + inline auto interpolate_loss_host(const HadronicTablesHost& T, double Gamma) + -> double { + if (!(Gamma > T.gamma_th) || !(Gamma >= T.gamma_min)) { + return 0.0; + } + if (Gamma >= T.gamma_max) { + return T.I.back(); + } + const double yy = std::log10(Gamma - T.gamma_th); + if (yy < T.y_min) { + return 0.0; + } + if (yy >= T.y_max) { + return T.I.back(); + } + // bracket by bisection on the stored nodes + std::size_t lo = 0, hi = T.size() - 1; + while (hi - lo > 1) { + const std::size_t mid = (lo + hi) / 2; + if (T.y[mid] <= yy) { + lo = mid; + } else { + hi = mid; + } + } + const double t = (yy - T.y[lo]) / (T.y[hi] - T.y[lo]); + return std::exp( + std::log(T.I[lo]) + t * (std::log(T.I[hi]) - std::log(T.I[lo]))); + } + + /** + * @brief Mean loss per interaction (Gamma) and mean energy of the + * absorbed photons eps_mean(Gamma): linear in y of ln and of + * eps_mean between the nodes of the host table; the value at the + * first node below the lower edge, the value at the last node at and + * above the upper edge + */ + inline auto interpolate_outcome_host(const HadronicTablesHost& T, + double Gamma, + double& Dmean, + double& eps_mean) -> void { + const std::size_t last = T.size() - 1; + if (!(Gamma > T.gamma_th) || !(Gamma >= T.gamma_min)) { + Dmean = T.Dmean[0]; + eps_mean = T.eps_mean[0]; + return; + } + if (Gamma >= T.gamma_max) { + Dmean = T.Dmean[last]; + eps_mean = T.eps_mean[last]; + return; + } + const double yy = std::log10(Gamma - T.gamma_th); + if (yy < T.y_min) { + Dmean = T.Dmean[0]; + eps_mean = T.eps_mean[0]; + return; + } + if (yy >= T.y_max) { + Dmean = T.Dmean[last]; + eps_mean = T.eps_mean[last]; + return; + } + std::size_t lo = 0, hi = last; + while (hi - lo > 1) { + const std::size_t mid = (lo + hi) / 2; + if (T.y[mid] <= yy) { + lo = mid; + } else { + hi = mid; + } + } + const double t = (yy - T.y[lo]) / (T.y[hi] - T.y[lo]); + Dmean = std::exp(std::log(T.Dmean[lo]) + + t * (std::log(T.Dmean[hi]) - std::log(T.Dmean[lo]))); + eps_mean = T.eps_mean[lo] + t * (T.eps_mean[hi] - T.eps_mean[lo]); + } + + /** + * @brief Interaction rate J(Gamma): linear in y of ln J between the nodes + * of the host table, as `HadronicTables::J` on the device + */ + inline auto interpolate_rate_host(const HadronicTablesHost& T, double Gamma) + -> double { + if (!(Gamma > T.gamma_th) || !(Gamma >= T.gamma_min)) { + return 0.0; + } + if (Gamma >= T.gamma_max) { + return T.J.back(); + } + const double yy = std::log10(Gamma - T.gamma_th); + if (yy < T.y_min) { + return 0.0; + } + if (yy >= T.y_max) { + return T.J.back(); + } + std::size_t lo = 0, hi = T.size() - 1; + while (hi - lo > 1) { + const std::size_t mid = (lo + hi) / 2; + if (T.y[mid] <= yy) { + lo = mid; + } else { + hi = mid; + } + } + const double t = (yy - T.y[lo]) / (T.y[hi] - T.y[lo]); + return std::exp( + std::log(T.J[lo]) + t * (std::log(T.J[hi]) - std::log(T.J[lo]))); + } + +} // namespace arch::bh + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_INTERPOLATE_H diff --git a/src/archetypes/emission/bethe_heitler/bh_physics.h b/src/archetypes/emission/bethe_heitler/bh_physics.h new file mode 100644 index 000000000..98580dafe --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_physics.h @@ -0,0 +1,1145 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_physics.h + * @brief Rates of Bethe-Heitler pair production (p + gamma -> p + e- + e+) + * by a proton on a prescribed isotropic photon field, and their tables + * @implements + * - arch::bh::sigma_tilde -> double + * - arch::bh::born_qk_hook -> QkFunction& + * - arch::bh::born_q_k_delta -> double + * - arch::bh::GaussLegendre + * - arch::bh::Quadrature + * - arch::bh::Cumulatives + * - arch::bh::PhotonBath + * - arch::bh::MonoBath + * - arch::bh::PowerlawBath + * - arch::bh::BlackbodyBath + * - arch::bh::RateValues + * - arch::bh::BetheHeitlerRates + * - arch::bh::HadronicTablesHost + * - arch::bh::table_upper_edge -> double + * - arch::bh::build_tables -> HadronicTablesHost + * - arch::bh::validate_tables -> void + * - arch::bh::BathSpec + * - arch::bh::make_bath -> std::shared_ptr + * @namespaces: + * - arch::bh:: + * - arch::bh::constants:: + * + * @note + * Host-only code in double precision, whatever the precision of the build. + * It does not depend on Kokkos. + * + * @note + * Units: energies in m_e c^2, momenta in m_e c, cross sections in + * alpha r_e^2, the rates J and I per unit photon density in alpha r_e^2 c. + * Gamma is the Lorentz factor of the proton and beta its velocity, eps the + * photon energy in the simulation frame, k (also written eps') the photon + * energy in the rest frame of the proton. + * + * @note + * Contents: + * - sigma_tilde(k): total cross section on a static point charge (Maximon + * 1968, eqs. 10 and 12, joined at k = 4); + * - q_k(k): mean momentum absorbed by the proton along the photon + * direction in its rest frame, supplied by bh_born_qk.h through a hook; + * - Cumulatives: Phi(x) = int_2^x k sigma dk, phi(x) = int_2^x k sigma q_k + * dk and psi(x) = int_2^x sigma q_k dk, built once on a grid in + * ln(k - 2); + * - PhotonBath (monochromatic, power law, black body): number spectrum of + * the photon field, normalised to one photon; + * - BetheHeitlerRates: the interaction rate J(Gamma), the energy-loss rate + * I(Gamma), the mean loss per interaction = I / J and the mean energy + * of the absorbed photons, with no expansion in beta; + * - HadronicTablesHost, build_tables: the rates on a grid in + * y = log10(Gamma - Gamma_th), Gamma_th being the threshold Lorentz + * factor of the hardest photon of the spectrum. + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_PHYSICS_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_PHYSICS_H + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace arch::bh { + + // ------------------------------------------------------------------------ // + // Constants + // ------------------------------------------------------------------------ // + namespace constants { + inline constexpr double PI = 3.14159265358979323846264338327950288; + inline constexpr double ZETA3 = 1.20205690315959428539973816151144999; + // range of the rest-frame photon energy k covered by the tables + inline constexpr double K_MIN = 2.0; + inline constexpr double K_MAX = 1000.0; + // junction of Maximon's two series + inline constexpr double K_JUNCTION = 4.0; + // the tables end where the largest rest-frame photon energy reaches + // ENVELOPE_FRACTION * mu_r, mu_r being the proton-to-electron mass ratio + // (the cross sections are those of a static charge: no proton recoil) + inline constexpr double ENVELOPE_FRACTION = 0.05; + // fraction of the peak of I that defines the lower grid edge + inline constexpr double LOWER_EDGE_FRACTION = 1.0e-12; + // nodes per decade of y: first decade above the lower edge, and beyond + inline constexpr int NODES_PER_DECADE_FINE = 256; + inline constexpr int NODES_PER_DECADE_COARSE = 64; + // a regular node closer than this (in y) to the upper edge is replaced by it + inline constexpr double ENDPOINT_COALESCING = 1.0e-9; + } // namespace constants + + // ------------------------------------------------------------------------ // + // Microscopic functions of the rest-frame photon energy k (= eps') + // ------------------------------------------------------------------------ // + + /** + * @brief Maximon 1968 eq. (10): threshold series, 2 < k < 4 + * @param delta k - 2 (passed directly to avoid cancellation near threshold) + */ + inline double sigma_tilde_series10_delta(double delta) { + if (delta <= 0.0) { + return 0.0; + } + const double k = 2.0 + delta; + const double rho = 2.0 * delta / (k + 2.0 + 2.0 * std::sqrt(2.0 * k)); + const double r = delta / k; + const double poly = 1.0 + rho * (0.5 + rho * (23.0 / 40.0 + + rho * (11.0 / 60.0 + + rho * (29.0 / 960.0)))); + return (2.0 * constants::PI / 3.0) * r * r * r * poly; + } + + /** + * @brief Maximon 1968 eq. (12): asymptotic series in (2/k)^2, k >= 4 + */ + inline double sigma_tilde_series12(double k) { + const double L = std::log(2.0 * k); + const double L2 = L * L; + const double L3 = L2 * L; + const double u = 2.0 / k; + const double u2 = u * u; + const double u4 = u2 * u2; + const double u6 = u4 * u2; + const double pi2 = constants::PI * constants::PI; + const double t0 = (28.0 / 9.0) * L - 218.0 / 27.0; + const double t2 = 6.0 * L - 3.5 + (2.0 / 3.0) * L3 - L2 - (pi2 / 3.0) * L + + 2.0 * constants::ZETA3 + pi2 / 6.0; + const double t4 = (3.0 / 16.0) * L + 0.125; + const double t6 = (29.0 / (9.0 * 256.0)) * L - 77.0 / (27.0 * 512.0); + return t0 + u2 * t2 - u4 * t4 - u6 * t6; + } + + /** + * @brief sigma_tilde(2 + delta) in units of alpha r_e^2 (0 for delta <= 0) + */ + inline double sigma_tilde_delta(double delta) { + if (delta <= 0.0) { + return 0.0; + } + if (delta < constants::K_JUNCTION - 2.0) { + return sigma_tilde_series10_delta(delta); + } + return sigma_tilde_series12(2.0 + delta); + } + + /** + * @brief sigma_tilde(k), total cross section, units of alpha r_e^2 + */ + inline double sigma_tilde(double k) { + return sigma_tilde_delta(k - 2.0); + } + + /** + * @brief Hook for q_k(2 + delta), the mean momentum absorbed by the proton + * along the photon direction in its rest frame [m_e c] + * @note bh_born_qk.h computes q_k from the Born cross sections of + * bh_restframe.h (which includes this header) and registers its + * function here at static initialisation. A program that builds the + * cumulatives has to include bh_born_qk.h in at least one translation + * unit: `born_q_k_delta` throws otherwise. + */ + using QkFunction = double (*)(double); + + inline QkFunction& born_qk_hook() { + static QkFunction p = nullptr; + return p; + } + + inline double born_q_k_delta(double delta) { + const QkFunction p = born_qk_hook(); + if (p == nullptr) { + throw std::logic_error( + "born_q_k_delta: the Born q_k provider is not registered (include " + "archetypes/emission/bethe_heitler/bh_born_qk.h in the program)"); + } + return p(delta); + } + + // ------------------------------------------------------------------------ // + // Gauss-Legendre rule on [-1, 1] + // ------------------------------------------------------------------------ // + struct GaussLegendre { + std::vector x, w; + + explicit GaussLegendre(int n) { + if (n < 2 || n > 64) { + throw std::invalid_argument("GaussLegendre: order must be in [2, 64]"); + } + x.resize(n); + w.resize(n); + for (int i = 0; i < n; ++i) { + double z = std::cos(constants::PI * (i + 0.75) / (n + 0.5)); + double pp = 1.0; + for (int it = 0; it < 100; ++it) { + double p1 = 1.0, p2 = 0.0; + for (int j = 0; j < n; ++j) { + const double p3 = p2; + p2 = p1; + p1 = ((2.0 * j + 1.0) * z * p2 - j * p3) / (j + 1.0); + } + pp = n * (z * p1 - p2) / (z * z - 1.0); + const double z1 = z; + z = z1 - p1 / pp; + if (std::abs(z - z1) < 1.0e-16) { + break; + } + } + x[i] = -z; + w[i] = 2.0 / ((1.0 - z * z) * pp * pp); + } + } + + int order() const { + return static_cast(x.size()); + } + }; + + // ------------------------------------------------------------------------ // + // Parameters of the quadratures of the rates + // ------------------------------------------------------------------------ // + struct Quadrature { + // cell width in t = ln(k - 2) of the cumulative grid + double h_log_delta = 0.02; + // panel width in v = ln(eps / eps_th) of the integral over the spectrum + double h_log_eps = 0.02; + // start of the cumulative grid, k - 2 = delta0 (threshold laws below it) + double delta0 = 1.0e-8; + // Gauss-Legendre order per cell / panel + int gl_order = 16; + // upper end of the range of k + double k_max = constants::K_MAX; + }; + + // ------------------------------------------------------------------------ // + // Cumulatives Phi, phi, psi of the cross section over k, with q_k taken + // from the hook: Gauss-Legendre on cells uniform in t = ln(k - 2), with a + // node at the junction of the two series of sigma_tilde + // ------------------------------------------------------------------------ // + class Cumulatives { + public: + struct Values { + double Phi { 0.0 }; // int_2^x k sigma dk + double phi { 0.0 }; // int_2^x k sigma q_k dk + double psi { 0.0 }; // int_2^x sigma q_k dk + }; + + explicit Cumulatives(const Quadrature& q = Quadrature {}) + : m_delta0 { q.delta0 } + , m_kmax { q.k_max } + , m_h { q.h_log_delta } + , m_gl { q.gl_order } { + if (!(m_delta0 > 0.0) || m_delta0 >= 1.0) { + throw std::invalid_argument("Cumulatives: delta0 must be in (0, 1)"); + } + if (m_kmax <= constants::K_JUNCTION) { + throw std::invalid_argument("Cumulatives: k_max must exceed 4"); + } + if (!(m_h > 0.0)) { + throw std::invalid_argument("Cumulatives: h_log_delta must be > 0"); + } + const double t0 = std::log(m_delta0); + const double t1 = std::log(constants::K_JUNCTION - 2.0); + const double t2 = std::log(m_kmax - 2.0); + // segment 1: [t0, t1], segment 2: [t1, t2]; node exactly at t1 + const auto n1 = static_cast(std::ceil((t1 - t0) / m_h)); + const auto n2 = static_cast(std::ceil((t2 - t1) / m_h)); + m_t.reserve(n1 + n2 + 1); + for (std::size_t i = 0; i < n1; ++i) { + m_t.push_back( + t0 + (t1 - t0) * static_cast(i) / static_cast(n1)); + } + m_t.push_back(t1); + for (std::size_t i = 1; i < n2; ++i) { + m_t.push_back( + t1 + (t2 - t1) * static_cast(i) / static_cast(n2)); + } + m_t.push_back(t2); + m_junction = n1; + // cumulative sums; the start is the analytic threshold law + m_cum.resize(m_t.size()); + m_cum[0] = analytic(m_delta0); + for (std::size_t i = 1; i < m_t.size(); ++i) { + const Values c = cell(m_t[i - 1], m_t[i]); + m_cum[i].Phi = m_cum[i - 1].Phi + c.Phi; + m_cum[i].phi = m_cum[i - 1].phi + c.phi; + m_cum[i].psi = m_cum[i - 1].psi + c.psi; + } + } + + /** + * @brief Cumulatives at k = 2 + delta (zero for delta <= 0) + */ + Values operator()(double delta) const { + if (!(delta > 0.0)) { + return Values {}; + } + if (delta <= m_delta0) { + return analytic(delta); + } + const double dmax = m_kmax - 2.0; + if (delta > dmax) { + if (delta <= dmax * (1.0 + 1.0e-9)) { + delta = dmax; + } else { + throw std::domain_error( + "Cumulatives: k = " + std::to_string(2.0 + delta) + + " outside the tabulated range [2, " + std::to_string(m_kmax) + "]"); + } + } + const double t = std::log(delta); + // locate the cell: t in [m_t[j], m_t[j+1]) + auto it = std::upper_bound(m_t.begin(), m_t.end(), t); + std::size_t j = static_cast(it - m_t.begin()); + if (j == 0) { + j = 1; + } + if (j >= m_t.size()) { + j = m_t.size() - 1; + } + --j; + const Values p = cell(m_t[j], t); + return Values { m_cum[j].Phi + p.Phi, + m_cum[j].phi + p.phi, + m_cum[j].psi + p.psi }; + } + + /** + * @brief Threshold laws for d = k - 2 -> 0: Phi -> (pi/24) d^4, + * phi -> (pi/12) d^4, psi -> (pi/24) d^4, from sigma -> (pi/12) d^3 + * and q_k(2) = 2 + * @note Used below the start of the grid, delta0 = 1e-8 by default, where + * the next order is a relative correction of order delta0 to a part + * that is (delta0 / d)^4 of any cumulative + */ + static Values analytic(double delta) { + const double d4 = delta * delta * delta * delta; + return Values { (constants::PI / 24.0) * d4, + (constants::PI / 12.0) * d4, + (constants::PI / 24.0) * d4 }; + } + + private: + // integrands in t = ln(delta), including the Jacobian dk = delta dt + Values integrand(double t) const { + const double delta = std::exp(t); + const double k = 2.0 + delta; + const double s = sigma_tilde_delta(delta); + const double q = born_q_k_delta(delta); + return Values { k * s * delta, k * s * q * delta, s * q * delta }; + } + + Values cell(double a, double b) const { + Values out; + const double mid = 0.5 * (a + b); + const double half = 0.5 * (b - a); + for (int i = 0; i < m_gl.order(); ++i) { + const Values f = integrand(mid + half * m_gl.x[i]); + const double w = half * m_gl.w[i]; + out.Phi += w * f.Phi; + out.phi += w * f.phi; + out.psi += w * f.psi; + } + return out; + } + + double m_delta0; + double m_kmax; + double m_h; + GaussLegendre m_gl; + std::vector m_t; + std::vector m_cum; + std::size_t m_junction { 0 }; + }; + + // ------------------------------------------------------------------------ // + // Photon baths: number spectrum n~(eps) of the isotropic photon field in the + // simulation frame, normalised to unit integral over the retained range + // [eps_min, eps_max]; eps_max < 2 is required + // ------------------------------------------------------------------------ // + class PhotonBath { + public: + virtual ~PhotonBath() = default; + + virtual bool is_mono() const { + return false; + } + + virtual double eps0() const { + throw std::logic_error("PhotonBath: eps0 is defined only for mono baths"); + } + + // retained range (for a mono bath both equal eps0) + virtual double eps_min() const = 0; + virtual double eps_max() const = 0; + + // normalised number spectrum (not meaningful for mono) + virtual double density(double eps) const = 0; + + // interior energies at which the spectrum is not smooth, used as panel + // edges of the integrals over the spectrum (none by default) + virtual std::vector breakpoints() const { + return {}; + } + + // discarded number and energy fractions of the unclipped spectrum + virtual double clipped_number_fraction() const { + return 0.0; + } + + virtual double clipped_energy_fraction() const { + return 0.0; + } + + // mean photon energy of the normalised spectrum on the retained range + virtual double mean_eps() const = 0; + + // the cutoff energy that sets Gamma_th: eps0 or eps_max + double eps_cut() const { + return is_mono() ? eps0() : eps_max(); + } + + double gamma_th() const { + const double e = eps_cut(); + return 1.0 / e + 0.25 * e; + } + + // Gamma_th beta_th = 1/e - e/4 exactly (so that Gamma_th (1 + beta_th) = 2/e) + double gamma_th_beta_th() const { + const double e = eps_cut(); + return 1.0 / e - 0.25 * e; + } + + protected: + static void require_eps_max_below_two(double eps_max) { + if (!(eps_max < 2.0)) { + throw std::invalid_argument( + "PhotonBath: eps_max = " + std::to_string(eps_max) + + " must be < 2 (the particle must lose energy in every outcome)"); + } + } + }; + + /** + * @brief Monochromatic photons of energy eps0 + */ + class MonoBath : public PhotonBath { + public: + explicit MonoBath(double eps0) : m_eps0 { eps0 } { + if (!(eps0 > 0.0)) { + throw std::invalid_argument("MonoBath: eps0 must be > 0"); + } + require_eps_max_below_two(eps0); + } + + bool is_mono() const override { + return true; + } + + double eps0() const override { + return m_eps0; + } + + double eps_min() const override { + return m_eps0; + } + + double eps_max() const override { + return m_eps0; + } + + double density(double) const override { + throw std::logic_error("MonoBath: density is a delta function"); + } + + double mean_eps() const override { + return m_eps0; + } + + private: + double m_eps0; + }; + + /** + * @brief Power law dn/deps ~ eps^(-index) on [eps_min, eps_max] + */ + class PowerlawBath : public PhotonBath { + public: + PowerlawBath(double eps_min, double eps_max, double index) + : m_eps_min { eps_min } + , m_eps_max { eps_max } + , m_index { index } { + if (!(eps_min > 0.0) || !(eps_max > eps_min)) { + throw std::invalid_argument( + "PowerlawBath: require 0 < eps_min < eps_max"); + } + require_eps_max_below_two(eps_max); + m_norm = 1.0 / power_integral(eps_min, eps_max, -index); + } + + double eps_min() const override { + return m_eps_min; + } + + double eps_max() const override { + return m_eps_max; + } + + double density(double eps) const override { + if (eps < m_eps_min || eps > m_eps_max) { + return 0.0; + } + return m_norm * std::pow(eps, -m_index); + } + + double mean_eps() const override { + return m_norm * power_integral(m_eps_min, m_eps_max, 1.0 - m_index); + } + + /** + * @brief int_a^b eps^p deps (exact) + */ + static double power_integral(double a, double b, double p) { + // (b^t - a^t)/t = a^t L expm1(x)/x with t = p + 1, L = ln(b/a), x = t L; + // the limit expm1(x)/x -> 1 is taken on |x|, not on |t| alone + const double t = p + 1.0; + const double L = std::log(b / a); + const double x = t * L; + if (std::abs(x) < 1.0e-18) { + return std::pow(a, t) * L; + } + return std::pow(a, t) * L * (std::expm1(x) / x); + } + + private: + double m_eps_min, m_eps_max, m_index, m_norm; + }; + + /** + * @brief Black body of temperature theta = k_B T / (m_e c^2), clipped to + * [eps_min, eps_max] + */ + class BlackbodyBath : public PhotonBath { + public: + BlackbodyBath(double theta, double eps_min, double eps_max) + : m_theta { theta } + , m_eps_min { eps_min } + , m_eps_max { eps_max } { + if (!(theta > 0.0)) { + throw std::invalid_argument("BlackbodyBath: theta must be > 0"); + } + if (eps_min < 0.0 || !(eps_max > eps_min)) { + throw std::invalid_argument( + "BlackbodyBath: require 0 <= eps_min < eps_max"); + } + require_eps_max_below_two(eps_max); + // retained and discarded moments of the unclipped Planck spectrum + const double n_total = 2.0 * constants::ZETA3 * theta * theta * theta; + const double e_total = (std::pow(constants::PI, 4) / 15.0) * theta * + theta * theta * theta; + const double n_ret = moment(eps_min, eps_max, 0); + const double e_ret = moment(eps_min, eps_max, 1); + const double n_head = eps_min > 0.0 ? moment(0.0, eps_min, 0) : 0.0; + const double e_head = eps_min > 0.0 ? moment(0.0, eps_min, 1) : 0.0; + const double n_tail = tail_number(eps_max / theta) * theta * theta * theta; + const double e_tail = tail_energy(eps_max / theta) * theta * theta * + theta * theta; + m_norm = 1.0 / n_ret; + m_mean = e_ret / n_ret; + m_clipped_number = (n_head + n_tail) / n_total; + m_clipped_energy = (e_head + e_tail) / e_total; + m_closure_number = (n_head + n_ret + n_tail) / n_total - 1.0; + m_closure_energy = (e_head + e_ret + e_tail) / e_total - 1.0; + } + + double eps_min() const override { + return m_eps_min; + } + + double eps_max() const override { + return m_eps_max; + } + + double density(double eps) const override { + if (eps < m_eps_min || eps > m_eps_max) { + return 0.0; + } + return m_norm * planck(eps); + } + + double clipped_number_fraction() const override { + return m_clipped_number; + } + + double clipped_energy_fraction() const override { + return m_clipped_energy; + } + + // residuals of (head + retained + tail) / total - 1 (quadrature check) + double closure_number() const { + return m_closure_number; + } + + double closure_energy() const { + return m_closure_energy; + } + + double mean_eps() const override { + return m_mean; + } + + // unnormalised Planck number spectrum eps^2 / (exp(eps/theta) - 1) + double planck(double eps) const { + if (eps <= 0.0) { + return 0.0; + } + return eps * eps / std::expm1(eps / m_theta); + } + + /** + * @brief int_a^inf x^2 / (e^x - 1) dx = sum_n e^{-na} (a^2/n + 2a/n^2 + 2/n^3) + */ + static double tail_number(double a) { + double sum = 0.0; + for (int n = 1; n < 2000000; ++n) { + const double term = std::exp(-n * a) * + (a * a / n + 2.0 * a / (static_cast(n) * n) + + 2.0 / (static_cast(n) * n * n)); + sum += term; + if (term < 1.0e-18 * sum) { + break; + } + } + return sum; + } + + /** + * @brief int_a^inf x^3 / (e^x - 1) dx + * = sum_n e^{-na} (a^3/n + 3a^2/n^2 + 6a/n^3 + 6/n^4) + */ + static double tail_energy(double a) { + double sum = 0.0; + for (int n = 1; n < 2000000; ++n) { + const double dn = static_cast(n); + const double term = std::exp(-n * a) * + (a * a * a / dn + 3.0 * a * a / (dn * dn) + + 6.0 * a / (dn * dn * dn) + 6.0 / (dn * dn * dn * dn)); + sum += term; + if (term < 1.0e-18 * sum) { + break; + } + } + return sum; + } + + private: + // int_a^b eps^m planck(eps) deps by composite Gauss-Legendre + double moment(double a, double b, int m) const { + const GaussLegendre gl { 16 }; + const int npan = std::max( + 64, + static_cast(std::ceil((b - a) / (0.05 * m_theta)))); + const double h = (b - a) / npan; + double sum = 0.0; + for (int p = 0; p < npan; ++p) { + const double lo = a + h * p; + const double mid = lo + 0.5 * h; + const double half = 0.5 * h; + for (int i = 0; i < gl.order(); ++i) { + const double e = mid + half * gl.x[i]; + sum += half * gl.w[i] * planck(e) * (m == 0 ? 1.0 : std::pow(e, m)); + } + } + return sum; + } + + double m_theta, m_eps_min, m_eps_max; + double m_norm { 1.0 }, m_mean { 0.0 }; + double m_clipped_number { 0.0 }, m_clipped_energy { 0.0 }; + double m_closure_number { 0.0 }, m_closure_energy { 0.0 }; + }; + + // ------------------------------------------------------------------------ // + // Rates of a proton of Lorentz factor Gamma, with no expansion in beta + // ------------------------------------------------------------------------ // + struct RateValues { + double gamma { 0.0 }; + double beta { 0.0 }; + double J { 0.0 }; // interactions per unit photon density, alpha r_e^2 c + double I { 0.0 }; // energy loss (m_e c^2) per unit photon density + double Dmean { 0.0 }; // I / J + double eps_mean { 0.0 }; // mean energy of the absorbed photons + }; + + /** + * @brief Interaction rate J and energy-loss rate I of a proton in the bath + * + * @note + * With k_hi = Gamma eps (1 + beta) and k_lo = Gamma eps (1 - beta) the + * rest-frame energies of the photons of energy eps that meet the proton + * head on and from behind, + * J(Gamma) = 1 / (2 Gamma^2 beta) int deps n~(eps) / eps^2 + * [Phi(k_hi) - Phi(k_lo)], + * I(Gamma) = 1 / (2 Gamma beta) int deps n~(eps) / eps^2 + * [phi - (eps / Gamma) psi]_(k_lo)^(k_hi), + * the mean loss in an interaction with a photon of energies (eps, k) being + * q_k (Gamma - eps / k). For a monochromatic bath n~ is a delta function at + * eps0. For a broad bath the integral over eps is done by Gauss-Legendre on + * panels uniform in ln(eps), with panel edges at the junction k_hi = 4 of + * the two series of the cross section and at the breakpoints of the + * spectrum. + */ + class BetheHeitlerRates { + public: + BetheHeitlerRates(std::shared_ptr bath, + const Quadrature& q = Quadrature {}) + : m_bath { std::move(bath) } + , m_q { q } + , m_cum { q } + , m_gl { q.gl_order } { + if (!m_bath) { + throw std::invalid_argument("BetheHeitlerRates: null bath"); + } + if (!(m_q.h_log_eps > 0.0)) { + throw std::invalid_argument("BetheHeitlerRates: h_log_eps must be > 0"); + } + } + + const PhotonBath& bath() const { + return *m_bath; + } + + /** + * @brief eps_c Gamma (1 + beta) - 2 for Gamma = Gamma_th + x, cancellation-free + */ + double delta_hi_cut(double x) const { + const double gth = m_bath->gamma_th(); + const double gbth = m_bath->gamma_th_beta_th(); + const double gamma = gth + x; + const double gb = std::sqrt((gamma - 1.0) * (gamma + 1.0)); + return m_bath->eps_cut() * x * (1.0 + (gamma + gth) / (gb + gbth)); + } + + /** + * @brief Rates at Gamma = Gamma_th + x (x > 0) + */ + RateValues at_offset(double x) const { + if (!(x > 0.0)) { + throw std::invalid_argument( + "BetheHeitlerRates: x = Gamma - Gamma_th must be > 0"); + } + RateValues out; + const double gamma = m_bath->gamma_th() + x; + const double gb = std::sqrt((gamma - 1.0) * (gamma + 1.0)); // Gamma beta + const double beta = gb / gamma; + const double A = gamma + gb; // Gamma (1 + beta) + out.gamma = gamma; + out.beta = beta; + const double d_max = delta_hi_cut(x); // eps_c A - 2 + + if (m_bath->is_mono()) { + const double e0 = m_bath->eps0(); + const Cumulatives::Values c = m_cum(d_max); + // eps'_lo = Gamma eps (1 - beta) = eps / A < 2 for eps < 2: Phi(lo) = 0 + out.J = c.Phi / (2.0 * gamma * gb * e0 * e0); + out.I = (c.phi - (e0 / gamma) * c.psi) / (2.0 * gb * e0 * e0); + out.eps_mean = e0; + out.Dmean = out.J > 0.0 ? out.I / out.J : 0.0; + return out; + } + + // broad bath: integrate in v = ln(eps / eps_th), eps_th = 2 / A + const double eps_th = 2.0 / A; + const double v_max = std::log1p(0.5 * d_max); // ln(eps_max / eps_th) + const double v_min = m_bath->eps_min() > eps_th + ? std::log(m_bath->eps_min() / eps_th) + : 0.0; + if (!(v_max > v_min)) { + return out; + } + std::vector edges { v_min }; + const double v4 = std::log(2.0); // eps' = 4 (series junction) + if (v4 > v_min && v4 < v_max) { + edges.push_back(v4); + } + for (const double eb : m_bath->breakpoints()) { + const double vb = std::log(eb / eps_th); + if (vb > v_min && vb < v_max) { + edges.push_back(vb); + } + } + edges.push_back(v_max); + std::sort(edges.begin(), edges.end()); + + double SJ = 0.0, SI = 0.0, SE = 0.0; + for (std::size_t s = 0; s + 1 < edges.size(); ++s) { + const double L = edges[s + 1] - edges[s]; + if (!(L > 0.0)) { + continue; + } + const int npan = std::max(1, + static_cast(std::ceil(L / m_q.h_log_eps))); + const double hp = L / npan; + for (int p = 0; p < npan; ++p) { + const double lo = edges[s] + hp * p; + const double mid = lo + 0.5 * hp; + const double half = 0.5 * hp; + for (int i = 0; i < m_gl.order(); ++i) { + const double v = mid + half * m_gl.x[i]; + const double w = half * m_gl.w[i]; + const double eps = eps_th * std::exp(v); + const double n = m_bath->density(eps); + if (!(n > 0.0)) { + continue; + } + const double d_hi = 2.0 * std::expm1(v); // eps A - 2 + const double d_lo = eps / A - 2.0; // < 0 for eps < 2 + const Cumulatives::Values hi = m_cum(d_hi); + const Cumulatives::Values lo_ = m_cum(d_lo); + const double dPhi = hi.Phi - lo_.Phi; + const double dphi = hi.phi - lo_.phi; + const double dpsi = hi.psi - lo_.psi; + // d eps = eps dv; integrands n/eps^2 (...) and n/eps (...) + SJ += w * n * dPhi / eps; + SI += w * n * (dphi - (eps / gamma) * dpsi) / eps; + SE += w * n * dPhi; + } + } + } + out.J = SJ / (2.0 * gamma * gb); + out.I = SI / (2.0 * gb); + out.eps_mean = SJ > 0.0 ? SE / SJ : 0.0; + out.Dmean = out.J > 0.0 ? out.I / out.J : 0.0; + return out; + } + + RateValues at_gamma(double gamma) const { + return at_offset(gamma - m_bath->gamma_th()); + } + + private: + std::shared_ptr m_bath; + Quadrature m_q; + Cumulatives m_cum; + GaussLegendre m_gl; + }; + + // ------------------------------------------------------------------------ // + // The tables of the rates on the host + // ------------------------------------------------------------------------ // + struct HadronicTablesHost { + // grid + double gamma_th { 0.0 }; // threshold Lorentz factor of the hardest photon + double gamma_min { 0.0 }; // lower edge (I = 1e-12 of its peak) + double gamma_max { 0.0 }; // upper edge (see table_upper_edge) + double y_min { 0.0 }; + double y_max { 0.0 }; + std::size_t n_fine { 0 }; // nodes in the first decade (incl. both ends) + std::size_t n_coarse { 0 }; // nodes after the first decade (excl. y_min + 1) + int nodes_per_decade_fine { constants::NODES_PER_DECADE_FINE }; + int nodes_per_decade_coarse { constants::NODES_PER_DECADE_COARSE }; + // upper edge + double mu_r { 0.0 }; // proton-to-electron mass ratio + double gamma_p_max_input { 0.0 }; // requested upper edge (0 = none) + double eps_prime_max { 0.0 }; // min(0.05 mu_r, 1000) + double gamma_envelope { 0.0 }; // Gamma at which eps'_hi = eps_prime_max + double I_peak { 0.0 }; + double gamma_at_I_peak { 0.0 }; // Gamma of the peak of I (Gamma_max if there) + // bath + double clipped_number_fraction { 0.0 }; + double clipped_energy_fraction { 0.0 }; + // nodes + std::vector gamma, beta, y, J, I, Dmean, eps_mean; + + std::size_t size() const { + return gamma.size(); + } + }; + + /** + * @brief Gamma (1 + beta) = A <=> Gamma = (A + 1/A) / 2 + */ + inline double gamma_from_A(double A) { + return 0.5 * (A + 1.0 / A); + } + + /** + * @brief Upper edge of the table: Gamma at which the largest rest-frame + * photon energy, eps'_hi = Gamma eps_c (1 + beta) with eps_c the + * hardest photon of the spectrum, reaches min(0.05 mu_r, 1000); or + * gamma_p_max if this is positive and smaller + * @param mu_r proton-to-electron mass ratio + * @param gamma_p_max requested upper edge (0 for none) + */ + inline double table_upper_edge(const PhotonBath& bath, + double mu_r, + double gamma_p_max, + double* eps_prime_max_out = nullptr, + double* gamma_envelope_out = nullptr) { + if (!std::isfinite(mu_r) || !(mu_r > 0.0)) { + throw std::invalid_argument( + "table_upper_edge: mass_ratio must be finite and positive, " + "got " + + std::to_string(mu_r)); + } + const double kmax = std::min(constants::ENVELOPE_FRACTION * mu_r, + constants::K_MAX); + if (!(kmax > constants::K_MIN)) { + throw std::invalid_argument( + "table_upper_edge: no Bethe-Heitler-active interval: " + "mass_ratio = " + + std::to_string(mu_r) + " gives a cap min(0.05 mass_ratio, 1000) = " + + std::to_string(kmax) + " <= 2"); + } + if (gamma_p_max != 0.0 && + (!std::isfinite(gamma_p_max) || !(gamma_p_max > 1.0))) { + throw std::invalid_argument( + "table_upper_edge: gamma_max must be a finite number > 1 (0 = " + "auto), got " + + std::to_string(gamma_p_max)); + } + const double A = kmax / bath.eps_cut(); + const double genv = gamma_from_A(A); + if (eps_prime_max_out) { + *eps_prime_max_out = kmax; + } + if (gamma_envelope_out) { + *gamma_envelope_out = genv; + } + return gamma_p_max > 0.0 ? std::min(gamma_p_max, genv) : genv; + } + + /** + * @brief Build the table of the rates on a grid in + * y = log10(Gamma - Gamma_th): 256 nodes per decade over the first + * decade above the lower edge, 64 per decade after, last node exactly + * at the upper edge + * @note The lower edge is where I falls to 1e-12 of its peak, the upper + * edge is given by `table_upper_edge` + */ + inline HadronicTablesHost build_tables(const BetheHeitlerRates& rates, + double mu_r, + double gamma_p_max = 0.0) { + using namespace constants; + const PhotonBath& bath = rates.bath(); + HadronicTablesHost T; + T.mu_r = mu_r; + T.gamma_p_max_input = gamma_p_max; + T.gamma_th = bath.gamma_th(); + T.gamma_max = table_upper_edge(bath, + mu_r, + gamma_p_max, + &T.eps_prime_max, + &T.gamma_envelope); + if (!(T.gamma_max > T.gamma_th)) { + throw std::invalid_argument( + "build_tables: upper edge Gamma_max = " + std::to_string(T.gamma_max) + + " does not exceed Gamma_th = " + std::to_string(T.gamma_th)); + } + T.clipped_number_fraction = bath.clipped_number_fraction(); + T.clipped_energy_fraction = bath.clipped_energy_fraction(); + + const double x_max = T.gamma_max - T.gamma_th; + T.y_max = std::log10(x_max); + + // peak of I over the active interval: coarse scan in y, then local refinement + double y_lo_scan = T.y_max - 14.0; + double y_peak = T.y_max; + T.I_peak = 0.0; + { + const int nscan = 141; + const double dy = (T.y_max - y_lo_scan) / (nscan - 1); + for (int i = 0; i < nscan; ++i) { + const double yy = y_lo_scan + dy * i; + const double Ii = rates.at_offset(std::pow(10.0, yy)).I; + if (Ii > T.I_peak) { + T.I_peak = Ii; + y_peak = yy; + } + } + // golden-section refinement around the scan maximum + double a = std::max(y_lo_scan, y_peak - dy), + b = std::min(T.y_max, y_peak + dy); + const double gr = 0.5 * (std::sqrt(5.0) - 1.0); + double c = b - gr * (b - a), d = a + gr * (b - a); + double fc = rates.at_offset(std::pow(10.0, c)).I; + double fd = rates.at_offset(std::pow(10.0, d)).I; + for (int it = 0; it < 60; ++it) { + if (fc > fd) { + b = d; + d = c; + fd = fc; + c = b - gr * (b - a); + fc = rates.at_offset(std::pow(10.0, c)).I; + } else { + a = c; + c = d; + fc = fd; + d = a + gr * (b - a); + fd = rates.at_offset(std::pow(10.0, d)).I; + } + } + const double Im = std::max(fc, fd); + if (Im > T.I_peak) { + T.I_peak = Im; + y_peak = fc > fd ? c : d; + } + T.gamma_at_I_peak = (std::abs(y_peak - T.y_max) < ENDPOINT_COALESCING) + ? T.gamma_max + : T.gamma_th + std::pow(10.0, y_peak); + } + + // lower edge: I(y) = LOWER_EDGE_FRACTION * I_peak by bisection in y + const double target = LOWER_EDGE_FRACTION * T.I_peak; + { + double a = y_lo_scan, b = y_peak; + double fa = rates.at_offset(std::pow(10.0, a)).I; + if (fa >= target) { + // extend downwards (should not happen for any admissible bath) + for (int it = 0; it < 20 && fa >= target; ++it) { + a -= 2.0; + fa = rates.at_offset(std::pow(10.0, a)).I; + } + if (fa >= target) { + throw std::runtime_error( + "build_tables: cannot bracket the lower edge"); + } + } + for (int it = 0; it < 200; ++it) { + const double m = 0.5 * (a + b); + const double fm = rates.at_offset(std::pow(10.0, m)).I; + if (fm < target) { + a = m; + } else { + b = m; + } + if (b - a < 1.0e-13) { + break; + } + } + T.y_min = 0.5 * (a + b); + } + T.gamma_min = T.gamma_th + std::pow(10.0, T.y_min); + + // nodes + std::vector ys; + const double y_tiny = ENDPOINT_COALESCING; + const double dyf = 1.0 / NODES_PER_DECADE_FINE; + const double dyc = 1.0 / NODES_PER_DECADE_COARSE; + for (int i = 0; i <= NODES_PER_DECADE_FINE; ++i) { + const double yy = T.y_min + dyf * i; + if (yy >= T.y_max - y_tiny) { + break; + } + ys.push_back(yy); + } + T.n_fine = ys.size(); + if (T.y_min + 1.0 < T.y_max - y_tiny) { + for (int j = 1;; ++j) { + const double yy = T.y_min + 1.0 + dyc * j; + if (yy >= T.y_max - y_tiny) { + break; + } + ys.push_back(yy); + } + } + ys.push_back(T.y_max); + T.n_coarse = ys.size() - T.n_fine; + + T.y.reserve(ys.size()); + for (const double yy : ys) { + const double x = std::pow(10.0, yy); + const RateValues r = rates.at_offset(x); + T.y.push_back(yy); + T.gamma.push_back(r.gamma); + T.beta.push_back(r.beta); + T.J.push_back(r.J); + T.I.push_back(r.I); + T.Dmean.push_back(r.Dmean); + T.eps_mean.push_back(r.eps_mean); + } + // the last node is exactly the upper edge + T.gamma.back() = T.gamma_max; + return T; + } + + /** + * @brief Sanity checks of a built table: monotone Gamma, finite, J, I > 0 + */ + inline void validate_tables(const HadronicTablesHost& T) { + if (T.size() < 2) { + throw std::runtime_error("validate_tables: fewer than two nodes"); + } + for (std::size_t i = 0; i < T.size(); ++i) { + if (!std::isfinite(T.gamma[i]) || !std::isfinite(T.J[i]) || + !std::isfinite(T.I[i]) || !std::isfinite(T.Dmean[i]) || + !std::isfinite(T.eps_mean[i]) || !std::isfinite(T.beta[i])) { + throw std::runtime_error( + "validate_tables: non-finite entry at node " + std::to_string(i)); + } + if (!(T.J[i] > 0.0) || !(T.I[i] > 0.0)) { + throw std::runtime_error( + "validate_tables: J or I <= 0 at node " + std::to_string(i)); + } + if (i > 0 && !(T.gamma[i] > T.gamma[i - 1])) { + throw std::runtime_error( + "validate_tables: Gamma not increasing at node " + std::to_string(i)); + } + } + } + + // ------------------------------------------------------------------------ // + // Specification of a photon bath by the name of its spectrum and parameters + // ------------------------------------------------------------------------ // + struct BathSpec { + std::string type; // mono | powerlaw | blackbody + double eps0 { 0.0 }; + double eps_min { -1.0 }; + double eps_max { -1.0 }; + double index { 0.0 }; + double theta { 0.0 }; + }; + + inline std::shared_ptr make_bath(const BathSpec& s) { + if (s.type == "mono") { + return std::make_shared(s.eps0); + } + if (s.type == "powerlaw") { + return std::make_shared(s.eps_min, s.eps_max, s.index); + } + if (s.type == "blackbody") { + return std::make_shared(s.theta, + s.eps_min < 0.0 ? 0.0 : s.eps_min, + s.eps_max); + } + throw std::invalid_argument( + "make_bath: unknown photon spectrum '" + s.type + "'"); + } + +} // namespace arch::bh + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_PHYSICS_H diff --git a/src/archetypes/emission/bethe_heitler/bh_restframe.h b/src/archetypes/emission/bethe_heitler/bh_restframe.h new file mode 100644 index 000000000..cbb6a195c --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_restframe.h @@ -0,0 +1,918 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_restframe.h + * @brief Differential cross sections of Bethe-Heitler pair production on a + * static point charge (Z = 1, unscreened, Born approximation) in the + * rest frame of the charge, and their moments + * @implements + * - arch::bh::rf::momentum -> double + * - arch::bh::rf::energy_minus_momentum -> double + * - arch::bh::rf::dsigma_dE_T<> -> T + * - arch::bh::rf::dsigma_dE -> double + * - arch::bh::rf::dsigma_dE_dcos_T<> -> T + * - arch::bh::rf::dsigma_dE_dcos_closed -> double + * - arch::bh::rf::RestFrameQuadrature + * - arch::bh::rf::integrate_energy<> -> double + * - arch::bh::rf::integrate_angle<> -> double + * - arch::bh::rf::Moments + * - arch::bh::rf::moments<> -> Moments + * - arch::bh::rf::parallel_for_index<> -> void + * @namespaces: + * - arch::bh::rf:: + * - arch::bh::rf::stable:: + * + * @note + * Host-only code that does not depend on Kokkos. The cross sections are + * templated on the floating type and used in double precision. + * + * @note + * Units: energies in m_e c^2, momenta in m_e c, cross sections in + * alpha r_e^2. All quantities are in the rest frame of the proton: k is the + * photon energy, E+ and E- are the total energies of the positron and of the + * electron (E+ + E- = k: the proton takes momentum but no energy), + * p = sqrt(E^2 - 1), theta is the angle of a lepton to the direction of the + * photon. + * + * @note + * Cross sections: + * - the energy law dsigma/dE+: the cross section integrated over the + * directions of both leptons, Motz, Olsen & Koch 1969, Rev. Mod. Phys. + * 41, 581, formula 3D-1000 (Heitler 1954, The Quantum Theory of + * Radiation, p. 258, eq. 8). Its integral over E+ is the total cross + * section, of which `sigma_tilde(k)` of bh_physics.h is a series + * representation; + * - the angular law d^2 sigma/(dE+ dcos theta+): the cross section + * integrated over the direction of the other lepton, Motz, Olsen & Koch + * 1969, formula 3D-2000, which is eq. (10) of Blumenthal 1970, Phys. Rev. + * D 1, 1596 (with the symbols of his eq. 11). By the symmetry of the Born + * cross section under the exchange of the two leptons the same law holds + * for the electron with E+ -> E-. + * + * @note + * `moments` gives the mean momentum absorbed by the proton along the photon + * direction, q_k(k) = k - 2

, by Gauss-Legendre quadrature of + * the angular law over E+ and cos theta+. + * + * @note + * Both closed forms are sums of terms of order 1/p^4 and 1/p^2 that cancel to + * a result of order p^2 when a lepton is slow. They are evaluated with a + * representation that is stable in double precision (namespace `stable`): + * power series near the threshold, a Taylor series computed at run time when + * one lepton is slow, and the closed forms written without the logarithm of a + * number close to 1 elsewhere. + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_RESTFRAME_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_RESTFRAME_H + +#include "archetypes/emission/bethe_heitler/bh_physics.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) + #include +#endif + +namespace arch::bh::rf { + + // ------------------------------------------------------------------------ // + // Kinematic helpers + // ------------------------------------------------------------------------ // + + /// p = sqrt(E^2 - 1) without cancellation + inline double momentum(double E) { + return E > 1.0 ? std::sqrt((E - 1.0) * (E + 1.0)) : 0.0; + } + + /// E - p = 1 / (E + p) + inline double energy_minus_momentum(double E, double p) { + return 1.0 / (E + p); + } + + // ------------------------------------------------------------------------ // + // Stable evaluation of the two closed forms + // + // The energy law and the angular law are sums of terms of order 1/p^4 and + // 1/p^2 that cancel to a result of order p^2 as the lepton momenta go to + // zero: the relative cancellation is of order p^6 at threshold (both + // momenta small) and of order p+^2 or worse at an end point of the energy + // range (one momentum small). Three regions of (p+, p-) are distinguished: + // + // - threshold region, both momenta <= P_SW = 0.15: power series with + // coefficients computed in exact rational arithmetic + // (bh_threshold_series.inc). The energy law is a series B(a, b) in + // a = p+^2 and b = p-^2 of total degree 16 (152 coefficients; its + // logarithm is 2 artanh(p+ p- / (1 + E+ E-)), odd in each momentum, so + // that B depends on the momenta through a and b only). The angular law + // is a series K(p+, p-^2, cos theta) of terms p+^i (p-^2)^j cos^l theta + // with i + 2 j <= 20 (503 coefficients). The terms that the cancellation + // removes vanish identically in rational arithmetic. The relative + // truncation error is at most about 1e-14 at p = P_SW; + // - slow region, the momentum that enters as 1/p^2 (p+ for the angular + // law, the smaller momentum for the energy law) below P_SLOW = 0.1 and + // the other above P_SW: a truncated Taylor series in that momentum, + // computed at run time (`Tps`, 20 terms). The coefficients of orders 0 + // and 1, which the cancellation sets to zero, are dropped exactly; the + // others are computed from quantities of order one. The truncation error + // is at most P_SLOW^18; + // - general region: the closed forms with sub-expressions that involve no + // logarithm of a number close to 1: eps = 2 asinh(p), + // L = 2 artanh(p+ p- / (1 + E+ E-)), eps^Q = 2 artanh(p- / Q). The + // rounding error is amplified by at most about + // 1 / (P_SLOW^2 P_SW^2) ~ 4e3: the relative error is below 2e-11. + // + // Every region is evaluated in the template type T. + // ------------------------------------------------------------------------ // + namespace stable { + + inline constexpr double P_SW = 0.15; // threshold region: both momenta <= P_SW + inline constexpr double P_SLOW = 0.1; // slow region: the critical momentum < P_SLOW + inline constexpr int TPS_N = 20; // terms of the run-time Taylor series + +#include "archetypes/emission/bethe_heitler/bh_threshold_series.inc" + + enum class Region : int { + Threshold = 0, + Slow = 1, + General = 2 + }; + + /// truncated univariate power series sum_{n + struct Tps { + T c[N]; + + Tps() { + for (int n = 0; n < N; ++n) { + c[n] = T(0); + } + } + + explicit Tps(T v) : Tps() { + c[0] = v; + } + + static Tps var() { + Tps r; + if (N > 1) { + r.c[1] = T(1); + } + return r; + } + + friend Tps operator+(const Tps& x, const Tps& y) { + Tps r; + for (int n = 0; n < N; ++n) { + r.c[n] = x.c[n] + y.c[n]; + } + return r; + } + + friend Tps operator-(const Tps& x, const Tps& y) { + Tps r; + for (int n = 0; n < N; ++n) { + r.c[n] = x.c[n] - y.c[n]; + } + return r; + } + + friend Tps operator-(const Tps& x) { + Tps r; + for (int n = 0; n < N; ++n) { + r.c[n] = -x.c[n]; + } + return r; + } + + friend Tps operator+(const Tps& x, T v) { + Tps r = x; + r.c[0] += v; + return r; + } + + friend Tps operator-(const Tps& x, T v) { + Tps r = x; + r.c[0] -= v; + return r; + } + + friend Tps operator*(const Tps& x, T v) { + Tps r; + for (int n = 0; n < N; ++n) { + r.c[n] = x.c[n] * v; + } + return r; + } + + friend Tps operator*(const Tps& x, const Tps& y) { + Tps r; + for (int n = 0; n < N; ++n) { + T s = T(0); + for (int m = 0; m <= n; ++m) { + s += x.c[m] * y.c[n - m]; + } + r.c[n] = s; + } + return r; + } + }; + + template + inline Tps recip(const Tps& x) { + Tps r; + const T r0 = T(1) / x.c[0]; + r.c[0] = r0; + for (int n = 1; n < N; ++n) { + T s = T(0); + for (int m = 1; m <= n; ++m) { + s += x.c[m] * r.c[n - m]; + } + r.c[n] = -r0 * s; + } + return r; + } + + template + inline Tps sqrt(const Tps& x) { + Tps r; + r.c[0] = std::sqrt(x.c[0]); + for (int n = 1; n < N; ++n) { + T s = x.c[n]; + for (int m = 1; m < n; ++m) { + s -= r.c[m] * r.c[n - m]; + } + r.c[n] = s / (T(2) * r.c[0]); + } + return r; + } + + /// artanh of a series with |x0| < 1: f' = x'/(1 - x^2) + template + inline Tps atanh(const Tps& x) { + Tps d; + for (int n = 0; n + 1 < N; ++n) { + d.c[n] = T(n + 1) * x.c[n + 1]; + } + const Tps q = d * recip(Tps(T(1)) - x * x); + Tps r; + r.c[0] = std::atanh(x.c[0]); + for (int n = 1; n < N; ++n) { + r.c[n] = q.c[n - 1] / T(n); + } + return r; + } + + /// sum_n coef(n) x^n for a series x without constant term (Horner) + template + inline Tps compose(const Tps& x, C&& coef) { + Tps r(coef(N - 1)); + for (int n = N - 2; n >= 0; --n) { + r = r * x + coef(n); + } + return r; + } + + /// coefficient of x^n in asinh(sqrt(x))/sqrt(x): (-1)^n (2n-1)!!/((2n)!! (2n+1)) + template + inline T asinh_over_coef(int n) { + T c = T(1); + for (int m = 1; m <= n; ++m) { + c *= -T(2 * m - 1) / T(2 * m); + } + return c / T(2 * n + 1); + } + + /// 2 asinh(p)/p for p >= 0 (p^2 = a), stable at p -> 0 + template + inline T two_asinh_over(T p, T a) { + if (p < T(0.05)) { + T s = T(0); + for (int n = 12; n >= 0; --n) { + s = s * a + asinh_over_coef(n); + } + return T(2) * s; + } + return T(2) * std::asinh(p) / p; + } + + /// 2 artanh(t)/t for |t| < 1, stable at t -> 0 + template + inline T two_atanh_over(T t) { + const T t2 = t * t; + if (t2 < T(0.0025)) { + T s = T(0); + for (int n = 14; n >= 0; --n) { + s = s * t2 + T(1) / T(2 * n + 1); + } + return T(2) * s; + } + return T(2) * std::atanh(t) / t; + } + + // ---------------------------------------------------------------------- // + // the threshold series + // ---------------------------------------------------------------------- // + + /// B(a, b) of the energy law (both momenta <= P_SW) + template + inline T series_B(T a, T b) { + T s = T(0); + for (int i = BS_DEG; i >= 0; --i) { + T r = T(0); + for (int j = BS_DEG - i; j >= 0; --j) { + r = r * b + static_cast(BS_C[i][j]); + } + s = s * a + r; + } + return s; + } + + /// K(p+, b = p-^2, c = cos theta) of the angular law (both momenta <= P_SW) + template + inline T series_K(T p, T b, T c) { + T pw_p[KS_MAXI + 1], pw_b[KS_MAXJ + 1], pw_c[KS_MAXL + 1]; + pw_p[0] = pw_b[0] = pw_c[0] = T(1); + for (int n = 1; n <= KS_MAXI; ++n) { + pw_p[n] = pw_p[n - 1] * p; + } + for (int n = 1; n <= KS_MAXJ; ++n) { + pw_b[n] = pw_b[n - 1] * b; + } + for (int n = 1; n <= KS_MAXL; ++n) { + pw_c[n] = pw_c[n - 1] * c; + } + // highest weights first (smallest terms first) + T s = T(0); + for (int n = KS_N - 1; n >= 0; --n) { + s += static_cast(KS_C[n]) * pw_p[KS_I[n]] * pw_b[KS_J[n]] * + pw_c[KS_L[n]]; + } + return s; + } + + // ---------------------------------------------------------------------- // + // the energy law: the bracket times a b in the general region, and the + // series for a slow lepton + // ---------------------------------------------------------------------- // + + /** + * @brief Q = B a b of the energy law with stable sub-expressions: + * Q = -(4/3) a b - 2 E+E- (a + b) + E- R+ b + E+ R- a - R+ R- a b + + * M N, R = eps/p = 2 asinh(p)/p, M = L/(p+ p-) = 2 artanh(t)/t /(1 + E+E-) + * with t = p+ p-/(1 + E+E-), N = k^2 (E+^2 E-^2 + a b - E+E-) - + * (8/3) E+E- a b - (k/2) [(E+E- - a) R+ b + (E+E- - b) R- a] + */ + template + inline T energy_Q_general(T Ep, T Em, T pp, T pm, T a, T b) { + const T k = Ep + Em; + const T EE = Ep * Em; + const T Rp = two_asinh_over(pp, a); + const T Rm = two_asinh_over(pm, b); + const T i1 = T(1) / (T(1) + EE); + const T M = two_atanh_over(pp * pm * i1) * i1; + const T ab = a * b; + const T Nn = k * k * (EE * EE + ab - EE) - (T(8) / T(3)) * EE * ab - + T(0.5) * k * ((EE - a) * Rp * b + (EE - b) * Rm * a); + return -(T(4) / T(3)) * ab - T(2) * EE * (a + b) + Em * Rp * b + + Ep * Rm * a - Rp * Rm * ab + M * Nn; + } + + /** + * @brief B of the energy law for p+ < P_SLOW (p+ the smaller momentum): the + * same Q as a series in u = p+, orders 0 and 1 dropped (zero + * identically: B is finite at p+ = 0), B = sum_{n>=2} Q_n p+^(n-2) / b + */ + template + inline T energy_B_slow(T pp, T pm, T Em, T b) { + using X = Tps; + const X u = X::var(); + const X a = u * u; + const X Ep = sqrt(a + T(1)); + const X Rp = compose(a, [](int n) { + return T(2) * asinh_over_coef(n); + }); + const T Rm = two_asinh_over(pm, b); + const X EE = Ep * Em; + const X k = Ep + Em; + const X i1 = recip(EE + T(1)); + const X t2 = a * i1 * i1 * b; + const X M = compose(t2, + [](int n) { + return T(1) / T(2 * n + 1); + }) * + i1 * T(2); + const X ab = a * b; + const X Nn = k * k * (EE * EE + ab - EE) - EE * ab * (T(8) / T(3)) - + k * T(0.5) * ((EE - a) * Rp * b + (EE - b) * a * Rm); + const X Q = ab * (-T(4) / T(3)) - EE * (a + b) * T(2) + Rp * (Em * b) + + Ep * a * Rm - Rp * ab * Rm + M * Nn; + T s = T(0); + for (int n = TPS_N - 1; n >= 2; --n) { + s = s * pp + Q.c[n]; + } + return s / b; + } + + /// the region of the energy law for momenta pp <= pm + template + inline Region energy_region(T pp, T pm) { + if (pm <= T(P_SW)) { + return Region::Threshold; + } + if (pp < T(P_SLOW)) { + return Region::Slow; + } + return Region::General; + } + + } // namespace stable + + // ------------------------------------------------------------------------ // + // The energy law: Motz, Olsen & Koch 1969, formula 3D-1000 (Heitler 1954, + // p. 258, eq. 8) + // ------------------------------------------------------------------------ // + + /** + * @brief dsigma/dE+ in alpha r_e^2 per m_e c^2 (Motz, Olsen & Koch 1969, + * formula 3D-1000, Z = 1, unscreened; Heitler 1954, p. 258, eq. 8), + * evaluated in the type T with the stable representation of namespace + * `stable`. Zero outside 1 < E+ < k - 1. dsigma/dE+ = p+ p- B / k^3. + */ + template + inline T dsigma_dE_T(T k, T Ep) { + T Em = k - Ep; + if (!(Ep > T(1)) || !(Em > T(1))) { + return T(0); + } + // the law is symmetric under E+ <-> E-: evaluate with the operands in a + // canonical order so that the values at E and at k - E are bitwise equal + // whenever the two energies are exactly complementary + if (Ep > Em) { + std::swap(Ep, Em); + } + const T xp = Ep - T(1), xm = Em - T(1); + const T a = xp * (xp + T(2)), b = xm * (xm + T(2)); + const T pp = std::sqrt(a), pm = std::sqrt(b); + T B; + switch (stable::energy_region(pp, pm)) { + case stable::Region::Threshold: + B = stable::series_B(a, b); + break; + case stable::Region::Slow: + B = stable::energy_B_slow(pp, pm, Em, b); + break; + default: + B = stable::energy_Q_general(Ep, Em, pp, pm, a, b) / (a * b); + break; + } + return pp * pm * B / (k * k * k); + } + + /// the energy law evaluated in the type T, returned as a double (the + /// quadratures are in double) + template + inline double dsigma_dE_as(double k, double Ep) { + return static_cast( + dsigma_dE_T(static_cast(k), static_cast(Ep))); + } + + /// the energy law in double precision + inline double dsigma_dE(double k, double Ep) { + return dsigma_dE_as(k, Ep); + } + + // ------------------------------------------------------------------------ // + // The angular law: the closed form of Sauter, Gluckstern and Hull (Motz, + // Olsen & Koch 1969, formula 3D-2000 = Blumenthal 1970, eq. 10 with the + // symbols of his eq. 11) + // ------------------------------------------------------------------------ // + + namespace stable { + + /** + * @brief The bracket K of the angular law in the general region, + * d^2 sigma/(dE+ dcos theta+) = -p+ p- K / (4 k^3), with stable + * sub-expressions: L = 2 artanh(p+ p- / (1 + E+ E-)), + * eps- = 2 asinh(p-), eps^Q = 2 artanh(p- / Q) + * @param omc 1 - cos theta+ + * @param sL sign of the terms in L (-1 in the cross section) + * @param se sign of the term in eps- (+1 in the cross section) + * @param sQ sign of the terms in eps^Q (+1 in the cross section) + */ + template + inline T angle_K_general(T Ep, T Em, T pp, T pm, T omc, T sL, T se, T sQ) { + const T k = Ep + Em; + const T a = T(1) / (Ep + pp); // E+ - p+ + const T sp2 = omc * (T(2) - omc); + const T D = a + pp * omc; // Delta+ = E+ - p+ cos theta+ + const T D2 = D * D, D4 = D2 * D2; + const T pp2 = pp * pp; + const T k2 = k * k; + const T Ep2 = Ep * Ep, Em2 = Em * Em; + // Q^2 = |k z^ - p+|^2 = (E- + a)^2 + 2 k p+ omc + const T Q2 = (Em + a) * (Em + a) + T(2) * k * pp * omc; + const T Q = std::sqrt(Q2); + const T i1 = T(1) / (T(1) + Ep * Em); + const T M = two_atanh_over(pp * pm * i1) * i1; // L/(p+ p-) + const T Rm = two_asinh_over(pm, pm * pm); // eps-/p- + const T eQ = two_atanh_over(pm / Q) / (Q * Q); // eps^Q/(p- Q) + const T t1 = T(8) * sp2 * (T(2) * Ep2 + T(1)) / (pp2 * D4); + const T t2 = -T(2) * (T(5) * Ep2 - T(2) * Em * Ep + T(3)) / (pp2 * D2); + const T t3 = -T(2) * (pp2 - k2) / (Q2 * D2); + const T t4 = -T(4) * Em / (pp2 * D); + const T t5 = M * (T(4) * Ep * sp2 * (T(3) * k + pp2 * Em) / (pp2 * D4) + + T(4) * Ep2 * (Ep2 + Em2) / (pp2 * D2) + + (T(2) - T(2) * (T(7) * Ep2 + T(3) * Em * Ep + Em2)) / + (pp2 * D2) + + T(2) * k * (Ep2 - Ep * Em - T(1)) / (pp2 * D)); + const T t6 = T(4) * Rm / D; + const T t7 = eQ * + (T(4) / D2 - T(6) * k / D - T(2) * k * (pp2 - k2) / (Q2 * D)); + return t1 + t2 + t3 + t4 + sL * t5 + se * t6 + sQ * t7; + } + + /** + * @brief K of the angular law for p+ < P_SLOW (p- > P_SW): K p+^2 as a + * series in u = p+, orders 0 and 1 dropped (zero identically: K is + * finite at p+ = 0), K = sum_{n>=2} (K p+^2)_n p+^(n-2) + */ + template + inline T angle_K_slow(T pp, T pm, T Em, T omc) { + using X = Tps; + const X u = X::var(); + const X p2 = u * u; + const X Ep = sqrt(p2 + T(1)); + const X k = Ep + Em; + const X Ep2 = Ep * Ep; + const T Em2 = Em * Em; + const X k2 = k * k; + const T sp2 = omc * (T(2) - omc); + const X aa = Ep - u; // E+ - p+ + const X Dl = aa + u * omc; // E+ - p+ cos theta + const X invD = recip(Dl); + const X invD2 = invD * invD; + const X invD4 = invD2 * invD2; + const X Q2 = (aa + Em) * (aa + Em) + k * u * (T(2) * omc); + const X invQ2 = recip(Q2); + const X invQ = recip(sqrt(Q2)); + const X eQ = atanh(invQ * pm) * invQ * (T(2) / pm); // eps^Q/(p- Q) + const X EE = Ep * Em; + const X i1 = recip(EE + T(1)); + const T b = pm * pm; + const X M = compose(p2 * i1 * i1 * b, + [](int n) { + return T(1) / T(2 * n + 1); + }) * + i1 * T(2); + const T Rm = two_asinh_over(pm, b); + const X T1 = (Ep2 * T(2) + T(1)) * invD4 * (T(8) * sp2); + const X T2 = (Ep2 * T(5) - Ep * (T(2) * Em) + T(3)) * invD2 * T(-2); + const X T3 = p2 * (p2 - k2) * invQ2 * invD2 * T(-2); + const X T4 = invD * (T(-4) * Em); + const X T5 = -( + M * (Ep * (k * T(3) + p2 * Em) * invD4 * (T(4) * sp2) + + Ep2 * (Ep2 + Em2) * invD2 * T(4) + + ((Ep2 * T(7) + Ep * (T(3) * Em) + Em2) * T(-2) + T(2)) * invD2 + + k * (Ep2 - Ep * Em - T(1)) * invD * T(2))); + const X T6 = p2 * invD * (T(4) * Rm); + const X T7 = eQ * p2 * + (invD2 * T(4) - k * invD * T(6) - + k * (p2 - k2) * invQ2 * invD * T(2)); + const X Kp2 = T1 + T2 + T3 + T4 + T5 + T6 + T7; + T s = T(0); + for (int n = TPS_N - 1; n >= 2; --n) { + s = s * pp + Kp2.c[n]; + } + return s; + } + + /// the region of the angular law (p+ the momentum of the lepton whose angle + /// is given) + template + inline Region angle_region(T pp, T pm) { + if (pp <= T(P_SW) && pm <= T(P_SW)) { + return Region::Threshold; + } + if (pp < T(P_SLOW)) { + return Region::Slow; + } + return Region::General; + } + + } // namespace stable + + /** + * @brief d^2 sigma/(dE+ dcos theta+) in alpha r_e^2 per m_e c^2 (Motz, Olsen + * & Koch 1969, formula 3D-2000 = Blumenthal 1970, eq. 10), evaluated + * in the type T with the stable representation of namespace `stable`. + * Zero outside 1 < E+ < k - 1. + * d^2 sigma/(dE+ dcos theta+) = -p+ p- K / (4 k^3). + * @param k photon energy + * @param Ep energy of the lepton whose angle is given + * @param omc 1 - cos theta+ (passed directly to resolve the forward peak) + */ + template + inline T dsigma_dE_dcos_T(T k, T Ep, T omc) { + const T Em = k - Ep; + if (!(Ep > T(1)) || !(Em > T(1)) || !(omc >= T(0)) || !(omc <= T(2))) { + return T(0); + } + const T xp = Ep - T(1), xm = Em - T(1); + const T pp = std::sqrt(xp * (xp + T(2))), pm = std::sqrt(xm * (xm + T(2))); + T K; + switch (stable::angle_region(pp, pm)) { + case stable::Region::Threshold: + K = stable::series_K(pp, pm * pm, T(1) - omc); + break; + case stable::Region::Slow: + K = stable::angle_K_slow(pp, pm, Em, omc); + break; + default: + K = stable::angle_K_general(Ep, Em, pp, pm, omc, T(-1), T(1), T(1)); + break; + } + return -pp * pm * K / (T(4) * k * k * k); + } + + /// the angular law evaluated in the type T, returned as a double + template + inline double dsigma_dE_dcos_as(double k, double Ep, double omc) { + return static_cast(dsigma_dE_dcos_T(static_cast(k), + static_cast(Ep), + static_cast(omc))); + } + + /// the angular law in double precision + inline double dsigma_dE_dcos_closed(double k, double Ep, double omc) { + return dsigma_dE_dcos_as(k, Ep, omc); + } + + // ------------------------------------------------------------------------ // + // Quadratures over E+ and over cos theta+ + // ------------------------------------------------------------------------ // + + /** + * @brief Parameters of the quadratures over E+ and over cos theta+ + */ + struct RestFrameQuadrature { + int gl_order = 16; // Gauss-Legendre order per panel + int energy_panels = 16; // panels in s, E+ = 1 + (k - 2) sin^2(pi s/2) + double h_t_angle = 0.5; // panel width in t = ln(omc + w), w = (E+ - p+)/p+ + }; + + /** + * @brief int_1^{k-1} f(E+) dE+ with E+ = 1 + (k - 2) sin^2(pi s/2), which + * removes the sqrt end-point behaviour of p+ p- + */ + template + inline double integrate_energy(double k, F&& f, const RestFrameQuadrature& q) { + if (!(k > 2.0)) { + return 0.0; + } + const GaussLegendre gl(q.gl_order); + const double d = k - 2.0; + const int np = std::max(1, q.energy_panels); + double sum = 0.0; + for (int p = 0; p < np; ++p) { + const double s0 = static_cast(p) / np, + s1 = static_cast(p + 1) / np; + const double sm = 0.5 * (s0 + s1), sh = 0.5 * (s1 - s0); + for (int i = 0; i < gl.order(); ++i) { + const double s = sm + sh * gl.x[i]; + const double sn = std::sin(0.5 * constants::PI * s); + const double E = 1.0 + d * sn * sn; + const double jac = d * 0.5 * constants::PI * std::sin(constants::PI * s); + sum += sh * gl.w[i] * jac * f(E); + } + } + return sum; + } + + /// the scale of the forward peak of the angular law in omc = 1 - cos theta+: + /// (E+ - p+)/p+ + inline double angular_scale(double Ep) { + const double pp = momentum(Ep); + return pp > 0.0 ? energy_minus_momentum(Ep, pp) / pp : 2.0; + } + + /** + * @brief int_0^2 f(omc) d(omc) (omc = 1 - cos theta+) with t = ln(omc + w), + * w = (E+ - p+)/p+, panels of width <= h_t_angle + */ + template + inline double integrate_angle(double Ep, F&& f, const RestFrameQuadrature& q) { + const double w = angular_scale(Ep); + const double t0 = std::log(w), t1 = std::log(2.0 + w); + const GaussLegendre gl(q.gl_order); + const int np = std::max(1, + static_cast(std::ceil((t1 - t0) / q.h_t_angle))); + double sum = 0.0; + for (int p = 0; p < np; ++p) { + const double a = t0 + (t1 - t0) * static_cast(p) / np; + const double b = t0 + (t1 - t0) * static_cast(p + 1) / np; + const double tm = 0.5 * (a + b), th = 0.5 * (b - a); + for (int i = 0; i < gl.order(); ++i) { + const double t = tm + th * gl.x[i]; + const double et = std::exp(t); + const double omc = std::min(2.0, std::max(0.0, et - w)); + sum += th * gl.w[i] * et * f(omc); + } + } + return sum; + } + + /// int d^2 sigma/(dE+ dcos theta+) dcos theta+ at fixed E+: the energy law + /// from the angular law evaluated in the type T + template + inline double dsigma_dE_from_angular_law(double k, + double Ep, + const RestFrameQuadrature& q) { + return integrate_angle( + Ep, + [k, Ep](double omc) { + return dsigma_dE_dcos_as(k, Ep, omc); + }, + q); + } + + // ------------------------------------------------------------------------ // + // Moments and the recoil + // ------------------------------------------------------------------------ // + + struct Moments { + double k { 0.0 }; + double sigma_g { 0.0 }; // int dsigma/dE+ dE+ + double sigma_maximon { 0.0 }; // sigma_tilde(k), Maximon's series + double sigma_h { 0.0 }; // int int d^2 sigma dcos theta+ dE+ + double mean_E { 0.0 }; // (= = k/2 by symmetry) + double mean_pcos { 0.0 }; // + double q_k { 0.0 }; // k - 2

= 2 <(E - p) + p (1 - cos theta)> + }; + + /** + * @brief The moments at photon energy k of the energy law and of the + * angular law evaluated in the type T + * @note q_k = k - 2

is the mean momentum absorbed by the + * proton along the direction of the photon [m_e c] + */ + template + inline Moments moments(double k, const RestFrameQuadrature& q) { + Moments m; + m.k = k; + m.sigma_maximon = sigma_tilde(k); + if (!(k > 2.0) || !(m.sigma_maximon > 0.0)) { + m.q_k = 2.0; + return m; + } + // the moments are normalised by the integrals of the laws themselves, not + // by Maximon's series, whose truncation error (1.5e-4 at k = 4) would + // otherwise enter them; sigma_g and sigma_h are returned alongside + m.sigma_g = integrate_energy( + k, + [k](double E) { + return dsigma_dE_as(k, E); + }, + q); + m.mean_E = integrate_energy( + k, + [k](double E) { + return E * dsigma_dE_as(k, E); + }, + q) / + m.sigma_g; + // and the total cross section from the angular law + m.sigma_h = integrate_energy( + k, + [&](double E) { + return dsigma_dE_from_angular_law(k, E, q); + }, + q); + m.mean_pcos = integrate_energy( + k, + [&](double E) { + const double pp = momentum(E); + return pp * integrate_angle( + E, + [&](double omc) { + return dsigma_dE_dcos_as(k, E, omc) * + (1.0 - omc); + }, + q); + }, + q) / + m.sigma_h; + // q_k = k - 2

written without cancellation: with + // k - 2 p cos = (k - 2E) + 2 (E - p) + 2 p (1 - cos) and = 0 + // exactly, by the symmetry of the energy law under the exchange of the + // two leptons, q_k = 2 <(E - p) + p (1 - cos theta)>, a mean of positive + // terms; the direct difference loses about 1e-9 relative at k ~ 1000 in + // double precision (q_k ~ 0.04 from 2

~ 1000) + m.q_k = 2.0 * + integrate_energy( + k, + [&](double E) { + const double pp = momentum(E); + const double emp = energy_minus_momentum(E, pp); + return integrate_angle( + E, + [&](double omc) { + return dsigma_dE_dcos_as(k, E, omc) * (emp + pp * omc); + }, + q); + }, + q) / + m.sigma_h; + return m; + } + + // ------------------------------------------------------------------------ // + // A small pool of host threads for the work per table node + // ------------------------------------------------------------------------ // + + /** + * @brief Number of host threads the build of the tables starts by default + * @note The number of processors the calling thread may run on, where + * that can be read (its affinity mask on Linux), so that an MPI rank + * bound to its cores does not start threads for those of its + * neighbours; the hardware concurrency elsewhere, or if the mask + * cannot be read; at least one. + * @note This is a count, not a guarantee: it is read when it is called, + * it does not follow a later change of the mask, and it knows + * nothing of a limit on processor time that leaves the mask wide. + */ + inline auto thread_limit() -> unsigned { + unsigned n = std::thread::hardware_concurrency(); +#if defined(__linux__) + cpu_set_t mask; + CPU_ZERO(&mask); + if (sched_getaffinity(0, sizeof(mask), &mask) == 0) { + const auto allowed = static_cast(CPU_COUNT(&mask)); + if (allowed > 0u and (n == 0u or allowed < n)) { + n = allowed; + } + } +#endif + return std::max(1u, n); + } + + /** + * @brief Call f(i) for every i in [0, n) on host threads + * @param n_threads number of threads (0: `thread_limit()`; a larger + * request is reduced to it) + * @note An exception thrown by f is rethrown in the calling thread + * @note Every index is computed by one call of f, so the result does not + * depend on the number of threads + */ + template + inline void parallel_for_index(std::size_t n, F&& f, unsigned n_threads = 0) { + if (n == 0) { + return; + } + const unsigned limit = thread_limit(); + n_threads = (n_threads == 0) ? limit : std::min(n_threads, limit); + n_threads = static_cast(std::min(n_threads, n)); + if (n_threads <= 1) { + for (std::size_t i = 0; i < n; ++i) { + f(i); + } + return; + } + std::atomic next { 0 }; + std::vector pool; + std::vector errors(n_threads); + for (unsigned t = 0; t < n_threads; ++t) { + pool.emplace_back([&, t]() { + try { + for (;;) { + const std::size_t i = next.fetch_add(1); + if (i >= n) { + break; + } + f(i); + } + } catch (...) { + errors[t] = std::current_exception(); + } + }); + } + for (auto& th : pool) { + th.join(); + } + for (auto& e : errors) { + if (e) { + std::rethrow_exception(e); + } + } + } + +} // namespace arch::bh::rf + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_RESTFRAME_H diff --git a/src/archetypes/emission/bethe_heitler/bh_sampler_device.h b/src/archetypes/emission/bethe_heitler/bh_sampler_device.h new file mode 100644 index 000000000..933f00059 --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_sampler_device.h @@ -0,0 +1,545 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_sampler_device.h + * @brief Device views of the tables of the outcome of a Bethe-Heitler + * interaction, and the sampling of one interaction on the device + * @implements + * - arch::bh::SampledPair + * - arch::bh::SamplerTables + * - arch::bh::mirror_sampler_to_device -> SamplerTables + * - arch::bh::build_sampler_tables -> SamplerTables + * @namespaces: + * - arch::bh:: + * + * @note + * The host tables (`rf::RestFrameTables`, `rf::SamplerCumulatives` and + * `rf::BathEpsTables` of bh_sampler_host.h) are built in double precision on + * the host. `mirror_sampler_to_device` copies the CDF tables into views in + * single precision (a resolution of 1e-7 is sufficient for a CDF) and the + * small arrays (the nodes in k, ln Phi, the Gamma nodes) into views in double + * precision. The inversions return a position in double precision from the + * CDF values in single precision, and the kinematics that follows a draw is + * in double precision. + * + * @note + * `SamplerTables::draw` samples the outcome of one interaction of a proton + * of Lorentz factor Gamma in the order described in bh_sampler_host.h: the + * energy eps of the absorbed photon, its energy k in the rest frame of the + * proton, the azimuth of the photon, the energy of the electron (the + * positron takes the rest), the angle of each lepton to the photon and the + * two azimuths. Eight uniform random numbers are used. The momenta are + * boosted to the simulation frame and returned in the frame whose z axis is + * the velocity of the proton: the caller rotates them with the direction of + * the proton. + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_SAMPLER_DEVICE_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_SAMPLER_DEVICE_H + +#include "arch/kokkos_aliases.h" + +#include "archetypes/emission/bethe_heitler/bh_physics.h" +#include "archetypes/emission/bethe_heitler/bh_sampler_host.h" + +#include + +#include +#include +#include +#include +#include + +namespace arch::bh { + + /** + * @brief Outcome of one interaction: energies in m_e c^2, momenta in m_e c + * in the frame whose z axis is the velocity of the proton. "rest + * frame" is that of the proton, "sim" the simulation frame + */ + struct SampledPair { + double eps { 0.0 }; // photon energy (sim) + double k { 0.0 }; // photon energy eps' (rest frame) + double Em { 0.0 }; // e- energy (rest frame) + double Ep { 0.0 }; // e+ energy (rest frame) + double E_m { 0.0 }; // e- energy (sim) + double E_p { 0.0 }; // e+ energy (sim) + double pm[3] { 0.0, 0.0, 0.0 }; // e- momentum (sim) + double pp[3] { 0.0, 0.0, 0.0 }; // e+ momentum (sim) + double kph[3] { 0.0, 0.0, 0.0 }; // photon momentum (sim; |kph| = eps) + double D { 0.0 }; // E_m + E_p - eps: energy lost by the proton + }; + + /** + * @brief Device views of the sampler tables and the sampling of the outcome + */ + struct SamplerTables { + bool valid { false }; + // rest-frame CDF tables + int n_k { 0 }, n_s { 0 }, n_tau { 0 }; + array_t t_k; // ln(k - 2) at the nodes + array_t cdf_E; // [n_k][n_s + 1] + array_t cdf_A; // [n_k][n_s + 1][n_tau + 1] + // ln Phi in t = ln(k - 2): uniform nodes cum_t0 + i cum_dt, i = 0..n_cum-1 + int n_cum { 0 }; + double cum_t0 { 0.0 }, cum_dt { 0.0 }, cum_delta0 { 0.0 }, cum_kmax { 0.0 }; + array_t ln_phi; + // the photon-energy tables of a broad bath + bool mono { true }; + double eps0 { 0.0 }, gamma_th { 0.0 }; + int n_gamma { 0 }, n_eps { 0 }; + double eps_min_bath { 0.0 }, ln_eps_hi { 0.0 }; // the grid of each node + array_t y_nodes; // log10(Gamma - Gamma_th) + array_t cdf_u; // [n_gamma][n_eps + 1] at x_j = j/n_eps + // total size of the views in bytes + std::size_t bytes { 0 }; + + // ---------------------------------------------------------------------- // + // inversion helpers + // ---------------------------------------------------------------------- // + + /// position in [0, n] (cell units) where the 2-mixture of float CDFs reaches u + Inline auto invert2(const std::size_t o0, + const std::size_t o1, + double w0, + double w1, + int n, + double u, + const array_t& C) const -> double { + int lo = 0, hi = n; + while (hi - lo > 1) { + const int mid = (lo + hi) / 2; + const double v = w0 * static_cast(C(o0 + mid)) + + w1 * static_cast(C(o1 + mid)); + if (v <= u) { + lo = mid; + } else { + hi = mid; + } + } + const double c0 = w0 * static_cast(C(o0 + lo)) + + w1 * static_cast(C(o1 + lo)); + const double c1 = w0 * static_cast(C(o0 + lo + 1)) + + w1 * static_cast(C(o1 + lo + 1)); + double f = (c1 > c0) ? (u - c0) / (c1 - c0) : 0.5; + f = f < 0.0 ? 0.0 : (f > 1.0 ? 1.0 : f); + return static_cast(lo) + f; + } + + /// position where the 4-mixture of float CDFs reaches u + Inline auto invert4(const std::size_t o[4], + const double w[4], + int n, + double u, + const array_t& C) const -> double { + auto value = [&](int j) { + double v = 0.0; + for (int a = 0; a < 4; ++a) { + v += w[a] * static_cast(C(o[a] + j)); + } + return v; + }; + int lo = 0, hi = n; + while (hi - lo > 1) { + const int mid = (lo + hi) / 2; + if (value(mid) <= u) { + lo = mid; + } else { + hi = mid; + } + } + const double c0 = value(lo), c1 = value(lo + 1); + double f = (c1 > c0) ? (u - c0) / (c1 - c0) : 0.5; + f = f < 0.0 ? 0.0 : (f > 1.0 ? 1.0 : f); + return static_cast(lo) + f; + } + + /// bracketing nodes in k and the weight of the upper one + Inline void locate_k(double k, int& i, double& w) const { + const double t = math::log(k - 2.0 > 1.0e-300 ? k - 2.0 : 1.0e-300); + if (t <= t_k(0)) { + i = 0; + w = 0.0; + return; + } + if (t >= t_k(n_k - 1)) { + i = n_k - 2; + w = 1.0; + return; + } + int lo = 0, hi = n_k - 1; + while (hi - lo > 1) { + const int mid = (lo + hi) / 2; + if (t_k(mid) <= t) { + lo = mid; + } else { + hi = mid; + } + } + i = lo; + w = (t - t_k(lo)) / (t_k(lo + 1) - t_k(lo)); + } + + Inline auto sample_s(double k, double u) const -> double { + int i; + double w; + locate_k(k, i, w); + const std::size_t o0 = static_cast(i) * (n_s + 1); + const std::size_t o1 = static_cast(i + 1) * (n_s + 1); + return invert2(o0, o1, 1.0 - w, w, n_s, u, cdf_E) / n_s; + } + + Inline auto sample_tau(double k, double s, double u) const -> double { + int i; + double w; + locate_k(k, i, w); + const double sc = (s < 0.0 ? 0.0 : (s > 1.0 ? 1.0 : s)) * n_s; + int j = static_cast(sc); + if (j > n_s - 1) { + j = n_s - 1; + } + const double v = sc - static_cast(j); + const std::size_t row = static_cast(n_tau + 1); + const std::size_t o[4] = { + (static_cast(i) * (n_s + 1) + j) * row, + (static_cast(i) * (n_s + 1) + j + 1) * row, + (static_cast(i + 1) * (n_s + 1) + j) * row, + (static_cast(i + 1) * (n_s + 1) + j + 1) * row + }; + const double W[4] = { (1.0 - w) * (1.0 - v), + (1.0 - w) * v, + w * (1.0 - v), + w * v }; + return invert4(o, W, n_tau, u, cdf_A) / n_tau; + } + + Inline static auto E_of_s(double k, double s) -> double { + const double sn = math::sin(0.5 * constants::PI * s); + return 1.0 + (k - 2.0) * sn * sn; + } + + Inline static auto momentum(double E) -> double { + return E > 1.0 ? math::sqrt((E - 1.0) * (E + 1.0)) : 0.0; + } + + Inline static auto omc_of_tau(double E, double tau) -> double { + const double p = momentum(E); + const double w = p > 0.0 ? 1.0 / ((E + p) * p) : 2.0; + const double t = math::log(w) + tau * (math::log(2.0 + w) - math::log(w)); + const double om = math::exp(t) - w; + return om < 0.0 ? 0.0 : (om > 2.0 ? 2.0 : om); + } + + // ---------------------------------------------------------------------- // + // Phi(x) = int_2^x k sigma dk and its inverse + // ---------------------------------------------------------------------- // + Inline auto cum_eval(const array_t& ln, double delta, double power) const + -> double { + if (!(delta > 0.0)) { + return 0.0; + } + if (delta <= cum_delta0) { + return math::exp(ln(0)) * math::pow(delta / cum_delta0, power); + } + if (delta >= cum_kmax - 2.0) { + return math::exp(ln(n_cum - 1)); + } + const double t = math::log(delta); + int j = static_cast((t - cum_t0) / cum_dt); + j = j < 0 ? 0 : (j > n_cum - 2 ? n_cum - 2 : j); + const double tj = cum_t0 + j * cum_dt; + const double f = (t - tj) / cum_dt; + return math::exp(ln(j) + f * (ln(j + 1) - ln(j))); + } + + Inline auto Phi(double delta) const -> double { + return cum_eval(ln_phi, delta, 4.0); + } + + Inline auto invert_Phi(double target) const -> double { + if (!(target > 0.0)) { + return 0.0; + } + const double lt = math::log(target); + if (lt <= ln_phi(0)) { + return math::pow(24.0 * target / constants::PI, 0.25); + } + if (lt >= ln_phi(n_cum - 1)) { + return cum_kmax - 2.0; + } + int lo = 0, hi = n_cum - 1; + while (hi - lo > 1) { + const int mid = (lo + hi) / 2; + if (ln_phi(mid) <= lt) { + lo = mid; + } else { + hi = mid; + } + } + const double f = (lt - ln_phi(lo)) / (ln_phi(lo + 1) - ln_phi(lo)); + return math::exp(cum_t0 + (lo + f) * cum_dt); + } + + // ---------------------------------------------------------------------- // + // the photon energy of a broad bath + // ---------------------------------------------------------------------- // + Inline auto sample_eps(double gamma, double u) const -> double { + if (mono) { + return eps0; + } + const double yy = math::log10( + gamma - gamma_th > 1.0e-300 ? gamma - gamma_th : 1.0e-300); + int i; + double w; + if (yy <= y_nodes(0)) { + i = 0; + w = 0.0; + } else if (yy >= y_nodes(n_gamma - 1)) { + i = n_gamma - 2; + w = 1.0; + } else { + int lo = 0, hi = n_gamma - 1; + while (hi - lo > 1) { + const int mid = (lo + hi) / 2; + if (y_nodes(mid) <= yy) { + lo = mid; + } else { + hi = mid; + } + } + i = lo; + w = (yy - y_nodes(lo)) / (y_nodes(lo + 1) - y_nodes(lo)); + } + const std::size_t o0 = static_cast(i) * (n_eps + 1); + const std::size_t o1 = static_cast(i + 1) * (n_eps + 1); + const double pos = invert2(o0, o1, 1.0 - w, w, n_eps, u, cdf_u); + // x = pos/n_eps on the grid of this Gamma: [eps_lo(Gamma), eps_max] in ln eps + const double A = gamma + math::sqrt((gamma - 1.0) * (gamma + 1.0)); + const double ln_lo = math::log(eps_min_bath > 2.0 / A ? eps_min_bath + : 2.0 / A); + return math::exp(ln_lo + (pos / n_eps) * (ln_eps_hi - ln_lo)); + } + + // ---------------------------------------------------------------------- // + // the outcome of one interaction + // ---------------------------------------------------------------------- // + + /** + * @brief Draw the outcome of one interaction of a proton of Lorentz + * factor gamma: the absorbed photon and the two leptons, with the + * momenta in the frame whose z axis is the velocity of the proton + * @param gen random number generator with a method `drand()` that returns + * a uniform number in [0, 1); it is called eight times + * @param out the outcome + */ + template + Inline void draw(double gamma, Gen& gen, SampledPair& out) const { + const double gb = math::sqrt((gamma - 1.0) * (gamma + 1.0)); + const double beta = gb / gamma; + const double A = gamma + gb; + double eps = sample_eps(gamma, gen.drand()); + double dhi = eps * A - 2.0; + // below the threshold at this Gamma (possible in the tail of the mixture + // of the two bracketing nodes): the smallest energy above the threshold + if (!(dhi > 0.0)) { + eps = 2.0 / A * (1.0 + 1.0e-12); + dhi = eps * A - 2.0; + } + const double u2 = gen.drand(); + double delta = invert_Phi(u2 * Phi(dhi)); + delta = delta < 0.0 ? 0.0 : (delta > dhi ? dhi : delta); + const double k = 2.0 + delta; + // direction of the photon in the rest frame, relative to the velocity + // of the proton (z) + double cos_k = (eps / (gamma * k) - 1.0) / beta; + cos_k = cos_k < -1.0 ? -1.0 : (cos_k > 1.0 ? 1.0 : cos_k); + const double sin_k = math::sqrt( + (1.0 - cos_k) * (1.0 + cos_k) > 0.0 ? (1.0 - cos_k) * (1.0 + cos_k) : 0.0); + const double phi_k = 2.0 * constants::PI * gen.drand(); + const double kx = sin_k * math::cos(phi_k), ky = sin_k * math::sin(phi_k), + kz = cos_k; + // lepton energies + const double s = sample_s(k, gen.drand()); + const double Em = E_of_s(k, s), Ep = k - Em; + const double pm_ = momentum(Em), pp_ = momentum(Ep); + // angles to the photon and azimuths + const double omcm = omc_of_tau(Em, sample_tau(k, s, gen.drand())); + const double omcp = omc_of_tau(Ep, sample_tau(k, 1.0 - s, gen.drand())); + const double phm = 2.0 * constants::PI * gen.drand(), + php = 2.0 * constants::PI * gen.drand(); + const double cm = 1.0 - omcm, sm = math::sqrt(omcm * (2.0 - omcm) > 0.0 + ? omcm * (2.0 - omcm) + : 0.0); + const double cp = 1.0 - omcp, sp = math::sqrt(omcp * (2.0 - omcp) > 0.0 + ? omcp * (2.0 - omcp) + : 0.0); + // orthonormal basis (e1, e2) perpendicular to the direction of the photon + double e1x, e1y, e1z; + if (math::abs(kx) < 0.9) { + e1x = 1.0 - kx * kx; + e1y = -kx * ky; + e1z = -kx * kz; + } else { + e1x = -ky * kx; + e1y = 1.0 - ky * ky; + e1z = -ky * kz; + } + const double l1 = math::sqrt(e1x * e1x + e1y * e1y + e1z * e1z); + e1x /= l1; + e1y /= l1; + e1z /= l1; + const double e2x = ky * e1z - kz * e1y, e2y = kz * e1x - kx * e1z, + e2z = kx * e1y - ky * e1x; + // rest-frame momenta + double qm[3], qp[3]; + { + const double ax = sm * math::cos(phm), ay = sm * math::sin(phm); + qm[0] = pm_ * (ax * e1x + ay * e2x + cm * kx); + qm[1] = pm_ * (ax * e1y + ay * e2y + cm * ky); + qm[2] = pm_ * (ax * e1z + ay * e2z + cm * kz); + const double bx = sp * math::cos(php), by = sp * math::sin(php); + qp[0] = pp_ * (bx * e1x + by * e2x + cp * kx); + qp[1] = pp_ * (bx * e1y + by * e2y + cp * ky); + qp[2] = pp_ * (bx * e1z + by * e2z + cp * kz); + } + // boost along z: E = gamma E' + gamma beta p'_z, p_z = gamma p'_z + gamma beta E' + out.E_m = gamma * Em + gb * qm[2]; + out.pm[0] = qm[0]; + out.pm[1] = qm[1]; + out.pm[2] = gamma * qm[2] + gb * Em; + out.E_p = gamma * Ep + gb * qp[2]; + out.pp[0] = qp[0]; + out.pp[1] = qp[1]; + out.pp[2] = gamma * qp[2] + gb * Ep; + // the absorbed photon in the simulation frame: + // cos theta_k = (1 - eps'/(Gamma eps))/beta, same azimuth + double cos_l = (1.0 - k / (gamma * eps)) / beta; + cos_l = cos_l < -1.0 ? -1.0 : (cos_l > 1.0 ? 1.0 : cos_l); + const double sin_l = math::sqrt( + (1.0 - cos_l) * (1.0 + cos_l) > 0.0 ? (1.0 - cos_l) * (1.0 + cos_l) : 0.0); + out.kph[0] = eps * sin_l * math::cos(phi_k); + out.kph[1] = eps * sin_l * math::sin(phi_k); + out.kph[2] = eps * cos_l; + out.eps = eps; + out.k = k; + out.Em = Em; + out.Ep = Ep; + out.D = out.E_m + out.E_p - eps; + } + }; + + /** + * @brief Copy the host sampler tables to device views (single precision for + * the CDFs); throws on inconsistent tables; the total size in bytes is + * recorded in `bytes` + */ + inline auto mirror_sampler_to_device(const rf::RestFrameTables& T, + const rf::SamplerCumulatives& C, + const rf::BathEpsTables& B) + -> SamplerTables { + SamplerTables D; + if (T.n_k() < 2 || T.n_s < 1 || T.n_tau < 1) { + throw std::invalid_argument( + "mirror_sampler_to_device: empty rest-frame tables"); + } + if (T.cdf_E.size() != T.n_k() * static_cast(T.n_s + 1) || + T.cdf_A.size() != T.n_k() * static_cast(T.n_s + 1) * + static_cast(T.n_tau + 1)) { + throw std::invalid_argument( + "mirror_sampler_to_device: inconsistent rest-frame table sizes"); + } + D.n_k = static_cast(T.n_k()); + D.n_s = T.n_s; + D.n_tau = T.n_tau; + D.t_k = array_t { "bh_s_tk", T.n_k() }; + D.cdf_E = array_t { "bh_s_cdfE", T.cdf_E.size() }; + D.cdf_A = array_t { "bh_s_cdfA", T.cdf_A.size() }; + { + auto h = Kokkos::create_mirror_view(D.t_k); + for (std::size_t i = 0; i < T.n_k(); ++i) { + h(i) = T.t_k[i]; + } + Kokkos::deep_copy(D.t_k, h); + } + { + auto h = Kokkos::create_mirror_view(D.cdf_E); + for (std::size_t i = 0; i < T.cdf_E.size(); ++i) { + h(i) = static_cast(T.cdf_E[i]); + } + Kokkos::deep_copy(D.cdf_E, h); + } + { + auto h = Kokkos::create_mirror_view(D.cdf_A); + for (std::size_t i = 0; i < T.cdf_A.size(); ++i) { + h(i) = static_cast(T.cdf_A[i]); + } + Kokkos::deep_copy(D.cdf_A, h); + } + // cumulatives + if (C.size() < 2) { + throw std::invalid_argument( + "mirror_sampler_to_device: empty cumulatives"); + } + D.n_cum = static_cast(C.size()); + D.cum_t0 = C.t().front(); + D.cum_dt = (C.t().back() - C.t().front()) / static_cast(C.size() - 1); + D.cum_delta0 = C.delta0(); + D.cum_kmax = C.kmax(); + D.ln_phi = array_t { "bh_s_lnphi", C.size() }; + { + auto h1 = Kokkos::create_mirror_view(D.ln_phi); + for (std::size_t i = 0; i < C.size(); ++i) { + h1(i) = C.lnPhi()[i]; + } + Kokkos::deep_copy(D.ln_phi, h1); + } + // bath + D.mono = B.mono; + D.eps0 = B.eps0; + D.gamma_th = B.gamma_th; + std::size_t bath_bytes = 0; + if (!B.mono) { + if (B.gamma.size() < 2 || B.n_eps < 1 || + B.cdf_u.size() != B.gamma.size() * static_cast(B.n_eps + 1)) { + throw std::invalid_argument( + "mirror_sampler_to_device: inconsistent photon-energy tables"); + } + D.n_gamma = static_cast(B.gamma.size()); + D.n_eps = B.n_eps; + D.eps_min_bath = B.eps_min_bath; + D.ln_eps_hi = B.ln_eps_hi; + D.y_nodes = array_t { "bh_s_y", B.y.size() }; + D.cdf_u = array_t { "bh_s_cdfu", B.cdf_u.size() }; + auto hy = Kokkos::create_mirror_view(D.y_nodes); + auto hu = Kokkos::create_mirror_view(D.cdf_u); + for (std::size_t i = 0; i < B.y.size(); ++i) { + hy(i) = B.y[i]; + } + for (std::size_t i = 0; i < B.cdf_u.size(); ++i) { + hu(i) = static_cast(B.cdf_u[i]); + } + Kokkos::deep_copy(D.y_nodes, hy); + Kokkos::deep_copy(D.cdf_u, hu); + bath_bytes = B.y.size() * sizeof(double) + B.cdf_u.size() * sizeof(float); + } + D.bytes = T.n_k() * sizeof(double) + + (T.cdf_E.size() + T.cdf_A.size()) * sizeof(float) + + C.size() * sizeof(double) + bath_bytes; + D.valid = true; + return D; + } + + /** + * @brief Build the host sampler tables for a bath and its rate table and + * mirror them to the device + */ + inline auto build_sampler_tables(const PhotonBath& bath, + const HadronicTablesHost& H, + unsigned n_threads = 0) -> SamplerTables { + const rf::RestFrameTables T = rf::RestFrameTables::build(16, 256, 256, 8, n_threads); + const rf::SamplerCumulatives C; + const rf::BathEpsTables B = rf::BathEpsTables::build(bath, H, C, 2048, 8, n_threads); + return mirror_sampler_to_device(T, C, B); + } + +} // namespace arch::bh + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_SAMPLER_DEVICE_H diff --git a/src/archetypes/emission/bethe_heitler/bh_sampler_host.h b/src/archetypes/emission/bethe_heitler/bh_sampler_host.h new file mode 100644 index 000000000..f7a8c4845 --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_sampler_host.h @@ -0,0 +1,469 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_sampler_host.h + * @brief Host tables from which the outcome of a Bethe-Heitler interaction + * is sampled: the energy of the absorbed photon, and the energies and + * angles of the two leptons in the rest frame of the proton + * @implements + * - arch::bh::rf::SamplerCumulatives + * - arch::bh::rf::RestFrameTables + * - arch::bh::rf::BathEpsTables + * @namespaces: + * - arch::bh::rf:: + * + * @note + * Host-only code in double precision that does not depend on Kokkos. The + * device views of these tables and the sampling itself are in + * bh_sampler_device.h. + * + * @note + * The outcome of an interaction of a proton of Lorentz factor Gamma is drawn + * in this order (eps is the photon energy in the simulation frame, k = eps' + * its energy in the rest frame of the proton, E' and theta' the energy of a + * lepton and its angle to the photon in that frame): + * - eps, with a density proportional to n~(eps) / eps^2 Phi(k_hi), where + * k_hi = Gamma eps (1 + beta) and Phi(x) = int_2^x k sigma dk + * (`BathEpsTables`; a monochromatic bath has a single energy); + * - k in [2, k_hi], with a density proportional to k sigma(k) + * (`SamplerCumulatives`); + * - the energy of the electron from the energy law, then the angle of each + * lepton to the photon from the angular law at its energy + * (`RestFrameTables`); the two angles are drawn independently. + * + * @note + * Grids: + * - nodes in k: uniform in log10(k - 2) from k - 2 = 1e-4 to the upper end + * k = 1000 of the tables, `nodes_per_decade` (16) per decade, the end + * point appended; + * - lepton energy on s in [0, 1] with E' = 1 + (k - 2) sin^2(pi s / 2), + * `n_s` (256) cells; + * - lepton angle on tau in [0, 1] with t = ln(1 - cos theta' + w) = + * ln w + tau (ln(2 + w) - ln w), where w = (E' - p') / p' is the scale of + * the forward peak, `n_tau` (256) cells; + * - the CDFs are stored at the cell edges. Sampling inverts the mixture of + * the CDFs of the bracketing nodes (weights linear in ln(k - 2) and in + * s) by bisection over the edges and linear interpolation inside a cell: + * the sampled density is piecewise constant in s and in tau; + * - ln Phi on a fine grid in t = ln(k - 2), of spacing 0.005 from + * k - 2 = 1e-8 to 998, interpolated linearly in t; + * - the CDF of eps of a broad bath at every Gamma node of the rate table, + * each on its own grid uniform in + * x = ln(eps / eps_lo) / ln(eps_max / eps_lo), with + * eps_lo = max(eps_min, 2 / (Gamma (1 + beta))), of at least 2048 cells + * at most 1e-3 wide in ln(eps). Between two nodes the CDFs are mixed at + * fixed x with weights linear in y = log10(Gamma - Gamma_th). + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_SAMPLER_HOST_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_SAMPLER_HOST_H + +#include "archetypes/emission/bethe_heitler/bh_physics.h" +#include "archetypes/emission/bethe_heitler/bh_restframe.h" + +#include +#include +#include +#include +#include +#include + +namespace arch::bh::rf { + + // ------------------------------------------------------------------------ // + // Phi(x) = int_2^x k sigma dk on a fine grid in t = ln(k - 2), from which + // the rest-frame photon energy is drawn: ln Phi is stored at the nodes and + // interpolated linearly in t + // ------------------------------------------------------------------------ // + class SamplerCumulatives { + public: + explicit SamplerCumulatives(double h = 0.005, + double delta0 = 1.0e-8, + double kmax = constants::K_MAX, + int gl = 16) + : m_h { h } + , m_delta0 { delta0 } + , m_kmax { kmax } { + if (!(h > 0.0) || !(delta0 > 0.0) || !(kmax > 4.0)) { + throw std::invalid_argument("SamplerCumulatives: bad grid parameters"); + } + const GaussLegendre G(gl); + const double t0 = std::log(delta0), t1 = std::log(kmax - 2.0); + const auto n = static_cast(std::ceil((t1 - t0) / h)); + m_t.resize(n + 1); + for (std::size_t i = 0; i <= n; ++i) { + m_t[i] = t0 + (t1 - t0) * static_cast(i) / static_cast(n); + } + // threshold law at delta0: k sigma -> (pi/6) d^3, Phi -> (pi/24) d^4 + double Phi = (constants::PI / 24.0) * std::pow(delta0, 4.0); + m_lnPhi.resize(n + 1); + m_lnPhi[0] = std::log(Phi); + for (std::size_t i = 1; i <= n; ++i) { + const double a = m_t[i - 1], b = m_t[i]; + const double mid = 0.5 * (a + b), half = 0.5 * (b - a); + double c1 = 0.0; + for (int g = 0; g < G.order(); ++g) { + const double t = mid + half * G.x[g]; + const double delta = std::exp(t); + const double k = 2.0 + delta; + const double s = sigma_tilde_delta(delta); + const double wgt = half * G.w[g] * delta; // dk = delta dt + c1 += wgt * k * s; + } + Phi += c1; + m_lnPhi[i] = std::log(Phi); + } + } + + double h() const { + return m_h; + } + + double delta0() const { + return m_delta0; + } + + double kmax() const { + return m_kmax; + } + + std::size_t size() const { + return m_t.size(); + } + + const std::vector& t() const { + return m_t; + } + + const std::vector& lnPhi() const { + return m_lnPhi; + } + + double Phi(double delta) const { + return eval(m_lnPhi, delta, 4.0); + } + + private: + double eval(const std::vector& ln, double delta, double power) const { + if (!(delta > 0.0)) { + return 0.0; + } + if (delta <= m_delta0) { + return std::exp(ln.front()) * std::pow(delta / m_delta0, power); + } + const double dmax = m_kmax - 2.0; + if (delta >= dmax) { + return std::exp(ln.back()); + } + const double t = std::log(delta); + const auto it = std::upper_bound(m_t.begin(), m_t.end(), t); + std::size_t j = static_cast(it - m_t.begin()); + j = std::min(std::max(j, 1), m_t.size() - 1) - 1; + const double f = (t - m_t[j]) / (m_t[j + 1] - m_t[j]); + return std::exp(ln[j] + f * (ln[j + 1] - ln[j])); + } + + double m_h, m_delta0, m_kmax; + std::vector m_t, m_lnPhi; + }; + + // ------------------------------------------------------------------------ // + // The CDF tables of the energy law and of the angular law + // ------------------------------------------------------------------------ // + struct RestFrameTables { + // grid + std::vector t_k; // ln(k - 2) at the nodes + int n_s { 256 }; + int n_tau { 256 }; + int nodes_per_decade { 16 }; + // CDFs at the edges: cdf_E[ik][js], cdf_A[ik][js][jt] + std::vector cdf_E; + std::vector cdf_A; + + std::size_t n_k() const { + return t_k.size(); + } + + // lepton energy at the position s in [0, 1] + static double E_of_s(double k, double s) { + const double sn = std::sin(0.5 * constants::PI * s); + return 1.0 + (k - 2.0) * sn * sn; + } + + /// the angular law used for the tables + double law(double k, double E, double omc) const { + return dsigma_dE_dcos_closed(k, E, omc); + } + + /** + * @brief Build the tables (threads over the nodes in k) + * @param nodes_per_decade nodes per decade of k - 2 + * @param n_s cells in lepton energy + * @param n_tau cells in lepton angle + * @param gl_cell Gauss-Legendre order per cell + * @param n_threads host threads (0: `thread_limit()`) + */ + static RestFrameTables build(int nodes_per_decade = 16, + int n_s = 256, + int n_tau = 256, + int gl_cell = 8, + unsigned n_threads = 0) { + RestFrameTables T; + T.n_s = n_s; + T.n_tau = n_tau; + T.nodes_per_decade = nodes_per_decade; + for (int i = 0;; ++i) { + const double delta = std::pow( + 10.0, + -4.0 + static_cast(i) / nodes_per_decade); + if (2.0 + delta >= constants::K_MAX) { + break; + } + T.t_k.push_back(std::log(delta)); + } + T.t_k.push_back(std::log(constants::K_MAX - 2.0)); + const std::size_t nk = T.t_k.size(); + T.cdf_E.assign(nk * (n_s + 1), 0.0); + T.cdf_A.assign(nk * (n_s + 1) * (n_tau + 1), 0.0); + const GaussLegendre G(gl_cell); + parallel_for_index( + nk, + [&](std::size_t ik) { + const double k = 2.0 + std::exp(T.t_k[ik]); + double* CE = T.cdf_E.data() + ik * (n_s + 1); + // energy CDF on the s cells + const double hs = 1.0 / n_s; + CE[0] = 0.0; + for (int j = 0; j < n_s; ++j) { + double cell = 0.0; + for (int g = 0; g < G.order(); ++g) { + const double s = (j + 0.5 * (1.0 + G.x[g])) * hs; + const double E = E_of_s(k, s); + const double jac = (k - 2.0) * 0.5 * constants::PI * + std::sin(constants::PI * s); + cell += 0.5 * hs * G.w[g] * jac * dsigma_dE(k, E); + } + CE[j + 1] = CE[j] + cell; + } + const double tot = CE[n_s]; + for (int j = 0; j <= n_s; ++j) { + CE[j] = tot > 0.0 ? std::min(1.0, CE[j] / tot) + : static_cast(j) / n_s; + } + CE[n_s] = 1.0; + // angular CDFs at the s nodes (end nodes evaluated half a cell inside) + const double ht = 1.0 / n_tau; + for (int j = 0; j <= n_s; ++j) { + const double s_eval = std::min( + 1.0 - 0.5 * hs, + std::max(0.5 * hs, static_cast(j) * hs)); + const double E = E_of_s(k, s_eval); + const double wsc = angular_scale(E); + const double ta = std::log(wsc), tb = std::log(2.0 + wsc); + double* CA = T.cdf_A.data() + (ik * (n_s + 1) + j) * (n_tau + 1); + CA[0] = 0.0; + for (int l = 0; l < n_tau; ++l) { + double cell = 0.0; + for (int g = 0; g < G.order(); ++g) { + const double tau = (l + 0.5 * (1.0 + G.x[g])) * ht; + const double t = ta + tau * (tb - ta); + const double om = std::min(2.0, std::max(0.0, std::exp(t) - wsc)); + cell += 0.5 * ht * G.w[g] * (tb - ta) * std::exp(t) * + T.law(k, E, om); + } + CA[l + 1] = CA[l] + std::max(0.0, cell); + } + const double totA = CA[n_tau]; + for (int l = 0; l <= n_tau; ++l) { + CA[l] = totA > 0.0 ? std::min(1.0, CA[l] / totA) + : static_cast(l) / n_tau; + } + CA[n_tau] = 1.0; + } + }, + n_threads); + return T; + } + }; + + // ------------------------------------------------------------------------ // + // The photon-energy tables of a broad bath at the Gamma nodes + // ------------------------------------------------------------------------ // + /** + * @brief CDF of the energy eps of the photon absorbed by a proton of + * Lorentz factor Gamma in a broad bath, at a list of Gamma nodes + * + * @note + * Each Gamma node has its own grid, adapted to the interval of photon + * energies above the threshold at that Gamma, [eps_lo(Gamma), eps_max] with + * eps_lo(Gamma) = max(eps_min of the bath, 2 / (Gamma (1 + beta))), uniform + * in x = ln(eps / eps_lo) / ln(eps_max / eps_lo) in [0, 1] (`n_eps` cells). + * A single grid in ln(eps) common to all the nodes would cover this + * interval with a few cells near the threshold, the threshold falling + * inside a cell, and bias by up to 3.5e-5. At a Gamma between two + * nodes their CDFs are mixed at fixed x (weights linear in + * y = log10(Gamma - Gamma_th)) and x is mapped to eps with eps_lo of that + * Gamma, so that the threshold is respected at every Gamma and not only at + * the nodes. Inside a cell the sampled density is uniform in x, that is in + * ln(eps). The bias of that this leaves is of second order in the + * width h of the cell in ln(eps) (2.9e-7 at h = 1.9e-3), so the number of + * cells is max(`n_eps`, ceil(widest range of a node / `h_max`)), with + * h_max = 1e-3 by default: the width of the cells, not their number, is + * held fixed when the range of Gamma grows. + * + * @note + * The mixture at fixed x assumes that the shapes at the two bracketing + * nodes are related by the rescaling of [eps_lo(Gamma), eps_max], which + * holds where eps_lo is smooth. eps_lo has a kink at Gamma_c, where + * 2 / (Gamma (1 + beta)) = eps_min: below it the interval starts at the + * threshold, where the density vanishes, above it at the lower edge of the + * bath. In a cell in Gamma that contains Gamma_c the sampled CDF would be + * wrong by up to 1.7e-3 (for a power law on [0.1, 1.5]), so `build_at` + * adds Gamma_c as a node for every broad bath with eps_min > 0 when it + * falls strictly between two of the nodes given. These tables therefore + * have their own list of nodes: `gamma` and `y` are the list given plus + * Gamma_c, and an index into them is not an index of the rate table. + */ + struct BathEpsTables { + bool mono { true }; + double eps0 { 0.0 }; + double gamma_th { 0.0 }; + double eps_min_bath { 0.0 }; // the bath's lower edge (0 if none) + double ln_eps_hi { 0.0 }; // ln eps_max + std::vector y; // log10(Gamma - Gamma_th) at the nodes + std::vector gamma; // the nodes: the list given to `build_at` plus Gamma_c (see above) + int n_eps { 2048 }; + std::vector cdf_u; // [n_gamma][n_eps + 1] CDF of eps at x_j = j/n_eps + + /// ln eps_lo(Gamma) = ln max(eps_min, 2/(Gamma (1 + beta))) + static double ln_eps_lo_of(double g, double eps_min_bath) { + const double A = g + std::sqrt((g - 1.0) * (g + 1.0)); + return std::log(std::max(eps_min_bath, 2.0 / A)); + } + + double ln_eps_lo(double g) const { + return ln_eps_lo_of(g, eps_min_bath); + } + + /// the Gamma of the kink of eps_lo: 2/A = eps_min with A = Gamma (1 + + /// beta), Gamma = (A + 1/A)/2; 0 without a lower edge + static double gamma_kink(double eps_min_bath) { + if (!(eps_min_bath > 0.0)) { + return 0.0; + } + const double A = 2.0 / eps_min_bath; + return 0.5 * (A + 1.0 / A); + } + + /** + * @brief Build the tables at the Gamma nodes of the rate table H + * @param n_eps smallest number of cells in photon energy + * @param gl_cell Gauss-Legendre order per cell + * @param n_threads host threads (0: `thread_limit()`) + * @param h_max largest width of a cell in ln(eps) (0: no bound) + */ + static BathEpsTables build(const PhotonBath& bath, + const HadronicTablesHost& H, + const SamplerCumulatives& cum, + int n_eps = 2048, + int gl_cell = 8, + unsigned n_threads = 0, + double h_max = 1.0e-3) { + return build_at(bath, H.gamma, cum, n_eps, gl_cell, n_threads, h_max); + } + + /// the same at an explicit, increasing list of Gamma nodes (> Gamma_th), + /// plus Gamma_c when it falls strictly between two of them (a Gamma_c + /// outside the range of the list, or on a node, leaves no cell that + /// contains the kink) + static BathEpsTables build_at(const PhotonBath& bath, + const std::vector& nodes, + const SamplerCumulatives& cum, + int n_eps = 2048, + int gl_cell = 8, + unsigned n_threads = 0, + double h_max = 1.0e-3) { + BathEpsTables B; + B.gamma_th = bath.gamma_th(); + B.gamma = nodes; + B.mono = bath.is_mono(); + if (B.mono) { + B.eps0 = bath.eps0(); + return B; + } + if (nodes.size() < 2) { + throw std::invalid_argument( + "BathEpsTables: at least two Gamma nodes are needed"); + } + const double g_c = gamma_kink(std::max(0.0, bath.eps_min())); + const auto up = std::upper_bound(B.gamma.begin(), B.gamma.end(), g_c); + if (g_c > 0.0 && up != B.gamma.begin() && up != B.gamma.end() && + g_c > *(up - 1) * (1.0 + 1.0e-12) && g_c < *up * (1.0 - 1.0e-12)) { + B.gamma.insert(up, g_c); + } + const std::vector& gammas = B.gamma; + B.y.resize(gammas.size()); + for (std::size_t i = 0; i < gammas.size(); ++i) { + if (!(gammas[i] > B.gamma_th) || (i > 0 && !(gammas[i] > gammas[i - 1]))) { + throw std::invalid_argument( + "BathEpsTables: Gamma nodes must be increasing and above Gamma_th"); + } + B.y[i] = std::log10(gammas[i] - B.gamma_th); + } + B.eps_min_bath = std::max(0.0, bath.eps_min()); + B.ln_eps_hi = std::log(bath.eps_max()); + double widest = 0.0; + for (const double g : gammas) { + widest = std::max(widest, B.ln_eps_hi - B.ln_eps_lo(g)); + } + if (h_max > 0.0) { + n_eps = std::max(n_eps, static_cast(std::ceil(widest / h_max))); + } + B.n_eps = n_eps; + const std::size_t ng = gammas.size(); + B.cdf_u.assign(ng * (n_eps + 1), 0.0); + const GaussLegendre G(gl_cell); + parallel_for_index( + ng, + [&](std::size_t ig) { + const double g = gammas[ig]; + const double gb = std::sqrt((g - 1.0) * (g + 1.0)); + const double A = g + gb; + const double lo = B.ln_eps_lo(g); + if (!(B.ln_eps_hi > lo)) { + throw std::invalid_argument( + "BathEpsTables: empty photon-energy range at Gamma " + + std::to_string(g)); + } + const double h = (B.ln_eps_hi - lo) / n_eps; + double* Cu = B.cdf_u.data() + ig * (n_eps + 1); + Cu[0] = 0.0; + for (int j = 0; j < n_eps; ++j) { + double cu = 0.0; + const double a = lo + h * j; + const double mid = a + 0.5 * h, half = 0.5 * h; + for (int q = 0; q < G.order(); ++q) { + const double eps = std::exp(mid + half * G.x[q]); + const double n = bath.density(eps); + const double dhi = eps * A - 2.0; + if (!(n > 0.0) || !(dhi > 0.0)) { + continue; + } + const double w = half * G.w[q] * n / + eps; // d eps / eps^2 = d(ln eps) / eps + cu += w * cum.Phi(dhi); + } + Cu[j + 1] = Cu[j] + cu; + } + for (int j = 0; j <= n_eps; ++j) { + Cu[j] = Cu[n_eps] > 0.0 ? std::min(1.0, Cu[j] / Cu[n_eps]) + : static_cast(j) / n_eps; + } + Cu[n_eps] = 1.0; + }, + n_threads); + return B; + } + }; + +} // namespace arch::bh::rf + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_SAMPLER_HOST_H diff --git a/src/archetypes/emission/bethe_heitler/bh_tables_device.h b/src/archetypes/emission/bethe_heitler/bh_tables_device.h new file mode 100644 index 000000000..2e357696f --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_tables_device.h @@ -0,0 +1,204 @@ +/** + * @file archetypes/emission/bethe_heitler/bh_tables_device.h + * @brief Device views of the Bethe-Heitler rate table and the lookup of the + * interaction rate J(Gamma) on the device + * @implements + * - arch::bh::HadronicTables + * - arch::bh::mirror_tables_to_device -> HadronicTables + * @namespaces: + * - arch::bh:: + * + * @note + * The host table (`arch::bh::HadronicTablesHost`, bh_physics.h) is built in + * double precision on the host. `mirror_tables_to_device` copies its node + * arrays into `Kokkos::View` and records the description of the + * grid. The lookup interpolates ln J linearly in + * y = log10(Gamma - Gamma_th); it returns 0 below the lower edge of the + * table and the value at the last node above its upper edge. All the + * arithmetic is in double precision. + * + * @note + * Nodes: y_min + i / 256 for i = 0..256 (the first decade, `n_fine` nodes + * with both ends), then y_min + 1 + j / 64 for j >= 1 while below + * y_max - 1e-9, then y_max, where Gamma is exactly the upper edge. The cell + * is located with the index computed from this layout, and the interpolation + * uses the stored positions of the nodes, so that the shorter last interval + * and a table that ends within the first decade are handled by the same + * code. + */ + +#ifndef ARCHETYPES_EMISSION_BETHE_HEITLER_BH_TABLES_DEVICE_H +#define ARCHETYPES_EMISSION_BETHE_HEITLER_BH_TABLES_DEVICE_H + +#include "arch/kokkos_aliases.h" + +#include "archetypes/emission/bethe_heitler/bh_interpolate.h" +#include "archetypes/emission/bethe_heitler/bh_physics.h" + +#include + +#include +#include +#include + +namespace arch::bh { + + /** + * @brief Device views of the rate table and the description of its grid + * @note `log_rate` holds ln J at the nodes (interpolated linearly in y), + * `rate` the values of J at the nodes + */ + struct HadronicTables { + // threshold Lorentz factor (the grid variable is y = log10(Gamma - gamma_th)) + double gamma_th { 0.0 }; + double gamma_min { 0.0 }; // lower edge: J = 0 below it + double gamma_max { 0.0 }; // upper edge: the edge value is returned above it + double y_min { 0.0 }; + double y_max { 0.0 }; + double dy_fine { 1.0 / 256.0 }; + double dy_coarse { 1.0 / 64.0 }; + int n_fine { 0 }; // nodes in the first decade (including both ends) + int n { 0 }; // total node count + + array_t y; // node positions in y + array_t gamma; // node Gamma + array_t rate; // J(Gamma) + array_t log_rate; // ln J + + /** + * @brief Index of the cell containing y (0 <= idx <= n - 2), for + * y_min <= y < y_max + */ + Inline auto cell_index(double yy) const -> int { + int idx; + if (yy < y_min + 1.0 || n_fine < 257) { + idx = static_cast((yy - y_min) / dy_fine); + } else { + idx = (n_fine - 1) + static_cast((yy - y_min - 1.0) / dy_coarse); + } + if (idx < 0) { + idx = 0; + } + if (idx > n - 2) { + idx = n - 2; + } + // guard against the rounding of the computed index: at most one step + if (idx + 1 < n - 1 && yy >= y(idx + 1)) { + ++idx; + } + if (idx > 0 && yy < y(idx)) { + --idx; + } + return idx; + } + + /** + * @brief Linear interpolation in y of a log-valued node array + * @param logv ln of the node values, linv the node values themselves + * @param above set to true if Gamma lies above the upper edge (edge value + * returned) + * @return the interpolated value, 0 below the lower edge + */ + Inline auto interpolate_log(const array_t& logv, + const array_t& linv, + double Gamma, + bool& above) const -> double { + above = false; + if (!(Gamma > gamma_th) || !(Gamma >= gamma_min)) { + return 0.0; + } + if (Gamma >= gamma_max) { + above = Gamma > gamma_max; + return linv(n - 1); // the edge value (the last node exactly) + } + const double yy = math::log10(Gamma - gamma_th); + if (yy < y_min) { + return 0.0; + } + if (yy >= y_max) { + return linv(n - 1); + } + const int i = cell_index(yy); + const double y0 = y(i), y1 = y(i + 1); + const double t = (yy - y0) / (y1 - y0); + return math::exp(logv(i) + t * (logv(i + 1) - logv(i))); + } + + /** + * @brief Interaction rate J(Gamma) per unit photon density (alpha r_e^2 c) + */ + Inline auto J(double Gamma) const -> double { + bool above; + return interpolate_log(log_rate, rate, Gamma, above); + } + }; + + /** + * @brief Copy the host table to device views + * @throws std::invalid_argument on an empty or inconsistent host table + */ + inline auto mirror_tables_to_device(const HadronicTablesHost& T) + -> HadronicTables { + if (T.size() < 2) { + throw std::invalid_argument( + "mirror_tables_to_device: fewer than two nodes in the host table"); + } + if (T.y.size() != T.size() || T.I.size() != T.size() || T.J.size() != T.size() || + T.Dmean.size() != T.size() || T.eps_mean.size() != T.size()) { + throw std::invalid_argument( + "mirror_tables_to_device: inconsistent node array sizes"); + } + if (T.n_fine < 2 || T.n_fine > T.size()) { + throw std::invalid_argument( + "mirror_tables_to_device: n_fine = " + std::to_string(T.n_fine) + + " inconsistent with " + std::to_string(T.size()) + " nodes"); + } + HadronicTables D; + D.gamma_th = T.gamma_th; + D.gamma_min = T.gamma_min; + D.gamma_max = T.gamma_max; + D.y_min = T.y_min; + D.y_max = T.y_max; + D.dy_fine = 1.0 / static_cast(T.nodes_per_decade_fine); + D.dy_coarse = 1.0 / static_cast(T.nodes_per_decade_coarse); + D.n_fine = static_cast(T.n_fine); + D.n = static_cast(T.size()); + + const auto n = T.size(); + D.y = array_t { "bh_y", n }; + D.gamma = array_t { "bh_gamma", n }; + D.rate = array_t { "bh_rate", n }; + D.log_rate = array_t { "bh_log_rate", n }; + + auto h_y = Kokkos::create_mirror_view(D.y); + auto h_g = Kokkos::create_mirror_view(D.gamma); + auto h_J = Kokkos::create_mirror_view(D.rate); + auto h_lJ = Kokkos::create_mirror_view(D.log_rate); + for (std::size_t i = 0; i < n; ++i) { + if (!(T.I[i] > 0.0) || !(T.J[i] > 0.0) || !std::isfinite(T.I[i]) || + !std::isfinite(T.J[i])) { + throw std::invalid_argument( + "mirror_tables_to_device: I or J not positive and finite at node " + + std::to_string(i)); + } + h_y(i) = T.y[i]; + h_g(i) = T.gamma[i]; + h_J(i) = T.J[i]; + h_lJ(i) = std::log(T.J[i]); + if (!(T.Dmean[i] > 0.0) || !std::isfinite(T.Dmean[i]) || + !(T.eps_mean[i] > 0.0) || !std::isfinite(T.eps_mean[i])) { + throw std::invalid_argument("mirror_tables_to_device: or eps_mean " + "not positive and finite at node " + + std::to_string(i)); + } + } + Kokkos::deep_copy(D.y, h_y); + Kokkos::deep_copy(D.gamma, h_g); + Kokkos::deep_copy(D.rate, h_J); + Kokkos::deep_copy(D.log_rate, h_lJ); + return D; + } + +} // namespace arch::bh + +#endif // ARCHETYPES_EMISSION_BETHE_HEITLER_BH_TABLES_DEVICE_H diff --git a/src/archetypes/emission/bethe_heitler/bh_threshold_series.inc b/src/archetypes/emission/bethe_heitler/bh_threshold_series.inc new file mode 100644 index 000000000..4686d4033 --- /dev/null +++ b/src/archetypes/emission/bethe_heitler/bh_threshold_series.inc @@ -0,0 +1,167 @@ +// Coefficients of the power series of the Bethe-Heitler cross sections near +// the threshold (both lepton momenta small), computed in exact rational +// arithmetic and rounded to 25 digits; do not edit by hand. This file is +// included inside the namespace arch::bh::rf::stable (bh_restframe.h). +// Energy law (Motz, Olsen & Koch 1969, formula 3D-1000): +// dsigma/dE+ = p+ p- B(a, b)/k^3, a = p+^2, b = p-^2, +// B = sum_{i+j<=16} BS_C[i][j] a^i b^j (B is symmetric; BS_C[1][0] = BS_C[0][1] = 4/3). +// Angular law (Motz, Olsen & Koch 1969, formula 3D-2000 = Blumenthal 1970, eq. 10): +// d^2sigma/(dE+ dcos) = -p+ p- K/(4 k^3), +// K = sum_n KS_C[n] p+^KS_I[n] (p-^2)^KS_J[n] cos^KS_L[n], with KS_I + 2 KS_J <= 20, +// sorted by (KS_I, KS_J, KS_L). +inline constexpr int BS_DEG = 16; +inline constexpr long double BS_C[17][17] = { + { 0.0L, 1.333333333333333333333333e+0L, -4.333333333333333333333333e-1L, 2.464285714285714285714286e-1L, -1.663690476190476190476190e-1L, 1.226100288600288600288600e-1L, -9.540554931179931179931180e-2L, 7.706201133935508935508936e-2L, -6.397447703312822798116916e-2L, 5.423821388516991264669283e-2L, -4.675714396937737990853316e-2L, 4.085870780226938857416757e-2L, -3.610894984345855247454186e-2L, 3.221628904052795928273102e-2L, -2.897814592917574336382250e-2L, 2.624976464277781514559586e-2L, -2.392519809095534222680833e-2L }, + { 1.333333333333333333333333e+0L, -1.111111111111111111111111e-1L, 3.611111111111111111111111e-2L, -1.150793650793650793650794e-2L, 2.480158730158730158730159e-3L, 1.240830928330928330928331e-3L, -2.845790638759388759388759e-3L, 3.514208592333592333592334e-3L, -3.739859188503489974078209e-3L, 3.748654864237687621975548e-3L, -3.650772806569200090630044e-3L, 3.502417371734919816393181e-3L, -3.333101889739065131280710e-3L, 3.158530117060072987826423e-3L, -2.987012202732508813795345e-3L, 2.822801289290288163917724e-3L, 0.0L }, + { -4.333333333333333333333333e-1L, 3.611111111111111111111111e-2L, -3.916666666666666666666667e-2L, 2.694444444444444444444444e-2L, -1.942212301587301587301587e-2L, 1.470278491762866762866763e-2L, -1.156845397079772079772080e-2L, 9.379946586977836977836978e-3L, -7.788259857387557295645531e-3L, 6.591638072755817319720183e-3L, -5.667187265280162299681456e-3L, 4.936611439440957889431565e-3L, -4.348085829364488914437740e-3L, 3.866170148589425213633141e-3L, -3.465939180522600314471033e-3L, 0.0L, 0.0L }, + { 2.464285714285714285714286e-1L, -1.150793650793650793650794e-2L, 2.694444444444444444444444e-2L, -2.043225623582766439909297e-2L, 1.555503885582010582010582e-2L, -1.222223832714904143475572e-2L, 9.885201294241472812901384e-3L, -8.188041006818908604622890e-3L, 6.915784027891505159756210e-3L, -5.935828272125220874909895e-3L, 5.163493787393258198747335e-3L, -4.542806514173636296431308e-3L, 4.035591655701228916749627e-3L, -3.615083081931701200527014e-3L, 0.0L, 0.0L, 0.0L }, + { -1.663690476190476190476190e-1L, 2.480158730158730158730159e-3L, -1.942212301587301587301587e-2L, 1.555503885582010582010582e-2L, -1.219196084104938271604938e-2L, 9.769530444753659039373325e-3L, -8.016344917328455274883846e-3L, 6.714444494174428140201950e-3L, -5.721758976556882657799587e-3L, 4.946739032995272519505321e-3L, -4.329130064797311211354059e-3L, 3.828183749580512915306257e-3L, -3.415598869028094159024852e-3L, 0.0L, 0.0L, 0.0L, 0.0L }, + { 1.226100288600288600288600e-1L, 1.240830928330928330928331e-3L, 1.470278491762866762866763e-2L, -1.222223832714904143475572e-2L, 9.769530444753659039373325e-3L, -7.934089071055132337599870e-3L, 6.575907301571712844034273e-3L, -5.551405609171024907632050e-3L, 4.760783001871719463248262e-3L, -4.137531063891828105867536e-3L, 3.636888490021842566193637e-3L, -3.228076844609984849346464e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { -9.540554931179931179931180e-2L, -2.845790638759388759388759e-3L, -1.156845397079772079772080e-2L, 9.885201294241472812901384e-3L, -8.016344917328455274883846e-3L, 6.575907301571712844034273e-3L, -5.492037861974291511551127e-3L, 4.664726788495912844871178e-3L, -4.020397651238569835622915e-3L, 3.508670403481073529969467e-3L, -3.095044150199677369110229e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { 7.706201133935508935508936e-2L, 3.514208592333592333592334e-3L, 9.379946586977836977836978e-3L, -8.188041006818908604622890e-3L, 6.714444494174428140201950e-3L, -5.551405609171024907632050e-3L, 4.664726788495912844871178e-3L, -3.981626555339222168649252e-3L, 3.445739615589875024818130e-3L, -3.017592278690856011929410e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { -6.397447703312822798116916e-2L, -3.739859188503489974078209e-3L, -7.788259857387557295645531e-3L, 6.915784027891505159756210e-3L, -5.721758976556882657799587e-3L, 4.760783001871719463248262e-3L, -4.020397651238569835622915e-3L, 3.445739615589875024818130e-3L, -2.992271232701552196406817e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { 5.423821388516991264669283e-2L, 3.748654864237687621975548e-3L, 6.591638072755817319720183e-3L, -5.935828272125220874909895e-3L, 4.946739032995272519505321e-3L, -4.137531063891828105867536e-3L, 3.508670403481073529969467e-3L, -3.017592278690856011929410e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { -4.675714396937737990853316e-2L, -3.650772806569200090630044e-3L, -5.667187265280162299681456e-3L, 5.163493787393258198747335e-3L, -4.329130064797311211354059e-3L, 3.636888490021842566193637e-3L, -3.095044150199677369110229e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { 4.085870780226938857416757e-2L, 3.502417371734919816393181e-3L, 4.936611439440957889431565e-3L, -4.542806514173636296431308e-3L, 3.828183749580512915306257e-3L, -3.228076844609984849346464e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { -3.610894984345855247454186e-2L, -3.333101889739065131280710e-3L, -4.348085829364488914437740e-3L, 4.035591655701228916749627e-3L, -3.415598869028094159024852e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { 3.221628904052795928273102e-2L, 3.158530117060072987826423e-3L, 3.866170148589425213633141e-3L, -3.615083081931701200527014e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { -2.897814592917574336382250e-2L, -2.987012202732508813795345e-3L, -3.465939180522600314471033e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { 2.624976464277781514559586e-2L, 2.822801289290288163917724e-3L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, + { -2.392519809095534222680833e-2L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L, 0.0L }, +}; +inline constexpr int KS_W = 20; +inline constexpr int KS_N = 503; +inline constexpr int KS_MAXI = 20; +inline constexpr int KS_MAXJ = 10; +inline constexpr int KS_MAXL = 20; +inline constexpr unsigned char KS_I[KS_N] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20}; +inline constexpr unsigned char KS_J[KS_N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +inline constexpr unsigned char KS_L[KS_N] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7, 0, 2, 4, 6, 0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 10, 0, 2, 4, 6, 8, 10, 0, 2, 4, 6, 8, 10, 0, 2, 4, 6, 8, 10, 0, 2, 4, 6, 8, 10, 0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9, 11, 1, 3, 5, 7, 9, 11, 1, 3, 5, 7, 9, 11, 1, 3, 5, 7, 9, 11, 1, 3, 5, 7, 9, 11, 0, 2, 4, 6, 8, 10, 12, 0, 2, 4, 6, 8, 10, 12, 0, 2, 4, 6, 8, 10, 12, 0, 2, 4, 6, 8, 10, 12, 0, 2, 4, 6, 8, 10, 12, 1, 3, 5, 7, 9, 11, 13, 1, 3, 5, 7, 9, 11, 13, 1, 3, 5, 7, 9, 11, 13, 1, 3, 5, 7, 9, 11, 13, 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, 1, 3, 5, 7, 9, 11, 13, 15, 1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 14, 16, 0, 2, 4, 6, 8, 10, 12, 14, 16, 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17, 1, 3, 5, 7, 9, 11, 13, 15, 17, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; +inline constexpr long double KS_C[KS_N] = { + -2.666666666666666666666667e+0L, 8.666666666666666666666667e-1L, -4.928571428571428571428571e-1L, 3.327380952380952380952381e-1L, + -2.452200577200577200577201e-1L, 1.908110986235986235986236e-1L, -1.541240226787101787101787e-1L, 1.279489540662564559623383e-1L, + -1.084764277703398252933857e-1L, 9.351428793875475981706632e-2L, -6.666666666666666666666667e+0L, 2.466666666666666666666667e+0L, + -1.514285714285714285714286e+0L, 1.073214285714285714285714e+0L, -8.178300865800865800865801e-1L, 6.520998099123099123099123e-1L, + -5.366164651320901320901321e-1L, 4.520620256862214582802818e-1L, -3.878318962031985687171446e-1L, -4.000000000000000000000000e+0L, + 4.000000000000000000000000e+0L, 4.833333333333333333333333e+0L, -1.383333333333333333333333e+1L, -2.191666666666666666666667e+0L, + 6.358333333333333333333333e+0L, 1.452083333333333333333333e+0L, -4.287202380952380952380952e+0L, -1.074107142857142857142857e+0L, + 3.207440476190476190476190e+0L, 8.419857052669552669552670e-1L, -2.533402101370851370851371e+0L, -6.851912735701798201798202e-1L, + 2.072648564543095793095793e+0L, 5.726688323612151737151737e-1L, -1.739091748637647075147075e+0L, -4.883878507241328932505403e-1L, + 1.487602707303419619596090e+0L, 4.231918790961612320213326e-1L, -1.292067566473909821795851e+0L, -1.000000000000000000000000e+1L, + 1.000000000000000000000000e+1L, 1.783333333333333333333333e+1L, -2.550000000000000000000000e+1L, -9.383333333333333333333333e+0L, + 1.421666666666666666666667e+1L, 6.743154761904761904761905e+0L, -1.043422619047619047619048e+1L, -5.255505952380952380952381e+0L, + 8.219097222222222222222222e+0L, 4.274383342352092352092352e+0L, -6.727127299783549783549784e+0L, -3.575517884892884892884893e+0L, + 5.650757575757575757575758e+0L, 3.053068928142170329670330e+0L, -4.839321374697351259851260e+0L, -2.648868800996414737223561e+0L, + 4.207837428078840073325367e+0L, 4.500000000000000000000000e+0L, -2.050000000000000000000000e+1L, 1.600000000000000000000000e+1L, + -6.833333333333333333333333e+0L, 4.608333333333333333333333e+1L, -4.300000000000000000000000e+1L, 3.922916666666666666666667e+0L, + -2.844375000000000000000000e+1L, 2.818333333333333333333333e+1L, -2.947619047619047619047619e+0L, 2.207797619047619047619048e+1L, + -2.232797619047619047619048e+1L, 2.369134424603174603174603e+0L, -1.807920386904761904761905e+1L, 1.848055555555555555555556e+1L, + -1.972035646645021645021645e+0L, 1.523375467848124098124098e+1L, -1.567644074675324675324675e+1L, 1.679979723509996947496947e+0L, + -1.309047400895545426795427e+1L, 1.353324260375041625041625e+1L, -1.455875764860139860139860e+0L, 1.141794972063526751026751e+1L, + -1.184433684262785825285825e+1L, 1.278699298106503127183274e+0L, -1.007905722452572320449159e+1L, 1.048281481558423194452606e+1L, + 1.350000000000000000000000e+1L, -3.350000000000000000000000e+1L, 2.000000000000000000000000e+1L, -3.208333333333333333333333e+1L, + 9.941666666666666666666667e+1L, -6.766666666666666666666667e+1L, 2.120625000000000000000000e+1L, -7.075208333333333333333333e+1L, + 5.086666666666666666666667e+1L, -1.717187500000000000000000e+1L, 5.892752976190476190476190e+1L, -4.321964285714285714285714e+1L, + 1.450574156746031746031746e+1L, -5.058280009920634920634921e+1L, 3.752430555555555555555556e+1L, -1.252158301767676767676768e+1L, + 4.413284462932900432900433e+1L, -3.299036120129870129870130e+1L, 1.097070826580103923853924e+1L, -3.896734861004880536130536e+1L, + 2.929145060668498168498168e+1L, -9.722968745393061799311799e+0L, 3.474048783383500180375180e+1L, -2.622576735872634310134310e+1L, + -3.625000000000000000000000e+0L, 2.662500000000000000000000e+1L, -4.300000000000000000000000e+1L, 2.000000000000000000000000e+1L, + 8.947916666666666666666667e+0L, -9.776041666666666666666667e+1L, 1.903333333333333333333333e+2L, -1.008333333333333333333333e+2L, + -6.166666666666666666666667e+0L, 7.379583333333333333333333e+1L, -1.533875000000000000000000e+2L, 8.534166666666666666666667e+1L, + 5.136235119047619047619048e+0L, -6.393697916666666666666667e+1L, 1.363473214285714285714286e+2L, -7.736755952380952380952381e+1L, + -4.436524987599206349206349e+0L, 5.655608103918650793650794e+1L, -1.224825644841269841269841e+2L, 7.034930555555555555555556e+1L, + 3.899895967205537518037518e+0L, -5.053718282856466450216450e+1L, 1.106300240124458874458874e+2L, -6.409010078463203463203463e+1L, + -3.468855737361596736596737e+0L, 4.550171517935189810189810e+1L, -1.004129156813238844488844e+2L, 5.855101054544413919413919e+1L, + 3.113750278313266594516595e+0L, -4.123187571570139929514930e+1L, 9.156745570781215312465312e+1L, -5.366834736173115079365079e+1L, + -1.025000000000000000000000e+1L, 3.525000000000000000000000e+1L, -3.900000000000000000000000e+1L, 1.400000000000000000000000e+1L, + 4.944791666666666666666667e+1L, -2.395104166666666666666667e+2L, 3.340000000000000000000000e+2L, -1.438333333333333333333333e+2L, + -3.875104166666666666666667e+1L, 2.033322916666666666666667e+2L, -3.002958333333333333333333e+2L, 1.351500000000000000000000e+2L, + 3.456104910714285714285714e+1L, -1.874757068452380952380952e+2L, 2.836595238095238095238095e+2L, -1.301657738095238095238095e+2L, + -3.129428323412698412698413e+1L, 1.732965029761904761904762e+2L, -2.662868303571428571428571e+2L, 1.237622519841269841269841e+2L, + 2.850746841320571789321789e+1L, -1.602003273175392316017316e+2L, 2.489350344967532467532468e+2L, -1.167903239989177489177489e+2L, + -2.608437076026187354312354e+1L, 1.482330410596890089077589e+2L, -2.323372454856341575091575e+2L, 1.098045401213369963369963e+2L, + 1.906250000000000000000000e+0L, -1.215625000000000000000000e+1L, 1.775000000000000000000000e+1L, -7.500000000000000000000000e+0L, + -1.118750000000000000000000e+1L, 1.705208333333333333333333e+2L, -5.098958333333333333333333e+2L, 5.482500000000000000000000e+2L, + -1.980000000000000000000000e+2L, 8.906250000000000000000000e+0L, -1.500036458333333333333333e+2L, 4.803520833333333333333333e+2L, + -5.434562500000000000000000e+2L, 2.043000000000000000000000e+2L, -8.078097098214285714285714e+0L, 1.422622209821428571428571e+2L, + -4.693909226190476190476190e+2L, 5.435208333333333333333333e+2L, -2.082726190476190476190476e+2L, 7.428141663566468253968254e+0L, + -1.345740904792906746031746e+2L, 4.527555648561507936507937e+2L, -5.324863715277777777777778e+2L, 2.067537698412698412698413e+2L, + -6.859179546581890331890332e+0L, 1.268240408408865440115440e+2L, -4.328362513950892857142857e+2L, 5.150291455289502164502165e+2L, + -2.019904356060606060606061e+2L, 6.351151506913225663225663e+0L, -1.192807194500920086857587e+2L, 4.116648423597886488511489e+2L, + -4.943630642063015109890110e+2L, 1.954390267284798534798535e+2L, 4.687500000000000000000000e-1L, 1.953125000000000000000000e+1L, + -6.550000000000000000000000e+1L, 6.950000000000000000000000e+1L, -2.400000000000000000000000e+1L, -6.983854166666666666666667e+1L, + 4.625989583333333333333333e+2L, -9.817291666666666666666667e+2L, 8.535833333333333333333333e+2L, -2.646666666666666666666667e+2L, + 6.257161458333333333333333e+1L, -4.506960937500000000000000e+2L, 1.015225000000000000000000e+3L, -9.240479166666666666666667e+2L, + 2.972666666666666666666667e+2L, -6.049795386904761904761905e+1L, 4.524463355654761904761905e+2L, -1.047891592261904761904762e+3L, + 9.753760416666666666666667e+2L, -3.197392857142857142857143e+2L, 5.821694529699900793650794e+1L, -4.462936744326636904761905e+2L, + 1.053366610863095238095238e+3L, -9.959439856150793650793651e+2L, 3.309095238095238095238095e+2L, -5.568890225849454365079365e+1L, + 4.348119304970745400432900e+2L, -1.041041118565679112554113e+3L, 9.962014187635281385281385e+2L, -3.344852768759018759018759e+2L, + 4.062500000000000000000000e-1L, -2.946875000000000000000000e+1L, 1.521875000000000000000000e+2L, -2.771250000000000000000000e+2L, + 2.140000000000000000000000e+2L, -6.000000000000000000000000e+1L, 1.353776041666666666666667e+1L, -2.657643229166666666666667e+2L, + 1.075822916666666666666667e+3L, -1.751406250000000000000000e+3L, 1.273166666666666666666667e+3L, -3.451666666666666666666667e+2L, + -1.211363932291666666666667e+1L, 2.642111653645833333333333e+2L, -1.148338541666666666666667e+3L, 1.970841666666666666666667e+3L, + -1.493616666666666666666667e+3L, 4.189916666666666666666667e+2L, 1.181055268787202380952381e+1L, -2.705470598493303571428571e+2L, + 1.216061123511904761904762e+3L, -2.142552008928571428571429e+3L, 1.659297321428571428571429e+3L, -4.741383928571428571428571e+2L, + -1.147685934399801587301587e+1L, 2.715722733754960317460317e+2L, -1.249084499782986111111111e+3L, 2.241853734188988095238095e+3L, + -1.763605505952380952380952e+3L, 5.108562500000000000000000e+2L, 1.108360103370479347041847e+1L, -2.686557959354285037878788e+2L, + 1.257480520713552940115440e+3L, -2.289479417888426677489177e+3L, 1.823340293560606060606061e+3L, -5.339046097132034632034632e+2L, + 1.554687500000000000000000e+1L, -1.639843750000000000000000e+2L, 5.141875000000000000000000e+2L, -7.077500000000000000000000e+2L, + 4.520000000000000000000000e+2L, -1.100000000000000000000000e+2L, 9.313932291666666666666667e+1L, -7.845742187500000000000000e+2L, + 2.241708333333333333333333e+3L, -2.942239583333333333333333e+3L, 1.832833333333333333333333e+3L, -4.408333333333333333333333e+2L, + -9.307369791666666666666667e+1L, 8.551434895833333333333333e+2L, -2.598971354166666666666667e+3L, 3.577051041666666666666667e+3L, + -2.315241666666666666666667e+3L, 5.748833333333333333333333e+2L, 9.644270949590773809523810e+1L, -9.235574067615327380952381e+2L, + 2.895056696428571428571429e+3L, -4.085269233630952380952381e+3L, 2.700209226190476190476190e+3L, -6.826925595238095238095238e+2L, + -9.797485138423859126984127e+1L, 9.652492945110987103174603e+2L, -3.092797150142609126984127e+3L, 4.444287233382936507936508e+3L, + -2.983654464285714285714286e+3L, 7.647427083333333333333333e+2L, -3.167968750000000000000000e+0L, 1.029804687500000000000000e+2L, + -5.787187500000000000000000e+2L, 1.322406250000000000000000e+3L, -1.481000000000000000000000e+3L, 8.135000000000000000000000e+2L, + -1.760000000000000000000000e+2L, -1.598307291666666666666667e+1L, 3.846448567708333333333333e+2L, -1.967231770833333333333333e+3L, + 4.298145833333333333333333e+3L, -4.707791666666666666666667e+3L, 2.561083333333333333333333e+3L, -5.530000000000000000000000e+2L, + 1.576166178385416666666667e+1L, -4.231248291015625000000000e+2L, 2.328983528645833333333333e+3L, -5.374581770833333333333333e+3L, + 6.146847916666666666666667e+3L, -3.464702083333333333333333e+3L, 7.708166666666666666666667e+2L, -1.636051897321428571428571e+1L, + 4.630922316778273809523810e+2L, -2.644695435732886904761905e+3L, 6.282026543898809523809524e+3L, -7.358093750000000000000000e+3L, + 4.232499404761904761904762e+3L, -9.584029761904761904761905e+2L, 1.670456610785590277777778e+1L, -4.902518266950334821428571e+2L, + 2.873949848477802579365079e+3L, -6.972009934198288690476190e+3L, 8.312989118303571428571429e+3L, -4.856232626488095238095238e+3L, + 1.114755555555555555555556e+3L, -3.750390625000000000000000e+1L, 4.295351562500000000000000e+2L, -1.620750000000000000000000e+3L, + 2.914718750000000000000000e+3L, -2.758500000000000000000000e+3L, 1.332500000000000000000000e+3L, -2.600000000000000000000000e+2L, + -1.192330729166666666666667e+2L, 1.220496744791666666666667e+3L, -4.389898437500000000000000e+3L, 7.717734375000000000000000e+3L, + -7.235208333333333333333333e+3L, 3.489083333333333333333333e+3L, -6.830000000000000000000000e+2L, 1.305701416015625000000000e+2L, + -1.461664461263020833333333e+3L, 5.603630859375000000000000e+3L, -1.034818723958333333333333e+4L, 1.009431041666666666666667e+4L, + -5.031643750000000000000000e+3L, 1.013133333333333333333333e+3L, -1.437563610258556547619048e+2L, 1.683043911016555059523810e+3L, + -6.673404838634672619047619e+3L, 1.266375954241071428571429e+4L, -1.263860833333333333333333e+4L, 6.425015029761904761904762e+3L, + -1.316177976190476190476190e+3L, 6.285644531250000000000000e+0L, -2.120122070312500000000000e+2L, 1.388070312500000000000000e+3L, + -3.907968750000000000000000e+3L, 5.787500000000000000000000e+3L, -4.744875000000000000000000e+3L, 2.047000000000000000000000e+3L, + -3.640000000000000000000000e+2L, 1.851005045572916666666667e+1L, -5.281245524088541666666667e+2L, 3.267272786458333333333333e+3L, + -8.966954427083333333333333e+3L, 1.313944791666666666666667e+4L, -1.074855208333333333333333e+4L, 4.650666666666666666666667e+3L, + -8.321666666666666666666667e+2L, -1.982605794270833333333333e+1L, 6.330649414062500000000000e+2L, -4.224345426432291666666667e+3L, + 1.226755745442708333333333e+4L, -1.879862708333333333333333e+4L, 1.595428750000000000000000e+4L, -7.120745833333333333333333e+3L, + 1.308641666666666666666667e+3L, 2.174890427362351190476190e+1L, -7.348345104399181547619048e+2L, 5.102358878580729166666667e+3L, + -1.528741827683221726190476e+4L, 2.403813422619047619047619e+4L, -2.085353013392857142857143e+4L, 9.486444940476190476190476e+3L, + -1.772961607142857142857143e+3L, 6.513281250000000000000000e+1L, -8.460312500000000000000000e+2L, 3.786851562500000000000000e+3L, + -8.460328125000000000000000e+3L, 1.063812500000000000000000e+4L, -7.692750000000000000000000e+3L, 2.999000000000000000000000e+3L, + -4.900000000000000000000000e+2L, 1.480092366536458333333333e+2L, -1.784694376627604166666667e+3L, 7.744819010416666666666667e+3L, + -1.708011328125000000000000e+4L, 2.140363541666666666666667e+4L, -1.551213541666666666666667e+4L, 6.082333333333333333333333e+3L, + -1.001833333333333333333333e+3L, -1.753112833658854166666667e+2L, 2.317370487467447916666667e+3L, -1.073956788736979166666667e+4L, + 2.491893398437500000000000e+4L, -3.253710416666666666666667e+4L, 2.440383645833333333333333e+4L, -9.852887500000000000000000e+3L, + 1.664616666666666666666667e+3L, -9.694702148437500000000000e+0L, 3.594730224609375000000000e+2L, -2.717610351562500000000000e+3L, + 9.135957031250000000000000e+3L, -1.686734375000000000000000e+4L, 1.841246875000000000000000e+4L, -1.190775000000000000000000e+4L, + 4.234500000000000000000000e+3L, -6.400000000000000000000000e+2L, -2.110774739583333333333333e+1L, 6.970181477864583333333333e+2L, + -5.062434163411458333333333e+3L, 1.673657519531250000000000e+4L, -3.073654687500000000000000e+4L, 3.359035416666666666666667e+4L, + -2.183385416666666666666667e+4L, 7.823250000000000000000000e+3L, -1.193333333333333333333333e+3L, 2.428554890950520833333333e+1L, + -9.000167277018229166666667e+2L, 7.065206958007812500000000e+3L, -2.475803884277343750000000e+4L, 4.761817539062500000000000e+4L, + -5.405751822916666666666667e+4L, 3.628541041666666666666667e+4L, -1.336631458333333333333333e+4L, 2.088800000000000000000000e+3L, + -9.819055175781250000000000e+1L, 1.441911254882812500000000e+3L, -7.497623046875000000000000e+3L, 2.005871484375000000000000e+4L, + -3.149621875000000000000000e+4L, 3.035740625000000000000000e+4L, -1.775350000000000000000000e+4L, 5.803500000000000000000000e+3L, + -8.160000000000000000000000e+2L, -1.793659871419270833333333e+2L, 2.490849751790364583333333e+3L, -1.266537036132812500000000e+4L, + 3.361304101562500000000000e+4L, -5.275893750000000000000000e+4L, 5.106103645833333333333333e+4L, -3.006852083333333333333333e+4L, + 9.915250000000000000000000e+3L, -1.408000000000000000000000e+3L, 1.334814453125000000000000e+1L, -5.477624511718750000000000e+2L, + 4.713708740234375000000000e+3L, -1.845568505859375000000000e+4L, 4.085967187500000000000000e+4L, -5.574496875000000000000000e+4L, + 4.807831250000000000000000e+4L, -2.565662500000000000000000e+4L, 7.760000000000000000000000e+3L, -1.020000000000000000000000e+3L, + 2.376726786295572916666667e+1L, -8.920257822672526041666667e+2L, 7.442021280924479166666667e+3L, -2.879394706217447916666667e+4L, + 6.359266406250000000000000e+4L, -8.701037369791666666666667e+4L, 7.550348958333333333333333e+4L, -4.062119791666666666666667e+4L, + 1.240283333333333333333333e+4L, -1.647166666666666666666667e+3L, 1.364589233398437500000000e+2L, -2.244362976074218750000000e+3L, + 1.331767944335937500000000e+4L, -4.154675976562500000000000e+4L, 7.828409375000000000000000e+4L, -9.434492187500000000000000e+4L, + 7.360156250000000000000000e+4L, -3.611175000000000000000000e+4L, 1.016200000000000000000000e+4L, -1.254000000000000000000000e+3L, + -1.721046447753906250000000e+1L, 7.789048004150390625000000e+2L, -7.530210571289062500000000e+3L, 3.368366662597656250000000e+4L, + -8.701270898437500000000000e+4L, 1.425074960937500000000000e+5L, -1.537169687500000000000000e+5L, 1.094420312500000000000000e+5L, + -4.968650000000000000000000e+4L, 1.307150000000000000000000e+4L, -1.520000000000000000000000e+3L, +}; diff --git a/src/framework/parameters/extra.cpp b/src/framework/parameters/extra.cpp index cf7e3bc87..c3602eacd 100644 --- a/src/framework/parameters/extra.cpp +++ b/src/framework/parameters/extra.cpp @@ -10,6 +10,7 @@ #include +#include #include #include #include @@ -117,6 +118,98 @@ namespace ntt { compton_nominal_photon_energy = ONE / SQR(compton_gamma_qed.value()); } + if (extra.at("bethe_heitler_emission")) { + const auto bh = toml::find(toml_data, "radiation", "emission", "bethe_heitler"); + bethe_heitler_electron_species = toml::find(bh, "electron_species"); + bethe_heitler_positron_species = toml::find(bh, "positron_species"); + bethe_heitler_optical_depth = toml::find(bh, "optical_depth"); + bethe_heitler_mass_ratio = toml::find_or( + bh, + "mass_ratio", + defaults::bethe_heitler::mass_ratio); + bethe_heitler_pair_weight = toml::find_or( + bh, + "pair_weight", + defaults::bethe_heitler::pair_weight); + bethe_heitler_max_probability = toml::find_or( + bh, + "max_probability", + defaults::bethe_heitler::max_probability); + bethe_heitler_max_loss_fraction = toml::find_or( + bh, + "max_loss_fraction", + defaults::bethe_heitler::max_loss_fraction); + bethe_heitler_gamma_max = toml::find_or(bh, + "gamma_max", + defaults::bethe_heitler::gamma_max); + bethe_heitler_photon_spectrum = fmt::toLower( + toml::find_or(bh, + "photon_spectrum", + defaults::bethe_heitler::photon_spectrum)); + // the keys each spectrum needs are required, the others unused + const auto& spectrum = bethe_heitler_photon_spectrum.value(); + if (spectrum == "mono") { + bethe_heitler_photon_energy = toml::find(bh, "photon_energy"); + } else if (spectrum == "powerlaw") { + bethe_heitler_photon_energy_min = toml::find(bh, "photon_energy_min"); + bethe_heitler_photon_energy_max = toml::find(bh, "photon_energy_max"); + bethe_heitler_photon_index = toml::find(bh, "photon_index"); + } else if (spectrum == "blackbody") { + bethe_heitler_photon_temperature = toml::find( + bh, + "photon_temperature"); + bethe_heitler_photon_energy_min = toml::find_or(bh, + "photon_energy_min", + ZERO); + bethe_heitler_photon_energy_max = toml::find(bh, "photon_energy_max"); + } else { + raise::Error("radiation.emission.bethe_heitler.photon_spectrum must " + "be mono, powerlaw or blackbody", + HERE); + } + // comparisons with a NaN are false: it would pass the checks below + for (const auto& value : { bethe_heitler_optical_depth, + bethe_heitler_mass_ratio, + bethe_heitler_pair_weight, + bethe_heitler_max_probability, + bethe_heitler_max_loss_fraction, + bethe_heitler_gamma_max, + bethe_heitler_photon_energy, + bethe_heitler_photon_energy_min, + bethe_heitler_photon_energy_max, + bethe_heitler_photon_index, + bethe_heitler_photon_temperature }) { + raise::ErrorIf(value.has_value() and not std::isfinite(value.value()), + "Bethe-Heitler parameters must be finite", + HERE); + } + raise::ErrorIf(bethe_heitler_electron_species.value() == + bethe_heitler_positron_species.value(), + "Bethe-Heitler electron_species and positron_species " + "must be different", + HERE); + raise::ErrorIf(bethe_heitler_optical_depth.value() < ZERO, + "Bethe-Heitler optical_depth must be >= 0", + HERE); + raise::ErrorIf(bethe_heitler_pair_weight.value() <= ZERO, + "Bethe-Heitler pair_weight must be > 0", + HERE); + raise::ErrorIf( + (bethe_heitler_pair_weight.value() != ONE) and + (not params->template get("particles.use_weights")), + "Bethe-Heitler pair_weight != 1 requires " + "particles.use_weights = true", + HERE); + raise::ErrorIf((bethe_heitler_max_probability.value() <= ZERO) or + (bethe_heitler_max_probability.value() > ONE), + "Bethe-Heitler max_probability must be in (0, 1]", + HERE); + raise::ErrorIf((bethe_heitler_max_loss_fraction.value() <= ZERO) or + (bethe_heitler_max_loss_fraction.value() >= ONE), + "Bethe-Heitler max_loss_fraction must be in (0, 1)", + HERE); + } + if (toml_data.contains("two_body") and toml_data.at("two_body").contains("thomson_mean_free_path")) { twobody_thomson_mean_free_path = toml::find( @@ -197,6 +290,34 @@ namespace ntt { compton_nominal_photon_energy.value()); } + if (extra.at("bethe_heitler_emission")) { + const std::string prefix = "radiation.emission.bethe_heitler."; + params->set(prefix + "electron_species", + bethe_heitler_electron_species.value()); + params->set(prefix + "positron_species", + bethe_heitler_positron_species.value()); + params->set(prefix + "optical_depth", bethe_heitler_optical_depth.value()); + params->set(prefix + "mass_ratio", bethe_heitler_mass_ratio.value()); + params->set(prefix + "pair_weight", bethe_heitler_pair_weight.value()); + params->set(prefix + "max_probability", + bethe_heitler_max_probability.value()); + params->set(prefix + "max_loss_fraction", + bethe_heitler_max_loss_fraction.value()); + params->set(prefix + "gamma_max", bethe_heitler_gamma_max.value()); + params->set(prefix + "photon_spectrum", + bethe_heitler_photon_spectrum.value()); + params->set(prefix + "photon_energy", + bethe_heitler_photon_energy.value_or(ZERO)); + params->set(prefix + "photon_energy_min", + bethe_heitler_photon_energy_min.value_or(ZERO)); + params->set(prefix + "photon_energy_max", + bethe_heitler_photon_energy_max.value_or(ZERO)); + params->set(prefix + "photon_index", + bethe_heitler_photon_index.value_or(ZERO)); + params->set(prefix + "photon_temperature", + bethe_heitler_photon_temperature.value_or(ZERO)); + } + params->set("two_body.thomson_optical_depth", twobody_thomson_optical_depth.value()); params->set("two_body.thomson_mean_free_path", diff --git a/src/framework/parameters/extra.h b/src/framework/parameters/extra.h index 2da7728bd..0a849af88 100644 --- a/src/framework/parameters/extra.h +++ b/src/framework/parameters/extra.h @@ -56,6 +56,21 @@ namespace ntt { std::optional compton_nominal_probability; std::optional compton_nominal_photon_energy; + std::optional bethe_heitler_electron_species; + std::optional bethe_heitler_positron_species; + std::optional bethe_heitler_optical_depth; + std::optional bethe_heitler_mass_ratio; + std::optional bethe_heitler_pair_weight; + std::optional bethe_heitler_max_probability; + std::optional bethe_heitler_max_loss_fraction; + std::optional bethe_heitler_gamma_max; + std::optional bethe_heitler_photon_spectrum; + std::optional bethe_heitler_photon_energy; + std::optional bethe_heitler_photon_energy_min; + std::optional bethe_heitler_photon_energy_max; + std::optional bethe_heitler_photon_index; + std::optional bethe_heitler_photon_temperature; + // two-body interaction parameters std::optional twobody_thomson_optical_depth; std::optional twobody_thomson_mean_free_path; diff --git a/src/framework/parameters/parameters.cpp b/src/framework/parameters/parameters.cpp index 080944b4c..22e25b94a 100644 --- a/src/framework/parameters/parameters.cpp +++ b/src/framework/parameters/parameters.cpp @@ -293,11 +293,14 @@ namespace ntt { /* extra physics ------------------------------------------------------ */ params::Extra extra_params {}; const std::map extra_extra_flags = { - { "synchrotron_drag",isPromised("radiation.drag.synchrotron.gamma_rad") }, - { "compton_drag", isPromised("radiation.drag.compton.gamma_rad") }, - { "synchrotron_emission", - isPromised("radiation.emission.synchrotron.photon_species") }, - { "compton_emission", isPromised("radiation.emission.compton.photon_species") } + { "synchrotron_drag",isPromised("radiation.drag.synchrotron.gamma_rad") }, + { "compton_drag", isPromised("radiation.drag.compton.gamma_rad") }, + { "synchrotron_emission", + isPromised("radiation.emission.synchrotron.photon_species") }, + { "compton_emission", + isPromised("radiation.emission.compton.photon_species") }, + { "bethe_heitler_emission", + isPromised("radiation.emission.bethe_heitler.electron_species") } }; extra_params.read(extra_extra_flags, toml_data, this); extra_params.setParams(extra_extra_flags, this); diff --git a/src/framework/parameters/particles.cpp b/src/framework/parameters/particles.cpp index 6f1a23c03..e56e0a78f 100644 --- a/src/framework/parameters/particles.cpp +++ b/src/framework/parameters/particles.cpp @@ -89,6 +89,8 @@ namespace ntt { return EmissionType::COMPTON; } else if (fmt::toLower(emission_policy_str) == "custom") { return EmissionType::CUSTOM; + } else if (fmt::toLower(emission_policy_str) == "bethe_heitler") { + return EmissionType::BETHE_HEITLER; } else { raise::Error(fmt::format("Invalid emission_policy value: %s", emission_policy_str.c_str()), @@ -165,7 +167,8 @@ namespace ntt { auto emission_policy_flag = getEmissionPolicyFlag(emission_policy_str); raise::ErrorIf((emission_policy_flag == EmissionType::SYNCHROTRON or - emission_policy_flag == EmissionType::COMPTON) and + emission_policy_flag == EmissionType::COMPTON or + emission_policy_flag == EmissionType::BETHE_HEITLER) and is_massless, "Radiative emission policies are only applicable to " "massive particles", @@ -207,6 +210,12 @@ namespace ntt { } else if (emission_policy_flag == EmissionType::COMPTON) { params->promiseToDefine("radiation.emission.compton.photon_species"); params->promiseToDefine("radiation.drag.compton.gamma_rad"); + } else if (emission_policy_flag == EmissionType::BETHE_HEITLER) { + raise::ErrorIf(engine_enum != SimEngine::SRPIC, + "Bethe-Heitler emission is only supported for SRPIC", + HERE); + params->promiseToDefine( + "radiation.emission.bethe_heitler.electron_species"); } return ParticleSpecies(idx, diff --git a/src/global/defaults.h b/src/global/defaults.h index a0d64af4c..7f0df781e 100644 --- a/src/global/defaults.h +++ b/src/global/defaults.h @@ -123,6 +123,15 @@ namespace ntt::defaults { namespace twobody { const real_t thomson_optical_depth = 1.0; } // namespace twobody + + namespace bethe_heitler { + const real_t mass_ratio = 1836.15267343; + const real_t pair_weight = 1.0; + const real_t max_probability = 0.1; + const real_t max_loss_fraction = 0.04; + const real_t gamma_max = 0.0; + const std::string photon_spectrum = "mono"; + } // namespace bethe_heitler } // namespace ntt::defaults #endif // GLOBAL_DEFAULTS_H diff --git a/src/global/enums.h b/src/global/enums.h index b88f2da95..9fdd38cc1 100644 --- a/src/global/enums.h +++ b/src/global/enums.h @@ -17,7 +17,7 @@ * * - enum ntt::ParticlePusher // photon, boris, vay, gca, none * - enum ntt::RadiativeDrag // compton, synchrotron, none - * - enum ntt::EmissionType // none, synchrotron, inversecompton, custom + * - enum ntt::EmissionType // none, synchrotron, inversecompton, custom, bethe_heitler * - enum ntt::OutputSmoothingTypeFlag // none, const, spline * * @namespaces: @@ -378,10 +378,11 @@ namespace ntt { namespace EmissionType { enum EmissionTypeFlag_ : uint8_t { - NONE = 0, - SYNCHROTRON = 1, - COMPTON = 2, - CUSTOM = 3, + NONE = 0, + SYNCHROTRON = 1, + COMPTON = 2, + CUSTOM = 3, + BETHE_HEITLER = 4, }; inline auto to_string(uint8_t flags) -> std::string { @@ -394,6 +395,8 @@ namespace ntt { return "compton"; case CUSTOM: return "custom"; + case BETHE_HEITLER: + return "bethe_heitler"; default: return "unknown"; } diff --git a/src/kernels/pushers/sr_policies.h b/src/kernels/pushers/sr_policies.h index cc34698a5..5cea1b695 100644 --- a/src/kernels/pushers/sr_policies.h +++ b/src/kernels/pushers/sr_policies.h @@ -21,11 +21,14 @@ #include "utils/comparators.h" #include "utils/param_container.h" +#include "archetypes/emission/bethe_heitler.h" #include "archetypes/emission/compton.h" #include "archetypes/emission/synchrotron.h" #include "framework/parameters/parameters.h" #include "kernels/pushers/context.h" +#include + namespace kernel::sr { template ( + "radiation.emission.bethe_heitler.electron_species"); + const auto positron_species = params.get( + "radiation.emission.bethe_heitler.positron_species"); + raise::ErrorIf(electron_species == 0u or positron_species == 0u or + electron_species > domain.species.size() or + positron_species > domain.species.size(), + "Invalid electron_species or positron_species for " + "Bethe-Heitler emission", + HERE); + raise::ErrorIf(electron_species == positron_species, + "Bethe-Heitler electron_species and positron_species " + "must be different", + HERE); + auto& electrons = domain.species[electron_species - 1]; + auto& positrons = domain.species[positron_species - 1]; + // the mass sets the energy of the particle: an infinite one passes + // `mass > 0` + raise::ErrorIf(not(pusher_ctx.mass > 0.0f) or + not std::isfinite(pusher_ctx.mass), + "Species with Bethe-Heitler emission must have a finite, " + "positive mass", + HERE); + // the lepton momenta are drawn in units of m_e c + raise::ErrorIf(not cmp::AlmostEqual_host(electrons.mass(), 1.0f) or + not cmp::AlmostEqual_host(positrons.mass(), 1.0f), + "Bethe-Heitler lepton species must have mass = 1 (the " + "unit of mass is the electron mass)", + HERE); + // a pair is neutral: the two charges must cancel exactly as stored, + // or every pair would add the difference to the charge of the grid + raise::ErrorIf(not(electrons.charge() < 0.0f) or + not std::isfinite(electrons.charge()) or + not(positrons.charge() == -electrons.charge()), + "Bethe-Heitler lepton species must have exactly opposite " + "charges (negative for electron_species)", + HERE); + auto& tables = ::arch::emission::bh::GetTables(params, pusher_ctx.dt); + return ::arch::emission::BetheHeitler(electrons, + positrons, + electron_species, + positron_species, + pusher_ctx.mass, + pusher_ctx.dt, + domain.index(), + params, + tables, + domain.random_pool()); } else { raise::Error("Invalid emission type for MakeEmissionPolicy", HERE); return ::traits::emission::NoPolicy_t {}; @@ -184,6 +236,12 @@ namespace kernel::sr { params, pusher_ctx)); break; + case ntt::EmissionType::BETHE_HEITLER: + next(MakePusherPolicyEmission( + domain, + params, + pusher_ctx)); + break; case ntt::EmissionType::CUSTOM: DispatchEmissionPolicy(pgen, domain, pusher_ctx, next); break; diff --git a/tests/archetypes/CMakeLists.txt b/tests/archetypes/CMakeLists.txt index 4c1aad515..fc67ecbb4 100644 --- a/tests/archetypes/CMakeLists.txt +++ b/tests/archetypes/CMakeLists.txt @@ -29,3 +29,4 @@ gen_test(field_setter) gen_test(powerlaw) gen_test(pgen) gen_test(qed_compton) +gen_test(bethe_heitler) diff --git a/tests/archetypes/bethe_heitler.cpp b/tests/archetypes/bethe_heitler.cpp new file mode 100644 index 000000000..d8393a9dc --- /dev/null +++ b/tests/archetypes/bethe_heitler.cpp @@ -0,0 +1,1048 @@ +#include "archetypes/emission/bethe_heitler.h" + +#include "enums.h" +#include "global.h" + +#include "arch/kokkos_aliases.h" +#include "utils/error.h" +#include "utils/formatting.h" +#include "utils/numeric.h" +#include "utils/param_container.h" + +#include "metrics/minkowski.h" + +#include "framework/containers/particles.h" +#include "kernels/deposition/currents/global.hpp" +#include "kernels/injectors.hpp" +#include "kernels/pushers/context.h" +#include "kernels/pushers/sr.hpp" +#include "kernels/pushers/sr_policies.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace ntt; + +namespace { + + using metric_t = metric::Minkowski; + using species_t = Particles; + using emission_t = arch::emission::BetheHeitler; + + constexpr ncells_t NX1 = 32u, NX2 = 24u; + + // monochromatic photons of 0.5 m_e c^2; emitters of mass 1 at Gamma_p = 10; + // tables up to Gamma_p = 12 + const double MASS_RATIO = 1836.15267343; + const double GAMMA_P = 10.0; + const double GAMMA_MAX = 12.0; + + void check(bool condition, const std::string& msg) { + if (not condition) { + throw std::runtime_error(msg); + } + } + + auto make_params(real_t optical_depth, + real_t pair_weight = ONE, + real_t max_probability = static_cast(0.1), + bool use_weights = false) -> prm::Parameters { + prm::Parameters params; + const std::string prefix = "radiation.emission.bethe_heitler."; + params.set(prefix + "electron_species", static_cast(1)); + params.set(prefix + "positron_species", static_cast(2)); + params.set(prefix + "optical_depth", optical_depth); + params.set(prefix + "mass_ratio", static_cast(MASS_RATIO)); + params.set(prefix + "pair_weight", pair_weight); + params.set(prefix + "max_probability", max_probability); + params.set(prefix + "max_loss_fraction", static_cast(0.04)); + params.set(prefix + "gamma_max", static_cast(GAMMA_MAX)); + params.set(prefix + "photon_spectrum", std::string("mono")); + params.set(prefix + "photon_energy", static_cast(0.5)); + params.set(prefix + "photon_energy_min", ZERO); + params.set(prefix + "photon_energy_max", ZERO); + params.set(prefix + "photon_index", ZERO); + params.set(prefix + "photon_temperature", ZERO); + params.set("particles.use_weights", use_weights); + return params; + } + + auto make_species(spidx_t index, float mass, float charge, npart_t maxnpart) + -> species_t { + return species_t(index, + "s" + std::to_string(index), + mass, + charge, + maxnpart, + 0u, + 0u, + ParticlePusher::BORIS, + false, + RadiativeDrag::NONE, + EmissionType::NONE, + 0u, + 0u); + } + + // momentum (in units of m c, for a species of mass 1) at the given Gamma_p + auto momentum_at(double gamma_p) -> double { + const double K = MASS_RATIO * (gamma_p - 1.0); + const double gamma = 1.0 + K; + return std::sqrt((gamma - 1.0) * (gamma + 1.0)); + } + + // emitters at random positions (in one cell if `one_cell`, and then at + // least `margin` away from its faces) with isotropic momenta of the same + // magnitude + void fill_emitters(species_t& emitters, + npart_t n, + double u, + std::uint64_t seed, + bool one_cell = false, + double margin = 0.0) { + auto i1_h = Kokkos::create_mirror_view(emitters.i1); + auto i2_h = Kokkos::create_mirror_view(emitters.i2); + auto dx1_h = Kokkos::create_mirror_view(emitters.dx1); + auto dx2_h = Kokkos::create_mirror_view(emitters.dx2); + auto ux1_h = Kokkos::create_mirror_view(emitters.ux1); + auto ux2_h = Kokkos::create_mirror_view(emitters.ux2); + auto ux3_h = Kokkos::create_mirror_view(emitters.ux3); + auto wei_h = Kokkos::create_mirror_view(emitters.weight); + auto tag_h = Kokkos::create_mirror_view(emitters.tag); + auto state = seed; + auto next = [&state]() { + // splitmix64 -> uniform in [0, 1) + state += 0x9E3779B97F4A7C15ULL; + std::uint64_t z = state; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; + z = z ^ (z >> 31); + return static_cast(z >> 11) * 0x1.0p-53; + }; + for (npart_t p = 0u; p < n; ++p) { + i1_h(p) = one_cell ? static_cast(NX1 / 2u) + : static_cast(next() * NX1); + i2_h(p) = one_cell ? static_cast(NX2 / 2u) + : static_cast(next() * NX2); + dx1_h(p) = static_cast(margin + (1.0 - 2.0 * margin) * next()); + dx2_h(p) = static_cast(margin + (1.0 - 2.0 * margin) * next()); + const double cos_t = 2.0 * next() - 1.0; + const double sin_t = std::sqrt(1.0 - cos_t * cos_t); + const double phi = 2.0 * constant::PI * next(); + ux1_h(p) = static_cast(u * sin_t * std::cos(phi)); + ux2_h(p) = static_cast(u * sin_t * std::sin(phi)); + ux3_h(p) = static_cast(u * cos_t); + wei_h(p) = ONE; + tag_h(p) = ParticleTag::alive; + } + Kokkos::deep_copy(emitters.i1, i1_h); + Kokkos::deep_copy(emitters.i2, i2_h); + Kokkos::deep_copy(emitters.dx1, dx1_h); + Kokkos::deep_copy(emitters.dx2, dx2_h); + Kokkos::deep_copy(emitters.ux1, ux1_h); + Kokkos::deep_copy(emitters.ux2, ux2_h); + Kokkos::deep_copy(emitters.ux3, ux3_h); + Kokkos::deep_copy(emitters.weight, wei_h); + Kokkos::deep_copy(emitters.tag, tag_h); + emitters.set_npart(n); + } + + auto pusher_context(const species_t& species, real_t dt) + -> kernel::sr::PusherContext { + return kernel::sr::PusherContext { species.index(), + species.pusher(), + species.radiative_drag_flags(), + species.mass(), + species.charge(), + static_cast(0), + dt, + ONE, + static_cast(NX1), + static_cast(NX2), + 1 }; + } + + // previous positions of all the slots of a species set to one point: the + // state that particles removed earlier leave behind + void set_previous(species_t& species, int i1, int i2, prtldx_t dx1, prtldx_t dx2) { + Kokkos::deep_copy(species.i1_prev, i1); + Kokkos::deep_copy(species.i2_prev, i2); + Kokkos::deep_copy(species.dx1_prev, dx1); + Kokkos::deep_copy(species.dx2_prev, dx2); + } + + // control: the same policy with the insertion of the built-in policies + // (kernel::InjectParticle alone), which leaves the previous position of + // the new particle as it finds it + struct WithoutPreviousPosition { + using Payload = emission_t::Payload; + + emission_t base; + + auto emitted_species_indices() const -> std::vector { + return base.emitted_species_indices(); + } + + auto numbers_injected() const -> std::vector { + return base.numbers_injected(); + } + + Inline auto shouldEmit(const coord_t& x_Cd, + const coord_t& x_Ph, + const vec_t& u_Ph, + const vec_t& ep_Ph, + const vec_t& bp_Ph, + vec_t& delta_u_Ph, + Payload& payload) const -> Kokkos::pair { + return base.shouldEmit(x_Cd, x_Ph, u_Ph, ep_Ph, bp_Ph, delta_u_Ph, payload); + } + + Inline void emit(const tuple_t& xi_Cd, + const tuple_t& dxi_Cd, + const vec_t&, + real_t weight, + real_t phi, + const Payload& payload) const { + const auto w = static_cast(base.pair_weight) * weight; + kernel::InjectParticle( + base.electron_offset + payload.ticket, + base.electron_i1, + base.electron_i2, + base.electron_i3, + base.electron_dx1, + base.electron_dx2, + base.electron_dx3, + base.electron_ux1, + base.electron_ux2, + base.electron_ux3, + base.electron_phi, + base.electron_weight, + base.electron_tag, + base.electron_pld_i, + xi_Cd, + dxi_Cd, + { payload.u_electron[0], payload.u_electron[1], payload.u_electron[2] }, + w, + phi); + kernel::InjectParticle( + base.positron_offset + payload.ticket, + base.positron_i1, + base.positron_i2, + base.positron_i3, + base.positron_dx1, + base.positron_dx2, + base.positron_dx3, + base.positron_ux1, + base.positron_ux2, + base.positron_ux3, + base.positron_phi, + base.positron_weight, + base.positron_tag, + base.positron_pld_i, + xi_Cd, + dxi_Cd, + { payload.u_positron[0], payload.u_positron[1], payload.u_positron[2] }, + w, + phi); + } + }; + + template + void push_emitters(species_t& emitters, + const E& emission, + const metric_t& metric, + const ndfield_t& EB, + real_t dt) { + const auto policy = kernel::sr::PusherPolicy { emission }; + const auto boundaries = kernel::sr::PusherBoundaries { + { { PrtlBC::PERIODIC, PrtlBC::PERIODIC }, + { PrtlBC::PERIODIC, PrtlBC::PERIODIC } } + }; + Kokkos::parallel_for("ParticlePusher", + emitters.rangeActiveParticles(), + kernel::sr::Pusher_kernel( + pusher_context(emitters, dt), + boundaries, + emitters, + EB, + metric, + policy)); + } + + // one push of the emitters with the Bethe-Heitler policy (or with the + // control that does not write the previous position); returns the number + // of pairs inserted + auto push_with_emission(species_t& emitters, + species_t& electrons, + species_t& positrons, + const metric_t& metric, + const ndfield_t& EB, + const prm::Parameters& params, + real_t dt, + random_number_pool_t& random_pool, + bool write_previous = true) -> npart_t { + auto& tables = arch::emission::bh::GetTables(params, dt); + const emission_t emission { electrons, + positrons, + electrons.index(), + positrons.index(), + emitters.mass(), + dt, + 0u, + params, + tables, + random_pool }; + // the push, then what the engine does with the answers of the policy: + // the species it names receive the numbers of particles it reports + const auto push_and_count = [&](const auto& policy) -> npart_t { + push_emitters(emitters, policy, metric, EB, dt); + const auto species = policy.emitted_species_indices(); + const auto n_injected = policy.numbers_injected(); + check(species.size() == 2u and n_injected.size() == 2u and + species[0] == electrons.index() and species[1] == positrons.index(), + "the policy does not name the electron and the positron species"); + electrons.set_npart(electrons.npart() + n_injected[0]); + electrons.set_counter(electrons.counter() + n_injected[0]); + positrons.set_npart(positrons.npart() + n_injected[1]); + positrons.set_counter(positrons.counter() + n_injected[1]); + return n_injected[0]; + }; + return write_previous ? push_and_count(emission) + : push_and_count(WithoutPreviousPosition { emission }); + } + + void push_plain(species_t& species, + const metric_t& metric, + const ndfield_t& EB, + real_t dt) { + const auto policy = kernel::sr::PusherPolicy {}; + const auto boundaries = kernel::sr::PusherBoundaries { + { { PrtlBC::PERIODIC, PrtlBC::PERIODIC }, + { PrtlBC::PERIODIC, PrtlBC::PERIODIC } } + }; + Kokkos::parallel_for("ParticlePusher", + species.rangeActiveParticles(), + kernel::sr::Pusher_kernel( + pusher_context(species, dt), + boundaries, + species, + EB, + metric, + policy)); + } + + // currents of one species, folded periodically onto the active cells: + // J[comp][i + NX1 * j] accumulated in double on the host + void deposit(const species_t& species, + const metric_t& metric, + real_t dt, + std::vector>& J) { + ndfield_t cur { "cur", NX1 + 2u * N_GHOSTS, NX2 + 2u * N_GHOSTS }; + auto scatter_cur = Kokkos::Experimental::create_scatter_view(cur); + Kokkos::parallel_for( + "CurrentsDeposit", + species.rangeActiveParticles(), + kernel::DepositCurrents_kernel( + scatter_cur, + species, + metric, + static_cast(species.charge()), + dt)); + Kokkos::Experimental::contribute(cur, scatter_cur); + auto cur_h = Kokkos::create_mirror_view(cur); + Kokkos::deep_copy(cur_h, cur); + const int n1 = static_cast(NX1), n2 = static_cast(NX2); + const int ng = static_cast(N_GHOSTS); + for (int g1 = 0; g1 < n1 + 2 * ng; ++g1) { + for (int g2 = 0; g2 < n2 + 2 * ng; ++g2) { + const int i = ((g1 - ng) % n1 + n1) % n1; + const int j = ((g2 - ng) % n2 + n2) % n2; + for (int c = 0; c < 3; ++c) { + J[c][i + n1 * j] += static_cast(cur_h(g1, g2, c)); + } + } + } + } + + // charge on the nodes with the first-order shape (the one of the deposit) + void charge_density(const species_t& species, std::vector& rho) { + auto i1_h = Kokkos::create_mirror_view(species.i1); + auto i2_h = Kokkos::create_mirror_view(species.i2); + auto dx1_h = Kokkos::create_mirror_view(species.dx1); + auto dx2_h = Kokkos::create_mirror_view(species.dx2); + auto wei_h = Kokkos::create_mirror_view(species.weight); + auto tag_h = Kokkos::create_mirror_view(species.tag); + Kokkos::deep_copy(i1_h, species.i1); + Kokkos::deep_copy(i2_h, species.i2); + Kokkos::deep_copy(dx1_h, species.dx1); + Kokkos::deep_copy(dx2_h, species.dx2); + Kokkos::deep_copy(wei_h, species.weight); + Kokkos::deep_copy(tag_h, species.tag); + const int n1 = static_cast(NX1), n2 = static_cast(NX2); + const double q = static_cast(species.charge()); + for (npart_t p = 0u; p < species.npart(); ++p) { + if (tag_h(p) != ParticleTag::alive) { + continue; + } + const double w = q * static_cast(wei_h(p)); + const double fx = static_cast(dx1_h(p)); + const double fy = static_cast(dx2_h(p)); + const int i = (i1_h(p) % n1 + n1) % n1, ip = (i + 1) % n1; + const int j = (i2_h(p) % n2 + n2) % n2, jp = (j + 1) % n2; + rho[i + n1 * j] += w * (1.0 - fx) * (1.0 - fy); + rho[ip + n1 * j] += w * fx * (1.0 - fy); + rho[i + n1 * jp] += w * (1.0 - fx) * fy; + rho[ip + n1 * jp] += w * fx * fy; + } + } + + // max over the nodes of |d rho / dt + div J| + auto continuity_residual(const std::vector& rho_old, + const std::vector& rho_new, + const std::vector>& J, + double dt) -> double { + const int n1 = static_cast(NX1), n2 = static_cast(NX2); + double residual = 0.0; + for (int i = 0; i < n1; ++i) { + for (int j = 0; j < n2; ++j) { + const int im = (i - 1 + n1) % n1, jm = (j - 1 + n2) % n2; + const double r = (rho_new[i + n1 * j] - rho_old[i + n1 * j]) / dt + + (J[0][i + n1 * j] - J[0][im + n1 * j]) + + (J[1][i + n1 * j] - J[1][i + n1 * jm]); + residual = std::max(residual, std::abs(r)); + } + } + return residual; + } + + // kinetic energies [m c^2] of the particles of a species, in double + auto kinetic_energies(const species_t& species) -> std::vector { + auto ux1_h = Kokkos::create_mirror_view(species.ux1); + auto ux2_h = Kokkos::create_mirror_view(species.ux2); + auto ux3_h = Kokkos::create_mirror_view(species.ux3); + Kokkos::deep_copy(ux1_h, species.ux1); + Kokkos::deep_copy(ux2_h, species.ux2); + Kokkos::deep_copy(ux3_h, species.ux3); + std::vector K(species.npart()); + for (npart_t p = 0u; p < species.npart(); ++p) { + const double u_sqr = static_cast(ux1_h(p)) * ux1_h(p) + + static_cast(ux2_h(p)) * ux2_h(p) + + static_cast(ux3_h(p)) * ux3_h(p); + K[p] = u_sqr / (std::sqrt(1.0 + u_sqr) + 1.0); + } + return K; + } + + // the part of a domain that the factory of the policy uses + struct MockDomain { + std::deque species; + random_number_pool_t pool { 1 }; + + void add_species(float mass, float charge) { + const auto index = static_cast(species.size() + 1u); + species.emplace_back(index, + "s" + std::to_string(index), + mass, + charge, + 16u, + 0u, + 0u, + ParticlePusher::BORIS, + false, + RadiativeDrag::NONE, + EmissionType::NONE, + 0u, + 0u); + } + + auto index() const -> unsigned int { + return 0u; + } + + auto random_pool() -> random_number_pool_t& { + return pool; + } + }; + + /* + * Charge conservation of the newly created pairs. One step of 2000 + * emitters in a periodic box: + * - leptons not yet pushed (species listed before the emitters): their + * in-plane current is exactly zero, and the continuity equation holds + * for all the species together; + * - leptons pushed in the same step (species listed after the + * emitters): the continuity equation holds. + */ + void test_charge() { + const metric_t metric { + { NX1, NX2 }, + { { 0.0, static_cast(NX1) }, { 0.0, static_cast(NX2) } }, + {} + }; + const auto dt = static_cast(0.45); + const ndfield_t EB { "EB", NX1 + 2u * N_GHOSTS, NX2 + 2u * N_GHOSTS }; + random_number_pool_t random_pool { 12345 }; + + const npart_t n_emitters = 2000u; + auto electrons = make_species(1, 1.0f, -1.0f, n_emitters); + auto positrons = make_species(2, 1.0f, 1.0f, n_emitters); + auto emitters = make_species(3, 1.0f, 1.0f, n_emitters); + fill_emitters(emitters, n_emitters, momentum_at(GAMMA_P), 1u); + + // optical depth giving a probability of 0.07 per step at GAMMA_P + auto params = make_params(static_cast(1e-6)); + const auto rate = arch::emission::bh::GetTables(params, dt).rate(GAMMA_P); + params = make_params(static_cast(0.07 / (rate * dt))); + + const std::size_t n_nodes = NX1 * NX2; + std::vector rho_old(n_nodes, 0.0); + charge_density(emitters, rho_old); + + const auto n_pairs = push_with_emission(emitters, + electrons, + positrons, + metric, + EB, + params, + dt, + random_pool); + check(n_pairs > 100u, "charge: too few pairs created"); + check(electrons.npart() == n_pairs and positrons.npart() == n_pairs, + "charge: wrong number of leptons"); + + // round-off of the deposit: the offsets within the cell are stored (and + // partly summed) in `prtldx_t` whatever the precision of the build + const double eps = std::max( + static_cast(std::numeric_limits::epsilon()), + static_cast(std::numeric_limits::epsilon())); + + double residual_unpushed { 0.0 }, residual_pushed { 0.0 }; + + // leptons not yet pushed + { + std::vector> J_leptons(3, + std::vector(n_nodes, 0.0)); + deposit(electrons, metric, dt, J_leptons); + deposit(positrons, metric, dt, J_leptons); + double j_max = 0.0; + for (std::size_t n = 0; n < n_nodes; ++n) { + j_max = std::max(j_max, std::abs(J_leptons[0][n])); + j_max = std::max(j_max, std::abs(J_leptons[1][n])); + } + check( + j_max == 0.0, + fmt::format("charge: in-plane current of unpushed leptons %.3e != 0", + j_max)); + + auto J_all = J_leptons; + deposit(emitters, metric, dt, J_all); + std::vector rho_new(n_nodes, 0.0); + charge_density(emitters, rho_new); + charge_density(electrons, rho_new); + charge_density(positrons, rho_new); + residual_unpushed = continuity_residual(rho_old, rho_new, J_all, dt); + check(residual_unpushed < 100.0 * eps, + fmt::format("charge: continuity residual %.3e (leptons not pushed)", + residual_unpushed)); + } + + // leptons pushed in the step in which they are created + { + push_plain(electrons, metric, EB, dt); + push_plain(positrons, metric, EB, dt); + std::vector> J_all(3, std::vector(n_nodes, 0.0)); + deposit(emitters, metric, dt, J_all); + deposit(electrons, metric, dt, J_all); + deposit(positrons, metric, dt, J_all); + std::vector rho_new(n_nodes, 0.0); + charge_density(emitters, rho_new); + charge_density(electrons, rho_new); + charge_density(positrons, rho_new); + residual_pushed = continuity_residual(rho_old, rho_new, J_all, dt); + check(residual_pushed < 100.0 * eps, + fmt::format("charge: continuity residual %.3e (leptons pushed)", + residual_pushed)); + } + std::cout << fmt::format("charge: %u pairs, continuity residuals %.3e " + "(leptons not pushed) and %.3e (pushed)", + n_pairs, + residual_unpushed, + residual_pushed) + << std::endl; + } + + // largest in-plane current that one species deposits + auto max_inplane_current(const species_t& species, + const metric_t& metric, + real_t dt, + std::vector>& J_all) -> double { + std::vector> J(3, std::vector(NX1 * NX2, 0.0)); + deposit(species, metric, dt, J); + double j_max = 0.0; + for (std::size_t n = 0; n < NX1 * NX2; ++n) { + j_max = std::max(j_max, std::abs(J[0][n])); + j_max = std::max(j_max, std::abs(J[1][n])); + for (int c = 0; c < 3; ++c) { + J_all[c][n] += J[c][n]; + } + } + return j_max; + } + + /* + * Charge conservation when the slots of the new leptons have been used + * before. 2000 emitters in one cell; the previous positions of all the + * lepton slots are set to one point for the electrons and to another for + * the positrons, in two arms: + * - same cell: both points are in the cell of the emitters, so the + * offsets within the cell differ from those of the new leptons and the + * cell indices do not; + * - neighbouring cells: the two points are in the two cells diagonally + * opposite across the cell of the emitters, so the cell indices differ + * too, in both directions. The emitters stay in the middle half of + * their cell, which keeps every displacement that the deposit can be + * given, with the previous position written in full, in part or not at + * all, within one cell. + * In each arm, with the leptons not yet pushed: + * - each lepton species alone deposits no in-plane current, and the + * continuity equation holds for all the species together; + * - control: on the same state, the insertion of the built-in policies, + * which does not write the previous position, must violate both (the + * continuity equation by more than 1000 times the limit). + * A policy that wrote only the cell indices or only the offsets, only one + * direction or only one species fails one of the two arms. The test is + * two-dimensional: the previous position in the third direction is not + * exercised, and a policy that failed to write that one alone would pass. + */ + void test_charge_reused_slots() { + const metric_t metric { + { NX1, NX2 }, + { { 0.0, static_cast(NX1) }, { 0.0, static_cast(NX2) } }, + {} + }; + const auto dt = static_cast(0.45); + const ndfield_t EB { "EB", NX1 + 2u * N_GHOSTS, NX2 + 2u * N_GHOSTS }; + + auto params = make_params(static_cast(1e-6)); + const auto rate = arch::emission::bh::GetTables(params, dt).rate(GAMMA_P); + params = make_params(static_cast(0.07 / (rate * dt))); + + const double eps = std::max( + static_cast(std::numeric_limits::epsilon()), + static_cast(std::numeric_limits::epsilon())); + const std::size_t n_nodes = NX1 * NX2; + const npart_t n_emitters = 2000u; + const int cell1 = static_cast(NX1 / 2u), + cell2 = static_cast(NX2 / 2u); + + struct Arm { + std::string name; + // previous position of the electron slots: cell and offsets + int electron_i1, electron_i2; + double electron_dx1, electron_dx2; + // previous position of the positron slots + int positron_i1, positron_i2; + double positron_dx1, positron_dx2; + // distance of the emitters from the faces of their cell, and their seed + double margin; + std::uint64_t seed; + }; + + const std::vector arms { + { "same cell",cell1,cell2,0.2, 0.7,cell1,cell2,0.8, 0.3,0.0, 5u }, + { "neighbouring cells", + cell1 - 1, + cell2 + 1, + 0.8, 0.2, + cell1 + 1, + cell2 - 1, + 0.2, 0.8, + 0.25, 6u } + }; + + for (const auto& arm : arms) { + for (const bool write_previous : { true, false }) { + random_number_pool_t random_pool { 2468 }; + auto electrons = make_species(1, 1.0f, -1.0f, n_emitters); + auto positrons = make_species(2, 1.0f, 1.0f, n_emitters); + auto emitters = make_species(3, 1.0f, 1.0f, n_emitters); + fill_emitters(emitters, + n_emitters, + momentum_at(GAMMA_P), + arm.seed, + true, + arm.margin); + set_previous(electrons, + arm.electron_i1, + arm.electron_i2, + static_cast(arm.electron_dx1), + static_cast(arm.electron_dx2)); + set_previous(positrons, + arm.positron_i1, + arm.positron_i2, + static_cast(arm.positron_dx1), + static_cast(arm.positron_dx2)); + + std::vector rho_old(n_nodes, 0.0); + charge_density(emitters, rho_old); + // all the charge is on the four nodes of one cell: the round-off of + // the sums is measured against the largest term, not against one + double scale = 1.0; + for (const auto& rho : rho_old) { + scale = std::max(scale, std::abs(rho) / static_cast(dt)); + } + const double limit = 100.0 * eps * scale; + const auto n_pairs = push_with_emission(emitters, + electrons, + positrons, + metric, + EB, + params, + dt, + random_pool, + write_previous); + + std::vector> J_all(3, std::vector(n_nodes, 0.0)); + const double j_electrons = max_inplane_current(electrons, metric, dt, J_all); + const double j_positrons = max_inplane_current(positrons, metric, dt, J_all); + deposit(emitters, metric, dt, J_all); + std::vector rho_new(n_nodes, 0.0); + charge_density(emitters, rho_new); + charge_density(electrons, rho_new); + charge_density(positrons, rho_new); + const double residual = continuity_residual(rho_old, rho_new, J_all, dt); + + // the numbers first, so that a run that fails shows them + const std::string label = "reused slots, " + arm.name + ", " + + (write_previous + ? "policy" + : "control without the previous position"); + std::cout + << fmt::format( + "%s: %u pairs, in-plane currents %.3e (electrons) and " + "%.3e (positrons), continuity residual %.3e (limit %.3e)", + label.c_str(), + n_pairs, + j_electrons, + j_positrons, + residual, + limit) + << std::endl; + + check(n_pairs > 100u, label + ": too few pairs created"); + if (write_previous) { + check(j_electrons == 0.0 and j_positrons == 0.0, + fmt::format("%s: in-plane current of unpushed leptons %.3e " + "(electrons), %.3e (positrons) != 0", + label.c_str(), + j_electrons, + j_positrons)); + check(residual < limit, + fmt::format("%s: continuity residual %.3e (limit %.3e)", + label.c_str(), + residual, + limit)); + } else { + check(j_electrons > 1.0 and j_positrons > 1.0 and residual > 1.0e3 * limit, + fmt::format("%s: charge is conserved without the previous " + "position (currents %.3e, %.3e, continuity " + "residual %.3e)", + label.c_str(), + j_electrons, + j_positrons, + residual)); + } + } + } + } + + /* + * Rate and mean loss at a fixed Gamma_p. One step of 200000 emitters: + * - the number of pairs against the expectation p N, within 4 standard + * deviations of the binomial law; + * - the mean energy lost per interaction against the tabulated , + * within 4 standard errors of the sample mean. + */ + void test_rate_and_loss() { + const metric_t metric { + { NX1, NX2 }, + { { 0.0, static_cast(NX1) }, { 0.0, static_cast(NX2) } }, + {} + }; + const auto dt = static_cast(0.45); + const ndfield_t EB { "EB", NX1 + 2u * N_GHOSTS, NX2 + 2u * N_GHOSTS }; + random_number_pool_t random_pool { 6789 }; + + const npart_t n_emitters = 200000u; + auto electrons = make_species(1, 1.0f, -1.0f, 40000u); + auto positrons = make_species(2, 1.0f, 1.0f, 40000u); + auto emitters = make_species(3, 1.0f, 1.0f, n_emitters); + fill_emitters(emitters, n_emitters, momentum_at(GAMMA_P), 2u); + + auto params = make_params(static_cast(1e-6)); + const auto& tables = arch::emission::bh::GetTables(params, dt); + const auto rate = tables.rate(GAMMA_P); + params = make_params(static_cast(0.07 / (rate * dt))); + const double probability = + static_cast(params.template get( + "radiation.emission.bethe_heitler.optical_depth")) * + rate * static_cast(dt); + const double mean_loss = tables.mean_loss(GAMMA_P); + + const auto K_before = kinetic_energies(emitters); + const auto n_pairs = push_with_emission(emitters, + electrons, + positrons, + metric, + EB, + params, + dt, + random_pool); + const auto K_after = kinetic_energies(emitters); + + const double expected = probability * n_emitters; + const double sigma = std::sqrt(expected * (1.0 - probability)); + check( + std::abs(static_cast(n_pairs) - expected) < 4.0 * sigma, + fmt::format("rate: %u pairs, expected %.1f +- %.1f", n_pairs, expected, sigma)); + + // losses of the emitters that interacted (the others are not touched) + double sum = 0.0, sum_sqr = 0.0; + npart_t n_changed = 0u; + for (npart_t p = 0u; p < n_emitters; ++p) { + const double loss = K_before[p] - K_after[p]; + if (loss != 0.0) { + sum += loss; + sum_sqr += loss * loss; + ++n_changed; + } + } + check(n_changed == n_pairs, "loss: recoils and pairs differ in number"); + const double mean = sum / n_changed; + const double variance = sum_sqr / n_changed - mean * mean; + const double std_error = std::sqrt(variance / n_changed); + check(std::abs(mean - mean_loss) < 4.0 * std_error, + fmt::format("loss: mean %.5f +- %.5f, tabulated %.5f", + mean, + std_error, + mean_loss)); + std::cout + << fmt::format("rate: %u pairs, expected %.1f +- %.1f; loss: mean " + "%.5f +- %.5f, tabulated %.5f", + n_pairs, + expected, + sigma, + mean, + std_error, + mean_loss) + << std::endl; + } + + /* + * Refusals and capacity: + * - full lepton species: the pairs that do not fit are not created, the + * corresponding emitters are not touched, and the counter says so; + * - a probability above `max_probability` raises, at startup from the + * tables and at runtime from the kernel; + * - `pair_weight != 1` without `particles.use_weights` raises; + * - a NaN optical depth or probability bound raises, and so does a + * timestep that is not finite; + * - lepton species whose charges do not cancel exactly are refused, and + * so is an emitting species of infinite mass. + */ + void test_refusals_and_capacity() { + const metric_t metric { + { NX1, NX2 }, + { { 0.0, static_cast(NX1) }, { 0.0, static_cast(NX2) } }, + {} + }; + const auto dt = static_cast(0.45); + const ndfield_t EB { "EB", NX1 + 2u * N_GHOSTS, NX2 + 2u * N_GHOSTS }; + random_number_pool_t random_pool { 4242 }; + + auto params = make_params(static_cast(1e-6)); + const auto rate = arch::emission::bh::GetTables(params, dt).rate(GAMMA_P); + const auto optical_depth = static_cast(0.07 / (rate * dt)); + params = make_params(optical_depth); + + // capacity + { + const npart_t n_emitters = 2000u, capacity = 64u; + auto electrons = make_species(1, 1.0f, -1.0f, capacity); + auto positrons = make_species(2, 1.0f, 1.0f, capacity + 10u); + auto emitters = make_species(3, 1.0f, 1.0f, n_emitters); + fill_emitters(emitters, n_emitters, momentum_at(GAMMA_P), 3u); + const auto before = arch::emission::bh::GetCounters(); + const auto K_before = kinetic_energies(emitters); + const auto n_pairs = push_with_emission(emitters, + electrons, + positrons, + metric, + EB, + params, + dt, + random_pool); + const auto K_after = kinetic_energies(emitters); + const auto after = arch::emission::bh::GetCounters(); + npart_t n_changed = 0u; + for (npart_t p = 0u; p < n_emitters; ++p) { + if (K_before[p] != K_after[p]) { + ++n_changed; + } + } + check(n_pairs == capacity and electrons.npart() == capacity and + positrons.npart() == capacity, + "capacity: wrong number of pairs inserted"); + check(n_changed == capacity, "capacity: recoil without a pair"); + check(after.pairs - before.pairs == capacity, "capacity: wrong pair counter"); + check(after.capacity_dropped > before.capacity_dropped, + "capacity: dropped pairs not counted"); + std::cout << "capacity: " << n_pairs << " pairs inserted, " + << after.capacity_dropped - before.capacity_dropped + << " dropped and counted" << std::endl; + } + +#if !defined(MPI_ENABLED) + // with MPI an error aborts; these checks need it to throw + auto raises = [](auto&& f) { + try { + f(); + } catch (const std::exception&) { + return true; + } + return false; + }; + + // probability above max_probability: startup check on the tables + check(raises([&]() { + const auto too_dense = make_params( + static_cast(2) * optical_depth); + arch::emission::bh::GetTables(too_dense, dt); + }), + "refusal: probability above max_probability not refused at startup"); + + // ... and at runtime: tables checked with one optical depth, policy + // built with a larger one + check( + raises([&]() { + auto& tables = arch::emission::bh::GetTables(params, dt); + auto electrons = make_species(1, 1.0f, -1.0f, 1000u); + auto positrons = make_species(2, 1.0f, 1.0f, 1000u); + auto emitters = make_species(3, 1.0f, 1.0f, 100u); + fill_emitters(emitters, 100u, momentum_at(GAMMA_P), 4u); + const auto too_dense = make_params(static_cast(2) * optical_depth); + const emission_t emission { electrons, + positrons, + electrons.index(), + positrons.index(), + emitters.mass(), + dt, + 0u, + too_dense, + tables, + random_pool }; + const auto policy = kernel::sr::PusherPolicy { emission }; + const auto boundaries = kernel::sr::PusherBoundaries { + { { PrtlBC::PERIODIC, PrtlBC::PERIODIC }, + { PrtlBC::PERIODIC, PrtlBC::PERIODIC } } + }; + Kokkos::parallel_for("ParticlePusher", + emitters.rangeActiveParticles(), + kernel::sr::Pusher_kernel( + pusher_context(emitters, dt), + boundaries, + emitters, + EB, + metric, + policy)); + emission.numbers_injected(); + }), + "refusal: probability above max_probability not refused at runtime"); + + // pair_weight != 1 without particle weights + check(raises([&]() { + const auto weighted = make_params(optical_depth, + static_cast(2), + static_cast(0.1), + false); + arch::emission::bh::GetTables(weighted, dt); + }), + "refusal: pair_weight != 1 accepted without use_weights"); + // a NaN optical depth or probability bound is refused (it would + // otherwise switch the process off without a word) + const auto not_a_number = std::numeric_limits::quiet_NaN(); + check(raises([&]() { + arch::emission::bh::GetTables(make_params(not_a_number), dt); + }), + "refusal: NaN optical_depth accepted"); + check(raises([&]() { + arch::emission::bh::GetTables( + make_params(optical_depth, ONE, not_a_number), + dt); + }), + "refusal: NaN max_probability accepted"); + // ... and so is a timestep that is not finite: a NaN and minus infinity + // would pass the bound on the probability + const auto infinity = std::numeric_limits::infinity(); + for (const auto bad_dt : { not_a_number, infinity, -infinity }) { + check(raises([&]() { + arch::emission::bh::GetTables(params, bad_dt); + }), + fmt::format("refusal: timestep %g accepted", + static_cast(bad_dt))); + } + + // the charges of the two lepton species must cancel exactly: a positron + // charge one unit in the last place above that is refused by the factory + const auto make_policy = [&](float positron_charge, float emitter_mass = 1.0f) { + MockDomain domain; + domain.add_species(1.0f, -1.0f); + domain.add_species(1.0f, positron_charge); + domain.add_species(emitter_mass, 1.0f); + kernel::sr::MakePusherPolicyEmission( + domain, + params, + pusher_context(domain.species[2], dt)); + }; + check(not raises([&]() { + make_policy(1.0f); + }), + "refusal: exactly opposite lepton charges refused"); + check(raises([&]() { + make_policy(std::nextafter(1.0f, 2.0f)); + }), + "refusal: lepton charges that do not cancel exactly accepted"); + // the mass of the emitting species must be finite + check(raises([&]() { + make_policy(1.0f, std::numeric_limits::infinity()); + }), + "refusal: emitting species of infinite mass accepted"); + std::cout << "refusals: raised as expected" << std::endl; +#endif + } + +} // namespace + +auto main(int argc, char* argv[]) -> int { + GlobalInitialize(argc, argv); + try { + test_charge(); + test_charge_reused_slots(); + test_rate_and_loss(); + test_refusals_and_capacity(); + } catch (std::exception& e) { + std::cerr << e.what() << std::endl; + GlobalFinalize(); + return 1; + } + GlobalFinalize(); + return 0; +}