Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions Common/CommonMethods.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,107 @@ def FiniteDifferenceDerivative(y:np.ndarray[float], x:np.ndarray[float]):
else:
dydx[-1] = (dx2_1 * y_pp + (dx2_2 - dx2_1)*y_0 - dx2_2*y_p)/(dx_1*dx_2*(dx_1 - dx_2))
return dydx


def ComputeScalarDivergenceSources(grid:np.ndarray, rho:np.ndarray, T:np.ndarray, cp:np.ndarray,
k_lam:np.ndarray, Y_k:np.ndarray, D_k:np.ndarray, DT_k:np.ndarray,
h_k:np.ndarray, species_names:list[str], major_species:list[str],
pv_species:list[str], pv_weights:list[float],
mixfrac_coeffs:np.ndarray):
"""Compute the preferential diffusion closure sources S_PV, S_Z, S_h (Eq. 16 of Schepers &
van Oijen, C&F 280 (2025), model B2) for a 1D flamelet in conservative form.

The differential (non-unity-Lewis) diffusion flux of each non-major species, in the
positive-gradient convention in which the closure enters the CFD as +d/dx(...),

J_k = rho*(D_k - alpha)*dY_k/dx + (DT_k/T)*dT/dx, alpha = lambda/(rho*cp),

matches the sign convention of the runtime Eq. (14) fluxes for the major species
(molecular +div(c*(rho*D - lambda/cp) grad Y), Soret +div((DT/T) grad T)). The sources are

S_phi = d/dx( sum_k c_{phi,k} * J_k ), k not a major species,

with the weight INSIDE the divergence — for S_h the species enthalpy h_k(T) varies along
the flamelet and taking it outside drops the J_k*dh_k/dx work term, leaving a
non-conservative source whose integral does not vanish.

Discretization: two-point face fluxes J_{i+1/2} divided by the trapezoidal quadrature
weights w_i, so that sum_i w_i*S_i telescopes EXACTLY to J(x_N) - J(x_0) on the
non-uniform flamelet grid. The end fluxes are evaluated one-sidedly and retained: for
freely-propagating flamelets they vanish, for burner-stabilized flamelets the cold-end
flux is genuinely non-zero (the flame exchanges mass with the burner face). Because the
tabulated source must integrate to zero over every flamelet regardless (it acts away from
boundaries in the CFD), the residual J(x_N) - J(x_0) is removed by an |S|-weighted
compensation, making the trapezoidal integral of the returned sources exactly zero.

:return: (S_PV, S_Z, S_h, residuals) with residuals the pre-compensation integrals
{"S_PV": float, "S_Z": float, "S_h": float} in the unit of the respective flux.
"""
n_pts = len(grid)
dx = np.diff(grid)
# Trapezoidal quadrature weights on the non-uniform grid.
w = np.zeros(n_pts)
w[0] = 0.5 * dx[0]
w[-1] = 0.5 * dx[-1]
w[1:-1] = 0.5 * (dx[:-1] + dx[1:])

alpha = k_lam / (rho * cp)
coef_fick = rho * (D_k - alpha[np.newaxis, :]) # (n_species, n_pts)
coef_soret = DT_k / T[np.newaxis, :] # (n_species, n_pts)
dT_face = np.diff(T) / dx

weights = {"S_PV": np.zeros(len(species_names)), "S_Z": np.zeros(len(species_names))}
for isp, sp in enumerate(species_names):
if sp in major_species:
continue
if sp in pv_species:
weights["S_PV"][isp] = pv_weights[pv_species.index(sp)]
if mixfrac_coeffs is not None:
weights["S_Z"][isp] = mixfrac_coeffs[isp]

# Summed weighted face fluxes (n_faces = n_pts-1) and one-sided end fluxes.
J_face = {"S_PV": np.zeros(n_pts - 1), "S_Z": np.zeros(n_pts - 1), "S_h": np.zeros(n_pts - 1)}
J_end = {"S_PV": np.zeros(2), "S_Z": np.zeros(2), "S_h": np.zeros(2)}
for isp, sp in enumerate(species_names):
if sp in major_species:
continue
dY_face = np.diff(Y_k[isp, :]) / dx
Jk_face = 0.5 * (coef_fick[isp, :-1] + coef_fick[isp, 1:]) * dY_face \
+ 0.5 * (coef_soret[isp, :-1] + coef_soret[isp, 1:]) * dT_face
Jk_0 = coef_fick[isp, 0] * dY_face[0] + coef_soret[isp, 0] * dT_face[0]
Jk_N = coef_fick[isp, -1] * dY_face[-1] + coef_soret[isp, -1] * dT_face[-1]
for name in ("S_PV", "S_Z"):
c = weights[name][isp]
if c != 0.0:
J_face[name] += c * Jk_face
J_end[name] += c * np.array([Jk_0, Jk_N])
h_face = 0.5 * (h_k[isp, :-1] + h_k[isp, 1:])
J_face["S_h"] += h_face * Jk_face
J_end["S_h"] += np.array([h_k[isp, 0] * Jk_0, h_k[isp, -1] * Jk_N])

