id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,540,220
|
ion_viscosity.cxx
|
bendudson_hermes-3/src/ion_viscosity.cxx
|
/// Ion viscosity model
#include <bout/constants.hxx>
#include <bout/fv_ops.hxx>
#include <bout/difops.hxx>
#include <bout/output_bout_types.hxx>
#include <bout/mesh.hxx>
#include "../include/ion_viscosity.hxx"
#include "../include/div_ops.hxx"
using bout::globals::mesh;
IonViscosity::IonViscosity(std::string name, Options& alloptions, Solver*) {
auto& options = alloptions[name];
eta_limit_alpha = options["eta_limit_alpha"]
.doc("Viscosity flux limiter coefficient. <0 = turned off")
.withDefault(-1.0);
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
perpendicular = options["perpendicular"]
.doc("Include perpendicular flow? (Requires phi)")
.withDefault<bool>(false);
if (perpendicular) {
// Read curvature vector
try {
Curlb_B.covariant = false; // Contravariant
mesh->get(Curlb_B, "bxcv");
} catch (BoutException& e) {
// May be 2D, reading as 3D
Vector2D curv2d;
curv2d.covariant = false;
mesh->get(curv2d, "bxcv");
Curlb_B = curv2d;
}
if (Options::root()["mesh"]["paralleltransform"]["type"].as<std::string>()
== "shifted") {
Field2D I;
mesh->get(I, "sinty");
Curlb_B.z += I * Curlb_B.x;
}
// Normalisations
const Options& units = alloptions["units"];
const BoutReal Bnorm = units["Tesla"];
const BoutReal Lnorm = units["meters"];
auto coord = mesh->getCoordinates();
Curlb_B.x /= Bnorm;
Curlb_B.y *= SQ(Lnorm);
Curlb_B.z *= SQ(Lnorm);
Curlb_B *= 2. / coord->Bxy;
}
}
void IonViscosity::transform(Options &state) {
AUTO_TRACE();
Options& allspecies = state["species"];
auto coord = mesh->getCoordinates();
const Field2D Bxy = coord->Bxy;
const Field2D sqrtB = sqrt(Bxy);
const Field2D Grad_par_logB = Grad_par(log(Bxy));
// Loop through all species
for (auto& kv : allspecies.getChildren()) {
if (kv.first == "e") {
continue; // Skip electrons -> only ions
}
const auto& species_name = kv.first;
Options& species = allspecies[species_name];
if (!(isSetFinal(species["pressure"], "ion_viscosity") and
isSetFinal(species["velocity"], "ion_viscosity") and
isSetFinal(species["charge"], "ion_viscosity"))) {
// Species doesn't have a pressure, velocity and charge => Skip
continue;
}
if (std::fabs(get<BoutReal>(species["charge"])) < 1e-3) {
// No charge
continue;
}
const Field3D tau = 1. / get<Field3D>(species["collision_frequency"]);
const Field3D P = get<Field3D>(species["pressure"]);
const Field3D V = get<Field3D>(species["velocity"]);
// Parallel ion viscosity (4/3 * 0.96 coefficient)
Field3D eta = 1.28 * P * tau;
if (eta_limit_alpha > 0.) {
// SOLPS-style flux limiter
// Values of alpha ~ 0.5 typically
const Field3D q_cl = eta * Grad_par(V); // Collisional value
const Field3D q_fl = eta_limit_alpha * P; // Flux limit
eta = eta / (1. + abs(q_cl / q_fl));
eta.getMesh()->communicate(eta);
eta.applyBoundary("neumann");
}
// This term is the parallel flow part of
// -(2/3) B^(3/2) Grad_par(Pi_ci / B^(3/2))
const Field3D div_Pi_cipar = sqrtB * FV::Div_par_K_Grad_par(eta / Bxy, sqrtB * V);
add(species["momentum_source"], div_Pi_cipar);
subtract(species["energy_source"], V * div_Pi_cipar); // Internal energy
if (!perpendicular) {
if (diagnose) {
const Field2D P_av = DC(P);
const Field2D tau_av = DC(tau);
const Field2D V_av = DC(V);
// Parallel ion stress tensor component, calculated here because before it was only div_Pi_cipar
Field2D Pi_cipar = -0.96 * P_av * tau_av *
(2. * Grad_par(V_av) + V_av * Grad_par_logB);
Field2D Pi_ciperp = 0 * Pi_cipar; // Perpendicular components and divergence of current J equal to 0 for only parallel viscosity case
Field2D DivJ = 0 * Pi_cipar;
// Find the diagnostics struct for this species
auto search = diagnostics.find(species_name);
if (search == diagnostics.end()) {
// First time, create diagnostic
diagnostics.emplace(species_name, Diagnostics {Pi_ciperp, Pi_cipar, DivJ});
} else {
// Update diagnostic values
auto& d = search->second;
d.Pi_ciperp = Pi_ciperp;
d.Pi_cipar = Pi_cipar;
d.DivJ = DivJ;
}
}
continue; // Skip perpendicular flow parts below
}
// The following calculation is performed on the axisymmetric components
// Need electrostatic potential for ExB flow
const Field2D phi_av = DC(get<Field3D>(state["fields"]["phi"]));
// Density and temperature needed for diamagnetic flows
const Field2D N_av = DC(get<Field3D>(species["density"]));
const Field2D T_av = DC(get<Field3D>(species["temperature"]));
const Field2D P_av = DC(P);
const Field2D tau_av = DC(tau);
const Field2D V_av = DC(V);
// Parallel ion stress tensor component
Field2D Pi_cipar = -0.96 * P_av * tau_av *
(2. * Grad_par(V_av) + V_av * Grad_par_logB);
// Could also be written as:
// Pi_cipar = -0.96*Pi*tau*2.*Grad_par(sqrt(Bxy)*Vi)/sqrt(Bxy);
// Perpendicular ion stress tensor
// 0.96 P tau kappa * (V_E + V_di + 1.61 b x Grad(T)/B )
// Note: Heat flux terms are neglected for now
Field2D Pi_ciperp = -0.5 * 0.96 * P_av * tau_av *
(Curlb_B * Grad(phi_av + 1.61 * T_av) - Curlb_B * Grad(P_av) / N_av);
// Limit size of stress tensor components
// If the off-diagonal components of the pressure tensor are large compared
// to the scalar pressure, then the model is probably breaking down.
// This can happen in very low density regions
BOUT_FOR(i, Pi_ciperp.getRegion("RGN_NOBNDRY")) {
if (fabs(Pi_ciperp[i]) > P_av[i]) {
Pi_ciperp[i] = SIGN(Pi_ciperp[i]) * P_av[i];
}
if (fabs(Pi_cipar[i]) > P_av[i]) {
Pi_cipar[i] = SIGN(Pi_cipar[i]) * P_av[i];
}
}
// Apply perpendicular boundary conditions
Pi_ciperp.applyBoundary("neumann");
Pi_cipar.applyBoundary("neumann");
// Apply parallel boundary conditions
int jy = 1;
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
Pi_ciperp(r.ind, jy) = Pi_ciperp(r.ind, jy + 1);
Pi_cipar(r.ind, jy) = Pi_cipar(r.ind, jy + 1);
}
jy = mesh->yend + 1;
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
Pi_ciperp(r.ind, jy) = Pi_ciperp(r.ind, jy - 1);
Pi_cipar(r.ind, jy) = Pi_cipar(r.ind, jy - 1);
}
mesh->communicate(Pi_ciperp, Pi_cipar);
const Field3D div_Pi_ciperp = - (2. / 3) * Grad_par(Pi_ciperp) + Pi_ciperp * Grad_par_logB;
//const Field3D div_Pi_ciperp = - (2. / 3) * B32 * Grad_par(Pi_ciperp / B32);
add(species["momentum_source"], div_Pi_ciperp);
subtract(species["energy_source"], V_av * div_Pi_ciperp);
// Total scalar ion viscous pressure
Field2D Pi_ci = Pi_cipar + Pi_ciperp;
#if CHECKLEVEL >= 1
for (auto& i : N_av.getRegion("RGN_NOBNDRY")) {
if (!std::isfinite(Pi_cipar[i])) {
throw BoutException("{} Pi_cipar non-finite at {}.\n", species_name, i);
}
if (!std::isfinite(Pi_ciperp[i])) {
throw BoutException("{} Pi_ciperp non-finite at {}.\n", species_name, i);
}
}
#endif
Pi_ci.applyBoundary("neumann");
// Divergence of current in vorticity equation
Field3D DivJ = Div(0.5 * Pi_ci * Curlb_B) -
Div_n_bxGrad_f_B_XPPM(1. / 3, Pi_ci, false, true);
add(state["fields"]["DivJextra"], DivJ);
// Transfer of energy between ion internal energy and ExB flow
subtract(species["energy_source"],
Field3D(0.5 * Pi_ci * Curlb_B * Grad(phi_av + P_av)
- (1 / 3) * bracket(Pi_ci, phi_av + P_av, BRACKET_STD)));
if (diagnose) {
// Find the diagnostics struct for this species
auto search = diagnostics.find(species_name);
if (search == diagnostics.end()) {
// First time, create diagnostic
diagnostics.emplace(species_name, Diagnostics {Pi_ciperp, Pi_cipar, DivJ});
} else {
// Update diagnostic values
auto& d = search->second;
d.Pi_ciperp = Pi_ciperp;
d.Pi_cipar = Pi_cipar;
d.DivJ = DivJ;
}
}
}
}
void IonViscosity::outputVars(Options &state) {
AUTO_TRACE();
if (diagnose) {
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
for (const auto& it : diagnostics) {
const std::string& species_name = it.first;
const auto& d = it.second;
set_with_attrs(state[std::string("P") + species_name + std::string("_ciperp")], d.Pi_ciperp,
{{"time_dimension", "t"},
{"units", "Pa"},
{"conversion", Pnorm},
{"standard_name", "Viscous pressure"},
{"long_name", species_name + " perpendicular collisional viscous pressure"},
{"species", species_name},
{"source", "ion_viscosity"}});
set_with_attrs(state[std::string("P") + species_name + std::string("_cipar")], d.Pi_cipar,
{{"time_dimension", "t"},
{"units", "Pa"},
{"conversion", Pnorm},
{"standard_name", "Viscous pressure"},
{"long_name", species_name + " parallel collisional viscous pressure"},
{"species", species_name},
{"source", "ion_viscosity"}});
set_with_attrs(state[std::string("DivJvis_") + species_name], d.DivJ,
{{"time_dimension", "t"},
{"units", "A m^-3"},
{"conversion", SI::qe * Nnorm * Omega_ci},
{"long_name", std::string("Divergence of viscous current due to species") + species_name},
{"species", species_name},
{"source", "ion_viscosity"}});
}
}
}
| 10,364
|
C++
|
.cxx
| 241
| 35.356846
| 141
| 0.59493
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,221
|
transform.cxx
|
bendudson_hermes-3/src/transform.cxx
|
#include "../include/transform.hxx"
#include <bout/utils.hxx> // for trim, strsplit
Transform::Transform(std::string name, Options& alloptions, Solver* UNUSED(solver)) {
Options& options = alloptions[name];
const auto trim_chars = " \t\r()";
const auto str = trim(
options["transforms"].doc("Comma-separated list e.g. a = b, c = d"), trim_chars);
for (const auto& assign_str : strsplit(str, ',')) {
auto assign_lr = strsplit(assign_str, '=');
if (assign_lr.size() != 2) {
throw BoutException("Expected one assignment ('=') in '{}'", assign_str);
}
const auto left = trim(assign_lr.front(), trim_chars);
const auto right = trim(assign_lr.back(), trim_chars);
transforms[left] = right;
}
}
void Transform::transform(Options& state) {
for (const auto& lr : transforms) {
state[lr.first] = state[lr.second].copy();
}
}
| 879
|
C++
|
.cxx
| 22
| 36.045455
| 87
| 0.652893
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,222
|
solkit_hydrogen_charge_exchange.cxx
|
bendudson_hermes-3/src/solkit_hydrogen_charge_exchange.cxx
|
#include "../include/solkit_hydrogen_charge_exchange.hxx"
#include "../include/integrate.hxx" // for cellAverage
void SOLKITHydrogenChargeExchange::calculate_rates(Options& atom, Options& ion) {
const auto AA = get<BoutReal>(ion["AA"]);
// Check that mass is consistent
ASSERT1(get<BoutReal>(atom["AA"]) == AA);
// Densities
const Field3D Natom = floor(get<Field3D>(atom["density"]), 1e-5);
const Field3D Nion = floor(get<Field3D>(ion["density"]), 1e-5);
const Field3D Vatom = IS_SET(atom["velocity"]) ? GET_VALUE(Field3D, atom["velocity"]) : 0.0;
const Field3D Vion = IS_SET(ion["velocity"]) ? GET_VALUE(Field3D, ion["velocity"]) : 0.0;
const Field3D friction = cellAverage(
[&](BoutReal natom, BoutReal nion, BoutReal vatom, BoutReal vion){
// CONSTANT CROSS-SECTION 3E-19m2, COLD ION/NEUTRAL AND STATIC NEUTRAL ASSUMPTION
auto R = natom * nion * 3e-19 * fabs(vion) *
(Nnorm * rho_s0);
return AA * (vion - vatom) * R;
},
Natom.getRegion("RGN_NOBNDRY"))(Natom, Nion, Vatom, Vion);
// Transfer momentum
subtract(ion["momentum_source"], friction);
add(atom["momentum_source"], friction);
}
| 1,179
|
C++
|
.cxx
| 23
| 46.391304
| 94
| 0.672174
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,223
|
electron_viscosity.cxx
|
bendudson_hermes-3/src/electron_viscosity.cxx
|
/// Braginskii electron viscosity
#include <bout/fv_ops.hxx>
#include <bout/mesh.hxx>
#include <bout/difops.hxx>
#include <bout/constants.hxx>
#include "../include/electron_viscosity.hxx"
ElectronViscosity::ElectronViscosity(std::string name, Options& alloptions, Solver*) {
auto& options = alloptions[name];
eta_limit_alpha = options["eta_limit_alpha"]
.doc("Viscosity flux limiter coefficient. <0 = turned off")
.withDefault(-1.0);
diagnose = options["diagnose"].doc("Output diagnostics?").withDefault<bool>(false);
}
void ElectronViscosity::transform(Options& state) {
AUTO_TRACE();
Options& species = state["species"]["e"];
if (!isSetFinal(species["pressure"], "electron_viscosity")) {
throw BoutException("No electron pressure => Can't calculate electron viscosity");
}
if (!isSetFinal(species["velocity"], "electron_viscosity")) {
throw BoutException("No electron velocity => Can't calculate electron viscosity");
}
const Field3D tau = 1. / get<Field3D>(species["collision_frequency"]);
const Field3D P = get<Field3D>(species["pressure"]);
const Field3D V = get<Field3D>(species["velocity"]);
Coordinates* coord = P.getCoordinates();
const Field3D Bxy = coord->Bxy;
const Field3D sqrtB = sqrt(Bxy);
// Parallel electron viscosity
Field3D eta = (4. / 3) * 0.73 * P * tau;
if (eta_limit_alpha > 0.) {
// SOLPS-style flux limiter
// Values of alpha ~ 0.5 typically
const Field3D q_cl = eta * Grad_par(V); // Collisional value
const Field3D q_fl = eta_limit_alpha * P; // Flux limit
eta = eta / (1. + abs(q_cl / q_fl));
eta.getMesh()->communicate(eta);
eta.applyBoundary("neumann");
}
// Save term for output diagnostic
viscosity = sqrtB * FV::Div_par_K_Grad_par(eta / Bxy, sqrtB * V);
add(species["momentum_source"], viscosity);
}
void ElectronViscosity::outputVars(Options& state) {
AUTO_TRACE();
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
auto Cs0 = get<BoutReal>(state["Cs0"]);
if (diagnose) {
set_with_attrs(state["SNVe_viscosity"], viscosity,
{{"time_dimension", "t"},
{"units", "kg m^-2 s^-2"},
{"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci},
{"standard_name", "momentum source"},
{"long_name", "electron parallel viscosity"},
{"species", "e"},
{"source", "electron_viscosity"}});
}
}
| 2,572
|
C++
|
.cxx
| 60
| 36.766667
| 86
| 0.638699
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,224
|
polarisation_drift.cxx
|
bendudson_hermes-3/src/polarisation_drift.cxx
|
#include "../include/polarisation_drift.hxx"
#include <bout/constants.hxx>
#include <bout/fv_ops.hxx>
#include <bout/output_bout_types.hxx>
#include <bout/invert_laplace.hxx>
#include <bout/difops.hxx>
using bout::globals::mesh;
PolarisationDrift::PolarisationDrift(std::string name,
Options &alloptions,
Solver *UNUSED(solver)) {
AUTO_TRACE();
// Get options for this component
auto& options = alloptions[name];
// Cache the B^2 value
auto coord = mesh->getCoordinates();
Bsq = SQ(coord->Bxy);
phiSolver = Laplacian::create(&options["laplacian"]);
// For zero polarisation drift fluxes through the boundary the
// radial electric field at the boundary should be constant
// (e.g. zero), so zero-gradient radial BC on phi_G.
phiSolver->setInnerBoundaryFlags(0);
phiSolver->setOuterBoundaryFlags(0);
boussinesq = options["boussinesq"]
.doc("Assume a uniform mass density in calculating the polarisation drift")
.withDefault<bool>(true);
if (boussinesq) {
average_atomic_mass =
options["average_atomic_mass"]
.doc("Weighted average atomic mass, for polarisaion current "
"(Boussinesq approximation)")
.withDefault<BoutReal>(2.0); // Deuterium
} else {
average_atomic_mass = 1.0;
// Use a density floor to prevent divide-by-zero errors
density_floor = options["density_floor"].doc("Minimum density floor").withDefault(1e-5);
}
advection = options["advection"]
.doc("Include advection by polarisation drift, using potential flow approximation?")
.withDefault<bool>(true);
diamagnetic_polarisation =
options["diamagnetic_polarisation"]
.doc("Include diamagnetic drift in polarisation current?")
.withDefault<bool>(true);
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
}
void PolarisationDrift::transform(Options &state) {
AUTO_TRACE();
// Iterate through all subsections
Options& allspecies = state["species"];
// Calculate divergence of all currents except the polarisation current
if (IS_SET(state["fields"]["DivJdia"])) {
DivJ = get<Field3D>(state["fields"]["DivJdia"]);
} else {
DivJ = 0.0;
}
// Parallel current due to species parallel flow
for (auto& kv : allspecies.getChildren()) {
const Options& species = kv.second;
if (!species.isSet("charge") or !species.isSet("momentum")) {
continue; // Not charged, or no parallel flow
}
const BoutReal Z = get<BoutReal>(species["charge"]);
if (fabs(Z) < 1e-5) {
continue; // Not charged
}
const Field3D NV = GET_VALUE(Field3D, species["momentum"]);
const BoutReal A = get<BoutReal>(species["AA"]);
// Note: Using NV rather than N*V so that the cell boundary flux is correct
DivJ += Div_par((Z / A) * NV);
}
if (diamagnetic_polarisation) {
// Compression of ion diamagnetic contribution to polarisation velocity
// Note: For now this ONLY includes the parallel and diamagnetic current terms
// Other terms e.g. ion viscous current, are in their separate components
if (!boussinesq) {
throw BoutException("diamagnetic_polarisation not implemented for non-Boussinesq");
}
// Calculate energy exchange term nonlinear in pressure
// (3 / 2) ddt(Pi) += (Pi / n0) * Div((Pe + Pi) * Curlb_B + Jpar);
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first]; // Note: need non-const
if (!(IS_SET_NOBOUNDARY(species["pressure"]) and species.isSet("charge")
and species.isSet("AA"))) {
// No pressure, charge or mass -> no polarisation current due to
// diamagnetic flow
continue;
}
const auto charge = get<BoutReal>(species["charge"]);
if (fabs(charge) < 1e-5) {
// No charge
continue;
}
const auto P = GET_NOBOUNDARY(Field3D, species["pressure"]);
const auto AA = get<BoutReal>(species["AA"]);
add(species["energy_source"],
P * (AA / average_atomic_mass / charge) * DivJ);
}
}
if (!advection) {
return;
}
// Calculate advection terms using a potential-flow approximation
// Calculate the total mass density of species
// which contribute to polarisation current
Field3D mass_density;
if (boussinesq) {
mass_density = average_atomic_mass;
} else {
mass_density = 0.0;
for (auto& kv : allspecies.getChildren()) {
const Options& species = kv.second;
if (!(species.isSet("charge") and species.isSet("AA"))) {
continue; // No charge or mass -> no current
}
if (fabs(get<BoutReal>(species["charge"])) < 1e-5) {
continue; // Zero charge
}
const BoutReal A = get<BoutReal>(species["AA"]);
const Field3D N = GET_NOBOUNDARY(Field3D, species["density"]);
mass_density += A * N;
}
// Apply a floor to prevent divide-by-zero errors
mass_density = floor(mass_density, density_floor);
}
if (IS_SET(state["fields"]["DivJextra"])) {
DivJ += get<Field3D>(state["fields"]["DivJextra"]);
}
if (IS_SET(state["fields"]["DivJcol"])) {
DivJ += get<Field3D>(state["fields"]["DivJcol"]);
}
// Solve for time derivative of potential
// Using Div(mass_density / B^2 Grad_perp(dphi/dt)) = DivJ
phiSolver->setCoefC(mass_density / Bsq);
// Calculate time derivative of generalised potential
// The assumption is that the polarisation drift can be parameterised
// as a potential flow
phi_pol = phiSolver->solve(DivJ * Bsq / mass_density);
// Ensure that potential is set in communication guard cells
mesh->communicate(phi_pol);
// Zero flux
phi_pol.applyBoundary("neumann");
// Polarisation drift is given by
//
// v_p = - (m_i / (Z_i * B^2)) * Grad(phi_pol)
//
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first]; // Note: need non-const
if (!(species.isSet("charge") and species.isSet("AA"))) {
continue; // No charge or mass -> no current
}
const BoutReal Z = get<BoutReal>(species["charge"]);
if (fabs(Z) < 1e-5) {
continue; // Not charged
}
const BoutReal A = get<BoutReal>(species["AA"]);
// Shared coefficient in polarisation velocity
Field3D coef = (A / Z) / Bsq;
if (IS_SET(species["density"])) {
auto N = GET_VALUE(Field3D, species["density"]);
add(species["density_source"], FV::Div_a_Grad_perp(N * coef, phi_pol));
}
if (IS_SET(species["pressure"])) {
auto P = GET_VALUE(Field3D, species["pressure"]);
add(species["energy_source"], (5. / 2) * FV::Div_a_Grad_perp(P * coef, phi_pol));
}
if (IS_SET(species["momentum"])) {
auto NV = GET_VALUE(Field3D, species["momentum"]);
add(species["momentum_source"], FV::Div_a_Grad_perp(NV * coef, phi_pol));
}
}
}
void PolarisationDrift::outputVars(Options &state) {
AUTO_TRACE();
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
if (diagnose) {
set_with_attrs(state["DivJpol"], -DivJ,
{{"time_dimension", "t"},
{"units", "A m^-3"},
{"conversion", SI::qe * Nnorm * Omega_ci},
{"long_name", "Divergence of polarisation current"},
{"source", "polarisation_drift"}});
set_with_attrs(state["phi_pol"], phi_pol,
{{"time_dimension", "t"},
{"units", "V / s"},
{"conversion", Tnorm * Omega_ci},
{"standard_name", "flow potential"},
{"long_name", "polarisation flow potential"},
{"source", "polarisation_drift"}});
}
}
| 7,892
|
C++
|
.cxx
| 195
| 34.312821
| 92
| 0.637422
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,225
|
component.cxx
|
bendudson_hermes-3/src/component.cxx
|
#include "../include/component.hxx"
std::unique_ptr<Component> Component::create(const std::string &type,
const std::string &name,
Options &alloptions,
Solver *solver) {
return std::unique_ptr<Component>(
ComponentFactory::getInstance().create(type, name, alloptions, solver));
}
constexpr decltype(ComponentFactory::type_name) ComponentFactory::type_name;
constexpr decltype(ComponentFactory::section_name) ComponentFactory::section_name;
constexpr decltype(ComponentFactory::option_name) ComponentFactory::option_name;
constexpr decltype(ComponentFactory::default_type) ComponentFactory::default_type;
bool isSetFinal(const Options& option, const std::string& location) {
#if CHECKLEVEL >= 1
// Mark option as final, both inside the domain and the boundary
const_cast<Options&>(option).attributes["final"] = location;
const_cast<Options&>(option).attributes["final-domain"] = location;
#endif
return option.isSet();
}
bool isSetFinalNoBoundary(const Options& option, const std::string& location) {
#if CHECKLEVEL >= 1
// Mark option as final inside the domain, but not in the boundary
const_cast<Options&>(option).attributes["final-domain"] = location;
#endif
return option.isSet();
}
| 1,350
|
C++
|
.cxx
| 27
| 42.962963
| 82
| 0.700835
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,226
|
electromagnetic.cxx
|
bendudson_hermes-3/src/electromagnetic.cxx
|
#include "../include/electromagnetic.hxx"
#include <bout/constants.hxx>
#include <bout/mesh.hxx>
#include <bout/invert_laplace.hxx>
// Set the default acceptance tolerances for the Naulin solver.
// These are used if the maximum iterations is reached.
// Note: A loose tolerance is used because repeated iterations
// can usually recover tight tolerances.
BOUT_OVERRIDE_DEFAULT_OPTION("electromagnetic:laplacian:type", "naulin");
BOUT_OVERRIDE_DEFAULT_OPTION("electromagnetic:laplacian:rtol_accept", 1e-2);
BOUT_OVERRIDE_DEFAULT_OPTION("electromagnetic:laplacian:atol_accept", 1e-6);
BOUT_OVERRIDE_DEFAULT_OPTION("electromagnetic:laplacian:maxits", 1000);
Electromagnetic::Electromagnetic(std::string name, Options &alloptions, Solver* solver) {
AUTO_TRACE();
Options& units = alloptions["units"];
BoutReal Bnorm = units["Tesla"];
BoutReal Tnorm = units["eV"];
BoutReal Nnorm = units["inv_meters_cubed"];
// Note: This is NOT plasma beta as usually defined, but
// is a factor of 2 too small (if Ti=0) or 4 (if Ti = Te)
// This is the normalisation parameter in the Helmholtz equation
beta_em = SI::mu0 * SI::qe * Tnorm * Nnorm / SQ(Bnorm);
output_info.write("Electromagnetic: beta_em = {}", beta_em);
auto& options = alloptions[name];
// Use the "Naulin" solver because we need to include toroidal
// variations of the density (A coefficient)
aparSolver = Laplacian::create(&options["laplacian"]);
aparSolver->savePerformance(*solver, "AparSolver");
const_gradient = options["const_gradient"]
.doc("Extrapolate gradient of Apar into all radial boundaries?")
.withDefault<bool>(false);
// Give Apar an initial value because we solve Apar by iteration
// starting from the previous solution
// Note: On restart the value is restored (if available) in restartVars
Apar = 0.0;
if (const_gradient) {
// Set flags to take the gradient from the RHS
aparSolver->setInnerBoundaryFlags(INVERT_DC_GRAD + INVERT_AC_GRAD + INVERT_RHS);
aparSolver->setOuterBoundaryFlags(INVERT_DC_GRAD + INVERT_AC_GRAD + INVERT_RHS);
last_time = 0.0;
apar_boundary_timescale = options["apar_boundary_timescale"]
.doc("Timescale for Apar boundary relaxation [seconds]")
.withDefault(1e-8)
/ get<BoutReal>(alloptions["units"]["seconds"]);
} else if (options["apar_boundary_neumann"]
.doc("Neumann on all radial boundaries?")
.withDefault<bool>(false)) {
// Set zero-gradient (neumann) boundary condition DC on the core
aparSolver->setInnerBoundaryFlags(INVERT_DC_GRAD + INVERT_AC_GRAD);
aparSolver->setOuterBoundaryFlags(INVERT_DC_GRAD + INVERT_AC_GRAD);
} else if (options["apar_core_neumann"]
.doc("Neumann radial boundary in the core? False => Dirichlet")
.withDefault<bool>(true)
and bout::globals::mesh->periodicY(bout::globals::mesh->xstart)) {
// Set zero-gradient (neumann) boundary condition DC on the core
aparSolver->setInnerBoundaryFlags(INVERT_DC_GRAD);
}
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
magnetic_flutter = options["magnetic_flutter"]
.doc("Set magnetic flutter terms (Apar_flutter)?")
.withDefault<bool>(false);
}
void Electromagnetic::restartVars(Options& state) {
AUTO_TRACE();
// NOTE: This is a hack because we know that the loaded restart file
// is passed into restartVars in PhysicsModel::postInit
// The restart value should be used in init() rather than here
static bool first = true;
if (first and state.isSet("Apar")) {
first = false;
Apar = state["Apar"].as<Field3D>();
output.write("\nElectromagnetic: Read Apar from restart file (min {}, max {})\n", min(Apar), max(Apar));
}
// Save the Apar field. It is solved using an iterative method,
// so converges faster with the value from the previous iteration.
set_with_attrs(state["Apar"], Apar,
{{"standard_name", "b dot A"},
{"long_name", "Parallel component of vector potential A"},
{"source", "electromagnetic"}});
}
void Electromagnetic::transform(Options &state) {
AUTO_TRACE();
Options& allspecies = state["species"];
// Sum coefficients over species
//
// Laplace(A||) - alpha_em * beta_em A|| = - beta_em * Ajpar
alpha_em = 0.0;
Ajpar = 0.0;
for (auto& kv : allspecies.getChildren()) {
const Options& species = kv.second;
if (!IS_SET(species["charge"]) or !species.isSet("momentum")) {
continue; // Not charged, or no parallel flow
}
const BoutReal Z = get<BoutReal>(species["charge"]);
if (fabs(Z) < 1e-5) {
continue; // Not charged
}
// Cannot rely on boundary conditions being set
const Field3D N = GET_NOBOUNDARY(Field3D, species["density"]);
// Non-final because we're going to change momentum
const Field3D mom = getNonFinal<Field3D>(species["momentum"]);
const BoutReal A = get<BoutReal>(species["AA"]);
// Coefficient in front of A_||
alpha_em += floor(N, 1e-5) * (SQ(Z) / A);
// Right hand side
Ajpar += mom * (Z / A);
}
// Invert Helmholtz equation for Apar
aparSolver->setCoefA((-beta_em) * alpha_em);
if (const_gradient) {
// Set gradient boundary condition from gradient inside boundary
Field3D rhs = (-beta_em) * Ajpar;
const auto* mesh = Apar.getMesh();
const auto* coords = Apar.getCoordinates();
BoutReal time = get<BoutReal>(state["time"]);
BoutReal weight = 1.0;
if (time > last_time) {
weight = exp((last_time - time) / apar_boundary_timescale);
}
last_time = time;
if (mesh->firstX()) {
const int x = mesh->xstart - 1;
for (int y = mesh->ystart; y <= mesh->yend; y++) {
for (int z = mesh->zstart; z <= mesh->zend; z++) {
rhs(x, y, z) = (weight * (Apar(x + 1, y, z) - Apar(x, y, z)) +
(1 - weight) * (Apar(x + 2, y, z) - Apar(x + 1, y, z))) /
(sqrt(coords->g_11(x, y)) * coords->dx(x, y));
}
}
}
if (mesh->lastX()) {
const int x = mesh->xend + 1;
for (int y = mesh->ystart; y <= mesh->yend; y++) {
for (int z = mesh->zstart; z <= mesh->zend; z++) {
rhs(x, y, z) = (weight * (Apar(x, y, z) - Apar(x - 1, y, z)) +
(1 - weight) * (Apar(x - 1, y, z) - Apar(x - 2, y, z))) /
sqrt(coords->g_11(x, y)) / coords->dx(x, y);
}
}
}
// Use previous value of Apar as initial guess
Apar = aparSolver->solve(rhs, Apar);
} else {
Apar = aparSolver->solve((-beta_em) * Ajpar, Apar);
}
// Save in the state
set(state["fields"]["Apar"], Apar);
// Update momentum
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first]; // Note: need non-const
if (!species.isSet("charge") or !species.isSet("momentum")) {
continue; // Not charged, or no parallel flow
}
const BoutReal Z = get<BoutReal>(species["charge"]);
if (fabs(Z) < 1e-5) {
continue; // Not charged
}
const BoutReal A = get<BoutReal>(species["AA"]);
const Field3D N = GET_NOBOUNDARY(Field3D, species["density"]);
Field3D nv = getNonFinal<Field3D>(species["momentum"]);
nv -= Z * N * Apar;
// Note: velocity is momentum / (A * N)
Field3D v = getNonFinal<Field3D>(species["velocity"]);
v -= (Z / A) * N * Apar / floor(N, 1e-5);
// Need to update the guard cells
bout::globals::mesh->communicate(nv, v);
v.applyBoundary("dirichlet");
nv.applyBoundary("dirichlet");
set(species["momentum"], nv);
set(species["velocity"], v);
}
if (magnetic_flutter) {
// Magnetic flutter terms
Apar_flutter = Apar - DC(Apar);
// Ensure that guard cells are communicated
Apar.getMesh()->communicate(Apar_flutter);
set(state["fields"]["Apar_flutter"], Apar_flutter);
#if 0
// Create a vector A from covariant components
// (A^x, A^y, A^z)
// Note: b = e_y / (JB)
const auto* coords = Apar.getCoordinates();
Vector3D A;
A.covariant = true;
A.x = A.z = 0.0;
A.y = Apar_flutter * (coords->J * coords->Bxy);
// Perturbed magnetic field vector
// Note: Contravariant components (dB_x, dB_y, dB_z)
Vector3D delta_B = Curl(A);
// Set components of the perturbed unit vector
// Note: Options can't (yet) contain vectors
set(state["fields"]["deltab_flutter_x"], delta_B.x / coords->Bxy);
set(state["fields"]["deltab_flutter_z"], delta_B.z / coords->Bxy);
#endif
}
}
void Electromagnetic::outputVars(Options &state) {
// Normalisations
auto Bnorm = get<BoutReal>(state["Bnorm"]);
auto rho_s0 = get<BoutReal>(state["rho_s0"]);
set_with_attrs(state["beta_em"], beta_em, {
{"long_name", "Helmholtz equation parameter"}
});
set_with_attrs(state["Apar"], Apar, {
{"time_dimension", "t"},
{"units", "T m"},
{"conversion", Bnorm * rho_s0},
{"standard_name", "b dot A"},
{"long_name", "Parallel component of vector potential A"}
});
if (magnetic_flutter) {
set_with_attrs(state["Apar_flutter"], Apar_flutter, {
{"time_dimension", "t"},
{"units", "T m"},
{"conversion", Bnorm * rho_s0},
{"standard_name", "b dot A"},
{"long_name", "Vector potential A|| used in flutter terms"}
});
}
if (diagnose) {
set_with_attrs(state["Ajpar"], Ajpar, {
{"time_dimension", "t"},
});
set_with_attrs(state["alpha_em"], alpha_em, {
{"time_dimension", "t"},
});
}
}
| 9,569
|
C++
|
.cxx
| 230
| 36.473913
| 108
| 0.641335
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,227
|
sheath_boundary_insulating.cxx
|
bendudson_hermes-3/src/sheath_boundary_insulating.cxx
|
/// Implements an insulating sheath, so J = 0 but ions still flow
/// to the wall. Potential (if set) is linearly extrapolated into the boundary.
#include "../include/sheath_boundary_insulating.hxx"
#include <bout/output_bout_types.hxx>
#include "bout/constants.hxx"
#include "bout/mesh.hxx"
using bout::globals::mesh;
namespace {
BoutReal clip(BoutReal value, BoutReal min, BoutReal max) {
if (value < min)
return min;
if (value > max)
return max;
return value;
}
BoutReal floor(BoutReal value, BoutReal min) {
if (value < min)
return min;
return value;
}
Ind3D indexAt(const Field3D& f, int x, int y, int z) {
int ny = f.getNy();
int nz = f.getNz();
return Ind3D{(x * ny + y) * nz + z, ny, nz};
}
/// Limited free gradient of log of a quantity
/// This ensures that the guard cell values remain positive
/// while also ensuring that the quantity never increases
///
/// fm fc | fp
/// ^ boundary
///
/// exp( 2*log(fc) - log(fm) )
///
BoutReal limitFree(BoutReal fm, BoutReal fc) {
if (fm < fc) {
return fc; // Neumann rather than increasing into boundary
}
if (fm < 1e-10) {
return fc; // Low / no density condition
}
BoutReal fp = SQ(fc) / fm;
#if CHECKLEVEL >= 2
if (!std::isfinite(fp)) {
throw BoutException("SheathBoundary limitFree: {}, {} -> {}", fm, fc, fp);
}
#endif
return fp;
}
}
SheathBoundaryInsulating::SheathBoundaryInsulating(std::string name, Options &alloptions, Solver *) {
AUTO_TRACE();
Options &options = alloptions[name];
Ge = options["secondary_electron_coef"]
.doc("Effective secondary electron emission coefficient")
.withDefault(0.0);
if ((Ge < 0.0) or (Ge > 1.0)) {
throw BoutException("Secondary electron emission must be between 0 and 1 ({:e})", Ge);
}
sin_alpha = options["sin_alpha"]
.doc("Sin of the angle between magnetic field line and wall surface. "
"Should be between 0 and 1")
.withDefault(1.0);
if ((sin_alpha < 0.0) or (sin_alpha > 1.0)) {
throw BoutException("Range of sin_alpha must be between 0 and 1");
}
lower_y = options["lower_y"].doc("Boundary on lower y?").withDefault<bool>(true);
upper_y = options["upper_y"].doc("Boundary on upper y?").withDefault<bool>(true);
gamma_e = options["gamma_e"]
.doc("Electron sheath heat transmission coefficient")
.withDefault(3.5);
}
void SheathBoundaryInsulating::transform(Options &state) {
AUTO_TRACE();
Options& allspecies = state["species"];
Options& electrons = allspecies["e"];
// Need electron properties
// Not const because boundary conditions will be set
Field3D Ne = toFieldAligned(floor(GET_NOBOUNDARY(Field3D, electrons["density"]), 0.0));
Field3D Te = toFieldAligned(GET_NOBOUNDARY(Field3D, electrons["temperature"]));
Field3D Pe = IS_SET_NOBOUNDARY(electrons["pressure"])
? toFieldAligned(getNoBoundary<Field3D>(electrons["pressure"]))
: Te * Ne;
// Ratio of specific heats
const BoutReal electron_adiabatic =
IS_SET(electrons["adiabatic"]) ? get<BoutReal>(electrons["adiabatic"]) : 5. / 3;
// Mass, normalised to proton mass
const BoutReal Me =
IS_SET(electrons["AA"]) ? get<BoutReal>(electrons["AA"]) : SI::Me / SI::Mp;
// This is for applying boundary conditions
Field3D Ve = IS_SET_NOBOUNDARY(electrons["velocity"])
? toFieldAligned(getNoBoundary<Field3D>(electrons["velocity"]))
: zeroFrom(Ne);
Field3D NVe = IS_SET_NOBOUNDARY(electrons["momentum"])
? toFieldAligned(getNoBoundary<Field3D>(electrons["momentum"]))
: zeroFrom(Ne);
Coordinates *coord = mesh->getCoordinates();
//////////////////////////////////////////////////////////////////
// Electrostatic potential
// If phi is set, set free boundary condition
Field3D phi;
if (IS_SET_NOBOUNDARY(state["fields"]["phi"])) {
phi = toFieldAligned(getNoBoundary<Field3D>(state["fields"]["phi"]));
// Free boundary potential linearly extrapolated
if (lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->ystart, jz);
phi[i.ym()] = 2 * phi[i] - phi[i.yp()];
}
}
}
if (upper_y) {
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->yend, jz);
phi[i.yp()] = 2 * phi[i] - phi[i.ym()];
}
}
}
// Set the potential, including boundary conditions
phi = fromFieldAligned(phi);
setBoundary(state["fields"]["phi"], phi);
}
//////////////////////////////////////////////////////////////////
// Electrons
if (lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->ystart, jz);
auto ip = i.yp();
auto im = i.ym();
// Free gradient of log electron density and temperature
// Limited so that the values don't increase into the sheath
// This ensures that the guard cell values remain positive
// exp( 2*log(N[i]) - log(N[ip]) )
Ne[im] = limitFree(Ne[ip], Ne[i]);
Te[im] = limitFree(Te[ip], Te[i]);
Pe[im] = limitFree(Pe[ip], Pe[i]);
// Set zero flow through boundary
// This will be modified when iterating over the ions
Ve[im] = - Ve[i];
NVe[im] = - NVe[i];
}
}
}
if (upper_y) {
// This is essentially the same as at the lower y boundary
// except ystart -> yend, ip <-> im
//
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->yend, jz);
auto ip = i.yp();
auto im = i.ym();
Ne[ip] = limitFree(Ne[im], Ne[i]);
Te[ip] = limitFree(Te[im], Te[i]);
Pe[ip] = limitFree(Pe[im], Pe[i]);
Ve[ip] = - Ve[i];
NVe[ip] = - NVe[i];
}
}
}
// Set electron density and temperature, now with boundary conditions
setBoundary(electrons["density"], fromFieldAligned(Ne));
setBoundary(electrons["temperature"], fromFieldAligned(Te));
setBoundary(electrons["pressure"], fromFieldAligned(Pe));
//////////////////////////////////////////////////////////////////
// Iterate through all ions
// Sum the ion currents into the wall to calculate the electron flow
for (auto& kv : allspecies.getChildren()) {
if (kv.first == "e") {
continue; // Skip electrons
}
Options& species = allspecies[kv.first]; // Note: Need non-const
// Ion charge
const BoutReal Zi =
IS_SET(species["charge"]) ? get<BoutReal>(species["charge"]) : 0.0;
if (Zi == 0.0) {
continue; // Neutral -> skip
}
// Characteristics of this species
const BoutReal Mi = get<BoutReal>(species["AA"]);
const BoutReal adiabatic = IS_SET(species["adiabatic"])
? get<BoutReal>(species["adiabatic"])
: 5. / 3; // Ratio of specific heats (ideal gas)
// Density and temperature boundary conditions will be imposed (free)
Field3D Ni = toFieldAligned(floor(getNoBoundary<Field3D>(species["density"]), 0.0));
Field3D Ti = toFieldAligned(getNoBoundary<Field3D>(species["temperature"]));
Field3D Pi = species.isSet("pressure")
? toFieldAligned(getNoBoundary<Field3D>(species["pressure"]))
: Ni * Ti;
// Get the velocity and momentum
// These will be modified at the boundaries
// and then put back into the state
Field3D Vi = species.isSet("velocity")
? toFieldAligned(getNoBoundary<Field3D>(species["velocity"]))
: zeroFrom(Ni);
Field3D NVi = species.isSet("momentum")
? toFieldAligned(getNoBoundary<Field3D>(species["momentum"]))
: Mi * Ni * Vi;
// Energy source will be modified in the domain
Field3D energy_source = species.isSet("energy_source")
? toFieldAligned(getNonFinal<Field3D>(species["energy_source"]))
: zeroFrom(Ni);
if (lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->ystart, jz);
auto ip = i.yp();
auto im = i.ym();
// Free gradient of log electron density and temperature
// This ensures that the guard cell values remain positive
// exp( 2*log(N[i]) - log(N[ip]) )
Ni[im] = limitFree(Ni[ip], Ni[i]);
Ti[im] = limitFree(Ti[ip], Ti[i]);
Pi[im] = limitFree(Pi[ip], Pi[i]);
// Calculate sheath values at half-way points (cell edge)
const BoutReal nesheath = 0.5 * (Ne[im] + Ne[i]);
const BoutReal nisheath = 0.5 * (Ni[im] + Ni[i]);
const BoutReal tesheath = floor(0.5 * (Te[im] + Te[i]), 1e-5); // electron temperature
const BoutReal tisheath = floor(0.5 * (Ti[im] + Ti[i]), 1e-5); // ion temperature
// Ion sheath heat transmission coefficient
// Equation (22) in Tskhakaya 2005
// with
//
// 1 / (1 + ∂_{ln n_e} ln s_i = s_i ∂_z n_e / ∂_z n_i
// (from comparing C_i^2 in eq. 9 with eq. 20
//
//
BoutReal s_i = clip(nisheath / floor(nesheath, 1e-10), 0, 1); // Concentration
BoutReal grad_ne = Ne[i] - nesheath;
BoutReal grad_ni = Ni[i] - nisheath;
if (fabs(grad_ni) < 1e-3) {
grad_ni = grad_ne = 1e-3; // Remove kinetic correction term
}
// Ion speed into sheath
// Equation (9) in Tskhakaya 2005
//
BoutReal C_i_sq =
clip((adiabatic * tisheath + Zi * s_i * tesheath * grad_ne / grad_ni) / Mi,
0, 100); // Limit for e.g. Ni zero gradient
// Ion sheath heat transmission coefficient
const BoutReal gamma_i = 2.5 + 0.5 * Mi * C_i_sq / tisheath;
const BoutReal visheath = - sqrt(C_i_sq); // Negative -> into sheath
// Set boundary conditions on flows
Vi[im] = 2. * visheath - Vi[i];
NVi[im] = 2. * Mi * nisheath * visheath - NVi[i];
// Add electron flow to balance current
Ve[im] += 2. * visheath * Zi;
NVe[im] += 2. * Me * nisheath * visheath;
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is negative because visheath < 0
BoutReal q =
((gamma_i - 1 - 1 / (adiabatic - 1)) * tisheath - 0.5 * Mi * C_i_sq)
* nisheath * visheath;
if (q > 0.0) {
q = 0.0;
}
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[im])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[im]));
// Divide by volume of cell to get energy loss rate (< 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
ASSERT1(std::isfinite(power));
ASSERT2(power <= 0.0);
energy_source[i] += power;
}
}
}
if (upper_y) {
// Note: This is essentially the same as the lower boundary,
// but with directions reversed e.g. ystart -> yend, ip <-> im
//
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->yend, jz);
auto ip = i.yp();
auto im = i.ym();
// Free gradient of log electron density and temperature
// This ensures that the guard cell values remain positive
// exp( 2*log(N[i]) - log(N[ip]) )
Ni[ip] = limitFree(Ni[im], Ni[i]);
Ti[ip] = limitFree(Ti[im], Ti[i]);
Pi[ip] = limitFree(Pi[im], Pi[i]);
// Calculate sheath values at half-way points (cell edge)
const BoutReal nesheath = 0.5 * (Ne[ip] + Ne[i]);
const BoutReal nisheath = 0.5 * (Ni[ip] + Ni[i]);
const BoutReal tesheath = floor(0.5 * (Te[ip] + Te[i]), 1e-5); // electron temperature
const BoutReal tisheath = floor(0.5 * (Ti[ip] + Ti[i]), 1e-5); // ion temperature
// Ion sheath heat transmission coefficient
//
// 1 / (1 + ∂_{ln n_e} ln s_i = s_i * ∂n_e / (s_i * ∂n_e + ∂ n_i)
BoutReal s_i = (nesheath > 1e-5) ? nisheath / nesheath : 0.0; // Concentration
BoutReal grad_ne = Ne[i] - nesheath;
BoutReal grad_ni = Ni[i] - nisheath;
if (fabs(grad_ni) < 1e-3) {
grad_ni = grad_ne = 1e-3; // Remove kinetic correction term
}
// Ion speed into sheath
// Equation (9) in Tskhakaya 2005
//
BoutReal C_i_sq =
clip((adiabatic * tisheath + Zi * s_i * tesheath * grad_ne / grad_ni) / Mi,
0, 100); // Limit for e.g. Ni zero gradient
const BoutReal gamma_i = 2.5 + 0.5 * Mi * C_i_sq / tisheath; // + Δγ
const BoutReal visheath = sqrt(C_i_sq); // Positive -> into sheath
// Set boundary conditions on flows
Vi[ip] = 2. * visheath - Vi[i];
NVi[ip] = 2. * Mi * nisheath * visheath - NVi[i];
// Add electron flow to balance current
Ve[ip] += 2. * visheath * Zi;
NVe[ip] += 2. * Me * nisheath * visheath;
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is positive because visheath > 0
BoutReal q =
((gamma_i - 1 - 1 / (adiabatic - 1)) * tisheath - 0.5 * C_i_sq * Mi)
* nisheath * visheath;
if (q < 0.0) {
q = 0.0;
}
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[ip])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[ip]));
// Divide by volume of cell to get energy loss rate (> 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
ASSERT1(std::isfinite(power));
ASSERT2(power >= 0.0);
energy_source[i] -= power; // Note: Sign negative because power > 0
}
}
}
// Finished boundary conditions for this species
// Put the modified fields back into the state.
setBoundary(species["density"], fromFieldAligned(Ni));
setBoundary(species["temperature"], fromFieldAligned(Ti));
setBoundary(species["pressure"], fromFieldAligned(Pi));
if (species.isSet("velocity")) {
setBoundary(species["velocity"], fromFieldAligned(Vi));
}
if (species.isSet("momentum")) {
setBoundary(species["momentum"], fromFieldAligned(NVi));
}
// Additional loss of energy through sheath
// Note: Already includes any previously set sources
set(species["energy_source"], fromFieldAligned(energy_source));
}
//////////////////////////////////////////////////////////////////
// Electrons
// This time adding energy sink, having calculated flow
//
Field3D electron_energy_source = electrons.isSet("energy_source")
? toFieldAligned(getNonFinal<Field3D>(electrons["energy_source"]))
: zeroFrom(Ne);
if (lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->ystart, jz);
auto ip = i.yp();
auto im = i.ym();
const BoutReal nesheath = 0.5 * (Ne[im] + Ne[i]);
const BoutReal tesheath = 0.5 * (Te[im] + Te[i]); // electron temperature
// Electron velocity into sheath (< 0). Calculated from ion flow
const BoutReal vesheath = 0.5 * (Ve[im] + Ve[i]);
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is negative because vesheath < 0
BoutReal q = ((gamma_e - 1 - 1 / (electron_adiabatic - 1)) * tesheath
- 0.5 * Me * SQ(vesheath))
* nesheath * vesheath;
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[im])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[im]));
// Divide by volume of cell to get energy loss rate (< 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
#if CHECKLEVEL >= 1
if (!std::isfinite(power)) {
throw BoutException("Non-finite power at {} : Te {} Ne {} Ve {}", i, tesheath, nesheath, vesheath);
}
#endif
electron_energy_source[i] += power;
}
}
}
if (upper_y) {
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->yend, jz);
auto ip = i.yp();
auto im = i.ym();
const BoutReal nesheath = 0.5 * (Ne[ip] + Ne[i]);
const BoutReal tesheath = 0.5 * (Te[ip] + Te[i]); // electron temperature
const BoutReal vesheath = 0.5 * (Ve[im] + Ve[i]); // From ion flow
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is positive because vesheath > 0
BoutReal q = ((gamma_e - 1 - 1 / (electron_adiabatic - 1)) * tesheath
- 0.5 * Me * SQ(vesheath))
* nesheath * vesheath;
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[ip])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[ip]));
// Divide by volume of cell to get energy loss rate (> 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
#if CHECKLEVEL >= 1
if (!std::isfinite(power)) {
throw BoutException("Non-finite power {} at {} : Te {} Ne {} Ve {} => q {}, flux {}",
power, i, tesheath, nesheath, vesheath, q, flux);
}
#endif
electron_energy_source[i] -= power;
}
}
}
// Set energy source (negative in cell next to sheath)
set(electrons["energy_source"], fromFieldAligned(electron_energy_source));
if (IS_SET_NOBOUNDARY(electrons["velocity"])) {
setBoundary(electrons["velocity"], fromFieldAligned(Ve));
}
if (IS_SET_NOBOUNDARY(electrons["momentum"])) {
setBoundary(electrons["momentum"], fromFieldAligned(NVe));
}
}
| 18,786
|
C++
|
.cxx
| 425
| 36.435294
| 102
| 0.57604
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,228
|
zero_current.cxx
|
bendudson_hermes-3/src/zero_current.cxx
|
#include <bout/difops.hxx>
#include "../include/zero_current.hxx"
ZeroCurrent::ZeroCurrent(std::string name, Options& alloptions, Solver*)
: name(name) {
AUTO_TRACE();
Options &options = alloptions[name];
charge = options["charge"].doc("Particle charge. electrons = -1");
ASSERT0(charge != 0.0);
}
void ZeroCurrent::transform(Options &state) {
AUTO_TRACE();
// Current due to other species
Field3D current;
// Now calculate forces on other species
Options& allspecies = state["species"];
for (auto& kv : allspecies.getChildren()) {
if (kv.first == name) {
continue; // Skip self
}
Options& species = allspecies[kv.first]; // Note: Need non-const
if (!(species.isSet("density") and species.isSet("charge"))) {
continue; // Needs both density and charge to contribute
}
if (isSetFinalNoBoundary(species["velocity"], "zero_current")) {
// If velocity is set, update the current
// Note: Mark final so can't be set later
const Field3D N = getNoBoundary<Field3D>(species["density"]);
const BoutReal charge = get<BoutReal>(species["charge"]);
const Field3D V = getNoBoundary<Field3D>(species["velocity"]);
if (!current.isAllocated()) {
// Not yet allocated -> Set to the value
// This avoids having to set to zero initially and add the first time
current = charge * N * V;
} else {
current += charge * N * V;
}
}
}
if (!current.isAllocated()) {
// No currents, probably not what is intended
throw BoutException("No other species to set velocity from");
}
// Get the species density
Options& species = state["species"][name];
if (species["velocity"].isSet()) {
throw BoutException("Cannot use zero_current in species {} if velocity already set\n", name);
}
Field3D N = getNoBoundary<Field3D>(species["density"]);
velocity = current / (-charge * floor(N, 1e-5));
set(species["velocity"], velocity);
}
void ZeroCurrent::outputVars(Options &state) {
AUTO_TRACE();
auto Cs0 = get<BoutReal>(state["Cs0"]);
// Save the velocity
set_with_attrs(state[std::string("V") + name], velocity,
{{"time_dimension", "t"},
{"units", "m / s"},
{"conversion", Cs0},
{"long_name", name + " parallel velocity"},
{"standard_name", "velocity"},
{"species", name},
{"source", "zero_current"}});
}
| 2,494
|
C++
|
.cxx
| 64
| 32.828125
| 97
| 0.627801
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,229
|
ionisation.cxx
|
bendudson_hermes-3/src/ionisation.cxx
|
#include "../include/ionisation.hxx"
#include "../include/integrate.hxx"
Ionisation::Ionisation(std::string name, Options &alloptions, Solver *) {
// Get options for this component
auto& options = alloptions[name];
Eionize = options["Eionize"].doc("Ionisation energy cost").withDefault(30.);
// Get the units
const auto& units = alloptions["units"];
Tnorm = get<BoutReal>(units["eV"]);
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
FreqNorm = 1. / get<BoutReal>(units["seconds"]);
// Normalise
Eionize /= Tnorm;
}
void Ionisation::transform(Options &state) {
// Get neutral atom properties
Options& hydrogen = state["species"]["h"];
Field3D Nn = get<Field3D>(hydrogen["density"]);
Field3D Tn = get<Field3D>(hydrogen["temperature"]);
Field3D Vn = get<Field3D>(hydrogen["velocity"]);
auto AA = get<BoutReal>(hydrogen["AA"]);
Options& electron = state["species"]["e"];
Field3D Ne = get<Field3D>(electron["density"]);
Field3D Te = get<Field3D>(electron["temperature"]);
Options& ion = state["species"]["h+"];
ASSERT1(AA == get<BoutReal>(ion["AA"]));
Field3D reaction_rate = cellAverage(
[&](BoutReal ne, BoutReal nn, BoutReal te) {
return ne * nn * atomic_rates.ionisation(te * Tnorm) * Nnorm / FreqNorm;
},
Ne.getRegion("RGN_NOBNDRY"))(Ne, Nn, Te);
// Particles move from hydrogen to ion
subtract(hydrogen["density_source"],
reaction_rate);
add(ion["density_source"],
reaction_rate);
// Move momentum from hydrogen to ion
Field3D momentum_exchange = reaction_rate * AA * Vn;
subtract(hydrogen["momentum_source"],
momentum_exchange);
add(ion["momentum_source"],
momentum_exchange);
// Move energy from hydrogen to ion
Field3D energy_exchange = reaction_rate * (3. / 2) * Tn;
subtract(hydrogen["energy_source"],
energy_exchange);
add(ion["energy_source"],
energy_exchange);
// Radiate energy from electrons
subtract(electron["energy_source"],
Eionize * reaction_rate);
}
| 2,050
|
C++
|
.cxx
| 52
| 34.961538
| 80
| 0.677126
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,231
|
evolve_density.cxx
|
bendudson_hermes-3/src/evolve_density.cxx
|
#include <bout/constants.hxx>
#include <bout/fv_ops.hxx>
#include <bout/field_factory.hxx>
#include <bout/output_bout_types.hxx>
#include <bout/derivs.hxx>
#include <bout/difops.hxx>
#include <bout/initialprofiles.hxx>
#include "../include/div_ops.hxx"
#include "../include/evolve_density.hxx"
#include "../include/hermes_utils.hxx"
#include "../include/hermes_build_config.hxx"
using bout::globals::mesh;
EvolveDensity::EvolveDensity(std::string name, Options& alloptions, Solver* solver)
: name(name) {
AUTO_TRACE();
auto& options = alloptions[name];
bndry_flux = options["bndry_flux"]
.doc("Allow flows through radial boundaries")
.withDefault<bool>(true);
poloidal_flows =
options["poloidal_flows"].doc("Include poloidal ExB flow").withDefault<bool>(true);
density_floor = options["density_floor"].doc("Minimum density floor").withDefault(1e-5);
low_n_diffuse = options["low_n_diffuse"]
.doc("Parallel diffusion at low density")
.withDefault<bool>(false);
low_n_diffuse_perp = options["low_n_diffuse_perp"]
.doc("Perpendicular diffusion at low density")
.withDefault<bool>(false);
pressure_floor = density_floor * (1./get<BoutReal>(alloptions["units"]["eV"]));
low_p_diffuse_perp = options["low_p_diffuse_perp"]
.doc("Perpendicular diffusion at low pressure")
.withDefault<bool>(false);
hyper_z = options["hyper_z"].doc("Hyper-diffusion in Z").withDefault(-1.0);
evolve_log = options["evolve_log"]
.doc("Evolve the logarithm of density?")
.withDefault<bool>(false);
if (evolve_log) {
// Evolve logarithm of density
solver->add(logN, std::string("logN") + name);
// Save the density to the restart file
// so the simulation can be restarted evolving density
// get_restart_datafile()->addOnce(N, std::string("N") + name);
if (!alloptions["hermes"]["restarting"]) {
// Set logN from N input options
initial_profile(std::string("N") + name, N);
logN = log(N);
} else {
// Ignore these settings
Options::root()[std::string("N") + name].setConditionallyUsed();
}
} else {
// Evolve the density in time
solver->add(N, std::string("N") + name);
}
// Charge and mass
charge = options["charge"].doc("Particle charge. electrons = -1");
AA = options["AA"].doc("Particle atomic mass. Proton = 1");
diagnose =
options["diagnose"].doc("Output additional diagnostics?").withDefault<bool>(false);
const Options& units = alloptions["units"];
const BoutReal Nnorm = units["inv_meters_cubed"];
const BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>();
auto& n_options = alloptions[std::string("N") + name];
source_time_dependent = n_options["source_time_dependent"]
.doc("Use a time-dependent source?")
.withDefault<bool>(false);
source_only_in_core = n_options["source_only_in_core"]
.doc("Zero the source outside the closed field-line region?")
.withDefault<bool>(false);
source_normalisation = Nnorm * Omega_ci;
time_normalisation = 1./Omega_ci;
// Try to read the density source from the mesh
// Units of particles per cubic meter per second
source = 0.0;
mesh->get(source, std::string("N") + name + "_src");
// Allow the user to override the source from input file
source = n_options["source"]
.doc("Source term in ddt(N" + name + std::string("). Units [m^-3/s]"))
.withDefault(source)
/ source_normalisation;
// If time dependent, parse the function with respect to time from the input file
if (source_time_dependent) {
auto str = n_options["source_prefactor"]
.doc("Time-dependent function of multiplier on ddt(N" + name + std::string(") source."))
.as<std::string>();
source_prefactor_function = FieldFactory::get()->parse(str, &n_options);
}
// Putting source at first X index would put it in both PFR in core, this ensures only core
if (source_only_in_core) {
for (int x = mesh->xstart; x <= mesh->xend; x++) {
if (!mesh->periodicY(x)) {
// Not periodic, so not in core
for (int y = mesh->ystart; y <= mesh->yend; y++) {
for (int z = mesh->zstart; z <= mesh->zend; z++) {
source(x, y, z) = 0.0;
}
}
}
}
}
neumann_boundary_average_z = alloptions[std::string("N") + name]["neumann_boundary_average_z"]
.doc("Apply neumann boundary with Z average?")
.withDefault<bool>(false);
}
void EvolveDensity::transform(Options& state) {
AUTO_TRACE();
if (evolve_log) {
// Evolving logN, but most calculations use N
N = exp(logN);
}
mesh->communicate(N);
if (neumann_boundary_average_z) {
// Take Z (usually toroidal) average and apply as X (radial) boundary condition
if (mesh->firstX()) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
BoutReal Navg = 0.0; // Average N in Z
for (int k = 0; k < mesh->LocalNz; k++) {
Navg += N(mesh->xstart, j, k);
}
Navg /= mesh->LocalNz;
// Apply boundary condition
for (int k = 0; k < mesh->LocalNz; k++) {
N(mesh->xstart - 1, j, k) = 2. * Navg - N(mesh->xstart, j, k);
N(mesh->xstart - 2, j, k) = N(mesh->xstart - 1, j, k);
}
}
}
if (mesh->lastX()) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
BoutReal Navg = 0.0; // Average N in Z
for (int k = 0; k < mesh->LocalNz; k++) {
Navg += N(mesh->xend, j, k);
}
Navg /= mesh->LocalNz;
for (int k = 0; k < mesh->LocalNz; k++) {
N(mesh->xend + 1, j, k) = 2. * Navg - N(mesh->xend, j, k);
N(mesh->xend + 2, j, k) = N(mesh->xend + 1, j, k);
}
}
}
}
auto& species = state["species"][name];
set(species["density"], floor(N, 0.0)); // Density in state always >= 0
set(species["AA"], AA); // Atomic mass
if (charge != 0.0) { // Don't set charge for neutral species
set(species["charge"], charge);
}
if (low_n_diffuse) {
// Calculate a diffusion coefficient which can be used in N, P and NV equations
auto* coord = mesh->getCoordinates();
Field3D low_n_coeff =
SQ(coord->dy) * coord->g_22
* log(density_floor / clamp(N, 1e-3 * density_floor, density_floor));
low_n_coeff.applyBoundary("neumann");
set(species["low_n_coeff"], low_n_coeff);
}
// The particle source needs to be known in other components
// (e.g when electromagnetic terms are enabled)
// So evaluate them here rather than in finally()
if (source_time_dependent) {
// Evaluate the source_prefactor function at the current time in seconds and scale source with it
BoutReal time = get<BoutReal>(state["time"]);
BoutReal source_prefactor = source_prefactor_function ->generate(bout::generator::Context().set("x",0,"y",0,"z",0,"t",time*time_normalisation));
final_source = source * source_prefactor;
} else {
final_source = source;
}
final_source.allocate(); // Ensure unique memory storage.
add(species["density_source"], final_source);
}
void EvolveDensity::finally(const Options& state) {
AUTO_TRACE();
auto& species = state["species"][name];
// Get density boundary conditions
// but retain densities which fall below zero
N.setBoundaryTo(get<Field3D>(species["density"]));
if ((fabs(charge) > 1e-5) and state.isSection("fields") and state["fields"].isSet("phi")) {
// Electrostatic potential set and species is charged -> include ExB flow
Field3D phi = get<Field3D>(state["fields"]["phi"]);
ddt(N) = -Div_n_bxGrad_f_B_XPPM(N, phi, bndry_flux, poloidal_flows,
true); // ExB drift
} else {
ddt(N) = 0.0;
}
if (species.isSet("velocity")) {
// Parallel velocity set
Field3D V = get<Field3D>(species["velocity"]);
// Wave speed used for numerical diffusion
// Note: For simulations where ion density is evolved rather than electron density,
// the fast electron dynamics still determine the stability.
Field3D fastest_wave;
if (state.isSet("fastest_wave")) {
fastest_wave = get<Field3D>(state["fastest_wave"]);
} else {
Field3D T = get<Field3D>(species["temperature"]);
BoutReal AA = get<BoutReal>(species["AA"]);
fastest_wave = sqrt(T / AA);
}
ddt(N) -= FV::Div_par_mod<hermes::Limiter>(N, V, fastest_wave, flow_ylow);
if (state.isSection("fields") and state["fields"].isSet("Apar_flutter")) {
// Magnetic flutter term
const Field3D Apar_flutter = get<Field3D>(state["fields"]["Apar_flutter"]);
// Note: Using -Apar_flutter rather than reversing sign in front,
// so that upwinding is handled correctly
ddt(N) -= Div_n_g_bxGrad_f_B_XZ(N, V, -Apar_flutter);
}
}
if (low_n_diffuse) {
// Diffusion which kicks in at very low density, in order to
// help prevent negative density regions
Field3D low_n_coeff = get<Field3D>(species["low_n_coeff"]);
ddt(N) += FV::Div_par_K_Grad_par(low_n_coeff, N);
}
if (low_n_diffuse_perp) {
ddt(N) += Div_Perp_Lap_FV_Index(density_floor / floor(N, 1e-3 * density_floor), N,
bndry_flux);
}
if (low_p_diffuse_perp) {
Field3D Plim = floor(get<Field3D>(species["pressure"]), 1e-3 * pressure_floor);
ddt(N) += Div_Perp_Lap_FV_Index(pressure_floor / Plim, N, true);
}
if (hyper_z > 0.) {
auto* coord = N.getCoordinates();
ddt(N) -= hyper_z * SQ(SQ(coord->dz)) * D4DZ4(N);
}
// Collect the external source from above with all the sources from
// elsewhere (collisions, reactions, etc) for diagnostics
Sn = get<Field3D>(species["density_source"]);
ddt(N) += Sn;
// Scale time derivatives
if (state.isSet("scale_timederivs")) {
ddt(N) *= get<Field3D>(state["scale_timederivs"]);
}
if (evolve_log) {
ddt(logN) = ddt(N) / N;
}
#if CHECKLEVEL >= 1
for (auto& i : N.getRegion("RGN_NOBNDRY")) {
if (!std::isfinite(ddt(N)[i])) {
throw BoutException("ddt(N{}) non-finite at {}. Sn={}\n", name, i, Sn[i]);
}
}
#endif
if (diagnose) {
// Save flows if they are set
if (species.isSet("particle_flow_xlow")) {
flow_xlow = get<Field3D>(species["particle_flow_xlow"]);
}
if (species.isSet("particle_flow_ylow")) {
flow_ylow += get<Field3D>(species["particle_flow_ylow"]);
}
}
}
void EvolveDensity::outputVars(Options& state) {
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
if (evolve_log) {
// Save density to output files
state[std::string("N") + name].force(N);
}
state[std::string("N") + name].setAttributes({{"time_dimension", "t"},
{"units", "m^-3"},
{"conversion", Nnorm},
{"standard_name", "density"},
{"long_name", name + " number density"},
{"species", name},
{"source", "evolve_density"}});
if (diagnose) {
set_with_attrs(
state[std::string("ddt(N") + name + std::string(")")], ddt(N),
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"long_name", std::string("Rate of change of ") + name + " number density"},
{"species", name},
{"source", "evolve_density"}});
set_with_attrs(state[std::string("SN") + name], Sn,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "total density source"},
{"long_name", name + " total number density source"},
{"species", name},
{"source", "evolve_density"}});
set_with_attrs(state[std::string("S") + name + std::string("_src")], final_source,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "external density source"},
{"long_name", name + " external number density source"},
{"species", name},
{"source", "evolve_density"}});
// If fluxes have been set then add them to the output
auto rho_s0 = get<BoutReal>(state["rho_s0"]);
if (flow_xlow.isAllocated()) {
set_with_attrs(state[fmt::format("pf{}_tot_xlow", name)], flow_xlow,
{{"time_dimension", "t"},
{"units", "s^-1"},
{"conversion", rho_s0 * SQ(rho_s0) * Nnorm * Omega_ci},
{"standard_name", "particle flow"},
{"long_name", name + " particle flow in X. Note: May be incomplete."},
{"species", name},
{"source", "evolve_density"}});
}
if (flow_ylow.isAllocated()) {
set_with_attrs(state[fmt::format("pf{}_tot_ylow", name)], flow_ylow,
{{"time_dimension", "t"},
{"units", "s^-1"},
{"conversion", rho_s0 * SQ(rho_s0) * Nnorm * Omega_ci},
{"standard_name", "particle flow"},
{"long_name", name + " particle flow in Y. Note: May be incomplete."},
{"species", name},
{"source", "evolve_density"}});
}
}
}
| 13,819
|
C++
|
.cxx
| 317
| 35.55836
| 148
| 0.580201
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,232
|
hydrogen_charge_exchange.cxx
|
bendudson_hermes-3/src/hydrogen_charge_exchange.cxx
|
#include "../include/hydrogen_charge_exchange.hxx"
void HydrogenChargeExchange::calculate_rates(Options& atom1, Options& ion1,
Options& atom2, Options& ion2,
Field3D &R,
Field3D &atom_mom, Field3D &ion_mom,
Field3D &atom_energy, Field3D &ion_energy,
Field3D &atom_rate, Field3D &ion_rate,
BoutReal &rate_multiplier,
bool &no_neutral_cx_mom_gain) {
// Temperatures and masses of initial atom and ion
const Field3D Tatom = get<Field3D>(atom1["temperature"]);
const BoutReal Aatom = get<BoutReal>(atom1["AA"]);
ASSERT1(get<BoutReal>(ion2["AA"]) == Aatom); // Check that the mass is consistent
const Field3D Tion = get<Field3D>(ion1["temperature"]);
const BoutReal Aion = get<BoutReal>(ion1["AA"]);
ASSERT1(get<BoutReal>(atom2["AA"]) == Aion); // Check that the mass is consistent
// Calculate effective temperature in eV
Field3D Teff = (Tatom / Aatom + Tion / Aion) * Tnorm;
for (auto& i : Teff.getRegion("RGN_NOBNDRY")) {
if (Teff[i] < 0.01) {
Teff[i] = 0.01;
} else if (Teff[i] > 10000) {
Teff[i] = 10000;
}
}
const Field3D lnT = log(Teff);
Field3D ln_sigmav = -18.5028;
Field3D lnT_n = lnT; // (lnT)^n
// b0 -1.850280000000E+01 b1 3.708409000000E-01 b2 7.949876000000E-03
// b3 -6.143769000000E-04 b4 -4.698969000000E-04 b5 -4.096807000000E-04
// b6 1.440382000000E-04 b7 -1.514243000000E-05 b8 5.122435000000E-07
for (BoutReal b : {0.3708409, 7.949876e-3, -6.143769e-4, -4.698969e-4, -4.096807e-4,
1.440382e-4, -1.514243e-5, 5.122435e-7}) {
ln_sigmav += b * lnT_n;
lnT_n *= lnT;
}
// Get rate coefficient, convert cm^3/s to m^3/s then normalise
// Optionally multiply by arbitrary multiplier
const Field3D sigmav = exp(ln_sigmav) * (1e-6 * Nnorm / FreqNorm) * rate_multiplier;
const Field3D Natom = floor(get<Field3D>(atom1["density"]), 1e-5);
const Field3D Nion = floor(get<Field3D>(ion1["density"]), 1e-5);
R = Natom * Nion * sigmav; // Rate coefficient. This is an output parameter.
if ((&atom1 != &atom2) or (&ion1 != &ion2)) {
// Transfer particles atom1 -> ion2, ion1 -> atom2
subtract(atom1["density_source"], R);
add(ion2["density_source"], R);
subtract(ion1["density_source"], R);
add(atom2["density_source"], R);
} // Skip the case where the same isotope swaps places
// Transfer momentum
auto atom1_velocity = get<Field3D>(atom1["velocity"]);
auto ion1_velocity = get<Field3D>(ion1["velocity"]);
// Transfer fom atom1 to ion2
atom_mom = R * Aatom * atom1_velocity;
subtract(atom1["momentum_source"], atom_mom);
if (no_neutral_cx_mom_gain == false) {
add(ion2["momentum_source"], atom_mom);
}
// Transfer from ion1 to atom2
ion_mom = R * Aion * ion1_velocity;
subtract(ion1["momentum_source"], ion_mom);
add(atom2["momentum_source"], ion_mom);
// Frictional heating: Friction force between ions and atoms
// converts kinetic energy to thermal energy
//
// This handles the general case that ion1 != ion2
// and atom1 != atom2
auto ion2_velocity = get<Field3D>(ion2["velocity"]);
add(ion2["energy_source"], 0.5 * Aatom * R * SQ(ion2_velocity - atom1_velocity));
auto atom2_velocity = get<Field3D>(atom2["velocity"]);
add(atom2["energy_source"], 0.5 * Aion * R * SQ(atom2_velocity - ion1_velocity));
// Transfer thermal energy
atom_energy = (3. / 2) * R * Tatom;
subtract(atom1["energy_source"], atom_energy);
add(ion2["energy_source"], atom_energy);
ion_energy = (3. / 2) * R * Tion;
subtract(ion1["energy_source"], ion_energy);
add(atom2["energy_source"], ion_energy);
// Update collision frequency for the two colliding species in s^-1
atom_rate = Nion * sigmav;
ion_rate = Natom * sigmav;
add(atom1["collision_frequency"], atom_rate);
add(ion1["collision_frequency"], ion_rate);
}
| 4,124
|
C++
|
.cxx
| 84
| 41.785714
| 87
| 0.626305
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,233
|
fixed_fraction_ions.cxx
|
bendudson_hermes-3/src/fixed_fraction_ions.cxx
|
#include "../include/fixed_fraction_ions.hxx"
FixedFractionIons::FixedFractionIons(std::string name, Options &alloptions,
Solver *UNUSED(solver)) {
std::string fractions_str =
alloptions[name]["fractions"]
.doc("Comma-separated list of pairs e.g. "
"'species1@fraction1, species2@fraction2'")
.as<std::string>();
for (const auto &pair : strsplit(fractions_str, ',')) {
auto species_frac = strsplit(pair, '@');
if (species_frac.size() != 2) {
throw BoutException("Expected 'species @ fraction', but got %s",
pair.c_str());
}
std::string species = trim(species_frac.front());
BoutReal fraction = stringToReal(trim(species_frac.back()));
fractions.emplace_back(std::pair<std::string, BoutReal>(species, fraction));
}
// Check that there are some species
if (fractions.size() == 0) {
throw BoutException("No ion species specified. Got fractions = '%s'",
fractions_str.c_str());
}
}
void FixedFractionIons::transform(Options &state) {
AUTO_TRACE();
// Electron density
auto Ne = get<Field3D>(state["species"]["e"]["density"]);
for (const auto &spec_frac : fractions) {
set(state["species"][spec_frac.first]["density"],
Ne * spec_frac.second);
}
}
| 1,346
|
C++
|
.cxx
| 33
| 33.606061
| 80
| 0.619157
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,234
|
recycling.cxx
|
bendudson_hermes-3/src/recycling.cxx
|
#include "../include/recycling.hxx"
#include <bout/utils.hxx> // for trim, strsplit
#include "../include/hermes_utils.hxx" // For indexAt
#include "../include/hermes_utils.hxx" // For indexAt
#include <bout/coordinates.hxx>
#include <bout/mesh.hxx>
#include <bout/constants.hxx>
using bout::globals::mesh;
Recycling::Recycling(std::string name, Options& alloptions, Solver*) {
AUTO_TRACE();
const Options& units = alloptions["units"];
const BoutReal Tnorm = units["eV"];
Options& options = alloptions[name];
auto species_list = strsplit(options["species"]
.doc("Comma-separated list of species to recycle")
.as<std::string>(),
',');
// Neutral pump
// Mark cells as having a pump by setting the Field2D is_pump to 1 in the grid file
// Works only on SOL and PFR edges, where it locally modifies the recycle multiplier to the pump albedo
is_pump = 0.0;
mesh->get(is_pump, std::string("is_pump"));
for (const auto& species : species_list) {
std::string from = trim(species, " \t\r()"); // The species name in the list
if (from.empty())
continue; // Missing
// Get the options for this species
Options& from_options = alloptions[from];
std::string to = from_options["recycle_as"]
.doc("Name of the species to recycle into")
.as<std::string>();
diagnose =
from_options["diagnose"].doc("Save additional diagnostics?").withDefault<bool>(false);
BoutReal target_recycle_multiplier =
from_options["target_recycle_multiplier"]
.doc("Multiply the target recycled flux by this factor. Should be >=0 and <= 1")
.withDefault<BoutReal>(1.0);
BoutReal sol_recycle_multiplier =
from_options["sol_recycle_multiplier"]
.doc("Multiply the sol recycled flux by this factor. Should be >=0 and <= 1")
.withDefault<BoutReal>(1.0);
BoutReal pfr_recycle_multiplier =
from_options["pfr_recycle_multiplier"]
.doc("Multiply the pfr recycled flux by this factor. Should be >=0 and <= 1")
.withDefault<BoutReal>(1.0);
BoutReal pump_recycle_multiplier =
from_options["pump_recycle_multiplier"]
.doc("Multiply the pump boundary recycling flux by this factor (like albedo). Should be >=0 and <= 1")
.withDefault<BoutReal>(1.0);
BoutReal target_recycle_energy = from_options["target_recycle_energy"]
.doc("Fixed energy of the recycled particles at target [eV]")
.withDefault<BoutReal>(3.0)
/ Tnorm; // Normalise from eV
BoutReal sol_recycle_energy = from_options["sol_recycle_energy"]
.doc("Fixed energy of the recycled particles at sol [eV]")
.withDefault<BoutReal>(3.0)
/ Tnorm; // Normalise from eV
BoutReal pfr_recycle_energy = from_options["pfr_recycle_energy"]
.doc("Fixed energy of the recycled particles at pfr [eV]")
.withDefault<BoutReal>(3.0)
/ Tnorm; // Normalise from eV
BoutReal target_fast_recycle_fraction =
from_options["target_fast_recycle_fraction"]
.doc("Fraction of ions undergoing fast reflection at target")
.withDefault<BoutReal>(0);
BoutReal pfr_fast_recycle_fraction =
from_options["pfr_fast_recycle_fraction"]
.doc("Fraction of ions undergoing fast reflection at pfr")
.withDefault<BoutReal>(0);
BoutReal sol_fast_recycle_fraction =
from_options["sol_fast_recycle_fraction"]
.doc("Fraction of ions undergoing fast reflection at sol")
.withDefault<BoutReal>(0);
BoutReal target_fast_recycle_energy_factor =
from_options["target_fast_recycle_energy_factor"]
.doc("Fraction of energy retained by fast recycled neutrals at target")
.withDefault<BoutReal>(0);
BoutReal sol_fast_recycle_energy_factor =
from_options["sol_fast_recycle_energy_factor"]
.doc("Fraction of energy retained by fast recycled neutrals at sol")
.withDefault<BoutReal>(0);
BoutReal pfr_fast_recycle_energy_factor =
from_options["pfr_fast_recycle_energy_factor"]
.doc("Fraction of energy retained by fast recycled neutrals at pfr")
.withDefault<BoutReal>(0);
if ((target_recycle_multiplier < 0.0) or (target_recycle_multiplier > 1.0)
or (sol_recycle_multiplier < 0.0) or (sol_recycle_multiplier > 1.0)
or (pfr_recycle_multiplier < 0.0) or (pfr_recycle_multiplier > 1.0)
or (pump_recycle_multiplier < 0.0) or (pump_recycle_multiplier > 1.0)) {
throw BoutException("All recycle multipliers must be betweeen 0 and 1");
}
// Populate recycling channel vector
channels.push_back({
from, to,
target_recycle_multiplier, sol_recycle_multiplier, pfr_recycle_multiplier, pump_recycle_multiplier,
target_recycle_energy, sol_recycle_energy, pfr_recycle_energy,
target_fast_recycle_fraction, pfr_fast_recycle_fraction, sol_fast_recycle_fraction,
target_fast_recycle_energy_factor, sol_fast_recycle_energy_factor, pfr_fast_recycle_energy_factor});
// Boolean flags for enabling recycling in different regions
target_recycle = from_options["target_recycle"]
.doc("Recycling in the targets?")
.withDefault<bool>(false);
sol_recycle = from_options["sol_recycle"]
.doc("Recycling in the SOL edge?")
.withDefault<bool>(false);
pfr_recycle = from_options["pfr_recycle"]
.doc("Recycling in the PFR edge?")
.withDefault<bool>(false);
neutral_pump = from_options["neutral_pump"]
.doc("Neutral pump enabled? Note, need location in grid file")
.withDefault<bool>(false);
}
}
void Recycling::transform(Options& state) {
AUTO_TRACE();
// Get metric tensor components
Coordinates* coord = mesh->getCoordinates();
const Field2D& J = coord->J;
const Field2D& dy = coord->dy;
const Field2D& dx = coord->dx;
const Field2D& dz = coord->dz;
const Field2D& g_22 = coord->g_22;
const Field2D& g11 = coord->g11;
for (const auto& channel : channels) {
const Options& species_from = state["species"][channel.from];
const Field3D N = get<Field3D>(species_from["density"]);
const Field3D V = get<Field3D>(species_from["velocity"]); // Parallel flow velocity
const Field3D T = get<Field3D>(species_from["temperature"]); // Ion temperature
Options& species_to = state["species"][channel.to];
const Field3D Nn = get<Field3D>(species_to["density"]);
const Field3D Pn = get<Field3D>(species_to["pressure"]);
const Field3D Tn = get<Field3D>(species_to["temperature"]);
const BoutReal AAn = get<BoutReal>(species_to["AA"]);
// Recycling particle and energy sources will be added to these global sources
// which are then passed to the density and pressure equations
density_source = species_to.isSet("density_source")
? getNonFinal<Field3D>(species_to["density_source"])
: 0.0;
energy_source = species_to.isSet("energy_source")
? getNonFinal<Field3D>(species_to["energy_source"])
: 0.0;
// Recycling at the divertor target plates
if (target_recycle) {
// Fast recycling needs to know how much energy the "from" species is losing to the boundary
if (species_from.isSet("energy_flow_ylow")) {
energy_flow_ylow = get<Field3D>(species_from["energy_flow_ylow"]);
} else {
energy_flow_ylow = 0;
if (channel.target_fast_recycle_fraction > 0) {
throw BoutException("Target fast recycle enabled but no sheath heat flow available in energy_flow_ylow! \nCurrently only sheath_boundary_simple is supported for fast recycling.");
}
}
target_recycle_density_source = 0;
target_recycle_energy_source = 0;
// Lower Y boundary
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
// Calculate flux through surface [normalised m^-2 s^-1],
// should be positive since V < 0.0
BoutReal flux =
-0.5 * (N(r.ind, mesh->ystart, jz) + N(r.ind, mesh->ystart - 1, jz)) * 0.5
* (V(r.ind, mesh->ystart, jz) + V(r.ind, mesh->ystart - 1, jz));
if (flux < 0.0) {
flux = 0.0;
}
// Flow of recycled neutrals into domain [s-1]
BoutReal flow =
channel.target_multiplier * flux
* (J(r.ind, mesh->ystart) + J(r.ind, mesh->ystart - 1)) / (sqrt(g_22(r.ind, mesh->ystart)) + sqrt(g_22(r.ind, mesh->ystart - 1)))
* 0.5*(dx(r.ind, mesh->ystart) + dx(r.ind, mesh->ystart - 1)) * 0.5*(dz(r.ind, mesh->ystart) + dz(r.ind, mesh->ystart - 1));
BoutReal volume = J(r.ind, mesh->ystart) * dx(r.ind, mesh->ystart) * dy(r.ind, mesh->ystart) * dz(r.ind, mesh->ystart);
// Calculate sources in the final cell [m^-3 s^-1]
target_recycle_density_source(r.ind, mesh->ystart, jz) += flow / volume; // For diagnostic
density_source(r.ind, mesh->ystart, jz) += flow / volume; // For use in solver
// Energy of recycled particles
BoutReal ion_energy_flow = energy_flow_ylow(r.ind, mesh->ystart, jz) * -1; // This is ylow end so take first domain cell and flip sign
// Blend fast (ion energy) and thermal (constant energy) recycling
// Calculate returning neutral heat flow in [W]
BoutReal recycle_energy_flow =
ion_energy_flow * channel.target_multiplier * channel.target_fast_recycle_energy_factor * channel.target_fast_recycle_fraction // Fast recycling part
+ flow * (1 - channel.target_fast_recycle_fraction) * channel.target_energy; // Thermal recycling part
// Divide heat flow in [W] by cell volume to get source in [m^-3 s^-1]
target_recycle_energy_source(r.ind, mesh->ystart, jz) += recycle_energy_flow / volume;
energy_source(r.ind, mesh->ystart, jz) += recycle_energy_flow / volume;
}
}
// Upper Y boundary
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
// Calculate flux of ions into target from Ne and Vi boundary
// This calculation is supposed to be consistent with the flow
// of plasma from FV::Div_par(N, V)
for (int jz = 0; jz < mesh->LocalNz; jz++) {
// Flux through surface [normalised m^-2 s^-1], should be positive
BoutReal flux = 0.5 * (N(r.ind, mesh->yend, jz) + N(r.ind, mesh->yend + 1, jz))
* 0.5 * (V(r.ind, mesh->yend, jz) + V(r.ind, mesh->yend + 1, jz));
if (flux < 0.0) {
flux = 0.0;
}
// Flow of recycled neutrals into domain [s-1]
BoutReal flow =
channel.target_multiplier * flux
* (J(r.ind, mesh->yend) + J(r.ind, mesh->yend + 1)) / (sqrt(g_22(r.ind, mesh->yend)) + sqrt(g_22(r.ind, mesh->yend + 1)))
* 0.5*(dx(r.ind, mesh->yend) + dx(r.ind, mesh->yend + 1)) * 0.5*(dz(r.ind, mesh->yend) + dz(r.ind, mesh->yend + 1));
BoutReal volume = J(r.ind, mesh->yend) * dx(r.ind, mesh->yend) * dy(r.ind, mesh->yend) * dz(r.ind, mesh->yend);
// Calculate sources in the final cell [m^-3 s^-1]
target_recycle_density_source(r.ind, mesh->yend, jz) += flow / volume; // For diagnostic
density_source(r.ind, mesh->yend, jz) += flow / volume; // For use in solver
// Energy of recycled particles
BoutReal ion_energy_flow = energy_flow_ylow(r.ind, mesh->yend + 1, jz); // Ion heat flow to wall in [W]. This is yup end so take guard cell
// Blend fast (ion energy) and thermal (constant energy) recycling
// Calculate returning neutral heat flow in [W]
BoutReal recycle_energy_flow =
ion_energy_flow * channel.target_multiplier * channel.target_fast_recycle_energy_factor * channel.target_fast_recycle_fraction // Fast recycling part
+ flow * (1 - channel.target_fast_recycle_fraction) * channel.target_energy; // Thermal recycling part
// Divide heat flow in [W] by cell volume to get source in [m^-3 s^-1]
target_recycle_energy_source(r.ind, mesh->yend, jz) += recycle_energy_flow / volume;
energy_source(r.ind, mesh->yend, jz) += recycle_energy_flow / volume;
}
}
}
// Initialise counters of pump recycling fluxes
wall_recycle_density_source = 0;
wall_recycle_energy_source = 0;
pump_density_source = 0;
pump_energy_source = 0;
// Get edge particle and heat for the species being recycled
if (sol_recycle or pfr_recycle) {
if (species_from.isSet("energy_flow_xlow")) {
energy_flow_xlow = get<Field3D>(species_from["energy_flow_xlow"]);
} else if ((channel.sol_fast_recycle_fraction > 0) or (channel.pfr_fast_recycle_fraction > 0)) {
throw BoutException("SOL/PFR fast recycle enabled but no cell edge heat flow available, check your wall BC choice");
};
if (species_from.isSet("particle_flow_xlow")) {
particle_flow_xlow = get<Field3D>(species_from["particle_flow_xlow"]);
} else if ((channel.sol_fast_recycle_fraction > 0) or (channel.pfr_fast_recycle_fraction > 0)) {
throw BoutException("SOL/PFR fast recycle enabled but no cell edge particle flow available, check your wall BC choice");
};
}
// Recycling at the SOL edge (2D/3D only)
if (sol_recycle) {
// Flow out of domain is positive in the positive coordinate direction
Field3D radial_particle_outflow = particle_flow_xlow;
Field3D radial_energy_outflow = energy_flow_xlow;
if(mesh->lastX()){ // Only do this for the processor which has the edge region
for(int iy=0; iy < mesh->LocalNy ; iy++){
for(int iz=0; iz < mesh->LocalNz; iz++){
// Volume of cell adjacent to wall which will receive source
BoutReal volume = J(mesh->xend, iy) * dx(mesh->xend, iy)
* dy(mesh->xend, iy) * dz(mesh->xend, iy);
// If cell is a pump, overwrite multiplier with pump multiplier
BoutReal multiplier = channel.sol_multiplier;
if ((is_pump(mesh->xend, iy) == 1.0) and (neutral_pump)) {
multiplier = channel.pump_multiplier;
}
// Flow of recycled species back from the edge due to recycling
// SOL edge = LHS flow of inner guard cells on the high X side (mesh->xend+1)
// Recycling source is 0 for each cell where the flow goes into instead of out of the domain
BoutReal recycle_particle_flow = 0;
if (radial_particle_outflow(mesh->xend+1, iy, iz) > 0) {
recycle_particle_flow = multiplier * radial_particle_outflow(mesh->xend+1, iy, iz);
}
BoutReal ion_energy_flow = radial_energy_outflow(mesh->xend+1, iy, iz); // Ion heat flow to wall in [W]. This is on xlow edge so take guard cell
// Blend fast (ion energy) and thermal (constant energy) recycling
// Calculate returning neutral heat flow in [W]
BoutReal recycle_energy_flow =
ion_energy_flow * channel.sol_multiplier * channel.sol_fast_recycle_energy_factor * channel.sol_fast_recycle_fraction // Fast recycling part
+ recycle_particle_flow * (1 - channel.sol_fast_recycle_fraction) * channel.sol_energy; // Thermal recycling part
// Calculate neutral pump neutral sinks due to neutral impingement
// These are additional to particle sinks due to recycling
BoutReal pump_neutral_energy_sink = 0;
BoutReal pump_neutral_particle_sink = 0;
if ((is_pump(mesh->xend, iy) == 1.0) and (neutral_pump)) {
auto i = indexAt(Nn, mesh->xend, iy, iz); // Final domain cell
auto is = i.xm(); // Second to final domain cell
auto ig = i.xp(); // First guard cell
// Free boundary condition on Nn, Pn, Tn
// These are NOT communicated back into state and will exist only in this component
// This will prevent neutrals leaking through cross-field transport from neutral_mixed or other components
// While enabling us to still calculate radial wall fluxes separately here
BoutReal nnguard = SQ(Nn[i]) / Nn[is];
BoutReal pnguard = SQ(Pn[i]) / Pn[is];
BoutReal tnguard = SQ(Tn[i]) / Tn[is];
// Calculate wall conditions
BoutReal nnsheath = 0.5 * (Nn[i] + nnguard);
BoutReal tnsheath = 0.5 * (Tn[i] + tnguard);
BoutReal v_th = 0.25 * sqrt( 8*tnsheath / (PI*AAn) ); // Stangeby p.69 eqns. 2.21, 2.24
// Convert dy to poloidal length: dl = dy * sqrt(g22) = dy * h_theta
// Convert dz to toroidal length: = dz*sqrt(g_33) = dz * R = 2piR
// Calculate radial wall area in [m^2]
// Calculate final cell volume [m^3]
BoutReal dpolsheath = 0.5*(coord->dy[i] + coord->dy[ig]) * 1/( 0.5*(sqrt(coord->g22[i]) + sqrt(coord->g22[ig])) );
BoutReal dtorsheath = 0.5*(coord->dz[i] + coord->dz[ig]) * 0.5*(sqrt(coord->g_33[i]) + sqrt(coord->g_33[ig]));
BoutReal dasheath = dpolsheath * dtorsheath; // [m^2]
BoutReal dv = coord->J[i] * coord->dx[i] * coord->dy[i] * coord->dz[i];
// Calculate particle and energy fluxes of neutrals hitting the pump
// Assume thermal velocity greater than perpendicular velocity and use it for flux calc
BoutReal pump_neutral_particle_flow = v_th * nnsheath * dasheath; // [s^-1]
pump_neutral_particle_sink = pump_neutral_particle_flow / dv * (1 - multiplier); // Particle sink [s^-1 m^-3]
// Use gamma=2.0 as per Stangeby p.69, total energy of static Maxwellian
BoutReal pump_neutral_energy_flow = 2.0 * tnsheath * v_th * nnsheath * dasheath; // [W]
pump_neutral_energy_sink = pump_neutral_energy_flow / dv * (1 - multiplier); // heatsink [W m^-3]
// Divide flows by volume to get sources
// Save to pump diagnostic
pump_density_source(mesh->xend, iy, iz) += recycle_particle_flow/volume - pump_neutral_particle_sink;
pump_energy_source(mesh->xend, iy, iz) += recycle_energy_flow/volume - pump_neutral_energy_sink;
} else {
// Save to wall diagnostic (pump sinks are 0 if not on pump)
wall_recycle_density_source(mesh->xend, iy, iz) += recycle_particle_flow/volume - pump_neutral_particle_sink;
wall_recycle_energy_source(mesh->xend, iy, iz) += recycle_energy_flow/volume - pump_neutral_energy_sink;
}
// Save to solver
density_source(mesh->xend, iy, iz) += recycle_particle_flow/volume - pump_neutral_particle_sink;
energy_source(mesh->xend, iy, iz) += recycle_energy_flow/volume - pump_neutral_energy_sink;
}
}
}
}
// Recycling at the PFR edge (2D/3D only)
if (pfr_recycle) {
// PFR is flipped compared to edge: x=0 is at the PFR edge. Therefore outflow is in the negative coordinate direction.
Field3D radial_particle_outflow = particle_flow_xlow * -1;
Field3D radial_energy_outflow = energy_flow_xlow * -1;
if(mesh->firstX()){ // Only do this for the processor which has the core region
if (!mesh->periodicY(mesh->xstart)) { // Only do this for the processor with a periodic Y, i.e. the PFR
for(int iy=0; iy < mesh->LocalNy ; iy++){
for(int iz=0; iz < mesh->LocalNz; iz++){
// Volume of cell adjacent to wall which will receive source
BoutReal volume = J(mesh->xstart, iy) * dx(mesh->xstart, iy)
* dy(mesh->xstart, iy) * dz(mesh->xstart, iy);
// If cell is a pump, overwrite multiplier with pump multiplier
BoutReal multiplier = channel.pfr_multiplier;
if ((is_pump(mesh->xstart, iy) == 1.0) and (neutral_pump)) {
multiplier = channel.pump_multiplier;
}
// Flow of recycled species back from the edge due to recycling
// PFR edge = LHS flow of the first domain cell on the low X side (mesh->xstart)
// Recycling source is 0 for each cell where the flow goes into instead of out of the domain
BoutReal recycle_particle_flow = 0;
if (radial_particle_outflow(mesh->xstart, iy, iz) > 0) {
recycle_particle_flow = multiplier * radial_particle_outflow(mesh->xstart, iy, iz);
}
BoutReal ion_energy_flow = radial_energy_outflow(mesh->xstart, iy, iz); // Ion heat flow to wall in [W]. This is on xlow edge so take first domain cell
// Blend fast (ion energy) and thermal (constant energy) recycling
// Calculate returning neutral heat flow in [W]
BoutReal recycle_energy_flow =
ion_energy_flow * channel.pfr_multiplier * channel.pfr_fast_recycle_energy_factor * channel.pfr_fast_recycle_fraction // Fast recycling part
+ recycle_particle_flow * (1 - channel.pfr_fast_recycle_fraction) * channel.pfr_energy; // Thermal recycling part
// Calculate neutral pump neutral sinks due to neutral impingement
// These are additional to particle sinks due to recycling
BoutReal pump_neutral_energy_sink = 0;
BoutReal pump_neutral_particle_sink = 0;
// Add to appropriate diagnostic field depending if pump or not
if ((is_pump(mesh->xstart, iy) == 1.0) and (neutral_pump)) {
auto i = indexAt(Nn, mesh->xstart, iy, iz); // Final domain cell
auto is = i.xp(); // Second to final domain cell
auto ig = i.xm(); // First guard cell
// Free boundary condition on Nn, Pn, Tn
// These are NOT communicated back into state and will exist only in this component
// This will prevent neutrals leaking through cross-field transport from neutral_mixed or other components
// While enabling us to still calculate radial wall fluxes separately here
BoutReal nnguard = SQ(Nn[i]) / Nn[is];
BoutReal pnguard = SQ(Pn[i]) / Pn[is];
BoutReal tnguard = SQ(Tn[i]) / Tn[is];
// Calculate wall conditions
BoutReal nnsheath = 0.5 * (Nn[i] + nnguard);
BoutReal tnsheath = 0.5 * (Tn[i] + tnguard);
BoutReal v_th = 0.25 * sqrt( 8*tnsheath / (PI*AAn) ); // Stangeby p.69 eqns. 2.21, 2.24
// Convert dy to poloidal length: dl = dy * sqrt(g22) = dy * h_theta
// Convert dz to toroidal length: = dz*sqrt(g_33) = dz * R = 2piR
// Calculate radial wall area in [m^2]
// Calculate final cell volume [m^3]
BoutReal dpolsheath = 0.5*(coord->dy[i] + coord->dy[ig]) * 1/( 0.5*(sqrt(coord->g22[i]) + sqrt(coord->g22[ig])) );
BoutReal dtorsheath = 0.5*(coord->dz[i] + coord->dz[ig]) * 0.5*(sqrt(coord->g_33[i]) + sqrt(coord->g_33[ig]));
BoutReal dasheath = dpolsheath * dtorsheath; // [m^2]
BoutReal dv = coord->J[i] * coord->dx[i] * coord->dy[i] * coord->dz[i];
// Calculate particle and energy fluxes of neutrals hitting the pump
// Assume thermal velocity greater than perpendicular velocity and use it for flux calc
BoutReal pump_neutral_particle_flow = v_th * nnsheath * dasheath; // [s^-1]
pump_neutral_particle_sink = pump_neutral_particle_flow / dv * (1 - multiplier); // Particle sink [s^-1 m^-3]
// Use gamma=2.0 as per Stangeby p.69, total energy of static Maxwellian
BoutReal pump_neutral_energy_flow = 2.0 * tnsheath * v_th * nnsheath * dasheath; // [W]
pump_neutral_energy_sink = pump_neutral_energy_flow / dv * (1 - multiplier); // heatsink [W m^-3]
// Divide flows by volume to get sources
// Save to pump diagnostic
pump_density_source(mesh->xstart, iy, iz) += recycle_particle_flow/volume - pump_neutral_particle_sink;
pump_energy_source(mesh->xstart, iy, iz) += recycle_energy_flow/volume - pump_neutral_energy_sink;
} else {
// Save to wall diagnostic (pump sinks are 0 if not on pump)
wall_recycle_density_source(mesh->xstart, iy, iz) += recycle_particle_flow/volume - pump_neutral_particle_sink;
wall_recycle_energy_source(mesh->xstart, iy, iz) += recycle_energy_flow/volume - pump_neutral_energy_sink;
}
// Save to solver
density_source(mesh->xstart, iy, iz) += recycle_particle_flow/volume - pump_neutral_particle_sink;
energy_source(mesh->xstart, iy, iz) += recycle_energy_flow/volume - pump_neutral_energy_sink;
}
}
}
}
}
// Put the updated sources back into the state
set<Field3D>(species_to["density_source"], density_source);
set<Field3D>(species_to["energy_source"], energy_source);
}
}
void Recycling::outputVars(Options& state) {
AUTO_TRACE();
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
if (diagnose) {
for (const auto& channel : channels) {
AUTO_TRACE();
// Save particle and energy source for the species created during recycling
// Target recycling
if (target_recycle) {
set_with_attrs(state[{std::string("S") + channel.to + std::string("_target_recycle")}], target_recycle_density_source,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "particle source"},
{"long_name", std::string("Target recycling particle source of ") + channel.to},
{"source", "recycling"}});
set_with_attrs(state[{std::string("E") + channel.to + std::string("_target_recycle")}], target_recycle_energy_source,
{{"time_dimension", "t"},
{"units", "W m^-3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "energy source"},
{"long_name", std::string("Target recycling energy source of ") + channel.to},
{"source", "recycling"}});
}
// Wall recycling
if ((sol_recycle) or (pfr_recycle)) {
set_with_attrs(state[{std::string("S") + channel.to + std::string("_wall_recycle")}], wall_recycle_density_source,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "particle source"},
{"long_name", std::string("Wall recycling particle source of ") + channel.to},
{"source", "recycling"}});
set_with_attrs(state[{std::string("E") + channel.to + std::string("_wall_recycle")}], wall_recycle_energy_source,
{{"time_dimension", "t"},
{"units", "W m^-3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "energy source"},
{"long_name", std::string("Wall recycling energy source of ") + channel.to},
{"source", "recycling"}});
}
// Neutral pump
if (neutral_pump) {
set_with_attrs(state[{std::string("S") + channel.to + std::string("_pump")}], pump_density_source,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "particle source"},
{"long_name", std::string("Pump recycling particle source of ") + channel.to},
{"source", "recycling"}});
set_with_attrs(state[{std::string("E") + channel.to + std::string("_pump")}], pump_energy_source,
{{"time_dimension", "t"},
{"units", "W m^-3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "energy source"},
{"long_name", std::string("Pump recycling energy source of ") + channel.to},
{"source", "recycling"}});
set_with_attrs(state[{std::string("is_pump")}], is_pump,
{{"standard_name", "neutral pump location"},
{"long_name", std::string("Neutral pump location")},
{"source", "recycling"}});
}
}
}
}
| 30,178
|
C++
|
.cxx
| 473
| 50.718816
| 189
| 0.587169
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,235
|
component_scheduler.cxx
|
bendudson_hermes-3/src/component_scheduler.cxx
|
#include "../include/component_scheduler.hxx"
#include <bout/utils.hxx> // for trim, strsplit
ComponentScheduler::ComponentScheduler(Options &scheduler_options,
Options &component_options,
Solver *solver) {
std::string component_names = scheduler_options["components"]
.doc("Components in order of execution")
.as<std::string>();
// For now split on ','. Something like "->" might be better
for (const auto &name : strsplit(component_names, ',')) {
// Ignore brackets, to allow these to be used to span lines.
// In future brackets may be useful for complex scheduling
auto name_trimmed = trim(name, " \t\r()");
if (name_trimmed.empty()) {
continue;
}
// For each component e.g. "e", several Component types can be created
// but if types are not specified then the component name is used
std::string types = component_options[name_trimmed].isSet("type")
? component_options[name_trimmed]["type"].as<std::string>()
: name_trimmed;
for (const auto &type : strsplit(types, ',')) {
auto type_trimmed = trim(type, " \t\r()");
if (type_trimmed.empty()) {
continue;
}
components.push_back(Component::create(type_trimmed,
name_trimmed,
component_options,
solver));
}
}
}
std::unique_ptr<ComponentScheduler> ComponentScheduler::create(Options &scheduler_options,
Options &component_options,
Solver *solver) {
return std::make_unique<ComponentScheduler>(scheduler_options,
component_options, solver);
}
void ComponentScheduler::transform(Options &state) {
// Run through each component
for(auto &component : components) {
component->transform(state);
}
// Enable components to update themselves based on the final state
for(auto &component : components) {
component->finally(state);
}
}
void ComponentScheduler::outputVars(Options &state) {
// Run through each component
for(auto &component : components) {
component->outputVars(state);
}
}
void ComponentScheduler::restartVars(Options &state) {
// Run through each component
for(auto &component : components) {
component->restartVars(state);
}
}
void ComponentScheduler::precon(const Options &state, BoutReal gamma) {
for(auto &component : components) {
component->precon(state, gamma);
}
}
| 2,796
|
C++
|
.cxx
| 66
| 31.318182
| 90
| 0.583579
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,236
|
snb_conduction.cxx
|
bendudson_hermes-3/src/snb_conduction.cxx
|
#include <bout/constants.hxx>
#include "../include/snb_conduction.hxx"
#include <bout/bout.hxx>
using bout::globals::mesh;
void SNBConduction::transform(Options& state) {
auto& units = state["units"];
const auto rho_s0 = get<BoutReal>(units["meters"]);
const auto Tnorm = get<BoutReal>(units["eV"]);
const auto Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
const auto Omega_ci = 1. / get<BoutReal>(units["seconds"]);
Options& electrons = state["species"]["e"];
// Note: Needs boundary conditions on temperature
const Field3D Te = GET_VALUE(Field3D, electrons["temperature"]) * Tnorm; // eV
const Field3D Ne = GET_VALUE(Field3D, electrons["density"]) * Nnorm; // In m^-3
// SNB non-local heat flux. Also returns the Spitzer-Harm value for comparison
// Note: Te in eV, Ne in Nnorm
Field2D dy_orig = mesh->getCoordinates()->dy;
mesh->getCoordinates()->dy *= rho_s0; // Convert distances to m
// Inputs in eV and m^-3
Div_Q_SNB = snb.divHeatFlux(Te, Ne, &Div_Q_SH);
// Restore the metric tensor
mesh->getCoordinates()->dy = dy_orig;
// Normalise from eV/m^3/s
Div_Q_SNB /= Tnorm * Nnorm * Omega_ci;
Div_Q_SH /= Tnorm * Nnorm * Omega_ci;
// Divergence of heat flux appears with a minus sign in energy source:
//
// ddt(3/2 P) = .. - Div(q)
subtract(electrons["energy_source"], Div_Q_SNB);
}
void SNBConduction::outputVars(Options& state) {
AUTO_TRACE();
if (diagnose) {
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
BoutReal DivQnorm = SI::qe * Tnorm * Nnorm * Omega_ci;
set_with_attrs(state["Div_Q_SH"], Div_Q_SH,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", DivQnorm},
{"long_name", "Divergence of Spitzer-Harm electron heat conduction"},
{"source", "snb_conduction"}});
set_with_attrs(state["Div_Q_SNB"], Div_Q_SNB,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", DivQnorm},
{"long_name", "Divergence of SNB electron heat conduction"},
{"source", "snb_conduction"}});
}
}
| 2,293
|
C++
|
.cxx
| 51
| 38.294118
| 89
| 0.611036
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,237
|
noflow_boundary.cxx
|
bendudson_hermes-3/src/noflow_boundary.cxx
|
#include "../include/noflow_boundary.hxx"
#include "bout/mesh.hxx"
using bout::globals::mesh;
namespace {
Ind3D indexAt(const Field3D& f, int x, int y, int z) {
int ny = f.getNy();
int nz = f.getNz();
return Ind3D{(x * ny + y) * nz + z, ny, nz};
}
}
void NoFlowBoundary::transform(Options& state) {
AUTO_TRACE();
// Make sure that the state has been set for this species
ASSERT1(state["species"].isSection(name));
Options& species = state["species"][name];
// Apply zero-gradient boundary conditions to state variables
for (const std::string field : {"density", "temperature", "pressure"}) {
if (!species.isSet(field)) {
continue; // Skip variables which are not set
}
// Note: Not assuming boundary is set because we're going to set it
Field3D var = GET_NOBOUNDARY(Field3D, species[field]);
var.clearParallelSlices();
if (noflow_lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(var, r.ind, mesh->ystart, jz);
auto im = i.ym();
var[im] = var[i];
}
}
}
if (noflow_upper_y) {
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(var, r.ind, mesh->yend, jz);
auto ip = i.yp();
var[ip] = var[i];
}
}
}
// Promise that we're only modifying the boundary
setBoundary<Field3D>(species[field], var);
}
// Apply zero-value boundary conditions to flows
for (const std::string field : {"velocity", "momentum"}) {
if (!species.isSet(field)) {
continue; // Skip variables which are not set
}
Field3D var = GET_NOBOUNDARY(Field3D, species[field]);
var.clearParallelSlices();
if (noflow_lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(var, r.ind, mesh->ystart, jz);
auto im = i.ym();
var[im] = - var[i];
}
}
}
if (noflow_upper_y) {
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(var, r.ind, mesh->yend, jz);
auto ip = i.yp();
var[ip] = - var[i];
}
}
}
// Promise that we're only modifying the boundary
setBoundary<Field3D>(species[field], var);
}
}
| 2,563
|
C++
|
.cxx
| 73
| 29
| 76
| 0.587616
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,238
|
sheath_boundary.cxx
|
bendudson_hermes-3/src/sheath_boundary.cxx
|
#include "../include/sheath_boundary.hxx"
#include <bout/output_bout_types.hxx>
#include "bout/constants.hxx"
#include "bout/mesh.hxx"
using bout::globals::mesh;
namespace {
BoutReal clip(BoutReal value, BoutReal min, BoutReal max) {
if (value < min)
return min;
if (value > max)
return max;
return value;
}
BoutReal floor(BoutReal value, BoutReal min) {
if (value < min)
return min;
return value;
}
Ind3D indexAt(const Field3D& f, int x, int y, int z) {
int ny = f.getNy();
int nz = f.getNz();
return Ind3D{(x * ny + y) * nz + z, ny, nz};
}
/// Limited free gradient of log of a quantity
/// This ensures that the guard cell values remain positive
/// while also ensuring that the quantity never increases
///
/// fm fc | fp
/// ^ boundary
///
/// exp( 2*log(fc) - log(fm) )
///
BoutReal limitFree(BoutReal fm, BoutReal fc) {
if (fm < fc) {
return fc; // Neumann rather than increasing into boundary
}
if (fm < 1e-10) {
return fc; // Low / no density condition
}
BoutReal fp = SQ(fc) / fm;
#if CHECKLEVEL >= 2
if (!std::isfinite(fp)) {
throw BoutException("SheathBoundary limitFree: {}, {} -> {}", fm, fc, fp);
}
#endif
return fp;
}
}
SheathBoundary::SheathBoundary(std::string name, Options &alloptions, Solver *) {
AUTO_TRACE();
Options &options = alloptions[name];
Ge = options["secondary_electron_coef"]
.doc("Effective secondary electron emission coefficient")
.withDefault(0.0);
if ((Ge < 0.0) or (Ge > 1.0)) {
throw BoutException("Secondary electron emission must be between 0 and 1 ({:e})", Ge);
}
sin_alpha = options["sin_alpha"]
.doc("Sin of the angle between magnetic field line and wall surface. "
"Should be between 0 and 1")
.withDefault(1.0);
if ((sin_alpha < 0.0) or (sin_alpha > 1.0)) {
throw BoutException("Range of sin_alpha must be between 0 and 1");
}
lower_y = options["lower_y"].doc("Boundary on lower y?").withDefault<bool>(true);
upper_y = options["upper_y"].doc("Boundary on upper y?").withDefault<bool>(true);
always_set_phi =
options["always_set_phi"]
.doc("Always set phi field? Default is to only modify if already set")
.withDefault<bool>(false);
const Options& units = alloptions["units"];
const BoutReal Tnorm = units["eV"];
// Read wall voltage, convert to normalised units
wall_potential = options["wall_potential"]
.doc("Voltage of the wall [Volts]")
.withDefault(Field3D(0.0))
/ Tnorm;
// Convert to field aligned coordinates
wall_potential = toFieldAligned(wall_potential);
// Note: wall potential at the last cell before the boundary is used,
// not the value at the boundary half-way between cells. This is due
// to how twist-shift boundary conditions and non-aligned inputs are
// treated; using the cell boundary gives incorrect results.
floor_potential = options["floor_potential"]
.doc("Apply a floor to wall potential when calculating Ve?")
.withDefault<bool>(true);
}
void SheathBoundary::transform(Options &state) {
AUTO_TRACE();
Options& allspecies = state["species"];
Options& electrons = allspecies["e"];
// Need electron properties
// Not const because boundary conditions will be set
Field3D Ne = toFieldAligned(floor(GET_NOBOUNDARY(Field3D, electrons["density"]), 0.0));
Field3D Te = toFieldAligned(GET_NOBOUNDARY(Field3D, electrons["temperature"]));
Field3D Pe = IS_SET_NOBOUNDARY(electrons["pressure"])
? toFieldAligned(getNoBoundary<Field3D>(electrons["pressure"]))
: Te * Ne;
// Ratio of specific heats
const BoutReal electron_adiabatic =
IS_SET(electrons["adiabatic"]) ? get<BoutReal>(electrons["adiabatic"]) : 5. / 3;
// Mass, normalised to proton mass
const BoutReal Me =
IS_SET(electrons["AA"]) ? get<BoutReal>(electrons["AA"]) : SI::Me / SI::Mp;
// This is for applying boundary conditions
Field3D Ve = IS_SET_NOBOUNDARY(electrons["velocity"])
? toFieldAligned(getNoBoundary<Field3D>(electrons["velocity"]))
: zeroFrom(Ne);
Field3D NVe = IS_SET_NOBOUNDARY(electrons["momentum"])
? toFieldAligned(getNoBoundary<Field3D>(electrons["momentum"]))
: zeroFrom(Ne);
Coordinates *coord = mesh->getCoordinates();
//////////////////////////////////////////////////////////////////
// Electrostatic potential
// If phi is set, use free boundary condition
// If phi not set, calculate assuming zero current
Field3D phi;
if (IS_SET_NOBOUNDARY(state["fields"]["phi"])) {
phi = toFieldAligned(getNoBoundary<Field3D>(state["fields"]["phi"]));
} else {
// Calculate potential phi assuming zero current
// Note: This is equation (22) in Tskhakaya 2005, with I = 0
// Need to sum s_i Z_i C_i over all ion species
//
// To avoid looking up species for every grid point, this
// loops over the boundaries once per species.
Field3D ion_sum {zeroFrom(Ne)};
phi = emptyFrom(Ne); // So phi is field aligned
// Iterate through charged ion species
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first];
if ((kv.first == "e") or !IS_SET(species["charge"])
or (get<BoutReal>(species["charge"]) == 0.0)) {
continue; // Skip electrons and non-charged ions
}
const Field3D Ni = toFieldAligned(floor(GET_NOBOUNDARY(Field3D, species["density"]), 0.0));
const Field3D Ti = toFieldAligned(GET_NOBOUNDARY(Field3D, species["temperature"]));
const BoutReal Mi = GET_NOBOUNDARY(BoutReal, species["AA"]);
const BoutReal Zi = GET_NOBOUNDARY(BoutReal, species["charge"]);
const BoutReal adiabatic = IS_SET(species["adiabatic"])
? get<BoutReal>(species["adiabatic"])
: 5. / 3; // Ratio of specific heats (ideal gas)
if (lower_y) {
// Sum values, put result in mesh->ystart
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ni, r.ind, mesh->ystart, jz);
auto ip = i.yp();
// Free boundary extrapolate ion concentration
BoutReal s_i = clip(0.5 * (3. * Ni[i] / Ne[i] - Ni[ip] / Ne[ip]),
0.0, 1.0); // Limit range to [0,1]
if (!std::isfinite(s_i)) {
s_i = 1.0;
}
BoutReal te = Te[i];
BoutReal ti = Ti[i];
// Equation (9) in Tskhakaya 2005
BoutReal grad_ne = Ne[ip] - Ne[i];
BoutReal grad_ni = Ni[ip] - Ni[i];
// Note: Needed to get past initial conditions, perhaps transients
// but this shouldn't happen in steady state
// Note: Factor of 2 to be consistent with later calculation
if (fabs(grad_ni) < 2e-3) {
grad_ni = grad_ne = 2e-3; // Remove kinetic correction term
}
BoutReal C_i_sq = clip(
(adiabatic * ti + Zi * s_i * te * grad_ne / grad_ni)
/ Mi,
0, 100); // Limit for e.g. Ni zero gradient
// Note: Vzi = C_i * sin(α)
ion_sum[i] += s_i * Zi * sin_alpha * sqrt(C_i_sq);
}
}
}
if (upper_y) {
// Sum values, put results in mesh->yend
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ni, r.ind, mesh->yend, jz);
auto im = i.ym();
BoutReal s_i =
clip(0.5 * (3. * Ni[i] / Ne[i] - Ni[im] / Ne[im]), 0.0, 1.0);
if (!std::isfinite(s_i)) {
s_i = 1.0;
}
BoutReal te = Te[i];
BoutReal ti = Ti[i];
// Equation (9) in Tskhakaya 2005
BoutReal grad_ne = Ne[i] - Ne[im];
BoutReal grad_ni = Ni[i] - Ni[im];
if (fabs(grad_ni) < 2e-3) {
grad_ni = grad_ne = 2e-3; // Remove kinetic correction term
}
BoutReal C_i_sq = clip(
(adiabatic * ti + Zi * s_i * te * grad_ne / grad_ni)
/ Mi,
0, 100); // Limit for e.g. Ni zero gradient
ion_sum[i] += s_i * Zi * sin_alpha * sqrt(C_i_sq);
}
}
}
}
phi.allocate();
// ion_sum now contains sum s_i Z_i C_i over all ion species
// at mesh->ystart and mesh->yend indices
if (lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(phi, r.ind, mesh->ystart, jz);
if (Te[i] <= 0.0) {
phi[i] = 0.0;
} else {
phi[i] = Te[i] * log(sqrt(Te[i] / (Me * TWOPI)) * (1. - Ge) / ion_sum[i]);
}
const BoutReal phi_wall = wall_potential[i];
phi[i] += phi_wall; // Add bias potential
phi[i.yp()] = phi[i.ym()] = phi[i]; // Constant into sheath
}
}
}
if (upper_y) {
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(phi, r.ind, mesh->yend, jz);
if (Te[i] <= 0.0) {
phi[i] = 0.0;
} else {
phi[i] = Te[i] * log(sqrt(Te[i] / (Me * TWOPI)) * (1. - Ge) / ion_sum[i]);
}
const BoutReal phi_wall = wall_potential[i];
phi[i] += phi_wall; // Add bias potential
phi[i.yp()] = phi[i.ym()] = phi[i];
}
}
}
}
//////////////////////////////////////////////////////////////////
// Electrons
Field3D electron_energy_source = electrons.isSet("energy_source")
? toFieldAligned(getNonFinal<Field3D>(electrons["energy_source"]))
: zeroFrom(Ne);
if (lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->ystart, jz);
auto ip = i.yp();
auto im = i.ym();
// Free gradient of log electron density and temperature
// Limited so that the values don't increase into the sheath
// This ensures that the guard cell values remain positive
// exp( 2*log(N[i]) - log(N[ip]) )
Ne[im] = limitFree(Ne[ip], Ne[i]);
Te[im] = limitFree(Te[ip], Te[i]);
Pe[im] = limitFree(Pe[ip], Pe[i]);
// Free boundary potential linearly extrapolated
phi[im] = 2 * phi[i] - phi[ip];
const BoutReal nesheath = 0.5 * (Ne[im] + Ne[i]);
const BoutReal tesheath = 0.5 * (Te[im] + Te[i]); // electron temperature
const BoutReal phi_wall = wall_potential[i];
const BoutReal phisheath = floor_potential ? floor(
0.5 * (phi[im] + phi[i]), phi_wall) // Electron saturation at phi = phi_wall
: 0.5 * (phi[im] + phi[i]);
// Electron sheath heat transmission
const BoutReal gamma_e = floor(2 / (1. - Ge) + (phisheath - phi_wall) / floor(tesheath, 1e-5), 0.0);
// Electron velocity into sheath (< 0)
const BoutReal vesheath = (tesheath < 1e-10) ?
0.0 :
-sqrt(tesheath / (TWOPI * Me)) * (1. - Ge) * exp(-(phisheath - phi_wall) / tesheath);
Ve[im] = 2 * vesheath - Ve[i];
NVe[im] = 2. * Me * nesheath * vesheath - NVe[i];
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is negative because vesheath < 0
BoutReal q = ((gamma_e - 1 - 1 / (electron_adiabatic - 1)) * tesheath
- 0.5 * Me * SQ(vesheath))
* nesheath * vesheath;
if (q > 0.0) {
// Note: This could happen if tesheath > 2*phisheath
q = 0.0;
}
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[im])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[im]));
// Divide by volume of cell to get energy loss rate (< 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
#if CHECKLEVEL >= 1
if (!std::isfinite(power)) {
throw BoutException("Non-finite power at {} : Te {} Ne {} Ve {} phi {}, {}", i, tesheath, nesheath, vesheath, phi[i], phi[ip]);
}
#endif
electron_energy_source[i] += power;
}
}
}
if (upper_y) {
// This is essentially the same as at the lower y boundary
// except ystart -> yend, ip <-> im
//
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->yend, jz);
auto ip = i.yp();
auto im = i.ym();
// Free gradient of log electron density and temperature
// This ensures that the guard cell values remain positive
// exp( 2*log(N[i]) - log(N[ip]) )
Ne[ip] = limitFree(Ne[im], Ne[i]);
Te[ip] = limitFree(Te[im], Te[i]);
Pe[ip] = limitFree(Pe[im], Pe[i]);
// Free boundary potential linearly extrapolated
phi[ip] = 2 * phi[i] - phi[im];
const BoutReal nesheath = 0.5 * (Ne[ip] + Ne[i]);
const BoutReal tesheath = 0.5 * (Te[ip] + Te[i]); // electron temperature
const BoutReal phi_wall = wall_potential[i];
const BoutReal phisheath = floor_potential ? floor(0.5 * (phi[ip] + phi[i]), phi_wall) // Electron saturation at phi = phi_wall
: 0.5 * (phi[ip] + phi[i]);
// Electron sheath heat transmission
const BoutReal gamma_e = floor(2 / (1. - Ge) + (phisheath - phi_wall) / floor(tesheath, 1e-5), 0.0);
// Electron velocity into sheath (> 0)
const BoutReal vesheath = (tesheath < 1e-10) ?
0.0 :
sqrt(tesheath / (TWOPI * Me)) * (1. - Ge) * exp(-(phisheath - phi_wall) / tesheath);
Ve[ip] = 2 * vesheath - Ve[i];
NVe[ip] = 2. * Me * nesheath * vesheath - NVe[i];
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is positive because vesheath > 0
BoutReal q = ((gamma_e - 1 - 1 / (electron_adiabatic - 1)) * tesheath
- 0.5 * Me * SQ(vesheath))
* nesheath * vesheath;
if (q < 0.0) {
// Note: This could happen if tesheath > 2*phisheath
q = 0.0;
}
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[ip])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[ip]));
// Divide by volume of cell to get energy loss rate (> 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
#if CHECKLEVEL >= 1
if (!std::isfinite(power)) {
throw BoutException("Non-finite power {} at {} : Te {} Ne {} Ve {} phi {}, {} => q {}, flux {}",
power, i, tesheath, nesheath, vesheath, phi[i], phi[im], q, flux);
}
#endif
electron_energy_source[i] -= power;
}
}
}
// Set electron density and temperature, now with boundary conditions
// Note: Clear parallel slices because they do not contain correct boundary conditions
Ne.clearParallelSlices();
Te.clearParallelSlices();
Pe.clearParallelSlices();
setBoundary(electrons["density"], fromFieldAligned(Ne));
setBoundary(electrons["temperature"], fromFieldAligned(Te));
setBoundary(electrons["pressure"], fromFieldAligned(Pe));
// Add energy source (negative in cell next to sheath)
// Note: already includes previously set sources
set(electrons["energy_source"], fromFieldAligned(electron_energy_source));
if (IS_SET_NOBOUNDARY(electrons["velocity"])) {
Ve.clearParallelSlices();
setBoundary(electrons["velocity"], fromFieldAligned(Ve));
}
if (IS_SET_NOBOUNDARY(electrons["momentum"])) {
NVe.clearParallelSlices();
setBoundary(electrons["momentum"], fromFieldAligned(NVe));
}
if (always_set_phi or IS_SET_NOBOUNDARY(state["fields"]["phi"])) {
// Set the potential, including boundary conditions
phi.clearParallelSlices();
setBoundary(state["fields"]["phi"], fromFieldAligned(phi));
}
//////////////////////////////////////////////////////////////////
// Iterate through all ions
for (auto& kv : allspecies.getChildren()) {
if (kv.first == "e") {
continue; // Skip electrons
}
Options& species = allspecies[kv.first]; // Note: Need non-const
// Ion charge
const BoutReal Zi =
IS_SET(species["charge"]) ? get<BoutReal>(species["charge"]) : 0.0;
if (Zi == 0.0) {
continue; // Neutral -> skip
}
// Characteristics of this species
const BoutReal Mi = get<BoutReal>(species["AA"]);
const BoutReal adiabatic = IS_SET(species["adiabatic"])
? get<BoutReal>(species["adiabatic"])
: 5. / 3; // Ratio of specific heats (ideal gas)
// Density and temperature boundary conditions will be imposed (free)
Field3D Ni = toFieldAligned(floor(getNoBoundary<Field3D>(species["density"]), 0.0));
Field3D Ti = toFieldAligned(getNoBoundary<Field3D>(species["temperature"]));
Field3D Pi = species.isSet("pressure")
? toFieldAligned(getNoBoundary<Field3D>(species["pressure"]))
: Ni * Ti;
// Get the velocity and momentum
// These will be modified at the boundaries
// and then put back into the state
Field3D Vi = species.isSet("velocity")
? toFieldAligned(getNoBoundary<Field3D>(species["velocity"]))
: zeroFrom(Ni);
Field3D NVi = species.isSet("momentum")
? toFieldAligned(getNoBoundary<Field3D>(species["momentum"]))
: Mi * Ni * Vi;
// Energy source will be modified in the domain
Field3D energy_source = species.isSet("energy_source")
? toFieldAligned(getNonFinal<Field3D>(species["energy_source"]))
: zeroFrom(Ni);
if (lower_y) {
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->ystart, jz);
auto ip = i.yp();
auto im = i.ym();
// Free gradient of log electron density and temperature
// This ensures that the guard cell values remain positive
// exp( 2*log(N[i]) - log(N[ip]) )
Ni[im] = limitFree(Ni[ip], Ni[i]);
Ti[im] = limitFree(Ti[ip], Ti[i]);
Pi[im] = limitFree(Pi[ip], Pi[i]);
// Calculate sheath values at half-way points (cell edge)
const BoutReal nesheath = 0.5 * (Ne[im] + Ne[i]);
const BoutReal nisheath = 0.5 * (Ni[im] + Ni[i]);
const BoutReal tesheath = floor(0.5 * (Te[im] + Te[i]), 1e-5); // electron temperature
const BoutReal tisheath = floor(0.5 * (Ti[im] + Ti[i]), 1e-5); // ion temperature
// Ion sheath heat transmission coefficient
// Equation (22) in Tskhakaya 2005
// with
//
// 1 / (1 + ∂_{ln n_e} ln s_i = s_i ∂_z n_e / ∂_z n_i
// (from comparing C_i^2 in eq. 9 with eq. 20
//
//
BoutReal s_i = clip(nisheath / floor(nesheath, 1e-10), 0, 1); // Concentration
BoutReal grad_ne = Ne[i] - nesheath;
BoutReal grad_ni = Ni[i] - nisheath;
if (fabs(grad_ni) < 1e-3) {
grad_ni = grad_ne = 1e-3; // Remove kinetic correction term
}
// Ion speed into sheath
// Equation (9) in Tskhakaya 2005
//
BoutReal C_i_sq =
clip((adiabatic * tisheath + Zi * s_i * tesheath * grad_ne / grad_ni) / Mi,
0, 100); // Limit for e.g. Ni zero gradient
// Ion sheath heat transmission coefficient
const BoutReal gamma_i = 2.5 + 0.5 * Mi * C_i_sq / tisheath;
const BoutReal visheath = - sqrt(C_i_sq); // Negative -> into sheath
// Set boundary conditions on flows
Vi[im] = 2. * visheath - Vi[i];
NVi[im] = 2. * Mi * nisheath * visheath - NVi[i];
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is negative because visheath < 0
BoutReal q =
((gamma_i - 1 - 1 / (adiabatic - 1)) * tisheath - 0.5 * Mi * C_i_sq)
* nisheath * visheath;
if (q > 0.0) {
q = 0.0;
}
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[im])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[im]));
// Divide by volume of cell to get energy loss rate (< 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
ASSERT1(std::isfinite(power));
ASSERT2(power <= 0.0);
energy_source[i] += power;
}
}
}
if (upper_y) {
// Note: This is essentially the same as the lower boundary,
// but with directions reversed e.g. ystart -> yend, ip <-> im
//
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(Ne, r.ind, mesh->yend, jz);
auto ip = i.yp();
auto im = i.ym();
// Free gradient of log electron density and temperature
// This ensures that the guard cell values remain positive
// exp( 2*log(N[i]) - log(N[ip]) )
Ni[ip] = limitFree(Ni[im], Ni[i]);
Ti[ip] = limitFree(Ti[im], Ti[i]);
Pi[ip] = limitFree(Pi[im], Pi[i]);
// Calculate sheath values at half-way points (cell edge)
const BoutReal nesheath = 0.5 * (Ne[ip] + Ne[i]);
const BoutReal nisheath = 0.5 * (Ni[ip] + Ni[i]);
const BoutReal tesheath = floor(0.5 * (Te[ip] + Te[i]), 1e-5); // electron temperature
const BoutReal tisheath = floor(0.5 * (Ti[ip] + Ti[i]), 1e-5); // ion temperature
// Ion sheath heat transmission coefficient
//
// 1 / (1 + ∂_{ln n_e} ln s_i = s_i * ∂n_e / (s_i * ∂n_e + ∂ n_i)
BoutReal s_i = clip(nisheath / floor(nesheath, 1e-10), 0, 1); // Concentration
BoutReal grad_ne = Ne[i] - nesheath;
BoutReal grad_ni = Ni[i] - nisheath;
if (fabs(grad_ni) < 1e-3) {
grad_ni = grad_ne = 1e-3; // Remove kinetic correction term
}
// Ion speed into sheath
// Equation (9) in Tskhakaya 2005
//
BoutReal C_i_sq =
clip((adiabatic * tisheath + Zi * s_i * tesheath * grad_ne / grad_ni) / Mi,
0, 100); // Limit for e.g. Ni zero gradient
const BoutReal gamma_i = 2.5 + 0.5 * Mi * C_i_sq / tisheath; // + Δγ
const BoutReal visheath = sqrt(C_i_sq); // Positive -> into sheath
// Set boundary conditions on flows
Vi[ip] = 2. * visheath - Vi[i];
NVi[ip] = 2. * Mi * nisheath * visheath - NVi[i];
// Take into account the flow of energy due to fluid flow
// This is additional energy flux through the sheath
// Note: Here this is positive because visheath > 0
BoutReal q =
((gamma_i - 1 - 1 / (adiabatic - 1)) * tisheath - 0.5 * C_i_sq * Mi)
* nisheath * visheath;
if (q < 0.0) {
q = 0.0;
}
// Multiply by cell area to get power
BoutReal flux = q * (coord->J[i] + coord->J[ip])
/ (sqrt(coord->g_22[i]) + sqrt(coord->g_22[ip]));
// Divide by volume of cell to get energy loss rate (> 0)
BoutReal power = flux / (coord->dy[i] * coord->J[i]);
ASSERT1(std::isfinite(power));
ASSERT2(power >= 0.0);
energy_source[i] -= power; // Note: Sign negative because power > 0
}
}
}
// Finished boundary conditions for this species
// Put the modified fields back into the state.
Ni.clearParallelSlices();
Ti.clearParallelSlices();
Pi.clearParallelSlices();
setBoundary(species["density"], fromFieldAligned(Ni));
setBoundary(species["temperature"], fromFieldAligned(Ti));
setBoundary(species["pressure"], fromFieldAligned(Pi));
if (species.isSet("velocity")) {
Vi.clearParallelSlices();
setBoundary(species["velocity"], fromFieldAligned(Vi));
}
if (species.isSet("momentum")) {
NVi.clearParallelSlices();
setBoundary(species["momentum"], fromFieldAligned(NVi));
}
// Additional loss of energy through sheath
// Note: Already includes previously set sources
set(species["energy_source"], fromFieldAligned(energy_source));
}
}
| 25,285
|
C++
|
.cxx
| 554
| 36.787004
| 135
| 0.566968
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,239
|
relax_potential.cxx
|
bendudson_hermes-3/src/relax_potential.cxx
|
#include <bout/fv_ops.hxx>
#include <bout/solver.hxx>
using bout::globals::mesh;
#include "../include/div_ops.hxx"
#include "../include/relax_potential.hxx"
RelaxPotential::RelaxPotential(std::string name, Options& alloptions, Solver* solver) {
AUTO_TRACE();
auto* coord = mesh->getCoordinates();
auto& options = alloptions[name];
exb_advection = options["exb_advection"]
.doc("Include nonlinear ExB advection?")
.withDefault<bool>(true);
diamagnetic =
options["diamagnetic"].doc("Include diamagnetic current?").withDefault<bool>(true);
diamagnetic_polarisation =
options["diamagnetic_polarisation"]
.doc("Include diamagnetic drift in polarisation current?")
.withDefault<bool>(true);
boussinesq = options["boussinesq"]
.doc("Use the Boussinesq approximation?")
.withDefault<bool>(true);
average_atomic_mass = options["average_atomic_mass"]
.doc("Weighted average atomic mass, for polarisaion current "
"(Boussinesq approximation)")
.withDefault<BoutReal>(2.0); // Deuterium
poloidal_flows =
options["poloidal_flows"].doc("Include poloidal ExB flow").withDefault<bool>(true);
lambda_1 = options["lambda_1"].doc("λ_1 > λ_2 > 1").withDefault(1.0);
lambda_2 = options["lambda_2"].doc("λ_2 > 1").withDefault(10.0);
solver->add(Vort, "Vort"); // Vorticity evolving
solver->add(phi1, "phi1"); // Evolving scaled potential ϕ_1 = λ_2 ϕ
if (diamagnetic) {
// Read curvature vector
try {
Curlb_B.covariant = false; // Contravariant
mesh->get(Curlb_B, "bxcv");
} catch (BoutException& e) {
// May be 2D, reading as 3D
Vector2D curv2d;
curv2d.covariant = false;
mesh->get(curv2d, "bxcv");
Curlb_B = curv2d;
}
if (Options::root()["mesh"]["paralleltransform"]["type"].as<std::string>()
== "shifted") {
Field2D I;
mesh->get(I, "sinty");
Curlb_B.z += I * Curlb_B.x;
}
Options& units = alloptions["units"];
BoutReal Bnorm = units["Tesla"];
BoutReal Lnorm = units["meters"];
Curlb_B.x /= Bnorm;
Curlb_B.y *= SQ(Lnorm);
Curlb_B.z *= SQ(Lnorm);
Curlb_B *= 2. / coord->Bxy;
}
Bsq = SQ(coord->Bxy);
}
void RelaxPotential::transform(Options& state) {
AUTO_TRACE();
// Scale potential
phi = phi1 / lambda_2;
phi.applyBoundary("neumann");
Vort.applyBoundary("neumann");
auto& fields = state["fields"];
ddt(Vort) = 0.0;
if (diamagnetic) {
// Diamagnetic current. This is calculated here so that the energy sources/sinks
// can be calculated for the evolving species.
Vector3D Jdia;
Jdia.x = 0.0;
Jdia.y = 0.0;
Jdia.z = 0.0;
Jdia.covariant = Curlb_B.covariant;
Options& allspecies = state["species"];
// Pre-calculate this rather than calculate for each species
Vector3D Grad_phi = Grad(phi);
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first]; // Note: need non-const
if (!(IS_SET_NOBOUNDARY(species["pressure"]) and IS_SET(species["charge"])
and (get<BoutReal>(species["charge"]) != 0.0))) {
continue; // No pressure or charge -> no diamagnetic current
}
// Note that the species must have a charge, but charge is not used,
// because it cancels out in the expression for current
auto P = GET_NOBOUNDARY(Field3D, species["pressure"]);
Vector3D Jdia_species = P * Curlb_B; // Diamagnetic current for this species
// This term energetically balances diamagnetic term
// in the vorticity equation
subtract(species["energy_source"], Jdia_species * Grad_phi);
Jdia += Jdia_species; // Collect total diamagnetic current
}
// Note: This term is central differencing so that it balances
// the corresponding compression term in the species pressure equations
Field3D DivJdia = Div(Jdia);
ddt(Vort) += DivJdia;
if (diamagnetic_polarisation) {
// Calculate energy exchange term nonlinear in pressure
// ddt(Pi) += Pi * Div((Pe + Pi) * Curlb_B);
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first]; // Note: need non-const
if (!(IS_SET_NOBOUNDARY(species["pressure"]) and IS_SET(species["charge"])
and IS_SET(species["AA"]))) {
continue; // No pressure, charge or mass -> no polarisation current due to
// rate of change of diamagnetic flow
}
auto P = GET_NOBOUNDARY(Field3D, species["pressure"]);
add(species["energy_source"], (3. / 2) * P * DivJdia);
}
}
set(fields["DivJdia"], DivJdia);
}
set(fields["vorticity"], Vort);
set(fields["phi"], phi);
}
void RelaxPotential::finally(const Options& state) {
AUTO_TRACE();
const Options& allspecies = state["species"];
phi = get<Field3D>(state["fields"]["phi"]);
Vort = get<Field3D>(state["fields"]["vorticity"]);
if (exb_advection) {
ddt(Vort) -= Div_n_bxGrad_f_B_XPPM(Vort, phi, bndry_flux, poloidal_flows);
}
if (state.isSection("fields") and state["fields"].isSet("DivJextra")) {
auto DivJextra = get<Field3D>(state["fields"]["DivJextra"]);
// Parallel current is handled here, to allow different 2D or 3D closures
// to be used
ddt(Vort) += DivJextra;
}
// Parallel current due to species parallel flow
for (auto& kv : allspecies.getChildren()) {
const Options& species = kv.second;
if (!species.isSet("charge") or !species.isSet("momentum")) {
continue; // Not charged, or no parallel flow
}
const BoutReal Z = get<BoutReal>(species["charge"]);
if (fabs(Z) < 1e-5) {
continue; // Not charged
}
const Field3D N = get<Field3D>(species["density"]);
const Field3D NV = get<Field3D>(species["momentum"]);
const BoutReal A = get<BoutReal>(species["AA"]);
// Note: Using NV rather than N*V so that the cell boundary flux is correct
ddt(Vort) += Div_par((Z / A) * NV);
}
// Solve diffusion equation for potential
if (boussinesq) {
ddt(phi1) =
lambda_1 * (FV::Div_a_Grad_perp(average_atomic_mass / Bsq, phi) - Vort);
if (diamagnetic_polarisation) {
for (auto& kv : allspecies.getChildren()) {
// Note: includes electrons (should it?)
const Options& species = kv.second;
if (!species.isSet("charge")) {
continue; // Not charged
}
const BoutReal Z = get<BoutReal>(species["charge"]);
if (fabs(Z) < 1e-5) {
continue; // Not charged
}
if (!species.isSet("pressure")) {
continue; // No pressure
}
const BoutReal A = get<BoutReal>(species["AA"]);
const Field3D P = get<Field3D>(species["pressure"]);
ddt(phi1) += lambda_1 * FV::Div_a_Grad_perp(A / Bsq, P);
}
}
} else {
// Non-Boussinesq. Calculate mass density by summing over species
// Calculate vorticity from potential phi
Field3D phi_vort = 0.0;
for (auto& kv : allspecies.getChildren()) {
const Options& species = kv.second;
if (!species.isSet("charge")) {
continue; // Not charged
}
const BoutReal Zi = get<BoutReal>(species["charge"]);
if (fabs(Zi) < 1e-5) {
continue; // Not charged
}
const BoutReal Ai = get<BoutReal>(species["AA"]);
const Field3D Ni = get<Field3D>(species["density"]);
phi_vort += FV::Div_a_Grad_perp((Ai / Bsq) * Ni, phi);
if (diamagnetic_polarisation and species.isSet("pressure")) {
// Calculate the diamagnetic flow contribution
const Field3D Pi = get<Field3D>(species["pressure"]);
phi_vort += FV::Div_a_Grad_perp(Ai / Bsq, Pi);
}
}
ddt(phi1) = lambda_1 * (phi_vort - Vort);
}
}
void RelaxPotential::outputVars(Options& state) {
AUTO_TRACE();
// Normalisations
auto Tnorm = state["Tnorm"].as<BoutReal>();
set_with_attrs(state["phi"], phi,
{{"time_dimension", "t"},
{"units", "V"},
{"conversion", Tnorm},
{"standard_name", "potential"},
{"long_name", "plasma potential"},
{"source", "relax_potential"}});
}
| 8,385
|
C++
|
.cxx
| 206
| 33.73301
| 89
| 0.618543
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,240
|
temperature_feedback.cxx
|
bendudson_hermes-3/src/temperature_feedback.cxx
|
#include "../include/temperature_feedback.hxx"
#include <bout/mesh.hxx>
using bout::globals::mesh;
void TemperatureFeedback::transform(Options& state) {
Options& species = state["species"][name];
// Doesn't need all boundaries to be set
Field3D T = getNoBoundary<Field3D>(species["temperature"]);
auto time = get<BoutReal>(state["time"]);
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
int jz = 0;
if (control_target_temperature) {
error = temperature_setpoint - T(r.ind, mesh->yend, jz);
} else {
error = temperature_setpoint - T(r.ind, mesh->ystart, jz);
}
// PI controller, using crude integral of the error
if (temperature_error_lasttime < 0.0) {
// First time this has run
temperature_error_lasttime = time;
temperature_error_last = error;
}
// Integrate using Trapezium rule
if (time > temperature_error_lasttime) { // Since time can decrease
temperature_error_integral += (time - temperature_error_lasttime) * 0.5 *
(error + temperature_error_last);
}
if ((temperature_error_integral < 0.0) && temperature_integral_positive) {
// Limit temperature_error_integral to be >= 0
temperature_error_integral = 0.0;
}
// Calculate source from combination of error and integral
integral_term = temperature_controller_i * temperature_error_integral;
proportional_term = temperature_controller_p * error;
source_multiplier = proportional_term + integral_term;
if ((source_multiplier < 0.0) && temperature_source_positive) {
source_multiplier = 0.0; // Don't remove particles
}
temperature_error_last = error;
temperature_error_lasttime = time;
break;
}
// The upstream temperature is only present in processor 0, so for other
// processors the above loop is skipped. Need to broadcast the values from
// processor 0 to the other processors
if (control_target_temperature) {
MPI_Bcast(&source_multiplier, 1, MPI_DOUBLE, BoutComm::size()-1, BoutComm::get());
MPI_Bcast(&proportional_term, 1, MPI_DOUBLE, BoutComm::size()-1, BoutComm::get());
MPI_Bcast(&integral_term, 1, MPI_DOUBLE, BoutComm::size()-1, BoutComm::get());
} else {
MPI_Bcast(&source_multiplier, 1, MPI_DOUBLE, 0, BoutComm::get());
MPI_Bcast(&proportional_term, 1, MPI_DOUBLE, 0, BoutComm::get());
MPI_Bcast(&integral_term, 1, MPI_DOUBLE, 0, BoutComm::get());
}
ASSERT2(std::isfinite(source_multiplier));
// std::list<std::string>::iterator species_it = species_list.begin();
// std::list<std::string>::iterator scaling_factor_it = scaling_factors_list.begin();
// while (species_it != species_list.end() && scaling_factor_it != scaling_factors_list.end()) {
// std::string sourced_species = trim(*species_it, " \t\r()"); // The species name in the list
// BoutReal scaling_factor = stringToReal(trim(*scaling_factor_it, " \t\r()"));
// if (sourced_species.empty())
// continue; // Missing
// add(state["species"][sourced_species]["energy_source"], scaling_factor * source_multiplier * source_shape);
// ++species_it;
// ++scaling_factor_it;
// }
auto species_it = species_list.begin();
auto scaling_factor_it = scaling_factors_list.begin();
while (species_it != species_list.end() && scaling_factor_it != scaling_factors_list.end()) {
std::string trimmed_species = trim(*species_it);
std::string trimmed_scaling_factor = trim(*scaling_factor_it);
if (trimmed_species.empty() || trimmed_scaling_factor.empty()) {
++species_it;
++scaling_factor_it;
continue; // Skip this iteration if either trimmed string is empty
}
BoutReal scaling_factor = stringToReal(trimmed_scaling_factor);
add(state["species"][trimmed_species]["energy_source"], scaling_factor * source_multiplier * source_shape);
++species_it;
++scaling_factor_it;
}
// Scale the source and add to the species temperature source
// add(species["energy_source"], source_multiplier * source_shape);
// add(state["species"]["d+"]["energy_source"], source_multiplier * source_shape);
}
| 4,195
|
C++
|
.cxx
| 84
| 44.880952
| 116
| 0.675735
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,241
|
vorticity.cxx
|
bendudson_hermes-3/src/vorticity.cxx
|
#include "../include/vorticity.hxx"
#include "../include/div_ops.hxx"
#include <bout/constants.hxx>
#include <bout/fv_ops.hxx>
#include <bout/invert/laplacexy.hxx>
#include <bout/derivs.hxx>
#include <bout/difops.hxx>
#include <bout/invert_laplace.hxx>
using bout::globals::mesh;
namespace {
BoutReal floor(BoutReal value, BoutReal min) {
if (value < min)
return min;
return value;
}
Ind3D indexAt(const Field3D& f, int x, int y, int z) {
int ny = f.getNy();
int nz = f.getNz();
return Ind3D{(x * ny + y) * nz + z, ny, nz};
}
/// Limited free gradient of log of a quantity
/// This ensures that the guard cell values remain positive
/// while also ensuring that the quantity never increases
///
/// fm fc | fp
/// ^ boundary
///
/// exp( 2*log(fc) - log(fm) )
///
BoutReal limitFree(BoutReal fm, BoutReal fc) {
if (fm < fc) {
return fc; // Neumann rather than increasing into boundary
}
if (fm < 1e-10) {
return fc; // Low / no density condition
}
BoutReal fp = SQ(fc) / fm;
#if CHECKLEVEL >= 2
if (!std::isfinite(fp)) {
throw BoutException("SheathBoundary limitFree: {}, {} -> {}", fm, fc, fp);
}
#endif
return fp;
}
}
Vorticity::Vorticity(std::string name, Options& alloptions, Solver* solver) {
AUTO_TRACE();
solver->add(Vort, "Vort");
auto& options = alloptions[name];
// Normalisations
const Options& units = alloptions["units"];
const BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>();
const BoutReal Bnorm = units["Tesla"];
const BoutReal Lnorm = units["meters"];
exb_advection = options["exb_advection"]
.doc("Include ExB advection (nonlinear term)?")
.withDefault<bool>(true);
exb_advection_simplified = options["exb_advection_simplified"]
.doc("Simplify nonlinear ExB advection form?")
.withDefault<bool>(true);
diamagnetic =
options["diamagnetic"].doc("Include diamagnetic current?").withDefault<bool>(true);
sheath_boundary = options["sheath_boundary"]
.doc("Set potential to j=0 sheath at radial boundaries? (default = 0)")
.withDefault<bool>(false);
diamagnetic_polarisation =
options["diamagnetic_polarisation"]
.doc("Include diamagnetic drift in polarisation current?")
.withDefault<bool>(true);
collisional_friction =
options["collisional_friction"]
.doc("Damp vorticity based on mass-weighted collision frequency")
.withDefault<bool>(false);
average_atomic_mass = options["average_atomic_mass"]
.doc("Weighted average atomic mass, for polarisation current "
"(Boussinesq approximation)")
.withDefault<BoutReal>(2.0); // Deuterium
bndry_flux = options["bndry_flux"]
.doc("Allow flows through radial boundaries")
.withDefault<bool>(true);
poloidal_flows =
options["poloidal_flows"].doc("Include poloidal ExB flow").withDefault<bool>(true);
split_n0 = options["split_n0"]
.doc("Split phi into n=0 and n!=0 components")
.withDefault<bool>(false);
viscosity = options["viscosity"]
.doc("Kinematic viscosity [m^2/s]")
.withDefault<BoutReal>(0.0)
/ (Lnorm * Lnorm * Omega_ci);
viscosity.applyBoundary("dirichlet");
hyper_z = options["hyper_z"].doc("Hyper-viscosity in Z. < 0 -> off").withDefault(-1.0);
// Numerical dissipation terms
// These are required to suppress parallel zig-zags in
// cell centred formulations. Essentially adds (hopefully small)
// parallel currents
vort_dissipation = options["vort_dissipation"]
.doc("Parallel dissipation of vorticity")
.withDefault<bool>(false);
phi_dissipation = options["phi_dissipation"]
.doc("Parallel dissipation of potential [Recommended]")
.withDefault<bool>(true);
phi_boundary_relax = options["phi_boundary_relax"]
.doc("Relax x boundaries of phi towards Neumann?")
.withDefault<bool>(false);
phi_sheath_dissipation = options["phi_sheath_dissipation"]
.doc("Add dissipation when phi < 0.0 at the sheath")
.withDefault<bool>(false);
damp_core_vorticity = options["damp_core_vorticity"]
.doc("Damp vorticity at the core boundary?")
.withDefault<bool>(false);
// Add phi to restart files so that the value in the boundaries
// is restored on restart. This is done even when phi is not evolving,
// so that phi can be saved and re-loaded
// Set initial value. Will be overwritten if restarting
phi = 0.0;
auto coord = mesh->getCoordinates();
if (split_n0) {
// Create an XY solver for n=0 component
laplacexy = new LaplaceXY(mesh);
// Set coefficients for Boussinesq solve
laplacexy->setCoefs(average_atomic_mass / SQ(coord->Bxy), 0.0);
}
phiSolver = Laplacian::create(&options["laplacian"]);
// Set coefficients for Boussinesq solve
phiSolver->setCoefC(average_atomic_mass / SQ(coord->Bxy));
if (phi_boundary_relax) {
// Set the last update time to -1, so it will reset
// the first time RHS function is called
phi_boundary_last_update = -1.;
phi_core_averagey = options["phi_core_averagey"]
.doc("Average phi core boundary in Y?")
.withDefault<bool>(false) and mesh->periodicY(mesh->xstart);
phi_boundary_timescale = options["phi_boundary_timescale"]
.doc("Timescale for phi boundary relaxation [seconds]")
.withDefault(1e-4)
/ get<BoutReal>(alloptions["units"]["seconds"]);
// Normalise to internal time units
phiSolver->setInnerBoundaryFlags(INVERT_SET);
phiSolver->setOuterBoundaryFlags(INVERT_SET);
}
// Read curvature vector
try {
Curlb_B.covariant = false; // Contravariant
mesh->get(Curlb_B, "bxcv");
} catch (BoutException& e) {
try {
// May be 2D, reading as 3D
Vector2D curv2d;
curv2d.covariant = false;
mesh->get(curv2d, "bxcv");
Curlb_B = curv2d;
} catch (BoutException& e) {
if (diamagnetic) {
// Need curvature
throw;
} else {
output_warn.write("No curvature vector in input grid");
Curlb_B = 0.0;
}
}
}
if (Options::root()["mesh"]["paralleltransform"]["type"].as<std::string>()
== "shifted") {
Field2D I;
mesh->get(I, "sinty");
Curlb_B.z += I * Curlb_B.x;
}
Curlb_B.x /= Bnorm;
Curlb_B.y *= SQ(Lnorm);
Curlb_B.z *= SQ(Lnorm);
Curlb_B *= 2. / coord->Bxy;
Bsq = SQ(coord->Bxy);
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
}
void Vorticity::transform(Options& state) {
AUTO_TRACE();
phi.name = "phi";
auto& fields = state["fields"];
// Set the boundary of phi. Both 2D and 3D fields are kept, though the 3D field
// is constant in Z. This is for efficiency, to reduce the number of conversions.
// Note: For now the boundary values are all at the midpoint,
// and only phi is considered, not phi + Pi which is handled in Boussinesq solves
Pi_hat = 0.0; // Contribution from ion pressure, weighted by atomic mass / charge
if (diamagnetic_polarisation) {
// Diamagnetic term in vorticity. Note this is weighted by the mass
// This includes all species, including electrons
Options& allspecies = state["species"];
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first]; // Note: need non-const
if (!(IS_SET_NOBOUNDARY(species["pressure"]) and species.isSet("charge")
and species.isSet("AA"))) {
continue; // No pressure, charge or mass -> no polarisation current
}
const auto charge = get<BoutReal>(species["charge"]);
if (fabs(charge) < 1e-5) {
// No charge
continue;
}
// Don't need sheath boundary
const auto P = GET_NOBOUNDARY(Field3D, species["pressure"]);
const auto AA = get<BoutReal>(species["AA"]);
Pi_hat += P * (AA / average_atomic_mass / charge);
}
}
Pi_hat.applyBoundary("neumann");
if (phi_boundary_relax) {
// Update the boundary regions by relaxing towards zero gradient
// on a given timescale.
BoutReal time = get<BoutReal>(state["time"]);
if (phi_boundary_last_update < 0.0) {
// First time this has been called.
phi_boundary_last_update = time;
} else if (time > phi_boundary_last_update) {
// Only update if time has advanced
// Uses an exponential decay of the weighting of the value in the boundary
// so that the solution is well behaved for arbitrary steps
BoutReal weight = exp(-(time - phi_boundary_last_update) / phi_boundary_timescale);
phi_boundary_last_update = time;
if (mesh->firstX()) {
BoutReal phivalue = 0.0;
if (phi_core_averagey) {
BoutReal philocal = 0.0;
for (int j = mesh->ystart; j <= mesh->yend; j++) {
for (int k = 0; k < mesh->LocalNz; k++) {
philocal += phi(mesh->xstart, j, k);
}
}
MPI_Comm comm_inner = mesh->getYcomm(0);
int np;
MPI_Comm_size(comm_inner, &np);
MPI_Allreduce(&philocal,
&phivalue,
1, MPI_DOUBLE,
MPI_SUM, comm_inner);
phivalue /= (np * mesh->LocalNz * mesh->LocalNy);
}
for (int j = mesh->ystart; j <= mesh->yend; j++) {
if (!phi_core_averagey) {
phivalue = 0.0; // Calculate phi boundary for each Y index separately
for (int k = 0; k < mesh->LocalNz; k++) {
phivalue += phi(mesh->xstart, j, k);
}
phivalue /= mesh->LocalNz; // Average in Z of point next to boundary
}
// Old value of phi at boundary
BoutReal oldvalue =
0.5 * (phi(mesh->xstart - 1, j, 0) + phi(mesh->xstart, j, 0));
// New value of phi at boundary, relaxing towards phivalue
BoutReal newvalue = weight * oldvalue + (1. - weight) * phivalue;
// Set phi at the boundary to this value
for (int k = 0; k < mesh->LocalNz; k++) {
phi(mesh->xstart - 1, j, k) = 2. * newvalue - phi(mesh->xstart, j, k);
// Note: This seems to make a difference, but don't know why.
// Without this, get convergence failures with no apparent instability
// (all fields apparently smooth, well behaved)
phi(mesh->xstart - 2, j, k) = phi(mesh->xstart - 1, j, k);
}
}
}
if (mesh->lastX()) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
BoutReal phivalue = 0.0;
for (int k = 0; k < mesh->LocalNz; k++) {
phivalue += phi(mesh->xend, j, k);
}
phivalue /= mesh->LocalNz; // Average in Z of point next to boundary
// Old value of phi at boundary
BoutReal oldvalue = 0.5 * (phi(mesh->xend + 1, j, 0) + phi(mesh->xend, j, 0));
// New value of phi at boundary, relaxing towards phivalue
BoutReal newvalue = weight * oldvalue + (1. - weight) * phivalue;
// Set phi at the boundary to this value
for (int k = 0; k < mesh->LocalNz; k++) {
phi(mesh->xend + 1, j, k) = 2. * newvalue - phi(mesh->xend, j, k);
// Note: This seems to make a difference, but don't know why.
// Without this, get convergence failures with no apparent instability
// (all fields apparently smooth, well behaved)
phi(mesh->xend + 2, j, k) = phi(mesh->xend + 1, j, k);
}
}
}
}
} else {
// phi_boundary_relax = false
//
// Set boundary from temperature, to be consistent with j=0 at sheath
// Sheath multiplier Te -> phi (2.84522 for Deuterium)
BoutReal sheathmult = 0.0;
if (sheath_boundary) {
BoutReal Me_Mp = get<BoutReal>(state["species"]["e"]["AA"]);
sheathmult = log(0.5 * sqrt(1. / (Me_Mp * PI)));
}
Field3D Te; // Electron temperature, use for outer boundary conditions
if (state["species"]["e"].isSet("temperature")) {
// Electron temperature set
Te = GET_NOBOUNDARY(Field3D, state["species"]["e"]["temperature"]);
} else {
Te = 0.0;
}
// Sheath multiplier Te -> phi (2.84522 for Deuterium if Ti = 0)
if (mesh->firstX()) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
BoutReal teavg = 0.0; // Average Te in Z
for (int k = 0; k < mesh->LocalNz; k++) {
teavg += Te(mesh->xstart, j, k);
}
teavg /= mesh->LocalNz;
BoutReal phivalue = sheathmult * teavg;
// Set midpoint (boundary) value
for (int k = 0; k < mesh->LocalNz; k++) {
phi(mesh->xstart - 1, j, k) = 2. * phivalue - phi(mesh->xstart, j, k);
// Note: This seems to make a difference, but don't know why.
// Without this, get convergence failures with no apparent instability
// (all fields apparently smooth, well behaved)
phi(mesh->xstart - 2, j, k) = phi(mesh->xstart - 1, j, k);
}
}
}
if (mesh->lastX()) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
BoutReal teavg = 0.0; // Average Te in Z
for (int k = 0; k < mesh->LocalNz; k++) {
teavg += Te(mesh->xend, j, k);
}
teavg /= mesh->LocalNz;
BoutReal phivalue = sheathmult * teavg;
// Set midpoint (boundary) value
for (int k = 0; k < mesh->LocalNz; k++) {
phi(mesh->xend + 1, j, k) = 2. * phivalue - phi(mesh->xend, j, k);
// Note: This seems to make a difference, but don't know why.
// Without this, get convergence failures with no apparent instability
// (all fields apparently smooth, well behaved)
phi(mesh->xend + 2, j, k) = phi(mesh->xend + 1, j, k);
}
}
}
}
// Update boundary conditions. Two issues:
// 1) Solving here for phi + Pi, and then subtracting Pi from the result
// The boundary values should therefore include Pi
// 2) The INVERT_SET flag takes the value in the guard (boundary) cell
// and sets the boundary between cells to this value.
// This shift by 1/2 grid cell is important.
Field3D phi_plus_pi = phi + Pi_hat;
if (mesh->firstX()) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
for (int k = 0; k < mesh->LocalNz; k++) {
// Average phi + Pi at the boundary, and set the boundary cell
// to this value. The phi solver will then put the value back
// onto the cell mid-point
phi_plus_pi(mesh->xstart - 1, j, k) =
0.5 * (phi_plus_pi(mesh->xstart - 1, j, k) + phi_plus_pi(mesh->xstart, j, k));
}
}
}
if (mesh->lastX()) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
for (int k = 0; k < mesh->LocalNz; k++) {
phi_plus_pi(mesh->xend + 1, j, k) =
0.5 * (phi_plus_pi(mesh->xend + 1, j, k) + phi_plus_pi(mesh->xend, j, k));
}
}
}
// Calculate potential
if (split_n0) {
////////////////////////////////////////////
// Split into axisymmetric and non-axisymmetric components
Field2D Vort2D = DC(Vort); // n=0 component
Field2D phi_plus_pi_2d = DC(phi_plus_pi);
phi_plus_pi -= phi_plus_pi_2d;
phi_plus_pi_2d = laplacexy->solve(Vort2D, phi_plus_pi_2d);
// Solve non-axisymmetric part using X-Z solver
phi = phi_plus_pi_2d
+ phiSolver->solve((Vort - Vort2D) * (Bsq / average_atomic_mass), phi_plus_pi)
- Pi_hat;
} else {
phi = phiSolver->solve(Vort * (Bsq / average_atomic_mass), phi_plus_pi) - Pi_hat;
}
// Ensure that potential is set in the communication guard cells
mesh->communicate(phi);
// Outer boundary cells
if (mesh->firstX()) {
for (int i = mesh->xstart - 2; i >= 0; --i) {
for (int j = mesh->ystart; j <= mesh->yend; ++j) {
for (int k = 0; k < mesh->LocalNz; ++k) {
phi(i, j, k) = phi(i + 1, j, k);
}
}
}
}
if (mesh->lastX()) {
for (int i = mesh->xend + 2; i < mesh->LocalNx; ++i) {
for (int j = mesh->ystart; j <= mesh->yend; ++j) {
for (int k = 0; k < mesh->LocalNz; ++k) {
phi(i, j, k) = phi(i - 1, j, k);
}
}
}
}
ddt(Vort) = 0.0;
if (diamagnetic) {
// Diamagnetic current. This is calculated here so that the energy sources/sinks
// can be calculated for the evolving species.
Vector3D Jdia;
Jdia.x = 0.0;
Jdia.y = 0.0;
Jdia.z = 0.0;
Jdia.covariant = Curlb_B.covariant;
Options& allspecies = state["species"];
for (auto& kv : allspecies.getChildren()) {
Options& species = allspecies[kv.first]; // Note: need non-const
if (!(IS_SET_NOBOUNDARY(species["pressure"]) and IS_SET(species["charge"]))) {
continue; // No pressure or charge -> no diamagnetic current
}
if (fabs(get<BoutReal>(species["charge"])) < 1e-5) {
// No charge
continue;
}
// Note that the species must have a charge, but charge is not used,
// because it cancels out in the expression for current
auto P = GET_NOBOUNDARY(Field3D, species["pressure"]);
// Note: We need boundary conditions on P, so apply the same
// free boundary condition as sheath_boundary.
if (P.hasParallelSlices()) {
Field3D &P_ydown = P.ydown();
Field3D &P_yup = P.yup();
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
P_ydown(r.ind, mesh->ystart - 1, jz) = 2 * P(r.ind, mesh->ystart, jz) - P_yup(r.ind, mesh->ystart + 1, jz);
}
}
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
P_yup(r.ind, mesh->yend + 1, jz) = 2 * P(r.ind, mesh->yend, jz) - P_ydown(r.ind, mesh->yend - 1, jz);
}
}
} else {
Field3D P_fa = toFieldAligned(P);
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(P_fa, r.ind, mesh->ystart, jz);
P_fa[i.ym()] = limitFree(P_fa[i.yp()], P_fa[i]);
}
}
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(P_fa, r.ind, mesh->yend, jz);
P_fa[i.yp()] = limitFree(P_fa[i.ym()], P_fa[i]);
}
}
P = fromFieldAligned(P_fa);
}
// Note: This calculation requires phi derivatives at the Y boundaries
// Setting to free boundaries
if (phi.hasParallelSlices()) {
Field3D &phi_ydown = phi.ydown();
Field3D &phi_yup = phi.yup();
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
phi_ydown(r.ind, mesh->ystart - 1, jz) = 2 * phi(r.ind, mesh->ystart, jz) - phi_yup(r.ind, mesh->ystart + 1, jz);
}
}
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
phi_yup(r.ind, mesh->yend + 1, jz) = 2 * phi(r.ind, mesh->yend, jz) - phi_ydown(r.ind, mesh->yend - 1, jz);
}
}
} else {
Field3D phi_fa = toFieldAligned(phi);
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
phi_fa(r.ind, mesh->ystart - 1, jz) = 2 * phi_fa(r.ind, mesh->ystart, jz) - phi_fa(r.ind, mesh->ystart + 1, jz);
}
}
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
phi_fa(r.ind, mesh->yend + 1, jz) = 2 * phi_fa(r.ind, mesh->yend, jz) - phi_fa(r.ind, mesh->yend - 1, jz);
}
}
phi = fromFieldAligned(phi_fa);
}
Vector3D Jdia_species = P * Curlb_B; // Diamagnetic current for this species
// This term energetically balances diamagnetic term
// in the vorticity equation
subtract(species["energy_source"], Jdia_species * Grad(phi));
Jdia += Jdia_species; // Collect total diamagnetic current
}
// Note: This term is central differencing so that it balances
// the corresponding compression term in the species pressure equations
DivJdia = Div(Jdia);
ddt(Vort) += DivJdia;
set(fields["DivJdia"], DivJdia);
}
if (collisional_friction) {
// Damping of vorticity due to collisions
// Calculate a mass-weighted collision frequency
Field3D sum_A_nu_n =
zeroFrom(Vort); // Sum of atomic mass * collision frequency * density
Field3D sum_A_n = zeroFrom(Vort); // Sum of atomic mass * density
const Options& allspecies = state["species"];
for (const auto& kv : allspecies.getChildren()) {
const Options& species = kv.second;
if (!(species.isSet("charge") and species.isSet("AA"))) {
continue; // No charge or mass -> no current
}
if (fabs(get<BoutReal>(species["charge"])) < 1e-5) {
continue; // Zero charge
}
const BoutReal A = get<BoutReal>(species["AA"]);
const Field3D N = GET_NOBOUNDARY(Field3D, species["density"]);
const Field3D AN = A * N;
sum_A_n += AN;
if (IS_SET(species["collision_frequency"])) {
sum_A_nu_n += AN * GET_VALUE(Field3D, species["collision_frequency"]);
}
}
Field3D weighted_collision_frequency = sum_A_nu_n / sum_A_n;
weighted_collision_frequency.applyBoundary("neumann");
DivJcol = -FV::Div_a_Grad_perp(
weighted_collision_frequency * average_atomic_mass / Bsq, phi + Pi_hat);
ddt(Vort) += DivJcol;
set(fields["DivJcol"], DivJcol);
}
set(fields["vorticity"], Vort);
set(fields["phi"], phi);
}
void Vorticity::finally(const Options& state) {
AUTO_TRACE();
phi = get<Field3D>(state["fields"]["phi"]);
if (exb_advection) {
// These terms come from divergence of polarisation current
if (exb_advection_simplified) {
// By default this is a simplified nonlinear term
ddt(Vort) -= Div_n_bxGrad_f_B_XPPM(Vort, phi, bndry_flux, poloidal_flows);
} else {
// If diamagnetic_polarisation = false and B is constant, then
// this term reduces to the simplified form above.
//
// Because this is implemented in terms of an operation on the result
// of an operation, we need to communicate and the resulting stencil is
// wider than the simple form.
ddt(Vort) -=
Div_n_bxGrad_f_B_XPPM(0.5 * Vort, phi, bndry_flux, poloidal_flows);
// V_ExB dot Grad(Pi)
Field3D vEdotGradPi = bracket(phi, Pi_hat, BRACKET_ARAKAWA);
vEdotGradPi.applyBoundary("free_o2");
// delp2(phi) term
Field3D DelpPhi_2B2 = 0.5 * average_atomic_mass * Delp2(phi) / Bsq;
DelpPhi_2B2.applyBoundary("free_o2");
mesh->communicate(vEdotGradPi, DelpPhi_2B2);
ddt(Vort) -= FV::Div_a_Grad_perp(0.5 * average_atomic_mass / Bsq, vEdotGradPi);
ddt(Vort) -= Div_n_bxGrad_f_B_XPPM(DelpPhi_2B2, phi + Pi_hat, bndry_flux,
poloidal_flows);
}
}
if (state.isSection("fields") and state["fields"].isSet("DivJextra")) {
auto DivJextra = get<Field3D>(state["fields"]["DivJextra"]);
// Parallel current is handled here, to allow different 2D or 3D closures
// to be used
ddt(Vort) += DivJextra;
}
// Parallel current due to species parallel flow
for (auto& kv : state["species"].getChildren()) {
const Options& species = kv.second;
if (!species.isSet("charge") or !species.isSet("momentum")) {
continue; // Not charged, or no parallel flow
}
const BoutReal Z = get<BoutReal>(species["charge"]);
if (fabs(Z) < 1e-5) {
continue; // Not charged
}
const Field3D N = get<Field3D>(species["density"]);
const Field3D NV = get<Field3D>(species["momentum"]);
const BoutReal A = get<BoutReal>(species["AA"]);
// Note: Using NV rather than N*V so that the cell boundary flux is correct
ddt(Vort) += Div_par((Z / A) * NV);
}
// Viscosity
ddt(Vort) += FV::Div_a_Grad_perp(viscosity, Vort);
if (vort_dissipation) {
// Adds dissipation term like in other equations
Field3D sound_speed = get<Field3D>(state["sound_speed"]);
ddt(Vort) -= FV::Div_par(Vort, 0.0, sound_speed);
}
if (phi_dissipation) {
// Adds dissipation term like in other equations, but depending on gradient of
// potential
Field3D sound_speed = get<Field3D>(state["sound_speed"]);
ddt(Vort) -= FV::Div_par(-phi, 0.0, sound_speed);
}
if (hyper_z > 0) {
// Form of hyper-viscosity to suppress zig-zags in Z
auto* coord = Vort.getCoordinates();
ddt(Vort) -= hyper_z * SQ(SQ(coord->dz)) * D4DZ4(Vort);
}
if (phi_sheath_dissipation) {
// Dissipation when phi < 0.0 at the sheath
auto phi_fa = toFieldAligned(phi);
Field3D dissipation{zeroFrom(phi_fa)};
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(phi_fa, r.ind, mesh->ystart, jz);
BoutReal phisheath = 0.5*(phi_fa[i] + phi_fa[i.ym()]);
dissipation[i] = -floor(-phisheath, 0.0);
}
}
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
for (int jz = 0; jz < mesh->LocalNz; jz++) {
auto i = indexAt(phi_fa, r.ind, mesh->yend, jz);
BoutReal phisheath = 0.5*(phi_fa[i] + phi_fa[i.yp()]);
dissipation[i] = -floor(-phisheath, 0.0);
}
}
ddt(Vort) += fromFieldAligned(dissipation);
}
if (damp_core_vorticity) {
// Damp axisymmetric vorticity near core boundary
if (mesh->firstX() and mesh->periodicY(mesh->xstart)) {
for (int j = mesh->ystart; j <= mesh->yend; j++) {
BoutReal vort_avg = 0.0; // Average Vort in Z
for (int k = 0; k < mesh->LocalNz; k++) {
vort_avg += Vort(mesh->xstart, j, k);
}
vort_avg /= mesh->LocalNz;
for (int k = 0; k < mesh->LocalNz; k++) {
ddt(Vort)(mesh->xstart, j, k) -= 0.01 * vort_avg;
}
}
}
}
}
void Vorticity::outputVars(Options& state) {
AUTO_TRACE();
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
state["Vort"].setAttributes({{"time_dimension", "t"},
{"units", "C m^-3"},
{"conversion", SI::qe * Nnorm},
{"long_name", "vorticity"},
{"source", "vorticity"}});
set_with_attrs(state["phi"], phi,
{{"time_dimension", "t"},
{"units", "V"},
{"conversion", Tnorm},
{"standard_name", "potential"},
{"long_name", "plasma potential"},
{"source", "vorticity"}});
if (diagnose) {
set_with_attrs(state["ddt(Vort)"], ddt(Vort),
{{"time_dimension", "t"},
{"units", "A m^-3"},
{"conversion", SI::qe * Nnorm * Omega_ci},
{"long_name", "Rate of change of vorticity"},
{"source", "vorticity"}});
if (diamagnetic) {
set_with_attrs(state["DivJdia"], DivJdia,
{{"time_dimension", "t"},
{"units", "A m^-3"},
{"conversion", SI::qe * Nnorm * Omega_ci},
{"long_name", "Divergence of diamagnetic current"},
{"source", "vorticity"}});
}
if (collisional_friction) {
set_with_attrs(state["DivJcol"], DivJcol,
{{"time_dimension", "t"},
{"units", "A m^-3"},
{"conversion", SI::qe * Nnorm * Omega_ci},
{"long_name", "Divergence of collisional current"},
{"source", "vorticity"}});
}
}
}
| 28,680
|
C++
|
.cxx
| 675
| 34.616296
| 125
| 0.582649
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,242
|
anomalous_diffusion.cxx
|
bendudson_hermes-3/src/anomalous_diffusion.cxx
|
#include "../include/anomalous_diffusion.hxx"
#include "../include/div_ops.hxx"
#include <bout/fv_ops.hxx>
#include <bout/output_bout_types.hxx>
using bout::globals::mesh;
AnomalousDiffusion::AnomalousDiffusion(std::string name, Options& alloptions, Solver*)
: name(name) {
// Normalisations
const Options& units = alloptions["units"];
const BoutReal rho_s0 = units["meters"];
const BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>();
const BoutReal diffusion_norm = rho_s0 * rho_s0 * Omega_ci; // m^2/s
Options& options = alloptions[name];
// Set in the mesh or options (or both)
anomalous_D = 0.0;
include_D = (mesh->get(anomalous_D, std::string("D_") + name) == 0)
|| options.isSet("anomalous_D");
// Option overrides mesh value
anomalous_D = options["anomalous_D"]
.doc("Anomalous particle diffusion coefficient [m^2/s]")
.withDefault(anomalous_D)
/ diffusion_norm;
anomalous_chi = 0.0;
include_chi = (mesh->get(anomalous_chi, std::string("chi_") + name) == 0)
|| options.isSet("anomalous_chi");
anomalous_chi = options["anomalous_chi"]
.doc("Anomalous thermal diffusion coefficient [m^2/s]")
.withDefault(anomalous_chi)
/ diffusion_norm;
anomalous_nu = 0.0;
include_nu = (mesh->get(anomalous_nu, std::string("nu_") + name) == 0)
|| options.isSet("anomalous_nu");
anomalous_nu = options["anomalous_nu"]
.doc("Anomalous momentum diffusion coefficient [m^2/s]")
.withDefault(anomalous_nu)
/ diffusion_norm;
anomalous_sheath_flux = options["anomalous_sheath_flux"]
.doc("Allow anomalous diffusion into sheath?")
.withDefault<bool>(false);
diagnose = alloptions[name]["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
}
void AnomalousDiffusion::transform(Options& state) {
AUTO_TRACE();
Options& species = state["species"][name];
// Diffusion operates on 2D (axisymmetric) profiles
// Note: Includes diffusion in Y, so set boundary fluxes
// to zero by imposing neumann boundary conditions.
const Field3D N = GET_NOBOUNDARY(Field3D, species["density"]);
Field2D N2D = DC(N);
const Field3D T = species.isSet("temperature")
? GET_NOBOUNDARY(Field3D, species["temperature"])
: 0.0;
Field2D T2D = DC(T);
const Field3D V =
species.isSet("velocity") ? GET_NOBOUNDARY(Field3D, species["velocity"]) : 0.0;
Field2D V2D = DC(V);
if (!anomalous_sheath_flux) {
// Apply Neumann Y boundary condition, so no additional flux into boundary
// Note: Not setting radial (X) boundaries since those set radial fluxes
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
N2D(r.ind, mesh->ystart - 1) = N2D(r.ind, mesh->ystart);
T2D(r.ind, mesh->ystart - 1) = T2D(r.ind, mesh->ystart);
V2D(r.ind, mesh->ystart - 1) = V2D(r.ind, mesh->ystart);
}
for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) {
N2D(r.ind, mesh->yend + 1) = N2D(r.ind, mesh->yend);
T2D(r.ind, mesh->yend + 1) = T2D(r.ind, mesh->yend);
V2D(r.ind, mesh->yend + 1) = V2D(r.ind, mesh->yend);
}
}
Field3D flow_xlow, flow_ylow; // Flows through cell faces
if (include_D) {
// Particle diffusion. Gradients of density drive flows of particles,
// momentum and energy. The implementation here is equivalent to an
// advection velocity
//
// v_D = - D Grad_perp(N) / N
add(species["density_source"], Div_a_Grad_perp_upwind_flows(anomalous_D, N2D,
flow_xlow, flow_ylow));
add(species["particle_flow_xlow"], flow_xlow);
add(species["particle_flow_ylow"], flow_ylow);
// Note: Upwind operators used, or unphysical increases
// in temperature and flow can be produced
auto AA = get<BoutReal>(species["AA"]);
add(species["momentum_source"], Div_a_Grad_perp_upwind_flows(AA * V2D * anomalous_D, N2D,
flow_xlow, flow_ylow));
add(species["momentum_flow_xlow"], flow_xlow);
add(species["momentum_flow_ylow"], flow_ylow);
add(species["energy_source"],
Div_a_Grad_perp_upwind_flows((3. / 2) * T2D * anomalous_D, N2D,
flow_xlow, flow_ylow));
add(species["energy_flow_xlow"], flow_xlow);
add(species["energy_flow_ylow"], flow_ylow);
}
if (include_chi) {
// Gradients in temperature that drive energy flows
add(species["energy_source"], Div_a_Grad_perp_upwind_flows(anomalous_chi * N2D, T2D, flow_xlow, flow_ylow));
add(species["energy_flow_xlow"], flow_xlow);
add(species["energy_flow_ylow"], flow_ylow);
}
if (include_nu) {
// Gradients in flow speed that drive momentum flows
auto AA = get<BoutReal>(species["AA"]);
add(species["momentum_source"], Div_a_Grad_perp_upwind_flows(anomalous_nu * AA * N2D, V2D, flow_xlow, flow_ylow));
add(species["momentum_flow_xlow"], flow_xlow);
add(species["momentum_flow_ylow"], flow_ylow);
}
}
void AnomalousDiffusion::outputVars(Options& state) {
AUTO_TRACE();
// Normalisations
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
auto rho_s0 = get<BoutReal>(state["rho_s0"]);
if (diagnose) {
AUTO_TRACE();
// Save particle, momentum and energy channels
set_with_attrs(state[{std::string("anomalous_D_") + name}], anomalous_D,
{{"time_dimension", "t"},
{"units", "m^2 s^-1"},
{"conversion", rho_s0 * rho_s0 * Omega_ci},
{"standard_name", "anomalous density diffusion"},
{"long_name", std::string("Anomalous density diffusion of ") + name},
{"source", "anomalous_diffusion"}});
set_with_attrs(state[{std::string("anomalous_Chi_") + name}], anomalous_chi,
{{"time_dimension", "t"},
{"units", "m^2 s^-1"},
{"conversion", rho_s0 * rho_s0 * Omega_ci},
{"standard_name", "anomalous thermal diffusion"},
{"long_name", std::string("Anomalous thermal diffusion of ") + name},
{"source", "anomalous_diffusion"}});
set_with_attrs(state[{std::string("anomalous_nu_") + name}], anomalous_nu,
{{"time_dimension", "t"},
{"units", "m^2 s^-1"},
{"conversion", rho_s0 * rho_s0 * Omega_ci},
{"standard_name", "anomalous momentum diffusion"},
{"long_name", std::string("Anomalous momentum diffusion of ") + name},
{"source", "anomalous_diffusion"}});
}
}
| 7,029
|
C++
|
.cxx
| 141
| 39.900709
| 118
| 0.588364
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,243
|
upstream_density_feedback.cxx
|
bendudson_hermes-3/src/upstream_density_feedback.cxx
|
#include "../include/upstream_density_feedback.hxx"
#include <bout/mesh.hxx>
using bout::globals::mesh;
void UpstreamDensityFeedback::transform(Options& state) {
Options& species = state["species"][name];
// Doesn't need all boundaries to be set
Field3D N = getNoBoundary<Field3D>(species["density"]);
auto time = get<BoutReal>(state["time"]);
for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) {
int jz = 0;
error = density_upstream - N(r.ind, mesh->ystart, jz);
// PI controller, using crude integral of the error
if (density_error_lasttime < 0.0) {
// First time this has run
density_error_lasttime = time;
density_error_last = error;
}
// Integrate using Trapezium rule
if (time > density_error_lasttime) { // Since time can decrease
density_error_integral += (time - density_error_lasttime) * 0.5 *
(error + density_error_last);
}
if ((density_error_integral < 0.0) && density_integral_positive) {
// Limit density_error_integral to be >= 0
density_error_integral = 0.0;
}
// Calculate source from combination of error and integral
integral_term = density_controller_i * density_error_integral;
proportional_term = density_controller_p * error;
source_multiplier = proportional_term + integral_term;
if ((source_multiplier < 0.0) && density_source_positive) {
source_multiplier = 0.0; // Don't remove particles
}
density_error_last = error;
density_error_lasttime = time;
break;
}
// The upstream density is only present in processor 0, so for other
// processors the above loop is skipped. Need to broadcast the values from
// processor 0 to the other processors
MPI_Bcast(&source_multiplier, 1, MPI_DOUBLE, 0, BoutComm::get());
MPI_Bcast(&proportional_term, 1, MPI_DOUBLE, 0, BoutComm::get());
MPI_Bcast(&integral_term, 1, MPI_DOUBLE, 0, BoutComm::get());
ASSERT2(std::isfinite(source_multiplier));
// Scale the source and add to the species density source
add(species["density_source"], source_multiplier * density_source_shape);
// Adding particles to a flowing plasma reduces its kinetic energy
// -> Increase internal energy
if (IS_SET_NOBOUNDARY(species["velocity"]) and IS_SET(species["AA"])) {
const Field3D V = GET_NOBOUNDARY(Field3D, species["velocity"]);
const BoutReal Mi = get<BoutReal>(species["AA"]);
// Internal energy source
add(species["energy_source"], 0.5 * Mi * SQ(V) * source_multiplier * density_source_shape);
}
}
| 2,556
|
C++
|
.cxx
| 55
| 41.945455
| 95
| 0.693607
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,244
|
hermes-3.hxx
|
bendudson_hermes-3/hermes-3.hxx
|
/*
Copyright B.Dudson, J.Leddy, University of York, September 2016
email: benjamin.dudson@york.ac.uk
This file is part of Hermes-2 (Hot ion, multifluid).
Hermes is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Hermes is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Hermes. If not, see <http://www.gnu.org/licenses/>.
*/
class Hermes;
#ifndef HERMES_H
#define HERMES_H
#include <bout/physicsmodel.hxx>
#include "include/component_scheduler.hxx"
class Hermes : public PhysicsModel {
public:
virtual ~Hermes() {}
protected:
int init(bool restarting) override;
int rhs(BoutReal t) override;
int precon(BoutReal t, BoutReal gamma, BoutReal delta);
/// Add variables to be written to the output file
///
/// Adds units and then calls each component in turn
void outputVars(Options& options) override;
/// Add variables to restart file
void restartVars(Options& options) override;
private:
/// Organises and schedules model components
std::unique_ptr<ComponentScheduler> scheduler;
/// Stores the dimensional units
Options units;
/// The evolving state
Options state;
/// Input normalisation constants
BoutReal Tnorm, Nnorm, Bnorm;
/// Derived normalisation constants
BoutReal Cs0, Omega_ci, rho_s0;
};
#endif // HERMES_H
| 1,767
|
C++
|
.h
| 46
| 34.73913
| 72
| 0.750588
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,245
|
quasineutral.hxx
|
bendudson_hermes-3/include/quasineutral.hxx
|
#pragma once
#ifndef QUASINEUTRAL
#define QUASINEUTRAL
#include "component.hxx"
/// Calculate density from sum of other species densities * charge
/// to ensure that net charge = 0
///
/// This is useful in simulations where multiple species are being evolved.
/// Note that only one species' density can be calculated this way,
/// and it should be calculated last once all other densities are known.
///
/// Saves the density to the output (dump) files as N<name>
///
struct Quasineutral : public Component {
/// Inputs
/// ------
///
/// @param name Short name for species e.g. "e"
/// @param alloptions Component configuration options
/// - <name>
/// - charge Required to have a particle charge
/// - AA Atomic mass
///
Quasineutral(std::string name, Options &alloptions, Solver *UNUSED(solver));
///
/// Sets in state
/// - species
/// - <name>
/// - density
/// - charge
/// - AA
void transform(Options &state) override;
/// Get the final density for output
/// including any boundary conditions applied
void finally(const Options &state) override;
void outputVars(Options &state) override;
private:
std::string name; ///< Name of this species
BoutReal charge; ///< The charge of this species
BoutReal AA; ///< Atomic mass
Field3D density; ///< The density (for writing to output)
};
namespace {
RegisterComponent<Quasineutral>
registercomponentquasineutral("quasineutral");
}
#endif // QUASINEUTRAL
| 1,516
|
C++
|
.h
| 47
| 29.87234
| 78
| 0.689938
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,246
|
amjuel_hyd_recombination.hxx
|
bendudson_hermes-3/include/amjuel_hyd_recombination.hxx
|
#pragma once
#ifndef AMJUEL_HYD_RECOMBINATION_H
#define AMJUEL_HYD_RECOMBINATION_H
#include <bout/constants.hxx>
#include "amjuel_reaction.hxx"
/// Hydrogen recombination, Amjuel rates
///
/// Includes both radiative and 3-body recombination
struct AmjuelHydRecombination : public AmjuelReaction {
AmjuelHydRecombination(std::string name, Options& alloptions, Solver* solver)
: AmjuelReaction(name, alloptions, solver) {}
void calculate_rates(Options& electron, Options& atom, Options& ion,
Field3D& reaction_rate, Field3D& momentum_exchange,
Field3D& energy_exchange, Field3D& energy_loss, BoutReal& rate_multiplier, BoutReal& radiation_multiplier);
};
/// Hydrogen recombination
/// Templated on a char to allow 'h', 'd' and 't' species to be treated with the same code
template <char Isotope>
struct AmjuelHydRecombinationIsotope : public AmjuelHydRecombination {
AmjuelHydRecombinationIsotope(std::string name, Options& alloptions, Solver* solver)
: AmjuelHydRecombination(name, alloptions, solver) {
diagnose = alloptions[name]["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
rate_multiplier = alloptions[{Isotope}]["K_rec_multiplier"]
.doc("Scale the recombination rate by this factor")
.withDefault<BoutReal>(1.0);
radiation_multiplier = alloptions[{Isotope}]["R_rec_multiplier"]
.doc("Scale the recombination radiation (incl. 3 body) rate by this factor")
.withDefault<BoutReal>(1.0);
}
void transform(Options& state) override {
Options& electron = state["species"]["e"];
Options& atom = state["species"][{Isotope}]; // e.g. "h"
Options& ion = state["species"][{Isotope, '+'}]; // e.g. "h+"
Field3D reaction_rate, momentum_exchange, energy_exchange, energy_loss;
calculate_rates(electron, atom, ion, reaction_rate, momentum_exchange,
energy_exchange, energy_loss, rate_multiplier, radiation_multiplier);
if (diagnose) {
S = -reaction_rate;
F = -momentum_exchange;
E = -energy_exchange;
R = -energy_loss;
}
}
void outputVars(Options& state) override {
AUTO_TRACE();
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
auto Cs0 = get<BoutReal>(state["Cs0"]);
if (diagnose) {
// Save particle, momentum and energy channels
std::string atom{Isotope};
std::string ion{Isotope, '+'};
set_with_attrs(state[{'S', Isotope, '+', '_', 'r', 'e', 'c'}], S,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "particle source"},
{"long_name", std::string("Particle source due to recombnation of ")
+ ion + " to " + atom},
{"source", "amjuel_hyd_recombination"}});
set_with_attrs(
state[{'F', Isotope, '+', '_', 'r', 'e', 'c'}], F,
{{"time_dimension", "t"},
{"units", "kg m^-2 s^-2"},
{"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci},
{"standard_name", "momentum transfer"},
{"long_name", (std::string("Momentum transfer due to recombination of ") + ion
+ " to " + atom)},
{"source", "amjuel_hyd_recombination"}});
set_with_attrs(
state[{'E', Isotope, '+', '_', 'r', 'e', 'c'}], E,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "energy transfer"},
{"long_name", (std::string("Energy transfer due to recombination of ") + ion
+ " to " + atom)},
{"source", "amjuel_hyd_recombination"}});
set_with_attrs(
state[{'R', Isotope, '+', '_', 'r', 'e', 'c'}], R,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "radiation loss"},
{"long_name", (std::string("Radiation loss due to recombination of ") + ion
+ " to " + atom)},
{"source", "amjuel_hyd_recombination"}});
}
}
private:
bool diagnose; ///< Outputting diagnostics?
BoutReal rate_multiplier, radiation_multiplier; ///< Scaling factor on reaction rate
Field3D S; ///< Particle exchange
Field3D F; ///< Momentum exchange
Field3D E; ///< Energy exchange
Field3D R; ///< Radiation loss
};
namespace {
/// Register three components, one for each hydrogen isotope
/// so no isotope dependence included.
RegisterComponent<AmjuelHydRecombinationIsotope<'h'>>
register_recombination_h("h+ + e -> h");
RegisterComponent<AmjuelHydRecombinationIsotope<'d'>>
register_recombination_d("d+ + e -> d");
RegisterComponent<AmjuelHydRecombinationIsotope<'t'>>
register_recombination_t("t+ + e -> t");
} // namespace
#endif // AMJUEL_HYD_RECOMBINATION_H
| 5,353
|
C++
|
.h
| 113
| 38.39823
| 130
| 0.591109
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,247
|
sheath_closure.hxx
|
bendudson_hermes-3/include/sheath_closure.hxx
|
#pragma once
#ifndef SHEATH_CLOSURE_H
#define SHEATH_CLOSURE_H
#include "component.hxx"
/// 2D closure, modelling currents through a sheath
///
/// This should only be used where one grid cell is used in y (ny=1).
/// For domains with multiple Y points, use sheath_boundary
struct SheathClosure : public Component {
/// Inputs
/// - units
/// - meters Length normalisation
/// - <name>
/// - connection_length Parallel connection length in meters
///
SheathClosure(std::string name, Options &options, Solver *);
/// Inputs
/// - fields
/// - phi Electrostatic potential
///
/// Optional inputs
/// - species
/// - density
/// - pressure
///
/// Modifies
/// - species
/// - e
/// - density_source (If density present)
/// - density_source and energy_source (If sinks=true)
/// - fields
/// - DivJdia Divergence of current
///
void transform(Options &state) override;
private:
BoutReal L_par; // Normalised connection length
BoutReal sheath_gamma; // Sheath heat transmission coefficient
BoutReal sheath_gamma_ions; // Sheath heat transmission coefficient for ions
BoutReal offset; // Potential at which the sheath current is zero
bool sinks; // Include sinks of density and energy?
};
namespace {
RegisterComponent<SheathClosure>
registercomponentsheathclosure("sheath_closure");
}
#endif // SHEATH_CLOSURE_H
| 1,424
|
C++
|
.h
| 46
| 28.347826
| 78
| 0.690789
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,248
|
simple_pump.hxx
|
bendudson_hermes-3/include/simple_pump.hxx
|
#pragma once
#ifndef simple_pump_H
#define simple_pump_H
#include "component.hxx"
#include <bout/constants.hxx>
struct SimplePump : public Component {
SimplePump(std::string name, Options& alloptions, Solver*) : name(name) {
Options& options = alloptions[name];
const auto& units = alloptions["units"];
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
Omega_ci = 1.0 / get<BoutReal>(units["seconds"]);
residence_time = (options["residence_time"]
.doc("Pumping time-constant. Units [s]")
.as<BoutReal>()
) * Omega_ci;
sink_shape = (options["sink_shape"]
.doc("Shape of pumping sink.")
.withDefault(Field3D(0.0))
);
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
};
void transform(Options& state) override {
Field3D species_density = getNoBoundary<Field3D>(state["species"][name]["density"]);
pumping_sink = (sink_shape * species_density) * (-1.0 / residence_time);
add(state["species"][name]["density_source"], pumping_sink);
};
void outputVars(Options& state) override {
AUTO_TRACE();
if (diagnose) {
set_with_attrs(
state[std::string("simple_pump_src_shape_" + name)], sink_shape,
{{"long_name", "simple pump source shape"},
{"source", "simple_pump"}});
set_with_attrs(
state[std::string("simple_pump_sink_" + name)], pumping_sink,
{{"time_dimension", "t"},
{"units", "m^-3 / s"},
{"conversion", Nnorm * Omega_ci},
{"long_name", "simple pump source shape"},
{"source", "simple_pump"}});
}}
private:
std::string name; ///< The species name
Field3D sink_shape;
Field3D pumping_sink;
BoutReal Nnorm;
BoutReal Omega_ci;
BoutReal residence_time;
bool diagnose;
};
namespace {
RegisterComponent<SimplePump> register_simple_pump("simple_pump");
}
#endif // simple_pump_H
| 2,039
|
C++
|
.h
| 56
| 29.642857
| 92
| 0.617782
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,249
|
ion_viscosity.hxx
|
bendudson_hermes-3/include/ion_viscosity.hxx
|
#pragma once
#ifndef ION_VISCOSITY_H
#define ION_VISCOSITY_H
#include "component.hxx"
/// Ion viscosity terms
///
/// Adds a viscosity to all species which are not electrons
///
/// Uses Braginskii collisional form, combined with a
/// SOLPS-like flux limiter.
///
/// Needs to be calculated after collisions, because collision
/// frequency is used to calculate parallel viscosity
///
/// The ion stress tensor Pi_ci is split into perpendicular and
/// parallel pieces:
///
/// Pi_ci = Pi_ciperp + Pi_cipar
///
/// In the parallel ion momentum equation the Pi_cipar term
/// is solved as a parallel diffusion, so is treated separately
/// All other terms are added to Pi_ciperp, even if they are
/// not really parallel parts
struct IonViscosity : public Component {
/// Inputs
/// - <name>
/// - eta_limit_alpha: float, default -1
/// Flux limiter coefficient. < 0 means off.
/// - perpendicular: bool, default false
/// Include perpendicular flows?
/// Requires curvature vector and phi potential
///
IonViscosity(std::string name, Options& alloptions, Solver*);
/// Inputs
/// - species
/// - <name> (skips "e")
/// - pressure (skips if not present)
/// - velocity (skips if not present)
/// - collision_frequency
///
/// Sets in the state
/// - species
/// - <name>
/// - momentum_source
///
void transform(Options &state) override;
/// Save variables to the output
void outputVars(Options &state) override;
private:
BoutReal eta_limit_alpha; ///< Flux limit coefficient
bool perpendicular; ///< Include perpendicular flow? (Requires phi)
Vector2D Curlb_B; ///< Curvature vector Curl(b/B)
bool diagnose; ///< Output additional diagnostics?
/// Per-species diagnostics
struct Diagnostics {
Field3D Pi_ciperp; ///< Perpendicular part of Pi scalar
Field3D Pi_cipar; ///< Parallel part of Pi scalar
Field3D DivJ; ///< Divergence of current in vorticity equation
};
/// Store diagnostics for each species
std::map<std::string, Diagnostics> diagnostics;
};
namespace {
RegisterComponent<IonViscosity> registercomponentionviscosity("ion_viscosity");
}
#endif
| 2,205
|
C++
|
.h
| 66
| 31.090909
| 79
| 0.694366
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,250
|
ionisation.hxx
|
bendudson_hermes-3/include/ionisation.hxx
|
#pragma once
#ifndef IONISATION_H
#define IONISATION_H
#include "component.hxx"
#include "radiation.hxx"
class Ionisation : public Component {
public:
Ionisation(std::string name, Options &options, Solver *);
void transform(Options &state) override;
private:
UpdatedRadiatedPower atomic_rates {}; // Atomic rates (H.Willett)
BoutReal Eionize; // Energy loss per ionisation [eV]
BoutReal Tnorm, Nnorm, FreqNorm; // Normalisations
};
namespace {
RegisterComponent<Ionisation> registersolverionisation("ionisation");
}
#endif // IONISATION_H
| 564
|
C++
|
.h
| 18
| 29.055556
| 69
| 0.782364
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,251
|
adas_neon.hxx
|
bendudson_hermes-3/include/adas_neon.hxx
|
#pragma once
#ifndef ADAS_NEON_H
#define ADAS_NEON_H
#include "adas_reaction.hxx"
#include <array>
#include <initializer_list>
/// Ionisation energies in eV
/// from https://www.webelements.com/neon/atoms.html
/// Conversion 1 kJ mol‑1 = 1.0364e-2 eV
/// These are added (removed) from the electron energy during recombination (ionisation)
constexpr std::array<BoutReal, 10> neon_ionisation_energy{
21.56, 40.96, 63.42, 97.19, 126.24, 157.93, 207.27, 239.09, 1195.78, 1362.16};
/// The name of the species. This initializer list can be passed to a string
/// constructor, or used to index into an Options tree.
///
/// ne, ne+, ne+2, ne+3, ...
///
/// Special cases for level=0, 1 and 10
///
/// @tparam level The ionisation level: 0 is neutral, 10 is fully stripped.
template <int level>
constexpr std::initializer_list<char> neon_species_name{'n', 'e', '+', '0' + level};
template <>
constexpr std::initializer_list<char> neon_species_name<10>{'n', 'e', '+', '1', '0'};
template <>
constexpr std::initializer_list<char> neon_species_name<1>{'n', 'e', '+'};
template <>
constexpr std::initializer_list<char> neon_species_name<0>{'n', 'e'};
/// ADAS effective ionisation (ADF11)
///
/// @tparam level The ionisation level of the ion on the left of the reaction
template <int level>
struct ADASNeonIonisation : public OpenADAS {
ADASNeonIonisation(std::string, Options& alloptions, Solver*)
: OpenADAS(alloptions["units"], "scd96_ne.json", "plt96_ne.json", level,
-neon_ionisation_energy[level]) {}
void transform(Options& state) override {
calculate_rates(
state["species"]["e"], // Electrons
state["species"][neon_species_name<level>], // From this ionisation state
state["species"][neon_species_name<level + 1>] // To this state
);
}
};
/////////////////////////////////////////////////
/// ADAS effective recombination coefficients (ADF11)
///
/// @tparam level The ionisation level of the ion on the right of the reaction
template <int level>
struct ADASNeonRecombination : public OpenADAS {
/// @param alloptions The top-level options. Only uses the ["units"] subsection.
ADASNeonRecombination(std::string, Options& alloptions, Solver*)
: OpenADAS(alloptions["units"], "acd96_ne.json", "prb96_ne.json", level,
neon_ionisation_energy[level]) {}
void transform(Options& state) override {
calculate_rates(
state["species"]["e"], // Electrons
state["species"][neon_species_name<level + 1>], // From this ionisation state
state["species"][neon_species_name<level>] // To this state
);
}
};
/// @tparam level The ionisation level of the ion on the right of the reaction
/// @tparam Hisotope The hydrogen isotope ('h', 'd' or 't')
template <int level, char Hisotope>
struct ADASNeonCX : public OpenADASChargeExchange {
/// @param alloptions The top-level options. Only uses the ["units"] subsection.
ADASNeonCX(std::string, Options& alloptions, Solver*)
: OpenADASChargeExchange(alloptions["units"], "ccd89_ne.json", level) {}
void transform(Options& state) override {
Options& species = state["species"];
calculate_rates(
species["e"], // Electrons
species[neon_species_name<level + 1>], // From this ionisation state
species[{Hisotope}], // and this neutral hydrogen atom
species[neon_species_name<level>], // To this state
species[{Hisotope, '+'}] // and this hydrogen ion
);
}
};
namespace {
// Ionisation by electron-impact
RegisterComponent<ADASNeonIonisation<0>> register_ionisation_ne0("ne + e -> ne+ + 2e");
RegisterComponent<ADASNeonIonisation<1>> register_ionisation_ne1("ne+ + e -> ne+2 + 2e");
RegisterComponent<ADASNeonIonisation<2>> register_ionisation_ne2("ne+2 + e -> ne+3 + 2e");
RegisterComponent<ADASNeonIonisation<3>> register_ionisation_ne3("ne+3 + e -> ne+4 + 2e");
RegisterComponent<ADASNeonIonisation<4>> register_ionisation_ne4("ne+4 + e -> ne+5 + 2e");
RegisterComponent<ADASNeonIonisation<5>> register_ionisation_ne5("ne+5 + e -> ne+6 + 2e");
RegisterComponent<ADASNeonIonisation<6>> register_ionisation_ne6("ne+6 + e -> ne+7 + 2e");
RegisterComponent<ADASNeonIonisation<7>> register_ionisation_ne7("ne+7 + e -> ne+8 + 2e");
RegisterComponent<ADASNeonIonisation<8>> register_ionisation_ne8("ne+8 + e -> ne+9 + 2e");
RegisterComponent<ADASNeonIonisation<9>> register_ionisation_ne9("ne+9 + e -> ne+10 + 2e");
// Recombination
RegisterComponent<ADASNeonRecombination<0>> register_recombination_ne0("ne+ + e -> ne");
RegisterComponent<ADASNeonRecombination<1>> register_recombination_ne1("ne+2 + e -> ne+");
RegisterComponent<ADASNeonRecombination<2>> register_recombination_ne2("ne+3 + e -> ne+2");
RegisterComponent<ADASNeonRecombination<3>> register_recombination_ne3("ne+4 + e -> ne+3");
RegisterComponent<ADASNeonRecombination<4>> register_recombination_ne4("ne+5 + e -> ne+4");
RegisterComponent<ADASNeonRecombination<5>> register_recombination_ne5("ne+6 + e -> ne+5");
RegisterComponent<ADASNeonRecombination<6>> register_recombination_ne6("ne+7 + e -> ne+6");
RegisterComponent<ADASNeonRecombination<7>> register_recombination_ne7("ne+8 + e -> ne+7");
RegisterComponent<ADASNeonRecombination<8>> register_recombination_ne8("ne+9 + e -> ne+8");
RegisterComponent<ADASNeonRecombination<9>> register_recombination_ne9("ne+10 + e -> ne+9");
// Charge exchange
RegisterComponent<ADASNeonCX<0, 'h'>> register_cx_ne0h("ne+ + h -> ne + h+");
RegisterComponent<ADASNeonCX<1, 'h'>> register_cx_ne1h("ne+2 + h -> ne+ + h+");
RegisterComponent<ADASNeonCX<2, 'h'>> register_cx_ne2h("ne+3 + h -> ne+2 + h+");
RegisterComponent<ADASNeonCX<3, 'h'>> register_cx_ne3h("ne+4 + h -> ne+3 + h+");
RegisterComponent<ADASNeonCX<4, 'h'>> register_cx_ne4h("ne+5 + h -> ne+4 + h+");
RegisterComponent<ADASNeonCX<5, 'h'>> register_cx_ne5h("ne+6 + h -> ne+5 + h+");
RegisterComponent<ADASNeonCX<6, 'h'>> register_cx_ne6h("ne+7 + h -> ne+6 + h+");
RegisterComponent<ADASNeonCX<7, 'h'>> register_cx_ne7h("ne+8 + h -> ne+7 + h+");
RegisterComponent<ADASNeonCX<8, 'h'>> register_cx_ne8h("ne+9 + h -> ne+8 + h+");
RegisterComponent<ADASNeonCX<9, 'h'>> register_cx_ne9h("ne+10 + h -> ne+9 + h+");
RegisterComponent<ADASNeonCX<0, 'd'>> register_cx_ne0d("ne+ + d -> ne + d+");
RegisterComponent<ADASNeonCX<1, 'd'>> register_cx_ne1d("ne+2 + d -> ne+ + d+");
RegisterComponent<ADASNeonCX<2, 'd'>> register_cx_ne2d("ne+3 + d -> ne+2 + d+");
RegisterComponent<ADASNeonCX<3, 'd'>> register_cx_ne3d("ne+4 + d -> ne+3 + d+");
RegisterComponent<ADASNeonCX<4, 'd'>> register_cx_ne4d("ne+5 + d -> ne+4 + d+");
RegisterComponent<ADASNeonCX<5, 'd'>> register_cx_ne5d("ne+6 + d -> ne+5 + d+");
RegisterComponent<ADASNeonCX<6, 'd'>> register_cx_ne6d("ne+7 + d -> ne+6 + d+");
RegisterComponent<ADASNeonCX<7, 'd'>> register_cx_ne7d("ne+8 + d -> ne+7 + d+");
RegisterComponent<ADASNeonCX<8, 'd'>> register_cx_ne8d("ne+9 + d -> ne+8 + d+");
RegisterComponent<ADASNeonCX<9, 'd'>> register_cx_ne9d("ne+10 + d -> ne+9 + d+");
RegisterComponent<ADASNeonCX<0, 't'>> register_cx_ne0t("ne+ + t -> ne + t+");
RegisterComponent<ADASNeonCX<1, 't'>> register_cx_ne1t("ne+2 + t -> ne+ + t+");
RegisterComponent<ADASNeonCX<2, 't'>> register_cx_ne2t("ne+3 + t -> ne+2 + t+");
RegisterComponent<ADASNeonCX<3, 't'>> register_cx_ne3t("ne+4 + t -> ne+3 + t+");
RegisterComponent<ADASNeonCX<4, 't'>> register_cx_ne4t("ne+5 + t -> ne+4 + t+");
RegisterComponent<ADASNeonCX<5, 't'>> register_cx_ne5t("ne+6 + t -> ne+5 + t+");
RegisterComponent<ADASNeonCX<6, 't'>> register_cx_ne6t("ne+7 + t -> ne+6 + t+");
RegisterComponent<ADASNeonCX<7, 't'>> register_cx_ne7t("ne+8 + t -> ne+7 + t+");
RegisterComponent<ADASNeonCX<8, 't'>> register_cx_ne8t("ne+9 + t -> ne+8 + t+");
RegisterComponent<ADASNeonCX<9, 't'>> register_cx_ne9t("ne+10 + t -> ne+9 + t+");
} // namespace
#endif // ADAS_NEON_H
| 7,995
|
C++
|
.h
| 136
| 56.213235
| 92
| 0.672917
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,252
|
relax_potential.hxx
|
bendudson_hermes-3/include/relax_potential.hxx
|
#pragma once
#ifndef RELAX_POTENTIAL_H
#define RELAX_POTENTIAL_H
#include <bout/vector2d.hxx>
#include "component.hxx"
/// Evolve vorticity and potential in time.
///
/// Uses a relaxation method for the potential, which is valid for
/// steady state, but not for timescales shorter than the relaxation
/// timescale.
///
struct RelaxPotential : public Component {
/// Options
///
/// - <name>
/// - diamagnetic
/// - diamagnetic_polarisation
/// - average_atomic_mass
/// - bndry_flux
/// - poloidal_flows
/// - split_n0
/// - laplacian
/// Options for the Laplacian phi solver
///
RelaxPotential(std::string name, Options& options, Solver* solver);
/// Optional inputs
///
/// - species
/// - pressure and charge => Calculates diamagnetic terms [if diamagnetic=true]
/// - pressure, charge and mass => Calculates polarisation current terms
/// [if diamagnetic_polarisation=true]
///
/// Sets in the state
/// - species
/// - [if has pressure and charge]
/// - energy_source
/// - fields
/// - vorticity
/// - phi Electrostatic potential
/// - DivJdia Divergence of diamagnetic current [if diamagnetic=true]
///
/// Note: Diamagnetic current calculated here, but could be moved
/// to a component with the diamagnetic drift advection terms
void transform(Options& state) override;
/// Optional inputs
/// - fields
/// - DivJextra Divergence of current, including parallel current
/// Not including diamagnetic or polarisation currents
///
void finally(const Options& state) override;
void outputVars(Options& state) override;
private:
Field3D Vort; // Evolving vorticity
Field3D phi1; // Scaled electrostatic potential, evolving in time ϕ_1 = λ_2 ϕ
Field3D phi; // Electrostatic potential
bool exb_advection; //< Include nonlinear ExB advection?
bool diamagnetic; //< Include diamagnetic current?
bool diamagnetic_polarisation; //< Include diamagnetic drift in polarisation current?
bool boussinesq; ///< Use the Boussinesq approximation?
BoutReal average_atomic_mass; //< Weighted average atomic mass, for polarisaion current
// (Boussinesq approximation)
bool poloidal_flows; ///< Include poloidal ExB flow?
bool bndry_flux; ///< Allow flows through radial boundaries?
bool sheath_boundary; ///< Set outer boundary to j=0?
Field2D Bsq; ///< SQ(coord->Bxy)
Vector2D Curlb_B; ///< Curvature vector Curl(b/B)
BoutReal lambda_1, lambda_2; ///< Relaxation parameters
};
namespace {
RegisterComponent<RelaxPotential> registercomponentrelaxpotential("relax_potential");
}
#endif // RELAX_POTENTIAL_H
| 2,799
|
C++
|
.h
| 72
| 35.722222
| 90
| 0.676872
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,253
|
hydrogen_charge_exchange.hxx
|
bendudson_hermes-3/include/hydrogen_charge_exchange.hxx
|
#pragma once
#ifndef HYDROGEN_CHARGE_EXCHANGE_H
#define HYDROGEN_CHARGE_EXCHANGE_H
#include <bout/constants.hxx>
#include "component.hxx"
/// Hydrogen charge exchange total rate coefficient
///
/// p + H(1s) -> H(1s) + p
///
/// Reaction 3.1.8 from Amjuel (p43)
///
/// Scaled to different isotope masses and finite neutral particle
/// temperatures by using the effective temperature (Amjuel p43)
///
/// T_eff = (M/M_1)T_1 + (M/M_2)T_2
///
///
/// Important: If this is included then ion_neutral collisions
/// should probably be disabled in the `collisions` component,
/// to avoid double-counting.
///
struct HydrogenChargeExchange : public Component {
///
/// @param alloptions Settings, which should include:
/// - units
/// - eV
/// - inv_meters_cubed
/// - seconds
HydrogenChargeExchange(std::string name, Options& alloptions, Solver*) {
// Get the units
const auto& units = alloptions["units"];
Tnorm = get<BoutReal>(units["eV"]);
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
FreqNorm = 1. / get<BoutReal>(units["seconds"]);
}
protected:
BoutReal Tnorm, Nnorm, FreqNorm; ///< Normalisations
/// Calculate the charge exchange cross-section
///
/// atom1 + ion1 -> atom2 + ion2
///
/// and transfer of mass, momentum and energy from:
///
/// atom1 -> ion2, ion1 -> atom2
///
/// Assumes that both atom1 and ion1 have:
/// - AA
/// - density
/// - velocity
/// - temperature
///
/// Sets in all species:
/// - density_source [If atom1 != atom2 or ion1 != ion2]
/// - momentum_source
/// - energy_source
///
/// Modifies collision_frequency for atom1 and ion1
///
/// Diagnostic output
/// R Reaction rate, transfer of particles in case of different isotopes
/// atom_mom Momentum removed from atom1, added to ion2
/// ion_mom Momentum removed from ion1, added to atom2
/// atom_energy Energy removed from atom1, added to ion2
/// ion_energy Energy removed from ion1, added to atom2
///
void calculate_rates(Options& atom1, Options& ion1, Options& atom2, Options& ion2,
Field3D& R, Field3D& atom_mom, Field3D& ion_mom,
Field3D& atom_energy, Field3D& ion_energy,
Field3D& atom_rate, Field3D& ion_rate,
BoutReal& rate_multiplier,
bool& no_neutral_cx_mom_gain);
};
/// Hydrogen charge exchange
/// Templated on a char to allow 'h', 'd' and 't' species to be treated with the same code
///
/// @tparam Isotope1 The isotope ('h', 'd' or 't') of the initial atom
/// @tparam Isotope2 The isotope ('h', 'd' or 't') of the initial ion
///
/// atom + ion -> ion + atom
/// Isotope1 + Isotope2+ -> Isotope1+ + Isotope2
///
/// Diagnostics
/// -----------
///
/// If diagnose = true is set in the options, then the following diagnostics are saved:
/// - F<Isotope1><Isotope2>+_cx (e.g. Fhd+_cx) the momentum added to Isotope1 atoms due
/// due to charge exchange with Isotope2 ions.
/// There is a corresponding loss of momentum for the
/// Isotope1 ions d/dt(NVh) = ... + Fhd+_cx // Atom
/// momentum source d/dt(NVh+) = ... - Fhd+_cx // Ion
/// momentum sink
/// - E<Isotope1><Isotope2>+_cx Energy added to Isotope1 atoms due to charge exchange
/// with
/// Isotope2 ions. This contributes to two pressure
/// equations d/dt(3/2 Ph) = ... + Ehd+_cx d/dt(3/2 Ph+) =
/// ... - Ehd+_cx
///
/// If Isotope1 != Isotope2 then there is also the source of energy for Isotope2 atoms
/// and a source of particles:
/// - F<Isotope2>+<Isotope1>_cx Source of momentum for Isotope2 ions, sink for Isotope2
/// atoms
/// - E<Isotope2>+<Isotope1>_cx Source of energy for Isotope2 ions, sink for Isotope2
/// atoms
/// - S<Isotope1><Isotope2>+_cx Source of Isotope1 atoms due to charge exchange with
/// Isotope2 ions
/// Note: S<Isotope2><Isotope1>+_cx =
/// -S<Isotope1><Isotope2>+_cx For example Shd+_cx
/// contributes to four density equations: d/dt(Nh) = ...
/// + Shd+_cx d/dt(Nh+) = ... - Shd+_cx d/dt(Nd) = ... -
/// Shd+_cx d/dt(Nd+) = ... + Shd+_cx
///
template <char Isotope1, char Isotope2>
struct HydrogenChargeExchangeIsotope : public HydrogenChargeExchange {
HydrogenChargeExchangeIsotope(std::string name, Options& alloptions, Solver* solver)
: HydrogenChargeExchange(name, alloptions, solver) {
//// Options under [reactions]
diagnose = alloptions[name]["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
// This is useful for testing the impact of enabling the neutral momentum equation.
// When set to true, CX behaves as if using diffusive neutrals but the neutral transport
// still enjoys the full momentum equation treatment.
no_neutral_cx_mom_gain = alloptions[name]["no_neutral_cx_mom_gain"]
.doc("If true, ion momentum in CX is still lost but not given to the neutrals")
.withDefault<bool>(false);
// Options under neutral species of isotope 1 (on LHS of reaction)
rate_multiplier = alloptions[{Isotope1}]["K_cx_multiplier"]
.doc("Scale the charge exchange rate by this factor")
.withDefault<BoutReal>(1.0);
}
void transform(Options& state) override {
Field3D R, atom_mom, ion_mom, atom_energy, ion_energy;
calculate_rates(state["species"][{Isotope1}], // e.g. "h"
state["species"][{Isotope2, '+'}], // e.g. "d+"
state["species"][{Isotope2}], // e.g. "d"
state["species"][{Isotope1, '+'}], // e.g. "h+"
R, atom_mom, ion_mom, atom_energy, ion_energy, // Transfer channels
atom_rate, ion_rate, // Collision rates in s^-1
rate_multiplier, // Arbitrary user set multiplier
no_neutral_cx_mom_gain); // Make CX behave as in diffusive neutrals?
if (diagnose) {
// Calculate diagnostics to be written to dump file
if (Isotope1 == Isotope2) {
// Simpler case of same isotopes
// - No net particle source/sink
// - atoms lose atom_mom, gain ion_mom
//
F = ion_mom - atom_mom; // Momentum transferred to atoms due to CX with ions
E = ion_energy - atom_energy; // Energy transferred to atoms
} else {
// Different isotopes
S = -R; // Source of Isotope1 atoms
F = -atom_mom; // Source of momentum for Isotope1 atoms
F2 = -ion_mom; // Source of momentum for Isotope2 ions
E = -atom_energy; // Source of energy for Isotope1 atoms
E2 = -ion_energy; // Source of energy for Isotope2 ions
}
}
}
void outputVars(Options& state) override {
AUTO_TRACE();
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
auto Cs0 = get<BoutReal>(state["Cs0"]);
if (diagnose) {
// Save particle, momentum and energy channels
std::string atom1{Isotope1};
std::string ion1{Isotope1, '+'};
std::string atom2{Isotope2};
std::string ion2{Isotope2, '+'};
set_with_attrs(state[{'F', Isotope1, Isotope2, '+', '_', 'c', 'x'}], // e.g Fhd+_cx
F,
{{"time_dimension", "t"},
{"units", "kg m^-2 s^-2"},
{"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci},
{"standard_name", "momentum transfer"},
{"long_name", (std::string("Momentum transfer to ") + atom1
+ " from " + ion1 + " due to CX with " + ion2)},
{"source", "hydrogen_charge_exchange"}});
set_with_attrs(state[{'E', Isotope1, Isotope2, '+', '_', 'c', 'x'}], // e.g Edt+_cx
E,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "energy transfer"},
{"long_name", (std::string("Energy transfer to ") + atom1 + " from "
+ ion1 + " due to CX with " + ion2)},
{"source", "hydrogen_charge_exchange"}});
set_with_attrs(state[{'K', Isotope1, Isotope2, '+', '_', 'c', 'x'}], // e.g Kdt+_cx
atom_rate,
{{"time_dimension", "t"},
{"units", "s^-1"},
{"conversion", Omega_ci},
{"standard_name", "collision frequency"},
{"long_name", (std::string("CX collision frequency between") + atom1 + " and "
+ ion1 + " producing" + ion2 + " and" + atom2 + ". Note Kab != Kba")},
{"source", "hydrogen_charge_exchange"}});
if (Isotope1 != Isotope2) {
// Different isotope => particle source, second momentum & energy channel
set_with_attrs(
state[{'F', Isotope2, '+', Isotope1, '_', 'c', 'x'}], // e.g Fd+h_cx
F2,
{{"time_dimension", "t"},
{"units", "kg m^-2 s^-2"},
{"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci},
{"standard_name", "momentum transfer"},
{"long_name", (std::string("Momentum transfer to ") + ion2 + " from " + atom2
+ " due to CX with " + atom1)},
{"source", "hydrogen_charge_exchange"}});
set_with_attrs(
state[{'E', Isotope2, '+', Isotope1, '_', 'c', 'x'}], // e.g Et+d_cx
E2,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "energy transfer"},
{"long_name", (std::string("Energy transfer to ") + ion2 + " from " + atom2
+ " due to CX with " + atom1)},
{"source", "hydrogen_charge_exchange"}});
// Source of isotope1 atoms
set_with_attrs(
state[{'S', Isotope1, Isotope2, '+', '_', 'c', 'x'}], // e.g Shd+_cx
S,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "particle transfer"},
{"long_name", (std::string("Particle transfer to ") + atom1 + " from " + ion1
+ " due to charge exchange with " + ion2)},
{"source", "hydrogen_charge_exchange"}});
}
}
}
private:
bool diagnose; ///< Outputting diagnostics?
BoutReal rate_multiplier; ///< Multiply rate by arbitrary user set factor
Field3D S; ///< Particle exchange, used if Isotope1 != Isotope2
Field3D F, F2; ///< Momentum exchange
Field3D E, E2; ///< Energy exchange
Field3D atom_rate, ion_rate; ///< Collision rates in s^-1
bool no_neutral_cx_mom_gain; ///< Make CX behave as in diffusive neutrals?
};
namespace {
/// Register three components, one for each hydrogen isotope
/// so no isotope dependence included.
RegisterComponent<HydrogenChargeExchangeIsotope<'h', 'h'>>
register_cx_hh("h + h+ -> h+ + h");
RegisterComponent<HydrogenChargeExchangeIsotope<'d', 'd'>>
register_cx_dd("d + d+ -> d+ + d");
RegisterComponent<HydrogenChargeExchangeIsotope<'t', 't'>>
register_cx_tt("t + t+ -> t+ + t");
// Charge exchange between different isotopes
RegisterComponent<HydrogenChargeExchangeIsotope<'h', 'd'>>
register_cx_hd("h + d+ -> h+ + d");
RegisterComponent<HydrogenChargeExchangeIsotope<'d', 'h'>>
register_cx_dh("d + h+ -> d+ + h");
RegisterComponent<HydrogenChargeExchangeIsotope<'h', 't'>>
register_cx_ht("h + t+ -> h+ + t");
RegisterComponent<HydrogenChargeExchangeIsotope<'t', 'h'>>
register_cx_th("t + h+ -> t+ + h");
RegisterComponent<HydrogenChargeExchangeIsotope<'d', 't'>>
register_cx_dt("d + t+ -> d+ + t");
RegisterComponent<HydrogenChargeExchangeIsotope<'t', 'd'>>
register_cx_td("t + d+ -> t+ + d");
} // namespace
#endif // HYDROGEN_CHARGE_EXCHANGE_H
| 12,972
|
C++
|
.h
| 269
| 40.319703
| 111
| 0.546725
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,254
|
evolve_energy.hxx
|
bendudson_hermes-3/include/evolve_energy.hxx
|
#pragma once
#ifndef EVOLVE_ENERGY_H
#define EVOLVE_ENERGY_H
#include <bout/field3d.hxx>
#include "component.hxx"
/// Evolves species internal energy in time
///
/// # Mesh inputs
///
/// P<name>_src A source of pressure, in Pascals per second
/// This can be over-ridden by the `source` option setting.
///
struct EvolveEnergy : public Component {
///
/// # Inputs
///
/// - <name>
/// - bndry_flux Allow flows through radial boundaries? Default is true
/// - density_floor Minimum density floor. Default 1e-5 normalised units.
/// - diagnose Output additional diagnostic fields?
/// - evolve_log Evolve logarithm of pressure? Default is false
/// - hyper_z Hyper-diffusion in Z
/// - kappa_coefficient Heat conduction constant. Default is 3.16 for
/// electrons, 3.9 otherwise
/// - kappa_limit_alpha Flux limiter, off by default.
/// - poloidal_flows Include poloidal ExB flows? Default is true
/// - precon Enable preconditioner? Note: solver may not use it even if
/// enabled.
/// - thermal_conduction Include parallel heat conduction? Default is true
///
/// - E<name> e.g. "Ee", "Ed+"
/// - source Source of energy [W / s].
/// NOTE: This overrides mesh input P<name>_src
/// - source_only_in_core Zero the source outside the closed field-line
/// region?
/// - neumann_boundary_average_z Apply Neumann boundaries with Z average?
///
EvolveEnergy(std::string name, Options& options, Solver* solver);
/// Inputs
/// - species
/// - <name>
/// - density
/// - velocity
///
/// Sets
/// - species
/// - <name>
/// - pressure
/// - temperature
///
void transform(Options& state) override;
///
/// Optional inputs
///
/// - species
/// - <name>
/// - velocity. Must have sound_speed or temperature
/// - energy_source
/// - collision_rate (needed if thermal_conduction on)
/// - fields
/// - phi Electrostatic potential -> ExB drift
///
void finally(const Options& state) override;
void outputVars(Options& state) override;
/// Preconditioner
///
void precon(const Options& UNUSED(state), BoutReal gamma) override;
private:
std::string name; ///< Short name of the species e.g. h+
Field3D E; ///< Energy (normalised): P + 1/2 m n v^2
Field3D P; ///< Pressure (normalised)
Field3D T, N; ///< Temperature, density
BoutReal adiabatic_index; ///< Ratio of specific heats, γ = Cp / Cv
BoutReal Cv; /// Heat capacity at constant volume (3/2 for ideal monatomic gas)
bool bndry_flux;
bool neumann_boundary_average_z; ///< Apply neumann boundary with Z average?
bool poloidal_flows;
bool thermal_conduction; ///< Include thermal conduction?
BoutReal kappa_coefficient; ///< Leading numerical coefficient in parallel heat flux
///< calculation
BoutReal kappa_limit_alpha; ///< Flux limit if >0
bool evolve_log; ///< Evolve logarithm of E?
Field3D logE; ///< Natural logarithm of E
BoutReal density_floor; ///< Minimum density for calculating T
Field3D kappa_par; ///< Parallel heat conduction coefficient
Field3D source; ///< External power source
Field3D Se; ///< Total energy source
BoutReal hyper_z; ///< Hyper-diffusion
bool diagnose; ///< Output additional diagnostics?
bool enable_precon; ///< Enable preconditioner?
Field3D flow_xlow, flow_ylow; ///< Energy flow diagnostics
};
namespace {
RegisterComponent<EvolveEnergy> registercomponentevolveenergy("evolve_energy");
}
#endif // EVOLVE_ENERGY_H
| 3,754
|
C++
|
.h
| 96
| 36.03125
| 89
| 0.641033
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,255
|
amjuel_hyd_ionisation.hxx
|
bendudson_hermes-3/include/amjuel_hyd_ionisation.hxx
|
#pragma once
#ifndef AMJUEL_HYD_IONISATION_H
#define AMJUEL_HYD_IONISATION_H
#include <bout/constants.hxx>
#include "amjuel_reaction.hxx"
/// Hydrogen ionisation, Amjuel rates
struct AmjuelHydIonisation : public AmjuelReaction {
AmjuelHydIonisation(std::string name, Options& alloptions, Solver* solver)
: AmjuelReaction(name, alloptions, solver) {}
void calculate_rates(Options& electron, Options& atom, Options& ion,
Field3D& reaction_rate, Field3D& momentum_exchange,
Field3D& energy_exchange, Field3D& energy_loss, BoutReal& rate_multiplier, BoutReal& radiation_multiplier);
};
/// Hydrogen ionisation
/// Templated on a char to allow 'h', 'd' and 't' species to be treated with the same code
template <char Isotope>
struct AmjuelHydIonisationIsotope : public AmjuelHydIonisation {
AmjuelHydIonisationIsotope(std::string name, Options& alloptions, Solver* solver)
: AmjuelHydIonisation(name, alloptions, solver) {
diagnose = alloptions[name]["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
rate_multiplier = alloptions[{Isotope}]["K_iz_multiplier"]
.doc("Scale the ionisation rate by this factor")
.withDefault<BoutReal>(1.0);
radiation_multiplier = alloptions[{Isotope}]["R_ex_multiplier"]
.doc("Scale the ionisation excitation/de-excitation radiation rate by this factor")
.withDefault<BoutReal>(1.0);
}
void transform(Options& state) override {
Options& electron = state["species"]["e"];
Options& atom = state["species"][{Isotope}]; // e.g. "h"
Options& ion = state["species"][{Isotope, '+'}]; // e.g. "h+"
Field3D reaction_rate, momentum_exchange, energy_exchange, energy_loss;
calculate_rates(electron, atom, ion, reaction_rate, momentum_exchange,
energy_exchange, energy_loss, rate_multiplier, radiation_multiplier);
if (diagnose) {
S = reaction_rate;
F = momentum_exchange;
E = energy_exchange;
R = -energy_loss;
}
}
void outputVars(Options& state) override {
AUTO_TRACE();
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Tnorm = get<BoutReal>(state["Tnorm"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
auto Cs0 = get<BoutReal>(state["Cs0"]);
if (diagnose) {
// Save particle, momentum and energy channels
std::string atom{Isotope};
std::string ion{Isotope, '+'};
set_with_attrs(state[{'S', Isotope, '+', '_', 'i', 'z'}], S,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "particle source"},
{"long_name", std::string("Ionisation of ") + atom + " to " + ion},
{"source", "amjuel_hyd_ionisation"}});
set_with_attrs(
state[{'F', Isotope, '+', '_', 'i', 'z'}], F,
{{"time_dimension", "t"},
{"units", "kg m^-2 s^-2"},
{"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci},
{"standard_name", "momentum transfer"},
{"long_name", (std::string("Momentum transfer due to ionisation of ") + atom
+ " to " + ion)},
{"source", "amjuel_hyd_ionisation"}});
set_with_attrs(state[{'E', Isotope, '+', '_', 'i', 'z'}], E,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "energy transfer"},
{"long_name", (std::string("Energy transfer due to ionisation of ")
+ atom + " to " + ion)},
{"source", "amjuel_hyd_ionisation"}});
set_with_attrs(state[{'R', Isotope, '+', '_', 'e', 'x'}], R,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", Pnorm * Omega_ci},
{"standard_name", "radiation loss"},
{"long_name", (std::string("Radiation loss due to ionisation of ")
+ atom + " to " + ion)},
{"source", "amjuel_hyd_ionisation"}});
}
}
private:
bool diagnose; ///< Outputting diagnostics?
BoutReal rate_multiplier, radiation_multiplier; ///< Scaling factor on reaction rate
Field3D S; ///< Particle exchange
Field3D F; ///< Momentum exchange
Field3D E; ///< Energy exchange
Field3D R; ///< Radiation loss
};
namespace {
/// Register three components, one for each hydrogen isotope
/// so no isotope dependence included.
RegisterComponent<AmjuelHydIonisationIsotope<'h'>>
registerionisation_h("h + e -> h+ + 2e");
RegisterComponent<AmjuelHydIonisationIsotope<'d'>>
registerionisation_d("d + e -> d+ + 2e");
RegisterComponent<AmjuelHydIonisationIsotope<'t'>>
registerionisation_t("t + e -> t+ + 2e");
} // namespace
#endif // AMJUEL_HYD_IONISATION_H
| 5,282
|
C++
|
.h
| 108
| 38.694444
| 130
| 0.57384
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,256
|
neutral_parallel_diffusion.hxx
|
bendudson_hermes-3/include/neutral_parallel_diffusion.hxx
|
#pragma once
#ifndef NEUTRAL_PARALLEL_DIFFUSION_H
#define NEUTRAL_PARALLEL_DIFFUSION_H
#include "component.hxx"
/// Add effective diffusion of neutrals in a 1D system,
/// by projecting cross-field diffusion onto parallel distance.
///
/// Note: This needs to be calculated after the collision frequency,
/// so is a collective component. This therefore applies diffusion
/// to all neutral species i.e. those with no (or zero) charge
///
/// Diagnostics
/// -----------
///
/// If diagnose = true then the following outputs are saved for
/// each neutral species
///
/// - D<name>_Dpar Parallel diffusion coefficient e.g. Dhe_Dpar
/// - S<name>_Dpar Density source due to diffusion
/// - E<name>_Dpar Energy source due to diffusion
/// - F<name>_Dpar Momentum source due to diffusion
///
struct NeutralParallelDiffusion : public Component {
NeutralParallelDiffusion(std::string name, Options &alloptions, Solver *) {
auto& options = alloptions[name];
dneut = options["dneut"]
.doc("cross-field diffusion projection (B / Bpol)^2")
.as<BoutReal>();
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
equation_fix = options["equation_fix"]
.doc("Fix correcting pressure advection and conductivity factors?")
.withDefault<bool>(true);
thermal_conduction = options["thermal_conducton"]
.doc("Enable conduction?")
.withDefault<bool>(true);
viscosity = options["viscosity"]
.doc("Enable viscosity?")
.withDefault<bool>(true);
}
///
/// Inputs
/// - species
/// - <all neutrals> # Applies to all neutral species
/// - AA
/// - collision_frequency
/// - density
/// - temperature
/// - pressure [optional, or density * temperature]
/// - velocity [optional]
/// - momentum [if velocity set]
///
/// Sets
/// - species
/// - <name>
/// - density_source
/// - energy_source
/// - momentum_source [if velocity set]
void transform(Options &state) override;
/// Save variables to the output
void outputVars(Options &state) override;
private:
BoutReal dneut; ///< cross-field diffusion projection (B / Bpol)^2
bool diagnose; ///< Output diagnostics?
bool equation_fix; ///< Fix incorrect 3/2 factor in pressure advection?
bool thermal_conduction; ///< Enable conduction?
bool viscosity; ///< Enable viscosity?
/// Per-species diagnostics
struct Diagnostics {
Field3D Dn; ///< Diffusion coefficient
Field3D S; ///< Particle source
Field3D E; ///< Energy source
Field3D F; ///< Momentum source
};
/// Store diagnostics for each species
std::map<std::string, Diagnostics> diagnostics;
};
namespace {
RegisterComponent<NeutralParallelDiffusion>
register_component_neutral_parallel_diffusion("neutral_parallel_diffusion");
}
#endif // NEUTRAL_PARALLEL_DIFFUSION_H
| 2,983
|
C++
|
.h
| 83
| 32.493976
| 80
| 0.672324
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,257
|
vorticity.hxx
|
bendudson_hermes-3/include/vorticity.hxx
|
#pragma once
#ifndef VORTICITY_H
#define VORTICITY_H
#include <bout/vector2d.hxx>
#include "component.hxx"
class LaplaceXY;
class Laplacian;
/// Evolve electron density in time
///
struct Vorticity : public Component {
/// Options
///
/// - <name>
/// - average_atomic_mass: float, default 2.0
/// Weighted average ion atomic mass for polarisation current
/// - bndry_flux: bool, default true
/// Allow flows through radial (X) boundaries?
/// - collisional_friction: bool, default false
/// Damp vorticity based on mass-weighted collision frequency?
/// - diagnose: bool, false
/// Output additional diagnostics?
/// - diamagnetic: bool, default true
/// Include diamagnetic current, using curvature vector?
/// - diamagnetic_polarisation: bool, default true
/// Include ion diamagnetic drift in polarisation current?
/// - exb_advection: bool, default true
/// Include ExB advection (nonlinear term)?
/// - hyper_z: float, default -1.0
/// Hyper-viscosity in Z. < 0 means off
/// - laplacian: subsection
/// Options for the Laplacian phi solver
/// - phi_boundary_relax: bool, default false
/// Relax radial phi boundaries towards zero-gradient?
/// - phi_boundary_timescale: float, 1e-4
/// Timescale for phi boundary relaxation [seconds]
/// - phi_core_averagey: bool, default false
/// Average phi core boundary in Y? (if phi_boundary_relax)
/// - phi_dissipation: bool, default true
/// Parallel dissipation of potential (Recommended)
/// - poloidal_flows: bool, default true
/// Include poloidal ExB flow?
/// - sheath_boundary: bool, default false
/// If phi_boundary_relax is false, set the radial boundary to the sheath potential?
/// - split_n0: bool, default false
/// Split phi into n=0 and n!=0 components?
/// - viscosity: Field2D, default 0.0
/// Kinematic viscosity [m^2/s]
/// - vort_dissipation: bool, default false
/// Parallel dissipation of vorticity?
/// - damp_core_vorticity: bool, default false
/// Damp axisymmetric component of vorticity in cell next to core boundary
///
Vorticity(std::string name, Options &options, Solver *solver);
/// Optional inputs
///
/// - species
/// - pressure and charge => Calculates diamagnetic terms [if diamagnetic=true]
/// - pressure, charge and mass => Calculates polarisation current terms [if diamagnetic_polarisation=true]
///
/// Sets in the state
/// - species
/// - [if has pressure and charge]
/// - energy_source
/// - fields
/// - vorticity
/// - phi Electrostatic potential
/// - DivJdia Divergence of diamagnetic current [if diamagnetic=true]
///
/// Note: Diamagnetic current calculated here, but could be moved
/// to a component with the diamagnetic drift advection terms
void transform(Options &state) override;
/// Optional inputs
/// - fields
/// - DivJextra Divergence of current, including parallel current
/// Not including diamagnetic or polarisation currents
///
void finally(const Options &state) override;
void outputVars(Options &state) override;
// Save and restore potential phi
void restartVars(Options& state) override {
AUTO_TRACE();
// NOTE: This is a hack because we know that the loaded restart file
// is passed into restartVars in PhysicsModel::postInit
// The restart value should be used in init() rather than here
static bool first = true;
if (first and state.isSet("phi")) {
first = false;
phi = state["phi"].as<Field3D>();
}
// Save the potential
set_with_attrs(state["phi"], phi,
{{"long_name", "plasma potential"},
{"source", "vorticity"}});
}
private:
Field3D Vort; // Evolving vorticity
Field3D phi; // Electrostatic potential
std::unique_ptr<Laplacian> phiSolver; // Laplacian solver in X-Z
Field3D Pi_hat; ///< Contribution from ion pressure, weighted by atomic mass / charge
bool exb_advection; // Include nonlinear ExB advection?
bool exb_advection_simplified; // Simplify nonlinear ExB advection form?
bool diamagnetic; // Include diamagnetic current?
bool diamagnetic_polarisation; // Include diamagnetic drift in polarisation current
BoutReal average_atomic_mass; // Weighted average atomic mass, for polarisaion current (Boussinesq approximation)
bool poloidal_flows; ///< Include poloidal ExB flow?
bool bndry_flux; ///< Allow flows through radial boundaries?
bool collisional_friction; ///< Damping of vorticity due to collisional friction
bool sheath_boundary; ///< Set outer boundary to j=0?
bool vort_dissipation; ///< Parallel dissipation of vorticity
bool phi_dissipation; ///< Parallel dissipation of potential
bool phi_sheath_dissipation; ///< Dissipation at the sheath if phi < 0
bool damp_core_vorticity; ///< Damp axisymmetric component of vorticity
bool phi_boundary_relax; ///< Relax boundary to zero-gradient
BoutReal phi_boundary_timescale; ///< Relaxation timescale [normalised]
BoutReal phi_boundary_last_update; ///< Time when last updated
bool phi_core_averagey; ///< Average phi core boundary in Y?
bool split_n0; // Split phi into n=0 and n!=0 components
LaplaceXY* laplacexy; // Laplacian solver in X-Y (n=0)
Field2D Bsq; // SQ(coord->Bxy)
Vector2D Curlb_B; // Curvature vector Curl(b/B)
BoutReal hyper_z; ///< Hyper-viscosity in Z
Field2D viscosity; ///< Kinematic viscosity
// Diagnostic outputs
Field3D DivJdia, DivJcol; // Divergence of diamagnetic and collisional current
bool diagnose; ///< Output additional diagnostics?
};
namespace {
RegisterComponent<Vorticity> registercomponentvorticity("vorticity");
}
#endif // VORTICITY_H
| 5,872
|
C++
|
.h
| 130
| 41.730769
| 115
| 0.694595
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,258
|
upstream_density_feedback.hxx
|
bendudson_hermes-3/include/upstream_density_feedback.hxx
|
#pragma once
#ifndef UPSTREAM_DENSITY_FEEDBACK_H
#define UPSTREAM_DENSITY_FEEDBACK_H
#include "component.hxx"
/// Adds a time-varying density source, depending on the difference
/// between the upstream density at y=0 and the specified value
struct UpstreamDensityFeedback : public Component {
/// Inputs
/// - <name> (e.g. "d+")
/// - density_upstream Upstream density (y=0) in m^-3
/// - density_controller_p Feedback proportional to error
/// - density_controller_i Feedback proportional to error integral
/// - density_integral_positive Force integral term to be positive? (default: false)
/// - density_source_positive Force density source to be positive? (default: true)
/// - diagnose Output diagnostic information?
///
/// - N<name> (e.g. "Nd+")
/// - source_shape The initial source that is scaled by a time-varying factor
///
UpstreamDensityFeedback(std::string name, Options& alloptions, Solver*) : name(name) {
const auto& units = alloptions["units"];
BoutReal Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
BoutReal FreqNorm = 1. / get<BoutReal>(units["seconds"]);
Options& options = alloptions[name];
density_upstream =
options["density_upstream"].doc("Upstream density (at y=0) [m^-3]").as<BoutReal>()
/ Nnorm;
density_controller_p = options["density_controller_p"]
.doc("Feedback controller proportional (p) parameter")
.withDefault(1e-2);
density_controller_i = options["density_controller_i"]
.doc("Feedback controller integral (i) parameter")
.withDefault(1e-3);
density_integral_positive = options["density_integral_positive"]
.doc("Force integral term to be positive?")
.withDefault<bool>(false);
density_source_positive = options["density_source_positive"]
.doc("Force source to be positive?")
.withDefault<bool>(true);
// NOTE: density_error_integral should be set from the restart file here.
// There doesn't seem to be a way to get the restart Options,
// so for now this is set in restartVars
// Source shape the same as used in EvolveDensity
density_source_shape =
alloptions[std::string("N") + name]["source_shape"]
.doc("Source term in ddt(N" + name + std::string("). Units [m^-3/s]"))
.withDefault(Field3D(0.0))
/ (Nnorm * FreqNorm);
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
}
/// Inputs
/// - <name>
/// - density
///
/// Outputs
///
/// - <name>
/// - density_source
///
void transform(Options& state) override;
void outputVars(Options& state) override {
AUTO_TRACE();
if (diagnose) {
// Normalisations
auto Nnorm = get<BoutReal>(state["Nnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
// Shape is not time-dependent and has units of [m-3 s-1]
set_with_attrs(
state[std::string("density_feedback_src_shape_") + name], density_source_shape,
{{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"long_name", name + " density source shape"},
{"source", "upstream_density_feedback"}});
// The source multiplier is time-dependent, but dimensionless
// because all the units are attached to the shape
set_with_attrs(state[std::string("density_feedback_src_mult_") + name],
source_multiplier,
{{"time_dimension", "t"},
{"long_name", name + " density source multiplier"},
{"source", "upstream_density_feedback"}});
set_with_attrs(state[std::string("S") + name + std::string("_feedback")], density_source_shape * source_multiplier,
{{"time_dimension", "t"},
{"units", "m^-3 s^-1"},
{"conversion", Nnorm * Omega_ci},
{"standard_name", "density source"},
{"long_name", name + "upstream density feedback controller source"},
{"source", "upstream_density_feedback"}});
// Save proportional and integral component of source for diagnostics/tuning
// Multiplier = proportional term + integral term
set_with_attrs(
state[std::string("density_feedback_src_p_") + name], proportional_term,
{{"time_dimension", "t"},
{"long_name", name + " proportional feedback term"},
{"source", "upstream_density_feedback"}});
set_with_attrs(
state[std::string("density_feedback_src_i_") + name], integral_term,
{{"time_dimension", "t"},
{"long_name", name + " integral feedback term"},
{"source", "upstream_density_feedback"}});
}
}
void restartVars(Options& state) override {
AUTO_TRACE();
// NOTE: This is a hack because we know that the loaded restart file
// is passed into restartVars in PhysicsModel::postInit
// The restart value should be used in init() rather than here
static bool first = true;
if (first and state.isSet(name + "_density_error_integral")) {
first = false;
density_error_integral = state[name + "_density_error_integral"].as<BoutReal>();
}
// Save the density error integral
set_with_attrs(state[name + "_density_error_integral"], density_error_integral,
{{"long_name", name + " density error integral"},
{"source", "upstream_density_feedback"}});
}
private:
std::string name; ///< The species name
BoutReal density_upstream; ///< Normalised upstream density
BoutReal density_controller_p, density_controller_i; ///< PI controller parameters
BoutReal error;
BoutReal density_error_integral{0.0}; ///< Time integral of the error
bool density_integral_positive; ///< Force integral term to be positive?
bool density_source_positive; ///< Force source to be positive?
// Terms used in Trapezium rule integration of error
BoutReal density_error_lasttime{-1.0};
BoutReal density_error_last{0.0};
Field3D density_source_shape; ///< This shape source is scaled up and down
BoutReal source_multiplier; ///< Factor to multiply source
BoutReal proportional_term, integral_term; ///< Components of resulting source for diagnostics
bool diagnose; ///< Output diagnostic information?
};
namespace {
RegisterComponent<UpstreamDensityFeedback> register_uds("upstream_density_feedback");
}
#endif // UPSTREAM_DENSITY_FEEDBACK_H
| 6,869
|
C++
|
.h
| 138
| 41.094203
| 121
| 0.616913
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,259
|
scale_timederivs.hxx
|
bendudson_hermes-3/include/scale_timederivs.hxx
|
#pragma once
#ifndef SCALE_TIMEDERIVS_H
#define SCALE_TIMEDERIVS_H
#include "component.hxx"
#include <bout/globals.hxx>
/// Scale time derivatives of the system
///
/// This is intended for steady-state calculations
/// where the aim is to reach ddt -> 0
///
struct ScaleTimeDerivs : public Component {
ScaleTimeDerivs(std::string, Options&, Solver*) {}
/// Sets in the state
///
/// - scale_timederivs
///
void transform(Options &state) override {
auto* coord = bout::globals::mesh->getCoordinates();
Field2D dl2 = coord->g_22 * SQ(coord->dy);
// Scale by parallel heat conduction CFL timescale
auto Te = get<Field3D>(state["species"]["e"]["temperature"]);
Field3D dt = dl2 / pow(floor(Te, 1e-5), 5./2);
scaling = dt / max(dt, true); // Saved for output
state["scale_timederivs"] = scaling;
}
void outputVars(Options& state) override {
set_with_attrs(
state["scale_timederivs"], scaling,
{{"time_dimension", "t"},
{"long_name", "Scaling factor applied to all time derivatives"},
{"source", "scale_timederivs"}});
}
private:
Field3D scaling; // The scaling factor applied to each cell
};
namespace {
RegisterComponent<ScaleTimeDerivs> registercomponentscaletimederivs("scale_timederivs");
}
#endif // SCALE_TIMEDERIVS_H
| 1,316
|
C++
|
.h
| 39
| 30.282051
| 88
| 0.690608
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,260
|
sheath_boundary_simple.hxx
|
bendudson_hermes-3/include/sheath_boundary_simple.hxx
|
#pragma once
#ifndef SHEATH_BOUNDARY_SIMPLE_H
#define SHEATH_BOUNDARY_SIMPLE_H
#include "component.hxx"
/// Boundary condition at the wall in Y
///
/// This is a collective component, because it couples all charged species
///
/// This implements a simple boundary condition, where each species
/// goes to their own sound velocity at the sheath entrance.
///
/// Notes:
/// - It is recommended to use SheathBoundary rather than SheathBoundarySimple;
/// this is here for comparison to that more complete model.
///
struct SheathBoundarySimple : public Component {
/// # Input options
/// - <name> e.g. "sheath_boundary_simple"
/// - lower_y Boundary on lower y?
/// - upper_y Boundary on upper y?
/// - gamma_e Electron sheath heat transmission coefficient
/// - gamma_i Ion sheath heat transmission coefficient
/// - sheath_ion_polytropic Ion polytropic coefficient in Bohm sound speed. Default 1.
/// - wall_potential Voltage of the wall [Volts]
/// - secondary_electron_coef Effective secondary electron emission coefficient
/// - sin_alpha Sine of the angle between magnetic field line and wall surface (0 to 1)
/// - always_set_phi Always set phi field? Default is to only modify if already set
SheathBoundarySimple(std::string name, Options &options, Solver *);
///
/// # Inputs
/// - species
/// - e
/// - density
/// - temperature
/// - pressure Optional
/// - velocity Optional
/// - mass Optional
/// - adiabatic Optional. Ratio of specific heats, default 5/3.
/// - <ions> if charge is set (i.e. not neutrals)
/// - charge
/// - mass
/// - density
/// - temperature
/// - pressure Optional
/// - velocity Optional. Default 0
/// - momentum Optional. Default mass * density * velocity
/// - adiabatic Optional. Ratio of specific heats, default 5/3.
/// - fields
/// - phi Optional. If not set, calculated at boundary (see note below)
///
/// # Outputs
/// - species
/// - e
/// - density Sets boundary
/// - temperature Sets boundary
/// - velocity Sets boundary
/// - energy_source
/// - <ions>
/// - density Sets boundary
/// - temperature Sets boundary
/// - velocity Sets boundary
/// - momentum Sets boundary
/// - energy_source
/// - fields
/// - phi Sets boundary
///
/// If the field phi is set, then this is used in the boundary condition.
/// If not set, phi at the boundary is calculated and stored in the state.
/// Note that phi in the domain will not be set, so will be invalid data.
///
///
void transform(Options &state) override;
private:
BoutReal Ge; // Secondary electron emission coefficient
BoutReal sin_alpha; // sin of angle between magnetic field and wall.
BoutReal gamma_e; ///< Electron sheath heat transmission
BoutReal gamma_i; ///< Ion sheath heat transmission
BoutReal sheath_ion_polytropic; ///< Polytropic coefficient in sheat velocity
bool lower_y; // Boundary on lower y?
bool upper_y; // Boundary on upper y?
bool always_set_phi; ///< Set phi field?
Field3D wall_potential; ///< Voltage of the wall. Normalised units.
bool no_flow; ///< No flow speed, only remove energy
BoutReal density_boundary_mode, pressure_boundary_mode, temperature_boundary_mode; ///< BC mode: 0=LimitFree, 1=ExponentialFree, 2=LinearFree
};
namespace {
RegisterComponent<SheathBoundarySimple>
registercomponentsheathboundarysimple("sheath_boundary_simple");
}
#endif // SHEATH_BOUNDARY_SIMPLE_H
| 3,762
|
C++
|
.h
| 90
| 39.133333
| 143
| 0.648361
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,261
|
amjuel_helium.hxx
|
bendudson_hermes-3/include/amjuel_helium.hxx
|
#pragma once
#ifndef AMJUEL_HELIUM_H
#define AMJUEL_HELIUM_H
#include "amjuel_reaction.hxx"
/// e + he -> he+ + 2e
/// Amjuel reaction 2.3.9a, page 161
/// Not resolving metastables, only transporting ground state
struct AmjuelHeIonisation01 : public AmjuelReaction {
AmjuelHeIonisation01(std::string name, Options& alloptions, Solver* solver)
: AmjuelReaction(name, alloptions, solver) {
rate_multiplier = alloptions[std::string("he")]["ionisation_rate_multiplier"]
.doc("Scale the ionisation rate by this factor")
.withDefault<BoutReal>(1.0);
radiation_multiplier = alloptions[std::string("he")]["ionisation_radiation_rate_multiplier"]
.doc("Scale the ionisation rate by this factor")
.withDefault<BoutReal>(1.0);
}
void calculate_rates(Options& state,
Field3D &reaction_rate, Field3D &momentum_exchange,
Field3D &energy_exchange, Field3D &energy_loss, BoutReal &rate_multiplier, BoutReal &radiation_multiplier);
void transform(Options& state) override{
Field3D reaction_rate, momentum_exchange, energy_exchange, energy_loss;
calculate_rates(state, reaction_rate, momentum_exchange, energy_exchange, energy_loss, rate_multiplier, radiation_multiplier);
};
private:
BoutReal rate_multiplier, radiation_multiplier; ///< Scaling factor on reaction rate
};
/// e + he+ -> he
/// Amjuel reaction 2.3.13a
/// Not resolving metastables. Includes radiative + threebody + dielectronic.
/// Fujimoto Formulation II
struct AmjuelHeRecombination10 : public AmjuelReaction {
AmjuelHeRecombination10(std::string name, Options& alloptions, Solver* solver)
: AmjuelReaction(name, alloptions, solver) {
rate_multiplier = alloptions[name]["recombination_rate_multiplier"]
.doc("Scale the recombination rate by this factor")
.withDefault<BoutReal>(1.0);
radiation_multiplier = alloptions[name]["recombination_radiation_multiplier"]
.doc("Scale the recombination radiation rate by this factor")
.withDefault<BoutReal>(1.0);
}
void calculate_rates(Options& state,
Field3D &reaction_rate, Field3D &momentum_exchange,
Field3D &energy_exchange, Field3D &energy_loss, BoutReal &rate_multiplier, BoutReal &radiation_multiplier);
void transform(Options& state) override{
Field3D reaction_rate, momentum_exchange, energy_exchange, energy_loss;
calculate_rates(state, reaction_rate, momentum_exchange, energy_exchange, energy_loss, rate_multiplier, radiation_multiplier);
};
private:
BoutReal rate_multiplier, radiation_multiplier; ///< Scaling factor on reaction rate
};
/// e + he+ -> he+2 + 2e
/// Amjuel reaction 2.2C, page 189
// NOTE: Currently missing energy loss / radiation data
// struct AmjuelHeIonisation12 : public AmjuelReaction {
// AmjuelHeIonisation12(std::string name, Options& alloptions, Solver* solver)
// : AmjuelReaction(name, alloptions, solver) {}
// void transform(Options& state) override;
// };
namespace {
RegisterComponent<AmjuelHeIonisation01> register_ionisation_01("he + e -> he+ + 2e");
RegisterComponent<AmjuelHeRecombination10> register_recombination_10("he+ + e -> he");
//-RegisterComponent<AmjuelHeIonisation12> register_ionisation_12("e + he+ -> he+2 + 2e");
} // namespace
#endif // AMJUEL_HELIUM_H
| 3,554
|
C++
|
.h
| 65
| 47.061538
| 131
| 0.690332
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,262
|
noflow_boundary.hxx
|
bendudson_hermes-3/include/noflow_boundary.hxx
|
#pragma once
#ifndef NOFLOW_BOUNDARY_H
#define NOFLOW_BOUNDARY_H
#include "component.hxx"
struct NoFlowBoundary : public Component {
NoFlowBoundary(std::string name, Options& alloptions, Solver*) : name(name) {
AUTO_TRACE();
Options& options = alloptions[name];
noflow_lower_y = options["noflow_lower_y"]
.doc("No-flow boundary on lower y?")
.withDefault<bool>(true);
noflow_upper_y = options["noflow_upper_y"]
.doc("No-flow boundary on upper y?")
.withDefault<bool>(true);
}
/// Inputs
/// - species
/// - <name>
/// - density [Optional]
/// - temperature [Optional]
/// - pressure [Optional]
/// - velocity [Optional]
/// - momentum [Optional]
void transform(Options& state) override;
private:
std::string name; ///<
bool noflow_lower_y; ///< No-flow boundary on lower y?
bool noflow_upper_y; ///< No-flow boundary on upper y?
};
namespace {
RegisterComponent<NoFlowBoundary> registercomponentnoflowboundary("noflow_boundary");
}
#endif // NOFLOW_BOUNDARY_H
| 1,161
|
C++
|
.h
| 33
| 29.606061
| 85
| 0.610169
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,263
|
electron_force_balance.hxx
|
bendudson_hermes-3/include/electron_force_balance.hxx
|
#pragma once
#ifndef ELECTRON_FORCE_BALANCE
#define ELECTRON_FORCE_BALANCE
#include "component.hxx"
/// Balance the parallel electron pressure gradient against
/// the electric field. Use this electric field to calculate
/// a force on the other species
///
/// E = (-∇p_e + F) / n_e
///
/// where F is the momentum source for the electrons.
///
/// Then uses this electric field to calculate a force on all
/// ion species.
///
/// Note: This needs to be put after collisions and other
/// components which impose forces on electrons
///
struct ElectronForceBalance : public Component {
ElectronForceBalance(std::string, Options&, Solver*) {}
/// Required inputs
/// - species
/// - e
/// - pressure
/// - density
/// - momentum_source [optional]
/// Asserts that charge = -1
///
/// Sets in the input
/// - species
/// - <all except e> if both density and charge are set
/// - momentum_source
///
void transform(Options &state) override;
};
namespace {
RegisterComponent<ElectronForceBalance> registercomponentelectronforcebalance("electron_force_balance");
}
#endif // ELECTRON_FORCE_BALANCE
| 1,167
|
C++
|
.h
| 39
| 28
| 104
| 0.694568
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,265
|
neutral_boundary.hxx
|
bendudson_hermes-3/include/neutral_boundary.hxx
|
#pragma once
#ifndef NEUTRAL_BOUNDARY_H
#define NEUTRAL_BOUNDARY_H
#include "component.hxx"
namespace {
Ind3D indexAt(const Field3D& f, int x, int y, int z) {
int ny = f.getNy();
int nz = f.getNz();
return Ind3D{(x * ny + y) * nz + z, ny, nz};
}
}; // namespace
/// Per-species boundary condition for neutral particles at
/// sheath (Y) boundaries.
///
/// Sets boundary conditions:
/// - Free boundary conditions on logarithm
/// of density, temperature and pressure
/// - No-flow boundary conditions on velocity
/// and momentum.
///
/// Adds an energy sink corresponding to a flux of heat to the walls.
///
/// Heat flux into the wall is
/// q = gamma_heat * n * T * v_th
///
/// where v_th = sqrt(eT/m) is the thermal speed
///
struct NeutralBoundary : public Component {
NeutralBoundary(std::string name, Options& options, Solver*);
///
/// state
/// - species
/// - <name>
/// - density Free boundary
/// - temperature Free boundary
/// - pressure Free boundary
/// - velocity [if set] Zero boundary
/// - momentum [if set] Zero boundary
/// - energy_source Adds wall losses
///
void transform(Options& state) override;
void outputVars(Options &state) override;
private:
std::string name; ///< Short name of species e.g "d"
BoutReal Tnorm; // Temperature normalisation [eV]
BoutReal target_energy_refl_factor, sol_energy_refl_factor, pfr_energy_refl_factor; ///< Fraction of energy retained after reflection
BoutReal target_fast_refl_fraction, sol_fast_refl_fraction, pfr_fast_refl_fraction; ///< Fraction of neutrals undergoing fast reflection
Field3D target_energy_source, wall_energy_source; ///< Diagnostic for power loss
bool diagnose; ///> Save diagnostic variables?
bool lower_y; ///< Boundary condition at lower y?
bool upper_y; ///< Boundary condition at upper y?
bool sol; ///< Boundary condition at sol?
bool pfr; ///< Boundary condition at pfr?
};
namespace {
RegisterComponent<NeutralBoundary>
registercomponentneutralboundary("neutral_boundary");
}
#endif // NEUTRAL_BOUNDARY_H
| 2,122
|
C++
|
.h
| 59
| 33.779661
| 138
| 0.694783
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,266
|
evolve_momentum.hxx
|
bendudson_hermes-3/include/evolve_momentum.hxx
|
#pragma once
#ifndef EVOLVE_MOMENTUM_H
#define EVOLVE_MOMENTUM_H
#include "component.hxx"
/// Evolve parallel momentum
struct EvolveMomentum : public Component {
EvolveMomentum(std::string name, Options &options, Solver *solver);
/// This sets in the state
/// - species
/// - <name>
/// - momentum
/// - velocity if density is defined
void transform(Options &state) override;
/// Calculate ddt(NV).
///
/// Inputs
/// - species
/// - <name>
/// - density
/// - velocity
/// - pressure (optional)
/// - momentum_source (optional)
/// - sound_speed (optional, used for numerical dissipation)
/// - temperature (only needed if sound_speed not provided)
/// - fields
/// - phi (optional)
void finally(const Options &state) override;
void outputVars(Options &state) override;
private:
std::string name; ///< Short name of species e.g "e"
Field3D NV; ///< Species parallel momentum (normalised, evolving)
Field3D NV_err; ///< Difference from momentum as input from solver
Field3D NV_solver; ///< Momentum as calculated in the solver
Field3D V; ///< Species parallel velocity
Field3D momentum_source; ///< From other components. Stored for diagnostic output
bool bndry_flux; // Allow flows through boundaries?
bool poloidal_flows; // Include ExB flow in Y direction?
BoutReal density_floor;
bool low_n_diffuse_perp; ///< Cross-field diffusion at low density?
BoutReal pressure_floor;
bool low_p_diffuse_perp; ///< Cross-field diffusion at low pressure?
BoutReal hyper_z; ///< Hyper-diffusion
bool diagnose; ///< Output additional diagnostics?
bool fix_momentum_boundary_flux; ///< Fix momentum flux to boundary condition?
Field3D flow_xlow, flow_ylow; ///< Momentum flow diagnostics
};
namespace {
RegisterComponent<EvolveMomentum> registercomponentevolvemomentum("evolve_momentum");
}
#endif // EVOLVE_MOMENTUM_H
| 1,979
|
C++
|
.h
| 50
| 36.76
| 85
| 0.692268
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,267
|
adas_reaction.hxx
|
bendudson_hermes-3/include/adas_reaction.hxx
|
#pragma once
#ifndef ADAS_REACTION_H
#define ADAS_REACTION_H
#include "component.hxx"
#include <vector>
/// Represent a 2D rate coefficient table (T,n)
/// Reads data from a file, then interpolates at required values.
struct OpenADASRateCoefficient {
/// Read the file, extracting data for the given ionisation level
/// @param filename The file to read. Path relative to run working directory
/// @param level The first index in the log coefficient array
/// (ionisation level)
OpenADASRateCoefficient(const std::string& filename, int level);
std::vector<std::vector<BoutReal>> log_coeff;
std::vector<BoutReal> log_temperature;
std::vector<BoutReal> log_density;
BoutReal Tmin, Tmax; ///< Range of T [eV]
BoutReal nmin, nmax; ///< Range of density [m^-3]
/// Inputs:
/// @param n Electron density in m^-3
/// @param T Electron temperature in eV
///
/// @returns rate in units of m^3/s or eV m^3/s
BoutReal evaluate(BoutReal T, BoutReal n);
};
/// Read in and perform calculations with OpenADAS data
/// https://open.adas.ac.uk/
///
/// Uses the JSON files produced by:
/// https://github.com/TBody/OpenADAS_to_JSON
struct OpenADAS : public Component {
///
/// Inputs
/// ------
/// @param units Options tree containing normalisation constants
/// @param rate_file A JSON file containing reaction rate <σv> rates (e.g. SCD, ACD)
/// @param radiation_file A JSON file containing radiation loss rates (e.g. PLT, PRB)
/// @param level The lower ionisation state in the transition
/// e.g. 0 for neutral -> 1st ionisation
/// and 1st -> neutral recombination
/// @param electron_heating The heating of the electrons per reaction [eV]
/// This is the ionisation energy, positive for recombination
/// and negative for ionisation
///
/// Notes
/// - The rate and radiation file names have "json_database/" prepended
///
OpenADAS(const Options& units, const std::string& rate_file,
const std::string& radiation_file, int level, BoutReal electron_heating)
: rate_coef(std::string("json_database/") + rate_file, level),
radiation_coef(std::string("json_database/") + radiation_file, level),
electron_heating(electron_heating) {
// Get the units
Tnorm = get<BoutReal>(units["eV"]);
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
FreqNorm = 1. / get<BoutReal>(units["seconds"]);
}
/// Perform the calculation of rates, and transfer of particles/momentum/energy
///
/// @param electron The electron species e.g. state["species"]["e"]
/// @param from_ion The ion on the left of the reaction
/// @param to_ion The ion on the right of the reaction
void calculate_rates(Options& electron, Options& from_ion, Options& to_ion);
private:
OpenADASRateCoefficient rate_coef; ///< Reaction rate coefficient
OpenADASRateCoefficient radiation_coef; ///< Energy loss (radiation) coefficient
BoutReal electron_heating; ///< Heating per reaction [eV]
BoutReal Tnorm, Nnorm, FreqNorm; ///< Normalisations
};
struct OpenADASChargeExchange : public Component {
OpenADASChargeExchange(const Options& units, const std::string& rate_file, int level)
: rate_coef(std::string("json_database/") + rate_file, level) {
// Get the units
Tnorm = get<BoutReal>(units["eV"]);
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
FreqNorm = 1. / get<BoutReal>(units["seconds"]);
}
/// Perform charge exchange
///
/// from_A + from_B -> to_A + to_B
///
/// from_A and to_A must have the same atomic mass
/// from_B and to_B must have the same atomic mass
/// The charge of from_A + from_B must equal the charge of to_A + to_B
void calculate_rates(Options& electron, Options& from_A, Options& from_B, Options& to_A,
Options& to_B);
private:
OpenADASRateCoefficient rate_coef; ///< Reaction rate coefficient
BoutReal Tnorm, Nnorm, FreqNorm; ///< Normalisations
};
#endif // ADAS_REACTION_H
| 4,086
|
C++
|
.h
| 91
| 41.494505
| 90
| 0.679387
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,268
|
isothermal.hxx
|
bendudson_hermes-3/include/isothermal.hxx
|
#pragma once
#ifndef ISOTHERMAL_H
#define ISOTHERMAL_H
#include "component.hxx"
/// Set temperature to a fixed value
///
struct Isothermal : public Component {
Isothermal(std::string name, Options &options, Solver *);
/// Inputs
/// - species
/// - <name>
/// - density (optional)
///
/// Sets in the state
///
/// - species
/// - <name>
/// - temperature
/// - pressure (if density is set)
///
void transform(Options &state) override;
void outputVars(Options &state) override;
private:
std::string name; // Species name
BoutReal T; ///< The normalised temperature
Field3D P; ///< The normalised pressure
bool diagnose; ///< Output additional diagnostics?
};
namespace {
RegisterComponent<Isothermal> registercomponentisothermal("isothermal");
}
#endif // ISOTHERMAL_H
| 831
|
C++
|
.h
| 32
| 23.53125
| 72
| 0.685209
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,269
|
sheath_boundary.hxx
|
bendudson_hermes-3/include/sheath_boundary.hxx
|
#pragma once
#ifndef SHEATH_BOUNDARY_H
#define SHEATH_BOUNDARY_H
#include "component.hxx"
/// Boundary condition at the wall in Y
///
/// This is a collective component, because it couples all charged species
///
/// These are based on
/// "Boundary conditions for the multi-ion magnetized plasma-wall transition"
/// by D.Tskhakaya, S.Kuhn. JNM 337-339 (2005), 405-409
///
/// Notes:
/// - The approximation used here is for ions having similar
/// gyro-orbit sizes
/// - No boundary condition is applied to neutral species
/// - Boundary conditions are applied to field-aligned fields
/// using to/fromFieldAligned
///
struct SheathBoundary : public Component {
/// # Input options
/// - <name> e.g. "sheath_boundary"
/// - lower_y Boundary on lower y?
/// - upper_y Boundary on upper y?
/// - wall_potential Voltage of the wall [Volts]
/// - floor_potential Apply floor to sheath potential?
/// - secondary_electron_coef Effective secondary electron emission coefficient
/// - sin_alpha Sine of the angle between magnetic field line and wall surface (0 to 1)
/// - always_set_phi Always set phi field? Default is to only modify if already set
SheathBoundary(std::string name, Options &options, Solver *);
///
/// # Inputs
/// - species
/// - e
/// - density
/// - temperature
/// - pressure Optional
/// - velocity Optional
/// - mass Optional
/// - adiabatic Optional. Ratio of specific heats, default 5/3.
/// - <ions> if charge is set (i.e. not neutrals)
/// - charge
/// - mass
/// - density
/// - temperature
/// - pressure Optional
/// - velocity Optional. Default 0
/// - momentum Optional. Default mass * density * velocity
/// - adiabatic Optional. Ratio of specific heats, default 5/3.
/// - fields
/// - phi Optional. If not set, calculated at boundary (see note below)
///
/// # Outputs
/// - species
/// - e
/// - density Sets boundary
/// - temperature Sets boundary
/// - velocity Sets boundary
/// - energy_source
/// - <ions>
/// - density Sets boundary
/// - temperature Sets boundary
/// - velocity Sets boundary
/// - momentum Sets boundary
/// - energy_source
/// - fields
/// - phi Sets boundary
///
/// If the field phi is set, then this is used in the boundary condition.
/// If not set, phi at the boundary is calculated and stored in the state.
/// Note that phi in the domain will not be set, so will be invalid data.
///
///
void transform(Options &state) override;
private:
BoutReal Ge; // Secondary electron emission coefficient
BoutReal sin_alpha; // sin of angle between magnetic field and wall.
bool lower_y; // Boundary on lower y?
bool upper_y; // Boundary on upper y?
bool always_set_phi; ///< Set phi field?
Field3D wall_potential; ///< Voltage at the wall. Normalised units.
bool floor_potential; ///< Apply floor to sheath potential?
};
namespace {
RegisterComponent<SheathBoundary>
registercomponentsheathboundary("sheath_boundary");
}
#endif // SHEATH_BOUNDARY_H
| 3,317
|
C++
|
.h
| 88
| 35.136364
| 106
| 0.631137
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,270
|
temperature_feedback.hxx
|
bendudson_hermes-3/include/temperature_feedback.hxx
|
#pragma once
#ifndef temperature_feedback_H
#define temperature_feedback_H
#include "component.hxx"
#include <bout/constants.hxx>
/// Adds a time-varying temperature source, depending on the difference
/// between the upstream temperature at y=0 and the specified value
struct TemperatureFeedback : public Component {
/// Inputs
/// - <name> (e.g. "d+")
/// - temperature_setpoint Desired temperature in eV
/// - control_target_temperature Adjust the pressure source to match the upstream (if false) or target (if true) temperature
/// - temperature_controller_p Feedback proportional to error
/// - temperature_controller_i Feedback proportional to error integral
/// - temperature_integral_positive Force integral term to be positive? (default: false)
/// - temperature_source_positive Force temperature source to be positive? (default: true)
/// - diagnose Output diagnostic information?
///
/// - T<name> (e.g. "Td+")
/// - source_shape The initial source that is scaled by a time-varying factor
///
TemperatureFeedback(std::string name, Options& alloptions, Solver*) : name(name) {
Options& options = alloptions[name];
const auto& units = alloptions["units"];
BoutReal Tnorm = get<BoutReal>(units["eV"]);
BoutReal Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
BoutReal Omega_ci = 1. / get<BoutReal>(units["seconds"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
BoutReal SPnorm = Pnorm * Omega_ci; // Pressure-source normalisation [Pa/s] or [W/m^3] if converted to energy
temperature_setpoint =
options["temperature_setpoint"].doc("Desired temperature in eV, upstream (y=0) unless control_target_temperature=true").as<BoutReal>()
/ Tnorm;
control_target_temperature = options["control_target_temperature"]
.doc("Adjust the pressure source to match the upstream (if false) or target (if true) temperature")
.withDefault<bool>(false);
temperature_controller_p = options["temperature_controller_p"]
.doc("Feedback controller proportional (p) parameter")
.withDefault(1e-2);
temperature_controller_i = options["temperature_controller_i"]
.doc("Feedback controller integral (i) parameter")
.withDefault(1e-3);
temperature_integral_positive = options["temperature_integral_positive"]
.doc("Force integral term to be positive?")
.withDefault<bool>(false);
temperature_source_positive = options["temperature_source_positive"]
.doc("Force source to be positive?")
.withDefault<bool>(true);
species_list = strsplit(options["species_for_temperature_feedback"]
.doc("Comma-separated list of species to apply the PI-controlled source to")
.as<std::string>(),
',');
scaling_factors_list = strsplit(options["scaling_factors_for_temperature_feedback"]
.doc("Comma-separated list of scaling factors to apply to the PI-controlled source, 1 for each species")
.as<std::string>(),
',');
if (species_list.size() != scaling_factors_list.size()) {
throw BoutException("TemperatureFeedback: species_list length doesn't match scaling_factors length. Need 1 scaling factor per species.");
}
// NOTE: temperature_error_integral should be set from the restart file here.
// There doesn't seem to be a way to get the restart Options,
// so for now this is set in restartVars
// Source shape the same as used in EvolvePressure
source_shape =
(alloptions[std::string("P") + name]["source_shape"]
.doc("Source term in ddt(P" + name + std::string("). Units [Pa/s], note P = 2/3 E."))
.withDefault(Field3D(0.0))
) / (SPnorm);
diagnose = options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
}
/// Inputs
/// - <name>
/// - temperature
///
/// Outputs
///
/// - <name>
/// - temperature_source
///
void transform(Options& state) override;
void outputVars(Options& state) override {
AUTO_TRACE();
if (diagnose) {
// Normalisations
auto Tnorm = get<BoutReal>(state["Tnorm"]);
auto Omega_ci = get<BoutReal>(state["Omega_ci"]);
auto Nnorm = get<BoutReal>(state["Nnorm"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
BoutReal SPnorm = Pnorm * Omega_ci; // Pressure-source normalisation [Pa/s] or [W/m^3] if converted to energy
// Shape is not time-dependent and has units of [Pa s-1]
set_with_attrs(
state[std::string("temperature_feedback_src_shape_") + name], source_shape,
{{"units", "Pa / s"},
{"conversion", SPnorm},
{"long_name", name + " temperature source shape"},
{"source", "temperature_feedback"}});
// The source multiplier is time-dependent, but dimensionless
// because all the units are attached to the shape
set_with_attrs(state[std::string("temperature_feedback_src_mult_") + name],
source_multiplier,
{{"time_dimension", "t"},
{"long_name", name + " temperature source multiplier"},
{"source", "temperature_feedback"}});
set_with_attrs(state[std::string("SP") + name + std::string("_feedback")], source_shape * source_multiplier,
{{"time_dimension", "t"},
{"units", "Pa / s"},
{"conversion", SPnorm},
{"standard_name", "temperature source"},
{"long_name", name + "upstream temperature feedback controller source"},
{"source", "temperature_feedback"}});
// Save proportional and integral component of source for diagnostics/tuning
// Multiplier = proportional term + integral term
set_with_attrs(
state[std::string("temperature_feedback_src_p_") + name], proportional_term,
{{"time_dimension", "t"},
{"long_name", name + " proportional feedback term"},
{"source", "temperature_feedback"}});
set_with_attrs(
state[std::string("temperature_feedback_src_i_") + name], integral_term,
{{"time_dimension", "t"},
{"long_name", name + " integral feedback term"},
{"source", "temperature_feedback"}});
}
}
void restartVars(Options& state) override {
AUTO_TRACE();
// NOTE: This is a hack because we know that the loaded restart file
// is passed into restartVars in PhysicsModel::postInit
// The restart value should be used in init() rather than here
static bool first = true;
if (first and state.isSet(name + "_temperature_error_integral")) {
first = false;
temperature_error_integral = state[name + "_temperature_error_integral"].as<BoutReal>();
}
// Save the temperature error integral
set_with_attrs(state[name + "_temperature_error_integral"], temperature_error_integral,
{{"long_name", name + " temperature error integral"},
{"source", "temperature_feedback"}});
}
private:
std::string name; ///< The species name
std::list<std::string> species_list; ///< Which species to apply the factor to
std::list<std::string> scaling_factors_list; ///< Factor to apply
BoutReal temperature_setpoint; ///< Normalised setpoint temperature
BoutReal temperature_controller_p, temperature_controller_i; ///< PI controller parameters
BoutReal error;
BoutReal temperature_error_integral{0.0}; ///< Time integral of the error
bool control_target_temperature; ///<Adjust the pressure source to match the upstream (if false) or target (if true) temperature
bool temperature_integral_positive; ///< Force integral term to be positive?
bool temperature_source_positive; ///< Force source to be positive?
// Terms used in Trapezium rule integration of error
BoutReal temperature_error_lasttime{-1.0};
BoutReal temperature_error_last{0.0};
Field3D source_shape; ///< This shape source is scaled up and down
BoutReal source_multiplier; ///< Factor to multiply source
BoutReal proportional_term, integral_term; ///< Components of resulting source for diagnostics
bool diagnose; ///< Output diagnostic information?
};
namespace {
RegisterComponent<TemperatureFeedback> register_uts("temperature_feedback");
}
#endif // temperature_feedback_H
| 8,967
|
C++
|
.h
| 163
| 45.478528
| 143
| 0.627899
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,271
|
collisions.hxx
|
bendudson_hermes-3/include/collisions.hxx
|
#pragma once
#ifndef COLLISIONS_H
#define COLLISIONS_H
#include <bout/field3d.hxx>
#include "component.hxx"
/// Calculates the collision rate of each species
/// with all other species
///
/// Important: Be careful when including both ion_neutral collisions
/// and reactions such as charge exchange, since that may
/// result in double counting. Similarly for
/// electron_neutral collisions and ionization reactions.
///
struct Collisions : public Component {
///
/// @param alloptions Settings, which should include:
/// - units
/// - eV
/// - inv_meters_cubed
/// - meters
/// - seconds
///
/// The following boolean options under alloptions[name] control
/// which collisions are calculated:
///
/// - electron_electron
/// - electron_ion
/// - electron_neutral
/// - ion_ion
/// - ion_neutral
/// - neutral_neutral
///
/// There are also switches for other terms:
///
/// - frictional_heating Include R dot v heating term as energy source? (includes Ohmic heating)
///
Collisions(std::string name, Options& alloptions, Solver*);
void transform(Options &state) override;
/// Add extra fields for output, or set attributes e.g docstrings
void outputVars(Options &state) override;
private:
BoutReal Tnorm; // Temperature normalisation [eV]
BoutReal Nnorm; // Density normalisation [m^-3]
BoutReal rho_s0; // Length normalisation [m]
BoutReal Omega_ci; // Frequency normalisation [s^-1]
/// Which types of collisions to include?
bool electron_electron, electron_ion, electron_neutral, ion_ion, ion_neutral,
neutral_neutral;
/// Include frictional heating term?
bool frictional_heating;
BoutReal ei_multiplier; // Arbitrary user-set multiplier on electron-ion collisions
/// Calculated collision rates saved for post-processing and use by other components
/// Saved in options, the BOUT++ dictionary-like object
Options collision_rates;
/// Save more diagnostics?
bool diagnose;
/// Update collision frequencies, momentum and energy exchange
/// nu_12 normalised frequency
/// momentum_coefficient Leading coefficient on parallel friction
/// e.g 0.51 for electron-ion with Zi=1
void collide(Options &species1, Options &species2, const Field3D &nu_12, BoutReal momentum_coefficient);
};
namespace {
RegisterComponent<Collisions> registercomponentcollisions("collisions");
}
#endif // COLLISIONS_H
| 2,512
|
C++
|
.h
| 66
| 35.378788
| 106
| 0.706414
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,272
|
integrate.hxx
|
bendudson_hermes-3/include/integrate.hxx
|
#pragma once
#ifndef INTEGRATE_H
#define INTEGRATE_H
#include <functional>
#include <bout/field3d.hxx>
#include <bout/coordinates.hxx>
#include <bout/fv_ops.hxx>
#include "../include/hermes_build_config.hxx"
/// Get the first argument from a parameter pack
template <typename Head, typename... Tail>
auto firstArg(const Head &head, Tail... ) {
return head;
}
/// Return the value at the left of a cell,
/// given cell centre values at this cell and two neighbours
template <typename CellEdges>
BoutReal cellLeft(BoutReal c, BoutReal m, BoutReal p) {
CellEdges cellboundary;
FV::Stencil1D s {.c = c, .m = m, .p = p};
cellboundary(s);
return s.L;
}
/// Return the value at the right of a cell,
/// given cell centre values at this cell and two neighbours
template <typename CellEdges>
BoutReal cellRight(BoutReal c, BoutReal m, BoutReal p) {
CellEdges cellboundary;
FV::Stencil1D s {.c = c, .m = m, .p = p};
cellboundary(s);
return s.R;
}
/// Take a function of BoutReals, and a region. Return
/// a function which takes fields (e.g. Field2D, Field3D),
/// and for every cell in the region evaluates the function
/// at quadrature points with weights.
/// These weights sum to 1, resulting in volume averaged values.
///
/// Uses a limiter to calculate values at cell edges. This is
/// needed so that as Ne goes to zero in a cell then atomic
/// rates also go to zero.
///
/// Example
/// Field3D Ne = ..., Te = ...;
///
/// Field3D result = cellAverage(
/// [](BoutReal Ne, BoutReal Te) {return Ne*Te;} // The function to evaluate
/// Ne.getRegion("RGN_NOBNDRY") // The region to iterate over
/// )(Ne, Te); // The input fields
///
/// Note that the order of the arguments to the lambda function
/// is the same as the input fields.
///
template <typename CellEdges = hermes::Limiter, typename Function, typename RegionType>
auto cellAverage(Function func, const RegionType ®ion) {
// Note: Capture by value or func and region go out of scope
return [=](const auto &... args) {
// Use the first argument to set the result mesh etc.
Field3D result{emptyFrom(firstArg(args...))};
result.allocate();
// Get the coordinate Jacobian
auto J = result.getCoordinates()->J;
BOUT_FOR(i, region) {
// Offset indices
auto yp = i.yp();
auto ym = i.ym();
auto Ji = J[i];
// Integrate in Y using Simpson's rule
// Using limiter to calculate cell edge values
result[i] =
4. / 6 * func((args[i])...) +
(Ji + J[ym]) / (12. * Ji) * func(cellLeft<CellEdges>(args[i], args[ym], args[yp])...) +
(Ji + J[yp]) / (12. * Ji) * func(cellRight<CellEdges>(args[i], args[ym], args[yp])...);
}
return result;
};
}
#endif // INTEGRATE_H
| 2,793
|
C++
|
.h
| 77
| 33.519481
| 95
| 0.664695
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,273
|
fixed_fraction_radiation.hxx
|
bendudson_hermes-3/include/fixed_fraction_radiation.hxx
|
#pragma once
#ifndef FIXED_FRACTION_RADIATION_H
#define FIXED_FRACTION_RADIATION_H
#include <bout/constants.hxx>
#include "component.hxx"
namespace {
/// Carbon in coronal equilibrium
/// From I.H.Hutchinson Nucl. Fusion 34 (10) 1337 - 1348 (1994)
///
/// Input: Electron temperature [eV]
/// Output: Radiation cooling curve [Wm^3]
/// (multiply by Ne * Ni to get W/m^3)
struct HutchinsonCarbon {
BoutReal curve(BoutReal Te) {
if (Te < 0.0) {
return 0.0;
}
return 2e-31*pow(Te/10., 3) / (1. + pow(Te/10., 4.5));
}
};
/// Below fits are from ADAS data by Mike Kryjak 03/06/2023 and supersede above deprecated fits
/// Data generated using radas https://github.com/cfs-energy/radas
/// Chose N = 1E20m-3 and tau = 0.5ms based on Moulton, 2021 (DOI: 10.1088/1741-4326/abe4b2)
/// Those values are applicable in the ITER scrape-off layer but may not be valid in other conditions.
/// The fits are 10 coefficient polynomials fitted in log-log space like the AMJUEL database in EIRENE
/// Argon
struct Argon_adas{
BoutReal curve(BoutReal Te) {
BoutReal logT = log(Te);
BoutReal log_out = 0;
if (Te >= 1.5 and Te <= 1500) {
log_out = log_out
-8.45410692e+01 * pow(logT, 0)
+1.57727040e+01 * pow(logT, 1)
-1.54264860e+01 * pow(logT, 2)
+1.49409902e+01 * pow(logT, 3)
-1.04815113e+01 * pow(logT, 4)
+5.00924595e+00 * pow(logT, 5)
-1.60029106e+00 * pow(logT, 6)
+3.29455609e-01 * pow(logT, 7)
-4.14036827e-02 * pow(logT, 8)
+2.87063206e-03 * pow(logT, 9)
-8.38888002e-05 * pow(logT, 10);
return exp(log_out);
} else if (Te < 1.5) {
return 1.95353412e-35;
} else {
return 1.22649600e-32;
}
}
};
/// Neon
struct Neon_adas{
BoutReal curve(BoutReal Te) {
BoutReal logT = log(Te);
BoutReal log_out = 0;
if (Te >= 2 and Te <= 1000) {
log_out = log_out
-8.21475117e+01 * pow(logT, 0)
+1.28929854e+01 * pow(logT, 1)
-4.74266289e+01 * pow(logT, 2)
+7.45222324e+01 * pow(logT, 3)
-5.75710722e+01 * pow(logT, 4)
+2.57375965e+01 * pow(logT, 5)
-7.12758563e+00 * pow(logT, 6)
+1.24287546e+00 * pow(logT, 7)
-1.32943407e-01 * pow(logT, 8)
+7.97368445e-03 * pow(logT, 9)
-2.05487897e-04 * pow(logT, 10);
return exp(log_out);
} else if (Te < 2) {
return 6.35304113e-36;
} else {
return 1.17894628e-32;
}
}
};
/// Nitrogen
struct Nitrogen_adas{
BoutReal curve(BoutReal Te) {
BoutReal logT = log(Te);
BoutReal log_out = 0;
if (Te >= 2 and Te <= 500) {
log_out = log_out
-5.01649969e+01 * pow(logT, 0)
-1.35749724e+02 * pow(logT, 1)
+2.73509608e+02 * pow(logT, 2)
-2.92109992e+02 * pow(logT, 3)
+1.90120639e+02 * pow(logT, 4)
-7.95164871e+01 * pow(logT, 5)
+2.17762218e+01 * pow(logT, 6)
-3.88334992e+00 * pow(logT, 7)
+4.34730098e-01 * pow(logT, 8)
-2.77683605e-02 * pow(logT, 9)
+7.72720422e-04 * pow(logT, 10);
return exp(log_out);
} else if (Te < 2) {
return 4.34835380e-34;
} else {
return 8.11096182e-33;
}
}
};
/// Carbon
struct Carbon_adas{
BoutReal curve(BoutReal Te) {
BoutReal logT = log(Te);
BoutReal log_out = 0;
if (Te >= 1 and Te <= 500) {
log_out = log_out
-7.87837896e+01 * pow(logT, 0)
+1.55326376e+00 * pow(logT, 1)
+1.65898194e+01 * pow(logT, 2)
-3.23804546e+01 * pow(logT, 3)
+3.12784663e+01 * pow(logT, 4)
-1.74826039e+01 * pow(logT, 5)
+5.91393245e+00 * pow(logT, 6)
-1.22974105e+00 * pow(logT, 7)
+1.54004499e-01 * pow(logT, 8)
-1.06797106e-02 * pow(logT, 9)
+3.15657594e-04 * pow(logT, 10);
return exp(log_out);
} else if (Te < 1) {
return 6.00623928e-35;
} else {
return 4.53057707e-33;
}
}
};
/// Argon simplified 1
/// Based on the ADAS curve above but simplified as a linear interpolation
/// between the LHS minimum, peak, bottom of RHS slope and final value at Te = 3000eV.
/// RHS shoulder is preserved.
/// Helpful for studying impact of cooling curve nonlinearity
struct Argon_simplified1{
BoutReal curve(BoutReal Te) {
if (Te < 0.52) {
return 0;
} else if (Te >= 0.52 and Te < 2.50) {
return (1.953534e-35*(2.50 - Te) + 6.053680e-34*(Te - 0.52)) / (2.50 - 0.52);
} else if (Te >= 2.50 and Te < 19.72) {
return (6.053680e-34*(19.72 - Te) + 2.175237e-31*(Te - 2.50)) / (19.72 - 2.50);
} else if (Te >= 19.72 and Te < 59.98) {
return (2.175237e-31*(59.98 - Te) + 4.190918e-32*(Te - 19.72)) / (59.98 - 19.72);
} else if (Te >= 59.98 and Te < 3000.00) {
return (4.190918e-32*(3000.00 - Te) + 1.226496e-32*(Te - 59.98)) / (3000.00 - 59.98);
} else {
return 1.226496e-32;
}
}
};
/// Argon simplified 2
/// Based on the ADAS curve above but simplified as a linear interpolation
/// between the LHS minimum, peak, and the bottom of RHS slope.
/// RHS shoulder is eliminated, radiation becomes 0 at 60eV.
/// Helpful for studying impact of cooling curve nonlinearity
struct Argon_simplified2{
BoutReal curve(BoutReal Te) {
if (Te < 0.52) {
return 0;
} else if (Te >= 0.52 and Te < 2.50) {
return (1.953534e-35*(2.50 - Te) + 6.053680e-34*(Te - 0.52)) / (2.50 - 0.52);
} else if (Te >= 2.50 and Te < 19.72) {
return (6.053680e-34*(19.72 - Te) + 2.175237e-31*(Te - 2.50)) / (19.72 - 2.50);
} else if (Te >= 19.72 and Te < 59.98) {
return (2.175237e-31*(59.98 - Te) + 0.000000e+00*(Te - 19.72)) / (59.98 - 19.72);
} else {
return 0.0;
}
}
};
/// Argon simplified 3
/// Based on the ADAS curve above but simplified as a linear interpolation
/// between the LHS minimum, peak, and the bottom of RHS slope.
/// RHS shoulder is eliminated, radiation becomes 0 at 60eV.
/// LHS / RHS asymmetry is eliminated.
/// Helpful for studying impact of cooling curve nonlinearity
struct Argon_simplified3{
BoutReal curve(BoutReal Te) {
if (Te < 0.52) {
return 0;
} else if (Te >= 0.52 and Te < 2.50) {
return (1.953534e-35*(2.50 - Te) + 6.053680e-34*(Te - 0.52)) / (2.50 - 0.52);
} else if (Te >= 2.50 and Te < 19.72) {
return (6.053680e-34*(19.72 - Te) + 2.175237e-31*(Te - 2.50)) / (19.72 - 2.50);
} else if (Te >= 19.72 and Te < 38.02) {
return (2.175237e-31*(38.02 - Te) + 0.000000e+00*(Te - 19.72)) / (38.02 - 19.72);
} else {
return 0.0;
};
}
};
/// Krypton
///
/// Radas version d50d6c3b (Oct 27, 2023)
/// Using N = 1E20m-3 and tau = 0.5ms
struct Krypton_adas {
BoutReal curve(BoutReal Te) {
if (Te >= 2 and Te <= 1500) {
BoutReal logT = log(Te);
BoutReal log_out =
-2.97405917e+01 * pow(logT, 0)
-2.25443986e+02 * pow(logT, 1)
+4.08713640e+02 * pow(logT, 2)
-3.86540549e+02 * pow(logT, 3)
+2.19566710e+02 * pow(logT, 4)
-7.93264990e+01 * pow(logT, 5)
+1.86185949e+01 * pow(logT, 6)
-2.82487288e+00 * pow(logT, 7)
+2.67070863e-01 * pow(logT, 8)
-1.43001273e-02 * pow(logT, 9)
+3.31179737e-04 * pow(logT, 10);
return exp(log_out);
} else if (Te < 2) {
return 8.01651285e-35;
} else {
return 6.17035971e-32;
}
}
};
/// Xenon
///
/// Radas version d50d6c3b (Oct 27, 2023)
/// Using N = 1E20m-3 and tau = 0.5ms
///
/// Note: Requires more than 10 coefficients to capture multiple
/// radiation peaks.
struct Xenon_adas {
BoutReal curve(BoutReal Te) {
if (Te >= 2 and Te <= 1300) {
BoutReal logT = log(Te);
BoutReal log_out =
+3.80572137e+02 * pow(logT, 0)
-3.05839745e+03 * pow(logT, 1)
+9.01104594e+03 * pow(logT, 2)
-1.55327244e+04 * pow(logT, 3)
+1.75819719e+04 * pow(logT, 4)
-1.38754866e+04 * pow(logT, 5)
+7.90608220e+03 * pow(logT, 6)
-3.32041900e+03 * pow(logT, 7)
+1.03912363e+03 * pow(logT, 8)
-2.42980719e+02 * pow(logT, 9)
+4.22211209e+01 * pow(logT, 10)
-5.36813849e+00 * pow(logT, 11)
+4.84652106e-01 * pow(logT, 12)
-2.94023979e-02 * pow(logT, 13)
+1.07416308e-03 * pow(logT, 14)
-1.78510623e-05 * pow(logT, 15);
return exp(log_out);
} else if (Te < 2) {
return 1.87187135e-33;
} else {
return 1.29785519e-31;
}
}
};
/// Tungsten
///
/// Radas version d50d6c3b (Oct 27, 2023)
/// Using N = 1E20m-3 and tau = 0.5ms
struct Tungsten_adas {
BoutReal curve(BoutReal Te) {
if (Te >= 1.25 and Te <= 1500) {
BoutReal logT = log(Te);
BoutReal log_out =
-7.24602210e+01 * pow(logT, 0)
-2.17524363e+01 * pow(logT, 1)
+1.90745408e+02 * pow(logT, 2)
-7.57571067e+02 * pow(logT, 3)
+1.84119395e+03 * pow(logT, 4)
-2.99842204e+03 * pow(logT, 5)
+3.40395125e+03 * pow(logT, 6)
-2.76328977e+03 * pow(logT, 7)
+1.63368844e+03 * pow(logT, 8)
-7.11076320e+02 * pow(logT, 9)
+2.28027010e+02 * pow(logT, 10)
-5.30145974e+01 * pow(logT, 11)
+8.46066686e+00 * pow(logT, 12)
-7.54960450e-01 * pow(logT, 13)
-1.61054010e-02 * pow(logT, 14)
+1.65520152e-02 * pow(logT, 15)
-2.70054697e-03 * pow(logT, 16)
+2.50286873e-04 * pow(logT, 17)
-1.43319310e-05 * pow(logT, 18)
+4.75258630e-07 * pow(logT, 19)
-7.03012454e-09 * pow(logT, 20);
return exp(log_out);
} else if (Te < 1.25) {
return 2.09814651e-32;
} else {
return 1.85078767e-31;
}
}
};
}
/// Set ion densities from electron densities
///
template <typename CoolingCurve>
struct FixedFractionRadiation : public Component {
/// Inputs
/// - <name>
/// - fraction
FixedFractionRadiation(std::string name, Options &alloptions, Solver *UNUSED(solver)) : name(name) {
auto& options = alloptions[name];
fraction = options["fraction"]
.doc("Impurity ion density as fraction of electron density")
.withDefault(0.0);
diagnose = options["diagnose"]
.doc("Output radiation diagnostic?")
.withDefault<bool>(false);
radiation_multiplier = options["R_multiplier"]
.doc("Scale the radiation rate by this factor")
.withDefault<BoutReal>(1.0);
// Get the units
auto& units = alloptions["units"];
Tnorm = get<BoutReal>(units["eV"]);
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
FreqNorm = 1. / get<BoutReal>(units["seconds"]);
}
/// Required inputs
///
/// - species
/// - e
/// - density
/// - temperature
///
/// Sets the electron energy loss
///
/// - species
/// - e
/// - energy_source
///
void transform(Options &state) override {
auto& electrons = state["species"]["e"];
// Don't need boundary cells
const Field3D Ne = GET_NOBOUNDARY(Field3D, electrons["density"]);
const Field3D Te = GET_NOBOUNDARY(Field3D, electrons["temperature"]);
radiation = cellAverage(
[&](BoutReal ne, BoutReal te) {
if (ne < 0.0 or te < 0.0) {
return 0.0;
}
// Fixed fraction ions
const BoutReal ni = fraction * ne;
// cooling in Wm^3 so normalise.
// Note factor of qe due to Watts rather than eV
return ne * ni * cooling.curve(te * Tnorm) * radiation_multiplier *
Nnorm / (SI::qe * Tnorm * FreqNorm);
},
Ne.getRegion("RGN_NOBNDRY"))(Ne, Te);
// Remove radiation from the electron energy source
subtract(electrons["energy_source"], radiation);
}
void outputVars(Options& state) override {
AUTO_TRACE();
if (diagnose) {
set_with_attrs(state[std::string("R") + name], -radiation,
{{"time_dimension", "t"},
{"units", "W / m^3"},
{"conversion", SI::qe * Tnorm * Nnorm * FreqNorm},
{"long_name", std::string("Radiation cooling ") + name},
{"source", "fixed_fraction_radiation"}});
}
}
private:
std::string name;
CoolingCurve cooling; ///< The cooling curve L(T) -> Wm^3
BoutReal fraction; ///< Fixed fraction
bool diagnose; ///< Output radiation diagnostic?
BoutReal radiation_multiplier; ///< Scale the radiation rate by this factor
Field3D radiation; ///< For output diagnostic
// Normalisations
BoutReal Tnorm, Nnorm, FreqNorm;
};
namespace {
RegisterComponent<FixedFractionRadiation<HutchinsonCarbon>>
registercomponentfixedfractionhutchinsonbcarbon("fixed_fraction_hutchinson_carbon");
RegisterComponent<FixedFractionRadiation<Carbon_adas>>
registercomponentfixedfractioncarbon("fixed_fraction_carbon");
RegisterComponent<FixedFractionRadiation<Nitrogen_adas>>
registercomponentfixedfractionnitrogen("fixed_fraction_nitrogen");
RegisterComponent<FixedFractionRadiation<Neon_adas>>
registercomponentfixedfractionneon("fixed_fraction_neon");
RegisterComponent<FixedFractionRadiation<Argon_adas>>
registercomponentfixedfractionargon("fixed_fraction_argon");
RegisterComponent<FixedFractionRadiation<Argon_simplified1>>
registercomponentfixedfractionargonsimplified1("fixed_fraction_argon_simplified1");
RegisterComponent<FixedFractionRadiation<Argon_simplified2>>
registercomponentfixedfractionargonsimplified2("fixed_fraction_argon_simplified2");
RegisterComponent<FixedFractionRadiation<Argon_simplified3>>
registercomponentfixedfractionargonsimplified3("fixed_fraction_argon_simplified3");
RegisterComponent<FixedFractionRadiation<Krypton_adas>>
registercomponentfixedfractionkrypton("fixed_fraction_krypton");
RegisterComponent<FixedFractionRadiation<Xenon_adas>>
registercomponentfixedfractionxenon("fixed_fraction_xenon");
RegisterComponent<FixedFractionRadiation<Tungsten_adas>>
registercomponentfixedfractiontungsten("fixed_fraction_tungsten");
}
#endif // FIXED_FRACTION_IONS_H
| 14,836
|
C++
|
.h
| 399
| 29.842105
| 104
| 0.587706
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,274
|
adas_lithium.hxx
|
bendudson_hermes-3/include/adas_lithium.hxx
|
#pragma once
#ifndef ADAS_LITHIUM_H
#define ADAS_LITHIUM_H
#include "adas_reaction.hxx"
#include <array>
#include <initializer_list>
/// Ionisation energies in eV
/// from https://www.webelements.com/lithium/atoms.html
/// Conversion 1 kJ mol‑1 = 1.0364e-2 eV
/// These are added (removed) from the electron energy during recombination (ionisation)
constexpr std::array<BoutReal, 3> lithium_ionisation_energy{
5.39, 75.64, 122.45};
/// The name of the species. This initializer list can be passed to a string
/// constructor, or used to index into an Options tree.
///
/// li, li+, li+2, ...
///
/// Special cases for level=0, 1 and 3
///
/// @tparam level The ionisation level: 0 is neutral, 3 is fully stripped.
template <int level>
constexpr std::initializer_list<char> lithium_species_name{'l', 'i', '+', '0' + level};
template <>
constexpr std::initializer_list<char> lithium_species_name<3>{'l', 'i', '+', '3'};
template <>
constexpr std::initializer_list<char> lithium_species_name<1>{'l', 'i', '+'};
template <>
constexpr std::initializer_list<char> lithium_species_name<0>{'l', 'i'};
/// ADAS effective ionisation (ADF11)
///
/// @tparam level The ionisation level of the ion on the left of the reaction
template <int level>
struct ADASLithiumIonisation : public OpenADAS {
ADASLithiumIonisation(std::string, Options& alloptions, Solver*)
: OpenADAS(alloptions["units"], "scd96_li.json", "plt96_li.json", level,
-lithium_ionisation_energy[level]) {}
void transform(Options& state) override {
calculate_rates(
state["species"]["e"], // Electrons
state["species"][lithium_species_name<level>], // From this ionisation state
state["species"][lithium_species_name<level + 1>] // To this state
);
}
};
/////////////////////////////////////////////////
/// ADAS effective recombination coefficients (ADF11)
///
/// @tparam level The ionisation level of the ion on the right of the reaction
template <int level>
struct ADASLithiumRecombination : public OpenADAS {
/// @param alloptions The top-level options. Only uses the ["units"] subsection.
ADASLithiumRecombination(std::string, Options& alloptions, Solver*)
: OpenADAS(alloptions["units"], "acd96_li.json", "prb96_li.json", level,
lithium_ionisation_energy[level]) {}
void transform(Options& state) override {
calculate_rates(
state["species"]["e"], // Electrons
state["species"][lithium_species_name<level + 1>], // From this ionisation state
state["species"][lithium_species_name<level>] // To this state
);
}
};
/// @tparam level The ionisation level of the ion on the right of the reaction
/// @tparam Hisotope The hydrogen isotope ('h', 'd' or 't')
template <int level, char Hisotope>
struct ADASLithiumCX : public OpenADASChargeExchange {
/// @param alloptions The top-level options. Only uses the ["units"] subsection.
ADASLithiumCX(std::string, Options& alloptions, Solver*)
: OpenADASChargeExchange(alloptions["units"], "ccd89_li.json", level) {}
void transform(Options& state) override {
Options& species = state["species"];
calculate_rates(
species["e"], // Electrons
species[lithium_species_name<level + 1>], // From this ionisation state
species[{Hisotope}], // and this neutral hydrogen atom
species[lithium_species_name<level>], // To this state
species[{Hisotope, '+'}] // and this hydrogen ion
);
}
};
namespace {
// Ionisation by electron-impact
RegisterComponent<ADASLithiumIonisation<0>> register_ionisation_li0("li + e -> li+ + 2e");
RegisterComponent<ADASLithiumIonisation<1>> register_ionisation_li1("li+ + e -> li+2 + 2e");
RegisterComponent<ADASLithiumIonisation<2>> register_ionisation_li2("li+2 + e -> li+3 + 2e");
// Recombination
RegisterComponent<ADASLithiumRecombination<0>> register_recombination_li0("li+ + e -> li");
RegisterComponent<ADASLithiumRecombination<1>> register_recombination_li1("li+2 + e -> li+");
RegisterComponent<ADASLithiumRecombination<2>> register_recombination_li2("li+3 + e -> li+2");
// Charge exchange
RegisterComponent<ADASLithiumCX<0, 'h'>> register_cx_li0h("li+ + h -> li + h+");
RegisterComponent<ADASLithiumCX<1, 'h'>> register_cx_li1h("li+2 + h -> li+ + h+");
RegisterComponent<ADASLithiumCX<2, 'h'>> register_cx_li2h("li+3 + h -> li+2 + h+");
RegisterComponent<ADASLithiumCX<0, 'd'>> register_cx_li0d("li+ + d -> li + d+");
RegisterComponent<ADASLithiumCX<1, 'd'>> register_cx_li1d("li+2 + d -> li+ + d+");
RegisterComponent<ADASLithiumCX<2, 'd'>> register_cx_li2d("li+3 + d -> li+2 + d+");
RegisterComponent<ADASLithiumCX<0, 't'>> register_cx_li0t("li+ + t -> li + t+");
RegisterComponent<ADASLithiumCX<1, 't'>> register_cx_li1t("li+2 + t -> li+ + t+");
RegisterComponent<ADASLithiumCX<2, 't'>> register_cx_li2t("li+3 + t -> li+2 + t+");
} // namespace
#endif // ADAS_LITHIUM_H
| 5,050
|
C++
|
.h
| 101
| 46.881188
| 94
| 0.672956
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,275
|
diamagnetic_drift.hxx
|
bendudson_hermes-3/include/diamagnetic_drift.hxx
|
#pragma once
#ifndef DIAMAGNETIC_DRIFT_H
#define DIAMAGNETIC_DRIFT_H
#include "component.hxx"
/// Calculate diamagnetic flows
struct DiamagneticDrift : public Component {
DiamagneticDrift(std::string name, Options &options, Solver *UNUSED(solver));
/// For every species, if it has:
/// - temperature
/// - charge
///
/// Modifies:
/// - density_source
/// - energy_source
/// - momentum_source
void transform(Options &state) override;
private:
Vector2D Curlb_B;
bool bndry_flux;
Field2D diamag_form;
};
namespace {
RegisterComponent<DiamagneticDrift> registercomponentdiamagnetic("diamagnetic_drift");
}
#endif // DIAMAGNETIC_DRIFT_H
| 675
|
C++
|
.h
| 25
| 24.6
| 86
| 0.74259
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,276
|
fixed_density.hxx
|
bendudson_hermes-3/include/fixed_density.hxx
|
#pragma once
#ifndef FIXED_DENSITY_H
#define FIXED_DENSITY_H
#include "component.hxx"
/// Set ion density to a fixed value
///
struct FixedDensity : public Component {
/// Inputs
/// - <name>
/// - AA
/// - charge
/// - density value (expression) in units of m^-3
FixedDensity(std::string name, Options& alloptions, Solver* UNUSED(solver))
: name(name) {
AUTO_TRACE();
auto& options = alloptions[name];
// Charge and mass
charge = options["charge"].doc("Particle charge. electrons = -1");
AA = options["AA"].doc("Particle atomic mass. Proton = 1");
// Normalisation of density
const BoutReal Nnorm = alloptions["units"]["inv_meters_cubed"];
// Get the density and normalise
N = options["density"].as<Field3D>() / Nnorm;
}
/// Sets in the state the density, mass and charge of the species
///
/// - species
/// - <name>
/// - AA
/// - charge
/// - density
void transform(Options& state) override {
AUTO_TRACE();
auto& species = state["species"][name];
if (charge != 0.0) { // Don't set charge for neutral species
set(species["charge"], charge);
}
set(species["AA"], AA); // Atomic mass
set(species["density"], N);
}
void outputVars(Options& state) override {
AUTO_TRACE();
auto Nnorm = get<BoutReal>(state["Nnorm"]);
// Save the density, not time dependent
set_with_attrs(state[std::string("N") + name], N,
{{"units", "m^-3"},
{"conversion", Nnorm},
{"standard_name", "density"},
{"long_name", name + " number density"},
{"species", name},
{"source", "fixed_density"}});
}
private:
std::string name; ///< Short name of species e.g "e"
BoutReal charge; ///< Species charge e.g. electron = -1
BoutReal AA; ///< Atomic mass e.g. proton = 1
Field3D N; ///< Species density (normalised)
};
namespace {
RegisterComponent<FixedDensity> registercomponentfixeddensity("fixed_density");
}
#endif // FIXED_DENSITY_H
| 2,094
|
C++
|
.h
| 62
| 28.516129
| 79
| 0.601783
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,277
|
evolve_density.hxx
|
bendudson_hermes-3/include/evolve_density.hxx
|
#pragma once
#ifndef EVOLVE_DENSITY_H
#define EVOLVE_DENSITY_H
#include "component.hxx"
/// Evolve species density in time
///
/// # Mesh inputs
///
/// N<name>_src A source of particles, per cubic meter per second.
/// This can be over-ridden by the `source` option setting.
struct EvolveDensity : public Component {
/// # Inputs
///
/// - <name>
/// - charge Particle charge e.g. hydrogen = 1
/// - AA Atomic mass number e.g. hydrogen = 1
/// - bndry_flux Allow flow through radial boundaries? Default is true.
/// - poloidal_flows Include poloidal ExB flows? Default is true.
/// - density_floor Minimum density floor. Default is 1e-5 normalised units
/// - low_n_diffuse Enhance parallel diffusion at low density? Default false
/// - hyper_z Hyper-diffusion in Z. Default off.
/// - evolve_log Evolve logarithm of density? Default false.
/// - diagnose Output additional diagnostics?
///
/// - N<name> e.g. "Ne", "Nd+"
/// - source Source of particles [/m^3/s]
/// NOTE: This overrides mesh input N<name>_src
/// - source_only_in_core Zero the source outside the closed field-line region?
/// - neumann_boundary_average_z Apply Neumann boundaries with Z average?
///
EvolveDensity(std::string name, Options &options, Solver *solver);
/// This sets in the state
/// - species
/// - <name>
/// - AA
/// - charge
/// - density
void transform(Options &state) override;
/// Calculate ddt(N).
///
/// Requires state components
/// - species
/// - <name>
/// - density
///
/// Optional components
/// - species
/// - <name>
/// - velocity If included, requires sound_speed or temperature
/// - density_source
/// - fields
/// - phi If included, ExB drift is calculated
void finally(const Options &state) override;
void outputVars(Options &state) override;
private:
std::string name; ///< Short name of species e.g "e"
BoutReal charge; ///< Species charge e.g. electron = -1
BoutReal AA; ///< Atomic mass e.g. proton = 1
Field3D N; ///< Species density (normalised, evolving)
bool bndry_flux; ///< Allow flows through boundaries?
bool poloidal_flows; ///< Include ExB flow in Y direction?
bool neumann_boundary_average_z; ///< Apply neumann boundary with Z average?
BoutReal density_floor;
bool low_n_diffuse; ///< Parallel diffusion at low density
bool low_n_diffuse_perp; ///< Perpendicular diffusion at low density
BoutReal pressure_floor; ///< When non-zero pressure is needed
bool low_p_diffuse_perp; ///< Add artificial cross-field diffusion at low pressure?
BoutReal hyper_z; ///< Hyper-diffusion in Z
bool evolve_log; ///< Evolve logarithm of density?
Field3D logN; ///< Logarithm of density (if evolving)
Field3D source, final_source; ///< External input source
Field3D Sn; ///< Total density source
bool source_only_in_core; ///< Zero source where Y is non-periodic?
bool source_time_dependent; ///< Is the input source time dependent?
BoutReal source_normalisation; ///< Normalisation factor [m^-3/s]
BoutReal time_normalisation; ///< Normalisation factor [s]
FieldGeneratorPtr source_prefactor_function;
/// Modifies the `source` member variable
void updateSource(BoutReal time);
bool diagnose; ///< Output additional diagnostics?
Field3D flow_xlow, flow_ylow; ///< Particle flow diagnostics
};
namespace {
RegisterComponent<EvolveDensity> registercomponentevolvedensity("evolve_density");
}
#endif // EVOLVE_DENSITY_H
| 3,691
|
C++
|
.h
| 86
| 40.093023
| 91
| 0.663692
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,278
|
snb_conduction.hxx
|
bendudson_hermes-3/include/snb_conduction.hxx
|
#pragma once
#ifndef SNB_CONDUCTION_H
#define SNB_CONDUCTION_H
#include "component.hxx"
#include <bout/snb.hxx>
/// Calculate electron heat flux using the Shurtz-Nicolai-Busquet (SNB) model
///
/// This component will only calculate divergence of heat flux for the
/// electron (`e`) species.
///
/// # Usage
///
/// Add as a top-level component after both electron temperature and
/// collision times have been calculated.
///
/// Important: If evolving electron pressure, disable thermal
/// conduction or that will continue to add Spitzer heat conduction.
///
/// ```
/// [hermes]
/// components = e, ..., collisions, snb_conduction
///
/// [e]
/// type = evolve_pressure, ...
/// thermal_conduction = false # For evolve_pressure
///
/// [snb_conduction]
/// diagnose = true # Saves heat flux diagnostics
/// ```
///
/// # Useful references:
///
/// * Braginskii equations by R.Fitzpatrick:
/// http://farside.ph.utexas.edu/teaching/plasma/Plasmahtml/node35.html
///
/// * J.P.Brodrick et al 2017: https://doi.org/10.1063/1.5001079 and
/// https://arxiv.org/abs/1704.08963
///
/// * Shurtz, Nicolai and Busquet 2000: https://doi.org/10.1063/1.1289512
///
struct SNBConduction : public Component {
/// Inputs
/// - <name>
/// - diagnose Saves Div_Q_SH and Div_Q_SNB
SNBConduction(std::string name, Options& alloptions, Solver*) : snb(alloptions[name]) {
AUTO_TRACE();
auto& options = alloptions[name];
diagnose = options["diagnose"]
.doc("Save additional output diagnostics")
.withDefault<bool>(false);
}
/// Inputs
/// - species
/// - e
/// - density
/// - collision_frequency
///
/// Sets
/// - species
/// - e
/// - energy_source
void transform(Options& state) override;
void outputVars(Options& state) override;
private:
bout::HeatFluxSNB snb;
Field3D Div_Q_SH, Div_Q_SNB; ///< Divergence of heat fluxes
bool diagnose; ///< Output additional diagnostics?
};
namespace {
RegisterComponent<SNBConduction> registercomponentsnbconduction("snb_conduction");
}
#endif // SNB_CONDUCTION_H
| 2,100
|
C++
|
.h
| 72
| 27.111111
| 89
| 0.682044
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,279
|
adas_carbon.hxx
|
bendudson_hermes-3/include/adas_carbon.hxx
|
#pragma once
#ifndef ADAS_CARBON_H
#define ADAS_CARBON_H
#include "adas_reaction.hxx"
#include <array>
#include <initializer_list>
/// Ionisation energies in eV
/// from https://www.webelements.com/carbon/atoms.html
/// Conversion 1 kJ mol‑1 = 1.0364e-2 eV
/// These are added (removed) from the electron energy during recombination (ionisation)
constexpr std::array<BoutReal, 6> carbon_ionisation_energy{
11.26, 24.38, 47.89, 64.49, 392.09, 489.99};
/// The name of the species. This initializer list can be passed to a string
/// constructor, or used to index into an Options tree.
///
/// c, c+, c+2, c+3, ...
///
/// Special cases for level=0, 1
///
/// @tparam level The ionisation level: 0 is neutral, 6 is fully stripped
template <int level>
constexpr std::initializer_list<char> carbon_species_name{'c', '+', '0' + level};
template <>
constexpr std::initializer_list<char> carbon_species_name<1>{'c', '+'};
template <>
constexpr std::initializer_list<char> carbon_species_name<0>{'c'};
/// ADAS effective ionisation (ADF11)
///
/// @tparam level The ionisation level of the ion on the left of the reaction
template <int level>
struct ADASCarbonIonisation : public OpenADAS {
ADASCarbonIonisation(std::string, Options& alloptions, Solver*)
: OpenADAS(alloptions["units"], "scd96_c.json", "plt96_c.json", level,
-carbon_ionisation_energy[level]) {}
void transform(Options& state) override {
calculate_rates(
state["species"]["e"], // Electrons
state["species"][carbon_species_name<level>], // From this ionisation state
state["species"][carbon_species_name<level + 1>] // To this state
);
}
};
/////////////////////////////////////////////////
/// ADAS effective recombination coefficients (ADF11)
///
/// @tparam level The ionisation level of the ion on the right of the reaction
template <int level>
struct ADASCarbonRecombination : public OpenADAS {
/// @param alloptions The top-level options. Only uses the ["units"] subsection.
ADASCarbonRecombination(std::string, Options& alloptions, Solver*)
: OpenADAS(alloptions["units"], "acd96_c.json", "prb96_c.json", level,
carbon_ionisation_energy[level]) {}
void transform(Options& state) override {
calculate_rates(
state["species"]["e"], // Electrons
state["species"][carbon_species_name<level + 1>], // From this ionisation state
state["species"][carbon_species_name<level>] // To this state
);
}
};
/// @tparam level The ionisation level of the ion on the right of the reaction
/// @tparam Hisotope The hydrogen isotope ('h', 'd' or 't')
template <int level, char Hisotope>
struct ADASCarbonCX : public OpenADASChargeExchange {
/// @param alloptions The top-level options. Only uses the ["units"] subsection.
ADASCarbonCX(std::string, Options& alloptions, Solver*)
: OpenADASChargeExchange(alloptions["units"], "ccd96_c.json", level) {}
void transform(Options& state) override {
Options& species = state["species"];
calculate_rates(
species["e"], // Electrons
species[carbon_species_name<level + 1>], // From this ionisation state
species[{Hisotope}], // and this neutral hydrogen atom
species[carbon_species_name<level>], // To this state
species[{Hisotope, '+'}] // and this hydrogen ion
);
}
};
namespace {
// Ionisation by electron-impact
RegisterComponent<ADASCarbonIonisation<0>> register_ionisation_c0("c + e -> c+ + 2e");
RegisterComponent<ADASCarbonIonisation<1>> register_ionisation_c1("c+ + e -> c+2 + 2e");
RegisterComponent<ADASCarbonIonisation<2>> register_ionisation_c2("c+2 + e -> c+3 + 2e");
RegisterComponent<ADASCarbonIonisation<3>> register_ionisation_c3("c+3 + e -> c+4 + 2e");
RegisterComponent<ADASCarbonIonisation<4>> register_ionisation_c4("c+4 + e -> c+5 + 2e");
RegisterComponent<ADASCarbonIonisation<5>> register_ionisation_c5("c+5 + e -> c+6 + 2e");
// Recombination
RegisterComponent<ADASCarbonRecombination<0>> register_recombination_c0("c+ + e -> c");
RegisterComponent<ADASCarbonRecombination<1>> register_recombination_c1("c+2 + e -> c+");
RegisterComponent<ADASCarbonRecombination<2>> register_recombination_c2("c+3 + e -> c+2");
RegisterComponent<ADASCarbonRecombination<3>> register_recombination_c3("c+4 + e -> c+3");
RegisterComponent<ADASCarbonRecombination<4>> register_recombination_c4("c+5 + e -> c+4");
RegisterComponent<ADASCarbonRecombination<5>> register_recombination_c5("c+6 + e -> c+5");
// Charge exchange
RegisterComponent<ADASCarbonCX<0, 'h'>> register_cx_c0h("c+ + h -> c + h+");
RegisterComponent<ADASCarbonCX<1, 'h'>> register_cx_c1h("c+2 + h -> c+ + h+");
RegisterComponent<ADASCarbonCX<2, 'h'>> register_cx_c2h("c+3 + h -> c+2 + h+");
RegisterComponent<ADASCarbonCX<3, 'h'>> register_cx_c3h("c+4 + h -> c+3 + h+");
RegisterComponent<ADASCarbonCX<4, 'h'>> register_cx_c4h("c+5 + h -> c+4 + h+");
RegisterComponent<ADASCarbonCX<5, 'h'>> register_cx_c5h("c+6 + h -> c+5 + h+");
RegisterComponent<ADASCarbonCX<0, 'd'>> register_cx_c0d("c+ + d -> c + d+");
RegisterComponent<ADASCarbonCX<1, 'd'>> register_cx_c1d("c+2 + d -> c+ + d+");
RegisterComponent<ADASCarbonCX<2, 'd'>> register_cx_c2d("c+3 + d -> c+2 + d+");
RegisterComponent<ADASCarbonCX<3, 'd'>> register_cx_c3d("c+4 + d -> c+3 + d+");
RegisterComponent<ADASCarbonCX<4, 'd'>> register_cx_c4d("c+5 + d -> c+4 + d+");
RegisterComponent<ADASCarbonCX<5, 'd'>> register_cx_c5d("c+6 + d -> c+5 + d+");
RegisterComponent<ADASCarbonCX<0, 't'>> register_cx_c0t("c+ + t -> c + t+");
RegisterComponent<ADASCarbonCX<1, 't'>> register_cx_c1t("c+2 + t -> c+ + t+");
RegisterComponent<ADASCarbonCX<2, 't'>> register_cx_c2t("c+3 + t -> c+2 + t+");
RegisterComponent<ADASCarbonCX<3, 't'>> register_cx_c3t("c+4 + t -> c+3 + t+");
RegisterComponent<ADASCarbonCX<4, 't'>> register_cx_c4t("c+5 + t -> c+4 + t+");
RegisterComponent<ADASCarbonCX<5, 't'>> register_cx_c5t("c+6 + t -> c+5 + t+");
} // namespace
#endif // ADAS_CARBON_H
| 6,144
|
C++
|
.h
| 114
| 51.017544
| 90
| 0.67005
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,280
|
component_scheduler.hxx
|
bendudson_hermes-3/include/component_scheduler.hxx
|
#pragma once
#ifndef COMPONENT_SCHEDULER_H
#define COMPONENT_SCHEDULER_H
#include "component.hxx"
#include <vector>
#include <memory>
/// Creates and schedules model components
///
/// Currently only one implementation, but in future alternative scheduler
/// types could be created. There is therefore a static create function
/// which in future could switch between types.
///
class ComponentScheduler {
public:
ComponentScheduler(Options &scheduler_options, Options &component_options,
Solver *solver);
/// Inputs
/// @param scheduler_options Configuration of the scheduler
/// Should contain "components", a comma-separated
/// list of component names
///
/// @param component_options Configuration of the components.
/// - <name>
/// - type = Component classes, ...
/// If not provided, the type is the same as the name
/// Multiple classes can be given, separated by commas.
/// All classes will use the same Options section.
/// - ... Options to control the component(s)
///
/// @param solver Used for time-dependent components
/// to evolve quantities
///
static std::unique_ptr<ComponentScheduler> create(Options &scheduler_options,
Options &component_options,
Solver *solver);
/// Run the scheduler, modifying the state.
/// This calls all components' transform() methods, then
/// all component's finally() methods.
void transform(Options &state);
/// Add metadata, extra outputs. This would typically
/// be called only for writing to disk, rather than every internal
/// timestep.
void outputVars(Options &state);
/// Add variables to restart files
void restartVars(Options &state);
/// Preconditioning
void precon(const Options &state, BoutReal gamma);
private:
/// The components to be executed in order
std::vector<std::unique_ptr<Component>> components;
};
#endif // COMPONENT_SCHEDULER_H
| 2,190
|
C++
|
.h
| 52
| 37.134615
| 80
| 0.635765
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,281
|
classical_diffusion.hxx
|
bendudson_hermes-3/include/classical_diffusion.hxx
|
#pragma once
#ifndef CLASSICAL_DIFFUSION_H
#define CLASSICAL_DIFFUSION_H
#include "component.hxx"
struct ClassicalDiffusion : public Component {
ClassicalDiffusion(std::string name, Options& alloptions, Solver*);
void transform(Options &state) override;
void outputVars(Options &state) override;
private:
Field2D Bsq; // Magnetic field squared
bool diagnose; ///< Output additional diagnostics?
Field3D Dn; ///< Particle diffusion coefficient
BoutReal custom_D; ///< User-set particle diffusion coefficient override
};
namespace {
RegisterComponent<ClassicalDiffusion> registercomponentclassicaldiffusion("classical_diffusion");
}
#endif // CLASSICAL_DIFFUSION_H
| 684
|
C++
|
.h
| 18
| 35.833333
| 97
| 0.805766
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,282
|
electron_viscosity.hxx
|
bendudson_hermes-3/include/electron_viscosity.hxx
|
#pragma once
#ifndef ELECTRON_VISCOSITY_H
#define ELECTRON_VISCOSITY_H
#include "component.hxx"
/// Electron viscosity
///
/// Adds Braginskii parallel electron viscosity, with SOLPS-style
/// viscosity flux limiter
///
/// Needs to be calculated after collisions, because collision
/// frequency is used to calculate parallel viscosity
///
/// References
/// - https://farside.ph.utexas.edu/teaching/plasma/lectures1/node35.html
///
struct ElectronViscosity : public Component {
/// Inputs
/// - <name>
/// - diagnose: bool, default false
/// Output diagnostic SNVe_viscosity?
/// - eta_limit_alpha: float, default -1.0
/// Flux limiter coefficient. < 0 means no limiter
ElectronViscosity(std::string name, Options& alloptions, Solver*);
/// Inputs
/// - species
/// - e
/// - pressure (skips if not present)
/// - velocity (skips if not present)
/// - collision_frequency
///
/// Sets in the state
/// - species
/// - e
/// - momentum_source
///
void transform(Options &state) override;
void outputVars(Options &state) override;
private:
BoutReal eta_limit_alpha; ///< Flux limit coefficient
bool diagnose; ///< Output viscosity diagnostic?
Field3D viscosity; ///< The viscosity momentum source
};
namespace {
RegisterComponent<ElectronViscosity> registercomponentelectronviscosity("electron_viscosity");
}
#endif
| 1,406
|
C++
|
.h
| 46
| 28.369565
| 94
| 0.705318
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,283
|
full_velocity.hxx
|
bendudson_hermes-3/include/full_velocity.hxx
|
#pragma once
#ifndef FULL_VELOCITY_H
#define FULL_VELOCITY_H
#include <string>
#include "component.hxx"
#include <bout/vector2d.hxx>
struct NeutralFullVelocity : public Component {
NeutralFullVelocity(const std::string& name, Options& options, Solver *solver);
/// Modify the given simulation state
void transform(Options &state) override;
/// Use the final simulation state to update internal state
/// (e.g. time derivatives)
void finally(const Options &state) override;
/// Add extra fields for output, or set attributes e.g docstrings
void outputVars(Options &state) override;
private:
Coordinates *coord; // Coordinate system
std::string name; // Name of this species
BoutReal AA; // Atomic mass
BoutReal Tnorm;
Field2D Nn2D; // Neutral gas density (evolving)
Field2D Pn2D; // Neutral gas pressure (evolving)
Vector2D Vn2D; // Neutral gas velocity
Field2D Tn2D;
Field2D DivV2D; // Divergence of gas velocity
// Transformation to cylindrical coordinates
// Grad x = Txr * Grad R + Txz * Grad Z
// Grad y = Tyr * Grad R + Tyz * Grad Z
Field2D Txr, Txz;
Field2D Tyr, Tyz;
// Grad R = Urx * Grad x + Ury * Grad y
// Grad Z = Uzx * Grad x + Uzy * Grad y
Field2D Urx, Ury;
Field2D Uzx, Uzy;
BoutReal gamma_ratio; // Ratio of specific heats
BoutReal neutral_viscosity; // Neutral gas viscosity
BoutReal neutral_bulk; // Neutral gas bulk viscosity
BoutReal neutral_conduction; // Neutral gas thermal conduction
BoutReal neutral_gamma; // Heat transmission for neutrals
// Outflowing boundaries for neutrals
bool outflow_ydown; // Allow neutral outflows?
};
#endif // FULL_VELOCITY_H
| 1,711
|
C++
|
.h
| 43
| 36.581395
| 81
| 0.722392
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,284
|
anomalous_diffusion.hxx
|
bendudson_hermes-3/include/anomalous_diffusion.hxx
|
#pragma once
#ifndef ANOMALOUS_DIFFUSION_H
#define ANOMALOUS_DIFFUSION_H
#include "component.hxx"
/// Add anomalous diffusion of density, momentum and energy
///
/// # Mesh inputs
///
/// D_<name>, chi_<name>, nu_<name>
/// e.g `D_e`, `chi_e`, `nu_e`
///
/// in units of m^2/s
///
struct AnomalousDiffusion : public Component {
/// # Inputs
///
/// - <name>
/// - anomalous_D This overrides D_<name> mesh input
/// - anomalous_chi This overrides chi_<name>
/// - anomalous_nu Overrides nu_<name>
/// - anomalous_sheath_flux Allow anomalous flux into sheath?
// Default false.
AnomalousDiffusion(std::string name, Options &alloptions, Solver *);
/// Inputs
/// - species
/// - <name>
/// - density
/// - temperature (optional)
/// - velocity (optional)
///
/// Sets in the state
///
/// - species
/// - <name>
/// - density_source
/// - momentum_source
/// - energy_source
///
void transform(Options &state) override;
void outputVars(Options &state) override;
private:
std::string name; ///< Species name
bool diagnose; ///< Outputting diagnostics?
bool include_D, include_chi, include_nu; ///< Which terms should be included?
Field2D anomalous_D; ///< Anomalous density diffusion coefficient
Field2D anomalous_chi; ///< Anomalous thermal diffusion coefficient
Field2D anomalous_nu; ///< Anomalous momentum diffusion coefficient
bool anomalous_sheath_flux; ///< Allow anomalous diffusion into sheath?
};
namespace {
RegisterComponent<AnomalousDiffusion> registercomponentanomalousdiffusion("anomalous_diffusion");
}
#endif // ANOMALOUS_DIFFUSION_H
| 1,699
|
C++
|
.h
| 53
| 29.622642
| 97
| 0.663203
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,285
|
div_ops.hxx
|
bendudson_hermes-3/include/div_ops.hxx
|
/*
Finite volume discretisations of divergence operators
***********
Copyright B.Dudson, J.Leddy, University of York, September 2016
email: benjamin.dudson@york.ac.uk
This file is part of Hermes.
Hermes is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Hermes is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Hermes. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DIV_OPS_H
#define DIV_OPS_H
#include <bout/field3d.hxx>
#include <bout/vector3d.hxx>
#include <bout/fv_ops.hxx>
/*!
* Diffusion in index space
*
* Similar to using Div_par_diffusion(SQ(mesh->dy)*mesh->g_22, f)
*
* @param[in] The field to be differentiated
* @param[in] bndry_flux Are fluxes through the boundary calculated?
*/
const Field3D Div_par_diffusion_index(const Field3D& f, bool bndry_flux = true);
const Field3D Div_n_bxGrad_f_B_XPPM(const Field3D& n, const Field3D& f,
bool bndry_flux = true, bool poloidal = false,
bool positive = false);
/// This version has an extra coefficient 'g' that is linearly interpolated
/// onto cell faces
const Field3D Div_n_g_bxGrad_f_B_XZ(const Field3D &n, const Field3D &g, const Field3D &f,
bool bndry_flux = true, bool positive = false);
const Field3D Div_Perp_Lap_FV_Index(const Field3D& a, const Field3D& f, bool xflux);
const Field3D Div_Z_FV_Index(const Field3D& a, const Field3D& f);
// 4th-order flux conserving term, in index space
const Field3D D4DX4_FV_Index(const Field3D& f, bool bndry_flux = false);
const Field3D D4DZ4_Index(const Field3D& f);
// Div ( k * Grad(f) )
const Field2D Laplace_FV(const Field2D& k, const Field2D& f);
/// Perpendicular diffusion including X and Y directions
const Field3D Div_a_Grad_perp_upwind(const Field3D& a, const Field3D& f);
/// Version of function that returns flows
const Field3D Div_a_Grad_perp_upwind_flows(const Field3D& a, const Field3D& f, Field3D& flux_xlow, Field3D& flux_ylow);
/// Version with energy flow diagnostic
const Field3D Div_par_K_Grad_par_mod(const Field3D& k, const Field3D& f, Field3D& flow_ylow,
bool bndry_flux = true);
namespace FV {
/// Superbee limiter
///
/// This corresponds to the limiter function
/// φ(r) = max(0, min(2r, 1), min(r,2)
///
/// The value at cell right (i.e. i + 1/2) is:
///
/// n.R = n.c - φ(r) (n.c - (n.p + n.c)/2)
/// = n.c + φ(r) (n.p - n.c)/2
///
/// Four regimes:
/// a) r < 1/2 -> φ(r) = 2r
/// n.R = n.c + gL
/// b) 1/2 < r < 1 -> φ(r) = 1
/// n.R = n.c + gR/2
/// c) 1 < r < 2 -> φ(r) = r
/// n.R = n.c + gL/2
/// d) 2 < r -> φ(r) = 2
/// n.R = n.c + gR
///
/// where the left and right gradients are:
/// gL = n.c - n.m
/// gR = n.p - n.c
///
struct Superbee {
void operator()(Stencil1D& n) {
BoutReal gL = n.c - n.L;
BoutReal gR = n.R - n.c;
// r = gL / gR
// Limiter is φ(r)
if (gL * gR < 0) {
// Different signs => Zero gradient
n.L = n.R = n.c;
} else {
BoutReal sign = SIGN(gL);
gL = fabs(gL);
gR = fabs(gR);
BoutReal half_slope = sign * BOUTMAX(BOUTMIN(gL, 0.5*gR),
BOUTMIN(gR, 0.5*gL));
n.L = n.c - half_slope;
n.R = n.c + half_slope;
}
}
};
template <typename CellEdges = MC>
const Field3D Div_par_fvv(const Field3D& f_in, const Field3D& v_in,
const Field3D& wave_speed_in, bool fixflux = true) {
ASSERT1(areFieldsCompatible(f_in, v_in));
ASSERT1(areFieldsCompatible(f_in, wave_speed_in));
Mesh* mesh = f_in.getMesh();
CellEdges cellboundary;
/// Ensure that f, v and wave_speed are field aligned
Field3D f = toFieldAligned(f_in, "RGN_NOX");
Field3D v = toFieldAligned(v_in, "RGN_NOX");
Field3D wave_speed = toFieldAligned(wave_speed_in, "RGN_NOX");
Coordinates* coord = f_in.getCoordinates();
Field3D result{zeroFrom(f)};
// Only need one guard cell, so no need to communicate fluxes
// Instead calculate in guard cells to preserve fluxes
int ys = mesh->ystart - 1;
int ye = mesh->yend + 1;
for (int i = mesh->xstart; i <= mesh->xend; i++) {
if (!mesh->firstY(i) || mesh->periodicY(i)) {
// Calculate in guard cell to get fluxes consistent between processors
ys = mesh->ystart - 1;
} else {
// Don't include the boundary cell. Note that this implies special
// handling of boundaries later
ys = mesh->ystart;
}
if (!mesh->lastY(i) || mesh->periodicY(i)) {
// Calculate in guard cells
ye = mesh->yend + 1;
} else {
// Not in boundary cells
ye = mesh->yend;
}
for (int j = ys; j <= ye; j++) {
// Pre-calculate factors which multiply fluxes
// For right cell boundaries
BoutReal common_factor = (coord->J(i, j) + coord->J(i, j + 1))
/ (sqrt(coord->g_22(i, j)) + sqrt(coord->g_22(i, j + 1)));
BoutReal flux_factor_rc = common_factor / (coord->dy(i, j) * coord->J(i, j));
BoutReal flux_factor_rp =
common_factor / (coord->dy(i, j + 1) * coord->J(i, j + 1));
// For left cell boundaries
common_factor = (coord->J(i, j) + coord->J(i, j - 1))
/ (sqrt(coord->g_22(i, j)) + sqrt(coord->g_22(i, j - 1)));
BoutReal flux_factor_lc = common_factor / (coord->dy(i, j) * coord->J(i, j));
BoutReal flux_factor_lm =
common_factor / (coord->dy(i, j - 1) * coord->J(i, j - 1));
for (int k = 0; k < mesh->LocalNz; k++) {
////////////////////////////////////////////
// Reconstruct f at the cell faces
// This calculates s.R and s.L for the Right and Left
// face values on this cell
// Reconstruct f at the cell faces
Stencil1D s;
s.c = f(i, j, k);
s.m = f(i, j - 1, k);
s.p = f(i, j + 1, k);
cellboundary(s); // Calculate s.R and s.L
// Reconstruct v at the cell faces
Stencil1D sv;
sv.c = v(i, j, k);
sv.m = v(i, j - 1, k);
sv.p = v(i, j + 1, k);
cellboundary(sv);
////////////////////////////////////////////
// Right boundary
// Calculate velocity at right boundary (y+1/2)
BoutReal v_mid = 0.5 * (sv.c + sv.p);
// And mid-point density at right boundary
BoutReal n_mid = 0.5 * (s.c + s.p);
BoutReal flux;
if (mesh->lastY(i) && (j == mesh->yend) && !mesh->periodicY(i)) {
// Last point in domain
if (fixflux) {
// Use mid-point to be consistent with boundary conditions
flux = n_mid * v_mid * v_mid;
} else {
// Add flux due to difference in boundary values
flux = s.R * sv.R * sv.R // Use right cell edge values
+ BOUTMAX(wave_speed(i, j, k), fabs(sv.c), fabs(sv.p))
* n_mid * (sv.R - v_mid); // Damp differences in velocity, not flux
}
} else {
// Maximum wave speed in the two cells
BoutReal amax = BOUTMAX(wave_speed(i, j, k), wave_speed(i, j + 1, k),
fabs(sv.c), fabs(sv.p));
flux = s.R * 0.5 * (sv.R + amax) * sv.R;
}
result(i, j, k) += flux * flux_factor_rc;
result(i, j + 1, k) -= flux * flux_factor_rp;
////////////////////////////////////////////
// Calculate at left boundary
v_mid = 0.5 * (sv.c + sv.m);
n_mid = 0.5 * (s.c + s.m);
if (mesh->firstY(i) && (j == mesh->ystart) && !mesh->periodicY(i)) {
// First point in domain
if (fixflux) {
// Use mid-point to be consistent with boundary conditions
flux = n_mid * v_mid * v_mid;
} else {
// Add flux due to difference in boundary values
flux =
s.L * sv.L * sv.L
- BOUTMAX(wave_speed(i, j, k), fabs(sv.c), fabs(sv.m))
* n_mid * (sv.L - v_mid);
}
} else {
// Maximum wave speed in the two cells
BoutReal amax = BOUTMAX(wave_speed(i, j, k), wave_speed(i, j - 1, k),
fabs(sv.c), fabs(sv.m));
flux = s.L * 0.5 * (sv.L - amax) * sv.L;
}
result(i, j, k) -= flux * flux_factor_lc;
result(i, j - 1, k) += flux * flux_factor_lm;
}
}
}
return fromFieldAligned(result, "RGN_NOBNDRY");
}
// Calculates viscous heating due to numerical momentum fluxes
// and flow of kinetic energy (in flow_ylow)
template <typename CellEdges = MC>
const Field3D Div_par_fvv_heating(const Field3D& f_in, const Field3D& v_in,
const Field3D& wave_speed_in, Field3D &flow_ylow,
bool fixflux = true) {
ASSERT1(areFieldsCompatible(f_in, v_in));
ASSERT1(areFieldsCompatible(f_in, wave_speed_in));
Mesh* mesh = f_in.getMesh();
CellEdges cellboundary;
/// Ensure that f, v and wave_speed are field aligned
Field3D f = toFieldAligned(f_in, "RGN_NOX");
Field3D v = toFieldAligned(v_in, "RGN_NOX");
Field3D wave_speed = toFieldAligned(wave_speed_in, "RGN_NOX");
Coordinates* coord = f_in.getCoordinates();
Field3D result{zeroFrom(f)};
flow_ylow = zeroFrom(f);
// Only need one guard cell, so no need to communicate fluxes
// Instead calculate in guard cells to preserve fluxes
int ys = mesh->ystart - 1;
int ye = mesh->yend + 1;
for (int i = mesh->xstart; i <= mesh->xend; i++) {
if (!mesh->firstY(i) || mesh->periodicY(i)) {
// Calculate in guard cell to get fluxes consistent between processors
ys = mesh->ystart - 1;
} else {
// Don't include the boundary cell. Note that this implies special
// handling of boundaries later
ys = mesh->ystart;
}
if (!mesh->lastY(i) || mesh->periodicY(i)) {
// Calculate in guard cells
ye = mesh->yend + 1;
} else {
// Not in boundary cells
ye = mesh->yend;
}
for (int j = ys; j <= ye; j++) {
// Pre-calculate factors which multiply fluxes
// For right cell boundaries
BoutReal common_factor = (coord->J(i, j) + coord->J(i, j + 1))
/ (sqrt(coord->g_22(i, j)) + sqrt(coord->g_22(i, j + 1)));
BoutReal flux_factor_rc = common_factor / (coord->dy(i, j) * coord->J(i, j));
BoutReal area_rp = common_factor * coord->dx(i, j + 1) * coord->dz(i, j + 1);
// For left cell boundaries
common_factor = (coord->J(i, j) + coord->J(i, j - 1))
/ (sqrt(coord->g_22(i, j)) + sqrt(coord->g_22(i, j - 1)));
BoutReal flux_factor_lc = common_factor / (coord->dy(i, j) * coord->J(i, j));
BoutReal area_lc = common_factor * coord->dx(i, j) * coord->dz(i, j);
for (int k = 0; k < mesh->LocalNz; k++) {
////////////////////////////////////////////
// Reconstruct f at the cell faces
// This calculates s.R and s.L for the Right and Left
// face values on this cell
// Reconstruct f at the cell faces
Stencil1D s;
s.c = f(i, j, k);
s.m = f(i, j - 1, k);
s.p = f(i, j + 1, k);
cellboundary(s); // Calculate s.R and s.L
// Reconstruct v at the cell faces
Stencil1D sv;
sv.c = v(i, j, k);
sv.m = v(i, j - 1, k);
sv.p = v(i, j + 1, k);
cellboundary(sv);
////////////////////////////////////////////
// Right boundary
// Calculate velocity at right boundary (y+1/2)
BoutReal v_mid = 0.5 * (sv.c + sv.p);
// And mid-point density at right boundary
BoutReal n_mid = 0.5 * (s.c + s.p);
if (mesh->lastY(i) && (j == mesh->yend) && !mesh->periodicY(i)) {
// Last point in domain
// Expected loss of kinetic energy into boundary
// This is used in the sheath boundary condition to calculate
// energy losses.
BoutReal expected_ke = 0.5 * n_mid * v_mid * v_mid * v_mid;
BoutReal flux_mom;
if (fixflux) {
// Mid-point consistent with boundary conditions
// but kinetic energy loss will not match expected
// -> Adjust energy balance in pressure equation
flux_mom = n_mid * v_mid * v_mid;
} else {
flux_mom = s.R * sv.R * sv.R
+ BOUTMAX(wave_speed(i, j, k), fabs(sv.c), fabs(sv.p))
* (s.R * sv.R - n_mid * v_mid);
}
// Assume that particle flux is fixed to boundary value
const BoutReal flux_part = n_mid * v_mid;
// d/dt(1/2 m n v^2) = v * d/dt(mnv) - 1/2 m v^2 * dn/dt
BoutReal actual_ke = sv.c * flux_mom - 0.5 * sv.c * sv.c * flux_part;
// Note: If the actual loss was higher than expected, then
// plasma heating is needed to compensate
result(i, j, k) += (actual_ke - expected_ke) * flux_factor_rc;
// Final flow through boundary is the expected value
flow_ylow(i, j + 1, k) += expected_ke * area_rp; //expected_ke * area_rp;
} else {
// Maximum wave speed in the two cells
BoutReal amax = BOUTMAX(wave_speed(i, j, k), wave_speed(i, j + 1, k),
fabs(sv.c), fabs(sv.p));
// Viscous heating due to relaxation of velocity towards midpoint
result(i, j, k) += (amax + 0.5 * sv.R) * s.R * (sv.c - sv.p) * (sv.R - v_mid) * flux_factor_rc;
// Kinetic energy flow into next cell.
// Note: Different from flow out of this cell; the difference
// is in the viscous heating.
BoutReal flux_part = s.R * 0.5 * (sv.R + amax);
BoutReal flux_mom = flux_part * sv.R;
flow_ylow(i, j + 1, k) += (sv.p * flux_mom - 0.5 * SQ(sv.p) * flux_part) * area_rp;
}
////////////////////////////////////////////
// Calculate at left boundary
v_mid = 0.5 * (sv.c + sv.m);
n_mid = 0.5 * (s.c + s.m);
// Expected KE loss. Note minus sign because negative v into boundary
BoutReal expected_ke = - 0.5 * n_mid * v_mid * v_mid * v_mid;
if (mesh->firstY(i) && (j == mesh->ystart) && !mesh->periodicY(i)) {
// First point in domain
BoutReal flux_mom;
if (fixflux) {
// Use mid-point to be consistent with boundary conditions
flux_mom = n_mid * v_mid * v_mid;
} else {
// Add flux due to difference in boundary values
flux_mom =
s.L * sv.L * sv.L
- BOUTMAX(wave_speed(i, j, k), fabs(sv.c), fabs(sv.m))
* (s.L * sv.L - n_mid * v_mid);
}
// Assume that density flux is fixed to boundary value
const BoutReal flux_part = n_mid * v_mid;
// d/dt(1/2 m n v^2) = v * d/dt(mnv) - 1/2 m v^2 * dn/dt
BoutReal actual_ke = - sv.c * flux_mom + 0.5 * sv.c * sv.c * flux_part;
result(i, j, k) += (actual_ke - expected_ke) * flux_factor_lc;
flow_ylow(i, j, k) -= expected_ke * area_lc;
} else {
// Maximum wave speed in the two cells
BoutReal amax = BOUTMAX(wave_speed(i, j, k), wave_speed(i, j - 1, k),
fabs(sv.c), fabs(sv.m));
// Viscous heating due to relaxation
result(i, j, k) += (amax - 0.5 * sv.L) * s.L * (sv.c - sv.m) * (sv.L - v_mid) * flux_factor_lc;
// Kinetic energy flow into this cell.
// Note: Different from flow out of left cell; the difference
// is in the viscous heating.
BoutReal flux_part = s.L * 0.5 * (sv.L - amax);
BoutReal flux_mom = flux_part * sv.L;
flow_ylow(i, j, k) += (sv.c * flux_mom - 0.5 * SQ(sv.c) * flux_part) * area_lc;
}
}
}
}
flow_ylow = fromFieldAligned(flow_ylow, "RGN_NOBNDRY");
return fromFieldAligned(result, "RGN_NOBNDRY");
}
/// Finite volume parallel divergence
///
/// NOTE: Modified version, applies limiter to velocity and field
/// Performs better (smaller overshoots) than Div_par
///
/// Preserves the sum of f*J*dx*dy*dz over the domain
///
/// @param[in] f_in The field being advected.
/// This will be reconstructed at cell faces
/// using the given CellEdges method
/// @param[in] v_in The advection velocity.
/// This will be interpolated to cell boundaries
/// using linear interpolation
/// @param[in] wave_speed_in Local maximum speed of all waves in the system at each
// point in space
/// @param[in] fixflux Fix the flux at the boundary to be the value at the
/// midpoint (for boundary conditions)
///
/// @param[out] flow_ylow Flow at the lower Y cell boundary
/// Already includes area factor * flux
///
/// NB: Uses to/from FieldAligned coordinates
template <typename CellEdges = MC>
const Field3D Div_par_mod(const Field3D& f_in, const Field3D& v_in,
const Field3D& wave_speed_in,
Field3D &flow_ylow, bool fixflux = true) {
ASSERT1_FIELDS_COMPATIBLE(f_in, v_in);
ASSERT1_FIELDS_COMPATIBLE(f_in, wave_speed_in);
Mesh* mesh = f_in.getMesh();
CellEdges cellboundary;
ASSERT2(f_in.getDirectionY() == v_in.getDirectionY());
ASSERT2(f_in.getDirectionY() == wave_speed_in.getDirectionY());
const bool are_unaligned =
((f_in.getDirectionY() == YDirectionType::Standard)
and (v_in.getDirectionY() == YDirectionType::Standard)
and (wave_speed_in.getDirectionY() == YDirectionType::Standard));
Field3D f = are_unaligned ? toFieldAligned(f_in, "RGN_NOX") : f_in;
Field3D v = are_unaligned ? toFieldAligned(v_in, "RGN_NOX") : v_in;
Field3D wave_speed =
are_unaligned ? toFieldAligned(wave_speed_in, "RGN_NOX") : wave_speed_in;
Coordinates* coord = f_in.getCoordinates();
Field3D result{zeroFrom(f)};
flow_ylow = zeroFrom(f);
// Only need one guard cell, so no need to communicate fluxes
// Instead calculate in guard cells to preserve fluxes
int ys = mesh->ystart - 1;
int ye = mesh->yend + 1;
for (int i = mesh->xstart; i <= mesh->xend; i++) {
if (!mesh->firstY(i) || mesh->periodicY(i)) {
// Calculate in guard cell to get fluxes consistent between processors
ys = mesh->ystart - 1;
} else {
// Don't include the boundary cell. Note that this implies special
// handling of boundaries later
ys = mesh->ystart;
}
if (!mesh->lastY(i) || mesh->periodicY(i)) {
// Calculate in guard cells
ye = mesh->yend + 1;
} else {
// Not in boundary cells
ye = mesh->yend;
}
for (int j = ys; j <= ye; j++) {
// Pre-calculate factors which multiply fluxes
#if not(BOUT_USE_METRIC_3D)
// For right cell boundaries
BoutReal common_factor = (coord->J(i, j) + coord->J(i, j + 1))
/ (sqrt(coord->g_22(i, j)) + sqrt(coord->g_22(i, j + 1)));
BoutReal flux_factor_rc = common_factor / (coord->dy(i, j) * coord->J(i, j));
BoutReal flux_factor_rp =
common_factor / (coord->dy(i, j + 1) * coord->J(i, j + 1));
BoutReal area_rp = common_factor * coord->dx(i, j + 1) * coord->dz(i, j + 1);
// For left cell boundaries
common_factor = (coord->J(i, j) + coord->J(i, j - 1))
/ (sqrt(coord->g_22(i, j)) + sqrt(coord->g_22(i, j - 1)));
BoutReal flux_factor_lc = common_factor / (coord->dy(i, j) * coord->J(i, j));
BoutReal flux_factor_lm =
common_factor / (coord->dy(i, j - 1) * coord->J(i, j - 1));
BoutReal area_lc = common_factor * coord->dx(i, j) * coord->dz(i, j);
#endif
for (int k = 0; k < mesh->LocalNz; k++) {
#if BOUT_USE_METRIC_3D
// For right cell boundaries
BoutReal common_factor =
(coord->J(i, j, k) + coord->J(i, j + 1, k))
/ (sqrt(coord->g_22(i, j, k)) + sqrt(coord->g_22(i, j + 1, k)));
BoutReal flux_factor_rc =
common_factor / (coord->dy(i, j, k) * coord->J(i, j, k));
BoutReal flux_factor_rp =
common_factor / (coord->dy(i, j + 1, k) * coord->J(i, j + 1, k));
BoutReal area_rp = common_factor * coord->dx(i, j + 1, k) * coord->dz(i, j + 1, k);
// For left cell boundaries
common_factor = (coord->J(i, j, k) + coord->J(i, j - 1, k))
/ (sqrt(coord->g_22(i, j, k)) + sqrt(coord->g_22(i, j - 1, k)));
BoutReal flux_factor_lc =
common_factor / (coord->dy(i, j, k) * coord->J(i, j, k));
BoutReal flux_factor_lm =
common_factor / (coord->dy(i, j - 1, k) * coord->J(i, j - 1, k));
BoutReal area_lc = common_factor * coord->dx(i, j, k) * coord->dz(i, j, k);
#endif
////////////////////////////////////////////
// Reconstruct f at the cell faces
// This calculates s.R and s.L for the Right and Left
// face values on this cell
// Reconstruct f at the cell faces
Stencil1D s;
s.c = f(i, j, k);
s.m = f(i, j - 1, k);
s.p = f(i, j + 1, k);
cellboundary(s); // Calculate s.R and s.L
////////////////////////////////////////////
// Reconstruct v at the cell faces
Stencil1D sv;
sv.c = v(i, j, k);
sv.m = v(i, j - 1, k);
sv.p = v(i, j + 1, k);
cellboundary(sv); // Calculate sv.R and sv.L
////////////////////////////////////////////
// Right boundary
BoutReal flux;
if (mesh->lastY(i) && (j == mesh->yend) && !mesh->periodicY(i)) {
// Last point in domain
// Calculate velocity at right boundary (y+1/2)
BoutReal vpar = 0.5 * (v(i, j, k) + v(i, j + 1, k));
BoutReal bndryval = 0.5 * (s.c + s.p);
if (fixflux) {
// Use mid-point to be consistent with boundary conditions
flux = bndryval * vpar;
} else {
// Add flux due to difference in boundary values
flux = s.R * vpar + wave_speed(i, j, k) * (s.R - bndryval);
}
} else {
// Maximum wave speed in the two cells
BoutReal amax = BOUTMAX(wave_speed(i, j, k), wave_speed(i, j + 1, k),
fabs(v(i, j, k)), fabs(v(i, j + 1, k)));
flux = s.R * 0.5 * (sv.R + amax);
}
result(i, j, k) += flux * flux_factor_rc;
result(i, j + 1, k) -= flux * flux_factor_rp;
flow_ylow(i, j + 1, k) += flux * area_rp;
////////////////////////////////////////////
// Calculate at left boundary
if (mesh->firstY(i) && (j == mesh->ystart) && !mesh->periodicY(i)) {
// First point in domain
BoutReal bndryval = 0.5 * (s.c + s.m);
BoutReal vpar = 0.5 * (v(i, j, k) + v(i, j - 1, k));
if (fixflux) {
// Use mid-point to be consistent with boundary conditions
flux = bndryval * vpar;
} else {
// Add flux due to difference in boundary values
flux = s.L * vpar - wave_speed(i, j, k) * (s.L - bndryval);
}
} else {
// Maximum wave speed in the two cells
BoutReal amax = BOUTMAX(wave_speed(i, j, k), wave_speed(i, j - 1, k),
fabs(v(i, j, k)), fabs(v(i, j - 1, k)));
flux = s.L * 0.5 * (sv.L - amax);
}
result(i, j, k) -= flux * flux_factor_lc;
result(i, j - 1, k) += flux * flux_factor_lm;
flow_ylow(i, j, k) += flux * area_lc;
}
}
}
if (are_unaligned) {
flow_ylow = fromFieldAligned(flow_ylow, "RGN_NOBNDRY");
}
return are_unaligned ? fromFieldAligned(result, "RGN_NOBNDRY") : result;
}
} // namespace FV
#endif // DIV_OPS_H
| 24,570
|
C++
|
.h
| 545
| 36.8
| 119
| 0.543502
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,286
|
zero_current.hxx
|
bendudson_hermes-3/include/zero_current.hxx
|
#pragma once
#ifndef ZERO_CURRENT
#define ZERO_CURRENT
#include "component.hxx"
/// Set the velocity of a species so that
/// there is no net current, by summing the current from
/// other species.
///
/// This is most often used in the electron species, but
/// does not need to be.
struct ZeroCurrent : public Component {
/// Inputs
/// ------
///
/// @param name Short name for species e.g. "e"
/// @param alloptions Component configuration options
/// - <name>
/// - charge (must not be zero)
ZeroCurrent(std::string name, Options& alloptions, Solver*);
/// Required inputs
/// - species
/// - <name>
/// - density
/// - charge
/// - <one or more other species>
/// - density
/// - velocity
/// - charge
///
/// Sets in the state
/// - species
/// - <name>
/// - velocity
///
void transform(Options &state) override;
void finally(const Options &state) override {
// Get the velocity with boundary condition applied.
// This is for output only
velocity = get<Field3D>(state["species"][name]["velocity"]);
}
void outputVars(Options &state) override;
private:
std::string name; ///< Name of this species
BoutReal charge; ///< The charge of this species
Field3D velocity; ///< Species velocity (for writing to output)
};
namespace {
RegisterComponent<ZeroCurrent> registercomponentzerocurrent("zero_current");
}
#endif // ZERO_CURRENT
| 1,462
|
C++
|
.h
| 50
| 26.58
| 76
| 0.655492
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,287
|
detachment_controller.hxx
|
bendudson_hermes-3/include/detachment_controller.hxx
|
#pragma once
#ifndef detachment_controller_H
#define detachment_controller_H
#include "component.hxx"
#include <bout/constants.hxx>
struct DetachmentController : public Component {
DetachmentController(std::string, Options& options, Solver*) {
ASSERT0(BoutComm::size() == 1); // Only works on one processor
Options& detachment_controller_options = options["detachment_controller"];
const auto& units = options["units"];
BoutReal Tnorm = get<BoutReal>(units["eV"]);
BoutReal Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
BoutReal Omega_ci = 1.0 / get<BoutReal>(units["seconds"]);
time_normalisation = 1.0 / Omega_ci;
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
connection_length = options["mesh"]["length"].as<BoutReal>();
detachment_front_setpoint =
detachment_controller_options["detachment_front_setpoint"]
.doc("How far from the divertor target should the detachment front be? (in m).")
.as<BoutReal>();
velocity_form = detachment_controller_options["velocity_form"]
.doc("Use the velocity form if true (default) or the position form if false.")
.withDefault(true);
min_time_for_change =
detachment_controller_options["min_time_for_change"]
.doc("Minimum time change before changing the control signal.")
.withDefault<BoutReal>(1E-12);
min_error_for_change =
detachment_controller_options["min_error_for_change"]
.doc("Minimum error change before changing the control signal.")
.withDefault<BoutReal>(0.0);
minval_for_source_multiplier =
detachment_controller_options["minval_for_source_multiplier"]
.doc("Minimum value for the control signal.")
.withDefault<BoutReal>(-INFINITY);
maxval_for_source_multiplier =
detachment_controller_options["maxval_for_source_multiplier"]
.doc("Maximum value for the control signal.")
.withDefault<BoutReal>(INFINITY);
species_for_source_shape =
detachment_controller_options["species_for_source_shape"]
.doc("Which species to select the source_shape from?")
.withDefault<std::string>("e");
neutral_species =
detachment_controller_options["neutral_species"]
.doc("Which is the main neutral species?")
.as<std::string>();
actuator =
detachment_controller_options["actuator"]
.doc("What should we adjust to control the detachment front position (options are 'power' or 'particles' (either main species or impurity))?")
.as<std::string>();
if (actuator == "power") {
control_mode = control_power;
response_sign = -1.0;
} else if (actuator == "particles") {
control_mode = control_particles;
response_sign = 1.0;
} else {
// Invalid control mode
ASSERT2(false);
}
control = detachment_controller_options["initial_control"]
.doc("Initial value for the source multiplier.")
.withDefault<BoutReal>(1.0);
previous_control = control;
control_offset = detachment_controller_options["control_offset"]
.doc("Expected control value when error equals zero.")
.withDefault<BoutReal>(1.0);
settling_time = detachment_controller_options["settling_time"]
.doc("Time taken to allow system to settle before switching on certain control terms (in seconds).")
.withDefault<BoutReal>(0.0);
ignore_restart = detachment_controller_options["ignore_restart"]
.doc("Ignore the restart file (mainly useful for development).")
.withDefault(false);
reset_integral_on_first_crossing = detachment_controller_options["reset_integral_on_first_crossing"]
.doc("Reset the error integral to zero when the detachment front first reaches the desired position.")
.withDefault(true);
controller_gain = detachment_controller_options["controller_gain"]
.doc("Detachment controller gain (Kc parameter)")
.withDefault(0.0);
integral_time = detachment_controller_options["integral_time"]
.doc("Detachment controller integral time")
.withDefault(INFINITY);
derivative_time = detachment_controller_options["derivative_time"]
.doc("Detachment controller detachment time")
.withDefault(0.0);
buffer_size = detachment_controller_options["buffer_size"]
.doc("Number of points to store for calculating derivatives.")
.withDefault(10);
species_list = strsplit(detachment_controller_options["species_list"]
.doc("Comma-separated list of species to apply the PI-controlled source to")
.as<std::string>(),
',');
scaling_factors_list = strsplit(detachment_controller_options["scaling_factors_list"]
.doc("Comma-separated list of scaling factors to apply to the PI-controlled source, 1 for each species")
.as<std::string>(),
',');
if (species_list.size() != scaling_factors_list.size()) {
throw BoutException("DetachmentController: species_list length doesn't match scaling_factors length. Need 1 scaling factor per species.");
}
if (control_mode == control_power) {
source_shape =
(options[std::string("P") + species_for_source_shape]["source_shape"]
.doc("Source term in ddt(P" + species_for_source_shape + std::string("). Units [Pa/s], note P = 2/3 E."))
.withDefault(Field3D(0.0))
) / (Pnorm * Omega_ci);
source_units = "Pa / s";
source_conversion = Pnorm * Omega_ci;
} else if (control_mode == control_particles) {
source_shape =
(options[std::string("N") + species_for_source_shape]["source_shape"]
.doc("Source term in ddt(N" + species_for_source_shape + std::string("). Units [m^-3/s]"))
.withDefault(Field3D(0.0))
) / (Nnorm * Omega_ci);
source_units = "m^-3 / s";
source_conversion = Nnorm * Omega_ci;
}
diagnose = detachment_controller_options["diagnose"]
.doc("Output additional diagnostics?")
.withDefault<bool>(false);
debug =
detachment_controller_options["debug"]
.doc("Print debugging information to the screen (0 for none, 1 for basic, 2 for extensive).")
.withDefault<int>(0);
};
void transform(Options& state) override;
void outputVars(Options& state) override {
AUTO_TRACE();
if (diagnose) {
set_with_attrs(
state[std::string("detachment_front_location")], detachment_front_location,
{{"units", "m"},
{"time_dimension", "t"},
{"long_name", "detachment front position"},
{"source", "detachment_controller"}});
// Shape is not time-dependent and has units
set_with_attrs(
state[std::string("detachment_control_src_shape")], source_shape,
{{"units", source_units},
{"conversion", source_conversion},
{"long_name", "detachment control source shape"},
{"source", "detachment_controller"}});
// The source multiplier is time-dependent, but dimensionless
// because all the units are attached to the shape
set_with_attrs(state[std::string("detachment_control_src_mult")], control,
{{"time_dimension", "t"},
{"long_name", "detachment control source multiplier"},
{"source", "detachment_controller"}});
set_with_attrs(state[std::string("detachment_source_feedback")], detachment_source_feedback,
{{"time_dimension", "t"},
{"units", source_units},
{"conversion", source_conversion},
{"standard_name", "detachment control source"},
{"long_name", "detachment control source"},
{"source", "detachment_controller"}});
set_with_attrs(state[std::string("detachment_control_proportional_term")], proportional_term,
{{"time_dimension", "t"},
{"standard_name", "proportional_term"},
{"long_name", "detachment control proportional term"},
{"source", "detachment_controller"}});
set_with_attrs(state[std::string("detachment_control_integral_term")], integral_term,
{{"time_dimension", "t"},
{"standard_name", "integral_term"},
{"long_name", "detachment control integral term"},
{"source", "detachment_controller"}});
set_with_attrs(state[std::string("detachment_control_derivative_term")], derivative_term,
{{"time_dimension", "t"},
{"standard_name", "derivative_term"},
{"long_name", "detachment control derivative term"},
{"source", "detachment_controller"}});
}}
void restartVars(Options& state) override {
AUTO_TRACE();
if ((initialise) && (not ignore_restart)) {
if (state.isSet("detachment_control_src_mult")) {
control = state["detachment_control_src_mult"].as<BoutReal>();
}
if (state.isSet("detachment_control_previous_control")) {
previous_control = state["detachment_control_previous_control"].as<BoutReal>();
}
if (state.isSet("detachment_control_error_integral")) {
error_integral = state["detachment_control_error_integral"].as<BoutReal>();
}
if (state.isSet("detachment_control_previous_time")) {
previous_time = state["detachment_control_previous_time"].as<BoutReal>();
}
if (state.isSet("detachment_control_previous_error")) {
previous_error = state["detachment_control_previous_error"].as<BoutReal>();
}
if (state.isSet("detachment_control_previous_derivative")) {
previous_derivative = state["detachment_control_previous_derivative"].as<BoutReal>();
}
if (state.isSet("detachment_control_number_of_crossings")) {
number_of_crossings = state["detachment_control_number_of_crossings"].as<BoutReal>();
}
initialise = false;
first_step = false;
}
set_with_attrs(state["detachment_control_src_mult"], control, {{"source", "detachment_controller"}});
set_with_attrs(state["detachment_control_previous_control"], previous_control, {{"source", "detachment_controller"}});
set_with_attrs(state["detachment_control_error_integral"], error_integral, {{"source", "detachment_controller"}});
set_with_attrs(state["detachment_control_previous_time"], previous_time, {{"source", "detachment_controller"}});
set_with_attrs(state["detachment_control_previous_error"], previous_error, {{"source", "detachment_controller"}});
set_with_attrs(state["detachment_control_previous_derivative"], previous_derivative, {{"source", "detachment_controller"}});
set_with_attrs(state["detachment_control_number_of_crossings"], number_of_crossings, {{"source", "detachment_controller"}});
}
private:
// Inputs variables
BoutReal connection_length;
BoutReal detachment_front_setpoint;
BoutReal min_time_for_change;
BoutReal min_error_for_change;
std::string species_for_source_shape;
std::string neutral_species;
std::string actuator;
bool ignore_restart;
bool velocity_form;
bool reset_integral_on_first_crossing;
BoutReal response_sign;
BoutReal controller_gain;
BoutReal integral_time;
BoutReal derivative_time;
std::list<std::string> species_list; ///< Which species to apply the factor to
std::list<std::string> scaling_factors_list; ///< Factor to apply
Field3D source_shape;
std::string source_units;
BoutReal source_conversion;
bool diagnose;
BoutReal minval_for_source_multiplier;
BoutReal maxval_for_source_multiplier;
BoutReal control_offset;
BoutReal settling_time;
int debug;
int control_mode;
int control_power{0};
int control_particles{1};
// System state variables for output
Field3D detachment_source_feedback{0.0};
BoutReal detachment_front_location{0.0};
BoutReal control{0.0};
BoutReal change_in_error{0.0};
BoutReal change_in_time{0.0};
BoutReal proportional_term{0.0};
BoutReal integral_term{0.0};
BoutReal derivative_term{0.0};
BoutReal time{0.0};
BoutReal error{0.0};
BoutReal derivative{0.0};
BoutReal change_in_derivative{0.0};
BoutReal change_in_control{0.0};
// Private system state variables for calculations
BoutReal error_integral{0.0};
BoutReal previous_time{0.0};
BoutReal previous_error{0.0};
BoutReal previous_control{0.0};
BoutReal previous_derivative{0.0};
BoutReal time_normalisation;
bool initialise{true};
bool first_step{true};
BoutReal number_of_crossings{0.0};
int buffer_size = 0;
std::vector<BoutReal> time_buffer;
std::vector<BoutReal> error_buffer;
};
namespace {
RegisterComponent<DetachmentController> register_detachment_controller("detachment_controller");
}
#endif // detachment_controller_H
| 13,575
|
C++
|
.h
| 268
| 40.925373
| 148
| 0.638611
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,288
|
polarisation_drift.hxx
|
bendudson_hermes-3/include/polarisation_drift.hxx
|
#pragma once
#ifndef POLARISATION_DRIFT_H
#define POLARISATION_DRIFT_H
#include "component.hxx"
class Laplacian;
/// Calculates polarisation drift terms for all charged species, both
/// ions and electrons.
///
/// Approximates the polarisation drift by a generalised flow potential `phi_pol`
///
/// v_pol = - (A / (Z * B^2)) * Grad_perp(phi_pol)
///
/// phi_pol is approximately the time derivative of the electric potential
/// in the frame of the flow, plus an ion diamagnetic contribution
///
/// phi_pol is calculated using:
///
/// Div(mass_density / B^2 * Grad_perp(phi_pol)) = Div(Jpar) + Div(Jdia) + ...
///
/// Where the divergence of currents on the right is calculated from:
/// - species[...]["momentum"] The parallel momentum of charged species
/// - DivJdia, diamagnetic current, calculated in vorticity component
/// - DivJcol collisional current, calculated in vorticity component
/// - DivJextra Other currents, eg. 2D parallel closures
///
/// The mass_density quantity is the sum of density * atomic mass for all
/// charged species (ions and electrons)
struct PolarisationDrift : public Component {
//
PolarisationDrift(std::string name, Options &options, Solver *UNUSED(solver));
/// Inputs
///
/// - species
/// - ... All species with both charge and mass
/// - AA
/// - charge
/// - density
/// - momentum (optional)
///
/// - fields
/// - DivJextra (optional)
/// - DivJdia (optional)
/// - DivJcol (optional)
///
/// Sets
///
/// - species
/// - ... All species with both charge and mass
/// - density_source
/// - energy_source (if pressure set)
/// - momentum_source (if momentum set)
///
void transform(Options &state) override;
void outputVars(Options &state) override;
private:
std::unique_ptr<Laplacian> phiSolver; // Laplacian solver in X-Z
Field2D Bsq; // Cached SQ(coord->Bxy)
// Diagnostic outputs
bool diagnose; ///< Save diagnostic outputs?
Field3D DivJ; //< Divergence of all other currents
Field3D phi_pol; //< Polarisation drift potential
bool boussinesq; // If true, assume a constant mass density in Jpol
BoutReal average_atomic_mass; // If boussinesq=true, mass density to use
BoutReal density_floor; // Minimum mass density if boussinesq=false
bool advection; // Advect fluids by an approximate polarisation velocity?
bool diamagnetic_polarisation; // Calculate compression terms?
};
namespace {
RegisterComponent<PolarisationDrift> registercomponentpolarisationdrift("polarisation_drift");
}
#endif // POLARISATION_DRIFT_H
| 2,619
|
C++
|
.h
| 71
| 34.661972
| 94
| 0.699527
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,289
|
component.hxx
|
bendudson_hermes-3/include/component.hxx
|
#pragma once
#ifndef HERMES_COMPONENT_H
#define HERMES_COMPONENT_H
#include <bout/options.hxx>
#include <bout/generic_factory.hxx>
#include <map>
#include <string>
#include <memory>
class Solver; // Time integrator
/// Interface for a component of a simulation model
///
/// The constructor of derived types should have signature
/// (std::string name, Options &options, Solver *solver)
///
struct Component {
virtual ~Component() {}
/// Modify the given simulation state
/// All components must implement this function
virtual void transform(Options &state) = 0;
/// Use the final simulation state to update internal state
/// (e.g. time derivatives)
virtual void finally(const Options &UNUSED(state)) { }
/// Add extra fields for output, or set attributes e.g docstrings
virtual void outputVars(Options &UNUSED(state)) { }
/// Add extra fields to restart files
virtual void restartVars(Options &UNUSED(state)) { }
/// Preconditioning
virtual void precon(const Options &UNUSED(state), BoutReal UNUSED(gamma)) { }
/// Create a Component
///
/// @param type The name of the component type to create (e.g. "evolve_density")
/// @param name The species/name for this instance.
/// @param options Component settings: options[name] are specific to this component
/// @param solver Time-integration solver
static std::unique_ptr<Component> create(const std::string &type, // The type to create
const std::string &name, // The species/name for this instance
Options &options, // Component settings: options[name] are specific to this component
Solver *solver); // Time integration solver
};
///////////////////////////////////////////////////////////////////
/// A factory for creating Components on demand, based on a string type name
/// The template arguments after ComponentFactory are the types of the arguments
/// to the Component constructor.
class ComponentFactory
: public Factory<Component, ComponentFactory, const std::string&, Options&, Solver*> {
public:
static constexpr auto type_name = "Component";
static constexpr auto section_name = "component";
static constexpr auto option_name = "type";
static constexpr auto default_type = "none";
};
/// Simpler name for Factory registration helper class
///
/// Usage:
///
/// #include "component.hxx"
/// namespace {
/// RegisterComponent<MyComponent> registercomponentmine("mycomponent");
/// }
template <typename DerivedType>
using RegisterComponent = ComponentFactory::RegisterInFactory<DerivedType>;
/// Faster non-printing getter for Options
/// If this fails, it will throw BoutException
///
/// This version allows the value to be modified later
/// i.e. the value returned is not the "final" value.
///
/// @tparam T The type the option should be converted to
///
/// @param option The Option whose value will be returned
template<typename T>
T getNonFinal(const Options& option) {
if (!option.isSet()) {
throw BoutException("Option {:s} has no value", option.str());
}
try {
return bout::utils::variantStaticCastOrThrow<Options::ValueType, T>(option.value);
} catch (const std::bad_cast &e) {
// Convert to a more useful error message
throw BoutException("Could not convert {:s} to type {:s}",
option.str(), typeid(T).name());
}
}
#define TOSTRING_(x) #x
#define TOSTRING(x) TOSTRING_(x)
/// Faster non-printing getter for Options
/// If this fails, it will throw BoutException
///
/// This marks the value as final, both in the domain and the boundary.
/// Subsequent calls to "set" this option will raise an exception.
///
/// @tparam T The type the option should be converted to
///
/// @param option The Option whose value will be returned
/// @param location An optional string to indicate where this value is used
template<typename T>
T get(const Options& option, const std::string& location = "") {
#if CHECKLEVEL >= 1
// Mark option as final, both inside the domain and the boundary
const_cast<Options&>(option).attributes["final"] = location;
const_cast<Options&>(option).attributes["final-domain"] = location;
#endif
return getNonFinal<T>(option);
}
/// Check if an option can be fetched
/// Sets the final flag so setting the value
/// afterwards will lead to an error
bool isSetFinal(const Options& option, const std::string& location = "");
#if CHECKLEVEL >= 1
/// A wrapper around isSetFinal() which captures debugging information
///
/// Usage:
/// if (IS_SET(option["value"]));
#define IS_SET(option) \
isSetFinal(option, __FILE__ ":" TOSTRING(__LINE__))
#else
#define IS_SET(option) \
isSetFinal(option)
#endif
/// Check if an option can be fetched
/// Sets the final flag so setting the value in the domain
/// afterwards will lead to an error
bool isSetFinalNoBoundary(const Options& option, const std::string& location = "");
#if CHECKLEVEL >= 1
/// A wrapper around isSetFinalNoBoundary() which captures debugging information
///
/// Usage:
/// if (IS_SET_NOBOUNDARY(option["value"]));
#define IS_SET_NOBOUNDARY(option) \
isSetFinalNoBoundary(option, __FILE__ ":" TOSTRING(__LINE__))
#else
#define IS_SET_NOBOUNDARY(option) \
isSetFinalNoBoundary(option)
#endif
#if CHECKLEVEL >= 1
/// A wrapper around get<>() which captures debugging information
///
/// Usage:
/// auto var = GET_VALUE(Field3D, option["value"]);
#define GET_VALUE(Type, option) \
get<Type>(option, __FILE__ ":" TOSTRING(__LINE__))
#else
#define GET_VALUE(Type, option) \
get<Type>(option)
#endif
/// Faster non-printing getter for Options
/// If this fails, it will throw BoutException
///
/// This marks the value as final in the domain.
/// The caller is assuming that the boundary values are non-final or invalid.
/// Subsequent calls to "set" this option will raise an exception,
/// but calls to "setBoundary" will not.
///
/// @tparam T The type the option should be converted to
///
/// @param option The Option whose value will be returned
/// @param location An optional string to indicate where this value is used
template<typename T>
T getNoBoundary(const Options& option, const std::string& location = "") {
#if CHECKLEVEL >= 1
// Mark option as final inside the domain
const_cast<Options&>(option).attributes["final-domain"] = location;
#endif
return getNonFinal<T>(option);
}
#if CHECKLEVEL >= 1
/// A wrapper around get<>() which captures debugging information
///
/// Usage:
/// auto var = GET_NOBOUNDARY(Field3D, option["value"]);
#define GET_NOBOUNDARY(Type, option) \
getNoBoundary<Type>(option, __FILE__ ":" TOSTRING(__LINE__))
#else
#define GET_NOBOUNDARY(Type, option) \
getNoBoundary<Type>(option)
#endif
/// Check whether value is valid, returning true
/// if invalid i.e contains non-finite values
template<typename T>
bool hermesDataInvalid(const T& value) {
return false; // Default
}
/// Check Field3D values.
/// Doesn't check boundary cells
template<>
inline bool hermesDataInvalid(const Field3D& value) {
for (auto& i : value.getRegion("RGN_NOBNDRY")) {
if (!std::isfinite(value[i])) {
return true;
}
}
return false;
}
/// Set values in an option. This could be optimised, but
/// currently the is_value private variable would need to be modified.
///
/// If the value has been used then raise an exception (if CHECK >= 1)
/// This is to prevent values being modified after use.
///
/// @tparam T The type of the value to set. Usually this is inferred
template<typename T>
Options& set(Options& option, T value) {
// Check that the value has not already been used
#if CHECKLEVEL >= 1
if (option.hasAttribute("final")) {
throw BoutException("Setting value of {} but it has already been used in {}.",
option.name(), option.attributes["final"].as<std::string>());
}
if (option.hasAttribute("final-domain")) {
throw BoutException("Setting value of {} but it has already been used in {}.",
option.name(),
option.attributes["final-domain"].as<std::string>());
}
if (hermesDataInvalid(value)) {
throw BoutException("Setting invalid value for '{}'", option.str());
}
#endif
option.force(std::move(value));
return option;
}
/// Set values in an option. This could be optimised, but
/// currently the is_value private variable would need to be modified.
///
/// This version only checks that the boundary cells have not
/// already been used by a call to get, not a call to getNoBoundary
/// or getNonFinal.
///
/// @tparam T The type of the value to set. Usually this is inferred
template<typename T>
Options& setBoundary(Options& option, T value) {
// Check that the value has not already been used
#if CHECKLEVEL >= 1
if (option.hasAttribute("final")) {
throw BoutException("Setting boundary of {} but it has already been used in {}.",
option.name(), option.attributes["final"].as<std::string>());
}
#endif
option.force(std::move(value));
return option;
}
/// Add value to a given option. If not already set, treats
/// as zero and sets the option to the value.
///
/// @tparam T The type of the value to add. The existing value
/// will be casted to this type
///
/// @param option The value to modify (or set if not already set)
/// @param value The quantity to add.
template<typename T>
Options& add(Options& option, T value) {
if (!option.isSet()) {
return set(option, value);
} else {
try {
return set(option, value + bout::utils::variantStaticCastOrThrow<Options::ValueType, T>(option.value));
} catch (const std::bad_cast &e) {
// Convert to a more useful error message
throw BoutException("Could not convert {:s} to type {:s}",
option.str(), typeid(T).name());
}
}
}
/// Add value to a given option. If not already set, treats
/// as zero and sets the option to the value.
///
/// @param option The value to modify (or set if not already set)
/// @param value The quantity to add.
template<typename T>
Options& subtract(Options& option, T value) {
if (!option.isSet()) {
return set(option, -value);
} else {
try {
return set(option, bout::utils::variantStaticCastOrThrow<Options::ValueType, T>(option.value) - value);
} catch (const std::bad_cast &e) {
// Convert to a more useful error message
throw BoutException("Could not convert {:s} to type {:s}",
option.str(), typeid(T).name());
}
}
}
template<typename T>
void set_with_attrs(Options& option, T value, std::initializer_list<std::pair<std::string, Options::AttributeType>> attrs) {
option.force(value);
option.setAttributes(attrs);
}
#if CHECKLEVEL >= 1
template<>
inline void set_with_attrs(Options& option, Field3D value, std::initializer_list<std::pair<std::string, Options::AttributeType>> attrs) {
if (!value.isAllocated()) {
throw BoutException("set_with_attrs: Field3D assigned to {:s} is not allocated", option.str());
}
option.force(value);
option.setAttributes(attrs);
}
#endif
#endif // HERMES_COMPONENT_H
| 11,233
|
C++
|
.h
| 297
| 34.757576
| 137
| 0.694934
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,290
|
solkit_neutral_parallel_diffusion.hxx
|
bendudson_hermes-3/include/solkit_neutral_parallel_diffusion.hxx
|
#pragma once
#ifndef SOLKIT_NEUTRAL_PARALLEL_DIFFUSION_H
#define SOLKIT_NEUTRAL_PARALLEL_DIFFUSION_H
#include "component.hxx"
/// Add effective diffusion of neutrals in a 1D system
///
/// This version is intended to match the calculation of neutral diffusion
/// in SOL-KiT (ca 2022).
///
struct SOLKITNeutralParallelDiffusion : public Component {
///
/// alloptions
/// - units
/// - eV
/// - meters
/// - inv_meters_cubed
/// - <name>
/// - neutral_temperature [eV]
///
SOLKITNeutralParallelDiffusion(std::string name, Options &alloptions, Solver *) {
auto Tnorm = get<BoutReal>(alloptions["units"]["eV"]);
auto& options = alloptions[name];
neutral_temperature = options["neutral_temperature"]
.doc("Neutral atom temperature [eV]")
.withDefault(3.0)
/ Tnorm; // Normalise
auto Nnorm = get<BoutReal>(alloptions["units"]["inv_meters_cubed"]);
auto rho_s0 = get<BoutReal>(alloptions["units"]["meters"]);
area_norm = 1. / (Nnorm * rho_s0);
}
///
/// Inputs
/// - species
/// - <all neutrals> # Applies to all neutral species
/// - AA
/// - density
///
/// Sets
/// - species
/// - <name>
/// - density_source
void transform(Options &state) override;
private:
BoutReal neutral_temperature; ///< Fixed neutral t
BoutReal area_norm; ///< Area normalisation [m^2]
};
namespace {
RegisterComponent<SOLKITNeutralParallelDiffusion>
register_solkit_neutral_parallel_diffusion("solkit_neutral_parallel_diffusion");
}
#endif // SOLKIT_NEUTRAL_PARALLEL_DIFFUSION_H
| 1,609
|
C++
|
.h
| 51
| 28.411765
| 84
| 0.661509
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,291
|
set_temperature.hxx
|
bendudson_hermes-3/include/set_temperature.hxx
|
#pragma once
#ifndef SET_TEMPERATURE_H
#define SET_TEMPERATURE_H
#include "component.hxx"
/// Set species temperature to the temperature of another species
///
/// # Example
///
/// [hermes]
/// components = e, d, ...
///
/// [e]
/// type = ... // Evolve Te
///
/// [d]
/// type = set_temperature, ...
///
/// temperature_from = e // Set Td = Te
struct SetTemperature : public Component {
/// Inputs
/// - <name>
/// - temperature_from name of species
SetTemperature(std::string name, Options& alloptions, Solver* UNUSED(solver))
: name(name) {
AUTO_TRACE();
auto& options = alloptions[name];
temperature_from = options["temperature_from"]
.doc("Name of species to take temperature from (e.g 'e')")
.as<std::string>();
diagnose = options["diagnose"]
.doc("Save additional output diagnostics")
.withDefault<bool>(false);
}
///
/// Inputs
/// - species
/// - <temperature_from>
/// - temperature
///
/// Sets in the state:
/// - species
/// - <name>
/// - temperature
/// - pressure (if density is set)
///
void transform(Options& state) override {
AUTO_TRACE();
// Get the temperature
T = GET_NOBOUNDARY(Field3D, state["species"][temperature_from]["temperature"]);
// Set temperature
auto& species = state["species"][name];
set(species["temperature"], T);
if (isSetFinalNoBoundary(species["density"])) {
// Note: The boundary of N may not be set yet
auto N = GET_NOBOUNDARY(Field3D, species["density"]);
set(species["pressure"], N * T);
}
}
void outputVars(Options& state) override {
AUTO_TRACE();
if (diagnose) {
auto Tnorm = get<BoutReal>(state["Tnorm"]);
// Save temperature to output files
set_with_attrs(state[std::string("T") + name], T,
{{"time_dimension", "t"},
{"units", "eV"},
{"conversion", Tnorm},
{"standard_name", "temperature"},
{"long_name", name + " temperature set from " + temperature_from},
{"species", name},
{"source", "set_temperature"}});
}
}
private:
std::string name; ///< Short name of species e.g "e"
std::string temperature_from; ///< The species that the temperature is taken from
Field3D T; ///< The temperature
bool diagnose; ///< Output diagnostics?
};
namespace {
RegisterComponent<SetTemperature> registercomponentsettemperature("set_temperature");
}
#endif // SET_TEMPERATURE_H
| 2,691
|
C++
|
.h
| 83
| 26.457831
| 88
| 0.574238
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,292
|
simple_conduction.hxx
|
bendudson_hermes-3/include/simple_conduction.hxx
|
#pragma once
#ifndef SIMPLE_CONDUCTION_H
#define SIMPLE_CONDUCTION_H
#include <bout/constants.hxx>
#include <bout/fv_ops.hxx>
#include "component.hxx"
/// Simplified models of parallel heat conduction
///
/// Intended mainly for testing.
///
/// Expressions taken from:
/// https://farside.ph.utexas.edu/teaching/plasma/lectures1/node35.html
struct SimpleConduction : public Component {
SimpleConduction(std::string name, Options& alloptions, Solver*) : name(name) {
auto& units = alloptions["units"];
Tnorm = units["eV"];
Nnorm = units["inv_meters_cubed"];
BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>();
auto& options = alloptions[name];
BoutReal kappa_coefficient =
options["kappa_coefficient"]
.doc("Numerical coefficient in parallel heat conduction. Default is 3.16 for "
"electrons, 3.9 otherwise")
.withDefault((name == "e") ? 3.16 : 3.9);
if (name == "e") {
// Electrons
kappa0 = kappa_coefficient * 6 * sqrt(2 * SI::Mp) * pow(PI * SI::qe * Tnorm, 1.5)
* SQ(SI::e0) / (SQ(SQ(SI::qe)) * Nnorm) * Omega_ci;
} else {
// Ions
kappa0 = kappa_coefficient * 12 * sqrt(SI::Mp) * pow(PI * SI::qe * Tnorm, 1.5)
* SQ(SI::e0) / (SQ(SQ(SI::qe)) * Nnorm) * Omega_ci;
}
// Fix the temperature in the heat conduction coefficients
temperature = options["conduction_temperature"]
.doc("Fix temperature in the calculation of the Coulomb log and "
"conduction coefficient. < 0 for not fixed")
.withDefault<BoutReal>(-1.0)
/ Tnorm;
density = options["conduction_density"]
.doc("Fix density in the calculation of the Coulomb log and conduction "
"coefficient. < 0 for not fixed")
.withDefault<BoutReal>(-1.0)
/ Nnorm;
boundary_flux = options["conduction_boundary_flux"]
.doc("Allow heat conduction through sheath boundaries?")
.withDefault<bool>(false);
}
void transform(Options& state) override {
auto& species = state["species"][name];
// Species time-evolving temperature
Field3D T = GET_NOBOUNDARY(Field3D, species["temperature"]);
Field3D Tcoef = T; // Temperature used in coefficients.
if (temperature > 0.0) {
Tcoef = temperature; // Fixed
}
Field3D N;
if (density > 0.0) {
N = density;
} else {
N = GET_NOBOUNDARY(Field3D, species["density"]);
}
auto AA = get<BoutReal>(species["AA"]);
Field3D coulomb_log = 6.6 - 0.5 * log(N * Nnorm / 1e20) + 1.5 * log(Tcoef * Tnorm);
// Parallel heat conduction coefficient
Field3D kappa_par = kappa0 * pow(Tcoef, 2.5) / (coulomb_log * sqrt(AA));
// Note: Flux through boundary turned off by default, because sheath heat flux
// is calculated and removed separately
Field3D DivQ = FV::Div_par_K_Grad_par(kappa_par, T, boundary_flux);
add(species["energy_source"], DivQ);
}
private:
std::string name; ///< Name of the species e.g. "e"
BoutReal kappa0; ///< Pre-calculated constant in heat conduction coefficient
BoutReal Nnorm, Tnorm; ///< Normalisation coefficients
BoutReal temperature; ///< Fix temperature if > 0
BoutReal density; ///< Fix density if > 0
bool boundary_flux; ///< Allow flux through sheath boundaries?
};
namespace {
RegisterComponent<SimpleConduction>
registercomponentsimpleconduction("simple_conduction");
}
#endif // SIMPLE_CONDUCTION_H
| 3,581
|
C++
|
.h
| 84
| 36.107143
| 90
| 0.636076
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,293
|
electromagnetic.hxx
|
bendudson_hermes-3/include/electromagnetic.hxx
|
#pragma once
#ifndef ELECTROMAGNETIC_H
#define ELECTROMAGNETIC_H
#include "component.hxx"
class Laplacian;
/// Electromagnetic potential A||
///
/// Reinterprets all species' parallel momentum as a combination
/// of a parallel flow and a magnetic contribution, i.e. canonical momentum.
///
/// m n v_{||} + Z e n A_{||}
///
/// Changes the "momentum" of each species so that after this component
/// the momentuum of each species is just
///
/// m n v_{||}
///
/// This component should be run after all species have set their
/// momentum, but before the momentum is used e.g to set boundary
/// conditions.
///
/// Calculates the electromagnetic potential A_{||} using
///
/// Laplace(Apar) - alpha_em * Apar = -Ajpar
///
/// By default outputs Apar every timestep. When `diagnose = true` in
/// also saves alpha_em and Ajpar.
///
struct Electromagnetic : public Component {
/// Options
/// - units
/// - <name>
/// - diagnose Saves Ajpar and alpha_em time-dependent values
///
Electromagnetic(std::string name, Options &options, Solver *solver);
/// Inputs
/// - species
/// - <..> All species with charge and parallel momentum
/// - charge
/// - momentum
/// - density
/// - AA
///
/// Sets
/// - species
/// - <..> All species with charge and parallel momentum
/// - momentum (modifies) to m n v||
/// - velocity (modifies) to v||
/// - fields
/// - Apar Electromagnetic potential
///
void transform(Options &state) override;
// Save and restore Apar from restart files
void restartVars(Options& state) override;
void outputVars(Options &state) override;
private:
Field3D Apar; // Electromagnetic potential A_||
Field3D Ajpar; // Total parallel current density
Field3D alpha_em; // Coefficient
BoutReal beta_em; // Normalisation coefficient mu_0 e T n / B^2
std::unique_ptr<Laplacian> aparSolver; // Laplacian solver in X-Z
bool const_gradient; // Set neumann boundaries by extrapolation
BoutReal apar_boundary_timescale; // Relaxation timescale
BoutReal last_time; // The last time the boundaries were updated
bool magnetic_flutter; ///< Set the magnetic flutter term?
Field3D Apar_flutter;
bool diagnose; ///< Output additional diagnostics?
};
namespace {
RegisterComponent<Electromagnetic> registercomponentelectromagnetic("electromagnetic");
}
#endif // ELECTROMAGNETIC_H
| 2,428
|
C++
|
.h
| 72
| 31.527778
| 87
| 0.693259
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,294
|
sheath_boundary_insulating.hxx
|
bendudson_hermes-3/include/sheath_boundary_insulating.hxx
|
#pragma once
#ifndef SHEATH_BOUNDARY_INSULATING_H
#define SHEATH_BOUNDARY_INSULATING_H
#include "component.hxx"
/// Insulating sheath boundary condition at the wall in Y
///
/// This is a collective component, because it couples all charged species
///
/// Adapted from the `sheath_boundary` component, but always sets the current
/// density to zero
struct SheathBoundaryInsulating : public Component {
SheathBoundaryInsulating(std::string name, Options &options, Solver *);
///
/// Inputs
/// - species
/// - e
/// - density
/// - temperature
/// - pressure Optional
/// - velocity Optional
/// - mass Optional
/// - adiabatic Optional. Ratio of specific heats, default 5/3.
/// - <ions> if charge is set (i.e. not neutrals)
/// - charge
/// - mass
/// - density
/// - temperature
/// - pressure Optional
/// - velocity Optional. Default 0
/// - momentum Optional. Default mass * density * velocity
/// - adiabatic Optional. Ratio of specific heats, default 5/3.
/// - fields
/// - phi Optional. If not set, calculated at boundary (see note below)
///
/// Outputs
/// - species
/// - e
/// - density Sets boundary
/// - temperature Sets boundary
/// - velocity Sets boundary
/// - energy_source
/// - <ions>
/// - density Sets boundary
/// - temperature Sets boundary
/// - velocity Sets boundary
/// - momentum Sets boundary
/// - energy_source
/// - fields
/// - phi Sets boundary
///
/// If the field phi is set, then this is used in the boundary condition.
/// If not set, phi at the boundary is calculated and stored in the state.
/// Note that phi in the domain will not be set, so will be invalid data.
///
///
void transform(Options &state) override;
private:
BoutReal Ge; // Secondary electron emission coefficient
BoutReal sin_alpha; // sin of angle between magnetic field and wall.
bool lower_y; // Boundary on lower y?
bool upper_y; // Boundary on upper y?
BoutReal gamma_e; ///< Electron sheath heat transmission
};
namespace {
RegisterComponent<SheathBoundaryInsulating>
registercomponentsheathboundaryinsulating("sheath_boundary_insulating");
}
#endif // SHEATH_BOUNDARY_INSULATING_H
| 2,378
|
C++
|
.h
| 68
| 32.308824
| 78
| 0.645372
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,295
|
recycling.hxx
|
bendudson_hermes-3/include/recycling.hxx
|
#pragma once
#ifndef RECYCLING_H
#define RECYCLING_H
#include "component.hxx"
/// Convert fluxes of species at boundaries
///
/// Since this must be calculated after boundary fluxes (e.g. sheath),
/// it is included as a top-level component
///
struct Recycling : public Component {
/// Inputs
///
/// - <name>
/// - species A comma-separated list of species to recycle
/// - <species>
/// - recycle_as The species to recycle into
/// - recycle_multiplier The recycled flux multiplier, between 0 and 1
/// - recycle_energy The energy of the recycled particles [eV]
///
Recycling(std::string name, Options &alloptions, Solver *);
/// Inputs
///
/// - species
/// - <species>
/// - density
/// - velocity
///
/// Outputs
///
/// - species
/// - <species>
/// - density_source
///
void transform(Options &state) override;
void outputVars(Options &state) override;
private:
struct RecycleChannel {
std::string from; ///< The species name to recycle
std::string to; ///< Species to recycle to
/// Flux multiplier (recycling fraction).
/// Combination of recycling fraction and species change e.g h+ -> h2 results in 0.5 multiplier
BoutReal target_multiplier, sol_multiplier, pfr_multiplier, pump_multiplier;
BoutReal target_energy, sol_energy, pfr_energy; ///< Energy of recycled particle (normalised to Tnorm)
BoutReal target_fast_recycle_fraction, pfr_fast_recycle_fraction, sol_fast_recycle_fraction; ///< Fraction of ions undergoing fast reflection
BoutReal target_fast_recycle_energy_factor, sol_fast_recycle_energy_factor, pfr_fast_recycle_energy_factor; ///< Fraction of energy retained by fast recycled neutrals
};
std::vector<RecycleChannel> channels; // Recycling channels
bool target_recycle, sol_recycle, pfr_recycle, neutral_pump; ///< Flags for enabling recycling in different regions
bool diagnose; ///< Save additional post-processing variables?
Field3D density_source, energy_source; ///< Recycling particle and energy sources for all locations
Field3D energy_flow_ylow, energy_flow_xlow; ///< Cell edge fluxes used for calculating fast recycling energy source
Field3D particle_flow_xlow; ///< Radial wall particle fluxes for recycling calc. No need to get poloidal from here, it's calculated from sheath velocity
Field2D is_pump; ///< 1 = pump, 0 = no pump. Works only in SOL/PFR. Provided by user in grid file.
// Recycling particle and energy sources for the different sources of recycling
// Note that SOL, PFR and pump are not applicable to 1D
Field3D target_recycle_density_source, target_recycle_energy_source;
Field3D wall_recycle_density_source, wall_recycle_energy_source; ///< Recycling particle and energy sources for pfr + sol recycling
Field3D pump_density_source, pump_energy_source; ///< Recycling particle and energy sources for pump recycling
};
namespace {
RegisterComponent<Recycling> registercomponentrecycling("recycling");
}
#endif // RECYCLING_H
| 3,066
|
C++
|
.h
| 63
| 45.571429
| 172
| 0.724046
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,296
|
hermes_utils.hxx
|
bendudson_hermes-3/include/hermes_utils.hxx
|
#pragma once
#ifndef HERMES_UTILS_H
#define HERMES_UTILS_H
inline BoutReal floor(BoutReal value, BoutReal min) {
if (value < min)
return min;
return value;
}
template<typename T, typename = bout::utils::EnableIfField<T>>
inline T clamp(const T& var, BoutReal lo, BoutReal hi, const std::string& rgn = "RGN_ALL") {
checkData(var);
T result = copy(var);
BOUT_FOR(d, var.getRegion(rgn)) {
if (result[d] < lo) {
result[d] = lo;
} else if (result[d] > hi) {
result[d] = hi;
}
}
return result;
}
template<typename T, typename = bout::utils::EnableIfField<T>>
Ind3D indexAt(const T& f, int x, int y, int z) {
int ny = f.getNy();
int nz = f.getNz();
return Ind3D{(x * ny + y) * nz + z, ny, nz};
}
#endif // HERMES_UTILS_H
| 768
|
C++
|
.h
| 28
| 24.5
| 92
| 0.648501
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,297
|
thermal_force.hxx
|
bendudson_hermes-3/include/thermal_force.hxx
|
#pragma once
#ifndef THERMAL_FORCE_H
#define THERMAL_FORCE_H
#include "component.hxx"
/// Simple calculation of the thermal force
///
/// Important: This implements a quite crude approximation,
/// which is intended for initial development and testing.
/// The expressions used are only valid for trace heavy ions and
/// light main ion species, and would not be valid for Helium impurities
/// in a D-T plasma, for example. For this reason only collisions
/// where one ion has an atomic mass < 4, and the other an atomic mass > 10
/// are considered. Warning messages will be logged for species combinations
/// which are not calculated.
///
/// Options used:
///
/// - <name>
/// - electron_ion : bool Include electron-ion collisions?
/// - ion_ion : bool Include ion-ion elastic collisions?
///
struct ThermalForce : public Component {
ThermalForce(std::string name, Options& alloptions, Solver*) {
Options& options = alloptions[name];
electron_ion = options["electron_ion"]
.doc("Include electron-ion collisions?")
.withDefault<bool>(true);
ion_ion = options["ion_ion"]
.doc("Include ion-ion elastic collisions?")
.withDefault<bool>(true);
}
/// Inputs
/// - species
/// - e [ if electron_ion true ]
/// - charge
/// - density
/// - temperature
/// - <species>
/// - charge [ Checks, skips species if not set ]
/// - AA
/// - temperature [ If AA < 4 i.e. "light" species ]
///
/// Outputs
/// - species
/// - e
/// - momentum_source [ if electron_ion true ]
/// - <species> [ if AA < 4 ("light") or AA > 10 ("heavy") ]
/// - momentum_source
///
void transform(Options &state) override;
private:
bool electron_ion; ///< Include electron-ion collisions?
bool ion_ion; ///< Include ion-ion elastic collisions?
bool first_time{true}; ///< True the first time transform() is called
};
namespace {
RegisterComponent<ThermalForce> registercomponentthermalforce("thermal_force");
}
#endif // THERMAL_FORCE_H
| 2,134
|
C++
|
.h
| 59
| 32.610169
| 79
| 0.640542
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,298
|
solkit_hydrogen_charge_exchange.hxx
|
bendudson_hermes-3/include/solkit_hydrogen_charge_exchange.hxx
|
#pragma once
#ifndef SOLKIT_HYDROGEN_CHARGE_EXCHANGE_H
#define SOLKIT_HYDROGEN_CHARGE_EXCHANGE_H
#include "component.hxx"
/// SOL-KiT Hydrogen charge exchange total rate coefficient
///
struct SOLKITHydrogenChargeExchange : public Component {
///
/// @param alloptions Settings, which should include:
/// - units
/// - inv_meters_cubed
/// - seconds
SOLKITHydrogenChargeExchange(std::string, Options& alloptions, Solver*) {
// Get the units
const auto& units = alloptions["units"];
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
rho_s0 = get<BoutReal>(units["meters"]);
}
/// Calculate the charge exchange cross-section
///
/// atom + ion -> atom + ion
///
/// Assumes that both atom and ion have:
/// - AA
/// - density
/// - velocity
///
/// Sets in all species:
/// - momentum_source
///
void calculate_rates(Options& atom, Options& ion);
protected:
BoutReal Nnorm, rho_s0; ///< Normalisations
};
/// Hydrogen charge exchange
/// Templated on a char to allow 'h', 'd' and 't' species to be treated with the same code
///
/// @tparam Isotope The isotope ('h', 'd' or 't') of the atom and ion
template <char Isotope>
struct SOLKITHydrogenChargeExchangeIsotope : public SOLKITHydrogenChargeExchange {
SOLKITHydrogenChargeExchangeIsotope(std::string name, Options& alloptions, Solver* solver)
: SOLKITHydrogenChargeExchange(name, alloptions, solver) {}
void transform(Options& state) override {
calculate_rates(state["species"][{Isotope}], // e.g. "h"
state["species"][{Isotope, '+'}]); // e.g. "d+"
}
};
namespace {
/// Register three components, one for each hydrogen isotope
RegisterComponent<SOLKITHydrogenChargeExchangeIsotope<'h'>>
register_solkit_cx_hh("solkit h + h+ -> h+ + h");
RegisterComponent<SOLKITHydrogenChargeExchangeIsotope<'d'>>
register_solkit_cx_dd("solkit d + d+ -> d+ + d");
RegisterComponent<SOLKITHydrogenChargeExchangeIsotope<'t'>>
register_solkit_cx_tt("solkit t + t+ -> t+ + t");
} // namespace
#endif // SOLKIT_HYDROGEN_CHARGE_EXCHANGE_H
| 2,126
|
C++
|
.h
| 57
| 34.298246
| 92
| 0.68559
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,299
|
fixed_velocity.hxx
|
bendudson_hermes-3/include/fixed_velocity.hxx
|
#pragma once
#ifndef FIXED_VELOCITY_H
#define FIXED_VELOCITY_H
#include "component.hxx"
/// Set parallel velocity to a fixed value
///
struct FixedVelocity : public Component {
FixedVelocity(std::string name, Options& alloptions, Solver* UNUSED(solver))
: name(name) {
AUTO_TRACE();
auto& options = alloptions[name];
// Normalisation of velocity
auto& units = alloptions["units"];
const BoutReal Cs0 = units["meters"].as<BoutReal>() / units["seconds"].as<BoutReal>();
// Get the velocity and normalise
V = options["velocity"].as<Field3D>() / Cs0;
}
/// This sets in the state
/// - species
/// - <name>
/// - velocity
/// - momentum
void transform(Options& state) override {
AUTO_TRACE();
auto& species = state["species"][name];
set(species["velocity"], V);
// If density is set, also set momentum
if (isSetFinalNoBoundary(species["density"])) {
const Field3D N = getNoBoundary<Field3D>(species["density"]);
const BoutReal AA = get<BoutReal>(species["AA"]); // Atomic mass
set(species["momentum"], AA * N * V);
}
}
void outputVars(Options& state) override {
AUTO_TRACE();
auto Cs0 = get<BoutReal>(state["Cs0"]);
// Save the density, not time dependent
set_with_attrs(state[std::string("V") + name], V,
{{"units", "m / s"},
{"conversion", Cs0},
{"long_name", name + " parallel velocity"},
{"standard_name", "velocity"},
{"species", name},
{"source", "fixed_velocity"}});
}
private:
std::string name; ///< Short name of species e.g "e"
Field3D V; ///< Species velocity (normalised)
};
namespace {
RegisterComponent<FixedVelocity> registercomponentfixedvelocity("fixed_velocity");
}
#endif // FIXED_VELOCITY_H
| 1,869
|
C++
|
.h
| 53
| 29.509434
| 90
| 0.618545
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,300
|
evolve_pressure.hxx
|
bendudson_hermes-3/include/evolve_pressure.hxx
|
#pragma once
#ifndef EVOLVE_PRESSURE_H
#define EVOLVE_PRESSURE_H
#include <bout/field3d.hxx>
#include "component.hxx"
/// Evolves species pressure in time
///
/// # Mesh inputs
///
/// P<name>_src A source of pressure, in Pascals per second
/// This can be over-ridden by the `source` option setting.
///
struct EvolvePressure : public Component {
///
/// # Inputs
///
/// - <name>
/// - bndry_flux Allow flows through radial boundaries? Default is true
/// - density_floor Minimum density floor. Default 1e-5 normalised units.
/// - diagnose Output additional diagnostic fields?
/// - evolve_log Evolve logarithm of pressure? Default is false
/// - hyper_z Hyper-diffusion in Z
/// - kappa_coefficient Heat conduction constant. Default is 3.16 for electrons, 3.9 otherwise
/// - kappa_limit_alpha Flux limiter, off by default.
/// - poloidal_flows Include poloidal ExB flows? Default is true
/// - precon Enable preconditioner? Note: solver may not use it even if enabled.
/// - p_div_v Use p * Div(v) form? Default is v * Grad(p) form
/// - thermal_conduction Include parallel heat conduction? Default is true
///
/// - P<name> e.g. "Pe", "Pd+"
/// - source Source of pressure [Pa / s].
/// NOTE: This overrides mesh input P<name>_src
/// - source_only_in_core Zero the source outside the closed field-line region?
/// - neumann_boundary_average_z Apply Neumann boundaries with Z average?
///
EvolvePressure(std::string name, Options& options, Solver* solver);
/// Inputs
/// - species
/// - <name>
/// - density
///
/// Sets
/// - species
/// - <name>
/// - pressure
/// - temperature Requires density
///
void transform(Options& state) override;
///
/// Optional inputs
///
/// - species
/// - <name>
/// - velocity. Must have sound_speed or temperature
/// - energy_source
/// - collision_rate (needed if thermal_conduction on)
/// - fields
/// - phi Electrostatic potential -> ExB drift
///
void finally(const Options& state) override;
void outputVars(Options& state) override;
/// Preconditioner
///
void precon(const Options &UNUSED(state), BoutReal gamma) override;
private:
std::string name; ///< Short name of the species e.g. h+
Field3D P; ///< Pressure (normalised)
Field3D T, N; ///< Temperature, density
bool bndry_flux;
bool neumann_boundary_average_z; ///< Apply neumann boundary with Z average?
bool poloidal_flows;
bool thermal_conduction; ///< Include thermal conduction?
BoutReal kappa_coefficient; ///< Leading numerical coefficient in parallel heat flux calculation
BoutReal kappa_limit_alpha; ///< Flux limit if >0
bool p_div_v; ///< Use p*Div(v) form? False -> v * Grad(p)
bool evolve_log; ///< Evolve logarithm of P?
Field3D logP; ///< Natural logarithm of P
BoutReal density_floor; ///< Minimum density for calculating T
bool low_n_diffuse_perp; ///< Cross-field diffusion at low density?
BoutReal temperature_floor; ///< Low temperature scale for low_T_diffuse_perp
bool low_T_diffuse_perp; ///< Add cross-field diffusion at low temperature?
BoutReal pressure_floor; ///< When non-zero pressure is needed
bool low_p_diffuse_perp; ///< Add artificial cross-field diffusion at low electron pressure?
Field3D kappa_par; ///< Parallel heat conduction coefficient
Field3D source, final_source; ///< External pressure source
Field3D Sp; ///< Total pressure source
FieldGeneratorPtr source_prefactor_function;
BoutReal hyper_z; ///< Hyper-diffusion
BoutReal hyper_z_T; ///< 4th-order dissipation in T
bool diagnose; ///< Output additional diagnostics?
bool enable_precon; ///< Enable preconditioner?
BoutReal source_normalisation; ///< Normalisation factor [Pa/s]
BoutReal time_normalisation; ///< Normalisation factor [s]
bool source_time_dependent; ///< Is the input source time dependent?
Field3D flow_xlow, flow_ylow; ///< Energy flow diagnostics
Field3D flow_ylow_conduction; ///< Conduction energy flow diagnostics
Field3D flow_ylow_kinetic; ///< Parallel flow of kinetic energy
bool numerical_viscous_heating; ///< Include heating due to numerical viscosity?
bool fix_momentum_boundary_flux; ///< Fix momentum flux to boundary condition?
Field3D Sp_nvh; ///< Pressure source due to artificial viscosity
};
namespace {
RegisterComponent<EvolvePressure> registercomponentevolvepressure("evolve_pressure");
}
#endif // EVOLVE_PRESSURE_H
| 4,675
|
C++
|
.h
| 105
| 41.704762
| 101
| 0.678972
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,301
|
sound_speed.hxx
|
bendudson_hermes-3/include/sound_speed.hxx
|
#pragma once
#ifndef SOUND_SPEED_H
#define SOUND_SPEED_H
#include "component.hxx"
#include <bout/constants.hxx>
/// Calculate the system sound speed
///
/// This uses the sum of all species pressures and mass densities
/// so should run after those have been set.
struct SoundSpeed : public Component {
SoundSpeed(std::string name, Options &alloptions, Solver*) {
Options &options = alloptions[name];
electron_dynamics = options["electron_dynamics"]
.doc("Include electron sound speed?")
.withDefault<bool>(true);
alfven_wave = options["alfven_wave"]
.doc("Include Alfven wave speed?")
.withDefault<bool>(false);
if (alfven_wave) {
// Calculate normalisation factor
const auto& units = alloptions["units"];
const auto Bnorm = get<BoutReal>(units["Tesla"]);
const auto Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
const auto Cs0 = get<BoutReal>(units["meters"]) / get<BoutReal>(units["seconds"]);
beta_norm = Bnorm / sqrt(SI::mu0 * Nnorm * SI::Mp) / Cs0;
}
temperature_floor = options["temperature_floor"]
.doc("Minimum temperature when calculating sound speeds [eV]")
.withDefault(0.0);
fastest_wave_factor = options["fastest_wave_factor"]
.doc("Multiply the fastest wave by this factor, affecting lax flux strength")
.withDefault(0.0);
if (temperature_floor > 0.0) {
temperature_floor /= get<BoutReal>(alloptions["units"]["eV"]);
}
}
/// This sets in the state
/// - sound_speed The collective sound speed, based on total pressure and total mass density
/// - fastest_wave The highest species sound speed at each point in the domain
///
/// Optional inputs:
/// - species
/// - ... // Iterates over all species
/// - density
/// - AA // Atomic mass
/// - pressure
///
void transform(Options &state) override;
private:
bool electron_dynamics; ///< Include electron sound speed?
bool alfven_wave; ///< Include Alfven wave speed?
BoutReal beta_norm{0.0}; ///< Normalisation factor for Alfven speed
BoutReal temperature_floor; ///< Minimum temperature when calculating speed
BoutReal fastest_wave_factor; ///< Multiply the fastest wave by this factor
};
namespace {
RegisterComponent<SoundSpeed> registercomponentsoundspeed("sound_speed");
}
#endif // SOUND_SPEED_H
| 2,375
|
C++
|
.h
| 59
| 36.254237
| 98
| 0.686496
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,302
|
binormal_stpm.hxx
|
bendudson_hermes-3/include/binormal_stpm.hxx
|
#pragma once
#ifndef BINORMAL_STPM_H
#define BINORMAL_STPM_H
#include <bout/field3d.hxx>
#include "component.hxx"
/// Adds terms to Density, Pressure and Momentum equations following the
/// stellarator 2-point model from Yuhe Feng et al., PPCF 53 (2011) 024009
/// The terms add the effective parallel contribution of perpendicular transport
/// which is of significance in long connection length scenarios.
/// B Shanahan 2023 <brendan.shanahan@ipp.mpg.de>
struct BinormalSTPM : public Component {
///
/// # Inputs
///
/// - <name>
/// - D Perpendicular density diffusion coefficient
/// - chi Perpendicular heat diffusion coefficient
/// - nu Perpendicular momentum diffusion coefficient
/// - Theta Field line pitch as described by Feng et al.
///
BinormalSTPM(std::string name, Options& options, Solver* solver);
/// Sets
/// - species
/// - <name>
/// - pressure correction
/// - momentum correction
/// - density correction
///
void transform(Options& state) override;
void outputVars(Options &state) override;
private:
std::string name; ///< Short name of the species e.g. h+
bool diagnose; ///< Output diagnostics?
Field3D Theta, chi, D, nu; ///< Field line pitch, anomalous thermal, momentum diffusion
Field3D nu_Theta, chi_Theta, D_Theta; ///< nu/Theta, chi/Theta, D/Theta, precalculated
Field3D Theta_inv; ///< Precalculate 1/Theta
};
namespace {
RegisterComponent<BinormalSTPM> registercomponentbinormalstpm("binormal_stpm");
}
#endif // BINORMAL_STPM
| 1,580
|
C++
|
.h
| 41
| 36.073171
| 89
| 0.704843
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,303
|
fixed_temperature.hxx
|
bendudson_hermes-3/include/fixed_temperature.hxx
|
#pragma once
#ifndef FIXED_TEMPERATURE_H
#define FIXED_TEMPERATURE_H
#include "component.hxx"
/// Set species temperature to a fixed value
///
struct FixedTemperature : public Component {
/// Inputs
/// - <name>
/// - temperature value (expression) in units of eV
FixedTemperature(std::string name, Options& alloptions, Solver* UNUSED(solver))
: name(name) {
AUTO_TRACE();
auto& options = alloptions[name];
// Normalisation of temperature
auto Tnorm = get<BoutReal>(alloptions["units"]["eV"]);
// Get the temperature and normalise
T = options["temperature"].doc("Constant temperature [eV]").as<Field3D>()
/ Tnorm; // Normalise
diagnose = options["diagnose"]
.doc("Save additional output diagnostics")
.withDefault<bool>(false);
}
/// Sets in the state the temperature and pressure of the species
///
/// Inputs
/// - species
/// - <name>
/// - density (optional)
///
/// Sets in the state
///
/// - species
/// - <name>
/// - temperature
/// - pressure (if density is set)
void transform(Options& state) override {
AUTO_TRACE();
auto& species = state["species"][name];
set(species["temperature"], T);
// If density is set, also set pressure
if (isSetFinalNoBoundary(species["density"])) {
// Note: The boundary of N may not be set yet
auto N = GET_NOBOUNDARY(Field3D, species["density"]);
P = N * T;
set(species["pressure"], P);
}
}
void outputVars(Options& state) override {
AUTO_TRACE();
auto Tnorm = get<BoutReal>(state["Tnorm"]);
// Save temperature to output files
set_with_attrs(state[std::string("T") + name], T,
{{"units", "eV"},
{"conversion", Tnorm},
{"standard_name", "temperature"},
{"long_name", name + " temperature"},
{"species", name},
{"source", "fixed_temperature"}});
if (diagnose) {
auto Nnorm = get<BoutReal>(state["Nnorm"]);
BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation
// Save pressure as time-varying field
set_with_attrs(state[std::string("P") + name], P,
{{"time_dimension", "t"},
{"units", "Pa"},
{"conversion", Pnorm},
{"standard_name", "pressure"},
{"long_name", name + " pressure"},
{"species", name},
{"source", "fixed_temperature"}});
}
}
private:
std::string name; ///< Short name of species e.g "e"
Field3D T; ///< Species temperature (normalised)
Field3D P; ///< Species pressure (normalised)
bool diagnose; ///< Output additional fields
};
namespace {
RegisterComponent<FixedTemperature> registercomponentfixedtemperature("fixed_temperature");
}
#endif // FIXED_TEMPERATURE_H
| 2,946
|
C++
|
.h
| 83
| 28.566265
| 91
| 0.588401
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,304
|
neutral_mixed.hxx
|
bendudson_hermes-3/include/neutral_mixed.hxx
|
#pragma once
#ifndef NEUTRAL_MIXED_H
#define NEUTRAL_MIXED_H
#include <memory>
#include <string>
#include <bout/invert_laplace.hxx>
#include "component.hxx"
/// Evolve density, parallel momentum and pressure
/// for a neutral gas species with cross-field diffusion
struct NeutralMixed : public Component {
///
/// @param name The name of the species e.g. "h"
/// @param options Top-level options. Settings will be taken from options[name]
/// @param solver Time-integration solver to be used
NeutralMixed(const std::string& name, Options& options, Solver *solver);
/// Modify the given simulation state
void transform(Options &state) override;
/// Use the final simulation state to update internal state
/// (e.g. time derivatives)
void finally(const Options &state) override;
/// Add extra fields for output, or set attributes e.g docstrings
void outputVars(Options &state) override;
/// Preconditioner
void precon(const Options &state, BoutReal gamma) override;
private:
std::string name; ///< Species name
Field3D Nn, Pn, NVn; // Density, pressure and parallel momentum
Field3D Vn; ///< Neutral parallel velocity
Field3D Tn; ///< Neutral temperature
Field3D Nnlim, Pnlim, logPnlim, Vnlim, Tnlim; // Limited in regions of low density
BoutReal AA; ///< Atomic mass (proton = 1)
Field3D Dnn; ///< Diffusion coefficient
Field3D DnnNn, DnnPn, DnnTn, DnnNVn; ///< Used for operators
bool sheath_ydown, sheath_yup;
BoutReal nn_floor; ///< Minimum Nn used when dividing NVn by Nn to get Vn.
BoutReal flux_limit; ///< Diffusive flux limit
BoutReal diffusion_limit; ///< Maximum diffusion coefficient
bool neutral_viscosity; ///< include viscosity?
bool evolve_momentum; ///< Evolve parallel momentum?
bool precondition {true}; ///< Enable preconditioner?
std::unique_ptr<Laplacian> inv; ///< Laplacian inversion used for preconditioning
Field3D density_source, pressure_source; ///< External input source
Field3D Sn, Sp, Snv; ///< Particle, pressure and momentum source
bool output_ddt; ///< Save time derivatives?
bool diagnose; ///< Save additional diagnostics?
Field3D particle_flow_ylow; ///< Flow diagnostics
Field3D energy_flow_ylow;
};
namespace {
RegisterComponent<NeutralMixed> registersolverneutralmixed("neutral_mixed");
}
#endif // NEUTRAL_MIXED_H
| 2,365
|
C++
|
.h
| 52
| 42.557692
| 84
| 0.743545
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,305
|
transform.hxx
|
bendudson_hermes-3/include/transform.hxx
|
#pragma once
#ifndef TRANSFORM_H
#define TRANSFORM_H
#include "component.hxx"
/// Apply changes to the state
///
struct Transform : public Component {
Transform(std::string name, Options& options, Solver*);
void transform(Options& state) override;
private:
std::map<std::string, std::string> transforms;
};
namespace {
RegisterComponent<Transform> registercomponenttransform("transform");
}
#endif // TRANSFORM_H
| 425
|
C++
|
.h
| 16
| 24.8125
| 69
| 0.779156
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,306
|
amjuel_reaction.hxx
|
bendudson_hermes-3/include/amjuel_reaction.hxx
|
#pragma once
#ifndef AMJUEL_REACTION_H
#define AMJUEL_REACTION_H
#include "component.hxx"
#include "integrate.hxx"
struct AmjuelReaction : public Component {
AmjuelReaction(std::string name, Options& alloptions, Solver*) {
// Get the units
const auto& units = alloptions["units"];
Tnorm = get<BoutReal>(units["eV"]);
Nnorm = get<BoutReal>(units["inv_meters_cubed"]);
FreqNorm = 1. / get<BoutReal>(units["seconds"]);
}
protected:
BoutReal Tnorm, Nnorm, FreqNorm; // Normalisations
BoutReal clip(BoutReal value, BoutReal min, BoutReal max) {
if (value < min)
return min;
if (value > max)
return max;
return value;
}
/// Evaluate a double polynomial fit in n and T
/// (page 20 of amjuel.pdf)
///
/// coefs[T][n]
/// Input in units:
/// n in m^-3
/// T in eV
///
/// Output in SI, units m^3/s, or eV m^3/s for energy loss
template <size_t rows, size_t cols>
BoutReal evaluate(const BoutReal (&coefs)[rows][cols], BoutReal T, BoutReal n) {
// Enforce range of validity
n = clip(n, 1e14, 1e22); // 1e8 - 1e16 cm^-3
T = clip(T, 0.1, 1e4);
BoutReal logntilde = log(n / 1e14); // Note: 1e8 cm^-3
BoutReal logT = log(T);
BoutReal result = 0.0;
BoutReal logT_n = 1.0; // log(T) ** n
for (size_t n = 0; n < cols; ++n) {
BoutReal logn_m = 1.0; // log(ntilde) ** m
for (size_t m = 0; m < rows; ++m) {
result += coefs[n][m] * logn_m * logT_n;
logn_m *= logntilde;
}
logT_n *= logT;
}
return exp(result) * 1e-6; // Note: convert cm^3 to m^3
}
/// Electron-driven reaction
/// e + from_ion -> to_ion [ + e? + e?]
///
/// Coefficients from Amjuel:
/// - rate_coefs Double-polynomial log fit [T][n] for <σv>
/// - radiation_coefs Double-polynomial log fit [T][n] for electron loss
/// electron_heating Energy added to electrons per reaction [eV]
template <size_t rows, size_t cols>
void electron_reaction(Options& electron, Options& from_ion, Options& to_ion,
const BoutReal (&rate_coefs)[rows][cols],
const BoutReal (&radiation_coefs)[rows][cols],
BoutReal electron_heating,
Field3D &reaction_rate,
Field3D &momentum_exchange,
Field3D &energy_exchange,
Field3D &energy_loss,
BoutReal rate_multiplier,
BoutReal radiation_multiplier) {
Field3D Ne = get<Field3D>(electron["density"]);
Field3D Te = get<Field3D>(electron["temperature"]);
Field3D N1 = get<Field3D>(from_ion["density"]);
Field3D T1 = get<Field3D>(from_ion["temperature"]);
Field3D V1 = get<Field3D>(from_ion["velocity"]);
auto AA = get<BoutReal>(from_ion["AA"]);
ASSERT1(AA == get<BoutReal>(to_ion["AA"]));
Field3D V2 = get<Field3D>(to_ion["velocity"]);
const BoutReal from_charge =
from_ion.isSet("charge") ? get<BoutReal>(from_ion["charge"]) : 0.0;
const BoutReal to_charge =
to_ion.isSet("charge") ? get<BoutReal>(to_ion["charge"]) : 0.0;
// Calculate reaction rate using cell averaging. Optionally scale by multiplier
reaction_rate = cellAverage(
[&](BoutReal ne, BoutReal n1, BoutReal te) {
return ne * n1 * evaluate(rate_coefs, te * Tnorm, ne * Nnorm) * Nnorm
/ FreqNorm * rate_multiplier;
},
Ne.getRegion("RGN_NOBNDRY"))(Ne, N1, Te);
// Particles
// For ionisation, "from_ion" is the neutral and "to_ion" is the ion
subtract(from_ion["density_source"], reaction_rate);
add(to_ion["density_source"], reaction_rate);
if (from_charge != to_charge) {
// To ensure quasineutrality, add electron density source
add(electron["density_source"], (to_charge - from_charge) * reaction_rate);
if (electron.isSet("velocity")) {
// Transfer of electron kinetic to thermal energy due to density source
auto Ve = get<Field3D>(electron["velocity"]);
auto Ae = get<BoutReal>(electron["AA"]);
add(electron["energy_source"], 0.5 * Ae * (to_charge - from_charge) * reaction_rate * SQ(Ve));
}
}
// Momentum
momentum_exchange = reaction_rate * AA * V1;
subtract(from_ion["momentum_source"], momentum_exchange);
add(to_ion["momentum_source"], momentum_exchange);
// Kinetic energy transfer to thermal energy
//
// This is a combination of three terms in the pressure
// (thermal energy) equation:
//
// d/dt(3/2 p_1) = ... - F_12 v_1 + W_12 - (1/2) m R v_1^2 // From ion
//
// d/dt(3/2 p_2) = ... - F_21 v_2 + W_21 + (1/2) m R v_2^2 // to_ion
//
// where forces are F_21 = -F_12, energy transfer W_21 = -W_12,
// and masses are equal so m_1 = m_2 = m
//
// Here the force F_21 = m R v_1 i.e. momentum_exchange
//
// As p_1 -> 0 the sum of the p_1 terms must go to zero.
// Hence:
//
// W_12 = F_12 v_1 + (1/2) m R v_1^2
// = -R m v_1^2 + (1/2) m R v_1^2
// = - (1/2) m R v_1^2
//
// d/dt(3/2 p_2) = - m R v_1 v_2 + (1/2) m R v_1^2 + (1/2) m R v_2^2
// = (1/2) m R (v_1 - v_2)^2
//
add(to_ion["energy_source"], 0.5 * AA * reaction_rate * SQ(V1 - V2));
// Ion thermal energy transfer
energy_exchange = reaction_rate * (3. / 2) * T1;
subtract(from_ion["energy_source"], energy_exchange);
add(to_ion["energy_source"], energy_exchange);
// Electron energy loss (radiation, ionisation potential)
energy_loss = cellAverage(
[&](BoutReal ne, BoutReal n1, BoutReal te) {
return ne * n1 * evaluate(radiation_coefs, te * Tnorm, ne * Nnorm) * Nnorm
/ (Tnorm * FreqNorm) * radiation_multiplier;
},
Ne.getRegion("RGN_NOBNDRY"))(Ne, N1, Te);
// Loss is reduced by heating
energy_loss -= (electron_heating / Tnorm) * reaction_rate * radiation_multiplier;
subtract(electron["energy_source"], energy_loss);
}
};
#endif // AMJUEL_REACTION_H
| 6,124
|
C++
|
.h
| 147
| 35.034014
| 102
| 0.589313
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,307
|
fixed_fraction_ions.hxx
|
bendudson_hermes-3/include/fixed_fraction_ions.hxx
|
#pragma once
#ifndef FIXED_FRACTION_IONS_H
#define FIXED_FRACTION_IONS_H
#include "component.hxx"
/// Set ion densities from electron densities
///
struct FixedFractionIons : public Component {
/// Inputs
/// - <name>
/// - fractions A comma-separated list of pairs separated by @
/// e.g. 'd+ @ 0.5, t+ @ 0.5'
FixedFractionIons(std::string name, Options &options, Solver *UNUSED(solver));
/// Required inputs
///
/// - species
/// - e
/// - density
///
/// Sets in the state the density of each species
///
/// - species
/// - <species1>
/// - density = <fraction1> * electron density
/// - ...
void transform(Options &state) override;
private:
std::vector<std::pair<std::string, BoutReal>> fractions;
};
namespace {
RegisterComponent<FixedFractionIons> registercomponentfixedfractionions("fixed_fraction_ions");
}
#endif // FIXED_FRACTION_IONS_H
| 930
|
C++
|
.h
| 32
| 26.59375
| 95
| 0.659193
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,308
|
test_extras.hxx
|
bendudson_hermes-3/tests/unit/test_extras.hxx
|
#ifndef TEST_EXTRAS_H__
#define TEST_EXTRAS_H__
#include "gtest/gtest.h"
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
#include "bout/boutcomm.hxx"
#include "bout/coordinates.hxx"
#include "bout/field3d.hxx"
#include "bout/mesh.hxx"
#include "bout/mpi_wrapper.hxx"
#include "bout/operatorstencil.hxx"
#include "bout/unused.hxx"
static constexpr BoutReal BoutRealTolerance{1e-15};
// FFTs have a slightly looser tolerance than other functions
static constexpr BoutReal FFTTolerance{1.e-12};
/// Does \p str contain \p substring?
::testing::AssertionResult IsSubString(const std::string& str,
const std::string& substring);
void fillField(Field3D& f, std::vector<std::vector<std::vector<BoutReal>>> values);
void fillField(Field2D& f, std::vector<std::vector<BoutReal>> values);
using bout::utils::EnableIfField;
/// Returns a field filled with the result of \p fill_function at each point
/// Arbitrary arguments can be passed to the field constructor
template <class T, class... Args, typename = EnableIfField<T>>
T makeField(const std::function<BoutReal(typename T::ind_type&)>& fill_function,
Args&&... args) {
T result{std::forward<Args>(args)...};
result.allocate();
for (auto i : result) {
result[i] = fill_function(i);
}
return result;
}
/// Teach googletest how to print SpecificInds
template <IND_TYPE N>
inline std::ostream& operator<<(std::ostream& out, const SpecificInd<N>& index) {
return out << index.ind;
}
/// Helpers to get the type of a Field as a string
auto inline getFieldType([[maybe_unused]] const Field2D& field) -> std::string {
return "Field2D";
}
auto inline getFieldType([[maybe_unused]] const Field3D& field) -> std::string {
return "Field3D";
}
auto inline getFieldType([[maybe_unused]] const FieldPerp& field) -> std::string {
return "FieldPerp";
}
/// Helpers to get the (x, y, z) index values, along with the
/// single-index of a Field index
auto inline getIndexXYZ(const Ind2D& index) -> std::string {
std::stringstream ss;
ss << index.x() << ", " << index.y() << "; [" << index.ind << "]";
return ss.str();
}
auto inline getIndexXYZ(const Ind3D& index) -> std::string {
std::stringstream ss;
ss << index.x() << ", " << index.y() << ", " << index.z() << "; [" << index.ind << "]";
return ss.str();
}
auto inline getIndexXYZ(const IndPerp& index) -> std::string {
std::stringstream ss;
ss << index.x() << ", " << index.y() << ", " << index.z() << "; [" << index.ind << "]";
return ss.str();
}
/// Is \p field equal to \p reference, with a tolerance of \p tolerance?
template <class T, class U, typename = EnableIfField<T, U>>
auto IsFieldEqual(const T& field, const U& reference,
const std::string& region = "RGN_ALL",
BoutReal tolerance = BoutRealTolerance) -> ::testing::AssertionResult {
for (auto i : field.getRegion(region)) {
if (fabs(field[i] - reference[i]) > tolerance) {
return ::testing::AssertionFailure()
<< getFieldType(field) << "(" << getIndexXYZ(i) << ") == " << field[i]
<< "; Expected: " << reference[i];
}
}
return ::testing::AssertionSuccess();
}
/// Is \p field equal to \p reference, with a tolerance of \p tolerance?
/// Overload for BoutReals
template <class T, typename = EnableIfField<T>>
auto IsFieldEqual(const T& field, BoutReal reference,
const std::string& region = "RGN_ALL",
BoutReal tolerance = BoutRealTolerance) -> ::testing::AssertionResult {
for (auto i : field.getRegion(region)) {
if (fabs(field[i] - reference) > tolerance) {
return ::testing::AssertionFailure()
<< getFieldType(field) << "(" << getIndexXYZ(i) << ") == " << field[i]
<< "; Expected: " << reference;
}
}
return ::testing::AssertionSuccess();
}
class Options;
/// FakeMesh has just enough information to create fields
///
/// Notes:
///
/// - This is a mesh for a single process, so the global and local
/// indices are the same.
///
/// - There is a single guard cell at each of the start/end x/y grids.
///
/// - Only the **grid** information is assumed to be used -- anything
/// else will likely **not** work!
class FakeMesh : public Mesh {
public:
FakeMesh(int nx, int ny, int nz) {
// Mesh only on one process, so global and local indices are the
// same
GlobalNx = nx;
GlobalNy = ny;
GlobalNz = nz;
LocalNx = nx;
LocalNy = ny;
LocalNz = nz;
OffsetX = 0;
OffsetY = 0;
OffsetZ = 0;
// Small "inner" region
xstart = 1;
xend = nx - 2;
ystart = 1;
yend = ny - 2;
zstart = 0;
zend = nz - 1;
StaggerGrids = false;
// Unused variables
periodicX = false;
NXPE = 1;
PE_XIND = 0;
IncIntShear = false;
maxregionblocksize = MAXREGIONBLOCKSIZE;
// Need some options for parallelTransform
options = Options::getRoot();
mpi = bout::globals::mpi;
}
void setCoordinates(std::shared_ptr<Coordinates> coords,
CELL_LOC location = CELL_CENTRE) {
coords_map[location] = coords;
}
void setGridDataSource(GridDataSource* source_in) { source = source_in; }
// Use this if the FakeMesh needs x- and y-boundaries
void createBoundaries() {
addBoundary(new BoundaryRegionXIn("core", ystart, yend, this));
addBoundary(new BoundaryRegionXOut("sol", ystart, yend, this));
addBoundary(new BoundaryRegionYUp("upper_target", xstart, xend, this));
addBoundary(new BoundaryRegionYDown("lower_target", xstart, xend, this));
}
comm_handle send(FieldGroup& UNUSED(g)) override { return nullptr; }
comm_handle sendX(FieldGroup& UNUSED(g), comm_handle UNUSED(handle) = nullptr,
bool UNUSED(disable_corners) = false) override {
return nullptr;
}
comm_handle sendY(FieldGroup& UNUSED(g),
comm_handle UNUSED(handle) = nullptr) override {
return nullptr;
}
int wait(comm_handle UNUSED(handle)) override { return 0; }
int getNXPE() override { return 1; }
int getNYPE() override { return 1; }
int getXProcIndex() override { return 1; }
int getYProcIndex() override { return 1; }
bool firstX() const override { return true; }
bool lastX() const override { return true; }
int sendXOut(BoutReal* UNUSED(buffer), int UNUSED(size), int UNUSED(tag)) override {
return 0;
}
int sendXIn(BoutReal* UNUSED(buffer), int UNUSED(size), int UNUSED(tag)) override {
return 0;
}
comm_handle irecvXOut(BoutReal* UNUSED(buffer), int UNUSED(size),
int UNUSED(tag)) override {
return nullptr;
}
comm_handle irecvXIn(BoutReal* UNUSED(buffer), int UNUSED(size),
int UNUSED(tag)) override {
return nullptr;
}
MPI_Comm getXcomm(int UNUSED(jy)) const override { return BoutComm::get(); }
MPI_Comm getYcomm(int UNUSED(jx)) const override { return BoutComm::get(); }
bool periodicY(int UNUSED(jx)) const override { return true; }
bool periodicY(int UNUSED(jx), BoutReal& UNUSED(ts)) const override { return true; }
int numberOfYBoundaries() const override { return 1; }
std::pair<bool, BoutReal> hasBranchCutLower(int UNUSED(jx)) const override {
return std::make_pair(false, 0.);
}
std::pair<bool, BoutReal> hasBranchCutUpper(int UNUSED(jx)) const override {
return std::make_pair(false, 0.);
}
bool firstY() const override { return true; }
bool lastY() const override { return true; }
bool firstY(int UNUSED(xpos)) const override { return true; }
bool lastY(int UNUSED(xpos)) const override { return true; }
RangeIterator iterateBndryLowerY() const override {
return RangeIterator(xstart, xend);
}
RangeIterator iterateBndryUpperY() const override {
return RangeIterator(xstart, xend);
}
RangeIterator iterateBndryLowerOuterY() const override { return RangeIterator(); }
RangeIterator iterateBndryLowerInnerY() const override { return RangeIterator(); }
RangeIterator iterateBndryUpperOuterY() const override { return RangeIterator(); }
RangeIterator iterateBndryUpperInnerY() const override { return RangeIterator(); }
void addBoundary(BoundaryRegion* region) override { boundaries.push_back(region); }
std::vector<BoundaryRegion*> getBoundaries() override { return boundaries; }
std::vector<std::shared_ptr<BoundaryRegionPar>>
getBoundariesPar(BoundaryParType UNUSED(type) = BoundaryParType::all) override {
return std::vector<std::shared_ptr<BoundaryRegionPar>>();
}
BoutReal GlobalX(int jx) const override { return jx; }
BoutReal GlobalY(int jy) const override { return jy; }
BoutReal GlobalX(BoutReal jx) const override { return jx; }
BoutReal GlobalY(BoutReal jy) const override { return jy; }
int getGlobalXIndex(int) const override { return 0; }
int getGlobalXIndexNoBoundaries(int) const override { return 0; }
int getGlobalYIndex(int y) const override { return y; }
int getGlobalYIndexNoBoundaries(int y) const override { return y; }
int getGlobalZIndex(int) const override { return 0; }
int getGlobalZIndexNoBoundaries(int) const override { return 0; }
int getLocalXIndex(int) const override { return 0; }
int getLocalXIndexNoBoundaries(int) const override { return 0; }
int getLocalYIndex(int y) const override { return y; }
int getLocalYIndexNoBoundaries(int y) const override { return y; }
int getLocalZIndex(int) const override { return 0; }
int getLocalZIndexNoBoundaries(int) const override { return 0; }
void initDerivs(Options* opt) {
StaggerGrids = true;
derivs_init(opt);
}
void createBoundaryRegions() {
addRegion2D("RGN_LOWER_Y",
Region<Ind2D>(0, LocalNx - 1, 0, ystart - 1, 0, 0, LocalNy, 1));
addRegion3D("RGN_LOWER_Y", Region<Ind3D>(0, LocalNx - 1, 0, ystart - 1, 0,
LocalNz - 1, LocalNy, LocalNz));
addRegion2D("RGN_LOWER_Y_THIN", getRegion2D("RGN_LOWER_Y"));
addRegion3D("RGN_LOWER_Y_THIN", getRegion3D("RGN_LOWER_Y"));
addRegion2D("RGN_UPPER_Y",
Region<Ind2D>(0, LocalNx - 1, yend + 1, LocalNy - 1, 0, 0, LocalNy, 1));
addRegion3D("RGN_UPPER_Y", Region<Ind3D>(0, LocalNx - 1, yend + 1, LocalNy - 1, 0,
LocalNz - 1, LocalNy, LocalNz));
addRegion2D("RGN_UPPER_Y_THIN", getRegion2D("RGN_UPPER_Y"));
addRegion3D("RGN_UPPER_Y_THIN", getRegion3D("RGN_UPPER_Y"));
addRegion2D("RGN_INNER_X",
Region<Ind2D>(0, xstart - 1, ystart, yend, 0, 0, LocalNy, 1));
addRegion3D("RGN_INNER_X", Region<Ind3D>(0, xstart - 1, ystart, yend, 0, LocalNz - 1,
LocalNy, LocalNz));
addRegionPerp("RGN_INNER_X",
Region<IndPerp>(0, xstart - 1, 0, 0, 0, LocalNz - 1, 1, LocalNz));
addRegionPerp("RGN_INNER_X_THIN",
Region<IndPerp>(0, xstart - 1, 0, 0, 0, LocalNz - 1, 1, LocalNz));
addRegion2D("RGN_INNER_X_THIN", getRegion2D("RGN_INNER_X"));
addRegion3D("RGN_INNER_X_THIN", getRegion3D("RGN_INNER_X"));
addRegion2D("RGN_OUTER_X",
Region<Ind2D>(xend + 1, LocalNx - 1, ystart, yend, 0, 0, LocalNy, 1));
addRegion3D("RGN_OUTER_X", Region<Ind3D>(xend + 1, LocalNx - 1, ystart, yend, 0,
LocalNz - 1, LocalNy, LocalNz));
addRegionPerp("RGN_OUTER_X", Region<IndPerp>(xend + 1, LocalNx - 1, 0, 0, 0,
LocalNz - 1, 1, LocalNz));
addRegionPerp("RGN_OUTER_X_THIN", Region<IndPerp>(xend + 1, LocalNx - 1, 0, 0, 0,
LocalNz - 1, 1, LocalNz));
addRegion2D("RGN_OUTER_X_THIN", getRegion2D("RGN_OUTER_X"));
addRegion3D("RGN_OUTER_X_THIN", getRegion3D("RGN_OUTER_X"));
const auto boundary_names = {"RGN_LOWER_Y", "RGN_UPPER_Y", "RGN_INNER_X",
"RGN_OUTER_X"};
// Sum up and get unique points in the boundaries defined above
addRegion2D("RGN_BNDRY",
std::accumulate(begin(boundary_names), end(boundary_names),
Region<Ind2D>{},
[this](Region<Ind2D>& a, const std::string& b) {
return a + getRegion2D(b);
})
.unique());
addRegion3D("RGN_BNDRY",
std::accumulate(begin(boundary_names), end(boundary_names),
Region<Ind3D>{},
[this](Region<Ind3D>& a, const std::string& b) {
return a + getRegion3D(b);
})
.unique());
addRegionPerp("RGN_BNDRY",
getRegionPerp("RGN_INNER_X") + getRegionPerp("RGN_OUTER_X"));
}
// Make this public so we can test it
using Mesh::msg_len;
private:
std::vector<BoundaryRegion*> boundaries;
};
/// FakeGridDataSource provides a non-null GridDataSource* source to use with FakeMesh, to
/// allow testing of methods that use 'source' - in particular allowing
/// source->hasXBoundaryGuards and source->hasXBoundaryGuards to be called.
/// By passing in a set of values, the mesh->get routines can be used.
class FakeGridDataSource : public GridDataSource {
public:
FakeGridDataSource() {}
/// Constructor setting values which can be fetched from this source
FakeGridDataSource(Options& values) : values(values.copy()) {}
/// Take an rvalue (e.g. initializer list), convert to lvalue and delegate constructor
FakeGridDataSource(Options&& values) : FakeGridDataSource(values) {}
bool hasVar(const std::string& UNUSED(name)) override { return false; }
bool get([[maybe_unused]] Mesh* m, std::string& sval, const std::string& name,
const std::string& def = "") override {
if (values[name].isSet()) {
sval = values[name].as<std::string>();
return true;
}
sval = def;
return false;
}
bool get([[maybe_unused]] Mesh* m, int& ival, const std::string& name,
int def = 0) override {
if (values[name].isSet()) {
ival = values[name].as<int>();
return true;
}
ival = def;
return false;
}
bool get([[maybe_unused]] Mesh* m, BoutReal& rval, const std::string& name,
BoutReal def = 0.0) override {
if (values[name].isSet()) {
rval = values[name].as<BoutReal>();
return true;
}
rval = def;
return false;
}
bool get(Mesh* mesh, Field2D& fval, const std::string& name, BoutReal def = 0.0,
CELL_LOC UNUSED(location) = CELL_DEFAULT) override {
if (values[name].isSet()) {
fval = values[name].as(Field2D(0.0, mesh));
return true;
}
fval = def;
return false;
}
bool get(Mesh* mesh, Field3D& fval, const std::string& name, BoutReal def = 0.0,
CELL_LOC UNUSED(location) = CELL_DEFAULT) override {
if (values[name].isSet()) {
fval = values[name].as(Field3D(0.0, mesh));
return true;
}
fval = def;
return false;
}
bool get(Mesh* mesh, FieldPerp& fval, const std::string& name, BoutReal def = 0.0,
CELL_LOC UNUSED(location) = CELL_DEFAULT) override {
if (values[name].isSet()) {
fval = values[name].as(FieldPerp(0.0, mesh));
return true;
}
fval = def;
return false;
}
bool get([[maybe_unused]] Mesh* m, [[maybe_unused]] std::vector<int>& var,
[[maybe_unused]] const std::string& name, [[maybe_unused]] int len,
[[maybe_unused]] int def = 0, Direction = GridDataSource::X) override {
throw BoutException("Not Implemented");
return false;
}
bool get([[maybe_unused]] Mesh* m, [[maybe_unused]] std::vector<BoutReal>& var,
[[maybe_unused]] const std::string& name, [[maybe_unused]] int len,
[[maybe_unused]] int def = 0,
Direction UNUSED(dir) = GridDataSource::X) override {
throw BoutException("Not Implemented");
return false;
}
bool hasXBoundaryGuards(Mesh* UNUSED(m)) override { return true; }
bool hasYBoundaryGuards() override { return true; }
private:
Options values; ///< Store values to be returned by get()
};
/// Test fixture to make sure the global mesh is our fake
/// one. Also initialize the global mesh_staggered for use in tests with
/// staggering. Multiple tests have exactly the same fixture, so use a type
/// alias to make a new test:
///
/// using MyTest = FakeMeshFixture;
class FakeMeshFixture : public ::testing::Test {
public:
FakeMeshFixture() {
WithQuietOutput quiet_info{output_info};
WithQuietOutput quiet_warn{output_warn};
delete bout::globals::mesh;
bout::globals::mpi = new MpiWrapper();
bout::globals::mesh = new FakeMesh(nx, ny, nz);
bout::globals::mesh->createDefaultRegions();
static_cast<FakeMesh*>(bout::globals::mesh)->setCoordinates(nullptr);
test_coords = std::make_shared<Coordinates>(
bout::globals::mesh, Field2D{1.0}, Field2D{1.0}, Field2D{1.0}, Field2D{1.0},
Field2D{1.0}, Field2D{1.0}, Field2D{1.0}, Field2D{1.0}, Field2D{0.0},
Field2D{0.0}, Field2D{0.0}, Field2D{1.0}, Field2D{1.0}, Field2D{1.0},
Field2D{0.0}, Field2D{0.0}, Field2D{0.0}, Field2D{0.0}, Field2D{0.0});
// Set some auxilliary variables
// Usually set in geometry()
// Note: For testing these are set to non-zero values
test_coords->G1 = test_coords->G2 = test_coords->G3 = 0.1;
// Set nonuniform corrections
test_coords->non_uniform = true;
test_coords->d1_dx = test_coords->d1_dy = 0.2;
test_coords->d1_dz = 0.0;
#if BOUT_USE_METRIC_3D
test_coords->Bxy.splitParallelSlices();
test_coords->Bxy.yup() = test_coords->Bxy.ydown() = test_coords->Bxy;
#endif
// No call to Coordinates::geometry() needed here
static_cast<FakeMesh*>(bout::globals::mesh)->setCoordinates(test_coords);
static_cast<FakeMesh*>(bout::globals::mesh)
->setGridDataSource(new FakeGridDataSource());
// May need a ParallelTransform to create fields, because create3D calls
// fromFieldAligned
test_coords->setParallelTransform(
bout::utils::make_unique<ParallelTransformIdentity>(*bout::globals::mesh));
dynamic_cast<FakeMesh*>(bout::globals::mesh)->createBoundaryRegions();
delete mesh_staggered;
mesh_staggered = new FakeMesh(nx, ny, nz);
mesh_staggered->StaggerGrids = true;
dynamic_cast<FakeMesh*>(mesh_staggered)->setCoordinates(nullptr);
dynamic_cast<FakeMesh*>(mesh_staggered)->setCoordinates(nullptr, CELL_XLOW);
dynamic_cast<FakeMesh*>(mesh_staggered)->setCoordinates(nullptr, CELL_YLOW);
dynamic_cast<FakeMesh*>(mesh_staggered)->setCoordinates(nullptr, CELL_ZLOW);
mesh_staggered->createDefaultRegions();
test_coords_staggered = std::make_shared<Coordinates>(
mesh_staggered, Field2D{1.0, mesh_staggered}, Field2D{1.0, mesh_staggered},
Field2D{1.0, mesh_staggered}, Field2D{1.0, mesh_staggered},
Field2D{1.0, mesh_staggered}, Field2D{1.0, mesh_staggered},
Field2D{1.0, mesh_staggered}, Field2D{1.0, mesh_staggered},
Field2D{0.0, mesh_staggered}, Field2D{0.0, mesh_staggered},
Field2D{0.0, mesh_staggered}, Field2D{1.0, mesh_staggered},
Field2D{1.0, mesh_staggered}, Field2D{1.0, mesh_staggered},
Field2D{0.0, mesh_staggered}, Field2D{0.0, mesh_staggered},
Field2D{0.0, mesh_staggered}, Field2D{0.0, mesh_staggered},
Field2D{0.0, mesh_staggered});
// Set some auxilliary variables
test_coords_staggered->G1 = test_coords_staggered->G2 = test_coords_staggered->G3 =
0.1;
// Set nonuniform corrections
test_coords_staggered->non_uniform = true;
test_coords_staggered->d1_dx = test_coords_staggered->d1_dy = 0.2;
test_coords_staggered->d1_dz = 0.0;
#if BOUT_USE_METRIC_3D
test_coords_staggered->Bxy.splitParallelSlices();
test_coords_staggered->Bxy.yup() = test_coords_staggered->Bxy.ydown() =
test_coords_staggered->Bxy;
#endif
// No call to Coordinates::geometry() needed here
test_coords_staggered->setParallelTransform(
bout::utils::make_unique<ParallelTransformIdentity>(*mesh_staggered));
// Set all coordinates to the same Coordinates object for now
static_cast<FakeMesh*>(mesh_staggered)->setCoordinates(test_coords_staggered);
static_cast<FakeMesh*>(mesh_staggered)
->setCoordinates(test_coords_staggered, CELL_XLOW);
static_cast<FakeMesh*>(mesh_staggered)
->setCoordinates(test_coords_staggered, CELL_YLOW);
static_cast<FakeMesh*>(mesh_staggered)
->setCoordinates(test_coords_staggered, CELL_ZLOW);
}
~FakeMeshFixture() override {
delete bout::globals::mesh;
bout::globals::mesh = nullptr;
delete mesh_staggered;
mesh_staggered = nullptr;
delete bout::globals::mpi;
bout::globals::mpi = nullptr;
Options::cleanup();
}
static constexpr int nx = 3;
static constexpr int ny = 5;
static constexpr int nz = 7;
Mesh* mesh_staggered = nullptr;
std::shared_ptr<Coordinates> test_coords{nullptr};
std::shared_ptr<Coordinates> test_coords_staggered{nullptr};
};
#endif // TEST_EXTRAS_H__
| 21,259
|
C++
|
.h
| 477
| 38.530398
| 90
| 0.655921
|
bendudson/hermes-3
| 36
| 16
| 57
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,310
|
mainwindow.cpp
|
chenghaopeng_Cputroller/mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "utils.h"
#include <QDir>
#include <QDebug>
const QString speedMethod = "/pwm1_enable";
const QString manualSpeed = "/pwm1";
const QString currentSpeed = "/fan1_input";
const QString temperature = "/temp1_input";
const QString ONDEMAND = "ondemand", POWERSAVE = "powersave", PERFORMANCE = "performance";
QString findCPUDir() {
QString prefix = "/sys/class/hwmon";
QDir dirs(prefix);
dirs.setFilter(QDir::Dirs);
foreach(QFileInfo dir, dirs.entryInfoList()) {
if (dir.fileName() == "." || dir.fileName() == "..") continue;
QString fullDir = dir.absoluteFilePath();
if (Utils::isFileExist(fullDir + speedMethod) && Utils::isFileExist(fullDir + manualSpeed) && Utils::isFileExist(fullDir + currentSpeed) && Utils::isFileExist(fullDir + temperature)) {
return fullDir;
}
}
return "";
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setStyleSheet(Utils::readFile(":/static/default.qss"));
cpuDir = findCPUDir();
updateTimer = startTimer(500);
cpuNumber = Utils::exec("cpufreq-info | grep 'analyzing CPU'").split("\n").size();
}
void MainWindow::timerEvent(QTimerEvent *event) {
if (event->timerId() == updateTimer) {
update();
}
}
void MainWindow::changeStrategy(QString strategy) {
QStringList cmds;
cmds.append("#!/bin/bash");
for (int i = 0; i < cpuNumber; ++i) {
cmds.append("cpufreq-set -c " + QString::number(i) + " -g " + strategy);
}
QString shPath = "/tmp/Cputroller_" + strategy;
Utils::writeFile(shPath, cmds.join("\n"));
Utils::exec("chmod +x " + shPath);
Utils::sudo(shPath);
}
void MainWindow::update() {
ui->lblCpuFrequency->setText(Utils::exec("cat /proc/cpuinfo | grep -i mhz | awk 'BEGIN {sum=0; max=0; min=99999;} {if ($4 > max) max = $4; fi; if ($4 < min) min = $4; fi; sum += $4} END {printf(\"平均 %d 最大 %d 最小 %d\", int(sum / NR), max, min)}'"));
QString cm = Utils::exec("cpufreq-info -p | awk '{print($3)}'"), cmz;
if (cm == ONDEMAND) cmz = "按需";
else if (cm == PERFORMANCE) cmz = "性能";
else if (cm == POWERSAVE) cmz = "节能";
else cmz = "其他";
ui->lblCpuStrategy->setText(cmz);
if (!cpuDir.isEmpty()) {
ui->lblCpuTemperature->setText(Utils::exec("cat " + cpuDir + "/" + temperature + " | cut -c-2") + "℃");
if (Utils::exec("cat " + cpuDir + "/" + speedMethod) == "1") {
ui->lblFanSpeed->setText("手动 " + Utils::exec("cat " + cpuDir + "/" + manualSpeed) + "/255");
}
else {
ui->lblFanSpeed->setText("自动 " + Utils::exec("cat " + cpuDir + "/" + currentSpeed));
}
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnFanSpeedAuto_clicked()
{
if (cpuDir.isEmpty()) return;
Utils::writeSystemFile(cpuDir + "/" + speedMethod, "2");
}
void MainWindow::on_sdrFanSpeed_sliderReleased()
{
if (cpuDir.isEmpty()) return;
Utils::writeSystemFile(cpuDir + "/" + manualSpeed, QString::number(ui->sdrFanSpeed->value()));
}
void MainWindow::on_btnStrategyPerformance_clicked()
{
changeStrategy(PERFORMANCE);
}
void MainWindow::on_btnStrategyOndemand_clicked()
{
changeStrategy(ONDEMAND);
}
void MainWindow::on_btnStrategyPowersave_clicked()
{
changeStrategy(POWERSAVE);
}
| 3,436
|
C++
|
.cpp
| 93
| 32.354839
| 251
| 0.638324
|
chenghaopeng/Cputroller
| 36
| 6
| 3
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,311
|
utils.cpp
|
chenghaopeng_Cputroller/utils.cpp
|
#include "utils.h"
#include <QProcess>
#include <QTextStream>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QDir>
QString Utils::exec(const QString &cmd, QByteArray data) {
QProcess *process = new QProcess;
process->start("/bin/bash", QStringList() << "-c" << cmd);
if (!data.isEmpty()) {
process->write(data);
process->waitForBytesWritten();
process->closeWriteChannel();
}
process->waitForFinished();
QTextStream res(process->readAllStandardOutput());
process->kill();
process->close();
return res.readAll().trimmed();
}
QString Utils::sudo(const QString &cmd, QByteArray data) {
return Utils::exec("pkexec " + cmd, data);
}
QString Utils::writeFile(const QString &filePath, const QString &text) {
return Utils::exec("tee " + filePath, text.toUtf8());
}
QString Utils::writeSystemFile(const QString &filePath, const QString &text) {
return Utils::sudo("tee " + filePath, text.toUtf8());
}
QString Utils::readFile(const QString &filePath) {
QFile file(filePath);
file.open(QIODevice::ReadOnly);
QTextStream stream(&file);
QString text = stream.readAll();
file.close();
return text;
}
bool Utils::isFileExist(const QString &filePath) {
QFileInfo fileInfo(filePath);
return fileInfo.isFile();
}
| 1,357
|
C++
|
.cpp
| 42
| 28.071429
| 78
| 0.697584
|
chenghaopeng/Cputroller
| 36
| 6
| 3
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,312
|
utils.h
|
chenghaopeng_Cputroller/utils.h
|
#ifndef UTILS_H
#define UTILS_H
#include <QStringList>
class Utils {
public:
static QString exec(const QString &cmd, QByteArray data = QByteArray());
static QString sudo(const QString &cmd, QByteArray data = QByteArray());
static QString writeFile(const QString &filePath, const QString &text);
static QString writeSystemFile(const QString &filePath, const QString &text);
static QString readFile(const QString &filePath);
static bool isFileExist(const QString &filePath);
};
#endif // UTILS_H
| 521
|
C++
|
.h
| 13
| 37
| 81
| 0.762376
|
chenghaopeng/Cputroller
| 36
| 6
| 3
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,313
|
mainwindow.h
|
chenghaopeng_Cputroller/mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QString cpuDir;
int cpuNumber;
int updateTimer;
void update();
void changeStrategy(QString strategy);
protected:
void timerEvent(QTimerEvent *event);
private slots:
void on_btnFanSpeedAuto_clicked();
void on_sdrFanSpeed_sliderReleased();
void on_btnStrategyPerformance_clicked();
void on_btnStrategyOndemand_clicked();
void on_btnStrategyPowersave_clicked();
};
#endif // MAINWINDOW_H
| 713
|
C++
|
.h
| 29
| 20.862069
| 51
| 0.75188
|
chenghaopeng/Cputroller
| 36
| 6
| 3
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,314
|
rastertotmt88v.cc
|
groolot_epson-tm-t88v-driver/src/rastertotmt88v.cc
|
/******************************************************************************
*
* Epson TM-T88V Printer Driver for GNU/Linux
*
* Copyright (C) Seiko Epson Corporation 2019.
* Copyright (C) 2020 Grégory DAVID.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#include <cups/ppd.h>
#include <cups/raster.h>
#include <csignal>
#include <cstdint>
#include <errno.h>
#include <fcntl.h>
#include <cmath>
#include <sstream>
#include <string>
/*--------------------
* command declaration
*--------------------*/
#define ESC (0x1b)
#define GS (0x1d)
/*----------------
* MACRO (#define)
*----------------*/
#define EPTMD_BITS_TO_BYTES(bits) (((bits) + 7) / 8)
/*-----------------
* enum declaration
*-----------------*/
typedef enum
{
SUCCESS = 0,
FAILED = 1,
CANCEL = 2,
// Error codes
E_INIT_ARGS = 1001,
E_INIT_FAILED_OPEN_RASTER_FILE = 1002,
E_INIT_FAILED_CUPS_RASTER_READ = 1003,
//
E_STARTJOB_FAILED_SET_DEVICE = 2101,
E_STARTJOB_FAILED_SET_PRINT_SHEET = 2102,
E_STARTJOB_FAILED_SET_CONFIG_SHEET = 2103,
E_STARTJOB_FAILED_SET_NEAREND_PRINT = 2104,
E_STARTJOB_FAILED_SET_BASE_MOTION_UNIT = 2105,
E_STARTJOB_FAILED_OPEN_DRAWER = 2106,
E_STARTJOB_FAILED_SOUND_BUZZER = 2107,
E_STARTJOB_FAILED_WRITE_USER_FILE = 2108,
//
E_ENDJOB_FAILED_WRITE_USER_FILE = 2201,
E_ENDJOB_FAILED_CUT = 2202,
//
E_STARTPAGE_FAILED_WRITE_USER_FILE = 3102,
//
E_ENDPAGE_FAILED_WRITE_USER_FILE = 3201,
E_ENDPAGE_FAILED_CUT = 3202,
//
E_READRASTER_FAILED_DATA_ALLOC = 3301,
E_READRASTER_FAILED_READ_PIXELS = 3302,
//
E_WRITERASTER_FAILED_WRITE_BAND = 3403,
E_WRITERASTER_FAILED_WRITE_RASTER = 3404,
//
E_GETPARAMS_OPEN_PPD_FILE = 4001,
E_GETPARAMS_PPD_CONFLICTED_OPT = 4002,
//
E_GETMODELPPD_ATTR_HMOTION_NOTFIND = 4101,
E_GETMODELPPD_ATTR_HMOTION_OUT_OF_RANGE = 4102,
E_GETMODELPPD_ATTR_VMOTION_NOTFIND = 4103,
E_GETMODELPPD_ATTR_VMOTION_OUT_OF_RANGE = 4104,
//
E_GETPAPERREDUCPPD_ATTR_NOTFIND = 4201,
E_GETPAPERREDUCPPD_ATTR_OUT_OF_RANGE = 4202,
//
E_GETBUZZERDRAWERPPD_ATTR_NOTFIND = 4301,
E_GETBUZZERDRAWERPPD_ATTR_OUT_OF_RANGE = 4302,
//
E_GETPAPERCUTPPD_ATTR_NOTFIND = 4401,
E_GETPAPERCUTPPD_ATTR_OUT_OF_RANGE = 4402,
} EPTME_RESULT_CODE; // Result Code
typedef enum
{
TmPaperReductionOff = 0,
TmPaperReductionTop,
TmPaperReductionBottom,
TmPaperReductionBoth,
} EPTME_BLANK_SKIP_TYPE; // Paper Reduction
typedef enum
{
TmBuzzerNotUsed = 0,
TmBuzzerInternal,
TmBuzzerExternal,
} EPTME_BUZZER; // Buzzer Type
typedef enum
{
TmDrawerNotUsed = 0,
TmDrawer1,
TmDrawer2,
} EPTME_DRAWER; // Drawer No
typedef enum
{
TmNoCut = 0,
TmCutPerJob,
TmCutPerPage,
} EPTME_PAPER_CUT; // Paper Cut
/*--------------------------------
* Structure prototype declaration
*--------------------------------*/
typedef struct
{
char *p_printerName; // The name of the destination printer.
unsigned char h_motionUnit; // Horizontal motion units.
unsigned char v_motionUnit; // Vertical motion units.
EPTME_BLANK_SKIP_TYPE paperReduction; // Paper reduction settings.
EPTME_BUZZER buzzerControl; // Buzzer control settings.
EPTME_DRAWER drawerControl; // Drawer control settings.
EPTME_PAPER_CUT cutControl; // Paper cut settings.
unsigned maxBandLines; // Maximum band length.
} EPTMS_CONFIG_T; // Configuration parameters
typedef struct
{
cups_raster_t *p_raster;
cups_page_header2_t pageHeader;
unsigned char *p_pageBuffer;
} EPTMS_JOB_INFO_T; // Job Information parameters
using result_t = std::uint16_t;
/*----------------------------
* Global variable declaration
*----------------------------*/
char g_TmCanceled;
/*--------------------------------------
* Static function prototype declaration
*--------------------------------------*/
static void fprintf_DebugLog(EPTMS_CONFIG_T *);
static result_t Init(int, char *[], EPTMS_CONFIG_T *, EPTMS_JOB_INFO_T *, int *);
static result_t InitSignal(void);
static void SignalCallback(int);
static result_t GetParameters(char *[], EPTMS_CONFIG_T *);
static result_t GetModelSpecificFromPPD(ppd_file_t *, EPTMS_CONFIG_T *);
static result_t GetPaperReductionFromPPD(ppd_file_t *, EPTMS_CONFIG_T *);
static result_t GetBuzzerAndDrawerFromPPD(ppd_file_t *, EPTMS_CONFIG_T *);
static result_t GetPaperCutFromPPD(ppd_file_t *, EPTMS_CONFIG_T *);
static void Exit(EPTMS_JOB_INFO_T *, int *);
static result_t DoJob(EPTMS_CONFIG_T *, EPTMS_JOB_INFO_T *);
static result_t StartJob(EPTMS_CONFIG_T *, EPTMS_JOB_INFO_T *);
static result_t OpenDrawer(EPTMS_CONFIG_T *);
static result_t SoundBuzzer(EPTMS_CONFIG_T *);
static result_t EndJob(EPTMS_CONFIG_T *, EPTMS_JOB_INFO_T *, cups_page_header2_t *);
static result_t DoPage(EPTMS_CONFIG_T *, EPTMS_JOB_INFO_T *);
static result_t StartPage(EPTMS_CONFIG_T *);
static result_t EndPage(EPTMS_CONFIG_T *, cups_page_header2_t *);
static result_t ReadRaster(cups_page_header2_t *, cups_raster_t *, unsigned char *);
static void TransferRaster(unsigned char *, unsigned char *, cups_page_header2_t *, unsigned);
static result_t WriteRaster(EPTMS_CONFIG_T *, cups_page_header2_t *, unsigned char *);
static void AvoidDisturbingData(cups_page_header2_t *, unsigned char *, unsigned, unsigned);
static unsigned FindBlackRasterLineTop(cups_page_header2_t *, unsigned char *);
static unsigned FindBlackRasterLineEnd(cups_page_header2_t *, unsigned char *);
static result_t WriteBand(cups_page_header2_t *, unsigned char *, unsigned);
static result_t WriteUserFile(char *, const char *);
static unsigned int ReadUserFile(int, void *, unsigned int);
static result_t WriteData(unsigned char *, unsigned int);
int main(int argc, char **argv)
{
EPTMS_JOB_INFO_T JobInfo = {0};
EPTMS_CONFIG_T Config = {0};
int InputFd = -1;
result_t result = SUCCESS;
// Initializes process.
result = Init(argc, argv, &Config, &JobInfo, &InputFd);
// Processing print job.
if(SUCCESS == result)
{
result = DoJob(&Config, &JobInfo);
}
// Finalizes process.
Exit(&JobInfo, &InputFd);
// Error log output.
if(SUCCESS != result)
{
fprintf(stderr, "ERROR: Error Code=%d\n", result);
}
// Output message for debugging.
fprintf_DebugLog(&Config);
return result;
}
static void fprintf_DebugLog(EPTMS_CONFIG_T *p_config)
{
fprintf(stderr, "DEBUG: p_printerName = %s\n", p_config->p_printerName);
fprintf(stderr, "DEBUG: v_motionUnit = %u\n", p_config->v_motionUnit);
fprintf(stderr, "DEBUG: h_motionUnit = %u\n", p_config->h_motionUnit);
fprintf(stderr, "DEBUG: paperReduction = %d\n", p_config->paperReduction);
fprintf(stderr, "DEBUG: buzzerControl = %d\n", p_config->buzzerControl);
fprintf(stderr, "DEBUG: drawerControl = %d\n", p_config->drawerControl);
fprintf(stderr, "DEBUG: cutControl = %d\n", p_config->cutControl);
fprintf(stderr, "DEBUG: maxBandLines = %u\n", p_config->maxBandLines);
}
static result_t Init(int argc, char *argv[],
EPTMS_CONFIG_T *p_config,
EPTMS_JOB_INFO_T *p_jobInfo,
int *p_InputFd)
{
result_t result = SUCCESS;
// Initializes global variables.
g_TmCanceled = 0;
// Check parameters.
if((nullptr == argv) || ((6 != argc) && (7 != argc)))
{
return E_INIT_ARGS;
}
// Initializes signals.
result = InitSignal();
if(SUCCESS != result)
{
return result;
}
// Open a raster stream.
if(6 == argc)
{
*p_InputFd = 0;
}
else if(7 == argc)
{
*p_InputFd = open(argv[6], O_RDONLY);
if(*p_InputFd < 0)
{
return E_INIT_FAILED_OPEN_RASTER_FILE;
}
else {}
p_jobInfo->p_raster = cupsRasterOpen(*p_InputFd, CUPS_RASTER_READ);
if(nullptr == p_jobInfo->p_raster)
{
return E_INIT_FAILED_CUPS_RASTER_READ;
}
}
// Get parameters.
result = GetParameters(argv, p_config);
if(SUCCESS != result)
{
return result;
}
// Get printer name.
p_config->p_printerName = argv[0];
p_config->maxBandLines = 256;
return SUCCESS;
}
static result_t InitSignal(void)
{
sigset_t sigset;
{
//
if(0 != sigemptyset(&sigset))
{
return 1101;
}
if(0 != sigaddset(&sigset, SIGTERM))
{
return 1102;
}
if(0 != sigprocmask(SIG_BLOCK, &sigset, nullptr))
{
return 1103;
}
}
{
//
struct sigaction sigact_term;
if(0 != sigaction(SIGTERM, nullptr, &sigact_term))
{
return 1104;
}
sigact_term.sa_handler = SignalCallback;
sigact_term.sa_flags |= SA_RESTART;
if(0 != sigaction(SIGTERM, &sigact_term, nullptr))
{
return 1105;
}
}
if(0 != sigprocmask(SIG_UNBLOCK, &sigset, nullptr))
{
return 1106;
}
return SUCCESS;
}
static void SignalCallback(int signal_id)
{
(void)signal_id; // unused parameter
g_TmCanceled = 1;
}
static result_t GetParameters(char *argv[], EPTMS_CONFIG_T *p_config)
{
ppd_file_t *p_ppd = nullptr;
{
// Load the PPD file
p_ppd = ppdOpenFile(getenv("PPD"));
if(nullptr == p_ppd)
{
return 4001;
}
ppdMarkDefaults(p_ppd);
}
{
// Check conflict
cups_option_t *p_options = nullptr;
int num_option = cupsParseOptions(argv[5], 0, &p_options);
if(0 < num_option)
{
if(0 != cupsMarkOptions(p_ppd, num_option, p_options)) // 1 if conflicts exist, 0 otherwise
{
ppdClose(p_ppd);
cupsFreeOptions(num_option, p_options);
return 4002;
}
}
cupsFreeOptions(num_option, p_options);
}
result_t result = SUCCESS;
{
// Get parameters
if(SUCCESS == result)
{
result = GetModelSpecificFromPPD(p_ppd, p_config);
}
if(SUCCESS == result)
{
result = GetPaperReductionFromPPD(p_ppd, p_config);
}
if(SUCCESS == result)
{
result = GetPaperCutFromPPD(p_ppd, p_config);
}
if(SUCCESS == result)
{
result = GetBuzzerAndDrawerFromPPD(p_ppd, p_config);
}
}
// Unload the PPD file
ppdClose(p_ppd);
return result;
}
static result_t GetModelSpecificFromPPD(ppd_file_t *p_ppd, EPTMS_CONFIG_T *p_config)
{
{
char ppdKeyMotionUnit[] = "TmxMotionUnitHori";
ppd_attr_t *p_attribute = ppdFindAttr(p_ppd, ppdKeyMotionUnit, nullptr);
if(nullptr == p_attribute)
{
return E_GETMODELPPD_ATTR_HMOTION_NOTFIND;
}
p_config->h_motionUnit = (unsigned char)atol(p_attribute->value);
if((0 == p_config->h_motionUnit) || (255 < p_config->h_motionUnit)) // GS P Command Specification
{
return E_GETMODELPPD_ATTR_HMOTION_OUT_OF_RANGE;
}
}
{
char ppdKeyMotionUnit[] = "TmxMotionUnitVert";
ppd_attr_t *p_attribute = ppdFindAttr(p_ppd, ppdKeyMotionUnit, nullptr);
if(nullptr == p_attribute)
{
return E_GETMODELPPD_ATTR_VMOTION_NOTFIND;
}
p_config->v_motionUnit = (unsigned char)atol(p_attribute->value);
if((0 == p_config->v_motionUnit) || (255 < p_config->v_motionUnit)) // GS P Command Specification
{
return E_GETMODELPPD_ATTR_VMOTION_OUT_OF_RANGE;
}
}
return SUCCESS;
}
static result_t GetPaperReductionFromPPD(ppd_file_t *p_ppd, EPTMS_CONFIG_T *p_config)
{
char ppdKey[] = "TmxPaperReduction";
ppd_choice_t *p_choice = ppdFindMarkedChoice(p_ppd, ppdKey);
if(nullptr == p_choice)
{
return E_GETPAPERREDUCPPD_ATTR_NOTFIND;
}
if(0 == strcmp("Off", p_choice->choice))
{
p_config->paperReduction = TmPaperReductionOff;
}
else if(0 == strcmp("Top", p_choice->choice))
{
p_config->paperReduction = TmPaperReductionTop;
}
else if(0 == strcmp("Bottom", p_choice->choice))
{
p_config->paperReduction = TmPaperReductionBottom;
}
else if(0 == strcmp("Both", p_choice->choice))
{
p_config->paperReduction = TmPaperReductionBoth;
}
else
{
return E_GETPAPERREDUCPPD_ATTR_OUT_OF_RANGE;
}
return SUCCESS;
}
static result_t GetBuzzerAndDrawerFromPPD(ppd_file_t *p_ppd, EPTMS_CONFIG_T *p_config)
{
char ppdKey[] = "TmxBuzzerAndDrawer";
ppd_choice_t *p_choice = ppdFindMarkedChoice(p_ppd, ppdKey);
if(nullptr == p_choice)
{
return E_GETBUZZERDRAWERPPD_ATTR_NOTFIND;
}
if(0 == strcmp("NotUsed", p_choice->choice))
{
p_config->buzzerControl = TmBuzzerNotUsed;
p_config->drawerControl = TmDrawerNotUsed;
}
else if(0 == strcmp("InternalBuzzer", p_choice->choice))
{
p_config->buzzerControl = TmBuzzerInternal;
}
else if(0 == strcmp("ExternalBuzzer", p_choice->choice))
{
p_config->buzzerControl = TmBuzzerExternal;
}
else if(0 == strcmp("OpenDrawer1", p_choice->choice))
{
p_config->drawerControl = TmDrawer1;
}
else if(0 == strcmp("OpenDrawer2", p_choice->choice))
{
p_config->drawerControl = TmDrawer2;
}
else
{
return E_GETBUZZERDRAWERPPD_ATTR_OUT_OF_RANGE;
}
return SUCCESS;
}
static result_t GetPaperCutFromPPD(ppd_file_t *p_ppd, EPTMS_CONFIG_T *p_config)
{
char ppdKey[] = "TmxPaperCut";
ppd_choice_t *p_choice = ppdFindMarkedChoice(p_ppd, ppdKey);
if(nullptr == p_choice)
{
return E_GETPAPERCUTPPD_ATTR_NOTFIND;
}
if(0 == strcmp("NoCut", p_choice->choice))
{
p_config->cutControl = TmNoCut;
}
else if(0 == strcmp("CutPerJob", p_choice->choice))
{
p_config->cutControl = TmCutPerJob;
}
else if(0 == strcmp("CutPerPage", p_choice->choice))
{
p_config->cutControl = TmCutPerPage;
}
else
{
return E_GETPAPERCUTPPD_ATTR_OUT_OF_RANGE;
}
return SUCCESS;
}
static void Exit(EPTMS_JOB_INFO_T *p_jobInfo, int *p_InputFd)
{
if(nullptr != p_jobInfo->p_raster)
{
cupsRasterClose(p_jobInfo->p_raster);
p_jobInfo->p_raster = nullptr;
}
if(0 < *p_InputFd)
{
close(*p_InputFd);
*p_InputFd = -1;
}
}
static result_t DoJob(EPTMS_CONFIG_T *p_config, EPTMS_JOB_INFO_T *p_jobInfo)
{
result_t result = SUCCESS;
unsigned page = 0;
result = StartJob(p_config, p_jobInfo);
while(SUCCESS == result)
{
if(0 == cupsRasterReadHeader2(p_jobInfo->p_raster, &p_jobInfo->pageHeader))
{
result = SUCCESS;
break;
}
page++;
fprintf(stderr, "PAGE: %u %d\n", page, p_jobInfo->pageHeader.NumCopies);
fprintf(stderr, "DEBUG: cupsBytesPerLine = %u\n", p_jobInfo->pageHeader.cupsBytesPerLine);
fprintf(stderr, "DEBUG: cupsBitsPerPixel = %u\n", p_jobInfo->pageHeader.cupsBitsPerPixel);
fprintf(stderr, "DEBUG: cupsBitsPerColor = %u\n", p_jobInfo->pageHeader.cupsBitsPerColor);
fprintf(stderr, "DEBUG: cupsHeight = %u\n", p_jobInfo->pageHeader.cupsHeight);
fprintf(stderr, "DEBUG: cupsWidth = %u\n", p_jobInfo->pageHeader.cupsWidth);
if(1 != p_jobInfo->pageHeader.cupsBitsPerPixel)
{
result = 2001;
break;
}
if(nullptr == p_jobInfo->p_pageBuffer) // Allocate buffer of page.
{
std::size_t size = p_jobInfo->pageHeader.cupsHeight * EPTMD_BITS_TO_BYTES(p_jobInfo->pageHeader.cupsWidth);
p_jobInfo->p_pageBuffer = (unsigned char *)malloc(size);
if(nullptr == p_jobInfo->p_pageBuffer)
{
result = 2002;
break;
}
memset(p_jobInfo->p_pageBuffer, 0, size);
}
result = DoPage(p_config, p_jobInfo);
}
// Free buffer of page.
if(nullptr != p_jobInfo->p_pageBuffer)
{
free(p_jobInfo->p_pageBuffer);
p_jobInfo->p_pageBuffer = nullptr;
}
if(SUCCESS != result)
{
EndJob(p_config, p_jobInfo, &p_jobInfo->pageHeader);
}
else
{
result = EndJob(p_config, p_jobInfo, &p_jobInfo->pageHeader);
}
return result;
}
static result_t StartJob(EPTMS_CONFIG_T *p_config,
EPTMS_JOB_INFO_T *)
{
result_t result = SUCCESS;
if(0 != g_TmCanceled)
{
return CANCEL;
}
{
// Write configuration commands.
unsigned char CommandSetDevice[3 + 2] = { ESC, '=', 0x01, ESC, '@' };
result = WriteData(CommandSetDevice, sizeof(CommandSetDevice));
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_SET_DEVICE;
}
unsigned char CommandSetPrintSheet[4] = { ESC, 'c', '0', 0x02 };
result = WriteData(CommandSetPrintSheet, sizeof(CommandSetPrintSheet));
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_SET_PRINT_SHEET;
}
unsigned char CommandSetConfigSheet[4] = { ESC, 'c', '1', 0x02 };
result = WriteData(CommandSetConfigSheet, sizeof(CommandSetConfigSheet));
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_SET_CONFIG_SHEET;
}
unsigned char CommandSetNearendPrint[4] = { ESC, 'c', '3', 0x00 };
result = WriteData(CommandSetNearendPrint, sizeof(CommandSetNearendPrint));
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_SET_NEAREND_PRINT;
}
unsigned char CommandSetBaseMotionUnit[4] = { GS, 'P', 0x00, 0x00 };
CommandSetBaseMotionUnit[2] = p_config->h_motionUnit & 0xff;
CommandSetBaseMotionUnit[3] = p_config->v_motionUnit;
result = WriteData(CommandSetBaseMotionUnit, sizeof(CommandSetBaseMotionUnit));
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_SET_BASE_MOTION_UNIT;
}
}
// Drawer open.
result = OpenDrawer(p_config);
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_OPEN_DRAWER;
}
// Sound buzzer.
result = SoundBuzzer(p_config);
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_SOUND_BUZZER;
}
// Send user file.
result = WriteUserFile(p_config->p_printerName, "StartJob.prn");
if(SUCCESS != result)
{
return E_STARTJOB_FAILED_WRITE_USER_FILE;
}
return SUCCESS;
}
static result_t OpenDrawer(EPTMS_CONFIG_T *p_config)
{
result_t result = SUCCESS;
if(TmDrawerNotUsed == p_config->drawerControl)
{
return SUCCESS;
}
unsigned char Command[5] = { ESC, 'p', 0, 50 /* on time */, 200 /* off time */ };
Command[2] = static_cast<unsigned char>(p_config->drawerControl - 1); // pin no
result = WriteData(Command, sizeof(Command));
return result;
}
static result_t SoundBuzzer(EPTMS_CONFIG_T *p_config)
{
result_t result = SUCCESS;
if(TmBuzzerNotUsed == p_config->buzzerControl)
{
return SUCCESS;
}
else if(TmBuzzerInternal == p_config->buzzerControl) // Sound internal buzzer
{
unsigned char Command[5] = { ESC, 'p', 1/* pin no */, 50/* on time */, 200/* off time */ };
int n;
for(n = 0; n < 1 /* repeat count */; n++)
{
result = WriteData(Command, sizeof(Command));
if(SUCCESS != result)
{
return result;
}
}
}
else if(TmBuzzerExternal == p_config->buzzerControl) // Sound external buzzer
{
unsigned char Command[10] = { ESC, '(', 'A', 5, 0, 97, 100, 1, 50/* on time */, 200/* off time */ };
result = WriteData(Command, sizeof(Command));
if(SUCCESS != result)
{
return result;
}
}
else {}
return SUCCESS;
}
static result_t EndJob(EPTMS_CONFIG_T *p_config,
EPTMS_JOB_INFO_T *,
cups_page_header2_t *)
{
result_t result = SUCCESS;
if(0 != g_TmCanceled)
{
return CANCEL;
}
// Send user file.
result = WriteUserFile(p_config->p_printerName, "EndJob.prn");
if(SUCCESS != result)
{
return E_ENDJOB_FAILED_WRITE_USER_FILE;
}
// Feed and cut paper.
unsigned char Command[3 + 4] = { ESC, 'J', 0, GS, 'V', 66, 0 };
switch(p_config->cutControl)
{
case TmCutPerJob:
result = WriteData(Command, sizeof(Command));
if(SUCCESS != result)
{
return 2202;
}
break;
default:
break;
}
return SUCCESS;
}
static result_t DoPage(EPTMS_CONFIG_T *p_config, EPTMS_JOB_INFO_T *p_jobInfo)
{
result_t result;
result = StartPage(p_config);
if(SUCCESS == result)
{
result = ReadRaster(&p_jobInfo->pageHeader, p_jobInfo->p_raster, p_jobInfo->p_pageBuffer);
}
if(SUCCESS == result)
{
result = WriteRaster(p_config, &p_jobInfo->pageHeader, p_jobInfo->p_pageBuffer);
}
if(SUCCESS == result)
{
result = EndPage(p_config, &p_jobInfo->pageHeader);
}
return result;
}
static result_t StartPage(EPTMS_CONFIG_T *p_config)
{
int result;
// Send user file.
result = WriteUserFile(p_config->p_printerName, "StartPage.prn");
if(SUCCESS != result)
{
return E_STARTPAGE_FAILED_WRITE_USER_FILE;
}
return SUCCESS;
}
static result_t EndPage(EPTMS_CONFIG_T *p_config,
cups_page_header2_t *)
{
int result;
if(0 != g_TmCanceled)
{
return CANCEL;
}
// Send user file.
result = WriteUserFile(p_config->p_printerName, "EndPage.prn");
if(SUCCESS != result)
{
return E_ENDPAGE_FAILED_WRITE_USER_FILE;
}
// Feed and cut paper.
unsigned char Command[3 + 4] = { ESC, 'J', 0, GS, 'V', 66, 0 };
switch(p_config->cutControl)
{
case TmCutPerPage:
result = WriteData(Command, sizeof(Command));
if(SUCCESS != result)
{
return 3202;
}
break;
default:
break;
}
return SUCCESS;
}
static result_t ReadRaster(cups_page_header2_t *p_header, cups_raster_t *p_raster, unsigned char *p_pageBuffer)
{
result_t result;
unsigned char *p_data;
unsigned data_size = p_header->cupsBytesPerLine;
p_data = (unsigned char *)malloc(data_size);
if(nullptr == p_data)
{
return E_READRASTER_FAILED_DATA_ALLOC;
}
memset(p_data, 0, data_size);
unsigned i;
for(i = 0; i < p_header->cupsHeight; i++)
{
if(0 != g_TmCanceled)
{
result = CANCEL;
break;
}
unsigned num_bytes_read = cupsRasterReadPixels(p_raster, p_data, data_size);
if(data_size > num_bytes_read)
{
fprintf(stderr, "DEBUG: cupsRasterReadPixels() = %u:%u/%u\n", (i + 1), num_bytes_read, data_size);
result = E_READRASTER_FAILED_READ_PIXELS;
break;
}
TransferRaster(p_pageBuffer, p_data, p_header, i);
}
free(p_data);
return result;
}
static void TransferRaster(unsigned char *p_pageBuffer, unsigned char *p_data, cups_page_header2_t *p_header, unsigned line_no)
{
unsigned char *p_dest = p_pageBuffer + (EPTMD_BITS_TO_BYTES(p_header->cupsWidth) * line_no);
memcpy(p_dest, p_data, p_header->cupsBytesPerLine);
}
static result_t WriteRaster(EPTMS_CONFIG_T *p_config, cups_page_header2_t *p_header, unsigned char *p_pageBuffer)
{
unsigned line_no = 0;
unsigned start_line_no = 0; /* first raster line without top blank */
unsigned last_line_no = 0; /* last raster line without bottom blank */
unsigned char *p_data = nullptr;
result_t result;
// Get top margin
start_line_no = FindBlackRasterLineTop(p_header, p_pageBuffer);
if(p_header->cupsHeight == start_line_no) /* This page has not image */
{
return SUCCESS;
}
// Get bottom margin
last_line_no = FindBlackRasterLineEnd(p_header, p_pageBuffer) + 1;
// Avoid disturbing data
AvoidDisturbingData(p_header, p_pageBuffer, start_line_no, last_line_no);
// Command output : raster data (band unit)
for(line_no = start_line_no; (line_no + p_config->maxBandLines) < last_line_no; line_no += p_config->maxBandLines)
{
p_data = p_pageBuffer + (EPTMD_BITS_TO_BYTES(p_header->cupsWidth) * line_no);
result = WriteBand(p_header, p_data, p_config->maxBandLines);
if(SUCCESS != result)
{
return E_WRITERASTER_FAILED_WRITE_BAND;
}
if(0 != g_TmCanceled)
{
return CANCEL;
}
}
// Command output : raster data
if(line_no < last_line_no)
{
p_data = p_pageBuffer + (EPTMD_BITS_TO_BYTES(p_header->cupsWidth) * line_no);
result = WriteBand(p_header, p_data, (last_line_no - line_no));
if(SUCCESS != result)
{
return E_WRITERASTER_FAILED_WRITE_RASTER;
}
}
return SUCCESS;
}
static void AvoidDisturbingData(cups_page_header2_t *p_header, unsigned char *p_pageBuffer, unsigned start_line_no, unsigned last_line_no)
{
unsigned char *p_data = p_pageBuffer + (EPTMD_BITS_TO_BYTES(p_header->cupsWidth) * start_line_no);
unsigned long data_size = (last_line_no - start_line_no) * EPTMD_BITS_TO_BYTES(p_header->cupsWidth);
unsigned long i = 0;
for(; (i + 1) < data_size; i++)
{
if(0x10 == p_data[i])
{
if((0x04 == p_data[i + 1]) || (0x05 == p_data[i + 1]) || (0x14 == p_data[i + 1]))
{
p_data[i] = 0x30;
}
}
else if(0x1B == p_data[i])
{
if(0x3D == p_data[i + 1])
{
p_data[i] = 0x3B;
}
}
else {}
}
}
static unsigned FindBlackRasterLineTop(cups_page_header2_t *p_header, unsigned char *p_pageBuffer)
{
unsigned BytesPerLine = EPTMD_BITS_TO_BYTES(p_header->cupsWidth);
unsigned char *p_data = p_pageBuffer;
unsigned y;
for(y = 0; y < p_header->cupsHeight; y++)
{
unsigned x;
for(x = 0 ; x < BytesPerLine; x++)
{
if(0x00 != p_data[x])
{
return y;
}
}
p_data += BytesPerLine;
}
return p_header->cupsHeight;
}
static unsigned FindBlackRasterLineEnd(cups_page_header2_t *p_header, unsigned char *p_pageBuffer)
{
unsigned BytesPerLine = EPTMD_BITS_TO_BYTES(p_header->cupsWidth);
unsigned char *p_data = p_pageBuffer + (BytesPerLine * (p_header->cupsHeight - 1));
unsigned y;
for(y = 0; y < p_header->cupsHeight; y++)
{
unsigned x;
for(x = 0 ; x < BytesPerLine; x++)
{
if(0x00 != p_data[x])
{
return (p_header->cupsHeight - 1 - y);
}
}
p_data -= BytesPerLine;
}
return 0;
}
static result_t WriteBand(cups_page_header2_t *p_header, unsigned char *p_data, unsigned lines)
{
unsigned char CommandSetAbsolutePrintPosition[4] = { ESC, '$', 0, 0 };
result_t result = WriteData(CommandSetAbsolutePrintPosition, sizeof(CommandSetAbsolutePrintPosition));
if(SUCCESS != result)
{
return result;
}
unsigned long width = p_header->cupsWidth;
unsigned char CommandSetGraphicsdataGS8L112[17] = { GS, '8', 'L', 0, 0, 0, 0, 48, 112, 48, 1, 1, 49, 0, 0, 0, 0 };
CommandSetGraphicsdataGS8L112[3] = (unsigned char)(((EPTMD_BITS_TO_BYTES(width) * lines) + 10)) & 0xff;
CommandSetGraphicsdataGS8L112[4] = (unsigned char)(((EPTMD_BITS_TO_BYTES(width) * lines) + 10) >> 8) & 0xff;
CommandSetGraphicsdataGS8L112[5] = (unsigned char)(((EPTMD_BITS_TO_BYTES(width) * lines) + 10) >> 16) & 0xff;
CommandSetGraphicsdataGS8L112[6] = (unsigned char)(((EPTMD_BITS_TO_BYTES(width) * lines) + 10) >> 24) & 0xff;
CommandSetGraphicsdataGS8L112[13] = (unsigned char)((width) & 0xff);
CommandSetGraphicsdataGS8L112[14] = (unsigned char)((width >> 8) & 0xff);
CommandSetGraphicsdataGS8L112[15] = (unsigned char)((lines) & 0xff);
CommandSetGraphicsdataGS8L112[16] = (unsigned char)((lines >> 8) & 0xff);
result = WriteData(CommandSetGraphicsdataGS8L112, sizeof(CommandSetGraphicsdataGS8L112));
if(SUCCESS != result)
{
return result;
}
result = WriteData(p_data, (unsigned int)(EPTMD_BITS_TO_BYTES(width) * lines));
if(SUCCESS != result)
{
return result;
}
unsigned char CommandSetGraphicsdataGSpL50[7] = { GS, '(', 'L', 2, 0, 48, 50 };
result = WriteData(CommandSetGraphicsdataGSpL50, sizeof(CommandSetGraphicsdataGSpL50));
if(SUCCESS != result)
{
return result;
}
return SUCCESS;
}
static result_t WriteUserFile(char *p_printerName, const char *p_file_name)
{
result_t result;
// Output a file if it exists in a predetermined place. : /var/lib/tmx-cups
std::ostringstream path;
std::string os_specific_dirname;
#ifndef EPD_TM_MAC
os_specific_dirname = "/var/lib/tmx-cups";
#else
os_specific_dirname = "/Library/Caches/Epson/TerminalPrinter";
#endif
path << os_specific_dirname << p_printerName << "_" << p_file_name;
int fd = open(path.str().c_str(), O_RDONLY);
if(0 > fd)
{
if(ENOENT == errno) // No such file or directory
{
return SUCCESS;
}
return FAILED;
}
while(1)
{
char data[1024] = { 0 };
unsigned int size = ReadUserFile(fd, data, sizeof(data));
result = WriteData((unsigned char *)data, size);
if(SUCCESS != result)
{
close(fd);
return FAILED;
}
}
if(close(fd) < 0)
{
return FAILED;
}
return SUCCESS;
}
static unsigned int ReadUserFile(int fd, void *p_buffer, unsigned int buffer_size)
{
std::size_t total_size = 0;
char *p_data = (char *)p_buffer;
for(; buffer_size > total_size;)
{
std::size_t read_size = static_cast<std::size_t>(read(fd, p_data + total_size, (buffer_size - total_size)));
if(0 == read_size)
{
break;
}
total_size += read_size;
}
return static_cast<unsigned int>(total_size);
}
static result_t WriteData(unsigned char *p_buffer, unsigned int size)
{
char *p_data = (char *)p_buffer;
result_t result;
unsigned int count;
for(count = 0; size > count; count += result)
{
result = static_cast<result_t>(write(STDOUT_FILENO, (p_data + count), (size - count)));
if(SUCCESS == result)
{
break;
}
}
return (count == size) ? SUCCESS : FAILED;
}
| 29,450
|
C++
|
.cc
| 981
| 26.155963
| 138
| 0.66056
|
groolot/epson-tm-t88v-driver
| 35
| 13
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,315
|
installinfoutils.cpp
|
muhac_vmware-macos-unlocker/auto-unlocker/src/installinfoutils.cpp
|
#include "installinfoutils.h"
#ifdef _WIN32
#include "Windows.h"
#endif
VMWareInfoRetriever::VMWareInfoRetriever()
{
#ifdef _WIN32
char regBuf[MAX_PATH];
memset(regBuf, 0, MAX_PATH);
DWORD regSize = MAX_PATH;
DWORD regType = 0;
HKEY hResult;
RegOpenKeyEx(HKEY_VMWARE, HKEY_SUBKEY_VMWARE, 0, KEY_QUERY_VALUE, &hResult);
RegQueryValueEx(hResult, HKEY_QUERY_VALUE_INSTALLPATH, NULL, ®Type, (LPBYTE)regBuf, ®Size);
installPath = std::string(reinterpret_cast<char*>(regBuf));
memset(regBuf, 0, MAX_PATH);
regSize = MAX_PATH;
RegQueryValueEx(hResult, HKEY_QUERY_VALUE_INSTALLPATH64, NULL, ®Type, (LPBYTE)regBuf, ®Size);
installPath64 = std::string(regBuf);
memset(regBuf, 0, MAX_PATH);
regSize = MAX_PATH;
RegQueryValueEx(hResult, HKEY_QUERY_VALUE_PRODUCTVERSION, NULL, ®Type, (LPBYTE)regBuf, ®Size);
prodVersion = std::string(regBuf);
RegCloseKey(hResult);
#endif
}
std::string VMWareInfoRetriever::getInstallPath()
{
return installPath;
}
std::string VMWareInfoRetriever::getInstallPath64()
{
return installPath64;
}
std::string VMWareInfoRetriever::getProductVersion()
{
return prodVersion;
}
| 1,140
|
C++
|
.cpp
| 38
| 28.157895
| 101
| 0.780734
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,316
|
archiveutils.cpp
|
muhac_vmware-macos-unlocker/auto-unlocker/src/archiveutils.cpp
|
#include "archiveutils.h"
/**
Helper function to extract a file using filesystem::path and std::string
*/
bool Archive::extract_s(fs::path from, std::string filename, fs::path to)
{
std::string from_s = from.string();
std::string to_s = to.string();
const char* from_c = from_s.c_str();
const char* to_c = to_s.c_str();
return extract(from_c, filename.c_str(), to_c);
}
int Archive::copy_data(struct archive* ar, struct archive* aw)
{
int r;
const void* buff;
size_t size;
la_int64_t offset;
for (;;) {
r = archive_read_data_block(ar, &buff, &size, &offset);
if (r == ARCHIVE_EOF)
return (ARCHIVE_OK);
if (r < ARCHIVE_OK)
return (r);
r = archive_write_data_block(aw, buff, size, offset);
if (r < ARCHIVE_OK) {
fprintf(stderr, "%s\n", archive_error_string(aw));
return (r);
}
}
}
/**
Extract from archive "from", the file "filename" into path "to" (filename has to be included here too)
*/
bool Archive::extract(const char* from, const char* filename, const char* to)
{
struct archive* a;
struct archive* ext;
struct archive_entry* entry;
int flags;
int r;
/* Select which attributes we want to restore. */
flags = ARCHIVE_EXTRACT_TIME;
flags |= ARCHIVE_EXTRACT_PERM;
flags |= ARCHIVE_EXTRACT_ACL;
flags |= ARCHIVE_EXTRACT_FFLAGS;
a = archive_read_new();
archive_read_support_format_all(a);
archive_read_support_compression_all(a);
ext = archive_write_disk_new();
archive_write_disk_set_options(ext, flags);
archive_write_disk_set_standard_lookup(ext);
if ((r = archive_read_open_filename(a, from, 10240)))
return false;
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
if (r < ARCHIVE_OK)
logerr(archive_error_string(a));
if (r < ARCHIVE_WARN)
return false;
const char* entry_path = archive_entry_pathname(entry);
if (entry_path == NULL || strcmp(entry_path, filename) != 0)
continue;
else {
archive_entry_set_pathname(entry, to);
r = archive_write_header(ext, entry);
if (r < ARCHIVE_OK)
logerr(archive_error_string(ext));
else if (archive_entry_size(entry) > 0) {
r = copy_data(a, ext);
if (r < ARCHIVE_OK)
logerr(archive_error_string(ext));
if (r < ARCHIVE_WARN)
return false;
}
r = archive_write_finish_entry(ext);
if (r < ARCHIVE_OK)
logerr(archive_error_string(ext));
if (r < ARCHIVE_WARN)
return false;
break;
}
}
archive_read_close(a);
archive_read_free(a);
archive_write_close(ext);
archive_write_free(ext);
return true;
}
| 2,527
|
C++
|
.cpp
| 91
| 24.978022
| 103
| 0.679588
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,317
|
netutils.cpp
|
muhac_vmware-macos-unlocker/auto-unlocker/src/netutils.cpp
|
#include "netutils.h"
/**
Writes data received from Curl to a stream
*/
size_t Curl::write_data_file(char* ptr, size_t size, size_t nmemb, void* stream)
{
std::iostream* fstr = static_cast<std::iostream*>(stream);
size_t bytes = size * nmemb;
fstr->write(ptr, bytes);
return bytes;
}
static double dled = 0.0;
static double dltot = 0.0;
static bool progressrun = false;
void Curl::updateProgress()
{
while (progressrun)
{
if (dltot > 0)
{
double mBytesTotal = dltot / 1024 / 1024;
double mBytesNow = dled / 1024 / 1024;
std::cout << "Download progress: " << (std::min)(100, (std::max)(0, int(dled * 100 / dltot))) << " %, " << std::fixed << std::setprecision(2) << mBytesNow << " MB / " << mBytesTotal << " MB \r";
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int Curl::progress_callback(void* clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
dled = dlnow;
dltot = dltotal;
return 0;
}
CURLcode Curl::curlDownload(std::string url, std::string fileName)
{
CURL* curl = curl_easy_init();
if (curl)
{
std::fstream out_file(fileName, std::ios::out | std::ios::binary);
/* set URL to get here */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
if (DEBUG)
{
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
/* disable progress meter, set to 0L to enable and disable debug output */
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
}
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_file);
/* write the page body to this ofstream */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out_file);
/* if response is >400, return an error */
curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
/* progress monitoring function */
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
/* get it! */
dltot = 0.0;
dled = 0.0;
progressrun = true;
std::thread progressthread(updateProgress);
progressthread.detach();
CURLcode res = curl_easy_perform(curl);
progressrun = false;
out_file.close();
std::cout << std::endl;
curl_easy_cleanup(curl);
return res;
}
else return CURLE_FAILED_INIT;
}
CURLcode Curl::curlGet(std::string url, std::string& output)
{
CURL* curl = curl_easy_init();
if (curl)
{
std::stringstream sstream;
/* set URL to get here */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
if (DEBUG)
{
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
/* disable progress meter, set to 0L to enable and disable debug output */
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
}
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_file);
/* write the page body to the stringstream */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &sstream);
/* if response is >400, return an error */
curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
/* progress monitoring function */
/*curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);*/
/* get it! */
CURLcode res = curl_easy_perform(curl);
output = sstream.str();
curl_easy_cleanup(curl);
return res;
}
else return CURLE_FAILED_INIT;
}
| 3,283
|
C++
|
.cpp
| 102
| 29.578431
| 216
| 0.692138
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,318
|
debugutils.cpp
|
muhac_vmware-macos-unlocker/auto-unlocker/src/debugutils.cpp
|
#include "debugutils.h"
void logd(std::string msg)
{
#ifdef VERBOSE_DBG
std::cout << msg << std::endl;
#endif
}
void logerr(std::string err)
{
#ifdef VERBOSE_ERR
std::cerr << "Error: " << err << std::endl;
#endif
}
| 218
|
C++
|
.cpp
| 13
| 15.538462
| 44
| 0.681373
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,319
|
servicestoputils.cpp
|
muhac_vmware-macos-unlocker/auto-unlocker/src/servicestoputils.cpp
|
#include "servicestoputils.h"
#ifdef _WIN32
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#endif
void ServiceStopper::StopService_s(std::string serviceName)
{
#ifdef _WIN32
SERVICE_STATUS_PROCESS ssp;
ULONGLONG dwStartTime = GetTickCount64();
DWORD dwBytesNeeded;
ULONGLONG dwTimeout = 10000; // 30-second time-out
DWORD dwWaitTime;
// Get a handle to the SCM database.
SC_HANDLE schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
{
throw ServiceStopException("OpenSCManager failed (%d)", GetLastError());
return;
}
// Get a handle to the service.
SC_HANDLE schService = OpenService(
schSCManager, // SCM database
serviceName.c_str(), // name of service
SERVICE_STOP |
SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS);
if (schService == NULL)
{
throw ServiceStopException("OpenService failed (%d)", GetLastError());
CloseServiceHandle(schSCManager);
return;
}
// Make sure the service is not already stopped.
if (!QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded))
{
throw ServiceStopException("QueryServiceStatusEx failed (%d)", GetLastError());
goto stop_cleanup;
}
if (ssp.dwCurrentState == SERVICE_STOPPED)
{
throw ServiceStopException("Service is already stopped.");
goto stop_cleanup;
}
// If a stop is pending, wait for it.
while (ssp.dwCurrentState == SERVICE_STOP_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one-tenth of the wait hint but not less than 1 second
// and not more than 10 seconds.
dwWaitTime = ssp.dwWaitHint / 10;
if (dwWaitTime < 1000)
dwWaitTime = 1000;
else if (dwWaitTime > 10000)
dwWaitTime = 10000;
Sleep(dwWaitTime);
if (!QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded))
{
throw ServiceStopException("QueryServiceStatusEx failed (%d)", GetLastError());
goto stop_cleanup;
}
if (ssp.dwCurrentState == SERVICE_STOPPED)
{
throw ServiceStopException("Service stopped successfully.");
goto stop_cleanup;
}
if (GetTickCount64() - dwStartTime > dwTimeout)
{
throw ServiceStopException("Service stop timed out.");
goto stop_cleanup;
}
}
// If the service is running, dependencies must be stopped first.
StopDependantServices(schService, schSCManager);
// Send a stop code to the service.
if (!ControlService(
schService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS)&ssp))
{
throw ServiceStopException("ControlService failed (%d)", GetLastError());
goto stop_cleanup;
}
// Wait for the service to stop.
while (ssp.dwCurrentState != SERVICE_STOPPED)
{
Sleep(ssp.dwWaitHint);
if (!QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded))
{
throw ServiceStopException("QueryServiceStatusEx failed (%d)", GetLastError());
goto stop_cleanup;
}
if (ssp.dwCurrentState == SERVICE_STOPPED)
break;
if (GetTickCount64() - dwStartTime > dwTimeout)
{
throw ServiceStopException("Wait timed out");
goto stop_cleanup;
}
}
stop_cleanup:
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
#endif
}
bool ServiceStopper::StopDependantServices(SC_HANDLE schService, SC_HANDLE schSCManager)
{
#ifdef _WIN32
DWORD i;
DWORD dwBytesNeeded;
DWORD dwCount;
LPENUM_SERVICE_STATUS lpDependencies = NULL;
ENUM_SERVICE_STATUS ess;
SC_HANDLE hDepService;
SERVICE_STATUS_PROCESS ssp;
ULONGLONG dwStartTime = GetTickCount64();
ULONGLONG dwTimeout = 10000; // 10-second time-out
bool success = true;
// Pass a zero-length buffer to get the required buffer size.
if (EnumDependentServices(schService, SERVICE_ACTIVE,
lpDependencies, 0, &dwBytesNeeded, &dwCount))
{
// If the Enum call succeeds, then there are no dependent
// services, so do nothing.
return success;
}
else
{
if (GetLastError() != ERROR_MORE_DATA)
return false; // Unexpected error
// Allocate a buffer for the dependencies.
lpDependencies = (LPENUM_SERVICE_STATUS)HeapAlloc(
GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded);
if (!lpDependencies)
return false;
__try {
// Enumerate the dependencies.
if (!EnumDependentServices(schService, SERVICE_ACTIVE,
lpDependencies, dwBytesNeeded, &dwBytesNeeded,
&dwCount))
{
success = false;
__leave;
}
for (i = 0; i < dwCount; i++)
{
ess = *(lpDependencies + i);
// Open the service.
hDepService = OpenService(schSCManager,
ess.lpServiceName,
SERVICE_STOP | SERVICE_QUERY_STATUS);
if (!hDepService)
{
success = false;
__leave;
}
__try {
// Send a stop code.
if (!ControlService(hDepService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS)&ssp))
{
success = false;
__leave;
}
// Wait for the service to stop.
while (ssp.dwCurrentState != SERVICE_STOPPED)
{
Sleep(ssp.dwWaitHint);
if (!QueryServiceStatusEx(
hDepService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded))
{
success = false;
__leave;
}
if (ssp.dwCurrentState == SERVICE_STOPPED)
break;
if (GetTickCount64() - dwStartTime > dwTimeout)
{
success = false;
__leave;
}
}
}
__finally
{
// Always release the service handle.
CloseServiceHandle(hDepService);
}
}
}
__finally
{
// Always free the enumeration buffer.
HeapFree(GetProcessHeap(), 0, lpDependencies);
}
}
return success;
#else
return false;
#endif
}
bool ServiceStopper::StartService_s(std::string serviceName)
{
#ifdef _WIN32
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwOldCheckPoint;
ULONGLONG dwStartTickCount;
DWORD dwWaitTime;
DWORD dwBytesNeeded;
// Get a handle to the SCM database.
SC_HANDLE schSCManager = OpenSCManager(
NULL, // local computer
NULL, // servicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
{
throw ServiceStopException("OpenSCManager failed (%d)", GetLastError());
}
// Get a handle to the service.
SC_HANDLE schService = OpenService(
schSCManager, // SCM database
serviceName.c_str(), // name of service
SERVICE_ALL_ACCESS); // full access
if (schService == NULL)
{
CloseServiceHandle(schSCManager);
throw ServiceStopException("OpenService failed (%d)", GetLastError());
}
// Check the status in case the service is not stopped.
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE)&ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded)) // size needed if buffer is too small
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
throw ServiceStopException("QueryServiceStatusEx failed (%d)", GetLastError());
}
// Check if the service is already running. It would be possible
// to stop the service here, but for simplicity this example just returns.
if (ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING)
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
throw ServiceStopException("Cannot start the service because it is already running");
}
// Save the tick count and initial checkpoint.
dwStartTickCount = GetTickCount64();
dwOldCheckPoint = ssStatus.dwCheckPoint;
// Wait for the service to stop before attempting to start it.
while (ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one-tenth of the wait hint but not less than 1 second
// and not more than 10 seconds.
dwWaitTime = ssStatus.dwWaitHint / 10;
if (dwWaitTime < 1000)
dwWaitTime = 1000;
else if (dwWaitTime > 10000)
dwWaitTime = 10000;
Sleep(dwWaitTime);
// Check the status until the service is no longer stop pending.
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE)&ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded)) // size needed if buffer is too small
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
throw ServiceStopException("QueryServiceStatusEx failed (%d)\n", GetLastError());
}
if (ssStatus.dwCheckPoint > dwOldCheckPoint)
{
// Continue to wait and check.
dwStartTickCount = GetTickCount64();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if (GetTickCount64() - dwStartTickCount > ssStatus.dwWaitHint)
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
throw ServiceStopException("Timeout waiting for service to stop\n");
}
}
}
// Attempt to start the service.
if (!StartService(
schService, // handle to service
0, // number of arguments
NULL)) // no arguments
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
throw ServiceStopException("StartService failed (%d)\n", GetLastError());
}
// Check the status until the service is no longer start pending.
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE)&ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded)) // if buffer too small
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
throw ServiceStopException("QueryServiceStatusEx failed (%d)\n", GetLastError());
}
// Save the tick count and initial checkpoint.
dwStartTickCount = GetTickCount64();
dwOldCheckPoint = ssStatus.dwCheckPoint;
while (ssStatus.dwCurrentState == SERVICE_START_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one-tenth the wait hint, but no less than 1 second and no
// more than 10 seconds.
dwWaitTime = ssStatus.dwWaitHint / 10;
if (dwWaitTime < 1000)
dwWaitTime = 1000;
else if (dwWaitTime > 10000)
dwWaitTime = 10000;
Sleep(dwWaitTime);
// Check the status again.
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE)&ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded)) // if buffer too small
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
throw ServiceStopException("QueryServiceStatusEx failed (%d)\n", GetLastError());
}
if (ssStatus.dwCheckPoint > dwOldCheckPoint)
{
// Continue to wait and check.
dwStartTickCount = GetTickCount64();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if (GetTickCount64() - dwStartTickCount > ssStatus.dwWaitHint)
{
// No progress made within the wait hint.
break;
}
}
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
// Determine whether the service is running.
return (ssStatus.dwCurrentState == SERVICE_RUNNING);
#else
return false;
#endif
}
bool ServiceStopper::KillProcess(std::string procName)
{
#ifdef _WIN32
HANDLE hndl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
DWORD dwsma = GetLastError();
DWORD dwExitCode = 0;
PROCESSENTRY32 procEntry = { 0 };
procEntry.dwSize = sizeof(PROCESSENTRY32);
bool found = false;
Process32First(hndl, &procEntry);
do
{
if (!strcmpi(procEntry.szExeFile, procName.c_str()))
{
found = true;
break;
}
//cout<<"Running Process "<<" "<<procEntry.szExeFile<<endl;
} while (Process32Next(hndl, &procEntry));
if (found)
{
HANDLE hHandle;
hHandle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, procEntry.th32ProcessID);
::GetExitCodeProcess(hHandle, &dwExitCode);
return ::TerminateProcess(hHandle, dwExitCode);
}
// There is no need to inform the user that the process cannot be killed if it is the VMware Player version or it not running.
//else throw ServiceStopException("Couldn't kill %s, process not found.", procName.c_str());
#endif
return false;
}
| 12,734
|
C++
|
.cpp
| 417
| 27.088729
| 127
| 0.708085
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,320
|
patchutils.cpp
|
muhac_vmware-macos-unlocker/auto-unlocker/src/patchutils.cpp
|
#include "patchutils.h"
// Settings for memory and IO related stuff
#define FREAD_BUF_SIZE 2048 // 2 kB
// Flags needed for ELF parsing
#define E_CLASS64 2
#define E_SHT_RELA 4
// Capital letters range from 0x41 to 0x5A
// other letters from 0x61 to 0x7A
// total is 26 -- double of 13
std::string Patcher::rot13(const std::string& in)
{
std::string out;
for (char c : in)
{
if (c >= 0x41 && c <= 0x5A)
{
// CAPITAL LETTER
out += (((c - 0x41) + 13) % 26) + 0x41;
}
else if (c >= 0x61 && c <= 0x7A)
{
// NON CAPITAL LETTER
out += (((c - 0x61) + 13) % 26) + 0x61;
}
else
{
// NUMBER/SYMBOL/OTHER STUFF
out += c;
}
}
return out;
}
std::vector<char> Patcher::makeVector(const char* arr, size_t size)
{
return std::vector<char>(arr, arr+size);
}
bool Patcher::cmpcarr(const char* c1, const char* c2, size_t len)
{
return std::equal(c1, c1+len, c2);
}
// Different implementations for reusing the same memory stream
std::optional<unsigned long long> Patcher::searchForOffset(const std::vector<char>& memstream, const std::vector<char>& sequence, unsigned long long from)
{
if (from >= memstream.size() - sequence.size())
return {};
auto sRes = std::search(memstream.begin()+from, memstream.end(), sequence.begin(), sequence.end());
if (sRes != memstream.end())
return (sRes - memstream.begin());
else
return {};
}
std::optional<unsigned long long> Patcher::searchForLastOffset(const std::vector<char>& memstream, const std::vector<char>& sequence)
{
auto sRes = std::find_end(memstream.begin(), memstream.end(), sequence.begin(), sequence.end());
if (sRes != memstream.end())
return (sRes - memstream.begin());
else
return {};
}
std::optional<unsigned long long> Patcher::searchForOffset(std::fstream& stream, const std::vector<char>& sequence, unsigned long long from)
{
std::vector<char> memFile = readFile(stream);
if (from >= memFile.size() - sequence.size())
return {};
auto sRes = std::search(memFile.begin()+from, memFile.end(), sequence.begin(), sequence.end());
if (sRes != memFile.end())
return (sRes - memFile.begin());
else
return {};
}
std::optional<unsigned long long> Patcher::searchForLastOffset(std::fstream& stream, const std::vector<char>& sequence)
{
std::vector<char> memFile = readFile(stream);
auto sRes = std::find_end(memFile.begin(), memFile.end(), sequence.begin(), sequence.end());
if (sRes != memFile.end())
return (sRes - memFile.begin());
else
return {};
}
std::vector<char> Patcher::readFile(std::fstream& stream)
{
std::vector<char> memFile;
stream.clear();
stream.seekg(std::ios::beg);
std::array<char, FREAD_BUF_SIZE> buffer{};
while (!stream.eof())
{
stream.read(buffer.data(), buffer.size());
size_t readBytes = stream.gcount();
memFile.insert(memFile.end(), buffer.begin(), buffer.begin()+readBytes);
}
return memFile;
}
std::string Patcher::hexRepresentation(std::string bin)
{
std::stringstream out;
for (char c : bin)
{
out << std::setfill('0') << std::setw(2) << std::hex << (int)c << " ";
}
return out.str();
}
std::string Patcher::hexRepresentation(std::vector<char> bin)
{
std::stringstream out;
for (char c : bin)
{
out << std::setfill('0') << std::setw(2) << std::hex << (int)c << " ";
}
return out.str();
}
std::string Patcher::hexRepresentation(long long bin)
{
std::stringstream out;
out << "0x" << std::setfill('0') << std::setw(sizeof(long long)*2) << std::hex << bin;
return out.str();
}
void Patcher::printkey(int i, unsigned long long offset, const smc_key_struct& smc_key, const std::vector<char>& smc_data)
{
std::stringstream result;
result << std::setfill('0') << std::setw(3) << (i + 1);
result << " " << hexRepresentation(offset);
{
std::vector<char> arr( smc_key.s0, smc_key.s0 + 4); // copy into new vector
std::reverse(arr.begin(), arr.end()); // reverse -- as [::-1] does in python
std::string arr_str(arr.begin(), arr.end());
result << " " << arr_str;
}
{
result << " " << std::setfill('0') << std::setw(2) << (int)smc_key.B1;
}
{
std::vector<char> arr(smc_key.s2, smc_key.s2 + 4); // copy into new vector
std::reverse(arr.begin(), arr.end()); // reverse -- as [::-1] does in python
std::replace(arr.begin(), arr.end(), char(0x00), ' '); // replace 0x0 with ' '
std::string arr_str(arr.begin(), arr.end());
result << " " << arr_str;
}
{
result << " 0x" << std::setfill('0') << std::setw(2) << std::hex << (int)smc_key.B3;
}
{
result << " " << hexRepresentation(smc_key.Q4);
}
result << " " << hexRepresentation(smc_data);
logd(result.str());
}
void Patcher::patchSMC(fs::path name, bool isSharedObj)
{
std::fstream i_file(name, std::ios_base::binary | std::ios_base::out | std::ios_base::in);
if (!i_file.good())
throw PatchException("Couldn't open file %s", name.c_str());
long smc_old_memptr = 0;
long smc_new_memptr = 0;
// Read file into string variable
//vmx = f.read();
logd("Patching file: " + name.filename().string());
// Setup hex string for vSMC headers
// These are the private and public key counts
char smc_header_v0[] = SMC_HEADER_V0;
char smc_header_v1[] = SMC_HEADER_V1;
// Setup hex string for #KEY key
char key_key[] = KEY_KEY;
// Setup hex string for $Adr key
char adr_key[] = ADR_KEY;
// Load up whole file into memory
std::vector<char> memFile = readFile(i_file);
// Find the vSMC headers
auto res = searchForOffset(memFile, makeVector(smc_header_v0, SMC_HEADER_V0_SZ));
if (!res.has_value())
throw PatchException("Couldn't find smc_header_v0_offset");
unsigned long long smc_header_v0_offset = res.value() - 8;
res = searchForOffset(memFile, makeVector(smc_header_v1, SMC_HEADER_V1_SZ));
if (!res.has_value())
throw PatchException("Couldn't find smc_header_v1_offset");
unsigned long long smc_header_v1_offset = res.value() -8;
// Find '#KEY' keys
res = searchForOffset(memFile, makeVector(key_key, KEY_KEY_SZ)); //FIXME: doesn't work
if (!res.has_value())
throw PatchException("Couldn't find smc_key0 offset");
unsigned long long smc_key0 = res.value();
res = searchForLastOffset(memFile, makeVector(key_key, KEY_KEY_SZ));
if (!res.has_value())
throw PatchException("Couldn't find smc_key1 offset");
unsigned long long smc_key1 = res.value();
// Find '$Adr' key only V1 table
res = searchForOffset(memFile, makeVector(adr_key, ADR_KEY_SZ));
if (!res.has_value())
throw PatchException("Couldn't find smc_adr offset");
unsigned long long smc_adr = res.value();
memFile.clear();
// Print vSMC0 tables and keys
logd("appleSMCTableV0 (smc.version = \"0\")");
logd("appleSMCTableV0 Address : " + hexRepresentation(smc_header_v0_offset));
logd("appleSMCTableV0 Private Key #: 0xF2/242");
logd("appleSMCTableV0 Public Key #: 0xF0/240");
if ((smc_adr - smc_key0) != 72)
{
logd("appleSMCTableV0 Table : " + hexRepresentation(smc_key0));
auto res = patchKeys(i_file, smc_key0);
smc_old_memptr = res.first;
smc_new_memptr = res.second;
}
else if ((smc_adr - smc_key1) != 72)
{
logd("appleSMCTableV0 Table : " + hexRepresentation(smc_key1));
auto res = patchKeys(i_file, smc_key1);
smc_old_memptr = res.first;
smc_new_memptr = res.second;
}
logd("");
// Print vSMC1 tables and keys
logd("appleSMCTableV1 (smc.version = \"1\")");
logd("appleSMCTableV1 Address : " + hexRepresentation(smc_header_v1_offset));
logd("appleSMCTableV1 Private Key #: 0x01B4/436");
logd("appleSMCTableV1 Public Key #: 0x01B0/432");
if ((smc_adr - smc_key0) == 72)
{
logd("appleSMCTableV1 Table : " + hexRepresentation(smc_key0));
auto res = patchKeys(i_file, smc_key0);
smc_old_memptr = res.first, smc_new_memptr = res.second;
}
else if ((smc_adr - smc_key1) == 72)
{
logd("appleSMCTableV1 Table : " + hexRepresentation(smc_key1));
auto res = patchKeys(i_file, smc_key1);
smc_old_memptr = res.first, smc_new_memptr = res.second;
}
logd("");
// Find matching RELA record in.rela.dyn in ESXi ELF files
// This is temporary code until proper ELF parsing written
if (isSharedObj)
{
logd("Modifying RELA records from: " + hexRepresentation(smc_old_memptr) + " to " + hexRepresentation(smc_new_memptr));
patchElf(i_file, smc_old_memptr, smc_new_memptr);
}
// Tidy up
i_file.close();
}
std::pair<unsigned long long, unsigned long long> Patcher::patchKeys(std::fstream& file, long long key)
{
// Setup struct pack string
//std::string key_pack = "=4sB4sB6xQ";
// smc_old_memptr = 0
unsigned long long smc_new_memptr = 0;
// Do Until OSK1 read
int i = 0;
while (true)
{
// Read key into struct strand data byte str
long long offset = key + ((unsigned long long)i * 72);
file.clear();
file.seekg(offset);
smc_key_struct smc_key = { 0 };
file.read(reinterpret_cast<char*>(&smc_key), 24);
//auto smc_key = structUnpack(key_pack, rr);
std::vector<char> smc_data;
auto sz = smc_key.B1;
smc_data.resize(sz);
file.read(smc_data.data(), sz );
// Reset pointer to beginning of key entry
file.clear();
file.seekg(offset);
auto smc_key_0 = smc_key.s0;
std::string cmp = "SKL+";
std::string cmp1 = "0KSO";
std::string cmp2 = "1KSO";
if (cmpcarr(smc_key_0, cmp.data(), 4))
{
// Use the + LKS data routine for OSK0 / 1
smc_new_memptr = smc_key.Q4;
logd("+LKS Key: ");
printkey(i, offset, smc_key, smc_data); // too lazy for this one - but I coded it eventually
}
else if (cmpcarr(smc_key_0, cmp1.data(), 4))
{
//Write new data routine pointer from + LKS
logd("OSK0 Key Before:");
printkey(i, offset, smc_key, smc_data);
// smc_old_memptr = smc_key[4]
file.clear();
file.seekg(offset);
smc_key_struct towrite = { 0 };
memcpy(towrite.s0, smc_key.s0, 4);
towrite.B1 = smc_key.B1;
memcpy(towrite.s2, smc_key.s2, 4);
towrite.B3 = smc_key.B3;
towrite.Q4 = smc_new_memptr;
file.write(reinterpret_cast<char*>(&towrite), sizeof(smc_key_struct));
file.flush();
// Write new data for key
file.clear();
file.seekg(offset + 24);
std::string smc_new_data = rot13(SMC_NEW_DATA); // lulz
file.write(smc_new_data.data(), smc_new_data.size());
//f.write(smc_new_data.encode('UTF-8'))
file.flush();
// Re - read and print key
file.clear();
file.seekg(offset);
file.read(reinterpret_cast<char*>(&smc_key), 24);
smc_data.clear();
smc_data.resize(smc_key.B1);
file.read(smc_data.data(), smc_key.B1);
logd("OSK0 Key After:");
printkey(i, offset, smc_key, smc_data);
}
else if (cmpcarr(smc_key.s0, cmp2.data(), 4))
{
// Write new data routine pointer from + LKS
logd("OSK1 Key Before:");
printkey(i, offset, smc_key, smc_data);
unsigned long long smc_old_memptr = smc_key.Q4;
file.clear();
file.seekg(offset);
smc_key_struct towrite = { 0 };
memcpy(towrite.s0, smc_key.s0, 4);
towrite.B1 = smc_key.B1;
memcpy(towrite.s2, smc_key.s2, 4);
towrite.B3 = smc_key.B3;
towrite.Q4 = smc_new_memptr;
file.write(reinterpret_cast<char*>(&towrite), sizeof(smc_key_struct));
file.flush();
// Write new data for key
file.clear();
file.seekg(offset + 24);
std::string smc_new_data = rot13(SMC_NEW_DATA2); // so funny
file.write(smc_new_data.data(), smc_new_data.size());
file.flush();
// Re - read and print key
file.clear();
file.seekg(offset);
file.read(reinterpret_cast<char*>(&smc_key), 24);
smc_data.clear();
smc_data.resize(smc_key.B1);
file.read(smc_data.data(), smc_key.B1);
logd("OSK1 Key After:");
printkey(i, offset, smc_key, smc_data);
// Finished so get out of loop
return std::make_pair(smc_old_memptr, smc_new_memptr);
}
i += 1;
}
}
void Patcher::patchBase(fs::path name)
{
//Patch file
logd("GOS Patching: " + name.filename().string());
std::fstream file(name, std::ios_base::binary | std::ios_base::in | std::ios_base::out);
if (!file.good())
throw PatchException("Couldn't open file %s", name.c_str());
// Entry to search for in GOS table
// Should work for Workstation 12 - 15...
std::vector<char> memFile = readFile(file);
/* REGEX WAY --- Seems to not work
std::regex darwin = std::regex(DARWIN_REGEX);
std::string buf;
buf.resize(32);
// Loop through each entryand set top bit
// 0xBE -- > 0xBF (WKS 12)
// 0x3E -- > 0x3F (WKS 14)
unsigned int occurrences = 0;
auto reg_iter = std::cregex_iterator(memFile.data(), memFile.data()+memFile.size(), darwin);
for (auto it = reg_iter; it != std::cregex_iterator(); it++)
{
std::cmatch match = *it;
size_t pos = match.position();
file.clear();
file.seekg(pos + 32);
char flag = file.get();
flag = (flag | (1 << 0));
file.clear();
file.seekg(pos + 32);
file.put(flag);
logd("GOS Patched flag @: " + hexRepresentation(pos));
occurrences++;
} */
/* Iterative way */
std::vector<char> darwinPattern[4];
darwinPattern[0] = DARWIN_PATTERN_PERM_1;
darwinPattern[1] = DARWIN_PATTERN_PERM_2;
darwinPattern[2] = DARWIN_PATTERN_PERM_3;
darwinPattern[3] = DARWIN_PATTERN_PERM_4;
const size_t mStreamLen = memFile.size();
for (int i = 0; i < 4; i++)
{
const std::vector<char>& darwinPatt = darwinPattern[i];
std::optional<unsigned long long> val = 0;
do
{
val = searchForOffset(memFile, darwinPatt, val.value());
if (val.has_value())
{
auto pos = val.value();
file.clear();
file.seekg(pos + 32);
char flag = file.get();
flag |= 1;
file.clear();
file.seekg(pos + 32);
file.put(flag);
logd("GOS Patched flag @: " + hexRepresentation(pos));
val = val.value() + 40;
}
} while (val.has_value());
}
file.flush();
file.close();
logd("GOS Patched: " + name.filename().string());
}
void Patcher::patchVmkctl(fs::path name)
{
logd("smcPresent Patching: " + name.filename().string());
std::fstream file(name, std::ios_base::in | std::ios_base::out);
std::string find_str = VMKCTL_FIND_STR;
std::vector<char> find_crs(find_str.begin(), find_str.end());
auto offset = searchForOffset(file, find_crs);
if (offset.has_value())
{
std::string rep_str = VMKCTL_REPLACE_STR;
file.clear();
file.seekg(offset.value());
file.write(rep_str.data(), rep_str.size());
file.flush();
file.close();
}
else
throw PatchException("Couldn't find Vmkctl offset");
}
void Patcher::patchElf(std::fstream& file, long long oldoffset, long long newoffset)
{
file.clear();
file.seekg(std::ios_base::beg);
char buf[5];
memset(buf, 0, 5);
file.read(buf, 4);
if (strcmp(buf, "\x7f""ELF") != 0)
{
throw PatchException("Not an ELF binary.");
}
unsigned char u = file.get();
if (u != E_CLASS64)
{
throw PatchException("Not a 64 bit binary.");
}
file.clear();
file.seekg(40);
unsigned long long e_shoff;
file.read(reinterpret_cast<char*>(&e_shoff), sizeof(unsigned long long));
file.clear();
file.seekg(58);
unsigned short e_shentsize, e_shnum, e_shstrndx;
file.read(reinterpret_cast<char*>(&e_shentsize), sizeof(unsigned short));
file.read(reinterpret_cast<char*>(&e_shnum), sizeof(unsigned short));
file.read(reinterpret_cast<char*>(&e_shstrndx), sizeof(unsigned short));
printf("e_shoff: 0x%02llX e_shentsize: 0x%02X e_shnum:0x%02X e_shstrndx:0x%02X\n", e_shoff, e_shentsize,
e_shnum, e_shstrndx);
for (unsigned short i = 0; i < e_shnum; i++)
{
file.clear();
file.seekg(e_shoff + i * (unsigned long long)e_shentsize);
LLQQQQLLQQ e_sh = { 0 };
file.read(reinterpret_cast<char*>(&e_sh), e_shentsize);
auto e_sh_type = e_sh.l2;
auto e_sh_offset = e_sh.q3;
auto e_sh_size = e_sh.q4;
auto e_sh_entsize = e_sh.q6;
if (e_sh_type == E_SHT_RELA)
{
auto e_sh_nument = int(e_sh_size / e_sh_entsize);
for (int j = 0; j < e_sh_nument; j++)
{
file.clear();
file.seekg(e_sh_offset + e_sh_entsize * j);
QQq rela;
file.read(reinterpret_cast<char*>(&rela), e_sh_entsize);
auto r_offset = rela.Q1;
auto r_info = rela.Q2;
auto r_addend = rela.q3;
if (r_addend == oldoffset)
{
r_addend = newoffset;
file.clear();
file.seekg(e_sh_offset + e_sh_entsize * j);
QQq towr;
towr.Q1 = r_offset;
towr.Q2 = r_info;
towr.q3 = r_addend;
file.write(reinterpret_cast<char*>(&towr), sizeof(QQq));
logd("Relocation modified at: " + hexRepresentation(e_sh_offset + e_sh_entsize * j));
}
}
}
}
}
| 16,319
|
C++
|
.cpp
| 495
| 30.090909
| 154
| 0.664609
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,321
|
unlocker.cpp
|
muhac_vmware-macos-unlocker/auto-unlocker/src/unlocker.cpp
|
/************************************************************************************************
Unlocker - Patcher + Tools Downloader
Created by Paolo Infante
Based on "Unlocker" by DrDonk for a native solution to python errors and
virus warnings.
I coded from scratch all the patch routines (I tried to be consistent with C++ library usage
though you'll probably find a few memcpy here and there...) and tools download (using
libcurl for download and libarchive to uncompress the archives)
Should be cross-platform. Tested on Windows, I'm planning to test it on linux too
I tried my best to use STL whenever possible. I had to use external libraries:
libcurl, libarchive and zlib that I'm sure can be compiled on linux, though.
To ensure cross-platform fs access I used std::filesystem from c++17, so a compiler that
supports it is required.
If the case arises that I'm not able to use STL I'll try to find a multiplatform solution
or code different solutions for both win and linux (as I did for Registry access)
*************************************************************************************************/
#include <string>
#include "filesystem.hpp"
#include <map>
#include <curl/curl.h>
#include "config.h"
#include "netutils.h"
#include "versionparser.h"
#include "debugutils.h"
#include "buildsparser.h"
#include "archiveutils.h"
#include "installinfoutils.h"
#include "servicestoputils.h"
#include "patchutils.h"
#ifdef __linux__
#include <unistd.h>
#include <strings.h>
#define stricmp(a, b) strcasecmp(a, b)
#endif
#include <stdio.h>
#define CHECKRES(x) try{ (x); } catch (const Patcher::PatchException& exc) { logerr(exc.what()); }
#define KILL(x) (x); exit(1);
// Forward declarations
void preparePatch(fs::path backupPath);
void doPatch();
void downloadTools(std::string path);
void copyTools(std::string toolspath);
void stopServices();
void restartServices();
void install();
void uninstall();
void showhelp();
// Main function
int main(int argc, const char* argv[])
{
std::cout << "auto-unlocker " << PROG_VERSION << std::endl
<< std::endl;
#ifdef __linux__
if (geteuid() != 0)
{
// User not root and not elevated permissions
logd("The program is not running as root, the patch may not work properly.");
std::cout << "Running the program with sudo/as root is recommended, in most cases required... Do you want to continue? (y/N) ";
char c = getc(stdin);
if (c != 'y' && c != 'Y')
{
logd("Aborting...");
exit(0);
}
}
#endif
if (argc > 1)
{
const char* arg = argv[1];
if (stricmp(arg, UNINSTALL_OPTION) == 0)
uninstall();
else if (stricmp(arg, HELP_OPTION) == 0)
showhelp();
else if (stricmp(arg, INSTALL_OPTION) == 0)
install();
else
{
logd("Unrecognized command.");
logd("");
showhelp();
}
}
else {
fs::path backupFolder = BACKUP_FOLDER;
if (fs::exists(backupFolder))
{
std::cout << "A backup folder has been found. Do you wish to uninstall the previous patch? Type y to uninstall, n to continue with installation." << std::endl
<< "(Y/n) ";
char c = getc(stdin);
if (c == 'n' || c == 'N')
install();
else
uninstall();
} else install();
}
logd("Press enter to quit.");
getc(stdin);
return 0;
}
void install()
{
// Default output path is ./tools/
std::string toolsdirectory = (fs::path(".") / TOOLS_DOWNLOAD_FOLDER / "").string();
// Default backup path is ./backup/
fs::path backup = fs::path(".") / BACKUP_FOLDER;
logd("Killing services and backing up files...");
preparePatch(backup);
logd("Patching files...");
doPatch();
logd("Downloading tools into \"" + toolsdirectory + "\" directory...");
if (fs::exists(fs::path(".") / TOOLS_DOWNLOAD_FOLDER / FUSION_ZIP_TOOLS_NAME) && fs::exists(fs::path(".") / TOOLS_DOWNLOAD_FOLDER / FUSION_ZIP_PRE15_TOOLS_NAME))
{
std::cout << "Tools have been found in the executable folder. Do you want to use the existing tools instead of downloading them again?" << std::endl
<< "Please check that the existing tools are working and are the most recent ones." << std::endl
<< "(Y/n) ";
char c = getc(stdin);
if (c != 'y' && c != 'Y')
downloadTools(toolsdirectory);
}
else
downloadTools(toolsdirectory);
logd("Copying tools into program directory...");
copyTools(toolsdirectory);
restartServices();
logd("Patch complete.");
}
void uninstall()
{
#ifdef _WIN32
VMWareInfoRetriever vmInfo;
// Stop services
stopServices();
// Default output path is ./tools/
fs::path toolsdirectory = fs::path(".") / TOOLS_DOWNLOAD_FOLDER;
// Default backup path is ./backup/
fs::path backup = fs::path(".") / BACKUP_FOLDER;
fs::path vmwareInstallDir = vmInfo.getInstallPath();
fs::path vmwareInstallDir64 = vmInfo.getInstallPath64();
logd("Restoring files...");
// Copy contents of backup/
if (fs::exists(backup))
{
for (const auto& file : fs::directory_iterator(backup))
{
if (fs::is_regular_file(file))
{
try
{
if (fs::copy_file(file.path(), vmwareInstallDir / file.path().filename(), fs::copy_options::overwrite_existing))
logd("File \"" + file.path().string() + "\" restored successfully");
else
logerr("Error while restoring \"" + file.path().string() + "\".");
}
catch (fs::filesystem_error ex)
{
logerr(ex.what());
}
}
}
// Copy contents of backup/x64/
for (const auto& file : fs::directory_iterator(backup / "x64"))
{
if (fs::is_regular_file(file))
{
try
{
if (fs::copy_file(file.path(), vmwareInstallDir64 / file.path().filename(), fs::copy_options::overwrite_existing))
logd("File \"" + file.path().string() + "\" restored successfully");
else
logerr("Error while restoring \"" + file.path().string() + "\".");
}
catch (fs::filesystem_error ex)
{
logerr(ex.what());
}
}
}
}
else {
logerr("Couldn't find backup files...");
return;
}
// Remove darwin*.* from InstallDir
for (const auto& file : fs::directory_iterator(vmwareInstallDir))
{
if (fs::is_regular_file(file))
{
size_t is_drw = file.path().filename().string().find("darwin");
if (is_drw != std::string::npos && is_drw == 0)
fs::remove(file);
}
}
fs::remove_all(backup);
fs::remove_all(toolsdirectory);
// Restart services
restartServices();
logd("Uninstall complete.");
#elif defined (__linux__)
// Default output path is ./tools/
fs::path toolsdirectory = fs::path(".") / TOOLS_DOWNLOAD_FOLDER;
// Default backup path is ./backup/
fs::path backup = fs::path(".") / BACKUP_FOLDER;
fs::path vmwareDir = VM_LNX_PATH;
logd("Restoring files...");
// Copy contents of backup/
std::vector<std::string> lnxBins = VM_LNX_BINS;
for (const auto& file : lnxBins)
{
try
{
if (fs::copy_file(backup / file, vmwareDir / file, fs::copy_options::overwrite_existing))
logd("File \"" + (backup / file).string() + "\" restored successfully");
else
logerr("Error while restoring \"" + (backup / file).string() + "\".");
}
catch (fs::filesystem_error ex)
{
logerr(ex.what());
}
}
std::vector<std::string> vmLibCandidates = VM_LNX_LIB_CANDIDATES;
for (const auto& lib : vmLibCandidates)
{
if (fs::exists(fs::path(lib).parent_path()))
{
try
{
if (fs::copy_file(backup / fs::path(lib).filename(), fs::path(lib), fs::copy_options::overwrite_existing))
logd("File \"" + (backup / fs::path(lib).filename()).string() + "\" restored successfully");
else
logerr("Error while restoring \"" + (backup / fs::path(lib).filename()).string() + "\".");
}
catch (fs::filesystem_error ex)
{
logerr(ex.what());
}
break;
}
}
// Remove darwin*.* from InstallDir
for (const auto& file : fs::directory_iterator(VM_LNX_ISO_DESTPATH))
{
if (fs::is_regular_file(file))
{
size_t is_drw = file.path().filename().string().find("darwin");
if (is_drw != std::string::npos && is_drw == 0)
fs::remove(file);
}
}
fs::remove_all(backup);
fs::remove_all(toolsdirectory);
logd("Uninstall complete.");
#endif
}
void showhelp()
{
std::cout << "auto-unlocker" << std::endl << std::endl
<< "Run the program with one of these options:" << std::endl
<< " --install (default): install the patch" << std::endl
<< " --uninstall: remove the patch" << std::endl
<< " --help: show this help message" << std::endl;
}
// Other methods
// Copy tools to VMWare directory
void copyTools(std::string toolspath)
{
#ifdef _WIN32
VMWareInfoRetriever vmInfo;
fs::path copyto = vmInfo.getInstallPath();
fs::path toolsfrom = toolspath;
try
{
if (fs::copy_file(toolsfrom / FUSION_ZIP_TOOLS_NAME, copyto / FUSION_ZIP_TOOLS_NAME))
logd("File \"" + (toolsfrom / FUSION_ZIP_TOOLS_NAME).string() + "\" copy done.");
else
logerr("File \"" + (toolsfrom / FUSION_ZIP_TOOLS_NAME).string() + "\" could not be copied.");
}
catch (const std::exception & e)
{
logerr(e.what());
}
try
{
if (fs::copy_file(toolsfrom / FUSION_ZIP_PRE15_TOOLS_NAME, copyto / FUSION_ZIP_PRE15_TOOLS_NAME))
logd("File \"" + (toolsfrom / FUSION_ZIP_PRE15_TOOLS_NAME).string() + "\" copy done.");
else
logerr("File \"" + (toolsfrom / FUSION_ZIP_PRE15_TOOLS_NAME).string() + "\" could not be copied.");
}
catch (const std::exception & e)
{
logerr(e.what());
}
#elif defined (__linux__)
fs::path copyto = VM_LNX_ISO_DESTPATH;
fs::path toolsfrom = toolspath;
try
{
if (fs::copy_file(toolsfrom / FUSION_ZIP_TOOLS_NAME, copyto / FUSION_ZIP_TOOLS_NAME))
logd("File \"" + (toolsfrom / FUSION_ZIP_TOOLS_NAME).string() + "\" copy done.");
else
logerr("File \"" + (toolsfrom / FUSION_ZIP_TOOLS_NAME).string() + "\" could not be copied.");
}
catch (const std::exception & e)
{
logerr(e.what());
}
try
{
if (fs::copy_file(toolsfrom / FUSION_ZIP_PRE15_TOOLS_NAME, copyto / FUSION_ZIP_PRE15_TOOLS_NAME))
logd("File \"" + (toolsfrom / FUSION_ZIP_PRE15_TOOLS_NAME).string() + "\" copy done.");
else
logerr("File \"" + (toolsfrom / FUSION_ZIP_PRE15_TOOLS_NAME).string() + "\" could not be copied.");
}
catch (const std::exception & e)
{
logerr(e.what());
}
#endif
}
// Actual patch code
void doPatch()
{
#ifdef _WIN32
// Setup paths
VMWareInfoRetriever vmInfo;
std::string binList[] = VM_WIN_PATCH_FILES;
fs::path vmwarebase_path = vmInfo.getInstallPath();
fs::path vmx_path = vmInfo.getInstallPath64();
fs::path vmx = vmx_path / binList[0];
fs::path vmx_debug = vmx_path / binList[1];
fs::path vmx_stats = vmx_path / binList[2];
fs::path vmwarebase = vmwarebase_path / binList[3];
if(!fs::exists(vmx))
{
KILL(logerr("Vmx file not found"));
}
if(!fs::exists(vmx_debug))
{
KILL(logerr("Vmx file not found"));
}
if(!fs::exists(vmwarebase))
{
KILL(logerr("Vmx file not found"));
}
logd("File: " + vmx.filename().string());
CHECKRES(Patcher::patchSMC(vmx, false));
logd("File: " + vmx_debug.filename().string());
CHECKRES(Patcher::patchSMC(vmx_debug, false));
if (fs::exists(vmx_stats))
{
logd("File: " + vmx_stats.filename().string());
CHECKRES(Patcher::patchSMC(vmx_stats, false));
}
logd("File: " + vmwarebase.filename().string());
CHECKRES(Patcher::patchBase(vmwarebase));
#elif defined (__linux__)
fs::path vmBinPath = VM_LNX_PATH;
std::string binList[] = VM_LNX_BINS;
fs::path vmx = vmBinPath / binList[0];
fs::path vmx_debug = vmBinPath / binList[1];
fs::path vmx_stats = vmBinPath / binList[2];
// See if first candidate is good else use second one
std::string libCandidates[] = VM_LNX_LIB_CANDIDATES;
bool vmxso = true;
fs::path vmlib = libCandidates[0];
if (!fs::exists(vmlib)) {
vmlib = libCandidates[1];
vmxso = false;
}
if(!fs::exists(vmx))
{
KILL(logerr("Vmx file not found"));
}
if(!fs::exists(vmx_debug))
{
KILL(logerr("Vmx-debug file not found"));
}
if(!fs::exists(vmlib))
{
KILL(logerr("Vmlib file not found"));
}
logd("File: " + vmx.filename().string());
CHECKRES(Patcher::patchSMC(vmx, vmxso));
logd("File: " + vmx_debug.filename().string());
CHECKRES(Patcher::patchSMC(vmx_debug, vmxso));
if (fs::exists(vmx_stats))
{
logd("File: " + vmx_stats.filename().string());
CHECKRES(Patcher::patchSMC(vmx_stats, vmxso));
}
logd("File: " + vmlib.filename().string());
CHECKRES(Patcher::patchBase(vmlib));
#else
logerr("OS not supported");
exit(1);
#endif
}
void stopServices()
{
#ifdef _WIN32
// Stop services
auto srvcList = std::list<std::string> VM_KILL_SERVICES;
for (auto service : srvcList)
{
try
{
ServiceStopper::StopService_s(service);
logd("Service \"" + service + "\" stopped successfully.");
}
catch (const ServiceStopper::ServiceStopException& ex)
{
// There is no need to inform the user that the service cannot be stopped if that service does not exist in the current version.
//logerr("Couldn't stop service \"" + service + "\", " + std::string(ex.what()));
}
}
auto procList = std::list<std::string> VM_KILL_PROCESSES;
for (auto process : procList)
{
try {
if (ServiceStopper::KillProcess(process))
logd("Process \"" + process + "\" killed successfully.");
else
logerr("Could not kill process \"" + process + "\".");
}
catch (const ServiceStopper::ServiceStopException & ex)
{
logerr(ex.what());
}
}
#endif
}
void restartServices()
{
#ifdef _WIN32
logd("Restarting services...");
std::vector<std::string> servicesToStart = VM_KILL_SERVICES;
for (auto it = servicesToStart.rbegin(); it != servicesToStart.rend(); it++)
{
try
{
ServiceStopper::StartService_s(*it);
logd("Service \"" + *it + "\" started successfully.");
}
catch (const ServiceStopper::ServiceStopException & ex)
{
// There is no need to inform the user that the service cannot be started if that service does not exist in the current version.
//logerr("Couldn't start service " + *it);
}
}
#endif
}
// Kill services / processes and backup files
void preparePatch(fs::path backupPath)
{
#ifdef _WIN32
// Retrieve installation path from registry
VMWareInfoRetriever vmInstall;
stopServices();
// Backup files
auto filesToBackup = std::map<std::string, std::string> VM_WIN_BACKUP_FILES;
for (auto element : filesToBackup)
{
auto filen = element.first;
fs::path fPath = (vmInstall.getInstallPath() + filen);
fs::path destpath = backupPath / element.second;
if (!fs::exists(destpath))
fs::create_directory(destpath);
try
{
if (fs::copy_file(fPath, destpath / fPath.filename(), fs::copy_options::overwrite_existing))
logd("File \"" + fPath.string() + "\" backup done.");
else
logerr("File \"" + fPath.string() + "\" could not be copied.");
}
catch (const std::exception& e)
{
logerr(e.what());
}
}
#elif defined (__linux__)
//TODO: linux code here
// Backup files
std::string filesToBackup[] = VM_LNX_BACKUP_FILES;
fs::path destpath = backupPath;
for (auto element : filesToBackup)
{
fs::path fPath = element;
if (!fs::exists(destpath))
fs::create_directory(destpath);
try
{
if (fs::copy_file(fPath, destpath / fPath.filename(), fs::copy_options::overwrite_existing))
logd("File \"" + fPath.string() + "\" backup done.");
else
logerr("File \"" + fPath.string() + "\" could not be copied.");
}
catch (const std::exception & e)
{
logerr(e.what());
}
}
std::string libsAlternatives[] = VM_LNX_LIB_CANDIDATES;
for (auto lib : libsAlternatives)
{
fs::path libpath = lib;
if (fs::exists(libpath.parent_path()))
{
try
{
if (fs::copy_file(libpath, destpath / libpath.filename(), fs::copy_options::overwrite_existing))
logd("File \"" + libpath.string() + "\" backup done.");
else
logerr("File \"" + libpath.string() + "\" could not be copied.");
break;
}
catch (const std::exception & e)
{
logerr(e.what());
}
}
}
#else
// Either the compiler macros are not working or the the tool is trying to be compiled on an OS where it's not meant to be compiled
logerr("OS not supported");
exit(1); // Better stop before messing things up
#endif
}
// Download tools into "path"
void downloadTools(std::string path)
{
fs::path temppath = fs::temp_directory_path(); // extract files in the temp folder first
fs::create_directory(path); // create destination directory if it doesn't exist
curl_global_init(CURL_GLOBAL_ALL);
std::string url = FUSION_BASE_URL;
std::string releasesList;
Curl::curlGet(url, releasesList); // get the releases HTML page
VersionParser versionParser(releasesList); // parse HTML page to version numbers
if (versionParser.size() == 0)
{
logerr("No Fusion versions found in Download url location.");
return;
}
bool success = false;
// For each version number retrieve the latest build and check if tools are available
for (auto it = versionParser.cbegin(); it != versionParser.cend(); it++)
{
std::string version = it->getVersionText();
std::string versionurl = url + version + "/";
std::string versionhtml;
Curl::curlGet(versionurl, versionhtml);
BuildsParser builds(versionhtml); // parse the builds in the page
if (builds.size() > 0)
{
std::string buildurl = versionurl + builds.getLatest(); // use the latest build
std::string toolsurl = buildurl + FUSION_DEF_TOOLS_LOC;
std::string tools_pre15_url = buildurl + FUSION_DEF_PRE15_TOOLS_LOC;
std::string tools_diskpath = (temppath / FUSION_DEF_TOOLS_NAME).string();
std::string toolspre15_diskpath = (temppath / FUSION_DEF_PRE15_TOOLS_NAME).string();
bool toolsAvailable = (Curl::curlDownload(toolsurl, tools_diskpath) == CURLE_OK);
toolsAvailable &= (Curl::curlDownload(tools_pre15_url, toolspre15_diskpath) == CURLE_OK);
if (toolsAvailable) // if tools were successfully downloaded, extract them to destination folder
{
success = Archive::extract_s(temppath / FUSION_DEF_TOOLS_NAME, FUSION_DEF_TOOLS_ZIP, temppath / FUSION_DEF_TOOLS_ZIP);
success &= Archive::extract_s(temppath / FUSION_DEF_PRE15_TOOLS_NAME, FUSION_DEF_PRE15_TOOLS_ZIP, temppath / FUSION_DEF_PRE15_TOOLS_ZIP);
if (!success)
{
logerr("Couldn't extract zip files from tars");
continue;
}
success = Archive::extract_s(temppath / FUSION_DEF_TOOLS_ZIP, FUSION_TAR_TOOLS_ISO, path + FUSION_ZIP_TOOLS_NAME);
success &= Archive::extract_s(temppath / FUSION_DEF_PRE15_TOOLS_ZIP, FUSION_TAR_PRE15_TOOLS_ISO, path + FUSION_ZIP_PRE15_TOOLS_NAME);
// Cleanup zips
fs::remove(temppath / FUSION_DEF_TOOLS_ZIP);
fs::remove(temppath / FUSION_DEF_PRE15_TOOLS_ZIP);
if (!success)
{
logerr("Couldn't extract tools from zip files");
}
else
{
// Cleanup tars
fs::remove(temppath / FUSION_DEF_TOOLS_NAME);
fs::remove(temppath / FUSION_DEF_PRE15_TOOLS_NAME);
success = true;
break;
}
}
else {
// No tools available, try getting them from core fusion file
std::string coreurl = buildurl + FUSION_DEF_CORE_LOC;
std::string core_diskpath = (temppath / FUSION_DEF_CORE_NAME).string();
if (Curl::curlDownload(coreurl, core_diskpath) == CURLE_OK) // If the core package was successfully downloaded, extract the tools from it
{
logd("Extracting from .tar to temp folder ...");
fs::path temppath = fs::temp_directory_path();
success = Archive::extract_s(temppath/FUSION_DEF_CORE_NAME, FUSION_DEF_CORE_NAME_ZIP, temppath/FUSION_DEF_CORE_NAME_ZIP);
if (!success) {
logerr("Couldn't extract from the tar file");
// Error in the tar file, try the next version number
continue;
}
logd("Extracting from .zip to destination folder ...");
success = Archive::extract_s(temppath / FUSION_DEF_CORE_NAME_ZIP, FUSION_ZIP_TOOLS_ISO, path + FUSION_ZIP_TOOLS_NAME);
success = Archive::extract_s(temppath / FUSION_DEF_CORE_NAME_ZIP, FUSION_ZIP_PRE15_TOOLS_ISO, path + FUSION_ZIP_PRE15_TOOLS_NAME);
// Cleanup zip file
fs::remove(temppath / FUSION_DEF_CORE_NAME_ZIP);
if (!success)
logerr("Couldn't extract from the zip file"); // Error in the zip file, try the next version number
else
{
// Cleanup tar file
fs::remove(temppath / FUSION_DEF_CORE_NAME);
break; // All went good
}
}
// Cleanup tar file
fs::remove(temppath / FUSION_DEF_CORE_NAME);
}
// Cleanup tars
fs::remove(temppath / FUSION_DEF_TOOLS_NAME);
fs::remove(temppath / FUSION_DEF_PRE15_TOOLS_NAME);
}
}
if (success) {
logd("Tools successfully downloaded!");
}
else {
logerr("Couldn't find tools.");
}
curl_global_cleanup();
}
| 20,552
|
C++
|
.cpp
| 631
| 29.445325
| 162
| 0.669734
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,322
|
patchutils.h
|
muhac_vmware-macos-unlocker/auto-unlocker/include/patchutils.h
|
#ifndef PATCHUTILS_H
#define PATCHUTILS_H
#include "filesystem.hpp"
#include <fstream>
#include <optional>
#include <sstream>
#include <regex>
#include <iomanip>
#include <cstdarg>
#include <array>
#include "debugutils.h"
#include "config.h"
namespace Patcher
{
class PatchException : std::exception
{
public:
PatchException(const char* message, ...)
{
va_list args;
va_start(args, message);
char* buf = new char[1024];
vsprintf(buf, message, args);
va_end(args);
msg = buf;
}
~PatchException()
{
delete[] msg;
}
const char* what() const noexcept { return msg; }
private:
const char* msg;
};
struct LLQQQQLLQQ // couldn't find a better name LOL
{
unsigned long l1;
unsigned long l2;
unsigned long long q1;
unsigned long long q2;
unsigned long long q3;
unsigned long long q4;
unsigned long l3;
unsigned long l4;
unsigned long long q5;
unsigned long long q6;
};
struct QQq // it's starting to feel awkward
{
unsigned long long Q1, Q2;
long long q3;
};
struct smc_key_struct
{
char s0[4];
unsigned char B1;
char s2[4];
unsigned char B3;
unsigned char padding[6];
unsigned long long Q4;
};
// Utils
std::string rot13(const std::string& in);
std::vector<char> makeVector(const char* arr, size_t size);
std::string hexRepresentation(long long bin);
std::string hexRepresentation(std::vector<char> bin);
std::string hexRepresentation(std::string bin);
std::optional<unsigned long long> searchForOffset(const std::vector<char>& memstream, const std::vector<char>& sequence, unsigned long long from = 0);
std::optional<unsigned long long> searchForLastOffset(const std::vector<char>& memstream, const std::vector<char>& sequence);
std::optional<unsigned long long> searchForOffset(std::fstream& stream, const std::vector<char>& sequence, unsigned long long from = 0);
std::optional<unsigned long long> searchForLastOffset(std::fstream& stream, const std::vector<char>& sequence);
std::vector<char> readFile(std::fstream& stream);
bool cmpcarr(const char* c1, const char* c2, size_t len);
void printkey(int i, unsigned long long offset, const smc_key_struct& smc_key, const std::vector<char>& smc_data);
// Core functions
void patchSMC(fs::path name, bool isSharedObj);
std::pair<unsigned long long, unsigned long long> patchKeys(std::fstream& file, long long key);
void patchBase(fs::path name);
void patchVmkctl(fs::path name);
void patchElf(std::fstream& file, long long oldoffset, long long newoffset);
}
#endif // PATCHUTILS_H
| 2,538
|
C++
|
.h
| 82
| 28.536585
| 151
| 0.737638
|
muhac/vmware-macos-unlocker
| 35
| 17
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.