refactor(GridFire): updated outputs
This commit is contained in:
@@ -21,128 +21,26 @@
|
||||
|
||||
#include "gridfire/utils/gf_omp.h"
|
||||
|
||||
#include "nlohmann/json.hpp"
|
||||
|
||||
static std::terminate_handler g_previousHandler = nullptr;
|
||||
static std::vector<std::pair<double, std::unordered_map<std::string, std::pair<double, double>>>> g_callbackHistory;
|
||||
static bool s_wrote_abundance_history = false;
|
||||
void quill_terminate_handler();
|
||||
struct IntermediateResult {
|
||||
double time{};
|
||||
fourdst::composition::Composition comp;
|
||||
gridfire::reaction::ReactionSet reactions;
|
||||
std::vector<double> reaction_flows;
|
||||
double current_energy{};
|
||||
double current_neutrino_loss_rate{};
|
||||
|
||||
using namespace fourdst::composition;
|
||||
Composition rescale(const Composition& comp, double target_X, double target_Z) {
|
||||
// 1. Validate inputs
|
||||
if (target_X < 0.0 || target_Z < 0.0 || (target_X + target_Z) > 1.0 + 1e-14) {
|
||||
throw std::invalid_argument("Target mass fractions X and Z must be non-negative and sum to <= 1.0");
|
||||
}
|
||||
gridfire::reaction::ReactionSet inactive_reactions;
|
||||
std::vector<double> inactive_reaction_flows;
|
||||
};
|
||||
|
||||
// Force high precision for the target Y to ensure X+Y+Z = 1.0 exactly in our logic
|
||||
long double ld_target_X = static_cast<long double>(target_X);
|
||||
long double ld_target_Z = static_cast<long double>(target_Z);
|
||||
long double ld_target_Y = 1.0L - ld_target_X - ld_target_Z;
|
||||
|
||||
// Clamp Y to 0 if it dipped slightly below due to precision (e.g. X+Z=1.0000000001)
|
||||
if (ld_target_Y < 0.0L) ld_target_Y = 0.0L;
|
||||
|
||||
// 2. Manually calculate current Mass Totals (bypass getCanonicalComposition to avoid crashes)
|
||||
long double total_mass_H = 0.0L;
|
||||
long double total_mass_He = 0.0L;
|
||||
long double total_mass_Z = 0.0L;
|
||||
|
||||
// We need to iterate and identify species types manually
|
||||
// Standard definition: H (z=1), He (z=2), Metals (z>2)
|
||||
// Note: We use long double accumulators to prevent summation drift
|
||||
for (const auto& [spec, molar_abundance] : comp) {
|
||||
// Retrieve atomic properties.
|
||||
// Note: usage assumes fourdst::atomic::Species has .z() and .mass()
|
||||
// consistent with the provided composition.cpp
|
||||
int z = spec.z();
|
||||
double a = spec.mass();
|
||||
|
||||
long double mass_contribution = static_cast<long double>(molar_abundance) * static_cast<long double>(a);
|
||||
|
||||
if (z == 1) {
|
||||
total_mass_H += mass_contribution;
|
||||
} else if (z == 2) {
|
||||
total_mass_He += mass_contribution;
|
||||
} else {
|
||||
total_mass_Z += mass_contribution;
|
||||
}
|
||||
}
|
||||
|
||||
long double total_mass_current = total_mass_H + total_mass_He + total_mass_Z;
|
||||
|
||||
// Edge case: Empty composition
|
||||
if (total_mass_current <= 0.0L) {
|
||||
// Return empty or throw? If input was empty, return empty.
|
||||
if (comp.size() == 0) return comp;
|
||||
throw std::runtime_error("Input composition has zero total mass.");
|
||||
}
|
||||
|
||||
// 3. Calculate Scaling Factors
|
||||
// Factor = (Target_Mass_Fraction / Old_Mass_Fraction)
|
||||
// = (Target_Mass_Fraction) / (Old_Group_Mass / Total_Mass)
|
||||
// = (Target_Mass_Fraction * Total_Mass) / Old_Group_Mass
|
||||
|
||||
long double scale_H = 0.0L;
|
||||
long double scale_He = 0.0L;
|
||||
long double scale_Z = 0.0L;
|
||||
|
||||
if (ld_target_X > 1e-16L) {
|
||||
if (total_mass_H <= 1e-19L) {
|
||||
throw std::runtime_error("Cannot rescale Hydrogen to " + std::to_string(target_X) +
|
||||
" because input has no Hydrogen.");
|
||||
}
|
||||
scale_H = (ld_target_X * total_mass_current) / total_mass_H;
|
||||
}
|
||||
|
||||
if (ld_target_Y > 1e-16L) {
|
||||
if (total_mass_He <= 1e-19L) {
|
||||
throw std::runtime_error("Cannot rescale Helium to " + std::to_string((double)ld_target_Y) +
|
||||
" because input has no Helium.");
|
||||
}
|
||||
scale_He = (ld_target_Y * total_mass_current) / total_mass_He;
|
||||
}
|
||||
|
||||
if (ld_target_Z > 1e-16L) {
|
||||
if (total_mass_Z <= 1e-19L) {
|
||||
throw std::runtime_error("Cannot rescale Metals to " + std::to_string(target_Z) +
|
||||
" because input has no Metals.");
|
||||
}
|
||||
scale_Z = (ld_target_Z * total_mass_current) / total_mass_Z;
|
||||
}
|
||||
|
||||
// 4. Apply Scaling and Construct New Vectors
|
||||
std::vector<fourdst::atomic::Species> new_species;
|
||||
std::vector<double> new_abundances;
|
||||
new_species.reserve(comp.size());
|
||||
new_abundances.reserve(comp.size());
|
||||
|
||||
for (const auto& [spec, abundance] : comp) {
|
||||
new_species.push_back(spec);
|
||||
|
||||
long double factor = 0.0L;
|
||||
int z = spec.z();
|
||||
|
||||
if (z == 1) {
|
||||
factor = scale_H;
|
||||
} else if (z == 2) {
|
||||
factor = scale_He;
|
||||
} else {
|
||||
factor = scale_Z;
|
||||
}
|
||||
|
||||
// Calculate new abundance in long double then cast back
|
||||
long double new_val_ld = static_cast<long double>(abundance) * factor;
|
||||
new_abundances.push_back(static_cast<double>(new_val_ld));
|
||||
}
|
||||
|
||||
return Composition(new_species, new_abundances);
|
||||
}
|
||||
static std::vector<IntermediateResult> g_callbackHistory;
|
||||
|
||||
gridfire::NetIn init(const double temp, const double rho, const double tMax) {
|
||||
std::setlocale(LC_ALL, "");
|
||||
g_previousHandler = std::set_terminate(quill_terminate_handler);
|
||||
quill::Logger* logger = fourdst::logging::LogManager::getInstance().getLogger("log");
|
||||
logger->set_log_level(quill::LogLevel::Info);
|
||||
logger->set_log_level(quill::LogLevel::TraceL2);
|
||||
|
||||
using namespace gridfire;
|
||||
const std::vector<double> X = {0.7081145999999999, 2.94e-5, 0.276, 0.003, 0.0011, 9.62e-3, 1.62e-3, 5.16e-4};
|
||||
@@ -255,9 +153,7 @@ void log_results(const gridfire::NetOut& netOut, const gridfire::NetIn& netIn) {
|
||||
|
||||
|
||||
void record_abundance_history_callback(const gridfire::solver::PointSolverTimestepContext& ctx) {
|
||||
s_wrote_abundance_history = true;
|
||||
const auto& engine = ctx.engine;
|
||||
// std::unordered_map<std::string, std::pair<double, double>> abundances;
|
||||
std::vector<double> Y;
|
||||
for (const auto& species : engine.getNetworkSpecies(ctx.state_ctx)) {
|
||||
const size_t sid = engine.getSpeciesIndex(ctx.state_ctx, species);
|
||||
@@ -265,80 +161,84 @@ void record_abundance_history_callback(const gridfire::solver::PointSolverTimest
|
||||
Y.push_back(y > 0.0 ? y : 0.0); // Regularize tiny negative abundances to zero
|
||||
}
|
||||
|
||||
fourdst::composition::Composition comp(engine.getNetworkSpecies(ctx.state_ctx), Y);
|
||||
const fourdst::composition::Composition comp(engine.getNetworkSpecies(ctx.state_ctx), Y);
|
||||
IntermediateResult stepResult;
|
||||
stepResult.comp = comp;
|
||||
stepResult.time = ctx.t;
|
||||
stepResult.current_energy = ctx.current_total_energy;
|
||||
stepResult.current_neutrino_loss_rate = ctx.current_neutrino_energy_loss_rate;
|
||||
stepResult.reactions = engine.getNetworkReactions(ctx.state_ctx);
|
||||
|
||||
|
||||
std::unordered_map<std::string, std::pair<double, double>> abundances;
|
||||
for (const auto& sp : comp | std::views::keys) {
|
||||
abundances.emplace(std::string(sp.name()), std::make_pair(sp.mass(), comp.getMolarAbundance(sp)));
|
||||
for (const auto& reactionPtr : stepResult.reactions) {
|
||||
double flow = engine.calculateMolarReactionFlow(ctx.state_ctx, *reactionPtr, comp, ctx.T9, ctx.rho);
|
||||
stepResult.reaction_flows.push_back(flow);
|
||||
}
|
||||
g_callbackHistory.emplace_back(ctx.t, abundances);
|
||||
|
||||
stepResult.inactive_reactions = engine.getInactiveNetworkReactions(ctx.state_ctx);
|
||||
for (const auto& reactionPtr : stepResult.inactive_reactions) {
|
||||
double flow = engine.getInactiveReactionMolarReactionFlow(ctx.state_ctx, *reactionPtr, comp, ctx.T9, ctx.rho);
|
||||
stepResult.inactive_reaction_flows.push_back(flow);
|
||||
}
|
||||
g_callbackHistory.push_back(stepResult);
|
||||
}
|
||||
|
||||
|
||||
void save_callback_data(const std::string_view filename) {
|
||||
std::set<std::string> unique_species;
|
||||
for (const auto &abundances: g_callbackHistory | std::views::values) {
|
||||
for (const auto &species_name: abundances | std::views::keys) {
|
||||
unique_species.insert(species_name);
|
||||
}
|
||||
}
|
||||
std::ofstream csvFile(filename.data(), std::ios::out);
|
||||
csvFile << "t,";
|
||||
|
||||
size_t i = 0;
|
||||
for (const auto& species_name : unique_species) {
|
||||
csvFile << species_name;
|
||||
if (i < unique_species.size() - 1) {
|
||||
csvFile << ",";
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
csvFile << "\n";
|
||||
|
||||
for (const auto& [time, data] : g_callbackHistory) {
|
||||
csvFile << time << ",";
|
||||
size_t j = 0;
|
||||
for (const auto& species_name : unique_species) {
|
||||
if (!data.contains(species_name)) {
|
||||
csvFile << "0.0";
|
||||
} else {
|
||||
csvFile << data.at(species_name).second;
|
||||
}
|
||||
if (j < unique_species.size() - 1) {
|
||||
csvFile << ",";
|
||||
}
|
||||
++j;
|
||||
}
|
||||
csvFile << "\n";
|
||||
}
|
||||
|
||||
csvFile.close();
|
||||
}
|
||||
|
||||
void log_callback_data(const double temp) {
|
||||
if (s_wrote_abundance_history) {
|
||||
std::cout << "Saving abundance history to abundance_history.csv" << std::endl;
|
||||
save_callback_data("abundance_history_" + std::to_string(temp) + ".csv");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void quill_terminate_handler()
|
||||
{
|
||||
log_callback_data(1.5e7);
|
||||
quill::Backend::stop();
|
||||
if (g_previousHandler)
|
||||
g_previousHandler();
|
||||
else
|
||||
std::abort();
|
||||
}
|
||||
|
||||
void callback_main(const gridfire::solver::PointSolverTimestepContext& ctx) {
|
||||
record_abundance_history_callback(ctx);
|
||||
}
|
||||
|
||||
void save_callback(const std::string& filename) {
|
||||
// Save to JSON
|
||||
nlohmann::json j;
|
||||
for (const auto& record : g_callbackHistory) {
|
||||
nlohmann::json entry;
|
||||
entry["time"] = record.time;
|
||||
entry["current_energy"] = record.current_energy;
|
||||
entry["current_neutrino_loss_rate"] = record.current_neutrino_loss_rate;
|
||||
// make a sub-json for composition
|
||||
nlohmann::json comp_json;
|
||||
for (const auto& [species, abundance] : record.comp) {
|
||||
comp_json[species.name()] = abundance;
|
||||
}
|
||||
entry["composition"] = comp_json;
|
||||
entry["reactions"] = nlohmann::json::array();
|
||||
for (const auto& [reaction, flow] : std::views::zip(record.reactions, record.reaction_flows)) {
|
||||
nlohmann::json reaction_info;
|
||||
reaction_info["id"] = reaction->id();
|
||||
reaction_info["flow"] = flow;
|
||||
reaction_info["species"] = nlohmann::json::array();
|
||||
reaction_info["Q"] = reaction->qValue();
|
||||
for (const auto& sp : reaction->all_species()) {
|
||||
nlohmann::json species_info;
|
||||
species_info["name"] = sp.name();
|
||||
species_info["stoichiometry"] = reaction->stoichiometry(sp);
|
||||
reaction_info["species"].push_back(species_info);
|
||||
}
|
||||
entry["reactions"].push_back(reaction_info);
|
||||
}
|
||||
|
||||
entry["inactive_reactions"] = nlohmann::json::array();
|
||||
for (const auto& [reaction, flow] : std::views::zip(record.inactive_reactions, record.inactive_reaction_flows)) {
|
||||
nlohmann::json reaction_info;
|
||||
reaction_info["id"] = reaction->id();
|
||||
reaction_info["flow"] = flow;
|
||||
reaction_info["species"] = nlohmann::json::array();
|
||||
reaction_info["Q"] = reaction->qValue();
|
||||
for (const auto& sp : reaction->all_species()) {
|
||||
nlohmann::json species_info;
|
||||
species_info["name"] = sp.name();
|
||||
species_info["stoichiometry"] = reaction->stoichiometry(sp);
|
||||
reaction_info["species"].push_back(species_info);
|
||||
}
|
||||
entry["inactive_reactions"].push_back(reaction_info);
|
||||
}
|
||||
j.push_back(entry);
|
||||
}
|
||||
std::ofstream ofs(filename);
|
||||
ofs << j.dump(4);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
GF_PAR_INIT();
|
||||
using namespace gridfire;
|
||||
@@ -346,12 +246,18 @@ int main(int argc, char** argv) {
|
||||
double temp = 1.5e7;
|
||||
double rho = 1.5e2;
|
||||
double tMax = 3.1536e+16;
|
||||
bool save_intermediate_results = false;
|
||||
bool display_trigger = false;
|
||||
std::string output_filename = "abundance_history.json";
|
||||
|
||||
|
||||
CLI::App app("GridFire Quick CLI Test");
|
||||
app.add_option("--temp", temp, "Initial Temperature")->default_val(std::format("{:5.2E}", temp));
|
||||
app.add_option("--rho", rho, "Initial Density")->default_val(std::format("{:5.2E}", rho));
|
||||
app.add_option("--tmax", tMax, "Maximum Time")->default_val(std::format("{:5.2E}", tMax));
|
||||
app.add_option("--save_intermediate_results", save_intermediate_results, "Save Intermediate Results")->default_val("false");
|
||||
app.add_option("--output", output_filename, "Output filename for intermediate results")->default_val("abundance_history.json");
|
||||
app.add_option("--display_trigger_explanations", display_trigger, "Display trigger explanations during run")->default_val("false");
|
||||
|
||||
CLI11_PARSE(app, argc, argv);
|
||||
NetIn netIn = init(temp, rho, tMax);
|
||||
@@ -361,7 +267,14 @@ int main(int argc, char** argv) {
|
||||
|
||||
solver::PointSolverContext solver_context(*ctx_template);
|
||||
solver::PointSolver solver(engine);
|
||||
if (save_intermediate_results) {
|
||||
solver_context.callback = solver::TimestepCallback(callback_main);
|
||||
}
|
||||
|
||||
NetOut result = solver.evaluate(solver_context, netIn);
|
||||
NetOut result = solver.evaluate(solver_context, netIn, display_trigger);
|
||||
log_results(result, netIn);
|
||||
|
||||
if (save_intermediate_results) {
|
||||
save_callback(output_filename);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user