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: object

High-level interface for calculating thermochemical properties.

Uses the bundled thermo.db by 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)

property connected: bool

Whether the calculator is connected to the database.

connect()[source]

Connect to the database.

Returns:

True if connection succeeded, False otherwise.

Return type:

bool

close()[source]

Close the database connection.

Return type:

None

get_available_species(search_pattern='', exact_match=False)[source]

Return a list of available species, optionally filtered by name.

Parameters:
  • search_pattern (str) – Optional substring to filter species names.

  • exact_match (bool) – If True, use case-insensitive exact match (e.g. 'N2' returns only N2, not Be3N2). Defaults to False (substring search) for backward compatibility.

Returns:

List of SpeciesInfo with id, name, phase, molecular_weight.

Return type:

list[SpeciesInfo]

calculate_properties(species_id, temperature)[source]

Calculate thermochemical properties at a given temperature.

Parameters:
  • species_id (int) – Database ID of the species.

  • temperature (float) – Temperature in Kelvin.

Returns:

ThermoProperties with temperature, cp, h_relative, s, temp_interval, species_name, and phase. h_relative is the absolute H°(T) (NASA-7 convention): H°(298.15 K) equals the standard enthalpy of formation.

Raises:
Return type:

ThermoProperties

calculate_formation_enthalpy(species_id)[source]

Get enthalpy of formation at 298.15 K in J/mol.

Parameters:

species_id (int) – Database ID of the species.

Returns:

Enthalpy of formation in J/mol, or None if not available.

Return type:

float | None

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:
  • species_id (int) – Database ID of the species.

  • T1 (float) – Initial temperature in Kelvin.

  • T2 (float) – Final temperature in Kelvin.

Returns:

Enthalpy change in J/mol.

Raises:
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, temperature and t_ref may lie in different intervals.

Parameters:
  • species_id (int) – Database ID of the species.

  • temperature (float) – Final temperature in Kelvin.

  • t_ref (float) – Reference temperature in Kelvin (default 298.15).

Returns:

Sensible enthalpy change in J/mol, or None if not connected.

Raises:
Return type:

float | None

get_properties_range(species_id, temps)[source]

Calculate properties at multiple temperatures.

Parameters:
  • species_id (int) – Database ID of the species.

  • temps (list[float]) – List of temperatures in Kelvin.

Returns:

Dict mapping temperature → ThermoProperties, or None if all fail.

Return type:

dict[float, ThermoProperties] | 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:
  • species_id (int) – Database ID of the species.

  • temps (Sequence[float]) – Sequence of temperatures in Kelvin.

  • strict (bool) – If True, raise on an out-of-range temperature. If False (default), out-of-range values are skipped.

Returns:

Ordered list of ThermoProperties.

Raises:
Return type:

list[ThermoProperties]

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:
  • species_id (int) – Database ID of the species.

  • temperature (float) – Temperature in Kelvin.

Returns:

dCp/dT in J/(mol·K²).

Raises:
Return type:

float

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_ref is the dataset reference gas constant.

Parameters:
  • species_id (int) – Database ID of the species.

  • temperature (float) – Temperature in Kelvin.

Returns:

Dimensionless ratio Cp/Cv.

Raises:
Return type:

float

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_molar follows the NASA-7 convention (absolute H°(T), with H°(298.15 K) = ΔH°f).

Parameters:
  • mixture (Mixture) – Mixture of (species_id, mole_fraction) pairs.

  • temperature (float) – Temperature in Kelvin.

  • strict (bool) – If True (default), raise on any component out of range. If False, out-of-range components are skipped and the remaining fractions renormalized (a warning is logged).

Returns:

MixedProperties with molar and mass based Cp/H/S and molar mass.

Raises:
Return type:

MixedProperties

Exceptions

class pyglenn.ThermoCalcError[source]

Bases: Exception

Base exception for thermochemical calculation errors.

class pyglenn.CompositionError[source]

Bases: ThermoCalcError

Raised when a mixture composition is invalid.

class pyglenn.DatabaseNotConnectedError[source]

Bases: ThermoCalcError

Raised when attempting calculation without a database connection.