sources, residuals = [], {}
for name in ("S_PV", "S_Z", "S_h"):
S = np.zeros(n_pts)
Jf, (J0, JN) = J_face[name], J_end[name]
S[0] = (Jf[0] - J0) / w[0]
S[1:-1] = np.diff(Jf) / w[1:-1]
S[-1] = (JN - Jf[-1]) / w[-1]
# Exact telescoping: sum(w*S) = JN - J0. Remove the end-flux residual with an
# |S|-weighted compensation so the flamelet-wise integral vanishes identically.
#
# The compensation rescales the profile by residual/gross, so it is only meaningful
# while the end-flux residual is small compared with the gross redistribution the
# flamelet performs. On a state that carries no flame structure -- a burner flamelet
# that failed to ignite is essentially isothermal -- both quantities are numerical
# noise, and the ratio would amplify that noise into a large spurious source. Such a
# state has no preferential diffusion structure at all, so the correct source is zero.
residual = JN - J0
residuals[name] = residual
gross = np.sum(w * np.abs(S))
if gross > 0.0 and abs(residual) <= gross:
S -= np.abs(S) * (residual / gross)
elif gross > 0.0:
S = np.zeros(n_pts)
sources.append(S)

return sources[0], sources[1], sources[2], residuals
203 changes: 203 additions & 0 deletions Common/DataDrivenConfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,12 @@ class Config_FGM(Config):
__pv_weights:list[float] = DefaultSettings_FGM.pv_weights # Progress variable mass fraction weights.
__custom_pv_set:bool = False # User-defined progress variable

__pd_major_species:list[str] = DefaultSettings_FGM.pd_major_species # Major species carrying the resolved Eq. (14) flux in the CFD
__pd_method:str = DefaultSettings_FGM.pd_method # BETA_CORRECTION or SOURCE_TERM
__mixfrac_definition:str = DefaultSettings_FGM.mixfrac_definition # BILGER or ELEMENTAL
__mixfrac_element:str = DefaultSettings_FGM.mixfrac_element # element of the ELEMENTAL definition
__mixfrac_stoch:float = None # stoichiometric mixture fraction

__passive_species:list[str] = [] # Passive species for which to generate source terms.

__lookup_variables:list[str] = ["Heat_Release"] # Extra look-up variables to read from flamelet data
Expand Down Expand Up @@ -838,6 +844,7 @@ class Config_FGM(Config):
__mixfrac_coeff_carrier:float = None

__Le_avg_method = avg_Le_const
__enable_soret:bool = False # Solve the flamelets with thermal (Soret) diffusion (opt-in).
__Le_const_sp:np.ndarray[float] = None
__Le_avg_eq_ratio:float = None
__Le_avg_T_unb:float = None
Expand Down Expand Up @@ -1039,11 +1046,30 @@ def ComputeMixFracConstants(self):
W_s = self.gas.molecular_weights[i_s]
w_z[i_s] += g * n_atoms * W_e / W_s

if self.__mixfrac_definition == "ELEMENTAL":
# Eq. (11) of Schepers & van Oijen: the mixture fraction is the mass fraction of a single
# element. Normalising it to 0 in the oxidiser stream and 1 in the fuel stream leaves it
# identical to Bilger's definition along the whole mixing line (both are affine in Y and
# both are pinned at the same two stream states), so every equivalence-ratio conversion,
# inlet condition and table level in the workflow carries over unchanged. The two only
# part company for reacted states, where the element is distributed over the products --
# which is exactly the difference the model is meant to capture.
if self.__mixfrac_element is None:
self.__mixfrac_element = self.__selectMixtureFractionElement()
w_z = self.__elementMassFractionCoefficients(self.__mixfrac_element)

beta_o = np.sum(w_z * Y_o)
beta_f = np.sum(w_z * Y_f)
self.__mixfrac_coefficients = w_z / (beta_f - beta_o)
self.__mixfrac_constant = -beta_o / (beta_f - beta_o)
self.__mixfrac_coeff_carrier = self.__mixfrac_coefficients[self.gas.species_index(self.__carrier_specie)]

