From 93d8408a715fa85f7e0e26e939c1644e939795ed Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 31 Oct 2026 23:23:00 +0100 Subject: [PATCH 01/40] Flamelet: controlling variable roles from their names The names in CONTROLLING_VARIABLE_NAMES (ProgressVariable, EnthalpyTot, MixtureFraction) now set the role of each transported scalar, replacing the fixed positions I_PROGVAR, I_ENTH and I_MIXFRAC. EnthalpyTot is required together with ProgressVariable, MixtureFraction or both, so pure non-premixed (MixtureFraction, EnthalpyTot) manifolds are supported. - Table axes follow the order of the names; the third name is the level. - Without a progress variable the thickened flame correction is off and FLAME_FRONT initializes the mixture fraction, as before. - Preferential diffusion looks up only the beta terms of present variables. - The inlet profile template writes one column per controlling variable. Results are identical to develop for flamelet cases 01, 03, 05, 06, 07, 09 and the laminar diffusion flame tutorial. Co-Authored-By: Claude Opus 5.5 --- Common/include/option_structure.hpp | 16 ++--- Common/src/CConfig.cpp | 27 +++++++++ SU2_CFD/include/fluid/CFluidFlamelet.hpp | 3 +- .../numerics/species/flamelet_edge_flux.hpp | 28 ++++----- .../solvers/CSpeciesFlameletSolver.hpp | 4 +- SU2_CFD/src/fluid/CFluidFlamelet.cpp | 30 +++++----- SU2_CFD/src/solvers/CSolver.cpp | 9 ++- .../src/solvers/CSpeciesFlameletSolver.cpp | 59 ++++++++++--------- config_template.cfg | 5 +- 9 files changed, 108 insertions(+), 73 deletions(-) diff --git a/Common/include/option_structure.hpp b/Common/include/option_structure.hpp index 73b6b81e29e4..dc997fe824d1 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1525,14 +1525,13 @@ static const MapType Species_Model_Map = { }; /*! - * \brief Progress variable and enthalpy are the first and second entries in the lookup table. - * \note The order matters. + * \brief Names of the flamelet controlling variables in CONTROLLING_VARIABLE_NAMES; the name sets the role. */ -enum FLAMELET_SCALAR_VARIABLES { - I_PROGVAR, - I_ENTH, - I_MIXFRAC, -}; +namespace FLAMELET_CV_NAME { + constexpr const char* PROGVAR = "ProgressVariable"; + constexpr const char* ENTHALPY = "EnthalpyTot"; + constexpr const char* MIXFRAC = "MixtureFraction"; +} /*! * \brief the source terms for the flamelet method. At the moment only progress variable @@ -1607,6 +1606,9 @@ struct FluidFlamelet_ParsedOptions { unsigned short n_user_scalars = 0; /*!< \brief Number of user defined (auxiliary) scalar transport equations. */ unsigned short n_user_sources = 0; /*!< \brief Number of source terms for user defined (auxiliary) scalar transport equations. */ unsigned short n_control_vars = 0; /*!< \brief Number of controlling variables (independent variables) for the LUT. */ + int idx_progvar = -1; /*!< \brief Scalar index of the progress variable, -1 if absent. */ + int idx_enth = -1; /*!< \brief Scalar index of the total enthalpy. */ + int idx_mixfrac = -1; /*!< \brief Scalar index of the mixture fraction, -1 if absent. */ std::string *controlling_variable_names; /*!< \brief Names of the independent, transported scalars. */ std::string* cv_source_names; /*!< \brief Names of the source terms of the independent, transported scalars. */ diff --git a/Common/src/CConfig.cpp b/Common/src/CConfig.cpp index f2b171c9571f..47dab52611e5 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -6109,6 +6109,33 @@ void CConfig::SetPostprocessing(SU2_COMPONENT val_software, unsigned short val_i /*--- We can have additional user defined transported scalars ---*/ flamelet_ParsedOptions.n_scalars = flamelet_ParsedOptions.n_control_vars + flamelet_ParsedOptions.n_user_scalars; + /*--- The name of each controlling variable sets its role. ---*/ + auto& opts = flamelet_ParsedOptions; + for (int iCV = 0; iCV < opts.n_control_vars; iCV++) { + const string& name = opts.controlling_variable_names[iCV]; + int* idx = nullptr; + if (name == FLAMELET_CV_NAME::PROGVAR) idx = &opts.idx_progvar; + else if (name == FLAMELET_CV_NAME::ENTHALPY) idx = &opts.idx_enth; + else if (name == FLAMELET_CV_NAME::MIXFRAC) idx = &opts.idx_mixfrac; + else + SU2_MPI::Error("Unknown controlling variable " + name + ", expected " + + FLAMELET_CV_NAME::PROGVAR + ", " + FLAMELET_CV_NAME::ENTHALPY + " or " + + FLAMELET_CV_NAME::MIXFRAC + ".", CURRENT_FUNCTION); + if (*idx >= 0) + SU2_MPI::Error("Controlling variable " + name + " is listed twice.", + CURRENT_FUNCTION); + *idx = iCV; + } + if (opts.idx_enth < 0) + SU2_MPI::Error(string("CONTROLLING_VARIABLE_NAMES must include ") + FLAMELET_CV_NAME::ENTHALPY + ".", + CURRENT_FUNCTION); + if (opts.idx_progvar < 0 && opts.idx_mixfrac < 0) + SU2_MPI::Error(string("CONTROLLING_VARIABLE_NAMES must include ") + FLAMELET_CV_NAME::PROGVAR + " or " + + FLAMELET_CV_NAME::MIXFRAC + ".", CURRENT_FUNCTION); + + /*--- The thickened flame correction measures the progress variable gradient. ---*/ + if (opts.idx_progvar < 0) opts.thickenedflame_correction = false; + /*--- Check that spark ignition has required parameters defined ---*/ if (flamelet_ParsedOptions.ignition_method == FLAMELET_INIT_TYPE::SPARK) { /*--- Check if SPARK_INIT was explicitly set in config file ---*/ diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index 88b2e6603ee6..4b9d4c6e63cf 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -48,8 +48,7 @@ class CFluidFlamelet final : public CFluidModel { su2double beta_progvar, beta_enth_thermal, beta_enth, beta_mixfrac; int rank; - bool include_mixture_fraction = false, /*!< \brief include mixture fraction in controlling variables. */ - preferential_diffusion = false; /*!< \brief use preferential diffusion physics. */ + bool preferential_diffusion = false; /*!< \brief use preferential diffusion physics. */ unsigned short n_scalars, n_lookups, n_user_scalars, /*!< \brief number of passive reactant species. */ n_control_vars; /*!< \brief number of controlling variables. */ diff --git a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index dba70c948816..0d58cf2df681 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -50,7 +50,9 @@ class CScalarFlux_Flamelet final explicit CScalarFlux_Flamelet(const CConfig& config) : Base(config), preferentialDiffusion(config.GetFlameletParsedOptions().preferential_diffusion), - nControlVars(config.GetFlameletParsedOptions().n_control_vars) {} + nControlVars(config.GetFlameletParsedOptions().n_control_vars), + idxProgVar(config.GetFlameletParsedOptions().idx_progvar), + idxEnth(config.GetFlameletParsedOptions().idx_enth) {} /*! * \brief Preferential diffusion, two terms with the shape of the ordinary diffusion but of @@ -114,8 +116,6 @@ class CScalarFlux_Flamelet final } /*--- Thermal term, on the enthalpy equation alone, driven by the temperature gradient. ---*/ - if (nControlVars <= I_ENTH) return; - const Double T_i = gatherVariables(iPoint, side_i.flowNodes->GetPrimitive(), idx.Temperature()); const Double T_j = gatherVariables(jPoint, side_j.flowNodes->GetPrimitive(), idx.Temperature()); @@ -123,33 +123,29 @@ class CScalarFlux_Flamelet final const auto gradT_j = gatherVariables(jPoint, side_j.flowNodes->GetGradient_Primitive(), idx.Temperature()); const Double Dth_i = gatherVariables(iPoint, side_i.scalarNodes.GetAuxVar(), I_BETA_ENTH_THERMAL) * - gatherVariables(iPoint, side_i.scalarNodes.GetDiffusivity(), I_ENTH); + gatherVariables(iPoint, side_i.scalarNodes.GetDiffusivity(), idxEnth); const Double Dth_j = gatherVariables(jPoint, side_j.scalarNodes.GetAuxVar(), I_BETA_ENTH_THERMAL) * - gatherVariables(jPoint, side_j.scalarNodes.GetDiffusivity(), I_ENTH); + gatherVariables(jPoint, side_j.scalarNodes.GetDiffusivity(), idxEnth); const Double Dth = 0.5 * (rho.i * Dth_i + rho.j * Dth_j) + diffTurb; const Double projGradT = projectedGradient(opt, gradT_i, gradT_j, T_i, T_j, normal, vector_ij, dist2_ij); - res.flux_i(I_ENTH) -= Dth * projGradT; - if (!opt.oneSided) res.flux_j(I_ENTH) += Dth * projGradT; + res.flux_i(idxEnth) -= Dth * projGradT; + if (!opt.oneSided) res.flux_j(idxEnth) += Dth * projGradT; } private: const bool preferentialDiffusion; const unsigned short nControlVars; + const int idxProgVar, idxEnth; /*! * \brief Auxiliary variable holding the beta scalar of a controlling variable. */ - static FORCEINLINE unsigned short betaIndex(unsigned short iScalar) { - switch (iScalar) { - case I_PROGVAR: - return I_BETA_PROGVAR; - case I_ENTH: - return I_BETA_ENTH; - default: - return I_BETA_MIXFRAC; - } + FORCEINLINE unsigned short betaIndex(int iScalar) const { + if (iScalar == idxProgVar) return I_BETA_PROGVAR; + if (iScalar == idxEnth) return I_BETA_ENTH; + return I_BETA_MIXFRAC; } /*! diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index 7543d6d7f282..ee184202a7e9 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -41,7 +41,9 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { const su2double default_flame_thickness{1.0}; su2double global_flame_thickness; bool calc_flame_thickness{false}; - bool include_mixture_fraction = false; /*!< \brief include mixture fraction as a controlling variable. */ + int idx_progvar = -1; /*!< \brief Scalar index of the progress variable, -1 if absent. */ + int idx_enth = -1; /*!< \brief Scalar index of the total enthalpy. */ + int idx_flame_front = -1; /*!< \brief Scalar set by FLAME_FRONT: progress variable, else mixture fraction. */ /*!< \brief Number of points outside the manifold domain, shared across OpenMP threads so it can be * accumulated atomically and reduced by the master thread alone in Preprocessing. */ unsigned long n_not_in_domain_local = 0; diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index f142da539175..d9daf90ea6d8 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -44,7 +44,6 @@ CFluidFlamelet::CFluidFlamelet(CConfig* config, su2double value_pressure_operati /* -- number of auxiliary species transport equations, e.g. 1=CO, 2=NOx --- */ n_user_scalars = flamelet_options.n_user_scalars; n_control_vars = flamelet_options.n_control_vars; - include_mixture_fraction = (n_control_vars == 3); n_scalars = flamelet_options.n_scalars; if (rank == MASTER_NODE) { @@ -78,8 +77,8 @@ CFluidFlamelet::CFluidFlamelet(CConfig* config, su2double value_pressure_operati cout << "*** initializing the lookup table ***" << endl; cout << "*****************************************" << endl; } - look_up_table = new CLookUpTable(datadriven_fluid_options.datadriven_filenames[0], table_scalar_names[I_PROGVAR], - table_scalar_names[I_ENTH]); + look_up_table = new CLookUpTable(datadriven_fluid_options.datadriven_filenames[0], table_scalar_names[0], + table_scalar_names[1]); break; default: @@ -122,7 +121,7 @@ CFluidFlamelet::~CFluidFlamelet() { void CFluidFlamelet::SetTDState_h(su2double val_enthalpy, const su2double* val_scalars) { /*--- For the fluid flamelet model, the enthalpy (and the temperature) are passive scalars. - val_scalars contains the enthalpy as the second variable: val_scalars= (Progress_variable, enthalpy,...). + val_scalars contains the enthalpy at the index of EnthalpyTot in CONTROLLING_VARIABLE_NAMES. Consequently, the energy equation is not solved when the fluid flamelet model is used; instead the energy equation for enthalpy is solved in the species flamelet solver, and the enthalpy solution is overwritten in the CIncEulerSolver. Likewise, The temperature is retrieved from the look up table. Then, the thermodynamics state is fully determined with @@ -137,7 +136,7 @@ void CFluidFlamelet::SetTDState_T(su2double val_temperature, const su2double* va /*--- Add all quantities and their names to the look up vectors. ---*/ EvaluateDataSet(scalars_vector, FLAMELET_LOOKUP_OPS::THERMO, val_vars_TD); - Enthalpy = scalars_vector[1]; + Enthalpy = scalars_vector[flamelet_options.idx_enth]; Temperature = val_vars_TD[LOOKUP_TD::TEMPERATURE]; Cp = val_vars_TD[LOOKUP_TD::HEATCAPACITY]; Mu = val_vars_TD[LOOKUP_TD::VISCOSITY]; @@ -216,10 +215,11 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { varnames_PD.resize(FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS); val_vars_PD.resize(FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS); - varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_PROGVAR] = "Beta_ProgVar"; + /*--- Beta scalars of absent controlling variables are not in the manifold. ---*/ + varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_PROGVAR] = (flamelet_options.idx_progvar >= 0) ? "Beta_ProgVar" : "NULL"; varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH_THERMAL] = "Beta_Enth_Thermal"; varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH] = "Beta_Enth"; - varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_MIXFRAC] = "Beta_MixFrac"; + varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_MIXFRAC] = (flamelet_options.idx_mixfrac >= 0) ? "Beta_MixFrac" : "NULL"; val_vars_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_PROGVAR] = beta_progvar; val_vars_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH_THERMAL] = beta_enth_thermal; @@ -268,7 +268,8 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { } if (preferential_diffusion) { for (auto iVar = 0u; iVar < varnames_PD.size(); iVar++) { - LUT_idx_PD.push_back(look_up_table->GetIndexOfVar(varnames_PD[iVar])); + LUT_idx_PD.push_back(noSource(varnames_PD[iVar]) ? look_up_table->GetNullIndex() + : look_up_table->GetIndexOfVar(varnames_PD[iVar])); } } } @@ -279,9 +280,10 @@ unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_sca AD::StartPreacc(); for (auto iVar = 0u; iVar < input_scalar.size(); iVar++) AD::SetPreaccIn(input_scalar[iVar]); - su2double val_enth = input_scalar[I_ENTH]; - su2double val_prog = input_scalar[I_PROGVAR]; - su2double val_mixfrac = include_mixture_fraction ? input_scalar[I_MIXFRAC] : 0.0; + /*--- The table axes follow the order of the controlling variables, the third one is the table level. ---*/ + const su2double val_cv1 = input_scalar[0]; + const su2double val_cv2 = input_scalar[1]; + const su2double val_cv3 = (n_control_vars == 3) ? input_scalar[2] : 0.0; vector val_vars; vector refs_vars; vector LUT_idx; @@ -320,10 +322,10 @@ unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_sca case ENUM_DATADRIVEN_METHOD::LUT: if (output_refs.size() != LUT_idx.size()) SU2_MPI::Error(string("Output vector size incompatible with manifold lookup operation."), CURRENT_FUNCTION); - if (include_mixture_fraction) { - inside = look_up_table->LookUp_XYZ(LUT_idx, output_refs, val_prog, val_enth, val_mixfrac); + if (n_control_vars == 3) { + inside = look_up_table->LookUp_XYZ(LUT_idx, output_refs, val_cv1, val_cv2, val_cv3); } else { - inside = look_up_table->LookUp_XY(LUT_idx, output_refs, val_prog, val_enth); + inside = look_up_table->LookUp_XY(LUT_idx, output_refs, val_cv1, val_cv2); } break; case ENUM_DATADRIVEN_METHOD::MLP: diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 19f07df2e598..b36fac00d48f 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -3948,9 +3948,12 @@ void CSolver::LoadInletProfile(CGeometry **geometry, break; case SPECIES_MODEL::FLAMELET: { const auto& flamelet_config_options = config->GetFlameletParsedOptions(); - /*--- 2-equation flamelet model ---*/ - columnName << left << setw(24) << "PROGRESSVAR" << left << setw(24) << "ENTHALPYTOT"; - columnValue << config->GetInlet_SpeciesVal(Marker_Tag)[0] << "\t" << config->GetInlet_SpeciesVal(Marker_Tag)[1] <<"\t"; + for (unsigned short iCV = 0; iCV < flamelet_config_options.n_control_vars; iCV++) { + string cv_name = flamelet_config_options.controlling_variable_names[iCV]; + transform(cv_name.begin(), cv_name.end(), cv_name.begin(), ::toupper); + columnName << left << setw(24) << cv_name; + columnValue << config->GetInlet_SpeciesVal(Marker_Tag)[iCV] << "\t"; + } /*--- auxiliary species transport equations ---*/ for (unsigned short iReactant = 0; iReactant < flamelet_config_options.n_user_scalars; iReactant++) { columnName << left << setw(24) << flamelet_config_options.user_scalar_names[iReactant]; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 9fdf81663b4e..0130ef69ac67 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -48,7 +48,9 @@ CSpeciesFlameletSolver::CSpeciesFlameletSolver(CGeometry* geometry, CConfig* con /*--- Dimension of the problem. ---*/ nVar = flamelet_config_options.n_scalars; - include_mixture_fraction = (flamelet_config_options.n_control_vars == 3); + idx_progvar = flamelet_config_options.idx_progvar; + idx_enth = flamelet_config_options.idx_enth; + idx_flame_front = (idx_progvar >= 0) ? idx_progvar : flamelet_config_options.idx_mixfrac; Initialize(geometry, config, iMesh, nVar); @@ -214,7 +216,7 @@ void CSpeciesFlameletSolver::SetInitialCondition(CGeometry** geometry, CSolver** } const su2double temp_inlet = config->GetInc_Temperature_Init(); - su2double enth_inlet = config->GetSpecies_Init()[I_ENTH]; + su2double enth_inlet = config->GetSpecies_Init()[idx_enth]; su2double prog_burnt = 0, prog_unburnt, point_loc; su2double scalar_init[MAXNVAR]= {0.0}; @@ -254,11 +256,11 @@ void CSpeciesFlameletSolver::SetInitialCondition(CGeometry** geometry, CSolver** /*--- Set enthalpy based on initial temperature and scalars. ---*/ n_not_iterated_local += GetEnthFromTemp(fluid_model_local, temp_inlet, config->GetSpecies_Init(), &enth_inlet); - scalar_init[I_ENTH] = enth_inlet; + scalar_init[idx_enth] = enth_inlet; if (flame_front_ignition) prog_burnt = GetBurntProgressVariable(fluid_model_local, scalar_init, flamelet_config_options.Flame_T_ignition); - prog_unburnt = config->GetSpecies_Init()[I_PROGVAR]; + prog_unburnt = config->GetSpecies_Init()[idx_flame_front]; const auto nPoint_iMesh = geometry[i_mesh]->GetnPoint(); SU2_OMP_FOR_STAT(omp_chunk_size) for (unsigned long i_point = 0; i_point < nPoint_iMesh; i_point++) { @@ -277,26 +279,26 @@ void CSpeciesFlameletSolver::SetInitialCondition(CGeometry** geometry, CSolver** /* --- Unburnt region upstream of the flame. --- */ if (point_loc <= 0) { - scalar_init[I_PROGVAR] = prog_unburnt; + scalar_init[idx_flame_front] = prog_unburnt; n_points_unburnt_local++; /* --- Flame zone where we lineary increase from unburnt to burnt conditions. --- */ } else if ((point_loc > 0) && (point_loc <= flame_thickness)) { - scalar_init[I_PROGVAR] = prog_unburnt + point_loc * (prog_burnt - prog_unburnt) / flame_thickness; + scalar_init[idx_flame_front] = prog_unburnt + point_loc * (prog_burnt - prog_unburnt) / flame_thickness; n_points_flame_local++; /* --- Burnt region behind the flame zone. --- */ } else if ((point_loc > flame_thickness) && (point_loc <= flame_thickness + flame_burnt_thickness)) { - scalar_init[I_PROGVAR] = prog_burnt; + scalar_init[idx_flame_front] = prog_burnt; n_points_burnt_local++; /* --- Unburnt region downstream of the flame and burnt region. --- */ } else { - scalar_init[I_PROGVAR] = prog_unburnt; + scalar_init[idx_flame_front] = prog_unburnt; n_points_unburnt_local++; } } else { - scalar_init[I_PROGVAR] = prog_unburnt; + scalar_init[idx_flame_front] = prog_unburnt; } /* --- Perform manifold evaluation to check whether initial scalar is out-of-bounds. --- */ fluid_model_local->SetTDState_T(temp_inlet, scalar_init); @@ -490,7 +492,7 @@ void CSpeciesFlameletSolver::BC_HeatFlux_Wall(CGeometry* geometry, CSolver** sol /*--- Neumann condition: q_wall is the prescribed heat flux (W/m^2, positive into domain). This adds a source term dH/dn * lambda = q_wall to the enthalpy residual. ---*/ - LinSysRes(iPoint, I_ENTH) -= Wall_HeatFlux * Area; + LinSysRes(iPoint, idx_enth) -= Wall_HeatFlux * Area; } END_SU2_OMP_FOR } @@ -511,12 +513,12 @@ void CSpeciesFlameletSolver::BC_Inlet(CGeometry* geometry, CSolver** solver_cont } else { /*--- Use the enthalpy value directly from MARKER_INLET_SPECIES (default). The user is responsible for providing a thermodynamically consistent value. ---*/ - enth_inlet = config->GetInlet_SpeciesVal(Marker_Tag)[I_ENTH]; + enth_inlet = config->GetInlet_SpeciesVal(Marker_Tag)[idx_enth]; } SU2_OMP_FOR_STAT(OMP_MIN_SIZE) for (auto iVertex = 0u; iVertex < geometry->nVertex[val_marker]; iVertex++) { - Inlet_SpeciesVars[val_marker][iVertex][I_ENTH] = enth_inlet; + Inlet_SpeciesVars[val_marker][iVertex][idx_enth] = enth_inlet; } END_SU2_OMP_FOR @@ -550,7 +552,7 @@ void CSpeciesFlameletSolver::BC_Isothermal_Wall_Generic(CGeometry* geometry, CSo if (geometry->nodes->GetDomain(iPoint)) { if (config->GetMarker_StrongBC(Marker_Tag)) { /*--- Initial guess for enthalpy value. ---*/ - enth_wall = nodes->GetSolution(iPoint, I_ENTH); + enth_wall = nodes->GetSolution(iPoint, idx_enth); /*--- Set enthalpy on the wall. ---*/ n_not_iterated += GetEnthFromTemp(fluid_model_local, temp_wall, nodes->GetSolution(iPoint), &enth_wall); @@ -559,15 +561,15 @@ void CSpeciesFlameletSolver::BC_Isothermal_Wall_Generic(CGeometry* geometry, CSo condition (Dirichlet) and remove any contribution to the residual at this node. ---*/ - nodes->SetSolution(iPoint, I_ENTH, enth_wall); - nodes->SetSolution_Old(iPoint, I_ENTH, enth_wall); + nodes->SetSolution(iPoint, idx_enth, enth_wall); + nodes->SetSolution_Old(iPoint, idx_enth, enth_wall); - LinSysRes(iPoint, I_ENTH) = 0.0; + LinSysRes(iPoint, idx_enth) = 0.0; - nodes->SetVal_ResTruncError_Zero(iPoint, I_ENTH); + nodes->SetVal_ResTruncError_Zero(iPoint, idx_enth); if (implicit) { - Jacobian.DeleteValsRowi(iPoint, I_ENTH); + Jacobian.DeleteValsRowi(iPoint, idx_enth); } } else { /*--- Weak BC formulation. ---*/ @@ -597,7 +599,7 @@ void CSpeciesFlameletSolver::BC_Isothermal_Wall_Generic(CGeometry* geometry, CSo /*--- Apply a weak boundary condition for the energy equation. Compute the residual due to the prescribed heat flux. ---*/ - LinSysRes(iPoint, I_ENTH) -= thermal_conductivity * dTdn * Area; + LinSysRes(iPoint, idx_enth) -= thermal_conductivity * dTdn * Area; } } } @@ -641,10 +643,9 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF vector table_sources(flamelet_config_options.n_control_vars + 2 * flamelet_config_options.n_user_scalars); unsigned long misses = fluid_model_local->EvaluateDataSet(scalars, FLAMELET_LOOKUP_OPS::SOURCES, table_sources); - table_sources[I_PROGVAR] = fmax(0, table_sources[I_PROGVAR]); - nodes->SetTableMisses(iPoint, misses); - /*--- The source term for progress variable is always positive, we clip from below to make sure. --- */ + if (idx_progvar >= 0) table_sources[idx_progvar] = fmax(0, table_sources[idx_progvar]); + nodes->SetTableMisses(iPoint, misses); vector source_scalar(flamelet_config_options.n_scalars); for (auto iCV = 0u; iCV < flamelet_config_options.n_control_vars; iCV++) source_scalar[iCV] = table_sources[iCV]; @@ -715,7 +716,7 @@ unsigned long CSpeciesFlameletSolver::GetEnthFromTemp(CFluidModel* fluid_model, SU2_ZONE_SCOPED /*--- convergence criterion for temperature in [K], high accuracy needed for restarts. ---*/ su2double delta_temp_final = 0.001; - su2double enth_iter = scalar_solution[I_ENTH]; + su2double enth_iter = scalar_solution[idx_enth]; su2double delta_enth; su2double delta_temp_iter = 1e10; unsigned long exit_code = 0; @@ -730,7 +731,7 @@ unsigned long CSpeciesFlameletSolver::GetEnthFromTemp(CFluidModel* fluid_model, while ((abs(delta_temp_iter) > delta_temp_final) && (counter++ < counter_limit)) { /*--- Add all quantities and their names to the look up vectors. ---*/ - val_scalars[I_ENTH] = enth_iter; + val_scalars[idx_enth] = enth_iter; fluid_model->SetTDState_T(val_temp, val_scalars); su2double Temperature = fluid_model->GetTemperature(); @@ -758,14 +759,14 @@ su2double CSpeciesFlameletSolver::GetBurntProgressVariable(CFluidModel* fluid_mo su2double scalars[MAXNVAR], delta = 1e-3; for (auto iVar = 0u; iVar < nVar; iVar++) scalars[iVar] = scalar_solution[iVar]; bool outside = false; - scalars[I_PROGVAR] += delta; + scalars[idx_flame_front] += delta; while (!outside) { /*--- Note that 300.0 is a dummy temperature here and not used. ---*/ fluid_model->SetTDState_T(300.0, scalars); if ((fluid_model->GetExtrapolation() == 1) || fluid_model->GetTemperature() > T_ignition) outside = true; - scalars[I_PROGVAR] += delta; + scalars[idx_flame_front] += delta; } - su2double pv_burnt = scalars[I_PROGVAR] - delta; + su2double pv_burnt = scalars[idx_flame_front] - delta; if (rank == MASTER_NODE) { cout << "Burnt progress variable determined from flamelet table: " << pv_burnt << endl; cout << "Burnt temperature from flamelet table: " << fluid_model->GetTemperature() << endl; @@ -800,13 +801,13 @@ su2double CSpeciesFlameletSolver::GetOverallFlameThickness(CGeometry* geometry, SU2_OMP_FOR_(schedule(static,omp_chunk_size) SU2_NOWAIT) for (auto iPoint = 0u; iPoint < nPointDomain; iPoint++) { - su2double pv_local = nodes->GetSolution(iPoint, I_PROGVAR); + su2double pv_local = nodes->GetSolution(iPoint, idx_progvar); su2double T_local = solver_container[FLOW_SOL]->GetNodes()->GetTemperature(iPoint); /* Parallel projection of progress variable gradient against velocity */ su2double proj_grad_pv_u[MAXNDIM]={0}; for (auto iDim=0u; iDim < nDim; iDim++) { - su2double gradpv = nodes->GetGradient(iPoint, I_PROGVAR, iDim); + su2double gradpv = nodes->GetGradient(iPoint, idx_progvar, iDim); su2double val_u = flowNodes->GetVelocity(iPoint, iDim); proj_grad_pv_u[iDim] = gradpv * val_u * val_u / (flowNodes->GetVelocity2(iPoint) + EPS); } diff --git a/config_template.cfg b/config_template.cfg index 66d7b191879b..f63b472b0da8 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1049,7 +1049,10 @@ LOOKUP_NAMES= (MolarWeightMix, Conductivity, HeatRelease, Diffusivity) % Names of the controlling variables used to evaluate the look-up table and for which % transported scalar variables are generated. These names should coincide with those -% listed in the look-up table. +% listed in the look-up table. Accepted names are ProgressVariable, EnthalpyTot and +% MixtureFraction. EnthalpyTot is required, together with ProgressVariable (premixed), +% MixtureFraction (non-premixed) or both. The first two names are the table axes, +% the third one is the variable of the table levels. CONTROLLING_VARIABLE_NAMES= (ProgressVariable, EnthalpyTot) % Names of the source term variables as they are present in the look-up table. For From a7b87cf753fc72d00fff0f0322ce514884e86f76 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 31 Oct 2026 23:56:29 +0100 Subject: [PATCH 02/40] Flamelet: transport of progress variable and mixture fraction variance ProgressVariableVariance and MixtureFractionVariance in CONTROLLING_VARIABLE_NAMES are transported scalars that the manifold uses as a controlling variable, typically the table level of an assumed PDF table. Their source is the table entry in CONTROLLING_VARIABLE_SOURCE_NAMES plus the turbulent production 2 mu_t/Sc_t |grad(mean)|^2 and the dissipation C_d rho beta* omega var of the SST model, the latter implicit. - A variance requires its mean and KIND_TURB_MODEL= SST, is clipped at zero, and switches off the thickened flame correction; preferential diffusion is not available with it. - FLAMELET_VARIANCE_DISSIPATION_COEFF sets C_d (default 2.0). - The look-up table rejects more than three controlling variables. Co-Authored-By: Claude Opus 5.5 --- Common/include/option_structure.hpp | 5 +++ Common/src/CConfig.cpp | 27 +++++++++++-- .../solvers/CSpeciesFlameletSolver.hpp | 9 +++++ SU2_CFD/src/fluid/CFluidFlamelet.cpp | 2 + .../src/solvers/CSpeciesFlameletSolver.cpp | 39 +++++++++++++++++++ config_template.cfg | 13 +++++-- 6 files changed, 88 insertions(+), 7 deletions(-) diff --git a/Common/include/option_structure.hpp b/Common/include/option_structure.hpp index dc997fe824d1..463dab8f8c58 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1531,6 +1531,8 @@ namespace FLAMELET_CV_NAME { constexpr const char* PROGVAR = "ProgressVariable"; constexpr const char* ENTHALPY = "EnthalpyTot"; constexpr const char* MIXFRAC = "MixtureFraction"; + constexpr const char* PROGVAR_VAR = "ProgressVariableVariance"; + constexpr const char* MIXFRAC_VAR = "MixtureFractionVariance"; } /*! @@ -1609,6 +1611,9 @@ struct FluidFlamelet_ParsedOptions { int idx_progvar = -1; /*!< \brief Scalar index of the progress variable, -1 if absent. */ int idx_enth = -1; /*!< \brief Scalar index of the total enthalpy. */ int idx_mixfrac = -1; /*!< \brief Scalar index of the mixture fraction, -1 if absent. */ + int idx_progvar_var = -1; /*!< \brief Scalar index of the progress variable variance, -1 if absent. */ + int idx_mixfrac_var = -1; /*!< \brief Scalar index of the mixture fraction variance, -1 if absent. */ + su2double variance_dissipation_coeff = 2.0; /*!< \brief C_d in the variance dissipation C_d rho (eps/k) var. */ std::string *controlling_variable_names; /*!< \brief Names of the independent, transported scalars. */ std::string* cv_source_names; /*!< \brief Names of the source terms of the independent, transported scalars. */ diff --git a/Common/src/CConfig.cpp b/Common/src/CConfig.cpp index 47dab52611e5..635614c30bb3 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -1528,6 +1528,9 @@ void CConfig::SetConfig_Options() { /*!\brief FLAME_INIT_IGNITION \n DESCRIPTION: Ignition temperature for the flame initialization \ingroup Config*/ addDoubleOption("FLAME_INIT_IGNITION", flamelet_ParsedOptions.Flame_T_ignition, 5000.0); + /*!\brief FLAMELET_VARIANCE_DISSIPATION_COEFF \n DESCRIPTION: Coefficient C_d of the scalar variance dissipation C_d rho (eps/k) var \ingroup Config*/ + addDoubleOption("FLAMELET_VARIANCE_DISSIPATION_COEFF", flamelet_ParsedOptions.variance_dissipation_coeff, 2.0); + /*--- Options related to mass diffusivity and thereby the species solver. ---*/ /*!\brief DIFFUSIVITY_MODEL\n DESCRIPTION: mass diffusivity model \n DEFAULT constant disffusivity \ingroup Config*/ @@ -6117,10 +6120,13 @@ void CConfig::SetPostprocessing(SU2_COMPONENT val_software, unsigned short val_i if (name == FLAMELET_CV_NAME::PROGVAR) idx = &opts.idx_progvar; else if (name == FLAMELET_CV_NAME::ENTHALPY) idx = &opts.idx_enth; else if (name == FLAMELET_CV_NAME::MIXFRAC) idx = &opts.idx_mixfrac; + else if (name == FLAMELET_CV_NAME::PROGVAR_VAR) idx = &opts.idx_progvar_var; + else if (name == FLAMELET_CV_NAME::MIXFRAC_VAR) idx = &opts.idx_mixfrac_var; else - SU2_MPI::Error("Unknown controlling variable " + name + ", expected " + - FLAMELET_CV_NAME::PROGVAR + ", " + FLAMELET_CV_NAME::ENTHALPY + " or " + - FLAMELET_CV_NAME::MIXFRAC + ".", CURRENT_FUNCTION); + SU2_MPI::Error("Unknown controlling variable " + name + ", expected " + FLAMELET_CV_NAME::PROGVAR + ", " + + FLAMELET_CV_NAME::ENTHALPY + ", " + FLAMELET_CV_NAME::MIXFRAC + ", " + + FLAMELET_CV_NAME::PROGVAR_VAR + " or " + FLAMELET_CV_NAME::MIXFRAC_VAR + ".", + CURRENT_FUNCTION); if (*idx >= 0) SU2_MPI::Error("Controlling variable " + name + " is listed twice.", CURRENT_FUNCTION); @@ -6136,6 +6142,21 @@ void CConfig::SetPostprocessing(SU2_COMPONENT val_software, unsigned short val_i /*--- The thickened flame correction measures the progress variable gradient. ---*/ if (opts.idx_progvar < 0) opts.thickenedflame_correction = false; + /*--- A variance needs its mean and the turbulence time scale omega of the SST model. ---*/ + if ((opts.idx_progvar_var >= 0) && (opts.idx_progvar < 0)) + SU2_MPI::Error(string(FLAMELET_CV_NAME::PROGVAR_VAR) + " requires " + FLAMELET_CV_NAME::PROGVAR + ".", + CURRENT_FUNCTION); + if ((opts.idx_mixfrac_var >= 0) && (opts.idx_mixfrac < 0)) + SU2_MPI::Error(string(FLAMELET_CV_NAME::MIXFRAC_VAR) + " requires " + FLAMELET_CV_NAME::MIXFRAC + ".", + CURRENT_FUNCTION); + if ((opts.idx_progvar_var >= 0) || (opts.idx_mixfrac_var >= 0)) { + if (Kind_Turb_Model != TURB_MODEL::SST) + SU2_MPI::Error("Scalar variance transport requires KIND_TURB_MODEL= SST.", CURRENT_FUNCTION); + if (opts.preferential_diffusion) + SU2_MPI::Error("PREFERENTIAL_DIFFUSION is not available with scalar variance transport.", CURRENT_FUNCTION); + opts.thickenedflame_correction = false; + } + /*--- Check that spark ignition has required parameters defined ---*/ if (flamelet_ParsedOptions.ignition_method == FLAMELET_INIT_TYPE::SPARK) { /*--- Check if SPARK_INIT was explicitly set in config file ---*/ diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index ee184202a7e9..c9058ed1a98b 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -55,6 +55,15 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { */ void SetPreconditioner(CGeometry* geometry, CSolver** solver_container, CConfig* config); + /*! + * \brief Add the turbulent production 2 mu_t/Sc_t |grad(mean)|^2 and dissipation C_d rho beta* omega var + * of a scalar variance to the residual, the dissipation implicitly. + * \param[in] i_var - Scalar index of the variance. + * \param[in] i_mean - Scalar index of its mean. + */ + void ScalarVarianceResidual(CGeometry* geometry, CSolver** solver_container, const CConfig* config, int i_var, + int i_mean); + /*! * \brief Generic implementation of the isothermal wall also covering CHT cases, * for which the wall temperature is given by GetConjugateHeatVariable. diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index d9daf90ea6d8..a42fe2be7553 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -72,6 +72,8 @@ CFluidFlamelet::CFluidFlamelet(CConfig* config, su2double value_pressure_operati switch (Kind_DataDriven_Method) { case ENUM_DATADRIVEN_METHOD::LUT: + if (n_control_vars > 3) + SU2_MPI::Error("The look-up table supports at most three controlling variables.", CURRENT_FUNCTION); if (rank == MASTER_NODE) { cout << "*****************************************" << endl; cout << "*** initializing the lookup table ***" << endl; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 0130ef69ac67..f091e62ca03b 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -54,6 +54,10 @@ CSpeciesFlameletSolver::CSpeciesFlameletSolver(CGeometry* geometry, CConfig* con Initialize(geometry, config, iMesh, nVar); + /*--- A variance cannot become negative. ---*/ + for (const int i_var : {flamelet_config_options.idx_progvar_var, flamelet_config_options.idx_mixfrac_var}) + if (i_var >= 0) lowerlimit[i_var] = max(lowerlimit[i_var], su2double(0.0)); + /*--- Initialize the solution to the far-field state everywhere. ---*/ nodes = new CSpeciesFlameletVariable(Solution_Inf, nPoint, nDim, nVar, config); @@ -451,11 +455,46 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv } END_SU2_OMP_FOR + if (flamelet_config_options.idx_progvar_var >= 0) + ScalarVarianceResidual(geometry, solver_container, config, flamelet_config_options.idx_progvar_var, idx_progvar); + if (flamelet_config_options.idx_mixfrac_var >= 0) + ScalarVarianceResidual(geometry, solver_container, config, flamelet_config_options.idx_mixfrac_var, + flamelet_config_options.idx_mixfrac); + /*--- call the species solver for the shared sources (axisymmetric and custom python source term) ---*/ CSpeciesSolver::Source_Residual(geometry, solver_container, numerics_container, config, iMesh); } +void CSpeciesFlameletSolver::ScalarVarianceResidual(CGeometry* geometry, CSolver** solver_container, + const CConfig* config, int i_var, int i_mean) { + SU2_ZONE_SCOPED + + const bool implicit = (config->GetKind_TimeIntScheme() == EULER_IMPLICIT); + const su2double Sc_t = config->GetSchmidt_Number_Turbulent(); + const su2double C_d = flamelet_config_options.variance_dissipation_coeff; + const su2double beta_star = solver_container[TURB_SOL]->GetConstants()[6]; + const auto* flowNodes = su2staticcast_p(solver_container[FLOW_SOL]->GetNodes()); + const auto* turbNodes = solver_container[TURB_SOL]->GetNodes(); + + SU2_OMP_FOR_STAT(omp_chunk_size) + for (auto i_point = 0u; i_point < nPointDomain; i_point++) { + const su2double volume = geometry->nodes->GetVolume(i_point); + + su2double grad_mean2 = 0.0; + for (auto iDim = 0u; iDim < nDim; iDim++) grad_mean2 += pow(nodes->GetGradient(i_point, i_mean, iDim), 2); + const su2double production = 2.0 * flowNodes->GetEddyViscosity(i_point) / Sc_t * grad_mean2; + + /*--- Decay rate C_d eps/k with eps/k = beta* omega; the unknown is rho*var. ---*/ + const su2double decay = C_d * beta_star * turbNodes->GetSolution(i_point, 1); + const su2double rho_var = flowNodes->GetDensity(i_point) * nodes->GetSolution(i_point, i_var); + + LinSysRes(i_point, i_var) -= (production - decay * rho_var) * volume; + if (implicit) Jacobian.AddVal2Diag(i_point, i_var, decay * volume); + } + END_SU2_OMP_FOR +} + void CSpeciesFlameletSolver::BC_HeatFlux_Wall(CGeometry* geometry, CSolver** solver_container, CNumerics* conv_numerics, CNumerics* visc_numerics, CConfig* config, unsigned short val_marker) { diff --git a/config_template.cfg b/config_template.cfg index f63b472b0da8..e4e7076ca005 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1049,10 +1049,11 @@ LOOKUP_NAMES= (MolarWeightMix, Conductivity, HeatRelease, Diffusivity) % Names of the controlling variables used to evaluate the look-up table and for which % transported scalar variables are generated. These names should coincide with those -% listed in the look-up table. Accepted names are ProgressVariable, EnthalpyTot and -% MixtureFraction. EnthalpyTot is required, together with ProgressVariable (premixed), -% MixtureFraction (non-premixed) or both. The first two names are the table axes, -% the third one is the variable of the table levels. +% listed in the look-up table. Accepted names are ProgressVariable, EnthalpyTot, +% MixtureFraction, ProgressVariableVariance and MixtureFractionVariance. EnthalpyTot is +% required, together with ProgressVariable (premixed), MixtureFraction (non-premixed) or +% both. A variance requires its mean and KIND_TURB_MODEL= SST. The first two names are the +% table axes, the third one is the variable of the table levels. CONTROLLING_VARIABLE_NAMES= (ProgressVariable, EnthalpyTot) % Names of the source term variables as they are present in the look-up table. For @@ -1118,6 +1119,10 @@ SPARK_REACTION_RATES= (1000, 0, 0) % Approximate the thickness of the flame and suppress source terms and enhance diffusivity in cells with a lengthscale higher % than the flame thickness. THICKENED_FLAME_CORRECTION= YES +% +% Coefficient C_d of the dissipation C_d rho (eps/k) var of a transported scalar variance, +% with eps/k = beta* omega from the SST model. The production is 2 mu_t/Sc_t |grad(mean)|^2. +FLAMELET_VARIANCE_DISSIPATION_COEFF= 2.0 % Flame ignition temperature % Flame thickness calculations are performed when the maximum temperature in the flow solution exceeds this value. From f68c403f1a4af22420569d4e8d26c2b92427fd69 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Mon, 2 Nov 2026 19:20:22 +0100 Subject: [PATCH 03/40] Flamelet: bound the scalar variances, density factor in the auxiliary Jacobian A transported variance is limited to (mean - min)(max - mean), the variance of a two-point distribution on the range of its mean. The range is [0, 1] for the mixture fraction and the range of the table axis (or of the network input scaling) for the progress variable. The species solver solves for the increment of rho*Y, so the implicit Jacobian of the auxiliary-species source is source_cons / rho, not source_cons. The reference value of cfd_flamelet_ch4_cht changes in one residual by 4e-5. Co-Authored-By: Claude Sonnet 5.5 --- Common/include/containers/CLookUpTable.hpp | 7 ++++ Common/src/containers/CLookUpTable.cpp | 14 ++++++++ SU2_CFD/include/fluid/CFluidFlamelet.hpp | 7 ++++ SU2_CFD/include/fluid/CFluidModel.hpp | 9 +++++ .../solvers/CSpeciesFlameletSolver.hpp | 10 ++++++ SU2_CFD/src/fluid/CFluidFlamelet.cpp | 10 ++++++ .../src/solvers/CSpeciesFlameletSolver.cpp | 36 +++++++++++++++++-- TestCases/parallel_regression.py | 2 +- config_template.cfg | 4 ++- 9 files changed, 94 insertions(+), 5 deletions(-) diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index e455dd1f12d1..d5d8d5ea9be5 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -386,6 +386,13 @@ class CLookUpTable { return limits_table_x[i_level]; } + /*! + * \brief Minimum and maximum of a table coordinate over all table levels. + * \param[in] i_axis - Coordinate: 0 (first CV), 1 (second CV) or 2 (table level). + * \returns Pair of minimum and maximum value. + */ + std::pair GetTableRange(unsigned short i_axis) const; + /*! * \brief Check whether requested set of variables are included in the table. */ diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 05586d39585c..921f39f99292 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -153,6 +153,20 @@ void CLookUpTable::LoadTableRaw(const string& var_file_name_lut) { if (rank == MASTER_NODE) cout << " done." << endl; } +pair CLookUpTable::GetTableRange(unsigned short i_axis) const { + if (i_axis == 2) { + if (table_dim != 3) SU2_MPI::Error("The look-up table has no third coordinate.", CURRENT_FUNCTION); + return {*limits_table_z.first, *limits_table_z.second}; + } + const auto& limits = (i_axis == 0) ? limits_table_x : limits_table_y; + su2double lower = *limits[0].first, upper = *limits[0].second; + for (auto i_level = 1u; i_level < n_table_levels; i_level++) { + lower = min(lower, *limits[i_level].first); + upper = max(upper, *limits[i_level].second); + } + return {lower, upper}; +} + void CLookUpTable::FindTableLimits(const string& name_cv1, const string& name_cv2) { limits_table_x.resize(n_table_levels); limits_table_y.resize(n_table_levels); diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index 4b9d4c6e63cf..bf5c4384ac59 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -134,6 +134,13 @@ class CFluidFlamelet final : public CFluidModel { unsigned long EvaluateDataSet(const vector& input_scalar, unsigned short lookup_type, vector& output_refs); + /*! + * \brief Range of a controlling variable in the look-up table, or in the training data of the networks. + * \param[in] i_cv - Index of the controlling variable. + * \returns Pair of minimum and maximum value. + */ + std::pair GetControllingVariableRange(unsigned short i_cv) const override; + /*! * \brief Check for out-of-bounds condition for data set interpolation. * \return - within bounds (0) or out of bounds (1). diff --git a/SU2_CFD/include/fluid/CFluidModel.hpp b/SU2_CFD/include/fluid/CFluidModel.hpp index af9aa3e059b7..6903d0cb0a78 100644 --- a/SU2_CFD/include/fluid/CFluidModel.hpp +++ b/SU2_CFD/include/fluid/CFluidModel.hpp @@ -161,6 +161,15 @@ class CFluidModel { return 0; } + /*! + * \brief Range of a controlling variable covered by the data set. + * \param[in] i_cv - Index of the controlling variable. + * \returns Pair of minimum and maximum value. + */ + virtual std::pair GetControllingVariableRange(unsigned short i_cv) const { + return {-1.0e15, 1.0e15}; + } + /*! * \brief Get fluid dynamic viscosity. */ diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index c9058ed1a98b..71499522b84e 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -53,6 +53,16 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { * \param[in] solver_container - Container vector with all the solutions. * \param[in] config - Definition of the particular problem. */ + /*! + * \brief Limit the scalar variances to the maximum of a two-point distribution on the range of their mean. + * \param[in] geometry - Geometrical definition of the problem. + * \param[in] solver_container - Container vector with all the solutions. + * \param[in] config - Definition of the particular problem. + * \param[in] iMesh - Index of the mesh in multigrid computations. + */ + void Postprocessing(CGeometry* geometry, CSolver** solver_container, CConfig* config, + unsigned short iMesh) override; + void SetPreconditioner(CGeometry* geometry, CSolver** solver_container, CConfig* config); /*! diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index a42fe2be7553..474716860566 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -277,6 +277,16 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { } } +pair CFluidFlamelet::GetControllingVariableRange(unsigned short i_cv) const { + if (Kind_DataDriven_Method == ENUM_DATADRIVEN_METHOD::LUT) return look_up_table->GetTableRange(i_cv); +#ifdef USE_MLPCPP + const auto norm = iomap_TD->GetInputNorm(controlling_variable_names[i_cv]); + return {norm.first, norm.second}; +#else + return CFluidModel::GetControllingVariableRange(i_cv); +#endif +} + unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_scalar, unsigned short lookup_type, vector& output_refs) { AD::StartPreacc(); diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index f091e62ca03b..0db0c49d7381 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -425,6 +425,34 @@ void CSpeciesFlameletSolver::SetPreconditioner(CGeometry* geometry, CSolver** so END_SU2_OMP_FOR } +void CSpeciesFlameletSolver::Postprocessing(CGeometry* geometry, CSolver** solver_container, CConfig* config, + unsigned short iMesh) { + SU2_ZONE_SCOPED + + struct VarianceBound { + int i_var, i_mean; + su2double lower, upper; + }; + vector bounds; + if (flamelet_config_options.idx_progvar_var >= 0) { + const auto range = solver_container[FLOW_SOL]->GetFluidModel()->GetControllingVariableRange(idx_progvar); + bounds.push_back({flamelet_config_options.idx_progvar_var, idx_progvar, range.first, range.second}); + } + if (flamelet_config_options.idx_mixfrac_var >= 0) + bounds.push_back({flamelet_config_options.idx_mixfrac_var, flamelet_config_options.idx_mixfrac, 0.0, 1.0}); + + /*--- var <= (mean - lower) (upper - mean) for a variable bounded by lower and upper. ---*/ + SU2_OMP_FOR_STAT(omp_chunk_size) + for (auto i_point = 0u; i_point < nPoint; i_point++) { + for (const auto& bound : bounds) { + const su2double mean = nodes->GetSolution(i_point, bound.i_mean); + const su2double max_var = max((mean - bound.lower) * (bound.upper - mean), su2double(0.0)); + if (nodes->GetSolution(i_point, bound.i_var) > max_var) nodes->SetSolution(i_point, bound.i_var, max_var); + } + } + END_SU2_OMP_FOR +} + void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solver_container, CNumerics** numerics_container, CConfig* config, unsigned short iMesh) { SU2_ZONE_SCOPED @@ -433,10 +461,12 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv const auto n_CV = flamelet_config_options.n_control_vars; const auto n_aux = flamelet_config_options.n_user_scalars; const auto* fn = static_cast(nodes); + const auto* flowNodes = solver_container[FLOW_SOL]->GetNodes(); SU2_OMP_FOR_STAT(omp_chunk_size) for (auto i_point = 0u; i_point < nPointDomain; i_point++) { const su2double volume = geometry->nodes->GetVolume(i_point); + const su2double density = flowNodes->GetDensity(i_point); /*--- Add source terms from the lookup table directly to the residual. ---*/ for (auto i_var = 0; i_var < nVar; i_var++) { @@ -445,11 +475,11 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv /*--- Implicit: analytic Jacobian for auxiliary species from the split source form. * S_aux_i = source_prod_i + source_cons_i * Y_aux_i - * dS_aux_i/dY_aux_i = source_cons_i - * J_ii += -source_cons_i * V ---*/ + * dS_aux_i/d(rho Y_aux_i) = source_cons_i / rho + * J_ii += -source_cons_i / rho * V ---*/ if (implicit) { for (auto i_aux = 0u; i_aux < n_aux; i_aux++) { - Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) * volume); + Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) / density * volume); } } } diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 381fdd75e312..b4bfcc759bdb 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -2035,7 +2035,7 @@ def main(): cfd_flamelet_ch4_cht.cfg_dir = "flamelet/03_laminar_premixed_ch4_flame_cht_cfd" cfd_flamelet_ch4_cht.cfg_file = "lam_prem_ch4_cht_cfd_master.cfg" cfd_flamelet_ch4_cht.test_iter = 5 - cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410156, -3.171365, -10.884464, -12.615132, -6.614396] + cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410156, -3.171365, -10.884424, -12.615132, -6.614396] cfd_flamelet_ch4_cht.timeout = 1600 cfd_flamelet_ch4_cht.multizone = True test_list.append(cfd_flamelet_ch4_cht) diff --git a/config_template.cfg b/config_template.cfg index e4e7076ca005..c3d54d0d5dd5 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1053,7 +1053,9 @@ LOOKUP_NAMES= (MolarWeightMix, Conductivity, HeatRelease, Diffusivity) % MixtureFraction, ProgressVariableVariance and MixtureFractionVariance. EnthalpyTot is % required, together with ProgressVariable (premixed), MixtureFraction (non-premixed) or % both. A variance requires its mean and KIND_TURB_MODEL= SST. The first two names are the -% table axes, the third one is the variable of the table levels. +% table axes, the third one is the variable of the table levels. A variance is limited to +% (mean - min)(max - mean), with the range of the mean taken from the table (progress +% variable) or equal to [0, 1] (mixture fraction). CONTROLLING_VARIABLE_NAMES= (ProgressVariable, EnthalpyTot) % Names of the source term variables as they are present in the look-up table. For From 749a9c3a554eaed1965567f740d545ec4d4c93ea Mon Sep 17 00:00:00 2001 From: bigfooted Date: Mon, 2 Nov 2026 21:19:41 +0100 Subject: [PATCH 04/40] Flamelet: normalized variance in the manifold, combined variance source, restart by name The look-up table and the networks take each variance normalized by its upper limit (mean - min)(max - mean). The mixture fraction is bounded by 0 and 1, the progress variable by the manifold variables ProgressVariableMin and ProgressVariableMax. The conversion is done in CFluidFlamelet before every look-up, and the variance clip uses the same limit. This replaces the global table and network input ranges. The source of a variance is formed from the manifold variable mean(phi*S_phi) as 2 (mean(phi*S_phi) - mean(phi) mean(S_phi)); a NULL name gives no source. The flamelet restart is read by field name, and a variance missing from the restart file starts from its initial value. The MLP look-up query is paired also for a single look-up variable. Co-Authored-By: Claude Opus 5.5 --- Common/include/containers/CLookUpTable.hpp | 7 - Common/include/option_structure.hpp | 9 ++ Common/src/containers/CLookUpTable.cpp | 14 -- SU2_CFD/include/fluid/CFluidFlamelet.hpp | 40 ++++-- SU2_CFD/include/fluid/CFluidModel.hpp | 11 +- .../solvers/CSpeciesFlameletSolver.hpp | 1 + SU2_CFD/src/fluid/CFluidFlamelet.cpp | 133 +++++++++++++----- .../src/solvers/CSpeciesFlameletSolver.cpp | 36 ++--- SU2_CFD/src/solvers/CSpeciesSolver.cpp | 39 ++++- config_template.cfg | 13 +- 10 files changed, 206 insertions(+), 97 deletions(-) diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index d5d8d5ea9be5..e455dd1f12d1 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -386,13 +386,6 @@ class CLookUpTable { return limits_table_x[i_level]; } - /*! - * \brief Minimum and maximum of a table coordinate over all table levels. - * \param[in] i_axis - Coordinate: 0 (first CV), 1 (second CV) or 2 (table level). - * \returns Pair of minimum and maximum value. - */ - std::pair GetTableRange(unsigned short i_axis) const; - /*! * \brief Check whether requested set of variables are included in the table. */ diff --git a/Common/include/option_structure.hpp b/Common/include/option_structure.hpp index 463dab8f8c58..f34726036935 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1535,6 +1535,14 @@ namespace FLAMELET_CV_NAME { constexpr const char* MIXFRAC_VAR = "MixtureFractionVariance"; } +/*! + * \brief Manifold variables giving the range of the progress variable, the support of its PDF. + */ +namespace FLAMELET_PROGVAR_BOUNDS { + constexpr const char* MIN = "ProgressVariableMin"; + constexpr const char* MAX = "ProgressVariableMax"; +} + /*! * \brief the source terms for the flamelet method. At the moment only progress variable */ @@ -1550,6 +1558,7 @@ enum FLAMELET_LOOKUP_OPS { PREFDIF, /*!< \brief Preferential diffusion scalars. */ SOURCES, /*!< \brief Scalar source terms (controlling variables, passive species).*/ LOOKUP, /*!< \brief Passive look-up variables specified in config. */ + PROGVAR_BOUNDS, /*!< \brief Minimum and maximum of the progress variable. */ }; /*! diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 921f39f99292..05586d39585c 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -153,20 +153,6 @@ void CLookUpTable::LoadTableRaw(const string& var_file_name_lut) { if (rank == MASTER_NODE) cout << " done." << endl; } -pair CLookUpTable::GetTableRange(unsigned short i_axis) const { - if (i_axis == 2) { - if (table_dim != 3) SU2_MPI::Error("The look-up table has no third coordinate.", CURRENT_FUNCTION); - return {*limits_table_z.first, *limits_table_z.second}; - } - const auto& limits = (i_axis == 0) ? limits_table_x : limits_table_y; - su2double lower = *limits[0].first, upper = *limits[0].second; - for (auto i_level = 1u; i_level < n_table_levels; i_level++) { - lower = min(lower, *limits[i_level].first); - upper = max(upper, *limits[i_level].second); - } - return {lower, upper}; -} - void CLookUpTable::FindTableLimits(const string& name_cv1, const string& name_cv2) { limits_table_x.resize(n_table_levels); limits_table_y.resize(n_table_levels); diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index bf5c4384ac59..664edfa6ffcc 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -67,7 +67,12 @@ class CFluidFlamelet final : public CFluidModel { vector LUT_idx_TD, LUT_idx_Sources, LUT_idx_LookUp, - LUT_idx_PD; + LUT_idx_PD, + LUT_idx_ProgVarBounds; + + vector manifold_inputs; /*!< \brief Controlling variables with the variances normalized. */ + su2double limit_progvar_var = 0, /*!< \brief Upper limit of the progress variable variance. */ + limit_mixfrac_var = 0; /*!< \brief Upper limit of the mixture fraction variance. */ /*--- Class variables for the multi-layer perceptron method ---*/ #ifdef USE_MLPCPP @@ -77,7 +82,7 @@ class CFluidFlamelet final : public CFluidModel { MLPToolbox::CIOMap* iomap_PD; /*!< \brief Input-output map for the preferential diffusion scalars. */ MLPToolbox::CIOMap* iomap_Sources; /*!< \brief Input-output map for species source terms. */ MLPToolbox::CIOMap* iomap_LookUp; /*!< \brief Input-output map for passive look-up terms. */ - MLPToolbox::CIOMap* iomap_Current; + MLPToolbox::CIOMap* iomap_ProgVarBounds; /*!< \brief Input-output map for the progress variable range. */ #endif vector scalars_vector; @@ -85,15 +90,33 @@ class CFluidFlamelet final : public CFluidModel { vector varnames_TD, /*!< \brief Lookup names for thermodynamic state variables. */ varnames_Sources, /*!< \brief Lookup names for source terms. */ varnames_LookUp, /*!< \brief Lookup names for passive look-up terms. */ - varnames_PD; /*!< \brief Lookup names for preferential diffusion scalars. */ + varnames_PD, /*!< \brief Lookup names for preferential diffusion scalars. */ + varnames_ProgVarBounds; /*!< \brief Lookup names for the minimum and maximum progress variable. */ vector val_vars_TD, /*!< \brief References to thermodynamic state variables. */ val_vars_Sources, /*!< \brief References to source terms. */ val_vars_LookUp, /*!< \brief References passive look-up terms. */ - val_vars_PD; /*!< \brief References to preferential diffusion scalars. */ + val_vars_PD, /*!< \brief References to preferential diffusion scalars. */ + val_vars_ProgVarBounds; /*!< \brief References to the minimum and maximum progress variable. */ void PreprocessLookUp(CConfig* config); + /*! + * \brief Interpolate the manifold, without normalizing the inputs. + * \param[in] lookup_type - Look-up operation to be performed (FLAMELET_LOOKUP_OPS). + * \param[in] inputs - Manifold inputs in the order of the controlling variables. + * \param[out] output_refs - Interpolated output variables. + * \returns Whether the query is inside the manifold. + */ + bool LookUpManifold(unsigned short lookup_type, const vector& inputs, vector& output_refs); + + /*! + * \brief Set manifold_inputs to the controlling variables, each variance divided by its upper limit. + * \param[in] scalars - Transported scalars. + * \returns Whether the look-up of the progress variable range is inside the manifold. + */ + bool SetManifoldInputs(const su2double* scalars); + /*! \brief * Returns true if the string is null or zero (ignores case). */ @@ -135,11 +158,12 @@ class CFluidFlamelet final : public CFluidModel { vector& output_refs); /*! - * \brief Range of a controlling variable in the look-up table, or in the training data of the networks. - * \param[in] i_cv - Index of the controlling variable. - * \returns Pair of minimum and maximum value. + * \brief Largest value a scalar variance can take, (mean - min)(max - mean) for its mean. + * \param[in] scalars - Transported scalars. + * \param[in] i_var - Index of the variance. + * \returns Upper limit of the variance. */ - std::pair GetControllingVariableRange(unsigned short i_cv) const override; + su2double GetScalarVarianceLimit(const su2double* scalars, unsigned short i_var) override; /*! * \brief Check for out-of-bounds condition for data set interpolation. diff --git a/SU2_CFD/include/fluid/CFluidModel.hpp b/SU2_CFD/include/fluid/CFluidModel.hpp index 6903d0cb0a78..47528e25ff39 100644 --- a/SU2_CFD/include/fluid/CFluidModel.hpp +++ b/SU2_CFD/include/fluid/CFluidModel.hpp @@ -162,13 +162,12 @@ class CFluidModel { } /*! - * \brief Range of a controlling variable covered by the data set. - * \param[in] i_cv - Index of the controlling variable. - * \returns Pair of minimum and maximum value. + * \brief Largest value a scalar variance can take, (mean - min)(max - mean) for its mean. + * \param[in] scalars - Transported scalars. + * \param[in] i_var - Index of the variance. + * \returns Upper limit of the variance. */ - virtual std::pair GetControllingVariableRange(unsigned short i_cv) const { - return {-1.0e15, 1.0e15}; - } + virtual su2double GetScalarVarianceLimit(const su2double* scalars, unsigned short i_var) { return 1.0e15; } /*! * \brief Get fluid dynamic viscosity. diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index 71499522b84e..80a75b6b26f2 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -44,6 +44,7 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { int idx_progvar = -1; /*!< \brief Scalar index of the progress variable, -1 if absent. */ int idx_enth = -1; /*!< \brief Scalar index of the total enthalpy. */ int idx_flame_front = -1; /*!< \brief Scalar set by FLAME_FRONT: progress variable, else mixture fraction. */ + vector> variance_sources; /*!< \brief Variance and mean indices of variances with a chemical source. */ /*!< \brief Number of points outside the manifold domain, shared across OpenMP threads so it can be * accumulated atomically and reduced by the master thread alone in Preprocessing. */ unsigned long n_not_in_domain_local = 0; diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index 474716860566..1e959fcae847 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -52,6 +52,7 @@ CFluidFlamelet::CFluidFlamelet(CConfig* config, su2double value_pressure_operati cout << "Number of control variables: " << n_control_vars << endl; } scalars_vector.resize(n_scalars); + manifold_inputs.resize(n_control_vars); table_scalar_names.resize(n_scalars); for (auto iCV = 0u; iCV < n_control_vars; iCV++) @@ -117,6 +118,7 @@ CFluidFlamelet::~CFluidFlamelet() { delete iomap_LookUp; delete lookup_mlp; if (preferential_diffusion) delete iomap_PD; + if (flamelet_options.idx_progvar_var >= 0) delete iomap_ProgVarBounds; } #endif } @@ -228,6 +230,12 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { val_vars_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH] = beta_enth; val_vars_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_MIXFRAC] = beta_mixfrac; + /*--- The progress variable range normalizes its variance. ---*/ + if (flamelet_options.idx_progvar_var >= 0) { + varnames_ProgVarBounds = {FLAMELET_PROGVAR_BOUNDS::MIN, FLAMELET_PROGVAR_BOUNDS::MAX}; + val_vars_ProgVarBounds.resize(varnames_ProgVarBounds.size()); + } + preferential_diffusion = flamelet_options.preferential_diffusion; if (!preferential_diffusion && flamelet_options.preferential_diffusion) @@ -240,12 +248,16 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { iomap_LookUp = new MLPToolbox::CIOMap(controlling_variable_names, varnames_LookUp); lookup_mlp->PairVariableswithMLPs(*iomap_TD); lookup_mlp->PairVariableswithMLPs(*iomap_Sources); - if (n_lookups > 1) + if (n_lookups > 0) lookup_mlp->PairVariableswithMLPs(*iomap_LookUp); if (preferential_diffusion) { iomap_PD = new MLPToolbox::CIOMap(controlling_variable_names, varnames_PD); lookup_mlp->PairVariableswithMLPs(*iomap_PD); } + if (!varnames_ProgVarBounds.empty()) { + iomap_ProgVarBounds = new MLPToolbox::CIOMap(controlling_variable_names, varnames_ProgVarBounds); + lookup_mlp->PairVariableswithMLPs(*iomap_ProgVarBounds); + } #endif } else { for (auto iVar = 0u; iVar < varnames_TD.size(); iVar++) { @@ -274,84 +286,127 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { : look_up_table->GetIndexOfVar(varnames_PD[iVar])); } } + if (!varnames_ProgVarBounds.empty()) { + if (!look_up_table->CheckForVariables(varnames_ProgVarBounds)) + SU2_MPI::Error(string("Transporting ") + FLAMELET_CV_NAME::PROGVAR_VAR + " requires the variables " + + FLAMELET_PROGVAR_BOUNDS::MIN + " and " + FLAMELET_PROGVAR_BOUNDS::MAX + " in the table.", + CURRENT_FUNCTION); + for (const auto& name : varnames_ProgVarBounds) LUT_idx_ProgVarBounds.push_back(look_up_table->GetIndexOfVar(name)); + } } } -pair CFluidFlamelet::GetControllingVariableRange(unsigned short i_cv) const { - if (Kind_DataDriven_Method == ENUM_DATADRIVEN_METHOD::LUT) return look_up_table->GetTableRange(i_cv); -#ifdef USE_MLPCPP - const auto norm = iomap_TD->GetInputNorm(controlling_variable_names[i_cv]); - return {norm.first, norm.second}; -#else - return CFluidModel::GetControllingVariableRange(i_cv); -#endif +su2double CFluidFlamelet::GetScalarVarianceLimit(const su2double* scalars, unsigned short i_var) { + SetManifoldInputs(scalars); + if (i_var == flamelet_options.idx_progvar_var) return limit_progvar_var; + if (i_var == flamelet_options.idx_mixfrac_var) return limit_mixfrac_var; + return CFluidModel::GetScalarVarianceLimit(scalars, i_var); } -unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_scalar, unsigned short lookup_type, - vector& output_refs) { - AD::StartPreacc(); - for (auto iVar = 0u; iVar < input_scalar.size(); iVar++) AD::SetPreaccIn(input_scalar[iVar]); +bool CFluidFlamelet::SetManifoldInputs(const su2double* scalars) { + for (auto iCV = 0u; iCV < n_control_vars; iCV++) manifold_inputs[iCV] = scalars[iCV]; + + /*--- Variance divided by its upper limit, 0 where the mean is at a bound. ---*/ + auto normalize = [](su2double variance, su2double limit) { + return (limit > 0) ? fmin(fmax(variance / limit, su2double(0.0)), su2double(1.0)) : su2double(0.0); + }; + + const int i_zvar = flamelet_options.idx_mixfrac_var; + if (i_zvar >= 0) { + const su2double z = scalars[flamelet_options.idx_mixfrac]; + limit_mixfrac_var = fmax(z * (1.0 - z), su2double(0.0)); + manifold_inputs[i_zvar] = normalize(scalars[i_zvar], limit_mixfrac_var); + } + + bool inside{true}; + const int i_cvar = flamelet_options.idx_progvar_var; + if (i_cvar >= 0) { + /*--- The range of the progress variable does not depend on its variance. ---*/ + manifold_inputs[i_cvar] = 0.0; + inside = LookUpManifold(FLAMELET_LOOKUP_OPS::PROGVAR_BOUNDS, manifold_inputs, val_vars_ProgVarBounds); + const su2double c = scalars[flamelet_options.idx_progvar]; + limit_progvar_var = fmax((c - val_vars_ProgVarBounds[0]) * (val_vars_ProgVarBounds[1] - c), su2double(0.0)); + manifold_inputs[i_cvar] = normalize(scalars[i_cvar], limit_progvar_var); + } + return inside; +} - /*--- The table axes follow the order of the controlling variables, the third one is the table level. ---*/ - const su2double val_cv1 = input_scalar[0]; - const su2double val_cv2 = input_scalar[1]; - const su2double val_cv3 = (n_control_vars == 3) ? input_scalar[2] : 0.0; - vector val_vars; - vector refs_vars; - vector LUT_idx; +bool CFluidFlamelet::LookUpManifold(unsigned short lookup_type, const vector& inputs, + vector& output_refs) { + vector* LUT_idx = nullptr; +#ifdef USE_MLPCPP + MLPToolbox::CIOMap* iomap = nullptr; +#endif switch (lookup_type) { case FLAMELET_LOOKUP_OPS::THERMO: - LUT_idx = LUT_idx_TD; + LUT_idx = &LUT_idx_TD; #ifdef USE_MLPCPP - iomap_Current = iomap_TD; + iomap = iomap_TD; #endif break; case FLAMELET_LOOKUP_OPS::PREFDIF: - LUT_idx = LUT_idx_PD; + LUT_idx = &LUT_idx_PD; #ifdef USE_MLPCPP - iomap_Current = iomap_PD; + iomap = iomap_PD; #endif break; case FLAMELET_LOOKUP_OPS::SOURCES: - LUT_idx = LUT_idx_Sources; + LUT_idx = &LUT_idx_Sources; #ifdef USE_MLPCPP - iomap_Current = iomap_Sources; + iomap = iomap_Sources; #endif break; case FLAMELET_LOOKUP_OPS::LOOKUP: - LUT_idx = LUT_idx_LookUp; + LUT_idx = &LUT_idx_LookUp; #ifdef USE_MLPCPP - iomap_Current = iomap_LookUp; + iomap = iomap_LookUp; #endif break; - default: + case FLAMELET_LOOKUP_OPS::PROGVAR_BOUNDS: + LUT_idx = &LUT_idx_ProgVarBounds; +#ifdef USE_MLPCPP + iomap = iomap_ProgVarBounds; +#endif break; + default: + SU2_MPI::Error("Unknown manifold look-up operation.", CURRENT_FUNCTION); } - /*--- Add all quantities and their names to the look up vectors. ---*/ bool inside{true}; switch (Kind_DataDriven_Method) { case ENUM_DATADRIVEN_METHOD::LUT: - if (output_refs.size() != LUT_idx.size()) + if (output_refs.size() != LUT_idx->size()) SU2_MPI::Error(string("Output vector size incompatible with manifold lookup operation."), CURRENT_FUNCTION); + /*--- The table axes follow the order of the controlling variables, the third one is the table level. ---*/ if (n_control_vars == 3) { - inside = look_up_table->LookUp_XYZ(LUT_idx, output_refs, val_cv1, val_cv2, val_cv3); + inside = look_up_table->LookUp_XYZ(*LUT_idx, output_refs, inputs[0], inputs[1], inputs[2]); } else { - inside = look_up_table->LookUp_XY(LUT_idx, output_refs, val_cv1, val_cv2); + inside = look_up_table->LookUp_XY(*LUT_idx, output_refs, inputs[0], inputs[1]); } break; - case ENUM_DATADRIVEN_METHOD::MLP: - refs_vars.resize(output_refs.size()); - for (auto iVar = 0u; iVar < output_refs.size(); iVar++) refs_vars[iVar] = &output_refs[iVar]; + case ENUM_DATADRIVEN_METHOD::MLP: { #ifdef USE_MLPCPP - inside=lookup_mlp->Predict(*iomap_Current, input_scalar, refs_vars); + vector refs_vars(output_refs.size()); + for (auto iVar = 0u; iVar < output_refs.size(); iVar++) refs_vars[iVar] = &output_refs[iVar]; + inside = lookup_mlp->Predict(*iomap, inputs, refs_vars); #endif break; + } default: break; } - if (inside) extrapolation = 0; - else extrapolation = 1; + return inside; +} + +unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_scalar, unsigned short lookup_type, + vector& output_refs) { + AD::StartPreacc(); + for (auto iVar = 0u; iVar < input_scalar.size(); iVar++) AD::SetPreaccIn(input_scalar[iVar]); + + bool inside = SetManifoldInputs(input_scalar.data()); + inside = LookUpManifold(lookup_type, manifold_inputs, output_refs) && inside; + + extrapolation = inside ? 0 : 1; for (auto iVar = 0u; iVar < output_refs.size(); iVar++) AD::SetPreaccOut(output_refs[iVar]); AD::EndPreacc(); return extrapolation; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 0db0c49d7381..d3499c0c723b 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -58,6 +58,14 @@ CSpeciesFlameletSolver::CSpeciesFlameletSolver(CGeometry* geometry, CConfig* con for (const int i_var : {flamelet_config_options.idx_progvar_var, flamelet_config_options.idx_mixfrac_var}) if (i_var >= 0) lowerlimit[i_var] = max(lowerlimit[i_var], su2double(0.0)); + for (const auto& var_mean : {make_pair(flamelet_config_options.idx_progvar_var, idx_progvar), + make_pair(flamelet_config_options.idx_mixfrac_var, flamelet_config_options.idx_mixfrac)}) { + if (var_mean.first < 0) continue; + string source_name = flamelet_config_options.cv_source_names[var_mean.first]; + transform(source_name.begin(), source_name.end(), source_name.begin(), ::toupper); + if (source_name != "NULL" && source_name != "ZERO") variance_sources.push_back(var_mean); + } + /*--- Initialize the solution to the far-field state everywhere. ---*/ nodes = new CSpeciesFlameletVariable(Solution_Inf, nPoint, nDim, nVar, config); @@ -429,25 +437,16 @@ void CSpeciesFlameletSolver::Postprocessing(CGeometry* geometry, CSolver** solve unsigned short iMesh) { SU2_ZONE_SCOPED - struct VarianceBound { - int i_var, i_mean; - su2double lower, upper; - }; - vector bounds; - if (flamelet_config_options.idx_progvar_var >= 0) { - const auto range = solver_container[FLOW_SOL]->GetFluidModel()->GetControllingVariableRange(idx_progvar); - bounds.push_back({flamelet_config_options.idx_progvar_var, idx_progvar, range.first, range.second}); - } - if (flamelet_config_options.idx_mixfrac_var >= 0) - bounds.push_back({flamelet_config_options.idx_mixfrac_var, flamelet_config_options.idx_mixfrac, 0.0, 1.0}); + const int variances[] = {flamelet_config_options.idx_progvar_var, flamelet_config_options.idx_mixfrac_var}; + if (variances[0] < 0 && variances[1] < 0) return; - /*--- var <= (mean - lower) (upper - mean) for a variable bounded by lower and upper. ---*/ SU2_OMP_FOR_STAT(omp_chunk_size) for (auto i_point = 0u; i_point < nPoint; i_point++) { - for (const auto& bound : bounds) { - const su2double mean = nodes->GetSolution(i_point, bound.i_mean); - const su2double max_var = max((mean - bound.lower) * (bound.upper - mean), su2double(0.0)); - if (nodes->GetSolution(i_point, bound.i_var) > max_var) nodes->SetSolution(i_point, bound.i_var, max_var); + CFluidModel* fluid_model_local = solver_container[FLOW_SOL]->GetFluidModel(); + for (const int i_var : variances) { + if (i_var < 0) continue; + const su2double limit = fluid_model_local->GetScalarVarianceLimit(nodes->GetSolution(i_point), i_var); + if (nodes->GetSolution(i_point, i_var) > limit) nodes->SetSolution(i_point, i_var, limit); } } END_SU2_OMP_FOR @@ -714,6 +713,11 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF unsigned long misses = fluid_model_local->EvaluateDataSet(scalars, FLAMELET_LOOKUP_OPS::SOURCES, table_sources); /*--- The source term for progress variable is always positive, we clip from below to make sure. --- */ if (idx_progvar >= 0) table_sources[idx_progvar] = fmax(0, table_sources[idx_progvar]); + + /*--- Variance source 2 (mean(phi S) - mean(phi) mean(S)); the manifold gives mean(phi S). ---*/ + for (const auto& var_mean : variance_sources) + table_sources[var_mean.first] = + 2.0 * (table_sources[var_mean.first] - scalars[var_mean.second] * table_sources[var_mean.second]); nodes->SetTableMisses(iPoint, misses); vector source_scalar(flamelet_config_options.n_scalars); diff --git a/SU2_CFD/src/solvers/CSpeciesSolver.cpp b/SU2_CFD/src/solvers/CSpeciesSolver.cpp index 17e6e40807b5..2ce7ec50b157 100644 --- a/SU2_CFD/src/solvers/CSpeciesSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesSolver.cpp @@ -238,6 +238,36 @@ void CSpeciesSolver::LoadRestart(CGeometry** geometry, CSolver*** solver, CConfi if (incompressible && ((!energy) && (!weakly_coupled_heat))) skipVars--; + /*--- Restart field of each variable, -1 for a variable that starts from its initial value. ---*/ + vector restart_field(nVar); + for (auto iVar = 0u; iVar < nVar; iVar++) restart_field[iVar] = skipVars + iVar; + + /*--- Flamelet scalars are found by name, a missing variance starts from its initial value. ---*/ + if (config->GetKind_Species_Model() == SPECIES_MODEL::FLAMELET) { + const auto& options = config->GetFlameletParsedOptions(); + for (auto iVar = 0u; iVar < nVar; iVar++) { + const string& name = (iVar < options.n_control_vars) + ? options.controlling_variable_names[iVar] + : options.user_scalar_names[iVar - options.n_control_vars]; + const auto field = find_if(fields.begin(), fields.end(), [&name](string field_name) { + field_name.erase(remove(field_name.begin(), field_name.end(), '"'), field_name.end()); + return field_name == name; + }); + if (field != fields.end()) { + /*--- The fields start with the point index, which is not in the restart data. ---*/ + restart_field[iVar] = static_cast(distance(fields.begin(), field)) - 1; + } else if (static_cast(iVar) == options.idx_progvar_var || + static_cast(iVar) == options.idx_mixfrac_var) { + restart_field[iVar] = -1; + if (rank == MASTER_NODE) + cout << "The restart file has no field " << name << ", it starts from its initial value " + << config->GetSpecies_Init()[iVar] << "." << endl; + } else { + SU2_MPI::Error("The restart file " + restart_filename + " has no field " + name + ".", CURRENT_FUNCTION); + } + } + } + /*--- Load data from the restart into correct containers. ---*/ unsigned long counter = 0; @@ -251,9 +281,12 @@ void CSpeciesSolver::LoadRestart(CGeometry** geometry, CSolver*** solver, CConfi /*--- We need to store this point's data, so jump to the correct offset in the buffer of data from the restart file and load it. ---*/ - const auto index = counter * Restart_Vars[1] + skipVars; - for (auto iVar = 0u; iVar < nVar; iVar++) - nodes->SetSolution(iPoint_Local, iVar, Restart_Data[index + iVar]); + const auto index = counter * Restart_Vars[1]; + for (auto iVar = 0u; iVar < nVar; iVar++) { + const su2double value = (restart_field[iVar] >= 0) ? Restart_Data[index + restart_field[iVar]] + : config->GetSpecies_Init()[iVar]; + nodes->SetSolution(iPoint_Local, iVar, value); + } /*--- Increment the overall counter for how many points have been loaded. ---*/ counter++; diff --git a/config_template.cfg b/config_template.cfg index c3d54d0d5dd5..5611c63c9bd6 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1053,14 +1053,19 @@ LOOKUP_NAMES= (MolarWeightMix, Conductivity, HeatRelease, Diffusivity) % MixtureFraction, ProgressVariableVariance and MixtureFractionVariance. EnthalpyTot is % required, together with ProgressVariable (premixed), MixtureFraction (non-premixed) or % both. A variance requires its mean and KIND_TURB_MODEL= SST. The first two names are the -% table axes, the third one is the variable of the table levels. A variance is limited to -% (mean - min)(max - mean), with the range of the mean taken from the table (progress -% variable) or equal to [0, 1] (mixture fraction). +% table axes, the third one is the variable of the table levels. +% A variance is transported as such, but the table or network takes it normalized by its +% upper limit (mean - min)(max - mean), so with values in [0, 1]. For the mixture fraction +% min = 0 and max = 1. For the progress variable, min and max are the manifold variables +% ProgressVariableMin and ProgressVariableMax, which may depend on the other controlling +% variables but not on the variance. The variance is clipped to its upper limit. CONTROLLING_VARIABLE_NAMES= (ProgressVariable, EnthalpyTot) % Names of the source term variables as they are present in the look-up table. For % controlling variables without source terms, use "zero" or "null", similar to the -% option USER_SOURCE_NAMES. +% option USER_SOURCE_NAMES. For a variance, the variable is the mean of phi*S_phi, with +% S_phi the source of its mean phi; the chemical source of the variance is +% 2 (mean(phi*S_phi) - mean(phi) mean(S_phi)), or zero for NULL. CONTROLLING_VARIABLE_SOURCE_NAMES= (ProdRateTot_PV, NULL) % Method used to ignite the solution: From d88647f0cebdefe35228d5e68621a936bffdc128 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 15 Nov 2026 10:23:29 +0100 Subject: [PATCH 05/40] Couple passive periodic points to their masters in the implicit system With implicit periodicity, the PERIODIC_RESIDUAL comms delete the rows of the passive points (first marker of each pair) and add only their diagonal block to the master. The off-diagonal blocks of the passive rows, and the columns of other rows that refer to passive points, are lost. On a wedge one cell thick every point is periodic, so most of the Jacobian coupling disappears and the Newton step is useless above CFL ~25. CSolver::CouplePeriodicJacobian moves those blocks to the master rows and columns, rotated, before the comms. Only masters on the same rank and blocks that exist in the sparsity pattern are coupled. Blocks go through GetBlockView/SetBlock, so the quantized Q_LU_SGS storage works too. The edge between a point and its own periodic image is left out of the local time step. It only rotates the state, but it added the sound speed and the viscous term and made the time step ~60x too small on the axis of a wedge. New case TestCases/incomp_rans/morse_swirl_jet (Morse 1980 swirling jet, 5 deg one-cell wedge, SA) and regression test inc_turb_morse_swirl_jet (restart, 10 iterations); mesh and solution are in the TestCases branch fix_periodic_jacobian, which regression.yml points to until it is merged. Regression values of the periodic cases in parallel_regression.py and serial_regression.py are updated; hybrid and AD values are not. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/regression.yml | 8 +- .../include/solvers/CFVMFlowSolverBase.hpp | 5 + .../include/solvers/CFVMFlowSolverBase.inl | 2 + SU2_CFD/include/solvers/CScalarSolver.inl | 2 + SU2_CFD/include/solvers/CSolver.hpp | 21 +++ SU2_CFD/src/solvers/CSolver.cpp | 146 ++++++++++++++++++ .../incomp_rans/morse_swirl_jet/inlet_jet.dat | 65 ++++++++ .../incomp_rans/morse_swirl_jet/morse_sa.cfg | 99 ++++++++++++ .../morse_swirl_jet/morse_wedge.geo | 100 ++++++++++++ TestCases/parallel_regression.py | 38 +++-- TestCases/serial_regression.py | 16 +- 11 files changed, 475 insertions(+), 27 deletions(-) create mode 100644 TestCases/incomp_rans/morse_swirl_jet/inlet_jet.dat create mode 100644 TestCases/incomp_rans/morse_swirl_jet/morse_sa.cfg create mode 100644 TestCases/incomp_rans/morse_swirl_jet/morse_wedge.geo diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml index 323353274e5a..49b0773ff86b 100644 --- a/.github/workflows/regression.yml +++ b/.github/workflows/regression.yml @@ -235,7 +235,7 @@ jobs: uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: # -t -c - args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} + args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: @@ -284,7 +284,7 @@ jobs: uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: # -t -c - args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} -a "--tapetests" + args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} -a "--tapetests" - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: @@ -334,7 +334,7 @@ jobs: PMIX_MCA_gds: hash with: # -t -c - args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} -a "--tsan" + args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} -a "--tsan" - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2-tsan:261011-1107 with: @@ -379,7 +379,7 @@ jobs: uses: docker://ghcr.io/su2code/su2/test-su2-asan:261011-1107 with: # -t -c - args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} -a "--asan" + args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} -a "--asan" - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2-asan:261011-1107 with: diff --git a/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp b/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp index e0c24506a5e5..23e9d8c1a639 100644 --- a/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp +++ b/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp @@ -444,6 +444,10 @@ class CFVMFlowSolverBase : public CSolver { ompMasterAssignBarrier(Min_Delta_Time,1e30, Max_Delta_Time,0.0, Global_Delta_UnstTimeND,1e30); + /*--- Edges between a point and its own periodic image carry only the rotation of the state. ---*/ + const bool skipImages = implicit_periodic; + if (skipImages) SetPeriodicMaster(geometry, config); + /*--- Loop domain points. ---*/ SU2_OMP_FOR_DYN(omp_chunk_size) @@ -461,6 +465,7 @@ class CFVMFlowSolverBase : public CSolver { for (unsigned short iNeigh = 0; iNeigh < geometry->nodes->GetnPoint(iPoint); ++iNeigh) { auto jPoint = geometry->nodes->GetPoint(iPoint,iNeigh); + if (skipImages && ArePeriodicImages(iPoint, jPoint)) continue; auto iEdge = geometry->nodes->GetEdge(iPoint,iNeigh); auto Normal = geometry->edges->GetNormal(iEdge); diff --git a/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl b/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl index 9f1637b2b781..2e681c4f51d7 100644 --- a/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl +++ b/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl @@ -1325,6 +1325,8 @@ void CFVMFlowSolverBase::BC_Periodic(CGeometry* geometry, CSolver** solver accumulated correctly during the communications. For implicit calculations, the Jacobians and linear system are also correctly adjusted here. ---*/ + CouplePeriodicJacobian(geometry, config); + for (unsigned short iPeriodic = 1; iPeriodic <= config->GetnMarker_Periodic() / 2; iPeriodic++) { InitiatePeriodicComms(geometry, config, iPeriodic, PERIODIC_RESIDUAL); CompletePeriodicComms(geometry, config, iPeriodic, PERIODIC_RESIDUAL); diff --git a/SU2_CFD/include/solvers/CScalarSolver.inl b/SU2_CFD/include/solvers/CScalarSolver.inl index 941d68928493..041730ba8029 100644 --- a/SU2_CFD/include/solvers/CScalarSolver.inl +++ b/SU2_CFD/include/solvers/CScalarSolver.inl @@ -412,6 +412,8 @@ void CScalarSolver::BC_Periodic(CGeometry* geometry, CSolver** sol accumulated corectly during the communications. For implicit calculations the Jacobians and linear system are also correctly adjusted here. ---*/ + CouplePeriodicJacobian(geometry, config); + for (unsigned short iPeriodic = 1; iPeriodic <= config->GetnMarker_Periodic() / 2; iPeriodic++) { InitiatePeriodicComms(geometry, config, iPeriodic, PERIODIC_RESIDUAL); CompletePeriodicComms(geometry, config, iPeriodic, PERIODIC_RESIDUAL); diff --git a/SU2_CFD/include/solvers/CSolver.hpp b/SU2_CFD/include/solvers/CSolver.hpp index 882316b5c67a..15c336a33730 100644 --- a/SU2_CFD/include/solvers/CSolver.hpp +++ b/SU2_CFD/include/solvers/CSolver.hpp @@ -149,6 +149,8 @@ class CSolver { bool implicit_periodic; /*!< \brief Flag that controls whether the implicit system should be treated by the periodic BC comms. */ su2activematrix PeriodicProj; /*!< \brief Min/max reconstruction increments at periodic receive points (for limiters). */ std::unordered_map PeriodicProjIndex; /*!< \brief Local point to compact projection row. */ + vector PeriodicMaster; /*!< \brief Local master point of each passive periodic point on this rank, or -1. */ + vector PeriodicMasterMarker; /*!< \brief Periodic marker of each passive point, gives its rotation. */ bool dynamic_grid; /*!< \brief Flag that determines whether the grid is dynamic (moving or deforming + grid velocities). */ @@ -326,6 +328,25 @@ class CSolver { unsigned short val_periodic_index, unsigned short commType); + /*! + * \brief Move the off-diagonal Jacobian blocks of passive periodic points to their masters, rotated. + * \note Call before the PERIODIC_RESIDUAL comms. Only masters on the same rank and blocks in the sparsity pattern are coupled. + */ + void CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config); + + /*! + * \brief Map each passive periodic point to its master on the same rank (built once). + */ + void SetPeriodicMaster(CGeometry *geometry, const CConfig *config); + + /*! + * \brief Whether two points are periodic images of each other on this rank. + */ + inline bool ArePeriodicImages(unsigned long iPoint, unsigned long jPoint) const { + if (PeriodicMaster.empty()) return false; + return PeriodicMaster[iPoint] == static_cast(jPoint) || PeriodicMaster[jPoint] == static_cast(iPoint); + } + /*! * \brief Set number of linear solver iterations. * \param[in] val_iterlinsolver - Number of linear iterations. diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 19f07df2e598..ff93efbba720 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -4606,3 +4606,149 @@ void CSolver::SavelibROM(CGeometry *geometry, CConfig *config, bool converged) { #endif } + +void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { + if (config->GetnMarker_Periodic() == 0) return; + + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + + const auto nPeriodic = config->GetnMarker_Periodic(); + const auto nPointAll = geometry->GetnPoint(); + + if (PeriodicMaster.size() != nPointAll) { + PeriodicMaster.assign(nPointAll, -1); + PeriodicMasterMarker.assign(nPointAll, 0); + vector nPeriodicMarker(nPointAll, 0); + vector passive(nPointAll, false); + + for (auto iMarker = 0u; iMarker < config->GetnMarker_All(); iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; + /*--- Points receiving from the second marker of a pair have their rows removed (CompletePeriodicComms). ---*/ + const bool isPassive = config->GetMarker_All_PerBound(iMarker) <= nPeriodic / 2; + for (auto iVertex = 0ul; iVertex < geometry->nVertex[iMarker]; iVertex++) { + const auto* vertex = geometry->vertex[iMarker][iVertex]; + const auto iPoint = vertex->GetNode(); + nPeriodicMarker[iPoint]++; + if (!isPassive) continue; + passive[iPoint] = true; + if (vertex->GetDonorProcessor() == rank && vertex->GetDonorPoint() >= 0) { + PeriodicMaster[iPoint] = vertex->GetDonorPoint(); + PeriodicMasterMarker[iPoint] = iMarker; + } + } + } + + /*--- Points on several periodic markers keep the treatment of the comms only. ---*/ + for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { + const auto master = PeriodicMaster[iPoint]; + if (master < 0) continue; + if (nPeriodicMarker[iPoint] != 1 || nPeriodicMarker[master] != 1 || passive[master]) + PeriodicMaster[iPoint] = -1; + } + } + + } + END_SU2_OMP_SAFE_GLOBAL_ACCESS +} + +void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) { + SU2_ZONE_SCOPED + if (!implicit_periodic) return; + + SetPeriodicMaster(geometry, config); + + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + + /*--- Rotation from the frame of a passive point to the frame of its master. ---*/ + auto Rotation = [&](unsigned short iMarker, su2double (&Q)[3][3]) { + for (auto i = 0u; i < 3; i++) + for (auto j = 0u; j < 3; j++) Q[i][j] = (i == j); + if (!rotate_periodic) return false; + const auto* angles = config->GetPeriodicRotAngles(config->GetMarker_All_TagBound(iMarker)); + if (!GeometryToolbox::HasRotation(angles)) return false; + if (nDim == 2) { + su2double Q2[2][2]; + GeometryToolbox::RotationMatrix(angles[2], Q2); + for (auto i = 0u; i < 2; i++) + for (auto j = 0u; j < 2; j++) Q[i][j] = Q2[i][j]; + } else { + GeometryToolbox::RotationMatrix(angles[0], angles[1], angles[2], Q); + } + return true; + }; + + su2activematrix block(nVar, nVar), zero(nVar, nVar); + zero = su2double(0.0); + su2double v[3]; + + /*--- Copy a block through its view, which also decodes quantized storage. ---*/ + auto ReadBlock = [&](unsigned long iRow, unsigned long iCol) { + const auto view = Jacobian.GetBlockView(iRow, iCol); + if (!view) return false; + for (auto i = 0u; i < nVar; i++) + for (auto j = 0u; j < nVar; j++) block(i, j) = view(i, j); + return true; + }; + + auto RotateRows = [&](const su2double (&Q)[3][3]) { + for (auto c = 0u; c < nVar; c++) { + for (auto d = 0u; d < nDim; d++) v[d] = block(1 + d, c); + for (auto d = 0u; d < nDim; d++) { + su2double sum = 0.0; + for (auto e = 0u; e < nDim; e++) sum += Q[d][e] * v[e]; + block(1 + d, c) = sum; + } + } + }; + + /*--- Right product with Q^T: the passive increment is Q^T times the master increment. ---*/ + auto RotateColumns = [&](const su2double (&Q)[3][3]) { + for (auto r = 0u; r < nVar; r++) { + for (auto d = 0u; d < nDim; d++) v[d] = block(r, 1 + d); + for (auto d = 0u; d < nDim; d++) { + su2double sum = 0.0; + for (auto e = 0u; e < nDim; e++) sum += v[e] * Q[d][e]; + block(r, 1 + d) = sum; + } + } + }; + + su2double Qp[3][3], Qk[3][3]; + + /*--- Rows of passive points go to the rows of their masters. ---*/ + for (auto iPoint = 0ul; iPoint < nPointDomain; iPoint++) { + const auto master = PeriodicMaster[iPoint]; + if (master < 0) continue; + const bool rotP = Rotation(PeriodicMasterMarker[iPoint], Qp); + + for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { + if (!ReadBlock(iPoint, kPoint)) continue; + + long col = kPoint; + if (PeriodicMaster[kPoint] >= 0) { + col = PeriodicMaster[kPoint]; + if (Rotation(PeriodicMasterMarker[kPoint], Qk)) RotateColumns(Qk); + } + if (rotP) RotateRows(Qp); + + Jacobian.SetBlock(master, col, block); + } + } + + /*--- Columns of passive points go to the columns of their masters. ---*/ + for (auto iPoint = 0ul; iPoint < nPointDomain; iPoint++) { + if (PeriodicMaster[iPoint] >= 0) continue; + + for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { + const auto master = PeriodicMaster[kPoint]; + if (master < 0) continue; + if (!Jacobian.GetBlockView(iPoint, master) || !ReadBlock(iPoint, kPoint)) continue; + if (Rotation(PeriodicMasterMarker[kPoint], Qk)) RotateColumns(Qk); + Jacobian.SetBlock(iPoint, master, block); + Jacobian.SetBlock(iPoint, kPoint, zero); + } + } + + } + END_SU2_OMP_SAFE_GLOBAL_ACCESS +} diff --git a/TestCases/incomp_rans/morse_swirl_jet/inlet_jet.dat b/TestCases/incomp_rans/morse_swirl_jet/inlet_jet.dat new file mode 100644 index 000000000000..19f935ed891f --- /dev/null +++ b/TestCases/incomp_rans/morse_swirl_jet/inlet_jet.dat @@ -0,0 +1,65 @@ +NMARK= 1 +MARKER_TAG= inlet_jet +NROW=60 +NCOL=9 +# COORD-X COORD-Y COORD-Z TEMPERATURE VELOCITY NORMAL-X NORMAL-Y NORMAL-Z NU_TILDE +1.230000000000000e-02 4.915317250182741e-04 -2.146073858374531e-05 2.881500000000000e+02 3.404952035805443e+01 9.964500863218230e-01 3.977264224582153e-03 8.409165736575443e-02 2.108527391098338e-03 +1.230000000000000e-02 9.750124993671942e-04 -4.256996506995672e-05 2.881500000000000e+02 3.430313843595425e+01 9.880697227692148e-01 7.215987429835292e-03 1.538380722453961e-01 2.108527391098338e-03 +1.230000000000000e-02 9.750124993671942e-04 4.256996506995671e-05 2.881500000000000e+02 3.430313843595425e+01 9.880697227692148e-01 -6.219343030316790e-03 1.538815866796235e-01 2.108527391098338e-03 +1.230000000000000e-02 4.915317250182741e-04 2.146073858374531e-05 2.881500000000000e+02 3.404952035805443e+01 9.964500863218230e-01 -3.366941323155189e-03 8.411830463910938e-02 2.108527391098338e-03 +1.230000000000000e-02 1.458493273716226e-03 -6.367919155617299e-05 2.881500000000000e+02 3.454279085009219e+01 9.762877688261749e-01 1.014212659517094e-02 2.162390568526813e-01 2.108527391098338e-03 +1.230000000000000e-02 1.458493273716226e-03 6.367919155617298e-05 2.881500000000000e+02 3.454279085009220e+01 9.762877688261747e-01 -8.742942869563935e-03 2.163001465334435e-01 2.108527391098338e-03 +1.230000000000000e-02 1.941974048065509e-03 -8.478841804240026e-05 2.881500000000000e+02 3.473691736740481e+01 9.688679027627434e-01 1.201797138126057e-02 2.472863832886933e-01 2.108527391098338e-03 +1.230000000000000e-02 1.941974048065509e-03 8.478841804240026e-05 2.881500000000000e+02 3.473691736740481e+01 9.688679027627434e-01 -9.580189035078044e-03 2.473928191645333e-01 2.108527391098338e-03 +1.230000000000000e-02 2.425454822414266e-03 -1.058976445286045e-04 2.881500000000000e+02 3.491004480099832e+01 9.570479293413384e-01 1.437979231487217e-02 2.895729312564240e-01 2.108527391098338e-03 +1.230000000000000e-02 2.425454822414266e-03 1.058976445286045e-04 2.881500000000000e+02 3.491004480099832e+01 9.570479293413384e-01 -1.091287103953410e-02 2.897243003082949e-01 2.108527391098338e-03 +1.230000000000000e-02 2.908935596762439e-03 -1.270068710147833e-04 2.881500000000000e+02 3.511796986204671e+01 9.397713273854733e-01 1.714460373522862e-02 3.413735707211489e-01 2.108527391098338e-03 +1.230000000000000e-02 2.908935596762439e-03 1.270068710147833e-04 2.881500000000000e+02 3.511796986204671e+01 9.397713273854733e-01 -1.267330376870326e-02 3.415687918937142e-01 2.108527391098338e-03 +1.230000000000000e-02 3.392416371111116e-03 -1.481160975009841e-04 2.881500000000000e+02 3.528982116296100e+01 9.260512716016078e-01 1.892666174263513e-02 3.769228353925044e-01 2.108527391098338e-03 +1.230000000000000e-02 3.392416371111116e-03 1.481160975009841e-04 2.881500000000000e+02 3.528982116296100e+01 9.260512716016078e-01 -1.399634959659803e-02 3.771380974696337e-01 2.108527391098338e-03 +1.230000000000000e-02 3.875897145460034e-03 -1.692253239871954e-04 2.881500000000000e+02 3.551215523720097e+01 9.112425122050197e-01 2.065526075006717e-02 4.113519711313309e-01 2.108527391098338e-03 +1.230000000000000e-02 3.875897145460034e-03 1.692253239871954e-04 2.881500000000000e+02 3.551215523720097e+01 9.112425122050197e-01 -1.527502532774494e-02 4.115868772829392e-01 2.108527391098338e-03 +1.230000000000000e-02 4.359377919809123e-03 -1.903345504734142e-04 2.881500000000000e+02 3.573358919956365e+01 9.036946523831382e-01 2.172966451482030e-02 4.276257673880193e-01 2.108527391098338e-03 +1.230000000000000e-02 4.359377919809123e-03 1.903345504734141e-04 2.881500000000000e+02 3.573358919956365e+01 9.036946523831382e-01 -1.562306479376379e-02 4.278923872898056e-01 2.108527391098338e-03 +1.230000000000000e-02 4.842858694158044e-03 -2.114437769596256e-04 2.881500000000000e+02 3.596582688777886e+01 8.959717351739295e-01 2.278227706937255e-02 4.435263437733462e-01 2.108527391098338e-03 +1.230000000000000e-02 4.842858694158044e-03 2.114437769596256e-04 2.881500000000000e+02 3.596582688777886e+01 8.959717351739295e-01 -1.596028429275307e-02 4.438241984104884e-01 2.108527391098338e-03 +1.230000000000000e-02 5.326339468506962e-03 -2.325530034458370e-04 2.881500000000000e+02 3.597906269642409e+01 8.942078992003367e-01 2.331743914955868e-02 4.470442148593665e-01 2.108527391098338e-03 +1.230000000000000e-02 5.326339468506963e-03 2.325530034458369e-04 2.881500000000000e+02 3.597906269642409e+01 8.942078992003365e-01 -1.573376133324451e-02 4.473753253835411e-01 2.108527391098338e-03 +1.230000000000000e-02 5.809820242855882e-03 -2.536622299320483e-04 2.881500000000000e+02 3.598980701325640e+01 8.924123870269365e-01 2.385467051978150e-02 4.505897093535071e-01 2.108527391098338e-03 +1.230000000000000e-02 5.809820242855882e-03 2.536622299320483e-04 2.881500000000000e+02 3.598980701325640e+01 8.924123870269365e-01 -1.550758449662454e-02 4.509541509998167e-01 2.108527391098338e-03 +1.230000000000000e-02 6.293301017204801e-03 -2.747714564182597e-04 2.881500000000000e+02 3.585282925447235e+01 8.896639674444857e-01 2.453168460400286e-02 4.559563811171272e-01 2.108527391098338e-03 +1.230000000000000e-02 6.293301017204801e-03 2.747714564182596e-04 2.881500000000000e+02 3.585282925447235e+01 8.896639674444857e-01 -1.530088291903097e-02 4.563594066224945e-01 2.108527391098338e-03 +1.230000000000000e-02 6.776781791553593e-03 -2.958806829044656e-04 2.881500000000000e+02 3.571601787886337e+01 8.868903347339346e-01 2.521594161932737e-02 4.612913292527621e-01 2.108527391098338e-03 +1.230000000000000e-02 6.776781791553593e-03 2.958806829044654e-04 2.881500000000000e+02 3.571601787886337e+01 8.868903347339346e-01 -1.508420107551411e-02 4.617336905982094e-01 2.108527391098338e-03 +1.230000000000000e-02 7.260262565901019e-03 -3.169899093906116e-04 2.881500000000000e+02 3.548623354001720e+01 8.864116770742088e-01 2.614893873877201e-02 4.621586002113610e-01 2.108527391098338e-03 +1.230000000000000e-02 7.260262565901019e-03 3.169899093906116e-04 2.881500000000000e+02 3.548623354001720e+01 8.864116770742088e-01 -1.423034193634863e-02 4.626789773859011e-01 2.108527391098338e-03 +1.230000000000000e-02 7.743743340249600e-03 -3.380991358768083e-04 2.881500000000000e+02 3.525668118861410e+01 8.859251724448826e-01 2.709464097744716e-02 4.630361424973307e-01 2.108527391098338e-03 +1.230000000000000e-02 7.743743340249600e-03 3.380991358768082e-04 2.881500000000000e+02 3.525668118861410e+01 8.859251724448826e-01 -1.336472122993312e-02 4.636356037395652e-01 2.108527391098338e-03 +1.230000000000000e-02 8.227224114600015e-03 -3.592083623630850e-04 2.881500000000000e+02 3.506478345062848e+01 8.854458827588981e-01 2.818749458180924e-02 4.638868976965356e-01 2.108527391098338e-03 +1.230000000000000e-02 8.227224114600015e-03 3.592083623630849e-04 2.881500000000000e+02 3.506478345062848e+01 8.854458827588981e-01 -1.235017446476032e-02 4.645783700259899e-01 2.108527391098338e-03 +1.230000000000000e-02 8.710704888951459e-03 -3.803175888494065e-04 2.881500000000000e+02 3.487296185468804e+01 8.849593859884991e-01 2.929231168974371e-02 4.647460011949857e-01 2.108527391098338e-03 +1.230000000000000e-02 8.710704888951459e-03 3.803175888494064e-04 2.881500000000000e+02 3.487296185468804e+01 8.849593859884991e-01 -1.132443732297945e-02 4.655304955319002e-01 2.108527391098338e-03 +1.230000000000000e-02 9.194185663303368e-03 -4.014268153357484e-04 2.881500000000000e+02 3.409955958208356e+01 8.854079871950582e-01 3.041559804813040e-02 4.638184856240317e-01 2.108527391098338e-03 +1.230000000000000e-02 9.194185663303369e-03 4.014268153357484e-04 2.881500000000000e+02 3.409955958208356e+01 8.854079871950582e-01 -1.012458709981934e-02 4.647044102946019e-01 2.108527391098338e-03 +1.230000000000000e-02 9.677666437654643e-03 -4.225360418220627e-04 2.881500000000000e+02 3.331699155975138e+01 8.859007846674354e-01 3.159905365039384e-02 4.627972553224809e-01 2.109105393500574e-03 +1.230000000000000e-02 9.677666437654643e-03 4.225360418220626e-04 2.881500000000000e+02 3.331699155975138e+01 8.859007846674354e-01 -8.856628817969465e-03 4.637902110346906e-01 2.109105393500574e-03 +1.230000000000000e-02 1.016114721200506e-02 -4.436452683083394e-04 2.881500000000000e+02 3.202843334758530e+01 8.880303872600582e-01 3.344505778443284e-02 4.585667447739173e-01 2.150324507557260e-03 +1.230000000000000e-02 1.016114721200506e-02 4.436452683083392e-04 2.881500000000000e+02 3.202843334758530e+01 8.880303872600582e-01 -6.648935997922503e-03 4.597366887174077e-01 2.150324507557260e-03 +1.230000000000000e-02 1.064462798635547e-02 -4.647544947946160e-04 2.881500000000000e+02 2.931124680838526e+01 8.867853340771026e-01 3.559994489771646e-02 4.608084365428229e-01 1.769861196946197e-03 +1.230000000000000e-02 1.064462798635547e-02 4.647544947946160e-04 2.881500000000000e+02 2.931124680838526e+01 8.867853340771027e-01 -4.697625191813431e-03 4.621576609592430e-01 1.769861196946197e-03 +1.230000000000000e-02 1.112810876070589e-02 -4.858637212808926e-04 2.881500000000000e+02 2.511433201771983e+01 8.693698105783823e-01 3.824167144025443e-02 4.926801264718960e-01 1.630487557935555e-03 +1.230000000000000e-02 1.112810876070589e-02 4.858637212808926e-04 2.881500000000000e+02 2.511433201771983e+01 8.693698105783823e-01 -4.843752024720255e-03 4.941383111247607e-01 1.630487557935555e-03 +1.230000000000000e-02 1.161158953505630e-02 -5.069729477671694e-04 2.881500000000000e+02 2.068271201250798e+01 8.609729305189665e-01 3.996702674728404e-02 5.070781494864128e-01 1.435649787184269e-03 +1.230000000000000e-02 1.161158953505630e-02 5.069729477671693e-04 2.881500000000000e+02 2.068271201250798e+01 8.609729305189665e-01 -4.379832605461022e-03 5.086319199381131e-01 1.435649787184269e-03 +1.230000000000000e-02 1.209507030940672e-02 -5.280821742534461e-04 2.881500000000000e+02 1.425021780494439e+01 8.068188357102061e-01 3.404111642689164e-02 5.898174028762109e-01 1.164465134572247e-03 +1.230000000000000e-02 1.209507030940672e-02 5.280821742534461e-04 2.881500000000000e+02 1.425021780494439e+01 8.068188357102061e-01 -1.749439413157761e-02 5.905398483736696e-01 1.164465134572247e-03 +1.230000000000000e-02 1.257855108375714e-02 -5.491914007397227e-04 2.881500000000000e+02 9.891554779527372e+00 7.520381756169899e-01 2.135771076565043e-02 6.587734288854707e-01 1.158624905448327e-03 +1.230000000000000e-02 1.257855108375714e-02 5.491914007397226e-04 2.881500000000000e+02 9.891554779527372e+00 7.520381756169899e-01 -3.613944926881677e-02 6.581280442445954e-01 1.158624905448327e-03 +1.230000000000000e-02 1.306203185810882e-02 -5.703006272260550e-04 2.881500000000000e+02 6.393699027877189e+00 7.203924215589249e-01 -1.774214892046960e-02 6.933397256123091e-01 8.989716122905569e-04 +1.230000000000000e-02 1.306203185810882e-02 5.703006272260548e-04 2.881500000000000e+02 6.393699027877188e+00 7.203924215589250e-01 -7.810317344952432e-02 6.891550284642648e-01 8.989716122905569e-04 +1.230000000000000e-02 1.354551263246073e-02 -5.914098537123968e-04 2.881500000000000e+02 4.159475074460833e+00 6.958121544564141e-01 -1.056173699727177e-01 7.104156648545761e-01 8.550258250599377e-04 +1.230000000000000e-02 1.354551263246073e-02 5.914098537123966e-04 2.881500000000000e+02 4.159475074460833e+00 6.958121544564141e-01 -1.671322689231877e-01 6.985071584424246e-01 8.550258250599377e-04 +1.230000000000000e-02 1.402899340681264e-02 -6.125190801987386e-04 2.881500000000000e+02 3.466774653766527e+00 6.780817593465893e-01 -1.962656943156323e-01 7.082971868334907e-01 7.807626782637281e-04 +1.230000000000000e-02 1.402899340681264e-02 6.125190801987387e-04 2.881500000000000e+02 3.466774653766527e+00 6.780817593465893e-01 -2.572510114990779e-01 6.884962198328582e-01 7.807626782637281e-04 +1.230000000000000e-02 1.451247418116454e-02 -6.336283066850803e-04 2.881500000000000e+02 2.818095933870955e+00 6.413195442631660e-01 -3.269956285048218e-01 6.941059725177575e-01 7.066101318319812e-04 +1.230000000000000e-02 1.451247418116454e-02 6.336283066850801e-04 2.881500000000000e+02 2.818095933870956e+00 6.413195442631658e-01 -3.862466329960522e-01 6.629651428584297e-01 7.066101318319812e-04 diff --git a/TestCases/incomp_rans/morse_swirl_jet/morse_sa.cfg b/TestCases/incomp_rans/morse_swirl_jet/morse_sa.cfg new file mode 100644 index 000000000000..45a3bf2c8fed --- /dev/null +++ b/TestCases/incomp_rans/morse_swirl_jet/morse_sa.cfg @@ -0,0 +1,99 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% SU2 configuration file % +% Case description: Swirling jet in still air, S = 0.36, Re = 56,000 % +% (Morse 1980, ERCOFTAC Classic case 026), SA, 5 deg wedge % +% Author: Nijso Beishuizen % +% Institution: Bosch Thermotechnology % +% Date: Nov 15th, 2026 % +% File Version 8.6.0 "Harrier" % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% ------------- DIRECT, ADJOINT, AND LINEARIZED PROBLEM DEFINITION ------------% +% +SOLVER= INC_RANS +KIND_TURB_MODEL= SA +MATH_PROBLEM= DIRECT +RESTART_SOL= YES + +% ---------------- INCOMPRESSIBLE FLOW CONDITION DEFINITION -------------------% +% +% Air; the far field carries a co-flow of 1% of the jet exit velocity (34.46 m/s). +FLUID_MODEL= CONSTANT_DENSITY +INC_DENSITY_INIT= 1.2 +INC_VELOCITY_INIT= ( 0.345, 0.0, 0.0 ) +INC_NONDIM= DIMENSIONAL + +% --------------------------- VISCOSITY MODEL ---------------------------------% +% +% Re = U_exit D / nu = 56,000 with D = 0.0246 m. +VISCOSITY_MODEL= CONSTANT_VISCOSITY +MU_CONSTANT= 1.82e-05 +FREESTREAM_NU_FACTOR= 3.0 + +% -------------------- BOUNDARY CONDITION DEFINITION --------------------------% +% +% The jet enters at x/D = 0.5 with the profiles measured there (inlet_jet.dat). The far field supplies the +% entrained air through the inlet plane; at r = 30 D it suffices up to x/D = 100. +INC_INLET_TYPE= VELOCITY_INLET +MARKER_INLET= ( inlet_jet, 288.15, 34.10, 1.0, 0.0, 0.0 ) +SPECIFIED_INLET_PROFILE= YES +INLET_FILENAME= inlet_jet.dat +% The outlet is a far field too: a pressure outlet lets a reversed flow enter along the axis. +MARKER_FAR= ( farfield, outlet ) +MARKER_EULER= ( axis ) +MARKER_PERIODIC= ( periodic_1, periodic_2, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0 ) +MARKER_PLOTTING= ( axis ) +MARKER_MONITORING= ( axis ) + +% ------------- COMMON PARAMETERS DEFINING THE NUMERICAL METHOD ---------------% +% +NUM_METHOD_GRAD= GREEN_GAUSS +NUM_METHOD_GRAD_RECON= LEAST_SQUARES +CFL_NUMBER= 25 +CFL_ADAPT= YES +CFL_ADAPT_PARAM= ( 0.5, 1.1, 25, 2500, 0.001 ) +ITER= 1000 + +% ------------------------ LINEAR SOLVER DEFINITION ---------------------------% +% +LINEAR_SOLVER= FGMRES +LINEAR_SOLVER_PREC= ILU +LINEAR_SOLVER_ERROR= 1E-4 +LINEAR_SOLVER_ITER= 50 + +% -------------------- FLOW NUMERICAL METHOD DEFINITION -----------------------% +% +CONV_NUM_METHOD_FLOW= FDS +MUSCL_FLOW= YES +SLOPE_LIMITER_FLOW= VENKATAKRISHNAN +VENKAT_LIMITER_COEFF= 0.05 +TIME_DISCRE_FLOW= EULER_IMPLICIT + +% -------------------- TURBULENT NUMERICAL METHOD DEFINITION ------------------% +% +CONV_NUM_METHOD_TURB= SCALAR_UPWIND +MUSCL_TURB= NO +TIME_DISCRE_TURB= EULER_IMPLICIT + +% --------------------------- CONVERGENCE PARAMETERS --------------------------% +% +CONV_FIELD= RMS_PRESSURE +CONV_RESIDUAL_MINVAL= -10 +CONV_STARTITER= 10 + +% ------------------------- INPUT/OUTPUT INFORMATION --------------------------% +% +MESH_FILENAME= morse_wedge.su2 +MESH_FORMAT= SU2 +SOLUTION_FILENAME= solution_flow +RESTART_FILENAME= restart_flow +CONV_FILENAME= history +VOLUME_FILENAME= flow +SCREEN_OUTPUT= INNER_ITER, RMS_PRESSURE, RMS_VELOCITY-X, RMS_NU_TILDE, LINSOL_ITER, LINSOL_RESIDUAL, AVG_CFL +HISTORY_OUTPUT= ITER, RMS_RES, CFL_NUMBER +VOLUME_OUTPUT= COORDINATES, SOLUTION, PRIMITIVE, RESIDUAL +OUTPUT_FILES= RESTART, RESTART_ASCII, PARAVIEW +WRT_RESTART_COMPACT= NO +OUTPUT_WRT_FREQ= 100 diff --git a/TestCases/incomp_rans/morse_swirl_jet/morse_wedge.geo b/TestCases/incomp_rans/morse_swirl_jet/morse_wedge.geo new file mode 100644 index 000000000000..8e0323d752c5 --- /dev/null +++ b/TestCases/incomp_rans/morse_swirl_jet/morse_wedge.geo @@ -0,0 +1,100 @@ +// Structured wedge mesh for the Morse swirling jet (ERCOFTAC C26). +// The x-r plane is meshed at theta = -angle/2 and rotated about the jet axis (x) by the wedge angle, one cell thick. +// A slip wall at r = rmin replaces the axis, so all cells are hexahedra. Lengths are in nozzle diameters times D. +// +// gmsh morse_wedge.geo -3 -format su2 -o morse_wedge.su2 +// +// The mesh must be 3D (-3); a 2D mesh gives a file without volume elements. + +D = 0.0246; // nozzle diameter [m] +angle = 5; // wedge angle [deg] +x0 = 0.5; // inlet plane, x/D +xmax = 50; // outlet plane, x/D +rmin = 0.02; // slip wall replacing the axis, r/D +rjet = 0.5905; // outer radius of the measured inlet profile, r/D +rfine = 4; // end of the uniform radial spacing, r/D +rmax = 30; // far-field radius, r/D +dr = 0.02; // uniform radial spacing, r/D +dx0 = 0.02; // axial spacing at the inlet, x/D +dxmax = 0.25; // largest axial spacing, x/D +g = 1.03; // growth ratio of stretched spacings + +// Cells per segment: axial spacing grows from dx0 to dxmax, then stays uniform. +nx1 = Ceil(Log(dxmax / dx0) / Log(g)); +xg = x0 + dx0 * (g^nx1 - 1) / (g - 1); +nx2 = Round((xmax - xg) / dxmax); +nr1 = Round((rjet - rmin) / dr); +nr2 = Round((rfine - rjet) / dr); +nr3 = Round(Log(1 + (rmax - rfine) * (g - 1) / dr) / Log(g)); + +xs[] = {x0, xg, xmax}; +rs[] = {rmin, rjet, rfine, rmax}; +nxs[] = {nx1, nx2}; +gxs[] = {g, 1}; +nrs[] = {nr1, nr2, nr3}; +grs[] = {1, 1, g}; +a = -0.5 * angle * Pi / 180; + +For i In {0:2} + For j In {0:3} + p = newp; + Point(p) = {xs[i] * D, rs[j] * D * Cos(a), rs[j] * D * Sin(a)}; + P[i * 4 + j] = p; + EndFor +EndFor + +// Lines of constant r (H) and of constant x (V), all oriented towards larger x or r. +For i In {0:1} + For j In {0:3} + l = newl; + Line(l) = {P[i * 4 + j], P[(i + 1) * 4 + j]}; + Transfinite Curve{l} = nxs[i] + 1 Using Progression gxs[i]; + H[i * 4 + j] = l; + EndFor +EndFor +For i In {0:2} + For j In {0:2} + l = newl; + Line(l) = {P[i * 4 + j], P[i * 4 + j + 1]}; + Transfinite Curve{l} = nrs[j] + 1 Using Progression grs[j]; + V[i * 3 + j] = l; + EndFor +EndFor + +For i In {0:1} + For j In {0:2} + cl = newcl; + Curve Loop(cl) = {H[i * 4 + j], V[(i + 1) * 3 + j], -H[i * 4 + j + 1], -V[i * 3 + j]}; + s = news; + Plane Surface(s) = {cl}; + Transfinite Surface{s}; + Recombine Surface{s}; + S[i * 3 + j] = s; + EndFor +EndFor + +ext[] = Extrude {{1, 0, 0}, {0, 0, 0}, angle * Pi / 180} { Surface{S[]}; Layers{1}; Recombine; }; + +// Extrude returns, per source surface, the rotated copy, the volume and the four side surfaces. +For k In {0:5} + top[k] = ext[6 * k]; + vol[k] = ext[6 * k + 1]; +EndFor + +e = 1e-4 * D; +big = 2 * rmax * D; +inlet[] = Surface In BoundingBox{x0 * D - e, -big, -big, x0 * D + e, big, big}; +jet[] = Surface In BoundingBox{x0 * D - e, -big, -big, x0 * D + e, rjet * D + e, big}; +outlet[] = Surface In BoundingBox{xmax * D - e, -big, -big, xmax * D + e, big, big}; +axis[] = Surface In BoundingBox{x0 * D - e, -big, -big, xmax * D + e, rmin * D + e, big}; +side[] = Surface In BoundingBox{x0 * D - e, rmax * D * Cos(a) - e, -big, xmax * D + e, rmax * D + e, big}; +open[] = inlet[]; +open[] -= jet[]; + +Physical Surface("inlet_jet") = {jet[]}; +Physical Surface("farfield") = {open[], side[]}; +Physical Surface("outlet") = {outlet[]}; +Physical Surface("axis") = {axis[]}; +Physical Surface("periodic_1") = {S[]}; +Physical Surface("periodic_2") = {top[]}; +Physical Volume("fluid") = {vol[]}; diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index fe4214a965f2..a056a72a1133 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -397,7 +397,7 @@ def main(): flatplate_udobj.cfg_dir = "user_defined_functions" flatplate_udobj.cfg_file = "lam_flatplate.cfg" flatplate_udobj.test_iter = 20 - flatplate_udobj.test_vals = [-0.001015, 596.450000, 299.550000, 296.900000, 21.318000, 0.586640, 36.553000, 2.188800] + flatplate_udobj.test_vals = [-0.002654, 597.560000, 299.980000, 297.580000, 23.837000, 0.682260, 38.421000, 4.051900] test_list.append(flatplate_udobj) # Probe performance test (11 probes, ADT path) @@ -405,7 +405,7 @@ def main(): probe_performance_11.cfg_dir = "user_defined_functions" probe_performance_11.cfg_file = "test_11_probes.cfg" probe_performance_11.test_iter = 4 - probe_performance_11.test_vals = [-6.290748, 101020, 101050, 99123] # RMS_DENSITY, probe1, probe6, probe11 + probe_performance_11.test_vals = [-6.262158, 100860.000000, 99454.000000, 98936.000000] # RMS_DENSITY, probe1, probe6, probe11 # Tolerances are typically 0.001 in TestCase.py test_list.append(probe_performance_11) @@ -459,7 +459,7 @@ def main(): periodic2d_no_limiter.cfg_dir = "navierstokes/periodic2D" periodic2d_no_limiter.cfg_file = "no_limiter.cfg" periodic2d_no_limiter.test_iter = 100 - periodic2d_no_limiter.test_vals = [-3.216881, -0.582813, -0.629049, 2.266141, -1.056877, -811.470000] + periodic2d_no_limiter.test_vals = [-3.285602, -0.612937, -0.682765, 2.194736, -1.019117, -952.960000] test_list.append(periodic2d_no_limiter) # 2D rotational periodic sector with multigrid @@ -467,7 +467,7 @@ def main(): periodic2d_multigrid.cfg_dir = "navierstokes/periodic2D" periodic2d_multigrid.cfg_file = "multigrid.cfg" periodic2d_multigrid.test_iter = 300 - periodic2d_multigrid.test_vals = [-4.422778, -1.615251, -1.453736, 1.047350, -1.410225, -2060.600000] + periodic2d_multigrid.test_vals = [-4.405188, -1.589621, -1.470131, 1.066630, -1.430812, -2072.000000] test_list.append(periodic2d_multigrid) # 2D rotational periodic sector with limiter @@ -475,7 +475,7 @@ def main(): periodic2d.cfg_dir = "navierstokes/periodic2D" periodic2d.cfg_file = "config.cfg" periodic2d.test_iter = 100 - periodic2d.test_vals = [-3.266248, -0.617784, -0.620252, 2.216476, -1.007761, -1035.000000] + periodic2d.test_vals = [-3.308159, -0.637985, -0.693116, 2.172259, -1.021650, -958.960000] test_list.append(periodic2d) ########################## @@ -876,7 +876,7 @@ def main(): sp_pipeSlice_3d_dp_hf_tp.cfg_dir = "incomp_navierstokes/streamwise_periodic/pipeSlice_3d" sp_pipeSlice_3d_dp_hf_tp.cfg_file = "sp_pipeSlice_3d_dp_hf_tp.cfg" sp_pipeSlice_3d_dp_hf_tp.test_iter = 10 - sp_pipeSlice_3d_dp_hf_tp.test_vals = [-11.119796, -11.234737, -9.429479, -0.000023] + sp_pipeSlice_3d_dp_hf_tp.test_vals = [-13.241550, -13.260364, -10.953558, -0.000025] test_list.append(sp_pipeSlice_3d_dp_hf_tp) # 2D pin array with heat transfer BC on pin surfaces @@ -899,6 +899,14 @@ def main(): inc_turb_naca0012.test_vals = [-4.758064, -10.974498, -0.000005, -0.028653, 3, -5.740545, 2, -5.036110] test_list.append(inc_turb_naca0012) + # Swirling jet on a one-cell wedge, rotational periodicity (Morse 1980) + inc_turb_morse_swirl_jet = TestCase('inc_turb_morse_swirl_jet') + inc_turb_morse_swirl_jet.cfg_dir = "incomp_rans/morse_swirl_jet" + inc_turb_morse_swirl_jet.cfg_file = "morse_sa.cfg" + inc_turb_morse_swirl_jet.test_iter = 10 + inc_turb_morse_swirl_jet.test_vals = [-10.168926, -7.347914, -8.685155, 13.000000, -4.156951, 71.328000] + test_list.append(inc_turb_morse_swirl_jet) + # NACA0012, SST_SUST inc_turb_naca0012_sst_sust = TestCase('inc_turb_naca0012_sst_sust') inc_turb_naca0012_sst_sust.cfg_dir = "incomp_rans/naca0012" @@ -1284,7 +1292,7 @@ def main(): sbs_backward_step.cfg_dir = "backscatter/backward_step" sbs_backward_step.cfg_file = "backwardStep.cfg" sbs_backward_step.test_iter = 3 - sbs_backward_step.test_vals = [-6.352884, -3.465372, -5.507901, -3.906545, -9.506305, -6.365236, -6.331021, -6.331028] + sbs_backward_step.test_vals = [-6.353146, -3.465452, -5.470619, -3.906555, -9.506332, -6.365239, -6.331024, -6.331030] sbs_backward_step.unsteady = True sbs_backward_step.decompress = True sbs_backward_step.grid_file = "backward_step.su2" @@ -1304,7 +1312,7 @@ def main(): flatplate_unsteady.cfg_dir = "navierstokes/flatplate" flatplate_unsteady.cfg_file = "lam_flatplate_unst.cfg" flatplate_unsteady.test_iter = 3 - flatplate_unsteady.test_vals = [0.000008, -8.875128, -8.250204, -6.305788, -5.469452, -3.398230, 0.002075, -0.325535] + flatplate_unsteady.test_vals = [0.000008, -8.875141, -8.250617, -6.305804, -5.469459, -3.398234, 0.002074, -0.310165] flatplate_unsteady.unsteady = True test_list.append(flatplate_unsteady) @@ -1364,7 +1372,7 @@ def main(): Aachen_3D_restart.cfg_file = "aachen_3D_MP_restart.cfg" Aachen_3D_restart.test_iter = 5 Aachen_3D_restart.tol = 0.00001 - Aachen_3D_restart.test_vals = [-7.688483, -8.466346, -6.035067, -6.425967, -5.820125, -4.597817, -5.528297, -5.301466, -3.819862, -5.242356, -5.738805, -3.630202, -2.213240, -2.857919, -0.576864] + Aachen_3D_restart.test_vals = [-7.688485, -8.467588, -6.035067, -6.427338, -5.819784, -4.597818, -5.529569, -5.305004, -3.819863, -5.242440, -5.756583, -3.630202, -2.213244, -2.860891, -0.576864] test_list.append(Aachen_3D_restart) # Jones APU Turbocharger restart @@ -1372,7 +1380,7 @@ def main(): Jones_tc_restart.cfg_dir = "turbomachinery/APU_turbocharger" Jones_tc_restart.cfg_file = "Jones_restart.cfg" Jones_tc_restart.test_iter = 5 - Jones_tc_restart.test_vals = [-11.905727, -12.211201, -19.212537, -13.508616, -19.078613, -13.445675, 73286.000000, 73286.000000, 0.020056, 82.286000] + Jones_tc_restart.test_vals = [-11.914198, -12.203720, -19.150460, -13.443363, -19.037618, -13.395928, 73286.000000, 73286.000000, 0.020056, 82.286000] test_list.append(Jones_tc_restart) # 2D axial stage @@ -1380,7 +1388,7 @@ def main(): axial_stage2D.cfg_dir = "turbomachinery/axial_stage_2D" axial_stage2D.cfg_file = "Axial_stage2D.cfg" axial_stage2D.test_iter = 20 - axial_stage2D.test_vals = [1.167500, 1.598546, -2.928573, 2.573647, -2.527331, 3.016254, 106370.000000, 106370.000000, 5.726800, 64.383000] + axial_stage2D.test_vals = [1.176763, 1.601270, -2.961800, 2.541146, -2.531370, 3.013521, 106390.000000, 106390.000000, 5.735500, 64.426000] test_list.append(axial_stage2D) # 2D transonic stator restart @@ -1388,7 +1396,7 @@ def main(): transonic_stator_restart.cfg_dir = "turbomachinery/transonic_stator_2D" transonic_stator_restart.cfg_file = "transonic_stator_restart.cfg" transonic_stator_restart.test_iter = 20 - transonic_stator_restart.test_vals = [-4.365636, -2.482248, -2.081252, 1.729763, -1.467305, 3.231073, -471620.000000, 94.837000, -0.046834] + transonic_stator_restart.test_vals = [-4.389126, -2.515434, -2.103674, 1.706003, -1.488483, 3.231947, -471620.000000, 94.841000, -0.046801] transonic_stator_restart.test_vals_aarch64 = [-4.437809, -2.553049, -2.164729, 1.657542, -1.356823, 3.178788, -471620.000000, 94.842000, -0.040365] test_list.append(transonic_stator_restart) @@ -1397,7 +1405,7 @@ def main(): multi_interface.cfg_dir = "turbomachinery/multi_interface" multi_interface.cfg_file = "multi_interface_rst.cfg" multi_interface.test_iter = 5 - multi_interface.test_vals = [-8.634558, -8.895554, -9.348754] + multi_interface.test_vals = [-8.633076, -8.894747, -9.348617] multi_interface.test_vals_aarch64 = [-8.632227, -8.894736, -9.348706] test_list.append(multi_interface) @@ -1480,7 +1488,7 @@ def main(): bars_SST_2D.cfg_dir = "sliding_interface/bars_SST_2D" bars_SST_2D.cfg_file = "bars.cfg" bars_SST_2D.test_iter = 13 - bars_SST_2D.test_vals = [13.000000, -0.464267, -1.541047] + bars_SST_2D.test_vals = [13.000000, -0.464304, -1.546997] bars_SST_2D.multizone = True test_list.append(bars_SST_2D) @@ -1617,7 +1625,7 @@ def main(): solid_periodic_pins.cfg_dir = "solid_heat_conduction/periodic_pins" solid_periodic_pins.cfg_file = "configSolid.cfg" solid_periodic_pins.test_iter = 750 - solid_periodic_pins.test_vals = [-15.878962, -14.569206, 300.900000, 425.320000, 5.000000, -1.672653] + solid_periodic_pins.test_vals = [-15.931359, -14.386112, 300.900000, 425.320000, 0.000000, -14.007572] solid_periodic_pins.test_vals_aarch64 = [-15.879016, -14.569206, 300.900000, 425.320000, 5.000000, -1.672666] test_list.append(solid_periodic_pins) diff --git a/TestCases/serial_regression.py b/TestCases/serial_regression.py index 2dcd75403859..e152406b2d73 100755 --- a/TestCases/serial_regression.py +++ b/TestCases/serial_regression.py @@ -216,7 +216,7 @@ def main(): poiseuille.cfg_dir = "navierstokes/poiseuille" poiseuille.cfg_file = "lam_poiseuille.cfg" poiseuille.test_iter = 10 - poiseuille.test_vals = [-7.597002, -6.994814, 0.012154, 13.596296, 0] + poiseuille.test_vals = [-7.597001, -6.994813, 0.012127, 13.596354, 0.000000] test_list.append(poiseuille) # 2D Poiseuille flow (inlet profile file) @@ -936,7 +936,7 @@ def main(): ls89_sa.cfg_dir = "nicf/LS89" ls89_sa.cfg_file = "turb_SA_PR.cfg" ls89_sa.test_iter = 20 - ls89_sa.test_vals = [-5.041500, -13.379523, 0.179019, 0.420831] + ls89_sa.test_vals = [-5.047026, -13.385356, 0.179168, 0.421262] test_list.append(ls89_sa) # Rarefaction shock wave edge_VW @@ -965,7 +965,7 @@ def main(): Aachen_3D_restart.cfg_dir = "turbomachinery/Aachen_turbine" Aachen_3D_restart.cfg_file = "aachen_3D_MP_restart.cfg" Aachen_3D_restart.test_iter = 5 - Aachen_3D_restart.test_vals = [-7.689117, -8.476204, -6.036107, -6.427402, -5.831576, -4.599024, -5.530512, -5.305687, -3.821789, -5.243255, -5.754831, -3.631603, -2.213934, -2.895728, -0.578545] + Aachen_3D_restart.test_vals = [-7.690756, -8.480220, -6.040279, -6.426434, -5.831445, -4.598589, -5.536489, -5.307971, -3.830619, -5.244603, -5.766097, -3.635129, -2.215856, -2.900116, -0.583139] Aachen_3D_restart.enabled_with_asan = False test_list.append(Aachen_3D_restart) @@ -974,7 +974,7 @@ def main(): Jones_tc_restart.cfg_dir = "turbomachinery/APU_turbocharger" Jones_tc_restart.cfg_file = "Jones_restart.cfg" Jones_tc_restart.test_iter = 5 - Jones_tc_restart.test_vals = [-11.905629, -12.211684, -19.212618, -13.507994, -19.069281, -13.439288, 73286.000000, 73286.000000, 0.020056, 82.286000] + Jones_tc_restart.test_vals = [-11.913929, -12.201923, -19.149798, -13.441884, -19.033169, -13.395061, 73286.000000, 73286.000000, 0.020056, 82.286000] test_list.append(Jones_tc_restart) # 2D axial stage @@ -982,7 +982,7 @@ def main(): axial_stage2D.cfg_dir = "turbomachinery/axial_stage_2D" axial_stage2D.cfg_file = "Axial_stage2D.cfg" axial_stage2D.test_iter = 20 - axial_stage2D.test_vals = [1.167521, 1.598536, -2.928575, 2.573646, -2.527330, 3.016253, 106370.000000, 106370.000000, 5.726800, 64.383000] + axial_stage2D.test_vals = [1.177225, 1.602363, -2.962970, 2.540072, -2.535614, 3.008265, 106390.000000, 106390.000000, 5.735500, 64.426000] test_list.append(axial_stage2D) # 2D transonic stator restart @@ -990,7 +990,7 @@ def main(): transonic_stator_restart.cfg_dir = "turbomachinery/transonic_stator_2D" transonic_stator_restart.cfg_file = "transonic_stator_restart.cfg" transonic_stator_restart.test_iter = 20 - transonic_stator_restart.test_vals = [-4.367784, -2.492912, -2.082414, 1.727491, -1.466974, 3.224730, -471620.000000, 94.839000, -0.052082] + transonic_stator_restart.test_vals = [-4.391061, -2.520781, -2.103750, 1.703960, -1.488302, 3.226640, -471620.000000, 94.842000, -0.051820] transonic_stator_restart.test_vals_aarch64 = [-4.367784, -2.492912, -2.082414, 1.727491, -1.466974, 3.224730, -471620.000000, 94.839000, -0.052082] test_list.append(transonic_stator_restart) @@ -999,7 +999,7 @@ def main(): multi_interface.cfg_dir = "turbomachinery/multi_interface" multi_interface.cfg_file = "multi_interface_rst.cfg" multi_interface.test_iter = 5 - multi_interface.test_vals = [-8.634558, -8.895554, -9.348754] + multi_interface.test_vals = [-8.632926, -8.895296, -9.348618] multi_interface.test_vals_aarch64 = [-8.632227, -8.894736, -9.348706] test_list.append(multi_interface) @@ -1094,7 +1094,7 @@ def main(): bars_SST_2D.cfg_dir = "sliding_interface/bars_SST_2D" bars_SST_2D.cfg_file = "bars.cfg" bars_SST_2D.test_iter = 13 - bars_SST_2D.test_vals = [13.000000, -0.462697, -1.541051] + bars_SST_2D.test_vals = [13.000000, -0.462739, -1.546996] bars_SST_2D.multizone = True test_list.append(bars_SST_2D) From 8548a036f812eb0bf0e4eadaddaa4c6eb7798648 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 14 Nov 2026 08:54:23 +0100 Subject: [PATCH 06/40] Large wall distance instead of zero when there are no viscous walls Without viscous walls, CGeometry::ComputeWallDistance set the distance to zero at every point. The SA and SST source terms (and the LM transition sources) are skipped where the distance is zero, so a wall-free RANS domain such as a free jet had no turbulence production or destruction: the turbulence variables were only convected and diffused from the inflow. The distance is now 1e15. SA then takes its free-shear limit (S_hat -> Omega, destruction -> 0), SST gets F1 = F2 = 0 (k-epsilon branch), and DES length scales become the grid scale. 1e15 keeps d^2 far from overflow. The only affected regression test is rans/actuatordisk_bem: rms[nu_tilde] at iteration 15 changes from -10.32 to -8.60, because the restart was computed without SA sources. Co-Authored-By: Claude Opus 5.5 --- Common/include/geometry/CGeometry.hpp | 3 ++- Common/src/geometry/CGeometry.cpp | 6 ++++-- TestCases/parallel_regression.py | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Common/include/geometry/CGeometry.hpp b/Common/include/geometry/CGeometry.hpp index be300f79802d..92bd78016b39 100644 --- a/Common/include/geometry/CGeometry.hpp +++ b/Common/include/geometry/CGeometry.hpp @@ -1976,7 +1976,8 @@ class CGeometry { virtual void SetWallDistance(su2double val) {} /*! - * \brief Compute the distances to the closest vertex on viscous walls over the entire domain + * \brief Compute the distances to the closest vertex on viscous walls over the entire domain. + * \note Without viscous walls, all points get a distance of 1e15. * \param[in] config_container - Definition of the particular problem. * \param[in] geometry_container - Geometrical definition of the problem. */ diff --git a/Common/src/geometry/CGeometry.cpp b/Common/src/geometry/CGeometry.cpp index 8ecaf3a89c6f..985f56c263dd 100644 --- a/Common/src/geometry/CGeometry.cpp +++ b/Common/src/geometry/CGeometry.cpp @@ -4583,11 +4583,13 @@ void CGeometry::ComputeWallDistance(const CConfig* const* config_container, CGeo } } - /*--- If there are no viscous walls in the entire domain, set distances to zero ---*/ + /*--- Without viscous walls every point is far from a wall. The distance is large but finite, + * so that its square does not overflow, and the turbulence models take their free-shear limit. ---*/ if (allEmpty) { + constexpr passivedouble noWallDistance = 1e15; for (int iZone = 0; iZone < nZone; iZone++) { CGeometry* geometry = geometry_container[iZone][iInst][MESH_0]; - geometry->SetWallDistance(0.0); + geometry->SetWallDistance(noWallDistance); } continue; } diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 37143747ef57..9e628e892111 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -687,7 +687,7 @@ def main(): actuatordisk_bem.cfg_dir = "rans/actuatordisk_bem" actuatordisk_bem.cfg_file = "actuatordisk_bem.cfg" actuatordisk_bem.test_iter = 15 - actuatordisk_bem.test_vals = [-5.389236, -10.319122, 0.001362, -0.376528] + actuatordisk_bem.test_vals = [-5.389310, -8.599885, 0.001362, -0.376530] actuatordisk_bem.timeout = 3200 actuatordisk_bem.tol = 0.001 test_list.append(actuatordisk_bem) From 8bd6c746b6d80366615287558e6360aaf55b7fb9 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 19 Nov 2026 17:53:50 +0100 Subject: [PATCH 07/40] Implicit progress variable source Jacobian for flamelet solver The progress variable source was treated fully explicitly, which stalls the PV equation at high CFL. Add the decreasing part of dS/dPV, obtained from a forward-difference table lookup, to the Jacobian diagonal. With CFL 1e5, an ILU preconditioner and a consistent table, the unsteady 1D premixed flame converges in 8-10 inner iterations per time step and matches a 300-inner-iteration reference. Flamelet regression residuals shift slightly; reference values are not yet updated. Co-Authored-By: Claude Opus 5.5 --- .../variables/CSpeciesFlameletVariable.hpp | 11 +++++++++++ SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 17 ++++++++++++++++- .../src/variables/CSpeciesFlameletVariable.cpp | 1 + 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp b/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp index 6a8b21969f12..a7a4b0f98842 100644 --- a/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp +++ b/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp @@ -39,6 +39,7 @@ class CSpeciesFlameletVariable final : public CSpeciesVariable { MatrixType lookup_scalar; /*!< \brief Vector of the source terms from the lookup table for each scalar equation */ su2vector table_misses; /*!< \brief Vector of lookup table misses. */ MatrixType source_cons_jac; /*!< \brief Consumption-rate Jacobian dS_aux_i/dY_aux_i = source_cons_i, one column per user scalar. */ + VectorType source_pv_jac; /*!< \brief Derivative of the progress variable source with respect to the progress variable. */ public: /*! @@ -102,4 +103,14 @@ class CSpeciesFlameletVariable final : public CSpeciesVariable { inline su2double GetAuxSourceCons(unsigned long iPoint, unsigned long i_aux) const { return source_cons_jac(iPoint, i_aux); } + + /*! + * \brief Store the derivative of the progress variable source with respect to the progress variable. + */ + inline void SetSourceJacobianPV(unsigned long iPoint, su2double val) { source_pv_jac(iPoint) = val; } + + /*! + * \brief Get the derivative of the progress variable source with respect to the progress variable. + */ + inline su2double GetSourceJacobianPV(unsigned long iPoint) const { return source_pv_jac(iPoint); } }; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 9fdf81663b4e..5a0f0c753577 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -440,8 +440,12 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv /*--- Implicit: analytic Jacobian for auxiliary species from the split source form. * S_aux_i = source_prod_i + source_cons_i * Y_aux_i * dS_aux_i/dY_aux_i = source_cons_i - * J_ii += -source_cons_i * V ---*/ + * J_ii += -source_cons_i * V + * The progress variable gets the decreasing part of its source, per unit of rho*PV. ---*/ if (implicit) { + const su2double density = solver_container[FLOW_SOL]->GetNodes()->GetDensity(i_point); + const su2double dsource_dpv = fn->GetSourceJacobianPV(i_point); + Jacobian.AddVal2Diag(i_point, I_PROGVAR, fmax(0.0, -dsource_dpv) / density * volume); for (auto i_aux = 0u; i_aux < n_aux; i_aux++) { Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) * volume); } @@ -649,6 +653,17 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF vector source_scalar(flamelet_config_options.n_scalars); for (auto iCV = 0u; iCV < flamelet_config_options.n_control_vars; iCV++) source_scalar[iCV] = table_sources[iCV]; + /*--- Forward difference of the progress variable source, used only by the implicit Jacobian. ---*/ + if ((config->GetKind_TimeIntScheme() == EULER_IMPLICIT) && !AD::TapeActive()) { + const su2double delta = 1e-6; + vector scalars_pert = scalars; + scalars_pert[I_PROGVAR] += delta; + vector sources_pert(table_sources.size()); + fluid_model_local->EvaluateDataSet(scalars_pert, FLAMELET_LOOKUP_OPS::SOURCES, sources_pert); + const su2double dsource = (fmax(0, sources_pert[I_PROGVAR]) - table_sources[I_PROGVAR]) / delta; + static_cast(nodes)->SetSourceJacobianPV(iPoint, F * dsource); + } + /*--- Source term for the auxiliary species transport equations. ---*/ for (size_t i_aux = 0; i_aux < flamelet_config_options.n_user_scalars; i_aux++) { /*--- The source term for the auxiliary equations consists of a production term and a consumption term: diff --git a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index fabe59a038aa..46028e30bf12 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -54,6 +54,7 @@ CSpeciesFlameletVariable::CSpeciesFlameletVariable(const su2double* species_inf, lookup_scalar.resize(nPoint, flamelet_config_options.n_lookups) = su2double(0.0); table_misses.resize(nPoint) = 0; source_cons_jac.resize(nPoint, flamelet_config_options.n_user_scalars) = su2double(0.0); + source_pv_jac.resize(nPoint) = su2double(0.0); if (flamelet_config_options.preferential_diffusion) { nAuxVar = FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS; From b1387fae08045ca1e8bd4f7c29bff64ec961e580 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 19 Nov 2026 23:21:08 +0100 Subject: [PATCH 08/40] Update flamelet regression values for the implicit PV source Jacobian The extra Jacobian term changes the iteration history of the flamelet tests. The discrete adjoint tests change because the adjoint linear solves reuse the primal Jacobian; the converged adjoint is unchanged. Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression.py | 14 +++++++------- TestCases/parallel_regression_AD.py | 4 ++-- TestCases/tutorials.py | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 8b40bc4bc35f..6d982c5ec9ac 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -69,7 +69,7 @@ def main(): cfd_flamelet_ch4.cfg_dir = "flamelet/01_laminar_premixed_ch4_flame_cfd" cfd_flamelet_ch4.cfg_file = "lam_prem_ch4_cfd.cfg" cfd_flamelet_ch4.test_iter = 10 - cfd_flamelet_ch4.test_vals = [-10.539588, -12.650786, -5.649832, -13.470491, -17.249262, 94.854000] + cfd_flamelet_ch4.test_vals = [-10.539588, -12.650795, -5.649832, -13.470506, -17.249269, 94.854000] cfd_flamelet_ch4.new_output = True test_list.append(cfd_flamelet_ch4) @@ -78,7 +78,7 @@ def main(): cfd_flamelet_ch4_axi.cfg_dir = "flamelet/05_laminar_premixed_ch4_flame_cfd_axi" cfd_flamelet_ch4_axi.cfg_file = "lam_prem_ch4_cfd_axi.cfg" cfd_flamelet_ch4_axi.test_iter = 10 - cfd_flamelet_ch4_axi.test_vals = [-9.774148, -11.256092, -10.017960, -11.850827, -4.916267, 72.669000] + cfd_flamelet_ch4_axi.test_vals = [-9.774149, -11.256095, -10.017959, -11.850546, -4.916270, 72.669000] cfd_flamelet_ch4_axi.new_output = True test_list.append(cfd_flamelet_ch4_axi) @@ -88,7 +88,7 @@ def main(): cfd_flamelet_ch4_partial_premix.cfg_dir = "flamelet/06_laminar_partial_premixed_ch4_flame_cfd" cfd_flamelet_ch4_partial_premix.cfg_file = "lam_partial_prem_ch4_cfd.cfg" cfd_flamelet_ch4_partial_premix.test_iter = 10 - cfd_flamelet_ch4_partial_premix.test_vals = [-10.482722, -3.621055, -12.932224, -10.154391, 10.000000] + cfd_flamelet_ch4_partial_premix.test_vals = [-10.482684, -3.621055, -12.932224, -10.154389, 10.000000] cfd_flamelet_ch4_partial_premix.new_output = True test_list.append(cfd_flamelet_ch4_partial_premix) @@ -97,7 +97,7 @@ def main(): cfd_flamelet_h2.cfg_dir = "flamelet/07_laminar_premixed_h2_flame_cfd" cfd_flamelet_h2.cfg_file = "laminar_premixed_h2_flame_cfd.cfg" cfd_flamelet_h2.test_iter = 5 - cfd_flamelet_h2.test_vals = [-8.036799, -8.329782, -1.805324, -8.959656] + cfd_flamelet_h2.test_vals = [-8.036810, -8.328814, -1.805276, -8.959649] test_list.append(cfd_flamelet_h2) # Flame ignition methods @@ -105,7 +105,7 @@ def main(): flame_init_methods.cfg_dir = "flamelet/08_flame_init_method" flame_init_methods.cfg_file ="flamelet_initialization.py" flame_init_methods.command = TestCase.Command("mpirun -np 2", "python", "flamelet_initialization.py") - flame_init_methods.test_vals=[1600, 1600] + flame_init_methods.test_vals=[1600, 1595.82] flame_init_methods.new_output = True test_list.append(flame_init_methods) @@ -114,7 +114,7 @@ def main(): cfd_flamelet_ch4_unsteady.cfg_dir = "flamelet/09_laminar_premixed_ch4_flame_unsteady" cfd_flamelet_ch4_unsteady.cfg_file = "lam_prem_ch4_unsteady.cfg" cfd_flamelet_ch4_unsteady.test_iter = 5 - cfd_flamelet_ch4_unsteady.test_vals = [-8.856677, -8.095263, -9.153743, -9.321676] + cfd_flamelet_ch4_unsteady.test_vals = [-8.853384, -8.095207, -9.153687, -9.321693] cfd_flamelet_ch4_unsteady.test_vals_aarch64 = [-8.855500, -8.095195, -9.153704, -9.321686] test_list.append(cfd_flamelet_ch4_unsteady) @@ -2088,7 +2088,7 @@ def main(): cfd_flamelet_ch4_cht.cfg_dir = "flamelet/03_laminar_premixed_ch4_flame_cht_cfd" cfd_flamelet_ch4_cht.cfg_file = "lam_prem_ch4_cht_cfd_master.cfg" cfd_flamelet_ch4_cht.test_iter = 5 - cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410156, -3.171365, -10.884464, -12.615132, -6.614396] + cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410206, -3.171365, -10.884587, -12.615132, -6.614396] cfd_flamelet_ch4_cht.timeout = 1600 cfd_flamelet_ch4_cht.multizone = True test_list.append(cfd_flamelet_ch4_cht) diff --git a/TestCases/parallel_regression_AD.py b/TestCases/parallel_regression_AD.py index c180caf45f40..891557a0bf1e 100644 --- a/TestCases/parallel_regression_AD.py +++ b/TestCases/parallel_regression_AD.py @@ -373,7 +373,7 @@ def main(): discadj_flamelet_ch4_hx.cfg_file = "lam_prem_ch4_hx_ad.cfg" discadj_flamelet_ch4_hx.multizone = False discadj_flamelet_ch4_hx.test_iter = 10 - discadj_flamelet_ch4_hx.test_vals = [-9.083502, -9.033520, -9.529644, -8.442386, -15.399568, -6.169865, -18.881156] + discadj_flamelet_ch4_hx.test_vals = [-9.079012, -9.032987, -9.517245, -7.478949, -15.369708, -6.169865, -18.881156] test_list.append(discadj_flamelet_ch4_hx) # 2D planar laminar premixed flame on isothermal burner with conjugate heat transfer (restart) @@ -382,7 +382,7 @@ def main(): discadj_flamelet_ch4_cht.cfg_file = "lam_prem_ch4_cht_ad_master.cfg" discadj_flamelet_ch4_cht.multizone = True discadj_flamelet_ch4_cht.test_iter = 10 - discadj_flamelet_ch4_cht.test_vals = [-1.545058, 0.628666, -6.533534, -18.651078, -18.648552, -3.794724, -6.572494, 11.000000] + discadj_flamelet_ch4_cht.test_vals = [-1.545086, 0.628721, -6.533534, -18.651078, -18.648552, -3.794724, -6.572494, 11.000000] test_list.append(discadj_flamelet_ch4_cht) ###################################### diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index dd739f2e24d9..763f21e9ebd5 100644 --- a/TestCases/tutorials.py +++ b/TestCases/tutorials.py @@ -177,7 +177,7 @@ def main(): premixed_hydrogen.cfg_dir = "../Tutorials/incompressible_flow/Inc_Combustion/1__premixed_hydrogen" premixed_hydrogen.cfg_file = "H2_burner.cfg" premixed_hydrogen.test_iter = 10 - premixed_hydrogen.test_vals = [-8.769581, -9.719802, -10.162061, -3.439369, -11.529638] + premixed_hydrogen.test_vals = [-8.769564, -9.719765, -10.153710, -3.439336, -11.528098] test_list.append(premixed_hydrogen) ### Compressible Flow From 899ab149e8bd4440cae1abce6d355324a4ec9c13 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 21 Nov 2026 11:50:07 +0100 Subject: [PATCH 09/40] update monitor for unsteady plotting --- SU2_PY/SU2_MON | 2 +- SU2_PY/monitor.py | 194 +++++++++++++++++++++++++++++------ SU2_PY/tests/test_monitor.py | 42 +++++++- 3 files changed, 199 insertions(+), 39 deletions(-) diff --git a/SU2_PY/SU2_MON b/SU2_PY/SU2_MON index 638e47ad3af2..4f4bc0f7076f 100755 --- a/SU2_PY/SU2_MON +++ b/SU2_PY/SU2_MON @@ -1,2 +1,2 @@ #!/bin/bash -cd "$(dirname "$(readlink -f "$0")")" && python monitor.py "$@" +exec python "$(dirname "$(readlink -f "$0")")/monitor.py" "$@" diff --git a/SU2_PY/monitor.py b/SU2_PY/monitor.py index 44347c116ace..6797a8b07b28 100755 --- a/SU2_PY/monitor.py +++ b/SU2_PY/monitor.py @@ -46,12 +46,15 @@ RESIDUAL_PATTERN = re.compile("rms|Res") COEFFICIENT_PATTERN = re.compile("^(CD|CL|CMx|CMy|CMz|CFx|CFy|CFz)$") -# inner counter: first of these present in the history, else the row index +# inner counter: first of these present in the history, else the row number from 1 ITERATION_COLUMNS = ("Inner_Iter", "Outer_Iter") +INNER_COLUMN = "Inner_Iter" +OUTER_COLUMN = "Outer_Iter" TIME_COLUMN = "Time_Iter" MAX_POINTS = 4000 READ_BLOCK_BYTES = 32 * 1024 * 1024 UPDATE_INTERVAL_MS = 1000 +INNER_TIP = "Plot every inner iteration, not only the last one of each step" LOGO_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logoSU2.png") @@ -84,10 +87,13 @@ def reset(self): self.cols = None self.iter_col = None self.time_col = None + self.outer_col = None + self.has_inner_col = False self.names = [] self.buf = np.empty((1024, 0)) self.iters = np.empty(1024) self.times = np.empty(1024) + self.outers = np.empty(1024) self.n = 0 self.version += 1 self.readHeader() @@ -124,9 +130,14 @@ def readHeader(self): self.iter_col = allnames.index(counter) break self.time_col = allnames.index(TIME_COLUMN) if TIME_COLUMN in allnames else None + self.outer_col = ( + allnames.index(OUTER_COLUMN) if OUTER_COLUMN in allnames else None + ) + self.has_inner_col = INNER_COLUMN in allnames self.buf = np.empty((1024, len(self.cols))) self.iters = np.empty(1024) self.times = np.empty(1024) + self.outers = np.empty(1024) self.offset = offset # reads the complete lines appended since the last call; returns True if rows were added @@ -155,7 +166,11 @@ def update(self): wanted = sorted( { *self.cols, - *(c for c in (self.iter_col, self.time_col) if c is not None), + *( + c + for c in (self.iter_col, self.time_col, self.outer_col) + if c is not None + ), } ) table = pd.read_csv( @@ -169,17 +184,22 @@ def update(self): iters = ( table[self.iter_col].to_numpy() if self.iter_col is not None - else np.arange(self.n, self.n + len(table), dtype=np.float64) + else np.arange(self.n + 1, self.n + len(table) + 1, dtype=np.float64) ) times = ( table[self.time_col].to_numpy() if self.time_col is not None else iters ) + outers = ( + table[self.outer_col].to_numpy() + if self.outer_col is not None + else iters + ) except (pd.errors.EmptyDataError, pd.errors.ParserError, ValueError): break self.offset += end + 1 - self.append(rows, iters, times) + self.append(rows, iters, times, outers) added = True if added: @@ -192,35 +212,98 @@ def hasTime(self): # True once Time_Iter takes more than one value, i.e. the history is unsteady def timeAdvances(self): times = self.times[: self.n] - return self.hasTime() and self.n > 0 and times.max() > times.min() - - # rows at or after iteration 'start', thinned to at most MAX_POINTS; - # by time step, only the last row of each Time_Iter is kept - def rowsFrom(self, start, byTime=False): - counter = self.times if byTime and self.hasTime() else self.iters - counter = counter[: self.n] - keep = counter >= start - if byTime and self.hasTime(): - keep[:-1] &= counter[1:] != counter[:-1] - rows = np.flatnonzero(keep) - return rows[:: max(1, -(-len(rows) // MAX_POINTS))] - - def append(self, rows, iters, times): + return bool(self.hasTime() and self.n > 0 and times.max() > times.min()) + + # counter that groups the inner iterations into steps: the first of Time_Iter and + # Outer_Iter that advances, else the first present; None without Inner_Iter + def stepCounter(self): + if not self.has_inner_col or self.n == 0: + return None + present = [] + if self.hasTime(): + present.append(self.times[: self.n]) + if self.outer_col is not None: + present.append(self.outers[: self.n]) + for steps in present: + if steps.max() > steps.min(): + return steps + return present[0] if present else None + + # True once the history holds more than one step + def stepsAdvance(self): + steps = self.stepCounter() + return steps is not None and bool(steps.max() > steps.min()) + + # True when some time step or outer iteration holds more than one row + def hasInnerRows(self): + steps = self.stepCounter() + return steps is not None and bool(np.any(steps[1:] == steps[:-1])) + + # first row, row count and value of every group of equal step counters + @staticmethod + def groups(steps): + starts = np.flatnonzero(np.r_[True, steps[1:] != steps[:-1]]) + counts = np.diff(np.r_[starts, len(steps)]) + return starts, counts, steps[starts] + + # inner iterations counted over all steps, assuming Inner_Iter restarts at 0 every step + def cumulativeInner(self, steps): + starts, counts, _ = self.groups(steps) + within = np.arange(self.n) - np.repeat(starts, counts) + if self.has_inner_col: + within = self.iters[: self.n] + lengths = within[starts + counts - 1] + 1 + else: + lengths = counts + offsets = np.r_[0, np.cumsum(lengths)[:-1]] + return np.repeat(offsets, counts) + within + + # time step plus the fraction of the step, so the last row of a step lands on Time_Iter + def fractionalTime(self, steps): + starts, counts, values = self.groups(steps) + span = counts.astype(np.float64) + if len(span) > 1: + span[-1] = max(span[-1], span[-2]) + within = np.arange(self.n) - np.repeat(starts, counts) + return np.repeat(values - 1, counts) + (within + 1) / np.repeat(span, counts) + + # rows whose x value, or time step when plotted by time, is at or after 'start', and + # their x values, thinned to MAX_POINTS; + # without 'inner' only the last row of each time step or outer iteration is kept + def select(self, start, byTime=False, inner=False): + byTime = byTime and self.hasTime() + steps = self.stepCounter() + keep = np.ones(self.n, dtype=bool) + first = None + if steps is None: + x = (self.times if byTime else self.iters)[: self.n] + if byTime: + keep[:-1] = x[1:] != x[:-1] + elif inner: + x = self.fractionalTime(steps) if byTime else self.cumulativeInner(steps) + first = steps if byTime else None + else: + keep[:-1] = steps[1:] != steps[:-1] + x = self.times[: self.n] if byTime else self.cumulativeInner(steps) + rows = np.flatnonzero(keep & ((x if first is None else first) >= start)) + rows = rows[:: max(1, -(-len(rows) // MAX_POINTS))] + return rows, x[rows] + + def append(self, rows, iters, times, outers): needed = self.n + len(rows) if needed > len(self.buf): size = max(needed, 2 * len(self.buf)) grown = np.empty((size, self.buf.shape[1])) grown[: self.n] = self.buf[: self.n] self.buf = grown - grownIters = np.empty(size) - grownIters[: self.n] = self.iters[: self.n] - self.iters = grownIters - grownTimes = np.empty(size) - grownTimes[: self.n] = self.times[: self.n] - self.times = grownTimes + for name in ("iters", "times", "outers"): + column = np.empty(size) + column[: self.n] = getattr(self, name)[: self.n] + setattr(self, name, column) self.buf[self.n : needed] = rows self.iters[self.n : needed] = iters self.times[self.n : needed] = times + self.outers[self.n : needed] = outers self.n = needed @@ -267,7 +350,17 @@ def names(self): return self.reader.names if self.reader is not None else [] # plots the residuals from iteration 'start' on; ymin/ymax of None means automatic range - def plot(self, listonoff, normalize, start, ymin, ymax, byTime=False, update=True): + def plot( + self, + listonoff, + normalize, + start, + ymin, + ymax, + byTime=False, + inner=False, + update=True, + ): if self.reader is None: return if update: @@ -280,6 +373,7 @@ def plot(self, listonoff, normalize, start, ymin, ymax, byTime=False, update=Tru ymin, ymax, byTime, + inner, self.reader.version, ) if key == self.lastkey: @@ -297,19 +391,20 @@ def plot(self, listonoff, normalize, start, ymin, ymax, byTime=False, update=Tru ax.set_ylabel(self.ylabel) self.lines = [ax.plot([], [], label=names[i])[0] for i in shown] - ax.set_xlabel( - "time iterations" if byTime and self.reader.hasTime() else "iterations" - ) + if byTime and self.reader.hasTime(): + ax.set_xlabel("time iterations") + elif self.reader.stepsAdvance(): + ax.set_xlabel("cumulative inner iterations") + else: + ax.set_xlabel("iterations") n = self.reader.n - rows = self.reader.rowsFrom(start, byTime) - x = ( - self.reader.times if byTime and self.reader.hasTime() else self.reader.iters - )[rows] + rows, x = self.reader.select(start, byTime, inner) for line, i in zip(self.lines, shown): y = self.reader.buf[rows, i] if normalize and n > 1 and abs(self.reader.buf[1, i]) > 1e-6: y = 1 + y - self.reader.buf[1, i] line.set_data(x, y) + line.set_marker("o" if len(x) == 1 else "None") ax.set_autoscaley_on(True) ax.relim() @@ -386,6 +481,7 @@ def __init__(self, owner, pattern, ylabel, title): self.normalize = False self.chkbx = [] self.chkbx_names = [] + self.inner_advance = False self.make_tab(title) def setFile(self, filename, label, tooltip): @@ -403,6 +499,29 @@ def updateTimeSwitch(self): self.btn_time.setEnabled(has) self.btn_time.setChecked(has) + # enabled when some step holds several inner rows; checked by default until a + # second step appears, the tooltip gives the reason when greyed out + def updateInnerSwitch(self): + reader = self.figure.reader + has = reader is not None and reader.hasInnerRows() + advance = reader is not None and reader.stepsAdvance() + if reader is None or has: + reason = INNER_TIP + elif not reader.has_inner_col: + reason = "Not available: no Inner_Iter column, add ITER to HISTORY_OUTPUT" + elif reader.stepCounter() is None: + reason = "Every row of the history is an inner iteration" + else: + reason = "Not available: one row per time step, set HISTORY_WRT_FREQ_INNER" + self.btn_inner.setToolTip(reason) + if has != self.btn_inner.isEnabled() or advance != self.inner_advance or not has: + self.btn_inner.setEnabled(has) + self.btn_inner.setChecked( + (has and not advance) + or (reader is not None and reader.has_inner_col and not has and not advance) + ) + self.inner_advance = advance + def setRunning(self, running): self.btn_plot_data.setText("stop" if running else "start") self.btn_plot_data.setToolTip( @@ -491,8 +610,14 @@ def make_tab(self, title): self.btn_time.setToolTip( "Plot against Time_Iter (last inner iteration of each step) instead of inner iterations" ) + self.btn_time.setEnabled(False) self.btn_time.stateChanged.connect(lambda _: self.changedata()) + self.btn_inner = QCheckBox("Inner iterations") + self.btn_inner.setToolTip(INNER_TIP) + self.btn_inner.setEnabled(False) + self.btn_inner.stateChanged.connect(lambda _: self.changedata()) + # now we add all the buttons in a vertical list self.btn_layout = QVBoxLayout() self.btn_layout.addWidget(self.btn_openfile) @@ -500,6 +625,7 @@ def make_tab(self, title): self.btn_layout.addWidget(self.btn_plot_data) self.btn_layout.addWidget(self.btn_normalize) self.btn_layout.addWidget(self.btn_time) + self.btn_layout.addWidget(self.btn_inner) self.btn_layout.addLayout(range_layout) self.btn_layout.addLayout(self.chk_layout) @@ -542,6 +668,7 @@ def draw(self, update): self.parse(self.edit_ymin, float), self.parse(self.edit_ymax, float), self.btn_time.isChecked(), + self.btn_inner.isChecked(), update=update, ) @@ -552,6 +679,7 @@ def plot_data(self): if self.figure.names() != self.chkbx_names: self.update_chkbx(self.figure.names()) self.updateTimeSwitch() + self.updateInnerSwitch() self.draw(update=False) # ################################### # @@ -600,7 +728,7 @@ def getfile(self): fname = QFileDialog.getOpenFileName( self, "Open file", - "history.csv", + os.path.join(os.getcwd(), "history.csv"), filter="csv files (*.csv)\n" "dat files (*.dat)\n" "all files (*)", ) if fname[0] == "": diff --git a/SU2_PY/tests/test_monitor.py b/SU2_PY/tests/test_monitor.py index e0c4fe81a550..74146a91f67f 100644 --- a/SU2_PY/tests/test_monitor.py +++ b/SU2_PY/tests/test_monitor.py @@ -64,11 +64,43 @@ def test_time_iterations(self): reader = self.reader(names + body) self.assertTrue(reader.hasTime()) np.testing.assert_array_equal(reader.iters[: reader.n][:5], [0, 1, 2, 3, 0]) - rows = reader.rowsFrom(1, byTime=True) - np.testing.assert_array_equal(reader.times[rows], [1, 2]) + rows, x = reader.select(1, byTime=True) + np.testing.assert_array_equal(x, [1, 2]) np.testing.assert_array_equal(reader.iters[rows], [3, 3]) self.assertFalse(self.reader(CSV + row(0) + row(1)).hasTime()) + def test_inner_iterations(self): + names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' + body = "".join( + f"{t}, {i}, {-t - 0.1 * i}\n" for t in range(3) for i in range(4) + ) + reader = self.reader(names + body) + self.assertTrue(reader.hasInnerRows()) + rows, x = reader.select(0, inner=True) + np.testing.assert_array_equal(rows, np.arange(12)) + np.testing.assert_array_equal(x, np.arange(12)) + _, x = reader.select(-1, byTime=True, inner=True) + np.testing.assert_allclose(x[:5], [-0.75, -0.5, -0.25, 0, 0.25]) + rows, x = reader.select(0) + np.testing.assert_array_equal(rows, [3, 7, 11]) + np.testing.assert_array_equal(x, [3, 7, 11]) + + def test_first_time_step_has_inner_rows(self): + names = '"Time_Iter","Outer_Iter","Inner_Iter","rms[Rho]"\n' + reader = self.reader(names + "".join(f"1, 0, {i}, {-0.1 * i}\n" for i in range(5))) + self.assertTrue(reader.hasInnerRows()) + self.assertFalse(reader.stepsAdvance()) + np.testing.assert_array_equal(reader.select(0)[0], [4]) + np.testing.assert_array_equal(reader.select(0, inner=True)[1], np.arange(5)) + + def test_time_steps_only_have_no_inner_rows(self): + names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' + reader = self.reader(names + "0, 9, -1\n1, 4, -2\n2, 6, -3\n") + self.assertFalse(reader.hasInnerRows()) + _, x = reader.select(0) + np.testing.assert_array_equal(x, [9, 14, 21]) + self.assertFalse(self.reader(CSV + row(0) + row(1)).hasInnerRows()) + def test_steady_time_counter_does_not_advance(self): names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' reader = self.reader(names + "".join(f"0, {i}, {-0.1 * i}\n" for i in range(5))) @@ -80,7 +112,7 @@ def test_steady_time_counter_does_not_advance(self): def test_first_row_kept_when_it_passes_the_filter(self): names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' reader = self.reader(names + "100, 0, -1\n") - np.testing.assert_array_equal(reader.rowsFrom(100, byTime=True), [0]) + np.testing.assert_array_equal(reader.select(100, byTime=True)[0], [0]) def test_partial_zone_line_is_deferred(self): self.path.write_text(CSV + 'ZONE T="Conv') @@ -102,8 +134,8 @@ def test_incomplete_header_is_deferred(self): def test_sparse_iterations_and_start_filter(self): reader = self.reader(CSV + row(0) + row(10) + row(20) + row(30)) np.testing.assert_array_equal(reader.iters[: reader.n], [0, 10, 20, 30]) - rows = reader.rowsFrom(15) - np.testing.assert_array_equal(reader.iters[rows], [20, 30]) + _, x = reader.select(15) + np.testing.assert_array_equal(x, [20, 30]) def test_incremental_append_and_incomplete_line(self): reader = self.reader(CSV + row(0) + row(1)) From 479c107aab46b8cedf2bfead831a30cc89c4d464 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 21 Nov 2026 12:18:50 +0100 Subject: [PATCH 10/40] Couple only fully fitting periodic points; fix quantized accumulation - Accumulating SetBlock is a no-op on quantized (Q_LU_SGS) off-diagonal blocks, so the moved blocks were dropped. Quantized blocks are now decoded, added and re-encoded; full-precision blocks keep the in-place addition, so results are unchanged bit for bit. - A passive point is coupled only if every moved block exists in the sparsity pattern of its master. On thicker periodic meshes only the along-face blocks fit; moving those alone slowed the discrete adjoint (transonic_stator AD from -7.31 to -6.76 at iteration 79). Now these meshes behave as on develop, and one-cell wedges and slices keep the full coupling. - Loops run over a list of the coupled passive points instead of all points. - CompletePeriodicComms comments named the wrong marker as master. - Regression values: periodic tests without coupled points are back to their develop values; Morse (after #3014) and the two pipeSlice tests use the values computed by CI. Co-Authored-By: Claude Opus 5.5 --- .../include/solvers/CFVMFlowSolverBase.hpp | 2 +- SU2_CFD/include/solvers/CSolver.hpp | 8 +- SU2_CFD/src/solvers/CSolver.cpp | 88 +++++++++++++------ TestCases/parallel_regression.py | 34 +++---- TestCases/serial_regression.py | 16 ++-- 5 files changed, 90 insertions(+), 58 deletions(-) diff --git a/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp b/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp index 23e9d8c1a639..214a74bdac70 100644 --- a/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp +++ b/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp @@ -444,7 +444,7 @@ class CFVMFlowSolverBase : public CSolver { ompMasterAssignBarrier(Min_Delta_Time,1e30, Max_Delta_Time,0.0, Global_Delta_UnstTimeND,1e30); - /*--- Edges between a point and its own periodic image carry only the rotation of the state. ---*/ + /*--- Edges between a point and its periodic image are left out, their states are tied. ---*/ const bool skipImages = implicit_periodic; if (skipImages) SetPeriodicMaster(geometry, config); diff --git a/SU2_CFD/include/solvers/CSolver.hpp b/SU2_CFD/include/solvers/CSolver.hpp index 5d3c26c67f0d..27ef57df94a1 100644 --- a/SU2_CFD/include/solvers/CSolver.hpp +++ b/SU2_CFD/include/solvers/CSolver.hpp @@ -149,8 +149,9 @@ class CSolver { bool implicit_periodic; /*!< \brief Flag that controls whether the implicit system should be treated by the periodic BC comms. */ su2activematrix PeriodicProj; /*!< \brief Min/max reconstruction increments at periodic receive points (for limiters). */ std::unordered_map PeriodicProjIndex; /*!< \brief Local point to compact projection row. */ - vector PeriodicMaster; /*!< \brief Local master point of each passive periodic point on this rank, or -1. */ + vector PeriodicMaster; /*!< \brief Local master point of each coupled passive periodic point, or -1. */ vector PeriodicMasterMarker; /*!< \brief Periodic marker of each passive point, gives its rotation. */ + vector PeriodicPassive; /*!< \brief Coupled passive periodic points. */ bool dynamic_grid; /*!< \brief Flag that determines whether the grid is dynamic (moving or deforming + grid velocities). */ @@ -330,12 +331,13 @@ class CSolver { /*! * \brief Move the off-diagonal Jacobian blocks of passive periodic points to their masters, rotated. - * \note Call before the PERIODIC_RESIDUAL comms. Only masters on the same rank and blocks in the sparsity pattern are coupled. + * \note Call before the PERIODIC_RESIDUAL comms. A passive point is coupled if its master is on the same rank and + * all its blocks fit in the sparsity pattern. */ void CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config); /*! - * \brief Map each passive periodic point to its master on the same rank (built once). + * \brief Map each coupled passive periodic point to its master on the same rank (built once). */ void SetPeriodicMaster(CGeometry *geometry, const CConfig *config); diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 9140200db186..1d1b281f0e3a 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -1276,7 +1276,7 @@ void CSolver::CompletePeriodicComms(CGeometry *geometry, base_nodes->SetDelta_Time(iPoint,bufDRecv[buf_offset]); buf_offset++; - /*--- For implicit integration, we choose the first + /*--- For implicit integration, we choose the second periodic face of each pair to be the master/owner of the solution for the linear system while fixing the solution at the matching face during the solve. Here, @@ -1308,7 +1308,7 @@ void CSolver::CompletePeriodicComms(CGeometry *geometry, case PERIODIC_IMPLICIT: - /*--- For implicit integration, we choose the first + /*--- For implicit integration, we choose the second periodic face of each pair to be the master/owner of the solution for the linear system while fixing the solution at the matching face during the solve. Here, @@ -4670,6 +4670,28 @@ void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { if (nPeriodicMarker[iPoint] != 1 || nPeriodicMarker[master] != 1 || passive[master]) PeriodicMaster[iPoint] = -1; } + + /*--- A point is coupled only if all its blocks fit in the sparsity pattern of its master. Columns of passive + * points without a master are ignored, their increment is zero in the linear system. ---*/ + if (implicit_periodic) { + for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { + const auto master = PeriodicMaster[iPoint]; + if (master < 0) continue; + bool fits = true; + for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { + if (iPoint < nPointDomain && (!passive[kPoint] || PeriodicMaster[kPoint] >= 0)) { + const unsigned long col = passive[kPoint] ? PeriodicMaster[kPoint] : kPoint; + fits = fits && Jacobian.GetBlockView(master, col); + } + if (kPoint < nPointDomain && !passive[kPoint]) fits = fits && Jacobian.GetBlockView(kPoint, master); + } + if (!fits) PeriodicMaster[iPoint] = -1; + } + } + + PeriodicPassive.clear(); + for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) + if (PeriodicMaster[iPoint] >= 0) PeriodicPassive.push_back(iPoint); } } @@ -4702,7 +4724,7 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) return true; }; - su2activematrix block(nVar, nVar), zero(nVar, nVar); + su2activematrix block(nVar, nVar), sum(nVar, nVar), zero(nVar, nVar); zero = su2double(0.0); su2double v[3]; @@ -4715,13 +4737,25 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) return true; }; + /*--- Add block to an existing block. Quantized storage cannot accumulate, it is decoded, added and re-encoded. ---*/ + auto AddBlock = [&](unsigned long iRow, unsigned long iCol) { + const auto view = Jacobian.GetBlockView(iRow, iCol); + if (view.ptr) { + Jacobian.SetBlock(iRow, iCol, block); + return; + } + for (auto i = 0u; i < nVar; i++) + for (auto j = 0u; j < nVar; j++) sum(i, j) = view(i, j) + block(i, j); + Jacobian.SetBlock(iRow, iCol, sum); + }; + auto RotateRows = [&](const su2double (&Q)[3][3]) { for (auto c = 0u; c < nVar; c++) { for (auto d = 0u; d < nDim; d++) v[d] = block(1 + d, c); for (auto d = 0u; d < nDim; d++) { - su2double sum = 0.0; - for (auto e = 0u; e < nDim; e++) sum += Q[d][e] * v[e]; - block(1 + d, c) = sum; + su2double s = 0.0; + for (auto e = 0u; e < nDim; e++) s += Q[d][e] * v[e]; + block(1 + d, c) = s; } } }; @@ -4731,9 +4765,9 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) for (auto r = 0u; r < nVar; r++) { for (auto d = 0u; d < nDim; d++) v[d] = block(r, 1 + d); for (auto d = 0u; d < nDim; d++) { - su2double sum = 0.0; - for (auto e = 0u; e < nDim; e++) sum += v[e] * Q[d][e]; - block(r, 1 + d) = sum; + su2double s = 0.0; + for (auto e = 0u; e < nDim; e++) s += v[e] * Q[d][e]; + block(r, 1 + d) = s; } } }; @@ -4741,36 +4775,32 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) su2double Qp[3][3], Qk[3][3]; /*--- Rows of passive points go to the rows of their masters. ---*/ - for (auto iPoint = 0ul; iPoint < nPointDomain; iPoint++) { + for (const auto iPoint : PeriodicPassive) { + if (iPoint >= nPointDomain) continue; const auto master = PeriodicMaster[iPoint]; - if (master < 0) continue; const bool rotP = Rotation(PeriodicMasterMarker[iPoint], Qp); for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { - if (!ReadBlock(iPoint, kPoint)) continue; - - long col = kPoint; - if (PeriodicMaster[kPoint] >= 0) { - col = PeriodicMaster[kPoint]; - if (Rotation(PeriodicMasterMarker[kPoint], Qk)) RotateColumns(Qk); - } + const bool kPassive = PeriodicMaster[kPoint] >= 0; + const unsigned long col = kPassive ? PeriodicMaster[kPoint] : kPoint; + if (!Jacobian.GetBlockView(master, col) || !ReadBlock(iPoint, kPoint)) continue; + if (kPassive && Rotation(PeriodicMasterMarker[kPoint], Qk)) RotateColumns(Qk); if (rotP) RotateRows(Qp); - - Jacobian.SetBlock(master, col, block); + AddBlock(master, col); } } /*--- Columns of passive points go to the columns of their masters. ---*/ - for (auto iPoint = 0ul; iPoint < nPointDomain; iPoint++) { - if (PeriodicMaster[iPoint] >= 0) continue; + for (const auto iPoint : PeriodicPassive) { + const auto master = PeriodicMaster[iPoint]; + const bool rotP = Rotation(PeriodicMasterMarker[iPoint], Qp); - for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { - const auto master = PeriodicMaster[kPoint]; - if (master < 0) continue; - if (!Jacobian.GetBlockView(iPoint, master) || !ReadBlock(iPoint, kPoint)) continue; - if (Rotation(PeriodicMasterMarker[kPoint], Qk)) RotateColumns(Qk); - Jacobian.SetBlock(iPoint, master, block); - Jacobian.SetBlock(iPoint, kPoint, zero); + for (const auto jPoint : geometry->nodes->GetPoints(iPoint)) { + if (jPoint >= nPointDomain || PeriodicMaster[jPoint] >= 0) continue; + if (!Jacobian.GetBlockView(jPoint, master) || !ReadBlock(jPoint, iPoint)) continue; + if (rotP) RotateColumns(Qp); + AddBlock(jPoint, master); + Jacobian.SetBlock(jPoint, iPoint, zero); } } diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 2a7fc19f8b32..a7bdf3ef2f82 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -397,7 +397,7 @@ def main(): flatplate_udobj.cfg_dir = "user_defined_functions" flatplate_udobj.cfg_file = "lam_flatplate.cfg" flatplate_udobj.test_iter = 20 - flatplate_udobj.test_vals = [-0.002654, 597.560000, 299.980000, 297.580000, 23.837000, 0.682260, 38.421000, 4.051900] + flatplate_udobj.test_vals = [-0.001015, 596.450000, 299.550000, 296.900000, 21.318000, 0.586640, 36.553000, 2.188800] test_list.append(flatplate_udobj) # Probe performance test (11 probes, ADT path) @@ -405,7 +405,7 @@ def main(): probe_performance_11.cfg_dir = "user_defined_functions" probe_performance_11.cfg_file = "test_11_probes.cfg" probe_performance_11.test_iter = 4 - probe_performance_11.test_vals = [-6.262158, 100860.000000, 99454.000000, 98936.000000] # RMS_DENSITY, probe1, probe6, probe11 + probe_performance_11.test_vals = [-6.290748, 101020, 101050, 99123] # RMS_DENSITY, probe1, probe6, probe11 # Tolerances are typically 0.001 in TestCase.py test_list.append(probe_performance_11) @@ -459,7 +459,7 @@ def main(): periodic2d_no_limiter.cfg_dir = "navierstokes/periodic2D" periodic2d_no_limiter.cfg_file = "no_limiter.cfg" periodic2d_no_limiter.test_iter = 100 - periodic2d_no_limiter.test_vals = [-3.285602, -0.612937, -0.682765, 2.194736, -1.019117, -952.960000] + periodic2d_no_limiter.test_vals = [-3.216881, -0.582813, -0.629049, 2.266141, -1.056877, -811.470000] test_list.append(periodic2d_no_limiter) # 2D rotational periodic sector with multigrid @@ -467,7 +467,7 @@ def main(): periodic2d_multigrid.cfg_dir = "navierstokes/periodic2D" periodic2d_multigrid.cfg_file = "multigrid.cfg" periodic2d_multigrid.test_iter = 300 - periodic2d_multigrid.test_vals = [-4.405188, -1.589621, -1.470131, 1.066630, -1.430812, -2072.000000] + periodic2d_multigrid.test_vals = [-4.422778, -1.615251, -1.453736, 1.047350, -1.410225, -2060.600000] test_list.append(periodic2d_multigrid) # 2D rotational periodic sector with limiter @@ -475,7 +475,7 @@ def main(): periodic2d.cfg_dir = "navierstokes/periodic2D" periodic2d.cfg_file = "config.cfg" periodic2d.test_iter = 100 - periodic2d.test_vals = [-3.308159, -0.637985, -0.693116, 2.172259, -1.021650, -958.960000] + periodic2d.test_vals = [-3.266248, -0.617784, -0.620252, 2.216476, -1.007761, -1035.000000] test_list.append(periodic2d) ########################## @@ -894,7 +894,7 @@ def main(): sp_pipeSlice_3d_dp_hf_tp.cfg_dir = "incomp_navierstokes/streamwise_periodic/pipeSlice_3d" sp_pipeSlice_3d_dp_hf_tp.cfg_file = "sp_pipeSlice_3d_dp_hf_tp.cfg" sp_pipeSlice_3d_dp_hf_tp.test_iter = 10 - sp_pipeSlice_3d_dp_hf_tp.test_vals = [-13.241550, -13.260364, -10.953558, -0.000025] + sp_pipeSlice_3d_dp_hf_tp.test_vals = [-13.241752, -13.260502, -10.953562, -0.000025] test_list.append(sp_pipeSlice_3d_dp_hf_tp) # Same with the energy equation, periodic temperature and an integrated wall heat @@ -902,7 +902,7 @@ def main(): sp_pipeSlice_3d_dp_ihf_tp.cfg_dir = "incomp_navierstokes/streamwise_periodic/pipeSlice_3d" sp_pipeSlice_3d_dp_ihf_tp.cfg_file = "sp_pipeSlice_3d_dp_ihf_tp.cfg" sp_pipeSlice_3d_dp_ihf_tp.test_iter = 10 - sp_pipeSlice_3d_dp_ihf_tp.test_vals = [-11.120123, -5.196299, -0.000023, -0.015700] + sp_pipeSlice_3d_dp_ihf_tp.test_vals = [-12.253831, -5.369585, -0.000025, -0.015700] test_list.append(sp_pipeSlice_3d_dp_ihf_tp) # 2D pin array with heat transfer BC on pin surfaces @@ -930,7 +930,7 @@ def main(): inc_turb_morse_swirl_jet.cfg_dir = "incomp_rans/morse_swirl_jet" inc_turb_morse_swirl_jet.cfg_file = "morse_sa.cfg" inc_turb_morse_swirl_jet.test_iter = 10 - inc_turb_morse_swirl_jet.test_vals = [-10.168926, -7.347914, -8.685155, 13.000000, -4.156951, 71.328000] + inc_turb_morse_swirl_jet.test_vals = [-10.569835, -8.376495, -9.323474, 12.000000, -4.059383, 71.328000] test_list.append(inc_turb_morse_swirl_jet) # NACA0012, SST_SUST @@ -1318,7 +1318,7 @@ def main(): sbs_backward_step.cfg_dir = "backscatter/backward_step" sbs_backward_step.cfg_file = "backwardStep.cfg" sbs_backward_step.test_iter = 3 - sbs_backward_step.test_vals = [-6.353146, -3.465452, -5.470619, -3.906555, -9.506332, -6.365239, -6.331024, -6.331030] + sbs_backward_step.test_vals = [-6.352884, -3.465372, -5.507901, -3.906545, -9.506305, -6.365236, -6.331021, -6.331028] sbs_backward_step.unsteady = True sbs_backward_step.decompress = True sbs_backward_step.grid_file = "backward_step.su2" @@ -1338,7 +1338,7 @@ def main(): flatplate_unsteady.cfg_dir = "navierstokes/flatplate" flatplate_unsteady.cfg_file = "lam_flatplate_unst.cfg" flatplate_unsteady.test_iter = 3 - flatplate_unsteady.test_vals = [0.000008, -8.875141, -8.250617, -6.305804, -5.469459, -3.398234, 0.002074, -0.310165] + flatplate_unsteady.test_vals = [0.000008, -8.875128, -8.250204, -6.305788, -5.469452, -3.398230, 0.002075, -0.325535] flatplate_unsteady.unsteady = True test_list.append(flatplate_unsteady) @@ -1398,7 +1398,7 @@ def main(): Aachen_3D_restart.cfg_file = "aachen_3D_MP_restart.cfg" Aachen_3D_restart.test_iter = 5 Aachen_3D_restart.tol = 0.00001 - Aachen_3D_restart.test_vals = [-7.688485, -8.467588, -6.035067, -6.427338, -5.819784, -4.597818, -5.529569, -5.305004, -3.819863, -5.242440, -5.756583, -3.630202, -2.213244, -2.860891, -0.576864] + Aachen_3D_restart.test_vals = [-7.688483, -8.466346, -6.035067, -6.425967, -5.820125, -4.597817, -5.528297, -5.301466, -3.819862, -5.242356, -5.738805, -3.630202, -2.213240, -2.857919, -0.576864] test_list.append(Aachen_3D_restart) # Jones APU Turbocharger restart @@ -1406,7 +1406,7 @@ def main(): Jones_tc_restart.cfg_dir = "turbomachinery/APU_turbocharger" Jones_tc_restart.cfg_file = "Jones_restart.cfg" Jones_tc_restart.test_iter = 5 - Jones_tc_restart.test_vals = [-11.914198, -12.203720, -19.150460, -13.443363, -19.037618, -13.395928, 73286.000000, 73286.000000, 0.020056, 82.286000] + Jones_tc_restart.test_vals = [-11.905727, -12.211201, -19.212537, -13.508616, -19.078613, -13.445675, 73286.000000, 73286.000000, 0.020056, 82.286000] test_list.append(Jones_tc_restart) # 2D axial stage @@ -1414,7 +1414,7 @@ def main(): axial_stage2D.cfg_dir = "turbomachinery/axial_stage_2D" axial_stage2D.cfg_file = "Axial_stage2D.cfg" axial_stage2D.test_iter = 20 - axial_stage2D.test_vals = [1.176763, 1.601270, -2.961800, 2.541146, -2.531370, 3.013521, 106390.000000, 106390.000000, 5.735500, 64.426000] + axial_stage2D.test_vals = [1.167500, 1.598546, -2.928573, 2.573647, -2.527331, 3.016254, 106370.000000, 106370.000000, 5.726800, 64.383000] test_list.append(axial_stage2D) # 2D transonic stator restart @@ -1422,7 +1422,7 @@ def main(): transonic_stator_restart.cfg_dir = "turbomachinery/transonic_stator_2D" transonic_stator_restart.cfg_file = "transonic_stator_restart.cfg" transonic_stator_restart.test_iter = 20 - transonic_stator_restart.test_vals = [-4.389126, -2.515434, -2.103674, 1.706003, -1.488483, 3.231947, -471620.000000, 94.841000, -0.046801] + transonic_stator_restart.test_vals = [-4.365636, -2.482248, -2.081252, 1.729763, -1.467305, 3.231073, -471620.000000, 94.837000, -0.046834] transonic_stator_restart.test_vals_aarch64 = [-4.437809, -2.553049, -2.164729, 1.657542, -1.356823, 3.178788, -471620.000000, 94.842000, -0.040365] test_list.append(transonic_stator_restart) @@ -1431,7 +1431,7 @@ def main(): multi_interface.cfg_dir = "turbomachinery/multi_interface" multi_interface.cfg_file = "multi_interface_rst.cfg" multi_interface.test_iter = 5 - multi_interface.test_vals = [-8.633076, -8.894747, -9.348617] + multi_interface.test_vals = [-8.634558, -8.895554, -9.348754] multi_interface.test_vals_aarch64 = [-8.632227, -8.894736, -9.348706] test_list.append(multi_interface) @@ -1514,7 +1514,7 @@ def main(): bars_SST_2D.cfg_dir = "sliding_interface/bars_SST_2D" bars_SST_2D.cfg_file = "bars.cfg" bars_SST_2D.test_iter = 13 - bars_SST_2D.test_vals = [13.000000, -0.464304, -1.546997] + bars_SST_2D.test_vals = [13.000000, -0.464267, -1.541047] bars_SST_2D.multizone = True test_list.append(bars_SST_2D) @@ -1651,7 +1651,7 @@ def main(): solid_periodic_pins.cfg_dir = "solid_heat_conduction/periodic_pins" solid_periodic_pins.cfg_file = "configSolid.cfg" solid_periodic_pins.test_iter = 750 - solid_periodic_pins.test_vals = [-15.931359, -14.386112, 300.900000, 425.320000, 0.000000, -14.007572] + solid_periodic_pins.test_vals = [-15.878962, -14.569206, 300.900000, 425.320000, 5.000000, -1.672653] solid_periodic_pins.test_vals_aarch64 = [-15.879016, -14.569206, 300.900000, 425.320000, 5.000000, -1.672666] test_list.append(solid_periodic_pins) diff --git a/TestCases/serial_regression.py b/TestCases/serial_regression.py index 3d37cee52ee0..4871709e62d0 100755 --- a/TestCases/serial_regression.py +++ b/TestCases/serial_regression.py @@ -216,7 +216,7 @@ def main(): poiseuille.cfg_dir = "navierstokes/poiseuille" poiseuille.cfg_file = "lam_poiseuille.cfg" poiseuille.test_iter = 10 - poiseuille.test_vals = [-7.597001, -6.994813, 0.012127, 13.596354, 0.000000] + poiseuille.test_vals = [-7.597002, -6.994814, 0.012154, 13.596296, 0] test_list.append(poiseuille) # 2D Poiseuille flow (inlet profile file) @@ -936,7 +936,7 @@ def main(): ls89_sa.cfg_dir = "nicf/LS89" ls89_sa.cfg_file = "turb_SA_PR.cfg" ls89_sa.test_iter = 20 - ls89_sa.test_vals = [-5.047026, -13.385356, 0.179168, 0.421262] + ls89_sa.test_vals = [-5.041500, -13.379523, 0.179019, 0.420831] test_list.append(ls89_sa) # Rarefaction shock wave edge_VW @@ -965,7 +965,7 @@ def main(): Aachen_3D_restart.cfg_dir = "turbomachinery/Aachen_turbine" Aachen_3D_restart.cfg_file = "aachen_3D_MP_restart.cfg" Aachen_3D_restart.test_iter = 5 - Aachen_3D_restart.test_vals = [-7.690756, -8.480220, -6.040279, -6.426434, -5.831445, -4.598589, -5.536489, -5.307971, -3.830619, -5.244603, -5.766097, -3.635129, -2.215856, -2.900116, -0.583139] + Aachen_3D_restart.test_vals = [-7.689117, -8.476204, -6.036107, -6.427402, -5.831576, -4.599024, -5.530512, -5.305687, -3.821789, -5.243255, -5.754831, -3.631603, -2.213934, -2.895728, -0.578545] Aachen_3D_restart.enabled_with_asan = False test_list.append(Aachen_3D_restart) @@ -974,7 +974,7 @@ def main(): Jones_tc_restart.cfg_dir = "turbomachinery/APU_turbocharger" Jones_tc_restart.cfg_file = "Jones_restart.cfg" Jones_tc_restart.test_iter = 5 - Jones_tc_restart.test_vals = [-11.913929, -12.201923, -19.149798, -13.441884, -19.033169, -13.395061, 73286.000000, 73286.000000, 0.020056, 82.286000] + Jones_tc_restart.test_vals = [-11.905629, -12.211684, -19.212618, -13.507994, -19.069281, -13.439288, 73286.000000, 73286.000000, 0.020056, 82.286000] test_list.append(Jones_tc_restart) # 2D axial stage @@ -982,7 +982,7 @@ def main(): axial_stage2D.cfg_dir = "turbomachinery/axial_stage_2D" axial_stage2D.cfg_file = "Axial_stage2D.cfg" axial_stage2D.test_iter = 20 - axial_stage2D.test_vals = [1.177225, 1.602363, -2.962970, 2.540072, -2.535614, 3.008265, 106390.000000, 106390.000000, 5.735500, 64.426000] + axial_stage2D.test_vals = [1.167521, 1.598536, -2.928575, 2.573646, -2.527330, 3.016253, 106370.000000, 106370.000000, 5.726800, 64.383000] test_list.append(axial_stage2D) # 2D transonic stator restart @@ -990,7 +990,7 @@ def main(): transonic_stator_restart.cfg_dir = "turbomachinery/transonic_stator_2D" transonic_stator_restart.cfg_file = "transonic_stator_restart.cfg" transonic_stator_restart.test_iter = 20 - transonic_stator_restart.test_vals = [-4.391061, -2.520781, -2.103750, 1.703960, -1.488302, 3.226640, -471620.000000, 94.842000, -0.051820] + transonic_stator_restart.test_vals = [-4.367784, -2.492912, -2.082414, 1.727491, -1.466974, 3.224730, -471620.000000, 94.839000, -0.052082] transonic_stator_restart.test_vals_aarch64 = [-4.367784, -2.492912, -2.082414, 1.727491, -1.466974, 3.224730, -471620.000000, 94.839000, -0.052082] test_list.append(transonic_stator_restart) @@ -999,7 +999,7 @@ def main(): multi_interface.cfg_dir = "turbomachinery/multi_interface" multi_interface.cfg_file = "multi_interface_rst.cfg" multi_interface.test_iter = 5 - multi_interface.test_vals = [-8.632926, -8.895296, -9.348618] + multi_interface.test_vals = [-8.634558, -8.895554, -9.348754] multi_interface.test_vals_aarch64 = [-8.632227, -8.894736, -9.348706] test_list.append(multi_interface) @@ -1094,7 +1094,7 @@ def main(): bars_SST_2D.cfg_dir = "sliding_interface/bars_SST_2D" bars_SST_2D.cfg_file = "bars.cfg" bars_SST_2D.test_iter = 13 - bars_SST_2D.test_vals = [13.000000, -0.462739, -1.546996] + bars_SST_2D.test_vals = [13.000000, -0.462697, -1.541051] bars_SST_2D.multizone = True test_list.append(bars_SST_2D) From 11efe51fd90c63b90d40350f019c0274bfc8f73f Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 21 Nov 2026 15:28:53 +0100 Subject: [PATCH 11/40] Update the transonic_stator discrete adjoint values No periodic point is coupled in this case. The values change at the 1e-5 level on CI only; local builds of develop and of this branch give bit-identical results. Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression_AD.py | 2 +- TestCases/serial_regression_AD.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/TestCases/parallel_regression_AD.py b/TestCases/parallel_regression_AD.py index 879d3e7463ab..f92a7a2e53d0 100644 --- a/TestCases/parallel_regression_AD.py +++ b/TestCases/parallel_regression_AD.py @@ -251,7 +251,7 @@ def main(): discadj_trans_stator.cfg_dir = "disc_adj_turbomachinery/transonic_stator_2D" discadj_trans_stator.cfg_file = "transonic_stator.cfg" discadj_trans_stator.test_iter = 79 - discadj_trans_stator.test_vals = [79.000000, -7.555647, -10.335486, -10.356919, -13.629543] + discadj_trans_stator.test_vals = [79.000000, -7.555649, -10.335509, -10.356935, -13.629546] discadj_trans_stator.test_vals_aarch64 = [79.000000, -7.555647, -10.335486, -10.356919, -13.629543] test_list.append(discadj_trans_stator) diff --git a/TestCases/serial_regression_AD.py b/TestCases/serial_regression_AD.py index 05d44805e201..8fe4642b02dc 100644 --- a/TestCases/serial_regression_AD.py +++ b/TestCases/serial_regression_AD.py @@ -200,7 +200,7 @@ def main(): discadj_trans_stator.cfg_dir = "disc_adj_turbomachinery/transonic_stator_2D" discadj_trans_stator.cfg_file = "transonic_stator.cfg" discadj_trans_stator.test_iter = 79 - discadj_trans_stator.test_vals = [79.000000, -7.308168, -9.891121, -10.038669, -13.368502] + discadj_trans_stator.test_vals = [79.000000, -7.308175, -9.891136, -10.038680, -13.368508] discadj_trans_stator.test_vals_aarch64 = [79.000000, -7.308167, -9.891117, -10.038669, -13.368501] test_list.append(discadj_trans_stator) From d0a897ae93f3e20f4b17618e84d457bc06ef3144 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 21 Nov 2026 16:46:45 +0100 Subject: [PATCH 12/40] Run the regression tests on the TestCases develop branch Co-Authored-By: Claude Opus 5.5 --- .github/workflows/regression.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml index 49b0773ff86b..323353274e5a 100644 --- a/.github/workflows/regression.yml +++ b/.github/workflows/regression.yml @@ -235,7 +235,7 @@ jobs: uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: # -t -c - args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} + args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: @@ -284,7 +284,7 @@ jobs: uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: # -t -c - args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} -a "--tapetests" + args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} -a "--tapetests" - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2:261011-1107 with: @@ -334,7 +334,7 @@ jobs: PMIX_MCA_gds: hash with: # -t -c - args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} -a "--tsan" + args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} -a "--tsan" - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2-tsan:261011-1107 with: @@ -379,7 +379,7 @@ jobs: uses: docker://ghcr.io/su2code/su2/test-su2-asan:261011-1107 with: # -t -c - args: -b ${{github.ref}} -t develop -c fix_periodic_jacobian -s ${{matrix.testscript}} -a "--asan" + args: -b ${{github.ref}} -t develop -c develop -s ${{matrix.testscript}} -a "--asan" - name: Cleanup uses: docker://ghcr.io/su2code/su2/test-su2-asan:261011-1107 with: From eae8575d8b810fa80223d7c6ce403f03fb9a3a50 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Mon, 23 Nov 2026 22:39:09 +0100 Subject: [PATCH 13/40] Flamelet: option to read the chemical variance source from the manifold The chemical source of a transported scalar variance was formed in SU2 as 2 (mean(phi S) - mean(phi) mean(S)) from two interpolated manifold columns. Linear interpolation of mean(phi S) and mean(S) leaves a spurious term sum_i w_i (phi_i - phi) mean(S)_i, of order (dS/dphi) dphi^2, which does not vanish at zero variance. Behind the flame it is a sink that drives the variance below zero, and the clipping at zero then gives a two-iteration limit cycle. With FLAMELET_TABULATED_VARIANCE_SOURCE= YES the variance source column is taken as the chemical variance source itself, computed per manifold node where the mean and both integrals are exact; it is then zero at zero variance. The default NO keeps the previous behaviour. Co-Authored-By: Claude Opus 5.5 --- Common/include/option_structure.hpp | 1 + Common/src/CConfig.cpp | 2 ++ SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 9 +++++---- config_template.cfg | 4 ++++ 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/Common/include/option_structure.hpp b/Common/include/option_structure.hpp index f34726036935..0393d01ccae4 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1623,6 +1623,7 @@ struct FluidFlamelet_ParsedOptions { int idx_progvar_var = -1; /*!< \brief Scalar index of the progress variable variance, -1 if absent. */ int idx_mixfrac_var = -1; /*!< \brief Scalar index of the mixture fraction variance, -1 if absent. */ su2double variance_dissipation_coeff = 2.0; /*!< \brief C_d in the variance dissipation C_d rho (eps/k) var. */ + bool tabulated_variance_source = false; /*!< \brief The variance source column holds the chemical variance source itself. */ std::string *controlling_variable_names; /*!< \brief Names of the independent, transported scalars. */ std::string* cv_source_names; /*!< \brief Names of the source terms of the independent, transported scalars. */ diff --git a/Common/src/CConfig.cpp b/Common/src/CConfig.cpp index 635614c30bb3..67c179eadb3b 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -1530,6 +1530,8 @@ void CConfig::SetConfig_Options() { /*!\brief FLAMELET_VARIANCE_DISSIPATION_COEFF \n DESCRIPTION: Coefficient C_d of the scalar variance dissipation C_d rho (eps/k) var \ingroup Config*/ addDoubleOption("FLAMELET_VARIANCE_DISSIPATION_COEFF", flamelet_ParsedOptions.variance_dissipation_coeff, 2.0); + /*!\brief FLAMELET_TABULATED_VARIANCE_SOURCE \n DESCRIPTION: The variance source column of the manifold is the chemical variance source 2 (mean(phi S) - mean(phi) mean(S)) instead of mean(phi S) \ingroup Config*/ + addBoolOption("FLAMELET_TABULATED_VARIANCE_SOURCE", flamelet_ParsedOptions.tabulated_variance_source, false); /*--- Options related to mass diffusivity and thereby the species solver. ---*/ diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index d3499c0c723b..9b472c619d4a 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -714,10 +714,11 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF /*--- The source term for progress variable is always positive, we clip from below to make sure. --- */ if (idx_progvar >= 0) table_sources[idx_progvar] = fmax(0, table_sources[idx_progvar]); - /*--- Variance source 2 (mean(phi S) - mean(phi) mean(S)); the manifold gives mean(phi S). ---*/ - for (const auto& var_mean : variance_sources) - table_sources[var_mean.first] = - 2.0 * (table_sources[var_mean.first] - scalars[var_mean.second] * table_sources[var_mean.second]); + /*--- Variance source 2 (mean(phi S) - mean(phi) mean(S)), from mean(phi S) unless the manifold holds it. ---*/ + if (!flamelet_config_options.tabulated_variance_source) + for (const auto& var_mean : variance_sources) + table_sources[var_mean.first] = + 2.0 * (table_sources[var_mean.first] - scalars[var_mean.second] * table_sources[var_mean.second]); nodes->SetTableMisses(iPoint, misses); vector source_scalar(flamelet_config_options.n_scalars); diff --git a/config_template.cfg b/config_template.cfg index e48b08c4c8a2..f30b8739b1ae 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1130,6 +1130,10 @@ THICKENED_FLAME_CORRECTION= YES % Coefficient C_d of the dissipation C_d rho (eps/k) var of a transported scalar variance, % with eps/k = beta* omega from the SST model. The production is 2 mu_t/Sc_t |grad(mean)|^2. FLAMELET_VARIANCE_DISSIPATION_COEFF= 2.0 +% +% The variance source column of the manifold is the chemical variance source 2 (mean(phi S) - mean(phi) mean(S)) +% (YES) or mean(phi S) (NO). +FLAMELET_TABULATED_VARIANCE_SOURCE= NO % Flame ignition temperature % Flame thickness calculations are performed when the maximum temperature in the flow solution exceeds this value. From bba15c0b8786572fee043d9cf8e0e7d8a569e3e9 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Mon, 23 Nov 2026 22:39:09 +0100 Subject: [PATCH 14/40] Flamelet: implicit treatment of the chemical sink of a scalar variance A negative chemical variance source is added to the Jacobian as -S / (rho var), its linearization as proportional to rho var. The update then cannot drive the variance below zero, so the clipping at zero no longer enters the iteration. Positive sources stay explicit. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 9b472c619d4a..10655df398dd 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -520,6 +520,11 @@ void CSpeciesFlameletSolver::ScalarVarianceResidual(CGeometry* geometry, CSolver LinSysRes(i_point, i_var) -= (production - decay * rho_var) * volume; if (implicit) Jacobian.AddVal2Diag(i_point, i_var, decay * volume); + + /*--- A chemical sink is linearized as proportional to rho*var, which keeps the variance positive. ---*/ + const su2double chemical_source = nodes->GetScalarSources(i_point)[i_var]; + if (implicit && chemical_source < 0 && rho_var > 0) + Jacobian.AddVal2Diag(i_point, i_var, -chemical_source / rho_var * volume); } END_SU2_OMP_FOR } From 8741253e5b078e730820d6efaad56ee6e3d010f5 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Wed, 25 Nov 2026 18:26:14 +0100 Subject: [PATCH 15/40] Simplify the periodic Jacobian coupling - One helper, RotateMomentumBlock, computes Ql*B*Qr^T on the momentum rows and columns. It replaces the hand-unrolled 2D/3D rotation in the periodic comms and the Rotation/RotateRows/RotateColumns lambdas. - Rotation matrices are built once per marker instead of once per block. - CBlockView::apply decodes, adds and re-encodes quantized blocks instead of silently doing nothing, so AddBlock works with Q_LU_SGS and the local workaround is removed. - The time step skips an edge when j is the periodic donor of i on this rank, read from the geometry, independent of whether the point is coupled. This removes skipImages, ArePeriodicImages and the per-iteration call to SetPeriodicMaster. - SetPeriodicMaster is called once from CouplePeriodicJacobian; the redundant implicit_periodic test and the PeriodicPassive member are gone. Regression values are unchanged: for the periodic and Q_LU_SGS cases the results are identical to the previous commit. Co-Authored-By: Claude Opus 5.5 --- Common/include/linear_algebra/CSysMatrix.hpp | 19 +- .../include/solvers/CFVMFlowSolverBase.hpp | 8 +- SU2_CFD/include/solvers/CSolver.hpp | 20 +- SU2_CFD/src/solvers/CSolver.cpp | 241 +++++++----------- 4 files changed, 121 insertions(+), 167 deletions(-) diff --git a/Common/include/linear_algebra/CSysMatrix.hpp b/Common/include/linear_algebra/CSysMatrix.hpp index ed33589b31d2..07827f6106d4 100644 --- a/Common/include/linear_algebra/CSysMatrix.hpp +++ b/Common/include/linear_algebra/CSysMatrix.hpp @@ -227,8 +227,7 @@ struct CBlockView { /*! * \brief Write the block from callable \p f(i,j). * \p Overwrite=true overwrites (or quantizes for Q_LU_SGS off-diagonal blocks); - * \p Overwrite=false accumulates into non-quantized storage only — accumulating into - * quantized storage would require decode-accumulate-encode and is a silent no-op. + * \p Overwrite=false accumulates (quantized storage is decoded, added and re-encoded). * Only enabled for mutable (non-const ScalarType) views. */ template > = 0> @@ -241,8 +240,20 @@ struct CBlockView { else ptr[i * nVar + j] += f(i, j); } - } else if constexpr (Overwrite) { - if (qs) EncodeQuantBlock(f, qs, qv, nVar); + } else if (qs) { + if constexpr (Overwrite) { + EncodeQuantBlock(f, qs, qv, nVar); + } else { + using T = std::remove_const_t; + for (auto r = 0ul; r < nVar; ++r) { + /*--- The old scale is kept because EncodeQuantRow overwrites qs[r] before re-reading the row. ---*/ + const auto scale = DecodeQuantScale(qs[r]); + const auto sum = [&](unsigned long i, unsigned long j) { + return static_cast(qv[i * nVar + j] * scale) + f(i, j); + }; + EncodeQuantRow(sum, qs[r], qv + r * nVar, nVar, r); + } + } } } }; diff --git a/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp b/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp index 214a74bdac70..5f476cb5d45f 100644 --- a/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp +++ b/SU2_CFD/include/solvers/CFVMFlowSolverBase.hpp @@ -444,10 +444,6 @@ class CFVMFlowSolverBase : public CSolver { ompMasterAssignBarrier(Min_Delta_Time,1e30, Max_Delta_Time,0.0, Global_Delta_UnstTimeND,1e30); - /*--- Edges between a point and its periodic image are left out, their states are tied. ---*/ - const bool skipImages = implicit_periodic; - if (skipImages) SetPeriodicMaster(geometry, config); - /*--- Loop domain points. ---*/ SU2_OMP_FOR_DYN(omp_chunk_size) @@ -465,7 +461,9 @@ class CFVMFlowSolverBase : public CSolver { for (unsigned short iNeigh = 0; iNeigh < geometry->nodes->GetnPoint(iPoint); ++iNeigh) { auto jPoint = geometry->nodes->GetPoint(iPoint,iNeigh); - if (skipImages && ArePeriodicImages(iPoint, jPoint)) continue; + + /*--- The edge to a periodic image is left out, the states of both points are tied. ---*/ + if (implicit_periodic && IsPeriodicImage(geometry, config, iPoint, jPoint)) continue; auto iEdge = geometry->nodes->GetEdge(iPoint,iNeigh); auto Normal = geometry->edges->GetNormal(iEdge); diff --git a/SU2_CFD/include/solvers/CSolver.hpp b/SU2_CFD/include/solvers/CSolver.hpp index 27ef57df94a1..76c3c4b6695e 100644 --- a/SU2_CFD/include/solvers/CSolver.hpp +++ b/SU2_CFD/include/solvers/CSolver.hpp @@ -151,7 +151,6 @@ class CSolver { std::unordered_map PeriodicProjIndex; /*!< \brief Local point to compact projection row. */ vector PeriodicMaster; /*!< \brief Local master point of each coupled passive periodic point, or -1. */ vector PeriodicMasterMarker; /*!< \brief Periodic marker of each passive point, gives its rotation. */ - vector PeriodicPassive; /*!< \brief Coupled passive periodic points. */ bool dynamic_grid; /*!< \brief Flag that determines whether the grid is dynamic (moving or deforming + grid velocities). */ @@ -337,16 +336,25 @@ class CSolver { void CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config); /*! - * \brief Map each coupled passive periodic point to its master on the same rank (built once). + * \brief Map each coupled passive periodic point to its master on the same rank. */ void SetPeriodicMaster(CGeometry *geometry, const CConfig *config); /*! - * \brief Whether two points are periodic images of each other on this rank. + * \brief Whether jPoint is the periodic donor of iPoint on this rank. + * \note Only happens on meshes one cell thick in the periodic direction. */ - inline bool ArePeriodicImages(unsigned long iPoint, unsigned long jPoint) const { - if (PeriodicMaster.empty()) return false; - return PeriodicMaster[iPoint] == static_cast(jPoint) || PeriodicMaster[jPoint] == static_cast(iPoint); + inline bool IsPeriodicImage(const CGeometry *geometry, const CConfig *config, unsigned long iPoint, + unsigned long jPoint) const { + if (!geometry->nodes->GetPeriodicBoundary(iPoint) || !geometry->nodes->GetPeriodicBoundary(jPoint)) return false; + for (auto iMarker = 0u; iMarker < config->GetnMarker_All(); iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; + const auto iVertex = geometry->nodes->GetVertex(iPoint, iMarker); + if (iVertex < 0) continue; + const auto* vertex = geometry->vertex[iMarker][iVertex]; + if (vertex->GetDonorProcessor() == rank && vertex->GetDonorPoint() == static_cast(jPoint)) return true; + } + return false; } /*! diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 1d1b281f0e3a..974ea12a4e89 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -302,6 +302,23 @@ void CSolver::GetPeriodicCommCountAndType(const CConfig* config, } namespace PeriodicCommHelpers { + /*--- B = Ql*B*Qr^T on the momentum rows and columns of B, a null matrix leaves that side alone. ---*/ + template + void RotateMomentumBlock(const Matrix* Ql, const Matrix* Qr, unsigned short nDim, unsigned short nVar, + su2activematrix& B) { + auto rotate = [nDim](const Matrix& Q, auto&& x) { + su2double v[3]; + for (auto d = 0u; d < nDim; d++) v[d] = x(d); + for (auto d = 0u; d < nDim; d++) { + su2double s = 0.0; + for (auto e = 0u; e < nDim; e++) s += Q[d][e] * v[e]; + x(d) = s; + } + }; + if (Ql) for (auto c = 0u; c < nVar; c++) rotate(*Ql, [&](unsigned d) -> su2double& { return B(1 + d, c); }); + if (Qr) for (auto r = 0u; r < nVar; r++) rotate(*Qr, [&](unsigned d) -> su2double& { return B(r, 1 + d); }); + } + CVectorOfMatrix& selectGradient(CVariable* nodes, unsigned short commType) { switch(commType) { case PERIODIC_PRIM_GG: @@ -642,31 +659,11 @@ void CSolver::InitiatePeriodicComms(CGeometry *geometry, } } - /*--- Rotate the momentum rows and columns of the Jacobian, the residual of the - periodic match is Q*R(Q^T*U), so its Jacobian is Q*J*Q^T. First the rows. ---*/ + /*--- The residual of the periodic match is Q*R(Q^T*U), so its Jacobian is Q*J*Q^T. ---*/ if (rotate_periodic) { - for (iVar = 0; iVar < nVar; iVar++) { - if (nDim == 2) { - jacBlock[1][iVar] = rotMatrix2D[0][0]*block(1, iVar) + rotMatrix2D[0][1]*block(2, iVar); - jacBlock[2][iVar] = rotMatrix2D[1][0]*block(1, iVar) + rotMatrix2D[1][1]*block(2, iVar); - } else { - jacBlock[1][iVar] = rotMatrix3D[0][0]*block(1, iVar) + rotMatrix3D[0][1]*block(2, iVar) + - rotMatrix3D[0][2]*block(3, iVar); - jacBlock[2][iVar] = rotMatrix3D[1][0]*block(1, iVar) + rotMatrix3D[1][1]*block(2, iVar) + - rotMatrix3D[1][2]*block(3, iVar); - jacBlock[3][iVar] = rotMatrix3D[2][0]*block(1, iVar) + rotMatrix3D[2][1]*block(2, iVar) + - rotMatrix3D[2][2]*block(3, iVar); - } - } - - /*--- Then the columns, i.e. the momentum part of each row. ---*/ - - for (auto iRow = 0u; iRow < nVar; iRow++) { - su2double rotated[3] = {0.0}; - Rotate(zeros, &jacBlock[iRow][1], rotated); - for (auto jDim = 0u; jDim < nDim; jDim++) jacBlock[iRow][1+jDim] = rotated[jDim]; - } + if (nDim == 2) PeriodicCommHelpers::RotateMomentumBlock(&rotMatrix2D, &rotMatrix2D, nDim, nVar, jacBlock); + else PeriodicCommHelpers::RotateMomentumBlock(&rotMatrix3D, &rotMatrix3D, nDim, nVar, jacBlock); } /*--- Load the Jacobian terms into the buffer for sending. ---*/ @@ -4633,173 +4630,113 @@ void CSolver::SavelibROM(CGeometry *geometry, CConfig *config, bool converged) { } void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { - if (config->GetnMarker_Periodic() == 0) return; - - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { - const auto nPeriodic = config->GetnMarker_Periodic(); const auto nPointAll = geometry->GetnPoint(); - if (PeriodicMaster.size() != nPointAll) { - PeriodicMaster.assign(nPointAll, -1); - PeriodicMasterMarker.assign(nPointAll, 0); - vector nPeriodicMarker(nPointAll, 0); - vector passive(nPointAll, false); + PeriodicMaster.assign(nPointAll, -1); + PeriodicMasterMarker.assign(nPointAll, 0); + vector nPeriodicMarker(nPointAll, 0); + vector passive(nPointAll, false); - for (auto iMarker = 0u; iMarker < config->GetnMarker_All(); iMarker++) { - if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; - /*--- Points receiving from the second marker of a pair have their rows removed (CompletePeriodicComms). ---*/ - const bool isPassive = config->GetMarker_All_PerBound(iMarker) <= nPeriodic / 2; - for (auto iVertex = 0ul; iVertex < geometry->nVertex[iMarker]; iVertex++) { - const auto* vertex = geometry->vertex[iMarker][iVertex]; - const auto iPoint = vertex->GetNode(); - nPeriodicMarker[iPoint]++; - if (!isPassive) continue; - passive[iPoint] = true; - if (vertex->GetDonorProcessor() == rank && vertex->GetDonorPoint() >= 0) { - PeriodicMaster[iPoint] = vertex->GetDonorPoint(); - PeriodicMasterMarker[iPoint] = iMarker; - } + for (auto iMarker = 0u; iMarker < config->GetnMarker_All(); iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; + /*--- Points receiving from the second marker of a pair have their rows removed (CompletePeriodicComms). ---*/ + const bool isPassive = config->GetMarker_All_PerBound(iMarker) <= nPeriodic / 2; + for (auto iVertex = 0ul; iVertex < geometry->nVertex[iMarker]; iVertex++) { + const auto* vertex = geometry->vertex[iMarker][iVertex]; + const auto iPoint = vertex->GetNode(); + nPeriodicMarker[iPoint]++; + if (!isPassive) continue; + passive[iPoint] = true; + if (vertex->GetDonorProcessor() == rank && vertex->GetDonorPoint() >= 0) { + PeriodicMaster[iPoint] = vertex->GetDonorPoint(); + PeriodicMasterMarker[iPoint] = iMarker; } } + } - /*--- Points on several periodic markers keep the treatment of the comms only. ---*/ - for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { - const auto master = PeriodicMaster[iPoint]; - if (master < 0) continue; - if (nPeriodicMarker[iPoint] != 1 || nPeriodicMarker[master] != 1 || passive[master]) - PeriodicMaster[iPoint] = -1; - } + /*--- Points on several periodic markers keep the treatment of the comms only. ---*/ + for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { + const auto master = PeriodicMaster[iPoint]; + if (master < 0) continue; + if (nPeriodicMarker[iPoint] != 1 || nPeriodicMarker[master] != 1 || passive[master]) PeriodicMaster[iPoint] = -1; + } - /*--- A point is coupled only if all its blocks fit in the sparsity pattern of its master. Columns of passive - * points without a master are ignored, their increment is zero in the linear system. ---*/ - if (implicit_periodic) { - for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { - const auto master = PeriodicMaster[iPoint]; - if (master < 0) continue; - bool fits = true; - for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { - if (iPoint < nPointDomain && (!passive[kPoint] || PeriodicMaster[kPoint] >= 0)) { - const unsigned long col = passive[kPoint] ? PeriodicMaster[kPoint] : kPoint; - fits = fits && Jacobian.GetBlockView(master, col); - } - if (kPoint < nPointDomain && !passive[kPoint]) fits = fits && Jacobian.GetBlockView(kPoint, master); - } - if (!fits) PeriodicMaster[iPoint] = -1; + /*--- A point is coupled only if all its blocks fit in the sparsity pattern of its master. Columns of passive + * points without a master are ignored, their increment is zero in the linear system. ---*/ + for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { + const auto master = PeriodicMaster[iPoint]; + if (master < 0) continue; + const bool ownRow = iPoint < nPointDomain; + bool fits = true; + for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { + const bool kCoupled = PeriodicMaster[kPoint] >= 0; + if (ownRow && (!passive[kPoint] || kCoupled)) { + const unsigned long col = kCoupled ? PeriodicMaster[kPoint] : kPoint; + fits = fits && Jacobian.GetBlockView(master, col); } + if (kPoint < nPointDomain && !passive[kPoint]) fits = fits && Jacobian.GetBlockView(kPoint, master); } - - PeriodicPassive.clear(); - for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) - if (PeriodicMaster[iPoint] >= 0) PeriodicPassive.push_back(iPoint); - } - + if (!fits) PeriodicMaster[iPoint] = -1; } - END_SU2_OMP_SAFE_GLOBAL_ACCESS } void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) { SU2_ZONE_SCOPED - if (!implicit_periodic) return; - - SetPeriodicMaster(geometry, config); + if (!implicit_periodic || config->GetnMarker_Periodic() == 0) return; BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { - /*--- Rotation from the frame of a passive point to the frame of its master. ---*/ - auto Rotation = [&](unsigned short iMarker, su2double (&Q)[3][3]) { - for (auto i = 0u; i < 3; i++) - for (auto j = 0u; j < 3; j++) Q[i][j] = (i == j); - if (!rotate_periodic) return false; + if (PeriodicMaster.size() != geometry->GetnPoint()) SetPeriodicMaster(geometry, config); + + /*--- Rotation from the frame of each periodic marker to the frame of its match, null if none. ---*/ + using RotationMatrix = std::array, 3>; + const auto nMarker = config->GetnMarker_All(); + vector rotations(nMarker); + vector markerRotation(nMarker, nullptr); + for (auto iMarker = 0u; iMarker < nMarker && rotate_periodic; iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; const auto* angles = config->GetPeriodicRotAngles(config->GetMarker_All_TagBound(iMarker)); - if (!GeometryToolbox::HasRotation(angles)) return false; - if (nDim == 2) { - su2double Q2[2][2]; - GeometryToolbox::RotationMatrix(angles[2], Q2); - for (auto i = 0u; i < 2; i++) - for (auto j = 0u; j < 2; j++) Q[i][j] = Q2[i][j]; - } else { - GeometryToolbox::RotationMatrix(angles[0], angles[1], angles[2], Q); - } - return true; + if (!GeometryToolbox::HasRotation(angles)) continue; + if (nDim == 2) GeometryToolbox::RotationMatrix(angles[2], rotations[iMarker]); + else GeometryToolbox::RotationMatrix(angles[0], angles[1], angles[2], rotations[iMarker]); + markerRotation[iMarker] = &rotations[iMarker]; + } + auto Rotation = [&](unsigned long iPoint) -> const RotationMatrix* { + return PeriodicMaster[iPoint] >= 0 ? markerRotation[PeriodicMasterMarker[iPoint]] : nullptr; }; - su2activematrix block(nVar, nVar), sum(nVar, nVar), zero(nVar, nVar); + su2activematrix block(nVar, nVar), zero(nVar, nVar); zero = su2double(0.0); - su2double v[3]; - - /*--- Copy a block through its view, which also decodes quantized storage. ---*/ auto ReadBlock = [&](unsigned long iRow, unsigned long iCol) { const auto view = Jacobian.GetBlockView(iRow, iCol); - if (!view) return false; for (auto i = 0u; i < nVar; i++) for (auto j = 0u; j < nVar; j++) block(i, j) = view(i, j); - return true; }; - /*--- Add block to an existing block. Quantized storage cannot accumulate, it is decoded, added and re-encoded. ---*/ - auto AddBlock = [&](unsigned long iRow, unsigned long iCol) { - const auto view = Jacobian.GetBlockView(iRow, iCol); - if (view.ptr) { - Jacobian.SetBlock(iRow, iCol, block); - return; - } - for (auto i = 0u; i < nVar; i++) - for (auto j = 0u; j < nVar; j++) sum(i, j) = view(i, j) + block(i, j); - Jacobian.SetBlock(iRow, iCol, sum); - }; - - auto RotateRows = [&](const su2double (&Q)[3][3]) { - for (auto c = 0u; c < nVar; c++) { - for (auto d = 0u; d < nDim; d++) v[d] = block(1 + d, c); - for (auto d = 0u; d < nDim; d++) { - su2double s = 0.0; - for (auto e = 0u; e < nDim; e++) s += Q[d][e] * v[e]; - block(1 + d, c) = s; - } - } - }; - - /*--- Right product with Q^T: the passive increment is Q^T times the master increment. ---*/ - auto RotateColumns = [&](const su2double (&Q)[3][3]) { - for (auto r = 0u; r < nVar; r++) { - for (auto d = 0u; d < nDim; d++) v[d] = block(r, 1 + d); - for (auto d = 0u; d < nDim; d++) { - su2double s = 0.0; - for (auto e = 0u; e < nDim; e++) s += v[e] * Q[d][e]; - block(r, 1 + d) = s; - } - } - }; - - su2double Qp[3][3], Qk[3][3]; - /*--- Rows of passive points go to the rows of their masters. ---*/ - for (const auto iPoint : PeriodicPassive) { - if (iPoint >= nPointDomain) continue; + for (auto iPoint = 0ul; iPoint < nPointDomain; iPoint++) { const auto master = PeriodicMaster[iPoint]; - const bool rotP = Rotation(PeriodicMasterMarker[iPoint], Qp); - + if (master < 0) continue; for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { - const bool kPassive = PeriodicMaster[kPoint] >= 0; - const unsigned long col = kPassive ? PeriodicMaster[kPoint] : kPoint; - if (!Jacobian.GetBlockView(master, col) || !ReadBlock(iPoint, kPoint)) continue; - if (kPassive && Rotation(PeriodicMasterMarker[kPoint], Qk)) RotateColumns(Qk); - if (rotP) RotateRows(Qp); - AddBlock(master, col); + const unsigned long col = PeriodicMaster[kPoint] >= 0 ? PeriodicMaster[kPoint] : kPoint; + if (!Jacobian.GetBlockView(master, col)) continue; + ReadBlock(iPoint, kPoint); + PeriodicCommHelpers::RotateMomentumBlock(Rotation(iPoint), Rotation(kPoint), nDim, nVar, block); + Jacobian.AddBlock(master, col, block); } } /*--- Columns of passive points go to the columns of their masters. ---*/ - for (const auto iPoint : PeriodicPassive) { + for (auto iPoint = 0ul; iPoint < PeriodicMaster.size(); iPoint++) { const auto master = PeriodicMaster[iPoint]; - const bool rotP = Rotation(PeriodicMasterMarker[iPoint], Qp); - + if (master < 0) continue; for (const auto jPoint : geometry->nodes->GetPoints(iPoint)) { if (jPoint >= nPointDomain || PeriodicMaster[jPoint] >= 0) continue; - if (!Jacobian.GetBlockView(jPoint, master) || !ReadBlock(jPoint, iPoint)) continue; - if (rotP) RotateColumns(Qp); - AddBlock(jPoint, master); + if (!Jacobian.GetBlockView(jPoint, master)) continue; + ReadBlock(jPoint, iPoint); + PeriodicCommHelpers::RotateMomentumBlock(nullptr, Rotation(iPoint), nDim, nVar, block); + Jacobian.AddBlock(jPoint, master, block); Jacobian.SetBlock(jPoint, iPoint, zero); } } From 1eb9c59c063cdc1b5beb6613ffef1ce41b328355 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Wed, 25 Nov 2026 19:26:28 +0100 Subject: [PATCH 16/40] Address review: passive Jacobian blocks, loop names, nPoint - The moved Jacobian blocks and the rotation matrices of the coupling are passive types; RotateMomentumBlock is templated on the block scalar so the comms keep their active block. - Descriptive loop variables (iVar, jVar, iDim, jDim) in RotateMomentumBlock and ReadBlock. - SetPeriodicMaster and CouplePeriodicJacobian use the member nPoint instead of a local nPointAll. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/src/solvers/CSolver.cpp | 60 ++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 27 deletions(-) diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 974ea12a4e89..9c85dfcf99f5 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -303,20 +303,24 @@ void CSolver::GetPeriodicCommCountAndType(const CConfig* config, namespace PeriodicCommHelpers { /*--- B = Ql*B*Qr^T on the momentum rows and columns of B, a null matrix leaves that side alone. ---*/ - template + template void RotateMomentumBlock(const Matrix* Ql, const Matrix* Qr, unsigned short nDim, unsigned short nVar, - su2activematrix& B) { - auto rotate = [nDim](const Matrix& Q, auto&& x) { - su2double v[3]; - for (auto d = 0u; d < nDim; d++) v[d] = x(d); - for (auto d = 0u; d < nDim; d++) { - su2double s = 0.0; - for (auto e = 0u; e < nDim; e++) s += Q[d][e] * v[e]; - x(d) = s; + su2matrix& B) { + auto rotate = [nDim](const Matrix& Q, auto&& component) { + Scalar vec[3]; + for (auto iDim = 0u; iDim < nDim; iDim++) vec[iDim] = component(iDim); + for (auto iDim = 0u; iDim < nDim; iDim++) { + Scalar sum = 0.0; + for (auto jDim = 0u; jDim < nDim; jDim++) sum += Q[iDim][jDim] * vec[jDim]; + component(iDim) = sum; } }; - if (Ql) for (auto c = 0u; c < nVar; c++) rotate(*Ql, [&](unsigned d) -> su2double& { return B(1 + d, c); }); - if (Qr) for (auto r = 0u; r < nVar; r++) rotate(*Qr, [&](unsigned d) -> su2double& { return B(r, 1 + d); }); + if (Ql) + for (auto jVar = 0u; jVar < nVar; jVar++) + rotate(*Ql, [&](unsigned iDim) -> Scalar& { return B(1 + iDim, jVar); }); + if (Qr) + for (auto iVar = 0u; iVar < nVar; iVar++) + rotate(*Qr, [&](unsigned iDim) -> Scalar& { return B(iVar, 1 + iDim); }); } CVectorOfMatrix& selectGradient(CVariable* nodes, unsigned short commType) { @@ -4631,12 +4635,11 @@ void CSolver::SavelibROM(CGeometry *geometry, CConfig *config, bool converged) { void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { const auto nPeriodic = config->GetnMarker_Periodic(); - const auto nPointAll = geometry->GetnPoint(); - PeriodicMaster.assign(nPointAll, -1); - PeriodicMasterMarker.assign(nPointAll, 0); - vector nPeriodicMarker(nPointAll, 0); - vector passive(nPointAll, false); + PeriodicMaster.assign(nPoint, -1); + PeriodicMasterMarker.assign(nPoint, 0); + vector nPeriodicMarker(nPoint, 0); + vector passive(nPoint, false); for (auto iMarker = 0u; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; @@ -4656,7 +4659,7 @@ void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { } /*--- Points on several periodic markers keep the treatment of the comms only. ---*/ - for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { + for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { const auto master = PeriodicMaster[iPoint]; if (master < 0) continue; if (nPeriodicMarker[iPoint] != 1 || nPeriodicMarker[master] != 1 || passive[master]) PeriodicMaster[iPoint] = -1; @@ -4664,7 +4667,7 @@ void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { /*--- A point is coupled only if all its blocks fit in the sparsity pattern of its master. Columns of passive * points without a master are ignored, their increment is zero in the linear system. ---*/ - for (auto iPoint = 0ul; iPoint < nPointAll; iPoint++) { + for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { const auto master = PeriodicMaster[iPoint]; if (master < 0) continue; const bool ownRow = iPoint < nPointDomain; @@ -4687,10 +4690,10 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { - if (PeriodicMaster.size() != geometry->GetnPoint()) SetPeriodicMaster(geometry, config); + if (PeriodicMaster.size() != nPoint) SetPeriodicMaster(geometry, config); /*--- Rotation from the frame of each periodic marker to the frame of its match, null if none. ---*/ - using RotationMatrix = std::array, 3>; + using RotationMatrix = std::array, 3>; const auto nMarker = config->GetnMarker_All(); vector rotations(nMarker); vector markerRotation(nMarker, nullptr); @@ -4698,20 +4701,23 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; const auto* angles = config->GetPeriodicRotAngles(config->GetMarker_All_TagBound(iMarker)); if (!GeometryToolbox::HasRotation(angles)) continue; - if (nDim == 2) GeometryToolbox::RotationMatrix(angles[2], rotations[iMarker]); - else GeometryToolbox::RotationMatrix(angles[0], angles[1], angles[2], rotations[iMarker]); + const auto theta = SU2_TYPE::GetValue(angles[0]); + const auto phi = SU2_TYPE::GetValue(angles[1]); + const auto psi = SU2_TYPE::GetValue(angles[2]); + if (nDim == 2) GeometryToolbox::RotationMatrix(psi, rotations[iMarker]); + else GeometryToolbox::RotationMatrix(theta, phi, psi, rotations[iMarker]); markerRotation[iMarker] = &rotations[iMarker]; } auto Rotation = [&](unsigned long iPoint) -> const RotationMatrix* { return PeriodicMaster[iPoint] >= 0 ? markerRotation[PeriodicMasterMarker[iPoint]] : nullptr; }; - su2activematrix block(nVar, nVar), zero(nVar, nVar); - zero = su2double(0.0); + su2passivematrix block(nVar, nVar), zero(nVar, nVar); + zero = passivedouble(0.0); auto ReadBlock = [&](unsigned long iRow, unsigned long iCol) { const auto view = Jacobian.GetBlockView(iRow, iCol); - for (auto i = 0u; i < nVar; i++) - for (auto j = 0u; j < nVar; j++) block(i, j) = view(i, j); + for (auto iVar = 0u; iVar < nVar; iVar++) + for (auto jVar = 0u; jVar < nVar; jVar++) block(iVar, jVar) = view(iVar, jVar); }; /*--- Rows of passive points go to the rows of their masters. ---*/ @@ -4728,7 +4734,7 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) } /*--- Columns of passive points go to the columns of their masters. ---*/ - for (auto iPoint = 0ul; iPoint < PeriodicMaster.size(); iPoint++) { + for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { const auto master = PeriodicMaster[iPoint]; if (master < 0) continue; for (const auto jPoint : geometry->nodes->GetPoints(iPoint)) { From 24c8fbca24c8749bb620308d01802f2b3c8dcff1 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:18:32 +0100 Subject: [PATCH 17/40] Flamelet LUT: extrapolate linearly beyond the outer table levels Beyond the first and last table level the lookup used the outer level alone, so looked-up quantities stopped depending on the level variable. With preferential diffusion the mixture fraction is then no longer restored by its own diffusion and can run away, e.g. to negative values at a lean H2 flame tip. Queries outside the level range are now extrapolated linearly from the two outermost levels, up to one level spacing, and still reported as outside the manifold. Co-Authored-By: Claude Opus 5.5 --- Common/include/containers/CLookUpTable.hpp | 9 ++++ Common/src/containers/CLookUpTable.cpp | 55 +++++++++++++--------- 2 files changed, 43 insertions(+), 21 deletions(-) diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index e455dd1f12d1..e8f14408b751 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -272,6 +272,15 @@ class CLookUpTable { const su2double val_CV1, const su2double val_CV2, const su2double val_CV3); + /*! + * \brief Interpolate linearly in the third controlling variable between two table levels, or extrapolate + * when val_CV3 lies outside them. + * \returns whether the query point lies inside the data on both levels. + */ + bool InterpolateBetweenLevels(const std::vector& idx_var, std::vector& val_vars, + const su2double val_CV1, const su2double val_CV2, const su2double val_CV3, + std::pair levels); + /*! * \brief Find the triangle within which the query point (val_CV1, val_CV2) is located. * \param[in] val_CV1 - First controlling variable value. diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 05586d39585c..93ce64310d48 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -438,6 +438,26 @@ bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::ve return inside; } +bool CLookUpTable::InterpolateBetweenLevels(const std::vector& idx_var, + std::vector& val_vars, const su2double val_CV1, + const su2double val_CV2, const su2double val_CV3, + std::pair levels) { + /* Determine val_CV1 and val_CV2 for the two levels. */ + std::array, 2> lower_upper_CV1_2 = ComputeNormalizedXY(levels, val_CV1, val_CV2, val_CV3); + su2double val_CV1_lower = lower_upper_CV1_2[0][0], val_CV2_lower = lower_upper_CV1_2[0][1], + val_CV1_upper = lower_upper_CV1_2[1][0], val_CV2_upper = lower_upper_CV1_2[1][1]; + + /* Perform 2D interpolations on both levels. */ + std::vector val_vars_lower(val_vars.size()), val_vars_upper(val_vars.size()); + auto inside_lower = LookUp_XY(idx_var, val_vars_lower, val_CV1_lower, val_CV2_lower, levels.first); + auto inside_upper = LookUp_XY(idx_var, val_vars_upper, val_CV1_upper, val_CV2_upper, levels.second); + + /* Linear interpolation, or extrapolation, along the z-direction. */ + Linear_Interpolation(val_CV3, levels.first, levels.second, val_vars_lower, val_vars_upper, val_vars); + + return (inside_upper && inside_lower); +} + bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::vector& val_vars, const su2double val_CV1, const su2double val_CV2, const su2double val_CV3) { /*--- Perform quasi-3D interpolation for a vector of variables with names val_names_var @@ -447,28 +467,21 @@ bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::ve std::pair inclusion_levels = FindInclusionLevels(val_CV3); bool within_z_limits = (inclusion_levels.first != inclusion_levels.second); + /*--- Beyond the outer levels, extrapolate linearly from the two outermost levels, up to one level + * spacing beyond the table, so that looked-up quantities keep their dependence on val_CV3. ---*/ + if (!within_z_limits && n_table_levels > 1) { + const bool below = val_CV3 < z_values_levels.front(); + const unsigned long i_low = below ? 0 : n_table_levels - 2; + const pair outer_levels = make_pair(i_low, i_low + 1); + const su2double dz = z_values_levels[i_low + 1] - z_values_levels[i_low]; + const su2double z_extrap = below ? max(val_CV3, z_values_levels.front() - dz) + : min(val_CV3, z_values_levels.back() + dz); + InterpolateBetweenLevels(idx_var, val_vars, val_CV1, val_CV2, z_extrap, outer_levels); + return false; + } + if (within_z_limits) { - /* 2: Determine val_CV1 and val_CV2 for the inclusion table levels. */ - std::array, 2> lower_upper_CV1_2 = - ComputeNormalizedXY(inclusion_levels, val_CV1, val_CV2, val_CV3); - su2double val_CV1_lower = lower_upper_CV1_2[0][0], val_CV2_lower = lower_upper_CV1_2[0][1], - val_CV1_upper = lower_upper_CV1_2[1][0], val_CV2_upper = lower_upper_CV1_2[1][1]; - - /* 3: Perform 2D interpolations on upper and lower inclusion levels */ - unsigned long lower_level = inclusion_levels.first; - unsigned long upper_level = inclusion_levels.second; - - std::vector val_vars_lower, val_vars_upper; - val_vars_lower.resize(val_vars.size()); - val_vars_upper.resize(val_vars.size()); - auto inside_lower = LookUp_XY(idx_var, val_vars_lower, val_CV1_lower, val_CV2_lower, lower_level); - auto inside_upper = LookUp_XY(idx_var, val_vars_upper, val_CV1_upper, val_CV2_upper, upper_level); - - /* 4: Perform linear interpolation along the z-direction using the x-y interpolation results - from upper and lower trapezoidal maps */ - Linear_Interpolation(val_CV3, lower_level, upper_level, val_vars_lower, val_vars_upper, val_vars); - - return (inside_upper && inside_lower); + return InterpolateBetweenLevels(idx_var, val_vars, val_CV1, val_CV2, val_CV3, inclusion_levels); } else { /* Perform single, 2D interpolation when val_CV3 lies outside table bounds */ unsigned long bound_level = inclusion_levels.first; From 9cace00ee27694cba9bafaf3acf71105e3645217 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:18:32 +0100 Subject: [PATCH 18/40] Flamelet: block Jacobian of the preferential diffusion terms The preferential diffusion flux D grad(beta - phi) used the Jacobian of the ordinary diffusion, i.e. d(beta - phi)/dphi = 1, without the coupling between the controlling variables and without the thermal term of the enthalpy equation. For the mixture fraction of lean H2 flames dbeta/dZ is about 3-4, so the term was under-implicit and the mixture fraction and enthalpy oscillated with a period of two iterations near cooled walls. The solver now evaluates d(beta_i - phi_i)/dphi_j, with beta_T dT/dphi_j in the enthalpy row, by finite differences of the manifold lookup when the preferential diffusion scalars are updated: central differences inside the manifold, one-sided towards it at its edges, and the previous Jacobian where neither fits. The steps are 1e-3 of the global range of each controlling variable. The edge kernel assembles the full block. The residual is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../numerics/species/flamelet_edge_flux.hpp | 20 +++-- .../solvers/CSpeciesFlameletSolver.hpp | 11 ++- .../include/variables/CSpeciesVariable.hpp | 13 +++ .../src/solvers/CSpeciesFlameletSolver.cpp | 81 +++++++++++++++++++ .../variables/CSpeciesFlameletVariable.cpp | 2 + 5 files changed, 118 insertions(+), 9 deletions(-) diff --git a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index 0d58cf2df681..55b9ef747de8 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -58,9 +58,8 @@ class CScalarFlux_Flamelet final * \brief Preferential diffusion, two terms with the shape of the ordinary diffusion but of * states the model synthesises: div(D grad(beta - phi)) for each controlling variable, * and a thermal term div(beta_T D grad(T)) on the enthalpy equation. - * \note The thermal term has no implicit part, matching the treatment of the heat flux it - * models; the first term has the same thin shear layer Jacobian as the ordinary diffusion, - * because it is the same operator applied to a shifted state. + * \note The Jacobian couples the controlling variables through the derivatives of beta - phi, with + * the thermal term folded into the enthalpy row; the solver evaluates them from the manifold. */ template FORCEINLINE void extraDiffusionTerms(const FlowIndices& idx, const ScalarFluxOptions& opt, Int iPoint, @@ -106,11 +105,16 @@ class CScalarFlux_Flamelet final if (!opt.oneSided) res.flux_j(iScalar) += D * projGrad; if (opt.implicit) { - res.jac_ii(iScalar, iScalar) += D * proj_on_rho_i; - if (!opt.oneSided) { - res.jac_ij(iScalar, iScalar) -= D * proj_on_rho_j; - res.jac_ji(iScalar, iScalar) -= D * proj_on_rho_i; - res.jac_jj(iScalar, iScalar) += D * proj_on_rho_j; + for (auto jScalar = 0u; jScalar < nControlVars; ++jScalar) { + const auto iEntry = iScalar * nControlVars + jScalar; + const Double dState_i = gatherVariables(iPoint, side_i.scalarNodes.GetPrefDiffJacobian(), iEntry); + const Double dState_j = gatherVariables(jPoint, side_j.scalarNodes.GetPrefDiffJacobian(), iEntry); + res.jac_ii(iScalar, jScalar) += D * proj_on_rho_i * dState_i; + if (!opt.oneSided) { + res.jac_ij(iScalar, jScalar) -= D * proj_on_rho_j * dState_j; + res.jac_ji(iScalar, jScalar) -= D * proj_on_rho_i * dState_i; + res.jac_jj(iScalar, jScalar) += D * proj_on_rho_j * dState_j; + } } } } diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index 80a75b6b26f2..e989b63f2897 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -48,6 +48,14 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { /*!< \brief Number of points outside the manifold domain, shared across OpenMP threads so it can be * accumulated atomically and reduced by the master thread alone in Preprocessing. */ unsigned long n_not_in_domain_local = 0; + bool pd_jacobian = false; /*!< \brief Whether the preferential diffusion Jacobian is evaluated this iteration. */ + passivedouble pd_jacobian_step[MAXNVAR] = {0}; /*!< \brief Finite difference step per controlling variable. */ + + /*! + * \brief Set the finite difference steps of the preferential diffusion Jacobian, a fraction of the global + * range of each controlling variable. + */ + void SetPrefDiffJacobianSteps(); /*! * \brief Compute the preconditioner for low-Mach flows. * \param[in] geometry - Geometrical definition of the problem. @@ -127,7 +135,8 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { const vector& scalars); /*! - * \brief Retrieve the preferential diffusion scalar values from manifold. + * \brief Retrieve the preferential diffusion scalar values from manifold, and their derivatives to the + * controlling variables when the scheme is implicit. * \param[in] fluid_model_local - pointer to flamelet fluid model. * \param[in] iPoint - node ID. * \param[in] scalars - local scalar solution. diff --git a/SU2_CFD/include/variables/CSpeciesVariable.hpp b/SU2_CFD/include/variables/CSpeciesVariable.hpp index 197cd9db04a6..84185d8a6d97 100644 --- a/SU2_CFD/include/variables/CSpeciesVariable.hpp +++ b/SU2_CFD/include/variables/CSpeciesVariable.hpp @@ -39,10 +39,23 @@ class CSpeciesVariable : public CScalarVariable { MatrixType SpeciesSourceTerm; /*!< \brief Matrix (nPoint, nVar) of chemical source terms for species transport*/ MatrixType SpeciesSourceJacobian; /*!< \brief Matrix (nPoint, nVar) of the diagonal chemical source Jacobian. */ VectorType HeatRelease; /*!< \brief Vector of heat release due to combustion for species transport*/ + MatrixType PrefDiffJacobian; /*!< \brief Matrix (nPoint, nCV*nCV), row-major d(beta_i - phi_i)/d(phi_j) of the preferential diffusion terms. */ public: static constexpr size_t MAXNVAR = MAX_TRANSPORTED_SPECIES; /*!< \brief Max number of variables for static arrays. */ + /*! + * \brief Derivatives of the preferential diffusion states to the controlling variables, row-major per point. + */ + inline const MatrixType& GetPrefDiffJacobian() const { return PrefDiffJacobian; } + + /*! + * \brief Set one derivative of a preferential diffusion state, entry iCV*nCV + jCV. + */ + inline void SetPrefDiffJacobian(unsigned long iPoint, unsigned long iEntry, su2double val) { + PrefDiffJacobian(iPoint, iEntry) = val; + } + /*! * \brief Constructor of the class. * \param[in] species_inf - species variable values (initialization value). diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 10655df398dd..19139ebf5bcd 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -104,6 +104,12 @@ void CSpeciesFlameletSolver::Preprocessing(CGeometry* geometry, CSolver** solver SU2_OMP_SAFE_GLOBAL_ACCESS(config->SetGlobalParam(config->GetKind_Solver(), RunTime_EqSystem); n_not_in_domain_local = 0;) + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + pd_jacobian = flamelet_config_options.preferential_diffusion && (config->GetKind_TimeIntScheme() == EULER_IMPLICIT); + if (pd_jacobian) SetPrefDiffJacobianSteps(); + } + END_SU2_OMP_SAFE_GLOBAL_ACCESS + /* Update global flame thickness value. */ if (calc_flame_thickness) { /*--- Every thread takes part in this, it reduces over the points of the rank and over ranks, @@ -776,9 +782,84 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode for (auto i_beta = 0u; i_beta < FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS; i_beta++) { nodes->SetAuxVar(iPoint, i_beta, beta_scalar[i_beta]); } + if (!pd_jacobian) return misses; + + /*--- Differences of the beta scalars and of the temperature, which drives the thermal term: central inside + * the manifold, one-sided towards it at its edges, and the ordinary diffusion Jacobian where neither fits. ---*/ + const auto n_cv = flamelet_config_options.n_control_vars; + auto beta_index = [this](int i_cv) { + if (i_cv == idx_progvar) return I_BETA_PROGVAR; + if (i_cv == idx_enth) return I_BETA_ENTH; + return I_BETA_MIXFRAC; + }; + const su2double temperature = fluid_model_local->GetTemperature(); + vector scalars_fd(scalars), beta_plus(beta_scalar.size()), beta_minus(beta_scalar.size()); + + for (auto j_cv = 0u; j_cv < n_cv; j_cv++) { + const su2double step = pd_jacobian_step[j_cv]; + scalars_fd[j_cv] = scalars[j_cv] + step; + bool inside_plus = fluid_model_local->EvaluateDataSet(scalars_fd, FLAMELET_LOOKUP_OPS::PREFDIF, beta_plus) == 0; + fluid_model_local->SetTDState_T(temperature, scalars_fd.data()); + inside_plus = inside_plus && (fluid_model_local->GetExtrapolation() == 0); + su2double temperature_plus = fluid_model_local->GetTemperature(); + scalars_fd[j_cv] = scalars[j_cv] - step; + bool inside_minus = fluid_model_local->EvaluateDataSet(scalars_fd, FLAMELET_LOOKUP_OPS::PREFDIF, beta_minus) == 0; + fluid_model_local->SetTDState_T(temperature, scalars_fd.data()); + inside_minus = inside_minus && (fluid_model_local->GetExtrapolation() == 0); + su2double temperature_minus = fluid_model_local->GetTemperature(); + scalars_fd[j_cv] = scalars[j_cv]; + + su2double span = 2 * step; + if (!inside_plus) { + beta_plus = beta_scalar; + temperature_plus = temperature; + span = step; + } + if (!inside_minus) { + beta_minus = beta_scalar; + temperature_minus = temperature; + span = step; + } + const bool usable = (misses == 0) && (inside_plus || inside_minus); + + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + su2double value = (i_cv == j_cv) ? su2double(1.0) : su2double(0.0); + if (usable) { + const auto i_beta = beta_index(i_cv); + su2double d_state = (beta_plus[i_beta] - beta_minus[i_beta]) / span; + if (static_cast(i_cv) == idx_enth) + d_state += beta_scalar[I_BETA_ENTH_THERMAL] * (temperature_plus - temperature_minus) / span; + value = d_state - ((i_cv == j_cv) ? 1.0 : 0.0); + /*--- The total diagonal, ordinary diffusion included, is kept positive. ---*/ + if (i_cv == j_cv) value = max(value, su2double(-0.9)); + } + nodes->SetPrefDiffJacobian(iPoint, i_cv * n_cv + j_cv, value); + } + } + fluid_model_local->SetTDState_T(temperature, scalars.data()); return misses; } +void CSpeciesFlameletSolver::SetPrefDiffJacobianSteps() { + const auto n_cv = flamelet_config_options.n_control_vars; + passivedouble local_min[MAXNVAR], local_max[MAXNVAR], global_min[MAXNVAR], global_max[MAXNVAR]; + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + local_min[i_cv] = std::numeric_limits::max(); + local_max[i_cv] = std::numeric_limits::lowest(); + } + for (auto i_point = 0u; i_point < nPointDomain; i_point++) { + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + const passivedouble value = SU2_TYPE::GetValue(nodes->GetSolution(i_point, i_cv)); + local_min[i_cv] = min(local_min[i_cv], value); + local_max[i_cv] = max(local_max[i_cv], value); + } + } + SU2_MPI::Allreduce(local_min, global_min, n_cv, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(local_max, global_max, n_cv, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) + pd_jacobian_step[i_cv] = max(1e-3 * (global_max[i_cv] - global_min[i_cv]), 1e-12); +} + void CSpeciesFlameletSolver::Upwind_Residual(CGeometry* geometry, CSolver** solver_container, CNumerics**, CConfig* config, unsigned short iMesh) { SU2_ZONE_SCOPED diff --git a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index 41f46e9d2929..e81b7ab17d8d 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -58,5 +58,7 @@ CSpeciesFlameletVariable::CSpeciesFlameletVariable(const su2double* species_inf, if (flamelet_config_options.preferential_diffusion) { AuxVar.resize(nPoint, FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS) = su2double(0.0); Grad_AuxVar.resize(nPoint, FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS, nDim, 0.0); + const auto n_cv = flamelet_config_options.n_control_vars; + PrefDiffJacobian.resize(nPoint, n_cv * n_cv) = su2double(0.0); } } From c8e246d4cdf7cd4e0e315e17b3de6c2d2148c07f Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:31:34 +0100 Subject: [PATCH 19/40] Flamelet: keep the burnt state of the flame front initialization inside the manifold GetBurntProgressVariable marched the progress variable up in steps of 1e-3 and returned the first value that was outside the manifold, because the step taken after leaving it was subtracted only once. The whole burnt region of a flame front initialization then started just outside the table, where the lookup returns frozen values of the nearest nodes; in a lean H2 slit burner these points persisted as a band of progress variable above equilibrium. The march now keeps the last value inside the manifold. When it leaves the manifold, the edge is bisected and the burnt value is set 0.1% of the progress variable range inside it. When the ignition temperature is reached first, that value is returned as before. Co-Authored-By: Claude Opus 5.5 --- .../src/solvers/CSpeciesFlameletSolver.cpp | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 19139ebf5bcd..d0950eac39a6 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -918,15 +918,37 @@ su2double CSpeciesFlameletSolver::GetBurntProgressVariable(CFluidModel* fluid_mo SU2_ZONE_SCOPED su2double scalars[MAXNVAR], delta = 1e-3; for (auto iVar = 0u; iVar < nVar; iVar++) scalars[iVar] = scalar_solution[iVar]; - bool outside = false; - scalars[idx_flame_front] += delta; - while (!outside) { - /*--- Note that 300.0 is a dummy temperature here and not used. ---*/ + + /*--- Note that 300.0 is a dummy temperature here and not used. ---*/ + auto inside = [&](su2double pv) { + scalars[idx_flame_front] = pv; fluid_model->SetTDState_T(300.0, scalars); - if ((fluid_model->GetExtrapolation() == 1) || fluid_model->GetTemperature() > T_ignition) outside = true; - scalars[idx_flame_front] += delta; + return fluid_model->GetExtrapolation() == 0; + }; + + /*--- March up while the state stays inside the manifold, until the ignition temperature is exceeded. ---*/ + const su2double pv_unburnt = scalar_solution[idx_flame_front]; + su2double pv_burnt = pv_unburnt, pv_trial = pv_unburnt + delta; + bool ignited = false; + while (!ignited && inside(pv_trial)) { + pv_burnt = pv_trial; + ignited = fluid_model->GetTemperature() > T_ignition; + pv_trial += delta; } - su2double pv_burnt = scalars[idx_flame_front] - delta; + + /*--- The march left the manifold: bisect to its edge and keep a margin inside it. ---*/ + if (!ignited) { + su2double pv_out = pv_trial; + for (int iter = 0; iter < 30; iter++) { + const su2double pv_mid = 0.5 * (pv_burnt + pv_out); + if (inside(pv_mid)) pv_burnt = pv_mid; + else pv_out = pv_mid; + } + const su2double pv_margin = pv_burnt - 1e-3 * (pv_burnt - pv_unburnt); + if (inside(pv_margin)) pv_burnt = pv_margin; + } + inside(pv_burnt); + if (rank == MASTER_NODE) { cout << "Burnt progress variable determined from flamelet table: " << pv_burnt << endl; cout << "Burnt temperature from flamelet table: " << fluid_model->GetTemperature() << endl; From 140bb03b371af6cce8a8b5d30c4380b64e6447c5 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 20:44:45 +0100 Subject: [PATCH 20/40] Flamelet table range, reduced and implicit PV sources, local time steps, inlet profiles Flamelet manifold: - CLookUpTable computes the progress variable range of each table level as a function of the second controlling variable from the boundary edges (GetRangeCV1). With axes (c, h) and levels in the progress variable variance, the upper bound of c is capped by the table edge and lookups are moved just inside it. - Sources named *_Reduced are tabulated divided by c*(1-c*) and multiplied back in SU2, so they vanish at the progress variable bounds. - FLAMELET_IMPLICIT_PV_SOURCE adds the derivative of the progress variable source to the Jacobian where the source decreases with the progress variable. - The variance normalisation stays continuous at the bounds of the mean. Convergence: - BETA_LOCAL_FLOOR: local preconditioning parameter of the incompressible solver, beta from the local velocity bounded below by a fraction of the domain maximum (1 keeps the uniform value). - SCALAR_TIME_STEP_RATIO: scalars use their own local convective and diffusive time step, capped at this ratio times the flow time step (1 keeps the flow time step). Inlet profiles: - CMarkerProfileReaderFVM keeps the header skip per marker, so files with several markers are read correctly. - Flamelet inlets with a profile file take the enthalpy from the profile. Co-Authored-By: Claude Opus 5.5 --- Common/include/CConfig.hpp | 14 +++ Common/include/containers/CLookUpTable.hpp | 24 +++++ Common/include/option_structure.hpp | 1 + Common/src/CConfig.cpp | 8 ++ Common/src/containers/CLookUpTable.cpp | 95 +++++++++++++++++++ SU2_CFD/include/fluid/CFluidFlamelet.hpp | 16 ++++ SU2_CFD/include/fluid/CFluidModel.hpp | 8 ++ SU2_CFD/include/solvers/CScalarSolver.inl | 20 ++++ .../solvers/CSpeciesFlameletSolver.hpp | 1 + SU2_CFD/src/CMarkerProfileReaderFVM.cpp | 11 ++- SU2_CFD/src/fluid/CFluidFlamelet.cpp | 66 +++++++++++-- SU2_CFD/src/solvers/CIncEulerSolver.cpp | 7 +- .../src/solvers/CSpeciesFlameletSolver.cpp | 40 ++++++++ config_template.cfg | 12 +++ 14 files changed, 310 insertions(+), 13 deletions(-) diff --git a/Common/include/CConfig.hpp b/Common/include/CConfig.hpp index 17afb4dc5476..c684d97cecfa 100644 --- a/Common/include/CConfig.hpp +++ b/Common/include/CConfig.hpp @@ -449,6 +449,7 @@ class CConfig { CFLRedCoeff_AdjFlow, /*!< \brief CFL reduction coefficient for the adjoint problem. */ CFLRedCoeff_AdjTurb, /*!< \brief CFL reduction coefficient for the adjoint turbulent problem. */ CFLRedCoeff_Species, /*!< \brief CFL reduction coefficient on the species problem. */ + Scalar_TimeStep_Ratio, /*!< \brief Maximum ratio of the scalar to the flow time step. */ CFLFineGrid, /*!< \brief CFL of the finest grid. */ Max_DeltaTime, /*!< \brief Max delta time. */ Unst_CFL; /*!< \brief Unsteady CFL number. */ @@ -894,6 +895,7 @@ class CConfig { su2double Gamma, /*!< \brief Ratio of specific heats of the gas. */ Bulk_Modulus, /*!< \brief Value of the bulk modulus for incompressible flows. */ Beta_Factor, /*!< \brief Value of the epsilon^2 multiplier for Beta for the incompressible preconditioner. */ + Beta_Local_Floor, /*!< \brief Lower bound of the local velocity^2 in Beta, as a fraction of the domain maximum. */ Gas_Constant, /*!< \brief Specific gas constant. */ Gas_ConstantND, /*!< \brief Non-dimensional specific gas constant. */ *Molecular_Weight; /*!< \brief Molecular weight of an incompressible ideal gas (g/mol). */ @@ -1781,6 +1783,12 @@ class CConfig { */ su2double GetBeta_Factor(void) const { return Beta_Factor; } + /*! + * \brief Lower bound of the local velocity^2 in the incompressible preconditioner, as a fraction of the maximum. + * \return 1 gives a uniform Beta from the maximum velocity in the domain. + */ + su2double GetBeta_Local_Floor(void) const { return Beta_Local_Floor; } + /*! * \brief Get the value of specific gas constant. * \return Value of the constant: Gamma @@ -7494,6 +7502,12 @@ class CConfig { */ su2double GetCFLRedCoeff_Species() const { return CFLRedCoeff_Species; } + /*! + * \brief Maximum ratio of the scalar to the flow time step. + * \return 1 to use the flow time step, larger values to use the local scalar time step up to this ratio. + */ + su2double GetScalar_TimeStep_Ratio() const { return Scalar_TimeStep_Ratio; } + /*! * \brief Get the flow direction unit vector at an inlet boundary. * \param[in] val_index - Index corresponding to the inlet boundary. diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index e8f14408b751..30a1ac6bd480 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -99,6 +99,12 @@ class CLookUpTable { */ su2vector> hull; + /*! \brief Values of the second controlling variable at which the boundary of each table level has a vertex. */ + su2vector> range_CV2; + + /*! \brief First controlling variable on the lower and upper boundary at both ends of each range_CV2 interval. */ + su2vector>> range_CV1; + /*! \brief * Trapezoidal map objects for the table levels. */ @@ -143,6 +149,17 @@ class CLookUpTable { */ void IdentifyUniqueEdges(); + /*! + * \brief Tabulate the range of the first controlling variable covered by each table level, from its boundary edges. + */ + void ComputeRangeCV1(); + + /*! + * \brief Range of the first controlling variable covered by a table level at a value of the second. + * \returns false if the level has no extent in the second controlling variable. + */ + bool GetRangeCV1OnLevel(su2double val_CV2, unsigned long i_level, su2double& val_min, su2double& val_max) const; + /*! * \brief Read the lookup table from file and store the data. * \param[in] file_name_lut - the filename of the lookup table. @@ -305,6 +322,13 @@ class CLookUpTable { public: CLookUpTable(const std::string& file_name_lut, std::string name_CV1_in, std::string name_CV2_in); + /*! + * \brief Range of the first controlling variable inside the table at the given second and third controlling variable. + * \note For a 3D table, the range is common to both table levels the lookup interpolates between. + * \returns false if a level has no extent in the second controlling variable. + */ + bool GetRangeCV1(su2double val_CV2, su2double val_CV3, su2double& val_min, su2double& val_max); + /*! * \brief Print information to screen. */ diff --git a/Common/include/option_structure.hpp b/Common/include/option_structure.hpp index 0393d01ccae4..6dc0b4428d8b 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1624,6 +1624,7 @@ struct FluidFlamelet_ParsedOptions { int idx_mixfrac_var = -1; /*!< \brief Scalar index of the mixture fraction variance, -1 if absent. */ su2double variance_dissipation_coeff = 2.0; /*!< \brief C_d in the variance dissipation C_d rho (eps/k) var. */ bool tabulated_variance_source = false; /*!< \brief The variance source column holds the chemical variance source itself. */ + bool implicit_progvar_source = false; /*!< \brief Add the decreasing part of the progress variable source to the Jacobian. */ std::string *controlling_variable_names; /*!< \brief Names of the independent, transported scalars. */ std::string* cv_source_names; /*!< \brief Names of the source terms of the independent, transported scalars. */ diff --git a/Common/src/CConfig.cpp b/Common/src/CConfig.cpp index 67c179eadb3b..bf89f5633194 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -1446,6 +1446,8 @@ void CConfig::SetConfig_Options() { addDoubleOption("BULK_MODULUS", Bulk_Modulus, 1.42E5); /* DESCRIPTION: Epsilon^2 multipier in Beta calculation for incompressible preconditioner. */ addDoubleOption("BETA_FACTOR", Beta_Factor, 4.1); + /*!\brief BETA_LOCAL_FLOOR \n DESCRIPTION: Lower bound of the local velocity^2 in Beta, as a fraction of the maximum velocity^2. 1 gives a uniform Beta. \ingroup Config*/ + addDoubleOption("BETA_LOCAL_FLOOR", Beta_Local_Floor, 1.0); /*!\brief MACH_NUMBER \n DESCRIPTION: Mach number (non-dimensional, based on the free-stream values). 0.0 by default \ingroup Config*/ addDoubleOption("MACH_NUMBER", Mach, 0.0); /*!\brief INIT_OPTION \n DESCRIPTION: Init option to choose between Reynolds or thermodynamics quantities for initializing the solution \n OPTIONS: see \link InitOption_Map \endlink \n DEFAULT REYNOLDS \ingroup Config*/ @@ -1533,6 +1535,9 @@ void CConfig::SetConfig_Options() { /*!\brief FLAMELET_TABULATED_VARIANCE_SOURCE \n DESCRIPTION: The variance source column of the manifold is the chemical variance source 2 (mean(phi S) - mean(phi) mean(S)) instead of mean(phi S) \ingroup Config*/ addBoolOption("FLAMELET_TABULATED_VARIANCE_SOURCE", flamelet_ParsedOptions.tabulated_variance_source, false); + /*!\brief FLAMELET_IMPLICIT_PV_SOURCE \n DESCRIPTION: Treat the progress variable source implicitly where it decreases with the progress variable \ingroup Config*/ + addBoolOption("FLAMELET_IMPLICIT_PV_SOURCE", flamelet_ParsedOptions.implicit_progvar_source, false); + /*--- Options related to mass diffusivity and thereby the species solver. ---*/ /*!\brief DIFFUSIVITY_MODEL\n DESCRIPTION: mass diffusivity model \n DEFAULT constant disffusivity \ingroup Config*/ @@ -1955,6 +1960,9 @@ void CConfig::SetConfig_Options() { addDoubleOption("CFL_REDUCTION_ADJTURB", CFLRedCoeff_AdjTurb, 1.0); /*!\brief CFL_REDUCTION_SPECIES \n DESCRIPTION: Reduction factor of the CFL coefficient in the species problem \n DEFAULT: 1.0 */ addDoubleOption("CFL_REDUCTION_SPECIES", CFLRedCoeff_Species, 1.0); + /*!\brief SCALAR_TIME_STEP_RATIO \n DESCRIPTION: Maximum ratio of the scalar to the flow time step. Above 1, scalars use their local convective + * and diffusive time step, capped at this ratio times the flow time step. \n DEFAULT: 1.0 */ + addDoubleOption("SCALAR_TIME_STEP_RATIO", Scalar_TimeStep_Ratio, 1.0); /* DESCRIPTION: External iteration offset due to restart */ addUnsignedLongOption("EXT_ITER_OFFSET", ExtIter_OffSet, 0); // these options share nRKStep as their size, which is not a good idea in general diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 93ce64310d48..9347bff937e5 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -32,6 +32,8 @@ #include "../../../Common/include/linear_algebra/blas_structure.hpp" #include "../../../Common/include/toolboxes/CSquareMatrixCM.hpp" +#include + using namespace std; CLookUpTable::CLookUpTable(const string& var_file_name_lut, string name_CV1_in, string name_CV2_in) @@ -49,6 +51,7 @@ CLookUpTable::CLookUpTable(const string& var_file_name_lut, string name_CV1_in, if (rank == MASTER_NODE) cout << "Detecting all unique edges and setting edge to triangle connectivity ..." << endl; IdentifyUniqueEdges(); + ComputeRangeCV1(); if (rank == MASTER_NODE) cout << " done." << endl; @@ -396,6 +399,98 @@ void CLookUpTable::GetInterpMatInv(const su2double* vec_x, const su2double* vec_ } } +void CLookUpTable::ComputeRangeCV1() { + range_CV2.resize(n_table_levels); + range_CV1.resize(n_table_levels); + const su2double big = std::numeric_limits::max(); + + for (auto i_level = 0ul; i_level < n_table_levels; i_level++) { + const su2double* x = table_data[i_level][idx_CV1]; + const su2double* y = table_data[i_level][idx_CV2]; + + /*--- Boundary edges belong to a single triangle; store them with increasing y. ---*/ + vector> boundary; + for (auto i_edge = 0ul; i_edge < edges[i_level].size(); i_edge++) { + if (edge_to_triangle[i_level][i_edge].size() != 1) continue; + auto a = edges[i_level][i_edge][0], b = edges[i_level][i_edge][1]; + if (y[a] > y[b]) std::swap(a, b); + if (y[b] > y[a]) boundary.push_back({a, b}); + } + + auto& breaks = range_CV2[i_level]; + for (const auto& e : boundary) { + breaks.push_back(y[e[0]]); + breaks.push_back(y[e[1]]); + } + sort(breaks.begin(), breaks.end()); + breaks.erase(unique(breaks.begin(), breaks.end()), breaks.end()); + if (breaks.size() < 2) { + breaks.clear(); + continue; + } + + /*--- Between two breaks the boundary is linear; keep the edges with the lowest and highest x halfway. ---*/ + const auto n_intervals = breaks.size() - 1; + auto& range = range_CV1[i_level]; + range.assign(n_intervals, {0, 0, 0, 0}); + vector x_low_mid(n_intervals, big), x_high_mid(n_intervals, -big); + for (const auto& e : boundary) { + const auto a = e[0], b = e[1]; + auto x_at = [&](const su2double val_y) { return x[a] + (x[b] - x[a]) * (val_y - y[a]) / (y[b] - y[a]); }; + const auto k_begin = lower_bound(breaks.begin(), breaks.end(), y[a]) - breaks.begin(); + const auto k_end = lower_bound(breaks.begin(), breaks.end(), y[b]) - breaks.begin(); + for (auto k = k_begin; k < k_end; k++) { + const su2double x_mid = x_at(0.5 * (breaks[k] + breaks[k + 1])); + if (x_mid < x_low_mid[k]) { + x_low_mid[k] = x_mid; + range[k][0] = x_at(breaks[k]); + range[k][1] = x_at(breaks[k + 1]); + } + if (x_mid > x_high_mid[k]) { + x_high_mid[k] = x_mid; + range[k][2] = x_at(breaks[k]); + range[k][3] = x_at(breaks[k + 1]); + } + } + } + } +} + +bool CLookUpTable::GetRangeCV1OnLevel(const su2double val_CV2, const unsigned long i_level, su2double& val_min, + su2double& val_max) const { + const auto& breaks = range_CV2[i_level]; + if (breaks.empty()) return false; + const long n_intervals = breaks.size() - 1; + const long k = min(max(long(upper_bound(breaks.begin(), breaks.end(), val_CV2) - breaks.begin()) - 1, 0L), + n_intervals - 1); + const su2double t = fmin(fmax((val_CV2 - breaks[k]) / (breaks[k + 1] - breaks[k]), su2double(0.0)), su2double(1.0)); + const auto& range = range_CV1[i_level][k]; + val_min = range[0] + t * (range[1] - range[0]); + val_max = range[2] + t * (range[3] - range[2]); + return true; +} + +bool CLookUpTable::GetRangeCV1(const su2double val_CV2, const su2double val_CV3, su2double& val_min, + su2double& val_max) { + if (table_dim == 2) return GetRangeCV1OnLevel(val_CV2, 0, val_min, val_max); + auto levels = FindInclusionLevels(val_CV3); + if (levels.first == levels.second) return GetRangeCV1OnLevel(val_CV2, levels.first, val_min, val_max); + /*--- Map the range of each level back to the query, like the lookup maps the query to the levels. ---*/ + const auto map_0 = ComputeNormalizedXY(levels, 0.0, val_CV2, val_CV3); + const auto map_1 = ComputeNormalizedXY(levels, 1.0, val_CV2, val_CV3); + val_min = -std::numeric_limits::max(); + val_max = std::numeric_limits::max(); + for (auto side = 0u; side < 2; side++) { + const auto i_level = (side == 0) ? levels.first : levels.second; + su2double level_min, level_max; + if (!GetRangeCV1OnLevel(map_0[side][1], i_level, level_min, level_max)) return false; + const su2double x_0 = map_0[side][0], dx = map_1[side][0] - map_0[side][0]; + val_min = fmax(val_min, (level_min - x_0) / dx); + val_max = fmin(val_max, (level_max - x_0) / dx); + } + return true; +} + std::pair CLookUpTable::FindInclusionLevels(const su2double val_CV3) { /*--- Find the table levels with constant z-values directly below and above the query value val_CV3 ---*/ diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index 664edfa6ffcc..24cf13fef152 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -73,6 +73,7 @@ class CFluidFlamelet final : public CFluidModel { vector manifold_inputs; /*!< \brief Controlling variables with the variances normalized. */ su2double limit_progvar_var = 0, /*!< \brief Upper limit of the progress variable variance. */ limit_mixfrac_var = 0; /*!< \brief Upper limit of the mixture fraction variance. */ + bool progvar_range_from_table = false; /*!< \brief Bound the progress variable by the edge of the table. */ /*--- Class variables for the multi-layer perceptron method ---*/ #ifdef USE_MLPCPP @@ -117,6 +118,15 @@ class CFluidFlamelet final : public CFluidModel { */ bool SetManifoldInputs(const su2double* scalars); + /*! + * \brief Multiply the reduced sources by c*(1-c*), with c* the progress variable scaled to [0,1] by its range. + * \param[in] scalars - Transported scalars, after SetManifoldInputs. + * \param[in,out] sources - Source terms of the manifold. + */ + void ScaleReducedSources(const su2double* scalars, vector& sources) const; + + vector reduced_sources; /*!< \brief Whether a source is given divided by c*(1-c*). */ + /*! \brief * Returns true if the string is null or zero (ignores case). */ @@ -165,6 +175,12 @@ class CFluidFlamelet final : public CFluidModel { */ su2double GetScalarVarianceLimit(const su2double* scalars, unsigned short i_var) override; + /*! + * \brief Minimum and maximum progress variable at the state of the transported scalars. + * \returns Whether the manifold provides the progress variable range. + */ + bool GetProgressVariableBounds(const su2double* scalars, su2double& c_min, su2double& c_max) override; + /*! * \brief Check for out-of-bounds condition for data set interpolation. * \return - within bounds (0) or out of bounds (1). diff --git a/SU2_CFD/include/fluid/CFluidModel.hpp b/SU2_CFD/include/fluid/CFluidModel.hpp index 47528e25ff39..f04e88c388a2 100644 --- a/SU2_CFD/include/fluid/CFluidModel.hpp +++ b/SU2_CFD/include/fluid/CFluidModel.hpp @@ -169,6 +169,14 @@ class CFluidModel { */ virtual su2double GetScalarVarianceLimit(const su2double* scalars, unsigned short i_var) { return 1.0e15; } + /*! + * \brief Minimum and maximum progress variable at the state of the transported scalars. + * \returns Whether the fluid model provides the progress variable range. + */ + virtual bool GetProgressVariableBounds(const su2double* scalars, su2double& c_min, su2double& c_max) { + return false; + } + /*! * \brief Get fluid dynamic viscosity. */ diff --git a/SU2_CFD/include/solvers/CScalarSolver.inl b/SU2_CFD/include/solvers/CScalarSolver.inl index 941d68928493..d1c768dde47e 100644 --- a/SU2_CFD/include/solvers/CScalarSolver.inl +++ b/SU2_CFD/include/solvers/CScalarSolver.inl @@ -487,9 +487,29 @@ void CScalarSolver::SetTime_Step(CGeometry *geometry, CSolver **so const auto flowNodes = solver_container[FLOW_SOL]->GetNodes(); + const su2double max_ratio = config->GetScalar_TimeStep_Ratio(); + SU2_OMP_FOR_STAT(omp_chunk_size) for (unsigned long iPoint = 0; iPoint < nPointDomain; iPoint++) { su2double dt = nodes->GetLocalCFL(iPoint) / flowNodes->GetLocalCFL(iPoint) * flowNodes->GetDelta_Time(iPoint); + + /*--- Scalars are carried at the flow speed, without the artificial sound speed of the flow time step. ---*/ + if (max_ratio > 1.0 && !geometry->nodes->GetPhysicalBoundary(iPoint)) { + su2double lambda_conv = 0.0; + for (unsigned short iNeigh = 0; iNeigh < geometry->nodes->GetnNeighbor(iPoint); iNeigh++) { + const auto jPoint = geometry->nodes->GetPoint(iPoint, iNeigh); + const auto* normal = geometry->edges->GetNormal(geometry->nodes->GetEdge(iPoint, iNeigh)); + su2double proj_vel = 0.0; + for (unsigned short iDim = 0; iDim < nDim; iDim++) + proj_vel += 0.5 * (flowNodes->GetVelocity(iPoint, iDim) + flowNodes->GetVelocity(jPoint, iDim)) * normal[iDim]; + lambda_conv += fabs(proj_vel); + } + const su2double vol = geometry->nodes->GetVolume(iPoint); + const su2double cfl = nodes->GetLocalCFL(iPoint); + const su2double dt_conv = cfl * vol / max(lambda_conv, EPS); + const su2double dt_visc = cfl * 0.25 * vol * vol / max(flowNodes->GetMax_Lambda_Visc(iPoint), EPS); + dt = min({dt_conv, dt_visc, max_ratio * dt}); + } nodes->SetDelta_Time(iPoint, dt); } END_SU2_OMP_FOR diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index e989b63f2897..e5682927f930 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -45,6 +45,7 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { int idx_enth = -1; /*!< \brief Scalar index of the total enthalpy. */ int idx_flame_front = -1; /*!< \brief Scalar set by FLAME_FRONT: progress variable, else mixture fraction. */ vector> variance_sources; /*!< \brief Variance and mean indices of variances with a chemical source. */ + vector progvar_source_slope; /*!< \brief Derivative of the progress variable source to the progress variable. */ /*!< \brief Number of points outside the manifold domain, shared across OpenMP threads so it can be * accumulated atomically and reduced by the master thread alone in Preprocessing. */ unsigned long n_not_in_domain_local = 0; diff --git a/SU2_CFD/src/CMarkerProfileReaderFVM.cpp b/SU2_CFD/src/CMarkerProfileReaderFVM.cpp index c9850d87c215..9c9279b8da91 100644 --- a/SU2_CFD/src/CMarkerProfileReaderFVM.cpp +++ b/SU2_CFD/src/CMarkerProfileReaderFVM.cpp @@ -79,7 +79,7 @@ void CMarkerProfileReaderFVM::ReadMarkerProfile() { ifstream profile_file; profile_file.open(filename.data(), ios::in); bool nmarkFound = false; - unsigned long skip = 0; + vector skip; /*--- Identify the markers and data set in the profile file ---*/ @@ -95,6 +95,7 @@ void CMarkerProfileReaderFVM::ReadMarkerProfile() { numberOfRowsInProfile.resize(numberOfProfiles); numberOfColumnsInProfile.resize(numberOfProfiles); + skip.assign(numberOfProfiles, 0); for (unsigned short iMarker = 0 ; iMarker < numberOfProfiles; iMarker++) { @@ -120,15 +121,15 @@ void CMarkerProfileReaderFVM::ReadMarkerProfile() { getline (profile_file, text_line); string::size_type dataheader = text_line.find ("# COORD",0); if (dataheader == 0) { - skip = 0; + skip[iMarker] = 0; } else { /*--- no header, but we have read a line, so we have to read one line less data ---*/ - skip = 1; + skip[iMarker] = 1; } /*--- Skip the data. This is read in the next loop. ---*/ - for (unsigned long iRow = 0; iRow < (numberOfRowsInProfile[iMarker]-skip); iRow++) getline (profile_file, text_line); + for (unsigned long iRow = 0; iRow < (numberOfRowsInProfile[iMarker]-skip[iMarker]); iRow++) getline (profile_file, text_line); } } @@ -166,7 +167,7 @@ void CMarkerProfileReaderFVM::ReadMarkerProfile() { getline (profile_file, text_line); /*--- if skip=0 then we can expect column format description ---*/ - if (skip == 0) getline (profile_file, text_line); + if (skip[iMarker] == 0) getline (profile_file, text_line); /*--- Now read the data for each row and store. ---*/ diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index 1e959fcae847..5061050c62db 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -25,6 +25,7 @@ * License along with SU2. If not, see . */ +#include #include #include #include "../../include/fluid/CFluidFlamelet.hpp" @@ -236,6 +237,19 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { val_vars_ProgVarBounds.resize(varnames_ProgVarBounds.size()); } + /*--- Sources with this suffix are divided by c*(1-c*), so they vanish at the progress variable bounds. ---*/ + const string reduced_suffix = "_Reduced"; + reduced_sources.resize(n_sources); + for (auto iVar = 0u; iVar < n_sources; iVar++) { + const string& name = varnames_Sources[iVar]; + reduced_sources[iVar] = (name.size() > reduced_suffix.size()) && + (name.compare(name.size() - reduced_suffix.size(), reduced_suffix.size(), reduced_suffix) == 0); + if (reduced_sources[iVar] && varnames_ProgVarBounds.empty()) + SU2_MPI::Error(string("The reduced source ") + name + " requires transport of " + FLAMELET_CV_NAME::PROGVAR_VAR + + ", which provides the progress variable range.", + CURRENT_FUNCTION); + } + preferential_diffusion = flamelet_options.preferential_diffusion; if (!preferential_diffusion && flamelet_options.preferential_diffusion) @@ -292,6 +306,9 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { FLAMELET_PROGVAR_BOUNDS::MIN + " and " + FLAMELET_PROGVAR_BOUNDS::MAX + " in the table.", CURRENT_FUNCTION); for (const auto& name : varnames_ProgVarBounds) LUT_idx_ProgVarBounds.push_back(look_up_table->GetIndexOfVar(name)); + /*--- With table axes (c, h) and levels in the variance, the table edge bounds c at each h. ---*/ + progvar_range_from_table = (n_control_vars == 3) && (flamelet_options.idx_progvar == 0) && + (flamelet_options.idx_progvar_var == 2); } } } @@ -303,34 +320,70 @@ su2double CFluidFlamelet::GetScalarVarianceLimit(const su2double* scalars, unsig return CFluidModel::GetScalarVarianceLimit(scalars, i_var); } +bool CFluidFlamelet::GetProgressVariableBounds(const su2double* scalars, su2double& c_min, su2double& c_max) { + if (varnames_ProgVarBounds.empty()) return false; + SetManifoldInputs(scalars); + c_min = val_vars_ProgVarBounds[0]; + c_max = val_vars_ProgVarBounds[1]; + return true; +} + bool CFluidFlamelet::SetManifoldInputs(const su2double* scalars) { for (auto iCV = 0u; iCV < n_control_vars; iCV++) manifold_inputs[iCV] = scalars[iCV]; - /*--- Variance divided by its upper limit, 0 where the mean is at a bound. ---*/ - auto normalize = [](su2double variance, su2double limit) { - return (limit > 0) ? fmin(fmax(variance / limit, su2double(0.0)), su2double(1.0)) : su2double(0.0); + /*--- Variance divided by its upper limit plus an offset that keeps the ratio continuous at the bounds of the mean. ---*/ + auto normalize = [](su2double variance, su2double limit, su2double range) { + const su2double denominator = limit + 1e-12 * range * range; + return (denominator > 0) ? fmin(fmax(variance / denominator, su2double(0.0)), su2double(1.0)) : su2double(0.0); }; const int i_zvar = flamelet_options.idx_mixfrac_var; if (i_zvar >= 0) { const su2double z = scalars[flamelet_options.idx_mixfrac]; limit_mixfrac_var = fmax(z * (1.0 - z), su2double(0.0)); - manifold_inputs[i_zvar] = normalize(scalars[i_zvar], limit_mixfrac_var); + manifold_inputs[i_zvar] = normalize(scalars[i_zvar], limit_mixfrac_var, 1.0); } + /*--- Moves the progress variable of the lookup just inside the table edge and below c_max. ---*/ + const int i_c = flamelet_options.idx_progvar; + auto clamp_to_table = [&](su2double c_max) { + su2double edge_min, edge_max; + if (!look_up_table->GetRangeCV1(manifold_inputs[1], manifold_inputs[2], edge_min, edge_max)) return c_max; + const su2double margin = 1e-10 * (edge_max - edge_min); + manifold_inputs[i_c] = fmin(fmax(scalars[i_c], edge_min + margin), fmin(edge_max, c_max) - margin); + return edge_max; + }; + bool inside{true}; const int i_cvar = flamelet_options.idx_progvar_var; if (i_cvar >= 0) { /*--- The range of the progress variable does not depend on its variance. ---*/ manifold_inputs[i_cvar] = 0.0; + su2double edge_max{0}; + if (progvar_range_from_table) edge_max = clamp_to_table(std::numeric_limits::max()); inside = LookUpManifold(FLAMELET_LOOKUP_OPS::PROGVAR_BOUNDS, manifold_inputs, val_vars_ProgVarBounds); - const su2double c = scalars[flamelet_options.idx_progvar]; + if (progvar_range_from_table) val_vars_ProgVarBounds[1] = fmin(val_vars_ProgVarBounds[1], edge_max); + const su2double c = scalars[i_c]; limit_progvar_var = fmax((c - val_vars_ProgVarBounds[0]) * (val_vars_ProgVarBounds[1] - c), su2double(0.0)); - manifold_inputs[i_cvar] = normalize(scalars[i_cvar], limit_progvar_var); + manifold_inputs[i_cvar] = normalize(scalars[i_cvar], limit_progvar_var, + val_vars_ProgVarBounds[1] - val_vars_ProgVarBounds[0]); + if (progvar_range_from_table) clamp_to_table(val_vars_ProgVarBounds[1]); } return inside; } +void CFluidFlamelet::ScaleReducedSources(const su2double* scalars, vector& sources) const { + if (varnames_ProgVarBounds.empty()) return; + const su2double c_min = val_vars_ProgVarBounds[0]; + const su2double c_range = val_vars_ProgVarBounds[1] - c_min; + const su2double c_star = + (c_range > 0) ? fmin(fmax((scalars[flamelet_options.idx_progvar] - c_min) / c_range, su2double(0.0)), su2double(1.0)) + : su2double(0.0); + const su2double factor = c_star * (1.0 - c_star); + for (auto iVar = 0u; iVar < sources.size(); iVar++) + if (reduced_sources[iVar]) sources[iVar] *= factor; +} + bool CFluidFlamelet::LookUpManifold(unsigned short lookup_type, const vector& inputs, vector& output_refs) { vector* LUT_idx = nullptr; @@ -405,6 +458,7 @@ unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_sca bool inside = SetManifoldInputs(input_scalar.data()); inside = LookUpManifold(lookup_type, manifold_inputs, output_refs) && inside; + if (lookup_type == FLAMELET_LOOKUP_OPS::SOURCES) ScaleReducedSources(input_scalar.data(), output_refs); extrapolation = inside ? 0 : 1; for (auto iVar = 0u; iVar < output_refs.size(); iVar++) AD::SetPreaccOut(output_refs[iVar]); diff --git a/SU2_CFD/src/solvers/CIncEulerSolver.cpp b/SU2_CFD/src/solvers/CIncEulerSolver.cpp index 08af0f78e72b..ecbbcce2422d 100644 --- a/SU2_CFD/src/solvers/CIncEulerSolver.cpp +++ b/SU2_CFD/src/solvers/CIncEulerSolver.cpp @@ -2259,11 +2259,14 @@ void CIncEulerSolver::SetBeta_Parameter(CGeometry *geometry, CSolver **solver_co /*--- Allow an override if user supplies a large epsilon^2. ---*/ - su2double BetaInc2 = max(epsilon2_default, config->GetBeta_Factor()) * config->GetMax_Vel2(); + const su2double beta_factor = max(epsilon2_default, config->GetBeta_Factor()); + + /*--- Local velocity scale, bounded below by a fraction of the domain maximum. ---*/ + const su2double floor_vel2 = config->GetBeta_Local_Floor() * config->GetMax_Vel2(); SU2_OMP_FOR_STAT(omp_chunk_size) for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) - nodes->SetBetaInc2(iPoint, BetaInc2); + nodes->SetBetaInc2(iPoint, beta_factor * max(floor_vel2, nodes->GetVelocity2(iPoint))); END_SU2_OMP_FOR } diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index d0950eac39a6..a28f9312d8e4 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -70,6 +70,7 @@ CSpeciesFlameletSolver::CSpeciesFlameletSolver(CGeometry* geometry, CConfig* con nodes = new CSpeciesFlameletVariable(Solution_Inf, nPoint, nDim, nVar, config); SetBaseClassPointerToNodes(); + progvar_source_slope.assign(nPoint, 0.0); /*--- Store the initial CFL number for all grid points. ---*/ @@ -483,6 +484,9 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv * dS_aux_i/d(rho Y_aux_i) = source_cons_i / rho * J_ii += -source_cons_i / rho * V ---*/ if (implicit) { + /*--- Only a source that decreases with the progress variable is made implicit. ---*/ + if (idx_progvar >= 0 && progvar_source_slope[i_point] < 0) + Jacobian.AddVal2Diag(i_point, idx_progvar, -progvar_source_slope[i_point] / density * volume); for (auto i_aux = 0u; i_aux < n_aux; i_aux++) { Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) / density * volume); } @@ -581,6 +585,12 @@ void CSpeciesFlameletSolver::BC_Inlet(CGeometry* geometry, CSolver** solver_cont SU2_ZONE_SCOPED string Marker_Tag = config->GetMarker_All_TagBound(val_marker); + /*--- An inlet profile file provides the enthalpy at each vertex. ---*/ + if (config->GetInlet_Profile_From_File()) { + CSpeciesSolver::BC_Inlet(geometry, solver_container, conv_numerics, visc_numerics, config, val_marker); + return; + } + su2double enth_inlet; if (config->GetFlamelet_Enthalpy_BC() == FLAMELET_ENTHALPY_BC::FLOW_MARKERS) { /*--- Derive inlet enthalpy from MARKER_INLET temperature via Newton iteration on the LUT. @@ -725,6 +735,36 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF /*--- The source term for progress variable is always positive, we clip from below to make sure. --- */ if (idx_progvar >= 0) table_sources[idx_progvar] = fmax(0, table_sources[idx_progvar]); + /*--- Difference of the progress variable source within the table range, for its implicit treatment. ---*/ + if (idx_progvar >= 0 && flamelet_config_options.implicit_progvar_source && + config->GetKind_TimeIntScheme_Species() == EULER_IMPLICIT) { + const int idx_var = flamelet_config_options.idx_progvar_var; + const su2double c = scalars[idx_progvar]; + su2double c_min, c_max; + su2double c_lo = c - 1e-3, c_hi = c + 1e-3, s_var = 0.0; + const bool bounded = fluid_model_local->GetProgressVariableBounds(scalars.data(), c_min, c_max) && (c_max > c_min); + if (bounded) { + /*--- Both points lie strictly inside the range, at the normalized variance of the node. ---*/ + const su2double delta = 1e-3 * (c_max - c_min); + const su2double lower = c_min + 1e-2 * delta, upper = c_max - 1e-2 * delta; + const su2double c_in = fmin(fmax(c, lower), upper); + c_lo = fmax(c_in - delta, lower); + c_hi = fmin(c_in + delta, upper); + const su2double room = (c - c_min) * (c_max - c); + if (idx_var >= 0 && room > 0) s_var = fmin(fmax(scalars[idx_var] / room, su2double(0.0)), su2double(1.0)); + } + vector shifted(scalars), sources_shifted(table_sources.size()); + su2double source_pm[2]; + for (int side = 0; side < 2; side++) { + shifted[idx_progvar] = (side == 0) ? c_hi : c_lo; + if (bounded && idx_var >= 0) + shifted[idx_var] = s_var * (shifted[idx_progvar] - c_min) * (c_max - shifted[idx_progvar]); + fluid_model_local->EvaluateDataSet(shifted, FLAMELET_LOOKUP_OPS::SOURCES, sources_shifted); + source_pm[side] = fmax(0, sources_shifted[idx_progvar]); + } + progvar_source_slope[iPoint] = F * (source_pm[0] - source_pm[1]) / (c_hi - c_lo); + } + /*--- Variance source 2 (mean(phi S) - mean(phi) mean(S)), from mean(phi S) unless the manifold holds it. ---*/ if (!flamelet_config_options.tabulated_variance_source) for (const auto& var_mean : variance_sources) diff --git a/config_template.cfg b/config_template.cfg index f30b8739b1ae..fa5621678c40 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -354,6 +354,10 @@ INC_OUTLET_DAMPING= 0.1 BULK_MODULUS= 1.42E5 % Epsilon^2 multipier in Beta calculation for incompressible preconditioner. BETA_FACTOR= 4.1 +% +% Lower bound of the local velocity^2 in Beta, as a fraction of the maximum velocity^2 in the domain. +% 1 gives a uniform Beta from the maximum velocity; smaller values give a local Beta (default 1.0) +BETA_LOCAL_FLOOR= 1.0 % -------------- PRESSURE-BASED INCOMPRESSIBLE SOLVER DEFINITION ---------------% % @@ -968,6 +972,10 @@ TIME_DISCRE_SPECIES= EULER_IMPLICIT % Reduction factor of the CFL coefficient in the species problem CFL_REDUCTION_SPECIES= 1.0 % +% Maximum ratio of the scalar (turbulence and species) to the flow time step. Above 1, the +% scalars use their local convective and diffusive time step, capped at this ratio. +SCALAR_TIME_STEP_RATIO= 1.0 +% % Initial values for scalar transport SPECIES_INIT= 1.0 % @@ -1134,6 +1142,10 @@ FLAMELET_VARIANCE_DISSIPATION_COEFF= 2.0 % The variance source column of the manifold is the chemical variance source 2 (mean(phi S) - mean(phi) mean(S)) % (YES) or mean(phi S) (NO). FLAMELET_TABULATED_VARIANCE_SOURCE= NO +% +% Add the derivative of the progress variable source to the Jacobian where the source decreases +% with the progress variable (YES, NO). +FLAMELET_IMPLICIT_PV_SOURCE= NO % Flame ignition temperature % Flame thickness calculations are performed when the maximum temperature in the flow solution exceeds this value. From 11eab1de260c5436ea0c6bf8136916221d4bd227 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 23:01:49 +0100 Subject: [PATCH 21/40] Flamelet: always treat a decreasing progress variable source implicitly The implicit treatment of the progress variable source only adds the part where the source decreases with the progress variable to the Jacobian, so it strengthens the diagonal and leaves the residual unchanged. It is now used whenever the scalars are integrated implicitly, and the option FLAMELET_IMPLICIT_PV_SOURCE is removed. Co-Authored-By: Claude Opus 5.5 --- Common/include/option_structure.hpp | 1 - Common/src/CConfig.cpp | 3 --- SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 3 +-- config_template.cfg | 4 ---- 4 files changed, 1 insertion(+), 10 deletions(-) diff --git a/Common/include/option_structure.hpp b/Common/include/option_structure.hpp index 6dc0b4428d8b..0393d01ccae4 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1624,7 +1624,6 @@ struct FluidFlamelet_ParsedOptions { int idx_mixfrac_var = -1; /*!< \brief Scalar index of the mixture fraction variance, -1 if absent. */ su2double variance_dissipation_coeff = 2.0; /*!< \brief C_d in the variance dissipation C_d rho (eps/k) var. */ bool tabulated_variance_source = false; /*!< \brief The variance source column holds the chemical variance source itself. */ - bool implicit_progvar_source = false; /*!< \brief Add the decreasing part of the progress variable source to the Jacobian. */ std::string *controlling_variable_names; /*!< \brief Names of the independent, transported scalars. */ std::string* cv_source_names; /*!< \brief Names of the source terms of the independent, transported scalars. */ diff --git a/Common/src/CConfig.cpp b/Common/src/CConfig.cpp index bf89f5633194..2c8390c875b0 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -1535,9 +1535,6 @@ void CConfig::SetConfig_Options() { /*!\brief FLAMELET_TABULATED_VARIANCE_SOURCE \n DESCRIPTION: The variance source column of the manifold is the chemical variance source 2 (mean(phi S) - mean(phi) mean(S)) instead of mean(phi S) \ingroup Config*/ addBoolOption("FLAMELET_TABULATED_VARIANCE_SOURCE", flamelet_ParsedOptions.tabulated_variance_source, false); - /*!\brief FLAMELET_IMPLICIT_PV_SOURCE \n DESCRIPTION: Treat the progress variable source implicitly where it decreases with the progress variable \ingroup Config*/ - addBoolOption("FLAMELET_IMPLICIT_PV_SOURCE", flamelet_ParsedOptions.implicit_progvar_source, false); - /*--- Options related to mass diffusivity and thereby the species solver. ---*/ /*!\brief DIFFUSIVITY_MODEL\n DESCRIPTION: mass diffusivity model \n DEFAULT constant disffusivity \ingroup Config*/ diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index a28f9312d8e4..d6bb5329694c 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -736,8 +736,7 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF if (idx_progvar >= 0) table_sources[idx_progvar] = fmax(0, table_sources[idx_progvar]); /*--- Difference of the progress variable source within the table range, for its implicit treatment. ---*/ - if (idx_progvar >= 0 && flamelet_config_options.implicit_progvar_source && - config->GetKind_TimeIntScheme_Species() == EULER_IMPLICIT) { + if (idx_progvar >= 0 && config->GetKind_TimeIntScheme_Species() == EULER_IMPLICIT) { const int idx_var = flamelet_config_options.idx_progvar_var; const su2double c = scalars[idx_progvar]; su2double c_min, c_max; diff --git a/config_template.cfg b/config_template.cfg index fa5621678c40..64b767d00f39 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1142,10 +1142,6 @@ FLAMELET_VARIANCE_DISSIPATION_COEFF= 2.0 % The variance source column of the manifold is the chemical variance source 2 (mean(phi S) - mean(phi) mean(S)) % (YES) or mean(phi S) (NO). FLAMELET_TABULATED_VARIANCE_SOURCE= NO -% -% Add the derivative of the progress variable source to the Jacobian where the source decreases -% with the progress variable (YES, NO). -FLAMELET_IMPLICIT_PV_SOURCE= NO % Flame ignition temperature % Flame thickness calculations are performed when the maximum temperature in the flow solution exceeds this value. From 17e47b2b9221746180c9dba57df4a59773929fdd Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 23:01:49 +0100 Subject: [PATCH 22/40] Flamelet: preferential diffusion from the excess over unity Lewis numbers The preferential diffusion term was D grad(beta - phi), with beta from the manifold and phi the transported scalar. Outside the manifold beta keeps the value of the nearest table nodes while phi changes, so the term cancels the ordinary diffusion there and a node that leaves the table loses its diffusive coupling. In a lean H2 slit burner such nodes persisted as isolated spots of progress variable far above equilibrium. With PREFERENTIAL_DIFFUSION_EXCESS= YES the manifold columns *_Excess hold beta minus its value at unity Lewis numbers, which is zero without preferential diffusion. The flux is the ordinary diffusion plus D grad(delta), plus delta_T D grad(T) for the enthalpy, so outside the manifold only the ordinary diffusion remains. The block Jacobian uses d(delta)/d(phi) and falls back to the ordinary diffusion where the derivatives cannot be evaluated. Inside the manifold the fluxes equal those of the beta form. Co-Authored-By: Claude Opus 5.5 --- Common/include/option_structure.hpp | 1 + Common/src/CConfig.cpp | 3 +++ .../include/numerics/species/flamelet_edge_flux.hpp | 13 ++++++++----- SU2_CFD/src/fluid/CFluidFlamelet.cpp | 9 +++++---- SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 9 +++++++-- config_template.cfg | 4 ++++ 6 files changed, 28 insertions(+), 11 deletions(-) diff --git a/Common/include/option_structure.hpp b/Common/include/option_structure.hpp index 0393d01ccae4..c68a2022d61a 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1638,6 +1638,7 @@ struct FluidFlamelet_ParsedOptions { su2double* spark_reaction_rates; /*!< \brief Source terms for flamelet spark ignition option. */ unsigned short nspark; /*!< \brief Number of source terms for spark initialization. */ bool preferential_diffusion = false; /*!< \brief Preferential diffusion physics for flamelet solver.*/ + bool preferential_diffusion_excess = false; /*!< \brief The manifold holds the excess of beta over unity Lewis numbers. */ bool thickenedflame_correction{true}; /*!< \brief Thickened flame correction. */ su2double Flame_T_ignition = 5000; /*!< \brief Ignition temperature for the flame, used for initialization. */ diff --git a/Common/src/CConfig.cpp b/Common/src/CConfig.cpp index 2c8390c875b0..b86ace288017 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -2423,6 +2423,9 @@ void CConfig::SetConfig_Options() { /* DESCRIPTION: Enable preferential diffusion for FGM simulations. \n DEFAULT: false */ addBoolOption("PREFERENTIAL_DIFFUSION", flamelet_ParsedOptions.preferential_diffusion, false); + /* DESCRIPTION: Preferential diffusion from the *_Excess manifold columns, beta minus its value at unity Lewis numbers, + * added to the ordinary diffusion. \n DEFAULT: false */ + addBoolOption("PREFERENTIAL_DIFFUSION_EXCESS", flamelet_ParsedOptions.preferential_diffusion_excess, false); /*!\brief CONV_FILENAME \n DESCRIPTION: Output file convergence history (w/o extension) \n DEFAULT: history \ingroup Config*/ addStringOption("CONV_FILENAME", Conv_FileName, string("history")); diff --git a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index 55b9ef747de8..a655fe68354b 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -50,6 +50,7 @@ class CScalarFlux_Flamelet final explicit CScalarFlux_Flamelet(const CConfig& config) : Base(config), preferentialDiffusion(config.GetFlameletParsedOptions().preferential_diffusion), + unityLewisPart(config.GetFlameletParsedOptions().preferential_diffusion_excess ? 0.0 : 1.0), nControlVars(config.GetFlameletParsedOptions().n_control_vars), idxProgVar(config.GetFlameletParsedOptions().idx_progvar), idxEnth(config.GetFlameletParsedOptions().idx_enth) {} @@ -57,7 +58,8 @@ class CScalarFlux_Flamelet final /*! * \brief Preferential diffusion, two terms with the shape of the ordinary diffusion but of * states the model synthesises: div(D grad(beta - phi)) for each controlling variable, - * and a thermal term div(beta_T D grad(T)) on the enthalpy equation. + * and a thermal term div(beta_T D grad(T)) on the enthalpy equation. With the excess + * scalars of the manifold, beta - phi and beta_T are read directly. * \note The Jacobian couples the controlling variables through the derivatives of beta - phi, with * the thermal term folded into the enthalpy row; the solver evaluates them from the manifold. */ @@ -82,17 +84,17 @@ class CScalarFlux_Flamelet final const auto iBeta = betaIndex(iScalar); const Double phi_i = gatherVariables(iPoint, side_i.scalarNodes.GetAuxVar(), iBeta) - - gatherVariables(iPoint, side_i.scalarNodes.GetSolution(), iScalar); + unityLewisPart * gatherVariables(iPoint, side_i.scalarNodes.GetSolution(), iScalar); const Double phi_j = gatherVariables(jPoint, side_j.scalarNodes.GetAuxVar(), iBeta) - - gatherVariables(jPoint, side_j.scalarNodes.GetSolution(), iScalar); + unityLewisPart * gatherVariables(jPoint, side_j.scalarNodes.GetSolution(), iScalar); auto grad_i = gatherVariables(iPoint, side_i.scalarNodes.GetAuxVarGradient(), iBeta); auto grad_j = gatherVariables(jPoint, side_j.scalarNodes.GetAuxVarGradient(), iBeta); const auto gradPhi_i = gatherVariables(iPoint, side_i.scalarNodes.GetGradient(), iScalar); const auto gradPhi_j = gatherVariables(jPoint, side_j.scalarNodes.GetGradient(), iScalar); for (int iDim = 0; iDim < nDim; ++iDim) { - grad_i(iDim) -= gradPhi_i(iDim); - grad_j(iDim) -= gradPhi_j(iDim); + grad_i(iDim) -= unityLewisPart * gradPhi_i(iDim); + grad_j(iDim) -= unityLewisPart * gradPhi_j(iDim); } const Double D_i = gatherVariables(iPoint, side_i.scalarNodes.GetDiffusivity(), iScalar); @@ -140,6 +142,7 @@ class CScalarFlux_Flamelet final private: const bool preferentialDiffusion; + const su2double unityLewisPart; /*!< \brief 1 when beta holds the full scalar, 0 when it holds the excess. */ const unsigned short nControlVars; const int idxProgVar, idxEnth; diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index 5061050c62db..b632adee7ffd 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -221,10 +221,11 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { val_vars_PD.resize(FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS); /*--- Beta scalars of absent controlling variables are not in the manifold. ---*/ - varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_PROGVAR] = (flamelet_options.idx_progvar >= 0) ? "Beta_ProgVar" : "NULL"; - varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH_THERMAL] = "Beta_Enth_Thermal"; - varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH] = "Beta_Enth"; - varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_MIXFRAC] = (flamelet_options.idx_mixfrac >= 0) ? "Beta_MixFrac" : "NULL"; + const string suffix_PD = flamelet_options.preferential_diffusion_excess ? "_Excess" : ""; + varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_PROGVAR] = (flamelet_options.idx_progvar >= 0) ? "Beta_ProgVar" + suffix_PD : "NULL"; + varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH_THERMAL] = "Beta_Enth_Thermal" + suffix_PD; + varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH] = "Beta_Enth" + suffix_PD; + varnames_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_MIXFRAC] = (flamelet_options.idx_mixfrac >= 0) ? "Beta_MixFrac" + suffix_PD : "NULL"; val_vars_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_PROGVAR] = beta_progvar; val_vars_PD[FLAMELET_PREF_DIFF_SCALARS::I_BETA_ENTH_THERMAL] = beta_enth_thermal; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index d6bb5329694c..5030f54363e0 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -834,6 +834,11 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode const su2double temperature = fluid_model_local->GetTemperature(); vector scalars_fd(scalars), beta_plus(beta_scalar.size()), beta_minus(beta_scalar.size()); + /*--- The excess scalars hold beta - phi; without derivatives only the ordinary diffusion is implicit. ---*/ + const bool excess = flamelet_config_options.preferential_diffusion_excess; + const su2double unity_lewis_part = excess ? 0.0 : 1.0; + const su2double fallback_diagonal = excess ? 0.0 : 1.0; + for (auto j_cv = 0u; j_cv < n_cv; j_cv++) { const su2double step = pd_jacobian_step[j_cv]; scalars_fd[j_cv] = scalars[j_cv] + step; @@ -862,13 +867,13 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode const bool usable = (misses == 0) && (inside_plus || inside_minus); for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { - su2double value = (i_cv == j_cv) ? su2double(1.0) : su2double(0.0); + su2double value = (i_cv == j_cv) ? fallback_diagonal : su2double(0.0); if (usable) { const auto i_beta = beta_index(i_cv); su2double d_state = (beta_plus[i_beta] - beta_minus[i_beta]) / span; if (static_cast(i_cv) == idx_enth) d_state += beta_scalar[I_BETA_ENTH_THERMAL] * (temperature_plus - temperature_minus) / span; - value = d_state - ((i_cv == j_cv) ? 1.0 : 0.0); + value = d_state - ((i_cv == j_cv) ? unity_lewis_part : 0.0); /*--- The total diagonal, ordinary diffusion included, is kept positive. ---*/ if (i_cv == j_cv) value = max(value, su2double(-0.9)); } diff --git a/config_template.cfg b/config_template.cfg index 64b767d00f39..85f3ee71a777 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1095,6 +1095,10 @@ FLAME_INIT_METHOD= FLAME_FRONT % respectively are included in the manifold. % By default, this option is disabled. PREFERENTIAL_DIFFUSION= NO +% +% Preferential diffusion from the excess of beta over its value at unity Lewis numbers (the *_Excess +% manifold columns), added to the ordinary diffusion (YES, NO) +PREFERENTIAL_DIFFUSION_EXCESS= NO % FLAME_FRONT initialization % the flame is initialized using a plane, defined by a point and a normal. On one side, the solution is initialized From b2cd7c96a02647fba65aaa8e93b05f1e172a9b2b Mon Sep 17 00:00:00 2001 From: bigfooted Date: Fri, 27 Nov 2026 23:36:05 +0100 Subject: [PATCH 23/40] Move the progress variable source Jacobian into CFluidFlamelet The fluid model now provides dS_PV/dPV through GetProgVarSourceJacobian: analytically from the MLP Jacobian query, and by a forward difference on the PV source column only for the lookup table. The solver no longer perturbs the full source lookup and sets the derivative to zero where the PV source is clipped. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/include/fluid/CFluidFlamelet.hpp | 10 +++++ SU2_CFD/include/fluid/CFluidModel.hpp | 6 +++ SU2_CFD/src/fluid/CFluidFlamelet.cpp | 39 +++++++++++++++++++ .../src/solvers/CSpeciesFlameletSolver.cpp | 10 ++--- TestCases/tutorials.py | 2 +- 5 files changed, 59 insertions(+), 8 deletions(-) diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index 88b2e6603ee6..b11cad6dd036 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -78,6 +78,7 @@ class CFluidFlamelet final : public CFluidModel { MLPToolbox::CIOMap* iomap_PD; /*!< \brief Input-output map for the preferential diffusion scalars. */ MLPToolbox::CIOMap* iomap_Sources; /*!< \brief Input-output map for species source terms. */ MLPToolbox::CIOMap* iomap_LookUp; /*!< \brief Input-output map for passive look-up terms. */ + MLPToolbox::CIOMap* iomap_SourceJacobian; /*!< \brief Input-output map for the progress variable source Jacobian. */ MLPToolbox::CIOMap* iomap_Current; #endif @@ -93,6 +94,8 @@ class CFluidFlamelet final : public CFluidModel { val_vars_LookUp, /*!< \brief References passive look-up terms. */ val_vars_PD; /*!< \brief References to preferential diffusion scalars. */ + su2double source_pv_jac; /*!< \brief Derivative of the progress variable source with respect to the progress variable. */ + void PreprocessLookUp(CConfig* config); /*! \brief @@ -135,6 +138,13 @@ class CFluidFlamelet final : public CFluidModel { unsigned long EvaluateDataSet(const vector& input_scalar, unsigned short lookup_type, vector& output_refs); + /*! + * \brief Derivative of the progress variable source term with respect to the progress variable. + * \note Analytic for the MLP method, forward difference for the lookup table. + * \param[in] input_scalar - controlling variables used to interpolate manifold. + */ + su2double GetProgVarSourceJacobian(const vector& input_scalar) override; + /*! * \brief Check for out-of-bounds condition for data set interpolation. * \return - within bounds (0) or out of bounds (1). diff --git a/SU2_CFD/include/fluid/CFluidModel.hpp b/SU2_CFD/include/fluid/CFluidModel.hpp index af9aa3e059b7..29e8bfb89971 100644 --- a/SU2_CFD/include/fluid/CFluidModel.hpp +++ b/SU2_CFD/include/fluid/CFluidModel.hpp @@ -161,6 +161,12 @@ class CFluidModel { return 0; } + /*! + * \brief Derivative of the progress variable source term with respect to the progress variable. + * \param[in] input_scalar - data manifold query data. + */ + virtual su2double GetProgVarSourceJacobian(const vector& input_scalar) { return 0.0; } + /*! * \brief Get fluid dynamic viscosity. */ diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index f142da539175..7d4b293c7784 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -114,6 +114,7 @@ CFluidFlamelet::~CFluidFlamelet() { delete iomap_TD; delete iomap_Sources; delete iomap_LookUp; + delete iomap_SourceJacobian; delete lookup_mlp; if (preferential_diffusion) delete iomap_PD; } @@ -244,6 +245,11 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { iomap_PD = new MLPToolbox::CIOMap(controlling_variable_names, varnames_PD); lookup_mlp->PairVariableswithMLPs(*iomap_PD); } + iomap_SourceJacobian = + new MLPToolbox::CIOMap(controlling_variable_names, {varnames_Sources[I_PROGVAR]}); + iomap_SourceJacobian->AddQueryJacobian(varnames_Sources[I_PROGVAR], controlling_variable_names[I_PROGVAR], + &source_pv_jac); + lookup_mlp->PairVariableswithMLPs(*iomap_SourceJacobian); #endif } else { for (auto iVar = 0u; iVar < varnames_TD.size(); iVar++) { @@ -342,3 +348,36 @@ unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_sca AD::EndPreacc(); return extrapolation; } + +su2double CFluidFlamelet::GetProgVarSourceJacobian(const vector& input_scalar) { + const su2double val_prog = input_scalar[I_PROGVAR], val_enth = input_scalar[I_ENTH]; + const su2double val_mixfrac = include_mixture_fraction ? input_scalar[I_MIXFRAC] : 0.0; + switch (Kind_DataDriven_Method) { + case ENUM_DATADRIVEN_METHOD::LUT: { + const su2double delta = 1e-6; + const unsigned long idx = LUT_idx_Sources[I_PROGVAR]; + su2double source, source_pert; + if (include_mixture_fraction) { + look_up_table->LookUp_XYZ(idx, &source, val_prog, val_enth, val_mixfrac); + look_up_table->LookUp_XYZ(idx, &source_pert, val_prog + delta, val_enth, val_mixfrac); + } else { + look_up_table->LookUp_XY(idx, &source, val_prog, val_enth); + look_up_table->LookUp_XY(idx, &source_pert, val_prog + delta, val_enth); + } + source_pv_jac = (source_pert - source) / delta; + break; + } + case ENUM_DATADRIVEN_METHOD::MLP: { +#ifdef USE_MLPCPP + su2double source; + vector refs_vars{&source}; + if (!lookup_mlp->Predict(*iomap_SourceJacobian, input_scalar, refs_vars)) source_pv_jac = 0.0; +#endif + break; + } + default: + source_pv_jac = 0.0; + break; + } + return source_pv_jac; +} diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 5a0f0c753577..ba5489ed5c45 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -653,14 +653,10 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF vector source_scalar(flamelet_config_options.n_scalars); for (auto iCV = 0u; iCV < flamelet_config_options.n_control_vars; iCV++) source_scalar[iCV] = table_sources[iCV]; - /*--- Forward difference of the progress variable source, used only by the implicit Jacobian. ---*/ + /*--- Derivative of the progress variable source for the implicit Jacobian, zero where the source is clipped. ---*/ if ((config->GetKind_TimeIntScheme() == EULER_IMPLICIT) && !AD::TapeActive()) { - const su2double delta = 1e-6; - vector scalars_pert = scalars; - scalars_pert[I_PROGVAR] += delta; - vector sources_pert(table_sources.size()); - fluid_model_local->EvaluateDataSet(scalars_pert, FLAMELET_LOOKUP_OPS::SOURCES, sources_pert); - const su2double dsource = (fmax(0, sources_pert[I_PROGVAR]) - table_sources[I_PROGVAR]) / delta; + const su2double dsource = + (table_sources[I_PROGVAR] > 0) ? fluid_model_local->GetProgVarSourceJacobian(scalars) : su2double(0.0); static_cast(nodes)->SetSourceJacobianPV(iPoint, F * dsource); } diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index 763f21e9ebd5..9ced053c8f6d 100644 --- a/TestCases/tutorials.py +++ b/TestCases/tutorials.py @@ -177,7 +177,7 @@ def main(): premixed_hydrogen.cfg_dir = "../Tutorials/incompressible_flow/Inc_Combustion/1__premixed_hydrogen" premixed_hydrogen.cfg_file = "H2_burner.cfg" premixed_hydrogen.test_iter = 10 - premixed_hydrogen.test_vals = [-8.769564, -9.719765, -10.153710, -3.439336, -11.528098] + premixed_hydrogen.test_vals = [-8.769561, -9.719764, -10.153709, -3.439324, -11.528261] test_list.append(premixed_hydrogen) ### Compressible Flow From f09b17439d78a00bb101d6d29ee94622febeb94b Mon Sep 17 00:00:00 2001 From: bigfooted Date: Fri, 27 Nov 2026 23:51:45 +0100 Subject: [PATCH 24/40] Build the periodic coupling table once SetPeriodicMaster runs on the first call of CouplePeriodicJacobian, when the sparsity pattern of the Jacobian is fixed, and also stores the list of coupled points and the rotation matrix of each periodic marker. Cases with no coupled points return before the OpenMP safe-access region. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/include/solvers/CSolver.hpp | 4 ++- SU2_CFD/src/solvers/CSolver.cpp | 56 ++++++++++++++++------------- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/SU2_CFD/include/solvers/CSolver.hpp b/SU2_CFD/include/solvers/CSolver.hpp index 76c3c4b6695e..c9331916dbd3 100644 --- a/SU2_CFD/include/solvers/CSolver.hpp +++ b/SU2_CFD/include/solvers/CSolver.hpp @@ -151,6 +151,8 @@ class CSolver { std::unordered_map PeriodicProjIndex; /*!< \brief Local point to compact projection row. */ vector PeriodicMaster; /*!< \brief Local master point of each coupled passive periodic point, or -1. */ vector PeriodicMasterMarker; /*!< \brief Periodic marker of each passive point, gives its rotation. */ + vector PeriodicPassive; /*!< \brief Coupled passive periodic points. */ + vector PeriodicRotation; /*!< \brief Rotation of each periodic marker to its match, empty if none. */ bool dynamic_grid; /*!< \brief Flag that determines whether the grid is dynamic (moving or deforming + grid velocities). */ @@ -336,7 +338,7 @@ class CSolver { void CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config); /*! - * \brief Map each coupled passive periodic point to its master on the same rank. + * \brief Map each coupled passive periodic point to its master on the same rank, and set the marker rotations. */ void SetPeriodicMaster(CGeometry *geometry, const CConfig *config); diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 9c85dfcf99f5..0ee0fe214f96 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -4682,34 +4682,43 @@ void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { } if (!fits) PeriodicMaster[iPoint] = -1; } -} - -void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) { - SU2_ZONE_SCOPED - if (!implicit_periodic || config->GetnMarker_Periodic() == 0) return; - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { - - if (PeriodicMaster.size() != nPoint) SetPeriodicMaster(geometry, config); + PeriodicPassive.clear(); + for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) + if (PeriodicMaster[iPoint] >= 0) PeriodicPassive.push_back(iPoint); - /*--- Rotation from the frame of each periodic marker to the frame of its match, null if none. ---*/ - using RotationMatrix = std::array, 3>; - const auto nMarker = config->GetnMarker_All(); - vector rotations(nMarker); - vector markerRotation(nMarker, nullptr); - for (auto iMarker = 0u; iMarker < nMarker && rotate_periodic; iMarker++) { + /*--- Rotation from the frame of each periodic marker to the frame of its match, empty if none. ---*/ + PeriodicRotation.assign(config->GetnMarker_All(), su2passivematrix()); + for (auto iMarker = 0u; iMarker < config->GetnMarker_All() && rotate_periodic; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) continue; const auto* angles = config->GetPeriodicRotAngles(config->GetMarker_All_TagBound(iMarker)); if (!GeometryToolbox::HasRotation(angles)) continue; + auto& rotation = PeriodicRotation[iMarker]; + rotation.resize(3, 3) = passivedouble(0.0); const auto theta = SU2_TYPE::GetValue(angles[0]); const auto phi = SU2_TYPE::GetValue(angles[1]); const auto psi = SU2_TYPE::GetValue(angles[2]); - if (nDim == 2) GeometryToolbox::RotationMatrix(psi, rotations[iMarker]); - else GeometryToolbox::RotationMatrix(theta, phi, psi, rotations[iMarker]); - markerRotation[iMarker] = &rotations[iMarker]; + if (nDim == 2) GeometryToolbox::RotationMatrix(psi, rotation); + else GeometryToolbox::RotationMatrix(theta, phi, psi, rotation); } - auto Rotation = [&](unsigned long iPoint) -> const RotationMatrix* { - return PeriodicMaster[iPoint] >= 0 ? markerRotation[PeriodicMasterMarker[iPoint]] : nullptr; +} + +void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) { + SU2_ZONE_SCOPED + if (!implicit_periodic || config->GetnMarker_Periodic() == 0) return; + + /*--- The table is built on the first call, the sparsity pattern of the Jacobian is fixed by then. ---*/ + const bool built = PeriodicMaster.size() == nPoint; + if (built && PeriodicPassive.empty()) return; + + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + + if (!built) SetPeriodicMaster(geometry, config); + + auto Rotation = [&](unsigned long iPoint) -> const su2passivematrix* { + if (PeriodicMaster[iPoint] < 0) return nullptr; + const auto& rotation = PeriodicRotation[PeriodicMasterMarker[iPoint]]; + return rotation.size() ? &rotation : nullptr; }; su2passivematrix block(nVar, nVar), zero(nVar, nVar); @@ -4721,9 +4730,9 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) }; /*--- Rows of passive points go to the rows of their masters. ---*/ - for (auto iPoint = 0ul; iPoint < nPointDomain; iPoint++) { + for (const auto iPoint : PeriodicPassive) { + if (iPoint >= nPointDomain) continue; const auto master = PeriodicMaster[iPoint]; - if (master < 0) continue; for (const auto kPoint : geometry->nodes->GetPoints(iPoint)) { const unsigned long col = PeriodicMaster[kPoint] >= 0 ? PeriodicMaster[kPoint] : kPoint; if (!Jacobian.GetBlockView(master, col)) continue; @@ -4734,14 +4743,13 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) } /*--- Columns of passive points go to the columns of their masters. ---*/ - for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { + for (const auto iPoint : PeriodicPassive) { const auto master = PeriodicMaster[iPoint]; - if (master < 0) continue; for (const auto jPoint : geometry->nodes->GetPoints(iPoint)) { if (jPoint >= nPointDomain || PeriodicMaster[jPoint] >= 0) continue; if (!Jacobian.GetBlockView(jPoint, master)) continue; ReadBlock(jPoint, iPoint); - PeriodicCommHelpers::RotateMomentumBlock(nullptr, Rotation(iPoint), nDim, nVar, block); + PeriodicCommHelpers::RotateMomentumBlock(nullptr, Rotation(iPoint), nDim, nVar, block); Jacobian.AddBlock(jPoint, master, block); Jacobian.SetBlock(jPoint, iPoint, zero); } From 86f9c48eba1acd12067490d37e5ba0d945349c28 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Fri, 27 Nov 2026 23:51:59 +0100 Subject: [PATCH 25/40] Record the periodic volume when recording the mesh coordinates The periodic part of each dual volume was communicated once, in CommunicateInitialState, so in the discrete adjoint it did not depend on the mesh coordinates and the geometric sensitivities missed its derivative. CSolver::CommunicatePeriodicVolume resets and accumulates the periodic volume; the adjoint fluid iteration calls it after UpdateGeometry. On the Morse swirling jet (one-cell wedge, every point periodic) the adjoint derivative of the inlet static pressure with respect to a smooth mesh deformation changes from +22.6 to -2.02; central finite differences give -2.137. The primal is unchanged. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/include/solvers/CFVMFlowSolverBase.inl | 3 +-- SU2_CFD/include/solvers/CSolver.hpp | 6 ++++++ SU2_CFD/src/iteration/CDiscAdjFluidIteration.cpp | 2 ++ SU2_CFD/src/solvers/CSolver.cpp | 8 ++++++++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl b/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl index 54978dde434b..ae89a8135a03 100644 --- a/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl +++ b/SU2_CFD/include/solvers/CFVMFlowSolverBase.inl @@ -254,9 +254,8 @@ void CFVMFlowSolverBase::CommunicateInitialState(CGeometry* geometry, cons /*--- Communicate and store volume and the number of neighbors for any dual CVs that lie on on periodic markers. ---*/ + CommunicatePeriodicVolume(geometry, config); for (unsigned short iPeriodic = 1; iPeriodic <= config->GetnMarker_Periodic() / 2; iPeriodic++) { - InitiatePeriodicComms(geometry, config, iPeriodic, PERIODIC_VOLUME); - CompletePeriodicComms(geometry, config, iPeriodic, PERIODIC_VOLUME); InitiatePeriodicComms(geometry, config, iPeriodic, PERIODIC_NEIGHBORS); CompletePeriodicComms(geometry, config, iPeriodic, PERIODIC_NEIGHBORS); } diff --git a/SU2_CFD/include/solvers/CSolver.hpp b/SU2_CFD/include/solvers/CSolver.hpp index c9331916dbd3..9dd3c7be50c3 100644 --- a/SU2_CFD/include/solvers/CSolver.hpp +++ b/SU2_CFD/include/solvers/CSolver.hpp @@ -330,6 +330,12 @@ class CSolver { unsigned short val_periodic_index, unsigned short commType); + /*! + * \brief Set the periodic volume of each periodic point, the volume of its matches on the other periodic faces. + * \note Called again when the mesh coordinates are recorded, so the periodic volume depends on them. + */ + void CommunicatePeriodicVolume(CGeometry *geometry, const CConfig *config); + /*! * \brief Move the off-diagonal Jacobian blocks of passive periodic points to their masters, rotated. * \note Call before the PERIODIC_RESIDUAL comms. A passive point is coupled if its master is on the same rank and diff --git a/SU2_CFD/src/iteration/CDiscAdjFluidIteration.cpp b/SU2_CFD/src/iteration/CDiscAdjFluidIteration.cpp index 7c33451e6095..5fe40729f533 100644 --- a/SU2_CFD/src/iteration/CDiscAdjFluidIteration.cpp +++ b/SU2_CFD/src/iteration/CDiscAdjFluidIteration.cpp @@ -478,6 +478,8 @@ void CDiscAdjFluidIteration::SetDependencies(CSolver***** solver, CGeometry**** CGeometry::UpdateGeometry(geometry[iZone][iInst], config[iZone]); END_SU2_OMP_PARALLEL + solvers0[FLOW_SOL]->CommunicatePeriodicVolume(geometry0, config[iZone]); + CGeometry::ComputeWallDistance(config, geometry, iZone); } diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 0ee0fe214f96..0e68fce3927e 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -4633,6 +4633,14 @@ void CSolver::SavelibROM(CGeometry *geometry, CConfig *config, bool converged) { } +void CSolver::CommunicatePeriodicVolume(CGeometry *geometry, const CConfig *config) { + for (auto iPoint = 0ul; iPoint < geometry->GetnPoint(); iPoint++) geometry->nodes->SetPeriodicVolume(iPoint, 0.0); + for (unsigned short iPeriodic = 1; iPeriodic <= config->GetnMarker_Periodic() / 2; iPeriodic++) { + InitiatePeriodicComms(geometry, config, iPeriodic, PERIODIC_VOLUME); + CompletePeriodicComms(geometry, config, iPeriodic, PERIODIC_VOLUME); + } +} + void CSolver::SetPeriodicMaster(CGeometry *geometry, const CConfig *config) { const auto nPeriodic = config->GetnMarker_Periodic(); From cf9ced6158a7980384c7670809a987d866ade3f0 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 28 Nov 2026 09:32:38 +0100 Subject: [PATCH 26/40] Add a discrete-adjoint regression test for the Morse swirling jet discadj_incomp_turb_morse_swirl_jet runs 10 adjoint iterations of the one-cell periodic wedge from the converged primal solution, with the inlet static pressure as objective. Every point of the wedge is periodic, so the test covers the coupled Jacobian in the adjoint linear solve. Co-Authored-By: Claude Opus 5.5 --- .../morse_swirl_jet/morse_sa_adjoint.cfg | 103 ++++++++++++++++++ TestCases/parallel_regression_AD.py | 8 ++ 2 files changed, 111 insertions(+) create mode 100644 TestCases/incomp_rans/morse_swirl_jet/morse_sa_adjoint.cfg diff --git a/TestCases/incomp_rans/morse_swirl_jet/morse_sa_adjoint.cfg b/TestCases/incomp_rans/morse_swirl_jet/morse_sa_adjoint.cfg new file mode 100644 index 000000000000..58174f661dc1 --- /dev/null +++ b/TestCases/incomp_rans/morse_swirl_jet/morse_sa_adjoint.cfg @@ -0,0 +1,103 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% SU2 configuration file % +% Case description: Swirling jet in still air, S = 0.36, Re = 56,000 % +% (Morse 1980, ERCOFTAC Classic case 026), SA, 5 deg wedge % +% Author: Nijso Beishuizen % +% Institution: Bosch Thermotechnology % +% Date: Nov 15th, 2026 % +% File Version 8.6.0 "Harrier" % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% ------------- DIRECT, ADJOINT, AND LINEARIZED PROBLEM DEFINITION ------------% +% +SOLVER= INC_RANS +KIND_TURB_MODEL= SA +MATH_PROBLEM= DISCRETE_ADJOINT +RESTART_SOL= NO + +% ---------------- INCOMPRESSIBLE FLOW CONDITION DEFINITION -------------------% +% +% Air; the far field carries a co-flow of 1% of the jet exit velocity (34.46 m/s). +FLUID_MODEL= CONSTANT_DENSITY +INC_DENSITY_INIT= 1.2 +INC_VELOCITY_INIT= ( 0.345, 0.0, 0.0 ) +INC_NONDIM= DIMENSIONAL + +% --------------------------- VISCOSITY MODEL ---------------------------------% +% +% Re = U_exit D / nu = 56,000 with D = 0.0246 m. +VISCOSITY_MODEL= CONSTANT_VISCOSITY +MU_CONSTANT= 1.82e-05 +FREESTREAM_NU_FACTOR= 3.0 + +% -------------------- BOUNDARY CONDITION DEFINITION --------------------------% +% +% The jet enters at x/D = 0.5 with the profiles measured there (inlet_jet.dat). The far field supplies the +% entrained air through the inlet plane; at r = 30 D it suffices up to x/D = 100. +INC_INLET_TYPE= VELOCITY_INLET +MARKER_INLET= ( inlet_jet, 288.15, 34.10, 1.0, 0.0, 0.0 ) +SPECIFIED_INLET_PROFILE= YES +INLET_FILENAME= inlet_jet.dat +% The outlet is a far field too: a pressure outlet lets a reversed flow enter along the axis. +MARKER_FAR= ( farfield, outlet ) +MARKER_EULER= ( axis ) +MARKER_PERIODIC= ( periodic_1, periodic_2, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0 ) +MARKER_PLOTTING= ( axis ) +MARKER_MONITORING= ( axis ) +OBJECTIVE_FUNCTION= SURFACE_STATIC_PRESSURE +MARKER_ANALYZE= ( inlet_jet ) +MARKER_ANALYZE_AVERAGE= AREA + +% ------------- COMMON PARAMETERS DEFINING THE NUMERICAL METHOD ---------------% +% +NUM_METHOD_GRAD= GREEN_GAUSS +NUM_METHOD_GRAD_RECON= LEAST_SQUARES +CFL_NUMBER= 500 +CFL_ADAPT= NO +CFL_ADAPT_PARAM= ( 0.5, 1.1, 25, 2500, 0.001 ) +ITER= 10 + +% ------------------------ LINEAR SOLVER DEFINITION ---------------------------% +% +LINEAR_SOLVER= FGMRES +LINEAR_SOLVER_PREC= ILU +LINEAR_SOLVER_ERROR= 1E-4 +LINEAR_SOLVER_ITER= 50 + +% -------------------- FLOW NUMERICAL METHOD DEFINITION -----------------------% +% +CONV_NUM_METHOD_FLOW= FDS +MUSCL_FLOW= YES +SLOPE_LIMITER_FLOW= VENKATAKRISHNAN +VENKAT_LIMITER_COEFF= 0.05 +TIME_DISCRE_FLOW= EULER_IMPLICIT + +% -------------------- TURBULENT NUMERICAL METHOD DEFINITION ------------------% +% +CONV_NUM_METHOD_TURB= SCALAR_UPWIND +MUSCL_TURB= NO +TIME_DISCRE_TURB= EULER_IMPLICIT + +% --------------------------- CONVERGENCE PARAMETERS --------------------------% +% +CONV_FIELD= ADJOINT_PRESSURE +CONV_RESIDUAL_MINVAL= -10 +CONV_STARTITER= 10 + +% ------------------------- INPUT/OUTPUT INFORMATION --------------------------% +% +MESH_FILENAME= morse_wedge.su2 +MESH_FORMAT= SU2 +SOLUTION_FILENAME= solution_flow +RESTART_FILENAME= restart_flow +RESTART_ADJ_FILENAME= restart_adj +CONV_FILENAME= history +VOLUME_FILENAME= flow +SCREEN_OUTPUT= INNER_ITER, RMS_ADJ_PRESSURE, RMS_ADJ_VELOCITY-X, RMS_ADJ_NU_TILDE +HISTORY_OUTPUT= ITER, RMS_RES +VOLUME_OUTPUT= COORDINATES, SOLUTION, PRIMITIVE, RESIDUAL +OUTPUT_FILES= RESTART +WRT_RESTART_COMPACT= NO +OUTPUT_WRT_FREQ= 100 diff --git a/TestCases/parallel_regression_AD.py b/TestCases/parallel_regression_AD.py index ca3cfea19d98..659b3c8a452d 100644 --- a/TestCases/parallel_regression_AD.py +++ b/TestCases/parallel_regression_AD.py @@ -141,6 +141,14 @@ def main(): discadj_incomp_turb_NACA0012_sst.test_vals_aarch64 = [-4.294502, -3.069650, -7.086569, 0.000000, -1.151213] test_list.append(discadj_incomp_turb_NACA0012_sst) + # Adjoint Incompressible Turbulent Morse swirling jet, SA, one-cell periodic wedge + discadj_incomp_turb_morse_swirl_jet = TestCase('discadj_incomp_turb_morse_swirl_jet') + discadj_incomp_turb_morse_swirl_jet.cfg_dir = "incomp_rans/morse_swirl_jet" + discadj_incomp_turb_morse_swirl_jet.cfg_file = "morse_sa_adjoint.cfg" + discadj_incomp_turb_morse_swirl_jet.test_iter = 10 + discadj_incomp_turb_morse_swirl_jet.test_vals = [10.000000, -5.548784, -3.649149, -1.128684] + test_list.append(discadj_incomp_turb_morse_swirl_jet) + #################################################################### ### Disc. Adj. Axisymmetric RANS ### #################################################################### From 30ce5656d76b8ae6410088cfd16ced4fdb28a39d Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 28 Nov 2026 09:36:03 +0100 Subject: [PATCH 27/40] Flamelet: move the progress variable source Jacobian into CFluidFlamelet GetProgVarSourceJacobian gives dS_PV/dPV at constant normalized variance. The MLP method uses the network Jacobian, with the product rule for a reduced source; the lookup table keeps the central difference inside the progress variable range. The solver only stores the result. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/include/fluid/CFluidFlamelet.hpp | 9 +++ SU2_CFD/include/fluid/CFluidModel.hpp | 6 ++ SU2_CFD/src/fluid/CFluidFlamelet.cpp | 58 +++++++++++++++++++ .../src/solvers/CSpeciesFlameletSolver.cpp | 31 +--------- 4 files changed, 76 insertions(+), 28 deletions(-) diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index 24cf13fef152..ebe0bf464d3c 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -84,6 +84,7 @@ class CFluidFlamelet final : public CFluidModel { MLPToolbox::CIOMap* iomap_Sources; /*!< \brief Input-output map for species source terms. */ MLPToolbox::CIOMap* iomap_LookUp; /*!< \brief Input-output map for passive look-up terms. */ MLPToolbox::CIOMap* iomap_ProgVarBounds; /*!< \brief Input-output map for the progress variable range. */ + MLPToolbox::CIOMap* iomap_SourceJacobian; /*!< \brief Input-output map for the progress variable source Jacobian. */ #endif vector scalars_vector; @@ -127,6 +128,8 @@ class CFluidFlamelet final : public CFluidModel { vector reduced_sources; /*!< \brief Whether a source is given divided by c*(1-c*). */ + su2double source_pv_jac; /*!< \brief Network derivative of the progress variable source to the progress variable. */ + /*! \brief * Returns true if the string is null or zero (ignores case). */ @@ -181,6 +184,12 @@ class CFluidFlamelet final : public CFluidModel { */ bool GetProgressVariableBounds(const su2double* scalars, su2double& c_min, su2double& c_max) override; + /*! + * \brief Derivative of the progress variable source at constant normalized variance, zero where it is clipped. + * \note Analytic for the MLP method, a central difference inside the progress variable range for the table. + */ + su2double GetProgVarSourceJacobian(const vector& scalars) override; + /*! * \brief Check for out-of-bounds condition for data set interpolation. * \return - within bounds (0) or out of bounds (1). diff --git a/SU2_CFD/include/fluid/CFluidModel.hpp b/SU2_CFD/include/fluid/CFluidModel.hpp index f04e88c388a2..b0f97c8b5947 100644 --- a/SU2_CFD/include/fluid/CFluidModel.hpp +++ b/SU2_CFD/include/fluid/CFluidModel.hpp @@ -177,6 +177,12 @@ class CFluidModel { return false; } + /*! + * \brief Derivative of the progress variable source term with respect to the progress variable. + * \param[in] scalars - Transported scalars. + */ + virtual su2double GetProgVarSourceJacobian(const vector& scalars) { return 0.0; } + /*! * \brief Get fluid dynamic viscosity. */ diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index b632adee7ffd..ea800a76d0fa 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -120,6 +120,7 @@ CFluidFlamelet::~CFluidFlamelet() { delete lookup_mlp; if (preferential_diffusion) delete iomap_PD; if (flamelet_options.idx_progvar_var >= 0) delete iomap_ProgVarBounds; + if (flamelet_options.idx_progvar >= 0) delete iomap_SourceJacobian; } #endif } @@ -273,6 +274,12 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { iomap_ProgVarBounds = new MLPToolbox::CIOMap(controlling_variable_names, varnames_ProgVarBounds); lookup_mlp->PairVariableswithMLPs(*iomap_ProgVarBounds); } + const int i_c = flamelet_options.idx_progvar; + if (i_c >= 0) { + iomap_SourceJacobian = new MLPToolbox::CIOMap(controlling_variable_names, {varnames_Sources[i_c]}); + iomap_SourceJacobian->AddQueryJacobian(varnames_Sources[i_c], controlling_variable_names[i_c], &source_pv_jac); + lookup_mlp->PairVariableswithMLPs(*iomap_SourceJacobian); + } #endif } else { for (auto iVar = 0u; iVar < varnames_TD.size(); iVar++) { @@ -329,6 +336,57 @@ bool CFluidFlamelet::GetProgressVariableBounds(const su2double* scalars, su2doub return true; } +su2double CFluidFlamelet::GetProgVarSourceJacobian(const vector& scalars) { + const int i_c = flamelet_options.idx_progvar; + if (i_c < 0) return 0.0; + + if (Kind_DataDriven_Method == ENUM_DATADRIVEN_METHOD::MLP) { + su2double jacobian{0}; +#ifdef USE_MLPCPP + SetManifoldInputs(scalars.data()); + su2double source{0}; + vector refs_vars{&source}; + if (!lookup_mlp->Predict(*iomap_SourceJacobian, manifold_inputs, refs_vars)) return 0.0; + jacobian = source_pv_jac; + if (reduced_sources[i_c]) { + /*--- Product rule with the reduction factor c*(1-c*). ---*/ + const su2double c_min = val_vars_ProgVarBounds[0], c_range = val_vars_ProgVarBounds[1] - c_min; + if (c_range <= 0) return 0.0; + const su2double c_star = (scalars[i_c] - c_min) / c_range; + if (c_star <= 0 || c_star >= 1) return 0.0; + jacobian = c_star * (1.0 - c_star) * source_pv_jac + source * (1.0 - 2.0 * c_star) / c_range; + } + if (source <= 0) return 0.0; +#endif + return jacobian; + } + + const int idx_var = flamelet_options.idx_progvar_var; + const su2double c = scalars[i_c]; + su2double c_min, c_max; + su2double c_lo = c - 1e-3, c_hi = c + 1e-3, s_var = 0.0; + const bool bounded = GetProgressVariableBounds(scalars.data(), c_min, c_max) && (c_max > c_min); + if (bounded) { + /*--- Both points lie strictly inside the range, at the normalized variance of the node. ---*/ + const su2double delta = 1e-3 * (c_max - c_min); + const su2double lower = c_min + 1e-2 * delta, upper = c_max - 1e-2 * delta; + const su2double c_in = fmin(fmax(c, lower), upper); + c_lo = fmax(c_in - delta, lower); + c_hi = fmin(c_in + delta, upper); + const su2double room = (c - c_min) * (c_max - c); + if (idx_var >= 0 && room > 0) s_var = fmin(fmax(scalars[idx_var] / room, su2double(0.0)), su2double(1.0)); + } + vector shifted(scalars), sources_shifted(varnames_Sources.size()); + su2double source_pm[2]; + for (int side = 0; side < 2; side++) { + shifted[i_c] = (side == 0) ? c_hi : c_lo; + if (bounded && idx_var >= 0) shifted[idx_var] = s_var * (shifted[i_c] - c_min) * (c_max - shifted[i_c]); + EvaluateDataSet(shifted, FLAMELET_LOOKUP_OPS::SOURCES, sources_shifted); + source_pm[side] = fmax(0, sources_shifted[i_c]); + } + return (source_pm[0] - source_pm[1]) / (c_hi - c_lo); +} + bool CFluidFlamelet::SetManifoldInputs(const su2double* scalars) { for (auto iCV = 0u; iCV < n_control_vars; iCV++) manifold_inputs[iCV] = scalars[iCV]; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 5030f54363e0..065f807b8e90 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -735,34 +735,9 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF /*--- The source term for progress variable is always positive, we clip from below to make sure. --- */ if (idx_progvar >= 0) table_sources[idx_progvar] = fmax(0, table_sources[idx_progvar]); - /*--- Difference of the progress variable source within the table range, for its implicit treatment. ---*/ - if (idx_progvar >= 0 && config->GetKind_TimeIntScheme_Species() == EULER_IMPLICIT) { - const int idx_var = flamelet_config_options.idx_progvar_var; - const su2double c = scalars[idx_progvar]; - su2double c_min, c_max; - su2double c_lo = c - 1e-3, c_hi = c + 1e-3, s_var = 0.0; - const bool bounded = fluid_model_local->GetProgressVariableBounds(scalars.data(), c_min, c_max) && (c_max > c_min); - if (bounded) { - /*--- Both points lie strictly inside the range, at the normalized variance of the node. ---*/ - const su2double delta = 1e-3 * (c_max - c_min); - const su2double lower = c_min + 1e-2 * delta, upper = c_max - 1e-2 * delta; - const su2double c_in = fmin(fmax(c, lower), upper); - c_lo = fmax(c_in - delta, lower); - c_hi = fmin(c_in + delta, upper); - const su2double room = (c - c_min) * (c_max - c); - if (idx_var >= 0 && room > 0) s_var = fmin(fmax(scalars[idx_var] / room, su2double(0.0)), su2double(1.0)); - } - vector shifted(scalars), sources_shifted(table_sources.size()); - su2double source_pm[2]; - for (int side = 0; side < 2; side++) { - shifted[idx_progvar] = (side == 0) ? c_hi : c_lo; - if (bounded && idx_var >= 0) - shifted[idx_var] = s_var * (shifted[idx_progvar] - c_min) * (c_max - shifted[idx_progvar]); - fluid_model_local->EvaluateDataSet(shifted, FLAMELET_LOOKUP_OPS::SOURCES, sources_shifted); - source_pm[side] = fmax(0, sources_shifted[idx_progvar]); - } - progvar_source_slope[iPoint] = F * (source_pm[0] - source_pm[1]) / (c_hi - c_lo); - } + /*--- Derivative of the progress variable source, for its implicit treatment. ---*/ + if (idx_progvar >= 0 && config->GetKind_TimeIntScheme_Species() == EULER_IMPLICIT) + progvar_source_slope[iPoint] = F * fluid_model_local->GetProgVarSourceJacobian(scalars); /*--- Variance source 2 (mean(phi S) - mean(phi) mean(S)), from mean(phi S) unless the manifold holds it. ---*/ if (!flamelet_config_options.tabulated_variance_source) From 41173a6e5d2d3266bb742f96f106be8bb099140e Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 28 Nov 2026 13:30:51 +0100 Subject: [PATCH 28/40] Flamelet: stop the burnt progress variable march at the table maximum SetManifoldInputs clamps the progress variable to the table edge, so the lookup never reports extrapolation above the table maximum. When the unburnt state can not reach the ignition temperature (e.g. cooled burnt gas as free stream), GetBurntProgressVariable then marched forever and the flame front initialization hung. The march now also treats a progress variable above the table maximum as outside the manifold. Co-Authored-By: Claude Sonnet 5.5 --- SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 065f807b8e90..cfeed58de391 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -942,7 +942,10 @@ su2double CSpeciesFlameletSolver::GetBurntProgressVariable(CFluidModel* fluid_mo auto inside = [&](su2double pv) { scalars[idx_flame_front] = pv; fluid_model->SetTDState_T(300.0, scalars); - return fluid_model->GetExtrapolation() == 0; + if (fluid_model->GetExtrapolation() != 0) return false; + /*--- The lookup clamps the progress variable to the table edge, so the upper bound is checked explicitly. ---*/ + su2double c_min, c_max; + return !fluid_model->GetProgressVariableBounds(scalars, c_min, c_max) || pv <= c_max; }; /*--- March up while the state stays inside the manifold, until the ignition temperature is exceeded. ---*/ From 51bdfbf1e1335df1db8e909b8d2474025b53ff87 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 28 Nov 2026 17:46:47 +0100 Subject: [PATCH 29/40] Show the residual on passive periodic points The passive face of an implicit periodic pair had its residual zeroed, so the volume output showed residuals on only one of the two planes. PERIODIC_IMPLICIT now also sends the master's (rotated) residual to the passive point. The solution and convergence history are unchanged. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/src/solvers/CSolver.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index d36d3f1acaf6..762959f5847f 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -215,7 +215,7 @@ void CSolver::GetPeriodicCommCountAndType(const CConfig* config, MPI_TYPE = COMM_TYPE::DOUBLE; break; case PERIODIC_IMPLICIT: - COUNT_PER_POINT = nVar; + COUNT_PER_POINT = 2*nVar; MPI_TYPE = COMM_TYPE::DOUBLE; break; case PERIODIC_LAPLACIAN: @@ -693,12 +693,14 @@ void CSolver::InitiatePeriodicComms(CGeometry *geometry, for (iVar = 0; iVar < nVar; iVar++) { bufDSend[buf_offset+iVar] = base_nodes->GetSolution(iPoint, iVar); + bufDSend[buf_offset+nVar+iVar] = LinSysRes(iPoint, iVar); } - /*--- Rotate the momentum components of the solution array. ---*/ + /*--- Rotate the momentum components of the solution and of the residual. ---*/ if (rotate_periodic) { Rotate(zeros, &base_nodes->GetSolution(iPoint)[1], &bufDSend[buf_offset+1]); + Rotate(zeros, &LinSysRes(iPoint, 1), &bufDSend[buf_offset+nVar+1]); } break; @@ -1329,6 +1331,13 @@ void CSolver::CompletePeriodicComms(CGeometry *geometry, buf_offset++; } + /*--- The passive point shows the residual of the combined control volume of its master. ---*/ + + for (iVar = 0; iVar < nVar; iVar++) { + LinSysRes(iPoint, iVar) = bufDRecv[buf_offset]; + buf_offset++; + } + } break; From ac6529dc0f816057796d5d33b688e9881adf56c4 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 09:19:15 +0100 Subject: [PATCH 30/40] Fix forward-mode AD build of quantized block accumulation The accumulate lambda returned a CoDi expression in forward mode, which PassiveValue does not unwrap, so static_cast failed. Return T. Co-Authored-By: Claude Opus 5.5 --- Common/include/linear_algebra/CSysMatrix.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Common/include/linear_algebra/CSysMatrix.hpp b/Common/include/linear_algebra/CSysMatrix.hpp index 07827f6106d4..dfc32dc93a26 100644 --- a/Common/include/linear_algebra/CSysMatrix.hpp +++ b/Common/include/linear_algebra/CSysMatrix.hpp @@ -248,7 +248,7 @@ struct CBlockView { for (auto r = 0ul; r < nVar; ++r) { /*--- The old scale is kept because EncodeQuantRow overwrites qs[r] before re-reading the row. ---*/ const auto scale = DecodeQuantScale(qs[r]); - const auto sum = [&](unsigned long i, unsigned long j) { + const auto sum = [&](unsigned long i, unsigned long j) -> T { return static_cast(qv[i * nVar + j] * scale) + f(i, j); }; EncodeQuantRow(sum, qs[r], qv + r * nVar, nVar, r); From 3866f4e005094702b23cceec4d9a6128cc2ccc64 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 12:51:02 +0100 Subject: [PATCH 31/40] Fix forward-mode AD build of the periodic Jacobian coupling The Jacobian is active in forward AD, so the moved blocks use its scalar type there and stay passive otherwise. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/src/solvers/CSolver.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 32927b54abe5..278e737ff339 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -4922,8 +4922,10 @@ void CSolver::CouplePeriodicJacobian(CGeometry *geometry, const CConfig *config) return rotation.size() ? &rotation : nullptr; }; - su2passivematrix block(nVar, nVar), zero(nVar, nVar); - zero = passivedouble(0.0); + /*--- Blocks are passive, except in forward AD where the Jacobian itself is active. ---*/ + using BlockScalar = std::conditional_t::value, su2double, passivedouble>; + su2matrix block(nVar, nVar), zero(nVar, nVar); + zero = BlockScalar(0.0); auto ReadBlock = [&](unsigned long iRow, unsigned long iCol) { const auto view = Jacobian.GetBlockView(iRow, iCol); for (auto iVar = 0u; iVar < nVar; iVar++) From 0a03542781e3f321a3ca71c5389d20dd062e32d0 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 14:45:40 +0100 Subject: [PATCH 32/40] Update regression values after merging develop periodic3d_axis (new in develop) couples its one-cell wedge points; the Morse primal and adjoint values follow the develop changes; transonic_stator returns to the develop values. Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression.py | 4 ++-- TestCases/parallel_regression_AD.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index e758ebd76bee..e2f767f8831a 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -507,7 +507,7 @@ def main(): periodic3d_axis.cfg_dir = "navierstokes/periodic3D_axis" periodic3d_axis.cfg_file = "config.cfg" periodic3d_axis.test_iter = 100 - periodic3d_axis.test_vals = [-3.353165, 0.157501, 2.051458, -9.594400, -9.594400] + periodic3d_axis.test_vals = [-3.271569, -0.284345, 2.163829, -7.848400, -7.848400] test_list.append(periodic3d_axis) ########################## @@ -962,7 +962,7 @@ def main(): inc_turb_morse_swirl_jet.cfg_dir = "incomp_rans/morse_swirl_jet" inc_turb_morse_swirl_jet.cfg_file = "morse_sa.cfg" inc_turb_morse_swirl_jet.test_iter = 10 - inc_turb_morse_swirl_jet.test_vals = [-10.569835, -8.376495, -9.323474, 12.000000, -4.059383, 71.328000] + inc_turb_morse_swirl_jet.test_vals = [-10.569500, -8.370534, -9.323232, 12.000000, -4.041427, 71.328000] test_list.append(inc_turb_morse_swirl_jet) # NACA0012, SST_SUST diff --git a/TestCases/parallel_regression_AD.py b/TestCases/parallel_regression_AD.py index 659b3c8a452d..19288e429169 100644 --- a/TestCases/parallel_regression_AD.py +++ b/TestCases/parallel_regression_AD.py @@ -146,7 +146,7 @@ def main(): discadj_incomp_turb_morse_swirl_jet.cfg_dir = "incomp_rans/morse_swirl_jet" discadj_incomp_turb_morse_swirl_jet.cfg_file = "morse_sa_adjoint.cfg" discadj_incomp_turb_morse_swirl_jet.test_iter = 10 - discadj_incomp_turb_morse_swirl_jet.test_vals = [10.000000, -5.548784, -3.649149, -1.128684] + discadj_incomp_turb_morse_swirl_jet.test_vals = [10.000000, -5.548813, -3.649165, -1.128723] test_list.append(discadj_incomp_turb_morse_swirl_jet) #################################################################### @@ -259,7 +259,7 @@ def main(): discadj_trans_stator.cfg_dir = "disc_adj_turbomachinery/transonic_stator_2D" discadj_trans_stator.cfg_file = "transonic_stator.cfg" discadj_trans_stator.test_iter = 79 - discadj_trans_stator.test_vals = [79.000000, -7.555649, -10.335509, -10.356935, -13.629546] + discadj_trans_stator.test_vals = [79.000000, -7.555647, -10.335486, -10.356919, -13.629543] discadj_trans_stator.test_vals_aarch64 = [79.000000, -7.555647, -10.335486, -10.356919, -13.629543] test_list.append(discadj_trans_stator) From 0e34254b433aaa045ef0af2b5a2ca5bcaf08e50e Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 15:02:26 +0100 Subject: [PATCH 33/40] Apply black formatting to the monitor script and its tests Co-Authored-By: Claude Opus 5.5 --- SU2_PY/monitor.py | 17 ++++++++++++++--- SU2_PY/tests/test_monitor.py | 4 +++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/SU2_PY/monitor.py b/SU2_PY/monitor.py index 6797a8b07b28..c62a2c27d54d 100755 --- a/SU2_PY/monitor.py +++ b/SU2_PY/monitor.py @@ -184,7 +184,9 @@ def update(self): iters = ( table[self.iter_col].to_numpy() if self.iter_col is not None - else np.arange(self.n + 1, self.n + len(table) + 1, dtype=np.float64) + else np.arange( + self.n + 1, self.n + len(table) + 1, dtype=np.float64 + ) ) times = ( table[self.time_col].to_numpy() @@ -514,11 +516,20 @@ def updateInnerSwitch(self): else: reason = "Not available: one row per time step, set HISTORY_WRT_FREQ_INNER" self.btn_inner.setToolTip(reason) - if has != self.btn_inner.isEnabled() or advance != self.inner_advance or not has: + if ( + has != self.btn_inner.isEnabled() + or advance != self.inner_advance + or not has + ): self.btn_inner.setEnabled(has) self.btn_inner.setChecked( (has and not advance) - or (reader is not None and reader.has_inner_col and not has and not advance) + or ( + reader is not None + and reader.has_inner_col + and not has + and not advance + ) ) self.inner_advance = advance diff --git a/SU2_PY/tests/test_monitor.py b/SU2_PY/tests/test_monitor.py index 74146a91f67f..94defc541750 100644 --- a/SU2_PY/tests/test_monitor.py +++ b/SU2_PY/tests/test_monitor.py @@ -87,7 +87,9 @@ def test_inner_iterations(self): def test_first_time_step_has_inner_rows(self): names = '"Time_Iter","Outer_Iter","Inner_Iter","rms[Rho]"\n' - reader = self.reader(names + "".join(f"1, 0, {i}, {-0.1 * i}\n" for i in range(5))) + reader = self.reader( + names + "".join(f"1, 0, {i}, {-0.1 * i}\n" for i in range(5)) + ) self.assertTrue(reader.hasInnerRows()) self.assertFalse(reader.stepsAdvance()) np.testing.assert_array_equal(reader.select(0)[0], [4]) From 2fdac90bb8468e0607fc2281020827eba81fdc5a Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:18:32 +0100 Subject: [PATCH 34/40] Flamelet LUT: extrapolate linearly beyond the outer table levels Beyond the first and last table level the lookup used the outer level alone, so looked-up quantities stopped depending on the level variable. With preferential diffusion the mixture fraction is then no longer restored by its own diffusion and can run away, e.g. to negative values at a lean H2 flame tip. Queries outside the level range are now extrapolated linearly from the two outermost levels, up to one level spacing, and still reported as outside the manifold. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 24c8fbca24c8749bb620308d01802f2b3c8dcff1) --- Common/include/containers/CLookUpTable.hpp | 9 ++++ Common/src/containers/CLookUpTable.cpp | 54 +++++++++++++--------- 2 files changed, 42 insertions(+), 21 deletions(-) diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index e455dd1f12d1..e8f14408b751 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -272,6 +272,15 @@ class CLookUpTable { const su2double val_CV1, const su2double val_CV2, const su2double val_CV3); + /*! + * \brief Interpolate linearly in the third controlling variable between two table levels, or extrapolate + * when val_CV3 lies outside them. + * \returns whether the query point lies inside the data on both levels. + */ + bool InterpolateBetweenLevels(const std::vector& idx_var, std::vector& val_vars, + const su2double val_CV1, const su2double val_CV2, const su2double val_CV3, + std::pair levels); + /*! * \brief Find the triangle within which the query point (val_CV1, val_CV2) is located. * \param[in] val_CV1 - First controlling variable value. diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 05586d39585c..3d1012adf336 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -438,6 +438,25 @@ bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::ve return inside; } +bool CLookUpTable::InterpolateBetweenLevels(const std::vector& idx_var, std::vector& val_vars, + const su2double val_CV1, const su2double val_CV2, const su2double val_CV3, + std::pair levels) { + /* Determine val_CV1 and val_CV2 for the two levels. */ + std::array, 2> lower_upper_CV1_2 = ComputeNormalizedXY(levels, val_CV1, val_CV2, val_CV3); + su2double val_CV1_lower = lower_upper_CV1_2[0][0], val_CV2_lower = lower_upper_CV1_2[0][1], + val_CV1_upper = lower_upper_CV1_2[1][0], val_CV2_upper = lower_upper_CV1_2[1][1]; + + /* Perform 2D interpolations on both levels. */ + std::vector val_vars_lower(val_vars.size()), val_vars_upper(val_vars.size()); + auto inside_lower = LookUp_XY(idx_var, val_vars_lower, val_CV1_lower, val_CV2_lower, levels.first); + auto inside_upper = LookUp_XY(idx_var, val_vars_upper, val_CV1_upper, val_CV2_upper, levels.second); + + /* Linear interpolation, or extrapolation, along the z-direction. */ + Linear_Interpolation(val_CV3, levels.first, levels.second, val_vars_lower, val_vars_upper, val_vars); + + return (inside_upper && inside_lower); +} + bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::vector& val_vars, const su2double val_CV1, const su2double val_CV2, const su2double val_CV3) { /*--- Perform quasi-3D interpolation for a vector of variables with names val_names_var @@ -447,28 +466,21 @@ bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::ve std::pair inclusion_levels = FindInclusionLevels(val_CV3); bool within_z_limits = (inclusion_levels.first != inclusion_levels.second); + /*--- Beyond the outer levels, extrapolate linearly from the two outermost levels, up to one level + * spacing beyond the table, so that looked-up quantities keep their dependence on val_CV3. ---*/ + if (!within_z_limits && n_table_levels > 1) { + const bool below = val_CV3 < z_values_levels.front(); + const unsigned long i_low = below ? 0 : n_table_levels - 2; + const pair outer_levels = make_pair(i_low, i_low + 1); + const su2double dz = z_values_levels[i_low + 1] - z_values_levels[i_low]; + const su2double z_extrap = below ? su2double(max(val_CV3, z_values_levels.front() - dz)) + : su2double(min(val_CV3, z_values_levels.back() + dz)); + InterpolateBetweenLevels(idx_var, val_vars, val_CV1, val_CV2, z_extrap, outer_levels); + return false; + } + if (within_z_limits) { - /* 2: Determine val_CV1 and val_CV2 for the inclusion table levels. */ - std::array, 2> lower_upper_CV1_2 = - ComputeNormalizedXY(inclusion_levels, val_CV1, val_CV2, val_CV3); - su2double val_CV1_lower = lower_upper_CV1_2[0][0], val_CV2_lower = lower_upper_CV1_2[0][1], - val_CV1_upper = lower_upper_CV1_2[1][0], val_CV2_upper = lower_upper_CV1_2[1][1]; - - /* 3: Perform 2D interpolations on upper and lower inclusion levels */ - unsigned long lower_level = inclusion_levels.first; - unsigned long upper_level = inclusion_levels.second; - - std::vector val_vars_lower, val_vars_upper; - val_vars_lower.resize(val_vars.size()); - val_vars_upper.resize(val_vars.size()); - auto inside_lower = LookUp_XY(idx_var, val_vars_lower, val_CV1_lower, val_CV2_lower, lower_level); - auto inside_upper = LookUp_XY(idx_var, val_vars_upper, val_CV1_upper, val_CV2_upper, upper_level); - - /* 4: Perform linear interpolation along the z-direction using the x-y interpolation results - from upper and lower trapezoidal maps */ - Linear_Interpolation(val_CV3, lower_level, upper_level, val_vars_lower, val_vars_upper, val_vars); - - return (inside_upper && inside_lower); + return InterpolateBetweenLevels(idx_var, val_vars, val_CV1, val_CV2, val_CV3, inclusion_levels); } else { /* Perform single, 2D interpolation when val_CV3 lies outside table bounds */ unsigned long bound_level = inclusion_levels.first; From 9f3680860ca17f3fd90177d324b448f22802d6c2 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:18:32 +0100 Subject: [PATCH 35/40] Flamelet: block Jacobian of the preferential diffusion terms The preferential diffusion flux D grad(beta - phi) used the Jacobian of the ordinary diffusion, i.e. d(beta - phi)/dphi = 1, without the coupling between the controlling variables and without the thermal term of the enthalpy equation. For the mixture fraction of lean H2 flames dbeta/dZ is about 3-4, so the term was under-implicit and the mixture fraction and enthalpy oscillated with a period of two iterations near cooled walls. The solver now evaluates d(beta_i - phi_i)/dphi_j, with beta_T dT/dphi_j in the enthalpy row, by finite differences of the manifold lookup when the preferential diffusion scalars are updated: central differences inside the manifold, one-sided towards it at its edges, and the previous Jacobian where neither fits. The steps are 1e-3 of the global range of each controlling variable. The edge kernel assembles the full block. The residual is unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9cace00ee27694cba9bafaf3acf71105e3645217) --- .../numerics/species/flamelet_edge_flux.hpp | 20 +++-- .../solvers/CSpeciesFlameletSolver.hpp | 11 ++- .../include/variables/CSpeciesVariable.hpp | 13 +++ .../src/solvers/CSpeciesFlameletSolver.cpp | 84 +++++++++++++++++++ .../variables/CSpeciesFlameletVariable.cpp | 2 + 5 files changed, 121 insertions(+), 9 deletions(-) diff --git a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index dba70c948816..d476d6fbda29 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -56,9 +56,8 @@ class CScalarFlux_Flamelet final * \brief Preferential diffusion, two terms with the shape of the ordinary diffusion but of * states the model synthesises: div(D grad(beta - phi)) for each controlling variable, * and a thermal term div(beta_T D grad(T)) on the enthalpy equation. - * \note The thermal term has no implicit part, matching the treatment of the heat flux it - * models; the first term has the same thin shear layer Jacobian as the ordinary diffusion, - * because it is the same operator applied to a shifted state. + * \note The Jacobian couples the controlling variables through the derivatives of beta - phi, with + * the thermal term folded into the enthalpy row; the solver evaluates them from the manifold. */ template FORCEINLINE void extraDiffusionTerms(const FlowIndices& idx, const ScalarFluxOptions& opt, Int iPoint, @@ -104,11 +103,16 @@ class CScalarFlux_Flamelet final if (!opt.oneSided) res.flux_j(iScalar) += D * projGrad; if (opt.implicit) { - res.jac_ii(iScalar, iScalar) += D * proj_on_rho_i; - if (!opt.oneSided) { - res.jac_ij(iScalar, iScalar) -= D * proj_on_rho_j; - res.jac_ji(iScalar, iScalar) -= D * proj_on_rho_i; - res.jac_jj(iScalar, iScalar) += D * proj_on_rho_j; + for (auto jScalar = 0u; jScalar < nControlVars; ++jScalar) { + const auto iEntry = iScalar * nControlVars + jScalar; + const Double dState_i = gatherVariables(iPoint, side_i.scalarNodes.GetPrefDiffJacobian(), iEntry); + const Double dState_j = gatherVariables(jPoint, side_j.scalarNodes.GetPrefDiffJacobian(), iEntry); + res.jac_ii(iScalar, jScalar) += D * proj_on_rho_i * dState_i; + if (!opt.oneSided) { + res.jac_ij(iScalar, jScalar) -= D * proj_on_rho_j * dState_j; + res.jac_ji(iScalar, jScalar) -= D * proj_on_rho_i * dState_i; + res.jac_jj(iScalar, jScalar) += D * proj_on_rho_j * dState_j; + } } } } diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index 7543d6d7f282..5f9d6326dac2 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -45,6 +45,14 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { /*!< \brief Number of points outside the manifold domain, shared across OpenMP threads so it can be * accumulated atomically and reduced by the master thread alone in Preprocessing. */ unsigned long n_not_in_domain_local = 0; + bool pd_jacobian = false; /*!< \brief Whether the preferential diffusion Jacobian is evaluated this iteration. */ + passivedouble pd_jacobian_step[MAXNVAR] = {0}; /*!< \brief Finite difference step per controlling variable. */ + + /*! + * \brief Set the finite difference steps of the preferential diffusion Jacobian, a fraction of the global + * range of each controlling variable. + */ + void SetPrefDiffJacobianSteps(); /*! * \brief Compute the preconditioner for low-Mach flows. * \param[in] geometry - Geometrical definition of the problem. @@ -105,7 +113,8 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { const vector& scalars); /*! - * \brief Retrieve the preferential diffusion scalar values from manifold. + * \brief Retrieve the preferential diffusion scalar values from manifold, and their derivatives to the + * controlling variables when the scheme is implicit. * \param[in] fluid_model_local - pointer to flamelet fluid model. * \param[in] iPoint - node ID. * \param[in] scalars - local scalar solution. diff --git a/SU2_CFD/include/variables/CSpeciesVariable.hpp b/SU2_CFD/include/variables/CSpeciesVariable.hpp index 197cd9db04a6..84185d8a6d97 100644 --- a/SU2_CFD/include/variables/CSpeciesVariable.hpp +++ b/SU2_CFD/include/variables/CSpeciesVariable.hpp @@ -39,10 +39,23 @@ class CSpeciesVariable : public CScalarVariable { MatrixType SpeciesSourceTerm; /*!< \brief Matrix (nPoint, nVar) of chemical source terms for species transport*/ MatrixType SpeciesSourceJacobian; /*!< \brief Matrix (nPoint, nVar) of the diagonal chemical source Jacobian. */ VectorType HeatRelease; /*!< \brief Vector of heat release due to combustion for species transport*/ + MatrixType PrefDiffJacobian; /*!< \brief Matrix (nPoint, nCV*nCV), row-major d(beta_i - phi_i)/d(phi_j) of the preferential diffusion terms. */ public: static constexpr size_t MAXNVAR = MAX_TRANSPORTED_SPECIES; /*!< \brief Max number of variables for static arrays. */ + /*! + * \brief Derivatives of the preferential diffusion states to the controlling variables, row-major per point. + */ + inline const MatrixType& GetPrefDiffJacobian() const { return PrefDiffJacobian; } + + /*! + * \brief Set one derivative of a preferential diffusion state, entry iCV*nCV + jCV. + */ + inline void SetPrefDiffJacobian(unsigned long iPoint, unsigned long iEntry, su2double val) { + PrefDiffJacobian(iPoint, iEntry) = val; + } + /*! * \brief Constructor of the class. * \param[in] species_inf - species variable values (initialization value). diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index ba5489ed5c45..d5a8c5fbac39 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -90,6 +90,12 @@ void CSpeciesFlameletSolver::Preprocessing(CGeometry* geometry, CSolver** solver SU2_OMP_SAFE_GLOBAL_ACCESS(config->SetGlobalParam(config->GetKind_Solver(), RunTime_EqSystem); n_not_in_domain_local = 0;) + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + pd_jacobian = flamelet_config_options.preferential_diffusion && (config->GetKind_TimeIntScheme() == EULER_IMPLICIT); + if (pd_jacobian) SetPrefDiffJacobianSteps(); + } + END_SU2_OMP_SAFE_GLOBAL_ACCESS + /* Update global flame thickness value. */ if (calc_flame_thickness) { /*--- Every thread takes part in this, it reduces over the points of the rank and over ranks, @@ -707,9 +713,87 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode for (auto i_beta = 0u; i_beta < FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS; i_beta++) { nodes->SetAuxVar(iPoint, i_beta, beta_scalar[i_beta]); } + if (!pd_jacobian) return misses; + + /*--- Differences of the beta scalars and of the temperature, which drives the thermal term: central inside + * the manifold, one-sided towards it at its edges, and the ordinary diffusion Jacobian where neither fits. ---*/ + const auto n_cv = flamelet_config_options.n_control_vars; + auto beta_index = [](int i_cv) { + if (i_cv == I_PROGVAR) return I_BETA_PROGVAR; + if (i_cv == I_ENTH) return I_BETA_ENTH; + return I_BETA_MIXFRAC; + }; + const su2double temperature = fluid_model_local->GetTemperature(); + vector scalars_fd(scalars), beta_plus(beta_scalar.size()), beta_minus(beta_scalar.size()); + + for (auto j_cv = 0u; j_cv < n_cv; j_cv++) { + const su2double step = pd_jacobian_step[j_cv]; + scalars_fd[j_cv] = scalars[j_cv] + step; + bool inside_plus = fluid_model_local->EvaluateDataSet(scalars_fd, FLAMELET_LOOKUP_OPS::PREFDIF, beta_plus) == 0; + fluid_model_local->SetTDState_T(temperature, scalars_fd.data()); + inside_plus = inside_plus && (fluid_model_local->GetExtrapolation() == 0); + su2double temperature_plus = fluid_model_local->GetTemperature(); + scalars_fd[j_cv] = scalars[j_cv] - step; + bool inside_minus = fluid_model_local->EvaluateDataSet(scalars_fd, FLAMELET_LOOKUP_OPS::PREFDIF, beta_minus) == 0; + fluid_model_local->SetTDState_T(temperature, scalars_fd.data()); + inside_minus = inside_minus && (fluid_model_local->GetExtrapolation() == 0); + su2double temperature_minus = fluid_model_local->GetTemperature(); + scalars_fd[j_cv] = scalars[j_cv]; + + su2double span = 2 * step; + if (!inside_plus) { + beta_plus = beta_scalar; + temperature_plus = temperature; + span = step; + } + if (!inside_minus) { + beta_minus = beta_scalar; + temperature_minus = temperature; + span = step; + } + const bool usable = (misses == 0) && (inside_plus || inside_minus); + + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + su2double value = (i_cv == j_cv) ? su2double(1.0) : su2double(0.0); + if (usable) { + const auto i_beta = beta_index(i_cv); + su2double d_state = (beta_plus[i_beta] - beta_minus[i_beta]) / span; + if (i_cv == I_ENTH) + d_state += beta_scalar[I_BETA_ENTH_THERMAL] * (temperature_plus - temperature_minus) / span; + value = d_state - ((i_cv == j_cv) ? 1.0 : 0.0); + /*--- The total diagonal, ordinary diffusion included, is kept positive. ---*/ + if (i_cv == j_cv) value = max(value, su2double(-0.9)); + } + nodes->SetPrefDiffJacobian(iPoint, i_cv * n_cv + j_cv, value); + } + } + fluid_model_local->SetTDState_T(temperature, scalars.data()); return misses; } +void CSpeciesFlameletSolver::SetPrefDiffJacobianSteps() { + const auto n_cv = flamelet_config_options.n_control_vars; + passivedouble local_min[MAXNVAR], local_max[MAXNVAR], global_min[MAXNVAR], global_max[MAXNVAR]; + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + local_min[i_cv] = std::numeric_limits::max(); + local_max[i_cv] = std::numeric_limits::lowest(); + } + for (auto i_point = 0u; i_point < nPointDomain; i_point++) { + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + const passivedouble value = SU2_TYPE::GetValue(nodes->GetSolution(i_point, i_cv)); + local_min[i_cv] = min(local_min[i_cv], value); + local_max[i_cv] = max(local_max[i_cv], value); + } + } + SU2_MPI::Allreduce(local_min, global_min, n_cv, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(local_max, global_max, n_cv, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); + /*--- The magnitude floor keeps the step finite when the field is still uniform. ---*/ + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + const passivedouble magnitude = max(fabs(global_min[i_cv]), fabs(global_max[i_cv])); + pd_jacobian_step[i_cv] = max({1e-3 * (global_max[i_cv] - global_min[i_cv]), 1e-5 * magnitude, 1e-10}); + } +} + void CSpeciesFlameletSolver::Upwind_Residual(CGeometry* geometry, CSolver** solver_container, CNumerics**, CConfig* config, unsigned short iMesh) { SU2_ZONE_SCOPED diff --git a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index 46028e30bf12..4b1c845874b7 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -60,5 +60,7 @@ CSpeciesFlameletVariable::CSpeciesFlameletVariable(const su2double* species_inf, nAuxVar = FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS; AuxVar.resize(nPoint, FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS) = su2double(0.0); Grad_AuxVar.resize(nPoint, FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS, nDim, 0.0); + const auto n_cv = flamelet_config_options.n_control_vars; + PrefDiffJacobian.resize(nPoint, n_cv * n_cv) = su2double(0.0); } } From c91ac9beef41211bc670c42d53ef22598e702615 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:31:34 +0100 Subject: [PATCH 36/40] Flamelet: keep the burnt state of the flame front initialization inside the manifold GetBurntProgressVariable marched the progress variable up in steps of 1e-3 and returned the first value that was outside the manifold, because the step taken after leaving it was subtracted only once. The whole burnt region of a flame front initialization then started just outside the table, where the lookup returns frozen values of the nearest nodes; in a lean H2 slit burner these points persisted as a band of progress variable above equilibrium. The march now keeps the last value inside the manifold. When it leaves the manifold, the edge is bisected and the burnt value is set 0.1% of the progress variable range inside it. When the ignition temperature is reached first, that value is returned as before. Co-Authored-By: Claude Opus 5.5 --- .../src/solvers/CSpeciesFlameletSolver.cpp | 38 +++++++++++++++---- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index d5a8c5fbac39..e17242ac9519 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -852,15 +852,39 @@ su2double CSpeciesFlameletSolver::GetBurntProgressVariable(CFluidModel* fluid_mo SU2_ZONE_SCOPED su2double scalars[MAXNVAR], delta = 1e-3; for (auto iVar = 0u; iVar < nVar; iVar++) scalars[iVar] = scalar_solution[iVar]; - bool outside = false; - scalars[I_PROGVAR] += delta; - while (!outside) { - /*--- Note that 300.0 is a dummy temperature here and not used. ---*/ + + /*--- Note that 300.0 is a dummy temperature here and not used. ---*/ + auto inside = [&](su2double pv) { + scalars[I_PROGVAR] = pv; fluid_model->SetTDState_T(300.0, scalars); - if ((fluid_model->GetExtrapolation() == 1) || fluid_model->GetTemperature() > T_ignition) outside = true; - scalars[I_PROGVAR] += delta; + return fluid_model->GetExtrapolation() == 0; + }; + + /*--- March up while the state stays inside the manifold, until the ignition temperature is exceeded. ---*/ + const su2double pv_unburnt = scalar_solution[I_PROGVAR]; + su2double pv_burnt = pv_unburnt, pv_trial = pv_unburnt + delta; + bool ignited = false; + while (!ignited && inside(pv_trial)) { + pv_burnt = pv_trial; + ignited = fluid_model->GetTemperature() > T_ignition; + pv_trial += delta; + } + + /*--- The march left the manifold: bisect to its edge and keep a margin inside it. ---*/ + if (!ignited) { + su2double pv_out = pv_trial; + for (int iter = 0; iter < 30; iter++) { + const su2double pv_mid = 0.5 * (pv_burnt + pv_out); + if (inside(pv_mid)) + pv_burnt = pv_mid; + else + pv_out = pv_mid; + } + const su2double pv_margin = pv_burnt - 1e-3 * (pv_burnt - pv_unburnt); + if (inside(pv_margin)) pv_burnt = pv_margin; } - su2double pv_burnt = scalars[I_PROGVAR] - delta; + inside(pv_burnt); + if (rank == MASTER_NODE) { cout << "Burnt progress variable determined from flamelet table: " << pv_burnt << endl; cout << "Burnt temperature from flamelet table: " << fluid_model->GetTemperature() << endl; From 2215935646b17c429a7f5ba40de820dddac4c6ce Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 15:23:49 +0100 Subject: [PATCH 37/40] Update flamelet regression values for the preferential diffusion Jacobian Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression.py | 4 ++-- TestCases/tutorials.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index e6c8b08b1c66..086c5d7b9e88 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -97,7 +97,7 @@ def main(): cfd_flamelet_h2.cfg_dir = "flamelet/07_laminar_premixed_h2_flame_cfd" cfd_flamelet_h2.cfg_file = "laminar_premixed_h2_flame_cfd.cfg" cfd_flamelet_h2.test_iter = 5 - cfd_flamelet_h2.test_vals = [-8.036810, -8.328814, -1.805276, -8.959649] + cfd_flamelet_h2.test_vals = [-8.036773, -8.366862, -1.872906, -9.961343] test_list.append(cfd_flamelet_h2) # Flame ignition methods @@ -105,7 +105,7 @@ def main(): flame_init_methods.cfg_dir = "flamelet/08_flame_init_method" flame_init_methods.cfg_file ="flamelet_initialization.py" flame_init_methods.command = TestCase.Command("mpirun -np 2", "python", "flamelet_initialization.py") - flame_init_methods.test_vals=[1600, 1595.82] + flame_init_methods.test_vals=[1600, 1364.35] flame_init_methods.new_output = True test_list.append(flame_init_methods) diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index 0a00bff5434e..8bbf86fa9665 100644 --- a/TestCases/tutorials.py +++ b/TestCases/tutorials.py @@ -177,7 +177,7 @@ def main(): premixed_hydrogen.cfg_dir = "../Tutorials/incompressible_flow/Inc_Combustion/1__premixed_hydrogen" premixed_hydrogen.cfg_file = "H2_burner.cfg" premixed_hydrogen.test_iter = 10 - premixed_hydrogen.test_vals = [-8.769561, -9.719764, -10.153709, -3.439324, -11.528261] + premixed_hydrogen.test_vals = [-8.769698, -9.720818, -10.302347, -3.752803, -12.001923] test_list.append(premixed_hydrogen) ### Compressible Flow From f6caf6e1025eada5a71f60baccc8c681c543ad7b Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 15:50:16 +0100 Subject: [PATCH 38/40] Flamelet: table-range fixes, cached progress variable bounds, zero-variance source offset - The progress variable source Jacobian of the table uses a difference step of 1e-3 of the progress variable range of the table (GetRangeCV). - The table edge bounds the progress variable whenever it is the first table axis, and a progress variable beyond the edge is reported outside the manifold. - The progress variable range lookup is reused while the controlling variables other than the variance are unchanged (not in reverse mode AD). - The chemical variance source subtracts its value at zero variance, which is zero but for the interpolation error of the manifold. - THICKENED_FLAME_CORRECTION= YES is an error where it does not apply. - Scalar local time steps use the relative velocity on moving grids and include the periodic volume. - Passive periodic points show the residual of their master. - Unit test for the progress variable range of a table. Co-Authored-By: Claude Opus 5.5 --- Common/include/containers/CLookUpTable.hpp | 9 ++ Common/src/CConfig.cpp | 12 ++- Common/src/containers/CLookUpTable.cpp | 11 +++ SU2_CFD/include/fluid/CFluidFlamelet.hpp | 13 ++- SU2_CFD/include/solvers/CScalarSolver.inl | 13 ++- .../solvers/CSpeciesFlameletSolver.hpp | 12 +-- SU2_CFD/src/fluid/CFluidFlamelet.cpp | 54 ++++++++--- SU2_CFD/src/solvers/CSolver.cpp | 13 ++- .../src/solvers/CSpeciesFlameletSolver.cpp | 40 ++++++--- .../Common/containers/CLookupTable_tests.cpp | 29 ++++++ .../Common/containers/lookuptable_range.drg | 89 +++++++++++++++++++ config_template.cfg | 3 +- 12 files changed, 256 insertions(+), 42 deletions(-) create mode 100644 UnitTests/Common/containers/lookuptable_range.drg diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index 30a1ac6bd480..625688c218e9 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -151,6 +151,8 @@ class CLookUpTable { /*! * \brief Tabulate the range of the first controlling variable covered by each table level, from its boundary edges. + * \note The range at a value of the second controlling variable spans the outermost boundary edges, so a level + * is assumed to cover a single interval there, without holes or notches. */ void ComputeRangeCV1(); @@ -419,6 +421,13 @@ class CLookUpTable { return limits_table_x[i_level]; } + /*! + * \brief Range of a controlling variable over all table levels. + * \param[in] i_cv - 0 and 1 for the axes of the levels, 2 for the variable of the levels. + * \returns Pair of minimum and maximum value. + */ + std::pair GetRangeCV(unsigned short i_cv) const; + /*! * \brief Check whether requested set of variables are included in the table. */ diff --git a/Common/src/CConfig.cpp b/Common/src/CConfig.cpp index 42fc0f36116b..b39ee48361d7 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -6325,8 +6325,14 @@ void CConfig::SetPostprocessing(SU2_COMPONENT val_software, unsigned short val_i SU2_MPI::Error(string("CONTROLLING_VARIABLE_NAMES must include ") + FLAMELET_CV_NAME::PROGVAR + " or " + FLAMELET_CV_NAME::MIXFRAC + ".", CURRENT_FUNCTION); - /*--- The thickened flame correction measures the progress variable gradient. ---*/ - if (opts.idx_progvar < 0) opts.thickenedflame_correction = false; + /*--- The thickened flame correction is off where it does not apply, and an error where it was asked for. ---*/ + auto disable_thickened_flame = [&](const string& reason) { + if (OptionIsSet("THICKENED_FLAME_CORRECTION") && opts.thickenedflame_correction) + SU2_MPI::Error("THICKENED_FLAME_CORRECTION= YES is not available " + reason + ".", CURRENT_FUNCTION); + opts.thickenedflame_correction = false; + }; + if (opts.idx_progvar < 0) + disable_thickened_flame(string("without ") + FLAMELET_CV_NAME::PROGVAR); /*--- A variance needs its mean and the turbulence time scale omega of the SST model. ---*/ if ((opts.idx_progvar_var >= 0) && (opts.idx_progvar < 0)) @@ -6340,7 +6346,7 @@ void CConfig::SetPostprocessing(SU2_COMPONENT val_software, unsigned short val_i SU2_MPI::Error("Scalar variance transport requires KIND_TURB_MODEL= SST.", CURRENT_FUNCTION); if (opts.preferential_diffusion) SU2_MPI::Error("PREFERENTIAL_DIFFUSION is not available with scalar variance transport.", CURRENT_FUNCTION); - opts.thickenedflame_correction = false; + disable_thickened_flame("with scalar variance transport"); } /*--- Check that spark ignition has required parameters defined ---*/ diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 9347bff937e5..72b0a639030c 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -491,6 +491,17 @@ bool CLookUpTable::GetRangeCV1(const su2double val_CV2, const su2double val_CV3, return true; } +std::pair CLookUpTable::GetRangeCV(const unsigned short i_cv) const { + if (i_cv == 2) return make_pair(*limits_table_z.first, *limits_table_z.second); + const auto& limits = (i_cv == 0) ? limits_table_x : limits_table_y; + su2double val_min = *limits[0].first, val_max = *limits[0].second; + for (auto i_level = 1ul; i_level < n_table_levels; i_level++) { + val_min = min(val_min, *limits[i_level].first); + val_max = max(val_max, *limits[i_level].second); + } + return make_pair(val_min, val_max); +} + std::pair CLookUpTable::FindInclusionLevels(const su2double val_CV3) { /*--- Find the table levels with constant z-values directly below and above the query value val_CV3 ---*/ diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index ebe0bf464d3c..1f51747e9a4b 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -74,6 +74,16 @@ class CFluidFlamelet final : public CFluidModel { su2double limit_progvar_var = 0, /*!< \brief Upper limit of the progress variable variance. */ limit_mixfrac_var = 0; /*!< \brief Upper limit of the mixture fraction variance. */ bool progvar_range_from_table = false; /*!< \brief Bound the progress variable by the edge of the table. */ + su2double progvar_fd_step = 0; /*!< \brief Difference step of the progress variable source Jacobian of the table. */ + vector bounds_key; /*!< \brief Controlling variables of the last progress variable range lookup. */ + bool bounds_cached = false; /*!< \brief Whether bounds_key and val_vars_ProgVarBounds hold a lookup. */ + bool bounds_inside = true; /*!< \brief Whether the last progress variable range lookup was inside. */ + + /*! + * \brief Whether the progress variable range of the last lookup applies to these scalars, which become the key. + * \note Always false for reverse mode AD, where a stored value would not be part of the recorded preaccumulation. + */ + bool ProgVarBoundsCached(const su2double* scalars); /*--- Class variables for the multi-layer perceptron method ---*/ #ifdef USE_MLPCPP @@ -186,7 +196,8 @@ class CFluidFlamelet final : public CFluidModel { /*! * \brief Derivative of the progress variable source at constant normalized variance, zero where it is clipped. - * \note Analytic for the MLP method, a central difference inside the progress variable range for the table. + * \note It approximates the derivative at constant variance, for the implicit diagonal only. Analytic for the + * MLP method, a central difference inside the progress variable range for the table. */ su2double GetProgVarSourceJacobian(const vector& scalars) override; diff --git a/SU2_CFD/include/solvers/CScalarSolver.inl b/SU2_CFD/include/solvers/CScalarSolver.inl index d1c768dde47e..4a590822df52 100644 --- a/SU2_CFD/include/solvers/CScalarSolver.inl +++ b/SU2_CFD/include/solvers/CScalarSolver.inl @@ -493,18 +493,23 @@ void CScalarSolver::SetTime_Step(CGeometry *geometry, CSolver **so for (unsigned long iPoint = 0; iPoint < nPointDomain; iPoint++) { su2double dt = nodes->GetLocalCFL(iPoint) / flowNodes->GetLocalCFL(iPoint) * flowNodes->GetDelta_Time(iPoint); - /*--- Scalars are carried at the flow speed, without the artificial sound speed of the flow time step. ---*/ + /*--- Scalars are carried at the flow speed, without the artificial sound speed of the flow time step. + * Boundary points keep the flow time step, as the edge loop misses their boundary faces. ---*/ if (max_ratio > 1.0 && !geometry->nodes->GetPhysicalBoundary(iPoint)) { su2double lambda_conv = 0.0; for (unsigned short iNeigh = 0; iNeigh < geometry->nodes->GetnNeighbor(iPoint); iNeigh++) { const auto jPoint = geometry->nodes->GetPoint(iPoint, iNeigh); const auto* normal = geometry->edges->GetNormal(geometry->nodes->GetEdge(iPoint, iNeigh)); su2double proj_vel = 0.0; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - proj_vel += 0.5 * (flowNodes->GetVelocity(iPoint, iDim) + flowNodes->GetVelocity(jPoint, iDim)) * normal[iDim]; + for (unsigned short iDim = 0; iDim < nDim; iDim++) { + su2double vel = 0.5 * (flowNodes->GetVelocity(iPoint, iDim) + flowNodes->GetVelocity(jPoint, iDim)); + if (dynamic_grid) + vel -= 0.5 * (geometry->nodes->GetGridVel(iPoint)[iDim] + geometry->nodes->GetGridVel(jPoint)[iDim]); + proj_vel += vel * normal[iDim]; + } lambda_conv += fabs(proj_vel); } - const su2double vol = geometry->nodes->GetVolume(iPoint); + const su2double vol = geometry->nodes->GetVolume(iPoint) + geometry->nodes->GetPeriodicVolume(iPoint); const su2double cfl = nodes->GetLocalCFL(iPoint); const su2double dt_conv = cfl * vol / max(lambda_conv, EPS); const su2double dt_visc = cfl * 0.25 * vol * vol / max(flowNodes->GetMax_Lambda_Visc(iPoint), EPS); diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index e5682927f930..d4ba2597994e 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -57,12 +57,6 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { * range of each controlling variable. */ void SetPrefDiffJacobianSteps(); - /*! - * \brief Compute the preconditioner for low-Mach flows. - * \param[in] geometry - Geometrical definition of the problem. - * \param[in] solver_container - Container vector with all the solutions. - * \param[in] config - Definition of the particular problem. - */ /*! * \brief Limit the scalar variances to the maximum of a two-point distribution on the range of their mean. * \param[in] geometry - Geometrical definition of the problem. @@ -73,6 +67,12 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { void Postprocessing(CGeometry* geometry, CSolver** solver_container, CConfig* config, unsigned short iMesh) override; + /*! + * \brief Compute the preconditioner for low-Mach flows. + * \param[in] geometry - Geometrical definition of the problem. + * \param[in] solver_container - Container vector with all the solutions. + * \param[in] config - Definition of the particular problem. + */ void SetPreconditioner(CGeometry* geometry, CSolver** solver_container, CConfig* config); /*! diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index ea800a76d0fa..1cf4dd16313d 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -54,6 +54,7 @@ CFluidFlamelet::CFluidFlamelet(CConfig* config, su2double value_pressure_operati } scalars_vector.resize(n_scalars); manifold_inputs.resize(n_control_vars); + bounds_key.resize(n_control_vars); table_scalar_names.resize(n_scalars); for (auto iCV = 0u; iCV < n_control_vars; iCV++) @@ -308,15 +309,19 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { : look_up_table->GetIndexOfVar(varnames_PD[iVar])); } } + /*--- Difference step of the source Jacobian, a fraction of the progress variable range of the table. ---*/ + if (flamelet_options.idx_progvar >= 0) { + const auto range = look_up_table->GetRangeCV(flamelet_options.idx_progvar); + progvar_fd_step = 1e-3 * (range.second - range.first); + } if (!varnames_ProgVarBounds.empty()) { if (!look_up_table->CheckForVariables(varnames_ProgVarBounds)) SU2_MPI::Error(string("Transporting ") + FLAMELET_CV_NAME::PROGVAR_VAR + " requires the variables " + FLAMELET_PROGVAR_BOUNDS::MIN + " and " + FLAMELET_PROGVAR_BOUNDS::MAX + " in the table.", CURRENT_FUNCTION); for (const auto& name : varnames_ProgVarBounds) LUT_idx_ProgVarBounds.push_back(look_up_table->GetIndexOfVar(name)); - /*--- With table axes (c, h) and levels in the variance, the table edge bounds c at each h. ---*/ - progvar_range_from_table = (n_control_vars == 3) && (flamelet_options.idx_progvar == 0) && - (flamelet_options.idx_progvar_var == 2); + /*--- When the progress variable is the first table axis, the table edge also bounds it. ---*/ + progvar_range_from_table = (flamelet_options.idx_progvar == 0); } } } @@ -364,10 +369,11 @@ su2double CFluidFlamelet::GetProgVarSourceJacobian(const vector& scal const int idx_var = flamelet_options.idx_progvar_var; const su2double c = scalars[i_c]; su2double c_min, c_max; - su2double c_lo = c - 1e-3, c_hi = c + 1e-3, s_var = 0.0; + su2double c_lo = c - progvar_fd_step, c_hi = c + progvar_fd_step, s_var = 0.0; const bool bounded = GetProgressVariableBounds(scalars.data(), c_min, c_max) && (c_max > c_min); if (bounded) { - /*--- Both points lie strictly inside the range, at the normalized variance of the node. ---*/ + /*--- Both points lie inside the range, a hundredth of the step away from its ends, at the normalized + * variance of the node. ---*/ const su2double delta = 1e-3 * (c_max - c_min); const su2double lower = c_min + 1e-2 * delta, upper = c_max - 1e-2 * delta; const su2double c_in = fmin(fmax(c, lower), upper); @@ -403,12 +409,16 @@ bool CFluidFlamelet::SetManifoldInputs(const su2double* scalars) { manifold_inputs[i_zvar] = normalize(scalars[i_zvar], limit_mixfrac_var, 1.0); } - /*--- Moves the progress variable of the lookup just inside the table edge and below c_max. ---*/ + /*--- Moves the progress variable of the lookup just inside the table edge and below c_max. + * The margin keeps the query off the edge, where the point location is ambiguous. ---*/ const int i_c = flamelet_options.idx_progvar; + bool outside_edge = false; auto clamp_to_table = [&](su2double c_max) { su2double edge_min, edge_max; - if (!look_up_table->GetRangeCV1(manifold_inputs[1], manifold_inputs[2], edge_min, edge_max)) return c_max; + const su2double val_CV3 = (n_control_vars > 2) ? manifold_inputs[2] : su2double(0.0); + if (!look_up_table->GetRangeCV1(manifold_inputs[1], val_CV3, edge_min, edge_max)) return c_max; const su2double margin = 1e-10 * (edge_max - edge_min); + outside_edge = (scalars[i_c] < edge_min) || (scalars[i_c] > edge_max); manifold_inputs[i_c] = fmin(fmax(scalars[i_c], edge_min + margin), fmin(edge_max, c_max) - margin); return edge_max; }; @@ -418,17 +428,37 @@ bool CFluidFlamelet::SetManifoldInputs(const su2double* scalars) { if (i_cvar >= 0) { /*--- The range of the progress variable does not depend on its variance. ---*/ manifold_inputs[i_cvar] = 0.0; - su2double edge_max{0}; - if (progvar_range_from_table) edge_max = clamp_to_table(std::numeric_limits::max()); - inside = LookUpManifold(FLAMELET_LOOKUP_OPS::PROGVAR_BOUNDS, manifold_inputs, val_vars_ProgVarBounds); - if (progvar_range_from_table) val_vars_ProgVarBounds[1] = fmin(val_vars_ProgVarBounds[1], edge_max); + if (!ProgVarBoundsCached(scalars)) { + su2double edge_max{0}; + if (progvar_range_from_table) edge_max = clamp_to_table(std::numeric_limits::max()); + bounds_inside = LookUpManifold(FLAMELET_LOOKUP_OPS::PROGVAR_BOUNDS, manifold_inputs, val_vars_ProgVarBounds); + if (progvar_range_from_table) val_vars_ProgVarBounds[1] = fmin(val_vars_ProgVarBounds[1], edge_max); + } + inside = bounds_inside; const su2double c = scalars[i_c]; limit_progvar_var = fmax((c - val_vars_ProgVarBounds[0]) * (val_vars_ProgVarBounds[1] - c), su2double(0.0)); manifold_inputs[i_cvar] = normalize(scalars[i_cvar], limit_progvar_var, val_vars_ProgVarBounds[1] - val_vars_ProgVarBounds[0]); if (progvar_range_from_table) clamp_to_table(val_vars_ProgVarBounds[1]); } - return inside; + /*--- A progress variable beyond the table edge is outside the manifold, although the lookup is clamped. ---*/ + return inside && !outside_edge; +} + +bool CFluidFlamelet::ProgVarBoundsCached(const su2double* scalars) { +#ifdef CODI_REVERSE_TYPE + return false; +#else + /*--- The range depends on all controlling variables except the progress variable variance. ---*/ + bool same = bounds_cached; + for (auto iCV = 0u; iCV < n_control_vars; iCV++) { + if (static_cast(iCV) == flamelet_options.idx_progvar_var) continue; + same = same && (bounds_key[iCV] == scalars[iCV]); + bounds_key[iCV] = scalars[iCV]; + } + bounds_cached = true; + return same; +#endif } void CFluidFlamelet::ScaleReducedSources(const su2double* scalars, vector& sources) const { diff --git a/SU2_CFD/src/solvers/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 04d0a1e14947..97d8318e053d 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -215,7 +215,7 @@ void CSolver::GetPeriodicCommCountAndType(const CConfig* config, MPI_TYPE = COMM_TYPE::DOUBLE; break; case PERIODIC_IMPLICIT: - COUNT_PER_POINT = nVar; + COUNT_PER_POINT = 2*nVar; MPI_TYPE = COMM_TYPE::DOUBLE; break; case PERIODIC_LAPLACIAN: @@ -737,12 +737,14 @@ void CSolver::InitiatePeriodicComms(CGeometry *geometry, for (iVar = 0; iVar < nVar; iVar++) { bufDSend[buf_offset+iVar] = base_nodes->GetSolution(iPoint, iVar); + bufDSend[buf_offset+nVar+iVar] = LinSysRes(iPoint, iVar); } - /*--- Rotate the momentum components of the solution array. ---*/ + /*--- Rotate the momentum components of the solution and of the residual. ---*/ if (rotate_periodic) { Rotate(zeros, &base_nodes->GetSolution(iPoint)[1], &bufDSend[buf_offset+1]); + Rotate(zeros, &LinSysRes(iPoint, 1), &bufDSend[buf_offset+nVar+1]); } break; @@ -1392,6 +1394,13 @@ void CSolver::CompletePeriodicComms(CGeometry *geometry, buf_offset++; } + /*--- The passive point shows the residual of the combined control volume of its master. ---*/ + + for (iVar = 0; iVar < nVar; iVar++) { + LinSysRes(iPoint, iVar) = bufDRecv[buf_offset]; + buf_offset++; + } + } /*--- A point on a rotation axis takes the average over all the copies of its control diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index cfeed58de391..95029ffc4d69 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -479,14 +479,15 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv LinSysRes(i_point, i_var) -= nodes->GetScalarSources(i_point)[i_var] * volume; } - /*--- Implicit: analytic Jacobian for auxiliary species from the split source form. - * S_aux_i = source_prod_i + source_cons_i * Y_aux_i - * dS_aux_i/d(rho Y_aux_i) = source_cons_i / rho - * J_ii += -source_cons_i / rho * V ---*/ if (implicit) { /*--- Only a source that decreases with the progress variable is made implicit. ---*/ if (idx_progvar >= 0 && progvar_source_slope[i_point] < 0) Jacobian.AddVal2Diag(i_point, idx_progvar, -progvar_source_slope[i_point] / density * volume); + + /*--- Analytic Jacobian for auxiliary species from the split source form. + * S_aux_i = source_prod_i + source_cons_i * Y_aux_i + * dS_aux_i/d(rho Y_aux_i) = source_cons_i / rho + * J_ii += -source_cons_i / rho * V ---*/ for (auto i_aux = 0u; i_aux < n_aux; i_aux++) { Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) / density * volume); } @@ -512,7 +513,8 @@ void CSpeciesFlameletSolver::ScalarVarianceResidual(CGeometry* geometry, CSolver const bool implicit = (config->GetKind_TimeIntScheme() == EULER_IMPLICIT); const su2double Sc_t = config->GetSchmidt_Number_Turbulent(); const su2double C_d = flamelet_config_options.variance_dissipation_coeff; - const su2double beta_star = solver_container[TURB_SOL]->GetConstants()[6]; + constexpr int idx_sst_beta_star = 6; /*--- Position of beta* in the constants of CTurbSSTSolver. ---*/ + const su2double beta_star = solver_container[TURB_SOL]->GetConstants()[idx_sst_beta_star]; const auto* flowNodes = su2staticcast_p(solver_container[FLOW_SOL]->GetNodes()); const auto* turbNodes = solver_container[TURB_SOL]->GetNodes(); @@ -732,6 +734,25 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF vector table_sources(flamelet_config_options.n_control_vars + 2 * flamelet_config_options.n_user_scalars); unsigned long misses = fluid_model_local->EvaluateDataSet(scalars, FLAMELET_LOOKUP_OPS::SOURCES, table_sources); + nodes->SetTableMisses(iPoint, misses); + + /*--- Chemical variance source 2 (mean(phi S) - mean(phi) mean(S)), minus its value at zero variance. + * That value is zero exactly, but not after interpolation of the manifold. ---*/ + if (!variance_sources.empty()) { + const bool tabulated = flamelet_config_options.tabulated_variance_source; + auto variance_source = [&](const vector& sources, const pair& var_mean) { + if (tabulated) return sources[var_mean.first]; + return 2.0 * (sources[var_mean.first] - scalars[var_mean.second] * sources[var_mean.second]); + }; + vector scalars_zero(scalars), sources_zero(table_sources.size()); + for (const auto& var_mean : variance_sources) { + scalars_zero[var_mean.first] = 0.0; + fluid_model_local->EvaluateDataSet(scalars_zero, FLAMELET_LOOKUP_OPS::SOURCES, sources_zero); + scalars_zero[var_mean.first] = scalars[var_mean.first]; + table_sources[var_mean.first] = variance_source(table_sources, var_mean) - variance_source(sources_zero, var_mean); + } + } + /*--- The source term for progress variable is always positive, we clip from below to make sure. --- */ if (idx_progvar >= 0) table_sources[idx_progvar] = fmax(0, table_sources[idx_progvar]); @@ -739,13 +760,6 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF if (idx_progvar >= 0 && config->GetKind_TimeIntScheme_Species() == EULER_IMPLICIT) progvar_source_slope[iPoint] = F * fluid_model_local->GetProgVarSourceJacobian(scalars); - /*--- Variance source 2 (mean(phi S) - mean(phi) mean(S)), from mean(phi S) unless the manifold holds it. ---*/ - if (!flamelet_config_options.tabulated_variance_source) - for (const auto& var_mean : variance_sources) - table_sources[var_mean.first] = - 2.0 * (table_sources[var_mean.first] - scalars[var_mean.second] * table_sources[var_mean.second]); - nodes->SetTableMisses(iPoint, misses); - vector source_scalar(flamelet_config_options.n_scalars); for (auto iCV = 0u; iCV < flamelet_config_options.n_control_vars; iCV++) source_scalar[iCV] = table_sources[iCV]; @@ -849,7 +863,7 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode if (static_cast(i_cv) == idx_enth) d_state += beta_scalar[I_BETA_ENTH_THERMAL] * (temperature_plus - temperature_minus) / span; value = d_state - ((i_cv == j_cv) ? unity_lewis_part : 0.0); - /*--- The total diagonal, ordinary diffusion included, is kept positive. ---*/ + /*--- The total diagonal, ordinary diffusion included, keeps at least a tenth of the ordinary one. ---*/ if (i_cv == j_cv) value = max(value, su2double(-0.9)); } nodes->SetPrefDiffJacobian(iPoint, i_cv * n_cv + j_cv, value); diff --git a/UnitTests/Common/containers/CLookupTable_tests.cpp b/UnitTests/Common/containers/CLookupTable_tests.cpp index e51a6551eb7e..38a9caefee0a 100644 --- a/UnitTests/Common/containers/CLookupTable_tests.cpp +++ b/UnitTests/Common/containers/CLookupTable_tests.cpp @@ -136,3 +136,32 @@ TEST_CASE("LUTreader_3D", "[tabulated chemistry]") { look_up_table.LookUp_XYZ(idx_tag, &look_up_dat, prog, enth, mfrac); CHECK(look_up_dat == Approx(1.1738796125)); } + +TEST_CASE("LUT_range_CV1", "[tabulated chemistry]") { + /*--- Level 0 has a right edge x = 1 for y < 0 that leans to x = 0.5 at y = 1, level 1 spans x in [0, 2]. ---*/ + + CLookUpTable look_up_table("src/SU2/UnitTests/Common/containers/lookuptable_range.drg", "ProgressVariable", + "EnthalpyTot"); + + const auto range_x = look_up_table.GetRangeCV(0); + const auto range_y = look_up_table.GetRangeCV(1); + const auto range_z = look_up_table.GetRangeCV(2); + CHECK(SU2_TYPE::GetValue(range_x.first) == Approx(0.0)); + CHECK(SU2_TYPE::GetValue(range_x.second) == Approx(2.0)); + CHECK(SU2_TYPE::GetValue(range_y.first) == Approx(-1.0)); + CHECK(SU2_TYPE::GetValue(range_y.second) == Approx(1.0)); + CHECK(SU2_TYPE::GetValue(range_z.first) == Approx(0.0)); + CHECK(SU2_TYPE::GetValue(range_z.second) == Approx(1.0)); + + /*--- Halfway between the levels the query x maps to x/1.5 on level 0 and 2x/1.5 on level 1, and the + * range is the part covered by both levels. ---*/ + + su2double val_min, val_max; + REQUIRE(look_up_table.GetRangeCV1(-0.5, 0.5, val_min, val_max)); + CHECK(SU2_TYPE::GetValue(val_min) == Approx(0.0).margin(1e-12)); + CHECK(SU2_TYPE::GetValue(val_max) == Approx(1.5)); + + REQUIRE(look_up_table.GetRangeCV1(0.5, 0.5, val_min, val_max)); + CHECK(SU2_TYPE::GetValue(val_min) == Approx(0.0).margin(1e-12)); + CHECK(SU2_TYPE::GetValue(val_max) == Approx(0.75 * 1.5)); +} diff --git a/UnitTests/Common/containers/lookuptable_range.drg b/UnitTests/Common/containers/lookuptable_range.drg new file mode 100644 index 000000000000..45244645d191 --- /dev/null +++ b/UnitTests/Common/containers/lookuptable_range.drg @@ -0,0 +1,89 @@ +Dragon library + +
+[Version] +1.1.0 + +[Number of table levels] +2 + +[Number of points] +5 +4 + +[Number of triangles] +3 +2 + +[Number of hull points] +5 +4 + +[Progress variable definition] +prog var = 1*Y-CH4 + +[Progress variable range] +0.0 | 1.0 +0.0 | 2.0 + +[Enthalpy range] +-1.0 | 1.0 +-1.0 | 1.0 + +[Table levels] +0.0 +1.0 + +[Number of variables] +3 + +[Variable names] +1:ProgressVariable +2:EnthalpyTot +3:Density + +
+ + + +0.0 -1.0 1.0 +1.0 -1.0 1.0 +1.0 0.0 1.0 +0.5 1.0 1.0 +0.0 1.0 1.0 + + +0.0 -1.0 1.0 +2.0 -1.0 1.0 +2.0 1.0 1.0 +0.0 1.0 1.0 + + + + + +1 2 3 +1 3 4 +1 4 5 + + +1 2 3 +1 3 4 + + + + + +1 +2 +3 +4 +5 + + +1 +2 +3 +4 + + diff --git a/config_template.cfg b/config_template.cfg index 3cbbed1de2de..d3bdaf4347ef 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -1057,7 +1057,8 @@ CONTROLLING_VARIABLE_NAMES= (ProgressVariable, EnthalpyTot) % controlling variables without source terms, use "zero" or "null", similar to the % option USER_SOURCE_NAMES. For a variance, the variable is the mean of phi*S_phi, with % S_phi the source of its mean phi; the chemical source of the variance is -% 2 (mean(phi*S_phi) - mean(phi) mean(S_phi)), or zero for NULL. +% 2 (mean(phi*S_phi) - mean(phi) mean(S_phi)), or zero for NULL. Its value at zero variance, +% which is zero but for the interpolation error of the manifold, is subtracted. CONTROLLING_VARIABLE_SOURCE_NAMES= (ProdRateTot_PV, NULL) % Method used to ignite the solution: From ff86d5dac01cf211a3ec5c52b724023e549c428b Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 16:09:41 +0100 Subject: [PATCH 39/40] Fix the reverse mode AD build of the scalar time step and the variance source Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/include/solvers/CScalarSolver.inl | 2 +- SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/SU2_CFD/include/solvers/CScalarSolver.inl b/SU2_CFD/include/solvers/CScalarSolver.inl index 2986a6fa5ae6..9a7a5232d4d8 100644 --- a/SU2_CFD/include/solvers/CScalarSolver.inl +++ b/SU2_CFD/include/solvers/CScalarSolver.inl @@ -515,7 +515,7 @@ void CScalarSolver::SetTime_Step(CGeometry *geometry, CSolver **so const su2double cfl = nodes->GetLocalCFL(iPoint); const su2double dt_conv = cfl * vol / max(lambda_conv, EPS); const su2double dt_visc = cfl * 0.25 * vol * vol / max(flowNodes->GetMax_Lambda_Visc(iPoint), EPS); - dt = min({dt_conv, dt_visc, max_ratio * dt}); + dt = min({dt_conv, dt_visc, su2double(max_ratio * dt)}); } nodes->SetDelta_Time(iPoint, dt); } diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 796d7fe8e036..8cbb21c5c95a 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -740,7 +740,7 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF * That value is zero exactly, but not after interpolation of the manifold. ---*/ if (!variance_sources.empty()) { const bool tabulated = flamelet_config_options.tabulated_variance_source; - auto variance_source = [&](const vector& sources, const pair& var_mean) { + auto variance_source = [&](const vector& sources, const pair& var_mean) -> su2double { if (tabulated) return sources[var_mean.first]; return 2.0 * (sources[var_mean.first] - scalars[var_mean.second] * sources[var_mean.second]); }; From c23943ba440b064c192ab526db8d5f17fde4702e Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 16:28:28 +0100 Subject: [PATCH 40/40] Update flamelet regression values after the table-range and preferential diffusion changes Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression.py | 14 +++++++------- TestCases/tutorials.py | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index d9f5370b8b5a..54fc876110fb 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -69,7 +69,7 @@ def main(): cfd_flamelet_ch4.cfg_dir = "flamelet/01_laminar_premixed_ch4_flame_cfd" cfd_flamelet_ch4.cfg_file = "lam_prem_ch4_cfd.cfg" cfd_flamelet_ch4.test_iter = 10 - cfd_flamelet_ch4.test_vals = [-10.539588, -12.650786, -5.649832, -13.470491, -17.249262, 94.854000] + cfd_flamelet_ch4.test_vals = [-10.539588, -12.650796, -5.649832, -13.470508, -17.249270, 94.854000] cfd_flamelet_ch4.new_output = True test_list.append(cfd_flamelet_ch4) @@ -78,7 +78,7 @@ def main(): cfd_flamelet_ch4_axi.cfg_dir = "flamelet/05_laminar_premixed_ch4_flame_cfd_axi" cfd_flamelet_ch4_axi.cfg_file = "lam_prem_ch4_cfd_axi.cfg" cfd_flamelet_ch4_axi.test_iter = 10 - cfd_flamelet_ch4_axi.test_vals = [-9.774148, -11.256092, -10.017960, -11.850827, -4.916267, 72.669000] + cfd_flamelet_ch4_axi.test_vals = [-9.774149, -11.256095, -10.017959, -11.850546, -4.916270, 72.669000] cfd_flamelet_ch4_axi.new_output = True test_list.append(cfd_flamelet_ch4_axi) @@ -88,7 +88,7 @@ def main(): cfd_flamelet_ch4_partial_premix.cfg_dir = "flamelet/06_laminar_partial_premixed_ch4_flame_cfd" cfd_flamelet_ch4_partial_premix.cfg_file = "lam_partial_prem_ch4_cfd.cfg" cfd_flamelet_ch4_partial_premix.test_iter = 10 - cfd_flamelet_ch4_partial_premix.test_vals = [-10.482722, -3.621055, -12.932224, -10.154391, 10.000000] + cfd_flamelet_ch4_partial_premix.test_vals = [-10.482684, -3.621055, -12.932224, -10.154389, 10.000000] cfd_flamelet_ch4_partial_premix.new_output = True test_list.append(cfd_flamelet_ch4_partial_premix) @@ -97,7 +97,7 @@ def main(): cfd_flamelet_h2.cfg_dir = "flamelet/07_laminar_premixed_h2_flame_cfd" cfd_flamelet_h2.cfg_file = "laminar_premixed_h2_flame_cfd.cfg" cfd_flamelet_h2.test_iter = 5 - cfd_flamelet_h2.test_vals = [-8.036799, -8.329782, -1.805324, -8.959656] + cfd_flamelet_h2.test_vals = [-8.036773, -8.366862, -1.872906, -9.961343] test_list.append(cfd_flamelet_h2) # Flame ignition methods @@ -105,7 +105,7 @@ def main(): flame_init_methods.cfg_dir = "flamelet/08_flame_init_method" flame_init_methods.cfg_file ="flamelet_initialization.py" flame_init_methods.command = TestCase.Command("mpirun -np 2", "python", "flamelet_initialization.py") - flame_init_methods.test_vals=[1600, 1600] + flame_init_methods.test_vals=[1600, 1546.23] flame_init_methods.new_output = True test_list.append(flame_init_methods) @@ -114,7 +114,7 @@ def main(): cfd_flamelet_ch4_unsteady.cfg_dir = "flamelet/09_laminar_premixed_ch4_flame_unsteady" cfd_flamelet_ch4_unsteady.cfg_file = "lam_prem_ch4_unsteady.cfg" cfd_flamelet_ch4_unsteady.test_iter = 5 - cfd_flamelet_ch4_unsteady.test_vals = [-8.856677, -8.095263, -9.153743, -9.321676] + cfd_flamelet_ch4_unsteady.test_vals = [-8.853321, -8.095207, -9.153687, -9.321693] cfd_flamelet_ch4_unsteady.test_vals_aarch64 = [-8.855500, -8.095195, -9.153704, -9.321686] test_list.append(cfd_flamelet_ch4_unsteady) @@ -2164,7 +2164,7 @@ def main(): cfd_flamelet_ch4_cht.cfg_dir = "flamelet/03_laminar_premixed_ch4_flame_cht_cfd" cfd_flamelet_ch4_cht.cfg_file = "lam_prem_ch4_cht_cfd_master.cfg" cfd_flamelet_ch4_cht.test_iter = 5 - cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410156, -3.171365, -10.884424, -12.615132, -6.614396] + cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410206, -3.171365, -10.884554, -12.615132, -6.614395] cfd_flamelet_ch4_cht.timeout = 1600 cfd_flamelet_ch4_cht.multizone = True test_list.append(cfd_flamelet_ch4_cht) diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index e34b59eabbed..af75de193eb4 100644 --- a/TestCases/tutorials.py +++ b/TestCases/tutorials.py @@ -177,7 +177,7 @@ def main(): premixed_hydrogen.cfg_dir = "../Tutorials/incompressible_flow/Inc_Combustion/1__premixed_hydrogen" premixed_hydrogen.cfg_file = "H2_burner.cfg" premixed_hydrogen.test_iter = 10 - premixed_hydrogen.test_vals = [-8.769581, -9.719802, -10.162061, -3.439369, -11.529638] + premixed_hydrogen.test_vals = [-8.769700, -9.720819, -10.302361, -3.752816, -12.001938] test_list.append(premixed_hydrogen) ### Compressible Flow