API
Calculator
Thermochemical properties calculator.
Computes Cp(T), H°(T), S°(T) from NASA polynomial coefficients stored in a SQLite database.
- All values returned as floats in standard units:
Cp, S° → J/(mol·K) H° → J/mol
- class pyglenn.calculator.ThermochemicalCalculator(db_file=None)[source]
Bases:
objectHigh-level interface for calculating thermochemical properties.
Uses the bundled
thermo.dbby default — no manual build step needed.Supports context-manager protocol for automatic connection management:
with ThermochemicalCalculator() as calc: props = calc.calculate_properties(species_id, 1000.0)
- Parameters:
db_file (str | None)
- connect()[source]
Connect to the database.
- Returns:
True if connection succeeded, False otherwise.
- Return type:
- get_available_species(search_pattern='', exact_match=False)[source]
Return a list of available species, optionally filtered by name.
- Parameters:
- Returns:
List of SpeciesInfo with id, name, phase, molecular_weight.
- Return type:
- calculate_properties(species_id, temperature)[source]
Calculate thermochemical properties at a given temperature.
- Parameters:
- Returns:
ThermoProperties with temperature, cp, h_relative, s, temp_interval, species_name, and phase.
h_relativeis the absolute H°(T) (NASA-7 convention): H°(298.15 K) equals the standard enthalpy of formation.- Raises:
DatabaseNotConnectedError – If not connected to database.
SpeciesNotFoundError – If species_id is not in the database.
TemperatureOutOfRangeError – If temperature is outside all valid intervals for the species.
- Return type:
- calculate_enthalpy_change(species_id, T1, T2)[source]
Calculate ΔH°(T₂) − ΔH°(T₁) in J/mol.
Uses absolute H°(T) values (NASA-7 convention). The NASA-7 polynomials are continuous across interval boundaries, so T1 and T2 may lie in different intervals.
- Parameters:
- Returns:
Enthalpy change in J/mol.
- Raises:
DatabaseNotConnectedError – If not connected to database.
SpeciesNotFoundError – If species_id is not in the database.
TemperatureOutOfRangeError – If either T1 or T2 is outside valid intervals.
- Return type:
float | None
- h_sensible_to(species_id, temperature, t_ref=298.15)[source]
Sensible enthalpy H°(T) − H°(t_ref) in J/mol.
Convenience alias of
calculate_enthalpy_change()with a readable name and a default reference temperature of 298.15 K. Because the NASA-7 polynomials are continuous across interval boundaries,temperatureandt_refmay lie in different intervals.- Parameters:
- Returns:
Sensible enthalpy change in J/mol, or None if not connected.
- Raises:
SpeciesNotFoundError – If species_id is not in the database.
TemperatureOutOfRangeError – If
temperatureort_refis outside the valid intervals.
- Return type:
float | None
- calculate_properties_range(species_id, temps, *, strict=False)[source]
Calculate properties for many temperatures, loading data once.
Unlike
get_properties_range(), this loads the species intervals a single time and evaluates all temperatures in memory, preserving input order.- Parameters:
- Returns:
Ordered list of ThermoProperties.
- Raises:
DatabaseNotConnectedError – If not connected to database.
SpeciesNotFoundError – If species_id is not in the database.
TemperatureOutOfRangeError – If
strictand a temperature is outside the valid intervals.
- Return type:
- dcp_dt(species_id, temperature)[source]
Derivative of Cp with respect to temperature, in J/(mol·K²).
Analytical derivative of the NASA-7 Cp polynomial (Equation 1), denormalized with the dataset reference gas constant.
- Parameters:
- Returns:
dCp/dT in J/(mol·K²).
- Raises:
DatabaseNotConnectedError – If not connected to database.
SpeciesNotFoundError – If species_id is not in the database.
TemperatureOutOfRangeError – If temperature is outside all valid intervals for the species.
- Return type:
- gamma(species_id, temperature)[source]
Specific heat ratio Cp/Cv, assuming an ideal gas.
For an ideal gas Cv = Cp - R, so gamma = Cp / (Cp - r_ref), where
r_refis the dataset reference gas constant.- Parameters:
- Returns:
Dimensionless ratio Cp/Cv.
- Raises:
DatabaseNotConnectedError – If not connected to database.
SpeciesNotFoundError – If species_id is not in the database.
TemperatureOutOfRangeError – If temperature is outside all valid intervals for the species.
- Return type:
- mixture_properties(mixture, temperature, *, strict=True)[source]
Calculate properties of a mixture with a known composition.
No chemical equilibrium is solved: the composition is an input, not a result. Properties are composed per mole of mixture by mole-fraction weighting of each component’s properties, then converted to a mass basis with the mole-fraction-weighted mean molar mass (arithmetic mean,
M = Σ xᵢ Mᵢ).h_molarfollows the NASA-7 convention (absolute H°(T), with H°(298.15 K) = ΔH°f).- Parameters:
- Returns:
MixedProperties with molar and mass based Cp/H/S and molar mass.
- Raises:
DatabaseNotConnectedError – If not connected.
CompositionError – If the composition is invalid.
SpeciesNotFoundError – If a species id is not in the database.
TemperatureOutOfRangeError – If
strictand a component is out of range, or if every component is out of range.
- Return type:
Exceptions
- class pyglenn.ThermoCalcError[source]
Bases:
ExceptionBase exception for thermochemical calculation errors.
- class pyglenn.CompositionError[source]
Bases:
ThermoCalcErrorRaised when a mixture composition is invalid.
- class pyglenn.DatabaseNotConnectedError[source]
Bases:
ThermoCalcErrorRaised when attempting calculation without a database connection.
- class pyglenn.SpeciesNotFoundError(species_id)[source]
Bases:
ThermoCalcErrorRaised when a species ID is not found in the database.
- Parameters:
species_id (int)
- class pyglenn.TemperatureOutOfRangeError(temperature, species_name=None, temp_bounds=None)[source]
Bases:
ThermoCalcErrorRaised when the requested temperature is outside valid intervals.
Carries the requested temperature, the species name, and the overall valid temperature bounds (when known).
Models
Typed domain model for pyglenn thermochemical results.
These frozen dataclasses replace plain dict returns. They are converted at
the SQLite boundary via the from_mapping constructors and serialised back
with dataclasses.asdict() (or the to_dict convenience method).
- class pyglenn.models.NASACoefficients(a1, a2, a3, a4, a5, a6, a7, b1, b2)[source]
Bases:
objectThe nine NASA-7 polynomial coefficients (dimensionless).
- Parameters:
- class pyglenn.models.SpeciesInfo(id, name, formula=None, phase=None, molecular_weight=None, heat_of_formation_298K=None, num_intervals=None, comments=None, reference_code=None)[source]
Bases:
objectBasic metadata for a single species (no interval or coefficient data).
- Parameters:
- class pyglenn.models.IntervalData(interval_number, temp_min, temp_max, h_298_to_0, coefficients)[source]
Bases:
objectA single temperature interval with its NASA-7 coefficients.
- Parameters:
interval_number (int)
temp_min (float)
temp_max (float)
h_298_to_0 (float | None)
coefficients (NASACoefficients)
- coefficients: NASACoefficients
- class pyglenn.models.ThermoProperties(temperature, cp, h_relative, s, temp_interval, species_name, phase=None)[source]
Bases:
objectThermochemical properties at a single temperature.
cpandsare in J/(mol·K);h_relativeis the absolute enthalpy H°(T) in J/mol (NASA-7 convention), where H°(298.15 K) = ΔH°f(298.15 K).- Parameters:
- class pyglenn.models.SpeciesData(id, name, formula=None, phase=None, molecular_weight=None, heat_of_formation_298K=None, num_intervals=None, comments=None, reference_code=None, intervals=())[source]
Bases:
objectComplete species record including all intervals and coefficients.
- Parameters:
- intervals: tuple[IntervalData, ...] = ()
- class pyglenn.models.DatabaseStats(total_species, total_intervals, total_coeff_sets, species_by_phase, avg_molecular_weight=None)[source]
Bases:
objectAggregate database statistics.
- Parameters:
- class pyglenn.models.Mixture(species)[source]
Bases:
objectA thermochemical mixture defined by mole fractions.
speciesis an immutable sequence of(species_id, mole_fraction)pairs. Fractions are dimensionless and must be non-negative and sum to 1.0 within the tolerance ofvalidate().validate()checks self-consistency only (sum, sign, duplicates, emptiness). Species-id existence is checked by the calculator, which owns the database connection.- validate(tol=1e-09)[source]
Validate the composition, raising
CompositionErroron failure.Checks, in order: non-empty, no duplicate species ids, non-negative fractions, and mole fractions summing to 1.0 within
tol.- Parameters:
tol (float) – Absolute tolerance for the mole-fraction sum.
- Raises:
CompositionError – If any check fails.
- Return type:
None
- class pyglenn.models.MixedProperties(temperature, cp_mass, h_mass, s_mass, cp_molar, h_molar, s_molar, molar_mass)[source]
Bases:
objectThermochemical properties of a mixture at a single temperature.
*_molarvalues are per mole of mixture;*_massvalues are per kilogram of mixture.h_molaris the absolute enthalpy H°(T) in the NASA-7 convention (H°(298.15 K) = ΔH°f).molar_massis the mole-fraction-weighted mean molar mass (arithmetic mean) in kg/mol.- Parameters:
Fitting
Least-squares fitting of NASA-7 polynomials to tabulated Cp(T) data.
This module exposes fit_nasa7() (single temperature interval) and
fit_nasa7_multi() (several intervals with continuity of Cp and its
first derivative at each internal breakpoint). Both derive the integration
constants so that the NASA-7 enthalpy convention is satisfied exactly.
- pyglenn.fitting.fit_nasa7(temperatures, cp_values, *, t_ref=298.15, h_ref=0.0, s_ref=None, weights=None, r_ref=8.31451)[source]
Fit NASA-7 coefficients
a1..a7to tabulated Cp(T) data.Fits the seven heat-capacity coefficients by (weighted) least squares in the dimensionless form:
Cp/R = a1/T² + a2/T + a3 + a4·T + a5·T² + a6·T³ + a7·T⁴
The enthalpy integration constant
b1is not fitted: it is derived so that the NASA-7 conventionH°(t_ref) = h_refholds exactly. The entropy constantb2is derived froms_refwhen provided, and set to0.0otherwise.- Parameters:
temperatures (Sequence[float]) – Temperatures in Kelvin (must be strictly positive).
cp_values (Sequence[float]) – Heat capacity at each temperature, in J/(mol·K).
t_ref (float) – Reference temperature in Kelvin for the enthalpy anchor (default 298.15).
h_ref (float) – Enthalpy H° at
t_refin J/mol (default 0.0). The returnedb1guarantees H°(t_ref) == h_ref.s_ref (float | None) – Optional entropy S° at
t_refin J/(mol·K). When given, the returnedb2guarantees S°(t_ref) == s_ref.weights (Sequence[float] | None) – Optional per-point weights (same length as
temperatures). Defaults to uniform weights.r_ref (float) – Reference gas constant used to denormalize
cp_valuesandh_ref. Defaults toR_GLENN, the value used by the bundled database.
- Returns:
NASACoefficientswitha1..a7,b1andb2.- Raises:
ValueError – If the inputs are inconsistent, too short, or contain non-positive temperatures, non-finite values, or invalid weights.
- Return type:
Notes
NASA-7 convention. The enthalpy integration constant is
b1;a6anda7multiply T³ and T⁴ in the Cp polynomial and are not integration constants. The fitted coefficients follow the same convention as the rest of pyglenn, so they can be evaluated directly withpyglenn.ThermoDBQuery.calculate_cp().Conditioning. The fit is performed in the scaled variable
u = T / T_scale(withT_scalethe geometric mean temperature) to keep the design matrix well-conditioned. Very wide temperature ranges remain inherently ill-conditioned; NASA datasets split each species into several intervals, so prefer fitting one interval at a time.
- pyglenn.fitting.fit_nasa7_multi(temperatures, cp_values, breakpoints, *, t_ref=298.15, h_ref=0.0, s_ref=None, weights=None, r_ref=8.31451)[source]
Fit NASA-7 coefficients across several temperature intervals.
Fits one set of seven heat-capacity coefficients per interval, requiring that both
Cp/Rand its first temperature derivative are continuous at every internal breakpoint (a linear equality constraint in the least-squares problem). The enthalpy constantb1is anchored in the interval containingt_refand propagated so that H° is continuous across breakpoints;b2is anchored froms_refwhen provided and propagated so that S° is continuous, otherwise set to0.0everywhere.- Parameters:
temperatures (Sequence[float]) – Temperatures in Kelvin (strictly positive).
cp_values (Sequence[float]) – Heat capacity at each temperature, in J/(mol·K).
breakpoints (Sequence[float]) – Internal boundary temperatures, strictly increasing and inside the data range. A point with
T <= breakpointbelongs to the lower interval (matching pyglenn’s interval convention).t_ref (float) – Reference temperature for the enthalpy anchor (default 298.15).
h_ref (float) – Enthalpy H° at
t_refin J/mol (default 0.0). The interval containingt_refgets theb1that makes H°(t_ref) == h_ref.s_ref (float | None) – Optional entropy S° at
t_refin J/(mol·K).weights (Sequence[float] | None) – Optional per-point weights (same length as
temperatures).r_ref (float) – Reference gas constant (default
R_GLENN).
- Returns:
Tuple of
NASACoefficients, one per interval in increasing temperature order.- Raises:
ValueError – If the inputs are inconsistent, contain non-positive or non-finite values, invalid breakpoints or weights, or an interval has fewer than 7 points.
- Return type:
Notes
The continuity constraints concern the fitted Cp polynomial (value and first derivative), matching
fit_nasa7()’s NASA-7 convention (b1is the enthalpy constant, nota6). The constrained least-squares problem is solved with a null-space projection of the continuity constraints; each interval is scaled independently to keep the problem well-conditioned.
Database
Database query interface for thermochemical data. Provides SQLite access, species lookup, and NASA polynomial calculations.
- class pyglenn.database.ThermoDBQuery(db_file='thermo.db')[source]
Bases:
objectClass for querying thermochemical database.
- Parameters:
db_file (str)
- get_gas_constant_ref()[source]
Return the dataset gas constant, with a safe legacy fallback.
Legacy databases without valid metadata retain the historic universal constant. Database errors are deliberately allowed to propagate instead of being mistaken for a legacy-database condition.
- Return type:
- migrate_metadata()[source]
Add canonical dataset metadata to a connected legacy database.
This explicit, idempotent operation changes only the additive
metadatatable. It never rebuilds or alters thermochemical rows.- Return type:
None
- get_statistics()[source]
Get database statistics.
- Returns:
DatabaseStats with totals, phase counts, and average molecular weight.
- Return type:
- find_species(name, exact_match=False)[source]
Find species by name.
- Parameters:
- Returns:
List of matching SpeciesInfo (max 20).
- Return type:
- get_species_data(species_id)[source]
Get complete data for a species with all its intervals.
- Parameters:
species_id (int) – Database ID of the species.
- Returns:
SpeciesData with its
intervalstuple, or None if not found.- Return type:
SpeciesData | None
- get_species_info(species_id)[source]
Get lightweight species metadata without loading intervals.
- Parameters:
species_id (int) – Database ID of the species.
- Returns:
SpeciesInfo, or None if the species is not found.
- Return type:
SpeciesInfo | None
- get_temperature_bounds(species_id)[source]
Return the overall [temp_min, temp_max] covered by a species.
- get_species_for_temperature(species_id, temperature)[source]
Get the interval and coefficients valid at a specific temperature.
- Parameters:
- Returns:
IntervalData, or None if the temperature is out of range.
- Return type:
IntervalData | None
- list_all_species()[source]
List every species in a single ordered query.
- Returns:
List of all SpeciesInfo ordered by name.
- Return type:
- static calculate_cp(coeffs, temperature)[source]
Calculate Cp(T)/R using NASA-7 polynomial coefficients.
Builder
Database builder: converts thermo.inp (NASA FORTRAN format) → SQLite3.
- FORTRAN Record Structure (Appendix C):
RECORD 1 – Species identification RECORD 2 – General information RECORD 3 – Temperature interval definition RECORD 4 – First 5 polynomial coefficients RECORD 5 – Last 2 coefficients + integration constants
Records 3–5 repeat for each temperature interval.
- class pyglenn.builder.ThermoDBBuilder(inp_file, db_file)[source]
Bases:
objectBuild a SQLite database from a thermo.inp file.
- write_metadata()[source]
Write canonical dataset metadata using idempotent upserts.
The method intentionally does not commit; callers can include metadata writes in the same transaction as a database build.
- Return type:
None
- static parse_species_record(line)[source]
Extract species name (cols 1-16) and comments (cols 19-80).
- static is_temperature_line(line)[source]
Detect RECORD 3 (temperature interval).
A temperature line has two valid floats in cols 0-11 and 11-22 where the first is strictly less than the second.
- static is_coefficient_line(line)[source]
Detect coefficient lines containing FORTRAN D notation.
Uses regex to match the standard FORTRAN double-precision format (e.g.
1.23456789D+01), which is more robust than substring matching.