diff --git a/Common/include/CConfig.hpp b/Common/include/CConfig.hpp index 99078f030608..3194d3adb82f 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. */ @@ -895,6 +896,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). */ @@ -1780,6 +1782,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 @@ -7456,6 +7464,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 e455dd1f12d1..625688c218e9 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,19 @@ class CLookUpTable { */ void IdentifyUniqueEdges(); + /*! + * \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(); + + /*! + * \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. @@ -272,6 +291,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. @@ -296,6 +324,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. */ @@ -386,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/include/option_structure.hpp b/Common/include/option_structure.hpp index 8c6476d92125..151944993f1e 100644 --- a/Common/include/option_structure.hpp +++ b/Common/include/option_structure.hpp @@ -1525,14 +1525,23 @@ 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. + */ +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"; +} + +/*! + * \brief Manifold variables giving the range of the progress variable, the support of its PDF. */ -enum FLAMELET_SCALAR_VARIABLES { - I_PROGVAR, - I_ENTH, - I_MIXFRAC, -}; +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 @@ -1549,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. */ }; /*! @@ -1607,6 +1617,13 @@ 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. */ + 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. */ @@ -1621,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 c6480a2464cc..b39ee48361d7 100644 --- a/Common/src/CConfig.cpp +++ b/Common/src/CConfig.cpp @@ -1452,6 +1452,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*/ @@ -1534,6 +1536,11 @@ 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); + /*!\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. ---*/ /*!\brief DIFFUSIVITY_MODEL\n DESCRIPTION: mass diffusivity model \n DEFAULT constant disffusivity \ingroup Config*/ @@ -1956,6 +1963,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 @@ -2421,6 +2431,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")); @@ -6285,6 +6298,57 @@ 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 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 + ", " + 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); + *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 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)) + 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); + disable_thickened_flame("with scalar variance transport"); + } + /*--- 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/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 05586d39585c..13d554acd822 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,109 @@ 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::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 ---*/ @@ -438,6 +544,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 +573,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; diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index e59d176eeacc..7d05cdb32de8 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. */ @@ -68,7 +67,23 @@ 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. */ + 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 @@ -78,7 +93,8 @@ 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. */ + MLPToolbox::CIOMap* iomap_SourceJacobian; /*!< \brief Input-output map for the progress variable source Jacobian. */ #endif vector scalars_vector; @@ -86,15 +102,44 @@ 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 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*). */ + + 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). */ @@ -135,6 +180,27 @@ class CFluidFlamelet final : public CFluidModel { unsigned long EvaluateDataSet(const vector& input_scalar, unsigned short lookup_type, vector& output_refs); + /*! + * \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. + */ + 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 Derivative of the progress variable source at constant normalized variance, zero where it is clipped. + * \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; + /*! * \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..b0f97c8b5947 100644 --- a/SU2_CFD/include/fluid/CFluidModel.hpp +++ b/SU2_CFD/include/fluid/CFluidModel.hpp @@ -161,6 +161,28 @@ class CFluidModel { return 0; } + /*! + * \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 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 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/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index dba70c948816..a655fe68354b 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -50,15 +50,18 @@ class CScalarFlux_Flamelet final explicit CScalarFlux_Flamelet(const CConfig& config) : Base(config), preferentialDiffusion(config.GetFlameletParsedOptions().preferential_diffusion), - nControlVars(config.GetFlameletParsedOptions().n_control_vars) {} + 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) {} /*! * \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. + * 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. */ template FORCEINLINE void extraDiffusionTerms(const FlowIndices& idx, const ScalarFluxOptions& opt, Int iPoint, @@ -81,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); @@ -104,18 +107,21 @@ 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; + } } } } /*--- 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 +129,30 @@ 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 su2double unityLewisPart; /*!< \brief 1 when beta holds the full scalar, 0 when it holds the excess. */ 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/CScalarSolver.inl b/SU2_CFD/include/solvers/CScalarSolver.inl index 041730ba8029..9a7a5232d4d8 100644 --- a/SU2_CFD/include/solvers/CScalarSolver.inl +++ b/SU2_CFD/include/solvers/CScalarSolver.inl @@ -489,9 +489,34 @@ 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. + * 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++) { + 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) + 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); + dt = min({dt_conv, dt_visc, su2double(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 7543d6d7f282..d4ba2597994e 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -41,10 +41,32 @@ 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. */ + 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; + 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 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; + /*! * \brief Compute the preconditioner for low-Mach flows. * \param[in] geometry - Geometrical definition of the problem. @@ -53,6 +75,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. @@ -105,7 +136,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/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 f142da539175..1cf4dd16313d 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" @@ -44,7 +45,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) { @@ -53,6 +53,8 @@ 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); + bounds_key.resize(n_control_vars); table_scalar_names.resize(n_scalars); for (auto iCV = 0u; iCV < n_control_vars; iCV++) @@ -73,13 +75,15 @@ 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; 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: @@ -116,13 +120,15 @@ CFluidFlamelet::~CFluidFlamelet() { delete iomap_LookUp; 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 } 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 +143,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,16 +222,37 @@ 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"; - 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"; + /*--- Beta scalars of absent controlling variables are not in the manifold. ---*/ + 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; 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()); + } + + /*--- 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) @@ -238,12 +265,22 @@ 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); + } + 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++) { @@ -268,76 +305,251 @@ 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])); } } + /*--- 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)); + /*--- When the progress variable is the first table axis, the table edge also bounds it. ---*/ + progvar_range_from_table = (flamelet_options.idx_progvar == 0); + } } } -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]); +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); +} + +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; +} + +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 - 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 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); + 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]; + + /*--- 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, 1.0); + } + + /*--- 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; + 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; + }; - 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; - vector val_vars; - vector refs_vars; - vector LUT_idx; + 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; + 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]); + } + /*--- 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 { + 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; +#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); - if (include_mixture_fraction) { - inside = look_up_table->LookUp_XYZ(LUT_idx, output_refs, val_prog, val_enth, val_mixfrac); + /*--- 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, inputs[0], inputs[1], inputs[2]); } 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, 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; + 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]); AD::EndPreacc(); return extrapolation; diff --git a/SU2_CFD/src/solvers/CIncEulerSolver.cpp b/SU2_CFD/src/solvers/CIncEulerSolver.cpp index 046d4bc4037b..4ee7e4a9ef8a 100644 --- a/SU2_CFD/src/solvers/CIncEulerSolver.cpp +++ b/SU2_CFD/src/solvers/CIncEulerSolver.cpp @@ -2250,11 +2250,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/CSolver.cpp b/SU2_CFD/src/solvers/CSolver.cpp index 2ec8eae60279..717579d032c5 100644 --- a/SU2_CFD/src/solvers/CSolver.cpp +++ b/SU2_CFD/src/solvers/CSolver.cpp @@ -4166,9 +4166,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..8cbb21c5c95a 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -48,14 +48,29 @@ 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); + /*--- 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)); + + 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); SetBaseClassPointerToNodes(); + progvar_source_slope.assign(nPoint, 0.0); /*--- Store the initial CFL number for all grid points. ---*/ @@ -90,6 +105,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, @@ -214,7 +235,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 +275,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 +298,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); @@ -419,6 +440,25 @@ 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 + + const int variances[] = {flamelet_config_options.idx_progvar_var, flamelet_config_options.idx_mixfrac_var}; + if (variances[0] < 0 && variances[1] < 0) return; + + SU2_OMP_FOR_STAT(omp_chunk_size) + for (auto i_point = 0u; i_point < nPoint; i_point++) { + 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 +} + void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solver_container, CNumerics** numerics_container, CConfig* config, unsigned short iMesh) { SU2_ZONE_SCOPED @@ -427,33 +467,80 @@ 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++) { 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/dY_aux_i = source_cons_i - * J_ii += -source_cons_i * 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) * volume); + Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) / density * volume); } } } 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; + 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(); + + 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); + + /*--- 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 +} + void CSpeciesFlameletSolver::BC_HeatFlux_Wall(CGeometry* geometry, CSolver** solver_container, CNumerics* conv_numerics, CNumerics* visc_numerics, CConfig* config, unsigned short val_marker) { @@ -490,7 +577,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 } @@ -500,6 +587,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. @@ -511,12 +604,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 +643,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 +652,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 +690,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 +734,31 @@ 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); + /*--- 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) -> su2double { + 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]); + + /*--- 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); 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]; @@ -696,9 +810,92 @@ 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()); + + /*--- 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; + 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) ? 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) ? unity_lewis_part : 0.0); + /*--- 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); + } + } + 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 @@ -715,7 +912,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 +927,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(); @@ -757,15 +954,40 @@ 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[idx_flame_front] = pv; fluid_model->SetTDState_T(300.0, scalars); - if ((fluid_model->GetExtrapolation() == 1) || fluid_model->GetTemperature() > T_ignition) outside = true; - scalars[I_PROGVAR] += delta; + 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. ---*/ + 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[I_PROGVAR] - 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; @@ -800,13 +1022,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/SU2_CFD/src/solvers/CSpeciesSolver.cpp b/SU2_CFD/src/solvers/CSpeciesSolver.cpp index 00908f681403..13676acd1249 100644 --- a/SU2_CFD/src/solvers/CSpeciesSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesSolver.cpp @@ -242,6 +242,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; @@ -255,9 +285,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/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index fabe59a038aa..5d965127203b 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -59,5 +59,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); } } 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..c62a2c27d54d 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,24 @@ 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 +214,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 +352,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 +375,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 +393,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 +483,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 +501,38 @@ 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 +621,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 +636,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 +679,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 +690,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 +739,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..94defc541750 100644 --- a/SU2_PY/tests/test_monitor.py +++ b/SU2_PY/tests/test_monitor.py @@ -64,11 +64,45 @@ 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 +114,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 +136,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)) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index e2f767f8831a..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.884464, -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 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 951e5e6cbfcb..d3bdaf4347ef 100644 --- a/config_template.cfg +++ b/config_template.cfg @@ -356,6 +356,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 ---------------% % @@ -952,6 +956,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 % @@ -1033,12 +1041,24 @@ 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, +% 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 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. 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: @@ -1060,6 +1080,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 @@ -1099,6 +1123,14 @@ 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 +% +% 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.