# Stoichiometric mixture fraction, evaluated in the active definition. Kept separately
# because the offset above only coincides with it for Bilger's definition -- for the
# elemental definition of a fuel that carries no oxidiser-side element the offset is zero.
self.gas.TP = self.__T_unb_lower, DefaultSettings_FGM.pressure
self.gas.set_equivalence_ratio(1.0, self.__fuel_string, self.__oxidizer_string)
self.__mixfrac_stoch = float(np.dot(self.__mixfrac_coefficients, self.gas.Y) + self.__mixfrac_constant)
return

def GetMixtureFractionCoefficients(self):
Expand Down Expand Up @@ -1703,6 +1729,156 @@ def GetProgressVariableWeights(self):
"""
return self.__pv_weights

def SetPDMajorSpecies(self, major_species:list[str]):
"""Set the major species excluded from the S_PV/S_Z/S_h closure source terms.

Per Schepers & van Oijen (2025) Eq. 16, the divergence source terms cover only
non-major species. Major species are handled by a separate runtime preferential
diffusion flux in the CFD solver (using stored D-coefficients), so including them
in the source term would double-count their contribution.

Typical selections:
FGM A / B1: ["H2", "H2O"]
FGM B2: ["H2", "H2O", "H"]

:param major_species: list of species names to exclude from source terms.
:type major_species: list[str]
:raises Exception: if any species is not present in the reaction mechanism.
"""
if any(sp not in self.__species_in_mixture for sp in major_species):
raise Exception("Not all major species are present in the reaction mechanism.")
self.__pd_major_species = list(major_species)

def GetPDMajorSpecies(self):
"""Get the list of major species excluded from the S_PV/S_Z/S_h source terms.

:return: list of major species names.
:rtype: list[str]
"""
return self.__pd_major_species

def SetPreferentialDiffusionMethod(self, method:str=DefaultSettings_FGM.pd_method):
"""Select the preferential diffusion formulation, mirroring SU2's PREFERENTIAL_DIFFUSION_METHOD.

BETA_CORRECTION leaves the workflow exactly as it was: the four beta scalars of the
constant-Lewis correction, and Bilger's mixture fraction.

SOURCE_TERM selects model B2 of Schepers & van Oijen, C&F 280 (2025) 114332. The manifold
then also carries, per major species, the Eq. (14) molecular flux coefficients
"D_<cv>_<species>" and the mass fractions "Y-<species>" whose CFD-resolved gradients they
multiply, plus the combined Soret coefficients "DT_<cv>" and the Eq. (16) closure sources
"Res_<cv>" of the remaining species. It also switches the mixture fraction to the elemental
definition of the paper (Eq. 11), because that is the control variable the model is derived
for; the two definitions agree exactly on the mixing line, so inlet and initial states are
unaffected, and differ only for reacted states.

:param method: "BETA_CORRECTION" or "SOURCE_TERM".
:raises Exception: if the method is not recognised.
"""
if method not in DefaultSettings_FGM.pd_methods:
raise Exception("Preferential diffusion method should be one of %s"
% ", ".join(DefaultSettings_FGM.pd_methods))
self.__pd_method = method
if method == "SOURCE_TERM":
self.SetMixtureFractionDefinition("ELEMENTAL", self.__mixfrac_element)
return

def GetPreferentialDiffusionMethod(self):
"""Active preferential diffusion formulation.

:return: "BETA_CORRECTION" or "SOURCE_TERM".
:rtype: str
"""
return self.__pd_method

def SetMixtureFractionDefinition(self, definition:str=DefaultSettings_FGM.mixfrac_definition,
element:str=None):
"""Choose how the mixture fraction control variable is composed from the species.

BILGER uses Bilger's coupling function. ELEMENTAL uses the mass fraction of a single
element, normalised to 0 in the oxidiser stream and 1 in the fuel stream, which reduces to
Eq. (11) of Schepers & van Oijen for a pure fuel. The normalisation is what keeps the two
definitions identical along the whole mixing line, so every equivalence-ratio-to-mixture-
fraction conversion in the workflow stays valid under either choice.