class pyglenn.SpeciesNotFoundError(species_id)[source]

Bases: ThermoCalcError

Raised 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: ThermoCalcError

Raised when the requested temperature is outside valid intervals.

Carries the requested temperature, the species name, and the overall valid temperature bounds (when known).

Parameters:

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: object

The nine NASA-7 polynomial coefficients (dimensionless).

Parameters:
a1: float
a2: float
a3: float
a4: float
a5: float
a6: float
a7: float
b1: float
b2: float
classmethod from_mapping(mapping)[source]

Build from a mapping keyed by a1..``a7``, b1, b2.

Parameters:

mapping (Mapping[str, Any])

Return type:

NASACoefficients

to_dict()[source]

Return the coefficients as a plain dict.

Return type:

dict[str, float]

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: object

Basic metadata for a single species (no interval or coefficient data).

Parameters:
  • id (int)

  • name (str)

  • formula (str | None)

  • phase (str | None)

  • molecular_weight (float | None)

  • heat_of_formation_298K (float | None)

  • num_intervals (int | None)

  • comments (str | None)

  • reference_code (str | None)

id: int
name: str
formula: str | None = None
phase: str | None = None
molecular_weight: float | None = None
heat_of_formation_298K: float | None = None
num_intervals: int | None = None
comments: str | None = None
reference_code: str | None = None
classmethod from_mapping(mapping)[source]

Build from a dict or sqlite3.Row, tolerating missing keys.

Parameters:

mapping (Mapping[str, Any])

Return type:

SpeciesInfo

to_dict()[source]

Return the species metadata as a plain dict.

Return type:

dict[str, Any]

class pyglenn.models.IntervalData(interval_number, temp_min, temp_max, h_298_to_0, coefficients)[source]

Bases: object

A 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
to_dict()[source]

Return the interval as a plain dict (nested coefficients included).

Return type:

dict[str, Any]

class pyglenn.models.ThermoProperties(temperature, cp, h_relative, s, temp_interval, species_name, phase=None)[source]

Bases: object

Thermochemical properties at a single temperature.

cp and s are in J/(mol·K); h_relative is the absolute enthalpy H°(T) in J/mol (NASA-7 convention), where H°(298.15 K) = ΔH°f(298.15 K).

Parameters:
temperature: float
cp: float
h_relative: float
s: float
temp_interval: tuple[float, float]
species_name: str
phase: str | None = None
to_dict()[source]

Return the properties as a plain dict (tuple serialised as list).

Return type:

dict[str, Any]

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: object

Complete species record including all intervals and coefficients.

Parameters:
  • id (int)

  • name (str)

  • formula (str | None)

  • phase (str | None)

  • molecular_weight (float | None)

  • heat_of_formation_298K (float | None)

  • num_intervals (int | None)

  • comments (str | None)

  • reference_code (str | None)

  • intervals (tuple[IntervalData, ...])

id: int
name: str
formula: str | None = None
phase: str | None = None
molecular_weight: float | None = None
heat_of_formation_298K: float | None = None
num_intervals: int | None = None
comments: str | None = None
reference_code: str | None = None
intervals: tuple[IntervalData, ...] = ()
to_dict()[source]

Return the complete record as a plain dict with an intervals key.

Return type:

dict[str, Any]

class pyglenn.models.DatabaseStats(total_species, total_intervals, total_coeff_sets, species_by_phase, avg_molecular_weight=None)[source]

Bases: object

Aggregate database statistics.

Parameters:
  • total_species (int)

  • total_intervals (int)

  • total_coeff_sets (int)

  • species_by_phase (Mapping[str, int])

  • avg_molecular_weight (float | None)

total_species: int
total_intervals: int
total_coeff_sets: int
species_by_phase: Mapping[str, int]
avg_molecular_weight: float | None = None
to_dict()[source]

Return the statistics as a plain dict.

Return type:

dict[str, Any]

class pyglenn.models.Mixture(species)[source]

Bases: object

A thermochemical mixture defined by mole fractions.

species is 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 of validate().

validate() checks self-consistency only (sum, sign, duplicates, emptiness). Species-id existence is checked by the calculator, which owns the database connection.

