From 8bd6c746b6d80366615287558e6360aaf55b7fb9 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 19 Nov 2026 17:53:50 +0100 Subject: [PATCH 01/16] Implicit progress variable source Jacobian for flamelet solver The progress variable source was treated fully explicitly, which stalls the PV equation at high CFL. Add the decreasing part of dS/dPV, obtained from a forward-difference table lookup, to the Jacobian diagonal. With CFL 1e5, an ILU preconditioner and a consistent table, the unsteady 1D premixed flame converges in 8-10 inner iterations per time step and matches a 300-inner-iteration reference. Flamelet regression residuals shift slightly; reference values are not yet updated. Co-Authored-By: Claude Opus 5.5 --- .../variables/CSpeciesFlameletVariable.hpp | 11 +++++++++++ SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 17 ++++++++++++++++- .../src/variables/CSpeciesFlameletVariable.cpp | 1 + 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp b/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp index 6a8b21969f12..a7a4b0f98842 100644 --- a/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp +++ b/SU2_CFD/include/variables/CSpeciesFlameletVariable.hpp @@ -39,6 +39,7 @@ class CSpeciesFlameletVariable final : public CSpeciesVariable { MatrixType lookup_scalar; /*!< \brief Vector of the source terms from the lookup table for each scalar equation */ su2vector table_misses; /*!< \brief Vector of lookup table misses. */ MatrixType source_cons_jac; /*!< \brief Consumption-rate Jacobian dS_aux_i/dY_aux_i = source_cons_i, one column per user scalar. */ + VectorType source_pv_jac; /*!< \brief Derivative of the progress variable source with respect to the progress variable. */ public: /*! @@ -102,4 +103,14 @@ class CSpeciesFlameletVariable final : public CSpeciesVariable { inline su2double GetAuxSourceCons(unsigned long iPoint, unsigned long i_aux) const { return source_cons_jac(iPoint, i_aux); } + + /*! + * \brief Store the derivative of the progress variable source with respect to the progress variable. + */ + inline void SetSourceJacobianPV(unsigned long iPoint, su2double val) { source_pv_jac(iPoint) = val; } + + /*! + * \brief Get the derivative of the progress variable source with respect to the progress variable. + */ + inline su2double GetSourceJacobianPV(unsigned long iPoint) const { return source_pv_jac(iPoint); } }; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 9fdf81663b4e..5a0f0c753577 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -440,8 +440,12 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv /*--- Implicit: analytic Jacobian for auxiliary species from the split source form. * S_aux_i = source_prod_i + source_cons_i * Y_aux_i * dS_aux_i/dY_aux_i = source_cons_i - * J_ii += -source_cons_i * V ---*/ + * J_ii += -source_cons_i * V + * The progress variable gets the decreasing part of its source, per unit of rho*PV. ---*/ if (implicit) { + const su2double density = solver_container[FLOW_SOL]->GetNodes()->GetDensity(i_point); + const su2double dsource_dpv = fn->GetSourceJacobianPV(i_point); + Jacobian.AddVal2Diag(i_point, I_PROGVAR, fmax(0.0, -dsource_dpv) / density * volume); for (auto i_aux = 0u; i_aux < n_aux; i_aux++) { Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) * volume); } @@ -649,6 +653,17 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF vector source_scalar(flamelet_config_options.n_scalars); for (auto iCV = 0u; iCV < flamelet_config_options.n_control_vars; iCV++) source_scalar[iCV] = table_sources[iCV]; + /*--- Forward difference of the progress variable source, used only by the implicit Jacobian. ---*/ + if ((config->GetKind_TimeIntScheme() == EULER_IMPLICIT) && !AD::TapeActive()) { + const su2double delta = 1e-6; + vector scalars_pert = scalars; + scalars_pert[I_PROGVAR] += delta; + vector sources_pert(table_sources.size()); + fluid_model_local->EvaluateDataSet(scalars_pert, FLAMELET_LOOKUP_OPS::SOURCES, sources_pert); + const su2double dsource = (fmax(0, sources_pert[I_PROGVAR]) - table_sources[I_PROGVAR]) / delta; + static_cast(nodes)->SetSourceJacobianPV(iPoint, F * dsource); + } + /*--- Source term for the auxiliary species transport equations. ---*/ for (size_t i_aux = 0; i_aux < flamelet_config_options.n_user_scalars; i_aux++) { /*--- The source term for the auxiliary equations consists of a production term and a consumption term: diff --git a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index fabe59a038aa..46028e30bf12 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -54,6 +54,7 @@ CSpeciesFlameletVariable::CSpeciesFlameletVariable(const su2double* species_inf, lookup_scalar.resize(nPoint, flamelet_config_options.n_lookups) = su2double(0.0); table_misses.resize(nPoint) = 0; source_cons_jac.resize(nPoint, flamelet_config_options.n_user_scalars) = su2double(0.0); + source_pv_jac.resize(nPoint) = su2double(0.0); if (flamelet_config_options.preferential_diffusion) { nAuxVar = FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS; From b1387fae08045ca1e8bd4f7c29bff64ec961e580 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 19 Nov 2026 23:21:08 +0100 Subject: [PATCH 02/16] Update flamelet regression values for the implicit PV source Jacobian The extra Jacobian term changes the iteration history of the flamelet tests. The discrete adjoint tests change because the adjoint linear solves reuse the primal Jacobian; the converged adjoint is unchanged. Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression.py | 14 +++++++------- TestCases/parallel_regression_AD.py | 4 ++-- TestCases/tutorials.py | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 8b40bc4bc35f..6d982c5ec9ac 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -69,7 +69,7 @@ def main(): cfd_flamelet_ch4.cfg_dir = "flamelet/01_laminar_premixed_ch4_flame_cfd" cfd_flamelet_ch4.cfg_file = "lam_prem_ch4_cfd.cfg" cfd_flamelet_ch4.test_iter = 10 - cfd_flamelet_ch4.test_vals = [-10.539588, -12.650786, -5.649832, -13.470491, -17.249262, 94.854000] + cfd_flamelet_ch4.test_vals = [-10.539588, -12.650795, -5.649832, -13.470506, -17.249269, 94.854000] cfd_flamelet_ch4.new_output = True test_list.append(cfd_flamelet_ch4) @@ -78,7 +78,7 @@ def main(): cfd_flamelet_ch4_axi.cfg_dir = "flamelet/05_laminar_premixed_ch4_flame_cfd_axi" cfd_flamelet_ch4_axi.cfg_file = "lam_prem_ch4_cfd_axi.cfg" cfd_flamelet_ch4_axi.test_iter = 10 - cfd_flamelet_ch4_axi.test_vals = [-9.774148, -11.256092, -10.017960, -11.850827, -4.916267, 72.669000] + cfd_flamelet_ch4_axi.test_vals = [-9.774149, -11.256095, -10.017959, -11.850546, -4.916270, 72.669000] cfd_flamelet_ch4_axi.new_output = True test_list.append(cfd_flamelet_ch4_axi) @@ -88,7 +88,7 @@ def main(): cfd_flamelet_ch4_partial_premix.cfg_dir = "flamelet/06_laminar_partial_premixed_ch4_flame_cfd" cfd_flamelet_ch4_partial_premix.cfg_file = "lam_partial_prem_ch4_cfd.cfg" cfd_flamelet_ch4_partial_premix.test_iter = 10 - cfd_flamelet_ch4_partial_premix.test_vals = [-10.482722, -3.621055, -12.932224, -10.154391, 10.000000] + cfd_flamelet_ch4_partial_premix.test_vals = [-10.482684, -3.621055, -12.932224, -10.154389, 10.000000] cfd_flamelet_ch4_partial_premix.new_output = True test_list.append(cfd_flamelet_ch4_partial_premix) @@ -97,7 +97,7 @@ def main(): cfd_flamelet_h2.cfg_dir = "flamelet/07_laminar_premixed_h2_flame_cfd" cfd_flamelet_h2.cfg_file = "laminar_premixed_h2_flame_cfd.cfg" cfd_flamelet_h2.test_iter = 5 - cfd_flamelet_h2.test_vals = [-8.036799, -8.329782, -1.805324, -8.959656] + cfd_flamelet_h2.test_vals = [-8.036810, -8.328814, -1.805276, -8.959649] test_list.append(cfd_flamelet_h2) # Flame ignition methods @@ -105,7 +105,7 @@ def main(): flame_init_methods.cfg_dir = "flamelet/08_flame_init_method" flame_init_methods.cfg_file ="flamelet_initialization.py" flame_init_methods.command = TestCase.Command("mpirun -np 2", "python", "flamelet_initialization.py") - flame_init_methods.test_vals=[1600, 1600] + flame_init_methods.test_vals=[1600, 1595.82] flame_init_methods.new_output = True test_list.append(flame_init_methods) @@ -114,7 +114,7 @@ def main(): cfd_flamelet_ch4_unsteady.cfg_dir = "flamelet/09_laminar_premixed_ch4_flame_unsteady" cfd_flamelet_ch4_unsteady.cfg_file = "lam_prem_ch4_unsteady.cfg" cfd_flamelet_ch4_unsteady.test_iter = 5 - cfd_flamelet_ch4_unsteady.test_vals = [-8.856677, -8.095263, -9.153743, -9.321676] + cfd_flamelet_ch4_unsteady.test_vals = [-8.853384, -8.095207, -9.153687, -9.321693] cfd_flamelet_ch4_unsteady.test_vals_aarch64 = [-8.855500, -8.095195, -9.153704, -9.321686] test_list.append(cfd_flamelet_ch4_unsteady) @@ -2088,7 +2088,7 @@ def main(): cfd_flamelet_ch4_cht.cfg_dir = "flamelet/03_laminar_premixed_ch4_flame_cht_cfd" cfd_flamelet_ch4_cht.cfg_file = "lam_prem_ch4_cht_cfd_master.cfg" cfd_flamelet_ch4_cht.test_iter = 5 - cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410156, -3.171365, -10.884464, -12.615132, -6.614396] + cfd_flamelet_ch4_cht.test_vals = [-7.223149, -6.338839, -8.334392, -10.410206, -3.171365, -10.884587, -12.615132, -6.614396] cfd_flamelet_ch4_cht.timeout = 1600 cfd_flamelet_ch4_cht.multizone = True test_list.append(cfd_flamelet_ch4_cht) diff --git a/TestCases/parallel_regression_AD.py b/TestCases/parallel_regression_AD.py index c180caf45f40..891557a0bf1e 100644 --- a/TestCases/parallel_regression_AD.py +++ b/TestCases/parallel_regression_AD.py @@ -373,7 +373,7 @@ def main(): discadj_flamelet_ch4_hx.cfg_file = "lam_prem_ch4_hx_ad.cfg" discadj_flamelet_ch4_hx.multizone = False discadj_flamelet_ch4_hx.test_iter = 10 - discadj_flamelet_ch4_hx.test_vals = [-9.083502, -9.033520, -9.529644, -8.442386, -15.399568, -6.169865, -18.881156] + discadj_flamelet_ch4_hx.test_vals = [-9.079012, -9.032987, -9.517245, -7.478949, -15.369708, -6.169865, -18.881156] test_list.append(discadj_flamelet_ch4_hx) # 2D planar laminar premixed flame on isothermal burner with conjugate heat transfer (restart) @@ -382,7 +382,7 @@ def main(): discadj_flamelet_ch4_cht.cfg_file = "lam_prem_ch4_cht_ad_master.cfg" discadj_flamelet_ch4_cht.multizone = True discadj_flamelet_ch4_cht.test_iter = 10 - discadj_flamelet_ch4_cht.test_vals = [-1.545058, 0.628666, -6.533534, -18.651078, -18.648552, -3.794724, -6.572494, 11.000000] + discadj_flamelet_ch4_cht.test_vals = [-1.545086, 0.628721, -6.533534, -18.651078, -18.648552, -3.794724, -6.572494, 11.000000] test_list.append(discadj_flamelet_ch4_cht) ###################################### diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index dd739f2e24d9..763f21e9ebd5 100644 --- a/TestCases/tutorials.py +++ b/TestCases/tutorials.py @@ -177,7 +177,7 @@ def main(): premixed_hydrogen.cfg_dir = "../Tutorials/incompressible_flow/Inc_Combustion/1__premixed_hydrogen" premixed_hydrogen.cfg_file = "H2_burner.cfg" premixed_hydrogen.test_iter = 10 - premixed_hydrogen.test_vals = [-8.769581, -9.719802, -10.162061, -3.439369, -11.529638] + premixed_hydrogen.test_vals = [-8.769564, -9.719765, -10.153710, -3.439336, -11.528098] test_list.append(premixed_hydrogen) ### Compressible Flow From 899ab149e8bd4440cae1abce6d355324a4ec9c13 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sat, 21 Nov 2026 11:50:07 +0100 Subject: [PATCH 03/16] update monitor for unsteady plotting --- SU2_PY/SU2_MON | 2 +- SU2_PY/monitor.py | 194 +++++++++++++++++++++++++++++------ SU2_PY/tests/test_monitor.py | 42 +++++++- 3 files changed, 199 insertions(+), 39 deletions(-) diff --git a/SU2_PY/SU2_MON b/SU2_PY/SU2_MON index 638e47ad3af2..4f4bc0f7076f 100755 --- a/SU2_PY/SU2_MON +++ b/SU2_PY/SU2_MON @@ -1,2 +1,2 @@ #!/bin/bash -cd "$(dirname "$(readlink -f "$0")")" && python monitor.py "$@" +exec python "$(dirname "$(readlink -f "$0")")/monitor.py" "$@" diff --git a/SU2_PY/monitor.py b/SU2_PY/monitor.py index 44347c116ace..6797a8b07b28 100755 --- a/SU2_PY/monitor.py +++ b/SU2_PY/monitor.py @@ -46,12 +46,15 @@ RESIDUAL_PATTERN = re.compile("rms|Res") COEFFICIENT_PATTERN = re.compile("^(CD|CL|CMx|CMy|CMz|CFx|CFy|CFz)$") -# inner counter: first of these present in the history, else the row index +# inner counter: first of these present in the history, else the row number from 1 ITERATION_COLUMNS = ("Inner_Iter", "Outer_Iter") +INNER_COLUMN = "Inner_Iter" +OUTER_COLUMN = "Outer_Iter" TIME_COLUMN = "Time_Iter" MAX_POINTS = 4000 READ_BLOCK_BYTES = 32 * 1024 * 1024 UPDATE_INTERVAL_MS = 1000 +INNER_TIP = "Plot every inner iteration, not only the last one of each step" LOGO_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logoSU2.png") @@ -84,10 +87,13 @@ def reset(self): self.cols = None self.iter_col = None self.time_col = None + self.outer_col = None + self.has_inner_col = False self.names = [] self.buf = np.empty((1024, 0)) self.iters = np.empty(1024) self.times = np.empty(1024) + self.outers = np.empty(1024) self.n = 0 self.version += 1 self.readHeader() @@ -124,9 +130,14 @@ def readHeader(self): self.iter_col = allnames.index(counter) break self.time_col = allnames.index(TIME_COLUMN) if TIME_COLUMN in allnames else None + self.outer_col = ( + allnames.index(OUTER_COLUMN) if OUTER_COLUMN in allnames else None + ) + self.has_inner_col = INNER_COLUMN in allnames self.buf = np.empty((1024, len(self.cols))) self.iters = np.empty(1024) self.times = np.empty(1024) + self.outers = np.empty(1024) self.offset = offset # reads the complete lines appended since the last call; returns True if rows were added @@ -155,7 +166,11 @@ def update(self): wanted = sorted( { *self.cols, - *(c for c in (self.iter_col, self.time_col) if c is not None), + *( + c + for c in (self.iter_col, self.time_col, self.outer_col) + if c is not None + ), } ) table = pd.read_csv( @@ -169,17 +184,22 @@ def update(self): iters = ( table[self.iter_col].to_numpy() if self.iter_col is not None - else np.arange(self.n, self.n + len(table), dtype=np.float64) + else np.arange(self.n + 1, self.n + len(table) + 1, dtype=np.float64) ) times = ( table[self.time_col].to_numpy() if self.time_col is not None else iters ) + outers = ( + table[self.outer_col].to_numpy() + if self.outer_col is not None + else iters + ) except (pd.errors.EmptyDataError, pd.errors.ParserError, ValueError): break self.offset += end + 1 - self.append(rows, iters, times) + self.append(rows, iters, times, outers) added = True if added: @@ -192,35 +212,98 @@ def hasTime(self): # True once Time_Iter takes more than one value, i.e. the history is unsteady def timeAdvances(self): times = self.times[: self.n] - return self.hasTime() and self.n > 0 and times.max() > times.min() - - # rows at or after iteration 'start', thinned to at most MAX_POINTS; - # by time step, only the last row of each Time_Iter is kept - def rowsFrom(self, start, byTime=False): - counter = self.times if byTime and self.hasTime() else self.iters - counter = counter[: self.n] - keep = counter >= start - if byTime and self.hasTime(): - keep[:-1] &= counter[1:] != counter[:-1] - rows = np.flatnonzero(keep) - return rows[:: max(1, -(-len(rows) // MAX_POINTS))] - - def append(self, rows, iters, times): + return bool(self.hasTime() and self.n > 0 and times.max() > times.min()) + + # counter that groups the inner iterations into steps: the first of Time_Iter and + # Outer_Iter that advances, else the first present; None without Inner_Iter + def stepCounter(self): + if not self.has_inner_col or self.n == 0: + return None + present = [] + if self.hasTime(): + present.append(self.times[: self.n]) + if self.outer_col is not None: + present.append(self.outers[: self.n]) + for steps in present: + if steps.max() > steps.min(): + return steps + return present[0] if present else None + + # True once the history holds more than one step + def stepsAdvance(self): + steps = self.stepCounter() + return steps is not None and bool(steps.max() > steps.min()) + + # True when some time step or outer iteration holds more than one row + def hasInnerRows(self): + steps = self.stepCounter() + return steps is not None and bool(np.any(steps[1:] == steps[:-1])) + + # first row, row count and value of every group of equal step counters + @staticmethod + def groups(steps): + starts = np.flatnonzero(np.r_[True, steps[1:] != steps[:-1]]) + counts = np.diff(np.r_[starts, len(steps)]) + return starts, counts, steps[starts] + + # inner iterations counted over all steps, assuming Inner_Iter restarts at 0 every step + def cumulativeInner(self, steps): + starts, counts, _ = self.groups(steps) + within = np.arange(self.n) - np.repeat(starts, counts) + if self.has_inner_col: + within = self.iters[: self.n] + lengths = within[starts + counts - 1] + 1 + else: + lengths = counts + offsets = np.r_[0, np.cumsum(lengths)[:-1]] + return np.repeat(offsets, counts) + within + + # time step plus the fraction of the step, so the last row of a step lands on Time_Iter + def fractionalTime(self, steps): + starts, counts, values = self.groups(steps) + span = counts.astype(np.float64) + if len(span) > 1: + span[-1] = max(span[-1], span[-2]) + within = np.arange(self.n) - np.repeat(starts, counts) + return np.repeat(values - 1, counts) + (within + 1) / np.repeat(span, counts) + + # rows whose x value, or time step when plotted by time, is at or after 'start', and + # their x values, thinned to MAX_POINTS; + # without 'inner' only the last row of each time step or outer iteration is kept + def select(self, start, byTime=False, inner=False): + byTime = byTime and self.hasTime() + steps = self.stepCounter() + keep = np.ones(self.n, dtype=bool) + first = None + if steps is None: + x = (self.times if byTime else self.iters)[: self.n] + if byTime: + keep[:-1] = x[1:] != x[:-1] + elif inner: + x = self.fractionalTime(steps) if byTime else self.cumulativeInner(steps) + first = steps if byTime else None + else: + keep[:-1] = steps[1:] != steps[:-1] + x = self.times[: self.n] if byTime else self.cumulativeInner(steps) + rows = np.flatnonzero(keep & ((x if first is None else first) >= start)) + rows = rows[:: max(1, -(-len(rows) // MAX_POINTS))] + return rows, x[rows] + + def append(self, rows, iters, times, outers): needed = self.n + len(rows) if needed > len(self.buf): size = max(needed, 2 * len(self.buf)) grown = np.empty((size, self.buf.shape[1])) grown[: self.n] = self.buf[: self.n] self.buf = grown - grownIters = np.empty(size) - grownIters[: self.n] = self.iters[: self.n] - self.iters = grownIters - grownTimes = np.empty(size) - grownTimes[: self.n] = self.times[: self.n] - self.times = grownTimes + for name in ("iters", "times", "outers"): + column = np.empty(size) + column[: self.n] = getattr(self, name)[: self.n] + setattr(self, name, column) self.buf[self.n : needed] = rows self.iters[self.n : needed] = iters self.times[self.n : needed] = times + self.outers[self.n : needed] = outers self.n = needed @@ -267,7 +350,17 @@ def names(self): return self.reader.names if self.reader is not None else [] # plots the residuals from iteration 'start' on; ymin/ymax of None means automatic range - def plot(self, listonoff, normalize, start, ymin, ymax, byTime=False, update=True): + def plot( + self, + listonoff, + normalize, + start, + ymin, + ymax, + byTime=False, + inner=False, + update=True, + ): if self.reader is None: return if update: @@ -280,6 +373,7 @@ def plot(self, listonoff, normalize, start, ymin, ymax, byTime=False, update=Tru ymin, ymax, byTime, + inner, self.reader.version, ) if key == self.lastkey: @@ -297,19 +391,20 @@ def plot(self, listonoff, normalize, start, ymin, ymax, byTime=False, update=Tru ax.set_ylabel(self.ylabel) self.lines = [ax.plot([], [], label=names[i])[0] for i in shown] - ax.set_xlabel( - "time iterations" if byTime and self.reader.hasTime() else "iterations" - ) + if byTime and self.reader.hasTime(): + ax.set_xlabel("time iterations") + elif self.reader.stepsAdvance(): + ax.set_xlabel("cumulative inner iterations") + else: + ax.set_xlabel("iterations") n = self.reader.n - rows = self.reader.rowsFrom(start, byTime) - x = ( - self.reader.times if byTime and self.reader.hasTime() else self.reader.iters - )[rows] + rows, x = self.reader.select(start, byTime, inner) for line, i in zip(self.lines, shown): y = self.reader.buf[rows, i] if normalize and n > 1 and abs(self.reader.buf[1, i]) > 1e-6: y = 1 + y - self.reader.buf[1, i] line.set_data(x, y) + line.set_marker("o" if len(x) == 1 else "None") ax.set_autoscaley_on(True) ax.relim() @@ -386,6 +481,7 @@ def __init__(self, owner, pattern, ylabel, title): self.normalize = False self.chkbx = [] self.chkbx_names = [] + self.inner_advance = False self.make_tab(title) def setFile(self, filename, label, tooltip): @@ -403,6 +499,29 @@ def updateTimeSwitch(self): self.btn_time.setEnabled(has) self.btn_time.setChecked(has) + # enabled when some step holds several inner rows; checked by default until a + # second step appears, the tooltip gives the reason when greyed out + def updateInnerSwitch(self): + reader = self.figure.reader + has = reader is not None and reader.hasInnerRows() + advance = reader is not None and reader.stepsAdvance() + if reader is None or has: + reason = INNER_TIP + elif not reader.has_inner_col: + reason = "Not available: no Inner_Iter column, add ITER to HISTORY_OUTPUT" + elif reader.stepCounter() is None: + reason = "Every row of the history is an inner iteration" + else: + reason = "Not available: one row per time step, set HISTORY_WRT_FREQ_INNER" + self.btn_inner.setToolTip(reason) + if has != self.btn_inner.isEnabled() or advance != self.inner_advance or not has: + self.btn_inner.setEnabled(has) + self.btn_inner.setChecked( + (has and not advance) + or (reader is not None and reader.has_inner_col and not has and not advance) + ) + self.inner_advance = advance + def setRunning(self, running): self.btn_plot_data.setText("stop" if running else "start") self.btn_plot_data.setToolTip( @@ -491,8 +610,14 @@ def make_tab(self, title): self.btn_time.setToolTip( "Plot against Time_Iter (last inner iteration of each step) instead of inner iterations" ) + self.btn_time.setEnabled(False) self.btn_time.stateChanged.connect(lambda _: self.changedata()) + self.btn_inner = QCheckBox("Inner iterations") + self.btn_inner.setToolTip(INNER_TIP) + self.btn_inner.setEnabled(False) + self.btn_inner.stateChanged.connect(lambda _: self.changedata()) + # now we add all the buttons in a vertical list self.btn_layout = QVBoxLayout() self.btn_layout.addWidget(self.btn_openfile) @@ -500,6 +625,7 @@ def make_tab(self, title): self.btn_layout.addWidget(self.btn_plot_data) self.btn_layout.addWidget(self.btn_normalize) self.btn_layout.addWidget(self.btn_time) + self.btn_layout.addWidget(self.btn_inner) self.btn_layout.addLayout(range_layout) self.btn_layout.addLayout(self.chk_layout) @@ -542,6 +668,7 @@ def draw(self, update): self.parse(self.edit_ymin, float), self.parse(self.edit_ymax, float), self.btn_time.isChecked(), + self.btn_inner.isChecked(), update=update, ) @@ -552,6 +679,7 @@ def plot_data(self): if self.figure.names() != self.chkbx_names: self.update_chkbx(self.figure.names()) self.updateTimeSwitch() + self.updateInnerSwitch() self.draw(update=False) # ################################### # @@ -600,7 +728,7 @@ def getfile(self): fname = QFileDialog.getOpenFileName( self, "Open file", - "history.csv", + os.path.join(os.getcwd(), "history.csv"), filter="csv files (*.csv)\n" "dat files (*.dat)\n" "all files (*)", ) if fname[0] == "": diff --git a/SU2_PY/tests/test_monitor.py b/SU2_PY/tests/test_monitor.py index e0c4fe81a550..74146a91f67f 100644 --- a/SU2_PY/tests/test_monitor.py +++ b/SU2_PY/tests/test_monitor.py @@ -64,11 +64,43 @@ def test_time_iterations(self): reader = self.reader(names + body) self.assertTrue(reader.hasTime()) np.testing.assert_array_equal(reader.iters[: reader.n][:5], [0, 1, 2, 3, 0]) - rows = reader.rowsFrom(1, byTime=True) - np.testing.assert_array_equal(reader.times[rows], [1, 2]) + rows, x = reader.select(1, byTime=True) + np.testing.assert_array_equal(x, [1, 2]) np.testing.assert_array_equal(reader.iters[rows], [3, 3]) self.assertFalse(self.reader(CSV + row(0) + row(1)).hasTime()) + def test_inner_iterations(self): + names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' + body = "".join( + f"{t}, {i}, {-t - 0.1 * i}\n" for t in range(3) for i in range(4) + ) + reader = self.reader(names + body) + self.assertTrue(reader.hasInnerRows()) + rows, x = reader.select(0, inner=True) + np.testing.assert_array_equal(rows, np.arange(12)) + np.testing.assert_array_equal(x, np.arange(12)) + _, x = reader.select(-1, byTime=True, inner=True) + np.testing.assert_allclose(x[:5], [-0.75, -0.5, -0.25, 0, 0.25]) + rows, x = reader.select(0) + np.testing.assert_array_equal(rows, [3, 7, 11]) + np.testing.assert_array_equal(x, [3, 7, 11]) + + def test_first_time_step_has_inner_rows(self): + names = '"Time_Iter","Outer_Iter","Inner_Iter","rms[Rho]"\n' + reader = self.reader(names + "".join(f"1, 0, {i}, {-0.1 * i}\n" for i in range(5))) + self.assertTrue(reader.hasInnerRows()) + self.assertFalse(reader.stepsAdvance()) + np.testing.assert_array_equal(reader.select(0)[0], [4]) + np.testing.assert_array_equal(reader.select(0, inner=True)[1], np.arange(5)) + + def test_time_steps_only_have_no_inner_rows(self): + names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' + reader = self.reader(names + "0, 9, -1\n1, 4, -2\n2, 6, -3\n") + self.assertFalse(reader.hasInnerRows()) + _, x = reader.select(0) + np.testing.assert_array_equal(x, [9, 14, 21]) + self.assertFalse(self.reader(CSV + row(0) + row(1)).hasInnerRows()) + def test_steady_time_counter_does_not_advance(self): names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' reader = self.reader(names + "".join(f"0, {i}, {-0.1 * i}\n" for i in range(5))) @@ -80,7 +112,7 @@ def test_steady_time_counter_does_not_advance(self): def test_first_row_kept_when_it_passes_the_filter(self): names = '"Time_Iter","Inner_Iter","rms[Rho]"\n' reader = self.reader(names + "100, 0, -1\n") - np.testing.assert_array_equal(reader.rowsFrom(100, byTime=True), [0]) + np.testing.assert_array_equal(reader.select(100, byTime=True)[0], [0]) def test_partial_zone_line_is_deferred(self): self.path.write_text(CSV + 'ZONE T="Conv') @@ -102,8 +134,8 @@ def test_incomplete_header_is_deferred(self): def test_sparse_iterations_and_start_filter(self): reader = self.reader(CSV + row(0) + row(10) + row(20) + row(30)) np.testing.assert_array_equal(reader.iters[: reader.n], [0, 10, 20, 30]) - rows = reader.rowsFrom(15) - np.testing.assert_array_equal(reader.iters[rows], [20, 30]) + _, x = reader.select(15) + np.testing.assert_array_equal(x, [20, 30]) def test_incremental_append_and_incomplete_line(self): reader = self.reader(CSV + row(0) + row(1)) From b2cd7c96a02647fba65aaa8e93b05f1e172a9b2b Mon Sep 17 00:00:00 2001 From: bigfooted Date: Fri, 27 Nov 2026 23:36:05 +0100 Subject: [PATCH 04/16] Move the progress variable source Jacobian into CFluidFlamelet The fluid model now provides dS_PV/dPV through GetProgVarSourceJacobian: analytically from the MLP Jacobian query, and by a forward difference on the PV source column only for the lookup table. The solver no longer perturbs the full source lookup and sets the derivative to zero where the PV source is clipped. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/include/fluid/CFluidFlamelet.hpp | 10 +++++ SU2_CFD/include/fluid/CFluidModel.hpp | 6 +++ SU2_CFD/src/fluid/CFluidFlamelet.cpp | 39 +++++++++++++++++++ .../src/solvers/CSpeciesFlameletSolver.cpp | 10 ++--- TestCases/tutorials.py | 2 +- 5 files changed, 59 insertions(+), 8 deletions(-) diff --git a/SU2_CFD/include/fluid/CFluidFlamelet.hpp b/SU2_CFD/include/fluid/CFluidFlamelet.hpp index 88b2e6603ee6..b11cad6dd036 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -78,6 +78,7 @@ class CFluidFlamelet final : public CFluidModel { MLPToolbox::CIOMap* iomap_PD; /*!< \brief Input-output map for the preferential diffusion scalars. */ MLPToolbox::CIOMap* iomap_Sources; /*!< \brief Input-output map for species source terms. */ MLPToolbox::CIOMap* iomap_LookUp; /*!< \brief Input-output map for passive look-up terms. */ + MLPToolbox::CIOMap* iomap_SourceJacobian; /*!< \brief Input-output map for the progress variable source Jacobian. */ MLPToolbox::CIOMap* iomap_Current; #endif @@ -93,6 +94,8 @@ class CFluidFlamelet final : public CFluidModel { val_vars_LookUp, /*!< \brief References passive look-up terms. */ val_vars_PD; /*!< \brief References to preferential diffusion scalars. */ + su2double source_pv_jac; /*!< \brief Derivative of the progress variable source with respect to the progress variable. */ + void PreprocessLookUp(CConfig* config); /*! \brief @@ -135,6 +138,13 @@ class CFluidFlamelet final : public CFluidModel { unsigned long EvaluateDataSet(const vector& input_scalar, unsigned short lookup_type, vector& output_refs); + /*! + * \brief Derivative of the progress variable source term with respect to the progress variable. + * \note Analytic for the MLP method, forward difference for the lookup table. + * \param[in] input_scalar - controlling variables used to interpolate manifold. + */ + su2double GetProgVarSourceJacobian(const vector& input_scalar) override; + /*! * \brief Check for out-of-bounds condition for data set interpolation. * \return - within bounds (0) or out of bounds (1). diff --git a/SU2_CFD/include/fluid/CFluidModel.hpp b/SU2_CFD/include/fluid/CFluidModel.hpp index af9aa3e059b7..29e8bfb89971 100644 --- a/SU2_CFD/include/fluid/CFluidModel.hpp +++ b/SU2_CFD/include/fluid/CFluidModel.hpp @@ -161,6 +161,12 @@ class CFluidModel { return 0; } + /*! + * \brief Derivative of the progress variable source term with respect to the progress variable. + * \param[in] input_scalar - data manifold query data. + */ + virtual su2double GetProgVarSourceJacobian(const vector& input_scalar) { return 0.0; } + /*! * \brief Get fluid dynamic viscosity. */ diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index f142da539175..7d4b293c7784 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -114,6 +114,7 @@ CFluidFlamelet::~CFluidFlamelet() { delete iomap_TD; delete iomap_Sources; delete iomap_LookUp; + delete iomap_SourceJacobian; delete lookup_mlp; if (preferential_diffusion) delete iomap_PD; } @@ -244,6 +245,11 @@ void CFluidFlamelet::PreprocessLookUp(CConfig* config) { iomap_PD = new MLPToolbox::CIOMap(controlling_variable_names, varnames_PD); lookup_mlp->PairVariableswithMLPs(*iomap_PD); } + iomap_SourceJacobian = + new MLPToolbox::CIOMap(controlling_variable_names, {varnames_Sources[I_PROGVAR]}); + iomap_SourceJacobian->AddQueryJacobian(varnames_Sources[I_PROGVAR], controlling_variable_names[I_PROGVAR], + &source_pv_jac); + lookup_mlp->PairVariableswithMLPs(*iomap_SourceJacobian); #endif } else { for (auto iVar = 0u; iVar < varnames_TD.size(); iVar++) { @@ -342,3 +348,36 @@ unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_sca AD::EndPreacc(); return extrapolation; } + +su2double CFluidFlamelet::GetProgVarSourceJacobian(const vector& input_scalar) { + const su2double val_prog = input_scalar[I_PROGVAR], val_enth = input_scalar[I_ENTH]; + const su2double val_mixfrac = include_mixture_fraction ? input_scalar[I_MIXFRAC] : 0.0; + switch (Kind_DataDriven_Method) { + case ENUM_DATADRIVEN_METHOD::LUT: { + const su2double delta = 1e-6; + const unsigned long idx = LUT_idx_Sources[I_PROGVAR]; + su2double source, source_pert; + if (include_mixture_fraction) { + look_up_table->LookUp_XYZ(idx, &source, val_prog, val_enth, val_mixfrac); + look_up_table->LookUp_XYZ(idx, &source_pert, val_prog + delta, val_enth, val_mixfrac); + } else { + look_up_table->LookUp_XY(idx, &source, val_prog, val_enth); + look_up_table->LookUp_XY(idx, &source_pert, val_prog + delta, val_enth); + } + source_pv_jac = (source_pert - source) / delta; + break; + } + case ENUM_DATADRIVEN_METHOD::MLP: { +#ifdef USE_MLPCPP + su2double source; + vector refs_vars{&source}; + if (!lookup_mlp->Predict(*iomap_SourceJacobian, input_scalar, refs_vars)) source_pv_jac = 0.0; +#endif + break; + } + default: + source_pv_jac = 0.0; + break; + } + return source_pv_jac; +} diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 5a0f0c753577..ba5489ed5c45 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -653,14 +653,10 @@ unsigned long CSpeciesFlameletSolver::SetScalarSources(const CConfig* config, CF vector source_scalar(flamelet_config_options.n_scalars); for (auto iCV = 0u; iCV < flamelet_config_options.n_control_vars; iCV++) source_scalar[iCV] = table_sources[iCV]; - /*--- Forward difference of the progress variable source, used only by the implicit Jacobian. ---*/ + /*--- Derivative of the progress variable source for the implicit Jacobian, zero where the source is clipped. ---*/ if ((config->GetKind_TimeIntScheme() == EULER_IMPLICIT) && !AD::TapeActive()) { - const su2double delta = 1e-6; - vector scalars_pert = scalars; - scalars_pert[I_PROGVAR] += delta; - vector sources_pert(table_sources.size()); - fluid_model_local->EvaluateDataSet(scalars_pert, FLAMELET_LOOKUP_OPS::SOURCES, sources_pert); - const su2double dsource = (fmax(0, sources_pert[I_PROGVAR]) - table_sources[I_PROGVAR]) / delta; + const su2double dsource = + (table_sources[I_PROGVAR] > 0) ? fluid_model_local->GetProgVarSourceJacobian(scalars) : su2double(0.0); static_cast(nodes)->SetSourceJacobianPV(iPoint, F * dsource); } diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index 763f21e9ebd5..9ced053c8f6d 100644 --- a/TestCases/tutorials.py +++ b/TestCases/tutorials.py @@ -177,7 +177,7 @@ def main(): premixed_hydrogen.cfg_dir = "../Tutorials/incompressible_flow/Inc_Combustion/1__premixed_hydrogen" premixed_hydrogen.cfg_file = "H2_burner.cfg" premixed_hydrogen.test_iter = 10 - premixed_hydrogen.test_vals = [-8.769564, -9.719765, -10.153710, -3.439336, -11.528098] + premixed_hydrogen.test_vals = [-8.769561, -9.719764, -10.153709, -3.439324, -11.528261] test_list.append(premixed_hydrogen) ### Compressible Flow From 0e34254b433aaa045ef0af2b5a2ca5bcaf08e50e Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 15:02:26 +0100 Subject: [PATCH 05/16] Apply black formatting to the monitor script and its tests Co-Authored-By: Claude Opus 5.5 --- SU2_PY/monitor.py | 17 ++++++++++++++--- SU2_PY/tests/test_monitor.py | 4 +++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/SU2_PY/monitor.py b/SU2_PY/monitor.py index 6797a8b07b28..c62a2c27d54d 100755 --- a/SU2_PY/monitor.py +++ b/SU2_PY/monitor.py @@ -184,7 +184,9 @@ def update(self): iters = ( table[self.iter_col].to_numpy() if self.iter_col is not None - else np.arange(self.n + 1, self.n + len(table) + 1, dtype=np.float64) + else np.arange( + self.n + 1, self.n + len(table) + 1, dtype=np.float64 + ) ) times = ( table[self.time_col].to_numpy() @@ -514,11 +516,20 @@ def updateInnerSwitch(self): else: reason = "Not available: one row per time step, set HISTORY_WRT_FREQ_INNER" self.btn_inner.setToolTip(reason) - if has != self.btn_inner.isEnabled() or advance != self.inner_advance or not has: + if ( + has != self.btn_inner.isEnabled() + or advance != self.inner_advance + or not has + ): self.btn_inner.setEnabled(has) self.btn_inner.setChecked( (has and not advance) - or (reader is not None and reader.has_inner_col and not has and not advance) + or ( + reader is not None + and reader.has_inner_col + and not has + and not advance + ) ) self.inner_advance = advance diff --git a/SU2_PY/tests/test_monitor.py b/SU2_PY/tests/test_monitor.py index 74146a91f67f..94defc541750 100644 --- a/SU2_PY/tests/test_monitor.py +++ b/SU2_PY/tests/test_monitor.py @@ -87,7 +87,9 @@ def test_inner_iterations(self): def test_first_time_step_has_inner_rows(self): names = '"Time_Iter","Outer_Iter","Inner_Iter","rms[Rho]"\n' - reader = self.reader(names + "".join(f"1, 0, {i}, {-0.1 * i}\n" for i in range(5))) + reader = self.reader( + names + "".join(f"1, 0, {i}, {-0.1 * i}\n" for i in range(5)) + ) self.assertTrue(reader.hasInnerRows()) self.assertFalse(reader.stepsAdvance()) np.testing.assert_array_equal(reader.select(0)[0], [4]) From 2fdac90bb8468e0607fc2281020827eba81fdc5a Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:18:32 +0100 Subject: [PATCH 06/16] Flamelet LUT: extrapolate linearly beyond the outer table levels Beyond the first and last table level the lookup used the outer level alone, so looked-up quantities stopped depending on the level variable. With preferential diffusion the mixture fraction is then no longer restored by its own diffusion and can run away, e.g. to negative values at a lean H2 flame tip. Queries outside the level range are now extrapolated linearly from the two outermost levels, up to one level spacing, and still reported as outside the manifold. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 24c8fbca24c8749bb620308d01802f2b3c8dcff1) --- Common/include/containers/CLookUpTable.hpp | 9 ++++ Common/src/containers/CLookUpTable.cpp | 54 +++++++++++++--------- 2 files changed, 42 insertions(+), 21 deletions(-) diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index e455dd1f12d1..e8f14408b751 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -272,6 +272,15 @@ class CLookUpTable { const su2double val_CV1, const su2double val_CV2, const su2double val_CV3); + /*! + * \brief Interpolate linearly in the third controlling variable between two table levels, or extrapolate + * when val_CV3 lies outside them. + * \returns whether the query point lies inside the data on both levels. + */ + bool InterpolateBetweenLevels(const std::vector& idx_var, std::vector& val_vars, + const su2double val_CV1, const su2double val_CV2, const su2double val_CV3, + std::pair levels); + /*! * \brief Find the triangle within which the query point (val_CV1, val_CV2) is located. * \param[in] val_CV1 - First controlling variable value. diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 05586d39585c..3d1012adf336 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -438,6 +438,25 @@ bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::ve return inside; } +bool CLookUpTable::InterpolateBetweenLevels(const std::vector& idx_var, std::vector& val_vars, + const su2double val_CV1, const su2double val_CV2, const su2double val_CV3, + std::pair levels) { + /* Determine val_CV1 and val_CV2 for the two levels. */ + std::array, 2> lower_upper_CV1_2 = ComputeNormalizedXY(levels, val_CV1, val_CV2, val_CV3); + su2double val_CV1_lower = lower_upper_CV1_2[0][0], val_CV2_lower = lower_upper_CV1_2[0][1], + val_CV1_upper = lower_upper_CV1_2[1][0], val_CV2_upper = lower_upper_CV1_2[1][1]; + + /* Perform 2D interpolations on both levels. */ + std::vector val_vars_lower(val_vars.size()), val_vars_upper(val_vars.size()); + auto inside_lower = LookUp_XY(idx_var, val_vars_lower, val_CV1_lower, val_CV2_lower, levels.first); + auto inside_upper = LookUp_XY(idx_var, val_vars_upper, val_CV1_upper, val_CV2_upper, levels.second); + + /* Linear interpolation, or extrapolation, along the z-direction. */ + Linear_Interpolation(val_CV3, levels.first, levels.second, val_vars_lower, val_vars_upper, val_vars); + + return (inside_upper && inside_lower); +} + bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::vector& val_vars, const su2double val_CV1, const su2double val_CV2, const su2double val_CV3) { /*--- Perform quasi-3D interpolation for a vector of variables with names val_names_var @@ -447,28 +466,21 @@ bool CLookUpTable::LookUp_XYZ(const std::vector& idx_var, std::ve std::pair inclusion_levels = FindInclusionLevels(val_CV3); bool within_z_limits = (inclusion_levels.first != inclusion_levels.second); + /*--- Beyond the outer levels, extrapolate linearly from the two outermost levels, up to one level + * spacing beyond the table, so that looked-up quantities keep their dependence on val_CV3. ---*/ + if (!within_z_limits && n_table_levels > 1) { + const bool below = val_CV3 < z_values_levels.front(); + const unsigned long i_low = below ? 0 : n_table_levels - 2; + const pair outer_levels = make_pair(i_low, i_low + 1); + const su2double dz = z_values_levels[i_low + 1] - z_values_levels[i_low]; + const su2double z_extrap = below ? su2double(max(val_CV3, z_values_levels.front() - dz)) + : su2double(min(val_CV3, z_values_levels.back() + dz)); + InterpolateBetweenLevels(idx_var, val_vars, val_CV1, val_CV2, z_extrap, outer_levels); + return false; + } + if (within_z_limits) { - /* 2: Determine val_CV1 and val_CV2 for the inclusion table levels. */ - std::array, 2> lower_upper_CV1_2 = - ComputeNormalizedXY(inclusion_levels, val_CV1, val_CV2, val_CV3); - su2double val_CV1_lower = lower_upper_CV1_2[0][0], val_CV2_lower = lower_upper_CV1_2[0][1], - val_CV1_upper = lower_upper_CV1_2[1][0], val_CV2_upper = lower_upper_CV1_2[1][1]; - - /* 3: Perform 2D interpolations on upper and lower inclusion levels */ - unsigned long lower_level = inclusion_levels.first; - unsigned long upper_level = inclusion_levels.second; - - std::vector val_vars_lower, val_vars_upper; - val_vars_lower.resize(val_vars.size()); - val_vars_upper.resize(val_vars.size()); - auto inside_lower = LookUp_XY(idx_var, val_vars_lower, val_CV1_lower, val_CV2_lower, lower_level); - auto inside_upper = LookUp_XY(idx_var, val_vars_upper, val_CV1_upper, val_CV2_upper, upper_level); - - /* 4: Perform linear interpolation along the z-direction using the x-y interpolation results - from upper and lower trapezoidal maps */ - Linear_Interpolation(val_CV3, lower_level, upper_level, val_vars_lower, val_vars_upper, val_vars); - - return (inside_upper && inside_lower); + return InterpolateBetweenLevels(idx_var, val_vars, val_CV1, val_CV2, val_CV3, inclusion_levels); } else { /* Perform single, 2D interpolation when val_CV3 lies outside table bounds */ unsigned long bound_level = inclusion_levels.first; From 9f3680860ca17f3fd90177d324b448f22802d6c2 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:18:32 +0100 Subject: [PATCH 07/16] Flamelet: block Jacobian of the preferential diffusion terms The preferential diffusion flux D grad(beta - phi) used the Jacobian of the ordinary diffusion, i.e. d(beta - phi)/dphi = 1, without the coupling between the controlling variables and without the thermal term of the enthalpy equation. For the mixture fraction of lean H2 flames dbeta/dZ is about 3-4, so the term was under-implicit and the mixture fraction and enthalpy oscillated with a period of two iterations near cooled walls. The solver now evaluates d(beta_i - phi_i)/dphi_j, with beta_T dT/dphi_j in the enthalpy row, by finite differences of the manifold lookup when the preferential diffusion scalars are updated: central differences inside the manifold, one-sided towards it at its edges, and the previous Jacobian where neither fits. The steps are 1e-3 of the global range of each controlling variable. The edge kernel assembles the full block. The residual is unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9cace00ee27694cba9bafaf3acf71105e3645217) --- .../numerics/species/flamelet_edge_flux.hpp | 20 +++-- .../solvers/CSpeciesFlameletSolver.hpp | 11 ++- .../include/variables/CSpeciesVariable.hpp | 13 +++ .../src/solvers/CSpeciesFlameletSolver.cpp | 84 +++++++++++++++++++ .../variables/CSpeciesFlameletVariable.cpp | 2 + 5 files changed, 121 insertions(+), 9 deletions(-) diff --git a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index dba70c948816..d476d6fbda29 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -56,9 +56,8 @@ class CScalarFlux_Flamelet final * \brief Preferential diffusion, two terms with the shape of the ordinary diffusion but of * states the model synthesises: div(D grad(beta - phi)) for each controlling variable, * and a thermal term div(beta_T D grad(T)) on the enthalpy equation. - * \note The thermal term has no implicit part, matching the treatment of the heat flux it - * models; the first term has the same thin shear layer Jacobian as the ordinary diffusion, - * because it is the same operator applied to a shifted state. + * \note The Jacobian couples the controlling variables through the derivatives of beta - phi, with + * the thermal term folded into the enthalpy row; the solver evaluates them from the manifold. */ template FORCEINLINE void extraDiffusionTerms(const FlowIndices& idx, const ScalarFluxOptions& opt, Int iPoint, @@ -104,11 +103,16 @@ class CScalarFlux_Flamelet final if (!opt.oneSided) res.flux_j(iScalar) += D * projGrad; if (opt.implicit) { - res.jac_ii(iScalar, iScalar) += D * proj_on_rho_i; - if (!opt.oneSided) { - res.jac_ij(iScalar, iScalar) -= D * proj_on_rho_j; - res.jac_ji(iScalar, iScalar) -= D * proj_on_rho_i; - res.jac_jj(iScalar, iScalar) += D * proj_on_rho_j; + for (auto jScalar = 0u; jScalar < nControlVars; ++jScalar) { + const auto iEntry = iScalar * nControlVars + jScalar; + const Double dState_i = gatherVariables(iPoint, side_i.scalarNodes.GetPrefDiffJacobian(), iEntry); + const Double dState_j = gatherVariables(jPoint, side_j.scalarNodes.GetPrefDiffJacobian(), iEntry); + res.jac_ii(iScalar, jScalar) += D * proj_on_rho_i * dState_i; + if (!opt.oneSided) { + res.jac_ij(iScalar, jScalar) -= D * proj_on_rho_j * dState_j; + res.jac_ji(iScalar, jScalar) -= D * proj_on_rho_i * dState_i; + res.jac_jj(iScalar, jScalar) += D * proj_on_rho_j * dState_j; + } } } } diff --git a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp index 7543d6d7f282..5f9d6326dac2 100644 --- a/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp +++ b/SU2_CFD/include/solvers/CSpeciesFlameletSolver.hpp @@ -45,6 +45,14 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { /*!< \brief Number of points outside the manifold domain, shared across OpenMP threads so it can be * accumulated atomically and reduced by the master thread alone in Preprocessing. */ unsigned long n_not_in_domain_local = 0; + bool pd_jacobian = false; /*!< \brief Whether the preferential diffusion Jacobian is evaluated this iteration. */ + passivedouble pd_jacobian_step[MAXNVAR] = {0}; /*!< \brief Finite difference step per controlling variable. */ + + /*! + * \brief Set the finite difference steps of the preferential diffusion Jacobian, a fraction of the global + * range of each controlling variable. + */ + void SetPrefDiffJacobianSteps(); /*! * \brief Compute the preconditioner for low-Mach flows. * \param[in] geometry - Geometrical definition of the problem. @@ -105,7 +113,8 @@ class CSpeciesFlameletSolver final : public CSpeciesSolver { const vector& scalars); /*! - * \brief Retrieve the preferential diffusion scalar values from manifold. + * \brief Retrieve the preferential diffusion scalar values from manifold, and their derivatives to the + * controlling variables when the scheme is implicit. * \param[in] fluid_model_local - pointer to flamelet fluid model. * \param[in] iPoint - node ID. * \param[in] scalars - local scalar solution. diff --git a/SU2_CFD/include/variables/CSpeciesVariable.hpp b/SU2_CFD/include/variables/CSpeciesVariable.hpp index 197cd9db04a6..84185d8a6d97 100644 --- a/SU2_CFD/include/variables/CSpeciesVariable.hpp +++ b/SU2_CFD/include/variables/CSpeciesVariable.hpp @@ -39,10 +39,23 @@ class CSpeciesVariable : public CScalarVariable { MatrixType SpeciesSourceTerm; /*!< \brief Matrix (nPoint, nVar) of chemical source terms for species transport*/ MatrixType SpeciesSourceJacobian; /*!< \brief Matrix (nPoint, nVar) of the diagonal chemical source Jacobian. */ VectorType HeatRelease; /*!< \brief Vector of heat release due to combustion for species transport*/ + MatrixType PrefDiffJacobian; /*!< \brief Matrix (nPoint, nCV*nCV), row-major d(beta_i - phi_i)/d(phi_j) of the preferential diffusion terms. */ public: static constexpr size_t MAXNVAR = MAX_TRANSPORTED_SPECIES; /*!< \brief Max number of variables for static arrays. */ + /*! + * \brief Derivatives of the preferential diffusion states to the controlling variables, row-major per point. + */ + inline const MatrixType& GetPrefDiffJacobian() const { return PrefDiffJacobian; } + + /*! + * \brief Set one derivative of a preferential diffusion state, entry iCV*nCV + jCV. + */ + inline void SetPrefDiffJacobian(unsigned long iPoint, unsigned long iEntry, su2double val) { + PrefDiffJacobian(iPoint, iEntry) = val; + } + /*! * \brief Constructor of the class. * \param[in] species_inf - species variable values (initialization value). diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index ba5489ed5c45..d5a8c5fbac39 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -90,6 +90,12 @@ void CSpeciesFlameletSolver::Preprocessing(CGeometry* geometry, CSolver** solver SU2_OMP_SAFE_GLOBAL_ACCESS(config->SetGlobalParam(config->GetKind_Solver(), RunTime_EqSystem); n_not_in_domain_local = 0;) + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + pd_jacobian = flamelet_config_options.preferential_diffusion && (config->GetKind_TimeIntScheme() == EULER_IMPLICIT); + if (pd_jacobian) SetPrefDiffJacobianSteps(); + } + END_SU2_OMP_SAFE_GLOBAL_ACCESS + /* Update global flame thickness value. */ if (calc_flame_thickness) { /*--- Every thread takes part in this, it reduces over the points of the rank and over ranks, @@ -707,9 +713,87 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode for (auto i_beta = 0u; i_beta < FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS; i_beta++) { nodes->SetAuxVar(iPoint, i_beta, beta_scalar[i_beta]); } + if (!pd_jacobian) return misses; + + /*--- Differences of the beta scalars and of the temperature, which drives the thermal term: central inside + * the manifold, one-sided towards it at its edges, and the ordinary diffusion Jacobian where neither fits. ---*/ + const auto n_cv = flamelet_config_options.n_control_vars; + auto beta_index = [](int i_cv) { + if (i_cv == I_PROGVAR) return I_BETA_PROGVAR; + if (i_cv == I_ENTH) return I_BETA_ENTH; + return I_BETA_MIXFRAC; + }; + const su2double temperature = fluid_model_local->GetTemperature(); + vector scalars_fd(scalars), beta_plus(beta_scalar.size()), beta_minus(beta_scalar.size()); + + for (auto j_cv = 0u; j_cv < n_cv; j_cv++) { + const su2double step = pd_jacobian_step[j_cv]; + scalars_fd[j_cv] = scalars[j_cv] + step; + bool inside_plus = fluid_model_local->EvaluateDataSet(scalars_fd, FLAMELET_LOOKUP_OPS::PREFDIF, beta_plus) == 0; + fluid_model_local->SetTDState_T(temperature, scalars_fd.data()); + inside_plus = inside_plus && (fluid_model_local->GetExtrapolation() == 0); + su2double temperature_plus = fluid_model_local->GetTemperature(); + scalars_fd[j_cv] = scalars[j_cv] - step; + bool inside_minus = fluid_model_local->EvaluateDataSet(scalars_fd, FLAMELET_LOOKUP_OPS::PREFDIF, beta_minus) == 0; + fluid_model_local->SetTDState_T(temperature, scalars_fd.data()); + inside_minus = inside_minus && (fluid_model_local->GetExtrapolation() == 0); + su2double temperature_minus = fluid_model_local->GetTemperature(); + scalars_fd[j_cv] = scalars[j_cv]; + + su2double span = 2 * step; + if (!inside_plus) { + beta_plus = beta_scalar; + temperature_plus = temperature; + span = step; + } + if (!inside_minus) { + beta_minus = beta_scalar; + temperature_minus = temperature; + span = step; + } + const bool usable = (misses == 0) && (inside_plus || inside_minus); + + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + su2double value = (i_cv == j_cv) ? su2double(1.0) : su2double(0.0); + if (usable) { + const auto i_beta = beta_index(i_cv); + su2double d_state = (beta_plus[i_beta] - beta_minus[i_beta]) / span; + if (i_cv == I_ENTH) + d_state += beta_scalar[I_BETA_ENTH_THERMAL] * (temperature_plus - temperature_minus) / span; + value = d_state - ((i_cv == j_cv) ? 1.0 : 0.0); + /*--- The total diagonal, ordinary diffusion included, is kept positive. ---*/ + if (i_cv == j_cv) value = max(value, su2double(-0.9)); + } + nodes->SetPrefDiffJacobian(iPoint, i_cv * n_cv + j_cv, value); + } + } + fluid_model_local->SetTDState_T(temperature, scalars.data()); return misses; } +void CSpeciesFlameletSolver::SetPrefDiffJacobianSteps() { + const auto n_cv = flamelet_config_options.n_control_vars; + passivedouble local_min[MAXNVAR], local_max[MAXNVAR], global_min[MAXNVAR], global_max[MAXNVAR]; + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + local_min[i_cv] = std::numeric_limits::max(); + local_max[i_cv] = std::numeric_limits::lowest(); + } + for (auto i_point = 0u; i_point < nPointDomain; i_point++) { + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + const passivedouble value = SU2_TYPE::GetValue(nodes->GetSolution(i_point, i_cv)); + local_min[i_cv] = min(local_min[i_cv], value); + local_max[i_cv] = max(local_max[i_cv], value); + } + } + SU2_MPI::Allreduce(local_min, global_min, n_cv, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(local_max, global_max, n_cv, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); + /*--- The magnitude floor keeps the step finite when the field is still uniform. ---*/ + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + const passivedouble magnitude = max(fabs(global_min[i_cv]), fabs(global_max[i_cv])); + pd_jacobian_step[i_cv] = max({1e-3 * (global_max[i_cv] - global_min[i_cv]), 1e-5 * magnitude, 1e-10}); + } +} + void CSpeciesFlameletSolver::Upwind_Residual(CGeometry* geometry, CSolver** solver_container, CNumerics**, CConfig* config, unsigned short iMesh) { SU2_ZONE_SCOPED diff --git a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index 46028e30bf12..4b1c845874b7 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -60,5 +60,7 @@ CSpeciesFlameletVariable::CSpeciesFlameletVariable(const su2double* species_inf, nAuxVar = FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS; AuxVar.resize(nPoint, FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS) = su2double(0.0); Grad_AuxVar.resize(nPoint, FLAMELET_PREF_DIFF_SCALARS::N_BETA_TERMS, nDim, 0.0); + const auto n_cv = flamelet_config_options.n_control_vars; + PrefDiffJacobian.resize(nPoint, n_cv * n_cv) = su2double(0.0); } } From c91ac9beef41211bc670c42d53ef22598e702615 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Thu, 26 Nov 2026 06:31:34 +0100 Subject: [PATCH 08/16] Flamelet: keep the burnt state of the flame front initialization inside the manifold GetBurntProgressVariable marched the progress variable up in steps of 1e-3 and returned the first value that was outside the manifold, because the step taken after leaving it was subtracted only once. The whole burnt region of a flame front initialization then started just outside the table, where the lookup returns frozen values of the nearest nodes; in a lean H2 slit burner these points persisted as a band of progress variable above equilibrium. The march now keeps the last value inside the manifold. When it leaves the manifold, the edge is bisected and the burnt value is set 0.1% of the progress variable range inside it. When the ignition temperature is reached first, that value is returned as before. Co-Authored-By: Claude Opus 5.5 --- .../src/solvers/CSpeciesFlameletSolver.cpp | 38 +++++++++++++++---- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index d5a8c5fbac39..e17242ac9519 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -852,15 +852,39 @@ su2double CSpeciesFlameletSolver::GetBurntProgressVariable(CFluidModel* fluid_mo SU2_ZONE_SCOPED su2double scalars[MAXNVAR], delta = 1e-3; for (auto iVar = 0u; iVar < nVar; iVar++) scalars[iVar] = scalar_solution[iVar]; - bool outside = false; - scalars[I_PROGVAR] += delta; - while (!outside) { - /*--- Note that 300.0 is a dummy temperature here and not used. ---*/ + + /*--- Note that 300.0 is a dummy temperature here and not used. ---*/ + auto inside = [&](su2double pv) { + scalars[I_PROGVAR] = pv; fluid_model->SetTDState_T(300.0, scalars); - if ((fluid_model->GetExtrapolation() == 1) || fluid_model->GetTemperature() > T_ignition) outside = true; - scalars[I_PROGVAR] += delta; + return fluid_model->GetExtrapolation() == 0; + }; + + /*--- March up while the state stays inside the manifold, until the ignition temperature is exceeded. ---*/ + const su2double pv_unburnt = scalar_solution[I_PROGVAR]; + su2double pv_burnt = pv_unburnt, pv_trial = pv_unburnt + delta; + bool ignited = false; + while (!ignited && inside(pv_trial)) { + pv_burnt = pv_trial; + ignited = fluid_model->GetTemperature() > T_ignition; + pv_trial += delta; + } + + /*--- The march left the manifold: bisect to its edge and keep a margin inside it. ---*/ + if (!ignited) { + su2double pv_out = pv_trial; + for (int iter = 0; iter < 30; iter++) { + const su2double pv_mid = 0.5 * (pv_burnt + pv_out); + if (inside(pv_mid)) + pv_burnt = pv_mid; + else + pv_out = pv_mid; + } + const su2double pv_margin = pv_burnt - 1e-3 * (pv_burnt - pv_unburnt); + if (inside(pv_margin)) pv_burnt = pv_margin; } - su2double pv_burnt = scalars[I_PROGVAR] - delta; + inside(pv_burnt); + if (rank == MASTER_NODE) { cout << "Burnt progress variable determined from flamelet table: " << pv_burnt << endl; cout << "Burnt temperature from flamelet table: " << fluid_model->GetTemperature() << endl; From 2215935646b17c429a7f5ba40de820dddac4c6ce Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 15:23:49 +0100 Subject: [PATCH 09/16] Update flamelet regression values for the preferential diffusion Jacobian Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression.py | 4 ++-- TestCases/tutorials.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index e6c8b08b1c66..086c5d7b9e88 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -97,7 +97,7 @@ def main(): cfd_flamelet_h2.cfg_dir = "flamelet/07_laminar_premixed_h2_flame_cfd" cfd_flamelet_h2.cfg_file = "laminar_premixed_h2_flame_cfd.cfg" cfd_flamelet_h2.test_iter = 5 - cfd_flamelet_h2.test_vals = [-8.036810, -8.328814, -1.805276, -8.959649] + cfd_flamelet_h2.test_vals = [-8.036773, -8.366862, -1.872906, -9.961343] test_list.append(cfd_flamelet_h2) # Flame ignition methods @@ -105,7 +105,7 @@ def main(): flame_init_methods.cfg_dir = "flamelet/08_flame_init_method" flame_init_methods.cfg_file ="flamelet_initialization.py" flame_init_methods.command = TestCase.Command("mpirun -np 2", "python", "flamelet_initialization.py") - flame_init_methods.test_vals=[1600, 1595.82] + flame_init_methods.test_vals=[1600, 1364.35] flame_init_methods.new_output = True test_list.append(flame_init_methods) diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index 0a00bff5434e..8bbf86fa9665 100644 --- a/TestCases/tutorials.py +++ b/TestCases/tutorials.py @@ -177,7 +177,7 @@ def main(): premixed_hydrogen.cfg_dir = "../Tutorials/incompressible_flow/Inc_Combustion/1__premixed_hydrogen" premixed_hydrogen.cfg_file = "H2_burner.cfg" premixed_hydrogen.test_iter = 10 - premixed_hydrogen.test_vals = [-8.769561, -9.719764, -10.153709, -3.439324, -11.528261] + premixed_hydrogen.test_vals = [-8.769698, -9.720818, -10.302347, -3.752803, -12.001923] test_list.append(premixed_hydrogen) ### Compressible Flow From 1652a6da9830644d2f1886eed3e40885eaeaef8c Mon Sep 17 00:00:00 2001 From: Nijso Date: Sun, 29 Nov 2026 21:22:50 +0100 Subject: [PATCH 10/16] Potential fix for pull request finding 'CodeQL / Multiplication result converted to larger type' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index 4b1c845874b7..d3057a382aac 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -61,6 +61,6 @@ CSpeciesFlameletVariable::CSpeciesFlameletVariable(const su2double* species_inf, 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); + PrefDiffJacobian.resize(nPoint, static_cast(n_cv) * n_cv) = su2double(0.0); } } From ceb8532989c8fb6177da4fcd65dd2eeae6adc765 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 22:21:04 +0100 Subject: [PATCH 11/16] Move the SU2_MON changes to their own pull request Co-Authored-By: Claude Opus 5.5 --- SU2_PY/SU2_MON | 2 +- SU2_PY/monitor.py | 205 ++++++----------------------------- SU2_PY/tests/test_monitor.py | 44 +------- 3 files changed, 39 insertions(+), 212 deletions(-) diff --git a/SU2_PY/SU2_MON b/SU2_PY/SU2_MON index 4f4bc0f7076f..638e47ad3af2 100755 --- a/SU2_PY/SU2_MON +++ b/SU2_PY/SU2_MON @@ -1,2 +1,2 @@ #!/bin/bash -exec python "$(dirname "$(readlink -f "$0")")/monitor.py" "$@" +cd "$(dirname "$(readlink -f "$0")")" && python monitor.py "$@" diff --git a/SU2_PY/monitor.py b/SU2_PY/monitor.py index c62a2c27d54d..44347c116ace 100755 --- a/SU2_PY/monitor.py +++ b/SU2_PY/monitor.py @@ -46,15 +46,12 @@ 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 number from 1 +# inner counter: first of these present in the history, else the row index 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") @@ -87,13 +84,10 @@ 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() @@ -130,14 +124,9 @@ 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 @@ -166,11 +155,7 @@ def update(self): wanted = sorted( { *self.cols, - *( - c - for c in (self.iter_col, self.time_col, self.outer_col) - if c is not None - ), + *(c for c in (self.iter_col, self.time_col) if c is not None), } ) table = pd.read_csv( @@ -184,24 +169,17 @@ def update(self): iters = ( table[self.iter_col].to_numpy() if self.iter_col is not None - else np.arange( - self.n + 1, self.n + len(table) + 1, dtype=np.float64 - ) + else np.arange(self.n, self.n + len(table), 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, outers) + self.append(rows, iters, times) added = True if added: @@ -214,98 +192,35 @@ 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 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): + 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): 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 - for name in ("iters", "times", "outers"): - column = np.empty(size) - column[: self.n] = getattr(self, name)[: self.n] - setattr(self, name, column) + 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 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 @@ -352,17 +267,7 @@ 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, - inner=False, - update=True, - ): + def plot(self, listonoff, normalize, start, ymin, ymax, byTime=False, update=True): if self.reader is None: return if update: @@ -375,7 +280,6 @@ def plot( ymin, ymax, byTime, - inner, self.reader.version, ) if key == self.lastkey: @@ -393,20 +297,19 @@ def plot( ax.set_ylabel(self.ylabel) self.lines = [ax.plot([], [], label=names[i])[0] for i in shown] - 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") + ax.set_xlabel( + "time iterations" if byTime and self.reader.hasTime() else "iterations" + ) n = self.reader.n - rows, x = self.reader.select(start, byTime, inner) + rows = self.reader.rowsFrom(start, byTime) + x = ( + self.reader.times if byTime and self.reader.hasTime() else self.reader.iters + )[rows] 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() @@ -483,7 +386,6 @@ 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): @@ -501,38 +403,6 @@ 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( @@ -621,14 +491,8 @@ 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) @@ -636,7 +500,6 @@ 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) @@ -679,7 +542,6 @@ 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, ) @@ -690,7 +552,6 @@ 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) # ################################### # @@ -739,7 +600,7 @@ def getfile(self): fname = QFileDialog.getOpenFileName( self, "Open file", - os.path.join(os.getcwd(), "history.csv"), + "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 94defc541750..e0c4fe81a550 100644 --- a/SU2_PY/tests/test_monitor.py +++ b/SU2_PY/tests/test_monitor.py @@ -64,45 +64,11 @@ 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, x = reader.select(1, byTime=True) - np.testing.assert_array_equal(x, [1, 2]) + rows = reader.rowsFrom(1, byTime=True) + np.testing.assert_array_equal(reader.times[rows], [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))) @@ -114,7 +80,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.select(100, byTime=True)[0], [0]) + np.testing.assert_array_equal(reader.rowsFrom(100, byTime=True), [0]) def test_partial_zone_line_is_deferred(self): self.path.write_text(CSV + 'ZONE T="Conv') @@ -136,8 +102,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]) - _, x = reader.select(15) - np.testing.assert_array_equal(x, [20, 30]) + rows = reader.rowsFrom(15) + np.testing.assert_array_equal(reader.iters[rows], [20, 30]) def test_incremental_append_and_incomplete_line(self): reader = self.reader(CSV + row(0) + row(1)) From c3bc995bcef434f119874b5da78128f64dde9242 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Sun, 29 Nov 2026 22:57:59 +0100 Subject: [PATCH 12/16] Flamelet: clamp outside the mixture fraction range, robust PV source Jacobian, PD Jacobian off the tape The lookup table again uses the outer level for a mixture fraction outside the table range, instead of extrapolating every looked-up quantity by up to one level spacing. Only the preferential diffusion scalar beta_Z is continued, with beta_Z - Z kept at its boundary value, so that the mixture fraction keeps its own diffusion outside the table. The progress variable source Jacobian of the lookup table uses a backward difference when the forward perturbation leaves the manifold, and zero when both do. The finite difference Jacobian of the preferential diffusion terms is not evaluated while the tape records; the adjoint keeps the Jacobian of the untaped pass that precedes the recording. Comments are shortened. Co-Authored-By: Claude Opus 5.5 --- Common/include/containers/CLookUpTable.hpp | 17 +++--- Common/src/containers/CLookUpTable.cpp | 54 ++++++++----------- SU2_CFD/include/fluid/CFluidFlamelet.hpp | 2 +- .../numerics/species/flamelet_edge_flux.hpp | 3 +- SU2_CFD/src/fluid/CFluidFlamelet.cpp | 23 +++++--- .../src/solvers/CSpeciesFlameletSolver.cpp | 12 +++-- 6 files changed, 55 insertions(+), 56 deletions(-) diff --git a/Common/include/containers/CLookUpTable.hpp b/Common/include/containers/CLookUpTable.hpp index e8f14408b751..6307efe2fa65 100644 --- a/Common/include/containers/CLookUpTable.hpp +++ b/Common/include/containers/CLookUpTable.hpp @@ -272,15 +272,6 @@ 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. @@ -395,6 +386,14 @@ class CLookUpTable { return limits_table_x[i_level]; } + /*! + * \brief Determine the minimum and maximum value of the third controlling variable. + * \returns Pair of the values of the first and last table level. + */ + inline std::pair GetTableLimitsZ() const { + return std::make_pair(z_values_levels.front(), z_values_levels.back()); + } + /*! * \brief Check whether requested set of variables are included in the table. */ diff --git a/Common/src/containers/CLookUpTable.cpp b/Common/src/containers/CLookUpTable.cpp index 3d1012adf336..05586d39585c 100644 --- a/Common/src/containers/CLookUpTable.cpp +++ b/Common/src/containers/CLookUpTable.cpp @@ -438,25 +438,6 @@ 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 @@ -466,21 +447,28 @@ 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) { - return InterpolateBetweenLevels(idx_var, val_vars, val_CV1, val_CV2, val_CV3, inclusion_levels); + /* 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); } 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 b11cad6dd036..dd4da1359024 100644 --- a/SU2_CFD/include/fluid/CFluidFlamelet.hpp +++ b/SU2_CFD/include/fluid/CFluidFlamelet.hpp @@ -140,7 +140,7 @@ class CFluidFlamelet final : public CFluidModel { /*! * \brief Derivative of the progress variable source term with respect to the progress variable. - * \note Analytic for the MLP method, forward difference for the lookup table. + * \note Analytic for the MLP method, one-sided difference for the lookup table. * \param[in] input_scalar - controlling variables used to interpolate manifold. */ su2double GetProgVarSourceJacobian(const vector& input_scalar) override; diff --git a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index d476d6fbda29..bbd2f47f0a7f 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -56,8 +56,7 @@ class CScalarFlux_Flamelet final * \brief Preferential diffusion, two terms with the shape of the ordinary diffusion but of * states the model synthesises: div(D grad(beta - phi)) for each controlling variable, * and a thermal term div(beta_T D grad(T)) on the enthalpy equation. - * \note The 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. + * \note The Jacobian uses d(beta - phi)/dphi from the solver, thermal term included in the enthalpy row. */ template FORCEINLINE void extraDiffusionTerms(const FlowIndices& idx, const ScalarFluxOptions& opt, Int iPoint, diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index 7d4b293c7784..c9713aca8504 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -328,6 +328,12 @@ unsigned long CFluidFlamelet::EvaluateDataSet(const vector& input_sca 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); + /*--- Beyond the outer levels, beta_Z - Z keeps its boundary value. ---*/ + if (lookup_type == FLAMELET_LOOKUP_OPS::PREFDIF) { + const auto limits_z = look_up_table->GetTableLimitsZ(); + const su2double mixfrac_bound = min(max(val_mixfrac, limits_z.first), limits_z.second); + output_refs[FLAMELET_PREF_DIFF_SCALARS::I_BETA_MIXFRAC] += val_mixfrac - mixfrac_bound; + } } else { inside = look_up_table->LookUp_XY(LUT_idx, output_refs, val_prog, val_enth); } @@ -356,15 +362,20 @@ su2double CFluidFlamelet::GetProgVarSourceJacobian(const vector& inpu case ENUM_DATADRIVEN_METHOD::LUT: { const su2double delta = 1e-6; const unsigned long idx = LUT_idx_Sources[I_PROGVAR]; + auto lookup = [&](const su2double pv, su2double& source) { + if (include_mixture_fraction) return look_up_table->LookUp_XYZ(idx, &source, pv, val_enth, val_mixfrac); + return look_up_table->LookUp_XY(idx, &source, pv, val_enth); + }; + /*--- Forward difference, backward at the manifold edge, zero if neither stays inside. ---*/ su2double source, source_pert; - if (include_mixture_fraction) { - look_up_table->LookUp_XYZ(idx, &source, val_prog, val_enth, val_mixfrac); - look_up_table->LookUp_XYZ(idx, &source_pert, val_prog + delta, val_enth, val_mixfrac); + lookup(val_prog, source); + if (lookup(val_prog + delta, source_pert)) { + source_pv_jac = (source_pert - source) / delta; + } else if (lookup(val_prog - delta, source_pert)) { + source_pv_jac = (source - source_pert) / delta; } else { - look_up_table->LookUp_XY(idx, &source, val_prog, val_enth); - look_up_table->LookUp_XY(idx, &source_pert, val_prog + delta, val_enth); + source_pv_jac = 0.0; } - source_pv_jac = (source_pert - source) / delta; break; } case ENUM_DATADRIVEN_METHOD::MLP: { diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index e17242ac9519..3b4c3864b98d 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -91,7 +91,9 @@ void CSpeciesFlameletSolver::Preprocessing(CGeometry* geometry, CSolver** solver n_not_in_domain_local = 0;) BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { - pd_jacobian = flamelet_config_options.preferential_diffusion && (config->GetKind_TimeIntScheme() == EULER_IMPLICIT); + /*--- While recording, the Jacobian of the untaped pass before the recording is kept. ---*/ + pd_jacobian = flamelet_config_options.preferential_diffusion && + (config->GetKind_TimeIntScheme() == EULER_IMPLICIT) && !AD::TapeActive(); if (pd_jacobian) SetPrefDiffJacobianSteps(); } END_SU2_OMP_SAFE_GLOBAL_ACCESS @@ -447,7 +449,7 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv * 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 - * The progress variable gets the decreasing part of its source, per unit of rho*PV. ---*/ + * Progress variable: only the decreasing part of its source. ---*/ if (implicit) { const su2double density = solver_container[FLOW_SOL]->GetNodes()->GetDensity(i_point); const su2double dsource_dpv = fn->GetSourceJacobianPV(i_point); @@ -715,8 +717,7 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode } 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. ---*/ + /*--- Central differences of beta and temperature, one-sided at the manifold edge. ---*/ const auto n_cv = flamelet_config_options.n_control_vars; auto beta_index = [](int i_cv) { if (i_cv == I_PROGVAR) return I_BETA_PROGVAR; @@ -773,7 +774,8 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode 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]; + passivedouble local_min[MAXNVAR] = {0}, local_max[MAXNVAR] = {0}, global_min[MAXNVAR] = {0}, + global_max[MAXNVAR] = {0}; 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(); From 4dd35f65e03240b7c3ec8c0cfc147a558e9ae52e Mon Sep 17 00:00:00 2001 From: bigfooted Date: Mon, 30 Nov 2026 01:26:40 +0100 Subject: [PATCH 13/16] Update the flame initialization and premixed hydrogen regression values Both values are the ones the CI computes for this branch. Co-Authored-By: Claude Opus 5.5 --- TestCases/parallel_regression.py | 2 +- TestCases/tutorials.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 61ed72066984..70956ccfa01e 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -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, 1364.35] + flame_init_methods.test_vals=[1600, 1546.23] flame_init_methods.new_output = True test_list.append(flame_init_methods) diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index 8bbf86fa9665..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.769698, -9.720818, -10.302347, -3.752803, -12.001923] + premixed_hydrogen.test_vals = [-8.769700, -9.720819, -10.302361, -3.752816, -12.001938] test_list.append(premixed_hydrogen) ### Compressible Flow From 76d548e0c665f5c52e7d8e11b2836f558cc959b3 Mon Sep 17 00:00:00 2001 From: bigfooted Date: Mon, 30 Nov 2026 20:39:03 +0100 Subject: [PATCH 14/16] Fix the preferential diffusion Jacobian step in AD builds SetPrefDiffJacobianSteps reduced passivedouble arrays with MPI_DOUBLE. In AD builds MPI_DOUBLE maps to the AD type, so the reduced enthalpy range came back as zero and the enthalpy step fell to 1e-10, turning that Jacobian column into roundoff noise and making the discrete adjoint diverge in one iteration. The reduction now uses su2double buffers. With the fix the H2 PD/MLP adjoint matches develop at CFL 5 and converges at CFL 50 (A_P -10.6 in 3000 iterations), where develop diverges. Sensitivities agree with develop to 1e-9. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 3b4c3864b98d..9a7eb093c89e 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -774,8 +774,9 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode void CSpeciesFlameletSolver::SetPrefDiffJacobianSteps() { const auto n_cv = flamelet_config_options.n_control_vars; - passivedouble local_min[MAXNVAR] = {0}, local_max[MAXNVAR] = {0}, global_min[MAXNVAR] = {0}, - global_max[MAXNVAR] = {0}; + /*--- su2double buffers, since MPI_DOUBLE is the AD type in AD builds. ---*/ + su2double local_min[MAXNVAR] = {0}, local_max[MAXNVAR] = {0}, global_min[MAXNVAR] = {0}, + global_max[MAXNVAR] = {0}; 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(); @@ -783,16 +784,18 @@ void CSpeciesFlameletSolver::SetPrefDiffJacobianSteps() { 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); + local_min[i_cv] = min(SU2_TYPE::GetValue(local_min[i_cv]), value); + local_max[i_cv] = max(SU2_TYPE::GetValue(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}); + const passivedouble g_min = SU2_TYPE::GetValue(global_min[i_cv]); + const passivedouble g_max = SU2_TYPE::GetValue(global_max[i_cv]); + const passivedouble magnitude = max(fabs(g_min), fabs(g_max)); + pd_jacobian_step[i_cv] = max({1e-3 * (g_max - g_min), 1e-5 * magnitude, 1e-10}); } } From 2ee88577525e21099cc626567ede7e52d843380b Mon Sep 17 00:00:00 2001 From: bigfooted Date: Mon, 30 Nov 2026 21:55:11 +0100 Subject: [PATCH 15/16] Flamelet: thermal PD Jacobian with its own diffusivity, guard off-manifold points - Store dT/dphi separately from the beta block and scale it in the edge flux with the thermal diffusivity Dth used by the thermal flux. - Start the PD Jacobian at the identity block, its fallback value. - Return the identity block before the finite differences for points off the manifold. - The lookup-table PV source Jacobian is zero for a point outside the table. - Update cfd_flamelet_h2, flame_init_methods and premixed_hydrogen values. Co-Authored-By: Claude Opus 5.5 --- .../numerics/species/flamelet_edge_flux.hpp | 16 ++++++++++++++- .../include/variables/CSpeciesVariable.hpp | 4 ++-- SU2_CFD/src/fluid/CFluidFlamelet.cpp | 7 ++++--- .../src/solvers/CSpeciesFlameletSolver.cpp | 20 +++++++++++++------ .../variables/CSpeciesFlameletVariable.cpp | 5 ++++- TestCases/parallel_regression.py | 4 ++-- TestCases/tutorials.py | 2 +- 7 files changed, 42 insertions(+), 16 deletions(-) diff --git a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp index bbd2f47f0a7f..748dd720592f 100644 --- a/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp +++ b/SU2_CFD/include/numerics/species/flamelet_edge_flux.hpp @@ -56,7 +56,7 @@ class CScalarFlux_Flamelet final * \brief Preferential diffusion, two terms with the shape of the ordinary diffusion but of * states the model synthesises: div(D grad(beta - phi)) for each controlling variable, * and a thermal term div(beta_T D grad(T)) on the enthalpy equation. - * \note The Jacobian uses d(beta - phi)/dphi from the solver, thermal term included in the enthalpy row. + * \note The Jacobian uses d(beta - phi)/dphi and dT/dphi from the solver, each with the diffusivity of its flux. */ template FORCEINLINE void extraDiffusionTerms(const FlowIndices& idx, const ScalarFluxOptions& opt, Int iPoint, @@ -135,6 +135,20 @@ class CScalarFlux_Flamelet final res.flux_i(I_ENTH) -= Dth * projGradT; if (!opt.oneSided) res.flux_j(I_ENTH) += Dth * projGradT; + + if (opt.implicit) { + const auto iFirst = nControlVars * nControlVars; + for (auto jScalar = 0u; jScalar < nControlVars; ++jScalar) { + const Double dT_i = gatherVariables(iPoint, side_i.scalarNodes.GetPrefDiffJacobian(), iFirst + jScalar); + const Double dT_j = gatherVariables(jPoint, side_j.scalarNodes.GetPrefDiffJacobian(), iFirst + jScalar); + res.jac_ii(I_ENTH, jScalar) += Dth * proj_on_rho_i * dT_i; + if (!opt.oneSided) { + res.jac_ij(I_ENTH, jScalar) -= Dth * proj_on_rho_j * dT_j; + res.jac_ji(I_ENTH, jScalar) -= Dth * proj_on_rho_i * dT_i; + res.jac_jj(I_ENTH, jScalar) += Dth * proj_on_rho_j * dT_j; + } + } + } } private: diff --git a/SU2_CFD/include/variables/CSpeciesVariable.hpp b/SU2_CFD/include/variables/CSpeciesVariable.hpp index 84185d8a6d97..edd8465f23ff 100644 --- a/SU2_CFD/include/variables/CSpeciesVariable.hpp +++ b/SU2_CFD/include/variables/CSpeciesVariable.hpp @@ -39,7 +39,7 @@ 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. */ + MatrixType PrefDiffJacobian; /*!< \brief Matrix (nPoint, nCV*nCV + nCV): row-major d(beta_i - phi_i)/d(phi_j), then dT/d(phi_j). */ public: static constexpr size_t MAXNVAR = MAX_TRANSPORTED_SPECIES; /*!< \brief Max number of variables for static arrays. */ @@ -50,7 +50,7 @@ class CSpeciesVariable : public CScalarVariable { inline const MatrixType& GetPrefDiffJacobian() const { return PrefDiffJacobian; } /*! - * \brief Set one derivative of a preferential diffusion state, entry iCV*nCV + jCV. + * \brief Set one derivative: entry iCV*nCV + jCV of the beta block, or nCV*nCV + jCV for temperature. */ inline void SetPrefDiffJacobian(unsigned long iPoint, unsigned long iEntry, su2double val) { PrefDiffJacobian(iPoint, iEntry) = val; diff --git a/SU2_CFD/src/fluid/CFluidFlamelet.cpp b/SU2_CFD/src/fluid/CFluidFlamelet.cpp index c9713aca8504..1271725c08eb 100644 --- a/SU2_CFD/src/fluid/CFluidFlamelet.cpp +++ b/SU2_CFD/src/fluid/CFluidFlamelet.cpp @@ -366,10 +366,11 @@ su2double CFluidFlamelet::GetProgVarSourceJacobian(const vector& inpu if (include_mixture_fraction) return look_up_table->LookUp_XYZ(idx, &source, pv, val_enth, val_mixfrac); return look_up_table->LookUp_XY(idx, &source, pv, val_enth); }; - /*--- Forward difference, backward at the manifold edge, zero if neither stays inside. ---*/ + /*--- Forward difference, backward at the manifold edge, zero for a point outside. ---*/ su2double source, source_pert; - lookup(val_prog, source); - if (lookup(val_prog + delta, source_pert)) { + if (!lookup(val_prog, source)) { + source_pv_jac = 0.0; + } else if (lookup(val_prog + delta, source_pert)) { source_pv_jac = (source_pert - source) / delta; } else if (lookup(val_prog - delta, source_pert)) { source_pv_jac = (source - source_pert) / delta; diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 9a7eb093c89e..4738e180d71e 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -717,8 +717,17 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode } if (!pd_jacobian) return misses; - /*--- Central differences of beta and temperature, one-sided at the manifold edge. ---*/ const auto n_cv = flamelet_config_options.n_control_vars; + if (misses != 0) { + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { + for (auto j_cv = 0u; j_cv < n_cv; j_cv++) + nodes->SetPrefDiffJacobian(iPoint, i_cv * n_cv + j_cv, (i_cv == j_cv) ? su2double(1.0) : su2double(0.0)); + nodes->SetPrefDiffJacobian(iPoint, n_cv * n_cv + i_cv, 0.0); + } + return misses; + } + + /*--- Central differences of beta and temperature, one-sided at the manifold edge. ---*/ auto beta_index = [](int i_cv) { if (i_cv == I_PROGVAR) return I_BETA_PROGVAR; if (i_cv == I_ENTH) return I_BETA_ENTH; @@ -752,21 +761,20 @@ unsigned long CSpeciesFlameletSolver::SetPreferentialDiffusionScalars(CFluidMode temperature_minus = temperature; span = step; } - const bool usable = (misses == 0) && (inside_plus || inside_minus); + const bool usable = inside_plus || inside_minus; for (auto i_cv = 0u; i_cv < n_cv; i_cv++) { su2double value = (i_cv == j_cv) ? su2double(1.0) : su2double(0.0); if (usable) { const auto i_beta = beta_index(i_cv); - su2double d_state = (beta_plus[i_beta] - beta_minus[i_beta]) / span; - if (i_cv == I_ENTH) - d_state += beta_scalar[I_BETA_ENTH_THERMAL] * (temperature_plus - temperature_minus) / span; - value = d_state - ((i_cv == j_cv) ? 1.0 : 0.0); + value = (beta_plus[i_beta] - beta_minus[i_beta]) / span - ((i_cv == j_cv) ? 1.0 : 0.0); /*--- The total diagonal, ordinary diffusion included, is kept positive. ---*/ if (i_cv == j_cv) value = max(value, su2double(-0.9)); } nodes->SetPrefDiffJacobian(iPoint, i_cv * n_cv + j_cv, value); } + const su2double d_temperature = usable ? (temperature_plus - temperature_minus) / span : su2double(0.0); + nodes->SetPrefDiffJacobian(iPoint, n_cv * n_cv + j_cv, d_temperature); } fluid_model_local->SetTDState_T(temperature, scalars.data()); return misses; diff --git a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp index d3057a382aac..69f46c09744f 100644 --- a/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp +++ b/SU2_CFD/src/variables/CSpeciesFlameletVariable.cpp @@ -61,6 +61,9 @@ CSpeciesFlameletVariable::CSpeciesFlameletVariable(const su2double* species_inf, 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, static_cast(n_cv) * n_cv) = su2double(0.0); + PrefDiffJacobian.resize(nPoint, static_cast(n_cv) * n_cv + n_cv) = su2double(0.0); + /*--- Identity beta block, the value used where no finite difference is available. ---*/ + for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) + for (auto i_cv = 0u; i_cv < n_cv; i_cv++) PrefDiffJacobian(iPoint, i_cv * n_cv + i_cv) = 1.0; } } diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 70956ccfa01e..97318c0e5863 100755 --- a/TestCases/parallel_regression.py +++ b/TestCases/parallel_regression.py @@ -97,7 +97,7 @@ def main(): cfd_flamelet_h2.cfg_dir = "flamelet/07_laminar_premixed_h2_flame_cfd" cfd_flamelet_h2.cfg_file = "laminar_premixed_h2_flame_cfd.cfg" cfd_flamelet_h2.test_iter = 5 - cfd_flamelet_h2.test_vals = [-8.036773, -8.366862, -1.872906, -9.961343] + cfd_flamelet_h2.test_vals = [-8.036777, -8.366742, -1.870716, -9.961387] 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, 1546.23] + flame_init_methods.test_vals=[1600, 1547.97] flame_init_methods.new_output = True test_list.append(flame_init_methods) diff --git a/TestCases/tutorials.py b/TestCases/tutorials.py index af75de193eb4..5671eaab29cd 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.769700, -9.720819, -10.302361, -3.752816, -12.001938] + premixed_hydrogen.test_vals = [-8.769614, -9.720531, -10.308356, -3.720389, -12.006045] test_list.append(premixed_hydrogen) ### Compressible Flow From 7fa2ba59f85a0d91f66312021439a545378f8c6a Mon Sep 17 00:00:00 2001 From: bigfooted Date: Wed, 2 Dec 2026 19:21:41 +0100 Subject: [PATCH 16/16] Flamelet: divide the auxiliary species source Jacobian by density The scalar system is solved in rho*Y, so dS/d(rho*Y) = source_cons / rho, as for the progress variable source and the diffusion Jacobian. Regression values of the cases with auxiliary species are updated. Co-Authored-By: Claude Opus 5.5 --- SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp | 4 ++-- TestCases/parallel_regression.py | 4 ++-- TestCases/parallel_regression_AD.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp index 4738e180d71e..43dcd57e8b8b 100644 --- a/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp +++ b/SU2_CFD/src/solvers/CSpeciesFlameletSolver.cpp @@ -448,14 +448,14 @@ void CSpeciesFlameletSolver::Source_Residual(CGeometry* geometry, CSolver** solv /*--- Implicit: analytic Jacobian for auxiliary species from the split source form. * S_aux_i = source_prod_i + source_cons_i * Y_aux_i * dS_aux_i/dY_aux_i = source_cons_i - * J_ii += -source_cons_i * V + * J_ii += -source_cons_i / rho * V * Progress variable: only the decreasing part of its source. ---*/ if (implicit) { const su2double density = solver_container[FLOW_SOL]->GetNodes()->GetDensity(i_point); const su2double dsource_dpv = fn->GetSourceJacobianPV(i_point); Jacobian.AddVal2Diag(i_point, I_PROGVAR, fmax(0.0, -dsource_dpv) / density * volume); for (auto i_aux = 0u; i_aux < n_aux; i_aux++) { - Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) * volume); + Jacobian.AddVal2Diag(i_point, n_CV + i_aux, -fn->GetAuxSourceCons(i_point, i_aux) / density * volume); } } } diff --git a/TestCases/parallel_regression.py b/TestCases/parallel_regression.py index 97318c0e5863..a7f0014742d4 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.650795, -5.649832, -13.470506, -17.249269, 94.854000] + cfd_flamelet_ch4.test_vals = [-10.539588, -12.650795, -5.649832, -13.470508, -17.249269, 94.854000] cfd_flamelet_ch4.new_output = True test_list.append(cfd_flamelet_ch4) @@ -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.410206, -3.171365, -10.884587, -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.614396] cfd_flamelet_ch4_cht.timeout = 1600 cfd_flamelet_ch4_cht.multizone = True test_list.append(cfd_flamelet_ch4_cht) diff --git a/TestCases/parallel_regression_AD.py b/TestCases/parallel_regression_AD.py index 564d4d23edaa..3fca682b95af 100644 --- a/TestCases/parallel_regression_AD.py +++ b/TestCases/parallel_regression_AD.py @@ -381,7 +381,7 @@ def main(): discadj_flamelet_ch4_hx.cfg_file = "lam_prem_ch4_hx_ad.cfg" discadj_flamelet_ch4_hx.multizone = False discadj_flamelet_ch4_hx.test_iter = 10 - discadj_flamelet_ch4_hx.test_vals = [-9.079012, -9.032987, -9.517245, -7.478949, -15.369708, -6.169865, -18.881156] + discadj_flamelet_ch4_hx.test_vals = [-9.079012, -9.032987, -9.517245, -7.478949, -15.369708, -6.169865, -18.876518] test_list.append(discadj_flamelet_ch4_hx) # 2D planar laminar premixed flame on isothermal burner with conjugate heat transfer (restart) @@ -390,7 +390,7 @@ def main(): discadj_flamelet_ch4_cht.cfg_file = "lam_prem_ch4_cht_ad_master.cfg" discadj_flamelet_ch4_cht.multizone = True discadj_flamelet_ch4_cht.test_iter = 10 - discadj_flamelet_ch4_cht.test_vals = [-1.545086, 0.628721, -6.533534, -18.651078, -18.648552, -3.794724, -6.572494, 11.000000] + discadj_flamelet_ch4_cht.test_vals = [-1.545086, 0.628721, -6.533534, -18.651002, -18.648552, -3.794724, -6.572494, 11.000000] test_list.append(discadj_flamelet_ch4_cht) ######################################