:param definition: "BILGER" or "ELEMENTAL".
:param element: element for the ELEMENTAL definition; None auto-selects the element with the
largest mass fraction in the fuel stream that is absent from the oxidiser stream.
:raises Exception: if the definition or element is not recognised.
"""
if definition not in DefaultSettings_FGM.mixfrac_definitions:
raise Exception("Mixture fraction definition should be one of %s"
% ", ".join(DefaultSettings_FGM.mixfrac_definitions))
if element is not None and element not in self.gas.element_names:
raise Exception("Element %s is not present in the reaction mechanism." % element)
self.__mixfrac_definition = definition
self.__mixfrac_element = element
self.ComputeMixFracConstants()
return

def GetMixtureFractionDefinition(self):
"""Active mixture fraction definition.

:return: "BILGER" or "ELEMENTAL".
:rtype: str
"""
return self.__mixfrac_definition

def GetMixtureFractionElement(self):
"""Element used by the ELEMENTAL mixture fraction definition (None for BILGER).

:rtype: str
"""
return self.__mixfrac_element

def GetStoichiometricMixtureFraction(self):
"""Mixture fraction at stoichiometry, in the active definition.

Both definitions are normalised to the same mixing-line coordinate, so this is the same
number either way -- but it is NOT the mixture fraction offset, which only coincides with
it for Bilger's definition.

:rtype: float
"""
return self.__mixfrac_stoch

def __selectMixtureFractionElement(self):
"""Pick the element carried by the fuel stream and absent from the oxidiser stream.

With several candidates (a hydrocarbon carries both C and H) the one with the largest mass
fraction in the fuel stream is chosen and reported, so the choice is visible rather than
silent; SetMixtureFractionDefinition takes an explicit element to override it.
"""
self.gas.TP = self.__T_unb_lower, DefaultSettings_FGM.pressure
self.gas.set_mixture_fraction(0.0, self.__fuel_string, self.__oxidizer_string)
Y_o = np.copy(self.gas.Y)
self.gas.set_mixture_fraction(1.0, self.__fuel_string, self.__oxidizer_string)
Y_f = np.copy(self.gas.Y)

candidates = []
for element in self.gas.element_names:
c_e = self.__elementMassFractionCoefficients(element)
Z_f, Z_o = float(np.dot(c_e, Y_f)), float(np.dot(c_e, Y_o))
if Z_f - Z_o > 1e-12 and Z_o < 1e-12:
candidates.append((Z_f, element))
if not candidates:
raise Exception("No element is present in the fuel stream and absent from the oxidiser "
"stream, so the elemental mixture fraction is ambiguous. Pass the element "
"explicitly to SetMixtureFractionDefinition.")
candidates.sort(reverse=True)
element = candidates[0][1]
if len(candidates) > 1:
print("Elemental mixture fraction: using element %s (candidates: %s). Pass the element "
"explicitly to SetMixtureFractionDefinition to override."
% (element, ", ".join(c[1] for c in candidates)))
return element

def __elementMassFractionCoefficients(self, element:str):
"""Per-species mass fraction of one element: c_i = n_e(i) * W_e / W_i."""
W_e = self.gas.atomic_weights[self.gas.element_index(element)]
return np.array([self.gas.n_atoms(self.gas.species_name(i), element) * W_e
/ self.gas.molecular_weights[i] for i in range(self.gas.n_species)])

def SetDefaultProgressVariable(self):
"""Set progress variable to be weighted sum of fuel and oxidizer species (minus N2) and major product at stochiometry.
Weights are set as the inverse of specie molecular weight: negative for reactants, positive for product.
Expand Down Expand Up @@ -1914,6 +2090,33 @@ def PreferentialDiffusion(self):
"""
return self.__preferential_diffusion

def SetSoretDiffusion(self, enable:bool=True):
"""Include thermal (Soret) diffusion in the flamelet solution.

Off by default, which leaves existing flamelet data unchanged. Enable it for the
SOURCE_TERM method: the ``DT_<cv>`` coefficients written for each flamelet are read
straight off the Cantera solution, and the CFD applies them at runtime as the thermal
part of the preferential diffusion flux. Solving the flamelets without Soret while
tabulating Soret coefficients from them leaves the manifold and the runtime flux model
describing different physics, which matters for hydrogen in particular.

Cantera implements thermal diffusion only for the multicomponent transport model; with
any other transport model the setting is ignored and a warning is emitted once.

:param enable: whether to solve the flamelets with Soret diffusion, defaults to True
:type enable: bool, optional
"""
self.__enable_soret = enable
return

def GetSoretDiffusion(self):
"""Whether the flamelets are solved with thermal (Soret) diffusion.

:return: Soret diffusion setting.
:rtype: bool
"""
return self.__enable_soret

def SetAveragingMethod(self, avg_method=avg_Le_const):
self.__Le_avg_method = avg_method
return
Expand Down
Loading
Loading