Parameters:

species (tuple[tuple[int, float], ...])

species: tuple[tuple[int, float], ...]
validate(tol=1e-09)[source]

Validate the composition, raising CompositionError on 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

to_dict()[source]

Return the mixture as a plain dict (fractions serialised as lists).

Return type:

dict[str, Any]

class pyglenn.models.MixedProperties(temperature, cp_mass, h_mass, s_mass, cp_molar, h_molar, s_molar, molar_mass)[source]

Bases: object

Thermochemical properties of a mixture at a single temperature.

*_molar values are per mole of mixture; *_mass values are per kilogram of mixture. h_molar is the absolute enthalpy H°(T) in the NASA-7 convention (H°(298.15 K) = ΔH°f). molar_mass is the mole-fraction-weighted mean molar mass (arithmetic mean) in kg/mol.

Parameters:
temperature: float
cp_mass: float
h_mass: float
s_mass: float
cp_molar: float
h_molar: float
s_molar: float
molar_mass: float
to_dict()[source]

Return the properties as a plain dict.

Return type:

dict[str, Any]

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..a7 to 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 b1 is not fitted: it is derived so that the NASA-7 convention H°(t_ref) = h_ref holds exactly. The entropy constant b2 is derived from s_ref when provided, and set to 0.0 otherwise.

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_ref in J/mol (default 0.0). The returned b1 guarantees H°(t_ref) == h_ref.

  • s_ref (float | None) – Optional entropy S° at t_ref in J/(mol·K). When given, the returned b2 guarantees 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_values and h_ref. Defaults to R_GLENN, the value used by the bundled database.

Returns:

NASACoefficients with a1..a7, b1 and b2.

Raises:

ValueError – If the inputs are inconsistent, too short, or contain non-positive temperatures, non-finite values, or invalid weights.

Return type:

NASACoefficients

Notes

NASA-7 convention. The enthalpy integration constant is b1; a6 and a7 multiply 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 with pyglenn.ThermoDBQuery.calculate_cp().

