use crate::SimpleReactorsBVP::SimpleReactorBVP::SimpleReactorTask;
use crate::SimpleReactorsBVP::task_parser_reactor_BVP::{
SIMPLE_BVP_TEMPLATE, validate_reactor_bvp_task_map,
};
use crate::SimpleReactorsBVP::task_value_conversion::{UsizeConversionError, try_value_as_usize};
use crate::cli::reactor_help::REACTOR_ENG_HELPER;
use crate::gui::bvp_gui_config::{
AotToolchainRequest, BvpGuiConfig, BvpGuiMigrationReport, BvpSolverFamily,
GuiAotCodegenBackend, GuiExecutionBackend, aot_toolchain_request,
normalize_bvp_solver_backend_section, set_bvp_solver_family, validate_aot_toolchain_fields,
};
pub use crate::gui::document_lifecycle::{
DocumentLifecycleState, GuiFileOperationKind, GuiFileOperationResult,
};
use crate::gui::gui_plot::PlotWindow;
use RustedSciThe::command_interpreter::task_parser::{DocumentMap, DocumentParser, Value};
use eframe::egui;
use log::{info, warn};
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, mpsc};
use tabled::{Table, Tabled};
#[path = "combustion_execution.rs"]
mod combustion_execution;
#[path = "combustion_lifecycle.rs"]
mod combustion_lifecycle;
#[derive(Default, Debug, Clone, PartialEq)]
pub enum ProblemsEnum {
#[default]
None,
BVPSimple,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) enum BvpEditorTab {
#[default]
Physics,
Solver,
}
impl ProblemsEnum {
pub fn get_problem(&self) -> Option<&str> {
match self {
ProblemsEnum::None => None,
ProblemsEnum::BVPSimple => Some(SIMPLE_BVP_TEMPLATE),
}
}
}
impl std::fmt::Display for ProblemsEnum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
ProblemsEnum::None => "None",
ProblemsEnum::BVPSimple => "BVP Simple",
};
write!(f, "{}", s)
}
}
fn render_value(
ui: &mut egui::Ui,
value: &mut Value,
field_name: &str,
label_id: egui::Id,
) -> bool {
match value {
Value::String(s) => {
let response = ui.text_edit_singleline(s);
let _ = response.clone().labelled_by(label_id);
if response.changed() {
info!("Field '{}' changed to: {}", field_name, s);
}
response.hovered()
}
Value::Float(f) => {
let response = ui.add(egui::DragValue::new(f).speed(0.1).custom_formatter(|n, _| {
if n.abs() < 1e-3 && n != 0.0 {
format!("{:.2e}", n)
} else if n.abs() >= 100.0 {
format!("{:.1}", n)
} else {
format!("{:.6}", n)
}
}));
let _ = response.clone().labelled_by(label_id);
if response.changed() {
info!("Field '{}' changed to: {}", field_name, f);
}
response.hovered()
}
Value::Integer(i) => {
let response = ui.add(egui::DragValue::new(i).speed(1));
let _ = response.clone().labelled_by(label_id);
if response.changed() {
info!("Field '{}' changed to: {}", field_name, i);
}
response.hovered()
}
Value::Usize(u) => {
let response = ui.add(egui::DragValue::new(u).speed(1));
let _ = response.clone().labelled_by(label_id);
if response.changed() {
info!("Field '{}' changed to: {}", field_name, u);
}
response.hovered()
}
Value::Vector(vec) => {
let mut hovered = false;
for (i, v) in vec.iter_mut().enumerate() {
let response =
ui.add(egui::DragValue::new(v).speed(0.1).custom_formatter(|n, _| {
if n.abs() < 1e-3 && n != 0.0 {
format!("{:.2e}", n)
} else if n.abs() >= 100.0 {
format!("{:.1}", n)
} else {
format!("{:.6}", n)
}
}));
let _ = response.clone().labelled_by(label_id);
hovered |= response.hovered();
if response.changed() {
info!("Field '{}[{}]' changed to: {}", field_name, i, v);
}
}
hovered
}
Value::Boolean(b) => {
let response = ui.checkbox(b, "");
let _ = response.clone().labelled_by(label_id);
if response.changed() {
info!("Field '{}' changed to: {}", field_name, b);
}
response.hovered()
}
Value::Optional(opt) => {
let mut hovered = false;
ui.horizontal(|ui| {
if let Some(inner) = opt {
ui.label("Some:");
hovered = render_value(ui, inner, field_name, label_id);
} else {
ui.label("None");
}
});
hovered
}
}
}
#[derive(Clone, Copy)]
struct SectionRenderOptions {
framed: bool,
allow_add_field: bool,
hidden_fields: &'static [&'static str],
add_name_label: &'static str,
add_value_label: &'static str,
add_button_label: &'static str,
}
impl SectionRenderOptions {
const fn framed_read_only(hidden_fields: &'static [&'static str]) -> Self {
Self {
framed: true,
allow_add_field: false,
hidden_fields,
add_name_label: "New field:",
add_value_label: "Value:",
add_button_label: "Add Field",
}
}
const fn element_editor() -> Self {
Self {
framed: true,
allow_add_field: true,
hidden_fields: &[],
add_name_label: "Element:",
add_value_label: "Atom count:",
add_button_label: "Add element",
}
}
const fn compatibility(framed: bool) -> Self {
Self {
framed,
allow_add_field: true,
hidden_fields: &[],
add_name_label: "New field:",
add_value_label: "Value:",
add_button_label: "Add Field",
}
}
}
fn render_section(
ui: &mut egui::Ui,
name: &str,
section: &mut HashMap<String, Option<Vec<Value>>>,
new_field_name: &mut String,
new_field_value: &mut String,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
options: SectionRenderOptions,
) -> (bool, bool, Vec<String>) {
let mut add_field = false;
let mut delete_section = false;
let mut requested_field_deletions = Vec::new();
ui.push_id(name, |ui| {
ui.horizontal(|ui| {
let mut render_fields = |ui: &mut egui::Ui| {
let mut fields_to_delete = Vec::new();
let mut field_names = sorted_section_field_names(section);
for field_name in field_names.drain(..) {
if options.hidden_fields.contains(&field_name.as_str()) {
continue;
}
let Some(maybe_values) = section.get_mut(&field_name) else {
continue;
};
ui.push_id((name, field_name.as_str()), |ui| {
ui.horizontal(|ui| {
let field_label = ui.label(&field_name);
let mut field_control_hovered = false;
if field_label.hovered() {
if let Some(map) = help_map {
let help_key = format!("{}.{}", name, field_name);
if let Some((_, help_text)) =
map.iter().find(|(key, _)| *key == help_key)
{
*current_help = help_text.to_string();
}
}
}
if let Some(values) = maybe_values {
if values.len() > 1
&& values.iter().all(|v| matches!(v, Value::String(_)))
{
let mut combined_text = values
.iter()
.filter_map(|v| {
if let Value::String(s) = v {
Some(s.as_str())
} else {
None
}
})
.collect::<Vec<_>>()
.join(", ");
let response = ui.text_edit_singleline(&mut combined_text);
let _ = response.clone().labelled_by(field_label.id);
field_control_hovered = response.hovered();
if response.changed() {
let new_substances: Vec<Value> = combined_text
.split(',')
.map(|s| Value::String(s.trim().to_string()))
.filter(|v| {
if let Value::String(s) = v {
!s.is_empty()
} else {
true
}
})
.collect();
*values = new_substances;
info!(
"Field '{}' changed to: {}",
field_name, combined_text
);
}
} else {
for v in values.iter_mut() {
field_control_hovered |=
render_value(ui, v, &field_name, field_label.id);
}
}
} else {
ui.label("None");
}
if field_control_hovered {
if let Some(map) = help_map {
let help_key = format!("{}.{}", name, field_name);
if let Some((_, help_text)) =
map.iter().find(|(key, _)| *key == help_key)
{
*current_help = help_text.to_string();
}
}
}
if ui.button("❌").clicked() {
fields_to_delete.push(field_name.clone());
}
});
});
}
requested_field_deletions.extend(fields_to_delete);
if options.allow_add_field {
ui.separator();
ui.horizontal(|ui| {
let name_label = ui.label(options.add_name_label);
let name_response = ui.text_edit_singleline(new_field_name);
let _ = name_response.labelled_by(name_label.id);
let value_label = ui.label(options.add_value_label);
let value_response = ui.text_edit_singleline(new_field_value);
let _ = value_response.labelled_by(value_label.id);
if ui.button(options.add_button_label).clicked() {
add_field = true;
}
});
}
};
let section_response = if options.framed {
Some(
egui::Frame::group(ui.style())
.show(ui, |ui| {
let heading = ui.heading(name);
render_fields(ui);
heading
})
.inner,
)
} else {
let response = egui::CollapsingHeader::new(name)
.default_open(false)
.show(ui, |ui| render_fields(ui));
Some(response.header_response)
};
if section_response.is_some_and(|response| response.hovered()) {
if let Some(map) = help_map {
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == name) {
*current_help = help_text.to_string();
}
}
}
if ui.button("❌").clicked() {
delete_section = true;
}
});
});
(add_field, delete_section, requested_field_deletions)
}
pub(crate) fn sorted_section_field_names(
section: &HashMap<String, Option<Vec<Value>>>,
) -> Vec<String> {
let mut field_names = section.keys().cloned().collect::<Vec<_>>();
field_names.sort();
field_names
}
pub(crate) fn sorted_document_section_names(document: &DocumentMap) -> Vec<String> {
let mut section_names = document.keys().cloned().collect::<Vec<_>>();
section_names.sort();
section_names
}
const BVP_GRID_REFINEMENT_METHODS: &[&str] =
&["pearson", "grcarsmooke", "twopnt", "easy", "doubleoints"];
fn canonical_grid_refinement_method_name(raw: &str) -> Option<&'static str> {
let normalized = raw.trim().to_ascii_lowercase().replace(['-', ' '], "_");
match normalized.as_str() {
"pearson" => Some("pearson"),
"grcarsmooke" | "grcar_smooke" => Some("grcarsmooke"),
"twopnt" | "two_point" | "two_points" => Some("twopnt"),
"easy" => Some("easy"),
"doubleoints" | "double_points" | "doublepoints" => Some("doubleoints"),
_ => None,
}
}
fn grid_refinement_method_label(method: &str) -> &'static str {
match method {
"pearson" => "Pearson",
"grcarsmooke" => "Grcar-Smooke",
"twopnt" => "Two-point",
"easy" => "Easy",
"doubleoints" => "Double points",
_ => "Pearson",
}
}
fn default_grid_refinement_params(method: &str) -> Vec<f64> {
match method {
"pearson" => vec![0.1, 1.5],
"grcarsmooke" => vec![0.05, 0.05, 1.25],
"twopnt" => vec![0.05, 0.05, 1.25],
"easy" => vec![0.05],
"doubleoints" => Vec::new(),
_ => vec![0.1, 1.5],
}
}
fn grid_refinement_slot_to_params(slot: Option<&Vec<Value>>) -> Option<Vec<f64>> {
let values = slot?;
if let Some(vector) = values.first().and_then(|value| value.as_vector()) {
return Some(vector.clone());
}
let mut params = Vec::with_capacity(values.len());
for value in values {
params.push(value.as_float()?);
}
Some(params)
}
fn normalize_grid_refinement_section(section: &mut HashMap<String, Option<Vec<Value>>>) -> String {
let mut selected_method = None;
let mut selected_params = None;
for method in BVP_GRID_REFINEMENT_METHODS {
if let Some((key, slot)) = section
.iter()
.find(|(key, _)| canonical_grid_refinement_method_name(key) == Some(*method))
{
selected_method = Some(*method);
selected_params = grid_refinement_slot_to_params(slot.as_ref());
if key.as_str() != *method {
info!("Grid refinement alias '{}' normalized to '{}'", key, method);
}
break;
}
}
let method = selected_method.unwrap_or("pearson");
let mut params = default_grid_refinement_params(method);
if let Some(existing_params) = selected_params {
for (target, source) in params.iter_mut().zip(existing_params.into_iter()) {
if source.is_finite() {
*target = source;
}
}
}
section.clear();
section.insert(method.to_string(), Some(vec![Value::Vector(params)]));
method.to_string()
}
#[allow(dead_code)]
fn value_is_explicit_none(value: &Value) -> bool {
matches!(value, Value::Optional(None))
|| matches!(value, Value::String(value) if value.trim().eq_ignore_ascii_case("none"))
}
#[allow(dead_code)]
fn take_legacy_adaptive_marker(document: &mut DocumentMap) -> Option<bool> {
let strategy_params = document.get_mut("strategy_params")?;
let values = strategy_params.remove("adaptive")??;
let value = values.first()?;
Some(!value_is_explicit_none(value))
}
fn set_bvp_adaptive_grid_enabled(document: &mut DocumentMap, enabled: bool) {
if let Some(strategy_params) = document.get_mut("strategy_params") {
strategy_params.remove("adaptive");
}
if !enabled {
document.remove("adaptive_strategy");
document.remove("grid_refinement");
return;
}
let adaptive_strategy = ensure_section_mut(document, "adaptive_strategy");
adaptive_strategy.insert("version".to_string(), Some(vec![Value::Usize(1)]));
let _ = ensure_field_slot(adaptive_strategy, "max_refinements", Value::Usize(3));
let _ = normalize_usize_field(adaptive_strategy, "max_refinements");
let grid_refinement = ensure_section_mut(document, "grid_refinement");
normalize_grid_refinement_section(grid_refinement);
}
#[allow(dead_code)]
fn normalize_bvp_adaptive_grid_settings(document: &mut DocumentMap) {
let compatibility_marker = take_legacy_adaptive_marker(document);
let has_native_payload = document
.get("adaptive_strategy")
.is_some_and(|section| !section.is_empty())
|| document
.get("grid_refinement")
.is_some_and(|section| !section.is_empty());
let enabled = compatibility_marker.unwrap_or(has_native_payload);
set_bvp_adaptive_grid_enabled(document, enabled);
}
fn render_bvp_adaptive_grid_panel(
ui: &mut egui::Ui,
document: &mut DocumentMap,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let mut enabled = document.contains_key("adaptive_strategy");
ui.group(|ui| {
ui.vertical(|ui| {
let response = ui.checkbox(&mut enabled, "Adaptive grid refinement");
if response.hovered() {
if let Some(map) = help_map {
if let Some((_, help_text)) =
map.iter().find(|(key, _)| *key == "adaptive_strategy")
{
*current_help = help_text.to_string();
}
}
}
if response.changed() {
set_bvp_adaptive_grid_enabled(document, enabled);
info!("Adaptive grid refinement enabled: {}", enabled);
}
if enabled {
ui.label("Adaptive strategy version: 1");
egui::Grid::new("bvp_adaptive_strategy_grid")
.num_columns(2)
.striped(true)
.show(ui, |ui| {
let adaptive_strategy = ensure_section_mut(document, "adaptive_strategy");
let current_result = adaptive_strategy
.get("max_refinements")
.and_then(|slot| slot.as_ref())
.and_then(|values| values.first())
.map(try_value_as_usize)
.unwrap_or(Ok(3));
let label = ui.label("Maximum grid refinements");
let help_text = help_map.and_then(|map| {
map.iter()
.find(|(key, _)| *key == "adaptive_strategy.max_refinements")
.map(|(_, help_text)| *help_text)
});
if label.hovered() {
if let Some(help_text) = help_text {
*current_help = help_text.to_string();
}
}
match current_result {
Ok(mut max_refinements) => {
let response =
ui.add(egui::DragValue::new(&mut max_refinements).speed(1));
let _ = response.clone().labelled_by(label.id);
if response.hovered() {
if let Some(help_text) = help_text {
*current_help = help_text.to_string();
}
}
if response.changed() {
adaptive_strategy.insert(
"max_refinements".to_string(),
Some(vec![Value::Usize(max_refinements)]),
);
info!(
"Maximum grid refinements changed to: {}",
max_refinements
);
}
}
Err(error) => {
ui.horizontal(|ui| {
ui.colored_label(egui::Color32::RED, error.to_string());
if ui.button("Reset to 3").clicked() {
adaptive_strategy.insert(
"max_refinements".to_string(),
Some(vec![Value::Usize(3)]),
);
}
});
}
}
ui.end_row();
});
let (_, delete_requested) = render_grid_refinement_section(
ui,
ensure_section_mut(document, "grid_refinement"),
help_map,
current_help,
);
if delete_requested {
enabled = false;
set_bvp_adaptive_grid_enabled(document, false);
}
}
});
});
}
fn render_grid_refinement_section(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) -> (bool, bool) {
let mut delete_section = false;
let current_method = normalize_grid_refinement_section(section);
ui.horizontal(|ui| {
let section_header = egui::CollapsingHeader::new("grid_refinement")
.default_open(true)
.show(ui, |ui| {
egui::Grid::new("bvp_grid_refinement_strategy_grid")
.num_columns(2)
.striped(true)
.show(ui, |ui| {
let label_response = ui.label("Grid refinement strategy");
if label_response.hovered() {
if let Some(map) = help_map {
if let Some((_, help_text)) =
map.iter().find(|(key, _)| *key == "grid_refinement")
{
*current_help = help_text.to_string();
}
}
}
let mut selected_method = current_method.clone();
let method_combo = egui::ComboBox::from_id_salt("grid_refinement.method")
.selected_text(grid_refinement_method_label(&selected_method))
.show_ui(ui, |ui| {
for method in BVP_GRID_REFINEMENT_METHODS {
ui.selectable_value(
&mut selected_method,
(*method).to_string(),
grid_refinement_method_label(method),
);
}
});
let _ = method_combo.response.clone().labelled_by(label_response.id);
if method_combo.response.hovered() {
if let Some(map) = help_map {
if let Some((_, help_text)) =
map.iter().find(|(key, _)| *key == "grid_refinement")
{
*current_help = help_text.to_string();
}
}
}
ui.end_row();
if selected_method != current_method {
section.clear();
section.insert(
selected_method.clone(),
Some(vec![Value::Vector(default_grid_refinement_params(
&selected_method,
))]),
);
info!("Grid refinement strategy changed to: {}", selected_method);
}
let params = section
.get_mut(&selected_method)
.and_then(|slot| slot.as_mut())
.and_then(|values| values.first_mut())
.and_then(|value| match value {
Value::Vector(params) => Some(params),
_ => None,
})
.expect("grid refinement section should contain a vector payload");
let params_label = ui.label("Parameters");
if params.is_empty() {
ui.label("No parameters");
} else {
ui.horizontal(|ui| {
for (index, value) in params.iter_mut().enumerate() {
let response = ui.add(
egui::DragValue::new(value)
.speed(0.01)
.prefix(format!("p{}=", index + 1)),
);
let _ = response.clone().labelled_by(params_label.id);
if response.changed() {
info!(
"Grid refinement parameter {} changed to: {}",
index + 1,
value
);
}
}
});
}
ui.end_row();
});
});
if section_header.header_response.hovered() {
if let Some(map) = help_map {
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == "grid_refinement")
{
*current_help = help_text.to_string();
}
}
}
if ui.button("Delete").clicked() {
delete_section = true;
}
});
(false, delete_section)
}
#[allow(dead_code)]
fn current_grid_refinement_state(
section: &HashMap<String, Option<Vec<Value>>>,
) -> (String, Vec<f64>) {
for method in BVP_GRID_REFINEMENT_METHODS {
if let Some((_key, slot)) = section
.iter()
.find(|(key, _)| canonical_grid_refinement_method_name(key) == Some(*method))
{
let params = grid_refinement_slot_to_params(slot.as_ref())
.unwrap_or_else(|| default_grid_refinement_params(method));
return ((*method).to_string(), params);
}
}
let method = "pearson".to_string();
(method.clone(), default_grid_refinement_params(&method))
}
fn value_to_document_string(value: &Value) -> String {
match value {
Value::String(value) if value.is_empty() => "Some()".to_string(),
Value::String(value) => value.clone(),
Value::Float(value) => {
let rendered = value.to_string();
if rendered.contains('.') || rendered.contains('e') || rendered.contains('E') {
rendered
} else if !value.is_finite() {
rendered
} else {
format!("{rendered}.0")
}
}
Value::Integer(value) => value.to_string(),
Value::Usize(value) => value.to_string(),
Value::Boolean(value) => value.to_string(),
Value::Vector(values) => {
let values = values
.iter()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(", ");
format!("[{}]", values)
}
Value::Optional(Some(inner)) => format!("Some({})", value_to_document_string(inner)),
Value::Optional(None) => "None".to_string(),
}
}
fn values_to_document_string(values: &[Value]) -> String {
values
.iter()
.map(value_to_document_string)
.collect::<Vec<_>>()
.join(", ")
}
fn ensure_section_mut<'a>(
document: &'a mut DocumentMap,
section_name: &str,
) -> &'a mut HashMap<String, Option<Vec<Value>>> {
document
.entry(section_name.to_string())
.or_insert_with(HashMap::new)
}
pub(crate) fn insert_field_if_absent(
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: String,
value: Value,
) -> Result<(), String> {
match section.entry(field_name.clone()) {
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(Some(vec![value]));
Ok(())
}
std::collections::hash_map::Entry::Occupied(_) => Err(format!(
"Field `{}` already exists; existing data was preserved",
field_name
)),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DocumentDeleteRequest {
Section { section: String },
Field { section: String, field: String },
Species { species: String },
}
impl DocumentDeleteRequest {
fn description(&self) -> String {
match self {
Self::Section { section } => format!("section `{}`", section),
Self::Field { section, field } => {
format!("field `{}.{}`", section, field)
}
Self::Species { species } => {
format!("substance `{}` and its dependent data", species)
}
}
}
}
fn reaction_references_species(equation: &str, species: &str) -> bool {
equation
.split("=>")
.flat_map(|side| side.split('+'))
.any(|term| {
let term = term.trim();
if term == species {
return true;
}
let coefficient_end = term
.char_indices()
.take_while(|(_, ch)| ch.is_ascii_digit() || *ch == '.')
.map(|(index, ch)| index + ch.len_utf8())
.last();
coefficient_end.is_some_and(|end| term[end..].trim() == species)
})
}
pub(crate) fn add_bvp_species(document: &mut DocumentMap, species: &str) -> Result<(), String> {
let species = species.trim();
if species.is_empty() || species.contains(',') {
return Err("Substance name must be non-empty and cannot contain a comma.".to_string());
}
let process_conditions = document
.get_mut("process_conditions")
.ok_or_else(|| "Missing process_conditions section.".to_string())?;
let substances = process_conditions
.entry("substances".to_string())
.or_insert_with(|| Some(Vec::new()))
.get_or_insert_with(Vec::new);
if substances
.iter()
.filter_map(Value::as_string)
.any(|existing| existing == species)
{
return Err(format!("Substance `{species}` already exists."));
}
substances.push(Value::String(species.to_string()));
let boundary_conditions = document
.entry("boundary_condition".to_string())
.or_default();
boundary_conditions.insert(species.to_string(), Some(vec![Value::Float(0.0)]));
let diffusion = document
.entry("diffusion_coefficients".to_string())
.or_default();
let default_diffusion = diffusion
.values()
.filter_map(|values| values.as_ref()?.first()?.as_float())
.find(|value| value.is_finite() && *value > 0.0)
.unwrap_or(9.296e-6);
diffusion.insert(
species.to_string(),
Some(vec![Value::Float(default_diffusion)]),
);
document.entry(species.to_string()).or_default();
Ok(())
}
pub(crate) fn add_bvp_reaction(document: &mut DocumentMap, equation: &str) -> Result<(), String> {
let equation = equation.trim();
if equation.is_empty() {
return Err("Reaction equation cannot be empty.".to_string());
}
let reactions = document.entry("reactions".to_string()).or_default();
if reactions.contains_key(equation) {
return Err(format!("Reaction `{equation}` already exists."));
}
reactions.insert(
equation.to_string(),
Some(vec![Value::Vector(vec![1.0, 0.0, 0.0, 0.0])]),
);
Ok(())
}
pub(crate) fn apply_document_deletion(
document: &mut DocumentMap,
request: &DocumentDeleteRequest,
) -> bool {
match request {
DocumentDeleteRequest::Section { section } => document.remove(section).is_some(),
DocumentDeleteRequest::Field { section, field } => document
.get_mut(section)
.is_some_and(|section_map| section_map.remove(field).is_some()),
DocumentDeleteRequest::Species { species } => {
let mut removed = false;
if let Some(values) = document
.get_mut("process_conditions")
.and_then(|section| section.get_mut("substances"))
.and_then(Option::as_mut)
{
let before = values.len();
values.retain(|value| value.as_string().is_none_or(|name| name != species));
removed |= values.len() != before;
}
for section_name in ["boundary_condition", "diffusion_coefficients"] {
removed |= document
.get_mut(section_name)
.is_some_and(|section| section.remove(species).is_some());
}
removed |= document.remove(species).is_some();
if let Some(reactions) = document.get_mut("reactions") {
let before = reactions.len();
reactions.retain(|equation, _| !reaction_references_species(equation, species));
removed |= reactions.len() != before;
}
removed
}
}
}
fn ensure_field_slot<'a>(
section: &'a mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
default_value: Value,
) -> &'a mut Option<Vec<Value>> {
let entry = section
.entry(field_name.to_string())
.or_insert_with(|| Some(vec![default_value.clone()]));
if entry.is_none() {
*entry = Some(vec![default_value.clone()]);
}
if entry.as_ref().is_some_and(|values| values.is_empty()) {
*entry = Some(vec![default_value]);
}
entry
}
fn ensure_bvp_solver_backend_defaults(document: &mut DocumentMap) {
let family = BvpGuiConfig::from_document(document).0.core.family;
let section = ensure_section_mut(document, "solver_settings");
set_string_field(section, "solver_family", family.as_document_value());
let common_defaults = [
("telemetry", Value::String("off".to_string())),
(
"loglevel",
Value::Optional(Some(Box::new(Value::String("off".to_string())))),
),
];
for (field_name, value) in common_defaults {
let _ = ensure_field_slot(section, field_name, value);
}
match family {
BvpSolverFamily::Damped => {
let defaults = [
("scheme", Value::String("forward".to_string())),
("strategy", Value::String("Damped".to_string())),
("linear_sys_method", Value::Optional(None)),
(
"generated_backend",
Value::String("banded_lambdify".to_string()),
),
("symbolic_backend", Value::String("AtomView".to_string())),
("banded_linear_solver", Value::String("auto".to_string())),
("refinement_steps", Value::Usize(5)),
("abs_tolerance", Value::Float(1e-7)),
("max_iterations", Value::Usize(100)),
];
for (field_name, value) in defaults {
let _ = ensure_field_slot(section, field_name, value);
}
let _ = normalize_matrix_backend_aliases(section);
let _ = normalize_usize_field(section, "max_iterations");
let _ = normalize_usize_field(section, "refinement_steps");
normalize_bvp_solver_backend_section(section);
}
BvpSolverFamily::Frozen => {
let defaults = [
("scheme", Value::String("forward".to_string())),
("strategy", Value::String("Frozen".to_string())),
("linear_sys_method", Value::Optional(None)),
(
"generated_backend",
Value::String("banded_lambdify".to_string()),
),
("symbolic_backend", Value::String("AtomView".to_string())),
("tolerance", Value::Float(1e-6)),
("max_iterations", Value::Usize(50)),
];
for (field_name, value) in defaults {
let _ = ensure_field_slot(section, field_name, value);
}
let _ = normalize_matrix_backend_aliases(section);
let _ = normalize_usize_field(section, "max_iterations");
normalize_bvp_solver_backend_section(section);
}
BvpSolverFamily::Sci => {
let defaults = [
("execution", Value::String("lambdify".to_string())),
("assembly", Value::String("atom_view_native".to_string())),
("matrix_layout", Value::String("banded_auto".to_string())),
("tolerance", Value::Float(1e-4)),
("max_nodes", Value::Usize(256)),
];
for (field_name, value) in defaults {
let _ = ensure_field_slot(section, field_name, value);
}
let _ = normalize_usize_field(section, "max_nodes");
}
BvpSolverFamily::CorrectionNewton => {
}
}
}
fn seed_bvp_document_defaults(document: &mut DocumentMap) {
let (config, _) = BvpGuiConfig::from_document(document);
config.apply_to_document(document);
}
fn normalize_usize_field(
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
) -> Result<(), UsizeConversionError> {
let Some(values) = section.get_mut(field_name).and_then(|slot| slot.as_mut()) else {
return Ok(());
};
if let Some(first) = values.first_mut() {
let value = try_value_as_usize(first)?;
*first = Value::Usize(value);
values.truncate(1);
}
Ok(())
}
pub(crate) fn normalize_bvp_usize_fields(document: &mut DocumentMap) -> Result<(), String> {
const FIELDS: &[(&str, &str)] = &[
("process_conditions", "n_steps"),
("solver_settings", "max_iterations"),
("solver_settings", "refinement_steps"),
("solver_settings", "aot_residual_target_chunks"),
("solver_settings", "aot_jacobian_target_chunks"),
("strategy_params", "max_jac"),
("strategy_params", "max_damp_iter"),
("adaptive_strategy", "version"),
("adaptive_strategy", "max_refinements"),
];
for (section_name, field_name) in FIELDS {
let Some(section) = document.get_mut(*section_name) else {
continue;
};
normalize_usize_field(section, field_name).map_err(|error| {
format!("invalid integer field `{section_name}.{field_name}`: {error}")
})?;
}
for field_name in ["aot_residual_target_chunks", "aot_jacobian_target_chunks"] {
let Some(section) = document.get("solver_settings") else {
continue;
};
let Some(values) = section.get(field_name).and_then(Option::as_ref) else {
continue;
};
let Some(value) = values.first() else {
continue;
};
if try_value_as_usize(value).is_ok_and(|value| value == 0) {
return Err(format!(
"invalid integer field `solver_settings.{field_name}`: expected a positive chunk count"
));
}
}
Ok(())
}
fn string_field_value(
section: &HashMap<String, Option<Vec<Value>>>,
field_name: &str,
) -> Option<String> {
section
.get(field_name)
.and_then(|slot| slot.as_ref())
.and_then(|values| values.first())
.and_then(|value| value.as_string().cloned())
}
fn set_string_field(
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
value: &str,
) {
section.insert(
field_name.to_string(),
Some(vec![Value::String(value.to_string())]),
);
}
fn canonical_matrix_backend(value: &str) -> Option<&'static str> {
match value.trim().to_ascii_lowercase().as_str() {
"banded" => Some("Banded"),
"sparse" => Some("Sparse"),
_ => None,
}
}
fn normalize_matrix_backend_aliases(
section: &mut HashMap<String, Option<Vec<Value>>>,
) -> &'static str {
let method = string_field_value(section, "method")
.as_deref()
.and_then(canonical_matrix_backend);
let matrix_backend = string_field_value(section, "matrix_backend")
.as_deref()
.and_then(canonical_matrix_backend);
let backend = method.or(matrix_backend).unwrap_or("Banded");
set_string_field(section, "method", backend);
set_string_field(section, "matrix_backend", backend);
backend
}
fn optional_string_field_value(
section: &HashMap<String, Option<Vec<Value>>>,
field_name: &str,
) -> Option<String> {
let value = section
.get(field_name)
.and_then(|slot| slot.as_ref())
.and_then(|values| values.first())?;
match value {
Value::Optional(None) => None,
Value::Optional(Some(inner)) => inner.as_string().cloned(),
Value::String(value) if value.eq_ignore_ascii_case("none") => None,
Value::String(value) => Some(value.clone()),
_ => None,
}
}
fn set_optional_string_field(
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
value: Option<&str>,
) {
let value = value
.map(|value| Value::Optional(Some(Box::new(Value::String(value.to_string())))))
.unwrap_or(Value::Optional(None));
section.insert(field_name.to_string(), Some(vec![value]));
}
fn normalize_optional_string_field(
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
) {
let current_value = optional_string_field_value(section, field_name);
let is_valid_shape = section
.get(field_name)
.and_then(|slot| slot.as_ref())
.and_then(|values| values.first())
.map(|value| match value {
Value::Optional(None) => true,
Value::Optional(Some(inner)) => inner.as_string().is_some(),
Value::String(_) => true,
_ => false,
})
.unwrap_or(false);
if !is_valid_shape {
set_optional_string_field(section, field_name, None);
} else if matches!(
section
.get(field_name)
.and_then(|slot| slot.as_ref())
.and_then(|values| values.first()),
Some(Value::String(_))
) {
set_optional_string_field(section, field_name, current_value.as_deref());
}
}
fn bvp_species_section_names(document: &DocumentMap) -> Vec<String> {
let Some(process_conditions) = document.get("process_conditions") else {
return Vec::new();
};
let Some(substances) = process_conditions
.get("substances")
.and_then(|slot| slot.as_ref())
else {
return Vec::new();
};
substances
.iter()
.filter_map(|value| value.as_string().cloned())
.collect()
}
fn render_solver_backend_optional_string_choice_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
display_name: &str,
choices: &[(&str, Option<&str>)],
default_label: &str,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
normalize_optional_string_field(section, field_name);
let current_value = optional_string_field_value(section, field_name);
let current_label = choices
.iter()
.find(|(_, value)| value.map(str::to_string) == current_value)
.map(|(label, _)| *label)
.unwrap_or(default_label);
let label_response = ui.label(display_name);
if let Some(help_text) = help_map
.and_then(|map| {
map.iter()
.find(|(key, _)| *key == format!("solver_settings.{field_name}"))
})
.map(|(_, text)| *text)
{
label_response.clone().on_hover_text(help_text);
}
if label_response.hovered() {
if let Some(map) = help_map {
let help_key = format!("solver_settings.{}", field_name);
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == help_key) {
*current_help = help_text.to_string();
}
}
}
let mut selected_label = current_label.to_string();
let combo_response =
egui::ComboBox::from_id_salt(format!("solver_settings.{}.{}", display_name, field_name))
.selected_text(selected_label.as_str())
.show_ui(ui, |ui| {
for (label, _) in choices {
ui.selectable_value(&mut selected_label, (*label).to_string(), *label);
}
});
let combo_hovered = combo_response.response.hovered();
let _ = combo_response.response.labelled_by(label_response.id);
if combo_hovered {
if let Some(map) = help_map {
let help_key = format!("solver_settings.{}", field_name);
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == help_key) {
*current_help = help_text.to_string();
}
}
}
if selected_label != current_label {
let selected_value = choices
.iter()
.find(|(label, _)| *label == selected_label)
.and_then(|(_, value)| *value);
set_optional_string_field(section, field_name, selected_value);
info!(
"Field '{}' changed to: {}",
field_name,
selected_value.unwrap_or("None")
);
}
ui.end_row();
}
fn render_solver_backend_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
display_name: &str,
default_value: Value,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let values = ensure_field_slot(section, field_name, default_value);
let label_response = ui.label(display_name);
let mut input_hovered = false;
if label_response.hovered() {
if let Some(map) = help_map {
let help_key = format!("solver_settings.{}", field_name);
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == help_key) {
*current_help = help_text.to_string();
}
}
}
match values {
Some(values) => {
if values.is_empty() {
ui.label("None");
} else {
for value in values.iter_mut() {
input_hovered |= render_value(ui, value, field_name, label_response.id);
}
}
}
None => {
ui.label("None");
}
}
if input_hovered {
update_solver_field_help(field_name, help_map, current_help);
}
ui.end_row();
}
fn update_solver_field_help(
field_name: &str,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
if let Some(map) = help_map {
let help_key = format!("solver_settings.{field_name}");
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == help_key) {
*current_help = help_text.to_string();
}
}
}
fn render_solver_backend_optional_text_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
display_name: &str,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let label_response = ui.label(display_name);
let mut value = string_field_value(section, field_name).unwrap_or_default();
let response = ui.add(egui::TextEdit::singleline(&mut value).desired_width(220.0));
let _ = response.clone().labelled_by(label_response.id);
if response.changed() {
if value.trim().is_empty() {
section.remove(field_name);
} else {
set_string_field(section, field_name, &value);
}
}
if label_response.hovered() || response.hovered() {
if let Some(help_text) = help_map
.and_then(|map| {
map.iter()
.find(|(key, _)| *key == format!("solver_settings.{field_name}"))
})
.map(|(_, text)| *text)
{
*current_help = help_text.to_string();
}
}
ui.end_row();
}
fn render_solver_backend_usize_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
display_name: &str,
default_value: usize,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let current_value = {
let values = ensure_field_slot(section, field_name, Value::Usize(default_value));
values
.as_ref()
.and_then(|values| values.first())
.map(try_value_as_usize)
.unwrap_or(Ok(default_value))
};
let label_response = ui.label(display_name);
if label_response.hovered() {
if let Some(map) = help_map {
let help_key = format!("solver_settings.{}", field_name);
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == help_key) {
*current_help = help_text.to_string();
}
}
}
match current_value {
Ok(mut current_value) => {
let _ = normalize_usize_field(section, field_name);
let response = ui.add(egui::DragValue::new(&mut current_value).speed(1));
let _ = response.clone().labelled_by(label_response.id);
if response.changed() {
section.insert(
field_name.to_string(),
Some(vec![Value::Usize(current_value)]),
);
info!("Field '{}' changed to: {}", field_name, current_value);
}
if response.hovered() {
update_solver_field_help(field_name, help_map, current_help);
}
}
Err(error) => {
ui.horizontal(|ui| {
ui.colored_label(egui::Color32::RED, error.to_string());
if ui.button(format!("Reset to {default_value}")).clicked() {
section.insert(
field_name.to_string(),
Some(vec![Value::Usize(default_value)]),
);
}
});
}
}
ui.end_row();
}
fn render_solver_backend_optional_positive_usize_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
display_name: &str,
override_label: &str,
default_value: usize,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let label_response = ui.label(display_name);
let mut enabled = section.contains_key(field_name);
ui.horizontal(|ui| {
let toggle = ui.checkbox(&mut enabled, override_label);
let _ = toggle.clone().labelled_by(label_response.id);
if toggle.changed() {
if enabled {
section.insert(
field_name.to_string(),
Some(vec![Value::Usize(default_value)]),
);
} else {
section.remove(field_name);
}
}
if enabled {
let stored = section
.get(field_name)
.and_then(Option::as_ref)
.and_then(|values| values.first())
.map(try_value_as_usize);
let (mut value, validation_error) = match stored {
Some(Ok(value)) if value > 0 => (value, None),
Some(Ok(_)) => (default_value, Some("must be greater than zero".to_string())),
Some(Err(error)) => (default_value, Some(error.to_string())),
None => (default_value, Some("missing chunk count".to_string())),
};
let drag = ui.add(
egui::DragValue::new(&mut value)
.range(1..=usize::MAX)
.speed(1),
);
let _ = drag.clone().labelled_by(label_response.id);
if drag.changed() {
section.insert(field_name.to_string(), Some(vec![Value::Usize(value)]));
} else if let Some(error) = validation_error {
ui.colored_label(egui::Color32::RED, error);
if ui.button("Reset").clicked() {
section.insert(
field_name.to_string(),
Some(vec![Value::Usize(default_value)]),
);
}
}
if drag.hovered() {
update_solver_field_help(field_name, help_map, current_help);
}
} else {
ui.label("RST default");
}
if toggle.hovered() {
update_solver_field_help(field_name, help_map, current_help);
}
});
if label_response.hovered() {
update_solver_field_help(field_name, help_map, current_help);
}
ui.end_row();
}
fn render_solver_backend_choice_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
field_name: &str,
display_name: &str,
choices: &[&str],
default_value: &str,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let current_value = string_field_value(section, field_name).unwrap_or_else(|| {
let default_value = default_value.to_string();
set_string_field(section, field_name, &default_value);
default_value
});
let label_response = ui.label(display_name);
if label_response.hovered() {
if let Some(map) = help_map {
let help_key = format!("solver_settings.{}", field_name);
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == help_key) {
*current_help = help_text.to_string();
}
}
}
let mut selected_value = current_value.clone();
let combo_response =
egui::ComboBox::from_id_salt(format!("solver_settings.{}.{}", display_name, field_name))
.selected_text(selected_value.as_str())
.show_ui(ui, |ui| {
for choice in choices {
ui.selectable_value(&mut selected_value, (*choice).to_string(), *choice);
}
});
let combo_hovered = combo_response.response.hovered();
let _ = combo_response.response.labelled_by(label_response.id);
if combo_hovered {
if let Some(map) = help_map {
let help_key = format!("solver_settings.{}", field_name);
if let Some((_, help_text)) = map.iter().find(|(key, _)| *key == help_key) {
*current_help = help_text.to_string();
}
}
}
if selected_value != current_value {
set_string_field(section, field_name, &selected_value);
info!("Field '{}' changed to: {}", field_name, selected_value);
if field_name == "matrix_backend"
|| field_name == "aot_codegen_backend"
|| field_name == "aot_c_compiler"
{
normalize_bvp_solver_backend_section(section);
}
}
ui.end_row();
}
fn render_generated_backend_mode_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) -> bool {
let current_backend = string_field_value(section, "generated_backend")
.unwrap_or_else(|| "banded_lambdify".to_string());
let current_mode = GuiExecutionBackend::from_generated_backend(¤t_backend);
let current_label = match current_mode {
Some(GuiExecutionBackend::Aot) => "AOT".to_string(),
Some(GuiExecutionBackend::Lambdify) => "Lambdify".to_string(),
None => format!("Unsupported: {}", current_backend),
};
let label_response = ui.label("Residuals and Jacobian Backend");
if label_response.hovered() {
if let Some(map) = help_map {
if let Some((_, help_text)) = map
.iter()
.find(|(key, _)| *key == "solver_settings.generated_backend")
{
*current_help = help_text.to_string();
}
}
}
let mut selected_mode = current_label.clone();
let combo_response = egui::ComboBox::from_id_salt("solver_settings.generated_backend.mode")
.selected_text(selected_mode.as_str())
.show_ui(ui, |ui| {
ui.selectable_value(&mut selected_mode, "Lambdify".to_string(), "Lambdify");
ui.selectable_value(&mut selected_mode, "AOT".to_string(), "AOT");
});
let combo_hovered = combo_response.response.hovered();
let _ = combo_response.response.labelled_by(label_response.id);
if combo_hovered {
if let Some(map) = help_map {
if let Some((_, help_text)) = map
.iter()
.find(|(key, _)| *key == "solver_settings.generated_backend")
{
*current_help = help_text.to_string();
}
}
}
let changed = selected_mode != current_label;
if changed {
let matrix_backend =
string_field_value(section, "matrix_backend").unwrap_or_else(|| "Banded".to_string());
let backend_name = match (selected_mode.as_str(), matrix_backend.as_str()) {
("AOT", "Sparse") => "sparse_aot_tcc",
("AOT", _) => "banded_aot_tcc",
("Lambdify", "Sparse") => "sparse_lambdify",
_ => "banded_lambdify",
};
set_string_field(section, "generated_backend", backend_name);
normalize_bvp_solver_backend_section(section);
info!("Field 'generated_backend' changed to: {}", backend_name);
}
ui.end_row();
selected_mode == "AOT"
}
fn render_bvp_solver_backend_panel(
ui: &mut egui::Ui,
document: &mut DocumentMap,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
ensure_bvp_solver_backend_defaults(document);
let family_before = BvpGuiConfig::from_document(document).0.core.family;
ui.separator();
ui.label("Solver backend");
ui.label("Solver family and its route-specific settings");
ui.add_space(6.0);
{
let section = ensure_section_mut(document, "solver_settings");
render_solver_backend_choice_row(
ui,
section,
"solver_family",
"Solver family",
&["damped", "frozen", "sci", "correction_newton"],
"damped",
help_map,
current_help,
);
}
let family = BvpGuiConfig::from_document(document).0.core.family;
if family != family_before {
set_bvp_solver_family(document, family);
ensure_bvp_solver_backend_defaults(document);
}
match family {
BvpSolverFamily::Damped => {
ui.label("Compact HMX physical acceptance: passed for Damped.");
}
BvpSolverFamily::Frozen => {
ui.colored_label(
ui.visuals().warn_fg_color,
"Compact HMX physical acceptance is open: Frozen/Naive do not currently meet the boundary contract.",
);
}
BvpSolverFamily::Sci => {
ui.label("Compact HMX physical acceptance: passed for BVP_sci.");
}
BvpSolverFamily::CorrectionNewton => {
ui.label("CorrectionNewton is a fixed-mesh route; grid refinement is not available.");
}
}
let section = ensure_section_mut(document, "solver_settings");
if matches!(family, BvpSolverFamily::Damped | BvpSolverFamily::Frozen) {
normalize_bvp_solver_backend_section(section);
}
if family == BvpSolverFamily::Sci {
render_sci_solver_backend_controls(ui, section, help_map, current_help);
return;
}
if family == BvpSolverFamily::CorrectionNewton {
render_correction_newton_solver_backend_controls(ui, section, help_map, current_help);
return;
}
ui.label(match family {
BvpSolverFamily::Damped => "Damped Newton route",
BvpSolverFamily::Frozen => "Fixed-mesh Frozen/Naive route",
BvpSolverFamily::Sci => unreachable!(),
BvpSolverFamily::CorrectionNewton => unreachable!(),
});
ui.label("Residuals and Jacobian backend is exclusive: Lambdify or AOT.");
ui.label("Core solve");
egui::Grid::new("bvp_solver_backend_core_grid")
.num_columns(2)
.striped(true)
.show(ui, |ui| {
render_solver_backend_choice_row(
ui,
section,
"scheme",
"scheme",
&["forward", "trapezoid"],
"forward",
help_map,
current_help,
);
let matrix_backend_before = string_field_value(section, "matrix_backend")
.as_deref()
.and_then(canonical_matrix_backend)
.unwrap_or("Banded")
.to_string();
render_solver_backend_choice_row(
ui,
section,
"method",
"Linear algebra backend",
&["Banded", "Sparse"],
"Banded",
help_map,
current_help,
);
let matrix_backend_after = string_field_value(section, "method")
.as_deref()
.and_then(canonical_matrix_backend)
.unwrap_or("Banded");
set_string_field(section, "matrix_backend", matrix_backend_after);
if matrix_backend_after != matrix_backend_before {
normalize_bvp_solver_backend_section(section);
}
render_solver_backend_choice_row(
ui,
section,
"strategy",
"Nonlinear strategy",
if family == BvpSolverFamily::Damped {
&["Damped"][..]
} else {
&["Frozen", "Naive"][..]
},
if family == BvpSolverFamily::Damped {
"Damped"
} else {
"Frozen"
},
help_map,
current_help,
);
render_solver_backend_optional_string_choice_row(
ui,
section,
"linear_sys_method",
"Linear system method override",
&[("Auto", None), ("faithful", Some("faithful"))],
"Auto",
help_map,
current_help,
);
render_solver_backend_row(
ui,
section,
if family == BvpSolverFamily::Damped {
"abs_tolerance"
} else {
"tolerance"
},
if family == BvpSolverFamily::Damped {
"abs_tolerance"
} else {
"tolerance"
},
Value::Float(if family == BvpSolverFamily::Damped {
1e-7
} else {
1e-6
}),
help_map,
current_help,
);
render_solver_backend_usize_row(
ui,
section,
"max_iterations",
"max_iterations",
100,
help_map,
current_help,
);
let aot_enabled = string_field_value(section, "generated_backend")
.as_deref()
.and_then(GuiExecutionBackend::from_generated_backend)
== Some(GuiExecutionBackend::Aot);
let telemetry = string_field_value(section, "telemetry")
.unwrap_or_else(|| "off".to_string());
let telemetry_choices: &[&str] = if aot_enabled {
&["off", "counters", "detailed"]
} else {
&["off", "counters", "timings", "detailed"]
};
render_solver_backend_choice_row(
ui,
section,
"telemetry",
"Solver telemetry",
telemetry_choices,
"off",
help_map,
current_help,
);
if aot_enabled && telemetry.eq_ignore_ascii_case("timings") {
ui.colored_label(
egui::Color32::from_rgb(160, 90, 20),
"Timings telemetry is unavailable for the Damped AOT route; select Counters or Detailed.",
);
ui.end_row();
}
render_solver_backend_optional_string_choice_row(
ui,
section,
"loglevel",
"loglevel",
&[
("off", Some("off")),
("error", Some("error")),
("warn", Some("warn")),
("info", Some("info")),
("debug", Some("debug")),
],
"off",
help_map,
current_help,
);
if family == BvpSolverFamily::Damped {
render_solver_backend_choice_row(
ui,
section,
"bvp_logging_mode",
"Backend event logging",
&["off", "warnings", "detailed"],
"off",
help_map,
current_help,
);
render_solver_backend_usize_row(
ui,
section,
"bvp_logging_max_events",
"Maximum logged events",
256,
help_map,
current_help,
);
}
});
ui.add_space(8.0);
ui.label("Execution and assembly");
egui::Grid::new("bvp_solver_backend_generated_grid")
.num_columns(2)
.striped(true)
.show(ui, |ui| {
let aot_enabled =
render_generated_backend_mode_row(ui, section, help_map, current_help);
render_solver_backend_choice_row(
ui,
section,
"symbolic_backend",
"Symbolic backend",
&["AtomView", "ExprLegacy"],
"AtomView",
help_map,
current_help,
);
if aot_enabled {
render_solver_backend_choice_row(
ui,
section,
"aot_codegen_backend",
"AOT codegen backend",
&["C", "Zig", "Rust"],
"C",
help_map,
current_help,
);
let codegen_is_c = string_field_value(section, "aot_codegen_backend")
.as_deref()
.and_then(GuiAotCodegenBackend::parse)
== Some(GuiAotCodegenBackend::C);
if codegen_is_c {
render_solver_backend_choice_row(
ui,
section,
"aot_c_compiler",
"C compiler",
&["tcc", "gcc"],
"tcc",
help_map,
current_help,
);
}
render_solver_backend_choice_row(
ui,
section,
"aot_build_policy",
"AOT build policy",
&[
"build_if_missing",
"use_if_available",
"require_prebuilt",
"rebuild_always",
],
"build_if_missing",
help_map,
current_help,
);
render_solver_backend_choice_row(
ui,
section,
"aot_build_profile",
"AOT build profile",
&["release", "debug"],
"release",
help_map,
current_help,
);
render_solver_backend_choice_row(
ui,
section,
"aot_compile_preset",
"AOT compile preset",
&["production", "fast_build", "dev_fastest"],
"dev_fastest",
help_map,
current_help,
);
render_solver_backend_choice_row(
ui,
section,
"aot_execution_policy",
"AOT execution policy",
&["auto", "sequential", "parallel"],
"auto",
help_map,
current_help,
);
render_solver_backend_optional_positive_usize_row(
ui,
section,
"aot_residual_target_chunks",
"Residual target chunks",
"Override",
4,
help_map,
current_help,
);
render_solver_backend_optional_positive_usize_row(
ui,
section,
"aot_jacobian_target_chunks",
"Jacobian target chunks",
"Override",
4,
help_map,
current_help,
);
} else {
render_solver_backend_choice_row(
ui,
section,
"lambdify_execution_policy",
"Lambdify callback policy",
&["sequential", "parallel", "auto"],
"sequential",
help_map,
current_help,
);
if string_field_value(section, "lambdify_execution_policy")
.is_some_and(|policy| !policy.eq_ignore_ascii_case("sequential"))
{
render_solver_backend_usize_row(
ui,
section,
"lambdify_min_work",
"Minimum callback work",
128,
help_map,
current_help,
);
}
}
render_solver_backend_choice_row(
ui,
section,
"banded_linear_solver",
"Banded linear solver",
&[
"auto",
"faithful",
"block_tridiagonal",
"block_tridiagonal_consistent",
"faer_sparse",
"general_partial_pivot",
],
"auto",
help_map,
current_help,
);
render_solver_backend_usize_row(
ui,
section,
"refinement_steps",
"refinement_steps",
5,
help_map,
current_help,
);
let _ = aot_enabled;
});
}
fn render_correction_newton_solver_backend_controls(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
ui.label("Fixed-mesh CorrectionNewton route");
ui.label("This route solves on the supplied mesh; adaptive grid refinement is not available.");
ui.add_space(6.0);
egui::Grid::new("bvp_correction_newton_settings_grid")
.num_columns(2)
.striped(true)
.show(ui, |ui| {
for (field, label, choices, default) in [
(
"assembly",
"Symbolic assembly",
&["expr_legacy", "atom_view_native"][..],
"expr_legacy",
),
(
"execution",
"Execution",
&["lambdify", "aot"][..],
"lambdify",
),
(
"matrix_layout",
"Matrix layout",
&["sparse", "banded_auto", "dense"][..],
"sparse",
),
] {
render_solver_backend_choice_row(
ui,
section,
field,
label,
choices,
default,
help_map,
current_help,
);
}
for (field, label, value) in [
("absolute_tolerance", "Absolute tolerance", 1e-5),
(
"default_relative_tolerance",
"Default relative tolerance",
1e-5,
),
] {
render_solver_backend_row(
ui,
section,
field,
label,
Value::Float(value),
help_map,
current_help,
);
}
for (field, label, value) in [
("max_iterations", "Maximum Newton iterations", 100),
("max_jacobian_age", "Maximum Jacobian age", 5),
("max_damping_trials", "Maximum damping trials", 7),
] {
render_solver_backend_usize_row(
ui,
section,
field,
label,
value,
help_map,
current_help,
);
}
render_solver_backend_choice_row(
ui,
section,
"telemetry",
"Solver telemetry",
&["off", "counters", "timings", "detailed"],
"off",
help_map,
current_help,
);
render_solver_backend_optional_string_choice_row(
ui,
section,
"loglevel",
"Logging level",
&[
("off", Some("off")),
("error", Some("error")),
("warn", Some("warn")),
("info", Some("info")),
("debug", Some("debug")),
],
"off",
help_map,
current_help,
);
let aot_enabled = string_field_value(section, "execution")
.is_some_and(|execution| execution.eq_ignore_ascii_case("aot"));
if aot_enabled {
for (field, default) in [
("aot_codegen_backend", "C"),
("aot_build_policy", "build_if_missing"),
("aot_build_profile", "release"),
] {
if string_field_value(section, field).is_none() {
set_string_field(section, field, default);
}
}
render_solver_backend_choice_row(
ui,
section,
"aot_codegen_backend",
"AOT codegen backend",
&["C", "Zig", "Rust"],
"C",
help_map,
current_help,
);
render_solver_backend_choice_row(
ui,
section,
"aot_build_policy",
"AOT build policy",
&[
"use_if_available",
"build_if_missing",
"require_prebuilt",
"rebuild_always",
],
"build_if_missing",
help_map,
current_help,
);
render_solver_backend_choice_row(
ui,
section,
"aot_build_profile",
"AOT build profile",
&["release", "debug"],
"release",
help_map,
current_help,
);
if string_field_value(section, "aot_codegen_backend")
.is_some_and(|backend| backend.eq_ignore_ascii_case("c"))
{
if string_field_value(section, "aot_c_compiler").is_none() {
set_string_field(section, "aot_c_compiler", "tcc");
}
render_solver_backend_choice_row(
ui,
section,
"aot_c_compiler",
"C compiler",
&["tcc", "gcc"],
"tcc",
help_map,
current_help,
);
} else {
section.remove("aot_c_compiler");
}
render_solver_backend_optional_text_row(
ui,
section,
"aot_output_dir",
"AOT output directory",
help_map,
current_help,
);
} else {
for field in [
"aot_codegen_backend",
"aot_c_compiler",
"aot_build_policy",
"aot_build_profile",
"aot_output_dir",
"aot_handoff_path",
"aot_crate_name",
"aot_module_name",
"aot_residual_chunking",
"aot_residual_chunk_size",
"aot_sparse_jacobian_chunking",
"aot_sparse_jacobian_chunk_size",
"aot_banded_jacobian_chunking",
"aot_banded_jacobian_chunk_size",
] {
section.remove(field);
}
}
});
}
fn render_sci_solver_backend_controls(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let execution = string_field_value(section, "execution").unwrap_or_else(|| {
set_string_field(section, "execution", "lambdify");
"lambdify".to_string()
});
let aot_enabled = execution.eq_ignore_ascii_case("aot");
ui.label("BVP_sci collocation solver");
egui::Grid::new("bvp_sci_solver_settings_grid")
.num_columns(2)
.striped(true)
.show(ui, |ui| {
render_solver_backend_choice_row(
ui,
section,
"execution",
"Execution",
&["lambdify", "aot"],
"lambdify",
help_map,
current_help,
);
render_solver_backend_choice_row(
ui,
section,
"assembly",
"Symbolic assembly",
&["atom_view_native", "expr_legacy"],
"atom_view_native",
help_map,
current_help,
);
render_solver_backend_choice_row(
ui,
section,
"matrix_layout",
"Matrix layout",
&["dense", "sparse", "banded", "banded_auto"],
"banded_auto",
help_map,
current_help,
);
if string_field_value(section, "matrix_layout")
.is_some_and(|layout| layout.eq_ignore_ascii_case("banded"))
{
render_solver_backend_usize_row(
ui,
section,
"banded_lower",
"Lower bandwidth",
1,
help_map,
current_help,
);
render_solver_backend_usize_row(
ui,
section,
"banded_upper",
"Upper bandwidth",
1,
help_map,
current_help,
);
} else {
section.remove("banded_lower");
section.remove("banded_upper");
}
if !aot_enabled {
render_solver_backend_choice_row(
ui,
section,
"execution_policy",
"Callback execution policy",
&["sequential", "parallel", "auto"],
"sequential",
help_map,
current_help,
);
if string_field_value(section, "execution_policy")
.is_some_and(|policy| !policy.eq_ignore_ascii_case("sequential"))
{
render_solver_backend_usize_row(
ui,
section,
"execution_min_work",
"Minimum callback work",
128,
help_map,
current_help,
);
}
}
render_solver_backend_choice_row(
ui,
section,
"output_policy",
"Solution output",
&["final_only", "mesh_and_values", "dense_output"],
"mesh_and_values",
help_map,
current_help,
);
if string_field_value(section, "matrix_layout")
.is_some_and(|layout| layout.eq_ignore_ascii_case("sparse"))
{
render_solver_backend_choice_row(
ui,
section,
"sparse_factorization",
"Sparse factorization",
&["standard_faer", "superlu"],
"standard_faer",
help_map,
current_help,
);
} else {
section.remove("sparse_factorization");
}
render_solver_backend_row(
ui,
section,
"tolerance",
"Tolerance",
Value::Float(1e-4),
help_map,
current_help,
);
render_solver_backend_row(
ui,
section,
"boundary_tolerance",
"Boundary tolerance",
Value::Float(1e-6),
help_map,
current_help,
);
for (field, label, default) in [
("max_nodes", "Maximum mesh nodes", 256),
("max_newton_iterations", "Maximum Newton iterations", 10),
("max_jacobian_refreshes", "Maximum Jacobian refreshes", 4),
("max_mesh_refinements", "Maximum mesh refinements", 4),
("max_backtracking_steps", "Maximum backtracking steps", 8),
] {
render_solver_backend_usize_row(
ui,
section,
field,
label,
default,
help_map,
current_help,
);
}
render_solver_backend_choice_row(
ui,
section,
"telemetry",
"Solver telemetry",
&["off", "counters", "timings", "detailed"],
"off",
help_map,
current_help,
);
render_solver_backend_optional_string_choice_row(
ui,
section,
"loglevel",
"Logging level",
&[
("None", None),
("error", Some("error")),
("warn", Some("warn")),
("info", Some("info")),
("debug", Some("debug")),
("trace", Some("trace")),
],
"None",
help_map,
current_help,
);
if aot_enabled {
render_solver_backend_choice_row(
ui,
section,
"aot_build_policy",
"AOT build policy",
&[
"use_if_available",
"build_if_missing",
"require_prebuilt",
"rebuild_always",
],
"build_if_missing",
help_map,
current_help,
);
let build_policy = string_field_value(section, "aot_build_policy")
.unwrap_or_else(|| "build_if_missing".to_string());
if matches!(
build_policy.to_ascii_lowercase().as_str(),
"build_if_missing" | "rebuild_always"
) {
render_solver_backend_choice_row(
ui,
section,
"aot_build_profile",
"AOT build profile",
&["release", "debug"],
"release",
help_map,
current_help,
);
} else {
section.remove("aot_build_profile");
}
render_solver_backend_choice_row(
ui,
section,
"aot_codegen_backend",
"AOT codegen backend",
&["C", "Rust", "Zig"],
"C",
help_map,
current_help,
);
let c_codegen = string_field_value(section, "aot_codegen_backend")
.is_some_and(|backend| backend.eq_ignore_ascii_case("c"));
if c_codegen {
render_solver_backend_choice_row(
ui,
section,
"aot_c_compiler",
"C compiler",
&["tcc", "gcc"],
"tcc",
help_map,
current_help,
);
} else {
section.remove("aot_c_compiler");
}
for (field, label) in [
("aot_output_dir", "AOT output directory"),
("aot_handoff_path", "AOT handoff path"),
("aot_crate_name", "Generated crate name"),
("aot_module_name", "Generated module name"),
] {
render_solver_backend_optional_text_row(
ui,
section,
field,
label,
help_map,
current_help,
);
}
render_solver_backend_choice_row(
ui,
section,
"aot_residual_chunking",
"Residual chunking",
&["whole", "target_chunks", "output_count"],
"whole",
help_map,
current_help,
);
let residual_chunking = string_field_value(section, "aot_residual_chunking")
.unwrap_or_else(|| "whole".to_string());
if residual_chunking.eq_ignore_ascii_case("whole") {
section.remove("aot_residual_chunk_size");
} else {
render_solver_backend_usize_row(
ui,
section,
"aot_residual_chunk_size",
"Residual chunk size",
4,
help_map,
current_help,
);
}
let matrix_layout = string_field_value(section, "matrix_layout")
.unwrap_or_else(|| "banded_auto".to_string())
.to_ascii_lowercase();
if matches!(matrix_layout.as_str(), "sparse" | "banded_auto") {
render_solver_backend_choice_row(
ui,
section,
"aot_sparse_jacobian_chunking",
"Sparse Jacobian chunking",
&["whole", "target_chunks", "nnz", "rows"],
"whole",
help_map,
current_help,
);
let chunking = string_field_value(section, "aot_sparse_jacobian_chunking")
.unwrap_or_else(|| "whole".to_string());
if chunking.eq_ignore_ascii_case("whole") {
section.remove("aot_sparse_jacobian_chunk_size");
} else {
render_solver_backend_usize_row(
ui,
section,
"aot_sparse_jacobian_chunk_size",
"Sparse Jacobian chunk size",
4,
help_map,
current_help,
);
}
} else {
section.remove("aot_sparse_jacobian_chunking");
section.remove("aot_sparse_jacobian_chunk_size");
}
if matches!(matrix_layout.as_str(), "banded" | "banded_auto") {
render_solver_backend_choice_row(
ui,
section,
"aot_banded_jacobian_chunking",
"Banded Jacobian chunking",
&["whole", "target_chunks", "diagonals"],
"whole",
help_map,
current_help,
);
let chunking = string_field_value(section, "aot_banded_jacobian_chunking")
.unwrap_or_else(|| "whole".to_string());
if chunking.eq_ignore_ascii_case("whole") {
section.remove("aot_banded_jacobian_chunk_size");
} else {
render_solver_backend_usize_row(
ui,
section,
"aot_banded_jacobian_chunk_size",
"Banded Jacobian chunk size",
4,
help_map,
current_help,
);
}
} else {
section.remove("aot_banded_jacobian_chunking");
section.remove("aot_banded_jacobian_chunk_size");
}
} else {
for field in [
"aot_build_policy",
"aot_build_profile",
"aot_codegen_backend",
"aot_c_compiler",
"aot_output_dir",
"aot_handoff_path",
"aot_crate_name",
"aot_module_name",
"aot_residual_chunking",
"aot_residual_chunk_size",
"aot_sparse_jacobian_chunking",
"aot_sparse_jacobian_chunk_size",
"aot_banded_jacobian_chunking",
"aot_banded_jacobian_chunk_size",
] {
section.remove(field);
}
}
});
}
const BVP_PHYSICS_SECTIONS: &[&str] = &[
"process_conditions",
"boundary_condition",
"diffusion_coefficients",
"reactions",
"bounds",
];
const BVP_SOLVER_ADVANCED_SECTIONS: &[&str] = &["rel_tolerance", "strategy_params"];
const BVP_ADAPTIVE_SOLVER_SECTIONS: &[&str] = &["adaptive_strategy", "grid_refinement"];
const BVP_INITIAL_GUESS_SECTIONS: &[&str] = &["initial_guess"];
const BVP_POSTPROCESSING_SECTIONS: &[&str] = &["postprocessing"];
fn is_bvp_structured_section(section_name: &str, species_sections: &[String]) -> bool {
section_name == "solver_settings"
|| section_name == "kithe_settings"
|| BVP_PHYSICS_SECTIONS.contains(§ion_name)
|| BVP_SOLVER_ADVANCED_SECTIONS.contains(§ion_name)
|| BVP_ADAPTIVE_SOLVER_SECTIONS.contains(§ion_name)
|| BVP_INITIAL_GUESS_SECTIONS.contains(§ion_name)
|| BVP_POSTPROCESSING_SECTIONS.contains(§ion_name)
|| species_sections
.iter()
.any(|species| species == section_name)
}
fn suggested_reaction_equation(document: &DocumentMap) -> String {
let species = bvp_species_section_names(document);
let existing = document.get("reactions");
for reactant in &species {
for product in &species {
if reactant == product {
continue;
}
let candidate = format!("{reactant}=>{product}");
if !existing.is_some_and(|section| section.contains_key(&candidate)) {
return candidate;
}
}
}
String::new()
}
fn render_bvp_species_manager(
ui: &mut egui::Ui,
document: &mut DocumentMap,
name_draft: &mut String,
pending_deletion: &mut Option<DocumentDeleteRequest>,
status: &mut Option<String>,
is_error: &mut bool,
) {
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.heading("Substances");
let names = bvp_species_section_names(document);
for species in &names {
ui.horizontal(|ui| {
ui.label(species);
if ui.button("Remove substance").clicked() && pending_deletion.is_none() {
*pending_deletion = Some(DocumentDeleteRequest::Species {
species: species.clone(),
});
}
});
}
ui.separator();
ui.horizontal(|ui| {
let name_label = ui.label("Substance name");
let name_response = ui.text_edit_singleline(name_draft);
let name_response = name_response.labelled_by(name_label.id);
name_response.on_hover_text(
"Adding a substance also creates its boundary value, diffusion coefficient, and empty atomic-composition section.",
);
if ui.button("Add substance").clicked() {
match add_bvp_species(document, name_draft) {
Ok(()) => {
*status = Some(format!("Added substance `{}`.", name_draft.trim()));
*is_error = false;
name_draft.clear();
}
Err(message) => {
*status = Some(message);
*is_error = true;
}
}
}
});
});
}
fn render_bvp_reaction_manager(
ui: &mut egui::Ui,
document: &mut DocumentMap,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
equation_draft: &mut String,
pending_deletion: &mut Option<DocumentDeleteRequest>,
status: &mut Option<String>,
is_error: &mut bool,
) {
const PARAMETER_NAMES: [&str; 4] = ["A", "n", "E (J/mol)", "Q (J/mol)"];
const DEFAULT_PARAMETERS: [f64; 4] = [1.0, 0.0, 0.0, 0.0];
if equation_draft.is_empty() {
*equation_draft = suggested_reaction_equation(document);
}
let mut added_reaction = false;
egui::Frame::group(ui.style()).show(ui, |ui| {
let heading = ui.heading("Reactions");
if heading.hovered()
&& let Some((_, help)) =
help_map.and_then(|map| map.iter().find(|(key, _)| *key == "reactions"))
{
*current_help = (*help).to_string();
}
let equations = document
.get("reactions")
.map(sorted_section_field_names)
.unwrap_or_default();
let mut equation_renames = Vec::new();
if equations.is_empty() {
ui.label("No reactions defined.");
}
for (index, equation) in equations.into_iter().enumerate() {
let Some(Some(parameters)) = document
.get_mut("reactions")
.and_then(|reactions| reactions.get_mut(&equation))
else {
continue;
};
let valid_parameters = match parameters.as_slice() {
[Value::Vector(values)] => values.len() == DEFAULT_PARAMETERS.len(),
values if values.len() == DEFAULT_PARAMETERS.len() => {
values.iter().all(|value| matches!(value, Value::Float(_)))
}
_ => false,
};
ui.push_id(("bvp_reaction", index), |ui| {
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
let equation_label = ui.label(format!("Reaction {}", index + 1));
let mut edited_equation = equation.clone();
let response = ui.text_edit_singleline(&mut edited_equation);
let _ = response.clone().labelled_by(equation_label.id);
response
.on_hover_text("Reaction equation using the listed substance names.");
if edited_equation != equation {
equation_renames.push((equation.clone(), edited_equation));
}
if ui.button("Remove reaction").clicked() && pending_deletion.is_none() {
*pending_deletion = Some(DocumentDeleteRequest::Field {
section: "reactions".to_string(),
field: equation.clone(),
});
}
});
ui.horizontal(|ui| {
for (parameter_index, parameter_name) in PARAMETER_NAMES.iter().enumerate()
{
let parameter = if valid_parameters {
match parameters.as_mut_slice() {
[Value::Vector(values)] => values.get_mut(parameter_index),
_ => parameters.get_mut(parameter_index).and_then(|value| {
match value {
Value::Float(value) => Some(value),
_ => None,
}
}),
}
} else {
None
};
if let Some(parameter) = parameter {
ui.vertical(|ui| {
let label = ui.label(*parameter_name);
let response =
ui.add(egui::DragValue::new(parameter).speed(0.1));
let _ = response.labelled_by(label.id);
});
}
}
});
if !valid_parameters {
ui.colored_label(
egui::Color32::from_rgb(180, 30, 30),
"Expected four numeric reaction parameters [A, n, E, Q].",
);
}
});
});
}
for (old, new) in equation_renames {
let new = new.trim().to_string();
let Some(reactions) = document.get_mut("reactions") else {
continue;
};
if new.is_empty() {
*status = Some("Reaction equation cannot be empty.".to_string());
*is_error = true;
} else if old != new && reactions.contains_key(&new) {
*status = Some(format!("Reaction `{new}` already exists."));
*is_error = true;
} else if old != new {
if let Some(parameters) = reactions.remove(&old) {
reactions.insert(new.clone(), parameters);
*status = Some(format!("Updated reaction to `{new}`."));
*is_error = false;
}
}
}
ui.separator();
ui.horizontal(|ui| {
let label = ui.label("New reaction");
let response = ui.text_edit_singleline(equation_draft);
let _ = response.clone().labelled_by(label.id);
response
.on_hover_text("Add as many distinct reaction equations as the mechanism needs.");
if ui
.add_enabled(
!equation_draft.trim().is_empty(),
egui::Button::new("Add reaction"),
)
.clicked()
{
let equation = equation_draft.trim().to_string();
match add_bvp_reaction(document, &equation) {
Ok(()) => {
*status = Some(format!("Added reaction `{equation}`."));
*is_error = false;
*equation_draft = String::new();
added_reaction = true;
}
Err(message) => {
*status = Some(message);
*is_error = true;
}
}
}
});
});
if added_reaction {
*equation_draft = suggested_reaction_equation(document);
}
}
fn render_density_model_choice_row(
ui: &mut egui::Ui,
section: &mut HashMap<String, Option<Vec<Value>>>,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
) {
let selected = string_field_value(section, "density_model")
.unwrap_or_else(|| "ideal_gas_fixed_composition".to_string());
let label = ui.label("Density model");
let mut next = selected.clone();
let response = egui::ComboBox::from_id_salt("bvp_density_model")
.selected_text(match selected.as_str() {
"ideal_gas_fixed_composition" => "Ideal gas, fixed composition (temperature-dependent)",
"constant" => "Constant density",
_ => "Unsupported density model",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut next,
"ideal_gas_fixed_composition".to_string(),
"Ideal gas, fixed composition (temperature-dependent)",
);
ui.selectable_value(&mut next, "constant".to_string(), "Constant density");
});
let help = help_map
.and_then(|entries| {
entries
.iter()
.find(|(key, _)| *key == "process_conditions.density_model")
.map(|(_, help)| *help)
})
.unwrap_or(
"Select whether density varies with temperature or stays frozen at its reference value.",
);
if response.response.hovered() || label.hovered() {
*current_help = help.to_string();
}
let _ = response.response.labelled_by(label.id);
if next != selected {
set_string_field(section, "density_model", &next);
}
ui.label(help).on_hover_text(help);
}
fn render_bvp_section_group(
ui: &mut egui::Ui,
title: &str,
section_names: &[&str],
document: &mut DocumentMap,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
new_field_names: &mut HashMap<String, String>,
new_field_values: &mut HashMap<String, String>,
pending_deletion: &mut Option<DocumentDeleteRequest>,
framed_sections: bool,
) {
ui.group(|ui| {
ui.vertical(|ui| {
ui.heading(title);
ui.add_space(4.0);
let mut sections_to_process = Vec::new();
let mut sections_to_delete = Vec::new();
let mut fields_to_delete = Vec::new();
for section_name in section_names {
let Some(section) = document.get_mut(*section_name) else {
ui.horizontal(|ui| {
ui.colored_label(
egui::Color32::from_rgb(160, 110, 20),
format!("Missing canonical section: {}", section_name),
);
});
continue;
};
let field_name = new_field_names
.entry((*section_name).to_string())
.or_insert_with(String::new);
let field_value = new_field_values
.entry((*section_name).to_string())
.or_insert_with(String::new);
let (add_field, delete_section, requested_fields) =
if *section_name == "grid_refinement" {
let (add_field, delete_section) =
render_grid_refinement_section(ui, section, help_map, current_help);
(add_field, delete_section, Vec::new())
} else {
let options = if framed_sections {
let hidden_fields = if *section_name == "process_conditions" {
&["substances", "density_model"][..]
} else {
&[]
};
SectionRenderOptions::framed_read_only(hidden_fields)
} else {
let hidden_fields = if *section_name == "process_conditions" {
&["density_model"][..]
} else {
&[]
};
SectionRenderOptions {
hidden_fields,
..SectionRenderOptions::compatibility(false)
}
};
render_section(
ui,
section_name,
section,
field_name,
field_value,
help_map,
current_help,
options,
)
};
if *section_name == "process_conditions" {
render_density_model_choice_row(ui, section, help_map, current_help);
}
if add_field {
sections_to_process.push((
(*section_name).to_string(),
field_name.clone(),
field_value.clone(),
));
}
if delete_section {
sections_to_delete.push((*section_name).to_string());
}
fields_to_delete.extend(
requested_fields
.into_iter()
.map(|field| ((*section_name).to_string(), field)),
);
}
for section_name in sections_to_delete {
if pending_deletion.is_none() {
*pending_deletion = Some(DocumentDeleteRequest::Section {
section: section_name,
});
}
}
for (section, field) in fields_to_delete {
if pending_deletion.is_none() {
*pending_deletion = Some(DocumentDeleteRequest::Field { section, field });
}
}
for (section_name, field_name, field_value) in sections_to_process {
if !field_name.is_empty() {
let value = if field_value.parse::<f64>().is_ok() {
if let Ok(num) = field_value.parse::<f64>() {
Value::Float(num)
} else {
Value::String(field_value.clone())
}
} else if field_value.parse::<i64>().is_ok() {
if let Ok(num) = field_value.parse::<i64>() {
Value::Integer(num)
} else {
Value::String(field_value.clone())
}
} else if field_value.to_lowercase() == "true"
|| field_value.to_lowercase() == "false"
{
Value::Boolean(field_value.to_lowercase() == "true")
} else {
Value::String(field_value.clone())
};
let section = document
.entry(section_name.clone())
.or_insert_with(HashMap::new);
match insert_field_if_absent(section, field_name.clone(), value) {
Ok(()) => {
info!("Added field '{}' to section '{}'", field_name, section_name)
}
Err(message) => warn!("{}", message),
}
new_field_names.insert(section_name.clone(), String::new());
new_field_values.insert(section_name, String::new());
}
}
});
});
}
fn render_bvp_dynamic_section_group(
ui: &mut egui::Ui,
title: &str,
section_names: &[String],
document: &mut DocumentMap,
help_map: Option<&[(&str, &str)]>,
current_help: &mut String,
new_field_names: &mut HashMap<String, String>,
new_field_values: &mut HashMap<String, String>,
pending_deletion: &mut Option<DocumentDeleteRequest>,
framed_sections: bool,
) {
if section_names.is_empty() {
return;
}
ui.group(|ui| {
ui.vertical(|ui| {
ui.heading(title);
ui.add_space(4.0);
let mut sections_to_process = Vec::new();
let mut sections_to_delete = Vec::new();
let mut fields_to_delete = Vec::new();
for section_name in section_names {
let Some(section) = document.get_mut(section_name) else {
ui.horizontal(|ui| {
ui.colored_label(
egui::Color32::from_rgb(160, 110, 20),
format!("Missing canonical section: {}", section_name),
);
});
continue;
};
let field_name = new_field_names
.entry(section_name.clone())
.or_insert_with(String::new);
let field_value = new_field_values
.entry(section_name.clone())
.or_insert_with(String::new);
let (add_field, delete_section, requested_fields) = render_section(
ui,
section_name,
section,
field_name,
field_value,
help_map,
current_help,
if framed_sections {
SectionRenderOptions::element_editor()
} else {
SectionRenderOptions::compatibility(false)
},
);
if add_field {
sections_to_process.push((
section_name.clone(),
field_name.clone(),
field_value.clone(),
));
}
if delete_section {
sections_to_delete.push(section_name.clone());
}
fields_to_delete.extend(
requested_fields
.into_iter()
.map(|field| (section_name.clone(), field)),
);
}
for section_name in sections_to_delete {
if pending_deletion.is_none() {
*pending_deletion = Some(DocumentDeleteRequest::Section {
section: section_name,
});
}
}
for (section, field) in fields_to_delete {
if pending_deletion.is_none() {
*pending_deletion = Some(DocumentDeleteRequest::Field { section, field });
}
}
for (section_name, field_name, field_value) in sections_to_process {
if !field_name.is_empty() {
let value = if field_value.parse::<f64>().is_ok() {
if let Ok(num) = field_value.parse::<f64>() {
Value::Float(num)
} else {
Value::String(field_value.clone())
}
} else if field_value.parse::<i64>().is_ok() {
if let Ok(num) = field_value.parse::<i64>() {
Value::Integer(num)
} else {
Value::String(field_value.clone())
}
} else if field_value.to_lowercase() == "true"
|| field_value.to_lowercase() == "false"
{
Value::Boolean(field_value.to_lowercase() == "true")
} else {
Value::String(field_value.clone())
};
let section = document
.entry(section_name.clone())
.or_insert_with(HashMap::new);
match insert_field_if_absent(section, field_name.clone(), value) {
Ok(()) => {
info!("Added field '{}' to section '{}'", field_name, section_name)
}
Err(message) => warn!("{}", message),
}
new_field_names.insert(section_name.clone(), String::new());
new_field_values.insert(section_name, String::new());
}
}
});
});
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum CalculationState {
#[default]
Idle,
Running {
run_id: u64,
},
Cancelling {
run_id: u64,
},
Completed,
Failed,
}
impl CalculationState {
fn active_run_id(self) -> Option<u64> {
match self {
Self::Running { run_id } | Self::Cancelling { run_id } => Some(run_id),
Self::Idle | Self::Completed | Self::Failed => None,
}
}
fn is_active(self) -> bool {
self.active_run_id().is_some()
}
}
#[derive(Debug)]
struct BvpPlotData {
arg: String,
values: Vec<String>,
x_mesh: nalgebra::DVector<f64>,
solution: nalgebra::DMatrix<f64>,
}
#[derive(Debug)]
enum BvpWorkerOutcome {
Completed { plot: Option<BvpPlotData> },
Failed(String),
Cancelled,
}
#[derive(Debug)]
struct BvpWorkerMessage {
run_id: u64,
outcome: BvpWorkerOutcome,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct BvpGuiValidationReport {
pub issues: Vec<String>,
}
impl BvpGuiValidationReport {
pub(crate) fn is_valid(&self) -> bool {
self.issues.is_empty()
}
fn failure_message(&self) -> String {
format!(
"Calculation failed: task validation failed:\n- {}",
self.issues.join("\n- ")
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Tabled)]
pub(crate) struct BvpPreviewParameterRow {
#[tabled(rename = "Section")]
pub(crate) section: String,
#[tabled(rename = "Field")]
pub(crate) field: String,
#[tabled(rename = "Value")]
pub(crate) value: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Tabled)]
pub(crate) struct BvpPreviewEquationRow {
#[tabled(rename = "#")]
pub(crate) index: usize,
#[tabled(rename = "Unknown")]
pub(crate) unknown: String,
#[tabled(rename = "Equation")]
pub(crate) equation: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct BvpTaskPreviewSnapshot {
pub(crate) validation_report: BvpGuiValidationReport,
pub(crate) parameter_rows: Vec<BvpPreviewParameterRow>,
pub(crate) equation_rows: Vec<BvpPreviewEquationRow>,
pub(crate) equation_build_error: Option<String>,
}
fn validate_bvp_gui_document(
document: &DocumentMap,
problem: &ProblemsEnum,
) -> (DocumentMap, BvpGuiValidationReport) {
let mut normalized = document.clone();
let mut report = BvpGuiValidationReport::default();
if let Err(error) = normalize_bvp_usize_fields(&mut normalized) {
report.issues.push(error);
}
if let Err(error) = validate_aot_toolchain_fields(&normalized) {
report.issues.push(format!("AOT security: {error}"));
}
match problem {
ProblemsEnum::BVPSimple => {
let reactor_report = validate_reactor_bvp_task_map(&normalized);
report.issues.extend(
reactor_report
.issues
.into_iter()
.map(|issue| format!("{}: {}", issue.stage, issue.message)),
);
}
ProblemsEnum::None => report
.issues
.push("No calculation is available for the current problem type".to_string()),
}
(normalized, report)
}
fn bvp_preview_section_rank(section_name: &str, species_sections: &[String]) -> usize {
if section_name == "solver_settings" {
0
} else if BVP_PHYSICS_SECTIONS.contains(§ion_name) {
1
} else if species_sections
.iter()
.any(|species| species == section_name)
{
2
} else if BVP_SOLVER_ADVANCED_SECTIONS.contains(§ion_name) {
3
} else if BVP_ADAPTIVE_SOLVER_SECTIONS.contains(§ion_name) {
4
} else if BVP_INITIAL_GUESS_SECTIONS.contains(§ion_name) {
5
} else if BVP_POSTPROCESSING_SECTIONS.contains(§ion_name) {
6
} else {
7
}
}
pub(crate) fn collect_bvp_preview_parameter_rows(
document: &DocumentMap,
) -> Vec<BvpPreviewParameterRow> {
let species_sections = bvp_species_section_names(document);
let mut section_names = document.keys().cloned().collect::<Vec<_>>();
section_names.sort_by_key(|section_name| {
(
bvp_preview_section_rank(section_name, &species_sections),
section_name.clone(),
)
});
let mut rows = Vec::new();
for section_name in section_names {
let Some(section) = document.get(§ion_name) else {
continue;
};
let mut field_names = section.keys().cloned().collect::<Vec<_>>();
field_names.sort();
for field_name in field_names {
let value = match section.get(&field_name).and_then(|slot| slot.as_ref()) {
Some(values) if !values.is_empty() => values_to_document_string(values),
Some(_) => "<empty>".to_string(),
None => "None".to_string(),
};
rows.push(BvpPreviewParameterRow {
section: section_name.clone(),
field: field_name,
value,
});
}
}
rows
}
pub(crate) fn collect_bvp_preview_equation_rows(
reactor: &SimpleReactorTask,
) -> Vec<BvpPreviewEquationRow> {
let equation_count = reactor
.solver
.eq_system
.len()
.min(reactor.solver.unknowns.len());
let mut rows = Vec::with_capacity(equation_count);
for index in 0..equation_count {
let unknown = reactor
.solver
.unknowns
.get(index)
.cloned()
.unwrap_or_else(|| format!("eq_{}", index + 1));
let equation = reactor.solver.eq_system[index].pretty_print();
rows.push(BvpPreviewEquationRow {
index: index + 1,
unknown,
equation,
});
}
rows
}
pub(crate) fn build_bvp_task_preview_snapshot(
document: &DocumentMap,
problem: &ProblemsEnum,
) -> BvpTaskPreviewSnapshot {
let (normalized_document, validation_report) = validate_bvp_gui_document(document, problem);
let parameter_rows = collect_bvp_preview_parameter_rows(&normalized_document);
let mut snapshot = BvpTaskPreviewSnapshot {
validation_report,
parameter_rows,
equation_rows: Vec::new(),
equation_build_error: None,
};
match problem {
ProblemsEnum::BVPSimple => {
let mut reactor = SimpleReactorTask::new();
if let Err(error) = reactor.set_reactor_params_from_hashmap(&normalized_document) {
snapshot.equation_build_error =
Some(format!("Preview could not prepare the BVP task: {}", error));
} else if let Err(error) = reactor.setup_bvp() {
snapshot.equation_build_error = Some(format!(
"Preview could not assemble BVP equations: {}",
error
));
} else {
snapshot.equation_rows = collect_bvp_preview_equation_rows(&reactor);
}
}
ProblemsEnum::None => {
snapshot.equation_build_error =
Some("Preview is only available for the BVP problem type.".to_string());
}
}
snapshot
}
pub(crate) fn format_bvp_task_preview(snapshot: &BvpTaskPreviewSnapshot) -> String {
let mut report = String::from("=== BVP TASK PREVIEW ===\n");
if snapshot.validation_report.is_valid() {
report.push_str("Validation: ok\n");
} else {
report.push_str("Validation issues:\n");
for issue in &snapshot.validation_report.issues {
report.push_str(&format!("- {issue}\n"));
}
}
report.push_str("--- Normalized document ---\n");
if snapshot.parameter_rows.is_empty() {
report.push_str("(no document fields to preview)\n");
} else {
report.push_str(&Table::new(snapshot.parameter_rows.clone()).to_string());
report.push('\n');
}
if let Some(error) = &snapshot.equation_build_error {
report.push_str(error);
report.push('\n');
}
report.push_str("--- Assembled equations ---\n");
if snapshot.equation_rows.is_empty() {
report.push_str("(no equations to preview)\n");
} else {
report.push_str(&Table::new(snapshot.equation_rows.clone()).to_string());
}
report
}
pub(crate) fn print_bvp_task_preview(snapshot: &BvpTaskPreviewSnapshot) {
let report = format_bvp_task_preview(snapshot);
println!("{report}");
info!("{}", report);
}
fn execute_bvp_calculation(mut document: DocumentMap, problem: ProblemsEnum) -> BvpWorkerOutcome {
if let Err(message) = normalize_bvp_usize_fields(&mut document) {
return BvpWorkerOutcome::Failed(format!("Calculation blocked: {message}"));
}
if let Err(message) = validate_aot_toolchain_fields(&document) {
return BvpWorkerOutcome::Failed(format!("Calculation blocked: {}", message));
}
match problem {
ProblemsEnum::BVPSimple => {
info!("Starting BVP Simple calculation in worker thread.");
let gui_plot = document
.get("postprocessing")
.and_then(|postproc| postproc.get("gui_plot"))
.and_then(|slot| slot.as_ref())
.and_then(|values| values.first())
.and_then(Value::as_boolean)
.unwrap_or(true);
let return_to_dimension = document
.get("postprocessing")
.and_then(|postproc| postproc.get("return_to_dimension"))
.and_then(|slot| slot.as_ref())
.and_then(|values| values.first())
.and_then(Value::as_boolean)
.unwrap_or(true);
let mut reactor = SimpleReactorTask::new();
if let Err(error) = reactor.solve_from_parsed(document) {
return BvpWorkerOutcome::Failed(format!("Calculation failed: {}", error));
}
if !gui_plot {
return BvpWorkerOutcome::Completed { plot: None };
}
let render_data = match reactor.solution_render_data() {
Ok(data) => data,
Err(error) => {
return BvpWorkerOutcome::Failed(format!(
"Calculation completed, but result extraction failed: {error}"
));
}
};
let values = render_data
.unknowns
.iter()
.map(|name| match (name.as_str(), return_to_dimension) {
("Teta", true) => "Temperature (K)".to_string(),
("Teta", false) => "Teta (dimensionless)".to_string(),
("q", true) => "q (W/m^2)".to_string(),
("q", false) => "q_hat (scaled)".to_string(),
(name, true) if name.starts_with('J') => {
format!("{name} (kg/(m^2 s))")
}
(name, false) if name.starts_with('J') => {
format!("J_hat{} (scaled)", &name[1..])
}
(name, _) if name.starts_with('C') => {
format!("{name} (mass fraction)")
}
_ => name.clone(),
})
.collect::<Vec<_>>();
if render_data.x_mesh.len() != render_data.solution.nrows() {
return BvpWorkerOutcome::Failed(format!(
"Solver result shape mismatch: mesh has {} points but solution has {} rows",
render_data.x_mesh.len(),
render_data.solution.nrows()
));
}
if values.len() != render_data.solution.ncols() {
return BvpWorkerOutcome::Failed(format!(
"Solver result shape mismatch: {} unknowns but solution has {} columns",
values.len(),
render_data.solution.ncols()
));
}
BvpWorkerOutcome::Completed {
plot: Some(BvpPlotData {
arg: if return_to_dimension {
render_data.arg_name
} else {
format!("{} / L", render_data.arg_name)
},
values,
x_mesh: render_data.x_mesh,
solution: render_data.solution,
}),
}
}
ProblemsEnum::None => BvpWorkerOutcome::Failed(
"No calculation is available for the current problem type.".to_string(),
),
}
}
pub struct CombustionApp {
pub document: DocumentMap,
pub new_field_names: HashMap<String, String>,
pub new_field_values: HashMap<String, String>,
new_species_name: String,
new_reaction_equation: String,
pub selected_problem: ProblemsEnum,
pub(super) active_bvp_tab: BvpEditorTab,
pub current_file_path: Option<std::path::PathBuf>,
pub(crate) document_lifecycle: DocumentLifecycleState,
pub show_help_window: bool,
pub current_help_info: String,
pub last_run_message: Option<String>,
pub last_run_is_error: bool,
pub plot_window: Option<PlotWindow>,
pub(crate) pending_aot_confirmation: Option<AotToolchainRequest>,
pub(crate) pending_document_load: Option<std::path::PathBuf>,
pub(crate) pending_document_deletion: Option<DocumentDeleteRequest>,
pub(crate) pending_window_close: bool,
pub(crate) pending_problem_switch: Option<ProblemsEnum>,
confirmed_aot_request: Option<AotToolchainRequest>,
pub(crate) calculation_state: CalculationState,
calculation_receiver: Option<mpsc::Receiver<BvpWorkerMessage>>,
calculation_cancel: Option<Arc<AtomicBool>>,
next_run_id: u64,
validation_fingerprint: Option<String>,
pub(crate) validation_report: BvpGuiValidationReport,
pub(crate) bvp_gui_config: BvpGuiConfig,
pub(crate) bvp_gui_migration_report: BvpGuiMigrationReport,
}
impl CombustionApp {
pub fn new() -> Self {
Self::new_with_problem(ProblemsEnum::BVPSimple)
}
pub fn document_to_string(&self) -> String {
let mut result = String::new();
let mut section_names = self.document.keys().collect::<Vec<_>>();
section_names.sort();
for section_name in section_names {
let section_data = &self.document[section_name];
if section_data.is_empty() {
continue;
}
result.push_str(section_name);
result.push('\n');
let mut field_names = section_data.keys().collect::<Vec<_>>();
field_names.sort();
for field_name in field_names {
let maybe_values = §ion_data[field_name];
if let Some(values) = maybe_values {
result.push_str(&format!(
"{}: {}\n",
field_name,
values_to_document_string(values)
));
} else {
result.push_str(&format!("{}: None\n", field_name));
}
}
}
result
}
fn render_bvp_structured_editor(
&mut self,
ui: &mut egui::Ui,
help_map: Option<&[(&str, &str)]>,
) {
let mut editor_document = self.document.clone();
ui.group(|ui| {
render_bvp_solver_backend_panel(
ui,
&mut editor_document,
help_map,
&mut self.current_help_info,
);
});
ui.add_space(8.0);
ui.group(|ui| {
ui.heading("Equation assembly");
ui.label("KiThe symbolic RHS construction");
let section = ensure_section_mut(&mut editor_document, "kithe_settings");
let selected = string_field_value(section, "symbolic_rhs_assembly_policy")
.unwrap_or_else(|| "auto".to_string());
let label = ui.label("Assembly parallelism");
let mut next = selected.clone();
let response = egui::ComboBox::from_id_salt("bvp_symbolic_rhs_assembly_policy")
.selected_text(match selected.as_str() {
"sequential" => "Sequential",
"parallel" => "Parallel",
_ => "Auto",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut next, "auto".to_string(), "Auto");
ui.selectable_value(&mut next, "sequential".to_string(), "Sequential");
ui.selectable_value(&mut next, "parallel".to_string(), "Parallel");
});
let help = "Controls KiThe's symbolic equation construction; Auto selects sequential or parallel assembly by system size.";
if response.response.hovered() || label.hovered() {
self.current_help_info = help.to_string();
}
let _ = response.response.labelled_by(label.id);
if next != selected {
set_string_field(section, "symbolic_rhs_assembly_policy", &next);
}
ui.label(help).on_hover_text(help);
});
ui.add_space(8.0);
let family = BvpGuiConfig::from_document(&editor_document).0.core.family;
let advanced_sections: &[&str] = match family {
BvpSolverFamily::Damped => BVP_SOLVER_ADVANCED_SECTIONS,
BvpSolverFamily::Frozen => &["strategy_params"],
BvpSolverFamily::Sci => &[],
BvpSolverFamily::CorrectionNewton => &["rel_tolerance"],
};
if !advanced_sections.is_empty() {
render_bvp_section_group(
ui,
"Advanced solver settings",
advanced_sections,
&mut editor_document,
help_map,
&mut self.current_help_info,
&mut self.new_field_names,
&mut self.new_field_values,
&mut self.pending_document_deletion,
false,
);
}
if family == BvpSolverFamily::Damped {
render_bvp_adaptive_grid_panel(
ui,
&mut editor_document,
help_map,
&mut self.current_help_info,
);
}
render_bvp_section_group(
ui,
"Initial guess",
BVP_INITIAL_GUESS_SECTIONS,
&mut editor_document,
help_map,
&mut self.current_help_info,
&mut self.new_field_names,
&mut self.new_field_values,
&mut self.pending_document_deletion,
false,
);
render_bvp_section_group(
ui,
"Postprocessing",
BVP_POSTPROCESSING_SECTIONS,
&mut editor_document,
help_map,
&mut self.current_help_info,
&mut self.new_field_names,
&mut self.new_field_values,
&mut self.pending_document_deletion,
false,
);
self.document = editor_document;
self.sync_document_state_after_edit();
}
fn show_document_deletion_confirmation(&mut self, ctx: &egui::Context) {
let Some(request) = self.pending_document_deletion.clone() else {
return;
};
let mut confirm = false;
let mut cancel = false;
egui::Window::new("Confirm BVP data deletion")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.label(format!(
"Delete {}? This may make the reactor task incomplete.",
request.description()
));
ui.horizontal(|ui| {
if ui.button("Cancel deletion").clicked() {
cancel = true;
}
if ui.button("Confirm deletion").clicked() {
confirm = true;
}
});
});
if cancel {
self.pending_document_deletion = None;
self.last_run_message =
Some("Deletion cancelled; document data was preserved.".to_string());
self.last_run_is_error = false;
} else if confirm {
let removed = apply_document_deletion(&mut self.document, &request);
self.pending_document_deletion = None;
if removed {
self.last_run_message = Some(format!("Deleted {}.", request.description()));
self.last_run_is_error = false;
} else {
self.last_run_message = Some(format!(
"Could not delete {}; it no longer exists.",
request.description()
));
self.last_run_is_error = true;
}
self.sync_document_state_after_edit();
}
}
fn show_document_load_confirmation(&mut self, ctx: &egui::Context) {
let Some(path) = self.pending_document_load.clone() else {
return;
};
let mut confirm = false;
let mut cancel = false;
egui::Window::new("Confirm task load")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.label(format!(
"Load {}? This will replace the current task state.",
path.display()
));
ui.label("Confirm only if you want to discard unsaved edits or running work.");
ui.horizontal(|ui| {
if ui.button("Cancel load").clicked() {
cancel = true;
}
if ui.button("Load task").clicked() {
confirm = true;
}
});
});
if cancel {
self.cancel_pending_document_load();
} else if confirm {
let _ = self.confirm_pending_document_load();
}
}
fn show_window_close_confirmation(&mut self, ctx: &egui::Context, open: &mut bool) {
if !self.pending_window_close {
return;
}
let mut confirm = false;
let mut cancel = false;
egui::Window::new("Confirm window close")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.label("Close the window and discard the current task state?");
ui.label("Confirm only if you do not need the unsaved changes anymore.");
ui.horizontal(|ui| {
if ui.button("Cancel close").clicked() {
cancel = true;
}
if ui.button("Close window").clicked() {
confirm = true;
}
});
});
if cancel {
self.cancel_pending_window_close();
*open = true;
} else if confirm {
if self.confirm_pending_window_close() {
*open = false;
}
} else {
*open = true;
}
}
fn show_problem_switch_confirmation(&mut self, ctx: &egui::Context) {
let Some(requested_problem) = self.pending_problem_switch.clone() else {
return;
};
let mut confirm = false;
let mut cancel = false;
egui::Window::new("Confirm problem switch")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.label(format!(
"Switching to {} will replace the current task state.",
requested_problem
));
ui.label("Confirm only if you want to discard the current edits or running work.");
ui.horizontal(|ui| {
if ui.button("Cancel switch").clicked() {
cancel = true;
}
if ui.button("Switch problem").clicked() {
confirm = true;
}
});
});
if cancel {
self.cancel_pending_problem_switch();
} else if confirm {
if self.confirm_pending_problem_switch() {
info!("Switched to problem type: {}", self.selected_problem);
}
}
}
pub fn new_with_problem(problem: ProblemsEnum) -> Self {
let document = match problem.get_problem() {
Some(template) => {
let mut parser = DocumentParser::new(template.to_string());
match parser.parse_document() {
Ok(_) => info!("Parsed BVP template successfully"),
Err(e) => warn!("Error parsing BVP template: {}", e),
}
parser.get_result().cloned().unwrap_or_else(HashMap::new)
}
None => HashMap::new(),
};
let (bvp_gui_config, bvp_gui_migration_report) = BvpGuiConfig::from_document(&document);
Self {
document,
new_field_names: HashMap::new(),
new_field_values: HashMap::new(),
new_species_name: String::new(),
new_reaction_equation: String::new(),
selected_problem: problem,
active_bvp_tab: BvpEditorTab::Physics,
current_file_path: None,
document_lifecycle: DocumentLifecycleState::default(),
show_help_window: false,
current_help_info: String::new(),
last_run_message: None,
last_run_is_error: false,
plot_window: None,
pending_aot_confirmation: None,
pending_document_load: None,
pending_document_deletion: None,
pending_window_close: false,
pending_problem_switch: None,
confirmed_aot_request: None,
calculation_state: CalculationState::Idle,
calculation_receiver: None,
calculation_cancel: None,
next_run_id: 1,
validation_fingerprint: None,
validation_report: BvpGuiValidationReport::default(),
bvp_gui_config,
bvp_gui_migration_report,
}
.with_seeded_defaults()
}
fn with_seeded_defaults(mut self) -> Self {
if matches!(self.selected_problem, ProblemsEnum::BVPSimple) {
seed_bvp_document_defaults(&mut self.document);
}
self.document_lifecycle
.mark_clean_snapshot(self.current_validation_fingerprint());
self.refresh_bvp_gui_snapshot();
self
}
pub fn show(&mut self, ctx: &egui::Context, open: &mut bool) {
self.poll_calculation_worker(ctx);
self.refresh_validation_report();
self.refresh_bvp_gui_snapshot();
let was_open = *open;
let mut window_open = *open;
egui::Window::new("Gas-phase combustion BVP")
.open(&mut window_open)
.default_size(ctx.content_rect().size())
.resizable(true)
.collapsible(true)
.show(ctx, |ui| {
ui.horizontal(|ui| {
egui::ComboBox::from_label("File")
.selected_text("File")
.show_ui(ui, |ui| {
if ui.button("💾 Save").clicked() {
if let Some(path) = &self.current_file_path {
let _ = self.save_document(path.clone());
} else {
if let Some(path) = rfd::FileDialog::new()
.add_filter("text", &["txt"])
.save_file()
{
let _ = self.save_document(path);
}
}
}
if ui.button("💾 Save As...").clicked() {
if let Some(path) = rfd::FileDialog::new()
.add_filter("text", &["txt"])
.save_file()
{
let _ = self.save_document(path);
}
}
if ui.button("❓ Help").clicked() {
self.show_help_window = true;
}
});
ui.separator();
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if self.calculation_state.is_active() {
let cancelling = matches!(
self.calculation_state,
CalculationState::Cancelling { .. }
);
if ui
.add_enabled(
!cancelling,
egui::Button::new("Cancel calculation"),
)
.clicked()
{
self.cancel_calculation();
}
}
if ui.button("📁 Read Task").clicked() {
if let Some(path) = rfd::FileDialog::new()
.add_filter("text", &["txt"])
.add_filter("all", &["*"])
.pick_file()
{
let _ = self.request_document_load(path);
}
}
});
});
ui.separator();
ui.add_space(10.0);
ui.label("Gas-phase combustion / steady-state plug-flow BVP");
let help_map = match self.selected_problem {
ProblemsEnum::BVPSimple => Some(FIELD_HELP_MAP_BVP),
ProblemsEnum::None => None,
};
if matches!(self.selected_problem, ProblemsEnum::BVPSimple) {
ui.horizontal(|ui| {
ui.selectable_value(
&mut self.active_bvp_tab,
BvpEditorTab::Physics,
"Physics",
);
ui.selectable_value(
&mut self.active_bvp_tab,
BvpEditorTab::Solver,
"Solver",
);
});
}
ui.separator();
ui.horizontal(|ui| {
ui.label("ℹ");
ui.style_mut().text_styles.insert(
egui::TextStyle::Body,
egui::FontId::new(14.0, egui::FontFamily::Proportional),
);
let help_width = (ui.available_width() - 30.0).max(0.0);
let display_text = if self.current_help_info.is_empty() {
"Hover over fields and sections for help information"
} else {
&self.current_help_info
};
ui.add_sized(
[help_width, 28.0],
egui::Label::new(
egui::RichText::new(display_text)
.color(egui::Color32::BLACK)
.size(14.0),
),
);
});
if !self.bvp_gui_migration_report.warnings.is_empty() {
ui.group(|ui| {
ui.colored_label(
egui::Color32::from_rgb(150, 110, 20),
"Compatibility notes",
);
for warning in &self.bvp_gui_migration_report.warnings {
ui.label(format!("- {warning}"));
}
});
ui.add_space(8.0);
}
ui.add_space(20.0);
let editor_height = (ui.available_height() - 160.0).max(120.0);
egui::ScrollArea::vertical()
.max_height(editor_height)
.show(ui, |ui| {
if matches!(self.selected_problem, ProblemsEnum::BVPSimple) {
if self.active_bvp_tab == BvpEditorTab::Physics {
let bvp_species_sections = bvp_species_section_names(&self.document);
let family = BvpGuiConfig::from_document(&self.document).0.core.family;
let mut physics_sections = BVP_PHYSICS_SECTIONS.to_vec();
physics_sections.retain(|section| *section != "reactions");
if family != BvpSolverFamily::Damped {
physics_sections.retain(|section| *section != "bounds");
}
render_bvp_section_group(
ui,
"Physics",
&physics_sections,
&mut self.document,
help_map,
&mut self.current_help_info,
&mut self.new_field_names,
&mut self.new_field_values,
&mut self.pending_document_deletion,
true,
);
ui.add_space(8.0);
render_bvp_species_manager(
ui,
&mut self.document,
&mut self.new_species_name,
&mut self.pending_document_deletion,
&mut self.last_run_message,
&mut self.last_run_is_error,
);
ui.add_space(8.0);
render_bvp_reaction_manager(
ui,
&mut self.document,
help_map,
&mut self.current_help_info,
&mut self.new_reaction_equation,
&mut self.pending_document_deletion,
&mut self.last_run_message,
&mut self.last_run_is_error,
);
ui.add_space(8.0);
render_bvp_dynamic_section_group(
ui,
"Atomic composition",
&bvp_species_sections,
&mut self.document,
help_map,
&mut self.current_help_info,
&mut self.new_field_names,
&mut self.new_field_values,
&mut self.pending_document_deletion,
true,
);
ui.add_space(8.0);
ui.add_space(12.0);
egui::CollapsingHeader::new("Legacy raw document")
.default_open(false)
.show(ui, |ui| {
let mut sections_to_process = Vec::new();
let mut sections_to_delete = Vec::new();
let mut fields_to_delete = Vec::new();
let section_names = sorted_document_section_names(&self.document);
for section_name in section_names {
if is_bvp_structured_section(section_name.as_str(), &bvp_species_sections)
{
continue;
}
let Some(section_data) = self.document.get_mut(§ion_name) else {
continue;
};
let field_name = self
.new_field_names
.entry(section_name.clone())
.or_insert_with(String::new);
let field_value = self
.new_field_values
.entry(section_name.clone())
.or_insert_with(String::new);
let (add_field, delete_section, requested_fields) = render_section(
ui,
§ion_name,
section_data,
field_name,
field_value,
help_map,
&mut self.current_help_info,
SectionRenderOptions::compatibility(false),
);
if add_field {
sections_to_process.push((
section_name.clone(),
field_name.clone(),
field_value.clone(),
));
}
if delete_section {
sections_to_delete.push(section_name.clone());
}
fields_to_delete.extend(
requested_fields
.into_iter()
.map(|field| (section_name.clone(), field)),
);
}
for section_name in sections_to_delete {
self.document.remove(§ion_name);
info!("Deleted section: {}", section_name);
}
for (section, field) in fields_to_delete {
let request = DocumentDeleteRequest::Field { section, field };
if apply_document_deletion(&mut self.document, &request) {
info!("Deleted optional {}", request.description());
}
}
for (section_name, field_name, field_value) in sections_to_process {
if !field_name.is_empty() {
let value = if field_value.parse::<f64>().is_ok() {
Value::Float(field_value.parse().unwrap())
} else if field_value.parse::<i64>().is_ok() {
Value::Integer(field_value.parse().unwrap())
} else if field_value == "true"
|| field_value == "false"
{
Value::Boolean(field_value.parse().unwrap())
} else {
Value::String(field_value.clone())
};
if let Some(section) = self.document.get_mut(§ion_name) {
match insert_field_if_absent(
section,
field_name.clone(),
value,
) {
Ok(()) => info!(
"Added field '{}' to section '{}' with value: {}",
field_name, section_name, field_value
),
Err(message) => warn!("{}", message),
}
}
self.new_field_names
.insert(section_name.clone(), String::new());
self.new_field_values
.insert(section_name, String::new());
}
}
});
} else {
self.render_bvp_structured_editor(ui, help_map);
}
} else {
let mut sections_to_process = Vec::new();
let mut sections_to_delete = Vec::new();
let mut fields_to_delete = Vec::new();
let section_names = sorted_document_section_names(&self.document);
for section_name in section_names {
let Some(section_data) = self.document.get_mut(§ion_name) else {
continue;
};
let field_name = self
.new_field_names
.entry(section_name.clone())
.or_insert_with(String::new);
let field_value = self
.new_field_values
.entry(section_name.clone())
.or_insert_with(String::new);
let (add_field, delete_section, requested_fields) = render_section(
ui,
§ion_name,
section_data,
field_name,
field_value,
help_map,
&mut self.current_help_info,
SectionRenderOptions::compatibility(false),
);
if add_field {
sections_to_process.push((
section_name.clone(),
field_name.clone(),
field_value.clone(),
));
}
if delete_section {
sections_to_delete.push(section_name.clone());
}
fields_to_delete.extend(
requested_fields
.into_iter()
.map(|field| (section_name.clone(), field)),
);
}
for section_name in sections_to_delete {
self.document.remove(§ion_name);
info!("Deleted section: {}", section_name);
}
for (section, field) in fields_to_delete {
let request = DocumentDeleteRequest::Field { section, field };
if apply_document_deletion(&mut self.document, &request) {
info!("Deleted optional {}", request.description());
}
}
for (section_name, field_name, field_value) in sections_to_process {
if !field_name.is_empty() {
let value = if field_value.parse::<f64>().is_ok() {
Value::Float(field_value.parse().unwrap())
} else if field_value.parse::<i64>().is_ok() {
Value::Integer(field_value.parse().unwrap())
} else if field_value == "true" || field_value == "false" {
Value::Boolean(field_value.parse().unwrap())
} else {
Value::String(field_value.clone())
};
if let Some(section) = self.document.get_mut(§ion_name) {
match insert_field_if_absent(
section,
field_name.clone(),
value,
) {
Ok(()) => info!(
"Added field '{}' to section '{}' with value: {}",
field_name, section_name, field_value
),
Err(message) => warn!("{}", message),
}
}
self.new_field_names
.insert(section_name.clone(), String::new());
self.new_field_values.insert(section_name, String::new());
}
}
}
self.sync_document_state_after_edit();
});
ui.separator();
ui.add_space(10.0);
self.refresh_document_lifecycle_dirty_state();
if self.document_lifecycle.dirty {
ui.colored_label(
egui::Color32::from_rgb(180, 120, 20),
"Unsaved changes",
);
ui.add_space(4.0);
}
if let Some(message) = self.document_lifecycle.last_status_text() {
let status_color = if self.document_lifecycle.last_status_is_error() {
egui::Color32::from_rgb(180, 30, 30)
} else {
egui::Color32::from_rgb(20, 120, 40)
};
ui.label(
egui::RichText::new(message)
.color(status_color)
.size(14.0),
);
ui.add_space(4.0);
}
if let Some(message) = &self.last_run_message {
let status_color = if self.last_run_is_error {
egui::Color32::from_rgb(180, 30, 30)
} else {
egui::Color32::from_rgb(20, 120, 40)
};
ui.label(
egui::RichText::new(message.as_str())
.color(status_color)
.size(14.0),
);
ui.add_space(4.0);
}
ui.with_layout(egui::Layout::top_down(egui::Align::Center), |ui| {
let calculation_active = self.calculation_state.is_active();
let task_valid = self.validation_report.is_valid();
if !task_valid {
ui.group(|ui| {
ui.colored_label(egui::Color32::from_rgb(180, 30, 30), "Task validation");
for issue in &self.validation_report.issues {
ui.label(format!("- {issue}"));
}
});
ui.add_space(4.0);
}
ui.horizontal_centered(|ui| {
if matches!(self.selected_problem, ProblemsEnum::BVPSimple) {
let preview_button = egui::Button::new("Preview Task")
.min_size(egui::Vec2::new(160.0, 50.0))
.fill(egui::Color32::from_rgb(140, 150, 180));
if ui.add_sized([160.0, 50.0], preview_button).clicked() {
self.preview_bvp_task();
}
ui.add_space(8.0);
}
let button = egui::Button::new("🚀 RUN CALCULATION!")
.min_size(egui::Vec2::new(200.0, 50.0))
.fill(egui::Color32::from_rgb(160, 160, 160));
if ui
.add_enabled_ui(!calculation_active && task_valid, |ui| {
ui.add_sized([200.0, 50.0], button)
})
.inner
.clicked()
{
self.request_calculation();
}
});
});
});
if was_open && !window_open && !self.request_window_close() {
window_open = true;
}
*open = window_open;
self.show_aot_confirmation(ctx);
self.show_document_load_confirmation(ctx);
self.show_window_close_confirmation(ctx, open);
self.show_document_deletion_confirmation(ctx);
self.show_problem_switch_confirmation(ctx);
if self.show_help_window {
egui::Window::new("Help")
.open(&mut self.show_help_window)
.resizable(true)
.default_size([600.0, 400.0])
.show(ctx, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| match self.selected_problem {
ProblemsEnum::BVPSimple => {
ui.style_mut().text_styles.insert(
egui::TextStyle::Body,
egui::FontId::new(14.0, egui::FontFamily::Proportional),
);
ui.colored_label(egui::Color32::BLACK, REACTOR_ENG_HELPER);
}
ProblemsEnum::None => {
ui.style_mut().text_styles.insert(
egui::TextStyle::Body,
egui::FontId::new(14.0, egui::FontFamily::Proportional),
);
ui.colored_label(
egui::Color32::BLACK,
"No help available for this problem type.",
);
}
});
});
}
if let Some(plot_window) = &mut self.plot_window {
plot_window.show(ctx);
if !plot_window.visible {
self.plot_window = None;
}
}
}
}
pub const FIELD_HELP_MAP_BVP: &[(&str, &str)] = &[
("initial_guess", "Initial guess values for the numerical solver. Controls starting values for iterative solution process."),
("process_conditions", "Main physical and chemical parameters defining the reactor problem setup."),
("boundary_condition", "Physical inlet mass fractions and temperature [K]; optional outlet q [W/m^2] and species_flux [kg/(m^2 s)]. Flux inputs are converted to solver coordinates."),
("diffusion_coefficients", "Molecular diffusion coefficients for each chemical substance [m²/s]."),
("reactions", "Chemical reactions with Arrhenius kinetic parameters [A, n, E, Q]."),
("solver_settings", "Structured solver backend controls. Residuals/Jacobian assembly is exclusive: choose Lambdify or AOT, then refine matrix and symbolic backends with explicit dropdowns."),
("kithe_settings.symbolic_rhs_assembly_policy", "KiThe symbolic RHS equation assembly policy. Auto selects sequential or parallel construction based on system size; Sequential and Parallel force that policy."),
("solver_settings.solver_family", "BVP solver family: Damped, Frozen/Naive, BVP_sci, or fixed-mesh CorrectionNewton. Each family exposes only its supported settings."),
("bounds", "Variable bounds for solver convergence. Format: lower_bound, upper_bound for each variable type."),
("rel_tolerance", "Relative convergence tolerances for each variable type in the numerical solver."),
("strategy_params", "Advanced solver strategy parameters for damped Newton-Raphson method."),
("adaptive_strategy", "Adaptive grid refinement settings for automatic mesh improvement."),
("grid_refinement", "Grid refinement method and parameters for mesh adaptation algorithms."),
("postprocessing", "Output and visualization options for results processing and data export."),
("initial_guess.universal", "Universal initial guess value applied to all variables and mesh points. Type: Float. Typical: 1e-2"),
("initial_guess.C", "Initial guess for concentration variables. Type: Float. Range: 0.0-1.0"),
("initial_guess.J", "Initial guess for flux variables. Type: Float."),
("initial_guess.Teta", "Initial guess for dimensionless temperature variables. Type: Float."),
("initial_guess.q", "Initial guess for the solver-coordinate heat-flux state q_hat. Type: Float; not a physical W/m^2 input."),
("process_conditions.problem_name", "Optional problem identifier for documentation. Type: Optional<String>. Example: Some(\"HMX_decomposition\")"),
("process_conditions.problem_description", "Optional detailed problem description. Type: Optional<String>. Example: Some(\"HMX thermal decomposition study\")"),
("process_conditions.substances", "List of chemical substances in the system. Type: Vec<String>. Example: H2O, CO2, N2"),
("process_conditions.density_model", "Gas-density closure. `ideal_gas_fixed_composition` is the default and varies density as rho(T) = rho0*T0/T at fixed pressure and reference composition. `constant` freezes density at rho0."),
("process_conditions.t0", "Start position in dimensionless coordinates. Type: Float. Recommended: 0.0"),
("process_conditions.t_end", "End position in dimensionless coordinates. Type: Float. Recommended: 1.0"),
("process_conditions.n_steps", "Initial number of grid points for spatial discretization. Type: Usize. Range: 10-1000. Higher = more accurate but slower.
\n if enabled grid refinement mesh points will be added so recommended number is 15-50"),
("process_conditions.arg", "Independent variable name (spatial coordinate). Type: String. Typical: x, z, t"),
("process_conditions.Tm", "Maximum temperature in reaction zone [K]. All parameters like ro, D, etc. are calculated at this
temperature. Type: Float. Range: 300-3000K."),
("process_conditions.L", "Characteristic length scale [m]. Type: Float. Range: 1e-6 to 1e-4. Should span complete reaction zone"),
("process_conditions.dT", "Temperature difference for scaling [K]. Type: Float. Range: 100-2000K. Usually equals or slightly less then
\n intitial temperature (temperature from boundary condition)"),
("process_conditions.T_scale", "Temperature scaling factor [K]. Type: Float. Usually equals to Tm - dT. Used in dimensionless equations"),
("process_conditions.P", "System pressure [Pa]. Type: Float. Range: 1e3-1e8 Pa. Affects reaction rates and transport"),
("process_conditions.Cp", "Specific heat capacity [J/kg/K]. Type: Float. Material property for energy balance"),
("process_conditions.Lambda", "Thermal conductivity [W/m/K]. Type: Float. Controls heat conduction"),
("process_conditions.m", "Mass flux per unit area [kg/(m²·s)]. Type: Float. Range: 1e-6 to 1e3. This is not total mass flow [kg/s]."),
("process_conditions.M", "Average molar mass [kg/mol]. Type: Float. Used in gas law calculations"),
("process_conditions.thermal_effects", "Heat of reaction for each reaction [J/mol]. Type: Vec<Float>. Positive=exothermic, Negative=endothermic"),
("process_conditions.groups", "Enable custom atomic group definitions. Type: Boolean. true=use custom groups, false=standard elements"),
("boundary_condition.T", "Initial/boundary temperature [K]. Type: Float. Range: 200-2000K. Starting temperature of the system"),
("solver_settings.scheme", "Spatial discretization scheme. Type: String. Options: forward, trapezoid. forward remains the lightest-weight route."),
("solver_settings.method", "Linear algebra backend. Type: String. Options: Banded, Sparse. This is the canonical matrix-storage selector."),
("solver_settings.strategy", "Convergence strategy. Type: String. Options: Damped, Frozen, Naive. Damped remains the robust default."),
("solver_settings.execution", "Symbolic callback execution route. Options: lambdify or aot. AOT-specific fields are shown only for AOT."),
("solver_settings.assembly", "Symbolic expression frontend. Options: atom_view_native or expr_legacy."),
("solver_settings.matrix_layout", "Linear-system matrix layout. Supported options depend on the selected solver family."),
("solver_settings.absolute_tolerance", "CorrectionNewton absolute weighted-correction tolerance."),
("solver_settings.default_relative_tolerance", "CorrectionNewton relative tolerance used for states without an explicit rel_tolerance entry."),
("solver_settings.max_jacobian_age", "Maximum number of Newton steps for which CorrectionNewton reuses the Jacobian."),
("solver_settings.max_damping_trials", "Maximum damping trials per CorrectionNewton iteration."),
("solver_settings.banded_lower", "Lower bandwidth for BVP_sci when matrix_layout is banded."),
("solver_settings.banded_upper", "Upper bandwidth for BVP_sci when matrix_layout is banded."),
("solver_settings.tolerance", "Route-specific convergence tolerance. Used by Frozen and BVP_sci; Damped uses abs_tolerance."),
("solver_settings.boundary_tolerance", "BVP_sci boundary residual tolerance. Defaults to the solver's route default when omitted."),
("solver_settings.max_nodes", "Maximum collocation mesh nodes for BVP_sci."),
("solver_settings.max_newton_iterations", "Maximum Newton iterations for BVP_sci collocation."),
("solver_settings.max_jacobian_refreshes", "Maximum Jacobian refreshes during a BVP_sci solve."),
("solver_settings.max_mesh_refinements", "Maximum adaptive mesh refinements in BVP_sci."),
("solver_settings.max_backtracking_steps", "Maximum backtracking steps per BVP_sci nonlinear iteration."),
("solver_settings.execution_policy", "BVP_sci callback execution policy: sequential, parallel, or auto. Defaults to sequential."),
("solver_settings.execution_min_work", "Minimum callback work used by BVP_sci parallel/auto execution policies; requires execution_policy."),
("solver_settings.output_policy", "BVP_sci solution output selection policy."),
("solver_settings.sparse_factorization", "Sparse factorization backend for BVP_sci sparse matrix layout."),
("solver_settings.lambdify_execution_policy", "Damped Lambdify callback scheduling: sequential, parallel, or auto. Sequential remains the default."),
("solver_settings.lambdify_min_work", "Minimum work threshold for parallel/auto Damped Lambdify callbacks."),
("solver_settings.bvp_logging_mode", "Damped backend event logging: off, warnings, or detailed. Independent of log level and telemetry."),
("solver_settings.bvp_logging_max_events", "Maximum retained Damped backend log events when backend event logging is enabled."),
("solver_settings.linear_sys_method", "Optional linear-system override. Type: Optional<String>. Leave None for the default matrix-backend policy."),
("solver_settings.abs_tolerance", "Absolute convergence tolerance. Type: Float. Range: 1e-12 to 1e-3. Smaller=more accurate"),
("solver_settings.max_iterations", "Maximum solver iterations. Type: Usize. Range: 10-1000. Higher=more attempts to converge"),
("solver_settings.telemetry", "Internal solver telemetry. Type: String. Options: off, counters, timings, detailed. Defaults to off; logging is configured separately. A route may reject unsupported telemetry modes."),
("solver_settings.loglevel", "Common BVP text-logging level. Type: Optional<String>. Options: off, error, warn, info, debug; defaults to off."),
("solver_settings.generated_backend", "High-level solver preset used by the RustedSciThe backend. Type: String. Default: banded_lambdify."),
("solver_settings.matrix_backend", "Compatibility alias for solver_settings.method. The structured GUI synchronizes this field automatically."),
("solver_settings.backend_policy", "Derived execution policy from the visible backend selector. KiThe writes lambdify_only or aot_only automatically."),
("solver_settings.symbolic_backend", "Symbolic assembly backend. Type: String. Options: AtomView, ExprLegacy. AtomView is the default."),
("solver_settings.aot_codegen_backend", "AOT code generation backend. Type: String. Options: C, Rust, Zig. Only visible when the execution backend is AOT."),
("solver_settings.aot_c_compiler", "C compiler choice, visible only for the C codegen backend. Type: String. Options: tcc, gcc."),
("solver_settings.aot_build_policy", "AOT build lifecycle policy. Type: String. Options: use_if_available, build_if_missing, require_prebuilt, rebuild_always."),
("solver_settings.aot_build_profile", "AOT build profile. Type: String. Options: release, debug. Used only with build_if_missing or rebuild_always."),
("solver_settings.aot_output_dir", "Optional parent directory for generated BVP_sci AOT artifacts. Empty leaves the RST default unchanged."),
("solver_settings.aot_handoff_path", "Optional durable registry handoff path for process-isolated AOT artifact publication."),
("solver_settings.aot_crate_name", "Optional override for the generated Rust crate name."),
("solver_settings.aot_module_name", "Optional override for the generated module name."),
("solver_settings.aot_residual_chunking", "BVP_sci AOT residual grouping: whole, target_chunks, or output_count."),
("solver_settings.aot_residual_chunk_size", "Positive target chunk count or maximum outputs per residual chunk; required except when chunking is whole."),
("solver_settings.aot_sparse_jacobian_chunking", "Sparse Jacobian grouping: whole, target_chunks, nnz, or rows. Shown for sparse and automatic matrix layouts."),
("solver_settings.aot_sparse_jacobian_chunk_size", "Positive target count, nonzero-entry cap, or row count for sparse Jacobian chunks; required except when chunking is whole."),
("solver_settings.aot_banded_jacobian_chunking", "Banded Jacobian grouping: whole, target_chunks, or diagonals. Shown for banded and automatic matrix layouts."),
("solver_settings.aot_banded_jacobian_chunk_size", "Positive target count or diagonal count for banded Jacobian chunks; required except when chunking is whole."),
("solver_settings.aot_compile_preset", "AOT compile preset. Type: String. Options: production, fast_build, dev_fastest."),
("solver_settings.aot_execution_policy", "Runtime execution policy for compiled callbacks. Type: String. Options: auto, sequential, parallel."),
("solver_settings.aot_residual_target_chunks", "Optional positive target chunk count for Damped AOT residual generation. Leave Override off to use the RST default."),
("solver_settings.aot_jacobian_target_chunks", "Optional positive target chunk count for Damped AOT Jacobian generation. Leave Override off to use the RST default."),
("solver_settings.banded_linear_solver", "Banded linear solver policy. Type: String. Options: auto, faithful, block_tridiagonal, block_tridiagonal_consistent, faer_sparse, general_partial_pivot."),
("solver_settings.refinement_steps", "Iterative refinement steps for the banded linear solver. Type: Usize. Default: 5. Set 0 to disable extra refinement."),
("bounds.C", "Concentration variable bounds [lower, upper]. Type: Vec<Float>. Example: -10.0, 10.0. Prevents unphysical values"),
("bounds.J", "Flux variable bounds [lower, upper]. Type: Vec<Float>. Example: -1e20, 1e20. Wide bounds for numerical stability"),
("bounds.Teta", "Temperature variable bounds [lower, upper]. Type: Vec<Float>. Example: -100.0, 100.0. Dimensionless temperature limits"),
("bounds.q", "Heat flux variable bounds [lower, upper]. Type: Vec<Float>. Example: -1e20, 1e20. Energy flux constraints"),
("rel_tolerance.C", "Relative tolerance for concentration variables. Type: Float. Range: 1e-12 to 1e-3. Controls convergence precision"),
("rel_tolerance.J", "Relative tolerance for flux variables. Type: Float. Range: 1e-12 to 1e-3. Smaller=stricter convergence"),
("rel_tolerance.Teta", "Relative tolerance for temperature variables. Type: Float. Range: 1e-12 to 1e-3. Temperature convergence criterion"),
("rel_tolerance.q", "Relative tolerance for heat flux variables. Type: Float. Range: 1e-12 to 1e-3. Energy balance precision"),
("strategy_params.max_jac", "Maximum Jacobian matrix updates per iteration. Type: Optional<Integer>. Range: 1-10. Higher=more accurate but slower"),
("strategy_params.max_damp_iter", "Maximum damping iterations for convergence. Type: Optional<Integer>. Range: 1-50. Controls step size reduction"),
("strategy_params.damp_factor", "Damping factor for step size control. Type: Optional<Float>. Range: 0.1-0.9. Smaller=more conservative steps"),
("adaptive_strategy.version", "Grid refinement contract version. KiThe currently supports and seeds version 1 automatically."),
("adaptive_strategy.max_refinements", "Maximum number of refinement iterations. Type: Integer. Range: 1-10. More=finer final mesh"),
("grid_refinement.grcar_smooke", "Grcar-Smooke refinement parameters [tol1, tol2, factor]. Type: Vec<Float>. Controls mesh adaptation sensitivity"),
("grid_refinement.pearson", "Pearson refinement parameters [tol, factor]. Type: Vec<Float>. Alternative mesh refinement method"),
("grid_refinement.twopnt", "Two-point refinement parameters [tol1, tol2, factor]. Type: Vec<Float>. Boundary layer focused refinement"),
("grid_refinement.easy", "Simple refinement parameter [factor]. Type: Vec<Float>. Basic uniform refinement"),
("grid_refinement.double_points", "Double points refinement (no parameters). Type: Vec<Float>. Simple point doubling method"),
("postprocessing.gnuplot", "Generate gnuplot visualization files. Type: Boolean. true=create plots, false=no plotting"),
("postprocessing.save_to_csv", "Export results to CSV format. Type: Boolean. true=save CSV files, false=no CSV export"),
("postprocessing.filename", "Output filename prefix for saved files. Type: String. Used for all output file naming"),
("postprocessing.plot", "Generate native Rust plots. Type: Boolean. true=create internal plots, false=no native plotting"),
("postprocessing.save", "Save results to text files. Type: Boolean. true=save text output, false=no text files"),
("postprocessing.return_to_dimension", "Convert results back to dimensional units. Type: Boolean. true=dimensional output, false=dimensionless"),
("postprocessing.no_plots_in_terminal", "Disable terminal plot output. Type: Boolean. true=no terminal plots, false=show in terminal"),
];