bloc.chem#
Cantera, thermochemistry, and physics support helpers.
Submodules#
Attributes#
Classes#
Predicts the surface area of carbon based on temperature and residence time. |
|
General class for a physical prediction model. |
|
Predicts the surface area of carbon based on temperature and residence time. |
|
A resolved solid-carbon criterion for one mechanism, for traceability. |
Functions#
|
Radiative flux from a participating gas to the tube wall in W/m2. |
|
Natural convection coefficient at the external wall of a horizontal cylinder. |
|
Natural convection coefficient at the external wall of a vertical cylinder. |
|
Solve heat transfer through a series thermal resistance stack. |
|
Linearized radiative conductance for small temperature differences. |
|
Compute internal forced convection coefficient for gas in a circular tube. |
|
Thermal resistance of a conducto-convective heat transfer surface. |
|
Thermal resistance for radial conduction in cylindrical geometry. |
|
Convert composition from source mechanism to target mechanism. |
|
Create a Solution object from composition data. |
|
Return the temperature in °C for a given enthalpy in J/kg and for a given gas composition and pressure. |
|
Switch the mechanism of a gas object. |
Get density and enthalpy under Normal conditions according to DIN 1343. |
|
Get density and enthalpy under Standard Temperature & Pressure (STP). |
|
|
Return the Lower & Higher heating values (LHV, HHV) for the specified fuel, in J/kg. |
Collect all Reactors and Reservoirs in a Network. |
|
Return physical node names from a ReactorNet in topological (flow-path) order. |
|
|
Draw the network structure and render it as a PNG file. |
|
Collect thermodynamic properties (enthalpy, HHV, LHV, ...) for physical nodes. |
|
Collect per-node energy flow breakdown for the network. |
|
Derive a flat scalar outputs dict from a solved ReactorNet and optional states. |
|
Return the single conservative fallback for a mechanism not in the registry. |
Return a copy of the mechanism-basename -> resolved-criterion registry. |
|
|
Resolve the solid-carbon criterion to use, in order of precedence. |
|
Compute Lower Heating Values (lhv) and Higher Heating Values (hhv) for all species in a Cantera gas phase. |
|
Get the mole fraction of PAH species in the gas / states object based on the number of carbon atoms. |
|
Get the PAH species in the gas / states object based on the number of carbon atoms. |
|
Return the mass fraction of solid carbon species in the gas object. |
|
Return the mass fraction vector of solid carbon species from a Cantera states object. |
|
Return the mole fraction of solid carbon species in the gas object. |
|
Return the mole fraction vector of solid carbon species from a Cantera states object. |
|
Return a list of solid carbon species from the gas phase object. |
|
Get a reactor from a ReactorNet by name. |
|
Get or create a cached Solution object for a mechanism. |
|
Calculate thermodynamic property at specific conditions. |
|
Get a cached Solution object configured to specific thermodynamic state. |
|
Calculate thermodynamic property at specific conditions by reusing existing Solution. |
|
Return a list of solid carbon species from the gas phase object. |
|
Get or create a cached Solution object for a mechanism. |
|
Return path (str) of Cantera mechanism. |
|
Return the gas phase composition by removing solid species and renormalising the mole/mass fractions. |
|
Return a list of gaseous species from the gas object. |
|
Return the corrected density of the gas object, removing the solid species. |
Get density and enthalpy under Standard Temperature & Pressure (STP). |
|
Get density and enthalpy under Normal Temperature & Pressure (NTP). |
|
Get density and enthalpy under Normal conditions according to DIN 1343. |
|
|
Return the Lower & Higher heating values (LHV, HHV) for the specified fuel, in J/kg. |
Package Contents#
- class bloc.chem.KirkOthmer2004SurfaceArea#
Bases:
SurfaceAreaModelPredicts the surface area of carbon based on temperature and residence time.
The model must be initialized with data to be fitted through the
fit()method. Child classes come with prefitted data. See for instanceKirkOthmer2004SurfaceArea.The model uses a Linear regression trained on polynomial features of ; using a
PolynomialFeatureswith degree 2.- TEMPERATURE_DATA#
- RESIDENCE_TIME_DATA#
- SURFACE_AREA_DATA#
Predicts the surface area of carbon based on temperature and residence time.
Reference#
Kirk-Othmer Encyclopedia of Chemical Technology, Volume 4, 5th Edition ISBN: 978-0-471-48519-3; March 2004 https://www.wiley.com/en-us/Kirk-Othmer+Encyclopedia+of+Chemical+Technology%2C+Volume+4%2C+5th+Edition-p-9780471485193
Examples
- fit(temperature, residence_time, surface_area)#
Fit the model to experimental or reference data.
Note the model uses a LinearRegression with temperature and log10(residence_time) as input.
- predict(temperature, residence_time)#
Predict the surface area of carbon based on temperature and residence time.
- model#
- imputer#
- class bloc.chem.PhysicalModel(model, imputer)#
Bases:
objectGeneral class for a physical prediction model.
- model#
- imputer#
- fit(X, y)#
- predict(X)#
- bloc.chem.Pr_air_20C = 0.707#
- class bloc.chem.SurfaceAreaModel#
Bases:
PhysicalModelPredicts the surface area of carbon based on temperature and residence time.
The model must be initialized with data to be fitted through the
fit()method. Child classes come with prefitted data. See for instanceKirkOthmer2004SurfaceArea.The model uses a Linear regression trained on polynomial features of ; using a
PolynomialFeatureswith degree 2.- fit(temperature, residence_time, surface_area)#
Fit the model to experimental or reference data.
Note the model uses a LinearRegression with temperature and log10(residence_time) as input.
- predict(temperature, residence_time)#
Predict the surface area of carbon based on temperature and residence time.
- model#
- imputer#
- bloc.chem.alpha_air_20C = 2.25e-05#
- bloc.chem.compute_gas2wall_radiative_flux(T_g, T_w, kappa_grey, D)#
Radiative flux from a participating gas to the tube wall in W/m2.
Uses the grey gas approximation with cylindrical geometry (mean beam length approximation via spherical integral).
Assumptions:
Temperature and composition are uniform in the cross-section.
Grey body gas with absorption coefficient
kappa_grey.Walls are black (covered by soot); no wall reflection.
\[ \begin{align}\begin{aligned}f_{\mathrm{trans}} = 2 \int_0^{\pi/2} e^{-\kappa D \cos\theta} \cos^2\theta \sin\theta \, d\theta\\q_{\mathrm{rad}} = \left(\frac{2}{3} - f_{\mathrm{trans}}\right) \sigma_{\mathrm{SB}} (T_g^4 - T_w^4)\end{aligned}\end{align} \]Positive
q_radmeans net heat transfer from gas to wall.- Parameters:
T_g (
float) – Gas temperature in K.T_w (
float) – Wall temperature in K.kappa_grey (
float) – Grey gas absorption coefficient in 1/m. Usekappa_grey = 0to disable gas radiation.D (
float) – Tube inner diameter in m.
- Returns:
q_rad (
float) – Net radiative heat flux from gas to wall in W/m2.f_trans (
float) – Transmittance factor (dimensionless).
- bloc.chem.compute_hCC_natConv_horizCyl(diameter, length, T_wall_C, T_amb_C, conductivity=conductivity_air_20C, nu=nu_air_20C, alpha=alpha_air_20C, Pr=Pr_air_20C)#
Natural convection coefficient at the external wall of a horizontal cylinder.
Uses Churchill & Chu (1975) correlation.
\[ \begin{align}\begin{aligned}\mathrm{Ra}_D = \frac{g \beta (T_{\mathrm{wall}} - T_{\mathrm{amb}}) D^3}{\nu \alpha}\\\mathrm{Nu}_D = \left(0.6 + \frac{0.387 \mathrm{Ra}_D^{1/6}} {(1 + (0.559/\mathrm{Pr})^{9/16})^{8/27}}\right)^2, \quad h = \frac{\mathrm{Nu}_D \, k}{D}\end{aligned}\end{align} \]- Parameters:
diameter (
float) – Outer diameter in m.length (
float) – Cylinder length in m (unused in this correlation, kept for API consistency).T_wall_C (
float) – Wall temperature in deg C.T_amb_C (
float) – Ambient temperature in deg C.conductivity (
float, optional) – Fluid thermal conductivity in W/m/K. Defaults to air at 20 deg C.nu (
float, optional) – Kinematic viscosity in m2/s. Defaults to air at 20 deg C.alpha (
float, optional) – Thermal diffusivity in m2/s. Defaults to air at 20 deg C.Pr (
float, optional) – Prandtl number. Defaults to air at 20 deg C.
- Returns:
Convective heat transfer coefficient h in W/m2/K.
- Return type:
float
- bloc.chem.compute_hCC_natConv_vertCyl(diameter, length, T_wall_C, T_amb_C, conductivity=conductivity_air_20C, nu=nu_air_20C, alpha=alpha_air_20C, Pr=Pr_air_20C)#
Natural convection coefficient at the external wall of a vertical cylinder.
Correlation from Taine / Lefevre (1956).
Warning
Valid for laminar flow only; gives low h values.
\[ \begin{align}\begin{aligned}\mathrm{Ra}_L = \frac{g \beta (T_{\mathrm{wall}} - T_{\mathrm{amb}}) L^3}{\nu \alpha}\\\mathrm{Nu} = \frac{4}{3} \left(\frac{7 \mathrm{Ra}_L \mathrm{Pr}}{100 + 105 \mathrm{Pr}}\right)^{1/4} + 0.1143 \frac{272 + 315 \mathrm{Pr}}{64 + 63 \mathrm{Pr}} \frac{L}{D}, \quad h = \frac{\mathrm{Nu} \, k}{L}\end{aligned}\end{align} \]- Parameters:
diameter (
float) – Outer diameter in m.length (
float) – Cylinder length in m.T_wall_C (
float) – Wall temperature in deg C.T_amb_C (
float) – Ambient temperature in deg C.conductivity (
float, optional) – Fluid thermal conductivity in W/m/K. Defaults to air at 20 deg C.nu (
float, optional) – Kinematic viscosity in m2/s. Defaults to air at 20 deg C.alpha (
float, optional) – Thermal diffusivity in m2/s. Defaults to air at 20 deg C.Pr (
float, optional) – Prandtl number. Defaults to air at 20 deg C.
- Returns:
Convective heat transfer coefficient h in W/m2/K.
- Return type:
float
- bloc.chem.compute_heat_losses_linear(Tr_C, Tamb_C, R_list)#
Solve heat transfer through a series thermal resistance stack.
\[R_{\mathrm{tot}} = \sum_i R_i, \quad \Phi = \frac{T_{\mathrm{reac}} - T_{\mathrm{amb}}}{R_{\mathrm{tot}}}, \quad \Delta T_i = \Phi \, R_i\]- Parameters:
Tr_C (
float) – Temperature inside the reactor in deg C.Tamb_C (
float) – Ambient temperature in deg C.R_list (
listoffloat) – Thermal resistances in K/W, ordered from reactor interior to ambient.
- Returns:
{"Phi": float, "T_reac": float, "T_wall_ext": float, "T_amb": float, ...}wherePhiis heat loss in W.- Return type:
dict
- bloc.chem.compute_hrad_linearRadiation(eps, Tmoy)#
Linearized radiative conductance for small temperature differences.
\[h_{\mathrm{rad}} = \varepsilon \sigma_{\mathrm{SB}} \, 4 T_{\mathrm{moy}}^3\]- Parameters:
eps (
float) – Emissivity, dimensionless.Tmoy (
float) – Mean temperature in K.
- Returns:
Linearized radiative heat transfer coefficient in W/m2/K.
- Return type:
float
- bloc.chem.conductivity_air_20C = 0.0263#
- bloc.chem.g = 9.81#
- bloc.chem.internal_convection_h(diameter, mass_flow_rate, gas, x_position=None)#
Compute internal forced convection coefficient for gas in a circular tube.
Delegates to
ht.conv_internal.Nu_conv_internal()[CalebBell_ht] which dynamically selects the most accurate applicable correlation:Laminar developing flow (Re < 2300,
x_positionprovided): Baehr-Stephan laminar thermal/velocity entry.Laminar fully-developed (Re < 2300, no
x_position): Constant wall temperature, Nu = 3.66.Turbulent with entry effects (Re > 4000,
x_positionprovided): Hausen.Turbulent general (Re > 4000): Churchill-Zajic.
Turbulent, low Prandtl (Pr < 0.03): Martinelli.
Transport properties (viscosity, thermal conductivity, heat capacity) are read from the Cantera
Solutionobject at the current state. The gas mechanism must define a transport model (e.g. Mix or Multi); mechanisms withtransport_model == 'none'are not supported.- Parameters:
diameter (
float) – Tube inner diameter in m.mass_flow_rate (
float) – Mass flow rate through the tube in kg/s.gas (
cantera.Solution) – Gas object at the current thermodynamic state (must have transport).x_position (
floatorNone, optional) – Distance from the tube inlet in m. When provided, entry-length correlations are used; otherwise fully-developed flow is assumed.
- Returns:
Convective heat transfer coefficient h in W/m2/K.
- Return type:
float- Raises:
ValueError – If
gas.transport_model == 'none'(mechanism has no transport data).
See also
ht.conv_internal.Nu_conv_internalUnderlying correlation selector from the ht library.
Notes
For CH4 pyrolysis conditions (10 SLM, D = 100 mm), Re ~ 130–250 across the full temperature range (25–1600 deg C), so fully-developed laminar flow applies and Nu = 3.66. Radiation dominates at high temperatures.
- bloc.chem.nu_air_20C = 1.589e-05#
- bloc.chem.sigma_SB = 5.67e-08#
- bloc.chem.thermal_resistance_CC(h_CC, S)#
Thermal resistance of a conducto-convective heat transfer surface.
\[R = \frac{1}{h_{\mathrm{CC}} \, S}\]- Parameters:
h_CC (
float) – Heat transfer coefficient in W/m2/K.S (
float) – Surface area in m2.
- Returns:
Thermal resistance in K/W.
- Return type:
float
- bloc.chem.thermal_resistance_radial_conduction(diameter, length, conductivity, e_insulation)#
Thermal resistance for radial conduction in cylindrical geometry.
\[R = \frac{\ln(r_2/r_1)}{2\pi k L}, \quad r_1 = D/2, \quad r_2 = D/2 + e_{\mathrm{insulation}}\]- Parameters:
diameter (
float) – Inner diameter in m.length (
float) – Cylinder length in m.conductivity (
float) – Thermal conductivity of insulation in W/m/K.e_insulation (
float) – Insulation thickness in m.
- Returns:
Thermal resistance in K/W.
- Return type:
float
- bloc.chem.convert_composition_between_mechanisms(source_composition, source_T, source_P, source_mechanism, target_mechanism, htol=0.0001, Xtol=0.0001, verbose=False)#
Convert composition from source mechanism to target mechanism.
This function performs mechanism switching by returning composition data rather than Solution objects, avoiding unnecessary object creation in iterative algorithms.
- Parameters:
source_composition (
Dict[str,float]) – Mole fractions in source mechanismsource_T (
float) – Temperature in Ksource_P (
float) – Pressure in Pasource_mechanism (
str) – Source mechanism pathtarget_mechanism (
str) – Target mechanism pathhtol (
float) – Tolerance for enthalpy variationXtol (
float) – Tolerance for mole fraction variationverbose (
bool) – Print conversion details
- Returns:
target_composition (
Dict[str,float]) – Mole fractions in target mechanismtarget_T (
float) – Temperature in K (adjusted for enthalpy conservation)target_P (
float) – Pressure in Pa (unchanged)
- Raises:
ValueError – If enthalpy or composition variations exceed tolerances
- bloc.chem.create_gas_from_composition(mechanism, composition, temperature, pressure, use_cached=True)#
Create a Solution object from composition data.
This function provides a clean interface for creating Solution objects from composition data, with the option to use cached solutions for performance optimization.
- Parameters:
mechanism (
str) – Mechanism pathcomposition (
Dict[str,float]) – Mole fractionstemperature (
float) – Temperature in Kpressure (
float) – Pressure in Pause_cached (
bool) – Whether to use cached Solution (default True) Set to False for iterative property calculations
- Returns:
gas – Solution object at specified state
- Return type:
ct.Solution
- bloc.chem.find_temperature_from_enthalpy(h_mass, X, P_bar, mechanism)#
Return the temperature in °C for a given enthalpy in J/kg and for a given gas composition and pressure.
- Parameters:
h_mass (-) – Specific enthalpy target in J/kg
X (-) – Composition of the gas in mole fraction
P_bar (-) – Pressure in bar
mechanism (-) – Path to the mechanism file
- bloc.chem.switch_mechanism(gas, new_mechanism, htol=0.0001, Xtol=0.0001, verbose=False)#
Switch the mechanism of a gas object.
Useful to switch from plasma to reactor simulation for instance. As some species may not be present in the new mechanism, we compute the adjust the temperature of the new gas object to match the enthalpy of the old gas object, so that energy is conserved. Still, if the chemical enthalpy variation exceed htol, an error is raised. Similarly, if the mole fraction variation exceed Xtol, a error is raised.
- Parameters:
gas (
ct.Solution) – Gas objectnew_mechanism (
str) – Path to the new mechanism filehtol (
float) – Tolerance for the chemical enthalpy variation between the two mechanisms. Default is 1e-4.Xtol (
float) – Tolerance for the mole fraction variation between the two mechanisms. Default is 1e-4.verbose (
bool) – If True, print information about the process. Default is False.
- Returns:
gas_new – Gas object with the new mechanism
- Return type:
ct.Solution
- bloc.chem.get_DIN1343_properties(g)#
Get density and enthalpy under Normal conditions according to DIN 1343.
DIN1343 is the base value for the normal cubic meter (Nm3) and is defined as :
0°C (273.15 K), 1 atm (101.325 kPa), according to NTP by NIST
It should not be confused with :
0°C (273.15 K), 1 bar (100 kPa), according to STP by IUPAC (>=1982)
15°C (288.15 K), 1 atm (101.325 kPa): as in ISO 2533 conditions
References
https://en.wikipedia.org/wiki/Standard_temperature_and_pressure.
- bloc.chem.get_STP_properties_IUPAC(g)#
Get density and enthalpy under Standard Temperature & Pressure (STP).
Here STP is defined as :
0°C (273.15 K), 1 bar (100 kPa), according to STP by IUPAC (>=1982)
It should not be confused with :
- 0°C (273.15 K), 1 atm (101.325 kPa): as in STP by IUPAC (before 1982) and as in
DIN 1343, used as the base value for defining the standard cubic meter.
15°C (288.15 K), 1 atm (101.325 kPa): as in ISO 2533 conditions
20°C (293.15 K), 1 atm (101.325 kPa), as in Normal (NTP) conditions by NIST
References
https://en.wikipedia.org/wiki/Standard_temperature_and_pressure.
- bloc.chem.heating_values(fuel, mechanism=None, return_unit='J/kg', verbose=False)#
Return the Lower & Higher heating values (LHV, HHV) for the specified fuel, in J/kg.
The heating values are calculated by comparing initial enthalpy and final enthalpy after oxidation. The final product composition is determined in the case of a complete combustion, where all Carbon elements are oxydized to CO2, all Hydrogen elements are oxydized to H2O, and all Nitrogen elements become N2.
References: https://cantera.org/examples/jupyter/thermo/heating_value.ipynb.html
- Parameters:
fuel (
cantera.Solutionorcantera.Species) – Cantera Solution or Species object representing the fuel.mechanism (
str, optional) – kinetic mechanism including the thermodynamic data used to do the calculations. If not given (default), uses the mechanism of the fuel object.return_unit (
str, optional) – unit of the returned values, default is “J/kg”. Other units are not implemented yet.verbose (
bool, optional) – If True, print verbose output.
- Returns:
tupleoffloat– (LHV, HHV) in the specified unit (default is J/kg). LHV is the lower heating value, HHV is the higher heating value.If O2 is not defined in mechanism,returns nan.
Examples
- ::
import cantera import as ct from bloc.chem import heating_values
g = ct.Solution(“gri30.yaml”) g.TPX = 273.15, 1e5, “CH4:1” # °C, Pa, mole fraction lhv, hhv = heating_values(g) # J/kg
Notes
@Jean: Warning, according to Wikipedia, there are several definition of LHV. Here, we assume that water condensation energy is not recovered, but heat is recovered down to 25°C. Another widespread defintion considers that the products are cooled to 150°C –> no water condensation, nor heat recovery below 150°C.
- bloc.chem.collect_all_reactors_and_reservoirs(sim)#
Collect all Reactors and Reservoirs in a Network.
- Parameters:
sim (
cantera.ReactorNet)- Return type:
setofcantera.Reactor
- bloc.chem.get_physical_nodes_ordered(sim)#
Return physical node names from a ReactorNet in topological (flow-path) order.
Physical nodes are reactors/reservoirs that participate in at least one mass-flow connection (MassFlowController). Energy-only nodes (connected only via walls, e.g. Losses, Electricity) are excluded.
The ordering follows a topological sort starting from source nodes (those with no upstream mass-flow connection).
- bloc.chem.draw_network_and_render(sim, path=None, view=False)#
Draw the network structure and render it as a PNG file.
If
pathis None then PNG file path is the original file with _sim.png extension.- Parameters:
view – If True, open the rendered image with the system default viewer (blocks on some platforms; keep False for scripts, CI, and tests).
https (See)
Example
from bloc.chem import draw_network_and_render # add your simulation code # ``sim`` is the Cantera simulation object draw_network_and_render(sim)
- bloc.chem.collect_node_properties(sim, node_mass_flow_kg_s=None)#
Collect thermodynamic properties (enthalpy, HHV, LHV, …) for physical nodes.
Physical nodes are reactors/reservoirs that participate in at least one mass-flow connection (MassFlowController). Energy-only nodes (connected only via walls, e.g. Losses, Electricity) are excluded.
- Parameters:
sim (
cantera.ReactorNet) – The reactor network (already advanced/solved).- Returns:
- ``{node_name: {“enthalpy_mass_J_kg”: float,
”enthalpy_mole_J_kmol”: float, “HHV_MJ_kg”: float, “LHV_MJ_kg”: float, “sensible_heat_MJ_kg”: float, “volume_flow_Nm3_s”: float}}``
Values are
nanwhen the property cannot be computed (e.g. O2 not present in the mechanism for HHV/LHV).- Return type:
dict
- bloc.chem.collect_energy_flows(sim, connection_mass_flows_kg_s=None, connection_endpoints=None)#
Collect per-node energy flow breakdown for the network.
For each physical node, compute input and output energy components:
Inputs (energy flowing into the node):
Power (kW) – wall heat flowing into this node from non-physical sources
HHV_in (kW) – HHV carried by upstream mass streams entering this node
Sensible_heat_in (kW) – sensible enthalpy of upstream streams above ref.
Outputs (energy flowing out of the node):
Heat_losses (kW) – wall heat flowing from this node to loss reservoirs
HHV_out (kW) – HHV carried by downstream mass streams leaving this node
Sensible_heat_out (kW) – sensible enthalpy of downstream streams above ref.
- Parameters:
sim (
cantera.ReactorNet) – The solved reactor network.- Returns:
{node_name: {"inputs": {...}, "outputs": {...}}}where each sub-dict maps descriptive keys to values in kW. Keys are ordered following the physical node topological order.- Return type:
dict
- bloc.chem.derive_outputs_from_sim(sim, states=None, config=None, kpi_extractor=None, sim_extra=None)#
Derive a flat scalar outputs dict from a solved ReactorNet and optional states.
This is the primary extraction path replacing the legacy
res_dic. It produces a dict suitable forscenario_results["outputs"]in the Calculation Note pipeline.Generic thermodynamic outputs are extracted from the network topology (physical node order, outlet node T/P/X/Y, per-node HHV/LHV/flows). Model-specific KPIs (yields, efficiencies, costs) are added by an optional kpi_extractor callable registered per
reactor_kind.- Parameters:
sim (
cantera.ReactorNet) – Solved reactor network.states (
cantera.SolutionArrayordictorNone) – Time-series solution arrays (optional; forwarded to kpi_extractor).config (
parserorNone) – ctwrap config object (forwarded to kpi_extractor).kpi_extractor (
callableorNone) – Model-specific KPI function with signaturekpi_extractor(sim, states, config, sim_extra) -> dict. Its output is merged into the result; extractor keys override generic topology keys when they conflict.sim_extra (
dictorNone) – Supplementary scalar data not accessible from the ReactorNet topology after the advance loop (e.g. tube-furnaceE_conv_J,E_rad_J). Forwarded to kpi_extractor unchanged.
- Returns:
Flat dict of scalar outputs. Generic keys follow the naming convention
T_outlet_C,P_outlet_bar,X_{species},Y_{species},HHV_outlet_MJ_kg, etc. Model-specific keys are defined by the kpi_extractor.- Return type:
dict
- class bloc.chem.NCMinResult#
A resolved solid-carbon criterion for one mechanism, for traceability.
- Parameters:
n_c_min (
intorNone) – Count-based threshold: any species withn_C >= n_c_mincounts as solid, in addition to solid_species_names.Nonemeans there is no count-based rule at all for this mechanism – only solid_species_names matters (true for mechanisms with no PAH/soot continuum, e.g. Fincke_GRC: it hasC(s)/C(soot)but nothing else worth calling “solid” by carbon count).solid_species_names (
tupleofstr) – Named species that always count as solid, regardless of carbon count. Defaults to the same listbloc.chem.species.get_solid_carbon_species()itself defaults to; only overridden when a mechanism’s actual solid species differ (e.g. the Kassel/Holmen family only hasC(s), notC(soot)).source (
str) – One of"explicit_override","registry_basename","structural_fallback".note (
str, optional) – Human-readable justification (empty for an explicit override, which needs no justification beyond “the engineer set it”).
Examples
See PAH size-dependent melting vs. mechanism solid-carbon thresholds., which overlays every registered mechanism’s resolved
n_c_minagainst a PAH melting-point-vs-size phase diagram.- n_c_min: int | None#
- source: str#
- note: str = ''#
- solid_species_names: tuple[str, Ellipsis] = ('C(s)', 'C(soot)', 'CSOLID', 'C(gr)')#
- bloc.chem.auto_n_c_min(*, warn_on_guess=True)#
Return the single conservative fallback for a mechanism not in the registry.
Only reached when the mechanism isn’t in
_SOLID_CARBON_RULES_BY_MECHANISM(seeresolve_n_c_min()) – always warns that this is an unvalidated guess, so it gets noticed and someone adds a real, verified entry to the registry instead. This is a deliberately conservative fallback, not a substitute for registering a real mechanism.- Parameters:
warn_on_guess (
bool, optional) – SetFalseto silence the “unvalidated guess” warning.- Return type:
Examples
See PAH size-dependent melting vs. mechanism solid-carbon thresholds. for how the resolved threshold compares to a PAH melting-point-vs-size phase diagram.
- bloc.chem.registered_mechanisms()#
Return a copy of the mechanism-basename -> resolved-criterion registry.
For introspection/reporting – e.g. comparing every registered mechanism’s threshold against reference data – without reaching into this module’s private
_REGISTRY_BY_BASENAME.Examples
Used by PAH size-dependent melting vs. mechanism solid-carbon thresholds. to overlay every registered mechanism’s threshold against a PAH melting-point-vs-size phase diagram.
- bloc.chem.resolve_n_c_min(gas=None, *, config=None, mechanism=None, warn_on_guess=True)#
Resolve the solid-carbon criterion to use, in order of precedence.
An explicit
settings.get_carbon_yield.n_C_minin config (dict-like or attrs-style) always wins – an engineer’s deliberate override.A registry hit by mechanism basename (mechanism, or
gas.source).auto_n_c_min()’s single conservative fallback, loudly warned as an unvalidated guess – covers both an unregistered mechanism and a call with nothing to resolve against at all.
- Parameters:
gas – A live Cantera
Solution/SolutionArrayto classify, if one is already built (avoids constructing one just to resolve a threshold).config – A STONE config (dict or attrs-style) that may declare
settings.get_carbon_yield.n_C_min.mechanism – A bare mechanism name/path, used for registry lookup when gas isn’t available yet, or as a fallback identity when gas is given but its own
.sourcedoesn’t resolve to a recognized basename.warn_on_guess – Passed through to
auto_n_c_min(); setFalseto silence the “unvalidated guess” warning (e.g. in a tight loop that already warned once).
- Return type:
Examples
See PAH size-dependent melting vs. mechanism solid-carbon thresholds., which overlays every registered mechanism’s resolved
n_C_minagainst a PAH melting-point-vs-size phase diagram.
- bloc.chem.compute_hhv_lhv_all(gas)#
Compute Lower Heating Values (lhv) and Higher Heating Values (hhv) for all species in a Cantera gas phase.
- Parameters:
gas (
cantera.Solution) – Cantera gas phase object containing species and their thermodynamic data.- Returns:
One row per species in
gas.species_names(same order), with hhv and lhv in J/kg and J/kmol. Non-fuel species (inerts, no C/H) get zero.- Return type:
pd.DataFrame
Notes
Product enthalpies for complete combustion (
CO2,H2Ovapor/liquid) go through_combustion_product_enthalpy_mole(), which uses mechanism NASA data when available and falls back tocantera.Water()/cantera.CarbonDioxide()pure-fluid references otherwise.
- bloc.chem.get_PAH_mole_fraction(gas, n_C_min=6, n_C_max=300)#
Get the mole fraction of PAH species in the gas / states object based on the number of carbon atoms.
- bloc.chem.get_PAH_species(gas, n_C_min=6, n_C_max=300)#
Get the PAH species in the gas / states object based on the number of carbon atoms.
- bloc.chem.get_solid_carbon_mass_fraction(gas, solid_sp=['C(s)', 'C(soot)', 'CSOLID'], n_C_min=300)#
Return the mass fraction of solid carbon species in the gas object.
Solid species are identified by their name or by the number of carbon atoms, through
get_solid_carbon_species().- Parameters:
gas (
cantera.Solution) – The gas object containing gaseous species and soot.solid_sp (
listofstr, optional) – List of solid species to consider. Default is [“C(s)”, “C(soot)”, “CSOLID”].n_C_min (
int, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 300. This is used as a second filter to identify solid carbon species. A specie is considered solid if it satisfies one criterium (s in solid_sp) OR the other (n_C >= n_C_min).
- Returns:
The mass fraction of solid carbon species in the gas object.
- Return type:
float
- bloc.chem.get_solid_carbon_mass_fraction_from_states(states, solid_sp=['C(s)', 'C(soot)', 'CSOLID'], n_C_min=300)#
Return the mass fraction vector of solid carbon species from a Cantera states object.
Solid species are identified by their name or by the number of carbon atoms, through
get_solid_carbon_species().- Parameters:
states (
cantera.SolutionArray) – The states object from Cantera.solid_sp (
listofstr, optional) – List of solid species to consider. Default is [“C(s)”, “C(soot)”, “CSOLID”].n_C_min (
int, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 300. This is used as a second filter to identify solid carbon species. A specie is considered solid if it satisfies
- Returns:
The mass fraction vector of solid carbon species (for each time step).
- Return type:
np.ndarray
- bloc.chem.get_solid_carbon_mole_fraction(gas, solid_sp=['C(s)', 'C(soot)', 'CSOLID'], n_C_min=300)#
Return the mole fraction of solid carbon species in the gas object.
- Parameters:
gas (
cantera.Solutionorcantera.SolutionArray) – The gas object with composition set.solid_sp (
listofstr, optional) – List of solid species to consider. Default is [“C(s)”, “C(soot)”, “CSOLID”].n_C_min (
int, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 300.
- Returns:
The mole fraction of solid carbon species in the gas object.
- Return type:
float
- bloc.chem.get_solid_carbon_mole_fraction_from_states(states, solid_sp=['C(s)', 'C(soot)', 'CSOLID'], n_C_min=300)#
Return the mole fraction vector of solid carbon species from a Cantera states object.
Solid species are identified by their name or by the number of carbon atoms, through
get_solid_carbon_species().- Parameters:
states (
cantera.SolutionArray) – The states object from Cantera.solid_sp (
listofstr, optional) – List of solid species to consider. Default is [“C(s)”, “C(soot)”, “CSOLID”].n_C_min (
int, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 300. This is used as a second filter to identify solid carbon species. A specie is considered solid if it satisfies one criterium (s in solid_sp) OR the other (n_C >= n_C_min).
- Returns:
The mole fraction vector of solid carbon species (for each time step).
- Return type:
np.ndarray
- bloc.chem.get_solid_carbon_species(gas, n_C_min=80, solid_species_base=['C(s)', 'C(soot)', 'CSOLID', 'C(gr)'], return_indices=False)#
Return a list of solid carbon species from the gas phase object.
- Parameters:
gas (
cantera.Solutionorcantera.SolutionArray) – The solution object from Cantera.n_C_min (
intorNone, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 80, according to Martin et al., PR#182 (spark-cleantech-l3/bloc#182).Nonemeans “no count-based rule at all” – only solid_species_base marks a species as solid (seebloc.chem.solid_carbon_threshold.resolve_n_c_min(), which returnsNonefor mechanisms with no PAH/soot continuum, e.g. Fincke_GRC).solid_species_base (
listofstr, optional) – Predefined list of solid species names. Default is["C(s)", "C(soot)", "CSOLID", "C(gr)"].return_indices (
bool, optional) – IfTrue, return each solid species’ index intogas.species_names(int) instead of its name (str). DefaultFalse. Useful for callers that repeatedly index a state array (e.g.phase.Y[indices]) and would otherwise need a second pass throughcantera.Solution.species_index()to convert names to indices.
- Returns:
solid_species – Names (default) or indices (
return_indices=True) of species that have at least n_C_min carbon atoms OR are in the predefined solid species list.- Return type:
listofstrorlistofint
- bloc.chem.get_reactor_by_name(sim, name)#
Get a reactor from a ReactorNet by name.
- Parameters:
sim (
ct.ReactorNet) – The reactor network simulationname (
str) – Name of the reactor to find
- Returns:
The reactor with the given name, or None if not found
- Return type:
ct.ReactororNone
Examples
>>> import cantera as ct >>> gas = ct.Solution("gri30.yaml") >>> reactor = ct.IdealGasConstPressureReactor(gas, name="test_reactor") >>> sim = ct.ReactorNet([reactor]) >>> found_reactor = get_reactor_by_name(sim, "test_reactor") >>> print(found_reactor.name) test_reactor
- bloc.chem.MECHANISM_SOLUTION_CACHE: dict[str, cantera.Solution]#
- bloc.chem.get_cached_solution(mechanism_source)#
Get or create a cached Solution object for a mechanism.
This function provides centralized access to the MECHANISM_SOLUTION_CACHE, creating new Solution objects only when needed and reusing existing ones for performance optimization.
- Parameters:
mechanism_source (
str) – The mechanism source (e.g., ‘gri30.yaml’ or path to mechanism file)- Returns:
Cached Solution object for the mechanism
- Return type:
ct.Solution
Examples
>>> gas = get_cached_solution("gri30.yaml") >>> gas.TPX = 1000, ct.one_atm, {"H2": 1.0} >>> print(gas.T) 1000.0
- bloc.chem.get_property_at_conditions(mechanism_source, T, P, composition, property_name='h', use_cache=True)#
Calculate thermodynamic property at specific conditions.
This function can either use a cached Solution object (default, most efficient) or create a new temporary Solution object for each call. The cached approach uses MECHANISM_SOLUTION_CACHE to avoid object creation overhead and is recommended for most use cases.
- Parameters:
mechanism_source (
str) – The mechanism source (e.g., from gas.source)T (
float) – Temperature in KP (
float) – Pressure in Pacomposition (
strordict) – Composition as string (e.g., “H2:1”) or dictionaryproperty_name (
str, optional) – Property to calculate. Default is “h” (enthalpy). Options: “h”, “s”, “cp”, “cv”, “density”, etc.use_cache (
bool, optional) – Whether to use cached Solution objects. Default is True (recommended). Set to False to create a new temporary Solution object for each call.
- Returns:
The requested property value
- Return type:
float
Examples
>>> import cantera as ct >>> gas = ct.Solution("gri30.yaml") >>> # Get enthalpy of H2 at 1000K, 1atm using cached Solution (default) >>> h_ref = get_property_at_conditions(gas.source, 1000, ct.one_atm, "H2:1", "h") >>> # Get enthalpy without caching (creates new Solution object) >>> h_ref = get_property_at_conditions( ... gas.source, 1000, ct.one_atm, "H2:1", "h", use_cache=False ... )
- bloc.chem.get_cached_solution_at_state(mechanism_source, T, P, X)#
Get a cached Solution object configured to specific thermodynamic state.
This unified function uses the MECHANISM_SOLUTION_CACHE to avoid creating new Solution objects when configuring Solutions for plotting, post-processing, or other temporary operations.
WARNING: This function returns a mutable cached object that shares state across calls. Only use for operations where state mutation is acceptable.
SAFE USAGE: - Reactor/Reservoir creation (state is copied during instantiation) - Post-processing and visualization (single-use operations) - Final state analysis and composition extraction
UNSAFE USAGE: - Iterative property calculations (use fresh ct.Solution() instead) - Multiple property evaluations within same computational loop - Any operation requiring state isolation between calls
- Parameters:
mechanism_source (
str) – The mechanism source (e.g., from gas.source or state.source)T (
float) – Temperature in KP (
float) – Pressure in PaX (
dictorarray) – Composition as dictionary or array
- Returns:
A cached Solution object configured to the specified state. WARNING: This object is shared across all calls with the same mechanism.
- Return type:
ct.Solution
Examples
>>> # SAFE: Reactor creation (state copied) >>> gas_upstream = get_cached_solution_at_state(mechanism, T, P, X) >>> reservoir = ct.Reservoir(gas_upstream) # Safe - state copied
>>> # SAFE: Post-processing (single use) >>> gas_final = get_cached_solution_at_state( ... reactor_states.source, ... reactor_states.T[-1], ... reactor_states.P[-1], ... reactor_states.X[-1], ... ) >>> Y_out = get_gas_phase_composition(gas_final).mass_fraction_dict()
>>> # UNSAFE: Property calculations (use fresh Solution instead) >>> # gas = get_cached_solution_at_state(mechanism, T, P, X) # DON'T DO THIS >>> # h = gas.h # UNSAFE - contamination risk >>> gas = ct.Solution(mechanism) # DO THIS INSTEAD >>> gas.TPX = T, P, X >>> h = gas.h # SAFE - isolated object
- bloc.chem.get_property_at_conditions_reuse(existing_gas, T, P, composition, property_name='h')#
Calculate thermodynamic property at specific conditions by reusing existing Solution.
This is more efficient than get_property_at_conditions as it reuses an existing Solution object, saving the overhead of creating new objects.
DEPRECATED: Use get_property_at_conditions_cached() instead for better performance and to avoid interfering with existing Solution objects.
- Parameters:
existing_gas (
ct.Solution) – An existing Solution object to temporarily modifyT (
float) – Temperature in KP (
float) – Pressure in Pacomposition (
strordict) – Composition as string (e.g., “H2:1”) or dictionaryproperty_name (
str, optional) – Property to calculate. Default is “h” (enthalpy).
- Returns:
The requested property value
- Return type:
float
Examples
>>> import cantera as ct >>> gas = ct.Solution("gri30.yaml") >>> gas.TPX = 300, ct.one_atm, "CH4:1" # Set initial state >>> # Get enthalpy of H2 at 1000K, 1atm (gas state will be restored) >>> h_ref = get_property_at_conditions_reuse(gas, 1000, ct.one_atm, "H2:1", "h") >>> # gas is back to original state: 300K, CH4:1
- bloc.chem.get_solid_carbon_species(gas, n_C_min=80, solid_species_base=['C(s)', 'C(soot)', 'CSOLID', 'C(gr)'], return_indices=False)#
Return a list of solid carbon species from the gas phase object.
- Parameters:
gas (
cantera.Solutionorcantera.SolutionArray) – The solution object from Cantera.n_C_min (
intorNone, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 80, according to Martin et al., PR#182 (spark-cleantech-l3/bloc#182).Nonemeans “no count-based rule at all” – only solid_species_base marks a species as solid (seebloc.chem.solid_carbon_threshold.resolve_n_c_min(), which returnsNonefor mechanisms with no PAH/soot continuum, e.g. Fincke_GRC).solid_species_base (
listofstr, optional) – Predefined list of solid species names. Default is["C(s)", "C(soot)", "CSOLID", "C(gr)"].return_indices (
bool, optional) – IfTrue, return each solid species’ index intogas.species_names(int) instead of its name (str). DefaultFalse. Useful for callers that repeatedly index a state array (e.g.phase.Y[indices]) and would otherwise need a second pass throughcantera.Solution.species_index()to convert names to indices.
- Returns:
solid_species – Names (default) or indices (
return_indices=True) of species that have at least n_C_min carbon atoms OR are in the predefined solid species list.- Return type:
listofstrorlistofint
- bloc.chem.get_cached_solution(mechanism_source)#
Get or create a cached Solution object for a mechanism.
This function provides centralized access to the MECHANISM_SOLUTION_CACHE, creating new Solution objects only when needed and reusing existing ones for performance optimization.
- Parameters:
mechanism_source (
str) – The mechanism source (e.g., ‘gri30.yaml’ or path to mechanism file)- Returns:
Cached Solution object for the mechanism
- Return type:
ct.Solution
Examples
>>> gas = get_cached_solution("gri30.yaml") >>> gas.TPX = 1000, ct.one_atm, {"H2": 1.0} >>> print(gas.T) 1000.0
- bloc.chem.get_mechanism_path(mechanism_str)#
Return path (str) of Cantera mechanism.
Mechanism is looked up from (in order):
An absolute path (if exists) or relative path from the working directory
A relative path from the calling script’s folder.
The
CANTERA_DATAenvironment variable directory (used in Docker/Azure deployments where the package is installed into site-packages anddata/mechanisms/lives at a separate path, e.g./app/data/mechanisms).The
data/mechanisms/directory relative to the repository root (works in editable / development installs).The Cantera built-in data directory.
The mechanism name must include the
.yamlextension.Mechanism can then be fed to a
cantera.Solutionobject.Examples
- bloc.chem.get_gas_phase_composition(gas, solid_sp=['C(s)', 'C(soot)', 'CSOLID'], n_C_min=300)#
Return the gas phase composition by removing solid species and renormalising the mole/mass fractions.
- Parameters:
gas (
cantera.Solution) – The gas phase object from Cantera.solid_sp (
listofstr, optional) – List of solid species to remove from the gas phase composition. Default is [“C(s)”, “C(soot)”, “CSOLID”].n_C_min (
int, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 300.
- Returns:
The gas phase composition by removing solid species and renormalising the mole/mass fractions.
- Return type:
- bloc.chem.get_gas_species(gas, solid_sp=['C(s)', 'C(soot)', 'CSOLID'], n_C_min=300)#
Return a list of gaseous species from the gas object.
- Parameters:
gas (
cantera.Solution) – The gas object containing gaseous species and soot.solid_sp (
listofstr, optional) – List of solid species to consider. Default is [“C(s)”, “C(soot)”, “CSOLID”].n_C_min (
int, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 300. This is used as a second filter to identify solid carbon species. A specie is considered solid if it satisfies one criterium (s in solid_sp) OR the other (n_C >= n_C_min).
- Returns:
A list of gaseous species names (i.e., not solid carbon species).
- Return type:
listofstr
- bloc.chem.get_gas_phase_density(gas, solid_sp=['C(s)', 'C(soot)', 'CSOLID'], n_C_min=300)#
Return the corrected density of the gas object, removing the solid species.
- Parameters:
gas (
cantera.Solution) – The gas object containing gaseous species and soot. Works with states[i].solid_sp (
listofstr, optional) – List of solid species to consider. Default is [“C(s)”, “C(soot)”, “CSOLID”].n_C_min (
int, optional) – Minimum number of carbon atoms to consider a species as solid. Default is 300. This is used as a second filter to identify solid carbon species. A specie is considered solid if it satisfies one criterium (s in solid_sp) OR the other (n_C >= n_C_min).
- Returns:
The corrected density of the gas object, removing the solid species.
- Return type:
float
- bloc.chem.get_STP_properties_IUPAC(g)#
Get density and enthalpy under Standard Temperature & Pressure (STP).
Here STP is defined as :
0°C (273.15 K), 1 bar (100 kPa), according to STP by IUPAC (>=1982)
It should not be confused with :
- 0°C (273.15 K), 1 atm (101.325 kPa): as in STP by IUPAC (before 1982) and as in
DIN 1343, used as the base value for defining the standard cubic meter.
15°C (288.15 K), 1 atm (101.325 kPa): as in ISO 2533 conditions
20°C (293.15 K), 1 atm (101.325 kPa), as in Normal (NTP) conditions by NIST
References
https://en.wikipedia.org/wiki/Standard_temperature_and_pressure.
- bloc.chem.get_NTP_properties_NIST(g)#
Get density and enthalpy under Normal Temperature & Pressure (NTP).
Here NTP is defined as :
20°C (293.15 K), 1 atm (101.325 kPa), according to NTP by NIST
It should not be confused with :
0°C (273.15 K), 1 bar (100 kPa), according to STP by IUPAC (>=1982)
- 0°C (273.15 K), 1 atm (101.325 kPa): as in STP by IUPAC (before 1982) and as in
DIN 1343, used as the base value for defining the standard cubic meter.
15°C (288.15 K), 1 atm (101.325 kPa): as in ISO 2533 conditions
References
https://en.wikipedia.org/wiki/Standard_temperature_and_pressure.
- bloc.chem.get_DIN1343_properties(g)#
Get density and enthalpy under Normal conditions according to DIN 1343.
DIN1343 is the base value for the normal cubic meter (Nm3) and is defined as :
0°C (273.15 K), 1 atm (101.325 kPa), according to NTP by NIST
It should not be confused with :
0°C (273.15 K), 1 bar (100 kPa), according to STP by IUPAC (>=1982)
15°C (288.15 K), 1 atm (101.325 kPa): as in ISO 2533 conditions
References
https://en.wikipedia.org/wiki/Standard_temperature_and_pressure.
- bloc.chem.heating_values(fuel, mechanism=None, return_unit='J/kg', verbose=False)#
Return the Lower & Higher heating values (LHV, HHV) for the specified fuel, in J/kg.
The heating values are calculated by comparing initial enthalpy and final enthalpy after oxidation. The final product composition is determined in the case of a complete combustion, where all Carbon elements are oxydized to CO2, all Hydrogen elements are oxydized to H2O, and all Nitrogen elements become N2.
References: https://cantera.org/examples/jupyter/thermo/heating_value.ipynb.html
- Parameters:
fuel (
cantera.Solutionorcantera.Species) – Cantera Solution or Species object representing the fuel.mechanism (
str, optional) – kinetic mechanism including the thermodynamic data used to do the calculations. If not given (default), uses the mechanism of the fuel object.return_unit (
str, optional) – unit of the returned values, default is “J/kg”. Other units are not implemented yet.verbose (
bool, optional) – If True, print verbose output.
- Returns:
tupleoffloat– (LHV, HHV) in the specified unit (default is J/kg). LHV is the lower heating value, HHV is the higher heating value.If O2 is not defined in mechanism,returns nan.
Examples
- ::
import cantera import as ct from bloc.chem import heating_values
g = ct.Solution(“gri30.yaml”) g.TPX = 273.15, 1e5, “CH4:1” # °C, Pa, mole fraction lhv, hhv = heating_values(g) # J/kg
Notes
@Jean: Warning, according to Wikipedia, there are several definition of LHV. Here, we assume that water condensation energy is not recovered, but heat is recovered down to 25°C. Another widespread defintion considers that the products are cooled to 150°C –> no water condensation, nor heat recovery below 150°C.