Conditioning. The fit is performed in the scaled variable u = T / T_scale (with T_scale the 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/R and its first temperature derivative are continuous at every internal breakpoint (a linear equality constraint in the least-squares problem). The enthalpy constant b1 is anchored in the interval containing t_ref and propagated so that H° is continuous across breakpoints; b2 is anchored from s_ref when provided and propagated so that S° is continuous, otherwise set to 0.0 everywhere.

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 <= breakpoint belongs 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_ref in J/mol (default 0.0). The interval containing t_ref gets the b1 that makes H°(t_ref) == h_ref.

  • s_ref (float | None) – Optional entropy S° at t_ref in 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:

tuple[NASACoefficients, …]

Notes

The continuity constraints concern the fitted Cp polynomial (value and first derivative), matching fit_nasa7()’s NASA-7 convention (b1 is the enthalpy constant, not a6). 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: object

Class for querying thermochemical database.

Parameters:

db_file (str)

connect(*, auto_migrate=True)[source]

Connect to database.

Parameters:

auto_migrate (bool) – If True (default), add canonical dataset metadata to legacy databases automatically (see D3).

Returns:

True if connection succeeded, False otherwise.

Return type:

bool

close()[source]

Close connection.

Return type:

None

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:

float

migrate_metadata()[source]

Add canonical dataset metadata to a connected legacy database.

This explicit, idempotent operation changes only the additive metadata table. It never rebuilds or alters thermochemical rows.

Return type:

None

validate_database()[source]

Run integrity and semantic checks and return a validation report.

Returns:

Dict with valid (bool), errors (list[str]), warnings (list[str]), and counts (dict[str, int]).

Return type:

dict[str, Any]

get_statistics()[source]

Get database statistics.

Returns:

DatabaseStats with totals, phase counts, and average molecular weight.

Return type:

DatabaseStats

find_species(name, exact_match=False)[source]

Find species by name.

Parameters:
  • name (str) – Search pattern.

  • exact_match (bool) – If True, use case-insensitive exact match. If False (default), use substring match (LIKE).

Returns:

List of matching SpeciesInfo (max 20).

Return type:

list[SpeciesInfo]

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 intervals tuple, 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.

Parameters:

species_id (int) – Database ID of the species.

Returns:

Tuple of (min_temp, max_temp), or None if the species has no intervals.

Return type:

tuple[float, float] | None

get_species_for_temperature(species_id, temperature)[source]

Get the interval and coefficients valid at a specific temperature.

Parameters:
  • species_id (int) – Database ID of the species.

  • temperature (float) – Temperature in Kelvin.

Returns:

IntervalData, or None if the temperature is out of range.

Return type:

IntervalData | None

list_species_page(page=1, page_size=20)[source]

List species with pagination.

Parameters:
  • page (int) – Page number (1-based).

  • page_size (int) – Number of species per page.

Returns:

Tuple of (species_list, total_pages).

Return type:

tuple[list[SpeciesInfo], int]

list_all_species()[source]

List every species in a single ordered query.

Returns:

List of all SpeciesInfo ordered by name.

Return type:

list[SpeciesInfo]

static calculate_cp(coeffs, temperature)[source]

Calculate Cp(T)/R using NASA-7 polynomial coefficients.

Parameters:
Returns:

Dimensionless Cp/R.

Return type:

float

static calculate_h(coeffs, temperature)[source]

Calculate H°(T)/RT using NASA-7 polynomial coefficients.

Parameters:
Returns:

Dimensionless H/(RT).

Return type:

float

static calculate_s(coeffs, temperature)[source]

Calculate S°(T)/R using NASA-7 polynomial coefficients.

Parameters:
Returns:

Dimensionless S/R.

Return type:

float

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: object

Build a SQLite database from a thermo.inp file.

Parameters:
  • inp_file (str)

  • db_file (str)

connect()[source]

Connect to (or create) the SQLite database.

Return type:

None

close()[source]

Close the database connection.

Return type:

None

create_tables()[source]

Create the normalised table structure.

Return type:

None

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_float(value)[source]

Parse a FORTRAN-style float (‘D’ → ‘E’).

Parameters:

value (str) – String possibly in FORTRAN D notation.

Returns:

Float value or None if parsing fails.

Return type:

float | None

static parse_species_record(line)[source]

Extract species name (cols 1-16) and comments (cols 19-80).

Parameters:

line (str) – RECORD 1 line from thermo.inp.

Returns:

Tuple of (species_name, comments).

Return type:

tuple[str, str]

parse_general_info_record(line)[source]

Parse RECORD 2 – general information.

Parameters:

line (str) – RECORD 2 line from thermo.inp.

Returns:

Dict with num_intervals, ref_code, phase, molecular_weight, heat_of_formation.

Return type:

dict[str, Any]

static parse_temp_interval_record(line)[source]

Parse RECORD 3 – temperature interval.

Parameters:

line (str) – RECORD 3 line from thermo.inp.

Returns:

Dict with temp_min, temp_max, h_298_to_0.

Return type:

dict[str, Any]

static parse_coefficients_record(lines)[source]

Parse RECORDS 4-5 – polynomial coefficients.

Parameters:

lines (list[str]) – Two lines containing a1-a7 and b1-b2.

Returns:

Dict with keys a1-a7, b1, b2.

Return type:

dict[str, Any]

read_thermo_file()[source]

Read thermo.inp, stripping comments and blank lines.

Returns:

List of non-empty, non-comment lines.

Return type:

list[str]

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.

Parameters:

line (str) – A line from thermo.inp.

Returns:

True if the line appears to be a temperature interval record.

Return type:

bool

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.

Parameters:

line (str) – A line from thermo.inp.

Returns:

True if the line contains at least one FORTRAN D-format number.

Return type:

bool

static is_species_header(line)[source]

Return whether a line can be a species-identification record.

A coefficient line can fit entirely inside the fixed-width species-name field. It must therefore be rejected explicitly, rather than relying on whitespace in the apparent name.

Parameters:

line (str)

Return type:

bool

parse_and_load()[source]

Parse the thermo.inp file and populate the database atomically.

A species is inserted only after every declared interval and its two coefficient records have been parsed and validated. Malformed blocks are skipped without leaving partial rows behind.

Return type:

None